agentcontext

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package agentcontext preserves source-asserted agent records separately from kernel observations and analysis. Missing source information remains unknown.

Index

Constants

View Source
const (
	MaxDiscoveryFiles  = 4096
	MaxDiscoveryVisits = 20000
	MaxDiscoveryBytes  = 256 << 20
)
View Source
const (
	CurrentExecution = "current_execution"
	PriorContext     = "prior_context"
)
View Source
const (
	ParserVersion = "context-parser/v10"
	MaxInputBytes = 128 << 20
	MaxLineBytes  = 40 << 20
	MaxRecords    = 25000
)
View Source
const CapturePolicyVersion = "agentprovenance.context_capture/v1"
View Source
const SchemaVersion = "agentprovenance.agent_context/v1"

Variables

View Source
var ErrHookCaptureLimit = errors.New("normalized hook exceeds capture limit")
View Source
var ErrInvalidArgument = errors.New("invalid context argument")
View Source
var ErrSessionEnumerationLimit = errors.New("session enumeration resource limit exceeded")

Functions

func HookCaptureDiagnostic added in v0.10.0

func HookCaptureDiagnostic(code string) []byte

HookCaptureDiagnostic contains only a fixed code; source input is never logged on malformed or oversized hooks. Parse records it as a collection failure.

func Number

func Number(n int64) *int64

func RetainHookEvent added in v0.10.0

func RetainHookEvent(data []byte, policy CapturePolicy) ([]byte, error)

RetainHookEvent applies the run's policy before the hook sidecar is written. Filtered rows carry omission metadata, never a reference to discarded bytes.

func ToolNodeID

func ToolNodeID(e Entry) string

ToolNodeID namespaces a native call identity by run and actor. Transcript and hook channels can describe the same invocation, while separate runs cannot overwrite each other's graph nodes when a harness reuses a call ID.

Types

type Candidate

type Candidate struct {
	Path            string       `json:"path"`
	SessionID       string       `json:"session_id"`
	ParentSessionID string       `json:"parent_session_id,omitempty"`
	AgentID         string       `json:"agent_id,omitempty"`
	Workdir         string       `json:"workdir,omitempty"`
	CreatedAt       string       `json:"created_at,omitempty"`
	ModifiedAt      time.Time    `json:"modified_at"`
	Size            int64        `json:"size"`
	Cursor          SourceCursor `json:"cursor"`
	Issue           string       `json:"issue,omitempty"`
}

type CaptureOmission added in v0.10.0

type CaptureOmission struct {
	Category string `json:"category"`
	Reason   string `json:"reason"`
	Records  int64  `json:"records"`
}

type CapturePolicy added in v0.10.0

type CapturePolicy struct {
	Version       string          `json:"version"`
	Preset        string          `json:"preset"`
	ToolResults   bool            `json:"tool_results"`
	SourceRecords bool            `json:"source_records"`
	History       bool            `json:"history"`
	Configuration bool            `json:"configuration"`
	Overrides     map[string]bool `json:"overrides,omitempty"`
}

CapturePolicy governs additional context retention, independently of sensor, TLS and workspace snapshots. Once recorded, a run's policy is immutable.

func NewCapturePolicy added in v0.10.0

func NewCapturePolicy(preset string, toolResults *bool) (CapturePolicy, error)

type ContentRef

type ContentRef struct {
	Ref         string `json:"ref,omitempty"`
	Bytes       *int64 `json:"bytes"`
	SHA256      string `json:"sha256,omitempty"`
	MediaType   string `json:"media_type,omitempty"`
	Redacted    bool   `json:"redacted"`
	State       string `json:"state"`
	Reason      string `json:"reason,omitempty"`
	DigestScope string `json:"digest_scope,omitempty"`
}

type Counts

type Counts struct {
	Discovered   *int64 `json:"discovered"`
	Matched      *int64 `json:"matched"`
	Read         *int64 `json:"read"`
	Parsed       *int64 `json:"parsed"`
	Stored       *int64 `json:"stored"`
	Duplicates   *int64 `json:"duplicates"`
	Truncated    *int64 `json:"truncated"`
	Failed       *int64 `json:"failed"`
	Unrecognized *int64 `json:"unrecognized"`
	Deferred     *int64 `json:"deferred"`
}

Counts are observations over one processing range, not estimates of all activity. Nil means unknown; a successful empty scan can explicitly report 0.

type Coverage

type Coverage struct {
	SchemaVersion string            `json:"schema_version"`
	ID            string            `json:"id"`
	RunID         string            `json:"run_id"`
	Source        Source            `json:"source"`
	Status        Status            `json:"status"`
	ObservedAt    string            `json:"observed_at"`
	LastSuccessAt string            `json:"last_success_at,omitempty"`
	StartedAt     string            `json:"started_at,omitempty"`
	EndedAt       string            `json:"ended_at,omitempty"`
	FirstLine     int64             `json:"first_line,omitempty"`
	LastLine      int64             `json:"last_line,omitempty"`
	Counts        Counts            `json:"counts"`
	Issues        []Issue           `json:"issues"`
	MissingFields []string          `json:"missing_fields"`
	ObjectHash    string            `json:"object_hash,omitempty"`
	PriorContext  *PriorRange       `json:"prior_context,omitempty"`
	CapturePolicy *CapturePolicy    `json:"capture_policy,omitempty"`
	Omissions     []CaptureOmission `json:"omissions,omitempty"`
}

type DiscoverOptions

type DiscoverOptions struct {
	Harness string
	Root    string
	// CatalogRoot optionally locates Codex state catalogs outside the scan root.
	// No ambient home directory is consulted for explicitly acquired sources.
	CatalogRoot string
	Workdir     string
	SessionID   string
	// Snapshot captures a pre-execution cursor for candidates in this workdir.
	Snapshot bool
}

type Entry

type Entry struct {
	SchemaVersion string `json:"schema_version"`
	ID            string `json:"id"`
	RunID         string `json:"run_id"`
	Source        Source `json:"source"`
	SourceKey     string `json:"source_key"`
	Sequence      int64  `json:"sequence"`
	// SourceOrdinal is the normalized record's position within its physical
	// source line. Zero means older evidence did not record that position.
	SourceOrdinal int64      `json:"source_ordinal,omitempty"`
	Kind          string     `json:"kind"`
	Role          string     `json:"role,omitempty"`
	AgentID       string     `json:"agent_id,omitempty"`
	ToolCallID    string     `json:"tool_call_id,omitempty"`
	ToolName      string     `json:"tool_name,omitempty"`
	Status        string     `json:"status,omitempty"`
	RecordedAt    string     `json:"recorded_at,omitempty"`
	Content       ContentRef `json:"content"`
	RawContent    ContentRef `json:"raw_content"`
	// IntentContent is a derived, bounded model-message projection when the
	// source record is deliberately not retained. It is never an original record.
	IntentContent   *ContentRef      `json:"intent_content,omitempty"`
	MissingFields   []string         `json:"missing_fields,omitempty"`
	EvidenceRefs    []string         `json:"evidence_refs,omitempty"`
	ObjectHash      string           `json:"object_hash,omitempty"`
	CreatedAt       string           `json:"created_at,omitempty"`
	ExecutionScope  string           `json:"execution_scope,omitempty"`
	SessionMetadata *SessionMetadata `json:"session_metadata,omitempty"`
}

func (Entry) ContentReferences added in v0.10.0

func (e Entry) ContentReferences() []ContentRef

ContentReferences includes the derived intent source, when present. Callers must apply the same reading and sharing boundaries to it as to the raw row.

type EntryLinks struct {
	SchemaVersion string      `json:"schema_version"`
	RunID         string      `json:"run_id"`
	EntryID       string      `json:"entry_id"`
	Basis         string      `json:"basis"`
	Links         []GraphLink `json:"links"`
	HasMore       bool        `json:"has_more"`
	Reason        string      `json:"reason,omitempty"`
}
type GraphLink struct {
	NodeID   string `json:"node_id"`
	Relation string `json:"relation"`
}

type Inventory

type Inventory struct {
	Harness     string      `json:"harness"`
	Root        string      `json:"root"`
	CatalogRoot string      `json:"catalog_root,omitempty"`
	Candidates  []Candidate `json:"candidates"`
	Complete    bool        `json:"complete"`
	Issues      []Issue     `json:"issues"`
}

Inventory contains identities and resume boundaries, never conversation text. An incomplete inventory cannot establish a unique automatic binding.

func Discover

func Discover(ctx context.Context, opts DiscoverOptions) (Inventory, error)

type Issue

type Issue struct {
	Code  string `json:"code"`
	Line  int64  `json:"line,omitempty"`
	Field string `json:"field,omitempty"`
	Scope string `json:"scope,omitempty"`
}

type Overview

type Overview struct {
	SchemaVersion   string                         `json:"schema_version"`
	RunID           string                         `json:"run_id"`
	Coverage        []Coverage                     `json:"coverage"`
	Messages        *int64                         `json:"messages"`
	ToolCalls       *int64                         `json:"tool_calls"`
	ToolResults     *int64                         `json:"tool_results"`
	Snapshots       *int64                         `json:"snapshots"`
	HasMoreSources  bool                           `json:"has_more_sources"`
	RuntimeCoverage observability.RuntimeCoverage  `json:"runtime_coverage"`
	CapturePolicy   *CapturePolicy                 `json:"capture_policy,omitempty"`
	CaptureSettings *observability.CaptureSettings `json:"capture_settings,omitempty"`
}

type Page

type Page struct {
	SchemaVersion string  `json:"schema_version"`
	RunID         string  `json:"run_id"`
	Entries       []Entry `json:"entries"`
	NextCursor    string  `json:"next_cursor,omitempty"`
	HasMore       bool    `json:"has_more"`
	Limit         int     `json:"limit"`
}

type PageOptions

type PageOptions struct {
	RunID            string
	Harness          string
	SessionID        string
	SourceID         string
	Kind             string
	ToolCallID       string
	EntryID          string
	NodeID           string
	Group            string
	Cursor           string
	Limit            int
	IncludeRevisions bool
}

type ParseBudget

type ParseBudget struct {
	InputBytes int64
	Records    int
}

ParseBudget bounds a sequence of source imports, including decompressed input and records that are later rejected or deduplicated. It is not concurrency-safe. A nil budget keeps the normal per-source limits; zero means exhausted.

type ParseOptions

type ParseOptions struct {
	Harness         string
	Path            string
	SessionID       string
	ParentSessionID string
	AgentID         string
	Binding         string
	BindingEvidence []string
	// AfterLine is a physical source cursor captured before a resumed execution.
	// Earlier records are retained as prior context, never current execution.
	AfterLine int64
	Cursor    *SourceCursor
	Budget    *ParseBudget
}

type Parsed

type Parsed struct {
	Source   Source
	Records  []Record
	Coverage Coverage
}

func Parse

func Parse(ctx context.Context, r io.Reader, opts ParseOptions) (Parsed, error)

Parse reads a bounded physical transcript without consulting current agent configuration. Diagnostics intentionally contain codes/positions, never input.

type PriorRange

type PriorRange struct {
	FirstLine     int64    `json:"first_line"`
	LastLine      int64    `json:"last_line"`
	StartedAt     string   `json:"started_at,omitempty"`
	EndedAt       string   `json:"ended_at,omitempty"`
	Counts        Counts   `json:"counts"`
	MissingFields []string `json:"missing_fields"`
}

PriorRange describes the retained prefix separately from the current range. These records supply historical context, not evidence of execution in this run.

type Record

type Record struct {
	Key            string
	Sequence       int64
	SourceOrdinal  int64
	Kind           string
	Role           string
	AgentID        string
	ToolCallID     string
	ToolName       string
	Status         string
	RecordedAt     string
	Body           *string
	RawBody        *string
	MediaType      string
	MissingReason  string
	MissingFields  []string
	ExecutionScope string
	// Parsed values are position-specific, including unknown values. Nil lets
	// explicit Record callers use the source defaults.
	Workdir            *string
	ApplicationVersion *string
	// contains filtered or unexported fields
}

Record is a parser's transient output. Body never appears in the entry index or diagnostics: it is redacted and stored as bounded content-addressed chunks.

type SaveResult

type SaveResult struct {
	Stored     int      `json:"stored"`
	Duplicates int      `json:"duplicates"`
	Coverage   Coverage `json:"coverage"`
}

type SelectOptions

type SelectOptions struct {
	Workdir   string
	SessionID string // explicit native identity, including resume
	Path      string // explicit transcript; no directory heuristic
	StartedAt time.Time
	EndedAt   time.Time
}

type SelectedSource

type SelectedSource struct {
	Candidate
	AfterLine       int64         `json:"after_line"`
	Binding         string        `json:"binding"`
	BindingEvidence []string      `json:"binding_evidence"`
	ResumeCursor    *SourceCursor `json:"resume_cursor,omitempty"`
}

func (SelectedSource) ParseOptions

func (s SelectedSource) ParseOptions(harness string) ParseOptions

type Selection

type Selection struct {
	Sources []SelectedSource `json:"sources"`
	Status  Status           `json:"status"`
	Issues  []Issue          `json:"issues"`
}

func SelectSources

func SelectSources(ctx context.Context, before, after Inventory, opts SelectOptions) Selection

SelectSources never chooses by mtime. Without a native identity, only one new root session with matching cwd and a source timestamp in the run window can match. A resumed session requires an explicit identity and a verified prefix.

type Service

type Service struct {
	DB            *sql.DB
	Paths         store.Paths
	CapturePolicy *CapturePolicy
}

func (Service) CompareSnapshots

func (s Service) CompareSnapshots(ctx context.Context, runID, leftID, rightRunID, rightID string) (SnapshotComparison, error)

func (Service) EnsureCapturePolicy added in v0.10.0

func (s Service) EnsureCapturePolicy(ctx context.Context, run string) (CapturePolicy, error)

EnsureCapturePolicy fixes the policy before launch creates hook logs or starts a workload. Save uses the same transaction helper for later imports.

func (Service) Entries

func (s Service) Entries(ctx context.Context, opts PageOptions) (Page, error)

func (Service) EnumerateSessions added in v0.10.0

func (s Service) EnumerateSessions(ctx context.Context, opts SessionEnumerationOptions) ([]SessionIdentity, error)

EnumerateSessions walks latest source reports in bounded keyset pages and verifies their immutable identities before deduplicating native sessions. Export callers must use their already frozen (and selected) database for this entire operation and for all subsequent indexes. Overview is only a summary. Errors return no partial catalog, including cancellation and budget exhaustion.

func (Service) ImportFile

func (s Service) ImportFile(ctx context.Context, runID string, opts ParseOptions) (SaveResult, error)
func (s Service) Links(ctx context.Context, runID, entryID string) (EntryLinks, error)

Links exposes existing graph relationships, never a new matching inference. A result without a projected call deliberately has no execution destination.

func (Service) Overview

func (s Service) Overview(ctx context.Context, runID string) (Overview, error)

func (Service) ReadHandler

func (s Service) ReadHandler() http.Handler

ReadHandler is shared by the local dashboard and daemon. It only resolves registered objects within the requested run; it never accepts disk paths.

func (Service) Save

func (s Service) Save(ctx context.Context, runID string, src Source, records []Record, report Coverage) (SaveResult, error)

Save atomically appends immutable record revisions and a processing report. Re-reading unchanged records is a no-op; a late result or changed snapshot is a new revision. Neither a retry nor a parse failure deletes earlier evidence.

func (Service) SessionGraphScope added in v0.10.0

func (s Service) SessionGraphScope(ctx context.Context, run, harness, session string) (*provenance.GraphSessionScope, error)

SessionGraphScope selects existing tool and event links. A shared process, working directory or cgroup never expands the session's event membership.

func (Service) SessionRelations added in v0.10.0

func (s Service) SessionRelations(ctx context.Context, opts SessionRelationOptions) (SessionRelationsPage, error)

SessionRelations is a read projection over immutable source records. It never changes run membership or treats shared resources as a session relationship.

func (Service) SnapshotFields added in v0.10.0

func (s Service) SnapshotFields(ctx context.Context, entry Entry) ([]SnapshotField, string, error)

SnapshotFields projects a saved configuration into bounded, typed values. It does not merge sessions, select an effective policy, or open live files.

type SessionEnumerationOptions added in v0.10.0

type SessionEnumerationOptions struct {
	RunID string
	// Zero uses the fixed resource budget. Callers may lower, never raise it.
	MaxSources, MaxSessions int
}

type SessionIdentity added in v0.10.0

type SessionIdentity struct {
	Harness   string `json:"harness"`
	SessionID string `json:"session_id"`
}

SessionIdentity is namespaced by harness, not by source/channel or run.

type SessionMetadata added in v0.10.0

type SessionMetadata struct {
	ForkedFromID string `json:"forked_from_id,omitempty"`
}

SessionMetadata preserves native relationship facts independently of optional configuration bodies. A non-nil empty value records an observed absence of a fork.

type SessionRef added in v0.10.0

type SessionRef struct {
	RunID     string   `json:"run_id,omitempty"`
	RunIDs    []string `json:"run_ids,omitempty"`
	Harness   string   `json:"harness"`
	SessionID string   `json:"session_id"`
	Available bool     `json:"available"`
}

type SessionRelation added in v0.10.0

type SessionRelation struct {
	ID       string                    `json:"id"`
	Kind     string                    `json:"kind"`
	From     SessionRef                `json:"from"`
	To       SessionRef                `json:"to"`
	Evidence []SessionRelationEvidence `json:"evidence"`
	Issues   []string                  `json:"issues,omitempty"`
}

type SessionRelationEvidence added in v0.10.0

type SessionRelationEvidence struct {
	RunID      string `json:"run_id"`
	SourceID   string `json:"source_id"`
	ObjectHash string `json:"object_hash"`
	EntryID    string `json:"entry_id,omitempty"`
	RecordedAt string `json:"recorded_at,omitempty"`
	Basis      string `json:"basis"`
}

type SessionRelationOptions added in v0.10.0

type SessionRelationOptions struct {
	RunID, Harness, SessionID, Cursor string
	Limit                             int
	// Nil queries the local store. A non-nil set confines discovery to the
	// explicitly exported runs; private occurrences never enter a public replay.
	VisibleRuns []string
}

type SessionRelationsPage added in v0.10.0

type SessionRelationsPage struct {
	SchemaVersion string            `json:"schema_version"`
	Subject       SessionRef        `json:"subject"`
	Relations     []SessionRelation `json:"relations"`
	HasMore       bool              `json:"has_more"`
	NextCursor    string            `json:"next_cursor,omitempty"`
	Limit         int               `json:"limit"`
	Limited       bool              `json:"limited"`
	Issues        []string          `json:"issues"`
}

type SnapshotChange

type SnapshotChange struct {
	Path   string        `json:"path"`
	Before SnapshotValue `json:"before"`
	After  SnapshotValue `json:"after"`
}

type SnapshotComparison

type SnapshotComparison struct {
	SchemaVersion string           `json:"schema_version"`
	Scope         string           `json:"scope"`
	Status        string           `json:"status"`
	Left          Entry            `json:"left"`
	Right         Entry            `json:"right"`
	Changes       []SnapshotChange `json:"changes"`
	HasMore       bool             `json:"has_more"`
	Reason        string           `json:"reason,omitempty"`
}

SnapshotComparison compares recorded values, not effective permissions. An absent field means "not recorded here", never allowed, denied, or revoked.

type SnapshotField added in v0.10.0

type SnapshotField struct {
	Path  string        `json:"path"`
	Value SnapshotValue `json:"value"`
}

type SnapshotValue

type SnapshotValue struct {
	Present   bool   `json:"present"`
	Preview   string `json:"preview,omitempty"`
	Truncated bool   `json:"truncated"`
	SHA256    string `json:"sha256,omitempty"`
}

type Source

type Source struct {
	ID                 string   `json:"id"`
	Harness            string   `json:"harness"`
	Channel            string   `json:"channel,omitempty"`
	SessionID          string   `json:"session_id"`
	ParentSessionID    string   `json:"parent_session_id,omitempty"`
	AgentID            string   `json:"agent_id,omitempty"`
	Path               string   `json:"path,omitempty"`
	ParserVersion      string   `json:"parser_version"`
	ApplicationVersion string   `json:"application_version,omitempty"`
	FormatVersion      string   `json:"format_version,omitempty"`
	Binding            string   `json:"binding"`
	BindingEvidence    []string `json:"binding_evidence,omitempty"`
	Workdir            string   `json:"workdir,omitempty"`
}

type SourceCursor

type SourceCursor struct {
	Lines  int64  `json:"lines"`
	Bytes  int64  `json:"bytes"`
	SHA256 string `json:"sha256"`
	Valid  bool   `json:"valid"`
}

A cursor hashes complete decompressed physical lines. A growing final line stays outside the prefix and is retried, including in concatenated zstd files.

type Status

type Status string
const (
	Disabled          Status = "disabled"
	NoInput           Status = "no_input"
	Empty             Status = "empty"
	OK                Status = "ok"
	Partial           Status = "partial"
	Failed            Status = "failed"
	Ambiguous         Status = "ambiguous"
	LegacyNotRecorded Status = "legacy_not_recorded"
)

Jump to

Keyboard shortcuts

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