Documentation
¶
Overview ¶
Package workcensus is the shared source census engine for maintained clients. Statement work (#1615), source readers (credentials), bound-plan producers (#1640/#1583), capabilities (#1644), trim provenance (#1486), and storage context/envelope populations supply client data to this implementation. None needs its own AST or SSA extractor. Native capture guards (testing/capturecensus) also supply typed roots and responsibility targets as client data. Program.ReachableFrom and its Reachability.PathTo return the same conservative method/closure/wrapper population and a deterministic shortest function path. A path is an inventory witness, not a runtime or dominance proof; public behavioral controls remain the client's obligation. No client needs a private reachability walker. Program.SourceCallSites/SourceReferences on a generic source origin union visible instance invocations/carriers through compiler wrappers. Queries on a concrete instance stay specific. An uninvoked stored method value is a reference, never a fabricated call. Physical call positions remain distinct.
Loading and selecting ¶
Config supplies Dir, package Patterns, BuildFlags, Tests, Env, additional go/packages LoadMode bits, source Packages, Roots, Selectors and Overlay. Patterns select the packages whose SSA bodies are built. Dependencies outside that initial selection can have only export information; their unavailable bodies remain an explicit approximation boundary. A whole-module reachability client loads ./... even when Packages limits the selected source members to a smaller domain. Limiting member selection is different from omitting a maintained producer, registry implementation or intermediate caller body. IncludeInactive permits syntax-only selection of excluded build files; ExcludeGenerated is an explicit exclusion, reported in Inventory.Sources. Standard and client ContextTypes/ContextFields affect diagnostic Scope only. Scope uses declared source names, skipping discarded/unnamed parameters and receivers. A discarded child input cannot hide a usable lexical ancestor. Context and checkpoint naming policy is not part of reachability/selection.
Roots match package/function identity and optionally a declared method receiver; Required roots fail when missing. Method instances are normalized to source origins. VTA refines CHA over all visible source functions, including registry initializers and function values. Reachability unions generic instances and retains lexical callbacks through opaque dependency bodies.
Selectors are JSON-compatible data, with no executable predicate hooks. Reachability="reachable" selects statement work; "all" visits all declarations in the selected source packages independently of the call graph. Node selectors cover declarations (including arbitrary unused methods), lexical function literals, types/aliases, global variable/constant initializers, imports, files, loops, calls, identifiers, string/byte indexes and slices, maps, fields, comparisons and other supported syntax. Callee package/name, receiver/result types, underlying type shapes, source file/owner and build-state filters are generic data. Imported aliases and generic Index/IndexList calls resolve via go/types and conservative alias/VTA targets; inactive files have syntax but no fabricated type information.
Independent populations use different Groups. The first matching rule in a group wins per possible call target; alias targets union their kinds once per source node. A canonical adapter can therefore retain an existing primitive Kind without adding an extractor. For example:
config := workcensus.Config{
Dir: checkout, Patterns: []string{"./pkg/query/..."},
Roots: []workcensus.Root{{Package: "example/pkg/query", Name: "Execute", Required: true}},
Selectors: []workcensus.Selector{
{Kind: "range", Node: "range", Group: "work"},
{Kind: "copy", Node: "call", Builtin: true, Names: []string{"copy"}, Group: "work"},
{Kind: "text-index", Node: "index", OperandTypes: []string{"string"}, Reachability: "all"},
{Kind: "producer", Node: "declaration", Reachability: "all"},
},
}
actual, err := workcensus.Extract(config)
Config.Documents adds maintained JavaScript, TypeScript or TSX source paths. They use the same all-source selector/manifest API through the published Tree-sitter grammars. Named functions, assigned arrows, object/class methods, closures, declarations and source operations are selectable. They report byte offsets plus UTF16Offset/UTF16End and UTF-16 columns, with Typed/Reachable false. No Go semantic type/reachability claim is made for these languages. The optional language adapter requires CGO; a pure-Go census explicitly refuses syntax documents needing those grammars.
Config.SourceRoots discovers maintained files before package loading. Clients supply extension-to-language maps, directory/basename exclusions and syntax or lexical Mode. Excluded paths are reported in Sources. New Overlay files enter that same discovery, including previously unseen packages under plugins. Go files outside the loaded composition are parsed once as syntax-only sources; they never acquire fabricated type or reachability facts. Lexical documents use Node="text", Pattern (Go regexp) and optional FoldCase. A named language and explicit lexical mode make comments/values/declarations an approximation, rather than silently treating an unsupported language as an empty population. Syntax JS/TS/TSX still requires CGO; lexical peers and Go do not.
IncludeSyntax exposes Member.Syntax: the selected ast.Node, enclosing owner, ancestors, exact source bytes, FileSet and the already-loaded types.Info. This view is read-only, in-process and omitted from JSON. A capability client can use go/types Implements/NewMethodSet on selected TypeSpecs, including aliases/promoted/pointer implementations and their package scopes. A trim client joins selected identifiers/assignments/calls through Info.Defs/Uses object identities, with imported/dot/function aliases resolved by the engine. Clients keep domain analysis, never another packages.Load, parser, whole-tree walker, identity generator or manifest checker. Go type assertions (including type-switch nil targets), type switches and go statements are distinct nodes; AssertionType, CommaOK, OperandType and exact start/end coordinates are facts. Identical same-line expressions retain distinct lexical ordinals and offsets.
Policy.RequireSources pins the complete source population, including files with no selected operation. File fingerprints normalize CRLF/LF; coordinates still refer to the original bytes. Existing client IDs crosswalk to shared IDs using relative file, kind and exact source span, then reviewed population differences; retaining a private hash/manifest algorithm is unnecessary. Domain Facts may be attached only to engine-owned Members. Policy.FactKeys compares exact value sets; ClassFact requires the reviewed class to agree with a domain-produced fact. This validates consistency, not the domain inference. ForbiddenClasses require Member.Assignment matching an exact Policy.Assignment (member, digest, class, named owner and operator reference). Such an unresolved routing obligation gives no callee-delegation or behavioral-fix credit. Owner digests and required Subjects pin repair obligations independently of execution.
A source-reader client can supply strings.Split/Index/Fields and regexp method selectors, typed string/[]uint8 index/slice/range selectors, and broad loop candidates. A bound-plan client can select every declaration and body, with additional field/type/map/signature candidates. Broad declaration selection makes producers without familiar names or fact tokens visible. These are review candidates, not a determination that a string contains query text or that a map owns scope facts.
Identity, metadata and validation ¶
Source IDs are relative file + source owner + kind + lexical ordinal, never line numbers. Closures have lexical owner ordinals. Generic instantiations and SSA range-over-function callbacks do not duplicate source syntax. Members have formatted-syntax Digest and enclosing OwnerDigest, source positions, available signatures/underlying types, declared callees/references, and optional call arguments/types, offsets, context diagnostics and conservative bound evidence. Source declarations include global initializers and alias definitions.
Validate(actual, approved, Policy) rejects new, stale, changed, duplicate and unclassified members, missing reasons, and changed/duplicate root populations. Policy supplies the class set, ClassKinds, named Layers, and optional required OwnerDigest, ReviewOwner and behavioral Subjects with allowed owner/subject lists. ClassKinds maps each custom class to statement, non-statement, bounded, delegated, or review. Conventional class meanings cannot be overridden. A reachable member cannot be non-statement; a statement class requires reachability. A bounded class requires engine BoundKnown evidence and the exact inferred maximum/reason, not just matching human claims. Slice views never inherit the base current length; only a proven fixed extent is bounded. Delegated work requires Member.OwnerLayer and an OwnerLayer in Policy.Layers. Every actual call target must occur in that layer with a body digest matching Inventory.Definitions. Loops cannot delegate their enumeration to nested calls; invisible bodies and invented/stale targets cannot establish ownership. These consistency checks do not turn source evidence into execution credit.
failures := workcensus.Validate(actual, approved, workcensus.Policy{
Classes: []string{"reviewed", "bounded"},
ClassKinds: map[string]string{"reviewed": "review"},
RequireOwnerDigest: true,
})
Discovery never grants a class or rewrites an approval manifest. Production overlays in Config let negative controls use exactly the same Extract and Validate calls as their positive gate. Client roots, selectors and reviewed manifests are maintained separately from this generic package.
Delegation witnesses and controls ¶
A work client enables Policy.RequireDelegationWitnesses. Each callee in its OwnerLayer.Members then supplies Observations: CallWitness{MemberID, SiteID, Digest, Callee, RemovalControl}. The client selects observation calls as ordinary members. Validate checks the exact call site, its actual target, and its OwnerSymbol against the delegated source function, independently of the body pin. A nested closure cannot impersonate a direct observation in its parent. Policy.Controls supplies SourceControl{ID, MemberID, Replacement}; every witness must name its matching control. ExtractWithControl applies the type-correct replacement to the engine's source span and calls Extract again. The client runs ordinary Validate and asserts the delegated row's observation failure. The fixture refreshes the changed callee body pin and removes the observation approval too, proving rejection independently of stale hashes. A control that does not compile is invalid evidence. Source presence is not control-flow dominance or runtime work-budget/cancellation proof; those remain executable public obligations of the client.
CallWitness.SiteID must be copied from the selected Member.SiteID. It pins the occurrence independently of the membership ordinal: removing one of several identical calls cannot lend its proof to a later call. Member.ID retains its existing membership meaning (named owners survive line movement; anonymous owners are positional). SiteID is the one opaque occurrence format for Go, syntax peers and lexical peers, using kind/node and physical byte extent. Nested syntax sharing a start remains distinct, and duplicate actual sites fail Validate. Edited coordinates require fresh witness review. ExtractWithControl pads a neutral replacement to the selected byte span, retaining coordinates of every unaffected occurrence; the replacement must fit that span. Both delegated and containing-owner witnesses resolve SiteID and reject a missing identity, even when an identical digest survives under a reassigned ordinal.
Containing-owner witnesses ¶
Work inside a lower-owned function is not a delegated call. A client maps its class to ClassKinds[...]= "observing-owner" and supplies Member.ContainingOwner: ContainingOwnerWitness{OwnerID, OwnerDigest, Observation, Scope}. OwnerID is the exact containing Definition.ID, including a closure's lexical identity. The named OwnerLayer must contain that owner and its current body digest. The selected observation must occur directly in that same body and name a matching SourceControl; an observation in a nested callee or parent cannot substitute. ScopeWitness pins the actual argument (or receiver), its type and engine-owned ValueDefinition.Reference, optionally through a typed field path. A closure may name a captured lexical ancestor's binding. Shadowed, reassigned or escaping bindings fail closed. Computed aliases and opaque scope providers require separate client proof; the engine does not infer those identities. ExtractWithControl removes the observation while retaining the selected work. Validate then reports OWNER OBSERVATION MISSING for that work even if ordinary source/body pins are refreshed. This establishes the source witness and its removal contract, not dominance or the runtime observation's semantics.
Loaded analysis clients ¶
IncludeProgram returns Inventory.Program with the same loaded packages, FileSet, SSA program, function population and VTA/CHA graph used by Extract. LoadProgram(Config) supplies that view directly to SSA-effect clients without a redundant syntax inventory. It owns loading, building and generic function enumeration; callers retain domain-specific generic-instance/effect policy. SuccessfulCallEdge(call, resultIndex) supplies the SSA nil-result branch and its success successor for a client-declared acquisition convention. The client supplies the retained owner/method/field contract and must-flow through release; this generic fact alone grants no lock, callback or effect coverage. The stored-entity authority census uses it while retaining its own effect, acquisition and publication interpretation. #1644 can inspect the loaded type scopes/method sets; #1486 uses selected syntax/typed object identities. No second packages.Load, SSA build, call graph or generic source walk is needed. IncludeSyntheticFunctions(seeds) retains reachable compiler-generated bodies even when their objects belong to an export-only dependency. CallTargets uses the same VTA graph for bound, promoted and interface targets. SourceCallSites follows incoming edges through source-less wrappers to each nearest visible source invocation. SourceReferences supplies real source value carriers when no invocation is visible. Call sites and references are different facts; neither grants acquisition or callback lifetime. The graph conservatively unions possible receivers, so an anchor is not instance provenance. Clients must retain unresolved escaping effects, and report a missing source anchor explicitly rather than silently dropping a known effect. External invisible bodies, reflection and plugins keep their declared approximation limits. ImmutableCellValueAt supplies a narrow def/use fact for one dominating store into a local cell with only read-only captures. Mutation, opaque address use, an initializing store after the query site, or unsupported aliases return unknown. Type/dispatch clients can retain a receiver condition through that binding; unknown never removes the corresponding possible effect. MatchesFunctionValue supplies exact function/closure target identity through aliases, immutable cells and unanimous phi arms. Opaque or mixed values stay unknown. Clients can retain function-target conditions independently of type conditions; conservative VTA alternatives must not all become unconditional effects of every caller. This fact grants no receiver or lifetime proof.
ProveCallbackFrame(MakeClosure) adds a narrow lifetime witness for a callback protected by a private local mutex, permanent closed flag and once claim, with a joining seal deferred before handoff. CallbackFrameProof.Covers checks each actual work instruction. A retained function value is not thereby nonescaping: an effect outside the guard, goroutine or later deferred work is not covered. Clients must check every domain effect, including summaries discovered later in their fixed point. Missing seals/guards, early unlocks, reopened flags and unsupported aliases/bodies yield no proof. This is independent of publication names and client policy; it grants neither acquisition nor behavioral credit.
An all-source, rootless client may set SourceOnly=true with every selector's Reachability="all". It uses the same typed loader and source traversal without building SSA/CHA/VTA. IncludeSyntax still supplies types.Info and the actual loaded GoSyntax.Package, including empty compiled package scopes. Direct calls and source-assignment aliases remain visible. Indirect and interface targets not resolved by this mode have UnresolvedTargets=true and remain conservative call candidates despite callee-name/package filters. They cannot prove delegation or an observation target. Full extraction remains available for VTA target refinement. SourceOnly refuses Roots and IncludeProgram; it makes no reachability/context-access claim. Syntax-only inactive files retain their explicit boundary and have no fabricated types or package scopes.
Named owner identities survive comment/line movement. Repeatable blank, init and anonymous closure owners use physical byte positions, so removing another owner cannot reassign a retained entity's ID. Source controls preserve other coordinates; an ordinary source edit that moves such an owner requires fresh positional rows. Diagnostic //line directives never replace physical offsets. External generated compilation units use deterministic per-package unit order rather than cache paths; changing that provider order invalidates review. GoSyntax.Source/FileSet retain the actual physical source view. Each local var/const/type declaration has its own declaration kind rather than inheriting its containing function's kind, in both typed and syntax-only traversal. Binding references use unique named parameter/receiver/result roles and physical local declarations. Removing another local cannot reassign a scope binding. Anonymous syntax-peer owners are also positional; lexical peers have occurrence IDs without invented syntax or scope proof. Every client must re-extract frozen occurrences, bindings and positional owner data on migration.
Approximation boundaries ¶
Program.Functions unions compiler instances/wrappers with every function and method defined in the loaded types.Info, including unreferenced generic and private receiver declarations and their closures. Selecting a declaration as a root does not make it reachable from any other root. VTA derives its initial CHA population from that same union, rather than a linker-style subset.
Inventory records Roots, Sources, Definitions, InvisibleBodies and Limitations. Generated and inactive files are explicit; inactive semantic filters cannot resolve types. Reflection, plugins and dependency bodies not loaded into SSA require semantic review. Source generic signatures remain uninstantiated, although reachability unions their visible instances; synthetic wrappers without source are reported separately. Broad declaration selectors cover polymorphic producers that an exact instantiated-type selector cannot decide.
An all-source syntax census is not a universal call graph, an invisible-body proof, a cancellation dominance proof or evidence of scope/header semantics. Each client retains its own product-level behavioral controls and reviewed dispositions. Source membership and fingerprints establish review coverage. NilSuccessEdge supplies the shared structural nil-branch fact to SSA effect clients. Clients retain admission, dominance and lifetime interpretation.
Index ¶
- func CapturedStores(cell ssa.Value) []*ssa.Store
- func ContextInScope(fn *ssa.Function, contexts []ContextType, fields []string) string
- func DynamicCallTargets(graph *callgraph.Graph) map[ssa.CallInstruction][]*ssa.Function
- func FreeVarClosure(free *ssa.FreeVar) (*ssa.MakeClosure, int)
- func ImmutableCellValueAt(value ssa.Value, at ssa.Instruction) (ssa.Value, bool)
- func InlineFieldName(t types.Type, path []int) string
- func InlineFieldPaths(t types.Type, leaf func(types.Type) bool) [][]int
- func LocalCell(cell *ssa.Alloc) bool
- func MatchesFunctionValue(value ssa.Value, target *ssa.Function) (matches, known bool)
- func NilAt(v ssa.Value, block *ssa.BasicBlock) bool
- func NilComparison(cond ssa.Value) (ssa.Value, int, bool)
- func NilSuccessEdge(e ssa.Value) (*ssa.If, *ssa.BasicBlock)
- func NonNilAt(v ssa.Value, block *ssa.BasicBlock) bool
- func OutermostFunction(fn *ssa.Function) *ssa.Function
- func ParameterNilAt(param *ssa.Parameter, block *ssa.BasicBlock) bool
- func StableGuardValue(value ssa.Value) bool
- func StaticCall(caller, callee *ssa.Function) bool
- func SuccessfulCallEdge(call *ssa.Call, errIndex int) (*ssa.If, *ssa.BasicBlock)
- func SuppliedContexts(site ssa.CallInstruction, isContext func(types.Type) bool) []ssa.Value
- func Validate(actual, approved Inventory, policy Policy) []string
- type Assignment
- type CallPath
- type CallWitness
- type CallbackFrameProof
- type Config
- type ContainingOwnerWitness
- type ContextType
- type Definition
- type Document
- type FieldProjection
- type GoSyntax
- type Inventory
- type InvisibleBody
- type LayerMember
- type Member
- type NonNilResultContract
- type OwnerLayer
- type Policy
- type Program
- func (p *Program) CallTargets(site ssa.CallInstruction) []*ssa.Function
- func (p *Program) DirectReachableFrom(roots []Root) (Reachability, error)
- func (p *Program) ExternalDeferred() map[string]string
- func (p *Program) GuardedInlineFieldUses(value ssa.Value, path []int, projection FieldProjection) bool
- func (p *Program) IncludeSyntheticFunctions(seeds []*ssa.Function) []*ssa.Function
- func (p *Program) LoadedSource(path string) ([]byte, error)
- func (p *Program) MayBeNil(value ssa.Value, at ssa.Instruction) []string
- func (p *Program) MayBeNilWhy(value ssa.Value, at ssa.Instruction) (witness, why []string)
- func (p *Program) ModuleConfig() ([]byte, error)
- func (p *Program) ProjectFieldAt(value ssa.Value, path []int, at ssa.Instruction) FieldProjection
- func (p *Program) ReachableFrom(roots []Root) (Reachability, error)
- func (p *Program) SetNonNilResultContracts(contracts []NonNilResultContract) error
- func (p *Program) SourceCallPaths(fn *ssa.Function) []CallPath
- func (p *Program) SourceCallSites(fn *ssa.Function) []ssa.CallInstruction
- func (p *Program) SourceReferences(fn *ssa.Function) []ssa.Instruction
- func (p *Program) WalkCallerEdges(roots []*ssa.Function, ...)
- func (p *Program) WalkCallers(roots []*ssa.Function, ...)
- type Reachability
- type Root
- type ScopeWitness
- type Selector
- type SourceBoundary
- type SourceControl
- type SourceRoot
- type ValueDefinition
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CapturedStores ¶
CapturedStores is capturedStores for the census policy packages.
func ContextInScope ¶
func ContextInScope(fn *ssa.Function, contexts []ContextType, fields []string) string
ContextInScope is the context a source function can name: a named context parameter of fn or of a function enclosing it, or a configured receiver field. Extract records the same reading as a member's diagnostic Scope; clients that ask whether a request context exists use this owner. Empty means none.
func DynamicCallTargets ¶
DynamicCallTargets indexes a call graph's dynamic edges by their call sites. It is the one owner of which functions a dynamic site may call: every client builds its per-site view from it once, instead of scanning the graph per call.
func FreeVarClosure ¶
func FreeVarClosure(free *ssa.FreeVar) (*ssa.MakeClosure, int)
freeVarClosure returns the enclosing function's MakeClosure that binds a closure's free variable, with the binding's index, or nil: the one closure-binding resolution (freeVarBinding and DerivedOnlyFrom use it). FreeVarClosure is freeVarClosure for the census policy packages.
func ImmutableCellValueAt ¶
ImmutableCellValueAt returns the one value stored in a local cell before at, provided no other write or opaque address use can change it and that store cannot run again on the same cell after at. Read-only captures are allowed; a mutated, aliased or externally passed cell is unknown, and so is a store a later iteration of one loop reaches on the cell it stored. It is a def/use fact, not a lifetime or acquisition witness.
func InlineFieldName ¶
InlineFieldName describes a previously enumerated inline index path.
func InlineFieldPaths ¶
InlineFieldPaths enumerates context-independent inline leaves matching leaf. Pointer/container contents are deliberately not followed.
func LocalCell ¶
LocalCell is localCell for the census policy packages: every use of the cell is a load, a store of its whole value, or a capture whose uses are the same, so the value a load reads is one of the values its whole-cell stores put there, or its zero value. A field address is refused: a store through one changes part of a value those packages read whole, which is a different question from whether a reference derived from the object leaves its function. The stores a capturing closure makes are named by CapturedStores.
func MatchesFunctionValue ¶
MatchesFunctionValue checks the identity of a compiled function value against one conservative call target. It follows exact values, aliases, immutable local cells and unanimous phi arms. Unknown/escaping values return unknown; this never establishes a receiver instance, lifetime or acquisition.
func NilAt ¶
func NilAt(v ssa.Value, block *ssa.BasicBlock) bool
NilAt reports that block runs only after a nil test of the SSA value v took its nil branch: some If dominating block compares v with nil, and its nil successor is entered only from that test and dominates block. Code there has no value in v (for a context: no request on this path). Author: storage-format-owners lane (Claude), #1693, 30 October 2026.
func NilComparison ¶
NilComparison is the engine's one parser of a nil comparison: when cond is "x == nil", "nil == x", "x != nil" or "nil != x", it returns x and the index (0 or 1) of the If block's successor taken when x is nil. Author: storage-format-owners lane (Claude), #1693, 30 October 2026.
func NilSuccessEdge ¶
NilSuccessEdge returns the If comparing e with nil and its nil successor. This is a structural SSA fact, not proof of admission, dominance or lifetime. The input must be a valid SSA value with a referrer list.
func NonNilAt ¶
func NonNilAt(v ssa.Value, block *ssa.BasicBlock) bool
NonNilAt reports that block runs only after a nil test of the SSA value v took its non-nil branch: some If dominating block compares v with nil, and its non-nil successor is entered only from that test and dominates block. An SSA value cannot change after its test, so the fact holds for v throughout block. Author: storage-format-owners lane (Claude), #1693, 30 October 2026.
func OutermostFunction ¶
OutermostFunction is the source function that lexically encloses fn: fn itself, or the declaration containing a function literal. Author: storage-format-owners lane (Claude), #1693, 30 October 2026.
func ParameterNilAt ¶
func ParameterNilAt(param *ssa.Parameter, block *ssa.BasicBlock) bool
ParameterNilAt reports that block runs only where param is known nil: param itself is tested nil there (NilAt), or, for a parameter a closure captures (SSA spills it to a cell), a load of that cell whose only reaching definition is the parameter's store is.
func StableGuardValue ¶
StableGuardValue reports whether an SSA value has one definition throughout this function frame. Parameters stay fixed; definitions in cyclic blocks may denote different values on successive iterations and remain unproven. Repeated-guard proofs must also require the exact same SSA value.
func StaticCall ¶
StaticCall reports that caller calls callee directly (a static callee), not only through an interface or a function value.
func SuccessfulCallEdge ¶
SuccessfulCallEdge is the branch taken when the call's result errIndex is nil: the If of "err != nil" (or "== nil") and its successor without an error.
func SuppliedContexts ¶
SuppliedContexts lists the context values a call passes, in Is order: its context arguments, and what is stored into context fields of a struct it passes by value from a local variable.
Types ¶
type Assignment ¶
type Assignment struct {
ID string `json:"id"`
MemberID string `json:"member_id"`
Digest string `json:"digest"`
Class string `json:"class"`
Owner string `json:"owner"`
Reference string `json:"reference"`
}
Assignment routes an exact unresolved member to an operator-named owner. It is distinct from callee delegation and gives no behavioral fix credit.
type CallPath ¶
type CallPath struct {
Site ssa.CallInstruction
Via []*ssa.Function
}
CallPath is one way a real source call reaches a function: the call, and the source-less wrappers between it and the function, nearest the call first.
type CallWitness ¶
type CallWitness struct {
MemberID string `json:"member_id"`
SiteID string `json:"site_id"`
Digest string `json:"digest"`
Callee string `json:"callee"`
RemovalControl string `json:"removal_control"`
}
CallWitness pins an observation call selected by client data inside the exact delegated callee. It proves source presence, not execution on every path.
type CallbackFrameProof ¶
type CallbackFrameProof struct {
Frame *ssa.Function
Callback *ssa.MakeClosure
Mutex ssa.Value
Closed ssa.Value
Called ssa.Value
Seal ssa.Instruction
// contains filtered or unexported fields
}
CallbackFrameProof is a source proof for work inside a retained callback. The function value may escape. Only instructions covered by Covers are proved to finish before Frame returns: one local mutex serializes entry and joins it at sealing, a closed flag rejects later entry, and a second flag prevents a repeated invocation. This is not proof that an arbitrary callback is synchronous or that every effect of its body is protected. Clients must check each effect.
func ProveCallbackFrame ¶
func ProveCallbackFrame(mc *ssa.MakeClosure) (*CallbackFrameProof, bool)
ProveCallbackFrame recognizes a deliberately narrow, name-independent SSA lifetime protocol. The callback and seal use the same local sync.Mutex; a seal is deferred before the callback can be handed off; that seal joins the mutex and permanently closes it on every normal exit. All relevant cells must remain private to this frame and the two closures. Unsupported aliases, invisible helper bodies and missing proof return false, never a non-escaping assumption.
func (*CallbackFrameProof) Covers ¶
func (p *CallbackFrameProof) Covers(ins ssa.Instruction) bool
Covers reports whether an ordinary instruction is inside the proved critical section, below both rejection tests and the once claim. Starting asynchronous work or registering another deferred callback does not inherit that lifetime.
type Config ¶
type Config struct {
SourceOnly bool `json:"source_only,omitempty"`
IncludeProgram bool `json:"include_program,omitempty"`
IncludeSyntax bool `json:"include_syntax,omitempty"`
SourceRoots []SourceRoot `json:"source_roots,omitempty"`
Documents []Document `json:"documents,omitempty"`
Tests bool `json:"tests,omitempty"`
Env []string `json:"env,omitempty"`
LoadMode packages.LoadMode `json:"load_mode,omitempty"`
IncludeInactive bool `json:"include_inactive,omitempty"`
ExcludeGenerated bool `json:"exclude_generated,omitempty"`
Dir string `json:"dir,omitempty"`
Patterns []string `json:"patterns,omitempty"`
BuildFlags []string `json:"build_flags,omitempty"`
Packages []string `json:"packages,omitempty"`
Roots []Root `json:"roots,omitempty"`
Selectors []Selector `json:"selectors,omitempty"`
ContextTypes []ContextType `json:"context_types,omitempty"`
ContextFields []string `json:"context_fields,omitempty"`
Overlay map[string][]byte `json:"overlay,omitempty"`
}
Config describes a composed source tree. Clients supply roots, package scope, selectors and optional diagnostic context types as data, never extractors.
type ContainingOwnerWitness ¶
type ContainingOwnerWitness struct {
OwnerID string `json:"owner_id"`
OwnerDigest string `json:"owner_digest"`
Observation CallWitness `json:"observation"`
Scope ScopeWitness `json:"scope"`
}
ContainingOwnerWitness classifies work INSIDE an actual observing function. It never delegates enclosing enumeration to a nested call target. The named layer must contain this source owner, and the selected observation must be in this very body, with the required scope and a source-removal control.
type ContextType ¶
ContextType describes diagnostic context access, e.g. a standard Context parameter (empty Accessor), or a client's wrapper with ".Context()".
type Definition ¶
type Definition struct {
ID string `json:"id,omitempty"`
ParentID string `json:"parent_id,omitempty"`
Kind string `json:"kind,omitempty"`
Values []ValueDefinition `json:"values,omitempty"`
Writes []string `json:"writes,omitempty"`
Escapes []string `json:"escapes,omitempty"`
Symbol string `json:"symbol"`
Package string `json:"package"`
File string `json:"file"`
Digest string `json:"digest"`
}
Definition is an engine fact, independent of selectors and dispositions.
type Document ¶
type Document struct {
Path string `json:"path"`
Language string `json:"language"`
Mode string `json:"mode,omitempty"` // syntax (default) or explicit lexical approximation
}
Document declares an additional maintained language source. JavaScript, TypeScript and TSX use the shared all-source AST census; their Go type/SSA reachability is explicitly unavailable. Paths are relative to Config.Dir.
type FieldProjection ¶
type FieldProjection struct {
Values []ssa.Value
Witness, Why []string
Unknown bool
Field *types.Var // final inline field; conservative provenance on unknown writes
}
FieldProjection is the context-independent projection of an inline value field at a use. Values retain their real SSA provenance (no fabricated loads). Witness records zero/unknown or possibly nil inputs; Why records non-nil proof.
type GoSyntax ¶
type GoSyntax struct {
// Package is the actual loaded type scope, even when a compiled file has
// no owned objects. It is nil for source outside the typed composition.
Package *types.Package
Node ast.Node
Owner ast.Node
Ancestors []ast.Node
Info *types.Info
FileSet *token.FileSet
Source []byte
}
GoSyntax is a read-only, process-local view of a selected member. Clients may interpret its domain semantics without loading, parsing or walking source again. Info is nil for inactive or syntax-only documents. Object identity in Info.Defs/Uses joins def/use members; it is not a persisted source identity.
type Inventory ¶
type Inventory struct {
Program *Program `json:"-"`
Definitions []Definition `json:"definitions,omitempty"`
Sources []SourceBoundary `json:"sources,omitempty"`
InvisibleBodies []InvisibleBody `json:"invisible_bodies,omitempty"`
Limitations []string `json:"limitations,omitempty"`
Roots []string `json:"roots"`
Members []Member `json:"members"`
}
Inventory records the exact root and member populations for one composition.
func Extract ¶
Extract enumerates source using only Config data. SSA reachability and source declaration traversal are independent: all-source selectors include unused methods, aliases, global initializers and literals without familiar names. No classification manifest participates in discovery.
func ExtractWithControl ¶
func ExtractWithControl(c Config, control SourceControl) (Inventory, error)
ExtractWithControl performs source mutation, never inventory mutation. The returned candidate must go through the client's ordinary Validate call; a removal control requires a delegation-observation failure for its calling row.
type InvisibleBody ¶
type InvisibleBody struct{ Package, Name, Symbol, Signature, Synthetic string }
InvisibleBody reports a reached dependency or synthetic function whose body was unavailable to source selection. This is a declared approximation boundary.
type LayerMember ¶
type LayerMember struct {
OwnerID string `json:"owner_id,omitempty"`
Observations []CallWitness `json:"observations,omitempty"`
Symbol string `json:"symbol"`
Digest string `json:"digest"`
}
LayerMember pins a callee body present in the extracted source composition.
type Member ¶
type Member struct {
// SiteID pins this occurrence's byte position, independently of a kind's
// ordinal. Source controls preserve coordinates of unaffected occurrences.
SiteID string `json:"site_id,omitempty"`
UnresolvedTargets bool `json:"unresolved_targets,omitempty"`
OwnerID string `json:"owner_id,omitempty"`
ContainingOwner *ContainingOwnerWitness `json:"containing_owner,omitempty"`
ArgReferences []string `json:"arg_references,omitempty"`
ArgTypes []string `json:"arg_types,omitempty"`
ReceiverReference string `json:"receiver_reference,omitempty"`
ValueReference string `json:"value_reference,omitempty"`
File string `json:"file,omitempty"`
OwnerSymbol string `json:"owner_symbol,omitempty"`
Syntax *GoSyntax `json:"-"`
Facts map[string][]string `json:"facts,omitempty"`
Assignment string `json:"assignment,omitempty"`
OperandType string `json:"operand_type,omitempty"`
AssertionType string `json:"assertion_type,omitempty"`
CommaOK bool `json:"comma_ok,omitempty"`
EndLine int `json:"end_line,omitempty"`
EndColumn int `json:"end_column,omitempty"`
Node string `json:"node,omitempty"`
OwnerLayer string `json:"owner_layer,omitempty"`
BoundKnown bool `json:"bound_known,omitempty"`
Language string `json:"language,omitempty"`
EndOffset int `json:"end_offset,omitempty"`
UTF16Offset int `json:"utf16_offset,omitempty"`
UTF16End int `json:"utf16_end,omitempty"`
Column int `json:"column,omitempty"`
OwnerDigest string `json:"owner_digest,omitempty"`
ReviewOwner string `json:"review_owner,omitempty"`
Subjects []string `json:"subjects,omitempty"`
Declaration string `json:"declaration,omitempty"`
State string `json:"state,omitempty"`
Typed bool `json:"typed,omitempty"`
Signature string `json:"signature,omitempty"`
UnderlyingType string `json:"underlying_type,omitempty"`
Callees []string `json:"callees,omitempty"`
References []string `json:"references,omitempty"`
Owner string `json:"owner"`
Kind string `json:"kind"`
Reachable bool `json:"reachable,omitempty"`
ID string `json:"id"`
Digest string `json:"digest"`
Class string `json:"class"`
Reason string `json:"reason"`
Line int `json:"line"`
Code string `json:"code"`
Scope string `json:"scope,omitempty"`
Bound int64 `json:"bound,omitempty"`
BoundReason string `json:"bound_reason,omitempty"`
Offset int `json:"offset,omitempty"`
CalleeEnd int `json:"callee_end,omitempty"`
Open int `json:"open,omitempty"`
FunctionBody int `json:"function_body,omitempty"`
SliceType string `json:"slice_type,omitempty"`
ElementType string `json:"element_type,omitempty"`
Receiver string `json:"receiver,omitempty"`
ReceiverType string `json:"receiver_type,omitempty"`
CallSignature string `json:"call_signature,omitempty"`
StringInput bool `json:"string_input,omitempty"`
FailureReturn string `json:"failure_return,omitempty"`
Args []string `json:"args,omitempty"`
Format string `json:"format,omitempty"`
ScalarArgs []bool `json:"scalar_args,omitempty"`
}
Member identifies one source work site independently of its reviewed class. Digest pins formatted source; offsets and inferred bounds aid human review.
type NonNilResultContract ¶
NonNilResultContract is a client's reviewed assertion about a normal return, not an inferred theorem. The client must validate its source and writer evidence before registration. It affects only nil-flow result traversal; provenance, field loads and request-substitution analysis remain unchanged.
type OwnerLayer ¶
type OwnerLayer struct {
Name string `json:"name"`
Members []LayerMember `json:"members"`
}
OwnerLayer is client ownership data checked against actual source definitions.
type Policy ¶
type Policy struct {
RequireDelegationWitnesses bool `json:"require_delegation_witnesses,omitempty"`
Controls []SourceControl `json:"controls,omitempty"`
RequireSubjectsFor []string `json:"require_subjects_for,omitempty"`
ClassFact string `json:"class_fact,omitempty"`
RequireSources bool `json:"require_sources,omitempty"`
FactKeys []string `json:"fact_keys,omitempty"`
ForbiddenClasses []string `json:"forbidden_classes,omitempty"`
Assignments []Assignment `json:"assignments,omitempty"`
ClassKinds map[string]string `json:"class_kinds,omitempty"`
Layers []OwnerLayer `json:"layers,omitempty"`
Classes []string `json:"classes,omitempty"`
BoundedClasses []string `json:"bounded_classes,omitempty"`
RequireReviewOwner bool `json:"require_review_owner,omitempty"`
RequireSubjects bool `json:"require_subjects,omitempty"`
RequireOwnerDigest bool `json:"require_owner_digest,omitempty"`
Owners []string `json:"owners,omitempty"`
Subjects []string `json:"subjects,omitempty"`
}
Policy supplies reviewed classes and optional evidence-reference obligations. ReviewOwner and Subjects are client data, not claims of semantic execution. Custom classes require ClassKinds. Layers pin actual source callee bodies. BoundedClasses adds classes with bounded semantics; it cannot disable checks.
type Program ¶
type Program struct {
Root string
FileSet *token.FileSet
Packages []*packages.Package
SSA *ssa.Program
Functions []*ssa.Function
CallGraph *callgraph.Graph
// contains filtered or unexported fields
}
Program is the engine's read-only, process-local analysis view. Domain clients may analyze effects, method sets or def/use over these loaded objects without another loader, SSA builder, call graph or generic source traversal. Functions includes generic instances; clients retain domain-specific instance policies.
func LoadProgram ¶
LoadProgram owns generic package loading, SSA construction and VTA/CHA. It performs no domain classification. SSA-effect clients can use this view without requesting an additional syntax inventory; Extract uses this loader.
func (*Program) CallTargets ¶
func (p *Program) CallTargets(site ssa.CallInstruction) []*ssa.Function
CallTargets returns the conservative targets of the actual SSA call site, including compiler wrappers and VTA-resolved interface/function values. An empty result is unknown, not evidence that the call has no effects.
func (*Program) DirectReachableFrom ¶
func (p *Program) DirectReachableFrom(roots []Root) (Reachability, error)
DirectReachableFrom is the work roots perform themselves: static calls and function literals only, not the callbacks or interface values they may run. It shares ReachableFrom's walk; only the successor relation differs. Author: storage-format-owners lane (Claude), #1693, 30 October 2026.
func (*Program) ExternalDeferred ¶
ExternalDeferred lists each deferred callee judged from a separate source load of its package, with its verdict.
func (*Program) GuardedInlineFieldUses ¶
func (p *Program) GuardedInlineFieldUses(value ssa.Value, path []int, projection FieldProjection) bool
GuardedInlineFieldUses proves that a private inline field is read only in a sibling's non-nil arm, and that every semantic use takes the field's own non-nil edge. It examines the complete loaded field-use population, including retained copies, rather than treating an omitted field as a valid context. Unknown projections, representations and outward escapes confer no proof.
func (*Program) IncludeSyntheticFunctions ¶
IncludeSyntheticFunctions retains seeds and the compiler-created bodies they reference or call, transitively. A wrapper's object may belong to an external package even though its executable body was generated for a selected caller. This does not load external source bodies or change a client's root policy.
func (*Program) LoadedSource ¶
LoadedSource returns an owned copy of the exact bytes passed to the parser for a loaded file, including overlay and on-demand dependency source. It never substitutes current disk bytes for a compiled body.
func (*Program) MayBeNil ¶
MayBeNil reports whether value may be nil where at uses it, with a witness path (nil when it cannot). It follows SSA def/use within functions, parameters to their visible call sites, closure free variables to their bindings, phi arms, the returns of static callees, local cells, and struct fields to every store and to every allocation that leaves the field zero. A value used only after the non-nil edge of its own nil test is non-nil there. Results of external or context-package code, and of calls with no visible target, are non-nil (Go's non-nil interface convention); a nil visible behind a static, interface or function-value call is never assumed away, except on an error return when the use is reached only after that error tested nil, a lazily initialized field or cell, and a Recover block no deferred call can enter.
func (*Program) MayBeNilWhy ¶
MayBeNilWhy is MayBeNil with the reasons for a non-nil verdict: every proof rule (a nil test, a checked error, a non-nilable type, a cycle) and every model convention (an external or unresolved result, a parameter with no visible caller, an unmodelled value) that removed a path to nil. A non-nil verdict with no reason is one the model reached without deciding anything. Author: storage-format-owners lane (Claude), #1693, 30 October 2026.
func (*Program) ModuleConfig ¶
ModuleConfig returns the separately captured root go.mod metadata from loading. Module metadata is not a Go parser input. A missing module remains an error, rather than an empty successful attestation.
func (*Program) ProjectFieldAt ¶
func (p *Program) ProjectFieldAt(value ssa.Value, path []int, at ssa.Instruction) FieldProjection
ProjectFieldAt follows an exact inline struct index path in a value snapshot. Unknown calls, aliases and unsupported representations remain possible nil; this does not interpret pointer heaps or infer an external factory contract.
func (*Program) ReachableFrom ¶
func (p *Program) ReachableFrom(roots []Root) (Reachability, error)
ReachableFrom queries the already loaded program without loading or walking source again. Required roots must resolve. Empty Roots means no functions, rather than silently treating the whole program as statement reachable.
func (*Program) SetNonNilResultContracts ¶
func (p *Program) SetNonNilResultContracts(contracts []NonNilResultContract) error
SetNonNilResultContracts atomically replaces the reviewed result boundaries for this exact Program. Invalid identities or result indices leave the existing set untouched. Registration resets nil-flow memoized verdicts.
func (*Program) SourceCallPaths ¶
SourceCallPaths lists every path SourceCallSites follows, each with its wrappers, in stable order. A wrapper repeated on one path ends that path.
func (*Program) SourceCallSites ¶
func (p *Program) SourceCallSites(fn *ssa.Function) []ssa.CallInstruction
SourceCallSites follows incoming call-graph edges through source-less wrappers, stopping at the nearest real source invocation on each path. All alternatives are retained: attribution is not a proof of execution, acquisition, callback lifetime or association with one receiver instance. No result means there is no visible invocation, not that a value cannot run. A source-origin query unions its visible generic instances. Querying one concrete instance retains that instance's attribution instead.
func (*Program) SourceReferences ¶
func (p *Program) SourceReferences(fn *ssa.Function) []ssa.Instruction
SourceReferences retains the nearest real source instructions that refer to a function value through compiler wrappers. These are conservative carriers, not invocation witnesses. In particular a stored value remains an unresolved future effect even when no visible call-graph edge invokes it. Source origins include carriers of every visible generic instance; a query for a concrete instance remains specific to that instance.
func (*Program) WalkCallerEdges ¶
func (p *Program) WalkCallerEdges(roots []*ssa.Function, visit func(caller, callee *ssa.Function, paths []CallPath) (expand, stop bool))
WalkCallerEdges is WalkCallers with the call paths of each edge, so a decision about an edge can rest on that edge's own calls.
func (*Program) WalkCallers ¶
func (p *Program) WalkCallers(roots []*ssa.Function, visit func(caller, callee *ssa.Function) (expand, stop bool))
WalkCallers is the shared incoming walk, the reverse of ReachableFrom. From roots it follows SourceCallSites breadth-first; each site is attributed to its outermost enclosing source function. visit sees every distinct caller edge, because what a caller holds on its calls can differ by callee, and reports whether to walk past that caller and whether to stop. Only the expansion is deduplicated: a caller is expanded once, when any of its edges asks for it. A root is not visited as a caller. Visibility is the call graph's, never a runtime proof. Author: storage-format-owners lane (Claude), #1693, 30 October 2026.
type Reachability ¶
type Reachability struct {
Roots []string
Functions map[*ssa.Function]bool
// contains filtered or unexported fields
}
Reachability is the shared engine's conservative call/closure population for selected roots in a loaded Program. Functions is a read-only process-local set, including generic instances and closures through opaque callbacks.
func (Reachability) Contains ¶
func (r Reachability) Contains(root Root) bool
Contains reports whether a matching source function is in this population. This is source reachability, not proof that a call dominates every path.
func (Reachability) PathTo ¶
func (r Reachability) PathTo(root Root) []string
PathTo returns a deterministic shortest conservative function/closure path from one selected root to a matching target, or nil when none is visible. It uses the same population as Contains, including compiler wrappers and lexical callbacks through opaque code. It proves possible reachability, never runtime invocation, receiver-instance identity or path dominance.
type Root ¶
type Root struct {
Package string `json:"package,omitempty"`
Name string `json:"name,omitempty"`
Receiver string `json:"receiver,omitempty"`
Required bool `json:"required,omitempty"`
}
Root identifies a source entrypoint. Receiver optionally restricts a method by its declared named receiver (without pointer or generic arguments). Required roots fail extraction when no matching function is visible.
type ScopeWitness ¶
type ScopeWitness struct {
OwnerID string `json:"owner_id,omitempty"`
Value string `json:"value"`
Fields []string `json:"fields,omitempty"`
Type string `json:"type"`
Argument int `json:"argument,omitempty"`
Receiver bool `json:"receiver,omitempty"`
}
ScopeWitness requires an observation to use one exact typed value of its containing owner (or lexical ancestor). Fields is a direct field path from that binding. Receiver chooses the observation's receiver instead of Argument. This proves binding identity, not alias provenance or control-flow dominance.
type Selector ¶
type Selector struct {
Pattern string `json:"pattern,omitempty"`
Languages []string `json:"languages,omitempty"`
Kind string `json:"kind,omitempty"`
Node string `json:"node,omitempty"`
Group string `json:"group,omitempty"`
Reachability string `json:"reachability,omitempty"`
Packages []string `json:"packages,omitempty"`
PackagePrefixes []string `json:"package_prefixes,omitempty"`
Names []string `json:"names,omitempty"`
NamePrefixes []string `json:"name_prefixes,omitempty"`
NameContains []string `json:"name_contains,omitempty"`
Files []string `json:"files,omitempty"`
OwnerContains []string `json:"owner_contains,omitempty"`
States []string `json:"states,omitempty"`
ResultTypes []string `json:"result_types,omitempty"`
ReceiverTypes []string `json:"receiver_types,omitempty"`
OperandTypes []string `json:"operand_types,omitempty"`
TypeShapes []string `json:"type_shapes,omitempty"`
TypeContains []string `json:"type_contains,omitempty"`
Operators []string `json:"operators,omitempty"`
Builtin bool `json:"builtin,omitempty"`
UnwrapResults bool `json:"unwrap_results,omitempty"`
FoldCase bool `json:"fold_case,omitempty"`
KindFromSymbol bool `json:"kind_from_symbol,omitempty"`
}
Selector is a declarative union of names/prefixes/contains, intersected with the other supplied filters. Empty filters accept any value. Node names are declaration, function, method, closure, type, alias, var, const, import, file, external, for, range, call, identifier, index, slice, map, field, binary, switch, type-switch, type-assert, go, assign, return, composite, func-type and lexical text (with Pattern). Reachability is reachable (the default) or all. The first matching rule in each Group wins per possible call target; possible alias targets union their kinds once per source node. An empty Group defaults to Kind, allowing independent selector populations. Package filters describe callees for calls and source packages otherwise.
type SourceBoundary ¶
type SourceBoundary struct{ File, Package, State, Digest string }
SourceBoundary reports compiled, generated and inactive build files. Inactive syntax is selectable with IncludeInactive; its type information is unavailable.
type SourceControl ¶
type SourceControl struct {
ID string `json:"id"`
MemberID string `json:"member_id"`
Replacement string `json:"replacement"`
}
SourceControl replaces one engine-owned call span before running the SAME Extract path again. Clients supply a type-correct neutral replacement, such as error(nil). A compile failure is an invalid control, not a successful rejection.
type SourceRoot ¶
type SourceRoot struct {
Path string `json:"path"`
Languages map[string]string `json:"languages"`
Mode string `json:"mode,omitempty"`
ExcludeDirs []string `json:"exclude_dirs,omitempty"`
ExcludeFiles []string `json:"exclude_files,omitempty"`
}
SourceRoot discovers maintained documents independently of package loading, reachability or old members. Extension keys include the dot. Exclusions are client data: directory names and basename globs. Skipped paths are reported.
type ValueDefinition ¶
type ValueDefinition struct {
Reference string `json:"reference"`
Name string `json:"name"`
Type string `json:"type"`
Role string `json:"role"`
}
ValueDefinition is an engine-owned binding in one source owner. Its identity uses named parameter/receiver/result roles and physical local declarations. Unrelated binding removals cannot reassign the retained scope identity.
Source Files
¶
- aliases.go
- analysis.go
- callback_frame.go
- cell_value.go
- census.go
- consistency.go
- containing_owner.go
- context_fallback.go
- doc.go
- documents.go
- documents_cgo.go
- error_preservation.go
- evidence.go
- extract.go
- field_projection.go
- function_value.go
- guarded_inline_field.go
- identity.go
- nil_capability.go
- nil_flow.go
- nil_result_contract.go
- owner_values.go
- program.go
- reachability.go
- select_receive.go
- selectors.go
- success_edge.go
- synthetic.go
- witness.go