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
- Variables
- func NotePendingMiss(who, reason string) error
- func NoteSessionRepo(repoRoot, rootSHA, sessionID string) error
- func NoteStageMiss(repoRoot, rootSHA, who, reason string) error
- func NoteSubagentGap(repoRoot, rootSHA, event string) error
- func ReconstructModes() []string
- func Redactor(ctx context.Context, repoRoot string) (func(text, label string) (Redacted, error), error)
- func Routes() []string
- func SessionRepo(sessionID string) (string, error)
- func TranscriptSettled(raw []byte) bool
- type AgentTelemetry
- type CaptureMeta
- type CaptureResult
- type Completeness
- type Config
- type Destination
- type DiscardResult
- type DrainBudget
- type DrainFailure
- type DrainProgress
- type DrainResult
- type DroppedRecord
- type HarnessLineage
- type IngestFailure
- type IngestOptions
- type IngestResult
- type IngestSkip
- type Ingested
- type LineageLookup
- type LineageRef
- type MigrateEntry
- type MigrateOptions
- type MigrateResult
- type Orphan
- type Pending
- type PendingMeta
- type PlaceResult
- type Placed
- type Quarantined
- type ReconstructMode
- type ReconstructOptions
- type Reconstruction
- type Record
- type Redacted
- type RedactionResidualError
- type RepoBacklog
- type RepoResolver
- type Resolution
- type SeparationReport
- type StageMeta
- type StageMissNote
- type StageResult
- type Staged
- type StorePathError
- type SubagentGapNote
- type Telemetry
- type TokenCounts
- type TokenUsage
- type TurnCounts
- type Unplaced
- type Violation
Constants ¶
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.
const ( SkipOwnedElsewhere = "owned-elsewhere" SkipAmbiguousOwner = "ambiguous-owner" SkipNoSession = "no-session-id" SkipAmbiguousAgent = "ambiguous-agent-id" // SkipOwnerUnanswered is a transcript whose recorded directory is a // repository git did not answer for: its owner is unknown, not absent, so // it is neither stored nor offered for adoption as an orphan // (iss-2610051434156079). SkipOwnerUnanswered = "owner-unanswered" )
Skip reasons. A skip is a decision, and each of these names which one.
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.
const ConfigRelPath = ".abcd/config/history.json"
ConfigRelPath is the per-repo history configuration, relative to the repo root.
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" )
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 ¶
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") )
var ErrNoRepository = errors.New("not in a repository with a root commit")
ErrNoRepository is a RepoResolver's definite answer that a directory belongs to no repository with a root commit.
Functions ¶
func NotePendingMiss ¶ added in v0.16.0
NotePendingMiss records one session transcript the session-end hook read and could not even write into the pending directory. The marker sits in that directory, since the hook has no repository to put it beside, and the next session start reports it (TakePendingMiss).
func NoteSessionRepo ¶ added in v0.9.0
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 NoteStageMiss ¶ added in v0.16.0
NoteStageMiss records one transcript that was read and could not be staged, under the marker's own lock so concurrent misses each count. who names it ("sub-agent <id>" or "session <id>"). who and reason are stored as given, apart from a bound on the reason, and every reader sanitises them before printing.
func NoteSubagentGap ¶ added in v0.9.0
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 ReconstructModes ¶ added in v0.17.0
func ReconstructModes() []string
ReconstructModes returns the two modes, the default first: the one list Reconstruct checks a mode against and `history reconstruct --mode` declares.
func Redactor ¶ added in v0.17.0
func Redactor(ctx context.Context, repoRoot string) (func(text, label string) (Redacted, error), error)
Redactor is Redact with its scanner built once, for a caller that redacts many texts of one repository in one pass (the sweep's patch salvage, file by file): each call is Redact's two stages over one text, without building the scanner again. A scanner that cannot be built, or is degraded, refuses here as Redact refuses; one that degrades part-way refuses each later call.
func Routes ¶ added in v0.17.0
func Routes() []string
Routes returns the closed route vocabulary, native first: the set validRoutes is built from and `history capture --kind` declares.
func SessionRepo ¶ added in v0.9.0
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
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
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
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 and the redacted parts a drain kept of it (resumable.go).
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.
func DiscardPending ¶ added in v0.16.0
func DiscardPending(name string) (DiscardResult, error)
DiscardPending deletes one pending transcript by its filename, with its sidecar, under the session's lock. It is the only way a pending copy no start can place leaves the disk other than placement itself, and it is as irreversible as Discard: the caller confirms first.
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 DrainProgress ¶ added in v0.17.0
type DrainProgress struct {
SessionID string `json:"session_id"`
AgentID string `json:"agent_id,omitempty"`
// Done and Total are bytes of the framed transcript: redacted and kept,
// where the next pass continues from, and in all.
Done int64 `json:"done_bytes"`
Total int64 `json:"total_bytes"`
}
DrainProgress is one staged transcript a drain pass left part-redacted.
type DrainResult ¶
type DrainResult struct {
Captured []Record `json:"captured"`
Failed []DrainFailure `json:"failed"`
Remaining int `json:"remaining"` // staged entries not attempted: budget exhausted, or the pass's context ended
// 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"`
// Unfinished names each entry the pass left part-redacted because its
// context ended: the parts it kept stay, and the next pass continues from
// them.
Unfinished []DrainProgress `json:"unfinished,omitempty"`
// KeepFault is the first fault the pass met keeping a redacted part (its
// directory refused or unwritable, the disk full), said once. The pass
// carried on in memory past it, so it costs a later pass the work it
// could not keep and never the record.
KeepFault string `json:"keep_fault,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.
func DrainContext ¶ added in v0.17.0
func DrainContext(ctx context.Context, repoRoot, rootSHA string, budget DrainBudget) (DrainResult, error)
DrainContext is Drain under ctx, the bound of the hook it runs in, which sits under the host's limit for that hook. An entry the pass begins is finished in this pass, part after part, while ctx lasts, and the first redaction part of each entry runs whatever its size and whatever ctx says (resumable.go). Once ctx has ended the pass starts no further entry and no later part: it keeps the parts it finished, names the entry in Unfinished, and the next pass continues from them. An entry whose parts no later pass could use runs to its record whatever ctx says. The budget decides which entries the pass may reach, as it did before ctx existed. Before the entries, it removes the kept parts of every staged file that is gone (sweepProgress), whether or not anything is staged, short of a file whose lock is held or a ctx that has ended.
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
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
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 Pending ¶ added in v0.16.0
type Pending struct {
SessionID string `json:"session_id"`
Cwd string `json:"cwd,omitempty"`
SourcePath string `json:"source_path,omitempty"`
StagedAt time.Time `json:"staged_at"`
Path string `json:"path"`
Bytes int64 `json:"bytes"`
// Err is set when the entry's sidecar is missing or does not parse: it
// carries no trustworthy cwd, so it is never placed.
Err string `json:"error,omitempty"`
}
Pending is one transcript awaiting placement in a store.
func ListPending ¶ added in v0.16.0
ListPending returns the transcripts awaiting placement, oldest first. A pending directory that does not exist holds nothing.
type PendingMeta ¶ added in v0.16.0
PendingMeta is what the session-end hook knows about a transcript without asking git: whose it is, where the session ran, and where the bytes came from.
type PlaceResult ¶ added in v0.16.0
type PlaceResult struct {
Placed []Placed `json:"placed"`
Unplaced []Unplaced `json:"unplaced"`
// Dropped are the sessions that ended outside any repository: no store
// noted them and git says their directory is in none. No store will ever
// take them, so their raw copies are deleted rather than kept unredacted
// forever, which is what the session-end hook did before it staged by
// session id: it captured nothing for such a session.
Dropped []Unplaced `json:"dropped"`
}
PlaceResult reports one placement pass.
func PlacePending ¶ added in v0.16.0
func PlacePending(resolve RepoResolver) (PlaceResult, error)
PlacePending files every pending transcript in its store's staging lane, where the drain redacts and stores it. The store is the one the session's note names (NoteSessionRepo, written when the session started), or else the one resolve finds from the cwd the session ended in. The note comes first because it was written while the session's directory certainly existed; a worktree removed since leaves the cwd resolving to nothing.
A pending copy is removed only once its bytes are in the lane, and only if they are still the bytes that were staged: a SessionEnd re-firing during the placement wins. A transcript no store is found for stays, and is reported.
type Placed ¶ added in v0.16.0
type Placed struct {
SessionID string `json:"session_id"`
RootSHA string `json:"root_sha"`
// Via says how the store was found: "session-note" or "cwd".
Via string `json:"via"`
}
Placed is one pending transcript filed in a store's staging lane.
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 ¶
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
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 ¶
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:
- an exact record filename — one record, named outright;
- an exact agent id — one sub-agent's transcript;
- 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 Redacted ¶ added in v0.16.0
type Redacted struct {
// Text is the redacted text, the only form a caller may keep.
Text string
// Findings are what stage one found, their Matched fields masked.
Findings []scanner.Finding
// ScanGap names coverage the repository asked for and did not get, as
// CaptureResult.ScanGap does; empty when there is none.
ScanGap string
}
Redacted is one text through the store's redaction pass.
func Redact ¶ added in v0.16.0
Redact is the store's two-stage, fail-closed redaction pass over text, the one Capture runs on a transcript and the worktree store's notes archive runs on every file and manifest field it keeps, so there is one redaction path, not two: refuse a degraded scanner; scan with repoRoot's merged scanner and its armed gitleaks augmenter; redact; sweep the caller's home and refuse a survivor; then re-scan and refuse any blocking residual. A refusal on a residual is a *RedactionResidualError. label names the text in the scanner's findings.
type RedactionResidualError ¶
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 RepoResolver ¶ added in v0.16.0
RepoResolver finds the repository a working directory belongs to: its root and its root-commit SHA. The caller supplies it, because finding a repository is git and the front door owns that. It wraps ErrNoRepository when git answered that the directory is in no repository, or in one with no commit yet: a definite answer, unlike a directory that is gone or a git that did not answer.
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 StageMissNote ¶ added in v0.16.0
type StageMissNote struct {
Schema int `json:"schema"`
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
Count int `json:"count"`
LastWho string `json:"last_who"`
LastReason string `json:"last_reason"`
// EarlierLostAt is when an unreadable marker was replaced: misses before
// it were counted there and are not in Count. Zero when none was.
EarlierLostAt time.Time `json:"earlier_lost_at,omitzero"`
}
StageMissNote is the marker: how many transcripts were read but not staged, when the first and the last were, and whose the last was (a sub-agent or a session) and why.
func StageMiss ¶ added in v0.16.0
func StageMiss(repoRoot, rootSHA string) (StageMissNote, bool, error)
StageMiss reads the marker. A missing marker is not an error: no transcript has been missed.
func TakePendingMiss ¶ added in v0.16.0
func TakePendingMiss() (StageMissNote, bool, error)
TakePendingMiss reads the pending directory's miss marker and removes it, under the marker's lock, so the misses are reported once, by the session start that reads them. A missing marker is not an error.
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.
func StagePending ¶ added in v0.16.0
func StagePending(meta PendingMeta, raw []byte) (StageResult, error)
StagePending writes a session's raw transcript into the pending directory. It runs no git and reads no store: one stat, at most one read of this session's own pending copy, and two writes.
It is idempotent on content per session, under the same per-key lock the staging lane uses: identical bytes are a no-op (Wrote=false), different bytes replace the pending copy (Replaced=true), because a re-fired SessionEnd carries the later snapshot of the same session.
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 ¶
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 ¶
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 TokenUsage ¶ added in v0.16.1
type TokenUsage struct {
Input int64 `json:"input_tokens"`
Output int64 `json:"output_tokens"`
CacheCreationInput int64 `json:"cache_creation_input_tokens"`
CacheReadInput int64 `json:"cache_read_input_tokens"`
}
TokenUsage is the token-count shape of one API response as the harness's transcript records it on an assistant line's message: the uncached input, the output, and the input written to and read from the prompt cache. It is exported for the rules loader's fill reader (spc-2610111627213138 step 5), which reads the last response's input from a transcript's tail, so the two readers of a transcript's usage parse one shape.
func (TokenUsage) ContextInput ¶ added in v0.16.1
func (u TokenUsage) ContextInput() int64
ContextInput is the whole input of the response: the uncached input and the input written to and read from the cache. The three are disjoint, and together they are what the response's request held in the context window.
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 Unplaced ¶ added in v0.16.0
type Unplaced struct {
SessionID string `json:"session_id"`
Cwd string `json:"cwd,omitempty"`
Path string `json:"path"`
Reason string `json:"reason"`
}
Unplaced is one pending transcript no store could be found for. It stays pending, unredacted, until a later start places it.
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.