capmon

package module
v0.0.0-...-3e4fb61 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: Apache-2.0 Imports: 30 Imported by: ? modules, 0 packages

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

README

capmon

Standalone source of truth for AI coding tool capability data, plus the monitoring pipeline that keeps it accurate.

Capmon tracks which content types (rules, skills, agents, commands, MCP, hooks) each AI coding tool provider supports natively, watches the providers' upstream documentation for drift, and heals its own data when sources move. Capability dispositions and vocabularies conform to ACIF v0.1; capmon conforms to ACIF, never the reverse.

The data

All capability data lives under docs/ in this repo:

  • docs/provider-sources/ — per-provider source manifests: the upstream documentation URLs monitored for each content type.
  • docs/provider-formats/ — per-provider format docs: how each provider represents each content type, with canonical-key mappings.
  • docs/provider-capabilities/ — the authoritative capability baseline per provider, plus generated by-content-type views and the compatibility matrix.
  • docs/spec/canonical-keys.yaml — the canonical capability keys, each with a spec_ref to its owning ACIF section.

Downstream consumers pull this data; they do not push to it.

The pipeline

fetch  →  extract  →  recognize/derive  →  diff  →  report / heal
  • fetch — pulls ~150 upstream sources (raw GitHub files, HTTP pages, JS-rendered pages via chromedp) into a hash cache.
  • extract — per-format extractors (HTML, Markdown, Go, Rust, TypeScript, JSON, JSON Schema, YAML, TOML) turn sources into comparable field sets.
  • recognize/derive — per-provider recognizers map extracted fields onto the canonical capability model.
  • diff/report — compares against the committed state under docs/ and opens PRs/issues on this repo for drift (the healing layer).
  • check — content-hash drift detection across all providers (capmon check --all).

Usage

The CLI runs from the repo root (the --formats-dir/--sources-dir/ --canonical-keys defaults assume the working directory is the repo root):

go build -o capmon ./cmd/capmon
./capmon run                  # full pipeline
./capmon run --stage fetch-extract
./capmon run --stage report
./capmon check --all
./capmon verify               # validate provider-capabilities YAML
./capmon generate             # regenerate by-content-type views

cmd/provider-monitor is the sister tool that watches provider source URLs for rename/deprecation/URL drift; it finds docs/provider-sources/ from the working directory, or point it elsewhere with CAPMON_ROOT or --dir.

Consuming the published data

The /v1/ contract tree is published to GitHub Pages at https://openscribbler.github.io/capmon/. It is a live view of current data, not an archive — the URL major (/v1/) versions the contract (document shapes, paths, field semantics), never the data.

Fetch flow
  1. GET /index.json (unversioned root) → read latest and the majors array; follow the live major's index (v1/index.json).
  2. GET /v1/index.json → compare data_revision against your last-known value. It is a hash over provider data only and changes only when data changes, so "did anything change?" is one field compare. If unchanged, you already have the current data.
  3. On a change, use the per-file sha256 values under providers[] and files{} to fetch only the documents that changed.
  4. Fetch each capabilities/<slug>.json (and any pivots you need).
Integrity — verify before use

The sha256 values in index.json are change and corruption detection, not authenticity: they share an origin and a fate with the files they hash. Authenticity comes from build-provenance attestation bound to the publishing workflow's identity.

Integrity-sensitive consumers — anything that acts automatically on the data — MUST verify the attestation over v1/index.json, then each file's sha256 against it, and MUST fail closed: any mismatch aborts the fetch and triggers nothing downstream.

gh attestation verify v1-index.json --repo OpenScribbler/capmon
Staleness and polling
  • v1/index.json carries generated_at, cadence: "daily", and max_staleness_hours. If generated_at is older than max_staleness_hours, treat the feed as stale and keep your last-known-good copy. The feed is best-effort with no SLA.
  • Poll at most daily, and use HTTP conditional GET (If-None-Match / If-Modified-Since — Pages serves ETags and returns 304).
  • Deploys are not atomic at the CDN edge. On an index.json-vs-file hash mismatch, re-fetch after the propagation window (minutes) before treating it as an integrity failure.
Reading dispositions
  • supported absent means unknown — never treat it as false. "supported": true is verified/inferred support (see confidence); "supported": false is affirmatively not supported.
  • Treat every enum-valued field (confidence, status, conversion, …) as open: an unrecognized value is "unknown/other", never an error.
  • Ignore unknown fields, unknown canonical keys, and unknown files — producers may add any of these within a major.

Field and canonical-key semantics are specified in v1/spec/field-semantics.md; the JSON Schemas live under v1/schemas/.

CI

.github/workflows/pipeline.yml runs the full pipeline daily against the data in this repo. Heal PRs and drift issues are opened here using the workflow's own GITHUB_TOKEN. A scheduled keepalive re-enables the workflow through the Actions API so GitHub's 60-day-inactivity rule never disables the schedule — no scheduled job holds contents write on main (ADR 0005).

.github/workflows/publish.yml exports the /v1/ tree, attests it, and deploys it to GitHub Pages on any push to main under docs/ (and re-runs the fail-closed gate daily, skipping the deploy when data_revision is unchanged).

.github/workflows/ci.yml builds, vets, and tests on every push and PR. Drift-guard tests compare the recognizers and format docs against the data under docs/ in the same checkout.

License

Apache-2.0.

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.

  1. 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.

  2. 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.

  3. 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.

  4. 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).

  5. 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

View Source
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.

View Source
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.

View Source
const AgentsContentType = "agents"

AgentsContentType is the dot-path root for every agents capability emission.

View Source
const CommandsContentType = "commands"

CommandsContentType is the dot-path root for every commands capability emission.

View Source
const HooksContentType = "hooks"

HooksContentType is the dot-path root for every hooks capability emission.

View Source
const McpContentType = "mcp"

McpContentType is the dot-path root for every MCP capability emission.

View Source
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.

View Source
const RulesContentType = "rules"

RulesContentType is the dot-path root for every rules capability emission.

View Source
const SkillsContentType = "skills"

SkillsContentType is the dot-path root for every skills capability emission.

Variables

View Source
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.

View Source
var CanonicalCommandsKeys = []string{
	"argument_substitution",
	"builtin_commands",
}

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.

View Source
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.

View Source
var CanonicalMcpKeys = []string{
	"transport_types",
	"oauth_support",
	"env_var_expansion",
	"tool_filtering",
	"auto_approve",
	"marketplace",
	"resource_referencing",
	"enterprise_management",
}

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.

View Source
var CanonicalRulesKeys = []string{
	"activation_mode",
	"file_imports",
	"cross_provider_recognition",
	"auto_memory",
	"hierarchical_loading",
}

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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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

func AgeBasedEvict(cacheRoot string, maxAge time.Duration) (int, error)

AgeBasedEvict removes cache entries whose FetchedAt is older than maxAge. Returns the number of entries evicted.

func AppendCapmonChangeEvent

func AppendCapmonChangeEvent(_ context.Context, issueNumber int, body string) error

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 ChromedpRemoteURL

func ChromedpRemoteURL() string

ChromedpRemoteURL returns the CHROMEDP_URL env var value. Empty string means use local Chrome via DefaultExecAllocatorOptions.

func CloseResolvedWarningIssues

func CloseResolvedWarningIssues(_ context.Context, provider string, seenKeys map[string]bool) error

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

func CreateCapmonProviderIssue(_ context.Context, provider, title, body string) (int, error)

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

func CreateCapmonWarningIssue(_ context.Context, provider string, w ValidationWarning) (int, error)

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

func CreateDriftPR(_ context.Context, provider, runID string, diff CapabilityDiff) (string, error)

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

func CreateStructuralIssue(_ context.Context, provider, runID string, drift []string) error

CreateStructuralIssue creates a GitHub issue for structural drift (new sections).

func DeduplicatePR

func DeduplicatePR(_ context.Context, provider string) (string, bool, error)

DeduplicatePR checks if an open PR exists for capmon/drift-<provider>. Returns (existingPRURL, true) if found; ("", false) if not found.

func FetchURI

func FetchURI(ctx context.Context, uri, fetchMethod string) ([]byte, error)

FetchURI fetches a URI using HTTP GET, or a headless Chromium browser when fetchMethod is "chromedp". Returns the raw body.

func FindOpenCapmonHealPR

func FindOpenCapmonHealPR(provider, contentType string, sourceIndex int) (string, bool, error)

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

func FindOpenCapmonIssue(provider, contentType string) (int, bool, error)

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

func FindOpenCapmonProviderIssue(provider string) (int, bool, error)

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, 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.

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

func FormatDocPath(formatsDir, provider string) string

FormatDocPath returns the canonical filesystem path for a provider's format doc.

func GHRunner

func GHRunner(args ...string) ([]byte, error)

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

func GenerateContentTypeViews(capsDir, outDir string) error

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

func GenerateUnifiedDiff(oldContent, newContent []byte, path, sourceType string) (string, error)

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

func HealFailureAnchor(provider, contentType string, sourceIndex int) string

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

func HealPRAnchor(provider, contentType string, sourceIndex int) string

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 IsCached

func IsCached(cacheRoot, provider, sourceID string) bool

IsCached returns true if meta.json exists for the given provider+sourceID.

func IsCanonicalAgentsKey

func IsCanonicalAgentsKey(key string) bool

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

func IsCanonicalCommandsKey(key string) bool

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

func IsCanonicalHooksKey(key string) bool

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

func IsCanonicalMcpKey(key string) bool

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

func IsCanonicalRulesKey(key string) bool

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

func IsCanonicalSkillsKey(key string) bool

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

func IsRecognizerRegistered(provider string) bool

IsRecognizerRegistered reports whether a recognizer is registered for the given provider slug. Used in tests to assert full provider coverage.

func LoadAndRecognizeCache

func LoadAndRecognizeCache(cacheRoot, provider string) (map[string]string, error)

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 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:

  1. Fetch each source URI via FetchSource to populate the cache baseline.
  2. 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

func ProposeManifestHealPR(ctx context.Context, repoDir string, in HealPRInputs) (string, error)

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 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

func RecordConsecutiveFailure(_ context.Context, cacheRoot, provider string) error

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 RegisterExtractor

func RegisterExtractor(format string, ext Extractor)

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

func ResolveHealFailure(cacheRoot, provider, contentType string, sourceIndex int) error

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:

  1. ValidateSources for each provider (blocking)
  2. ValidateFormatDoc for each format doc (blocking)
  3. 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 /v1/ document tree in a temp dir on the same filesystem as OutDir, 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

func RunExportVerify(commit, baseURL string) error

RunExportVerify rebuilds the /v1/ tree 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 v1/index.json is fetched first so GeneratedAt/SourceCommit can be pinned from it, making the comparison total byte equality on every file — v1/index.json included. docs/ is 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 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 SHA256Hex

func SHA256Hex(data []byte) string

SHA256Hex computes "sha256:<hex>" for the given bytes.

func SanitizeExtractedString

func SanitizeExtractedString(s string) string

SanitizeExtractedString normalizes an extracted string value before writing to extracted.json. Exported for use by all extractor implementations.

func SanitizeSlug

func SanitizeSlug(slug string) (string, error)

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 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. provider_exclusive entries are preserved unconditionally unless ForceOverwriteExclusive is set.

func SeederSpecPath

func SeederSpecPath(specsDir, provider, contentType string) string

SeederSpecPath returns the conventional path for a seeder spec file given the directory, provider slug, and content type.

func SetGHCommandForTest

func SetGHCommandForTest(fn func(args ...string) ([]byte, error))

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

func SetGitRunnerForTest(fn func(dir string, args ...string) ([]byte, error))

SetGitRunnerForTest swaps the git runner. Pass nil to restore default.

func SetHTTPClientForTest

func SetHTTPClientForTest(c *http.Client)

SetHTTPClientForTest overrides the HTTP client in tests.

func SetRedirectClientForTest

func SetRedirectClientForTest(c *http.Client)

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

func SetValidateURLForTest(f func(string) error)

SetValidateURLForTest overrides the URL validator in tests.

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 preserving comments and formatting via the yaml.v3 Node API.

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

func ValidateContentResponse(body []byte, contentType, originalURL, finalURL string) error

ValidateContentResponse checks that a fetched HTTP response body represents readable, on-domain content. It performs three checks:

  1. 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.
  2. Content-Type does not indicate binary content
  3. 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

func ValidateFormatDoc(formatsDir, canonicalKeysPath, provider string) error

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:

  1. Required top-level fields: provider, last_fetched_at, content_types (non-empty)
  2. Each key in canonical_mappings must exist in canonical-keys.yaml for the content type
  3. Each provider_extensions entry must have: id, name, summary, source_ref, conversion
  4. confidence values must be confirmed | inferred | unknown
  5. conversion values must be translated | embedded | dropped | preserved | not-portable
  6. generation_method and notes are NOT validated (informational)

func ValidateSourceURL

func ValidateSourceURL(rawURL string) error

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

func ValidateSources(sourcesDir, provider string) error

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

type CacheEntry struct {
	Provider string
	SourceID string
	Raw      []byte
	Meta     CacheMeta
}

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 {
	Supported     bool     `yaml:"supported"`
	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.

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 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.

func (DefaultSourceFetcher) Fetch

func (DefaultSourceFetcher) Fetch(ctx context.Context, uri, fetchMethod string) ([]byte, error)

Fetch implements SourceFetcher.

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
	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

type FieldValue struct {
	Value     string `json:"value"`
	ValueHash string `json:"value_hash"`
}

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

func LoadFormatDoc(path string) (*FormatDoc, error)

LoadFormatDoc reads and unmarshals a format doc YAML file.

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 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
}

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 basename match
	// after normalization. Higher is better.
	Score float64
	// Reason briefly describes why this candidate was chosen (for PR body).
	Reason string
}

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 stem similarity to the original basename, 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
}

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 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.

Directories

Path Synopsis
cmd
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.

Jump to

Keyboard shortcuts

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