history

package
v0.14.2 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package history is abcd's native session-transcript store: the write/read/ redact engine that populates ~/.abcd.noindex/transcripts/<root-sha>/records/ and retires the specstory shim (adr-29). It is transport-agnostic — no stdout, no os.Exit, no CLI knowledge — so any surface can drive it and marshal its structured results.

The store's location, its root-SHA keying, the home-scoped opt-in that pulls one repo's transcripts into that repo, and the migration off the legacy location all live in location.go, behind the single Resolve seam this file's verbs go through. The store creates itself; no install step is a precondition of capture (iss-95).

The index.json registry and per-repo meta.json are owned by internal/core/ahoy and stay under ~/.abcd.noindex/history/; this package owns the corpus and nothing else.

Redaction is NOT reimplemented here. Every transcript is sanitised through internal/adapter/scanner — the same detector and masking discipline the launch path uses — in a two-stage, fail-closed capture: sanitise on write, then re-scan and refuse to write if any hard_fail secret or self home path survived. A stored record can never contain a live secret or an absolute home path.

Index

Constants

View Source
const (
	OnOrphanIgnore = "ignore"
	OnOrphanPrompt = "prompt"
)

The accepted on_orphan policies. Neither of them lets core prompt: `prompt` means core still ingests nothing and returns the orphan list, and the front door is what asks a human and re-invokes with the chosen names. An interactive question is a transport concern.

View Source
const (
	SkipOwnedElsewhere = "owned-elsewhere"
	SkipAmbiguousOwner = "ambiguous-owner"
	SkipNoSession      = "no-session-id"
	SkipAmbiguousAgent = "ambiguous-agent-id"
)

Skip reasons. A skip is a decision, and each of these names which one.

View Source
const (
	RouteNative = "native"
	RouteImport = "import"
	ToolHost    = "host"
)

A record names where its transcript came from with two separate labels (ruling J13 on iss-2608230752354928): the ROUTE it reached the store by, in source_kind, and the TOOL that produced it, in source_tool.

The route vocabulary is closed. `native` is abcd's own capture of the transcript the host harness wrote — its hooks, or its capture and ingest verbs reading that transcript. `import` is a transcript another tool exported, brought in through abcd. The tool vocabulary is open: any lowercase slug naming the producing tool, with `host` reserved for the harness abcd is installed in, which is what a native capture that names no tool records.

View Source
const ConfigRelPath = ".abcd/config/history.json"

ConfigRelPath is the per-repo history configuration, relative to the repo root.

View Source
const (
	// LocalStoreRelPath is the opt-in per-repo pull-in, relative to the repo
	// root. It is under .abcd/.work.local/ deliberately: that tier is gitignored
	// and per-worktree, so a pulled-in transcript is never a commit candidate and
	// never merge-conflicts between concurrent sessions.
	LocalStoreRelPath = ".abcd/.work.local/transcripts"
)
View Source
const StagedTTL = 7 * 24 * time.Hour

StagedTTL is how long a staged raw transcript may sit before it is reported as overdue.

Seven days, and the number is a reporting threshold rather than a deadline anything enforces, so it is chosen to be quiet in the normal case and loud in the broken one. An ordinary repository drains within a prompt or two of the stage — the live drain runs on UserPromptSubmit — so an entry reaching a WEEK means no session has opened that repository in a week, which is exactly the failure mode this constant exists to name. A shorter TTL would flag weekends and holidays; a longer one lets a fortnight of raw transcripts accumulate before anything says so, which is what actually happened.

Variables

View Source
var (

	// LocalRootsRelPath is the home-scoped declaration that pulls a repo's
	// transcripts into that repo, relative to the caller's home.
	LocalRootsRelPath = abcdhome.Rel("local-transcript-roots")

	// LocalRootsDisplay names that file in a diagnostic in tilde form, so a
	// message a user pastes into a shell works and no diagnostic carries the
	// caller's home path (iss-81, fsutil.RedactHome).
	LocalRootsDisplay = abcdhome.Display("local-transcript-roots")
)

Functions

func NoteSessionRepo added in v0.9.0

func NoteSessionRepo(repoRoot, rootSHA, sessionID string) error

NoteSessionRepo records that sessionID is running against the store keyed on rootSHA, so a later hook holding only that session id can find the store.

It is written by the hooks that CAN resolve a repository — SessionStart from the session's own cwd, and SubagentStop when its cwd still resolves — and read by the one that sometimes cannot. Writing it is best-effort by construction: a failure here degrades a fallback, never a capture.

func NoteSubagentGap added in v0.9.0

func NoteSubagentGap(repoRoot, rootSHA, event string) error

NoteSubagentGap records a SubagentStop payload that carried no agent_transcript_path. The first sighting sets FirstSeen and every sighting moves LastSeen and the count, so a reader can tell a harness that has never delivered the field from one that stopped, or started.

func SessionRepo added in v0.9.0

func SessionRepo(sessionID string) (string, error)

SessionRepo returns the root-commit SHA of the store that noted sessionID.

It reads no transcript: one directory listing of the user-level store and one stat per repository lane under it. A session id that two stores claim is refused rather than guessed — a transcript filed against the wrong repository is redacted by the wrong repository's scanner configuration, which is a privacy fault, not a misfiling. An unknown session returns an error naming that.

func TranscriptSettled added in v0.9.0

func TranscriptSettled(raw []byte) bool

TranscriptSettled reports whether a JSONL transcript's last non-blank line is a complete JSON value.

It is the predicate behind the stage-time half of the flush-race mitigation: a hook that fires the instant an agent stops may read a transcript the harness has not finished appending to, and a severed final line is the shape that has. The caller waits and re-reads on false; the wait is deliberately NOT in this package, because it must never happen inside the staging lock — a burst of simultaneous completions would serialise on a lock whose timeout was tuned for one SessionEnd.

Empty input is unsettled: there is nothing to have finished writing.

Whether SubagentStop actually fires before the flush is UNMEASURED. This is a mitigation, not an answer, and the measurement is a separate step.

Types

type AgentTelemetry added in v0.9.0

type AgentTelemetry struct {
	AgentID          string `json:"agent_id,omitempty"`
	IsMainThread     bool   `json:"is_main_thread"`
	ParentAgentID    string `json:"parent_agent_id,omitempty"`
	AgentType        string `json:"agent_type,omitempty"`
	SpawnDepth       int    `json:"spawn_depth"`
	SpawnAttribution string `json:"spawn_attribution,omitempty"`
	LineageSource    string `json:"lineage_source,omitempty"`
	AdoptedProject   string `json:"adopted_project,omitempty"`
	// Record is the record's BASENAME. Never a path: the artefact and its
	// telemetry must both survive the store being gone.
	Record string `json:"record"`

	StartedAt        *time.Time `json:"started_at,omitempty"`
	EndedAt          *time.Time `json:"ended_at,omitempty"`
	WallClockSeconds float64    `json:"wall_clock_seconds"`

	Turns     TurnCounts     `json:"turns"`
	Tokens    TokenCounts    `json:"tokens"`
	ToolCalls map[string]int `json:"tool_calls"`
	Models    []string       `json:"models"`

	// SpawnedIn names the thread the spawn point was found in — "main" or a
	// parent agent id — and SpawnedAtTurn / JoinedAtTurn are 1-based turn
	// indices in THAT thread. Zero means the point was not recovered, which is
	// reported in completeness rather than guessed.
	SpawnedIn      string `json:"spawned_in,omitempty"`
	SpawnedAtTurn  int    `json:"spawned_at_turn,omitempty"`
	JoinedAtTurn   int    `json:"joined_at_turn,omitempty"`
	SpawnToolUseID string `json:"spawn_tool_use_id,omitempty"`
	// PlacedBy names the rung that placed this agent: record (the stored
	// spawn_tool_use_id), transcript (the spawning transcript's own tool
	// result), or none.
	PlacedBy string `json:"placed_by,omitempty"`

	Lines            int `json:"lines"`
	LinesUnparseable int `json:"lines_unparseable"`
}

AgentTelemetry is one agent's row — the main thread included, as the agent with an empty id and depth zero.

type CaptureMeta added in v0.9.0

type CaptureMeta struct {
	SessionID string // the session the transcript belongs to (required)
	Kind      string // source_kind, the route: native | import (a legacy specstory-import is read as import + specstory)
	Tool      string // source_tool, the producing tool: a lowercase slug; empty on a native capture means the host

	AgentID        string // the sub-agent's own id; empty on the main thread
	ParentAgentID  string // the agent that spawned it; empty when the main thread did
	AgentType      string // the kind of agent, as the harness reports it
	SpawnDepth     int    // 0 for the main thread, 1 for a sub-agent of it, and so on
	SpawnToolUseID string // the tool call in the spawning transcript that launched it
	LineageSource  string // hook | ingest | migrated — which door the record came through

	// SpawnAttribution is which rung of the attribution ladder placed this
	// agent's spawn point: sidecar | transcript | unattributed. Required on a
	// sub-agent record, empty on the main thread.
	SpawnAttribution string

	// AdoptedProject names the harness project directory an ingested
	// transcript was adopted from. Set only by an adoption; empty everywhere
	// else.
	AdoptedProject string
}

CaptureMeta is everything Capture stamps onto a record besides the bytes and the store key: the session the transcript belongs to, the source kind, and the lineage that says which agent produced it.

It replaces the positional parameter list Capture used to take. Six more positional strings on a security-critical call is a transposition waiting to happen, and a transposed session and agent id would silently mis-attribute a transcript rather than fail.

Every string field here is externally supplied — the harness payload, a configuration file a contributor can edit — so every one of them passes through the same redaction gate as the transcript body. There is no field on this record the scanner does not see.

type CaptureResult

type CaptureResult struct {
	Record   Record            `json:"record"`
	Wrote    bool              `json:"wrote"`    // false on an idempotent no-op (source unchanged)
	Residual []scanner.Finding `json:"residual"` // populated only alongside RedactionResidualError
	// Superseded names the record this capture replaced, when a longer
	// transcript for the same (session, agent) arrived and the stored one was a
	// byte-prefix of it. Nil whenever nothing was replaced.
	Superseded *Record `json:"superseded,omitempty"`
	// ScanGap names the coverage the repository asked for and did not get: it
	// armed gitleaks in .abcd/config/gitleaks.json and the binary is not
	// installed. The transcript is still stored, scanned by the native
	// scanner, and this says so, with what gitleaks is and how to install it
	// (the 2026-09-25 ruling on iss-2608291814575788). Empty when there is no
	// gap.
	ScanGap string `json:"scan_gap,omitempty"`
}

CaptureResult reports the outcome of one capture.

func Capture

func Capture(repoRoot, rootSHA string, raw []byte, meta CaptureMeta) (CaptureResult, error)

Capture reads a raw session transcript, redacts it through the scanner (two-stage, fail-closed), and writes a record into this repo's lane of the store — ~/.abcd.noindex/transcripts/<rootSHA>/records/ by default.

It is idempotent on the source's sha256: an identical source already stored is a no-op (Wrote=false, existing record returned, mtime preserved). It is fail-closed: if a blocking span survives redaction it returns a *RedactionResidualError and writes nothing.

There is no install precondition: Resolve creates the store when it is absent and refuses anything on the path that is not a real directory. It never touches ahoy's index or meta.

type Completeness added in v0.9.0

type Completeness struct {
	// MainThreadPresent is false when no main-thread record exists for this
	// session. Reconstruction still renders — the sub-agents are the material
	// that survived — and every spawn point is then unrecoverable, which is
	// what AgentsWithoutSpawnPoint counts.
	MainThreadPresent bool `json:"main_thread_present"`

	RecordsFound int `json:"records_found"`
	RecordsUsed  int `json:"records_used"`

	// DroppedRecords names every record found and not used.
	DroppedRecords []DroppedRecord `json:"dropped_records,omitempty"`

	AgentsTotal              int `json:"agents_total"`
	AgentsUnattributed       int `json:"agents_unattributed"`
	AgentsWithoutSpawnPoint  int `json:"agents_without_spawn_point"`
	AgentsWithoutJoinPoint   int `json:"agents_without_join_point"`
	AgentsWithoutAgentType   int `json:"agents_without_agent_type"`
	AgentsWithoutParentInSet int `json:"agents_whose_parent_is_not_in_this_set"`

	// LinesUnparseable counts transcript lines that were not JSON. A truncated
	// capture normally shows up as exactly one of these, on the last line.
	LinesUnparseable int `json:"lines_unparseable"`
	// UsageWithoutMessageID counts responses whose usage could not be keyed on
	// a message id and so could not be de-duplicated. A non-zero value is the
	// one condition under which the token totals may be inflated.
	UsageWithoutMessageID int `json:"usage_without_message_id"`

	// AbsentFields names the telemetry inputs no source line carried. It is how
	// "zero tool calls" is told apart from "this harness does not record tool
	// calls".
	AbsentFields []string `json:"absent_fields,omitempty"`

	// ElidedBlocks / ElidedBytes report what the per-block cap removed from the
	// artefact. Telemetry is computed BEFORE any elision, so the counts above
	// describe the whole transcript whatever the artefact shows.
	ElidedBlocks int `json:"elided_blocks"`
	ElidedBytes  int `json:"elided_bytes"`
	// OmittedTurns counts turns spine mode left out of the artefact.
	OmittedTurns int `json:"omitted_turns"`

	// Notes carries anything else a reader must know, in words.
	Notes []string `json:"notes,omitempty"`
}

Completeness is what this reconstruction knows it does not know.

It is not decoration. A derived measure that cannot say what was missing invites the cross-run comparison it cannot support, and the corpus this reads is missing things routinely: on this machine 71 sub-agent sets have no parent transcript at all.

type Config added in v0.9.0

type Config struct {
	SchemaVersion int `json:"schema_version"`
	// IngestRoots are the directories `history ingest` walks when the operator
	// names no source. This is the ONLY place a transcript-source path lives: a
	// vendor's directory layout baked into code would be the on-disk dependency
	// this design exists to avoid.
	IngestRoots []string `json:"ingest_roots"`
	// AdoptProjects lists the harness project directory names this repository
	// claims. A transcript under a claimed name is ingested here, under THIS
	// repository's redaction configuration, when its own repository can no
	// longer be found on disk.
	AdoptProjects []string `json:"adopt_projects"`
	// OnOrphan is ignore (the default) or prompt.
	OnOrphan string `json:"on_orphan"`
}

Config is `.abcd/config/history.json`.

func DefaultConfig added in v0.9.0

func DefaultConfig() Config

DefaultConfig is what a repository with no configuration file gets: no declared roots, no claimed projects, and orphans ignored and reported.

func LoadConfig added in v0.9.0

func LoadConfig(repoRoot string) (Config, error)

LoadConfig reads a repository's history configuration.

An absent file is not an error — it is the default. Everything else is: a configuration that exists but cannot be read is a statement the operator made and this run cannot honour, and quietly falling back to the default would ingest under a policy nobody chose.

type Destination added in v0.9.0

type Destination struct {
	RepoRoot string `json:"repo_root"`
	RootSHA  string `json:"root_sha"`
}

Destination is the repository a run of Ingest writes into: its root for the scanner configuration, and its root-commit SHA for the store key.

type DiscardResult added in v0.9.0

type DiscardResult struct {
	Path    string   `json:"path"`
	Bytes   int64    `json:"bytes"`
	Removed []string `json:"removed"`
}

DiscardResult reports what one Discard removed.

func Discard added in v0.9.0

func Discard(repoRoot, rootSHA, name string) (DiscardResult, error)

Discard permanently deletes ONE staged or quarantined raw transcript, named by its bare filename, together with the sidecar and reason file describing it.

This is the only code path in abcd that destroys a transcript nothing has stored, and it exists because quarantine without an exit is a room with no door: a transcript the scanner will never pass would otherwise sit unredacted forever with no legitimate way to be rid of it. It is never called by a hook, a drain, or an expiry. The judgement that these particular bytes may go is a human one, and the confirmation for it belongs to the front door, not here — core neither prompts nor prints.

name is a bare filename by design: a caller passing a path could delete outside the store, and this function's whole risk profile is that it deletes. It must end in the staged suffix and contain no separator.

type DrainBudget added in v0.9.0

type DrainBudget struct {
	MaxEntries int   // entries attempted; <= 0 means unbounded
	MaxBytes   int64 // staged bytes attempted; <= 0 means unbounded
}

DrainBudget bounds one drain pass. A zero value is unbounded, which is what the explicit `abcd history drain` verb asks for.

The bound is a PAIR because the two costs are different. Redaction time tracks BYTES (roughly 0.7s per MB), so the byte bound is the one that protects an interactive session start; the count bound keeps a pathological many-tiny-transcripts case bounded too, which bytes alone would not. An intent that admits one staged file per sub-agent completion makes the second case ordinary rather than pathological.

type DrainFailure

type DrainFailure struct {
	SessionID string `json:"session_id"`
	Path      string `json:"path"`
	Err       string `json:"error"`
	// Permanent is true when the refusal is a property of the transcript's own
	// bytes rather than of the environment — today, exactly a
	// *RedactionResidualError. A permanent failure is never retried.
	Permanent bool `json:"permanent,omitempty"`
	// Quarantined records that the staged bytes were moved into quarantine/ as
	// a consequence, and where they went. False on every retryable failure, and
	// false on a permanent one whose move itself failed (which is reported in
	// Err rather than swallowed).
	Quarantined    bool   `json:"quarantined,omitempty"`
	QuarantinePath string `json:"quarantine_path,omitempty"`
}

DrainFailure is one staged transcript that could not be captured. The staged bytes are never deleted by a failure: a failure here is recoverable by hand, and deleting the only copy abcd holds would convert a reported problem into the silent permanent loss this whole mechanism exists to end.

The two kinds of failure are NOT the same fact, and reporting them alike was its own defect (iss-2609090722466403). A store path that is momentarily unwritable, a lock a peer holds, a source file that vanished — those are RETRYABLE: the next drain may well succeed, so the entry stays staged and stays queued. A transcript the fail-closed scanner refuses to pass is DETERMINISTIC: the same bytes will be refused by every future drain, forever, so leaving it queued buys nothing and costs a re-read and a re-scan of unredacted text on every pass while its raw copy sits there anyway. Permanent marks the second kind; such an entry is moved out of the drain queue into quarantine/ and reported there until an operator decides what becomes of it.

type DrainResult

type DrainResult struct {
	Captured  []Record       `json:"captured"`
	Failed    []DrainFailure `json:"failed"`
	Remaining int            `json:"remaining"` // staged entries not attempted, budget exhausted
	// Extended counts the entries whose recorded source file had grown into a
	// strict superset of the staged bytes by the time the drain read it — a
	// transcript that was staged before the harness finished writing it, caught
	// and completed. It is reported rather than left silent because the rate is
	// the measurement that decides whether the flush race is real: a zero here
	// across a corpus is evidence the event fires after the flush, and a
	// non-zero one is the count of transcripts that would otherwise have been
	// stored short.
	Extended int `json:"extended"`
	// Overdue counts the entries this pass SAW that were already past
	// StagedTTL, whether or not the pass reached them. It is the number a
	// notice must be able to say out loud: an overdue entry is unredacted text
	// that has outlived the guarantee staging makes about it.
	Overdue int `json:"overdue"`
	// ScanGap is the first capture's CaptureResult.ScanGap this pass saw: the
	// repository armed gitleaks and the binary is not installed, so what the
	// pass stored was masked by the native scanner alone. Carried here so an
	// automatic drain says so rather than dropping it (iss-2608291814575788).
	ScanGap string `json:"scan_gap,omitempty"`
}

DrainResult reports one drain pass.

func Drain

func Drain(repoRoot, rootSHA string, budget DrainBudget) (DrainResult, error)

Drain captures every staged transcript into the store and removes the ones it stored. It is the SessionStart half of capture.

budget bounds how many entries one pass attempts; <= 0 means all of them. The bound exists because a backlog drains at redaction speed and SessionStart is interactive: a repo with a dozen missed sessions would otherwise stall the user's first prompt. Whatever the budget leaves is reported in Remaining rather than dropped, so a partial pass is loud and the caller can say so.

A staged file is deleted ONLY when its transcript is in the store — either captured now or already present — and only while it still holds the bytes that were captured. The staging lock is deliberately NOT held across Capture: redaction is the cost staging exists to keep out of SessionEnd, and holding the lock through it would stall every concurrent hook for its duration. So a Stage that replaces the copy mid-drain wins the race by design: the removal re-checks the bytes under the lock, a replaced copy is left for the next pass, and the fresher transcript is never lost. Any failure leaves the file where it is.

type DroppedRecord added in v0.9.0

type DroppedRecord struct {
	Record  string `json:"record"`
	AgentID string `json:"agent_id,omitempty"`
	Bytes   int    `json:"bytes"`
	Reason  string `json:"reason"`
}

DroppedRecord names a record this reconstruction did NOT use, and why. The store can hold several records for one (session, agent) — supersession narrows that but does not close it, because a capture through a different door writes a fresh record rather than superseding one. Reconstruction picks one and says which, here and in the artefact; a silent pick would make two runs over the same store disagree with nothing to explain it.

type HarnessLineage added in v0.9.0

type HarnessLineage struct {
	AgentType      string
	ParentAgentID  string
	SpawnDepth     int
	SpawnToolUseID string
}

HarnessLineage is what the harness's own per-agent metadata can tell a migration about an agent it recorded: the kind of agent, how deep it was spawned, the tool call that launched it, and — at depth two and deeper — the agent that spawned it.

The spec says these fields "were never held" anywhere and so must stay empty on a migrated record. That is wrong on this machine and, as far as the store can tell, on any machine whose harness still has its per-agent metadata: the files are keyed by agent id and outlive the transcripts. Where they answer, the migration uses them; where they do not, the record says its lineage is unknown through spawn_attribution rather than by looking empty.

type IngestFailure added in v0.9.0

type IngestFailure struct {
	Path string `json:"path"`
	Err  string `json:"error"`
}

IngestFailure is a transcript this run could not read or could not store.

type IngestOptions added in v0.9.0

type IngestOptions struct {
	// Adopt names the harness project directories this run claims. A transcript
	// that would otherwise be an orphan and whose project is named here is
	// ingested under THIS repository's redaction configuration and stamped with
	// the name it was adopted from.
	Adopt []string
	// Lineage is the attribution ladder's first rung, supplied by the front
	// door. Optional.
	Lineage LineageLookup
	// MaxDepth bounds a directory walk; zero means ingestDefaultDepth.
	MaxDepth int
	// Session, when set, scopes the run to one session: only transcripts whose
	// lines name exactly this session id — its main thread and every sub-agent
	// it spawned — are placed and stored, and every other transcript found is
	// out of scope and not reported. It is the write-side twin of a session
	// listing (`history capture --session <id> --all`, iss-2609202046145653).
	// A file that could not be read is still reported as failed: it may have
	// been one of the session's.
	Session string
}

IngestOptions carries the policy a run applies.

type IngestResult added in v0.9.0

type IngestResult struct {
	Captured []Ingested      `json:"captured"`
	Skipped  []IngestSkip    `json:"skipped"`
	Orphans  []Orphan        `json:"orphans"`
	Failed   []IngestFailure `json:"failed"`
}

IngestResult reports four populations. Nothing is silent.

func Ingest added in v0.9.0

func Ingest(dest Destination, sources []string, opts IngestOptions) (IngestResult, error)

Ingest reads the named sources and stores every transcript the destination repository owns.

sources are explicit file or directory paths. There is no implicit "scan the harness's store" mode: a vendor path baked in here would be the on-disk dependency this design rules out, so a repository that ingests regularly declares its roots in its own configuration and the front door passes them in.

type IngestSkip added in v0.9.0

type IngestSkip struct {
	Path      string `json:"path"`
	SessionID string `json:"session_id,omitempty"`
	AgentID   string `json:"agent_id,omitempty"`
	Reason    string `json:"reason"`
	// RootSHA names the repository that owns it, when one was resolved. A SHA
	// names a repository without naming it.
	RootSHA string `json:"root_sha,omitempty"`
}

IngestSkip is a transcript this run deliberately did not store.

type Ingested added in v0.9.0

type Ingested struct {
	Path           string `json:"path"`
	SessionID      string `json:"session_id"`
	AgentID        string `json:"agent_id,omitempty"`
	AdoptedProject string `json:"adopted_project,omitempty"`
	RecordPath     string `json:"record_path"`
	// Wrote is false when the store already held these bytes. An ingest is
	// idempotent through Capture's own key, so a second run of the same
	// material reports every file and writes none of them.
	Wrote bool `json:"wrote"`
	// Via names which step placed the owning repository: session-cwd, store, or
	// file-cwd. It is reported because the three are not equally strong, and an
	// operator reading a surprising placement needs to know which one answered.
	Via string `json:"via"`
}

Ingested is one transcript that entered the store.

type LineageLookup added in v0.9.0

type LineageLookup func(LineageRef) (HarnessLineage, bool)

LineageLookup answers what the harness recorded about one agent.

It is a function rather than a path because core holds no knowledge of the harness's on-disk layout and must not acquire any: a design that reads a vendor's directory structure is one the vendor can silently break. The front door supplies the resolver, and a nil lookup simply means the rung does not answer — never an error.

type LineageRef added in v0.9.0

type LineageRef struct {
	SessionID  string
	AgentID    string
	SourcePath string
}

LineageRef identifies the agent a lookup is being asked about. SourcePath is set only when the caller is holding the transcript file itself (ingest does, migrate does not), so a resolver can take the cheap route of deriving the harness's metadata file from the transcript path before falling back to a search.

type MigrateEntry added in v0.9.0

type MigrateEntry struct {
	Path            string `json:"path"`
	StoredSessionID string `json:"stored_session_id"`
	SessionID       string `json:"session_id,omitempty"`
	AgentID         string `json:"agent_id,omitempty"`
	// ExtraSegment is whatever the composing binary put between the session
	// prefix and the agent marker (a workflow id, on this machine). It is
	// reported rather than stored: the schema has no field for it, and dropping
	// it silently would lose the only trace that these records were composed
	// differently from the rest.
	ExtraSegment     string `json:"extra_segment,omitempty"`
	AgentType        string `json:"agent_type,omitempty"`
	ParentAgentID    string `json:"parent_agent_id,omitempty"`
	SpawnDepth       int    `json:"spawn_depth,omitempty"`
	SpawnToolUseID   string `json:"spawn_tool_use_id,omitempty"`
	SpawnAttribution string `json:"spawn_attribution,omitempty"`
	Wrote            bool   `json:"wrote"`
	Refused          string `json:"refused,omitempty"`
}

MigrateEntry is one composite record's outcome.

type MigrateOptions added in v0.9.0

type MigrateOptions struct {
	// RepoRoot is the repository whose scanner configuration governs this
	// store. It is required in BOTH modes: the lineage a lookup returns is
	// externally supplied and lands in frontmatter, so it is redacted before it
	// is reported, not only before it is written.
	RepoRoot string
	// Apply switches the run from reporting to writing.
	Apply bool
	// Lineage is the attribution ladder's first rung. Optional.
	Lineage LineageLookup
}

MigrateOptions carries what the migration needs beyond the store key.

type MigrateResult added in v0.9.0

type MigrateResult struct {
	Applied   bool           `json:"applied"`
	Scanned   int            `json:"scanned"`
	Composite int            `json:"composite"`
	Migrated  []MigrateEntry `json:"migrated"`
	Refused   []MigrateEntry `json:"refused"`
}

MigrateResult is what one migration run saw and did.

func Migrate added in v0.9.0

func Migrate(rootSHA string, opts MigrateOptions) (MigrateResult, error)

Migrate repairs every record whose session_id is a composite identifier.

It reports by default and writes only under opts.Apply. Re-running it is a no-op: a record that already carries an agent id has been migrated, and a record whose session id is not a composite was never this verb's business.

type Orphan added in v0.9.0

type Orphan struct {
	Path      string `json:"path"`
	Project   string `json:"project"`
	SessionID string `json:"session_id,omitempty"`
	AgentID   string `json:"agent_id,omitempty"`
	// Cwd is the working directory the transcript recorded, as fsutil.DisplayPath
	// shows it: home-relative, or its directory name outside HOME.
	Cwd string `json:"cwd,omitempty"`
}

Orphan is a transcript whose owning repository could not be found on disk. Nothing is written for one unless its project is adopted by name.

type Quarantined added in v0.9.0

type Quarantined struct {
	SessionID     string    `json:"session_id"`
	AgentID       string    `json:"agent_id,omitempty"`
	Path          string    `json:"path"`
	SidecarPath   string    `json:"sidecar_path,omitempty"`
	ReasonPath    string    `json:"reason_path,omitempty"`
	Reason        string    `json:"reason,omitempty"`
	Bytes         int64     `json:"bytes"`
	StagedAt      time.Time `json:"staged_at,omitempty"`
	QuarantinedAt time.Time `json:"quarantined_at,omitempty"`
	// Err is set when the reason file is present but unreadable. The entry is
	// still listed: the bytes are what matter, and an entry hidden because its
	// metadata is broken is an entry nobody disposes of.
	Err string `json:"error,omitempty"`
}

Quarantined is one transcript that will never pass redaction, parked out of the drain queue. Its bytes are still RAW and still on disk — quarantine is a change of state, not of exposure — which is why the listings report it as loudly as they report a staged entry.

func ListQuarantined added in v0.9.0

func ListQuarantined(repoRoot, rootSHA string) ([]Quarantined, error)

ListQuarantined returns this repo's quarantined transcripts, oldest first. An absent quarantine dir is not an error: it means nothing has ever been parked.

type ReconstructMode added in v0.9.0

type ReconstructMode string

ReconstructMode selects how much of each sub-agent is rendered. The main thread is whole in both modes; only the branches differ.

const (
	// ModeFull renders every turn of every agent.
	ModeFull ReconstructMode = "full"
	// ModeSpine renders every turn of the main thread and, for each sub-agent,
	// its opening instruction and its closing turn, with the omission stated.
	ModeSpine ReconstructMode = "spine"
)

type ReconstructOptions added in v0.9.0

type ReconstructOptions struct {
	// SessionID is the session to reconstruct. Required.
	SessionID string
	// Mode is full (default) or spine.
	Mode ReconstructMode
	// MaxBlockBytes caps one rendered tool input or tool result. 0 is
	// unbounded. Whatever is elided is counted into the completeness block, so
	// a reader is never left guessing whether a short artefact is a short
	// session.
	MaxBlockBytes int
}

ReconstructOptions carries what reconstruction needs beyond the store key.

The spec gives the signature as Reconstruct(rootSHA, sessionID). It grew an options struct for one measured reason: the artefact has a size problem the spec does not acknowledge (see the package comment above), and both remedies — the mode and the per-block cap — are choices only the caller can make.

type Reconstruction added in v0.9.0

type Reconstruction struct {
	// Artefact is the Markdown document. It is deterministic — the same records
	// reconstruct to the same bytes — which is why no generation timestamp
	// appears in it; that lives on the telemetry.
	Artefact []byte `json:"-"`
	// ArtefactName and TelemetryName are the filenames a front door should use.
	ArtefactName  string `json:"artefact_name"`
	TelemetryName string `json:"telemetry_name"`
	// ArtefactBytes is the artefact's length, so a --json caller can report the
	// size without carrying the document through the envelope.
	ArtefactBytes int       `json:"artefact_bytes"`
	Telemetry     Telemetry `json:"telemetry"`
}

Reconstruction is one session rendered: the artefact bytes and the telemetry that describes them.

func Reconstruct added in v0.9.0

func Reconstruct(repoRoot, rootSHA string, opts ReconstructOptions) (Reconstruction, error)

Reconstruct renders one session into a single artefact and its telemetry.

It reads; it never writes and never learns a path. An empty session — no record of any kind — is an error, because the caller asked about something that is not there. A session whose MAIN THREAD is missing is not: it renders, labelled, because that is the majority shape of the sub-agent corpus.

type Record

type Record struct {
	SessionID    string    `json:"session_id"`
	RootCommit   string    `json:"root_commit"`
	CapturedAt   time.Time `json:"captured_at"`
	SourceKind   string    `json:"source_kind"` // the route: native | import
	SourceTool   string    `json:"source_tool"` // the producing tool; host on a native capture
	SourceSHA256 string    `json:"source_sha256"`
	Path         string    `json:"path"`
	Secrets      int       `json:"redacted_secrets"`
	HomePaths    int       `json:"redacted_home_paths"`

	// Lineage (schema 2). All optional; all empty/zero on a main-thread
	// record, which is exactly how a schema-1 record parses.
	AgentID          string `json:"agent_id,omitempty"`
	ParentAgentID    string `json:"parent_agent_id,omitempty"`
	AgentType        string `json:"agent_type,omitempty"`
	SpawnDepth       int    `json:"spawn_depth,omitempty"`
	SpawnToolUseID   string `json:"spawn_tool_use_id,omitempty"`
	LineageSource    string `json:"lineage_source,omitempty"`
	SpawnAttribution string `json:"spawn_attribution,omitempty"`

	// AdoptedProject (schema 3) names the harness project directory this
	// record was adopted from, on a transcript ingested into a repository that
	// claims that name because the repository the transcript recorded no longer
	// exists on disk. It is empty on everything else, and its presence is what
	// makes an adoption a property of the artefact rather than of a run's
	// output.
	AdoptedProject string `json:"adopted_project,omitempty"`

	// ContextStamps are the per-run context stamps the raw transcript carried
	// when it was captured, distinct and in first-seen order
	// (adr-2609021016275803). A session handed a reading bundle or a scribe
	// context through a tool the host retains carries that context's stamp, and
	// recording it here as METADATA is what lets the separation check stay out of
	// the bodies, as brief invariant 15's consumer list requires.
	//
	// Optional on read, so a record captured before the field existed parses
	// with none and recordSchemaVersion does not move.
	ContextStamps []string `json:"context_stamps,omitempty"`
}

Record is one stored transcript's metadata (its frontmatter). It never carries raw content — the redacted body is fetched separately via Read.

SessionID means one thing and one thing only: the session the transcript belongs to. On a sub-agent record it is the FULL, untruncated id of the spawning session, which is what the parent's own record carries too, so a reader holding a session id reaches the whole session by matching one field (adr-2609090636172016). Lineage is carried by the fields below, never by overloading the session id with a composite.

func List

func List(repoRoot, rootSHA string) ([]Record, error)

List returns this repo's records, newest first. It reads frontmatter only, never bodies. An empty store returns no records and no error (this repo has simply not been captured yet); a store path that is not a real directory is refused with an error.

It goes through Resolve like every other verb, so a read is also the moment a corpus left at the legacy location is migrated: a reader that skipped that would report the store as empty while the transcripts sat one directory away.

func ListForSession added in v0.9.0

func ListForSession(repoRoot, rootSHA, sessionID string) ([]Record, error)

ListForSession returns every record belonging to one session — the main thread and every sub-agent it spawned, at any depth — main thread first and otherwise newest first.

This is what a session identifier buys now that lineage is carried by fields: a sub-agent record holds the FULL, untruncated id of the spawning session, so one field match reaches the whole session. Under the composite identifier it could not, which is the defect adr-2609090636172016 records.

The main thread leads because it is what makes the rest legible: the branches are only interpretable against the spine that spawned them. An empty result is not an error — the session may simply have no records here.

func Read

func Read(repoRoot, rootSHA, key string) (Record, []byte, error)

Read returns the metadata and full redacted body of one record. It never un-redacts; the stored bytes are already sanitised.

The key is resolved in three steps, most specific first:

  1. an exact record filename — one record, named outright;
  2. an exact agent id — one sub-agent's transcript;
  3. a session id, preferring the MAIN-THREAD record and newest first. A reader who names a session is asking for its spine, even when a sub-agent of it was captured more recently; ListForSession is how they get the rest.

type RedactionResidualError

type RedactionResidualError struct {
	Residual []scanner.Finding
}

RedactionResidualError is returned by Capture when the stage-two re-scan finds a BLOCKING span that survived redaction — any identity or network span whatever its severity, plus every hard_fail one (scanner.BlockingResidual). NO file is written. It carries the surviving findings' kinds/locations only — the scanner has already masked their Matched fields, so no raw secret material is exposed.

func (*RedactionResidualError) Error

func (e *RedactionResidualError) Error() string

type RepoBacklog added in v0.9.0

type RepoBacklog struct {
	RootSHA string `json:"root_sha"`
	// Name is the repository's directory name from its meta.json, when the
	// store has one. It is what makes the notice actionable — "13 MB in a
	// repository whose root commit begins a1b2c3" is a riddle. Empty when the
	// repo was never registered.
	Name             string    `json:"name,omitempty"`
	Staged           int       `json:"staged"`
	StagedBytes      int64     `json:"staged_bytes"`
	Overdue          int       `json:"overdue"`
	OldestStagedAt   time.Time `json:"oldest_staged_at,omitempty"`
	Quarantined      int       `json:"quarantined"`
	QuarantinedBytes int64     `json:"quarantined_bytes"`
	// Orphaned marks a key whose recorded checkout no longer exists
	// (iss-2609091717146700): the drain needs that repository's own redaction
	// configuration, so with the checkout gone nothing will ever redact this
	// pile, and discard by root SHA is the only way it leaves. A key with no
	// recorded root, or one whose root cannot be examined, is not orphaned:
	// unknown is not gone.
	Orphaned bool `json:"orphaned,omitempty"`
}

RepoBacklog is one repository's holding of unredacted transcript text.

It is deliberately COUNTS AND SIZES and no content: the survey's whole point is that it is read from a repository other than the one it describes, and a notice that quoted another repository's session ids into this repository's session would be leaking exactly the thing the store redacts.

func SurveyBacklog added in v0.9.0

func SurveyBacklog() ([]RepoBacklog, error)

SurveyBacklog reports every repository in the store that is holding unredacted transcript text, newest-oldest by nothing — the order is by root SHA, which is stable and meaningless, so a caller that wants a ranking sorts for itself.

This exists because the store is keyed per repository and every reader of it was too: `abcd history staged` answers for the repository the operator is standing in, which is by construction a repository someone is using, and therefore one whose staged files are being drained. The pile that grows unbounded is the one in the repository nobody has opened for a fortnight, and no per-repo verb can ever see it (iss-2609090722466403).

An unreadable repository directory is SKIPPED rather than fatal: one broken key must not blind the survey to the other forty. A store that does not exist yet returns nothing and no error.

func (RepoBacklog) Total added in v0.9.0

func (b RepoBacklog) Total() int64

Total is the unredacted bytes this repository is holding, staged and quarantined alike. Both are raw; the distinction is whether anything will ever try to redact them again.

type Resolution added in v0.8.0

type Resolution struct {
	Base    string   `json:"base"`
	Records string   `json:"records"`
	Staging string   `json:"staging"`
	Local   bool     `json:"local"`
	Notes   []string `json:"notes"`
}

Resolution is where this repo's transcripts live, and what resolving it had to say out loud.

Notes is the out-of-band diagnostic channel, mirroring rules.Resolve: core never writes to stdout, so a migration it performed or a declaration it declined to honour is returned for the front door to print on stderr. A store that quietly moved a corpus, or quietly ignored an opt-in the caller wrote, would be indistinguishable from one that did neither.

func Resolve added in v0.8.0

func Resolve(repoRoot, rootSHA string) (Resolution, error)

Resolve returns this repo's store, creating it when absent, and migrating a corpus left at the legacy location into it.

It is the ONE seam every read and write path goes through, so the store can never be reached by a path that skipped the creation, the symlink discipline or the migration. It is idempotent and cheap: a resolved store is a handful of stat calls and, after the first call, a no-op migration.

Front doors call it explicitly as well, in order to PRINT Notes — the verbs below discard them, because a verb that printed would be a core package speaking to a terminal.

type SeparationReport added in v0.11.1

type SeparationReport struct {
	// Transcripts is how many records the store holds, and Stamped how many of
	// them carry at least one stamp.
	Transcripts int `json:"transcripts"`
	Stamped     int `json:"stamped"`
	// Runs is every run any stamp named, sorted, so a clean report says what it
	// examined.
	Runs       []string    `json:"runs"`
	Violations []Violation `json:"violations"`
	// Unobserved is true when there was nothing to examine, and Reason says why.
	Unobserved bool   `json:"unobserved"`
	Reason     string `json:"reason,omitempty"`
}

SeparationReport is what the check saw.

func SessionSeparation added in v0.11.1

func SessionSeparation(repoRoot, rootSHA string) (SeparationReport, error)

SessionSeparation runs the check over this repository's lane of the store. It reads record metadata through List and never opens a body for it.

func (SeparationReport) Summary added in v0.11.1

func (r SeparationReport) Summary() string

Summary is the report's one line, the same wherever it is rendered: the violations by name, or the property held with the runs seen, or the unobserved reason. It carries no path.

type StageMeta added in v0.9.0

type StageMeta struct {
	Lineage CaptureMeta
	// SourcePath is the transcript file the bytes were read from, recorded so
	// the drain can re-read it. It is never used to locate the staged bytes.
	SourcePath string
}

StageMeta is what a stage records about a transcript besides its bytes: the lineage Capture will eventually be handed, and the path the bytes came from.

Lineage is the same CaptureMeta the drain passes to Capture, so the staging sidecar and the record carry one shape and not two that can drift.

type StageResult

type StageResult struct {
	Staged Staged `json:"staged"`
	Wrote  bool   `json:"wrote"` // false when this session is already staged with identical bytes
	// Replaced is true when the session was already staged with DIFFERENT bytes
	// and that copy was replaced by this one; ReplacedBytes is the size of the
	// copy that was replaced. Both are zero on a first stage and on a no-op.
	Replaced      bool  `json:"replaced"`
	ReplacedBytes int64 `json:"replaced_bytes"`
}

StageResult reports the outcome of one stage.

func Stage

func Stage(repoRoot, rootSHA string, meta StageMeta, raw []byte) (StageResult, error)

Stage writes raw transcript bytes into the staging area without redacting them. It is the SessionEnd half of capture and must stay cheap: no scanner and no read of the store. Cost is one listing of the staging dir, at most one read of this session's own staged copy, and one write, so the hook's runtime is independent of the store's size — which is the entire point.

It is idempotent per session on CONTENT, and the whole list-compare-write runs under the staging lock so the guarantee holds across concurrent hooks (GHSA-xq36-hcgf-9wrj): a session already staged with identical bytes is a no-op (Wrote=false); a session staged with different bytes has that copy replaced at its existing path (Wrote=true, Replaced=true) — last-writer-wins, because a re-fired SessionEnd carrying different bytes is the later snapshot of the same session, and the fresher end-of-session bytes are the ones worth keeping. Either way one session has one staged file, whatever fires.

type Staged

type Staged struct {
	SessionID string    `json:"session_id"`
	StagedAt  time.Time `json:"staged_at"`
	Path      string    `json:"path"`
	Bytes     int64     `json:"bytes"`

	// Lineage, verbatim from the sidecar. All empty on a main-thread stage.
	AgentID          string `json:"agent_id,omitempty"`
	ParentAgentID    string `json:"parent_agent_id,omitempty"`
	AgentType        string `json:"agent_type,omitempty"`
	SpawnDepth       int    `json:"spawn_depth,omitempty"`
	SpawnToolUseID   string `json:"spawn_tool_use_id,omitempty"`
	LineageSource    string `json:"lineage_source,omitempty"`
	SpawnAttribution string `json:"spawn_attribution,omitempty"`

	// SourcePath is the file the staged bytes were read from. The drain re-reads
	// it, which is one of the two mitigations for a transcript staged before the
	// harness finished flushing it. Empty when the stage did not record one.
	SourcePath string `json:"source_path,omitempty"`
	// SidecarPath is the .stage.json beside Path; empty on a legacy entry.
	SidecarPath string `json:"sidecar_path,omitempty"`

	// Overdue is true once the entry has been staged longer than StagedTTL. It
	// is a REPORTING fact and a queue-ordering one, never a licence to delete:
	// the entry sorts to the front of the next drain and is named in the
	// session notices, and nothing else about it changes.
	Overdue bool `json:"overdue,omitempty"`

	// Err is set when the entry cannot be trusted — a sidecar that is present
	// but unreadable or unparseable. Such an entry is NOT drained: falling back
	// to the filename would read a sub-agent's key as a session id and file the
	// transcript under a session that does not exist. Drain reports it as a
	// failure and leaves the file alone.
	Err string `json:"error,omitempty"`
}

Staged is one raw transcript awaiting redaction.

Everything past Bytes comes from the .stage.json sidecar beside the .raw file. A staged file written by an older binary has no sidecar, so those fields are zero on it and it drains as a main-thread transcript — which is exactly what it is.

func ListStaged

func ListStaged(repoRoot, rootSHA string) ([]Staged, error)

ListStaged returns the transcripts awaiting redaction for this repo, oldest first. An absent staging dir is not an error: it means nothing is pending.

type StorePathError

type StorePathError struct {
	Path string
	Msg  string
}

StorePathError is a preflight fault: an owned store path is absent, a symlink, or otherwise unsafe. It is returned (never panicked) so the caller can surface a clean diagnostic and refuse the operation.

func (*StorePathError) Error

func (e *StorePathError) Error() string

type SubagentGapNote added in v0.9.0

type SubagentGapNote struct {
	Schema    int       `json:"schema"`
	FirstSeen time.Time `json:"first_seen"`
	LastSeen  time.Time `json:"last_seen"`
	Count     int       `json:"count"`
	Event     string    `json:"event"`
}

SubagentGapNote is the recorded fact that this harness fired SubagentStop without an agent_transcript_path. Absence of sub-agent records then has an explanation on disk instead of looking like an absence of sub-agents.

func SubagentGap added in v0.9.0

func SubagentGap(repoRoot, rootSHA string) (SubagentGapNote, bool, error)

SubagentGap reads the marker. A missing marker is not an error: it means this harness has always delivered the field, or has never fired the event.

type Telemetry added in v0.9.0

type Telemetry struct {
	SchemaVersion int    `json:"schema_version"`
	SessionID     string `json:"session_id"`
	RootCommit    string `json:"root_commit"`
	Mode          string `json:"mode"`
	// GeneratedAt is on the telemetry and NOT on the artefact, which keeps the
	// artefact deterministic: the same records reconstruct to the same bytes.
	GeneratedAt time.Time `json:"generated_at"`

	StartedAt        *time.Time `json:"started_at,omitempty"`
	EndedAt          *time.Time `json:"ended_at,omitempty"`
	WallClockSeconds float64    `json:"wall_clock_seconds"`

	Turns      TurnCounts     `json:"turns"`
	Tokens     TokenCounts    `json:"tokens"`
	ToolCalls  map[string]int `json:"tool_calls"`
	Models     []string       `json:"models"`
	AgentTypes []string       `json:"agent_types"`

	Agents       []AgentTelemetry `json:"agents"`
	Completeness Completeness     `json:"completeness"`
}

Telemetry is the machine-readable companion to the artefact.

type TokenCounts added in v0.9.0

type TokenCounts struct {
	Input              int64 `json:"input"`
	Output             int64 `json:"output"`
	CacheCreationInput int64 `json:"cache_creation_input"`
	CacheReadInput     int64 `json:"cache_read_input"`
	Total              int64 `json:"total"`
	// APIResponses is the number of DISTINCT responses counted — the
	// denominator of every per-response measure.
	APIResponses int `json:"api_responses"`
	// UsageLinesSeen is how many transcript lines carried a usage object.
	UsageLinesSeen int `json:"usage_lines_seen"`
}

TokenCounts is one agent's (or one session's) token usage.

APIResponses and UsageLinesSeen are BOTH reported, and the gap between them is the point. The harness writes one line per content block and repeats the same usage object on every line of one response, so summing lines multiplies a response's cost by its block count — measured at 2.44x on one stored transcript and 5.28x across ten. Counting one usage per distinct message id is the only correct reading, and publishing both counters is what lets a consumer verify that this file did that rather than take it on trust (iss-2609090723027424).

type TurnCounts added in v0.9.0

type TurnCounts struct {
	User      int `json:"user"`
	Assistant int `json:"assistant"`
	Total     int `json:"total"`
}

TurnCounts is the turn tally. A turn is one user message or one API response; an assistant response split across several transcript lines is ONE turn, on the same de-duplication as the tokens.

type Violation added in v0.11.1

type Violation struct {
	SessionID string `json:"session_id"`
	File      string `json:"file"`
	Run       string `json:"run"`
}

Violation is one retained transcript carrying both the reading stamp and the scribe stamp of one run, named by its session, its record file and the run. File is the record's basename, never a path.

Jump to

Keyboard shortcuts

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