installer

package
v0.0.0-...-2b757cf Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package installer's rule-append path implements D20's byte contract.

Index

Constants

View Source
const (
	MechanismSymlink   = "symlink"
	MechanismCopy      = "copy"
	MechanismHookMerge = "hook_merge"
	MechanismMCPMerge  = "mcp_merge"
	// MechanismRuleAppend is a rule appended to a monolithic rule file.
	// InstallRuleAppend returns no Placement; callers that record it build
	// one with this mechanism and the target file as Path.
	MechanismRuleAppend = "rule_append"
)

Variables

View Source
var ErrEntryNil = errors.New("installer: content entry is nil")

ErrEntryNil is returned by RecordInstall / BuildLockEntry when the caller passes a nil ContentEntry. Programmer error; callers should not produce this in practice.

View Source
var ErrHookInstalled = errors.New("already installed")

ErrHookInstalled is wrapped by the error for a hook PlaceHook refuses because installed.json, in the current or the legacy root, records it.

View Source
var ErrMCPInstalled = errors.New("already installed")

ErrMCPInstalled is the merge's error for an item whose servers the target config already holds, each placed by a record under the legacy root or with the same settings.

Functions

func AppendRuleToTarget

func AppendRuleToTarget(targetFile string, canonicalBody []byte) error

AppendRuleToTarget appends canonicalBody to targetFile per D20:

  1. If target does not exist or is empty, write "\n<canonicalBody>".
  2. Otherwise ensure target ends with "\n", then append "\n<canonicalBody>".

canonicalBody must already be in D12 canonical form (single trailing \n). The function re-normalizes defensively.

func ApplyConflictResolution

func ApplyConflictResolution(providers []provider.Provider, conflicts []Conflict, resolution ConflictResolution) []provider.Provider

ApplyConflictResolution filters the provider list based on the user's chosen resolution strategy. Providers not involved in any conflict are always kept.

func ApplyLinkFixes

func ApplyLinkFixes(actions []FixAction) []error

ApplyLinkFixes executes the plan. Returns the actions that failed with errors.

func BuildLockEntry

func BuildLockEntry(
	entry *moat.ContentEntry,
	registryURL string,
	rekorBundle json.RawMessage,
	now time.Time,
) (moat.LockEntry, string, error)

BuildLockEntry translates a moat.ContentEntry into a moat.LockEntry ready for lf.AddEntry, along with the expected Rekor data.hash.value the pre-write check will verify `sha256(signed_payload)` against.

Trust-tier labels come from ContentEntry.TrustTier() (not from a raw field), so the G-13 downgrade is honored — a manifest with attestation_hash_mismatch=true and a signing_profile still lands in the lockfile as SIGNED, not DUAL-ATTESTED.

For UNSIGNED tiers:

  • SignedPayload is nil (serializes to JSON null).
  • AttestationBundle is JSON null.
  • expectedDataHashValue is the empty string; AddEntry ignores it.

For SIGNED and DUAL-ATTESTED tiers:

  • SignedPayload is the canonical payload bytes as a string — the exact representation cosign verify-blob --offline will be handed during future offline verification.
  • AttestationBundle is the rekorBundle argument verbatim. Callers pass the raw Rekor response bytes (or the cosign bundle bytes) captured at verification time. Re-marshaling would reorder keys and break offline verify, which is why we carry RawMessage.
  • expectedDataHashValue is hex(sha256(signed_payload)). AddEntry recomputes and compares; any discrepancy rejects the entry.

registryURL goes into LockEntry.Registry and should match the manifest_uri used during sync, so a future `moat-verify` pass can correlate entries to the registry they were pinned from.

func CheckEnvVars

func CheckEnvVars(cfg *MCPConfig) map[string]bool

CheckEnvVars returns a map of env var name -> whether it's currently set.

func CheckHook

func CheckHook(item catalog.ContentItem, h converter.Hook, prov provider.Provider, repoRoot, settingsPath string, inst *Installed) error

CheckHook returns why PlaceHook would refuse item's hook h for prov before it changes anything: a name that is not one path element, an event the provider cannot take, a hook its adapter cannot represent, a command naming a script outside the item, or scripts the copy cannot read. Scanner findings are reported apart, because --force overrides them. A non-empty settingsPath is decoded too, so a provider config the merge cannot read refuses here, and a hook inst or the legacy root under repoRoot records as installed returns an error wrapping ErrHookInstalled.

func CheckMCP

func CheckMCP(item catalog.ContentItem, prov provider.Provider, repoRoot string, inst *Installed) error

CheckMCP reports the error PlaceMCP would return for an item, without writing anything.

func CopyContent

func CopyContent(src, dst string) error

CopyContent copies a file or directory from src to dst.

func CreateSymlink(source, target string) error

CreateSymlink creates a symlink from target to source. Creates parent directories as needed. If the target already exists (stale symlink, previous copy, etc.), it is removed and replaced with the new symlink.

func ExtractServerEntries

func ExtractServerEntries(rawData []byte, itemName string, jsonKey string) (map[string]json.RawMessage, error)

ExtractServerEntries reads config.json and returns a map of server names to their whitelisted config. Handles two formats:

  • Nested: {"mcpServers": {"name": {...}}} — extracts each entry
  • Flat: {"command": "node", ...} — uses itemName as the key

The jsonKey parameter specifies the provider's top-level key (e.g., "mcpServers", "servers", "context_servers"); a file without it is read under mcpServers.

func ForgetReverted

func ForgetReverted(inst *Installed, repoRoot string, paths []string)

ForgetReverted drops the hook and MCP records whose provider file is one of paths and no longer holds what the record placed. Removing a loadout restores or deletes those files, which takes out anything installed into them after the apply; a record left behind would report it installed and block installing it again. Records for other files, and records whose file cannot be read, stay.

func HasRegistryLineage

func HasRegistryLineage(item catalog.ContentItem) bool

HasRegistryLineage reports whether item came from a registry, as a registry item or a Library copy of one.

func HashBytes

func HashBytes(data []byte) string

HashBytes computes the SHA-256 hex digest of arbitrary data.

func HashFile

func HashFile(path string) (string, error)

HashFile computes the SHA-256 hash of a file's contents.

func HookConfigPath

func HookConfigPath(prov provider.Provider, base string) (string, error)

HookConfigPath resolves a provider's hook file location, rooted at base (a home directory or a resolver-supplied base dir). It is the single source of truth for hook file locations — installer.hookSettingsPathImpl, the loadout apply path, and orphan detection all route through it so no flow can diverge onto a wrong path. Returns an error for providers whose hooks syllago cannot manage.

ConfigLocations is intentionally NOT consulted — it is inconsistent across providers, which is the root of the "dead config" bug this work fixes.

func InstallPath

func InstallPath(item catalog.ContentItem, prov provider.Provider, home string) (string, error)

InstallPath returns the path an install of item for prov occupies under home, which is where UninstallFrom removes it: the legacy location when only that one holds it. It returns "" when prov merges item into a settings file or does not install it to a directory under home.

func InstallRuleAppend

func InstallRuleAppend(projectRoot, homeDir, providerSlug, targetFile, source string, rule *rulestore.Loaded) error

InstallRuleAppend performs a monolithic-file append install. The library rule's current_version bytes are the canonical body (already normalized per D11's "files on disk = canonical"). D14 uniqueness: the new record replaces any existing one for the same (LibraryID, TargetFile), so a stale record survives until the append succeeds.

func IsJSONMerge

func IsJSONMerge(prov provider.Provider, itemType catalog.ContentType) bool

IsJSONMerge returns true if the provider uses JSON merge for the given content type. Hooks always do: every hook install encodes through the provider's HookAdapter, including Pi's extension file, and a provider with no adapter refuses the install rather than receiving the Library folder unconverted.

func IsSymlinkedTo

func IsSymlinkedTo(path, repoRoot string) bool

IsSymlinkedTo checks if the given path is a symlink pointing into the repoRoot.

func IsSymlinkedToAny

func IsSymlinkedToAny(path string, roots []string) bool

IsSymlinkedToAny checks if path is a symlink pointing into any of the given roots.

func IsWindowsMount

func IsWindowsMount(path string) bool

IsWindowsMount returns true if the given path is on a WSL Windows mount (e.g., /mnt/c/). Symlinks don't work reliably on Windows mounts, so callers should use copy instead.

func MCPConfigKey

func MCPConfigKey(prov provider.Provider) string

MCPConfigKey returns the JSON key under which MCP servers are stored. Most providers use "mcpServers"; Zed uses "context_servers".

func MCPConfigPathFor

func MCPConfigPathFor(prov provider.Provider, repoRoot string) (string, error)

MCPConfigPathFor returns the config file path where MCP servers are stored for the given provider. Exported for use by the loadout package.

func MCPJSONKey

func MCPJSONKey(prov provider.Provider) string

MCPJSONKey returns the JSON path prov's settings files keep MCP servers under, which FindMCPLocations reads. OpenCode and Amp nest them apart from the key MCPConfigKey merges installs into.

func MCPKeyIn

func MCPKeyIn(cfgPath, key string) (bool, error)

MCPKeyIn reports whether the MCP config at cfgPath holds key, a server's JSON path as an MCP install records it.

func MarkPrivateConfirmed

func MarkPrivateConfirmed(session *moat.Session, registryURL, contentHash string)

MarkPrivateConfirmed records the operator's acknowledgement of a private-repo item for this (registry, hash) pair. Uses the same key-prefix convention as PreInstallCheck so a single Session tracks both confirmation classes without collision.

func MarkPublisherConfirmed

func MarkPublisherConfirmed(session *moat.Session, registryURL, contentHash string)

MarkPublisherConfirmed records that the operator has acknowledged a publisher-source revocation for this (registry, hash) pair so subsequent gate checks in the same session skip the prompt. Safe to call on a nil session — no-op. Thin pass-through to the moat package so callers have a single import surface for gate + confirmation.

func RecordInstall

func RecordInstall(
	lf *moat.Lockfile,
	entry *moat.ContentEntry,
	registryURL string,
	rekorBundle json.RawMessage,
	now time.Time,
) (moat.LockEntry, error)

RecordInstall composes BuildLockEntry with lf.AddEntry. On success the lockfile has a new entries[] row; AddEntry itself is responsible for the sha256(signed_payload) == expectedDataHashValue check, and returns ErrSignedPayloadHashMismatch on violation. Callers MUST NOT persist the lockfile until this returns nil — a half-applied install would poison subsequent offline verification.

Side effects on success: lf.Entries grows by one row. The caller is expected to Save() the lockfile after the install side-effect completes; RecordInstall itself never touches disk.

func ReplaceRuleAppend

func ReplaceRuleAppend(projectRoot, libraryID, targetFile string, newBody []byte, library map[string]*rulestore.Loaded) error

ReplaceRuleAppend splices the recorded version's block in-place per D20's byte contract. The caller must have already verified D16 State == Clean; this function re-runs the byte search at execute time (no offset caching) so intervening edits by another tool are detected as a missing-match error rather than silently clobbered.

Implementation notes:

  • The new body must already be in the library's history (caller appends via rulestore.AppendVersion if it's novel).
  • On exactly-one-match success, the record's VersionHash is updated to hash(newBody) and installed.json is saved atomically.
  • Zero or multiple matches error out with a descriptive message; the caller surfaces this as a D17 Modified state to the user.

func ResolveAppendScope

func ResolveAppendScope(targetFile, homeDir, projectRoot string) string

ResolveAppendScope classifies a rule-append TargetFile per D14: "global" when under homeDir, "project" when under projectRoot, "global" otherwise (absolute paths outside both).

func RuleAppendedIn

func RuleAppendedIn(targetFile string, rule *rulestore.Loaded) (bool, error)

RuleAppendedIn reports whether targetFile holds any version of rule as an appended block, by the search UninstallRuleAppend makes.

func SaveInstalled

func SaveInstalled(projectRoot string, inst *Installed) error

SaveInstalled writes .syllago/installed.json atomically.

func ScanProviderLinksChecked

func ScanProviderLinksChecked(providers []provider.Provider, home string, roots []string) ([]ScannedLink, []LinkScanError)

ScanProviderLinksChecked is ScanProviderLinks that also returns each install directory it could not read. A caller about to delete what the links point at needs to know a link may have gone unseen.

func SetCacheInvalidator

func SetCacheInvalidator(fn func(target string))

SetCacheInvalidator registers the hook. Called by installcheck in its init.

func SourcePathFor

func SourcePathFor(item catalog.ContentItem) string

SourcePathFor returns the filesystem source path used when installing item.

func UninstallRuleAppend

func UninstallRuleAppend(projectRoot, libraryID, targetFile string, library map[string]*rulestore.Loaded) error

UninstallRuleAppend searches targetFile for any historical version's bytes (canonical "\n<body>" pattern per D20) and removes the matched range if found exactly once. Zero or multiple matches return an error that callers should surface as D17 Modified state — actual decision routing lives in the Update flow (Phase 7).

Types

type ApplyHookResult

type ApplyHookResult struct {
	NativeEvent string // provider-native event key (or canonical when unmapped)
	Command     string // resolved handler command, for installed.json
	GroupHash   string // post-round-trip canonical identity
}

ApplyHookResult is the tracking data produced by merging one hook through the adapter path.

func ApplyCanonicalHook

func ApplyCanonicalHook(prov provider.Provider, h converter.Hook, path, resolvedCommand string) (ApplyHookResult, error)

ApplyCanonicalHook merges one manifest hook into the provider's hook file at path via the provider's HookAdapter, preserving sibling keys for shared-JSON providers. The path is caller-supplied so callers can use their own resolver; resolvedCommand, when non-empty, overrides the hook's handler command (callers resolve script/relative paths first).

This is the loadout apply entry point; installHook uses the same building blocks directly because it interleaves snapshotting and dedup.

type Conflict

type Conflict struct {
	// SharedPath is the filesystem path that multiple providers use.
	SharedPath string
	// InstallingTo is the provider whose InstallDir resolves to SharedPath.
	InstallingTo provider.Provider
	// AlsoReadBy are the other selected providers that also read from SharedPath.
	AlsoReadBy []provider.Provider
}

Conflict describes an install-path collision between providers. It occurs when one provider's InstallDir resolves to the same path that one or more other providers read via GlobalSharedReadPaths. Installing to all of these providers simultaneously would cause duplicate content and conflict warnings in the reading providers.

func DetectConflicts

func DetectConflicts(providers []provider.Provider, ct catalog.ContentType, homeDir string) []Conflict

DetectConflicts checks whether any pair of providers in the given slice would result in content being written to a path that another provider also reads, for the given content type. Conflicts are grouped by shared path. Returns nil if there are no conflicts.

type ConflictResolution

type ConflictResolution int

ConflictResolution represents how the user wants to handle an install-path conflict.

const (
	// ResolutionSharedOnly installs only to the shared path (e.g. ~/.agents/skills/).
	// The installer provider writes there; reader providers are skipped since they
	// will pick up the content automatically via their shared read path.
	ResolutionSharedOnly ConflictResolution = iota
	// ResolutionOwnDirsOnly installs to each provider's own canonical directory.
	// The provider that owns the shared path is skipped; readers each get their
	// own install with no write to the shared path.
	ResolutionOwnDirsOnly
	// ResolutionAll installs to all providers (current behavior).
	// May produce duplicate content warnings in providers that read the shared path.
	ResolutionAll
)

type DriftEntry

type DriftEntry struct {
	Type         string `json:"type"` // "hook", "mcp", or "symlink"
	Name         string `json:"name"`
	ExpectedHash string `json:"expectedHash"`
	ActualHash   string `json:"actualHash"` // empty if file is missing
	Status       string `json:"status"`     // "modified", "missing", or "ok"
}

DriftEntry reports a single content integrity mismatch.

func VerifyIntegrity

func VerifyIntegrity(projectRoot string) ([]DriftEntry, error)

VerifyIntegrity checks all installed content for drift. Items without a stored hash are skipped (pre-existing installs).

type FixAction

type FixAction struct {
	Kind      FixKind
	Link      ScannedLink
	NewSource string
}

FixAction is one planned repair for a broken provider link.

func PlanLinkFixes

func PlanLinkFixes(broken []ScannedLink, libraryItems []catalog.ContentItem) []FixAction

PlanLinkFixes maps each broken link to a repair: relink when the library (libraryItems) still contains a matching item, prune otherwise.

type FixKind

type FixKind string

FixKind is the repair applied to a broken link.

const (
	FixRelink FixKind = "relink" // library still has the item; point the link at it
	FixPrune  FixKind = "prune"  // no library match; remove the dead link
)

type GateBlock

type GateBlock struct {
	// Decision is the gate outcome. Every caller MUST switch on this.
	Decision MOATGateDecision

	// Revocation is populated for MOATGateHardBlock and
	// MOATGatePublisherWarn. Reason and DetailsURL drive the operator-
	// facing message; IssuingRegistryURL + ContentHash are the pair the
	// caller passes to Session.MarkConfirmed on Y.
	Revocation *moat.RevocationRecord

	// ObservedTier is the tier the manifest actually carried; MinTier is
	// the caller's policy floor. Both are set only for
	// MOATGateTierBelowPolicy.
	ObservedTier moat.TrustTier
	MinTier      moat.TrustTier
}

GateBlock is the return payload from PreInstallCheck. Exactly one of Revocation / tier fields is populated according to Decision; the remainder stay zero so callers can switch on Decision without defensive nil guards.

When Decision == MOATGateProceed, all detail fields are zero.

func PreInstallCheck

func PreInstallCheck(
	entry *moat.ContentEntry,
	registryURL string,
	lf *moat.Lockfile,
	revSet *moat.RevocationSet,
	session *moat.Session,
	minTier moat.TrustTier,
) GateBlock

PreInstallCheck enforces the MOAT gates BEFORE any filesystem side-effect.

Parameters:

  • entry: the manifest row being installed. Must be non-nil.
  • registryURL: the manifest_uri. Propagated into Revocation records and Session keys so a publisher revocation confirmed against registry A never auto-confirms the same hash observed on registry B (different operators, different trust decisions).
  • lf: the project lockfile. Nil is allowed (first-ever install) and means "no archival revocations known yet."
  • revSet: RevocationSet aggregated from the manifest(s) just synced. Nil means "no live revocations this run"; the caller has already run moat.Sync and chose not to cross-reference.
  • session: publisher-warn and private-prompt session suppressor. Nil is treated as "every check warns" — safe-by-default for short-lived CLI invocations.
  • minTier: the project's policy floor. Pass TrustTierUnsigned to accept anything.

Returns GateBlock. Never returns an error — all misuse is panic-worthy programmer bug (nil entry) and every legitimate input maps to a decision value.

type InstallMethod

type InstallMethod string

InstallMethod controls how content is placed in the target directory.

const (
	MethodSymlink InstallMethod = "symlink"
	MethodCopy    InstallMethod = "copy"
	// MethodAppend routes rule installs to InstallRuleAppend, which appends
	// the rule's canonical body to a monolithic file (e.g. CLAUDE.md) rather
	// than placing a file in a file-rules directory (D5). Only valid for
	// catalog.Rules on providers whose slug has a MonolithicFilenames entry.
	MethodAppend InstallMethod = "append"
)

type Installed

type Installed struct {
	Hooks       []InstalledHook       `json:"hooks,omitempty"`
	MCP         []InstalledMCP        `json:"mcp,omitempty"`
	Symlinks    []InstalledSymlink    `json:"symlinks,omitempty"`
	RuleAppends []InstalledRuleAppend `json:"ruleAppends,omitempty"`
}

Installed is the root structure for .syllago/installed.json.

func LoadInstalled

func LoadInstalled(projectRoot string) (*Installed, error)

LoadInstalled reads .syllago/installed.json. Returns an empty Installed if the file does not exist.

func (*Installed) FindHook

func (inst *Installed) FindHook(name, event, slug string) int

FindHook returns the index of the hook entry for name and event on the provider with that slug, or -1 if there is none.

func (*Installed) FindMCP

func (inst *Installed) FindMCP(name, slug string) int

FindMCP returns the index of the MCP entry for name on the provider with that slug, or -1 if there is none.

func (*Installed) FindMCPByServerKey

func (inst *Installed) FindMCPByServerKey(name, serverKey, slug string) int

FindMCPByServerKey returns the index of the MCP entry for name and serverKey on the provider with that slug, or -1 if there is none.

func (*Installed) FindRuleAppend

func (inst *Installed) FindRuleAppend(libraryID, targetFile string) int

FindRuleAppend returns the index of a rule append entry matching libraryID and targetFile, or -1. The (LibraryID, TargetFile) pair is unique per D14.

func (*Installed) RemoveHook

func (inst *Installed) RemoveHook(idx int)

RemoveHook removes the hook entry at the given index.

func (*Installed) RemoveMCP

func (inst *Installed) RemoveMCP(idx int)

RemoveMCP removes the MCP entry at the given index.

func (*Installed) RemoveRuleAppend

func (inst *Installed) RemoveRuleAppend(idx int)

RemoveRuleAppend removes the rule append entry at idx.

type InstalledHook

type InstalledHook struct {
	Name        string    `json:"name"`
	Event       string    `json:"event"`
	GroupHash   string    `json:"groupHash,omitempty"` // SHA256 of the matcher group JSON
	Command     string    `json:"command"`             // kept for display/debugging
	Source      string    `json:"source"`              // "export" or "loadout:<name>"
	Scope       string    `json:"scope,omitempty"`     // "global" or "project"
	Provider    string    `json:"provider,omitempty"`  // slug; empty on entries written before it was tracked
	InstalledAt time.Time `json:"installedAt"`
}

InstalledHook records a hook placed into settings.json by syllago.

type InstalledMCP

type InstalledMCP struct {
	Name        string    `json:"name"`
	ServerKey   string    `json:"serverKey,omitempty"`   // specific server key (new per-server installs)
	ServerNames []string  `json:"serverNames,omitempty"` // DEPRECATED: legacy bulk installs tracked all keys here
	ContentHash string    `json:"contentHash,omitempty"` // SHA-256 of config content at install time
	Source      string    `json:"source"`
	Provider    string    `json:"provider,omitempty"` // slug; empty on entries written before it was tracked
	InstalledAt time.Time `json:"installedAt"`
}

InstalledMCP records an MCP server placed into a provider config by syllago.

type InstalledRuleAppend

type InstalledRuleAppend struct {
	Name        string    `json:"name"`
	LibraryID   string    `json:"libraryId"`
	Provider    string    `json:"provider"`
	TargetFile  string    `json:"targetFile"`
	VersionHash string    `json:"versionHash"` // canonical "<algo>:<hex>" per D11
	Source      string    `json:"source"`
	Scope       string    `json:"scope,omitempty"`
	InstalledAt time.Time `json:"installedAt"`
}

InstalledRuleAppend records a rule appended to a provider's monolithic file (D14).

type InstalledSymlink struct {
	Path        string    `json:"path"`                  // absolute path of the symlink
	Target      string    `json:"target"`                // absolute path it points to
	ContentHash string    `json:"contentHash,omitempty"` // SHA-256 of target content at install time
	Source      string    `json:"source"`
	InstalledAt time.Time `json:"installedAt"`
}

InstalledSymlink records a symlink placed by syllago.

type ItemGate

type ItemGate struct {
	GateBlock
	Entry       *moat.ContentEntry
	RegistryURL string
}

ItemGate is the trust gate's answer for one catalog item, with the registry URL and entry it was checked against. Entry carries the hash the item holds, so a confirmation recorded against Entry.ContentHash covers exactly the content that will be installed.

func CheckItem

func CheckItem(item catalog.ContentItem, in *moat.GateInputs, lf *moat.Lockfile, session *moat.Session, minTier moat.TrustTier) (ItemGate, bool)

CheckItem runs PreInstallCheck for an item that came from a MOAT registry, reading the registry's cached manifest from in. A registry item names its registry in Registry. A Library copy names it in its metadata, with the hash it was staged at, and is checked at that hash: a revocation of the version the Library holds blocks it even after the registry has published a newer one.

The registry's attestations vouch only for the hash it lists. A copy staged at another hash, one that recorded no hash, or one the registry no longer lists carries no attestation, so a tier floor above unsigned refuses it; it is checked for revocations and for the listing's privacy declaration as well. A copy whose registry has no cached manifest is still checked when the lockfile or any cached registry revokes its hash.

ok is false for an item no MOAT registry, lockfile or revocation accounts for, which installs ungated.

type LinkClass

type LinkClass string

LinkClass classifies a syllago-owned symlink found in a provider install directory.

const (
	LinkHealthy LinkClass = "healthy" // target exists
	LinkBroken  LinkClass = "broken"  // target missing
)

type LinkScanError

type LinkScanError struct {
	Provider string
	Dir      string
	Err      error
}

LinkScanError is a provider install directory that exists but that a link scan could not read, so links in it went unseen.

func (LinkScanError) Error

func (e LinkScanError) Error() string

func (LinkScanError) Unwrap

func (e LinkScanError) Unwrap() error

type MCPConfig

type MCPConfig struct {
	Type    string            `json:"type,omitempty"`
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	URL     string            `json:"url,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
}

MCPConfig represents a parsed MCP server configuration.

func ParseMCPConfig

func ParseMCPConfig(itemPath string) (*MCPConfig, error)

ParseMCPConfig reads and parses config.json from an MCP item directory.

func ParseMCPServerConfig

func ParseMCPServerConfig(itemPath string, serverKey string) (*MCPConfig, error)

ParseMCPServerConfig reads config.json and returns the MCPConfig for a specific server. For nested format, extracts the entry matching serverKey. For flat format (or empty serverKey), returns the single config.

type MCPLocation

type MCPLocation struct {
	Scope   SettingsScope
	Path    string
	JSONKey string // "mcpServers", "context_servers", "mcp", "amp.mcpServers", etc.
}

MCPLocation describes one file where MCP configs were found.

func FindMCPLocations

func FindMCPLocations(prov provider.Provider, projectRoot, baseDir string) []MCPLocation

FindMCPLocations returns all files where MCP configs exist for a provider. For providers that store MCP in settings.json (alongside hooks), it checks both global and project scopes. For providers with dedicated MCP files, it checks those. For Claude Code, it checks both settings.json files AND dedicated files (~/.claude.json, .mcp.json).

type MOATGateDecision

type MOATGateDecision int

MOATGateDecision is the branch the caller should take after PreInstallCheck returns. Negative-space values beyond Proceed map to specific G-18 NonInteractiveFailure codes (documented on each variant).

const (
	// MOATGateProceed means no gate blocked the install. The caller
	// continues to the filesystem side-effect, then calls RecordInstall
	// to append the lockfile entry.
	MOATGateProceed MOATGateDecision = iota

	// MOATGateHardBlock means a registry-source revocation (archival or
	// live) applies. The caller MUST refuse to install — interactive
	// confirmation cannot override a registry-source block, per G-8.
	// Non-interactive callers MUST exit non-zero with a MOAT_* structured
	// error; no dedicated NonInteractiveFailure exit exists (registry-
	// source revocation is categorically fatal, not a gate).
	MOATGateHardBlock

	// MOATGatePublisherWarn means the item is publisher-revoked and the
	// session has not yet confirmed acceptance. Interactive callers MUST
	// prompt Y/n and on Yes call Session.MarkConfirmed to suppress
	// future warnings for the same (registry, hash) pair. Non-interactive
	// callers MUST exit with ExitMoatPublisherRevocation (12) per G-18.
	MOATGatePublisherWarn

	// MOATGatePrivatePrompt means the content_entry is declared with
	// private_repo=true and requires explicit operator acknowledgement
	// (G-10). Interactive callers MUST prompt; non-interactive callers
	// MUST exit with ExitMoatTOFUAcceptance (10) because the operator is
	// the only party who can confirm visibility expectations — the
	// acceptance shape matches TOFU semantically.
	MOATGatePrivatePrompt

	// MOATGateTierBelowPolicy means the item's computed TrustTier is
	// below the caller-supplied minimum. There is no interactive recovery
	// — the operator cannot upgrade a tier; only the publisher can. The
	// caller surfaces this as a structured error and exits.
	MOATGateTierBelowPolicy
)

func (MOATGateDecision) String

func (d MOATGateDecision) String() string

String returns a short human-readable label used for diagnostics and structured audit logs. Stable across versions; do NOT rewrite these — external scripts grep for the labels.

type Notice

type Notice struct {
	Kind     NoticeKind
	Severity string // scanner findings only: "high", "medium", "low", ...
	Message  string // may span lines (script security)
}

Notice is something an install has to tell the user. The installer never prints; it returns notices on the Placement, including alongside an error, so a blocked install can still say why.

func (Notice) String

func (n Notice) String() string

String renders the notice on one line, for front ends that show a short list rather than the CLI's install output.

type NoticeKind

type NoticeKind string

NoticeKind classifies a Notice so each front end can render it its own way.

const (
	// NoticeNote reports a change of plan the install made on its own, such
	// as copying instead of symlinking onto a Windows mount.
	NoticeNote NoticeKind = "note"
	// NoticeConversionWarning reports content the render for the target
	// provider dropped or approximated.
	NoticeConversionWarning NoticeKind = "conversion_warning"
	// NoticeScannerFinding reports one hook scanner finding; Severity holds
	// the scanner's severity.
	NoticeScannerFinding NoticeKind = "scanner_finding"
	// NoticeScannerError reports a scanner in the chain that failed to run.
	NoticeScannerError NoticeKind = "scanner_error"
	// NoticeScriptSecurity reports that a hook's bundled scripts were copied
	// to a stable location and will run as commands.
	NoticeScriptSecurity NoticeKind = "script_security"
)

type OrphanEntry

type OrphanEntry struct {
	Provider string `json:"provider"`
	Type     string `json:"type"`  // "hook" or "mcp"
	Key      string `json:"key"`   // event name for hooks, server name for MCP
	Index    int    `json:"index"` // array index for hooks, -1 for MCP
}

OrphanEntry describes a hook or MCP entry found in a provider's settings.json that is not tracked by installed.json. These entries may have been left behind by a crash between writing settings.json and updating installed.json.

func CheckOrphanedMerges

func CheckOrphanedMerges(projectRoot string, providers []provider.Provider) ([]OrphanEntry, error)

CheckOrphanedMerges reads settings.json for each detected provider and compares hooks/MCP entries against installed.json. Returns entries present in settings but not tracked by installed.json.

type Placement

type Placement struct {
	Mechanism string   // "symlink", "copy", "hook_merge", or "mcp_merge"
	Path      string   // destination path (symlink/copy) or settings file (merges)
	Keys      []string // full JSON keys for merges (e.g. "hooks.PreToolUse", "mcpServers.github"); nil otherwise
	Notices   []Notice // what the install has to tell the user; set even when it fails
	// contains filtered or unexported fields
}

Placement describes where an install (or uninstall) acted: the mechanism used, the filesystem destination, and — for JSON merges — the keys touched. String() renders the same human-readable description these functions used to return, so display call sites keep their exact output.

func Install

func Install(item catalog.ContentItem, prov provider.Provider, repoRoot string, method InstallMethod, baseDir string, scan ScanOptions) (Placement, error)

Install places the given item under the provider's install directory. For JSON merge types (MCP, hooks), it merges into the provider's config file. For filesystem types, it creates a symlink or copy depending on the method. baseDir overrides the home directory as the install root. If empty, uses home dir. scan configures the hook scanner chain; other content types ignore it. Returns placement metadata; Placement.String renders the legacy description.

func InstallWithResolver

func InstallWithResolver(item catalog.ContentItem, prov provider.Provider, repoRoot string, method InstallMethod, resolver *config.PathResolver, scan ScanOptions) (Placement, error)

InstallWithResolver places the given item under the provider's install directory, using the resolver for path resolution instead of a flat baseDir string. This respects the full priority chain: per-type path > CLI --base-dir > config baseDir > default.

func PlaceHook

func PlaceHook(item catalog.ContentItem, h converter.Hook, prov provider.Provider, repoRoot, settingsPath, scriptsDir string, inst *Installed, source string, scan ScanOptions) (Placement, error)

PlaceHook merges hook h, read from item, into the provider's hook file at settingsPath and appends its record to inst under source. It refuses an item with high-severity scanner findings unless scan.Force, and copies the scripts the hook runs into scriptsDir, so the scanned copy is the one that runs. The caller loads and saves inst.

func PlaceMCP

func PlaceMCP(item catalog.ContentItem, prov provider.Provider, repoRoot string, inst *Installed, source string) (Placement, error)

PlaceMCP merges an MCP item's servers into the provider's MCP config and appends their record to inst under source. The caller loads and saves inst, so several placements share one write of installed.json, and the caller keeps any backup of the config, so none is written beside it.

func Uninstall

func Uninstall(item catalog.ContentItem, prov provider.Provider, repoRoot string) (Placement, error)

Uninstall removes the given item from the provider's default install directory under the home directory. See UninstallFrom.

func UninstallFrom

func UninstallFrom(item catalog.ContentItem, prov provider.Provider, repoRoot, baseDir string, resolver *config.PathResolver) (Placement, error)

UninstallFrom removes the given item from where Install or InstallWithResolver placed it with the same baseDir or resolver. A non-nil resolver overrides baseDir, and an empty baseDir means the home directory. For JSON merge types, it removes the entry from the provider's config file and ignores baseDir and resolver, as Install does. For filesystem types, it removes the symlink or copy. Returns placement metadata; Placement.String renders the legacy description.

func (Placement) String

func (p Placement) String() string

type ScanOptions

type ScanOptions struct {
	Scanners []string // external scanner binaries (--hook-scanner)
	Force    bool     // install despite high-severity findings (--force)
}

ScanOptions configures the hook scanner chain for one install. The zero value runs only the builtin scanner and blocks on high-severity findings.

type ScannedLink struct {
	Provider    string
	ContentType catalog.ContentType
	Path        string
	Target      string
	Class       LinkClass
}

ScannedLink is one symlink in a provider install directory whose target resolves into a syllago-owned root.

func ScanProviderLinks(providers []provider.Provider, home string, roots []string) []ScannedLink

ScanProviderLinks walks each provider's install directory for every content type and returns the symlinks whose target resolves into any of roots. Symlinks pointing elsewhere (user-owned) and non-symlink entries are ignored. A directory it cannot read is skipped; ScanProviderLinksChecked reports it.

type SettingsLocation

type SettingsLocation struct {
	Scope SettingsScope
	Path  string
}

SettingsLocation describes one discovered settings.json file.

func FindSettingsLocations

func FindSettingsLocations(prov provider.Provider, projectRoot string) ([]SettingsLocation, error)

FindSettingsLocations returns all settings.json paths for the given provider that exist on disk, checking global and project-local scopes. projectRoot is the nearest git root (or cwd if not in a git repo).

func FindSettingsLocationsWithBase

func FindSettingsLocationsWithBase(prov provider.Provider, projectRoot, baseDir string) ([]SettingsLocation, error)

FindSettingsLocationsWithBase works like FindSettingsLocations but uses baseDir instead of the user's home directory for the global scope path.

type SettingsScope

type SettingsScope int

SettingsScope represents where a settings.json lives.

const (
	ScopeGlobal SettingsScope = iota
	ScopeProject
)

func (SettingsScope) String

func (s SettingsScope) String() string

type Status

type Status int

Status represents the install status of an item for a provider.

const (
	StatusNotAvailable Status = iota // provider doesn't support this content type
	StatusNotInstalled               // available but not installed
	StatusInstalled                  // installed (symlink points to our repo)
)

func CheckStatus

func CheckStatus(item catalog.ContentItem, prov provider.Provider, repoRoot string, registryPaths ...string) Status

CheckStatus checks whether an item is installed for a given provider. registryPaths contains additional valid symlink source roots (registry cache directories).

func CheckStatusWithResolver

func CheckStatusWithResolver(item catalog.ContentItem, prov provider.Provider, repoRoot string, resolver *config.PathResolver, registryPaths ...string) Status

CheckStatusWithResolver checks whether an item is installed, using the resolver for path resolution instead of the default home directory.

func StatusOf

func StatusOf(item catalog.ContentItem, prov provider.Provider, repoRoot string, registryPaths ...string) (Status, error)

StatusOf is CheckStatus that also reports when it could not tell. A non-nil error means a file the check needed could not be read or parsed, so the returned Status is a guess; a caller about to delete the item treats that provider as unknown rather than as not installed.

func (Status) String

func (s Status) String() string

Jump to

Keyboard shortcuts

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