Documentation
¶
Overview ¶
@facet: authoring/guardrails/adr-status-proposal @facet-role: primary
@facet: registry/integrity/backing-gaps @facet-role: primary
@facet: registry/layout/glossary-tools @facet-role: related
@facet: registry/layout/project-conventions @facet-role: primary
@facet: delivery/distribution/core-pin @facet-role: primary
@facet: registry/history/defect-ledger @facet-role: primary
@facet: registry/integrity/declared-deviations @facet-role: primary
@facet: registry/integrity/record-validation @facet-role: related
Package facet — identifier register.
@facet: registry/integrity/error-code-register @facet-role: primary
@facet: registry/integrity/scenario-outlines @facet-role: primary
@facet: registry/layout/private-anchors @facet-role: primary
@facet: registry/layout/glossary-tools @facet-role: related
@facet: registry/layout/source-scanning @facet-role: related
@facet: registry/layout/project-glossary @facet-role: primary
@facet: registry/integrity/unanchored-hotspots @facet-role: primary
@facet: registry/integrity/knowledge-gaps @facet-role: primary
Checks documentation coverage across source directories.
Checks that connect source anchors to registry records.
Checks scenario structure, examples and record size.
Checks shared entity vocabularies and error codes.
Checks glossary definitions, categories and term references.
Checks feature flags, knowledge, backing and deviations.
Checks record dependencies and supersession.
Checks references from records to repository documents.
Checks record IDs against the product taxonomy.
Checks variant declarations and lifecycle coverage.
Brokering a plugin's call to its own binary — and refusing the rest.
Lint rules an installed plugin brings with it, run by `facet lint`.
Package facet — what a plugin package is, and the one check every source of one goes through before it is trusted.
@facet: registry/integrity/record-validation @facet-role: related
@facet: navigation/interfaces/product-services @facet-role: config
@facet: registry/integrity/record-validation @facet-role: related
Package facet implements the FACET registry: loading records, resolving the source anchors that connect them to code, and the integrity checks that keep the two from drifting apart.
@facet: registry/layout/multi-registry @facet-role: related
Reading a plugin-declared directory of markdown files under the repository root, with a directory a plugin names rather than one fixed by the records layout.
@facet: registry/layout/source-scanning @facet-role: primary
@facet: authoring/guardrails/large-record-read @facet-role: primary
@facet: registry/layout/source-views @facet-role: related
@facet: registry/integrity/runner-test-execution @facet-role: related
@facet: registry/integrity/runner-test-discovery @facet-role: primary
@facet: registry/integrity/runner-test-execution @facet-role: primary
@facet: registry/integrity/runner-test-execution @facet-role: related
@facet: registry/integrity/runner-test-execution @facet-role: related
@facet: registry/integrity/runner-test-discovery @facet-role: related
@facet: registry/integrity/runner-test-discovery @facet-role: related
@facet: registry/integrity/undocumented-directories @facet-role: primary
Index ¶
- Constants
- Variables
- func AgentEnv(m *ManifestSidecar, g Grant) []string
- func AgentToolName(plugin, tool string) string
- func AgentToolRef(server, plugin, tool string) string
- func AnchorPaths(anchors []Anchor) []string
- func AnchorsByID(anchors []Anchor) map[string][]Anchor
- func AttributePrivateAnchors(previous PrivateAnchors, found []AnchorBlock, worktree string)
- func AttributePrivateAnchorsInView(previous PrivateAnchors, found []AnchorBlock, ...)
- func ChangedFiles(root string) []string
- func ClearReview(root string) error
- func ConfigPath(root string) string
- func ConventionsLabel(source string) string
- func DeclaresOptOut(data []byte) bool
- func DeletedFiles(root string) []string
- func DetectForge(remote string, declared map[string]string) (forge, source string)
- func FirstAdded(root string) map[string]string
- func FirstURL(out string) string
- func ForgeHostEnv(forge, host string) []string
- func FormatOutline(sections []Section) string
- func GitCommonDir(root string) (string, error)
- func GitDir(root string) (string, error)
- func GitTreeState(root string) (head string, dirty bool, err error)
- func HashFile(path string) (string, error)
- func Install(dir string, id string, staged string, manifest PackageManifest, ...) error
- func IsDefaultBranch(root, branch string) bool
- func IsTestPath(rel string) bool
- func LastChanged(root string) map[string]string
- func ListRepoFiles(dir, ext string) ([]string, error)
- func ListRepoFilesExts(dir string, exts []string) ([]string, error)
- func LoadPackage(src string, work string, opts LoadOptions) (packageSHA256 string, err error)
- func NewSourceWalker(root string) (*gocodewalker.FileWalker, chan *gocodewalker.File)
- func NormalizeADRStatus(status string) string
- func OpenPullRequest(dir, branch string, state PushForge, title, body string) (string, error)
- func PackageIDVersion(dir string) (string, string, error)
- func ParseEnumConstraint(constraint string) (values []string, ok bool)
- func ParseSHA256Sums(raw []byte) (map[string]string, error)
- func PrivateAnchorWorktree(root string) (string, error)
- func ReadExtsFor(reads []ReadDecl, dir string) ([]string, error)
- func ReadLargeRecordThreshold() int
- func ReadRecordFile(path string) ([]byte, error)
- func ReadRepoFile(dir, rel, ext string) (string, error)
- func ReadRepoFileExts(dir, rel string, exts []string) (string, error)
- func ReadSections(data string, names []string) (string, error)
- func RecordIndex(regs []Registry, opts IndexOptions) string
- func RegisterBundledPlugin(manifest PluginManifest)
- func RegisterProductDocument(document ProductDocument)
- func RegisterProductSection(name string, validate ProductSectionValidator)
- func RegisterProseSource(source ProseSource)
- func RegistryDrift(cs *ChangeSet, reg Registry, anchors []Anchor, followed, known map[string]bool) ([]Drift, []ReferenceChange)
- func RemoteHost(remote string) string
- func RenamedFiles(root string) map[string]string
- func RenderGlossary(g *Glossary) string
- func ResolveExisting(path string) string
- func ResolveReadDir(root, rel string) (string, error)
- func ResolveRepoReadPath(dir, rel, ext string) (string, error)
- func SavePrivateAnchors(gitDir string, pa PrivateAnchors) error
- func ScanLiterals(root string, opts ScanOptions, needles []string, excludePrefix string) (map[string]bool, error)
- func ScanWithFiles(root string, opts ScanOptions) ([]Anchor, []SourceFile, error)
- func SchemaFor(category string) string
- func SetBundledSidecarSum(bin, platform, sum string)
- func SidecarPath(gitDir, rel string) string
- func SourceInfoPath(dest, name string) (string, bool)
- func SourceRepositories(root string, registries []Registry) []string
- func SplitFrontMatter(data []byte) (front, body []byte, ok bool)
- func SplitID(s string) (registry, id string)
- func SplitSegments(id string) (domain, capability, feature string, ok bool)
- func StaleReferences(reg Registry, renames map[string]string) map[string][]string
- func TouchedRecords(registries []Registry, changed []string) map[string]bool
- func UnifiedDiff(path, before, after string) string
- func ValidReadDir(rel string) bool
- func ValidReadExt(ext string) bool
- func VerificationKinds() []string
- func WithinResolved(dir, path string) bool
- type ADRConfig
- type ADRStatusProposal
- type AgentTool
- type Anchor
- type AnchorBlock
- type Artifact
- type BackfillChange
- type BackfillOptions
- type BackfillReport
- type Backing
- type Band
- type Baseline
- type BranchSession
- type Calibration
- type CapabilityNode
- type ChangeSet
- func (c ChangeSet) Changed() []string
- func (c ChangeSet) Deleted() []string
- func (c ChangeSet) FollowedRecords(registries []Registry) map[string]bool
- func (c ChangeSet) OK() bool
- func (c *ChangeSet) ReferenceChanges(reg Registry, current []Anchor, known map[string]bool) []ReferenceChange
- func (c ChangeSet) Renamed() map[string]string
- func (c ChangeSet) RepositoryBaselines() []RepositoryBaseline
- type Classification
- type CodeBand
- type Commit
- type CommitResult
- type Config
- func (c *Config) ADRDirectory() string
- func (c *Config) All() []Registry
- func (c *Config) BPMNDirectory() string
- func (c *Config) CommitGateOff() bool
- func (c *Config) Description(name string) string
- func (c *Config) EmbeddingSettings() EmbeddingConfig
- func (c *Config) ErrorCodePattern() string
- func (c *Config) Forges() map[string]string
- func (c *Config) IndexPath(reg Registry) string
- func (c *Config) MultiRegistry() bool
- func (c *Config) Names() []string
- func (c *Config) ProductSection(name string, out any) (bool, error)
- func (c *Config) ResolveSourceView(selected string) (*sourceview.ResolvedView, error)
- func (c *Config) Select(name string) (Registry, error)
- func (c *Config) Trackers() []Tracker
- type CorePin
- type Deviation
- type Digest
- type DiscoveredRunner
- type DomainNode
- type Drift
- type DriftReport
- type EmbeddingConfig
- type EnumDeclaration
- type ErrorCode
- type ErrorCodeMention
- type ErrorCodeRegister
- type ExamplesBlock
- type Exclusion
- type FeatureTestResult
- type FileChange
- type FileCount
- type Finding
- type Fix
- type Flag
- type Generator
- type GitHubSource
- type GitRelevantSet
- type Glossary
- func (g *Glossary) Categorised() bool
- func (g *Glossary) CategoryDeclared(id string) bool
- func (g *Glossary) CategoryIDs() []string
- func (g *Glossary) Configured() bool
- func (g *Glossary) DuplicateCategories() []string
- func (g *Glossary) DuplicateTerms() []string
- func (g *Glossary) Grouped() []GlossaryGroup
- func (g *Glossary) TermSet() []string
- func (g *Glossary) UnusedCategories() []string
- type GlossaryCategory
- type GlossaryEdited
- type GlossaryGroup
- type GlossaryRenamed
- type GlossarySession
- type GlossaryTerm
- type Grant
- type HooksConfig
- type Hotspot
- type IndexEntry
- type IndexOptions
- type Input
- type InstallOptions
- type InstalledPlugin
- type KnowledgeTally
- type LintOptions
- type LoadOptions
- type Manifest
- type ManifestAITool
- type ManifestEvents
- type ManifestSidecar
- type Metric
- type Outline
- type PackageManifest
- type PluginBroker
- func (b *PluginBroker) AgentTools() []AgentTool
- func (b *PluginBroker) Allowed(id, tool string) error
- func (b *PluginBroker) AllowedForAgent(id, tool string) error
- func (b *PluginBroker) Call(ctx context.Context, id, tool string, args json.RawMessage) (SidecarReply, error)
- func (b *PluginBroker) CallForAgent(ctx context.Context, id, tool string, args json.RawMessage) (SidecarReply, error)
- func (b *PluginBroker) Granted(id string) (Grant, error)
- func (b *PluginBroker) Manifest(id string) (PluginManifest, error)
- func (b *PluginBroker) StopAll()
- type PluginManifest
- type PrivateAnchors
- func ListPrivateAnchors(gitDir string) ([]PrivateAnchors, error)
- func LoadPrivateAnchors(gitDir, rel string) (PrivateAnchors, error)
- func MergeSidecar(previous PrivateAnchors, found []AnchorBlock, clean []byte) PrivateAnchors
- func MergeSidecarInView(previous PrivateAnchors, found []AnchorBlock, clean []byte, ...) PrivateAnchors
- type ProductDocument
- type ProductSectionValidator
- type ProseSource
- type Provenance
- type PushForge
- type ReadDecl
- type Record
- func (rec Record) ActiveAnywhere() bool
- func (r Record) Backings() []Backing
- func (r Record) CommonPitfallsText() []string
- func (r Record) ContractScenarios() []string
- func (r Record) DefectTotal() int
- func (r Record) DefectsByFile() []FileCount
- func (r Record) Deviations() []Deviation
- func (r Record) EnumDeclarations() []EnumDeclaration
- func (r Record) ExcludedCommits() []Exclusion
- func (r Record) Fixes() []Fix
- func (r Record) Flags() []Flag
- func (r Record) Intent() string
- func (r Record) KnowledgeContradictions() []string
- func (r Record) KnowledgeCounts() KnowledgeTally
- func (r Record) KnowledgeGaps() []string
- func (r Record) KnowsCommit(sha string) bool
- func (r Record) LifecycleOn(variant string) (string, bool)
- func (r Record) Outlines() []Outline
- func (r Record) Provenances() []Provenance
- func (r Record) ScenarioStatements() []string
- func (r Record) Variants() map[string]VariantState
- type ReferenceChange
- type Registry
- func (r Registry) Adopted() bool
- func (r Registry) CategoryDir(category string) string
- func (r Registry) Claims(rel string) bool
- func (r Registry) GlossaryPath() string
- func (r Registry) IDForPath(path string) string
- func (r Registry) Label() string
- func (r Registry) LoadCategory(category string) (records []Record, err error)
- func (r Registry) LoadFeatures() ([]Record, error)
- func (r Registry) ManifestPath() string
- func (r Registry) PathForID(id string) string
- func (r Registry) RAGIndexPath() string
- func (r Registry) Rel(path string) string
- func (r Registry) ScanOptions() ScanOptions
- func (r Registry) TaxonomyPath() string
- func (r Registry) ValidateSourceView() error
- func (r Registry) VariantMapPath() string
- type RegistrySet
- func (s RegistrySet) Claimants(rel string) []Registry
- func (s RegistrySet) Multi() bool
- func (s RegistrySet) Owners(qualified string) []Registry
- func (s RegistrySet) Primary() Registry
- func (s RegistrySet) Qualify(reg Registry, id string) string
- func (s RegistrySet) Resolve(qualified string) (Registry, string, bool)
- type Report
- type RepositoryBaseline
- type ResolvedTicket
- type Runner
- type RunnerExecution
- type ScanOptions
- type Section
- type Severity
- type Sidecar
- type SidecarCall
- type SidecarReply
- type SidecarSpec
- type SourceFile
- type SourceInfo
- type SourceKind
- type SplitCheck
- type SplitLoss
- type StaleReference
- type State
- type Status
- type Subject
- type SuffixPair
- type Taxonomy
- func (t *Taxonomy) CapabilityDeclared(domain, capability string) bool
- func (t *Taxonomy) CapabilityNames(domain string) []string
- func (t *Taxonomy) ClassificationOf(domain, capability string) Classification
- func (t *Taxonomy) Configured() bool
- func (t *Taxonomy) DomainDeclared(domain string) bool
- func (t *Taxonomy) DomainNames() []string
- func (t *Taxonomy) OwnerTeam(domain string) string
- type TermMatch
- type TestDiscovery
- type TestExecution
- type TestFileCounts
- type TestFinding
- type TestSourceSnapshot
- type Tracker
- type UnanchoredFile
- type UndocumentedDir
- type VariantMap
- type VariantState
- type VerifyOptions
Constants ¶
const ( ADRStatusProposed = "proposed" ADRStatusAccepted = "accepted" ADRStatusSuperseded = "superseded" ADRStatusRejected = "rejected" )
The four ADR statuses. Writers write only these English values.
const ( Backed = "backed" Unbacked = "unbacked" )
Backing states a scenario may declare.
const ( MetricScenariosPerRecord = "scenarios per record" MetricRecordsPerCapability = "records per capability" MetricCapabilitiesPerDomain = "capabilities per domain" MetricRecordsPerFile = "records per anchored file" )
Metric names, exported so a caller can find one without matching prose.
const ( // BaselineOK means the baseline resolved and the comparison ran. BaselineOK = "ok" // BaselineMissing means the baseline does not resolve to a commit — a // repository with no commit yet, or a revision that does not exist. BaselineMissing = "no-baseline" // command that failed part way. BaselineUnavailable = "unavailable" // BaselineNoRepository means there is no git repository to ask, or no git. // Kept apart from BaselineUnavailable because the two call for different // responses: a project outside git has no history to lose, while a failed // command inside one has hidden whatever it would have found. BaselineNoRepository = "no-repository" )
Baseline statuses. A status is never folded into an empty result: "no drift" and "drift could not be determined" are different statements, and a consumer handed an empty list for both would report a repository without commits, or a typo in a baseline, as a clean one.
const ( // BaselineHead is the implicit default: the checkout's own HEAD. Nobody // recorded a review; a clean result means only that the working tree // matches the last commit. BaselineHead = "head" // BaselineAccepted is a snapshot 'facet drift accept' recorded in this // worktree. Everything after it — committed or not — is unreviewed. BaselineAccepted = "accepted" // BaselineExplicit is a revision the caller named. BaselineExplicit = "explicit" )
Baseline kinds: where the baseline came from, which is what decides how much a clean result is worth.
const ( // RefDeleted: the file carrying the anchor is gone. RefDeleted = "deleted" // RefRenamed: the file moved and the anchor moved with it. The // association survives; what goes stale is any record text that names // the old path. RefRenamed = "renamed" // RefAnchorRemoved: the file is still there and no longer carries the // anchor. RefAnchorRemoved = "anchor-removed" )
Reference-change kinds. They differ in what is left behind, which is what a reader has to decide about.
const ( // EvidenceBaseline: the baseline commit's own content. EvidenceBaseline = "baseline" // EvidencePrivateSidecar: the clone's private-anchor sidecar. The clean // filter keeps such anchors out of every commit, so the baseline cannot // show them; the sidecar is the only place they are written down. EvidencePrivateSidecar = "private-sidecar" )
Evidence names where a baseline association was read from.
const ( ConventionsFromRegistry = "registry" // the registry's own 'conventions' key ConventionsFromProject = "project" // the top-level 'conventions' key ConventionsFromDefault = "default" // FACET-CONVENTIONS.md at the root )
Where a registry's conventions document came from. Printed, so an agent and a person can tell an override from the shared document without reading the configuration themselves.
const ( RecordedByGitHistory = "git-history" RecordedByTracker = "tracker" RecordedByManual = "manual" )
How an entry came to be in the ledger.
const ( ConfirmedByCodeReview = "code-review" ConfirmedByTest = "test" ConfirmedByRuntime = "runtime" )
How a deviation's behaviour was established. Closed, because a reader weighs the claim by it — see the field's description in schema/facet.schema.json.
const ADRReadDirectory = "docs/adr"
ADRReadDirectory is the default ADR directory when none is configured.
const AcceptedBaselineRef = "refs/worktree/facet/drift-baseline"
AcceptedBaselineRef is where 'facet drift accept' keeps its snapshot.
const ConfigName = ".facetrc.yaml"
ConfigName is the project's committed FACET configuration.
const CreatedAtSlackDays = 14
CreatedAtSlackDays is the allowed lead time before the oldest anchored source file. The 14-day tolerance favours silence when documentation and code arrive separately: Git dates file entries, not the start of a product decision.
const DefaultConventionsName = "FACET-CONVENTIONS.md"
DefaultConventionsName is the project conventions document a repository may keep at its root without declaring anything.
const DefaultErrorCodePattern = `E\d{4}`
DefaultErrorCodePattern matches E followed by exactly four digits, with the first digit identifying a band. It is configurable; this naming convention is not a FACET requirement.
const DefaultFixPattern = `(?i)^(fix|bugfix|hotfix)(\([^)]*\))?!?:`
DefaultFixPattern is the heuristic that decides what counts as a bugfix.
const DefaultIndexBytes = 24 * 1024
DefaultIndexBytes is the budget one index gets, in bytes.
const DefaultReadExt = ".md"
DefaultReadExt is the only extension the plain-string form of "reads" allows. Nothing that existed before the object form changes meaning.
const DefaultRecordsDir = "docs/facets"
DefaultRecordsDir is where records live when nothing says otherwise.
const DefaultRegistryName = "default"
DefaultRegistryName is the implicit registry of a project that declares none. It is never printed for single-registry projects, where naming a registry the author never chose would be noise.
const ForgeFromRemote = "git remote"
ForgeFromRemote is the source of a forge this host recognised itself.
const GlossaryName = "glossary.yaml"
GlossaryName is the deployment's terminology list inside the records dir.
const GlossarySchemaVersion = "0.1"
GlossarySchemaVersion is the schema family a glossary written here declares.
const HostPluginAPI = 0
const IgnoreFile = ".facetignore"
IgnoreFile is FACET's own ignore file, read alongside .gitignore.
const LargeRecordBytes = 6000
LargeRecordBytes is the size above which a record is read by section rather than whole. Roughly 1.5k tokens: below it the outline costs about what the file does, so there is nothing to save.
const ManifestName = "generated.lock.yaml"
ManifestName is the generation manifest's location inside the records dir.
const PluginLintTool = "facet.lint"
PluginLintTool is the reserved tool name a plugin declares to contribute lint rules.
const RAGIndexName = "generated.rag.bin"
RAGIndexName is the index's file name inside the records directory.
const RepoReadMaxBytes = 1 << 20
RepoReadMaxBytes caps one repo.read answer.
const ScopeWorkingTree = "working-tree-against-baseline"
ScopeWorkingTree names what every change set compares: the working tree, with staged, unstaged and untracked changes, against one baseline commit. History before the baseline is not examined, and a result saying nothing changed is a statement about that window only — never proof that the registry was ever reviewed against older commits.
SharedVariant is the reserved name for code belonging to no single variant.
const SidecarDefaultTimeout = 30 * time.Second
SidecarDefaultTimeout bounds a call when the manifest names none.
const SidecarDirName = "facet/anchors"
SidecarDirName is where a clone keeps its private anchors, under the git directory every worktree of the clone shares — outside the tree, outside every commit, and gone with the clone rather than with a checkout. Shared on purpose: the filter's configuration and attributes are shared the same way, and a worktree that inherited the filter but not the anchors would read as a clone where they had all been lost.
const SidecarMaxFrame = 8 << 20 // 8 MiB
SidecarMaxFrame bounds one reply.
const TaxonomyName = "taxonomy.yaml"
TaxonomyName is the deployment's product decomposition inside the records dir.
const TestFailed = "failed"
TestFailed identifies failed execution evidence for a file or feature.
const TestPassed = "passed"
TestPassed identifies positive execution evidence for a file or feature.
const TestUnmeasured = "unmeasured"
TestUnmeasured identifies a file or feature without usable execution evidence.
const VariantMapName = "variants.yaml"
VariantMapName is the deployment's variant declaration inside the records dir.
Variables ¶
var ( // ErrGlossaryUndeclaredCategory refuses a category not declared in the // file, preventing a typo from creating a separate implicit group. ErrGlossaryUndeclaredCategory = errors.New("the glossary does not declare that category") // ErrGlossaryNoSuchTerm refuses renames and removals of undefined terms; // no change is reported for a term the glossary does not contain. ErrGlossaryNoSuchTerm = errors.New("the glossary does not define that term") // ErrGlossaryTermExists refuses a rename onto an existing term, preserving // both definitions rather than selecting one by overwrite. ErrGlossaryTermExists = errors.New("the glossary already defines that term") // ErrGlossaryEmptyTerm rejects blank names or definitions at the write // boundary, enforcing the schema requirement before changing the file. ErrGlossaryEmptyTerm = errors.New("a term needs a name and a definition") )
Named glossary refusal errors let callers distinguish failure conditions without matching diagnostic text.
var ADRStatusAliases = map[string]string{ "vorgeschlagen": ADRStatusProposed, "angenommen": ADRStatusAccepted, "abgelöst": ADRStatusSuperseded, "verworfen": ADRStatusRejected, }
ADRStatusAliases maps the German status values ADRs were written in before rc.1 to their English value. A reader accepts them so an existing ADR keeps its status; nothing writes them.
var BranchNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/-]{0,100}$`)
BranchNamePattern is what may be a branch or remote name.
var Categories = []string{"features", "policies", "assumptions", "data-entities"}
Categories of record the registry holds, in the order checks report them.
var ErrBranchName = errors.New("name is outside the branch name grammar")
ErrBranchName is a branch or remote name outside BranchNamePattern.
var ErrDefaultBranch = errors.New("the default branch is never a write target")
ErrDefaultBranch is the refusal that the target is never the branch the project merges into. A proposal a human merges is the one rule that makes everything else here bearable.
var ErrGitHubAssetMissing = errors.New("plugin: the release carries no *.facetplugin asset")
ErrGitHubAssetMissing means the named release carries no asset matching the plugin id.
var ErrGitHubChecksumsMissing = errors.New("plugin: the release carries no checksums.txt")
ErrGitHubChecksumsMissing means the release carries no checksums.txt.
var ErrGitHubSourceMalformed = errors.New("plugin: a github: source must be github:owner/repo@tag")
ErrGitHubSourceMalformed means a "github:" source did not parse as owner/repo@tag.
var ErrNoRepository = errors.New("this is not a git repository")
ErrNoRepository is a write asked of a directory git does not know about.
var ErrNoSidecar = errors.New("plugin: no sidecar declared")
ErrNoSidecar means the plugin declares tools but brings no binary.
var ErrNothingToCommit = errors.New("a commit must name what it commits")
ErrNothingToCommit is a commit that named nothing, or whose named paths hold nothing to record.
var ErrPluginAPIMismatch = errors.New("plugin: this reader does not offer the requested API")
ErrPluginAPIMismatch means the manifest names an API this reader does not offer.
var ErrPluginAlreadyInstalled = errors.New("plugin: already installed — use --replace")
ErrPluginAlreadyInstalled means the id already has a directory, and --replace was not given.
var ErrPluginChecksumMismatch = errors.New("plugin: checksum does not match")
ErrPluginChecksumMismatch means a file's content does not match what SHA256SUMS — or the manifest's own sidecar.sha256 — says it should be.
var ErrPluginEntryOutsideAllowList = errors.New("plugin: entry is not on the allow-list")
var ErrPluginHTTPRequiresChecksum = errors.New("plugin: an https:// source requires --sha256")
var ErrPluginIsBundled = errors.New("plugin: this id is bundled with the binary")
ErrPluginIsBundled means the id belongs to a plugin the binary already ships. Installing a second one under the same name would shadow whichever the broker reads first, and bundledManifests would then describe rights for a manifest nobody checked.
var ErrPluginNotInstalled = errors.New("plugin: not installed")
ErrPluginNotInstalled means there is no manifest under this id.
var ErrPluginPlainHTTPRefused = errors.New("plugin: only https:// sources are accepted")
ErrPluginPlainHTTPRefused means the source used http:// rather than https://. A checksum makes the download's integrity checkable but says nothing about who could read or replace it in flight before the check runs, which is exactly what TLS is for.
var ErrRepoReadDirInvalid = errors.New("declared read directory is not a directory below the repository root")
ErrRepoReadDirInvalid is a declared read directory that is not a plain relative path below the registry root: ".", "..", a hidden segment, an absolute path, or one that resolves outside the root through a symlink.
var ErrRepoReadPathEscape = errors.New("path leaves the declared directory")
ErrRepoReadPathEscape is a path that leaves the declared directory — judged after symlinks are resolved, because a string prefix is passed by a symlink.
var ErrRepoReadPathGrammar = errors.New("path is outside the read grammar")
ErrRepoReadPathGrammar is a path whose segments are outside the address grammar repo.read accepts.
var ErrRepoReadTooLarge = errors.New("file is larger than the read limit")
ErrRepoReadTooLarge is a file above RepoReadMaxBytes. repo.read serves prose; a file this size is not one, and reading it whole into a JSON answer would hold it in memory twice.
var ErrRepoReadWrongExt = errors.New("file extension is not one the manifest declares readable")
ErrRepoReadWrongExt is a path whose extension does not match what the caller declared readable: ".md" for the plain-string form of "reads", the listed extensions for the object form. An ADR is prose, not a place this tool would ever return a script or a credential from.
var ErrSidecarChecksum = errors.New("sidecar: checksum does not match")
ErrSidecarChecksum is returned when the binary is not the one that was verified. The caller aborts and names the source; it does not try another.
var ErrToolNotDeclared = errors.New("plugin: the manifest does not declare this tool")
ErrToolNotDeclared means the manifest does not carry this tool.
var ErrToolNotGranted = errors.New("plugin: this tool has not been granted")
ErrToolNotGranted means the grant does not allow it.
var ReviewOutcomes = []string{"behavior-unchanged", "record-updated", "references-repaired"}
Review outcomes 'facet drift accept' can record. They describe what the reviewer concluded about the changes since the previous baseline; none of them is a record field, and none changes a record's lifecycle.
Functions ¶
func AgentEnv ¶
func AgentEnv(m *ManifestSidecar, g Grant) []string
AgentEnv is agentEnv for callers outside this package: the variables a sidecar started for the agent may see under manifest m and grant g: those the manifest declares under both env and ai_env and the grant names under both env and ai_env.
func AgentToolName ¶
AgentToolName is the name the agent calls a plugin tool by, without the MCP server prefix.
func AgentToolRef ¶
AgentToolRef is the full name Claude Code addresses the tool by.
func AnchorPaths ¶
AnchorPaths lists the distinct files anchoring one feature, sorted.
func AnchorsByID ¶
AnchorsByID groups anchors by the feature they point at.
func AttributePrivateAnchors ¶
func AttributePrivateAnchors(previous PrivateAnchors, found []AnchorBlock, worktree string)
AttributePrivateAnchors preserves existing provenance across shared smudges and records the origin only for new blocks. Legacy blocks remain unknown.
func AttributePrivateAnchorsInView ¶
func AttributePrivateAnchorsInView(previous PrivateAnchors, found []AnchorBlock, worktree, repository, revision, contentHash string)
AttributePrivateAnchorsInView records provenance only for new associations. Identical tag text at a different declaration is a distinct placement.
@facet: registry/layout/source-views @facet-role: related
func ChangedFiles ¶
ChangedFiles lists tracked and untracked changes relative to the repository root, using its resolved baseline. Deleted paths retain their old names. It returns no paths when comparison is unavailable; use LoadChangeSet and inspect Baseline to distinguish that state from an unchanged working tree.
func ClearReview ¶
ClearReview forgets this worktree's accepted baseline, so comparisons fall back to HEAD.
func ConfigPath ¶
ConfigPath returns where a project's configuration lives.
func ConventionsLabel ¶
ConventionsLabel says, in words, where a registry's document came from.
func DeclaresOptOut ¶
DeclaresOptOut reports whether a file's bytes carry the ignore marker in the head. Exported for callers that do their own walk — the corpus builder reads every file once and must classify them the same way this scanner does.
func DeletedFiles ¶
DeletedFiles lists the paths removed since the baseline. A rename's old path is not a deletion; RenamedFiles reports those.
func DetectForge ¶
DetectForge works out which forge a remote points at, and says how it knows.
func FirstAdded ¶
FirstAdded maps repository-relative paths to their first commit day in one git log pass, avoiding a subprocess per file in hooks. It returns no result outside a repository, on Git failure, or for shallow history. Callers must treat an unavailable measurement as unexamined, never as passing dates.
func FirstURL ¶
FirstURL returns the first URL in a CLI's output, which is where both CLIs print the link to what they just made.
func ForgeHostEnv ¶
ForgeHostEnv names the server a forge CLI should talk to, or nothing.
func FormatOutline ¶
FormatOutline renders the section list as the one-line-per-section table the hook denial and the tool both show.
func GitCommonDir ¶
GitCommonDir resolves the directory a clone's worktrees share: the git directory itself for the main worktree, and wherever a linked worktree's 'commondir' file points otherwise. Config, attributes and the sidecar all live there, so one install serves every worktree of the clone.
func GitDir ¶
GitDir resolves the directory git keeps a checkout's state in: '.git' when it is a directory, or wherever a '.git' file points for a linked worktree or a submodule. Resolved by reading rather than by asking git, because the filter runs once per file and a subprocess per file is what makes a large 'git status' crawl.
func GitTreeState ¶
GitTreeState asks git for the checked-out commit and whether the tree has changes. It fails where root is not inside a repository or has no commit.
func Install ¶
func Install(dir string, id string, staged string, manifest PackageManifest, previous *PackageManifest, opts InstallOptions) error
Install moves a staged, already-verified package (see VerifyPackage) into dir/<id>, atomically: stage first, verify (the caller's job, before calling Install), then rename — so a check that fails never leaves a half-written plugin directory where the broker could find it.
func IsDefaultBranch ¶
IsDefaultBranch reports whether a name is one this host refuses to write to.
func IsTestPath ¶
IsTestPath is the default "outside tests" classifier for the test-only-anchors check: a repository-relative path is test code when its filename matches a common test-file convention, or one of its directory segments is a common test directory. Both lists are deliberately small and unsurprising; a project whose test layout does not match them supplies LintOptions.IsTestPath instead of asking this default to grow a config surface of its own.
func LastChanged ¶
LastChanged maps each path under root to the day of the newest commit that touched it, relative to root.
func ListRepoFiles ¶
ListRepoFiles lists every file with the given extension directly under a declared directory, sorted, relative and slash-separated.
func ListRepoFilesExts ¶
ListRepoFilesExts is ListRepoFiles for several extensions, merged and sorted. It offers exactly what ReadRepoFileExts reads.
func LoadPackage ¶
func LoadPackage(src string, work string, opts LoadOptions) (packageSHA256 string, err error)
LoadPackage resolves src to a staged, unverified directory under work (which must exist and be empty) and reports whether the staged package's own checksum equals what was expected (for a source where one applies).
func NewSourceWalker ¶
func NewSourceWalker(root string) (*gocodewalker.FileWalker, chan *gocodewalker.File)
NewSourceWalker returns the shared source walker and its file channel. All scans, progress counts and reachability checks must use the same file selection to avoid contradictory counts or false test-only findings. The caller starts the walker and drains the channel; Start closes it on return. Capture Start's error after draining, not concurrently with the receive loop.
func NormalizeADRStatus ¶
NormalizeADRStatus lower-cases a status and maps a German alias to its English value. An unknown word comes back lower-cased and unchanged, so the caller can still name it in a refusal.
func OpenPullRequest ¶
OpenPullRequest opens the pull request for a pushed branch whose checkout is dir.
func PackageIDVersion ¶
PackageIDVersion reads a plugin folder's id and version from its plugin.json, for naming the package, without verifying anything — Pack verifies. Both must be present; their shape is Pack's to judge.
func ParseEnumConstraint ¶
ParseEnumConstraint recognizes one constraint string as enum-shaped and returns its normalized values, or ok=false when the constraint is not enum-shaped at all — which is most constraints ("not-null", "unique", "max-length:255" are not enum declarations, and reporting them as such would be the defect, not the fix).
func ParseSHA256Sums ¶
ParseSHA256Sums parses a whole SHA256SUMS file into name → lowercase hex digest. Exported so a caller outside this package that needs to check one file against the same list (a server checking an entry file at serve time, rather than VerifyPackage's whole-directory pass at install) reads it through the one parser this package already trusts, instead of a second one that could read the format differently.
func PrivateAnchorWorktree ¶
PrivateAnchorWorktree identifies a worktree relative to its shared git directory, so relocating a clone does not turn its local anchors foreign.
func ReadExtsFor ¶
ReadExtsFor answers the extensions a manifest allows in dir: the union over every entry naming dir, so one directory declared twice is allowed what both say. It is empty when no entry names dir — the caller refuses that — and an error when an entry for dir carries an extension outside the grammar, which the schema refused at install but a manifest on disk can change after it did.
func ReadLargeRecordThreshold ¶
func ReadLargeRecordThreshold() int
ReadLargeRecordThreshold resolves the threshold, FACET_READ_GATE_BYTES overriding the default. A value that is not a positive integer is ignored rather than switching the gate off by accident.
func ReadRecordFile ¶
ReadRecordFile is a thin helper so the command can read a path the same way the tests hand bytes in.
func ReadRepoFile ¶
ReadRepoFile reads one file under a declared directory, refusing anything ResolveRepoReadPath refuses about the path.
func ReadRepoFileExts ¶
ReadRepoFileExts is ReadRepoFile for a directory that allows several extensions: the file's own extension must be one of exts.
func ReadSections ¶
ReadSections returns the text of the named sections, each headed by a comment line naming it, in the order asked. An unknown name is an error that lists the names that exist, never a guess at the nearest one.
func RecordIndex ¶
func RecordIndex(regs []Registry, opts IndexOptions) string
RecordIndex renders the index as the text an agent is given.
func RegisterBundledPlugin ¶
func RegisterBundledPlugin(manifest PluginManifest)
RegisterBundledPlugin adds the manifest of a plugin a linked product carries into the bundled catalogue. Builds register from init. It panics on an empty or repeated id: two manifests for one plugin would make its rights undecidable.
func RegisterProductDocument ¶
func RegisterProductDocument(document ProductDocument)
RegisterProductDocument adds a product's registry document. Builds register from init, so the documents are known before any lint runs. It panics on a document without a path or schema: both are programming errors of the build.
func RegisterProductSection ¶
func RegisterProductSection(name string, validate ProductSectionValidator)
RegisterProductSection makes the named top-level section the registering product's. It panics on a name Core already reads or another product has registered: both are programming errors of the build, and a silent second owner would make it undecidable which validator a project's file answers to.
func RegisterProseSource ¶
func RegisterProseSource(source ProseSource)
RegisterProseSource adds a product's prose to what a glossary rename reports. A build registers from init; a build that links no such product reports the records alone.
func RegistryDrift ¶
func RegistryDrift(cs *ChangeSet, reg Registry, anchors []Anchor, followed, known map[string]bool) ([]Drift, []ReferenceChange)
RegistryDrift answers the drift question for one registry over a change set already loaded, from anchors the caller already scanned.
func RemoteHost ¶
RemoteHost pulls the host out of the several shapes a git remote takes.
func RenamedFiles ¶
RenamedFiles maps the old path to the new one for every rename since the baseline.
func RenderGlossary ¶
RenderGlossary writes a glossary back out.
func ResolveExisting ¶
ResolveExisting resolves the nearest ancestor of a path that exists, so a directory about to be created can still be compared against.
func ResolveReadDir ¶
ResolveReadDir turns a declared read directory into an absolute path under root, refusing one outside the grammar and one whose resolved location leaves root — a declared "docs/adr" that is a symlink to $HOME passes the grammar and would otherwise hand out every .md file it points at.
func ResolveRepoReadPath ¶
ResolveRepoReadPath turns a caller-supplied relative path into an absolute one inside dir, refusing everything a host write path would refuse about a path, with dir as the root.
func SavePrivateAnchors ¶
func SavePrivateAnchors(gitDir string, pa PrivateAnchors) error
SavePrivateAnchors writes one file's sidecar, atomically, or removes it when there is nothing left to keep. Atomic because git may run the filter for several files at once, and a half-written sidecar is a lost anchor.
func ScanLiterals ¶
func ScanLiterals(root string, opts ScanOptions, needles []string, excludePrefix string) (map[string]bool, error)
ScanLiterals reports which nonempty needles occur in source files selected by opts. It searches literal bytes, including files without source anchors. excludePrefix skips walker paths beginning with that prefix, normally the absolute records directory, so a flag declaration cannot satisfy its own check.
func ScanWithFiles ¶
func ScanWithFiles(root string, opts ScanOptions) ([]Anchor, []SourceFile, error)
ScanWithFiles is ScanAnchors plus the files it walked past.
func SetBundledSidecarSum ¶
func SetBundledSidecarSum(bin, platform, sum string)
SetBundledSidecarSum records the checksum a build measured for one bundled sidecar binary on the given platform ("<GOOS>-<GOARCH>", e.g. "linux-amd64"). The program's entry point calls it once per sidecar at startup; this package and the sidecars never do, because a sidecar links this package and a sum it could reach would become part of the very bytes that sum measures.
func SidecarPath ¶
SidecarPath is where one file's private anchors are kept: the file's own path mirrored under the shared git directory, so a reader who wonders what is private in a file can open the answer by name.
func SourceInfoPath ¶
SourceInfoPath is the counterpart writeIntoPluginDir uses for reading: where .source.json (or grants.json) lives for a given plugin directory, given whether it is a --dev symlink. Exported so a caller outside this package (a server handing out an installed plugin's files, which has to know whether a served plugin is a --dev install before deciding whether to check it against SHA256SUMS) reads .source.json from the same place this package writes it, rather than assuming it always lives inside the plugin directory itself — which is false for exactly the --dev case that matters most.
func SourceRepositories ¶
SourceRepositories includes the workspace repository and the repositories containing explicitly declared sources. It does not discover ignored clones by walking the workspace.
@facet: registry/history/reference-changes @facet-role: related
func SplitFrontMatter ¶
SplitFrontMatter separates a Markdown file's YAML header from its prose.
func SplitSegments ¶
SplitSegments breaks a canonical id into its three segments. The last return value reports whether the id had exactly three non-empty segments; a caller holding a schema-valid record can ignore it, and a caller reading an anchor cannot. Named apart from SplitID, which separates a registry prefix.
func StaleReferences ¶
StaleReferences names the records that still mention a path git has recorded as renamed. The search is textual on purpose: a path can be named in 'verification', in a lineage note, or in prose, and all three go stale the same way.
func TouchedRecords ¶
TouchedRecords collects the feature ids whose record files are among the changed paths. A record that moved with its code has already been followed — a heuristic that only holds against HEAD; see ChangeSet.FollowedRecords.
func UnifiedDiff ¶
UnifiedDiff renders the change between two versions of a file.
func ValidReadDir ¶
ValidReadDir reports whether rel is a directory a manifest may declare under "reads": relative, slash-separated, and every segment in grammar.
func ValidReadExt ¶
ValidReadExt reports whether ext is an extension a manifest may declare under the object form of "reads".
func VerificationKinds ¶
func VerificationKinds() []string
VerificationKinds returns the schema-defined test categories in display order. Callers receive their own slice and cannot change Core discovery behavior.
func WithinResolved ¶
WithinResolved reports whether a path stays inside a directory once symlinks are resolved.
Types ¶
type ADRConfig ¶
type ADRConfig struct {
Directory string `yaml:"directory"`
}
ADRConfig is the optional ADR reader configuration in .facetrc.yaml.
type ADRStatusProposal ¶
type ADRStatusProposal struct {
Path string `json:"path"`
Current string `json:"current"`
Target string `json:"target"`
Reason string `json:"reason,omitempty"`
Successor string `json:"successor,omitempty"`
Before string `json:"before,omitempty"`
After string `json:"after,omitempty"`
Diff string `json:"diff"`
Achieved bool `json:"achieved"`
}
ADRStatusProposal is an inspection artifact, never permission to write. Successor is metadata only; this feature invents no successor line format.
func ProposeADRStatus ¶
func ProposeADRStatus(root, path, target, reason, successor string) (ADRStatusProposal, error)
ProposeADRStatus reads only the ADR plugin's existing scope. A missing or ambiguous status is refused; dates and other suffix prose stay opaque.
type AgentTool ¶
type AgentTool struct {
Plugin string
Tool string
Description string
// Input is the JSON Schema the plugin declared, passed to the model as
// written. Empty means the tool takes nothing.
Input json.RawMessage
}
AgentTool is one plugin tool the agent may call through facet mcp.
type Anchor ¶
type Anchor struct {
// Repository and Reference identify the selected source independently of its checkout.
Repository string `json:"repository,omitempty"`
Reference string `json:"reference,omitempty"`
ID string
// Registry is the name written in front of the id, empty when the tag was
// unqualified and therefore belongs to whichever registry scans the file.
Registry string
Path string
Line int
Role string
// Proves lists scenario IDs from the facet-proves tag following this
// anchor, in declaration order. Empty means no scenario association was
// declared; it does not establish whether the code implements a scenario.
Proves []string
}
Anchor is one @facet: tag found in source.
func ScanAnchors ¶
func ScanAnchors(root string, opts ScanOptions) ([]Anchor, error)
ScanAnchors finds every @facet: anchor under root.
func ScanContent ¶
ScanContent extracts the anchors carried by a file whose bytes the caller already holds.
type AnchorBlock ¶
type AnchorBlock struct {
Repository string `yaml:"repository,omitempty"`
OriginRevision string `yaml:"origin_revision,omitempty"`
OriginContentHash string `yaml:"origin_content_hash,omitempty"`
// OriginWorktree records where this block was first saved. Empty means a
// legacy sidecar whose provenance is unknown, never a proven local orphan.
OriginWorktree string `yaml:"origin_worktree,omitempty"`
// Lines are the anchor lines verbatim, indentation included, so a block
// goes back exactly as it was written.
Lines []string `yaml:"lines"`
// Before is the line the block sat directly above in the cleaned file,
// and Occurrence which of that line's repetitions — a file's package
// clause appears once, an empty line does not.
Before string `yaml:"before"`
Occurrence int `yaml:"occurrence"`
// AtEnd marks a block that closed the file, which has no line to sit
// above.
AtEnd bool `yaml:"at_end,omitempty"`
}
AnchorBlock is one run of anchor lines as they stand in a working copy, together with where they stand.
func InjectAnchors ¶
func InjectAnchors(clean []byte, blocks []AnchorBlock) ([]byte, []AnchorBlock)
InjectAnchors is the smudge half.
func InjectAnchorsInView ¶
func InjectAnchorsInView(content []byte, blocks []AnchorBlock, repository string) ([]byte, []AnchorBlock)
InjectAnchorsInView never applies an association explicitly owned by another logical repository. Existing exact placement checks handle version changes.
func StripPrivateAnchors ¶
func StripPrivateAnchors(path string, content, committed []byte) ([]byte, []AnchorBlock)
StripPrivateAnchors is the clean half.
func (AnchorBlock) Placeable ¶
func (b AnchorBlock) Placeable(lines []string) bool
Placeable reports whether the block's place exists in the given cleaned lines. Not stored: whether a block is orphaned is a fact about one checkout at one moment, and the sidecar is shared by every worktree of the clone.
type Artifact ¶
type Artifact struct {
Subject Subject `yaml:"subject"`
Feature string `yaml:"feature"`
Slots []string `yaml:"slots,omitempty"`
Generator Generator `yaml:"generator"`
GeneratedAt string `yaml:"generated_at,omitempty"`
Inputs []Input `yaml:"inputs"`
}
Artifact is one manifest entry.
type BackfillChange ¶
type BackfillChange struct {
Feature string `json:"feature"`
Path string `json:"path"`
Added []Fix `json:"added"`
}
BackfillChange is one record the pass would touch, and what it would add.
type BackfillOptions ¶
type BackfillOptions struct {
// Match overrides DefaultFixPattern. A repository that does not use
// Conventional Commits needs its own rule, and one baked into the binary
// would be a rule about somebody else's project.
Match string
// Since and Until are passed to git as authored-date bounds.
Since string
Until string
// Limit caps the commits walked, not the fixes found. Bounding the walk is
// what makes a run predictable in cost; bounding the result would make it
// unpredictable, because the density of fixes is not known in advance.
Limit int
// Rev is the revision to walk back from. Empty means HEAD.
Rev string
// DryRun reports what would be written without writing it.
DryRun bool
}
BackfillOptions bounds and steers a pass over the history.
type BackfillReport ¶
type BackfillReport struct {
// Candidates is how many commits the heuristic accepted.
Candidates int `json:"candidates"`
// Recorded is how many (commit, feature) attributions were appended.
Recorded int `json:"recorded"`
// Skipped is how many attributions a record had already judged.
Skipped int `json:"skipped"`
// Unresolved are candidates that touched no anchored file, listed rather
// than counted: they are the pass's blind spot made visible, and anyone
// deciding whether the ledger is trustworthy needs to see them.
Unresolved []Commit `json:"unresolved,omitempty"`
Changes []BackfillChange `json:"changes,omitempty"`
DryRun bool `json:"dry_run,omitempty"`
}
BackfillReport is what a pass did, or would have done.
func Backfill ¶
func Backfill(reg Registry, records []Record, anchors []Anchor, commits []Commit, opts BackfillOptions) (BackfillReport, error)
Backfill attributes candidate commits to records and appends what is new.
type Backing ¶
type Backing struct {
// Feature is the record's id.
Feature string `json:"feature"`
// Scenario is the scenario id the state belongs to.
Scenario string `json:"scenario"`
// Variant names the variant this entry overrides, empty for the scenario's
// shared state.
Variant string `json:"variant,omitempty"`
// Path is the record's location, for reporting.
Path string `json:"path,omitempty"`
State string `json:"state"`
Reason string `json:"reason,omitempty"`
UnblockedBy string `json:"unblocked_by,omitempty"`
}
Backing is one declared backing state: a scenario's own, or one variant's override of it.
func UnbackedScenarios ¶
UnbackedScenarios lists every unbacked state across the records, in registry order. This is the query the field exists to make answerable: which declared behaviour is not backed by data, and what would supply it.
type Band ¶
Band is the range a metric is ordinarily inside. Guidance, never a rule: nothing in this file fails a run, and a project whose shape is genuinely unusual keeps its shape.
type Baseline ¶
type Baseline struct {
// Ref is what was compared against: the caller's revision, HEAD, or
// AcceptedBaselineRef.
Ref string `json:"ref"`
// Kind is one of BaselineHead, BaselineAccepted, BaselineExplicit.
Kind string `json:"kind"`
// Commit is the resolved commit, empty when it did not resolve.
Commit string `json:"commit,omitempty"`
// Scope is always ScopeWorkingTree; it travels with the result so a
// reader never has to assume what window it covers.
Scope string `json:"scope"`
// Status is one of BaselineOK, BaselineMissing, BaselineUnavailable.
Status string `json:"status"`
// Error carries git's own words when the status is not ok.
Error string `json:"error,omitempty"`
// AcceptedAt and Outcome describe the last 'facet drift accept', when
// the baseline is one.
AcceptedAt string `json:"acceptedAt,omitempty"`
Outcome string `json:"outcome,omitempty"`
}
Baseline is the revision a change set was measured against, as resolved.
func AcceptReview ¶
AcceptReview records that the changes to the given paths — every change in the working tree when none are given — have been reviewed, by moving this worktree's accepted baseline forward to include them.
func AcceptReviewFromBaseline ¶
AcceptReviewFromBaseline starts a partial review at an explicitly confirmed revision, so incoming commits outside the reviewed paths remain unreviewed even when no accepted snapshot existed before the pull.
type BranchSession ¶
type BranchSession struct {
// Dir is the worktree root.
Dir string
// Branch is the branch this session writes on.
Branch string
// Root is the repository the worktree belongs to.
Root string
}
BranchSession is one write session: a branch and a worktree to write it in.
func OpenBranchSession ¶
func OpenBranchSession(root, branch string) (*BranchSession, error)
OpenBranchSession creates a branch and a worktree to write it in, for the repository whose working tree contains root.
func (*BranchSession) Close ¶
func (s *BranchSession) Close() error
Close removes the worktree and leaves the branch.
func (*BranchSession) Push ¶
func (s *BranchSession) Push(remote string) error
Push sends the session's branch to the remote.
type Calibration ¶
type Calibration struct {
Registry string `json:"registry,omitempty"`
Records int `json:"records"`
Scenarios int `json:"scenarios"`
AnchoredFiles int `json:"anchoredFiles"`
Domains int `json:"domains"`
Capabilities int `json:"capabilities"`
HasTaxonomy bool `json:"hasTaxonomy"`
// Knowledge counts answered, pending and not-applicable slots. Counts have
// no median or band; the fixed struct always marshals as an object.
Knowledge KnowledgeTally `json:"knowledge"`
// EchoedNames counts single-feature capabilities whose segment repeats the
// feature name, including names that differ only by a prefix or suffix.
EchoedNames int `json:"echoedNames"`
// SuffixPairs counts sibling IDs shaped as 'x' and 'x-<word>' within one
// capability. Both records contribute to the metrics; the count flags
// possible duplication without deciding whether they describe one feature.
SuffixPairs int `json:"suffixPairs"`
Metrics []Metric `json:"metrics"`
// Hotspots are the files no record claims, in directories where the
// neighbours are claimed — the one measurement here taken from the
// repository rather than from the registry. Never nil, for the same reason
// Readings is not.
Hotspots []UnanchoredFile `json:"hotspots"`
// Readings contains ordered diagnostic sentences. It is never nil, so JSON
// consumers always receive an array, including [] for a small registry.
Readings []string `json:"readings"`
}
Calibration is the shape of one registry.
func Calibrate ¶
func Calibrate(reg Registry, opts ScanOptions) (Calibration, error)
Calibrate measures one registry's shape.
func CalibrateFrom ¶
func CalibrateFrom(reg Registry, features []Record, scanned []Anchor, walked []SourceFile) (Calibration, error)
CalibrateFrom measures a registry a caller has already read.
type CapabilityNode ¶
type CapabilityNode struct {
Title string `yaml:"title"`
Purpose string `yaml:"purpose"`
Classification Classification `yaml:"classification"`
}
CapabilityNode is one capability: the second segment of an id.
type ChangeSet ¶
type ChangeSet struct {
Root string
Baseline Baseline
Files []FileChange
// Unreadable lists baseline paths whose previous content git could not
// produce, so their lost associations cannot be named. Reported, never
// dropped: an unreadable before-state is missing evidence, not an absence
// of change.
Unreadable []string
// contains filtered or unexported fields
}
ChangeSet is everything that moved between a baseline and the working tree.
func LoadChangeSet ¶
LoadChangeSet compares the working tree under root with ref. An empty ref means this worktree's accepted baseline when it has one, and HEAD otherwise.
func LoadSourceChangeSet ¶
LoadSourceChangeSet projects repository-local paths into the registry's workspace. Each repository keeps its own accepted review ref.
func (ChangeSet) Changed ¶
Changed lists every path that moved, by its current name; a deleted path by the name it had.
func (ChangeSet) Deleted ¶
Deleted lists the paths removed since the baseline. A rename's old path is not a deletion.
func (ChangeSet) FollowedRecords ¶
FollowedRecords is the set of record ids whose files changed — the "the record moved with its code" heuristic — or nil when the baseline is one somebody chose.
func (*ChangeSet) ReferenceChanges ¶
func (c *ChangeSet) ReferenceChanges(reg Registry, current []Anchor, known map[string]bool) []ReferenceChange
ReferenceChanges names, for one registry, every anchor association the working tree has moved or lost since the baseline.
func (ChangeSet) RepositoryBaselines ¶
func (c ChangeSet) RepositoryBaselines() []RepositoryBaseline
type Classification ¶
type Classification string
Classification is how much of the product's reason to exist lives in a node: Evans' core / supporting / generic subdomain. Strategic weight only — it is orthogonal to depth, which is already the id.
const ( ClassificationCore Classification = "core" ClassificationSupporting Classification = "supporting" ClassificationGeneric Classification = "generic" )
type CodeBand ¶
type CodeBand struct {
Band string `json:"band"`
Codes []string `json:"codes"`
// Gaps lists every code between the band's lowest and highest assigned
// code that nothing claims. Nothing below the lowest or above the
// highest is a gap — an unopened range is not a hole in one.
Gaps []string `json:"gaps,omitempty"`
// Next is one past the band's highest assigned code, empty when the
// band's codes are not uniform enough in shape to extend safely or that
// successor would exceed the fixed width.
Next string `json:"next,omitempty"`
}
CodeBand summarizes one band's assigned codes and the numbers nobody has claimed yet between the lowest and the highest assigned code — the question "what is the next free code in E2xxx" a register exists to answer without grepping a service's source and hoping.
type Commit ¶
type Commit struct {
SHA string `json:"sha"`
Date string `json:"date"`
Subject string `json:"subject"`
Issue string `json:"issue,omitempty"`
Files []string `json:"files"`
}
Commit is one candidate bugfix commit and what it changed.
func BugfixCommits ¶
func BugfixCommits(root string, opts BackfillOptions) ([]Commit, error)
BugfixCommits walks the history and returns the commits whose subject the heuristic accepts, newest first.
type CommitResult ¶
type CommitResult struct {
SHA string `json:"sha"`
Files []string `json:"files"`
// Skipped names the paths git had nothing to record about — the source half
// of a rename of a file this branch created and never committed, most
// often. Reported rather than dropped quietly, because "committed" and
// "committed all but one of the things you named" are different answers.
Skipped []string `json:"skipped,omitempty"`
}
CommitResult is what a commit produced.
type Config ¶
type Config struct {
SourceViews *sourceview.Config `yaml:"source_views,omitempty"`
// TestFeaturePrefix explicitly limits test evidence to one product area.
TestFeaturePrefix string `yaml:"test_feature_prefix"`
TestFeaturePrefixes []string `yaml:"test_feature_prefixes"`
// ADR configures the project-wide directory read by the ADR plugin.
ADR ADRConfig `yaml:"adr"`
BPMN ADRConfig `yaml:"bpmn"`
SchemaVersion string `yaml:"schema_version"`
Runners map[string]Runner `yaml:"runners"`
// Single-registry shorthand.
Records string `yaml:"records"`
Schema string `yaml:"schema"`
Sources []string `yaml:"sources"`
// Multi-registry form.
Registries map[string]registryEntry `yaml:"registries"`
// Conventions names the project's authoring conventions document, shared
// by every registry that does not declare its own. Absent means
// FACET-CONVENTIONS.md at the root if it exists, and nothing otherwise.
// See conventions.go for what the document is, and what it cannot do.
Conventions string `yaml:"conventions"`
// Embedding configures one retrieval index shared by all project registries.
// Each indexed chunk retains its originating registry.
Embedding EmbeddingConfig `yaml:"embedding"`
// ErrorCodes configures the identifier pattern 'facet errors' and the
// error-codes lint check scan for. It applies to the whole project, not
// to one registry: a company-wide numbering convention spans every
// registry the same way it spans every team.
ErrorCodes errorCodesEntry `yaml:"error_codes"`
// Forges names the forge behind a git host this tooling cannot recognise.
ForgeHosts map[string]string `yaml:"forges"`
// Hooks holds project-wide guard switches. Absent means all guards are on.
// The binary pre-tool-use gate and shell fallback read it from HEAD;
// commitGateOffAt implements the binary check in the CLI package.
Hooks HooksConfig `yaml:"hooks"`
// TrackerList is the 'trackers:' section: where the project keeps its
// issues and how a ticket key maps to one of them. Read through Trackers().
TrackerList []Tracker `yaml:"trackers"`
// Path is where the config was read from, empty when none exists.
Path string `yaml:"-"`
// contains filtered or unexported fields
}
Config is the parsed .facetrc.yaml.
func LoadConfig ¶
LoadConfig reads project configuration. A missing file is not an error; the project uses the default layout without requiring configuration.
func LoadConfigUnresolved ¶
LoadConfigUnresolved validates committed configuration without consulting local checkout bindings or invocation selection. Revision policy readers use this.
func LoadConfigWithResolvedSourceView ¶
func LoadConfigWithResolvedSourceView(root string, frozen *sourceview.ResolvedView) (*Config, error)
LoadConfigWithResolvedSourceView keeps the command's already selected checkout bindings, without reading or resolving local bindings again.
func LoadConfigWithSourceView ¶
LoadConfigWithSourceView resolves the invocation's explicit view without changing process environment or any checkout. Empty uses FACET_SOURCE_VIEW, then the shared default. Registry records remain rooted in the same project.
func (*Config) ADRDirectory ¶
ADRDirectory returns the project ADR directory, including for a nil Config.
func (*Config) BPMNDirectory ¶
func (*Config) CommitGateOff ¶
CommitGateOff reports whether the configuration switches the commit gate off. It answers false for a nil Config.
func (*Config) Description ¶
Description returns a registry's prose description, if it declared one.
func (*Config) EmbeddingSettings ¶
func (c *Config) EmbeddingSettings() EmbeddingConfig
EmbeddingSettings returns the embedding configuration with environment overrides applied.
func (*Config) ErrorCodePattern ¶
ErrorCodePattern returns the project's configured identifier pattern, or DefaultErrorCodePattern when none is declared — including for a nil Config, so a caller that skipped LoadConfig still gets the default rather than an empty pattern.
func (*Config) Forges ¶
Forges returns the project's forge declarations, empty when it makes none — including for a nil Config, so a caller that skipped LoadConfig gets the behaviour of a project that declares nothing rather than a panic.
func (*Config) MultiRegistry ¶
MultiRegistry reports whether the project declares more than the implicit one.
func (*Config) Names ¶
Names lists the declared registries, sorted. Empty for a single-registry project — the implicit registry has no name its author would recognise.
func (*Config) ProductSection ¶
ProductSection decodes the named top-level section into out. The first value is false when the configuration has no such key; out is then left untouched. It answers for a nil Config and for a project without .facetrc.yaml too.
func (*Config) ResolveSourceView ¶
func (c *Config) ResolveSourceView(selected string) (*sourceview.ResolvedView, error)
ResolveSourceView resolves one explicit selection. Configuration readers normally use the already frozen Registry.SourceView created by LoadConfig.
type CorePin ¶
type CorePin struct {
// File is the configuration the pin was read from.
File string
// Core is the required version without a leading "v".
Core string
}
CorePin is a validated project pin on the Core version, read from requires.core in .facetrc.yaml. It is deliberately not part of Config: LoadConfig never reads it, so a broken pin can never break configuration loading — and with it every hook, which would fall back to the default layout and go silent in a project whose records live elsewhere. Only the pin check reads and refuses it.
func ReadCorePin ¶
ReadCorePin reads only the 'requires:' section of a project's configuration.
type Deviation ¶
type Deviation struct {
// Feature is the record's id.
Feature string `json:"feature"`
// Scenario is the scenario id the deviation belongs to.
Scenario string `json:"scenario"`
// Path is the record's location, for reporting.
Path string `json:"path,omitempty"`
Reason string `json:"reason"`
// ConfirmedBy is how the behaviour was established, or "" when nobody
// recorded it. Empty means unrecorded, never unconfirmed.
ConfirmedBy string `json:"confirmed_by,omitempty"`
// TrackedAs is where the fix is tracked. Empty covers both an absent field
// and an explicit null: neither resolves to anything, and the distinction
// between "nobody said" and "nothing tracks it" is one a reader of the
// record makes, not one any check here acts on.
TrackedAs string `json:"tracked_as,omitempty"`
}
Deviation is one declared defect: behaviour the anchored code has that nobody wants, recorded against the scenario that describes it.
func DeclaredDeviations ¶
DeclaredDeviations lists every deviation across the records, in registry order. This is the question the field exists to make answerable: which documented behaviour is a defect rather than a promise, and where is each one tracked.
type Digest ¶
type Digest struct {
SHA256 string `yaml:"sha256"`
}
Digest identifies content. Content hashing is deliberate: modification times are not preserved by git, so a fresh checkout would mark every artifact stale.
type DiscoveredRunner ¶
type DiscoveredRunner struct {
Name string `json:"name"`
Measured bool `json:"measured"`
Files []string `json:"files"`
}
DiscoveredRunner names a runner and its selected repository-relative test files. Measured is true only after valid, nonempty discovery succeeds.
type DomainNode ¶
type DomainNode struct {
Title string `yaml:"title"`
Purpose string `yaml:"purpose"`
Classification Classification `yaml:"classification"`
Owner *taxonomyOwner `yaml:"owner"`
Capabilities map[string]CapabilityNode `yaml:"capabilities"`
}
DomainNode is one product domain: the first segment of an id.
type Drift ¶
type Drift struct {
// ID is the record whose anchored source moved.
ID string `json:"id"`
// Path is the changed file, relative to the repository root.
Path string `json:"path"`
// ChangedAt is the file's modification time. The change is in the working
// tree, measured against a baseline rather than a commit of its own, so
// there is no commit to date it by.
ChangedAt string `json:"changedAt"`
// Registry names which of a monorepo's registries reported the entry.
// Empty in a project declaring none, where the name would be invented.
Registry string `json:"registry,omitempty"`
}
Drift is anchored source that changed while the record it anchors did not.
@facet: authoring/guardrails/drift-notice @facet-role: related
type DriftReport ¶
type DriftReport struct {
Repositories []RepositoryBaseline `json:"repositories,omitempty"`
Baseline Baseline `json:"baseline"`
// Drift is anchored source that changed while its record stood still.
Drift []Drift `json:"drift"`
// StaleReferences are records still naming a path a rename moved.
StaleReferences []StaleReference `json:"staleReferences"`
// ReferenceChanges are the implementation associations that a deletion,
// a rename or a removed anchor moved or lost.
ReferenceChanges []ReferenceChange `json:"referenceChanges"`
// Unreadable names baseline paths whose previous content could not be
// read, so whatever they anchored is unknown rather than absent.
Unreadable []string `json:"unreadable"`
}
DriftReport is the one answer every surface gives: what moved since the baseline, what the baseline was, and which associations were lost.
func ComputeDrift ¶
func ComputeDrift(root string, registries []Registry, ref string) (DriftReport, error)
ComputeDrift runs the whole comparison for a project, once: one change set against one baseline, handed to every registry's own anchor scan. An empty ref means the worktree's accepted baseline, or HEAD when it has none.
func ComputeDriftInRepository ¶
func ComputeDriftInRepository(root string, registries []Registry, ref, repository string) (DriftReport, error)
ComputeDriftInRepository optionally selects one declared source repository.
type EmbeddingConfig ¶
type EmbeddingConfig struct {
// Provider is "openai" for any OpenAI-compatible /embeddings endpoint —
// which is nearly all of them, hosted and local alike — or "local" for the
// lexical embedder built into this binary.
Provider string `yaml:"provider"`
// BaseURL is the API root, without the trailing /embeddings.
BaseURL string `yaml:"base_url"`
// Model is the embedding model's name at that endpoint.
Model string `yaml:"model"`
// APIKeyEnv names the environment variable holding the bearer token. Empty
// is valid: a local Ollama or LM Studio wants no key.
APIKeyEnv string `yaml:"api_key_env"`
// Dimensions shortens the vector where the provider supports it. Zero
// leaves the model's own width.
Dimensions int `yaml:"dimensions"`
// Batch is how many chunks go in one request. Zero uses the default.
Batch int `yaml:"batch"`
// Index is where the vectors are written, relative to the repository root.
// Empty puts them beside the generation manifest.
Index string `yaml:"index"`
}
EmbeddingConfig says how to turn text into vectors, and where to keep them.
@facet: navigation/retrieval/embedding-configuration @facet-role: config
type EnumDeclaration ¶
type EnumDeclaration struct {
// Entity is the owning data-entity record's id.
Entity string
// Path is the record's location, for reporting.
Path string
// Field is the canonical_schema field name the constraint belongs to.
Field string
// Values is the declared value list, in the order written.
Values []string
}
EnumDeclaration is one field's enum-shaped constraint, extracted from a data-entity record's canonical_schema. Entity and Path identify the record it came from, so a divergence finding can name both sides of a discrepancy.
type ErrorCode ¶
type ErrorCode struct {
Code string `json:"code"`
// Band is the code's letter prefix plus its first digit — "E1" out of
// "E1074" — or empty when the match has no digits to band on at all.
Band string `json:"band,omitempty"`
Mentions []ErrorCodeMention `json:"mentions"`
}
ErrorCode is every place the pattern matched one distinct identifier, across the whole set of records extraction ran over.
type ErrorCodeMention ¶
type ErrorCodeMention struct {
Feature string `json:"feature"`
Path string `json:"path,omitempty"`
Field string `json:"field"`
}
ErrorCodeMention is one place a code was found: which record, which facet, and where that record lives on disk.
type ErrorCodeRegister ¶
ErrorCodeRegister is the extracted view over a set of records: every distinct identifier found, and the per-band summary built from them.
func ExtractErrorCodes ¶
func ExtractErrorCodes(records []Record, pattern string) (ErrorCodeRegister, error)
ExtractErrorCodes scans intent.summary, contract.scenarios[].statement, and knowledge.common_pitfalls across every given record for pattern, and groups what it finds into a register.
type ExamplesBlock ¶
type ExamplesBlock struct {
// Name is what the set of cases has in common, or "" when the block is
// unnamed. Empty means the author wrote no name, never that the block has
// no cases in common.
Name string
// Columns are the columns in effect for this block, inherited or its own.
Columns []string
// Inherited records where Columns came from, because a finding about a row
// in an inheriting block has to point the author at the block that
// actually declares the headings.
Inherited bool
// Rows are the cases, one slice of cells per case, positionally matched to
// Columns. Cells are kept as decoded values rather than as strings: what
// every caller here needs is how many there are, and stringifying them
// would invent a rendering that belongs to a reader.
Rows [][]any
}
ExamplesBlock is one named set of cases under a Scenario Outline: a heading row and the rows beneath it, for one rule.
type Exclusion ¶
type Exclusion struct {
Feature string `json:"feature"`
Path string `json:"path,omitempty"`
Commit string `json:"commit"`
Reason string `json:"reason"`
}
Exclusion is a commit a reviewer judged not to be a defect in this feature.
type FeatureTestResult ¶
type FeatureTestResult struct {
ID string `json:"id"`
State string `json:"state"`
Files map[string]string `json:"files"`
}
FeatureTestResult combines the execution states of a record's referenced test files. These associations do not establish scenario-level proof.
type FileChange ¶
type FileChange struct {
// Status is git's letter: A, M, D, R, T, or '?' for an untracked file.
Status byte
// Path is where the file is now; for a deletion, where it was.
Path string
// OldPath is the baseline path of a rename, empty otherwise.
OldPath string
}
FileChange is one path git reports between the baseline and the working tree.
type Finding ¶
type Finding struct {
Severity Severity `json:"severity"`
Check string `json:"check"`
// Registry names which of a monorepo's registries produced the finding.
// Empty in a project that declares none, where the name would be invented.
Registry string `json:"registry,omitempty"`
Path string `json:"path,omitempty"`
ID string `json:"id,omitempty"`
Message string `json:"message"`
Hint string `json:"hint,omitempty"`
}
Finding is one lint result.
func RunPluginLint ¶
RunPluginLint calls the lint tool of every plugin installed under pluginsDir that declares it, against reg, and returns their findings. An empty pluginsDir, a missing directory and a directory of plugins without "facet.lint" all return nil — `facet lint` then behaves exactly as it did before.
@facet: registry/integrity/plugin-lint @facet-role: primary
type Fix ¶
type Fix struct {
// Feature is the record's id.
Feature string `json:"feature"`
// Path is the record's location, for reporting.
Path string `json:"path,omitempty"`
Commit string `json:"commit"`
Date string `json:"date"`
// Files are the repository-relative paths the commit changed that carry an
// anchor for this feature — not every path the commit touched.
Files []string `json:"files"`
Subject string `json:"subject,omitempty"`
Issue string `json:"issue,omitempty"`
RecordedBy string `json:"recorded_by,omitempty"`
}
Fix is one bugfix commit attributed to one feature.
type Generator ¶
type Generator struct {
Pipeline string `yaml:"pipeline"`
Model string `yaml:"model,omitempty"`
PromptVersion string `yaml:"prompt_version,omitempty"`
}
Generator records the non-hermetic part of the pipeline. An LLM is not a deterministic compiler, so the model and prompt version are inputs: changing either invalidates the artifact exactly as a new compiler would.
type GitHubSource ¶
type GitHubSource struct {
APIBase string
DownloadBase string
HTTPClient *http.Client
Token string
}
GitHubSource resolves a github:owner/repo@tag reference to bytes, entirely through injected functions — the same shape bin/facet's shell functions have, kept swappable so a test can stand in an httptest server for GitHub itself rather than reaching the network.
type GitRelevantSet ¶
type GitRelevantSet struct {
// contains filtered or unexported fields
}
GitRelevantSet reports whether a walked path is one git itself considers relevant under the root GitRelevantFiles was called with.
func GitRelevantFiles ¶
func GitRelevantFiles(root string) (*GitRelevantSet, bool)
GitRelevantFiles selects tracked and non-ignored untracked files using git ls-files --exclude-standard, including local, global and XDG exclusions. Embedded repository directory entries are accepted as path prefixes. Returns unavailable outside a Git worktree or when Git fails; callers retain their ordinary walker filtering. Delegate ignore semantics to Git: walker-local patterns re-scope root rules in subdirectories. Exact path matching alone also loses files beneath the trailing-slash entries Git uses for embedded repositories.
func (*GitRelevantSet) Contains ¶
func (s *GitRelevantSet) Contains(path string) bool
Contains reports whether path (as gocodewalker's own File.Location - an absolute path built the same way this set's entries were) is one git itself would show.
type Glossary ¶
type Glossary struct {
SchemaVersion string `yaml:"schema_version"`
// Categories are the groups, in the order the project wants them shown. A
// list rather than a map, unlike the taxonomy's domains: the order of a
// glossary is the project's own — already why nothing sorts Terms — and a
// map would surrender it to whatever order the parser hands back.
Categories []GlossaryCategory `yaml:"categories"`
Terms []GlossaryTerm `yaml:"terms"`
}
Glossary is a project's terminology, declared once and linked everywhere.
func LoadGlossary ¶
LoadGlossary reads the deployment's terminology. A missing file is not an error — it means the project has not declared one.
func (*Glossary) Categorised ¶
Categorised reports whether anything in the file groups its terms at all.
func (*Glossary) CategoryDeclared ¶
CategoryDeclared reports whether the glossary declares a category id.
func (*Glossary) CategoryIDs ¶
CategoryIDs lists the declared category ids, in the order the file declares them and without repeating one declared twice.
func (*Glossary) Configured ¶
Configured reports whether the project declares a glossary at all. A project without one behaves exactly as it did before — the same rule that governs the variant map and the taxonomy, and the reason adoption is a decision rather than a migration.
func (*Glossary) DuplicateCategories ¶
DuplicateCategories lists every category id the glossary declares more than once, sorted. The sibling of DuplicateTerms, one level up.
func (*Glossary) DuplicateTerms ¶
DuplicateTerms lists every term the glossary defines more than once, sorted.
func (*Glossary) Grouped ¶
func (g *Glossary) Grouped() []GlossaryGroup
Grouped arranges the terms under their categories.
func (*Glossary) UnusedCategories ¶
UnusedCategories lists the declared categories no term names, in declared order.
type GlossaryCategory ¶
type GlossaryCategory struct {
// ID is what a term names this category by. A slug rather than the heading
// itself, so rewording the heading touches one line instead of every term.
ID string `yaml:"id"`
// Title is the heading in the product's own language.
Title string `yaml:"title"`
// Purpose is the one line saying which terms belong here, and by
// implication which do not. Optional, and the sentence somebody consults
// when deciding where a new term goes.
Purpose string `yaml:"purpose"`
}
GlossaryCategory is one group the terms fall into.
@facet: registry/layout/glossary-categories @facet-role: primary
type GlossaryEdited ¶
type GlossaryEdited struct {
// Diff contains the proposed unified change required by FACET §6.4,
// allowing the caller to present it for review.
Diff string `json:"diff"`
// Before and After are the file's bytes, so a caller needing the content
// does not have to read it back off the branch.
Before string `json:"-"`
After string `json:"-"`
}
GlossaryEdited reports what a glossary write did.
func RemoveGlossaryTerm ¶
func RemoveGlossaryTerm(path, term string) (GlossaryEdited, error)
RemoveGlossaryTerm undefines a term.
func SetGlossaryTerm ¶
func SetGlossaryTerm(path, term, definition, category string) (GlossaryEdited, error)
SetGlossaryTerm defines a term or changes the one that is there.
type GlossaryGroup ¶
type GlossaryGroup struct {
// ID is the category id, or "" for the terms that name no category.
ID string
// Title and Purpose are the declared wording, empty when Declared is false
// — there is none to show for a category the file does not declare, and
// inventing one here is inventing it for every surface.
Title string
Purpose string
// Declared reports whether this group is a category the file declares. An
// undeclared id (Declared false, ID set) is the error case; the
// uncategorised group (Declared false, ID empty) is the absent one.
Declared bool
Terms []GlossaryTerm
}
GlossaryGroup is one heading of a grouped glossary, with the terms under it.
type GlossaryRenamed ¶
type GlossaryRenamed struct {
GlossaryEdited
From string `json:"from"`
To string `json:"to"`
// StillSaying names what still writes the old spelling: record ids first,
// then the paths a registered prose source names, each in the order the
// registry holds them.
StillSaying []string `json:"stillSaying"`
}
GlossaryRenamed reports what a rename did, including what it could not do.
func RenameGlossaryTerm ¶
func RenameGlossaryTerm(reg Registry, path, from, to string) (GlossaryRenamed, error)
RenameGlossaryTerm changes a term's spelling, and reports what that orphaned.
type GlossarySession ¶
type GlossarySession struct {
*BranchSession
// GlossaryPath is the glossary inside the worktree. The only path any
// glossary write resolves to: no caller supplies one, so no caller can name
// another file.
GlossaryPath string
// contains filtered or unexported fields
}
GlossarySession is one open branch and the glossary on it.
func OpenGlossaryBranch ¶
func OpenGlossaryBranch(reg Registry, branch string) (*GlossarySession, error)
OpenGlossaryBranch opens a branch to write a glossary change on.
func (*GlossarySession) Commit ¶
func (s *GlossarySession) Commit(message string) (CommitResult, error)
Commit records the glossary change on the branch.
type GlossaryTerm ¶
type GlossaryTerm struct {
Term string `yaml:"term"`
// Category is the id of the group this term belongs under, from the
// glossary's own Categories list. Empty means nobody has categorised the
// term — not that it belongs somewhere general, which is the rule §4.4.2
// states for classification and the reason nothing here defaults.
Category string `yaml:"category"`
Definition string `yaml:"definition"`
// Renderings stores per-locale wording for translation consumers. The
// registry loads these values but does not apply them to generated output.
Renderings map[string]string `yaml:"renderings"`
}
GlossaryTerm is one term of art and what it means in this product.
type Grant ¶
type Grant struct {
Tools []string `json:"tools"`
AITools []string `json:"ai_tools"`
// Env names the variables the user let through to this plugin's binary.
Env []string `json:"env"`
AIEnv []string `json:"ai_env"`
}
Grant is the user's answer, recorded in grants.json, and the host holds it — never the plugin's own surface.
type HooksConfig ¶
type HooksConfig struct {
// CommitGate is "on" (the default when empty) or "off". Off stops the
// plugin's commit gate from judging this project's commits. The environment
// variable FACET_SKIP_COMMIT_GATE=1 remains the per-session escape hatch and
// wins over this. Only "on" and "off" are accepted: a typo such as "of"
// must not read as either.
CommitGate string `yaml:"commit_gate"`
}
HooksConfig is the optional 'hooks:' section of .facetrc.yaml.
@facet: authoring/guardrails/commit-gate @facet-role: config
type Hotspot ¶
type Hotspot struct {
Feature string `json:"feature"`
Path string `json:"path,omitempty"`
Total int `json:"total"`
LastFix string `json:"last_fix,omitempty"`
Files []FileCount `json:"files,omitempty"`
}
Hotspot is one feature's whole defect history, reduced to what a reader ranking features by fragility needs.
type IndexEntry ¶
IndexEntry is one record, reduced to what routing needs.
func BuildIndex ¶
func BuildIndex(regs []Registry) []IndexEntry
BuildIndex reads the registries and reduces each record to an entry.
type IndexOptions ¶
type IndexOptions struct {
// MaxBytes bounds the rendered index. Zero uses DefaultIndexBytes.
MaxBytes int
// Summaries includes the first sentence of each record's intent. Off gives
// the bare roster, which is what fits when a registry is very large.
Summaries bool
}
IndexOptions bounds what RecordIndex renders.
@facet: navigation/interfaces/record-roster @facet-role: primary
type Input ¶
type Input struct {
Role string `yaml:"role"` // record | anchor
URI string `yaml:"uri"` // repo-relative path
Digest Digest `yaml:"digest"`
}
Input is one thing that fed a generated artifact.
type InstallOptions ¶
type InstallOptions struct {
Replace bool
Source SourceInfo
DevLinkTarget string
}
InstallOptions carries what Install needs beyond the staged, verified package itself.
type InstalledPlugin ¶
type InstalledPlugin struct {
ID string
Manifest PackageManifest
Source SourceInfo
// VerifyError is set when the installed content no longer verifies —
// most relevant for a --dev install, whose bytes can change between
// `add --dev` and the next time this is read.
VerifyError error
// State is the one column a caller should read to ask "is this plugin
// loadable": "ok", or "invalid: <reason>". VerifyError already carries
// the same fact, but json.Marshal turns an error into "{}" — a plugin
// list served as JSON needs a plain string, not a value only Go's error
// interface can print, so State is computed once, here, and is what both
// `facet plugin list`'s text and --json output show.
State string
}
func InstalledPlugins ¶
func InstalledPlugins(dir string) ([]InstalledPlugin, error)
InstalledPlugins lists every plugin installed under dir, sorted by id. A directory that does not exist yields an empty list, not an error — an unconfigured or fresh plugins directory is the ordinary state, the one pluginsDir returns when no plugin was ever added.
type KnowledgeTally ¶
type KnowledgeTally struct {
Answered int `json:"answered"`
Open int `json:"open"`
Inapplicable int `json:"inapplicable"`
}
KnowledgeTally is the three-way split of a record's Knowledge slots: answered, still open, and declared to have no answer.
@facet: registry/layout/granularity-calibration @facet-role: related
func (*KnowledgeTally) Add ¶
func (k *KnowledgeTally) Add(o KnowledgeTally)
Add folds another tally into this one.
type LintOptions ¶
type LintOptions struct {
Scan ScanOptions
Schema bool // validate records against JSON Schema
Skip map[string]bool
// Today is an ISO date used for flag retirement checks. Injected rather
// than read from the clock so a run is reproducible (spec §6.3).
Today string
// OwnedElsewhere holds ids some other registry of the same project has a
// record for. It excuses an anchor only in shared code — see Shared.
OwnedElsewhere map[string]bool
// one registry. Nil means nothing is shared, which is true of every project
// declaring one registry.
Shared func(rel string) bool
// KnownRegistries contains the declared registry names. A qualified anchor
// prefix outside this set is reported as an unknown registry.
KnownRegistries map[string]bool
// KnownIDs holds every record id the project has, across all categories and
// all registries. A lineage reference is judged against the whole project,
// not against one registry: a monorepo's products legitimately depend on
// each other, and `depends_on` carries no registry prefix to say so.
KnownIDs map[string]bool
// IsTestPath classifies a repository-relative path as test code for the
// test-only-anchors check. Nil uses IsTestPath's default heuristic; a
// project whose tests, parity harnesses, or benchmarks live somewhere that
// default does not recognise supplies its own.
IsTestPath func(rel string) bool
// ErrorCodePattern is the regular expression the error-codes check uses to
// find stable identifiers in intent.summary, contract.scenarios[].statement,
// and knowledge.common_pitfalls. Empty means DefaultErrorCodePattern —
// the E\d{4} band — which is what a caller that never read
// .facetrc.yaml's error_codes key should get.
ErrorCodePattern string
// Changes is the change set the lost-anchors check reads, loaded once by
// LintAll for every registry. Nil means Lint loads one itself against the
// worktree's default baseline.
Changes *ChangeSet
// PluginsDir is the directory of installed plugins whose facet.lint
// sidecar tool runs as part of this lint (RunPluginLint). Empty means
// none run, which is what every caller that does not set it gets.
PluginsDir string
// Registry narrows LintAll to the findings of one declared registry. The
// others are still read: shared code and lineage are judged against the
// whole project, and linting one registry alone would report every shared
// anchor and cross-registry dependency of another product as dangling.
// Empty lints every registry.
Registry string
}
LintOptions selects which checks run.
type LoadOptions ¶
type LoadOptions struct {
// AssetSuffix selects a platform-specific GitHub release asset for native products.
AssetSuffix string
SHA256 string
// HTTPClient is used for an https:// source. Nil means http.DefaultClient.
HTTPClient *http.Client
// GitHub carries what a github: source needs to reach an API standing in
// for GitHub's — nil means the real one.
GitHub *GitHubSource
}
LoadOptions carries what a source needs beyond the source string itself.
type Manifest ¶
type Manifest struct {
SchemaVersion string `yaml:"schema_version"`
Artifacts []Artifact `yaml:"artifacts"`
}
Manifest is the committed record of what produced what.
func LoadManifest ¶
LoadManifest reads the generation manifest. A missing file is not an error — a project that has generated nothing yet has an empty manifest.
type ManifestAITool ¶
type ManifestAITool struct {
Tool string `json:"tool"`
Description string `json:"description"`
// Input is a JSON Schema object, passed to the model as written.
Input json.RawMessage `json:"input"`
}
ManifestAITool is one tool as the agent sees it.
type ManifestEvents ¶
type ManifestEvents struct {
Listens []string `json:"listens,omitempty"`
Emits []string `json:"emits,omitempty"`
}
ManifestEvents is the manifest's "events" block.
type ManifestSidecar ¶
type ManifestSidecar struct {
// Bin is the base name; the host appends the OS and architecture.
Bin string `json:"bin"`
Env []string `json:"env,omitempty"`
AIEnv []string `json:"ai_env,omitempty"`
// SHA256 maps "<os>-<arch>" to the checksum of that build.
SHA256 map[string]string `json:"sha256"`
}
ManifestSidecar declares the binary and what it may see.
type Metric ¶
type Metric struct {
Name string `json:"name"`
Median float64 `json:"median"`
Min int `json:"min"`
Max int `json:"max"`
Samples int `json:"samples"`
Below int `json:"below"`
Above int `json:"above"`
Band Band `json:"band"`
}
Metric is one measurement of the registry's shape, with the band it is judged against and how many samples fell outside it.
type Outline ¶
type Outline struct {
// Feature is the record's id.
Feature string
// Scenario is the scenario id the examples belong to.
Scenario string
// Path is the record's location, for reporting.
Path string
// Statement is the scenario's prose, carried along because the placeholders
// in it are half of what an outline asserts: without it the blocks are a
// table nobody can say is used.
Statement string
// Blocks are the example blocks, in the order the record declares them.
Blocks []ExamplesBlock
}
Outline is one contract scenario that declares examples: the statement whose placeholders the cases fill, and the blocks that fill them.
func (Outline) DeclaredColumns ¶
DeclaredColumns is the union of every block's columns, which is the set a placeholder may name.
func (Outline) Placeholders ¶
Placeholders lists the distinct parameters named in the statement, in the order they first appear.
type PackageManifest ¶
type PackageManifest struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
API int `json:"api"`
Entry string `json:"entry"`
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
License string `json:"license,omitempty"`
Homepage string `json:"homepage,omitempty"`
Areas []string `json:"areas,omitempty"`
Slots []string `json:"slots,omitempty"`
Tools []string `json:"tools,omitempty"`
AITools []ManifestAITool `json:"ai_tools,omitempty"`
Reads []ReadDecl `json:"reads,omitempty"`
Events *ManifestEvents `json:"events,omitempty"`
Sidecar *ManifestSidecar `json:"sidecar,omitempty"`
}
PackageManifest is plugin.json in full, as read from a package under verification.
func Pack ¶
func Pack(dir, outPath string) (PackageManifest, error)
func VerifyPackage ¶
func VerifyPackage(dir string, opts VerifyOptions) (PackageManifest, error)
func (PackageManifest) AddedRights ¶
func (m PackageManifest) AddedRights(other PackageManifest) bool
type PluginBroker ¶
type PluginBroker struct {
// contains filtered or unexported fields
}
PluginBroker resolves a call against one plugin directory.
func NewPluginBroker ¶
func NewPluginBroker(dir string) *PluginBroker
NewPluginBroker reads from one directory of installed plugins.
func NewPluginBrokerForPlatform ¶
func NewPluginBrokerForPlatform(dir, platform string) *PluginBroker
NewPluginBrokerForPlatform is NewPluginBroker with the platform string named explicitly, rather than read from runtime.GOOS/runtime.GOARCH.
func (*PluginBroker) AgentTools ¶
func (b *PluginBroker) AgentTools() []AgentTool
AgentTools lists every tool the user has granted to the agent, across every installed plugin.
func (*PluginBroker) Allowed ¶
func (b *PluginBroker) Allowed(id, tool string) error
Allowed returns nil only for a declared and granted tool, or a tool declared by a bundled manifest. It returns the manifest, grant, or permission error otherwise. Keep declaration and grant separate: editing a plugin manifest must not widen the reader's grant. Shipping a bundled manifest grants its tools and declared environment without an installed grants.json.
func (*PluginBroker) AllowedForAgent ¶
func (b *PluginBroker) AllowedForAgent(id, tool string) error
AllowedForAgent is Allowed plus the agent's own grant.
func (*PluginBroker) Call ¶
func (b *PluginBroker) Call(ctx context.Context, id, tool string, args json.RawMessage) (SidecarReply, error)
Call brokers one call: check, then route, and never the other way round.
func (*PluginBroker) CallForAgent ¶
func (b *PluginBroker) CallForAgent(ctx context.Context, id, tool string, args json.RawMessage) (SidecarReply, error)
CallForAgent brokers one call made by the agent.
func (*PluginBroker) Granted ¶
func (b *PluginBroker) Granted(id string) (Grant, error)
Granted reads what grants.json allows. A missing file means nothing.
func (*PluginBroker) Manifest ¶
func (b *PluginBroker) Manifest(id string) (PluginManifest, error)
Manifest reads and validates one plugin's manifest.
func (*PluginBroker) StopAll ¶
func (b *PluginBroker) StopAll()
StopAll ends every running sidecar. Called when the host exits.
type PluginManifest ¶
type PluginManifest struct {
ID string `json:"id"`
Tools []string `json:"tools"`
AITools []ManifestAITool `json:"ai_tools"`
Sidecar *ManifestSidecar `json:"sidecar"`
// Reads names the directories, relative to the registry root, this
// plugin may read through repo.list/repo.read. A directory absent
// from here is refused the same way an undeclared tool is: the manifest
// asks, and reading a directory nobody named would be a right the plugin
// granted itself. Empty for a plugin that never calls either tool.
Reads []ReadDecl `json:"reads"`
}
PluginManifest is the part of plugin.json the host reads.
type PrivateAnchors ¶
type PrivateAnchors struct {
Path string `yaml:"path"`
Blocks []AnchorBlock `yaml:"blocks"`
}
PrivateAnchors is the sidecar record for one file: the anchors that live in its working copy and nowhere in git.
func ListPrivateAnchors ¶
func ListPrivateAnchors(gitDir string) ([]PrivateAnchors, error)
ListPrivateAnchors walks every sidecar under a git directory.
func LoadPrivateAnchors ¶
func LoadPrivateAnchors(gitDir, rel string) (PrivateAnchors, error)
LoadPrivateAnchors reads one file's sidecar; a file without one has none.
func MergeSidecar ¶
func MergeSidecar(previous PrivateAnchors, found []AnchorBlock, clean []byte) PrivateAnchors
MergeSidecar decides what the sidecar holds after a clean: the blocks the working copy carries now, plus any previous block whose lines are absent but whose place is absent too.
func MergeSidecarInView ¶
func MergeSidecarInView(previous PrivateAnchors, found []AnchorBlock, clean []byte, worktree, repository, revision string) PrivateAnchors
MergeSidecarInView preserves other-version associations, including unknown legacy origins; only a known association from this exact context is removable.
func (PrivateAnchors) Orphans ¶
func (pa PrivateAnchors) Orphans(working []byte) []AnchorBlock
Orphans reports which of a file's private blocks are not standing in the given working-copy content: the ones no smudge could place.
type ProductDocument ¶
type ProductDocument struct {
// Path returns where the document lives in a registry.
Path func(reg Registry) string
// Schema is the file name of its schema inside the schema directory. The
// document is validated only where the project carries that schema.
Schema string
}
ProductDocument is a committed declaration a product keeps inside a registry, validated against a schema of the registry's schema directory the way Core's own registry documents are: by the full lint and by the write-time check of a single saved file. A build that does not link the product does not validate the document, and a project file at that path is then left alone.
type ProductSectionValidator ¶
ProductSectionValidator checks one product section of a loaded configuration. It reads the section through Config.ProductSection and returns an error that names ConfigName and the offending key, the way Core's own validation does.
type ProseSource ¶
ProseSource names the files of a product's prose, beside the records, whose text still writes term, as paths relative to the repository root. A source that cannot read its prose names nothing: the rename that asks has already succeeded, and an unreadable file is a finding for that product's own check.
type Provenance ¶
type Provenance struct {
// Kind is which verification bucket the test was declared under
// (unit_tests, property_tests, integration_tests, e2e_tests).
Kind string
// TestID is the test_ref's own id — a file path, a file-and-test-name
// pair, or a CI job id, in whatever form the project writes it.
TestID string
// Scenario is the contract scenario id this test claims to prove.
Scenario string
}
Provenance is one `proves` entry: a single test named as evidence for a single contract scenario. A test_ref with three scenarios in `proves` flattens to three Provenance values, one per scenario.
type PushForge ¶
PushForge contains only metadata needed after a proposal push. It makes no claim about the state or contents of the user's working files.
func ForgeForPush ¶
ForgeForPush reads the remote of the working tree at root and the forge declaration of the project at configRoot, without git status, which can read unfinished working files to hash them. An empty root has no remote.
type ReadDecl ¶
type ReadDecl struct {
Dir string
// Ext is empty for the string form. Use Exts for the effective list.
Ext []string
// contains filtered or unexported fields
}
ReadDecl is one entry of a manifest's "reads": a directory and the extensions readable in it. The plain-string form "docs/adr" is a ReadDecl with no Ext and means DefaultReadExt only; the object form {"dir": "rules", "ext": [".dmn"]} names its extensions.
func (ReadDecl) MarshalJSON ¶
MarshalJSON writes the form the entry came in.
func (*ReadDecl) UnmarshalJSON ¶
UnmarshalJSON accepts the string form and the object form and nothing else.
type Record ¶
type Record struct {
Path string
Category string
ID string `yaml:"id"`
SchemaVersion string `yaml:"schema_version"`
Lifecycle string `yaml:"lifecycle"`
Fields map[string]any `yaml:"-"`
}
Record is a loaded FACET record. Fields is the full decoded document, kept alongside the typed fields so schema validation and generic access work without a second parse.
func LoadRecord ¶
LoadRecord reads and decodes a single record.
func (Record) ActiveAnywhere ¶
ActiveAnywhere reports whether the feature is live on any variant.
func (Record) Backings ¶
Backings returns every declared backing state on the record, flattened: one entry per scenario that declares a state, plus one per per-variant override.
func (Record) CommonPitfallsText ¶
CommonPitfallsText returns every prose string under knowledge.common_pitfalls — the shared answer, plus any per-variant override answers — for identifier extraction. A slot with a question but no answer contributes nothing: that is a legitimate Knowledge gap (KnowledgeGaps reports it), not text to scan.
func (Record) ContractScenarios ¶
ContractScenarios lists the ids of the record's contract scenarios, in the order they are written.
func (Record) DefectTotal ¶
DefectTotal is the number of recorded fixes.
func (Record) DefectsByFile ¶
DefectsByFile counts how many recorded fixes touched each file, hottest first, ties broken by path so the order is stable.
func (Record) Deviations ¶
Deviations returns every declared deviation on the record, one per scenario that declares one.
func (Record) EnumDeclarations ¶
func (r Record) EnumDeclarations() []EnumDeclaration
EnumDeclarations extracts every enum-shaped constraint from a data-entity record's canonical_schema.fields, normalizing all four spellings ParseEnumConstraint recognizes. A field with none — including one declaring `type: enum` whose values are written some other way — contributes nothing; see ParseEnumConstraint for why that is a feature, not a gap.
func (Record) ExcludedCommits ¶
ExcludedCommits returns the commits deliberately not counted, with their reasons. Sorted by hash so output is stable.
func (Record) KnowledgeContradictions ¶
KnowledgeContradictions lists the Knowledge slots that both give an answer and declare there is none — an 'answer', or a 'derive_from' instructing a generator to render one, beside a 'not_applicable'.
func (Record) KnowledgeCounts ¶
func (r Record) KnowledgeCounts() KnowledgeTally
KnowledgeCounts splits this record's slots three ways.
@facet: registry/layout/granularity-calibration @facet-role: related
func (Record) KnowledgeGaps ¶
KnowledgeGaps lists the Knowledge slots that carry a question but no answer anywhere. These are the facts only a feature owner can supply, so they are reported as work for a human rather than filled in.
func (Record) KnowsCommit ¶
KnowsCommit reports whether this record has already judged a commit — either by recording it as a fix or by excluding it.
func (Record) LifecycleOn ¶
LifecycleOn reports the record's lifecycle for one variant. A record without a variants block applies its single lifecycle to every variant.
func (Record) Outlines ¶
Outlines returns every contract scenario on the record that declares examples, in the order the document declares them.
func (Record) Provenances ¶
func (r Record) Provenances() []Provenance
Provenances flattens every verification.*[].proves entry on the record, in the order the document declares them.
func (Record) ScenarioStatements ¶
ScenarioStatements lists the prose statement of every contract scenario, in declaration order — the Gherkin-style sentence a Given/When/Then is authored as. Unlike ContractScenarios, which returns the stable ids, this is the human-authored text an identifier extractor (facet errors) reads.
func (Record) Variants ¶
func (r Record) Variants() map[string]VariantState
Variants returns the record's per-variant states, or nil when the record is single-variant and carries a plain lifecycle instead.
type ReferenceChange ¶
type ReferenceChange struct {
Kind string `json:"kind"`
Registry string `json:"registry,omitempty"`
ID string `json:"id"`
Role string `json:"role,omitempty"`
// Path is where the anchor stood at the baseline.
Path string `json:"path"`
// NewPath is where the file is now, for a rename or for an anchor
// removed from a file that was also renamed.
NewPath string `json:"newPath,omitempty"`
Evidence string `json:"evidence"`
// Surviving counts this id's anchors still standing in the working tree.
// A lost association is reported whatever this says: losing one
// implementation is worth a look even when another remains. Zero is not
// upgraded to an error here — the orphan-records check owns that.
Surviving int `json:"surviving"`
}
ReferenceChange is one implementation association that moved or was lost between the baseline and the working tree.
func (ReferenceChange) Lost ¶
func (r ReferenceChange) Lost() bool
Lost reports whether the change leaves the record without an association it had. A rename that carried its anchor along does not.
type Registry ¶
type Registry struct {
Name string // declared name; empty for a project that declares none
Root string // repository root
RecordsDir string // absolute path to the records directory
SchemaDir string // absolute path to the JSON schemas
Sources []string // legacy path filters; with SourceView, scoped to selected repositories
SourceView *sourceview.ResolvedView // frozen coherent source selection; Root still owns the records
// ConventionsPath is the registry's effective conventions document,
// absolute, or empty when the project has none. ConventionsSource says
// which step of the precedence chose it (see resolveConventions).
ConventionsPath string
ConventionsSource string
// contains filtered or unexported fields
}
Registry describes where one project keeps its FACET data.
func Open ¶
Open resolves a project's default registry: the only one in a project that declares none, and the first declared one otherwise.
func (Registry) Adopted ¶
Adopted reports whether the project uses FACET at all. Every hook checks this first so the tooling stays inert in unrelated repositories.
func (Registry) CategoryDir ¶
CategoryDir returns the directory holding records of one category.
func (Registry) Claims ¶
Claims reports whether a root-relative path falls inside this registry's sources. A registry declaring no sources claims the whole repository.
func (Registry) GlossaryPath ¶
GlossaryPath returns where the glossary lives for a registry.
func (Registry) Label ¶
Label names the registry for a message, or returns an empty string when the project has only the implicit one and a name would be noise.
func (Registry) LoadCategory ¶
LoadCategory reads every record of one category, sorted by path so output is deterministic — FACET spec 6.3 requires byte-identical results for identical inputs at the same registry revision.
func (Registry) LoadFeatures ¶
LoadFeatures is the common case: every feature record in the registry.
func (Registry) ManifestPath ¶
ManifestPath returns where the manifest lives for a registry.
func (Registry) PathForID ¶
PathForID returns where a feature record with the given id must live. The path is the id, so a mismatch between the two is itself a defect.
func (Registry) RAGIndexPath ¶
RAGIndexPath returns where a registry's vector index lives by default.
func (Registry) ScanOptions ¶
func (r Registry) ScanOptions() ScanOptions
ScanOptions narrows an anchor scan to this registry's declared sources.
func (Registry) TaxonomyPath ¶
TaxonomyPath returns where the taxonomy lives for a registry.
func (Registry) ValidateSourceView ¶
ValidateSourceView reports resolution failures even for legacy Open/OpenSet callers whose return signature cannot carry a configuration error.
func (Registry) VariantMapPath ¶
VariantMapPath returns where the variant map lives for a registry.
type RegistrySet ¶
type RegistrySet []Registry
RegistrySet is a project's registries addressed as one thing, for the interfaces that answer questions about ids without knowing which registry a caller means: the MCP tools and the language server.
func OpenSet ¶
func OpenSet(root string) RegistrySet
OpenSet resolves the project registries, using the default registry when configuration cannot be read so the interface can still answer. Invalid source views remain failed selections on the fallback and cannot scan.
func (RegistrySet) Claimants ¶
func (s RegistrySet) Claimants(rel string) []Registry
Claimants lists every registry whose sources cover a repository-relative path. A path claimed by more than one is shared code.
func (RegistrySet) Multi ¶
func (s RegistrySet) Multi() bool
Multi reports whether ids need qualifying to be unambiguous.
func (RegistrySet) Owners ¶
func (s RegistrySet) Owners(qualified string) []Registry
Owners lists registries holding an id in RegistrySet order. Config.All builds its set in alphabetical name order.
func (RegistrySet) Primary ¶
func (s RegistrySet) Primary() Registry
Primary is the registry to answer for when nothing narrows the question.
type Report ¶
type Report struct {
Findings []Finding `json:"findings"`
Checked struct {
Records int `json:"records"`
Anchors int `json:"anchors"`
Registries []string `json:"registries,omitempty"`
} `json:"checked"`
}
Report collects findings across all checks.
func Lint ¶
func Lint(reg Registry, opts LintOptions) (Report, error)
Lint runs the registry's integrity checks.
func LintAll ¶
func LintAll(root string, opts LintOptions) (Report, error)
LintAll runs the checks over every declared registry for facet lint. A project declaring none receives exactly one pass over its default registry.
func ValidateRecord ¶
ValidateRecord checks the facts a write hook can establish from one saved record or registry document. Registry-wide contracts and source walks stay with Lint.
type RepositoryBaseline ¶
type RepositoryBaseline struct {
RecordHashes map[string]string `json:"record_hashes,omitempty"`
Repository string `json:"repository,omitempty"`
RegistryInput bool `json:"registry_input,omitempty"`
IdentityStatus string `json:"identity_status,omitempty"`
Path string `json:"path"`
Baseline Baseline `json:"baseline"`
}
RepositoryBaseline identifies each independently compared source repository.
func ReviewSourceRepositories ¶
func ReviewSourceRepositories(root string, registries []Registry, repository string, paths []string, outcome string, reset bool) ([]RepositoryBaseline, error)
ReviewSourceRepositories accepts or resets independently in each selected repository. Paths are workspace-relative; a clone's SHA must be selected with --repository rather than interpreted in the outer repository.
@facet: registry/history/drift-review @facet-role: related
func ReviewSourceRepositoriesFromBaseline ¶
func ReviewSourceRepositoriesFromBaseline(root string, registries []Registry, repository string, paths []string, outcome string, reset bool, ref string) ([]RepositoryBaseline, error)
ReviewSourceRepositoriesFromBaseline supports bootstrapping a partial catch-up review from the last reviewed revision instead of current HEAD.
type ResolvedTicket ¶
type ResolvedTicket struct {
Key string `json:"key"`
Tracker string `json:"tracker,omitempty"`
URL string `json:"url,omitempty"`
ByDefault bool `json:"by_default,omitempty"`
}
ResolvedTicket says which tracker a key belongs to and where it lives.
func ResolveTicket ¶
func ResolveTicket(trackers []Tracker, key, named string) ResolvedTicket
ResolveTicket assigns a key to a tracker: the one the reference names, else the first whose pattern matches, else the default. With no tracker found it returns the key alone — never an invented link.
type Runner ¶
type Runner struct {
Repository string `yaml:"repository"`
Cwd string `yaml:"cwd"`
Command string `yaml:"command"`
List string `yaml:"list"`
ListFormat string `yaml:"list_format"`
Report string `yaml:"report"`
ReportFile string `yaml:"report_file"`
}
Runner declares commands; discovery never executes Command or reads reports.
type RunnerExecution ¶
type RunnerExecution struct {
Name string `json:"name"`
Exit int `json:"exit_code"`
Results map[string]string `json:"files"`
ReportProblem string `json:"report_problem,omitempty"`
}
RunnerExecution reports a runner's exit code and file-level test states; ReportProblem explains why its report could not provide usable evidence.
type ScanOptions ¶
type ScanOptions struct {
View *sourceview.ResolvedView
Dirs []string // relative to root; empty means the root itself
// contains filtered or unexported fields
}
ScanOptions narrows a scan. Zero value means "the whole repository".
func ScanOptionsFromEnv ¶
func ScanOptionsFromEnv() ScanOptions
ScanOptionsFromEnv reads the source-directory override the shell tooling honours. Superseded by .facetrc.yaml's `sources`, and kept because CI jobs and migration scripts point the scan at a scratch tree, which a committed file cannot express.
type Section ¶
type Section struct {
Name string `json:"name"`
Bytes int `json:"bytes"`
Lines int `json:"lines"`
// contains filtered or unexported fields
}
Section is one addressable slice of a record file: a top-level key, or a key one level below it written as "parent.child".
func SectionOutline ¶
SectionOutline splits a record's YAML into its sections without parsing it.
type Sidecar ¶
type Sidecar struct {
// contains filtered or unexported fields
}
Sidecar is one plugin's running binary.
func NewSidecar ¶
func NewSidecar(spec SidecarSpec) (*Sidecar, error)
NewSidecar checks the binary before anything runs it.
func (*Sidecar) Call ¶
func (s *Sidecar) Call(ctx context.Context, call SidecarCall) (SidecarReply, error)
Call sends one request and waits for its reply.
type SidecarCall ¶
type SidecarCall struct {
Tool string `json:"tool"`
Args json.RawMessage `json:"args,omitempty"`
}
SidecarCall is one request to a plugin's binary.
type SidecarReply ¶
type SidecarReply struct {
Result json.RawMessage `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
SidecarReply is what comes back. Exactly one of Result or Error is set.
type SidecarSpec ¶
type SidecarSpec struct {
// Bin is the executable's path, already resolved for this OS and arch.
Bin string
// SHA256 is the checksum the binary must have, lowercase hex.
SHA256 string
// Env names the variables to pass through. Nothing else reaches the child.
Env []string
// Timeout bounds one call. Zero means SidecarDefaultTimeout.
Timeout time.Duration
}
SidecarSpec is what a plugin manifest declares about its binary.
type SourceFile ¶
type SourceFile struct {
Repository string `json:"repository,omitempty"`
Reference string `json:"reference,omitempty"`
// Path is absolute, as the walker produced it.
Path string
// Loc is the file's line count.
Loc int
// Anchored is true when the file carried at least one anchor this scan
// accepted.
Anchored bool
// OptedOut is true when the file declared the ignore marker in its head.
OptedOut bool
}
SourceFile is one file the scan opened, with the size and the answer that make it comparable to its neighbours.
func SelectedSourceFiles ¶
func SelectedSourceFiles(reg Registry) ([]SourceFile, error)
SelectedSourceFiles enumerates precisely the files used by the authoritative selected-view scanner, with local Path plus portable Repository/Reference. Corpus consumers should share this rather than discover additional clones.
type SourceInfo ¶
type SourceKind ¶
type SourceKind string
SourceKind names where an installed plugin's bytes came from, written into .source.json so a later `update` knows how to fetch the same thing again.
const ( SourceKindFile SourceKind = "file" SourceKindFolder SourceKind = "folder" SourceKindHTTPS SourceKind = "https" SourceKindGitHub SourceKind = "github" )
type SplitCheck ¶
type SplitCheck struct {
Parent string `json:"parent"`
Children []string `json:"children"`
Losses []SplitLoss `json:"losses"`
}
SplitCheck is what one comparison found.
func CheckSplit ¶
func CheckSplit(parentYAML []byte, childrenYAML map[string][]byte) (SplitCheck, error)
CheckSplit reports what the parent record carried and no child does.
@facet: registry/layout/recut-loss-detector @facet-role: primary
type SplitLoss ¶
SplitLoss is one thing that stood in the parent record and is in none of the children.
@facet: registry/layout/recut-loss-detector @facet-role: related
type StaleReference ¶
type StaleReference struct {
ID string `json:"id"`
Path string `json:"path"`
RenamedTo string `json:"renamedTo"`
Registry string `json:"registry,omitempty"`
}
StaleReference is one record that still names a path a rename has moved.
type Status ¶
type Status struct {
Artifact Artifact `json:"-"`
Path string `json:"path"`
Feature string `json:"feature"`
State State `json:"state"`
Reasons []string `json:"reasons,omitempty"`
}
Status is a checked artifact and why it landed in its state.
type SuffixPair ¶
type SuffixPair struct {
Capability string `json:"capability"`
Base string `json:"base"`
Suffixed string `json:"suffixed"`
Suffix string `json:"suffix"`
}
SuffixPair is one 'x' beside one 'x-<word>' in the same capability.
func SiblingSuffixPairs ¶
func SiblingSuffixPairs(featuresPerCapability map[string][]string) []SuffixPair
SiblingSuffixPairs returns sorted pairs of ids x and x-<word> in the same capability. Only a single alphanumeric suffix after the last hyphen matches. The shape suggests a duplicated feature but can also name legitimate neighbours, so callers warn and ask for review rather than reject records. @facet: registry/layout/doubled-features @facet-role: primary
type Taxonomy ¶
type Taxonomy struct {
SchemaVersion string `yaml:"schema_version"`
Domains map[string]DomainNode `yaml:"domains"`
}
Taxonomy declares the product decomposition ids are drawn from.
func LoadTaxonomy ¶
LoadTaxonomy reads the deployment's product decomposition. A missing file is not an error — it means the project has not declared one.
func (*Taxonomy) CapabilityDeclared ¶
CapabilityDeclared reports whether a capability exists under a domain.
func (*Taxonomy) CapabilityNames ¶
CapabilityNames lists the capabilities declared under a domain, sorted.
func (*Taxonomy) ClassificationOf ¶
func (t *Taxonomy) ClassificationOf(domain, capability string) Classification
ClassificationOf reports a node's strategic weight, inheriting the domain's value when the capability declares none.
func (*Taxonomy) Configured ¶
Configured reports whether the project declares a taxonomy at all. A project without one has no taxonomy constraints — the same rule that governs the variant map, and the reason adoption is a decision rather than a migration.
func (*Taxonomy) DomainDeclared ¶
DomainDeclared reports whether a domain segment exists in the taxonomy.
func (*Taxonomy) DomainNames ¶
DomainNames lists the declared domains, sorted.
type TermMatch ¶
TermMatch is one occurrence of a defined term in a piece of prose, with the byte offsets a caller slices the text on.
type TestDiscovery ¶
type TestDiscovery struct {
FeaturePrefixes []string `json:"feature_prefixes,omitempty"`
FeaturePrefix string `json:"feature_prefix,omitempty"`
Registry string `json:"registry,omitempty"`
Runners []DiscoveredRunner `json:"runners"`
Findings []TestFinding `json:"findings"`
// contains filtered or unexported fields
}
TestDiscovery combines one registry's runner selections and discovery findings. It records file discovery, without claiming tests passed.
func CheckTests ¶
func CheckTests(ctx context.Context, cfg *Config, reg Registry, selected string, update bool) (TestDiscovery, error)
CheckTests executes list only. Missing discovery makes absence unmeasured; known new unclaimed files still fail, even in a partially measured registry.
func (TestDiscovery) Failed ¶
func (r TestDiscovery) Failed() bool
Failed reports whether discovery produced an error finding.
type TestExecution ¶
type TestExecution struct {
InputProblem string `json:"input_problem,omitempty"`
RegistryIdentity string `json:"registry_identity,omitempty"`
RegistryRepository string `json:"registry_repository,omitempty"`
RegistrySnapshot *TestSourceSnapshot `json:"registry_snapshot,omitempty"`
SourceSnapshots map[string]TestSourceSnapshot `json:"source_snapshots,omitempty"`
SourceRevisions map[string]string `json:"source_revisions,omitempty"`
RecordHashes map[string]string `json:"record_hashes,omitempty"`
// Head is the commit the tests ran on and Dirty says whether the tree had
// uncommitted or untracked changes when they started. Both are measured
// before any runner starts and are left out where git could not be asked,
// so a report without them says "not measured" instead of "clean".
Head string `json:"head,omitempty"`
Dirty *bool `json:"dirty,omitempty"`
Discovery TestDiscovery `json:"discovery"`
Runners []RunnerExecution `json:"runners"`
Features []FeatureTestResult `json:"features"`
}
TestExecution combines discovery, runner results and derived feature states for one registry's test run.
func ExecuteTests ¶
func ExecuteTests(ctx context.Context, cfg *Config, reg Registry, selected string, update bool, stdout, stderr io.Writer) (result TestExecution, err error)
ExecuteTests runs commands verbatim after discovery. Only positively bound fresh per-file evidence can mark a feature passed; exit 0 supplies no evidence.
func (TestExecution) ExitCode ¶
func (r TestExecution) ExitCode() int
ExitCode preserves the first nonzero runner exit in sorted registry order. Drift and measured file failures use 1 only when all runner exits were zero.
func (TestExecution) FileCounts ¶
func (r TestExecution) FileCounts() TestFileCounts
FileCounts combines every discovered file across runners: failed wins over unmeasured, which wins over passed, and a file no report mentioned is unmeasured. Files of a runner whose discovery was not measured are unmeasured too.
func (TestExecution) HasUnmeasured ¶
func (r TestExecution) HasUnmeasured() bool
HasUnmeasured reports gaps in both feature claims and runner file evidence. This is opt-in CLI policy, separate from the runner's actual process exit.
type TestFileCounts ¶
type TestFileCounts struct {
Passed int `json:"passed"`
Failed int `json:"failed"`
Unmeasured int `json:"unmeasured"`
}
TestFileCounts tallies a run's test files by their combined state.
func (TestFileCounts) Measured ¶
func (c TestFileCounts) Measured() bool
Measured reports whether any file produced usable evidence. A run where everything is unmeasured has no failure count worth printing: zero failed of nothing measured is not "zero failing".
type TestFinding ¶
type TestFinding struct {
Severity string `json:"severity"`
Code string `json:"code"`
Runner string `json:"runner,omitempty"`
Path string `json:"path,omitempty"`
Message string `json:"message"`
}
TestFinding is discovery drift, never a test result.
type TestSourceSnapshot ¶
type TestSourceSnapshot struct {
Revision string `json:"revision"`
ContentHash string `json:"content_hash"`
Dirty bool `json:"dirty"`
}
TestSourceSnapshot is the state a repository was in when a test run started: its revision, a hash of the content the run read from it, and whether its working tree had uncommitted changes. A run records one per source repository of the registry's source view, and one for the registry's own records.
type Tracker ¶
type Tracker struct {
ID string `yaml:"id"`
Pattern string `yaml:"pattern"`
URL string `yaml:"url"`
Default bool `yaml:"default"`
// contains filtered or unexported fields
}
Tracker is one entry of the 'trackers:' list in .facetrc.yaml: where a project keeps its issues, how a key from there looks, and how to link to it.
@facet: registry/layout/ticket-trackers @facet-role: primary
type UnanchoredFile ¶
type UnanchoredFile struct {
// Path is relative to the registry root.
Path string
// Loc is the file's line count.
Loc int
// Dir is the directory the judgement was made in, relative to the root.
Dir string
// DirAnchoredPercent is how much of that directory, by line count, does
// carry an anchor. The number is the whole argument: it is what makes this
// file's silence stand out rather than be the local norm.
DirAnchoredPercent int
}
UnanchoredFile is one file no record claims, in a neighbourhood that is otherwise documented. (Hotspot is taken: defects.go ranks features by fragility, which is a different question about a different thing.)
func UnanchoredHotspots ¶
func UnanchoredHotspots(root string, files []SourceFile, isTest func(string) bool) []UnanchoredFile
UnanchoredHotspots reports unanchored files that sit in well-anchored directories.
type UndocumentedDir ¶
type UndocumentedDir struct {
// Dir is relative to the registry root.
Dir string
// Loc is the directory's line count, tests and opted-out files excluded.
Loc int
// Files is how many files that line count is spread over.
Files int
// Largest is the biggest file in it, relative to the root. "2655 lines
// somewhere" is not something a reader can start on; a file name is.
Largest string
}
UndocumentedDir is a directory in which no file carries an anchor at all.
func UndocumentedDirectories ¶
func UndocumentedDirectories(root string, files []SourceFile, isTest func(string) bool) []UndocumentedDir
UndocumentedDirectories reports directories in which nothing is anchored, in a repository that anchors a reasonable share of its code.
type VariantMap ¶
type VariantMap struct {
SchemaVersion string `yaml:"schema_version"`
Variants map[string]variantEntry `yaml:"variants"`
}
VariantMap declares which paths belong to which variant.
func LoadVariantMap ¶
func LoadVariantMap(path string) (*VariantMap, error)
LoadVariantMap reads the deployment's variant declaration. A missing file is not an error — it means the project is single-variant.
func (*VariantMap) Configured ¶
func (m *VariantMap) Configured() bool
Configured reports whether the project uses variants at all. A project without a variant map has no variant declarations.
func (*VariantMap) Declared ¶
func (m *VariantMap) Declared(name string) bool
Declared reports whether a variant name exists in the map.
func (*VariantMap) Names ¶
func (m *VariantMap) Names() []string
Names lists the declared variants, sorted.
func (*VariantMap) Replaces ¶
func (m *VariantMap) Replaces(name string) string
Replaces returns the variant this one supersedes, if any.
type VariantState ¶
VariantState is one variant's state for a feature.
type VerifyOptions ¶
type VerifyOptions struct {
SkipSums bool
// ExtraAllowed names files the allow-list (rule 3) must accept in addition
// to what the manifest itself earns. A raw, just-extracted package must
// never carry these — that would let a malicious package smuggle in a
// forged `.source.json` or forged `grants.json` under a name the host
// treats as its own. But an already-installed plugin directory legitimately
// carries them, because Install wrote them itself after the package's own
// files had already passed this same check. InstalledPlugins passes them
// here rather than weakening allowedNames for everyone.
ExtraAllowed []string
}
VerifyOptions changes which of the seven rules VerifyPackage enforces.
Source Files
¶
- adr_proposal.go
- backfill.go
- backing.go
- branch_session.go
- bundled_sidecar.go
- calibrate.go
- changes.go
- config.go
- conventions.go
- corepin.go
- created_at.go
- defects.go
- deviation.go
- drift.go
- enum.go
- errors.go
- examples.go
- filter.go
- forge.go
- front_matter.go
- gitignore.go
- glossary.go
- glossary_write.go
- hotspots.go
- index.go
- knowledge.go
- last_changed.go
- lint.go
- lint_adoption.go
- lint_anchors.go
- lint_contracts.go
- lint_entities.go
- lint_glossary.go
- lint_lifecycle.go
- lint_lineage.go
- lint_links.go
- lint_schema.go
- lint_taxonomy.go
- lint_test_coverage.go
- lint_variants.go
- lint_verification.go
- lost_anchors.go
- plugin_agent_tools.go
- plugin_broker.go
- plugininstall.go
- pluginlint.go
- pluginpack.go
- pluginpkg.go
- pluginsource.go
- pluginsource_github.go
- product_documents.go
- product_sections.go
- provenance.go
- reachability.go
- record.go
- registry.go
- repo_read.go
- scan.go
- sections.go
- sidecar.go
- sidecar_parentlink_linux.go
- source_changes.go
- source_runner.go
- split.go
- taxonomy.go
- test_cucumber.go
- test_discovery.go
- test_execution.go
- test_execution_unix.go
- test_reports.go
- test_safety.go
- test_safety_unix.go
- trackers.go
- undocumented.go
- variant.go
- verification_submodules.go
- write_paths.go