Documentation
¶
Overview ¶
Recognizer conformance contract.
Every recognizer registered via RegisterRecognizer MUST satisfy these five requirements. They are stated using RFC-2119 keywords (MUST / MUST NOT / SHOULD) so callers and tooling can reason about behavior precisely.
INPUT CONTRACT — Recognizers MUST treat the supplied RecognitionContext as read-only. They MUST NOT mutate the Fields map, the Landmarks slice, or any other field on the context. They MUST NOT retain references to ctx.Fields, ctx.Landmarks, or any string within them across calls. A recognizer that needs to keep data around for diagnostics MUST copy it.
OUTPUT CONTRACT — Every key in RecognitionResult.Capabilities MUST match the regular expression ^[a-z_]+(\.[a-z_]+)*$ . That is: lowercase ASCII letters and underscores, segments joined by literal dots, no leading/trailing dot, no empty segment. Tested by TestRecognitionConformance_KeyRegex.
PURITY — Recognizers MUST NOT perform I/O (no file reads, no network, no os.Stat). They MUST NOT read package-level mutable globals. They MUST NOT call time.Now, math/rand, crypto/rand, or any other source of nondeterminism. The only allowed inputs are the fields of the supplied RecognitionContext.
DETERMINISM — For two RecognitionContext values that are deeply equal (reflect.DeepEqual), recognizers MUST produce two RecognitionResult values that are deeply equal. Map iteration order MUST NOT leak into the output (build sorted keys when ordering matters).
STABILITY — Callers SHOULD construct RecognitionContext and read RecognitionResult by named field. Code outside the capmon package MUST NOT use struct literals to construct or destructure these types — the capmon package reserves the right to add fields without bumping a major version, and named-field access keeps such additions backward compatible.
Violations of (1) and (3) are silent corruption. Violations of (2) and (4) are caught by tests. Violation of (5) breaks at compile time the next time capmon adds a field, which is the intended trip-wire.
Package capmon implements the capability monitor pipeline. Four-stage pipeline: fetch → extract → diff → review.
Index ¶
- Constants
- Variables
- func AgeBasedEvict(cacheRoot string, maxAge time.Duration) (int, error)
- func AppendCapmonChangeEvent(_ context.Context, issueNumber int, body string) error
- func BuildHealPRBody(in HealPRInputs) string
- func BuildPRBody(w io.Writer, diff CapabilityDiff) error
- func CheckFetch(ctx context.Context, doer HTTPDoer, rawURL string) (body []byte, contentType, finalURL string, err error)
- func ChromedpRemoteURL() string
- func CloseResolvedWarningIssues(_ context.Context, provider string, seenKeys map[string]bool) error
- func CreateCapmonChangeIssue(_ context.Context, provider, contentType, title, body string) (int, error)
- func CreateCapmonProviderIssue(_ context.Context, provider, title, body string) (int, error)
- func CreateCapmonWarningIssue(_ context.Context, provider string, w ValidationWarning) (int, error)
- func CreateDriftPR(_ context.Context, provider, runID string, diff CapabilityDiff) (string, error)
- func CreateStructuralIssue(_ context.Context, provider, runID string, drift []string) error
- func DeduplicatePR(_ context.Context, provider string) (string, bool, error)
- func FetchURI(ctx context.Context, uri, fetchMethod string) ([]byte, error)
- func FindOpenCapmonHealPR(provider, contentType string, sourceIndex int) (string, bool, error)
- func FindOpenCapmonIssue(provider, contentType string) (int, bool, error)
- func FindOpenCapmonProviderIssue(provider string) (int, string, bool, error)
- func FindOpenCapmonWarningIssue(provider string, w ValidationWarning) (int, bool, error)
- func FormatDocPath(formatsDir, provider string) string
- func GHRunner(args ...string) ([]byte, error)
- func GenerateContentTypeViews(capsDir, outDir string) error
- func GenerateUnifiedDiff(oldContent, newContent []byte, path, sourceType string) (string, error)
- func HealFailureAnchor(provider, contentType string, sourceIndex int) string
- func HealPRAnchor(provider, contentType string, sourceIndex int) string
- func IsCached(cacheRoot, provider, sourceID string) bool
- func IsCanonicalAgentsKey(key string) bool
- func IsCanonicalCommandsKey(key string) bool
- func IsCanonicalHooksKey(key string) bool
- func IsCanonicalMcpKey(key string) bool
- func IsCanonicalRulesKey(key string) bool
- func IsCanonicalSkillsKey(key string) bool
- func IsRecognizerRegistered(provider string) bool
- func LoadAndRecognizeCache(cacheRoot, provider string) (map[string]string, error)
- func MarkStaleFilings(cacheRoot string, now time.Time) error
- func OnboardProvider(ctx context.Context, opts OnboardOptions) error
- func ProposeManifestHealPR(ctx context.Context, repoDir string, in HealPRInputs) (string, error)
- func ProviderIssueBodyWithAnchor(slug, body string) string
- func RecognizeContentTypeDotPaths(provider string, fields map[string]FieldValue) map[string]string
- func RecordConsecutiveFailure(_ context.Context, cacheRoot, provider string) error
- func RecordConsecutiveHealFailure(cacheRoot, provider, contentType string, sourceIndex int, result *HealResult) (int, error)
- func RecordUnmappedForm(cacheRoot string, obs UnmappedFormObservation) (int, error)
- func RegisterExtractor(format string, ext Extractor)
- func RegisterRecognizer(provider string, kind RecognizerKind, ...)
- func RenderCandidatesTable(outcomes []CandidateOutcome) string
- func ResolveHealFailure(cacheRoot, provider, contentType string, sourceIndex int) error
- func RunCapmonCheck(ctx context.Context, opts CapmonCheckOptions) error
- func RunExport(opts ExportOptions) error
- func RunExportVerify(commit, baseURL string) error
- func RunFetchStage(ctx context.Context, opts PipelineOptions, manifest *RunManifest) error
- func RunFreeze(opts FreezeOptions) (string, error)
- func RunPipeline(ctx context.Context, opts PipelineOptions) (exitClass int, err error)
- func SHA256Hex(data []byte) string
- func SanitizeExtractedString(s string) string
- func SanitizeSlug(slug string) (string, error)
- func ScanGraduationCandidates(cacheRoot, formatDocsDir, canonicalKeysPath string, now time.Time) ([]int, error)
- func SeedProviderCapabilities(opts SeedOptions) error
- func SeederSpecPath(specsDir, provider, contentType string) string
- func SetGHCommandForTest(fn func(args ...string) ([]byte, error))
- func SetGitHubBaseURLForTest(url string)
- func SetGitRunnerForTest(fn func(dir string, args ...string) ([]byte, error))
- func SetHTTPClientForTest(c *http.Client)
- func SetRedirectClientForTest(c *http.Client)
- func SetValidateURLForTest(f func(string) error)
- func UpdateCapmonProviderIssue(_ context.Context, provider string, issueNum int, existingBody, body string) (bool, error)
- func UpdateManifestURL(manifestPath, contentType string, sourceIndex int, ...) error
- func ValidateContentResponse(body []byte, contentType, originalURL, finalURL string) error
- func ValidateFormatDoc(formatsDir, canonicalKeysPath, provider string) error
- func ValidateSourceURL(rawURL string) error
- func ValidateSources(sourcesDir, provider string) error
- func WriteCacheEntry(cacheRoot string, entry CacheEntry) error
- func WriteCacheMeta(cacheRoot string, entry CacheEntry) error
- func WriteRunManifest(cacheRoot string, m RunManifest) error
- func WriteSeederSpec(spec *SeederSpec, path string) error
- type BackfillOptions
- type BackfillResult
- type CacheEntry
- func FetchChromedp(ctx context.Context, cacheRoot, provider, sourceID, rawURL string) (*CacheEntry, error)
- func FetchGitHubFile(ctx context.Context, ...) (*CacheEntry, error)
- func FetchSource(ctx context.Context, cacheRoot, provider, sourceID, rawURL string) (*CacheEntry, error)
- func ReadCacheEntry(cacheRoot, provider, sourceID string) (*CacheEntry, error)
- type CacheMeta
- type CandidateOutcome
- type CandidateOutcomeKind
- type CanonicalMapping
- type CapabilityDiff
- type CapmonCheckOptions
- type ConfirmEvidence
- type ConfirmFinding
- type ConfirmOptions
- type ConfirmResult
- type ConsideredCandidate
- type ContentTypeFormatDoc
- type ContentTypeSource
- type DefaultSourceFetcher
- type DocsConventions
- type ErrContentInvalid
- type ErrNoExtractor
- type ExportOptions
- type ExtensionExample
- type ExtractedSource
- type Extractor
- type FieldChange
- type FieldValue
- type FormatDoc
- type FreezeOptions
- type GoStructOptions
- type HTTPDoer
- type HashURLResult
- type HealEvent
- type HealPRInputs
- type HealResult
- type HealingConfig
- type InvalidKind
- type LandmarkOptions
- func AgentsLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
- func CommandsLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
- func HooksLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
- func McpLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
- func RulesLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
- func SkillsLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
- type LandmarkPattern
- func AgentsLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
- func CommandsLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
- func HooksLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
- func McpLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
- func RulesLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
- func SkillsLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
- type OnboardOptions
- type PipelineOptions
- type ProposedMapping
- type ProviderExtension
- type ProviderStatus
- type RecognitionContext
- type RecognitionResult
- type RecognizerKind
- type RedirectChain
- type RedirectHop
- type RenameCandidate
- type RunManifest
- type SeedOptions
- type SeederSpec
- type SelectorConfig
- type SourceEntry
- type SourceFetcher
- type SourceManifest
- type SourceRef
- type SourceResult
- type StringMatcher
- type UnmappedFormObservation
- type ValidationWarning
- type VariantCandidate
Constants ¶
const ( ConfirmVerdictReject = "reject" ConfirmVerdictUnconfirmed = "unconfirmed" )
Machine verdicts for a status:unmapped candidate. The already-mapped direction is machine-authoritative (reject); the genuinely-unmapped direction is never machine-closed — it lands unconfirmed and is handed to a human via a needs-human issue.
const ( // Path a: the token claim is an export member with // recognition_requiring:false — mapped-ness is statically decidable. ConfirmReasonStaticMember = "static-member" // Probe canonicalized the source form cleanly: the mechanism is mapped // (for a member token) or the candidate was mis-flagged (for a // non-member claim). ConfirmReasonProbeClean = "probe-clean" // Probe answered acif.hook.platform_mechanism_malformed: the mechanism // is mapped and the source form is an authoring error, not a gap. ConfirmReasonProbeMalformed = "probe-malformed" // Probe answered acif.hook.platform_unmappable for a token the export // says is a member: impl/spec skew — a human must reconcile. ConfirmReasonProbeSkew = "probe-skew" // Path c: no token claim, or the claim is not in the export — a genuine // Class B candidate. When a probe also answered platform_unmappable the // evidence is strengthened, but the reason code stays the same. ConfirmReasonNotInExport = "not-in-export" // The token is recognition-requiring but the candidate's scope has no // differentially-witnessed probe (adr/0001: no scope's class-B verdict // is machine-authoritative until that scope is differentially clean). ConfirmReasonScopeUntrusted = "scope-untrusted" // Degraded paths (hard invariant: these land unconfirmed, never reject, // never silent drop). ConfirmReasonProbeDegraded = "probe-degraded" ConfirmReasonSourceFormUnparsable = "source-form-unparsable" )
Stable reason codes recorded in confirm state files and issue bodies.
const ( MappingStatusAbsent = "absent" MappingStatusMapped = "mapped" MappingStatusUnmapped = "unmapped" )
MappingStatus values classify how a provider relates to a canonical key. The bool `supported` field this replaces was overloaded: `false` conflated "the provider genuinely lacks this concept" with "the provider has a mechanism I could not map" — two cases with opposite downstream meaning.
absent — the provider has no such mechanism; nothing to map, ever.
Never a Class B candidate.
mapped — the mechanism maps to the canonical key (the former supported: true).
unmapped — the provider HAS a mechanism but it does not map to the canonical
key yet; a Class B (mapping-row) candidate. Requires SourceForm.
const ( StatusRecognized = "recognized" StatusAnchorsMissing = "anchors_missing" StatusNotEvaluated = "not_evaluated" )
Status constants for RecognitionResult.Status. Use these in helpers and tests instead of raw string literals to keep the three-state pipeline grep-able.
const ( ExitClean = 0 // All providers extracted, no drift ExitDrifted = 1 // Drift detected, PR/issue opened ExitPartialFailure = 2 // Some providers failed, others succeeded ExitInfrastructureFailure = 3 // Chromedp/network/selector broken ExitFatal = 4 // Config corrupt, schema validation failed ExitPaused = 5 // .capmon-pause sentinel present )
Exit class constants for RunManifest.ExitClass.
const AgentsContentType = "agents"
AgentsContentType is the dot-path root for every agents capability emission.
const CommandsContentType = "commands"
CommandsContentType is the dot-path root for every commands capability emission.
const HooksContentType = "hooks"
HooksContentType is the dot-path root for every hooks capability emission.
const McpContentType = "mcp"
McpContentType is the dot-path root for every MCP capability emission.
const RealisticUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
RealisticUA is a current Chrome user-agent string. Headless Chrome's default UA contains "HeadlessChrome" which triggers bot detection on many sites.
const RulesContentType = "rules"
RulesContentType is the dot-path root for every rules capability emission.
const SkillsContentType = "skills"
SkillsContentType is the dot-path root for every skills capability emission.
Variables ¶
var CanonicalAgentsKeys = []string{
"definition_format",
"tool_restrictions",
"invocation_patterns",
"agent_scopes",
"model_selection",
"per_agent_mcp",
"subagent_spawning",
}
CanonicalAgentsKeys lists every recognized canonical key for the agents content type, in the same order as docs/spec/canonical-keys.yaml. Recognizers MUST only emit capability dot-paths whose first canonical-key segment appears in this list. Validation runs at AgentsLandmarkOptions construction time.
To add a key here, first add it to canonical-keys.yaml so the FormatDoc validator and seeder-spec audit stay in sync. The two lists drifting silently is the failure mode this slice protects against.
var CanonicalCommandsKeys = []string{
"argument_substitution",
"builtin_commands",
"command_scopes",
}
CanonicalCommandsKeys lists every recognized canonical key for the commands content type, in the same order as docs/spec/canonical-keys.yaml. Recognizers MUST only emit capability dot-paths whose first canonical-key segment appears in this list. Validation runs at CommandsLandmarkOptions construction time.
To add a key here, first add it to canonical-keys.yaml so the FormatDoc validator and seeder-spec audit stay in sync. The two lists drifting silently is the failure mode this slice protects against.
var CanonicalHooksKeys = []string{
"handler_types",
"matcher_patterns",
"decision_control",
"input_modification",
"async_execution",
"hook_scopes",
"json_io_protocol",
"context_injection",
"permission_control",
}
CanonicalHooksKeys lists every recognized canonical key for the hooks content type, in the same order as docs/spec/canonical-keys.yaml. Recognizers MUST only emit capability dot-paths whose first canonical-key segment appears in this list. Validation runs at HooksLandmarkOptions construction time.
To add a key here, first add it to canonical-keys.yaml so the FormatDoc validator and seeder-spec audit stay in sync. The two lists drifting silently is the failure mode this slice protects against.
var CanonicalMcpKeys = []string{
"transport_types",
"oauth_support",
"env_var_expansion",
"tool_filtering",
"auto_approve",
"marketplace",
"resource_referencing",
"enterprise_management",
"mcp_scopes",
}
CanonicalMcpKeys lists every recognized canonical key for the MCP content type, in the same order as docs/spec/canonical-keys.yaml. Recognizers MUST only emit capability dot-paths whose first canonical-key segment appears in this list. Validation runs at McpLandmarkOptions construction time.
To add a key here, first add it to canonical-keys.yaml so the FormatDoc validator and seeder-spec audit stay in sync. The two lists drifting silently is the failure mode this slice protects against.
var CanonicalRulesKeys = []string{
"activation_mode",
"file_imports",
"cross_provider_recognition",
"auto_memory",
"hierarchical_loading",
"rule_scopes",
}
CanonicalRulesKeys lists every recognized canonical key for the rules content type, in the same order as docs/spec/canonical-keys.yaml. Recognizers MUST only emit capability dot-paths whose first canonical-key segment appears in this list. Validation runs at RulesLandmarkOptions construction time.
To add a key here, first add it to canonical-keys.yaml so the FormatDoc validator and seeder-spec audit stay in sync. The two lists drifting silently is the failure mode this slice protects against.
var CanonicalSkillsKeys = []string{
"display_name",
"description",
"license",
"compatibility",
"metadata_map",
"disable_model_invocation",
"user_invocable",
"version",
"project_scope",
"global_scope",
"shared_scope",
"canonical_filename",
"custom_filename",
"auto_invocable",
"skill_bundled_resources",
}
CanonicalSkillsKeys lists every recognized canonical key for the skills content type, in the same order as docs/spec/canonical-keys.yaml. Recognizers MUST only emit capability dot-paths whose first canonical-key segment appears in this list. Validation runs at SkillsLandmarkOptions construction time.
To add a key here, first add it to canonical-keys.yaml so the FormatDoc validator and seeder-spec audit stay in sync. The two lists drifting silently is the failure mode this slice protects against.
var DefaultHealingStrategies = []string{"redirect", "github-rename", "variant"}
DefaultHealingStrategies lists the strategies tried in order when a source's Healing.Strategies list is empty. Each strategy is a pluggable heal path registered by the capmon package.
var KnownConventions = map[string]bool{ "cross-provider-agents-md": true, "cross-provider-skill-md": true, }
KnownConventions is the set of cross-provider convention names accepted as a substitute for source URIs. A content type with one of these names in its `convention:` field passes validation even with empty sources — the convention itself is the spec, and there is no upstream URL to monitor.
var KnownHealingStrategies = map[string]bool{ "redirect": true, "github-rename": true, "variant": true, }
KnownHealingStrategies is the set of healing strategy names accepted in source manifests. Unknown strategies fail validation.
var ValidMappingStatuses = []string{ MappingStatusAbsent, MappingStatusMapped, MappingStatusUnmapped, }
ValidMappingStatuses enumerates the allowed values for CanonicalMapping.Status.
var ValidProviderCategories = []string{
"cli",
"ide-extension",
"standalone-app",
"web-based",
}
ValidProviderCategories enumerates the allowed values for FormatDoc.Category. Changes here must stay in sync with the category validator in formatdoc_validate.go. Downstream consumers of the published data may also maintain category label maps keyed by these values.
Functions ¶
func AgeBasedEvict ¶
AgeBasedEvict removes cache entries whose FetchedAt is older than maxAge. Returns the number of entries evicted.
func AppendCapmonChangeEvent ¶
AppendCapmonChangeEvent appends a comment to an existing capmon issue. Used to record subsequent change detections on the same issue thread.
func BuildHealPRBody ¶
func BuildHealPRBody(in HealPRInputs) string
BuildHealPRBody renders the PR body for a heal. The body is deliberately terse: reviewers need to see the old URL, the new URL, and the proof. Everything else (logs, audit trail) goes in the run artifact.
func BuildPRBody ¶
func BuildPRBody(w io.Writer, diff CapabilityDiff) error
BuildPRBody writes a PR body to w for the given CapabilityDiff. Extracted values are NEVER passed through a template engine — they are written directly to the io.Writer inside triple-backtick fences.
func CheckFetch ¶
func CheckFetch(ctx context.Context, doer HTTPDoer, rawURL string) (body []byte, contentType, finalURL string, err error)
CheckFetch performs the canonical baseline fetch: a direct HTTP GET with pinned content negotiation, returning the body, Content-Type header, final URL (after redirects), and any error. EVERY code path that computes or compares a content_hash baseline (capmon check, capmon backfill, capmon hash-url, provmon's source-hash checker) MUST fetch through this function — the pinned headers ARE the hash contract:
- User-Agent: capmon/1.0
- Accept: text/markdown for *.md paths (code.claude.com intermittently serves rendered HTML without it), */* otherwise (curl's default; Mintlify hosts vary bytes on its absence).
- Accept-Encoding: identity, so the transport's implicit gzip never shapes the hashed bytes. A response that ignores the request and compresses anyway fails loudly instead of hashing wire bytes.
The canonical hash recipe is therefore:
curl -H 'User-Agent: capmon/1.0' -H 'Accept: <as above>' \
-H 'Accept-Encoding: identity' -L <url> | sha256sum
or, without remembering any of that, `capmon hash-url <url>`.
func ChromedpRemoteURL ¶
func ChromedpRemoteURL() string
ChromedpRemoteURL returns the CHROMEDP_URL env var value. Empty string means use local Chrome via DefaultExecAllocatorOptions.
func CloseResolvedWarningIssues ¶
CloseResolvedWarningIssues closes any open capmon-warn issues for a provider whose dedup keys are not in the seenKeys set. This auto-closes warnings that have been fixed since the last run.
func CreateCapmonChangeIssue ¶
func CreateCapmonChangeIssue(_ context.Context, provider, contentType, title, body string) (int, error)
CreateCapmonChangeIssue creates a GitHub issue for a content-change event. The issue body is prefixed with a hidden anchor comment <!-- capmon-check: <provider>/<contentType> --> for deduplication by FindOpenCapmonIssue. Returns the new issue number.
func CreateCapmonProviderIssue ¶
CreateCapmonProviderIssue creates a GitHub issue for a per-provider batched change event. The issue body is prefixed with <!-- capmon-check: <provider> --> for deduplication by FindOpenCapmonProviderIssue. Returns the new issue number.
func CreateCapmonWarningIssue ¶
CreateCapmonWarningIssue creates a GitHub issue for a validation warning. The issue body includes a hidden anchor with the dedup key for future lookups.
func CreateDriftPR ¶
CreateDriftPR creates a GitHub PR for field-level drift. Returns the PR URL. SanitizeSlug must be called on provider before reaching this function.
func CreateStructuralIssue ¶
CreateStructuralIssue creates a GitHub issue for structural drift (new sections).
func DeduplicatePR ¶
DeduplicatePR checks if an open PR exists for capmon/drift-<provider>. Returns (existingPRURL, true) if found; ("", false) if not found.
func FetchURI ¶
FetchURI fetches a URI using HTTP GET, or a headless Chromium browser when fetchMethod is "chromedp". Returns the raw body.
func FindOpenCapmonHealPR ¶
FindOpenCapmonHealPR searches for an open PR with label=capmon-heal whose body contains the anchor for (provider, contentType, sourceIndex). Returns the PR URL and true when a match exists.
func FindOpenCapmonIssue ¶
FindOpenCapmonIssue searches for an open GitHub issue with the capmon-change label and the provider:slug label, then filters by the hidden anchor comment <!-- capmon-check: <provider>/<contentType> -->. Returns (issueNumber, true, nil) when found, or (0, false, nil) when no matching issue exists.
func FindOpenCapmonProviderIssue ¶
FindOpenCapmonProviderIssue searches for an open GitHub issue with the capmon-change label and the provider:slug label, filtered by the provider-only anchor <!-- capmon-check: <provider> -->. Returns (issueNumber, body, true, nil) when found, or (0, "", false, nil) when no matching issue exists. Legacy per-(provider,contentType) anchors (<!-- capmon-check: slug/ct -->) do not match.
The body is returned so callers can refresh a stale anchor issue in place rather than skipping the run's findings entirely.
func FindOpenCapmonWarningIssue ¶
func FindOpenCapmonWarningIssue(provider string, w ValidationWarning) (int, bool, error)
FindOpenCapmonWarningIssue searches for an open GitHub issue matching a validation warning's dedup key. Returns (issueNumber, true, nil) when found.
func FormatDocPath ¶
FormatDocPath returns the canonical filesystem path for a provider's format doc.
func GHRunner ¶
GHRunner invokes the gh CLI with the given arguments, returning combined output. Exported for use by Stage 4 PR/issue creation (Task 9.2).
func GenerateContentTypeViews ¶
GenerateContentTypeViews reads all provider-capabilities/*.yaml and writes docs/provider-capabilities/by-content-type/<type>.yaml files. Each generated file begins with a THIS FILE IS GENERATED banner.
func GenerateUnifiedDiff ¶
GenerateUnifiedDiff returns a human-readable diff between oldContent and newContent labelled with path and a sourceType (used to select the truncation threshold). Returns an empty string if the contents are identical.
Truncation thresholds:
- sourceType == "source_code": 500 output lines
- all other types: 200 output lines
When truncated, a final indicator line is appended:
[truncated after N lines (~X bytes shown) — full diff at .capmon-cache/<slug>/]
func HealFailureAnchor ¶
HealFailureAnchor returns the hidden HTML comment for heal-failure issue dedup. Distinct from HealPRAnchor so a PR and an issue for the same source don't step on each other when gh searches.
func HealPRAnchor ¶
HealPRAnchor returns the hidden HTML comment used to deduplicate heal PRs and issues. The anchor is embedded in the PR body and searched by FindOpenCapmonHealPR.
func IsCanonicalAgentsKey ¶
IsCanonicalAgentsKey reports whether key is one of the canonical agents keys declared in CanonicalAgentsKeys. Used by AgentsLandmarkOptions to fail fast on typos and by tests to guard the canonical-keys.yaml ↔ Go drift surface.
func IsCanonicalCommandsKey ¶
IsCanonicalCommandsKey reports whether key is one of the canonical commands keys declared in CanonicalCommandsKeys. Used by CommandsLandmarkOptions to fail fast on typos and by tests to guard the canonical-keys.yaml ↔ Go drift surface.
func IsCanonicalHooksKey ¶
IsCanonicalHooksKey reports whether key is one of the canonical hooks keys declared in CanonicalHooksKeys. Used by HooksLandmarkOptions to fail fast on typos and by tests to guard the canonical-keys.yaml ↔ Go drift surface.
func IsCanonicalMcpKey ¶
IsCanonicalMcpKey reports whether key is one of the canonical MCP keys declared in CanonicalMcpKeys. Used by McpLandmarkOptions to fail fast on typos and by tests to guard the canonical-keys.yaml ↔ Go drift surface.
func IsCanonicalRulesKey ¶
IsCanonicalRulesKey reports whether key is one of the canonical rules keys declared in CanonicalRulesKeys. Used by RulesLandmarkOptions to fail fast on typos and by tests to guard the canonical-keys.yaml ↔ Go drift surface.
func IsCanonicalSkillsKey ¶
IsCanonicalSkillsKey reports whether key is one of the canonical skills keys declared in CanonicalSkillsKeys. Used by SkillsLandmarkOptions to fail fast on typos and by tests to guard the canonical-keys.yaml ↔ Go drift surface.
func IsRecognizerRegistered ¶
IsRecognizerRegistered reports whether a recognizer is registered for the given provider slug. Used in tests to assert full provider coverage.
func LoadAndRecognizeCache ¶
LoadAndRecognizeCache reads all extracted.json files for the given provider from the cache root, runs the registered recognizer, and returns a merged dot-path → value map. Source directories that are missing or corrupt are silently skipped.
func MarkStaleFilings ¶
MarkStaleFilings adds the stale label to filed ACIF-change issues whose tracked form or extension has not been observed for 30 or more days.
func OnboardProvider ¶
func OnboardProvider(ctx context.Context, opts OnboardOptions) error
OnboardProvider bootstraps a new provider into the capmon pipeline. It assumes ValidateSources has already been called by the caller (the cobra command does this before invoking OnboardProvider).
For each supported content type with at least one source:
- Fetch each source URI via FetchSource to populate the cache baseline.
- Create a GitHub issue recording the initial content hashes.
Fetch errors are non-blocking — the source is noted in the issue body but does not abort the run.
func ProposeManifestHealPR ¶
ProposeManifestHealPR updates the manifest, opens a branch, pushes it, and creates a PR tagged capmon-heal. Idempotent: if a matching PR is already open for this (provider, contentType, sourceIndex), the existing PR URL is returned and no new work is done.
The repoDir must be the root of the repo containing the capability data (the directory containing docs/provider-sources/). The manifestPath in HealPRInputs is expected to be absolute.
func ProviderIssueBodyWithAnchor ¶
ProviderIssueBodyWithAnchor prefixes body with the provider dedup anchor. Create and update must agree on this exact layout or an updated issue stops matching FindOpenCapmonProviderIssue.
func RecognizeContentTypeDotPaths ¶
func RecognizeContentTypeDotPaths(provider string, fields map[string]FieldValue) map[string]string
RecognizeContentTypeDotPaths dispatches to the registered recognizer for the provider and returns just the capability dot-paths. Backwards-compatible facade over the structured RecognizeWithContext — callers that need Status / MissingAnchors should use RecognizeWithContext directly.
Dot-path format: "<content_type>.<section>.<key>.<field>" → value Examples:
- "skills.supported" → "true"
- "skills.capabilities.display_name.mechanism" → "yaml frontmatter key: name"
- "skills.capabilities.display_name.confidence" → "confirmed"
If no recognizer is registered for the provider, logs a warning and returns an empty map. Recognition is pattern-based and deterministic — no LLM calls.
func RecordConsecutiveFailure ¶
RecordConsecutiveFailure increments the failure counter for a provider. Opens a GitHub issue after the 3rd consecutive failure.
func RecordConsecutiveHealFailure ¶
func RecordConsecutiveHealFailure(cacheRoot, provider, contentType string, sourceIndex int, result *HealResult) (int, error)
RecordConsecutiveHealFailure increments the heal-failure counter for a specific source. When the counter reaches healFailureThreshold, a GitHub issue is opened (or a comment is appended to the existing one) so a human can intervene — manual URL update, disable healing, or mark the source supported:false.
Returns (issueNumber, error). issueNumber is 0 when no issue was created this run (under threshold or append-to-existing path).
result carries the failure reason and the per-candidate diagnostic outcomes; both are surfaced in issue body / comment so reviewers see what each heal probe turned up.
func RecordUnmappedForm ¶
func RecordUnmappedForm(cacheRoot string, obs UnmappedFormObservation) (int, error)
RecordUnmappedForm persists the observation and files or refreshes the ACIF class-b issue once the distinct-content-item threshold is met.
This is the exported intake point for the sweep pipeline; the caller that detects totality-net diagnostics will be wired in separately.
Returns the issue number when an issue was created or updated this call.
func RegisterExtractor ¶
RegisterExtractor registers an extractor for a named format. Called from init() in each format package.
func RegisterRecognizer ¶
func RegisterRecognizer(provider string, kind RecognizerKind, fn func(RecognitionContext) RecognitionResult)
RegisterRecognizer adds a provider recognizer to the registry along with its declared RecognizerKind. Called from init() in per-provider recognize_*.go files.
Panics if a recognizer is already registered for the given provider — this is a programmer error caught at startup, not a recoverable runtime condition.
func RenderCandidatesTable ¶
func RenderCandidatesTable(outcomes []CandidateOutcome) string
RenderCandidatesTable renders outcomes as a markdown table for inclusion in PR bodies and GitHub issue bodies. Columns: Strategy, Candidate URL, Outcome, Status, Final URL, Detail. Redirect chains are inlined into the Final URL cell as `from -> to (302) -> to (302)`. An empty input yields an empty string so callers can omit the section entirely.
func ResolveHealFailure ¶
ResolveHealFailure clears the heal-failure counter and closes any open capmon-heal-fail issue for (provider, contentType, sourceIndex). Called when a heal attempt finally succeeds, so the next failure restarts the threshold count cleanly and reviewers don't see stale "broken" issues.
func RunCapmonCheck ¶
func RunCapmonCheck(ctx context.Context, opts CapmonCheckOptions) error
RunCapmonCheck runs the capmon check pipeline over all (or one filtered) provider format docs. It validates infrastructure, detects content drift, and creates or updates GitHub issues for each changed source.
Pipeline:
- ValidateSources for each provider (blocking)
- ValidateFormatDoc for each format doc (blocking)
- Fetch each source, compare hash, create/append issue on change
func RunExport ¶
func RunExport(opts ExportOptions) error
RunExport is the single exporter entry point used identically by the CLI, tests, and the publish workflow. It stages the complete current-major document tree in a temp dir on the same filesystem as OutDir, copies in every frozen major after verifying its recorded root hash, runs the fail-closed schema gate and provider-set assert against the staged tree, and only on full success atomically replaces OutDir. A partial or invalid export never touches a pre-existing OutDir.
func RunExportVerify ¶
RunExportVerify rebuilds the whole published site (current major, frozen majors, root index) from a source commit and diffs it byte-for-byte against the live published site under baseURL, returning nil on total byte-identity and EXPORT_004 naming the first divergent path otherwise. It is a maintainer/consumer conformance tool and is never part of the publish gate. The live current-major index.json is fetched first so GeneratedAt/SourceCommit can be pinned from it, making the comparison total byte equality on every file — that index included. docs/ and site-static/ are materialized at the commit via git archive, so the rebuild reflects the committed tree, never the working directory.
func RunFetchStage ¶
func RunFetchStage(ctx context.Context, opts PipelineOptions, manifest *RunManifest) error
RunFetchStage executes Stage 1 (fetch) only, populating manifest.Providers. Used by 'capmon fetch' to run the fetch stage without triggering extraction.
func RunFreeze ¶
func RunFreeze(opts FreezeOptions) (string, error)
RunFreeze copies the last live tree of opts.Major to opts.OutDir/<Major>/ and applies the single final mutation: status "frozen", superseded_by, and frozen_at on <Major>/index.json and on every per-provider document. Each provider document's superseded_by names its successor document (<SupersededBy>capabilities/<slug>.json, after Renames); the index's names the successor major. The provider sha256 entries in the index are updated to the mutated bytes; nothing else changes — all.json, the pivots, and data_revision keep their live bytes. The frozen tree is validated against its own pinned schemas and its root hash returned for recording in frozenMajors.
func RunPipeline ¶
func RunPipeline(ctx context.Context, opts PipelineOptions) (exitClass int, err error)
RunPipeline executes the capmon pipeline with the given options. Returns the exit class (0-5) and any fatal error.
func SanitizeExtractedString ¶
SanitizeExtractedString normalizes an extracted string value before writing to extracted.json. Exported for use by all extractor implementations.
func SanitizeSlug ¶
SanitizeSlug validates a provider slug is safe for use in branch names and PR bodies. Applied to both branch name construction and PR body construction in Stage 4.
func ScanGraduationCandidates ¶
func ScanGraduationCandidates(cacheRoot, formatDocsDir, canonicalKeysPath string, now time.Time) ([]int, error)
ScanGraduationCandidates walks provider format docs, records debounced per-(content type, extension id, provider) sightings, and files or refreshes ACIF class-c issues for extensions observed in 2 or more qualifying providers of the same content type. Extensions ACIF already covers for that content type, per canonicalKeysPath, are never sighted.
func SeedProviderCapabilities ¶
func SeedProviderCapabilities(opts SeedOptions) error
SeedProviderCapabilities creates or updates docs/provider-capabilities/<provider>.yaml from extracted data. It is idempotent: if the file already exists, extracted fields are merged in.
Extracted capability keys not registered in the canonical-key registry are routed to provider_exclusive as "<content_type>.<key>" nodes — never into content_types capabilities. Existing provider_exclusive entries are preserved: an extracted key colliding with one is skipped unless ForceOverwriteExclusive is set, in which case the colliding entries (and only those) are overwritten with a warning naming each. The section is never cleared wholesale.
func SeederSpecPath ¶
SeederSpecPath returns the conventional path for a seeder spec file given the directory, provider slug, and content type.
func SetGHCommandForTest ¶
SetGHCommandForTest replaces the gh runner with a test stub. Pass nil to restore the default. Must only be called from test code.
func SetGitHubBaseURLForTest ¶
func SetGitHubBaseURLForTest(url string)
SetGitHubBaseURLForTest overrides the GitHub API base URL in tests.
func SetGitRunnerForTest ¶
SetGitRunnerForTest swaps the git runner. Pass nil to restore default.
func SetHTTPClientForTest ¶
SetHTTPClientForTest overrides the HTTP client in tests.
func SetRedirectClientForTest ¶
SetRedirectClientForTest installs a custom *http.Client for FollowRedirectChain. Pass nil to restore the default no-follow client.
The injected client MUST set CheckRedirect to http.ErrUseLastResponse so the stdlib doesn't auto-follow redirects underneath us.
func SetValidateURLForTest ¶
SetValidateURLForTest overrides the URL validator in tests.
func UpdateCapmonProviderIssue ¶
func UpdateCapmonProviderIssue(_ context.Context, provider string, issueNum int, existingBody, body string) (bool, error)
UpdateCapmonProviderIssue refreshes the body of an existing provider anchor issue, re-prefixing the anchor so the issue stays dedup-discoverable.
When the rendered body matches existingBody the edit is skipped: the daily pipeline re-runs against providers whose issues nobody has triaged yet, and rewriting an identical body would re-notify every watcher each morning until the bot gets muted — which would recreate the very blind spot this replaced. Returns true when GitHub was actually written to.
func UpdateManifestURL ¶
func UpdateManifestURL(manifestPath, contentType string, sourceIndex int, expectedOldURL, newURL string) error
UpdateManifestURL opens the given manifest YAML, replaces the URL at content_types.<contentType>.sources[sourceIndex] with newURL, and writes the file back byte-for-byte identical except for that one line.
Returns an error if the target node is not found or the old URL at that location does not match expectedOldURL (defensive check against the manifest having been edited between fetch and heal).
func ValidateContentResponse ¶
ValidateContentResponse checks that a fetched HTTP response body represents readable, on-domain content. It performs three checks:
- Body is non-empty, and (for HTML responses only) at least minContentBytesHTML — avoids treating HTML stubs/redirect pages as valid while letting legitimate small source files pass.
- Content-Type does not indicate binary content
- The final URL's eTLD+1 matches the original URL's eTLD+1 — detects redirect-to-login domain hijacking
Returns *ErrContentInvalid for any failed check, allowing callers to distinguish content validity failures from other errors via errors.As. The Kind field on the returned error tags which check failed.
func ValidateFormatDoc ¶
ValidateFormatDoc validates a provider's format doc against the canonical keys vocabulary. It collects all errors (non-short-circuiting) and returns them as a combined error. Output uses ✓/✗ prefixes suitable for human-readable terminal output.
Validation rules:
- Required top-level fields: provider, last_fetched_at, content_types (non-empty)
- Each key in canonical_mappings must exist in canonical-keys.yaml for the content type
- Each provider_extensions entry must have: id, name, summary, source_ref, conversion
- confidence values must be confirmed | inferred | unknown
- conversion values must be translated | embedded | dropped | preserved | not-portable
- generation_method and notes are NOT validated (informational)
func ValidateSourceURL ¶
ValidateSourceURL enforces the SSRF allowlist: HTTPS only, no raw IPs, no hostnames that resolve to reserved/private address space. Must be called for every source URL at pipeline startup — NOT cached.
func ValidateSources ¶
ValidateSources validates that a provider's source manifest has at least one source URI for each content type, unless the content type is explicitly marked as not supported (supported: false). It also validates healing configuration per source.
func WriteCacheEntry ¶
func WriteCacheEntry(cacheRoot string, entry CacheEntry) error
WriteCacheEntry writes raw.bin and meta.json for one source.
func WriteCacheMeta ¶
func WriteCacheMeta(cacheRoot string, entry CacheEntry) error
WriteCacheMeta rewrites only the meta.json for an existing cache entry. Used to patch fields (Format, SourceURL) after FetchSource writes the initial entry.
func WriteRunManifest ¶
func WriteRunManifest(cacheRoot string, m RunManifest) error
WriteRunManifest persists the run manifest to <cacheRoot>/last-run.json.
func WriteSeederSpec ¶
func WriteSeederSpec(spec *SeederSpec, path string) error
WriteSeederSpec writes a SeederSpec to the given path using an atomic write (temp file → rename). This prevents partial writes from leaving a corrupt spec file if the process is interrupted.
Types ¶
type BackfillOptions ¶
type BackfillOptions struct {
// Force re-fetches and overwrites content_hash even when already populated.
Force bool
}
BackfillOptions controls BackfillFormatDoc behavior.
type BackfillResult ¶
type BackfillResult struct {
// Updated is the number of sources whose content_hash was written during this run.
Updated int
// Errors holds per-source fetch failures. A non-empty Errors slice does NOT
// abort the run — other sources still get backfilled — but the slice is also
// returned as a joined error from BackfillFormatDoc.
Errors []error
}
BackfillResult reports the outcome of a BackfillFormatDoc run.
func BackfillFormatDoc ¶
func BackfillFormatDoc(ctx context.Context, path string, fetcher SourceFetcher, opts BackfillOptions) (BackfillResult, error)
BackfillFormatDoc reads the FormatDoc YAML at path, fetches each source whose content_hash is missing or empty (or every source when opts.Force is true), and writes the computed sha256 back in place using byte-level surgery guided by yaml.Node positions. This preserves comments, blank lines, folded-scalar wrapping, and key order — only the touched lines change.
When at least one source is updated, the top-level last_fetched_at is also refreshed to the current UTC time.
type CacheEntry ¶
CacheEntry is the full in-memory representation of a cached source.
func FetchChromedp ¶
func FetchChromedp(ctx context.Context, cacheRoot, provider, sourceID, rawURL string) (*CacheEntry, error)
FetchChromedp fetches a URL using a headless Chromium browser. When CHROMEDP_URL is set, connects to a remote headless-shell sidecar. When unset, uses a local Chrome installation with stealth options to avoid bot detection (realistic UA, no automation flag, standard viewport).
After navigation, waits for JS frameworks to finish rendering before capturing the outer HTML of <body>.
func FetchGitHubFile ¶
func FetchGitHubFile(ctx context.Context, cacheRoot, provider, sourceID, owner, repo, ref, path string) (*CacheEntry, error)
FetchGitHubFile fetches a file from a GitHub repo via the Contents API, decodes base64 content, writes to cache, and returns the entry.
func FetchSource ¶
func FetchSource(ctx context.Context, cacheRoot, provider, sourceID, rawURL string) (*CacheEntry, error)
FetchSource fetches one source URL, writes to cache, and returns the entry. If content hash is unchanged from the last cached entry, returns the cached entry with Meta.Cached = true.
func ReadCacheEntry ¶
func ReadCacheEntry(cacheRoot, provider, sourceID string) (*CacheEntry, error)
ReadCacheEntry reads raw.bin and meta.json for one source.
type CacheMeta ¶
type CacheMeta struct {
FetchedAt time.Time `json:"fetched_at"`
ContentHash string `json:"content_hash"`
FetchStatus string `json:"fetch_status"`
FetchMethod string `json:"fetch_method"`
Cached bool `json:"cached,omitempty"`
// Format is the extractor format to use for this entry (e.g. "html", "json", "yaml").
// Set by the pipeline after fetching so Stage 2 knows which extractor to call.
Format string `json:"format,omitempty"`
SourceURL string `json:"source_url,omitempty"`
}
CacheMeta is the metadata stored alongside raw.bin for each fetched source.
type CandidateOutcome ¶
type CandidateOutcome struct {
URL string `json:"url"`
Strategy string `json:"strategy"`
Outcome CandidateOutcomeKind `json:"outcome"`
StatusCode int `json:"status_code,omitempty"`
FinalURL string `json:"final_url,omitempty"`
Redirects []RedirectHop `json:"redirects,omitempty"`
ContentType string `json:"content_type,omitempty"`
BodySize int `json:"body_size,omitempty"`
Detail string `json:"detail,omitempty"`
}
CandidateOutcome captures everything observed during a single candidate probe. The JSON form is persisted in the run manifest (HealEvent) and rendered into PR bodies and escalation issue bodies.
type CandidateOutcomeKind ¶
type CandidateOutcomeKind string
CandidateOutcomeKind is a closed enum tagging the outcome of probing a single heal candidate URL. Every probed candidate produces exactly one outcome; the value is what humans see in the diagnostic table when triaging drift.
const ( OutcomeSuccess CandidateOutcomeKind = "success" OutcomeRedirected CandidateOutcomeKind = "redirected" OutcomeHTTPError CandidateOutcomeKind = "http_error" OutcomeConnectError CandidateOutcomeKind = "connect_error" OutcomeBinaryContent CandidateOutcomeKind = "binary_content" OutcomeBodyTooSmall CandidateOutcomeKind = "body_too_small" OutcomeDomainMismatch CandidateOutcomeKind = "domain_mismatch" )
type CanonicalMapping ¶
type CanonicalMapping struct {
Status string `yaml:"status"`
SourceForm string `yaml:"source_form,omitempty"`
MechanismToken string `yaml:"mechanism_token,omitempty"`
Mechanism string `yaml:"mechanism"`
Paths []string `yaml:"paths,omitempty"`
Confidence string `yaml:"confidence"`
ProviderField string `yaml:"provider_field,omitempty"`
ExtensionID string `yaml:"extension_id,omitempty"`
}
CanonicalMapping records how a provider implements a canonical capability key. The canonical key itself is the map key in ContentTypeFormatDoc.CanonicalMappings.
Status classifies the relationship (absent | mapped | unmapped); see the MappingStatus constants.
SourceForm is required when Status is "unmapped": it is the verbatim minimal provider content snippet exhibiting the unmapped mechanism — canonicalizer- feedable input, NOT a prose description (prose belongs in Mechanism). The deferred Class B confirmation step runs a conforming canonicalizer over this snippet to confirm the totality-net diagnostic before any filing.
MechanismToken is the curator's source-mechanism token claim for a status:"unmapped" entry, when the mechanism is nameable in ACIF's published source-mechanism vocabulary (conformance/source-mechanisms.yaml). Optional — leave empty when no token plausibly names the mechanism. Consumed by `capmon acif-change confirm`: a claimed token that is a member of the export with recognition_requiring:false is machine-rejected as already-mapped. Only meaningful when Status is "unmapped".
ProviderField names the actual native field (frontmatter key, config key, TOML field, dot-notation path) when the mapping corresponds to a specific named field. Omitted when the mapping is structural or behavioral.
ExtensionID points to a ProviderExtension entry that describes the same concept in provider-specific detail. The component renders one unified row when set. The canonical mapping is the authority; the extension is the detail — so the authority points to the detail, not the other way around.
type CapabilityDiff ¶
type CapabilityDiff struct {
Provider string `json:"provider"`
RunID string `json:"run_id"`
Changes []FieldChange `json:"changes"`
StructuralDrift []string `json:"structural_drift,omitempty"`
ProposedYAMLPatch string `json:"proposed_yaml_patch,omitempty"`
}
CapabilityDiff is the Stage 3 output: structured diff + proposed YAML patch.
func DiffLandmarks ¶
func DiffLandmarks(provider, runID string, extracted, known []string) CapabilityDiff
DiffLandmarks compares extracted document landmarks against known landmarks in the YAML. New landmarks (headings not in knownLandmarks) are returned as structural drift entries.
func DiffProviderCapabilities ¶
func DiffProviderCapabilities(provider, runID string, extracted *ExtractedSource, current map[string]string) CapabilityDiff
DiffProviderCapabilities compares extracted fields against the current capability YAML values. current is a map of dot-delimited field paths to their string values from the YAML.
type CapmonCheckOptions ¶
type CapmonCheckOptions struct {
// FormatsDir is the directory containing provider format doc YAML files
// (default: "docs/provider-formats").
FormatsDir string
// SourcesDir is the directory containing provider source manifests
// (default: "docs/provider-sources").
SourcesDir string
// CacheRoot is the root of the capmon cache (default: ".capmon-cache").
CacheRoot string
// CanonicalKeysPath is the path to canonical-keys.yaml
// (default: "docs/spec/canonical-keys.yaml").
CanonicalKeysPath string
// ProviderFilter limits the run to a single provider slug. Empty means all.
ProviderFilter string
// DryRun logs actions but makes no GitHub API calls.
DryRun bool
}
CapmonCheckOptions configures a RunCapmonCheck run.
type ConfirmEvidence ¶
type ConfirmEvidence struct {
ExportRev string `json:"export_rev,omitempty"`
AdapterProtocol int `json:"adapter_protocol,omitempty"`
Implementation string `json:"implementation,omitempty"`
ImplVersion string `json:"impl_version,omitempty"`
AdapterResponse string `json:"adapter_response,omitempty"`
SourceForm string `json:"source_form,omitempty"`
}
ConfirmEvidence pins everything a human needs to audit a machine verdict.
type ConfirmFinding ¶
type ConfirmFinding struct {
Provider string `json:"provider"`
ContentType string `json:"content_type"`
CanonicalKey string `json:"canonical_key"`
MechanismToken string `json:"mechanism_token,omitempty"`
Verdict string `json:"verdict"`
Reason string `json:"reason"`
Detail string `json:"detail,omitempty"`
Degraded bool `json:"degraded,omitempty"`
IssueNumber int `json:"issue_number,omitempty"`
Evidence ConfirmEvidence `json:"evidence"`
}
ConfirmFinding is the machine verdict for one status:unmapped candidate.
type ConfirmOptions ¶
type ConfirmOptions struct {
FormatDocsDir string
CacheRoot string
ExportPath string
ExportRev string
AdapterPath string
ProbeTimeout time.Duration // per adapter request; defaults to 30s
Now time.Time
}
ConfirmOptions configures one `capmon acif-change confirm` run.
ExportPath is a local copy of ACIF's conformance/source-mechanisms.yaml; the caller fetches it pinned to a git rev and passes that rev as ExportRev, which is embedded verbatim in all evidence (mirrors how the drift check consumes capability-vocabulary.yaml).
AdapterPath is an executable speaking conformance adapter protocol 2 (one JSON request per line on stdin, one response per line on stdout, "hello" first). It must claim the hook scope. Empty means no probe is available: probe-requiring candidates land unconfirmed.
type ConfirmResult ¶
type ConfirmResult struct {
Findings []ConfirmFinding
Degraded bool
}
ConfirmResult is the outcome of a confirm run. Degraded reports that at least one candidate landed unconfirmed through a degraded path (export unreadable, adapter down or timed out, unparsable source form) — callers should signal it via the exit code so operators notice.
func ConfirmUnmappedCandidates ¶
func ConfirmUnmappedCandidates(opts ConfirmOptions) (*ConfirmResult, error)
ConfirmUnmappedCandidates walks provider format docs, machine-checks every status:unmapped canonical mapping against the ACIF source-mechanism export (plus a hook probe for shape-predicate mechanisms), and acts on the verdicts: reject → confirm-report state entry only (curator YAML and the event-sourced RecordUnmappedForm counters are never touched); unconfirmed → file or refresh a needs-human issue on the ACIF repo with pinned evidence.
HARD INVARIANT (fail-toward-unconfirmed): every degraded path lands the candidate at unconfirmed, never reject and never a silent drop. Suppressing a true vocabulary gap is invisible; filing a false candidate is a bounded ticket.
type ConsideredCandidate ¶
ConsideredCandidate is one ranked replacement a strategy proposed, whether or not it was probed. Reason carries the strategy's own explanation — for github-rename that is the stem and path similarity scores, which is what lets a reviewer see whether the winner won comfortably or by a hair.
type ContentTypeFormatDoc ¶
type ContentTypeFormatDoc struct {
Status string `yaml:"status"`
Sources []SourceRef `yaml:"sources"`
CanonicalMappings map[string]CanonicalMapping `yaml:"canonical_mappings"`
ProviderExtensions []ProviderExtension `yaml:"provider_extensions"`
LoadingModel string `yaml:"loading_model"`
Notes string `yaml:"notes"`
}
ContentTypeFormatDoc describes how a provider supports a single content type (e.g., "skills").
type ContentTypeSource ¶
type ContentTypeSource struct {
Supported *bool `yaml:"supported,omitempty"`
Convention string `yaml:"convention,omitempty"`
Sources []SourceEntry `yaml:"sources"`
}
ContentTypeSource groups all source entries for one content type. Supported is a pointer to distinguish "not specified" from explicitly false. When Supported is explicitly false, the content type is not supported by this provider and source URI checks are skipped.
Convention names a cross-provider implementation pattern (e.g. cross-provider-agents-md, cross-provider-skill-md) when the provider has no native upstream documentation to monitor. Setting Convention satisfies the validator's "must have sources" requirement for content types implemented purely via convention.
type DefaultSourceFetcher ¶
type DefaultSourceFetcher struct{}
DefaultSourceFetcher routes by fetch_method: "chromedp" goes through a headless browser, everything else through HTTP GET.
type DocsConventions ¶
type DocsConventions struct {
// QueryParamRequired is the literal query-string fragment (e.g.
// "?internal") that must be present on every doc URL fetched from this
// provider. Currently informational — read by operator tooling when
// proposing replacement URLs. Not auto-applied at fetch time;
// manifest URLs stay literal.
QueryParamRequired string `yaml:"query_param_required,omitempty"`
// AuthGatedPaths lists path substrings that, if a redirect lands on
// them, mean the candidate URL doesn't really exist for unauthenticated
// callers. Used by the heal pipeline to enrich the redirect diagnostic
// Detail so triagers see "auth gate" rather than just "redirected".
// Does NOT change correctness — any redirect on a heal candidate is
// already rejected (see qc7yf). This is human-triage signal only.
AuthGatedPaths []string `yaml:"auth_gated_paths,omitempty"`
// RetiredPaths lists URL paths the variant generator must NOT propose
// replacements for. Known-dead paths whose 404 is a permanent fact (the
// content moved to a query-param-gated section, an in-page anchor, or
// was removed outright). Matching is exact path equality against the
// candidate URL's path.
RetiredPaths []string `yaml:"retired_paths,omitempty"`
}
DocsConventions carries provider-specific URL hints used by the heal pipeline and operator tooling. All fields are optional; the schema is designed to accrete new fields per-provider as quirks surface (Cursor docs versioning, Cline auth-gated changelog, etc.).
This block is provider-wide, not per-content-type — conventions like "always append ?internal" apply to every doc URL on the host.
type ErrContentInvalid ¶
type ErrContentInvalid struct {
Kind InvalidKind
Reason string
}
ErrContentInvalid is returned by ValidateContentResponse when the fetched content fails one of the readability checks. It carries a Reason field for human-readable diagnostics and a Kind for machine routing; distinguishable via errors.As.
func (*ErrContentInvalid) Error ¶
func (e *ErrContentInvalid) Error() string
type ErrNoExtractor ¶
type ErrNoExtractor struct {
Format string
}
ErrNoExtractor is returned by Extract when no extractor is registered for the format. Callers should treat this as a capability gap (skip + warn), not a failure.
func (*ErrNoExtractor) Error ¶
func (e *ErrNoExtractor) Error() string
type ExportOptions ¶
type ExportOptions struct {
CapsDir string
CanonicalKeysPath string
SourcesDir string
PublishAssetsDir string
OutDir string
// StaticDir holds the frozen majors (site-static/), copied verbatim into
// the export after their root hashes verify.
StaticDir string
SourceCommit string
GeneratedAt string
}
ExportOptions carries every source path and run-varying value the exporter needs. All source locations are parameterized so tests can point at fixture dirs; GeneratedAt and SourceCommit are passed through verbatim — the exporter never calls time.Now() and never shells out to git.
type ExtensionExample ¶
type ExtensionExample struct {
Title string `yaml:"title,omitempty"`
Lang string `yaml:"lang"`
Code string `yaml:"code"`
Note string `yaml:"note,omitempty"`
}
ExtensionExample is a runnable snippet attached to a provider extension. Examples let the provider pages render copyable code blocks beside each capability so readers can see the syntax in context.
type ExtractedSource ¶
type ExtractedSource struct {
ExtractorVersion string `json:"extractor_version"`
Provider string `json:"provider"`
SourceID string `json:"source_id"`
Format string `json:"format"`
ExtractedAt time.Time `json:"extracted_at"`
Partial bool `json:"partial"`
Fields map[string]FieldValue `json:"fields"`
Landmarks []string `json:"landmarks"`
}
ExtractedSource is the Stage 2 output for one source document. capmon: pipeline-internal volatile state, no schema_version
func Extract ¶
func Extract(ctx context.Context, format string, raw []byte, cfg SelectorConfig) (*ExtractedSource, error)
Extract dispatches to the appropriate Extractor for the given format.
type Extractor ¶
type Extractor interface {
Extract(ctx context.Context, raw []byte, cfg SelectorConfig) (*ExtractedSource, error)
}
Extractor extracts structured fields from raw source bytes. Each format (html, markdown, typescript, etc.) registers its own implementation.
type FieldChange ¶
type FieldChange struct {
FieldPath string `json:"field_path"`
OldValue string `json:"old_value"`
NewValue string `json:"new_value"`
}
FieldChange describes a single field mutation detected in Stage 3.
type FieldValue ¶
FieldValue is an extracted scalar with its SHA-256 fingerprint.
type FormatDoc ¶
type FormatDoc struct {
Provider string `yaml:"provider"`
DocsURL string `yaml:"docs_url"`
Category string `yaml:"category"`
LastFetchedAt string `yaml:"last_fetched_at"`
LastChangedAt string `yaml:"last_changed_at"`
GenerationMethod string `yaml:"generation_method"`
ContentTypes map[string]ContentTypeFormatDoc `yaml:"content_types"`
}
FormatDoc is the top-level structure of a provider format document (docs/provider-formats/<slug>.yaml). It captures how a provider implements each content type, which canonical keys it supports, and any provider-specific extensions that have no canonical equivalent yet.
func LoadFormatDoc ¶
LoadFormatDoc reads and unmarshals a format doc YAML file.
type FreezeOptions ¶
type FreezeOptions struct {
// Major is the prefix being frozen, e.g. "v1".
Major string
// FromDir is an exported site root holding <Major>/ — the last live tree.
FromDir string
// OutDir is the static root the frozen tree lands under (site-static).
OutDir string
// SupersededBy is the successor major's path, e.g. "/v2/".
SupersededBy string
// FrozenAt is the RFC 3339 UTC freeze timestamp.
FrozenAt string
// Renames maps an old-major slug to its successor-major slug, so the
// vacated slug's document points at the doc that replaced it (ADR 0013).
Renames map[string]string
}
FreezeOptions parameterizes RunFreeze.
type GoStructOptions ¶
type GoStructOptions struct {
// ContentType is the top-level dot-path prefix: "skills", "rules", etc.
ContentType string
// StructPrefixes is the explicit allow-list of field-key prefixes to recognize.
// Each entry behaves like the old single-prefix StructPrefix — the OR of all
// entries is matched. Mutually exclusive with PrefixMatcher.
StructPrefixes []string
// PrefixMatcher is the escape hatch: a function that returns true for keys
// the recognizer should process. Mutually exclusive with StructPrefixes.
PrefixMatcher func(key string) bool
// KeyMapper converts a YAML key name to a canonical capability key.
// Unknown keys should be returned as-is.
KeyMapper func(yamlKey string) string
// MechanismPrefix is prepended to the YAML key in the mechanism string.
// Defaults to "yaml frontmatter key: " when empty.
MechanismPrefix string
}
GoStructOptions configures recognizeGoStruct for a specific content type. Each content type (skills, rules, hooks, …) has its own struct prefix in the extracted cache (e.g., "Skill." for skills, "Rule." for rules) and its own YAML-key-to-canonical-key mapping.
Prefix selection: exactly one of StructPrefixes or PrefixMatcher MUST be set. Validation runs at recognizer call time; misconfiguration panics with a descriptive message (programmer error, not a recoverable runtime condition).
- StructPrefixes is the explicit allow-list — preferred for the 95% case including multi-struct sources like codex (PR3) where a fixed set of struct names is known and a few related names must be excluded.
- PrefixMatcher is the escape hatch for arbitrary matching logic (regex, runtime computation, etc.). Use only when the allow-list cannot express the requirement.
func SkillsGoStructOptions ¶
func SkillsGoStructOptions() GoStructOptions
SkillsGoStructOptions returns the preset GoStructOptions for providers that implement the Agent Skills open standard (crush, roo-code, and any provider whose skills format mirrors the standard's Skill struct).
type HTTPDoer ¶
HTTPDoer is the minimal client surface CheckFetch needs; callers pass their own (test-overridable) client.
type HashURLResult ¶
HashURLResult carries what `capmon hash-url` reports for one fetch.
func HashURL ¶
func HashURL(ctx context.Context, rawURL string) (HashURLResult, error)
HashURL fetches rawURL exactly as the drift check does (fetchForCheck) and returns the canonical content hash with fetch metadata. It exists so curation can compute valid baselines without replicating the check path's header behavior by hand — curl is NOT byte-equivalent on every host.
type HealEvent ¶
type HealEvent struct {
ContentType string `json:"content_type"`
SourceIndex int `json:"source_index"`
OldURL string `json:"old_url"`
NewURL string `json:"new_url,omitempty"`
Strategy string `json:"strategy,omitempty"`
Success bool `json:"success"`
PRURL string `json:"pr_url,omitempty"`
IssueNumber int `json:"issue_number,omitempty"`
FailReason string `json:"fail_reason,omitempty"`
CandidateOutcomes []CandidateOutcome `json:"candidate_outcomes,omitempty"`
StrategyDeclines []string `json:"strategy_declines,omitempty"`
}
HealEvent is a record of one healing attempt made during Stage 1 Fetch. Both success and failure produce events so the run manifest carries a complete audit trail.
type HealPRInputs ¶
type HealPRInputs struct {
ManifestPath string // absolute path to docs/provider-sources/<slug>.yaml
Provider string // sanitized slug
ContentType string // e.g. "skills"
SourceIndex int // index into content_types.<ct>.sources
RunID string // unique per pipeline run (short SHA or timestamp)
OldURL string
Heal HealResult
}
HealPRInputs bundles everything needed to open a heal PR. Kept as a single struct so the callsite (pipeline.go Stage 1) doesn't need to thread six parameters.
type HealResult ¶
type HealResult struct {
Success bool
NewURL string
Strategy string
Proof string // short human-readable explanation for PR body
CandidateOutcomes []CandidateOutcome // every probed candidate, in attempt order
StrategyDeclines []string `json:"strategy_declines,omitempty"` // strategy-level decline reasons (e.g., "redirect: chain contains a temporary (302/307) redirect"), populated regardless of whether candidates were probed
FailReason string // populated when Success=false — derived summary or strategy-level decline
// Considered lists every candidate a strategy ranked, in rank order,
// including candidates never probed because an earlier one validated.
// CandidateOutcomes only records what was probed, and probing stops at the
// first success — so on the single-candidate-succeeds path the PR body had
// nothing to show but the answer itself. That is the path most likely to be
// wrong (ADR-0014), so the reviewer needs to see what it beat.
Considered []ConsideredCandidate `json:"considered,omitempty"`
}
HealResult captures the outcome of an AttemptHeal call. Success is true only when a candidate URL was found AND its content passed ValidateContentResponse with zero redirects observed during the fetch. CandidateOutcomes records every probe in order so humans triaging drift can see what each strategy turned up.
func AttemptHeal ¶
func AttemptHeal(ctx context.Context, src SourceEntry, conventions *DocsConventions, fetchErr error) (*HealResult, error)
AttemptHeal runs the configured healing strategies in order for a source whose fetch just failed. Returns a HealResult whose Success flag indicates whether a verified replacement was found.
Ordering is taken from src.EffectiveStrategies() — callers cannot bypass opt-out (healing.enabled=false causes AttemptHeal to return Success=false with a FailReason explaining the skip, never an error).
conventions, when non-nil, applies provider-specific URL hints from the source manifest's docs_conventions block: variant candidates matching RetiredPaths are dropped before probing, and OutcomeRedirected outcomes are enriched with an "auth gate" detail when the final URL matches an AuthGatedPaths substring. Conventions never change success/failure outcomes — they only filter inputs and annotate diagnostics.
The orchestrator never mutates src. All new URLs are proposed via the PR flow downstream of this call.
type HealingConfig ¶
type HealingConfig struct {
Enabled *bool `yaml:"enabled,omitempty"`
Strategies []string `yaml:"strategies,omitempty"`
}
HealingConfig controls reactive URL healing behavior for a single source. When nil or unset, reactive healing runs with all default strategies. Set Enabled=false to opt out — useful for stable sources that should fail loudly.
type InvalidKind ¶
type InvalidKind string
InvalidKind tags the specific reason ValidateContentResponse rejected a response. Heal callers map this 1:1 onto CandidateOutcomeKind so the reason for rejection can be reported structurally (without parsing the human-readable Reason string).
const ( InvalidBinaryContent InvalidKind = "binary_content" InvalidBodyTooSmall InvalidKind = "body_too_small" InvalidDomainMismatch InvalidKind = "domain_mismatch" )
type LandmarkOptions ¶
type LandmarkOptions struct {
// ContentType is the top-level dot-path prefix: "skills", "rules", etc.
ContentType string
// Patterns is the ordered list of capability detection rules.
Patterns []LandmarkPattern
}
LandmarkOptions configures recognizeLandmarks for a specific content type.
func AgentsLandmarkOptions ¶
func AgentsLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
AgentsLandmarkOptions builds a LandmarkOptions targeting the agents content type from the supplied patterns. It validates every pattern's Capability against CanonicalAgentsKeys (empty Capability is allowed — that pattern only contributes to the top-level agents.supported emission) and panics on any unknown key. The panic surfaces typos at recognizer registration time, not silently at extraction time.
For object-typed canonical keys (invocation_patterns, agent_scopes), Capability MAY use a dot-separated form like "invocation_patterns.at_mention" or "agent_scopes.project". Validation only checks the first segment.
func CommandsLandmarkOptions ¶
func CommandsLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
CommandsLandmarkOptions builds a LandmarkOptions targeting the commands content type from the supplied patterns. It validates every pattern's Capability against CanonicalCommandsKeys (empty Capability is allowed — that pattern only contributes to the top-level commands.supported emission) and panics on any unknown key. The panic surfaces typos at recognizer registration time, not silently at extraction time.
For object-typed canonical keys (argument_substitution), Capability MAY use a dot-separated form like "argument_substitution.dollar_arguments". Validation only checks the first segment.
func HooksLandmarkOptions ¶
func HooksLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
HooksLandmarkOptions builds a LandmarkOptions targeting the hooks content type from the supplied patterns. It validates every pattern's Capability against CanonicalHooksKeys (empty Capability is allowed — that pattern only contributes to the top-level hooks.supported emission) and panics on any unknown key. The panic surfaces typos at recognizer registration time, not silently at extraction time.
For object-typed canonical keys (handler_types, decision_control, hook_scopes), Capability MAY use a dot-separated form like "decision_control.block" or "hook_scopes.project". Validation only checks the first segment.
func McpLandmarkOptions ¶
func McpLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
McpLandmarkOptions builds a LandmarkOptions targeting the mcp content type from the supplied patterns. It validates every pattern's Capability against CanonicalMcpKeys (empty Capability is allowed — that pattern only contributes to the top-level mcp.supported emission) and panics on any unknown key. The panic surfaces typos at recognizer registration time, not silently at extraction time.
For object-typed canonical keys (transport_types, tool_filtering), Capability MAY use a dot-separated form like "transport_types.stdio" or "tool_filtering.allowlist". Validation only checks the first segment.
func RulesLandmarkOptions ¶
func RulesLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
RulesLandmarkOptions builds a LandmarkOptions targeting the rules content type from the supplied patterns. It validates every pattern's Capability against CanonicalRulesKeys (empty Capability is allowed — that pattern only contributes to the top-level rules.supported emission) and panics on any unknown key. The panic surfaces typos at recognizer registration time, not silently at extraction time.
For object-typed canonical keys (activation_mode, cross_provider_recognition), Capability MAY use a dot-separated form like "activation_mode.always" or "cross_provider_recognition.agents_md". Validation only checks the first segment.
func SkillsLandmarkOptions ¶
func SkillsLandmarkOptions(patterns ...LandmarkPattern) LandmarkOptions
SkillsLandmarkOptions builds a LandmarkOptions targeting the skills content type from the supplied patterns. It validates every pattern's Capability against CanonicalSkillsKeys (empty Capability is allowed — that pattern only contributes to the top-level skills.supported emission) and panics on any unknown key. The panic surfaces typos at recognizer registration time, not silently at extraction time.
For object-typed canonical keys (compatibility, metadata_map), Capability MAY use a dot-separated form like "compatibility.platforms" or "metadata_map.custom". Validation only checks the first segment.
type LandmarkPattern ¶
type LandmarkPattern struct {
// Capability is the canonical capability key segment (e.g., "frontmatter",
// "project_scope"). When empty, the pattern only contributes to the
// top-level <content_type>.supported = "true" emission.
Capability string
// Matchers must contain at least one entry. If any entry matches a landmark,
// the capability is detected (provided Required also passes).
Matchers []StringMatcher
// Required is the optional anchor set — every entry must match some landmark
// or the capability is suppressed. Empty Required means no anchor guard
// (the pattern fires on Matchers alone).
Required []StringMatcher
// Mechanism populates the .mechanism dot-path. Required when Capability is set.
Mechanism string
}
LandmarkPattern declares one capability detection rule for landmark-based recognizers (RecognizerKindDoc). One pattern produces zero or one capability.
Semantics:
- Required is the AND-anchor set. Every entry MUST find at least one landmark in the input or the pattern is suppressed and its anchors are reported under MissingAnchors. Required is the false-positive guardrail — it prevents a passing mention of "skill" from triggering the capability.
- Matchers is the OR-trigger set. If ANY entry matches a landmark in the input (and Required passed), the capability is emitted with confidence "inferred" and the matched landmark recorded under MatchedAnchors.
- Scope is an optional dot-path extension under <content_type>.capabilities. When empty, the capability is emitted at <content_type>.supported only.
- Mechanism is the human-readable explanation written to <content_type>.capabilities.<scope>.mechanism.
func AgentsLandmarkPattern ¶
func AgentsLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
AgentsLandmarkPattern is the convenience constructor for the common single-anchor case-insensitive substring match. Every documentation-source agents recognizer wires up several of these — inlining the StringMatcher literal at every call site obscures intent.
canonicalKey is the canonical agents key (validated by AgentsLandmarkOptions when the returned pattern is registered). anchor is the substring expected in some landmark heading. mechanism is the human-readable explanation written to the .mechanism dot-path. required is the optional anchor guard shared across patterns in the same recognizer (typically the provider's "Subagents" or "Agents" section heading) — pass nil when no guard is needed.
func CommandsLandmarkPattern ¶
func CommandsLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
CommandsLandmarkPattern is the convenience constructor for the common single-anchor case-insensitive substring match. Every documentation-source commands recognizer wires up several of these — inlining the StringMatcher literal at every call site obscures intent.
canonicalKey is the canonical commands key (validated by CommandsLandmarkOptions when the returned pattern is registered). anchor is the substring expected in some landmark heading. mechanism is the human-readable explanation written to the .mechanism dot-path. required is the optional anchor guard shared across patterns in the same recognizer (typically the provider's "Slash Commands" or "Commands" section heading) — pass nil when no guard is needed.
func HooksLandmarkPattern ¶
func HooksLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
HooksLandmarkPattern is the convenience constructor for the common single-anchor case-insensitive substring match. Every documentation-source hooks recognizer wires up several of these — inlining the StringMatcher literal at every call site obscures intent.
canonicalKey is the canonical hooks key (validated by HooksLandmarkOptions when the returned pattern is registered). anchor is the substring expected in some landmark heading. mechanism is the human-readable explanation written to the .mechanism dot-path. required is the optional anchor guard shared across patterns in the same recognizer (typically the provider's "Hooks" section heading) — pass nil when no guard is needed.
func McpLandmarkPattern ¶
func McpLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
McpLandmarkPattern is the convenience constructor for the common single-anchor case-insensitive substring match. Every documentation-source MCP recognizer wires up several of these — inlining the StringMatcher literal at every call site obscures intent.
canonicalKey is the canonical MCP key (validated by McpLandmarkOptions when the returned pattern is registered). anchor is the substring expected in some landmark heading. mechanism is the human-readable explanation written to the .mechanism dot-path. required is the optional anchor guard shared across patterns in the same recognizer (typically the provider's "MCP" section heading) — pass nil when no guard is needed.
func RulesLandmarkPattern ¶
func RulesLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
RulesLandmarkPattern is the convenience constructor for the common single-anchor case-insensitive substring match. Every documentation-source rules recognizer wires up several of these — inlining the StringMatcher literal at every call site obscures intent.
canonicalKey is the canonical rules key (validated by RulesLandmarkOptions when the returned pattern is registered). anchor is the substring expected in some landmark heading. mechanism is the human-readable explanation written to the .mechanism dot-path. required is the optional anchor guard shared across patterns in the same recognizer (typically the provider's "Rules" section heading) — pass nil when no guard is needed.
func SkillsLandmarkPattern ¶
func SkillsLandmarkPattern(canonicalKey, anchor, mechanism string, required []StringMatcher) LandmarkPattern
SkillsLandmarkPattern is the convenience constructor for the common single-anchor case-insensitive substring match. Every documentation-source skills recognizer wires up several of these — inlining the StringMatcher literal at every call site obscures intent.
canonicalKey is the canonical skills key (validated by SkillsLandmarkOptions when the returned pattern is registered). anchor is the substring expected in some landmark heading. mechanism is the human-readable explanation written to the .mechanism dot-path. required is the optional anchor guard shared across patterns in the same recognizer (typically the provider's "Skills" section heading) — pass nil when no guard is needed.
type OnboardOptions ¶
type OnboardOptions struct {
// Provider is the slug of the provider being onboarded (required).
Provider string
// SourcesDir is the directory containing provider source manifests.
SourcesDir string
// FormatsDir is the directory containing provider format docs (unused in
// onboard but accepted for parity with check options).
FormatsDir string
// CacheRoot is the root of the capmon cache.
CacheRoot string
// DryRun logs actions but makes no GitHub API calls.
DryRun bool
}
OnboardOptions configures an OnboardProvider run.
type PipelineOptions ¶
type PipelineOptions struct {
// ProviderFilter limits execution to a single provider slug. Empty = all providers.
ProviderFilter string
// Stage controls which pipeline stages run.
// "": all stages (1-4)
// "fetch-extract": stages 1-2 only
// "report": stages 3-4 only
Stage string
// DryRun prevents Stage 4 from creating PRs/issues; writes report to w instead.
DryRun bool
// CacheRoot is the path to .capmon-cache/. Defaults to ".capmon-cache".
CacheRoot string
// SourceManifestsDir is the path to docs/provider-sources/. Defaults to "docs/provider-sources".
SourceManifestsDir string
// CapabilitiesDir is the path to docs/provider-capabilities/. Defaults to "docs/provider-capabilities".
CapabilitiesDir string
// RepoRoot is the directory used as the working directory for git/gh
// commands. Defaults to ".". Used by reactive healing to open PRs that
// update source manifests.
RepoRoot string
// ProgressFn is called after each source is successfully fetched in Stage 1.
// cached is true when the source content matched the existing cache entry.
// Set to nil to disable per-source progress callbacks.
ProgressFn func(providerSlug, sourceID string, cached bool)
}
PipelineOptions controls which stages run and pipeline behavior.
type ProposedMapping ¶
type ProposedMapping struct {
CanonicalKey string `yaml:"canonical_key"`
Supported bool `yaml:"supported"`
Mechanism string `yaml:"mechanism"`
SourceField string `yaml:"source_field"`
SourceValue string `yaml:"source_value"`
Confidence string `yaml:"confidence"` // confirmed | inferred | unknown | ""
Notes string `yaml:"notes,omitempty"`
}
ProposedMapping describes how a single canonical capability key maps to a provider's native format fields.
type ProviderExtension ¶
type ProviderExtension struct {
ID string `yaml:"id"`
Name string `yaml:"name"`
Summary string `yaml:"summary"`
SourceRef string `yaml:"source_ref"`
GraduationCandidate bool `yaml:"graduation_candidate"`
GraduationNotes string `yaml:"graduation_notes,omitempty"`
Required *bool `yaml:"required"`
ValueType string `yaml:"value_type,omitempty"`
Examples []ExtensionExample `yaml:"examples,omitempty"`
ProviderField string `yaml:"provider_field,omitempty"`
Conversion string `yaml:"conversion"`
}
ProviderExtension captures a provider-specific capability that has no canonical key yet. Each extension has a stable ID for structural diff (detecting new additions across runs), a source reference pointing to where the capability was found, and a graduation candidate flag indicating whether the capability may be common enough across providers to warrant a canonical key.
Summary is one sentence (~150 chars max) describing what the feature is. Deep explanations belong on the page linked by SourceRef. (Replaces the longer Description field used in earlier schema versions.)
ProviderField names the actual native field when the extension describes a frontmatter key, config key, or TOML field. Also serves as the UI grouping signal: entries with ProviderField appear in "fields"; entries without it in "other".
Conversion declares what happens to the feature during format conversion. Must be one of: translated | embedded | dropped | preserved | not-portable.
type ProviderStatus ¶
type ProviderStatus struct {
Slug string `json:"slug,omitempty"`
Errors []string `json:"errors,omitempty"`
Warnings []string `json:"warnings,omitempty"`
SourcesFetched int `json:"sources_fetched,omitempty"`
SourcesCacheHit int `json:"sources_cache_hit,omitempty"`
SourcesExtracted int `json:"sources_extracted,omitempty"`
SourceResults []SourceResult `json:"source_results,omitempty"`
SourcesSkipped int `json:"sources_skipped,omitempty"`
NeedsBaseline bool `json:"needs_baseline,omitempty"`
HasDrift bool `json:"has_drift,omitempty"`
Diff *CapabilityDiff `json:"diff,omitempty"`
FetchStatus string `json:"fetch_status"`
ExtractStatus string `json:"extract_status"`
DiffStatus string `json:"diff_status"`
ActionTaken string `json:"action_taken"`
FixtureAgeDays *int `json:"fixture_age_days"`
HealEvents []HealEvent `json:"heal_events,omitempty"`
}
ProviderStatus tracks per-provider pipeline state for the RunManifest.
type RecognitionContext ¶
type RecognitionContext struct {
// Fields is the typed-code field map (e.g., "Skill.Name" → "name") produced by extractors.
Fields map[string]FieldValue
// Landmarks is the ordered list of structural anchors (e.g., heading titles, struct type names)
// produced by extractors. Empty for sources that have no landmark concept.
Landmarks []string
// Format is the extractor format identifier ("go", "rust", "typescript", "markdown", "html", …).
// Recognizers MAY branch on this when they need format-aware behavior, but most do not.
Format string
// Provider is the provider slug (e.g., "claude-code"). Present so generic helpers can
// log without requiring callers to thread a separate parameter.
Provider string
// SourceID identifies which extracted source produced these fields when a provider has
// multiple sources merged into one context. Empty when not applicable.
SourceID string
// Partial is true when the upstream extractor flagged this source as incomplete.
// Recognizers SHOULD downgrade confidence or skip emission when Partial is true.
Partial bool
}
RecognitionContext is the read-only input passed to every recognizer. Carries extracted fields, landmarks, and source metadata. Recognizers MUST treat this struct as read-only and MUST NOT retain references to its slices or maps across calls — see the package doc comment for the full conformance contract.
type RecognitionResult ¶
type RecognitionResult struct {
// Capabilities is the dot-path → value map consumed by the YAML writer.
// Keys MUST match ^[a-z_]+(\.[a-z_]+)*$ (enforced by TestRecognitionConformance_KeyRegex).
Capabilities map[string]string
// Status reports the recognizer's pipeline state:
// "recognized" — capabilities emitted (Capabilities non-empty)
// "anchors_missing" — required landmark anchors absent; capabilities suppressed
// "not_evaluated" — recognizer ran but produced no signal (e.g., no matching fields)
Status string
// MissingAnchors lists the named anchors a landmark-based recognizer required but did
// not find. Empty for non-landmark recognizers and for "recognized" results.
MissingAnchors []string
// MatchedAnchors lists the named anchors a landmark-based recognizer successfully matched.
// Useful for downstream observability; empty for non-landmark recognizers.
MatchedAnchors []string
}
RecognitionResult is the structured output of a recognizer. Returning a single struct (instead of a bare map) makes every recognizer surface the three-state status pipeline ("recognized" | "anchors_missing" | "not_evaluated") alongside its capability dot-paths.
Why a struct, not (map, error): recognizers are pure pattern-matching functions — there are no recoverable errors. The "did this fire?" signal needs to be surfaced to downstream observability without forcing every caller to introspect map size.
func RecognizeWithContext ¶
func RecognizeWithContext(provider string, ctx RecognitionContext) RecognitionResult
RecognizeWithContext dispatches to the registered recognizer for the provider using the structured RecognitionContext / RecognitionResult shape. This is the preferred entry point for new callers that need to observe the Status and MissingAnchors fields (added in PR4 for landmark-based recognition).
If no recognizer is registered for the provider, logs a warning and returns an empty result with Status == "not_evaluated".
type RecognizerKind ¶
type RecognizerKind int
RecognizerKind tags the recognition strategy a registered recognizer uses. Stored alongside the function in the registry for downstream tooling (capmon doctor, drift dashboards) that wants to slice metrics by strategy.
const ( // RecognizerKindUnknown is the zero value; a recognizer registered without a kind // is treated as Unknown and surfaces a warning in capmon health checks. RecognizerKindUnknown RecognizerKind = iota // RecognizerKindGoStruct matches typed Go struct fields via StructPrefixes. RecognizerKindGoStruct // RecognizerKindRustStruct matches typed Rust struct fields via StructPrefixes // (or PrefixMatcher for multi-struct allow-lists like codex). RecognizerKindRustStruct // RecognizerKindTSInterface matches typed TypeScript interface fields via StructPrefixes. RecognizerKindTSInterface // RecognizerKindDoc matches landmark/heading patterns from documentation-only sources // where there is no typed source code to extract. RecognizerKindDoc )
func RecognizerKindFor ¶
func RecognizerKindFor(provider string) RecognizerKind
RecognizerKindFor returns the declared RecognizerKind for the given provider, or RecognizerKindUnknown when no recognizer is registered.
func (RecognizerKind) String ¶
func (k RecognizerKind) String() string
String returns the lowercase form used in metrics and registry doctor output.
type RedirectChain ¶
type RedirectChain struct {
StartURL string
FinalURL string
Hops []RedirectHop
Permanent bool
TerminatingStatus int `json:"terminating_status,omitempty"`
}
RedirectChain is the result of walking an HTTP redirect chain manually. Each Hop is one response whose Location header produced the next URL. FinalURL is the last URL that returned a non-redirect status. Permanent is true only when every redirect in the chain was 301 or 308 — a single 302/307 anywhere in the chain makes the final URL a poor heal candidate because the origin may return a different target next time. TerminatingStatus is the HTTP status code returned by FinalURL (the first non-3xx response in the chain). Zero when the chain didn't terminate normally (e.g. errored out or hit max hops).
func FollowRedirectChain ¶
func FollowRedirectChain(ctx context.Context, rawURL string) (*RedirectChain, error)
FollowRedirectChain issues a HEAD request to rawURL and walks the redirect chain manually — up to maxRedirectHops hops. It returns the final URL and whether the entire chain was composed of permanent redirects (301/308).
Same-URL loops (a hop whose To equals its From, or a repeat of a URL seen earlier in the chain) terminate with an error.
Callers use this as the first healing strategy: if the chain ends at a 2xx URL and every hop is permanent, the final URL is a safe heal candidate.
type RedirectHop ¶
type RedirectHop struct {
From string `json:"from"`
To string `json:"to"`
Status int `json:"status"`
}
RedirectHop is one step in a redirect chain.
type RenameCandidate ¶
type RenameCandidate struct {
// Path is the full path within the repo (e.g. "docs/new-name.md").
Path string
// URL is the raw.githubusercontent.com URL rebuilt from the candidate path.
URL string
// Score is a similarity score in [0,1] where 1 is a perfect identity-stem
// match in the identical directory. Higher is better.
Score float64
// Reason briefly describes why this candidate was chosen (for PR body).
Reason string
// contains filtered or unexported fields
}
RenameCandidate is one possible replacement for a renamed file.
func DetectGitHubRename ¶
func DetectGitHubRename(ctx context.Context, rawURL string) ([]RenameCandidate, error)
DetectGitHubRename looks for a likely replacement file in the same repo and ref when a raw.githubusercontent.com URL 404s. It calls the git/trees API with ?recursive=1 to list all blobs, scores candidates by identity-stem similarity plus IDF-weighted path context, and returns ranked candidates.
Returns nil (with nil error) if rawURL is not a raw.githubusercontent.com URL or if the repo has no candidates above the similarity threshold.
Callers should apply ValidateContentResponse to the top candidate's URL before accepting it as a heal — this function only identifies *likely* replacements, not verified ones.
type RunManifest ¶
type RunManifest struct {
RunID string `json:"run_id"`
StartedAt time.Time `json:"started_at"`
FinishedAt time.Time `json:"finished_at"`
ExitClass int `json:"exit_class"`
SourcesAllCached bool `json:"sources_all_cached"`
Providers map[string]ProviderStatus `json:"providers"`
Warnings []string `json:"warnings"`
FingerprintDivergenceWarnings []string `json:"fingerprint_divergence_warnings"`
}
RunManifest is write-only observability output — never a pipeline input. capmon: never-read-as-input
func ReadLastRunManifest ¶
func ReadLastRunManifest(cacheRoot string) (*RunManifest, error)
ReadLastRunManifest reads the most recent run manifest from disk.
type SeedOptions ¶
type SeedOptions struct {
CapsDir string
Provider string
Extracted map[string]string // field path → value from extraction (Phase 9 wires full mapping)
ForceOverwriteExclusive bool
// CanonicalKeysPath locates the canonical-key registry used to decide
// whether an extracted capability key is canonical (→ content_types
// capabilities) or provider-exclusive (→ provider_exclusive). Defaults to
// docs/spec/canonical-keys.yaml.
CanonicalKeysPath string
}
SeedOptions configures a SeedProviderCapabilities invocation.
type SeederSpec ¶
type SeederSpec struct {
Provider string `yaml:"provider"`
ContentType string `yaml:"content_type"`
Format string `yaml:"format"`
FormatDocProvenance string `yaml:"format_doc_provenance,omitempty"`
SourceURIs []string `yaml:"source_uris,omitempty"`
ExtractionGaps []string `yaml:"extraction_gaps,omitempty"`
SourceExcerpt string `yaml:"source_excerpt,omitempty"`
ProposedMappings []ProposedMapping `yaml:"proposed_mappings"`
Notes string `yaml:"notes,omitempty"`
}
SeederSpec is the human-in-the-loop review document produced by the inspection bead for a single (provider, content_type) pair.
func DeriveSeederSpecs ¶
func DeriveSeederSpecs(doc *FormatDoc, canonicalKeysPath string) ([]*SeederSpec, error)
DeriveSeederSpecs produces one SeederSpec per supported content_type from a FormatDoc, deterministically. Identical inputs always produce identical outputs (no timestamps, no UUIDs). Content types with status "unsupported" are skipped entirely (no spec emitted). Returns an error if any canonical_mappings key is not in canonical-keys.yaml.
The returned slice is sorted by ContentType so callers can rely on stable ordering when writing per-content-type files to disk.
func LoadSeederSpec ¶
func LoadSeederSpec(path string) (*SeederSpec, error)
LoadSeederSpec reads and unmarshals a seeder spec YAML file at the given path.
type SelectorConfig ¶
type SelectorConfig struct {
Primary string `yaml:"primary"`
Fallback string `yaml:"fallback,omitempty"`
ExpectedContains string `yaml:"expected_contains,omitempty"`
MinResults int `yaml:"min_results,omitempty"`
UpdatedAt string `yaml:"updated_at,omitempty"`
}
SelectorConfig describes how to locate content within a fetched source.
type SourceEntry ¶
type SourceEntry struct {
URL string `yaml:"url"`
Type string `yaml:"type"`
Format string `yaml:"format"`
Selector SelectorConfig `yaml:"selector"`
Extracts []string `yaml:"extracts,omitempty"`
FetchMethod string `yaml:"fetch_method,omitempty"` // overrides manifest-level
Healing *HealingConfig `yaml:"healing,omitempty"`
}
SourceEntry is one source URL with its selector and extraction hints.
func (SourceEntry) EffectiveStrategies ¶
func (s SourceEntry) EffectiveStrategies() []string
EffectiveStrategies returns the healing strategy list for this source. An empty or absent configuration falls back to DefaultHealingStrategies.
func (SourceEntry) IsHealingEnabled ¶
func (s SourceEntry) IsHealingEnabled() bool
IsHealingEnabled reports whether reactive healing should run for this source. Default is true — callers must opt out via healing.enabled: false.
type SourceFetcher ¶
type SourceFetcher interface {
Fetch(ctx context.Context, uri, fetchMethod string) ([]byte, error)
}
SourceFetcher abstracts how BackfillFormatDoc fetches a single source URI. Production callers use DefaultSourceFetcher; tests pass a stub.
type SourceManifest ¶
type SourceManifest struct {
SchemaVersion string `yaml:"schema_version"`
Slug string `yaml:"slug"`
DisplayName string `yaml:"display_name"`
LastVerified string `yaml:"last_verified"`
FetchTier string `yaml:"fetch_tier,omitempty"`
FetchMethod string `yaml:"fetch_method,omitempty"`
DocsConventions *DocsConventions `yaml:"docs_conventions,omitempty"`
ContentTypes map[string]ContentTypeSource `yaml:"content_types"`
}
SourceManifest is the parsed form of docs/provider-sources/<slug>.yaml.
func LoadAllSourceManifests ¶
func LoadAllSourceManifests(dir string) ([]*SourceManifest, error)
LoadAllSourceManifests loads all *.yaml files from a directory.
func LoadSourceManifest ¶
func LoadSourceManifest(path string) (*SourceManifest, error)
LoadSourceManifest parses a single provider-sources YAML file.
type SourceRef ¶
type SourceRef struct {
URI string `yaml:"uri"`
Type string `yaml:"type"`
FetchMethod string `yaml:"fetch_method"`
ContentHash string `yaml:"content_hash"`
FetchedAt string `yaml:"fetched_at"`
Name string `yaml:"name,omitempty"`
Section string `yaml:"section,omitempty"`
}
SourceRef describes a single source URI that was fetched to populate the format doc. ContentHash stores the SHA-256 hash of the fetched content at fetch time, enabling drift detection via comparison in subsequent capmon check runs.
type SourceResult ¶
type SourceResult struct {
SourceID string `json:"source_id"`
URL string `json:"url"`
Cached bool `json:"cached"`
}
SourceResult is a per-source fetch outcome recorded during Stage 1. Populated only for successfully fetched sources; errors go to ProviderStatus.Errors.
type StringMatcher ¶
type StringMatcher struct {
// Kind is "exact" or "substring". Empty kind defaults to "substring"
// (the lower-precision, higher-recall option) so partial configurations
// don't silently fail to match.
Kind string
// Value is the literal string compared to landmarks. Stored verbatim;
// case-folding is controlled by CaseInsensitive at compare time.
Value string
// CaseInsensitive folds both the matcher value and the landmark to
// lowercase ASCII before comparison. Defaults to true (most landmarks
// are headings whose case may drift across doc updates).
CaseInsensitive bool
}
StringMatcher describes how to match a string against a landmark or item value. Two kinds in v1: "exact" and "substring". Regex is deliberately deferred — every regex we'd want today expresses cleanly as exact-or-substring, and adding regex later is a strictly additive change.
type UnmappedFormObservation ¶
type UnmappedFormObservation struct {
DiagnosticID string // e.g. "acif.rule.activation_mode_unmappable"
Provider string // provider slug
SourceForm string // the unmapped source-form value, verbatim
ContentItem string // stable identifier of the content item it fired on
ObservedAt time.Time
}
UnmappedFormObservation is one observed totality-net hit on real provider content.
type ValidationWarning ¶
type ValidationWarning struct {
File string // absolute path to the YAML file
Field string // dotted field path, e.g., "content_types.skills.provider_extensions[model].value_type"
Value string // the offending value
Message string // human-readable explanation
}
ValidationWarning is a non-fatal allow-list violation found in a format doc.
func ValidateFormatDocWithWarnings ¶
func ValidateFormatDocWithWarnings(formatsDir, canonicalKeysPath, provider string) ([]ValidationWarning, error)
ValidateFormatDocWithWarnings validates a format doc and returns both blocking errors and non-blocking allow-list warnings. The caller decides what to do with warnings (log, open GH issue, etc.).
func (ValidationWarning) DeduplicationKey ¶
func (w ValidationWarning) DeduplicationKey() string
DeduplicationKey returns the SHA-256-based key used to deduplicate GitHub issues for this warning. Key format: sha256(<file> + "\x00" + <field> + "\x00" + <value>), first 16 hex chars.
type VariantCandidate ¶
type VariantCandidate struct {
URL string
Reason string // short description of the transformation
}
VariantCandidate is one URL permutation probed via HEAD.
func GenerateVariants ¶
func GenerateVariants(rawURL string) []VariantCandidate
GenerateVariants returns a ranked list of plausible URL replacements for rawURL. Transformations include case swaps, separator swaps, and common doc-prefix substitutions (create-X ↔ add-X ↔ new-X).
The caller is expected to probe candidates in order and accept the first one whose HEAD returns 2xx and whose body passes ValidateContentResponse. Variants are generated deterministically so order is stable across runs.
func ProbeVariants ¶
func ProbeVariants(ctx context.Context, variants []VariantCandidate) (VariantCandidate, bool, error)
ProbeVariants issues HEAD requests against each candidate and returns the first one that responds with a 2xx status. The second return value is the matched candidate (or zero value). A returned bool of false means no variant responded successfully.
Uses a non-following client: HEAD 200 is the acceptance signal. The orchestrator will issue a real GET and call ValidateContentResponse before trusting the variant.
func SortedVariantsForTest ¶
func SortedVariantsForTest(vs []VariantCandidate) []VariantCandidate
SortedVariantsForTest returns variants in their generation order with stable ordering for tests. The underlying generator is already deterministic, but this hook lets tests assert on a sorted view when comparing sets.
Source Files
¶
- acifchange.go
- acifchange_confirm.go
- acifchange_graduation.go
- backfill.go
- cache.go
- check.go
- check_diff.go
- derive.go
- diff.go
- export.go
- export_canonical.go
- export_freeze.go
- export_gate.go
- export_index.go
- export_provider.go
- export_registry.go
- export_tree.go
- export_verify.go
- extractor.go
- fetch.go
- fetch_chromedp.go
- fetch_github.go
- fetch_validity.go
- formatdoc.go
- formatdoc_validate.go
- generate.go
- healing.go
- healing_diagnostics.go
- healing_github.go
- healing_issue.go
- healing_pr.go
- healing_redirect.go
- healing_variants.go
- manifest_persist.go
- onboard.go
- pipeline.go
- recognize.go
- recognize_agents.go
- recognize_amp.go
- recognize_claude_code.go
- recognize_cline.go
- recognize_codex.go
- recognize_commands.go
- recognize_compose.go
- recognize_copilot_cli.go
- recognize_crush.go
- recognize_cursor.go
- recognize_devin.go
- recognize_factory_droid.go
- recognize_gemini_cli.go
- recognize_hooks.go
- recognize_kiro.go
- recognize_landmarks.go
- recognize_mcp.go
- recognize_opencode.go
- recognize_pi.go
- recognize_roo_code.go
- recognize_rules.go
- recognize_skills.go
- recognize_types.go
- recognize_zed.go
- report.go
- sanitize.go
- seed.go
- seederspec.go
- sourceman.go
- sourceman_validate.go
- types.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
acifdrift
command
Command acifdrift diffs capmon's docs/spec/canonical-keys.yaml against ACIF's published capability-vocabulary export (conformance/capability-vocabulary.yaml in the ACIF repository).
|
Command acifdrift diffs capmon's docs/spec/canonical-keys.yaml against ACIF's published capability-vocabulary export (conformance/capability-vocabulary.yaml in the ACIF repository). |
|
capmon
command
Command capmon is the standalone CLI for the capability-monitor pipeline.
|
Command capmon is the standalone CLI for the capability-monitor pipeline. |
|
provider-monitor
command
provider-monitor checks provider source manifests for broken URLs and version drift.
|
provider-monitor checks provider source manifests for broken URLs and version drift. |
|
internal
|
|
|
Package provmon implements provider source manifest loading, URL health checking, and change detection for the provider monitoring pipeline.
|
Package provmon implements provider source manifest loading, URL health checking, and change detection for the provider monitoring pipeline. |