provenance

package
v3.16.0 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package provenance implements Provenance Records functionality for LineSpec. Provenance Records are structured YAML artifacts that capture organizational intent, constraints, and reasoning behind system changes.

Index

Constants

View Source
const (
	OverlapSpecsBlock = "block" // run touched sealed records' specs; roll back on failure
	OverlapSpecsWarn  = "warn"  // run them; a failure becomes a non-blocking FYI, completion proceeds
	OverlapSpecsOff   = "off"   // skip the cross-record teeth entirely (own specs still run)
)

Overlap-teeth severity modes for overlap_specs_on_complete. block is the default and matches the original Phase 3/4 behavior (prov-2026-bc57fbdc).

Variables

View Source
var IDPattern = regexp.MustCompile(`^prov-(\d{4})-(\d{3}|[a-f0-9]{8})(?:-[a-z0-9-]+)?$`)

IDPattern is the regex for valid provenance record IDs: prov-YYYY-NNN, prov-YYYY-XXXXXXXX, or with service suffix Supports both legacy sequential format (prov-YYYY-NNN) and new crypto random format (prov-YYYY-XXXXXXXX)

ValidStatuses contains all valid status values

View Source
var Version = "dev"

Version is the current version of the linespec tool This should be set during build time using ldflags

Functions

func AlwaysWritablePaths

func AlwaysWritablePaths(config *ProvenanceConfig, records []*Record, repoRoot string) []string

AlwaysWritablePaths returns the derived always-writable pattern set: the existing provenance.exclude_paths whitelist plus the authoring coop — the configured provenance directory, .linespec.yml, LineSpec's own managed .linespec/ state directory (managedStatePaths), and every associated_spec path across all loaded records (regardless of status), so the Brief-to-Blueprint-to-Imprint authoring chain can never block its own creation. This set is derived, never separately hand-maintained. repoRoot normalizes an absolute config.Dir to repo-relative, since every path this pattern set is matched against (from `git ls-files`) is repo-relative too.

func ColdStartSkip

func ColdStartSkip(records []*Record, config *ProvenanceConfig) bool

ColdStartSkip reports whether reconcile should skip enforcement entirely because the project has no provenance records yet. Hand-initialized projects default to warn-until-first-record (skip=true) so the tree is never locked down before there is anything to declare scope against. Projects created via `linespec clone` default to strict-deny (skip=false): ManifestURL being set means the project arrived pre-seeded with open records to enforce against.

func ComputeFileHash

func ComputeFileHash(filePath string) (string, error)

ComputeFileHash computes the SHA-256 hash of a file

func CurrentDate

func CurrentDate() string

CurrentDate returns the current date in ISO 8601 format (YYYY-MM-DD)

func CurrentYear

func CurrentYear() int

CurrentYear returns the current year as an integer

func GetAnalyzedFiles

func GetAnalyzedFiles(lintResult *LintResult, loader *Loader) []string

GetAnalyzedFiles returns the list of file paths for records in a LintResult

func GlobToRegex

func GlobToRegex(glob string) string

GlobToRegex converts a glob pattern to a regex pattern

func HashRecord

func HashRecord(r *Record) (string, error)

HashRecord computes a content hash for a single record. The hash covers all exported fields; FilePath is excluded because it is a runtime path, not part of the record's content.

func HintCreateNotSupersede

func HintCreateNotSupersede() string

HintCreateNotSupersede returns the canonical guidance shown whenever a change touches files already governed by existing records: create ONE new record covering your files and tag your commits with it — supersede only when you are deliberately revising the decision a record captured. This is the single source of that wording. The `next` create advice, the commit-violation hint (formatter.go), and any other surface all render from it so the framing that caused the original ~$400 incident can never drift between surfaces again.

func HintStaleScope

func HintStaleScope(file, recordID, shortSHA string) string

HintStaleScope returns the canonical, non-blocking message shown when a change touches a file governed by an already-implemented (sealed) record. It is informational only — no action is required, and it is NOT a reason to supersede anything. The wording lives here so the commit-time warning and any other surface stay single-sourced.

func IsAlwaysWritable

func IsAlwaysWritable(path string, alwaysWritable []string) bool

IsAlwaysWritable reports whether path matches the always-writable pattern set. It reuses exclude.go's pattern matching (regex/glob/directory-prefix/exact) so the always-writable set behaves identically to provenance.exclude_paths.

func IsPathExcluded

func IsPathExcluded(filePath string, excludePaths []string) bool

IsPathExcluded reports whether filePath matches any entry in excludePaths. Each entry may be:

  • A regex, recognized by leading and trailing slashes (e.g. /.*_gen\.go$/)
  • A glob pattern (contains * or ?)
  • A directory prefix (e.g. "docs" or "docs/" matches any file under docs/)
  • A full file path (exact match)

Matching is evaluated in the order listed above. The first matching entry makes the file exempt. An invalid regex or glob is silently skipped (no match).

func IsValidID

func IsValidID(id string) bool

IsValidID returns true if the ID matches the prov-YYYY-NNN format (with optional service suffix)

func IsWritablePath

func IsWritablePath(path string, alwaysWritable, openScope []string) (bool, error)

IsWritablePath reports whether path should be writable under the current projection: always-writable, or matching some open allowlist record's affected_scope pattern. An invalid pattern in a record cannot block enforcement of other, valid patterns, so it is skipped rather than erroring.

func LockFile

func LockFile(path string) error

LockFile strips write permission from every permission class of the file at path, leaving other bits (e.g. execute) untouched. Missing paths and directories are a no-op — reconcile only ever locks files it actually finds.

func MatchPattern

func MatchPattern(filePath, pattern string) (bool, error)

MatchPattern checks if a file path matches a pattern (exact, glob, or regex)

func MaterializeScope

func MaterializeScope(repoRoot string, scopePaths []string) error

MaterializeScope unlocks exactly the given repo-relative scope paths: an existing file is unlocked directly; a not-yet-existing declared path has its parent directory unlocked instead, so the file can be created without disturbing sibling files' own permission bits. This is the atomic permission side effect of `open` and of widening an already-open record's scope — call it with exactly the newly-covered paths so declaration and permission move together.

func NextID

func NextID(year int, existingIDs []string) (string, error)

NextID generates the next available ID for the given year using crypto random hex Format: prov-YYYY-XXXXXXXX where XXXXXXXX is 8 hex characters Retries up to 10 times if collision occurs, then returns error

func NormalizePath

func NormalizePath(filePath, repoRoot string) string

NormalizePath converts a file path to use forward slashes and make it relative to repo root

func OpenAllowlistScope

func OpenAllowlistScope(records []*Record) []string

OpenAllowlistScope returns the de-duplicated, sorted union of affected_scope patterns across every open, allowlist-mode record — the set of source-path patterns writability projects from. Non-open records and observed-mode records (empty affected_scope) contribute nothing: writability is a pure projection of open allowlist scope only.

func SeverityToSARIFLevel

func SeverityToSARIFLevel(severity Severity, enforcement string) string

SeverityToSARIFLevel maps LineSpec Severity to SARIF level

func TryGovernFromCache

func TryGovernFromCache(config *ProvenanceConfig, repoRoot string, output *os.File, color bool, opts GovernOptions) bool

TryGovernFromCache serves `linespec provenance govern` from the cached scope index without a full LoadAll, mirroring TryNextFromCache. Returns true when it handled the command; false to fall back to the heavy, authoritative path.

func TryNextFromCache

func TryNextFromCache(config *ProvenanceConfig, repoRoot string, output *os.File, color bool, opts NextOptions) bool

TryNextFromCache serves `linespec provenance next` from the cached scope index without a full LoadAll, when the cache is fresh. It returns true if it handled the command (output already rendered); false if the caller must fall back to the heavy, authoritative path — on a custom -c config, a cache miss/staleness, or any error. This is the per-edit-hook fast path.

func UnlockDir

func UnlockDir(path string) error

UnlockDir adds owner write+execute permission to the directory at path so a declared-but-not-yet-existing file can be created inside it. It does NOT alter the permission bits of any file already present in the directory — already-locked siblings remain locked. Missing paths and non-directories are a no-op.

func UnlockFile

func UnlockFile(path string) error

UnlockFile adds owner write permission to the file at path, leaving other bits untouched. Missing paths and directories are a no-op.

Types

type ActionKind

type ActionKind string

ActionKind enumerates the kinds of next action the advice engine can recommend.

const (
	// ActionCreate — no record governs the relevant files; create a blueprint.
	ActionCreate ActionKind = "create"
	// ActionOpen — a draft record governs the work; open it to enable enforcement.
	ActionOpen ActionKind = "open"
	// ActionAddSpec — an open record has no associated_specs; add a proof artifact.
	ActionAddSpec ActionKind = "add_spec"
	// ActionAddScope — a file is blocked by fswrite enforcement (prov-2026-8d2f5f2a):
	// the active open record does not yet declare it in affected_scope, so it stays
	// non-writable on disk.
	ActionAddScope ActionKind = "add_scope"
	// ActionCommit — there are staged changes; commit them tagged with the record.
	ActionCommit ActionKind = "commit"
	// ActionImplementImprint — an imprint of the active blueprint is not implemented.
	ActionImplementImprint ActionKind = "implement_imprint"
	// ActionComplete — the active record is ready to be completed.
	ActionComplete ActionKind = "complete"
	// ActionChooseRecord — more than one open record governs the files; pick one.
	ActionChooseRecord ActionKind = "choose_record"
	// ActionNone — nothing pending; the tree is clean and no work is in flight.
	ActionNone ActionKind = "none"
)

type AddScopeOptions

type AddScopeOptions struct {
	RecordID   string
	DryRun     bool
	ConfigFile string // Path to custom .linespec.yml file
}

AddScopeOptions holds options for the add-scope command.

type AssociatedSpec

type AssociatedSpec struct {
	Path       string `yaml:"path"`
	Type       string `yaml:"type,omitempty"`
	RunCommand string `yaml:"run_command,omitempty"`
}

AssociatedSpec represents a proof artifact with optional type annotation

type AuditOptions

type AuditOptions struct {
	Description string // Description of recent changes
	ConfigFile  string // Path to custom .linespec.yml file
}

AuditOptions holds options for the audit command

type CacheManager

type CacheManager struct {
	SharedRepos     []config.SharedRepoConfig
	CacheTTLMinutes int
	// contains filtered or unexported fields
}

CacheManager handles fetching and storing remote provenance directories. Each configured shared repo is cached under ~/.linespec/cache/<sha256-of-url>/provenance/. A sidecar .meta file records when the cache was last populated for TTL checks.

func NewCacheManager

func NewCacheManager(repos []config.SharedRepoConfig, ttlMinutes int) *CacheManager

NewCacheManager creates a CacheManager rooted at ~/.linespec/cache.

func (*CacheManager) IsFresh

func (c *CacheManager) IsFresh(repo config.SharedRepoConfig) bool

IsFresh reports whether the cached data for a repo was fetched within the TTL window.

func (*CacheManager) LoadedDirs

func (c *CacheManager) LoadedDirs() []string

LoadedDirs returns the provenance cache directories for all repos that have a populated cache (fresh or stale). These can be passed directly to the Loader.

func (*CacheManager) ProvenanceDir

func (c *CacheManager) ProvenanceDir(repo config.SharedRepoConfig) string

ProvenanceDir returns the path where a repo's provenance records are cached.

func (*CacheManager) Sync

func (c *CacheManager) Sync(repo config.SharedRepoConfig, force bool) (int, bool, error)

Sync fetches the provenance directory from a remote repo, unpacks it into the cache, and writes the .meta sidecar. Returns the record count and whether the cache was already fresh (skipped). Uses git archive where supported (SSH and some HTTPS hosts); falls back to a depth-1 sparse checkout for GitHub-style HTTPS remotes that reject git archive.

func (*CacheManager) SyncAll

func (c *CacheManager) SyncAll(force bool) []SyncResult

type CheckOptions

type CheckOptions struct {
	Commit      string // Single commit to check (default: HEAD)
	Range       string // Range to check (e.g., SHA..SHA)
	Record      string // Check only against a specific record
	Staged      bool   // Check staged files instead of committed
	MessageFile string // Path to commit message file (for staged mode)
	ConfigFile  string // Path to custom .linespec.yml file
}

CheckOptions holds options for the check command

type Commands

type Commands struct {
	Loader    *Loader
	Linter    *Linter
	Git       *Git
	Checker   *CommitChecker
	Formatter *Formatter
	Config    *ProvenanceConfig
	Cache     *CacheManager
	RepoRoot  string
	Embedder  *embeddings.Client
}

Commands provides all provenance CLI commands

func NewCommands

func NewCommands(config *ProvenanceConfig, repoRoot string, output *os.File, color bool) (*Commands, error)

NewCommands creates a new commands instance

func NewCommandsWithEmbedder

func NewCommandsWithEmbedder(config *ProvenanceConfig, repoRoot string, output *os.File, color bool, embedder *embeddings.Client) (*Commands, error)

NewCommandsWithEmbedder creates a new commands instance with optional embedding client

func (*Commands) AddScope

func (c *Commands) AddScope(opts AddScopeOptions) error

AddScope widens an already-allowlist record's affected_scope (prov-2026-8d2f5f2a, "Adding a path to an already-open record's affected_scope MUST go through a dedicated `linespec provenance add-scope` CLI verb"): it pulls files from commits already tagged with the record that are not yet declared, adds them to affected_scope, and — if the record is open — materializes write permission for exactly those newly-added paths in the same atomic operation. It errors if the record is not yet in allowlist mode (use LockScope first) or if there is nothing new to add.

func (*Commands) Audit

func (c *Commands) Audit(opts AuditOptions) error

Audit performs semantic audit comparing changes against provenance history

func (*Commands) Check

func (c *Commands) Check(opts CheckOptions) error

Check checks commits for violations

func (*Commands) Compile

func (c *Commands) Compile(opts CompileOptions) error

Compile rebuilds the hash manifest from all loaded records. It is idempotent: if every record hash and both graph hashes already match the stored manifest, no file is written and the command exits 0.

func (*Commands) Complete

func (c *Commands) Complete(opts CompleteOptions) error

func (*Commands) Context

func (c *Commands) Context(opts ContextOptions) error

func (*Commands) Create

func (c *Commands) Create(opts CreateOptions) error

Create creates a new provenance record

func (*Commands) Deprecate

func (c *Commands) Deprecate(opts DeprecateOptions) error

Deprecate marks a record as deprecated

func (*Commands) Generate

func (c *Commands) Generate(opts GenerateOptions) error

Generate builds a behavioral specification document from provenance records.

func (*Commands) Govern

func (c *Commands) Govern(opts GovernOptions) error

Govern reports the ACTIVE records (open + implemented) that govern the given files, plus the engine's primary next action so a caller can end with a `next` suggestion. Superseded/deprecated records are excluded — see activeGoverningRecords. This is the hook-facing lookup; the full `context` command still shows history.

func (*Commands) Graph

func (c *Commands) Graph(opts GraphOptions) error

Graph shows the provenance graph

func (*Commands) Index

func (c *Commands) Index(opts IndexOptions) error

Index generates embeddings for all implemented provenance records that don't have them

func (*Commands) InstallHooks

func (c *Commands) InstallHooks() error

InstallHooks installs git hooks

func (*Commands) InstallPlugin

func (c *Commands) InstallPlugin(opts InstallPluginOptions) error

InstallPlugin extracts the embedded Claude Code provenance plugin into the target config directory (default <repo>/.claude/plugins/linespec-provenance), preserving directory structure and re-applying the executable bit to *.sh hook scripts (which embed.FS drops). It writes ONLY the plugin's own files — it never edits or clobbers unrelated user Claude Code config.

func (*Commands) InstallSkills

func (c *Commands) InstallSkills(opts InstallSkillsOptions) error

InstallSkills copies all LineSpec Claude Code skills into a skills directory. Existing skill directories are overwritten silently.

func (*Commands) Lint

func (c *Commands) Lint(opts LintOptions) error

Lint runs the linter

func (*Commands) LockLayer

func (c *Commands) LockLayer(opts LockLayerOptions) error

LockLayer creates a locked layer record — an architectural declaration that is immediately implemented and locked

func (*Commands) LockScope

func (c *Commands) LockScope(opts LockScopeOptions) error

LockScope populates a record's affected_scope from its git history the first time (observed -> allowlist). Widening an already-allowlist record's scope is a distinct operation — see AddScope — so it errors here rather than silently doing something different from what --dry-run just printed.

func (*Commands) Next

func (c *Commands) Next(opts NextOptions) error

Next computes and renders the correct next provenance action for the current state. It is the I/O boundary for the advice engine: it gathers records, staged files, and working-tree changes, then hands a fully-populated NextState to the pure Advise function. Both the `next` command and the routed error hints (Phase 2c) render from that one engine.

Every call also re-derives the fswrite write-bit projection (prov-2026-8d2f5f2a) unconditionally, best-effort. Enforcement MUST NOT depend on the Claude Code plugin hooks being installed — a user may not have them set up — so this cannot be gated behind an env var only a hook script sets. `next` is the one command every workflow (manual CLI use, any agent harness, the plugin hooks) already calls before touching files, which makes it the natural place for "reconcile MUST run at agent session start" to actually hold in practice. A dedicated `linespec provenance reconcile` verb (see Reconcile) also exists for explicit/scripted invocation.

func (*Commands) Open

func (c *Commands) Open(opts OpenOptions) error

Open transitions a record from draft to open, enabling enforcement

func (*Commands) Publish

func (c *Commands) Publish(opts PublishOptions) error

Publish packages the loaded provenance records into a versioned, content-addressed linespec.manifest.json. It applies the transformation pipeline, serializes the provenance layer, hashes all present layers, and appends an immutable version entry. Optional layers (specs, code, prompt) are read from the paths in opts when provided. URL fields are left empty for the author to fill in after uploading.

func (*Commands) Reconcile

func (c *Commands) Reconcile(opts ReconcileOptions) error

Reconcile is the dedicated `linespec provenance reconcile` CLI verb (prov-2026-8d2f5f2a): it re-derives the entire fswrite write-bit projection from the current set of open records' scopes and reports what changed. It exists so reconcile can be invoked explicitly by any harness or script — enforcement must not depend on the Claude Code plugin hooks being installed. `next` (see Commands.Next) already calls this unconditionally on every invocation; this verb is for direct/scripted use.

func (*Commands) RunSpecs

func (c *Commands) RunSpecs(opts RunSpecsOptions) error

RunSpecs runs the associated_specs for a provenance record. It is called by the pre-commit hook when a record transitions from open to implemented. If run_associated_specs_on_complete is not enabled in config, it exits silently.

func (*Commands) Search

func (c *Commands) Search(opts SearchOptions) error

Search performs semantic search over provenance records

func (*Commands) Status

func (c *Commands) Status(opts StatusOptions) error

Status shows record status

func (*Commands) Sync

func (c *Commands) Sync(opts SyncOptions) error

Sync refreshes the local cache for all configured shared repos using git archive. Within the configured TTL window, a repo is skipped as already fresh unless Force is set.

type CommitChecker

type CommitChecker struct {
	Git          *Git
	Loader       *Loader
	ExcludePaths []string // patterns for files exempt from all provenance enforcement
}

CommitChecker checks commits for provenance violations

func NewCommitChecker

func NewCommitChecker(git *Git, loader *Loader) *CommitChecker

NewCommitChecker creates a new commit checker

func (*CommitChecker) AutoPopulateScope

func (c *CommitChecker) AutoPopulateScope(record *Record) error

AutoPopulateScope populates affected_scope from git commits for a record

func (*CommitChecker) CheckCommit

func (c *CommitChecker) CheckCommit(commit string) ([]Violation, error)

CheckCommit checks a single commit for violations

func (*CommitChecker) CheckForStaleScopeWarnings

func (c *CommitChecker) CheckForStaleScopeWarnings(record *Record, changedFiles []string) []StaleScopeWarning

CheckForStaleScopeWarnings checks implemented records for files in affected_scope that haven't actually changed since the record was sealed

func (*CommitChecker) CheckRange

func (c *CommitChecker) CheckRange(from, to string) ([]Violation, error)

CheckRange checks a range of commits for violations

func (*CommitChecker) CheckStaged

func (c *CommitChecker) CheckStaged(messageFile string, commitTagRequired bool) ([]Violation, error)

CheckStaged checks staged files against provenance records referenced in a commit message

type CompileOptions

type CompileOptions struct {
	ConfigFile string
}

CompileOptions holds options for the compile command

type CompleteOptions

type CompleteOptions struct {
	RecordID   string
	Force      bool
	ConfigFile string // Path to custom .linespec.yml file
}

CompleteOptions holds options for the complete command

type ContextOptions

type ContextOptions struct {
	Files      []string // File paths to check (positional args or --files)
	Format     string   // Output format: human (default), compact, json
	ConfigFile string   // Path to custom .linespec.yml file
}

ContextOptions holds options for the context command

type ContextRecord

type ContextRecord struct {
	Record     *Record  // The record itself
	IsAncestor bool     // True if this record is only in ancestry, not directly matched
	Ancestors  []string // Chain of supersedes relationships (oldest first, i.e., the chain from current to oldest ancestor)
}

ContextRecord represents a record in the context output

type ContextResult

type ContextResult struct {
	Files         []string         // Input files
	DirectMatches []*ContextRecord // Records that directly match the files
	Conflicts     []ScopeConflict  // Overlapping open records
	ExemptFiles   []string         // Files that match exclude_paths and are exempt from provenance rules
}

ContextResult holds the complete context output

type CreateOptions

type CreateOptions struct {
	Title      string
	Supersedes string
	Tags       []string
	NoEdit     bool
	IDSuffix   string     // Service suffix for ID (e.g., "user-service" creates prov-YYYY-NNN-user-service)
	Type       RecordType // Tier type: brief | blueprint | imprint
	ConfigFile string     // Path to custom .linespec.yml file
}

CreateOptions holds options for the create command

type DeprecateOptions

type DeprecateOptions struct {
	RecordID   string
	Reason     string
	ConfigFile string // Path to custom .linespec.yml file
}

DeprecateOptions holds options for the deprecate command

type Formatter

type Formatter struct {
	Output io.Writer
	Color  bool
}

Formatter handles output formatting for provenance commands

func NewFormatter

func NewFormatter(output io.Writer, color bool) *Formatter

NewFormatter creates a new formatter

func (*Formatter) FormatCheckResult

func (f *Formatter) FormatCheckResult(violations []Violation, staleWarnings []StaleScopeWarning, commit string)

FormatCheckResult formats the check command output

func (*Formatter) FormatCompleteSuccess

func (f *Formatter) FormatCompleteSuccess(record *Record)

FormatCompleteSuccess formats the complete command success output

func (*Formatter) FormatContext

func (f *Formatter) FormatContext(result *ContextResult)

FormatContext formats the context command output in human-readable format

func (*Formatter) FormatContextCompact

func (f *Formatter) FormatContextCompact(result *ContextResult)

FormatContextCompact formats the context in a compact, token-efficient format

func (*Formatter) FormatContextJSON

func (f *Formatter) FormatContextJSON(result *ContextResult) error

FormatContextJSON formats the context as JSON

func (*Formatter) FormatCreateSuccess

func (f *Formatter) FormatCreateSuccess(record *Record, superseded string)

FormatCreateSuccess formats the create command success output

func (*Formatter) FormatError

func (f *Formatter) FormatError(message string)

FormatError formats an error message

func (*Formatter) FormatGraph

func (f *Formatter) FormatGraph(loader *Loader, filter string, root string)

FormatGraph formats the provenance graph. When root is non-empty, only the subgraph centred on that record is shown: one level of implements parent (if any) plus all downstream implements and supersession children.

func (*Formatter) FormatJSON

func (f *Formatter) FormatJSON(data interface{}) error

FormatJSON outputs data as JSON

func (*Formatter) FormatLint

func (f *Formatter) FormatLint(result *LintResult, opts LintOptions)

FormatLint formats lint results, filtering issue output by severity based on opts. The summary line is always printed. With no filter flag set, only errors are shown.

func (*Formatter) FormatLockLayerSuccess

func (f *Formatter) FormatLockLayerSuccess(record *Record)

FormatLockLayerSuccess formats the lock-layer command success output

func (*Formatter) FormatLockScopeSuccess

func (f *Formatter) FormatLockScopeSuccess(record *Record, lockedPaths []string)

FormatLockScopeSuccess formats the lock-scope command success output

func (*Formatter) FormatNext

func (f *Formatter) FormatNext(actions []NextAction)

FormatNext renders advice-engine actions for humans. Element 0 is the single primary recommendation; any remaining actions are shown as follow-ups.

func (*Formatter) FormatNextJSON

func (f *Formatter) FormatNextJSON(actions []NextAction) error

FormatNextJSON emits the advice-engine actions as JSON for hook/agent consumption. The shape is stable: {"primary": <action>, "actions": [<action>...]}.

func (*Formatter) FormatStatus

func (f *Formatter) FormatStatus(loader *Loader, enforcement string, filter string)

FormatStatus formats the status output

func (*Formatter) FormatStatusDetailed

func (f *Formatter) FormatStatusDetailed(record *Record, loader *Loader)

FormatStatusDetailed formats detailed status for a single record

type GenerateOptions

type GenerateOptions struct {
	RecordID   string // optional: target a specific record
	Format     string // "markdown" (default) or "yaml"
	OutputFile string // optional: write to file instead of stdout
	ConfigFile string
}

GenerateOptions holds options for the generate command.

type Git

type Git struct {
	RepoRoot string
}

Git provides git operations for provenance integration

func NewGit

func NewGit(repoRoot string) *Git

NewGit creates a new Git helper

func (*Git) CommitRecord

func (g *Git) CommitRecord(message string, filePaths ...string) error

CommitRecord stages the given files and creates a commit with the provided message. Used by commands that have commit_on_status_change enabled.

func (*Git) ExtractProvenanceIDs

func (g *Git) ExtractProvenanceIDs(message string) []string

ExtractProvenanceIDs extracts provenance record IDs from a commit message Format: [prov-YYYY-NNN], [prov-YYYY-XXXXXXXX], or with service suffix

func (*Git) GetCommitMessage

func (g *Git) GetCommitMessage(commit string) (string, error)

GetCommitMessage returns the commit message for a given commit

func (*Git) GetCommitsForRecord

func (g *Git) GetCommitsForRecord(recordID string) ([]string, error)

GetCommitsForRecord returns all commits that reference a given record ID

func (*Git) GetCommitsInRange

func (g *Git) GetCommitsInRange(from, to string) ([]string, error)

GetCommitsInRange returns all commits between two references

func (*Git) GetFilesChangedInCommits

func (g *Git) GetFilesChangedInCommits(commits []string) ([]string, error)

GetFilesChangedInCommits returns all files changed across a set of commits

func (*Git) GetFilesChangedSince

func (g *Git) GetFilesChangedSince(fromSHA, toSHA string) ([]string, error)

GetFilesChangedSince returns files that have changed between two SHAs

func (*Git) GetGitEmail

func (g *Git) GetGitEmail() (string, error)

func (*Git) GetHeadSHA

func (g *Git) GetHeadSHA() (string, error)

GetHeadSHA returns the SHA of the current HEAD commit

func (*Git) GetModifiedFiles

func (g *Git) GetModifiedFiles(commit string) ([]string, error)

GetModifiedFiles returns files modified in a commit or commit range

func (*Git) GetStagedFiles

func (g *Git) GetStagedFiles() ([]string, error)

GetStagedFiles returns files staged for commit

func (*Git) GetWorkingTreeChanges

func (g *Git) GetWorkingTreeChanges() ([]string, error)

GetWorkingTreeChanges returns every file that differs from HEAD — staged and unstaged combined (`git diff --name-only HEAD`). It is the "what am I working on" signal the advice engine uses for ambient `next` when no intended files are given.

func (*Git) ReadCommitMessageFile

func (g *Git) ReadCommitMessageFile(path string) (string, error)

ReadCommitMessageFile reads the commit message from a file

func (*Git) Unstage

func (g *Git) Unstage(filePaths ...string) error

Unstage removes the given paths from the index, leaving working-tree contents untouched. Used to undo the `git add` performed by an auto-commit when a status-change transition is rolled back after a rejected commit.

type GovernOptions

type GovernOptions struct {
	Files      []string // files to look up governance for
	Format     string   // human (default) | json
	ConfigFile string   // path to custom .linespec.yml file
}

GovernOptions configures the `govern` command — the active-only per-file governance lookup the 5c plugin hook consumes.

type GraphOptions

type GraphOptions struct {
	Root       string // Start from specific record
	Filter     string // open | implemented | superseded | deprecated
	Format     string // human | json | dot
	ConfigFile string // Path to custom .linespec.yml file
}

GraphOptions holds options for the graph command

type Hasher

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

Hasher manages content hashing for provenance records and maintains the hash manifest.

func NewHasher

func NewHasher(repoRoot string) *Hasher

NewHasher creates a Hasher whose manifest lives at <repoRoot>/.linespec/hash_manifest.json.

func (*Hasher) CompileManifest

func (h *Hasher) CompileManifest(records []*Record) (bool, error)

CompileManifest recomputes hashes for every record and writes the manifest only when the result differs from what is already on disk. Returns true if the manifest was written, false if it was already up to date.

func (*Hasher) LoadManifest

func (h *Hasher) LoadManifest() (*hashManifest, error)

LoadManifest reads the hash manifest from disk. Returns an empty manifest if the file does not exist yet.

func (*Hasher) ManifestExists

func (h *Hasher) ManifestExists() bool

ManifestExists returns true if the hash manifest file exists on disk.

func (*Hasher) ManifestPath

func (h *Hasher) ManifestPath() string

func (*Hasher) SealRecord

func (h *Hasher) SealRecord(r *Record, allRecords []*Record) error

SealRecord computes the content hash for r, stores it in the manifest, and recomputes both graph hashes using all records provided in allRecords. The updated manifest is written atomically.

func (*Hasher) VerifyRecord

func (h *Hasher) VerifyRecord(r *Record) (stored, current string, ok bool, err error)

VerifyRecord returns the stored hash for recordID and the current content hash. ok is false when the manifest has no entry for the record.

type IndexOptions

type IndexOptions struct {
	DryRun     bool   // Show what would be indexed without doing it
	Force      bool   // Re-index even if embedding exists
	ConfigFile string // Path to custom .linespec.yml file
}

IndexOptions holds options for the index command

type InstallPluginOptions

type InstallPluginOptions struct {
	Path string // target plugins directory relative to repo root (default: .claude/plugins)
}

InstallPluginOptions holds options for the install-plugin command.

type InstallSkillsOptions

type InstallSkillsOptions struct {
	Path string // Target directory relative to repo root (default: .claude/skills)
}

InstallSkillsOptions holds options for the install-skills command

type Issue

type Issue struct {
	RecordID string
	Field    string
	Message  string
	Severity Severity
}

Issue represents a validation issue found in a record

type JSONGraph

type JSONGraph struct {
	Nodes []JSONGraphNode `json:"nodes"`
	Edges []JSONGraphEdge `json:"edges"`
}

JSONGraph is the top-level structure for --format json graph output.

func BuildJSONGraph

func BuildJSONGraph(loader *Loader) JSONGraph

BuildJSONGraph builds the graph for JSON output with typed edges.

type JSONGraphEdge

type JSONGraphEdge struct {
	From     string `json:"from"`
	To       string `json:"to"`
	EdgeType string `json:"edge_type"` // "supersedes", "implements", "related"
}

JSONGraphEdge represents a directed edge in the JSON graph output. EdgeType distinguishes supersedes, implements, and related relationships.

type JSONGraphNode

type JSONGraphNode struct {
	ID              string          `json:"id"`
	Title           string          `json:"title"`
	Status          string          `json:"status"`
	Type            string          `json:"type,omitempty"`
	Remote          bool            `json:"remote,omitempty"`
	Supersedes      string          `json:"supersedes,omitempty"`
	SupersededBy    string          `json:"superseded_by,omitempty"`
	Implements      string          `json:"implements,omitempty"`
	ImplementedBy   []string        `json:"implemented_by,omitempty"`
	Children        []JSONGraphNode `json:"children,omitempty"`
	ImplementsNodes []JSONGraphNode `json:"implements_nodes,omitempty"`
}

JSONGraphNode represents a node in the graph for JSON output

type JSONIssue

type JSONIssue struct {
	RecordID string `json:"record_id"`
	Field    string `json:"field"`
	Message  string `json:"message"`
	Severity string `json:"severity"`
}

JSONIssue represents a single issue for JSON output

type JSONLintResult

type JSONLintResult struct {
	Enforcement string      `json:"enforcement"`
	Total       int         `json:"total"`
	Passed      int         `json:"passed"`
	Warnings    int         `json:"warnings"`
	Errors      int         `json:"errors"`
	Issues      []JSONIssue `json:"issues"`
}

JSONLintResult represents lint results for JSON output

type LintOptions

type LintOptions struct {
	RecordID    string
	Enforcement string
	Format      string // human | json
	ConfigFile  string // Path to custom .linespec.yml file
	ShowWarn    bool   // show only warnings
	ShowInfo    bool   // show only hints/info
	ShowAll     bool   // show all severities
}

LintOptions holds options for the lint command

type LintResult

type LintResult struct {
	Issues       []Issue
	PassedCount  int
	WarningCount int
	ErrorCount   int
	HintCount    int
	Enforcement  string
}

LintResult contains the results of linting a record or set of records

func (*LintResult) Add

func (r *LintResult) Add(issue Issue)

Add adds an issue to the result

func (*LintResult) HasErrors

func (r *LintResult) HasErrors() bool

HasErrors returns true if there are any error-level issues

func (*LintResult) ToJSON

func (r *LintResult) ToJSON() *JSONLintResult

ToJSON converts LintResult to JSONLintResult

func (*LintResult) ToSARIF

func (r *LintResult) ToSARIF(loader *Loader, repoRoot string, analyzedFiles []string) *SARIFDocument

ToSARIF converts a LintResult to a SARIF document

type Linter

type Linter struct {
	Loader            *Loader
	Enforcement       string // none | warn | strict
	CommitTagRequired bool
	ExcludePaths      []string // patterns for files exempt from provenance rules
	Hasher            *Hasher  // nil when hash manifest is not configured
}

Linter validates Provenance Records according to the schema and enforcement rules

func NewLinter

func NewLinter(loader *Loader, enforcement string) *Linter

NewLinter creates a new linter

func (*Linter) LintAll

func (l *Linter) LintAll() *LintResult

LintAll validates all loaded records

func (*Linter) LintRecord

func (l *Linter) LintRecord(recordID string) *LintResult

LintRecord validates a single record

type Loader

type Loader struct {
	Records     []*Record
	RecordsByID map[string]*Record
	Dir         string
	SharedRepos []string
}

Loader handles loading and managing Provenance Records

func NewLoader

func NewLoader(dir string, sharedRepos []string) *Loader

NewLoader creates a new provenance loader for the given directory

func (*Loader) BuildGraph

func (l *Loader) BuildGraph() error

BuildGraph builds the ID index and validates relationships

func (*Loader) FilterByStatus

func (l *Loader) FilterByStatus(status Status) []*Record

FilterByStatus returns records filtered by status

func (*Loader) FilterByTag

func (l *Loader) FilterByTag(tag string) []*Record

FilterByTag returns records filtered by tag

func (*Loader) GetAllIDs

func (l *Loader) GetAllIDs() []string

GetAllIDs returns all record IDs

func (*Loader) GetRecord

func (l *Loader) GetRecord(id string) (*Record, bool)

GetRecord returns a record by ID

func (*Loader) LoadAll

func (l *Loader) LoadAll() error

LoadAll loads all provenance records from the configured directories

func (*Loader) LoadFile

func (l *Loader) LoadFile(path string) (*Record, error)

LoadFile loads a single provenance record from a YAML file

func (*Loader) LoadFromDir

func (l *Loader) LoadFromDir(dir string) error

LoadFromDir loads all prov-*.yml files from the given directory and its subdirectories.

func (*Loader) SaveRecord

func (l *Loader) SaveRecord(record *Record) error

SaveRecord saves a record to its file path, preserving original YAML formatting

type LockLayerOptions

type LockLayerOptions struct {
	Title      string
	NoEdit     bool
	ConfigFile string // Path to custom .linespec.yml file
}

LockLayerOptions holds options for the lock-layer command

type LockScopeOptions

type LockScopeOptions struct {
	RecordID   string
	DryRun     bool
	ConfigFile string // Path to custom .linespec.yml file
}

LockScopeOptions holds options for the lock-scope command

type Manifest

type Manifest struct {
	Name     string                     `json:"name,omitempty"`
	Latest   string                     `json:"latest"`
	Versions map[string]ManifestVersion `json:"versions"`
}

Manifest is the top-level structure for linespec.manifest.json.

type ManifestLayer

type ManifestLayer struct {
	SHA256   string            `json:"sha256"`
	URL      string            `json:"url"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

ManifestLayer holds the hash and optional URL for a single layer artifact.

type ManifestVersion

type ManifestVersion struct {
	CreatedAt string                   `json:"created_at"`
	RootHash  string                   `json:"root_hash"`
	Layers    map[string]ManifestLayer `json:"layers"`
}

ManifestVersion represents one immutable published version.

type NextAction

type NextAction struct {
	Kind     ActionKind `json:"kind"`
	Command  string     `json:"command,omitempty"`
	Reason   string     `json:"reason"`
	RecordID string     `json:"record_id,omitempty"`
	// Governing lists record IDs that govern the relevant files. It is advisory:
	// these records do NOT need to be superseded just because they govern the
	// files (Phase 1 framing).
	Governing []string `json:"governing,omitempty"`
	// Detail carries an optional multi-line elaboration (e.g. an associated_specs
	// YAML shape). Renderers may show or omit it.
	Detail string `json:"detail,omitempty"`
}

NextAction is a single recommended action: a ready-to-run command (with record IDs already substituted) plus a one-line human reason.

func Advise

func Advise(state NextState) []NextAction

Advise is THE advice engine: a pure function mapping provenance state to the ordered list of correct next actions, with record IDs filled in. It performs no I/O and has no side effects. Element 0 of the result is the single primary recommendation; later elements are optional follow-ups. The slice is never empty — a clean, idle state returns a single ActionNone.

type NextOptions

type NextOptions struct {
	Files      []string // intended files (--files / --plan / positional args)
	Format     string   // human (default) | json
	ConfigFile string   // path to custom .linespec.yml file
}

Context retrieves provenance context for the given files NextOptions configures the `next` command.

type NextState

type NextState struct {
	// Records is every loaded record (local + shared cache).
	Records []*Record
	// StagedFiles is `git diff --cached --name-only`.
	StagedFiles []string
	// ChangedFiles is the broader working/branch diff (unstaged + committed-on-branch).
	ChangedFiles []string
	// IntendedFiles is the set of files the agent plans to change (from
	// `next --files`/`--plan`). When non-empty it takes precedence over the git
	// diffs so governance surfaces during planning, before any edit.
	IntendedFiles []string
	// CommitTagRequired mirrors config.commit_tag_required; affects commit wording.
	CommitTagRequired bool
}

NextState is the already-gathered, side-effect-free snapshot the engine reasons over. The caller (the `next` command, an error-hint site, or a hook) gathers this; Advise itself performs no I/O. This is what makes the decision logic unit-testable and reusable from every surface.

type OpenOptions

type OpenOptions struct {
	RecordID   string
	ConfigFile string // Path to custom .linespec.yml file
}

OpenOptions holds options for the open command

type ProvenanceConfig

type ProvenanceConfig struct {
	Enforcement                  string
	Dir                          string
	ExcludePaths                 []string // glob/regex/path patterns for files exempt from provenance rules
	SharedRepos                  []config.SharedRepoConfig
	CacheTTLMinutes              int
	CommitTagRequired            bool
	AutoAffectedScope            bool
	RunAssociatedSpecsOnComplete bool
	OverlapSpecsOnComplete       string // block (default) | warn | off — severity of the cross-record overlap teeth at completion
	CommitOnStatusChange         bool
	Embedding                    *config.EmbeddingConfig
	ManifestURL                  string // source manifest URL, set by linespec clone
}

ProvenanceConfig holds provenance-related configuration

type ProvenanceSearchResult

type ProvenanceSearchResult struct {
	Record     *Record
	Similarity float64
}

ProvenanceSearchResult represents a single search result with record details

type PublishOptions

type PublishOptions struct {
	ManifestPath string // path to linespec.manifest.json; defaults to ./linespec.manifest.json
	Name         string // project name written to the manifest top-level name field
	Version      string // explicit version label; empty means auto-increment
	SpecsPath    string // optional path to specs artifact (file or directory)
	CodePath     string // optional path to code artifact (file or directory)
	PromptPath   string // optional path to prompt artifact file
}

PublishOptions controls the linespec provenance publish command.

type ReconcileOptions

type ReconcileOptions struct {
	Format     string // human (default) | json
	ConfigFile string // path to custom .linespec.yml file
}

ReconcileOptions holds options for the reconcile command.

type ReconcileResult

type ReconcileResult struct {
	Unlocked []string
	Locked   []string
}

ReconcileResult summarizes a reconcile pass: the repo-relative paths whose write bit was flipped in either direction.

func Reconcile

func Reconcile(repoRoot string, files []string, records []*Record, config *ProvenanceConfig) (*ReconcileResult, error)

Reconcile re-derives the entire write-bit state of files from the current set of open, allowlist-mode records' scopes. It is idempotent — a path already in the correct state is left untouched — and it never invents candidate paths: it walks only the caller-supplied files (e.g. a git-tracked file list), so it never reaches into VCS internals or untracked build output. Cold-start projects with no records yet are skipped entirely (see ColdStartSkip).

type Record

type Record struct {
	// Required fields
	ID        string `yaml:"id"`
	Title     string `yaml:"title"`
	Status    Status `yaml:"status"`
	CreatedAt string `yaml:"created_at"`
	Author    string `yaml:"author"`

	// Intent and reasoning
	Intent      string   `yaml:"intent"`
	Constraints []string `yaml:"constraints"`

	// Scope
	AffectedScope  []string `yaml:"affected_scope"`
	ForbiddenScope []string `yaml:"forbidden_scope"`

	// Tier type (brief | blueprint | imprint). Empty means blueprint (backward compat).
	Type RecordType `yaml:"type,omitempty"`

	// Graph relationships
	Supersedes   string   `yaml:"supersedes"`
	SupersededBy string   `yaml:"superseded_by"`
	Extends      string   `yaml:"extends,omitempty"`
	Implements   string   `yaml:"implements,omitempty"`
	Related      []string `yaml:"related"`

	// Proof of completion
	SealedAtSHA      string           `yaml:"sealed_at_sha"`
	AssociatedSpecs  []AssociatedSpec `yaml:"associated_specs"`
	AssociatedTraces []string         `yaml:"associated_traces"`
	Monitors         []string         `yaml:"monitors"`

	// Tags
	Tags []string `yaml:"tags"`

	// Lock layer governance
	Locked bool `yaml:"locked,omitempty"`

	// File path (not stored in YAML, set during loading)
	FilePath string `yaml:"-"`
}

Record represents a single Provenance Record See PROVENANCE_RECORD_SCHEMA.md for full documentation

func (*Record) IsInScope

func (r *Record) IsInScope(filePath string) (bool, error)

IsInScope returns true if the given file path matches the record's scope

func (*Record) IsMutableAfterImplemented

func (r *Record) IsMutableAfterImplemented(fieldName string) bool

IsMutableAfterImplemented returns true if the field can be modified after status is 'implemented'

func (*Record) ScopeMode

func (r *Record) ScopeMode() string

ScopeMode returns the scope mode based on affected_scope allowlist mode: affected_scope is non-empty observed mode: affected_scope is empty

type RecordType

type RecordType string

RecordType represents the tier of a Provenance Record in the hierarchy

const (
	RecordTypeBrief     RecordType = "brief"
	RecordTypeBlueprint RecordType = "blueprint"
	RecordTypeBug       RecordType = "bug"
	RecordTypeImprint   RecordType = "imprint"
)

func (RecordType) IsValid

func (t RecordType) IsValid() bool

IsValid returns true if the record type is a known value

type RunSpecsOptions

type RunSpecsOptions struct {
	RecordID   string
	ConfigFile string
}

RunSpecsOptions holds options for the run-specs command

type SARIFArtifact

type SARIFArtifact struct {
	Location *SARIFArtifactLocation `json:"location"`
	MimeType string                 `json:"mimeType,omitempty"`
	Hashes   map[string]string      `json:"hashes,omitempty"`
}

SARIFArtifact represents an artifact in the SARIF document

type SARIFArtifactLocation

type SARIFArtifactLocation struct {
	URI       string `json:"uri"`
	URIBaseID string `json:"uriBaseId,omitempty"`
}

SARIFArtifactLocation represents an artifact location in SARIF

type SARIFDocument

type SARIFDocument struct {
	Schema  string     `json:"$schema"`
	Version string     `json:"version"`
	Runs    []SARIFRun `json:"runs"`
}

SARIFDocument represents the root SARIF document

func NewSARIFDocument

func NewSARIFDocument() *SARIFDocument

NewSARIFDocument creates a new empty SARIF document

func (*SARIFDocument) ToJSON

func (doc *SARIFDocument) ToJSON() ([]byte, error)

ToJSON converts a SARIFDocument to JSON

type SARIFDriver

type SARIFDriver struct {
	Name           string      `json:"name"`
	Version        string      `json:"version"`
	InformationURI string      `json:"informationUri,omitempty"`
	Rules          []SARIFRule `json:"rules"`
}

SARIFDriver represents the driver information in SARIF

type SARIFLocation

type SARIFLocation struct {
	PhysicalLocation *SARIFPhysicalLocation `json:"physicalLocation"`
}

SARIFLocation represents a location in SARIF

type SARIFMessage

type SARIFMessage struct {
	Text string `json:"text"`
}

SARIFMessage represents a message in SARIF

type SARIFPhysicalLocation

type SARIFPhysicalLocation struct {
	ArtifactLocation *SARIFArtifactLocation `json:"artifactLocation"`
	Region           *SARIFRegion           `json:"region,omitempty"`
}

SARIFPhysicalLocation represents a physical location in SARIF

type SARIFRegion

type SARIFRegion struct {
	StartLine   int `json:"startLine,omitempty"`
	StartColumn int `json:"startColumn,omitempty"`
}

SARIFRegion represents a region in a file in SARIF

type SARIFResult

type SARIFResult struct {
	RuleID    string          `json:"ruleId"`
	Level     string          `json:"level"`
	Message   *SARIFMessage   `json:"message"`
	Locations []SARIFLocation `json:"locations"`
}

SARIFResult represents a single result (finding) in SARIF

type SARIFRule

type SARIFRule struct {
	ID                   string                  `json:"id"`
	Name                 string                  `json:"name"`
	ShortDescription     *SARIFMessage           `json:"shortDescription,omitempty"`
	FullDescription      *SARIFMessage           `json:"fullDescription,omitempty"`
	HelpURI              string                  `json:"helpUri,omitempty"`
	DefaultConfiguration *SARIFRuleConfiguration `json:"defaultConfiguration,omitempty"`
}

SARIFRule represents a rule in the SARIF tool descriptor

func GetAllRules

func GetAllRules() []SARIFRule

GetAllRules returns the complete rule catalog for SARIF

type SARIFRuleConfiguration

type SARIFRuleConfiguration struct {
	Level string `json:"level,omitempty"`
}

SARIFRuleConfiguration represents rule configuration in SARIF

type SARIFRuleID

type SARIFRuleID string

SARIFRuleID represents a stable rule identifier for lint rules

const (
	// Rule IDs as specified in the PRD - these are stable and must not change
	PROV001 SARIFRuleID = "PROV001" // InvalidYaml
	PROV002 SARIFRuleID = "PROV002" // MissingRequiredField
	PROV003 SARIFRuleID = "PROV003" // UnknownStatus
	PROV004 SARIFRuleID = "PROV004" // InvalidIdFormat
	PROV005 SARIFRuleID = "PROV005" // InvalidDateFormat
	PROV006 SARIFRuleID = "PROV006" // UnresolvedSupersedes
	PROV007 SARIFRuleID = "PROV007" // SupersededByMismatch
	PROV008 SARIFRuleID = "PROV008" // UnresolvedRelated
	PROV009 SARIFRuleID = "PROV009" // ScopeConflict
	PROV010 SARIFRuleID = "PROV010" // MissingAssociatedSpecs
	PROV011 SARIFRuleID = "PROV011" // ConstraintsWithoutSpecs
	PROV012 SARIFRuleID = "PROV012" // IntentWithoutConstraints
	PROV013 SARIFRuleID = "PROV013" // TitleTooLong
	PROV014 SARIFRuleID = "PROV014" // CircularSupersedes
	PROV015 SARIFRuleID = "PROV015" // ScopeOverlap
	PROV016 SARIFRuleID = "PROV016" // DeadRecord
	PROV017 SARIFRuleID = "PROV017" // ModifiedImplementedRecord
	PROV018 SARIFRuleID = "PROV018" // MissingSpecFile
	PROV019 SARIFRuleID = "PROV019" // InvalidRegexPattern
	PROV020 SARIFRuleID = "PROV020" // SupersessionTypeMismatch
	PROV021 SARIFRuleID = "PROV021" // ImplementsTypeMismatch
	PROV022 SARIFRuleID = "PROV022" // UnresolvedImplements
)

func GetRuleIDForIssue

func GetRuleIDForIssue(issue Issue) SARIFRuleID

GetRuleIDForIssue maps an Issue to its SARIF Rule ID

type SARIFRun

type SARIFRun struct {
	Tool      *SARIFTool      `json:"tool"`
	Results   []SARIFResult   `json:"results"`
	Artifacts []SARIFArtifact `json:"artifacts,omitempty"`
}

SARIFRun represents a single run in SARIF

type SARIFTool

type SARIFTool struct {
	Driver *SARIFDriver `json:"driver"`
}

SARIFTool represents the tool descriptor in SARIF

func NewSARIFTool

func NewSARIFTool() *SARIFTool

NewSARIFTool creates the tool descriptor with the complete rule catalog

type ScopeConflict

type ScopeConflict struct {
	File      string   // The file with conflicting governance
	RecordIDs []string // The IDs of conflicting records
}

ScopeConflict represents two or more open records with overlapping scope

type ScopeEntry

type ScopeEntry struct {
	ID             string     `json:"id"`
	Status         Status     `json:"status"`
	Type           RecordType `json:"type,omitempty"`
	AffectedScope  []string   `json:"affected_scope,omitempty"`
	ForbiddenScope []string   `json:"forbidden_scope,omitempty"`
	Implements     string     `json:"implements,omitempty"`
	HasSpecs       bool       `json:"has_specs"`
}

ScopeEntry is the compact cached projection of a record, carrying only the fields the advice engine (Advise) reads. Heavy prose (intent, constraints, title) is intentionally omitted.

type ScopeIndex

type ScopeIndex struct {
	Fingerprint string       `json:"fingerprint"`
	Entries     []ScopeEntry `json:"entries"`
}

ScopeIndex is the persisted scope cache: a fingerprint of the provenance-dir state plus the compact per-record entries.

type SearchOptions

type SearchOptions struct {
	Query      string // Natural language query
	Limit      int    // Maximum number of results
	ConfigFile string // Path to custom .linespec.yml file
}

SearchOptions holds options for the search command

type Severity

type Severity string

Severity represents the severity level of a validation issue

const (
	SeverityError   Severity = "error"
	SeverityWarning Severity = "warning"
	SeverityHint    Severity = "hint"
)

type StaleScopeWarning

type StaleScopeWarning struct {
	RecordID string
	File     string
	Message  string
}

StaleScopeWarning represents a warning about files in scope that haven't changed since sealing

type Status

type Status string

Status represents the lifecycle state of a Provenance Record

const (
	StatusDraft       Status = "draft"
	StatusOpen        Status = "open"
	StatusImplemented Status = "implemented"
	StatusSuperseded  Status = "superseded"
	StatusDeprecated  Status = "deprecated"
)

func (Status) IsValid

func (s Status) IsValid() bool

IsValid returns true if the status is a known value

type StatusOptions

type StatusOptions struct {
	RecordID   string
	Filter     string // open | implemented | superseded | deprecated | tag:xxx
	Format     string // human | json
	SaveScope  bool   // persist auto-populated scope to file
	ConfigFile string // Path to custom .linespec.yml file
}

StatusOptions holds options for the status command

type SyncOptions

type SyncOptions struct {
	Force bool // Ignore TTL and re-fetch even if cache is fresh
}

SyncOptions holds options for the sync command

type SyncResult

type SyncResult struct {
	Repo        config.SharedRepoConfig
	RecordCount int
	WasFresh    bool
	Err         error
}

SyncAll refreshes all configured repos. force=true ignores TTL. Returns a slice of results in the same order as SharedRepos.

type Violation

type Violation struct {
	RecordID string
	File     string
	Commit   string
	Message  string
}

Violation represents a forbidden scope violation

Jump to

Keyboard shortcuts

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