contextindex

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 46 Imported by: 0

Documentation

Index

Constants

View Source
const (
	VerdictUnframable  = "unframable"
	VerdictUnsupported = "unsupported"
	VerdictDirty       = "dirty"
	VerdictStale       = "stale"
	VerdictRetained    = "retained"
	VerdictAbsent      = "absent"
)

The SBQ-V0-008 verdicts. Every possessed entry gets exactly one, matched by literal repository-relative path against the loaded index's tables: no normalization, case folding, symlink resolution or Git process.

View Source
const (
	FallbackBudgetCompacted       = "budget-compacted"
	FallbackUnsupportedPossession = "unsupported-possession"
	FallbackMixedWorktree         = "mixed-worktree"
)

The SBQ-V0-010(d) fallback reasons. A fallback disables suppression for one whole operation; there is no partial fallback.

View Source
const (
	// UnparsedPythonGrammar marks a .py source the closed 3.12 grammar refused.
	// Every definition and import in the file is absent from the index.
	UnparsedPythonGrammar = "PYTHON_SOURCE_UNPARSED"
	// UnparsedNotText marks a source whose bytes are not decodable text, so no
	// line-oriented extractor ran over it at all.
	UnparsedNotText = "SOURCE_NOT_TEXT"
	// UnparsedGoGrammar marks a .go source go/parser refused. Symbols fall back
	// to the line scanner, so that table is approximate rather than absent;
	// imports have no fallback and are absent.
	UnparsedGoGrammar = "GO_SOURCE_UNPARSED"
	// UnparsedWebLexical marks a JavaScript or TypeScript source whose import
	// lexer reached end of file still inside a block comment or a template
	// literal. Everything after that opener was consumed as literal text, so
	// any import among those lines is missing from the edge set. The file is
	// still indexed and searchable; only its import row is short, which is
	// exactly the loss that would otherwise be indistinguishable from a file
	// that imports nothing.
	UnparsedWebLexical = "WEB_SOURCE_UNPARSED"
)
View Source
const (
	// LookupDefaultLimit is the result cap when the invocation names none.
	LookupDefaultLimit = 20

	// LookupIdentifierErrorCode is the typed refusal for an identifier or term
	// that is empty or over maxLookupIdentifierBytes.
	LookupIdentifierErrorCode = "unsupported-context-lookup-identifier"
)
View Source
const (
	// MinPacketBytes is the smallest budget that can hold the worst-case
	// mandatory abstaining envelope: a mixed-worktree query packet whose
	// abstention.reason, learning block, compacted intent, and 64-hex-char
	// sha256-format revision are all at their longest mandatory shape,
	// rounded up to the next 64-byte boundary for headroom. See
	// TestMinPacketBytesIsTheWorstCaseAbstainingEnvelopeRoundedUp in
	// receipt_budget_test.go, which re-derives this value from that
	// construction and fails if the mandatory field set grows past it.
	MinPacketBytes = 1_216
	MaxPacketBytes = 1_000_000
)
View Source
const (
	// SlotWeightsPath is the admitted learned slot-weight trace, beside the
	// local trace store.
	SlotWeightsPath = ".context-corvint/slot-weights.json"
	SlotWeightMin   = -2
	SlotWeightMax   = 2
)

Learned slot weights (learned-trace-admission-v0, LTA-V0-009..012). The live context path reads only the admitted file below; it never opens the self-observation or unplanned-read ledger (AGENTS.md invariant 4).

View Source
const (
	// TrustProjectAuthority is content the project owns as instruction,
	// specification, decision, contract, or ledger (AGENTS.md invariant 3).
	TrustProjectAuthority = "project-authority"
	// TrustRepositoryContent is content pinned to a blob of the tree at the
	// packet's revision and read by Corvint's own grammars or conventions.
	TrustRepositoryContent = "repository-content"
	// TrustRepositoryHistory is a relation read from commit history: a reason
	// to read a file, never proof of its content.
	TrustRepositoryHistory = "repository-history"
	// TrustExternalProvider is content fetched from a provider command or MCP
	// server (`internal/extevidence`).
	TrustExternalProvider = "external-provider"
	// TrustToolOutput is content a tool produced that no blob of the tree
	// pins: a learned ledger, an unverified analyzer contract, generated
	// documentation, and every label this table does not name.
	TrustToolOutput = "tool-output"
)

Trust classes (decision 0346; TCP-V0-023, FPK-V0-032). Every evidence row of a `context` packet and every `prove` proof row carries exactly one, derived from the `authority` label the row already carries and from nothing else, so the class adds no input and cannot disagree with the label.

View Source
const SyntaxAuthority = "syntax"

SyntaxAuthority is the weakest evidence label a citation can carry: the host language's grammar found the symbol, and no project-owned document says it is the answer. Product invariant 3 ranks it below every project-owned authority, so `setCoverage` treats a packet made only of it as uncorroborated.

View Source
const SyntaxOnlyUncertainty = "all results are syntax matches; no project-owned authority corroborates the task"

SyntaxOnlyUncertainty is the single deterministic line a query packet carries when nothing but the host language's syntax connects its results to the task.

View Source
const UnverifiedContractAuthority = "unverified-contract"

UnverifiedContractAuthority is the authority label `impact` emits for a governing decision it cannot resolve from a revision the caller did not author. `CF-V0-031` (ratified 2026-08-29) permits exactly two dispositions for such a surface: gain a caller-independent revision, or report its accepted-authority labels as unverified. `Impact(index, paths, limit)` has no base revision and no diff -- `paths` is the change set the caller *declares* -- so it takes the second, unconditionally. A guard keyed on `paths` would close nothing, which `CF-V0-025` forbids asserting: the cited decision reaches `recordResult` through a ledger record's `adr:` field, so an actor that authors the decision in its own change set need only omit the path. Withholding for every citation is the only disposition that does not depend on the caller's own declaration.

View Source
const UnverifiedLedgerAuthority = "unverified-ledger"

UnverifiedLedgerAuthority is the counterpart label for a canonical ledger record the caller's own change set declares. `range impact` does have a caller-independent base, so it withholds only where the ledger file is genuinely inside the computed change set -- a scoped refusal, not a blanket one.

Variables

View Source
var ErrSnapshotRefused = errors.New("snapshot body failed verification")

ErrSnapshotRefused reports that a read of a deferred load touched a pack body whose blocks failed verification. The result is withheld; the caller reloads through a loader that verifies every section up front, which refuses the pack as the IDX-SNAP-V0-003 miss and falls back to the gob snapshot, then the build.

View Source
var LearnableSlots = []string{"pair", "mentioned", "definition", "reverse-import", "reference", "cochange", "sibling", "test", "lexical", "documentation"}

LearnableSlots is TCP-V0-004's slot order without the reserved relations: the closed set a learned weight may reorder.

Functions

func AnalyzerSchemaID

func AnalyzerSchemaID() string

AnalyzerSchemaID is shared by experimental immutable stores of analyzer facts.

func CanonicalJSON

func CanonicalJSON(value any) ([]byte, error)

CanonicalJSON reproduces Python json.dumps(value, sort_keys=True, separators=(",", ":")) with its default ensure_ascii=True behavior.

func CheckpointResults

func CheckpointResults(index *Index, paths []string) []map[string]any

CheckpointResults returns current, unranked result identities for the admitted critical paths. It consumes no caller prose, trace, snapshot or ranking budget. Documents and ledger records retain references to paths outside their own id; symbol identities retain their declaration names while refreshing line numbers. Relationship results describe the declared eligible path set, as Impact does.

func CorpusGeneratedSource

func CorpusGeneratedSource(path string, data []byte) bool

CorpusGeneratedSource reuses the native generated-path/header rules even for inventoried files whose suffix excluded them before the native content read.

func CorpusRepositoryID

func CorpusRepositoryID(ctx context.Context, root, revision string) (string, error)

CorpusRepositoryID uses the same root-commit identity as external evidence. Shallow or grafted histories cannot establish that identity.

func DecodePythonUTF8

func DecodePythonUTF8(value []byte) string

DecodePythonUTF8 exposes the oracle-compatible decoder to scoped CLI adapters.

func DogfoodPromptContext

func DogfoodPromptContext(ctx context.Context, index *Index, task string, scope []PinnedIntentPointer, limit, budgetBytes int) (map[string]any, error)

DogfoodPromptContext implements only LCP-V0-010/011. It projects immutable selectors and fixed diagnostics; it never emits task fragments, reads history, or writes state. The caller owns index acquisition and its stability bracket. budgetBytes includes the canonical packet's terminating LF, not its enclosing event. Empty task is permitted for startup and remains unresolved; the event adapter must reject an empty user-prompt before calling this compiler. An envelope that cannot retain mandatory omissions is refused.

func EvalFeature

func EvalFeature(index *Index, featureID string, limit int, budget *int) (map[string]any, error)

EvalFeature is the evaluation-only feature compiler. Unlike the public feature command, it does not reject an otherwise supported Go candidate ranking merely because the repository also contains another source language.

func EvalImpact

func EvalImpact(index *Index, paths []string, limit int, budget *int) (map[string]any, error)

EvalImpact applies the shared packet budget to the broad impact kernel without changing the public impact command's qualified option surface.

func EvalQuery

func EvalQuery(ctx context.Context, index *Index, text string, limit int, budget *int, snapshots ...QueryTraceSnapshot) (map[string]any, error)

EvalQuery compiles the broad Python-compatible query profile used by eval. Its symbol ranking is qualified for Go sources; other indexed source kinds remain available as records, documents, evidence, and history paths.

func EvalQueryPending

func EvalQueryPending(ctx context.Context, index *Index, text string, limit int, budget *int, pending func() (QueryTraceSnapshot, error)) (map[string]any, error)

EvalQueryPending is EvalQuery for a trace snapshot that is still being read. The concurrent default path reads the local trace store beside the learn stage's opening observation and the ranking pass, none of which reads trace state; pending is resolved before the stage's first comparison and before every earlier return, so a trace read failure is still the first error the query reports and the receipt is the one the sequential form compiled.

func EvalQueryShared

func EvalQueryShared(ctx context.Context, index *Index, text string, limit int, budget *int, snapshot QueryTraceSnapshot, opening *LoaderObservation, traceClosing bool) (map[string]any, error)

EvalQueryShared is EvalQuery opening the learn stage's window on the loader's observation and closing it once. traceClosing says the trace read ran against that same opening (tracerecordrepo.ReadObserved) and left its closing comparison to this bracket; a read that was blocked by a dirty worktree never compared anything and owes nothing.

func EvidenceTerms

func EvidenceTerms(text string) map[string]struct{}

EvidenceTerms exposes the native lexical vocabulary without a second index.

func ExpandedRangeImpact

func ExpandedRangeImpact(ctx context.Context, index *Index, base string, limit int) (map[string]any, error)

ExpandedRangeImpact explicitly selects the experimental fixed-256-path profile. All remaining validation, resource bounds and semantics are shared with RangeImpact; no failed default request falls back to this profile.

func Feature

func Feature(index *Index, featureID string, limit int) (map[string]any, error)

Feature compiles an unbudgeted canonical-feature receipt.

func FeatureBudget

func FeatureBudget(index *Index, featureID string, limit int, budget *int) (map[string]any, error)

FeatureBudget compiles the Go-symbol feature slice and applies the shared Python-compatible packet budget selector.

func ForbiddenPathReason

func ForbiddenPathReason(value string) string

ForbiddenPathReason exposes the IDX-SNAP-V0-018 path screen: the exclusion reason for value, or "" when the screen admits it. Learned-trace path admission consumes it so the two can never hold different sets (decision 0102).

func Impact

func Impact(index *Index, paths []string, limit int) (map[string]any, error)

func ImpactPathAdmitted

func ImpactPathAdmitted(value string) bool

ImpactPathAdmitted reports whether the immutable index admits the path's suffix. It does not imply that impact has a reverse-import rule for it.

func ImpactRuleNamed

func ImpactRuleNamed(changedPath string) bool

ImpactRuleNamed reports whether `GPK-V0-027` names a reverse-import resolution rule for this path's suffix. It is the single predicate behind the receipt's coverage disclosure. Index admission is a separate predicate: an admitted suffix can lack a reverse-import rule without being refused.

func ImportAnchorLine

func ImportAnchorLine(source Source, imported string) (int, bool)

ImportAnchorLine returns the original native extractor's statement anchor.

func LoadContextSnapshot

func LoadContextSnapshot(ctx context.Context, root string) (*Index, bool, *LoaderObservation, error)

LoadContextSnapshot is LoadSnapshot for the context verb: the same read, the same hit, and on a miss the loader's observation. The observation is nil when the loader spawned nothing (no snapshot directory) or when HEAD moved during the load, so a build never opens on a pair that straddles two revisions. The hit path is unchanged: decode overlaps the status scan and a closing identity read still guards the hit.

func LoadContextSnapshotDeferred

func LoadContextSnapshotDeferred(ctx context.Context, root string) (*Index, bool, *LoaderObservation, error)

LoadContextSnapshotDeferred is LoadContextSnapshot for a caller that hands the index only to TaskContext: a pack hit verifies every section but the bodies when it opens, and each body when the packet first reads it. A body that fails makes TaskContext return ErrSnapshotRefused instead of a packet, and the caller reloads through LoadContextSnapshot. Other formats are unchanged.

func LoadQuerySnapshot

func LoadQuerySnapshot(ctx context.Context, root string) (*Index, bool, *LoaderObservation, error)

LoadQuerySnapshot is LoadSnapshot for the repository query path: the same read and the same hit, plus the loader's paired observation on a hit so the shared query bracket (CORVINT_QUERY_SHARED_OBSERVATION=1) can open on it. The observation is nil on a miss that spawned nothing or straddled two revisions.

func LoadSharedQuerySnapshot

func LoadSharedQuerySnapshot(ctx context.Context, root string) (*Index, bool, *LoaderObservation, error)

LoadSharedQuerySnapshot is LoadQuerySnapshot for a caller whose shared query bracket (CORVINT_QUERY_SHARED_OBSERVATION=1, proposed GPK-V0-065) closes on a full observation and compares it to the index. That closing is the identity re-read this loader otherwise makes after the decode, so a hit is returned without it, as LoadEventSnapshotObserved does for the harness window (GPK-V0-058); an identity that moves between the opening pair and the decode is refused at the bracket's closing instead of read as a miss here. The context also lets the closing status scan reuse the opening's metadata probes.

func LoadedEngineID

func LoadedEngineID() string

LoadedEngineID is the engine id loadSnapshot computes to name the snapshot file it opens: a digest of the running binary, taken with no child process (SBQ-V0-010(f)). It is the load-path id, not SnapshotReceipt.Engine, which is write-side only, and it spawns nothing, unlike ProbeSnapshot's Git identity read. Empty when the executable cannot be read, which disables snapshots.

func LookupAuthorityTriggers

func LookupAuthorityTriggers(index *Index, paths []string, limit int) (map[string]any, error)

LookupAuthorityTriggers compiles the trigger table for paths and returns the standard lookup envelope. An empty table is reported as `NO_CANDIDATES`, which is the dormant case and the common one.

func LookupDefinitions

func LookupDefinitions(index *Index, identifier string, limit int) (map[string]any, error)

LookupDefinitions lists the symbols defining identifier: exact-name matches first, then case-insensitive ones, each class ordered by rarity (fewest definers of that name first), then name, path, line.

func LookupGrep

func LookupGrep(index *Index, terms []string, limit int) (map[string]any, error)

LookupGrep ranks the sources holding the given terms by BM25 over the body and path term fields (TCP-V0-014's formula without the whole-identifier field or the stop list: the caller chose the terms) and quotes the matching lines of each listed source. Terms are matched as whole tokens of the term table; substring and regular-expression matching is the n-gram lane's scope.

func LookupReferences

func LookupReferences(index *Index, identifier string, limit int) (map[string]any, error)

LookupReferences lists the files that name identifier as a whole word (the identifier vocabulary, as written) or import a file defining it (the reverse-import rules of `impact`), with whole-word counts, excluding the defining files themselves.

func PossessionVerdict

func PossessionVerdict(index *Index, entry PossessedEntry) string

PossessionVerdict verdicts one entry at the loaded snapshot (SBQ-V0-008). Precedence is (a) unframable, (b) unsupported, (c) dirty, (d) stale, (e) retained, (f) absent.

func PythonImportCandidates

func PythonImportCandidates(sourcePath string) map[string]struct{}

PythonImportCandidates is the set of module spellings by which other Python sources may import sourcePath, reproducing src/context_corvint.py:723-731. Exported so other packages that resolve raw import specifiers to source paths (e.g. internal/disagree's structural channel) can reuse the same oracle-matching candidate set instead of re-deriving it.

func QueryAuthorityStart

func QueryAuthorityStart(ctx context.Context, index *Index, text string, limit int) (map[string]any, error)

QueryAuthorityStart compiles the deliberately narrow GPK-V0-028 task-start profile.

func QueryAuthorityStartBudget

func QueryAuthorityStartBudget(ctx context.Context, index *Index, text string, limit int, budget *int) (map[string]any, error)

QueryAuthorityStartBudget adds packet selection to the authority-start profile. The packet is the Python oracle's project-operations answer: the uniquely highest instruction result, a second ranked instruction document when the limit admits one, then at most three advisory learned-path candidates when the limit leaves room for them.

func QueryIntent

func QueryIntent(text string) string

QueryIntent exposes the existing classifier for bounded diagnostic metadata; it never retains the supplied task text.

func QuerySnapshotAuthority

func QuerySnapshotAuthority(index *Index, text string) (map[string]any, error)

QuerySnapshotAuthority selects immutable project authority only. Mutable traces and checkout-bracketed history are outside the explicit snapshot.

func RangeImpact

func RangeImpact(ctx context.Context, index *Index, base string, limit int) (map[string]any, error)

RangeImpact compiles hunk-qualified impact for one immutable base commit against the clean, stably captured HEAD represented by index.

func SnapshotDirectory

func SnapshotDirectory(root string) string

SnapshotDirectory is where a repository's snapshots live: `corvint/index` under the Git common directory, shared by every linked worktree, or the worktree's own `.corvint/index` when the common directory cannot be resolved from `.git` metadata without a Git process (DIRTY-CACHE-013).

func SortInvalidated

func SortInvalidated(entries []InvalidatedResult)

SortInvalidated orders delta.invalidated by (kind, id, path) alone. It is the one delta list exempt from operation order (SBQ-V0-010(f)).

func StabilizeReceipt

func StabilizeReceipt(receipt map[string]any) error

StabilizeReceipt re-runs the packet-byte fixed point over a receipt whose results changed (SBQ-V0-010(c)). It is the exported wrapper the batch verb uses: stabilizePacketBytes' own first statement is an unchecked type assertion on `coverage`, so an absent or mistyped coverage member must be a contextindex.Error here rather than a panic there.

func TaskContext

func TaskContext(ctx context.Context, index *Index, task, subject string, limit int) (map[string]any, error)

TaskContext compiles the task-context packet (task-context-packet-v0): the files an agent must read to act on one task, drawn from sources a lexical listing cannot express, with the task's own subject path kept out of the results. Every row carries one evidence line naming the relation that admitted it. The packet is read-only and Go-only; no oracle speaks it.

func TaskContextWeighted added in v0.8.0

func TaskContextWeighted(ctx context.Context, index *Index, task, subject string, limit int, admitted *AdmittedSlotWeights) (map[string]any, error)

TaskContextWeighted is TaskContext under an admitted learned trace. A nil trace is TaskContext exactly; otherwise the packet discloses the trace.

func TaskHasAnchors added in v0.8.0

func TaskHasAnchors(task string) bool

TaskHasAnchors reports whether task carries at least one TCP-V0-022 anchor, by the extraction the compiler applies under CORVINT_CONTEXT_ANCHORS=on, within the compiler's task bound; the retrieval bench reads it to report the anchor-bearing samples as their own stratum.

func TrimPythonSpace

func TrimPythonSpace(value string) string

TrimPythonSpace matches str.strip() for Python's Unicode whitespace set.

func TrustClass added in v0.7.0

func TrustClass(authority string) string

TrustClass derives the one trust class of a row from its authority label.

func TrustTainted added in v0.7.0

func TrustTainted(class string) bool

TrustTainted reports whether a class can satisfy no authority, governance, or basis requirement: content fetched from a provider or produced by a tool is read, never trusted, however it is labelled.

func ValidateFeature

func ValidateFeature(featureID string, limit int) error

ValidateFeature preserves the Python feature function's validation order.

func ValidateQueryAuthorityStart

func ValidateQueryAuthorityStart(text string, limit int) error

ValidateQueryAuthorityStart rejects query profiles that need no repository evidence before an index or Git operation is started.

func ValidateQueryCommand

func ValidateQueryCommand(text string, limit int) (string, error)

ValidateQueryCommand classifies and validates the standalone query profiles before an adapter opens the repository. Project operations take the authority-start validator; repository and agent-tooling tasks take the EvalQuery limit. Every UTF-8 task the oracle accepts is accepted.

func ValidateSlotWeights added in v0.8.0

func ValidateSlotWeights(weights SlotWeights) error

ValidateSlotWeights refuses an unknown relation or an out-of-range weight.

func WithSharedQueryObservation

func WithSharedQueryObservation(ctx context.Context) context.Context

WithSharedQueryObservation is the context of one shared query bracket: the isolated status scans it spawns answer their metadata probes from the first one's over unchanged bytes (gitstatus.WithProbeReuse).

Types

type AdmittedSlotWeights added in v0.8.0

type AdmittedSlotWeights struct {
	Weights SlotWeights
	SHA256  string
}

AdmittedSlotWeights is one gate-admitted learned slot-weight trace and the sha256 of the exact file bytes that carried it.

func LoadAdmittedSlotWeights added in v0.8.0

func LoadAdmittedSlotWeights(root string) (*AdmittedSlotWeights, error)

LoadAdmittedSlotWeights reads the admitted trace under root. An absent file is nil with no error (the default order); a symlink, oversized, malformed, unevaluated or out-of-range file fails closed with the rollback command named.

type Error

type Error struct {
	Code, Message string
	Cause         error
	// contains filtered or unexported fields
}

Error is a stable read-command failure. Ordinary Python-compatible domain and Git errors omit a code; native admission and isolation failures carry one. Cause is the original structured error this Error was rebuilt from, when a caller outside this package flattened one into Code/Message; it carries no Unwrap method, so it never changes what errors.As/errors.Is find elsewhere in a chain through an Error, and a caller that wants the original back (e.g. tracerecordrepo.TruncatedAncestryOf) reads Cause explicitly.

func (*Error) Error

func (err *Error) Error() string

type Exclusion

type Exclusion struct{ Path, Reason string }

type ExtractionNote

type ExtractionNote struct{ Path, Reason string }

ExtractionNote records that a source was admitted and indexed as text, but that its symbol extraction did not run cleanly over the whole file. It is the observable trace of a partial walk.

The index already reports Exclusion for a path it refused outright. A note is the weaker, and more dangerous, case: the path IS in the index, its text IS searchable, and a caller reading only the source count would conclude the file was fully understood. Recording the reason here is what stops a capped or lexically broken extraction from being indistinguishable from a file that genuinely declares nothing.

type GitFailure

type GitFailure struct {
	Arguments  []string
	Stderr     []byte
	ExitCode   int
	StartError error
}

GitFailure retains non-rendered subprocess details for command-scoped parity adapters.

func GitFailureDetails

func GitFailureDetails(err error) (GitFailure, bool)

GitFailureDetails returns a defensive copy without changing Error's public bytes.

type Index

type Index struct {
	Root, ObjectFormat, CommitRevision, Revision, ProfileID, Module string
	StatusSHA256                                                    string
	Sources                                                         map[string]Source
	// Tracked is every path in the tree at Revision, including the kinds the
	// index never reads; a caller naming a subject checks it here (TCP-V0-002).
	Tracked map[string]struct{}
	// Skipped records non-blob tree entries, including gitlinks (SBQ-V0-008).
	Skipped    map[string]struct{}
	Exclusions []Exclusion
	// UnsupportedSuffixCount counts the tracked blobs admittedEntries never
	// read because no allow-listed suffix admits them. They carry no
	// Exclusion row, so the receipt adds this count to its exclusion count
	// (GPK-V0-063) instead of asserting the index read everything else.
	UnsupportedSuffixCount         int
	DirtyPaths                     []string
	Features, Scenarios, Documents map[string]Record
	Markers                        map[string][]Marker
	Symbols                        []Symbol
	Imports                        map[string]map[string]struct{}
	// Unparsed lists, in path order, every admitted source whose facts were
	// dropped. It is the denominator that makes a silent extraction loss
	// countable.
	Unparsed []Unparsed
	// ApproximateImports counts the sources whose import edges no grammar
	// produced: the web languages, whose lexer tells code from comment and
	// literal but recognises no `require()` edge and resolves no specifier,
	// and every other non-Go language, whose scanner has no lexical state at
	// all. It is an aggregate rather than a per-source list because the
	// approximation is a property of the language support, not of any one
	// file: recording it per file would name every JavaScript source in the
	// repository and train its reader to ignore the field.
	ApproximateImports int
	// ExtractionNotes records sources that were indexed as text but whose
	// symbol walk did not complete. It is deliberately separate from
	// Exclusions: an excluded path is absent from Sources, while a noted path
	// is present, searchable, and only partly understood. It is also narrower
	// than Unparsed: Unparsed names a source a grammar refused outright, this
	// names one a scanner walked but could not finish.
	ExtractionNotes []ExtractionNote
	// Vocabulary is the packet's term table (termtable.go), built with the
	// tables on the build and packet paths and carried in the snapshot.
	Vocabulary *TermTable
	// contains filtered or unexported fields
}

func Build

func Build(ctx context.Context, root string) (*Index, error)

func BuildContext

func BuildContext(ctx context.Context, root, subject string) (*Index, error)

BuildContext compiles the same evidence as Build. Test-relation anchors consume imports beyond the explicit subject; omitting them changes cold packet ranks and coverage relative to a snapshot hit.

func BuildContextObserved

func BuildContextObserved(ctx context.Context, root, subject string, opening *LoaderObservation) (*Index, error)

BuildContextObserved is BuildContext opening its stability window on the loader's observation instead of spawning the identity and status pair again. A nil opening is BuildContext. The closing observation is still taken fresh, so the window it closes is the one the loader opened.

func BuildEval

func BuildEval(ctx context.Context, root string) (*Index, error)

BuildEval builds the index the harness query event evaluates over. EvalQuery ranks exclusively out of Features, Scenarios, Documents, Symbols and Markers, and reaches Imports only through featureImplementationCandidates, which reads index.Imports[markerPath] for the Go marker test paths of a competitive record. Extracting imports for those paths alone is the only table narrowing the query profile admits: every other table it reads is compiled in full.

BuildQuery stays narrow and unchanged -- it serves the authority-start query verb, which never hands its index to EvalQuery.

func BuildForSnapshot

func BuildForSnapshot(ctx context.Context, root string) (*Index, error)

BuildForSnapshot is the writer's full-table build. Other Build consumers do not opt into shard reads, preserving the oracle and harness build paths.

func BuildQuery

func BuildQuery(ctx context.Context, root, text string) (*Index, error)

BuildQuery captures the bounded immutable evidence required by the narrow authority-start query profile. Impact continues to use Build so its complete source index remains unchanged.

func BuildRevisionContext

func BuildRevisionContext(ctx context.Context, root, revision string) (*Index, error)

BuildRevisionContext uses the native immutable evidence reader at an explicit commit. It creates no snapshot and does not change HEAD or the working tree.

func BuildWithGitExecution

func BuildWithGitExecution(ctx context.Context, root, executable string, environment []string) (*Index, error)

BuildWithGitExecution builds the same immutable evidence as Build using a caller-qualified absolute Git executable and closed environment. Qualification of that executable, environment and repository belongs to the caller. This request reads source bytes only from immutable Git objects, never a worktree copy or persisted index, and never falls back to ambient Git settings.

func LoadEventSnapshot

func LoadEventSnapshot(ctx context.Context, root string, compact bool) (*Index, bool, error)

LoadEventSnapshot reads only the tables used by file-change and compact session-start. A clean compact event needs only the profile identifier; a dirty one reopens the immutable file for the impact tables it must rehydrate.

func LoadEventSnapshotDeferred

func LoadEventSnapshotDeferred(ctx context.Context, root string, compact bool) (*Index, bool, error)

LoadEventSnapshotDeferred is LoadEventSnapshot whose pack hit verifies each body when a read first touches it, under the same SnapshotRefusal contract as LoadSnapshotDeferred; the fallback is LoadEventSnapshot.

func LoadEventSnapshotObserved

func LoadEventSnapshotObserved(root string, compact bool, observation Observation) (*Index, bool, error)

LoadEventSnapshotObserved is LoadEventSnapshot for a caller whose own bracket already holds the opening observation and will take the closing one (CORVINT_HARNESS_SHARED_OBSERVATION=1, proposed GPK-V0-058). It spawns no Git process: the observation names the file and supplies the dirty set, and the caller's closing observation is the identity re-read this loader otherwise makes. The Observation is the one Observe returns: the identity that names the snapshot file and the status read whose sorted paths and digest a hit applies (IDX-SNAP-V0-010). Everything else -- the stat miss, the engine check, the header check, the compact and dirty decode choice -- is loadSnapshot's.

func LoadSnapshot

func LoadSnapshot(ctx context.Context, root string) (*Index, bool, error)

LoadSnapshot returns the snapshot of the repository's current tree with the worktree's dirty paths applied, or ok=false when no snapshot matches. It reads identity and status as a build's opening observation does, closes the hit with one identity re-read after status, and writes nothing.

func LoadSnapshotDeferred

func LoadSnapshotDeferred(ctx context.Context, root string) (*Index, bool, error)

LoadSnapshotDeferred is LoadSnapshot whose pack hit verifies each body when a read first touches it. The caller checks SnapshotRefusal after its reads and, on a refusal, discards the result and reloads through LoadSnapshot.

func (*Index) SnapshotRefusal

func (index *Index) SnapshotRefusal() error

SnapshotRefusal reports the first body verification failure a read of this deferred load found, wrapped in ErrSnapshotRefused. A caller of a deferred loader checks it after every read of the index and, when it is non-nil, discards what it computed.

func (*Index) UnparsedPaths

func (index *Index) UnparsedPaths() map[string]string

UnparsedPaths returns the set of paths whose facts were dropped, for callers that need membership rather than the ordered table.

type InvalidatedResult

type InvalidatedResult struct {
	Kind    string
	ID      string
	Path    string
	Verdict string
}

InvalidatedResult is one (result, invalidation-matched path) pair (SBQ-V0-009(h)). It is the one delta list keyed without an operation.

type LoaderObservation

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

LoaderObservation is the paired identity-and-status read a snapshot load made, carried out of a miss so the build that follows can open its stability window on it. IDX-SNAP-V0-002 already says the loader reads the repository exactly as a build's opening observation does; before this the miss threw that pair away and spawned it again, two of the eight Git processes a miss with the snapshot store present cost.

func (*LoaderObservation) Observation

func (opening *LoaderObservation) Observation() Observation

Observation is the loader's pair in Observe's exported shape, for a caller outside the package that checks a read against it. A pair carried out of a hit has no error on either side: the loader returned them instead.

type Marker

type Marker struct {
	Path, BlobHash string
	Line, Column   int
}

type Observation

type Observation struct {
	ObjectFormat, CommitRevision, Revision, StatusSHA256 string
	DirtyPaths                                           []string
}

Observation is the header-level repository state a caller needs to re-prove that the repository did not move, without compiling an index.

func Observe

func Observe(ctx context.Context, root string) (Observation, error)

Observe reads exactly the header fields Build derives from Git, opening no source and parsing nothing. ProfileID is deliberately absent: it is projectprofile.Detect over the source set, which is a pure function of the tree, so an equal Revision already implies an equal ProfileID.

type PinnedIntentPointer

type PinnedIntentPointer struct {
	Path     string `json:"path"`
	Revision string `json:"revision"`
	BlobHash string `json:"blob_hash"`
}

PinnedIntentPointer is a caller-owned enrollment declaration, not authority. An empty BlobHash means the path was unavailable when enrollment was pinned.

type PossessedEntry

type PossessedEntry struct {
	Path     string
	BlobHash string
}

PossessedEntry is one caller-supplied possession row (SBQ-V0-007(a)). The optional `line` is validated and ignored in V0, so it is not carried here: a stored line and one dropped after validation are indistinguishable on the wire.

type PossessionOutcome

type PossessionOutcome struct {
	Fallback    string
	Suppressed  []SuppressedResult
	Invalidated []InvalidatedResult
	Ignored     []PossessedEntry
}

PossessionOutcome is what one operation's possession list did to its receipt. A non-empty Fallback means suppression was disabled for that whole operation and every entry is echoed under Ignored.

func ApplyPossession

func ApplyPossession(index *Index, receipt map[string]any, entries []PossessedEntry) (PossessionOutcome, error)

ApplyPossession suppresses the results whose evidence the caller already holds, in place, and reports what the possession list did (SBQ-V0-009, SBQ-V0-010). The receipt is the one the standalone verb returned, so no verb's code path changes.

type QueryTrace

type QueryTrace struct {
	TraceID, Task, Outcome, Revision string
	OpenedPaths                      []string
	ChangedPaths                     []string
}

QueryTrace is the bounded trace-reader output EvalQuery is permitted to rank. Callers cannot use it to bypass trace-store validation: snapshots are accepted only through NewQueryTraceSnapshot. Revision is the commit the trace was recorded against. A candidate path's evidence always pins to the index's current blob for that path, which may postdate this revision; callers that build evidence from a trace MUST disclose Revision alongside the pin rather than let the current blob stand in for what the trace actually observed.

type QueryTraceSnapshot

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

QueryTraceSnapshot is an immutable, state-validating view of one completed tracerecordrepo.Read call.

func NewQueryTraceSnapshot

func NewQueryTraceSnapshot(state string, records []QueryTrace) (QueryTraceSnapshot, error)

NewQueryTraceSnapshot defensively copies a validated trace read for EvalQuery.

type Record

type Record struct {
	Kind, ID, Path, BlobHash string
	Line                     int
	Fields                   map[string]any
}

type SlotWeights added in v0.8.0

type SlotWeights map[string]int

SlotWeights maps a learnable relation to an integer in [SlotWeightMin, SlotWeightMax]; an absent relation weighs zero.

type SlotWeightsFile added in v0.8.0

type SlotWeightsFile struct {
	SchemaVersion int             `json:"schemaVersion"`
	Weights       SlotWeights     `json:"weights"`
	Evaluation    json.RawMessage `json:"evaluation"`
}

SlotWeightsFile is the admitted file's wire shape.

func DecodeSlotWeightsFile added in v0.8.0

func DecodeSlotWeightsFile(raw []byte) (SlotWeightsFile, error)

DecodeSlotWeightsFile strictly decodes and validates admitted-file bytes.

type SnapshotProbe

type SnapshotProbe struct {
	Path, Tree, Commit, Engine string
}

SnapshotProbe identifies a matching snapshot without decoding its index.

func ProbeSnapshot

func ProbeSnapshot(ctx context.Context, root string) (SnapshotProbe, bool, error)

ProbeSnapshot reads only the current snapshot's header. It reports a miss for a missing, corrupt, or mismatched file and never writes.

type SnapshotReceipt

type SnapshotReceipt struct {
	Path                 string
	Bytes                int64
	Tree, Commit, Engine string
	Sources, Symbols     int
	Evicted              int
	// SectionedPath and SectionedBytes name the experimental sectioned file
	// written beside the gob snapshot under CORVINT_SNAPSHOT_FORMAT=sectioned.
	SectionedPath  string
	SectionedBytes int64
	// PackPath and PackBytes name the experimental pack (`.aip`) written
	// beside the gob snapshot under CORVINT_SNAPSHOT_FORMAT=pack (proposed
	// IDX-SNAP-V0-015).
	PackPath  string
	PackBytes int64
}

SnapshotReceipt is what `corvint index` reports about the file it wrote.

func WriteSnapshot

func WriteSnapshot(index *Index) (SnapshotReceipt, error)

WriteSnapshot persists index for its tree, atomically, and keeps the directory to the store's entry bound (DIRTY-CACHE-007, snapshotStore.bound). Writers from several worktrees take no lock: each publishes a complete, synced file by rename onto the same key, the last rename wins, and a reader holds whichever complete file it opened (DIRTY-CACHE-013).

type Source

type Source struct {
	Path, BlobHash string
	Data           []byte
	Mode           string
	// Checked and Valid record one textDecodable pass over Data, made when the
	// source was pinned. Data is never written after that, so Text can alias
	// it instead of validating and copying the body on every call: on the
	// Beamfall corpus that copy and its garbage were a fifth of a build's CPU.
	Checked, Valid bool
	// contains filtered or unexported fields
}

func (Source) Text

func (source Source) Text() (text string, valid, loaded bool)

Text reports separately whether the source bytes were loaded and whether those loaded bytes are valid text. An unloaded source is never an empty one.

type SuppressedResult

type SuppressedResult struct {
	Kind string
	ID   string
	Rows int
}

SuppressedResult is one result that left `results` for `delta.suppressed` (SBQ-V0-009(f)). Rows is the count of that result's evidence rows.

type Symbol

type Symbol struct {
	Kind, Name, Path, BlobHash string
	Line                       int
	// EndLine is the declaration's last line, 1-based and inclusive, or 0 when
	// the extractor that produced the symbol names no extent. Only the Python
	// grammar reports one and only the Python context window reads it, because
	// the oracle clamps that window to the declaration end and clamps no other
	// (DR-0005, decision 0007 D4 as amended).
	EndLine int
}

type TermTable

type TermTable struct {
	Paths     []string
	Terms     termPostings
	Words     termPostings
	PathTerms termPostings
	// SymbolWindows inverts the ranking's symbol context windows: for key k,
	// Sources[Offsets[k]:Offsets[k+1]] are the positions in Index.Symbols,
	// ascending, whose window text (symbolwindows.go) yields k under terms().
	// The full compile builds it for the snapshot; an index compiled for one
	// query leaves it empty and scans the windows instead.
	SymbolWindows windowPostings
	// IdentGraph is the identifier definition/reference graph over Paths
	// (identgraph.go, TCP-V0-030), built with SymbolWindows by the full
	// compile.
	IdentGraph *identGraph
	// contains filtered or unexported fields
}

TermTable is the packet's vocabulary, built once per tree beside the other tables and carried in the snapshot: every readable source's lowercased camel-split tokens with their occurrence counts (Terms), its identifier words as written (Words), and the tokens of its path (PathTerms), each inverted so a task term costs one binary search and one posting walk instead of one pass over every source body (decision 0033). A source id is its position in Paths. A source over contextMaxBytes, or one whose bytes are not text, has no posting, which is the same absence the scan it replaces produced.

type Unparsed

type Unparsed struct{ Path, BlobHash, Facts, Reason, Detail string }

Unparsed names a source the index admitted and counted, but extracted no facts from. An Exclusion is a path the index never took in; an Unparsed path is one it did take in and then dropped the contents of. Without this table the two failure modes a caller most needs to separate -- a file that defines nothing, and a file whose definitions were discarded -- are the same observation: zero symbols against a source that is present and counted.

It exists because of the defect class this index is most exposed to: extraction that stops, emits nothing, and leaves the source counted as indexed, so the index reports success over partial data and no counter anywhere can observe the omission. A refusal that is recorded is recoverable; one that is swallowed is invisible until someone re-derives the truth set by hand.

Facts names which table went short -- "symbols" or "imports" -- because a source can be refused for one and complete for the other. Reason is the stable code a caller branches on. Detail carries the extractor's own refusal verbatim, which distinguishes a source the grammar rejected from one that merely exceeded a nesting limit. BlobHash binds the loss to exact bytes, so a caller can tell a recurring refusal from the same file changing underneath it.

Jump to

Keyboard shortcuts

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