hooksync

package
v1.0.0-rc.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package hooksync projects imported hooks into client hook configuration. It is the hook tenant of pkg/project: scripts are copied into a gridctl-owned directory per (hook, client), and the client's configuration is written with recorded ownership. gridctl never executes a hook.

Two channels exist. A merge-key target owns a region inside a shared file: matcher groups in a settings file (Claude Code), or one top-level key per hook in a hooks file (Antigravity). The write is an RFC 6902 patch on the parsed hujson tree, so bytes outside the patched region, including comments, stay as they were found. A dedicated-file target (OpenCode, Copilot CLI) owns one generated file per hook. The ownership decision table follows pkg/wiring and pkg/agentsync, with the identical-value adopt branch omitted: an unrecorded group or file is never claimed without --force.

Index

Constants

View Source
const (
	ChannelMergeKey      = "merge-key"
	ChannelDedicatedFile = "dedicated-file"
)

Channels name how a target owns its region. A merge-key target owns matcher groups inside a shared settings file, never the file itself. A dedicated-file target owns one generated file per hook.

View Source
const (
	RenderIdentity = "identity"
	RenderLossy    = "lossy"
)

Render classes. Identity groups are the definition's groups with absolute script paths. A lossy render is a dialect translation that names every dropped group and handler key.

View Source
const (
	ActionCopied             = "copied"
	ActionUpdated            = project.ActionUpdated
	ActionUnchanged          = project.ActionUnchanged
	ActionRemoved            = "removed"
	ActionSkippedDrift       = project.ActionSkippedDrift
	ActionSkippedForeign     = "skipped-foreign"
	ActionSkippedPinDrift    = "skipped-pin-drift"
	ActionSkippedUnmanaged   = "skipped-unmanaged"
	ActionSkippedUnavailable = project.ActionSkippedUnavailable
	ActionSkippedUnsupported = "skipped-unsupported"
	// ActionSkippedUnexpressible is a (hook, client) the target's dialect
	// cannot carry: no group has a mapped event and matcher.
	ActionSkippedUnexpressible = "skipped-unexpressible"
	ActionWouldCopy            = "would-copy"
	ActionWouldUpdate          = project.ActionWouldUpdate
	ActionWouldRemove          = "would-remove"
	ActionAlreadyGone          = "already-gone"
	ActionError                = project.ActionError

	StateInSync        = project.StateInSync
	StateStale         = project.StateStale
	StateDrifted       = project.StateDrifted
	StateTargetMissing = project.StateTargetMissing

	// SettingsUnparsableDetail is the prefix used when a settings file is
	// not valid JSON or JSONC. Force does not override that case.
	SettingsUnparsableDetail = "settings file is not valid JSON or JSONC: "
)

Variables

View Source
var (
	ErrUnknownClient = errors.New("unknown client")
	ErrUnknownHook   = errors.New("unknown hook")
	ErrNotProjected  = errors.New("hook is not projected")
)

Sentinel errors callers branch on.

View Source
var ErrNewerLockVersion = project.ErrNewerLockVersion

ErrNewerLockVersion signals projection state written by a newer gridctl. Aliased from the engine so callers' errors.Is checks work.

Functions

func HasFailures

func HasFailures(results []SyncResult) bool

HasFailures reports whether any sync result needs the caller's attention. Every skipped or failed row counts. Dry-run would-* rows do not.

func KnownSlugs

func KnownSlugs() []string

KnownSlugs lists target and unsupported slugs, for the unknown-client error.

func NeedsAttention

func NeedsAttention(statuses []ProjectionStatus) bool

NeedsAttention reports whether any projection requires action.

func RemovalRefusal

func RemovalRefusal(name string, row UnsyncResult) string

RemovalRefusal is the operator message for a blocked registry delete. It names the client and the unsync --force command.

func SettingsUnparsable

func SettingsUnparsable(detail string) bool

SettingsUnparsable reports whether detail names an unparsable settings file.

Types

type Entry

type Entry struct {
	// ConfigPath is the client file. For a merge-key target, Path on the
	// engine entry is the composite "<ConfigPath>#hooks/<name>" so several
	// hooks share one file; for a dedicated-file target Path is ConfigPath.
	ConfigPath string
	// Channel is display only. saveView writes it from the target table,
	// and every behavior branch reads the channel from FindTarget, so an
	// entry rewritten by an older gridctl behaves the same after upgrade.
	Channel string
	// ScriptDir is the absolute script copy.
	ScriptDir string
	// Hashes is the canonical hash history of the owned groups, newest last.
	Hashes []string
	// TreeHash is the hash of the script copy at sync time.
	TreeHash string
	// CreatedFile is true when gridctl created the settings file.
	CreatedFile bool
	Pack        string
	SyncedAt    time.Time
}

Entry is one recorded (hook, client) ownership record.

type LockFile

type LockFile struct {
	Records map[string]map[string]*Entry
}

LockFile is the hook-kind view over the unified project lockfile, keyed hook name → client slug. The engine owns the on-disk schema.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager owns hook projections. All target paths resolve against home. Mutating operations serialize on mu and on the engine's cross-process lock.

func NewManager

func NewManager(registryDir string) (*Manager, error)

NewManager builds a Manager rooted at the user's home directory. It is for end-of-the-line CLI call sites only: any caller in pkg/ or internal/ that tests can reach must use NewManagerWithHome.

func NewManagerWithHome

func NewManagerWithHome(home, registryDir string) *Manager

NewManagerWithHome builds a Manager rooted at an explicit home. Tests use this to stay isolated from $HOME.

func (*Manager) DetectedUnsupported

func (m *Manager) DetectedUnsupported() []UnsupportedClient

DetectedUnsupported returns unsupported clients detected under the manager home. The CLI prints one stderr note per row when sync was not given --clients. Pack apply turns the same list into skipped-unsupported rows.

func (*Manager) HasProjections

func (m *Manager) HasProjections(ctx context.Context) (bool, error)

HasProjections reports whether any hook is currently projected.

func (*Manager) Home

func (m *Manager) Home() string

Home returns the manager home. Pack status uses it to join rows.

func (*Manager) LockPath

func (m *Manager) LockPath() string

LockPath returns the unified projection lockfile path.

func (*Manager) Statuses

func (m *Manager) Statuses(ctx context.Context) ([]ProjectionStatus, error)

Statuses returns one row per recorded hook projection.

func (*Manager) Sync

func (m *Manager) Sync(ctx context.Context, names []string, opts SyncOptions) ([]SyncResult, error)

Sync projects hooks into every available target, or into --clients. The settings file is read and written once per client, not once per hook.

func (*Manager) Unsync

func (m *Manager) Unsync(ctx context.Context, names []string, opts UnsyncOptions) ([]UnsyncResult, error)

Unsync removes recorded groups whose hash is still one gridctl wrote, or any located groups when Force is set. Groups gridctl did not record are never deleted. The settings file is read and written once per client.

type ProjectionStatus

type ProjectionStatus struct {
	Hook        string     `json:"hook"`
	Client      string     `json:"client"`
	Channel     string     `json:"channel"`
	Render      string     `json:"render"`
	State       string     `json:"state"`
	Target      string     `json:"target"`
	ScriptDir   string     `json:"script_dir,omitempty"`
	Pack        string     `json:"pack,omitempty"`
	SyncedAt    *time.Time `json:"synced_at,omitempty"`
	Detail      string     `json:"detail,omitempty"`
	Remediation string     `json:"remediation,omitempty"`
}

ProjectionStatus is one recorded (hook, client) row.

type RenderFunc

type RenderFunc func(spec *hookSpec, name, scriptDir string) (rendered, error)

RenderFunc renders one hook for one target. It is a pure function of the parsed definition, the hook name, and the script directory.

type SyncOptions

type SyncOptions struct {
	Clients []string
	Force   bool
	DryRun  bool
	// Pack tags recorded projections. Empty keeps any existing tag.
	Pack string
}

SyncOptions configure a sync pass.

type SyncResult

type SyncResult struct {
	Hook        string `json:"hook,omitempty"`
	Client      string `json:"client"`
	Channel     string `json:"channel,omitempty"`
	Target      string `json:"target,omitempty"`
	Action      string `json:"action"`
	Detail      string `json:"detail,omitempty"`
	Remediation string `json:"remediation,omitempty"`
	BackupPath  string `json:"backup_path,omitempty"`
	Error       string `json:"error,omitempty"`
	ScriptDir   string `json:"script_dir,omitempty"`
}

SyncResult is one (hook, client) outcome.

func (SyncResult) ActionWasCopy

func (r SyncResult) ActionWasCopy() bool

type Target

type Target struct {
	Slug string
	Name string
	// Path is a ~-template expanded against the Manager's home. A
	// merge-key target names its shared settings file. A dedicated-file
	// target carries <name>, replaced with the hook name.
	Path string
	// DetectDirs mark the client as initialized on this machine.
	DetectDirs []string
	// Channel is ChannelMergeKey or ChannelDedicatedFile. Every behavior
	// branch reads it from this table, never from a lockfile entry.
	Channel string
	// RenderClass is RenderIdentity or RenderLossy, reported in status.
	RenderClass string
	// Render is the dialect renderer. Nil is the Claude Code identity render.
	Render RenderFunc
	// Key names the top-level key a keyed merge-key target owns in its
	// shared file, with <name> replaced by the hook name. Empty means the
	// target owns matcher groups under the file's hooks key.
	Key string
}

Target describes one client's hook destination.

func FindTarget

func FindTarget(slug string) (Target, bool)

FindTarget returns the projection target for slug.

func Targets

func Targets() []Target

Targets returns the projection targets in display order.

func (Target) PathFor

func (t Target) PathFor(home, hookName string) string

PathFor returns the target's destination for one hook: the shared settings file for a merge-key target, the hook's own file otherwise.

type UnenforcedHook

type UnenforcedHook struct {
	Name   string `json:"name"`
	Reason string `json:"reason"`
}

UnenforcedHook is one required hook that is not in-sync for a client.

func Unenforced

func Unenforced(client string, required []string, statuses []ProjectionStatus) []UnenforcedHook

Unenforced reports required hooks that are not enforced on client. Reason is one of "not projected", "drifted", "stale", "pin drift", or "client has no hook target". State and exit codes are the caller's.

type UnsupportedClient

type UnsupportedClient struct {
	Slug     string
	Name     string
	Location string
	// CoveredBy names the target slug whose projection this client reads.
	CoveredBy string
	// The client is detected when any DetectDirs entry is a directory or
	// any DetectFiles entry is a regular file.
	DetectDirs  []string
	DetectFiles []string
}

UnsupportedClient is a client with a hook mechanism gridctl does not write. Sync reports it; it never creates the native file.

func FindUnsupported

func FindUnsupported(slug string) (UnsupportedClient, bool)

FindUnsupported returns a known non-target client.

func UnsupportedClients

func UnsupportedClients() []UnsupportedClient

UnsupportedClients returns clients that have a hook mechanism and no target, in display order. Location is the native path named in skipped-unsupported rows and the stderr note. A covered client reads the CoveredBy target's projection.

func (UnsupportedClient) CoveredNote

func (c UnsupportedClient) CoveredNote() string

CoveredNote is the stderr note for a detected client. A covered client names the projection it reads; any other names its native location.

func (UnsupportedClient) Detail

func (c UnsupportedClient) Detail() string

Detail is the skipped-unsupported row detail: the native location, and for a covered client the target whose projection it reads.

type UnsyncOptions

type UnsyncOptions struct {
	All     bool
	Clients []string
	Force   bool
	DryRun  bool
}

UnsyncOptions configure an unsync pass.

type UnsyncResult

type UnsyncResult struct {
	Hook       string `json:"hook"`
	Client     string `json:"client"`
	Target     string `json:"target"`
	Action     string `json:"action"`
	Detail     string `json:"detail,omitempty"`
	BackupPath string `json:"backup_path,omitempty"`
	Error      string `json:"error,omitempty"`
}

UnsyncResult describes one removal.

func BlocksRemoval

func BlocksRemoval(results []UnsyncResult) (UnsyncResult, bool)

BlocksRemoval reports the first unsync row that did not retire the projection. removed and already-gone allow a registry delete to proceed. skipped-drift, skipped-unmanaged, error, and any other action do not.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL