types

package
v0.32.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package types defines application-layer DTOs, criteria objects, and read models shared by usecase and queryservice boundaries.

These types describe structured inputs and outputs for orchestration logic such as session summaries, handoff packs, and durable-memory views.

Index

Constants

View Source
const (
	// DefaultListEventBodyLimit caps the per-event body projection on
	// MCP list-style surfaces (list_events / search / get_context).
	// Callers pass body_limit=0 / full_body=true to opt out. The 500-
	// rune budget matches the historical default introduced in #799.
	DefaultListEventBodyLimit = 500

	// DefaultTopSnapshotBodyLimit caps recent-command and recent-failure
	// rows on `traceary top --snapshot --json` so a multi-hundred-line
	// command_executed payload does not balloon the script-friendly
	// snapshot output. The text snapshot keeps using truncateMessage for
	// tabular alignment.
	DefaultTopSnapshotBodyLimit = 500

	// DefaultHandoffRecentCommandLimit is the per-line summary cap used
	// for the handoff RECENT_COMMANDS list. The output is single-line
	// per row, so the budget is intentionally smaller than the list
	// surfaces above.
	DefaultHandoffRecentCommandLimit = 60

	// TruncationEllipsis is the marker appended to a truncated payload.
	// All operator-facing renderers use the same glyph so consumers can
	// detect truncation textually if they ignore the structured flag.
	TruncationEllipsis = "…"
)

Operator-facing recent-command renderers share the same rune-based truncation policy so a single noisy command_executed payload does not dominate either a terminal pane or an MCP context-window response. Full content is preserved in the database and remains retrievable through the explicit event detail / show surfaces, which bypass these limits.

View Source
const (
	// BackupRetentionManifestSchema identifies the digest-bound sidecar contract.
	BackupRetentionManifestSchema = "traceary.backup.retention/v1"
	// BackupRetentionManifestPrefix reserves sidecars outside capacity inventory.
	BackupRetentionManifestPrefix = ".traceary-retention-backup-"
)
View Source
const (

	// MaxReportPageSize bounds one internal database page before allocation.
	MaxReportPageSize = 100_000
)

Variables

This section is empty.

Functions

func BackupRetentionManifestName added in v0.31.0

func BackupRetentionManifestName(relativePath string) string

BackupRetentionManifestName returns the reserved sidecar name for a root-relative backup.

func DefaultActiveMemoryStatuses added in v0.5.0

func DefaultActiveMemoryStatuses() []domtypes.MemoryStatus

DefaultActiveMemoryStatuses returns the statuses included in read paths when callers do not request explicit memory statuses.

func ExtractPlainBody added in v0.8.1

func ExtractPlainBody(body string) string

ExtractPlainBody returns the flat-text projection of a body for readers that have not yet been updated to consume blocks directly. Behaviour:

  • Canonical transcript envelopes (JSON object with a "blocks" key): concatenate `text`-type block contents with "\n\n"; `thinking` blocks are excluded so memory extraction / search don't ingest internal reasoning as user-visible fact. If the envelope carries no text blocks (e.g. thinking-only) the result is an empty string — never the raw JSON envelope, which would leak reasoning to plain-text consumers.
  • Non-envelope JSON (e.g. a note body that legitimately stores `{"foo":"bar"}`): returned unchanged so domain data isn't silently discarded.
  • Legacy plain-text bodies: returned unchanged.
  • Malformed JSON: returned unchanged so the caller sees what's actually stored rather than silently losing data.

Use this at the boundary between storage and legacy consumers; prefer ParseEventBodyBlocks for new code that can render blocks.

func MarshalEventBodyBlocks added in v0.8.1

func MarshalEventBodyBlocks(blocks []EventBodyBlock) (string, error)

MarshalEventBodyBlocks serializes a block slice to the canonical JSON shape used for structured event bodies:

{"blocks":[{"type":"thinking","text":"..."},{"type":"text","text":"..."}]}

Callers that produce the blocks (hook runtime, CLI log writing transcript) use this to pin the persisted body format.

func SourceHookFromContext added in v0.8.1

func SourceHookFromContext(ctx context.Context) string

SourceHookFromContext extracts the hook-event identifier previously stored by WithSourceHook. Returns "" when none is present — the caller persists "" as NULL in the database so legacy / non-hook writes are distinguishable from hook-driven writes that simply forgot to tag.

func WithHookDelivery added in v0.31.0

func WithHookDelivery(ctx context.Context, input HookDeliveryInput) context.Context

WithHookDelivery returns a derived context carrying normalized delivery input. Empty native IDs are intentionally retained so usecases can preserve raw workspace provenance without enabling delivery deduplication.

func WithSourceHook added in v0.8.1

func WithSourceHook(ctx context.Context, name string) context.Context

WithSourceHook returns a derived context that carries the supplied hook-event identifier. Use this in hook runtime functions immediately before calling into an EventUsecase / SessionUsecase so the event written by the usecase picks up the tag.

name should be one of the stable identifiers documented on the events.source_hook migration (e.g. "stop", "session_start", "subagent_stop", "pre_compact", "after_agent"). Empty names are discarded — passing "" is equivalent to not calling WithSourceHook at all and keeps the column NULL.

Types

type AuditInput added in v0.20.0

type AuditInput struct {
	Command   string
	Input     string
	Output    string
	Client    domtypes.Client
	Agent     domtypes.Agent
	SessionID domtypes.SessionID
	Workspace domtypes.Workspace
	// ExitCode is the captured process exit code when a host provides one.
	ExitCode domtypes.Optional[int]
	// Failed marks a structural failure even when no numeric exit code is
	// available (e.g. Claude's PostToolUseFailure payload).
	Failed bool
	// FailureReason carries protocol-derived structured evidence. Its zero
	// value means unavailable; command payload text is never parsed as a reason.
	FailureReason domtypes.CommandFailureReason
}

AuditInput carries the fields the Audit usecase records for a single command / tool execution. Grouping them as a named value object keeps the Audit call safe: every field is set by name, so the attribution strings, ExitCode, and Failed flag cannot be silently transposed the way a long positional signature allowed. The redaction policy is passed separately because it is a capture policy, not audit data.

type AuditRedaction

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

AuditRedaction holds redaction and truncation settings for command audit recording.

func (AuditRedaction) AllowSecrets

func (r AuditRedaction) AllowSecrets() bool

AllowSecrets reports whether default secret redaction should be bypassed.

func (AuditRedaction) ExtraRedactPatterns

func (r AuditRedaction) ExtraRedactPatterns() []string

ExtraRedactPatterns returns additional redaction regex patterns.

func (AuditRedaction) MaxInputBytes

func (r AuditRedaction) MaxInputBytes() int

MaxInputBytes returns the maximum number of stored input bytes.

func (AuditRedaction) MaxOutputBytes

func (r AuditRedaction) MaxOutputBytes() int

MaxOutputBytes returns the maximum number of stored output bytes.

func (AuditRedaction) StructuredRules added in v0.10.0

func (r AuditRedaction) StructuredRules() []redaction.RuleConfig

StructuredRules returns configured structured redaction rules.

type AuditRedactionBuilder

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

AuditRedactionBuilder builds an AuditRedaction value.

func NewAuditRedactionBuilder

func NewAuditRedactionBuilder() *AuditRedactionBuilder

NewAuditRedactionBuilder starts building an empty AuditRedaction.

func (*AuditRedactionBuilder) AllowSecrets

func (b *AuditRedactionBuilder) AllowSecrets(allow bool) *AuditRedactionBuilder

AllowSecrets toggles whether default secret redaction is bypassed.

func (*AuditRedactionBuilder) Build

Build finalizes and returns the AuditRedaction.

func (*AuditRedactionBuilder) ExtraRedactPatterns

func (b *AuditRedactionBuilder) ExtraRedactPatterns(patterns []string) *AuditRedactionBuilder

ExtraRedactPatterns sets additional redaction regex patterns.

func (*AuditRedactionBuilder) MaxInputBytes

func (b *AuditRedactionBuilder) MaxInputBytes(n int) *AuditRedactionBuilder

MaxInputBytes sets the maximum number of stored input bytes.

func (*AuditRedactionBuilder) MaxOutputBytes

func (b *AuditRedactionBuilder) MaxOutputBytes(n int) *AuditRedactionBuilder

MaxOutputBytes sets the maximum number of stored output bytes.

func (*AuditRedactionBuilder) StructuredRules added in v0.10.0

func (b *AuditRedactionBuilder) StructuredRules(rules []redaction.RuleConfig) *AuditRedactionBuilder

StructuredRules sets structured redaction rules.

type BackupRetentionManifest added in v0.31.0

type BackupRetentionManifest struct {
	SchemaVersion string `json:"schema_version"`
	RelativePath  string `json:"relative_path"`
	BackupSHA256  string `json:"backup_sha256"`
	SourceLineage string `json:"source_lineage"`
	CreatedAt     string `json:"created_at"`
}

BackupRetentionManifest binds a backup digest to its source-store lineage.

type CandidateHygieneCounts added in v0.21.0

type CandidateHygieneCounts struct {
	// Stale counts candidates last updated before the staleness threshold.
	Stale int
	// Duplicate counts candidates that share an exact identity (same scope,
	// memory type, and fact) with another candidate in the scanned window,
	// matching the extraction dedupe key. Similarity / near-duplicate
	// detection stays in `memory admin hygiene scan`.
	Duplicate int
	// FragmentLike counts candidates whose fact looks like a diff fragment or
	// generated code (the obvious code/diff fragments that should not be
	// durable memories).
	FragmentLike int
	// ExtractedHidden counts candidates routed to the extracted-hidden source
	// by the extraction quality gate.
	ExtractedHidden int
	// LikelyActionable counts candidates flagged by none of the above.
	LikelyActionable int
}

CandidateHygieneCounts summarises the hygiene composition of durable-memory candidates within a bounded scan window. The four flag counts (Stale, Duplicate, FragmentLike, ExtractedHidden) are independent diagnostic dimensions and may overlap — a single candidate can be both stale and fragment-like, so they do not partition the candidate total. LikelyActionable is the complement: candidates flagged by none of the four, i.e. the queue an operator should actually review.

When the producing scan saturates its limit (signalled separately by the snapshot's scan_limit_reached), these counts reflect the scanned sample rather than the full backlog, mirroring the accepted/candidate totals.

type CloseStaleSessionsResult

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

CloseStaleSessionsResult is the result of a stale-session cleanup.

func CloseStaleSessionsResultOf

func CloseStaleSessionsResultOf(closedCount int) CloseStaleSessionsResult

CloseStaleSessionsResultOf creates a CloseStaleSessionsResult.

func (CloseStaleSessionsResult) ClosedCount

func (r CloseStaleSessionsResult) ClosedCount() int

ClosedCount returns the number of closed sessions.

type CodexCaptureDiagnosticCriteria added in v0.32.0

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

CodexCaptureDiagnosticCriteria scopes one complete, body-free diagnostic projection to a canonical workspace and half-open event window.

func CodexCaptureDiagnosticCriteriaOf added in v0.32.0

func CodexCaptureDiagnosticCriteriaOf(
	workspace types.Workspace,
	from, to time.Time,
) (CodexCaptureDiagnosticCriteria, error)

CodexCaptureDiagnosticCriteriaOf creates validated diagnostic criteria.

func (CodexCaptureDiagnosticCriteria) From added in v0.32.0

From returns the inclusive lower event bound.

func (CodexCaptureDiagnosticCriteria) To added in v0.32.0

To returns the exclusive upper event bound.

func (CodexCaptureDiagnosticCriteria) Workspace added in v0.32.0

Workspace returns the canonical workspace filter.

type CodexCaptureDiagnosticEvidence added in v0.32.0

type CodexCaptureDiagnosticEvidence struct {
	StoredEvents          int
	SessionStartObserved  bool
	PromptObserved        bool
	ToolObserved          bool
	CompactObserved       bool
	StopSessions          int
	StopSessionsWithUsage int
	UsageObservations     int
	UsageKnown            int
	UsageUnavailable      int
}

CodexCaptureDiagnosticEvidence is the complete body-free projection consumed by doctor. Session identities and event bodies never cross this boundary.

type CodexImportCriteria added in v0.7.0

type CodexImportCriteria struct {
	Root              string
	WorkspaceFallback domtypes.Workspace
}

CodexImportCriteria carries the inputs for a Codex MEMORY.md import run. WorkspaceFallback is applied only when the source file does not declare a more specific `applies_to: cwd=...` hint, so an explicit --workspace flag never overrides host-supplied provenance.

type CollectGarbageResult

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

CollectGarbageResult is the result of a garbage-collection run.

func CollectGarbageResultOf

func CollectGarbageResultOf(deletedCount int, before time.Time, dryRun bool) CollectGarbageResult

CollectGarbageResultOf creates a CollectGarbageResult.

func (CollectGarbageResult) Before

func (r CollectGarbageResult) Before() time.Time

Before returns the threshold used for the deletion.

func (CollectGarbageResult) DeletedCount

func (r CollectGarbageResult) DeletedCount() int

DeletedCount returns the number of deleted events.

func (CollectGarbageResult) DryRun

func (r CollectGarbageResult) DryRun() bool

DryRun reports whether the run was a dry run.

type CommandAuditMetadata added in v0.31.0

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

CommandAuditMetadata contains body-free command outcome facts.

func CommandAuditMetadataOf added in v0.31.0

func CommandAuditMetadataOf(exitCode domtypes.Optional[int], failed bool) CommandAuditMetadata

CommandAuditMetadataOf creates command outcome metadata.

func (CommandAuditMetadata) ExitCode added in v0.31.0

func (m CommandAuditMetadata) ExitCode() domtypes.Optional[int]

ExitCode returns the recorded command exit code when present.

func (CommandAuditMetadata) Failed added in v0.31.0

func (m CommandAuditMetadata) Failed() bool

Failed reports a structural or recorded command failure.

type CommandPayloadTruncation added in v0.16.0

type CommandPayloadTruncation struct {
	Body              string
	Truncated         bool
	OriginalRuneCount int
	OriginalByteCount int
}

CommandPayloadTruncation carries the result of applying the shared truncation policy to a recent-command body. Callers attach Truncated and OriginalRuneCount / OriginalByteCount to JSON shapes so consumers can tell that the value has been cut and can fetch the full event via explicit detail lookups.

func TruncateCommandPayload added in v0.16.0

func TruncateCommandPayload(body string, limit int) CommandPayloadTruncation

TruncateCommandPayload applies the shared rune-based truncation policy. A non-positive limit disables truncation entirely; the original body is returned with Truncated=false but the original counts are still populated so callers can record size metadata even when no cut occurred.

type ContentEventDedupeGroup added in v0.21.3

type ContentEventDedupeGroup struct {
	KeptEventID       string
	DuplicateEventIDs []string
	Kind              string
	Agent             string
	SourceHook        string
	// GroupKey is the forensic identity key (kind|client|agent|session|workspace|hook|body-hash).
	GroupKey string
}

ContentEventDedupeGroup is one duplicate group the dedupe run selected. The kept row is the canonical survivor (earliest parsed created_at, tie-broken by event id); every DuplicateEventID is a row that `--apply` quarantines.

func (ContentEventDedupeGroup) DuplicateCount added in v0.21.3

func (g ContentEventDedupeGroup) DuplicateCount() int

DuplicateCount returns the number of rows that would be (or were) quarantined for this group.

type ContentEventDedupeParams added in v0.21.3

type ContentEventDedupeParams struct {
	// Agent restricts the scan to events with this agent (e.g. "codex"). Empty
	// means every agent participates.
	Agent string
	// Apply moves duplicate rows into the quarantine archive. When false the run
	// reports candidates only and never mutates the store.
	Apply bool
	// Strict reports every exact duplicate group regardless of time gap. The
	// default clusters by the 10s proximity window (mirroring the
	// content-event-reliability doctor check) so only near-simultaneous (likely
	// hook double-write) groups are eligible.
	Strict bool
	// MaxScanRows bounds body materialization for diagnostic dry-runs. Zero
	// preserves the maintenance command's full-scan behavior. A positive bound
	// is invalid when Apply is true so cleanup can never mutate a partial view.
	MaxScanRows int
	// RunID identifies the apply run; it is recorded on every archived row so
	// `--restore <run-id>` can reverse exactly this run. Required when Apply is
	// true and ignored otherwise.
	RunID string
	// Now stamps archived_at. Required when Apply is true and ignored otherwise.
	Now time.Time
}

ContentEventDedupeParams configures a single content-event dedupe maintenance run (`traceary store dedupe content-events`).

The maintenance path targets only historical hook-originated prompt/transcript duplicates. Callers select a scope by Agent (the CLI surface exposes this as `--client codex`, but duplicates are written with events.client="hook", so the store-side filter is by agent). Apply gates the only data-mutating behavior: when false the run is a pure dry-run and never writes.

type ContentEventDedupeRestoreResult added in v0.21.3

type ContentEventDedupeRestoreResult struct {
	RunID         string
	RestoredCount int
}

ContentEventDedupeRestoreResult is the outcome of restoring a quarantine run.

type ContentEventDedupeResult added in v0.21.3

type ContentEventDedupeResult struct {
	RunID              string
	Applied            bool
	TotalEligibleCount int
	ScannedCount       int
	Groups             []ContentEventDedupeGroup
	Skipped            []ContentEventDedupeSkip
	Sources            []ContentEventDedupeSourceStat
}

ContentEventDedupeResult is the outcome of a dedupe run (dry-run or apply).

func (ContentEventDedupeResult) MovedCount added in v0.21.3

func (r ContentEventDedupeResult) MovedCount() int

MovedCount returns the total number of duplicate rows across all groups (the number of rows quarantined on apply, or that would be on dry-run).

type ContentEventDedupeSkip added in v0.21.3

type ContentEventDedupeSkip struct {
	GroupKey string
	EventIDs []string
	Reason   string
}

ContentEventDedupeSkip records a duplicate group skipped because at least one member carried a malformed timestamp or the ordering was otherwise ambiguous, so a canonical row could not be chosen safely. Skipped groups are never mutated; they are reported for operator follow-up.

type ContentEventDedupeSourceStat added in v0.31.0

type ContentEventDedupeSourceStat struct {
	Agent          string  `json:"agent"`
	SourceHook     string  `json:"source_hook"`
	ScannedCount   int     `json:"scanned_count"`
	GroupCount     int     `json:"group_count"`
	CandidateCount int     `json:"candidate_count"`
	CandidateRate  float64 `json:"candidate_rate"`
}

ContentEventDedupeSourceStat keeps heuristic candidate measurement separate from proven stable-ID redelivery metrics.

type ContextPack added in v0.5.0

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

ContextPack is the structured working-memory bundle shared by CLI and MCP handoff surfaces.

func ContextPackOf added in v0.5.0

func ContextPackOf(
	sessionID domtypes.SessionID,
	workspace domtypes.Workspace,
	label string,
	status string,
	totalEvents int,
	commandCount int,
	agents []string,
	workingState WorkingState,
	recentCommands []string,
	memories []MemorySummary,
) ContextPack

ContextPackOf creates a ContextPack.

func (ContextPack) AcceptedMemoryCount added in v0.16.0

func (c ContextPack) AcceptedMemoryCount() int

AcceptedMemoryCount returns the number of trusted accepted memories represented by the pack. For query-built packs this count reflects the accepted rows loaded under the context-pack limit.

func (ContextPack) Agents added in v0.5.0

func (c ContextPack) Agents() []string

Agents returns the participating agents.

func (ContextPack) CandidateMemoryCount added in v0.16.0

func (c ContextPack) CandidateMemoryCount() int

CandidateMemoryCount returns the number of candidate rows observed under the context-pack limit. Candidate facts are only included in MemoryNeedsReview when IncludeMemoryCandidates was requested.

func (ContextPack) CommandCount added in v0.5.0

func (c ContextPack) CommandCount() int

CommandCount returns the total number of command events in the session.

func (ContextPack) Label added in v0.5.0

func (c ContextPack) Label() string

Label returns the session label.

func (ContextPack) Memories added in v0.5.0

func (c ContextPack) Memories() []MemorySummary

Memories returns accepted durable memories relevant to the pack.

func (ContextPack) MemoryNeedsReview added in v0.16.0

func (c ContextPack) MemoryNeedsReview() []MemorySummary

MemoryNeedsReview returns candidate durable memories that were explicitly included for review. They are intentionally separate from Memories so host contexts do not treat unaccepted facts as trusted.

func (ContextPack) RecentCommandItems added in v0.31.0

func (c ContextPack) RecentCommandItems() []RecentCommandSummary

RecentCommandItems returns structured recent-command projections.

func (ContextPack) RecentCommands added in v0.5.0

func (c ContextPack) RecentCommands() []string

RecentCommands returns recent command summaries.

func (ContextPack) RequestedWorkspace added in v0.16.0

func (c ContextPack) RequestedWorkspace() domtypes.Workspace

RequestedWorkspace returns the workspace the caller asked for, which may differ from the matched session workspace when parent fallback was applied. Returns an empty workspace when the caller did not request any specific workspace.

func (ContextPack) SessionID added in v0.5.0

func (c ContextPack) SessionID() domtypes.SessionID

SessionID returns the session ID.

func (ContextPack) Status added in v0.5.0

func (c ContextPack) Status() string

Status returns the session status.

func (ContextPack) TotalEvents added in v0.5.0

func (c ContextPack) TotalEvents() int

TotalEvents returns the total number of events in the session.

func (ContextPack) WithMemoryCounts added in v0.16.0

func (c ContextPack) WithMemoryCounts(acceptedCount int, candidateCount int) ContextPack

WithMemoryCounts returns a copy of the pack with explicit trust counters. This is used by query-built packs to expose accepted and candidate counts even when candidates are intentionally omitted.

func (ContextPack) WithMemoryNeedsReview added in v0.16.0

func (c ContextPack) WithMemoryNeedsReview(candidates []MemorySummary, candidateCount int) ContextPack

WithMemoryNeedsReview returns a copy of the pack with the candidate review section and candidate count populated.

func (ContextPack) WithRecentCommandItems added in v0.31.0

func (c ContextPack) WithRecentCommandItems(items []RecentCommandSummary) ContextPack

WithRecentCommandItems returns a copy with structured recent-command projections. The legacy RecentCommands list remains unchanged.

func (ContextPack) WithRequestedWorkspace added in v0.16.0

func (c ContextPack) WithRequestedWorkspace(requested domtypes.Workspace) ContextPack

WithRequestedWorkspace returns a copy of the pack with the originally requested workspace recorded. When the requested value differs from the matched session workspace, callers can surface a parent-fallback hint via WorkspaceFallbackUsed.

func (ContextPack) WorkingState added in v0.5.0

func (c ContextPack) WorkingState() WorkingState

WorkingState returns the structured working-memory state.

func (ContextPack) Workspace added in v0.5.0

func (c ContextPack) Workspace() domtypes.Workspace

Workspace returns the workspace.

func (ContextPack) WorkspaceFallbackUsed added in v0.16.0

func (c ContextPack) WorkspaceFallbackUsed() bool

WorkspaceFallbackUsed reports whether the pack was assembled by walking up to a parent workspace because no session existed under the requested one.

type ContextPackCriteria added in v0.5.0

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

ContextPackCriteria describes how to assemble a structured handoff pack.

func (ContextPackCriteria) AllowStale added in v0.16.0

func (c ContextPackCriteria) AllowStale() bool

AllowStale reports whether stale active sessions are eligible for selection. Defaults to false so the handoff does not silently surface an abandoned session as the current working context.

func (ContextPackCriteria) IncludeMemoryCandidates added in v0.16.0

func (c ContextPackCriteria) IncludeMemoryCandidates() bool

IncludeMemoryCandidates reports whether candidate durable memories should be included in the review-oriented section of a context pack. Defaults to false so handoff / MCP context treat only accepted durable memories as trusted.

func (ContextPackCriteria) MemoryAsOf added in v0.8.0

func (c ContextPackCriteria) MemoryAsOf() domtypes.Optional[time.Time]

MemoryAsOf returns the point-in-time at which content validity should be evaluated when loading durable memories for the pack. A present value lets an operator time-travel handoff / memory_pack to "what was valid at time T" instead of "what is valid now". None (the default) evaluates validity against the current time.

func (ContextPackCriteria) MemoryLimit added in v0.5.0

func (c ContextPackCriteria) MemoryLimit() int

MemoryLimit returns the maximum number of durable memories to include.

func (ContextPackCriteria) MemoryPreset added in v0.8.0

func (c ContextPackCriteria) MemoryPreset() MemoryRetrievalPreset

MemoryPreset returns the retrieval preset to apply when loading durable memories for the pack. Empty means "no preset — use the default accepted-only behavior of the memory query path."

func (ContextPackCriteria) RecentCommandsLimit added in v0.5.0

func (c ContextPackCriteria) RecentCommandsLimit() int

RecentCommandsLimit returns the maximum number of recent commands to include.

func (ContextPackCriteria) SessionID added in v0.5.0

func (c ContextPackCriteria) SessionID() domtypes.SessionID

SessionID returns the target session filter.

func (ContextPackCriteria) StaleAfter added in v0.16.0

func (c ContextPackCriteria) StaleAfter() time.Duration

StaleAfter returns the duration after which an unended session is treated as stale. A zero or negative value disables the stale check (matching the historical behavior of the builder).

func (ContextPackCriteria) Workspace added in v0.5.0

func (c ContextPackCriteria) Workspace() domtypes.Workspace

Workspace returns the target workspace filter.

type ContextPackCriteriaBuilder added in v0.5.0

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

ContextPackCriteriaBuilder builds a ContextPackCriteria value.

func NewContextPackCriteriaBuilder added in v0.5.0

func NewContextPackCriteriaBuilder() *ContextPackCriteriaBuilder

NewContextPackCriteriaBuilder starts building a ContextPackCriteria with sensible defaults for command and memory limits.

func (*ContextPackCriteriaBuilder) AllowStale added in v0.16.0

AllowStale opts the caller in to stale active sessions. When false (the default), the builder skips a session whose start is older than StaleAfter so the handoff does not silently surface an abandoned session as the current working context.

func (*ContextPackCriteriaBuilder) Build added in v0.5.0

Build finalizes and returns the criteria.

func (*ContextPackCriteriaBuilder) IncludeMemoryCandidates added in v0.16.0

func (b *ContextPackCriteriaBuilder) IncludeMemoryCandidates(include bool) *ContextPackCriteriaBuilder

IncludeMemoryCandidates opts in to including candidate memories in a separate review-oriented section. Candidate backlog counts can still be populated when this is false, but candidate facts are not mixed into the trusted memory section.

func (*ContextPackCriteriaBuilder) MemoryAsOf added in v0.8.0

MemoryAsOf sets the as-of timestamp used when filtering memory validity windows. Callers pass domtypes.None[time.Time]() to clear any previously-set value and evaluate validity against "now".

func (*ContextPackCriteriaBuilder) MemoryLimit added in v0.5.0

MemoryLimit sets the durable memory limit.

func (*ContextPackCriteriaBuilder) MemoryPreset added in v0.8.0

MemoryPreset sets the retrieval preset used to pre-populate the durable-memory filters for the pack.

func (*ContextPackCriteriaBuilder) RecentCommandsLimit added in v0.5.0

func (b *ContextPackCriteriaBuilder) RecentCommandsLimit(limit int) *ContextPackCriteriaBuilder

RecentCommandsLimit sets the recent command limit.

func (*ContextPackCriteriaBuilder) SessionID added in v0.5.0

SessionID sets the target session ID.

func (*ContextPackCriteriaBuilder) StaleAfter added in v0.16.0

StaleAfter sets the duration after which an unended session is treated as stale. A zero or negative value disables the stale check.

func (*ContextPackCriteriaBuilder) Workspace added in v0.5.0

Workspace sets the target workspace.

type EventBodyBlock added in v0.8.1

type EventBodyBlock struct {
	Type EventBodyBlockType `json:"type"`
	Text string             `json:"text"`
}

EventBodyBlock is one element of a structured event body.

func DecodeCanonicalEnvelope added in v0.8.2

func DecodeCanonicalEnvelope(body string) ([]EventBodyBlock, bool)

DecodeCanonicalEnvelope is the exported form of decodeCanonicalEnvelope. Callers that need to render block-structured output (for example MCP tools that want to expose thinking vs text separately) can use it to decide whether a body is a canonical envelope worth serialising as blocks — returning ok=false means "fall back to the raw body / plain-text projection".

func ParseEventBodyBlocks added in v0.8.1

func ParseEventBodyBlocks(body string) []EventBodyBlock

ParseEventBodyBlocks returns the structured blocks encoded in body if it is JSON-shaped, and falls back to a single synthetic text block carrying the raw body for legacy rows (v0.8.0 and earlier) that predate #662. New code paths should always call this helper instead of inspecting body directly so legacy + new rows behave the same.

type EventBodyBlockType added in v0.8.1

type EventBodyBlockType string

EventBodyBlockType is the stable vocabulary for block types in a structured event body (transcript / prompt). Unknown types are preserved round-trip but downstream filters may skip them.

const (
	// EventBodyBlockTypeThinking marks a block that carries the
	// assistant's internal reasoning (Claude Code "thinking" blocks,
	// extended-thinking output). Downstream consumers like memory
	// extraction usually skip these to avoid ingesting reasoning as
	// durable facts.
	EventBodyBlockTypeThinking EventBodyBlockType = "thinking"
	// EventBodyBlockTypeText marks a user-visible block — the
	// assistant's rendered reply, or the user's prompt. Readers that
	// want "what the human saw" look at text blocks only.
	EventBodyBlockTypeText EventBodyBlockType = "text"
)

type EventBodyBlocks added in v0.8.1

type EventBodyBlocks struct {
	Blocks []EventBodyBlock `json:"blocks"`
}

EventBodyBlocks wraps a slice so JSON encoding can stay forward compatible (new sibling fields can be added without breaking existing consumers).

type EventBodyExtent added in v0.31.0

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

EventBodyExtent describes persisted event-body size and truncation facts. Unknown facts remain absent instead of being represented as zero or false.

func EventBodyExtentOf added in v0.31.0

func EventBodyExtentOf(
	originalBytes domtypes.Optional[int],
	storedBytes int,
	ingestTruncated domtypes.Optional[bool],
	storageTruncated domtypes.Optional[bool],
	bodyMetadataVersion domtypes.Optional[int],
) (EventBodyExtent, error)

EventBodyExtentOf creates persisted event-body extent metadata.

func (EventBodyExtent) BodyMetadataVersion added in v0.31.0

func (e EventBodyExtent) BodyMetadataVersion() domtypes.Optional[int]

BodyMetadataVersion returns the internal extraction version when known.

func (EventBodyExtent) IngestTruncated added in v0.31.0

func (e EventBodyExtent) IngestTruncated() domtypes.Optional[bool]

IngestTruncated reports known ingestion truncation.

func (EventBodyExtent) OriginalBytes added in v0.31.0

func (e EventBodyExtent) OriginalBytes() domtypes.Optional[int]

OriginalBytes returns the original payload size when the ingest path knew it.

func (EventBodyExtent) StorageTruncated added in v0.31.0

func (e EventBodyExtent) StorageTruncated() domtypes.Optional[bool]

StorageTruncated reports known storage-policy truncation.

func (EventBodyExtent) StoredBytes added in v0.31.0

func (e EventBodyExtent) StoredBytes() int

StoredBytes returns the persisted UTF-8 byte count.

type EventBodyPreview added in v0.31.0

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

EventBodyPreview is a bounded content read model for summary-producing surfaces. It never contains more body runes than the query's preview limit.

func EventBodyPreviewOf added in v0.31.0

func EventBodyPreviewOf(
	eventID domtypes.EventID,
	body string,
	storedBytes int,
	originalBytes domtypes.Optional[int],
	ingestTruncated domtypes.Optional[bool],
	storageTruncated domtypes.Optional[bool],
	createdAt time.Time,
) (EventBodyPreview, error)

EventBodyPreviewOf creates a bounded event-body preview.

func (EventBodyPreview) Body added in v0.31.0

func (p EventBodyPreview) Body() string

Body returns the bounded body prefix.

func (EventBodyPreview) CreatedAt added in v0.31.0

func (p EventBodyPreview) CreatedAt() time.Time

CreatedAt returns the event timestamp.

func (EventBodyPreview) EventID added in v0.31.0

func (p EventBodyPreview) EventID() domtypes.EventID

EventID returns the event identity.

func (EventBodyPreview) IngestTruncated added in v0.31.0

func (p EventBodyPreview) IngestTruncated() domtypes.Optional[bool]

IngestTruncated reports known ingestion truncation.

func (EventBodyPreview) OriginalBytes added in v0.31.0

func (p EventBodyPreview) OriginalBytes() domtypes.Optional[int]

OriginalBytes returns the original payload size when known.

func (EventBodyPreview) StorageTruncated added in v0.31.0

func (p EventBodyPreview) StorageTruncated() domtypes.Optional[bool]

StorageTruncated reports known storage-policy truncation.

func (EventBodyPreview) StoredBytes added in v0.31.0

func (p EventBodyPreview) StoredBytes() int

StoredBytes returns the persisted UTF-8 byte count.

type EventContextCriteria

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

EventContextCriteria holds filter parameters for context event retrieval. Zero-value fields are ignored (no filter applied).

func (EventContextCriteria) Agent

Agent returns the agent filter.

func (EventContextCriteria) Client

Client returns the client filter.

func (EventContextCriteria) Limit

func (c EventContextCriteria) Limit() int

Limit returns the maximum number of events to return.

func (EventContextCriteria) SessionID

func (c EventContextCriteria) SessionID() domtypes.SessionID

SessionID returns the session ID filter.

func (EventContextCriteria) Workspace

func (c EventContextCriteria) Workspace() domtypes.Workspace

Workspace returns the workspace filter.

type EventContextCriteriaBuilder

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

EventContextCriteriaBuilder builds an EventContextCriteria value.

func NewEventContextCriteriaBuilder

func NewEventContextCriteriaBuilder(limit int) *EventContextCriteriaBuilder

NewEventContextCriteriaBuilder starts building with the given limit. Limit is required; other fields are optional.

func (*EventContextCriteriaBuilder) Agent

Agent sets the agent filter.

func (*EventContextCriteriaBuilder) Build

Build finalizes and returns the EventContextCriteria.

func (*EventContextCriteriaBuilder) Client

Client sets the client filter.

func (*EventContextCriteriaBuilder) SessionID

SessionID sets the session ID filter.

func (*EventContextCriteriaBuilder) Workspace

Workspace sets the workspace filter.

type EventDetails

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

EventDetails pairs an Event with its optional CommandAudit.

func EventDetailsOf

func EventDetailsOf(event *model.Event, commandAudit domtypes.Optional[*model.CommandAudit]) (EventDetails, error)

EventDetailsOf creates an EventDetails value.

func (EventDetails) CommandAudit

func (d EventDetails) CommandAudit() domtypes.Optional[*model.CommandAudit]

CommandAudit returns the linked command audit.

func (EventDetails) Event

func (d EventDetails) Event() *model.Event

Event returns the event.

type EventListCriteria

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

EventListCriteria holds filter parameters for event listing. Zero-value fields are ignored (no filter applied).

Time range semantics (documented here so callers can reason about cursor advancement without reading the SQL): From is inclusive and To is exclusive. i.e. events with created_at == From are returned, events with created_at == To are not. Tail-style cursors that poll repeatedly with From set to the last seen timestamp must therefore dedupe returned events against an already-seen set at the boundary.

func (EventListCriteria) Agent

func (c EventListCriteria) Agent() domtypes.Agent

Agent returns the agent filter.

func (EventListCriteria) Client

func (c EventListCriteria) Client() domtypes.Client

Client returns the client filter.

func (EventListCriteria) FailuresOnly

func (c EventListCriteria) FailuresOnly() bool

FailuresOnly reports whether only failed commands should be returned.

func (EventListCriteria) From

func (c EventListCriteria) From() time.Time

From returns the lower bound of the time range (inclusive).

func (EventListCriteria) Kind

Kind returns the event kind filter.

func (EventListCriteria) Limit

func (c EventListCriteria) Limit() int

Limit returns the maximum number of results to return.

func (EventListCriteria) Offset

func (c EventListCriteria) Offset() int

Offset returns the number of results to skip before returning matches.

func (EventListCriteria) SessionID

func (c EventListCriteria) SessionID() domtypes.SessionID

SessionID returns the session ID filter.

func (EventListCriteria) SourceHook added in v0.8.1

func (c EventListCriteria) SourceHook() string

SourceHook returns the source-hook filter (empty string means no filter). Callers match events that were stamped with this hook identifier by the hook runtime (e.g. "stop", "subagent_stop", "pre_compact"). Matching includes a legacy body-prefix fallback while pre-#672 rows still exist.

func (EventListCriteria) To

func (c EventListCriteria) To() time.Time

To returns the upper bound of the time range (exclusive).

func (EventListCriteria) Workspace

func (c EventListCriteria) Workspace() domtypes.Workspace

Workspace returns the workspace filter.

type EventListCriteriaBuilder

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

EventListCriteriaBuilder builds an EventListCriteria value.

func NewEventListCriteriaBuilder

func NewEventListCriteriaBuilder(limit int) *EventListCriteriaBuilder

NewEventListCriteriaBuilder starts building with the given limit. Limit is required; other fields are optional.

func (*EventListCriteriaBuilder) Agent

Agent sets the agent filter.

func (*EventListCriteriaBuilder) Build

Build finalizes and returns the EventListCriteria.

func (*EventListCriteriaBuilder) Client

Client sets the client filter.

func (*EventListCriteriaBuilder) FailuresOnly

func (b *EventListCriteriaBuilder) FailuresOnly(failuresOnly bool) *EventListCriteriaBuilder

FailuresOnly restricts results to failed commands when set to true.

func (*EventListCriteriaBuilder) From

From sets the lower bound of the time range (inclusive).

func (*EventListCriteriaBuilder) Kind

Kind sets the event kind filter.

func (*EventListCriteriaBuilder) Offset

Offset sets the number of results to skip before returning matches.

func (*EventListCriteriaBuilder) SessionID

SessionID sets the session ID filter.

func (*EventListCriteriaBuilder) SourceHook added in v0.8.1

func (b *EventListCriteriaBuilder) SourceHook(sourceHook string) *EventListCriteriaBuilder

SourceHook sets the source-hook filter; empty string clears the filter.

func (*EventListCriteriaBuilder) To

To sets the upper bound of the time range (exclusive).

func (*EventListCriteriaBuilder) Workspace

Workspace sets the workspace filter.

type EventMetadata added in v0.31.0

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

EventMetadata is a body-free read model for event inspection surfaces.

func EventMetadataOf added in v0.31.0

func EventMetadataOf(
	eventID domtypes.EventID,
	kind domtypes.EventKind,
	client domtypes.Client,
	agent domtypes.Agent,
	sessionID domtypes.SessionID,
	workspace domtypes.Workspace,
	sourceHook string,
	createdAt time.Time,
	bodyExtent EventBodyExtent,
	commandAudit domtypes.Optional[CommandAuditMetadata],
) (EventMetadata, error)

EventMetadataOf creates a body-free event read model.

func (EventMetadata) Agent added in v0.31.0

func (m EventMetadata) Agent() domtypes.Agent

Agent returns the event agent.

func (EventMetadata) BodyExtent added in v0.31.0

func (m EventMetadata) BodyExtent() EventBodyExtent

BodyExtent returns persisted body size and truncation facts.

func (EventMetadata) Client added in v0.31.0

func (m EventMetadata) Client() domtypes.Client

Client returns the event client.

func (EventMetadata) CommandAudit added in v0.31.0

CommandAudit returns body-free command outcome metadata when linked.

func (EventMetadata) CreatedAt added in v0.31.0

func (m EventMetadata) CreatedAt() time.Time

CreatedAt returns the event timestamp.

func (EventMetadata) EventID added in v0.31.0

func (m EventMetadata) EventID() domtypes.EventID

EventID returns the event identity.

func (EventMetadata) Kind added in v0.31.0

func (m EventMetadata) Kind() domtypes.EventKind

Kind returns the event kind.

func (EventMetadata) SessionID added in v0.31.0

func (m EventMetadata) SessionID() domtypes.SessionID

SessionID returns the session identity.

func (EventMetadata) SourceHook added in v0.31.0

func (m EventMetadata) SourceHook() string

SourceHook returns the source hook attribution.

func (EventMetadata) Workspace added in v0.31.0

func (m EventMetadata) Workspace() domtypes.Workspace

Workspace returns the event workspace.

type EventProjection added in v0.31.0

type EventProjection string

EventProjection selects how much stored event content a read surface may materialize. The zero value preserves each presentation adapter's legacy body-limit behavior.

const (
	// EventProjectionLegacy delegates projection selection to compatibility
	// flags such as body_limit and full_body.
	EventProjectionLegacy EventProjection = ""
	// EventProjectionMetadata returns event metadata without stored body text.
	EventProjectionMetadata EventProjection = "metadata"
	// EventProjectionBounded returns stored body text under a response limit.
	EventProjectionBounded EventProjection = "bounded"
	// EventProjectionFull returns the full stored body.
	EventProjectionFull EventProjection = "full"
)

func EventProjectionFrom added in v0.31.0

func EventProjectionFrom(value string) (EventProjection, error)

EventProjectionFrom parses an optional public projection name.

type EventSearchCriteria

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

EventSearchCriteria holds filter parameters for full-text event search. Zero-value fields are ignored (no filter applied).

func (EventSearchCriteria) Agent

Agent returns the agent filter.

func (EventSearchCriteria) Client

func (c EventSearchCriteria) Client() domtypes.Client

Client returns the client filter.

func (EventSearchCriteria) FailuresOnly

func (c EventSearchCriteria) FailuresOnly() bool

FailuresOnly reports whether only failed commands should be returned.

func (EventSearchCriteria) From

func (c EventSearchCriteria) From() time.Time

From returns the lower bound of the time range (inclusive).

func (EventSearchCriteria) Kind

Kind returns the event kind filter.

func (EventSearchCriteria) Limit

func (c EventSearchCriteria) Limit() int

Limit returns the maximum number of results to return.

func (EventSearchCriteria) Offset

func (c EventSearchCriteria) Offset() int

Offset returns the number of results to skip before returning matches.

func (EventSearchCriteria) Query

func (c EventSearchCriteria) Query() string

Query returns the search query string.

func (EventSearchCriteria) SessionID

func (c EventSearchCriteria) SessionID() domtypes.SessionID

SessionID returns the session ID filter.

func (EventSearchCriteria) To

func (c EventSearchCriteria) To() time.Time

To returns the upper bound of the time range (exclusive).

func (EventSearchCriteria) Workspace

func (c EventSearchCriteria) Workspace() domtypes.Workspace

Workspace returns the workspace filter.

type EventSearchCriteriaBuilder

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

EventSearchCriteriaBuilder builds an EventSearchCriteria value.

func NewEventSearchCriteriaBuilder

func NewEventSearchCriteriaBuilder(limit int) *EventSearchCriteriaBuilder

NewEventSearchCriteriaBuilder starts building with the given limit. Limit is required; other fields are optional.

func (*EventSearchCriteriaBuilder) Agent

Agent sets the agent filter.

func (*EventSearchCriteriaBuilder) Build

Build finalizes and returns the EventSearchCriteria.

func (*EventSearchCriteriaBuilder) Client

Client sets the client filter.

func (*EventSearchCriteriaBuilder) FailuresOnly

func (b *EventSearchCriteriaBuilder) FailuresOnly(failuresOnly bool) *EventSearchCriteriaBuilder

FailuresOnly restricts results to failed commands when set to true.

func (*EventSearchCriteriaBuilder) From

From sets the lower bound of the time range (inclusive).

func (*EventSearchCriteriaBuilder) Kind

Kind sets the event kind filter.

func (*EventSearchCriteriaBuilder) Offset

Offset sets the number of results to skip before returning matches.

func (*EventSearchCriteriaBuilder) Query

Query sets the search query string.

func (*EventSearchCriteriaBuilder) SessionID

SessionID sets the session ID filter.

func (*EventSearchCriteriaBuilder) To

To sets the upper bound of the time range (exclusive).

func (*EventSearchCriteriaBuilder) Workspace

Workspace sets the workspace filter.

type FileRetentionApplyResult added in v0.31.0

type FileRetentionApplyResult struct {
	PlanID           string
	CandidateCount   int
	DeletedCount     int
	AlreadyCommitted int
	ConflictedCount  int
}

FileRetentionApplyResult reports idempotent execution outcomes.

type FileRetentionBatchPlan added in v0.31.0

type FileRetentionBatchPlan struct {
	Ordinal  string `json:"ordinal"`
	Identity string `json:"identity"`
}

FileRetentionBatchPlan enforces one durable batch per candidate.

type FileRetentionBudgetInput added in v0.31.0

type FileRetentionBudgetInput struct {
	MaxAge            *time.Duration
	MaxCount          *int
	MaxAllocatedBytes *int64
}

FileRetentionBudgetInput configures optional class-specific ceilings.

type FileRetentionBudgetPlan added in v0.31.0

type FileRetentionBudgetPlan struct {
	MaxAgeSeconds    string `json:"max_age_seconds,omitempty"`
	MaxCount         string `json:"max_count,omitempty"`
	MaxAllocatedByte string `json:"max_allocated_bytes,omitempty"`
}

FileRetentionBudgetPlan is a canonical string representation of optional ceilings.

type FileRetentionCandidatePlan added in v0.31.0

type FileRetentionCandidatePlan struct {
	Identity     string   `json:"identity"`
	RelativePath string   `json:"relative_path"`
	Reasons      []string `json:"reasons"`
}

FileRetentionCandidatePlan is one exact ordered deletion intent.

type FileRetentionCanonicalPayload added in v0.31.0

type FileRetentionCanonicalPayload struct {
	SchemaVersion string                   `json:"schema_version"`
	CreatedAt     string                   `json:"created_at"`
	ExpiresAt     string                   `json:"expires_at"`
	DatabasePath  string                   `json:"database_path"`
	Classes       []FileRetentionClassPlan `json:"classes"`
}

FileRetentionCanonicalPayload is the hash-covered file-retention-plan/v1 contract.

type FileRetentionCapacityRequest added in v0.31.0

type FileRetentionCapacityRequest struct {
	DatabasePath string
	Classes      []FileRetentionInventoryRequest
}

FileRetentionCapacityRequest selects read-only roots for operational status.

type FileRetentionCapacityStatus added in v0.31.0

type FileRetentionCapacityStatus struct {
	Class             string
	Root              string
	State             string
	FileCount         int
	VerifiedCount     int
	UnverifiedCount   int
	BlockingCount     int
	LogicalBytes      int64
	LogicalOverflow   bool
	AllocatedBytes    int64
	AllocatedKnown    bool
	AllocatedOverflow bool
	FloorRelativePath string
	RootAccess        FileRetentionRootAccessEvidence
}

FileRetentionCapacityStatus summarizes one verified inventory without creating an apply plan.

type FileRetentionCeilingPlan added in v0.31.0

type FileRetentionCeilingPlan struct {
	Ceiling   string `json:"ceiling"`
	Current   string `json:"current"`
	Projected string `json:"projected"`
}

FileRetentionCeilingPlan reports exact current/projected values.

type FileRetentionClassPlan added in v0.31.0

type FileRetentionClassPlan struct {
	Class          string                       `json:"class"`
	Root           string                       `json:"root"`
	RootIdentity   string                       `json:"root_identity"`
	LiveGeneration string                       `json:"live_generation"`
	Budget         FileRetentionBudgetPlan      `json:"budget"`
	Inventory      []FileRetentionInventoryPlan `json:"inventory"`
	Status         string                       `json:"status"`
	Ceilings       []FileRetentionCeilingPlan   `json:"ceilings"`
	Floor          *FileRetentionFloorPlan      `json:"floor,omitempty"`
	Candidates     []FileRetentionCandidatePlan `json:"candidates"`
	Batches        []FileRetentionBatchPlan     `json:"batches"`
	OrderedSteps   []string                     `json:"ordered_steps"`
}

FileRetentionClassPlan contains one independent class decision.

type FileRetentionClassRequest added in v0.31.0

type FileRetentionClassRequest struct {
	Class  string
	Root   string
	Budget FileRetentionBudgetInput
}

FileRetentionClassRequest configures one independent local file class.

type FileRetentionFloorPlan added in v0.31.0

type FileRetentionFloorPlan struct {
	Identity           string `json:"identity"`
	RelativePath       string `json:"relative_path"`
	Generation         string `json:"generation"`
	ContentSHA256      string `json:"content_sha256"`
	VerificationDigest string `json:"verification_digest"`
}

FileRetentionFloorPlan identifies the protected current-generation recovery point.

type FileRetentionInventoryEntry added in v0.31.0

type FileRetentionInventoryEntry struct {
	Identity             string
	RelativePath         string
	Device               uint64
	Inode                uint64
	LinkCount            uint64
	LogicalBytes         int64
	AllocatedBytes       int64
	AllocatedKnown       bool
	ModifiedAt           time.Time
	GenerationCreatedAt  time.Time
	GenerationProvenance string
	Generation           string
	ContentSHA256        string
	Verified             bool
	VerificationDigest   string
	VerificationReason   string
	MetadataRelativePath string
	MetadataSHA256       string
	Pinned               bool
	BlockingReason       string
}

FileRetentionInventoryEntry is one exact regular file or fail-closed blocker.

type FileRetentionInventoryPlan added in v0.31.0

type FileRetentionInventoryPlan struct {
	Identity             string `json:"identity"`
	RelativePath         string `json:"relative_path"`
	Device               string `json:"device"`
	Inode                string `json:"inode"`
	LinkCount            string `json:"link_count"`
	LogicalBytes         string `json:"logical_bytes"`
	AllocatedBytes       string `json:"allocated_bytes,omitempty"`
	AllocatedKnown       bool   `json:"allocated_known"`
	ModifiedAt           string `json:"modified_at"`
	GenerationCreatedAt  string `json:"generation_created_at"`
	GenerationProvenance string `json:"generation_provenance"`
	Generation           string `json:"generation"`
	ContentSHA256        string `json:"content_sha256"`
	Verified             bool   `json:"verified"`
	VerificationDigest   string `json:"verification_digest,omitempty"`
	VerificationReason   string `json:"verification_reason,omitempty"`
	MetadataRelativePath string `json:"metadata_relative_path,omitempty"`
	MetadataSHA256       string `json:"metadata_sha256,omitempty"`
	Pinned               bool   `json:"pinned"`
	Protected            bool   `json:"protected"`
	BlockingReason       string `json:"blocking_reason,omitempty"`
}

FileRetentionInventoryPlan is exact hash-covered inventory evidence.

type FileRetentionInventoryRequest added in v0.31.0

type FileRetentionInventoryRequest struct {
	Class        string
	Root         string
	DatabasePath string
}

FileRetentionInventoryRequest asks the adapter for a read-only complete root snapshot.

type FileRetentionInventorySnapshot added in v0.31.0

type FileRetentionInventorySnapshot struct {
	Class          string
	Root           string
	RootIdentity   string
	LiveGeneration string
	RootAccess     FileRetentionRootAccessEvidence
	Entries        []FileRetentionInventoryEntry
}

FileRetentionInventorySnapshot is body-free verified filesystem evidence.

type FileRetentionPlan added in v0.31.0

type FileRetentionPlan struct {
	PlanID           string                        `json:"plan_id"`
	CanonicalPayload FileRetentionCanonicalPayload `json:"canonical_payload"`
	Display          FileRetentionPlanDisplay      `json:"display,omitempty"`
}

FileRetentionPlan is a strict immutable local cleanup plan.

type FileRetentionPlanDisplay added in v0.31.0

type FileRetentionPlanDisplay struct {
	Summary string `json:"summary,omitempty"`
}

FileRetentionPlanDisplay contains non-authoritative operator text.

type FileRetentionPlanRequest added in v0.31.0

type FileRetentionPlanRequest struct {
	DatabasePath string
	OutputPath   string
	ExpiresAfter time.Duration
	Classes      []FileRetentionClassRequest
}

FileRetentionPlanRequest contains the explicit roots and policies to inspect.

type FileRetentionRootAccessEvidence added in v0.31.0

type FileRetentionRootAccessEvidence struct {
	ApplyState           FileRetentionRootApplyState
	CallerOwned          bool
	GroupOrOtherWritable bool
}

FileRetentionRootAccessEvidence is descriptor-bound ownership and mode evidence.

type FileRetentionRootApplyState added in v0.31.0

type FileRetentionRootApplyState string

FileRetentionRootApplyState reports whether exact apply accepts the inspected root boundary.

const (
	// FileRetentionRootApplyEligible means exact apply accepts the root boundary.
	FileRetentionRootApplyEligible FileRetentionRootApplyState = "eligible"
	// FileRetentionRootApplyUnsafeOwner means the caller does not own the root.
	FileRetentionRootApplyUnsafeOwner FileRetentionRootApplyState = "unsafe_owner"
	// FileRetentionRootApplyUnsafePermissions means group or other users may write the root.
	FileRetentionRootApplyUnsafePermissions FileRetentionRootApplyState = "unsafe_permissions"
	// FileRetentionRootApplyUnsupported means the platform cannot prove the boundary.
	FileRetentionRootApplyUnsupported FileRetentionRootApplyState = "unsupported"
)

type GarbageCollectionTarget added in v0.10.0

type GarbageCollectionTarget string

GarbageCollectionTarget identifies which store records a gc run prunes.

const (
	// GarbageCollectionTargetEvents prunes event rows older than the cutoff.
	GarbageCollectionTargetEvents GarbageCollectionTarget = "events"
	// GarbageCollectionTargetSessions prunes ended sessions with no surviving events.
	GarbageCollectionTargetSessions GarbageCollectionTarget = "sessions"
	// GarbageCollectionTargetMemories prunes expired or superseded memories.
	GarbageCollectionTargetMemories GarbageCollectionTarget = "memories"
	// GarbageCollectionTargetMemoryEdges prunes closed or orphaned memory edges.
	GarbageCollectionTargetMemoryEdges GarbageCollectionTarget = "memory_edges"
	// GarbageCollectionTargetAll applies every garbage-collection target in dependency order.
	GarbageCollectionTargetAll GarbageCollectionTarget = "all"
)

func GarbageCollectionTargetFrom added in v0.10.0

func GarbageCollectionTargetFrom(value string) (GarbageCollectionTarget, bool)

GarbageCollectionTargetFrom parses a CLI/API target value.

func (GarbageCollectionTarget) String added in v0.10.0

func (t GarbageCollectionTarget) String() string

String returns the serialized target value.

type HandoffSummary

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

HandoffSummary holds information for session handoff between agents.

func HandoffSummaryFromContextPack added in v0.5.0

func HandoffSummaryFromContextPack(pack ContextPack) HandoffSummary

HandoffSummaryFromContextPack converts a ContextPack into the legacy compatibility handoff summary shape.

func HandoffSummaryOf

func HandoffSummaryOf(
	sessionID domtypes.SessionID,
	workspace domtypes.Workspace,
	label string,
	status string,
	totalEvents int,
	commandCount int,
	agents []string,
	summary string,
	recentCommands []string,
) HandoffSummary

HandoffSummaryOf creates a HandoffSummary.

func (HandoffSummary) Agents

func (h HandoffSummary) Agents() []string

Agents returns the participating agents.

func (HandoffSummary) CommandCount

func (h HandoffSummary) CommandCount() int

CommandCount returns the command count.

func (HandoffSummary) Label

func (h HandoffSummary) Label() string

Label returns the session label.

func (HandoffSummary) RecentCommands

func (h HandoffSummary) RecentCommands() []string

RecentCommands returns recent command descriptions.

func (HandoffSummary) SessionID

func (h HandoffSummary) SessionID() domtypes.SessionID

SessionID returns the session ID.

func (HandoffSummary) Status

func (h HandoffSummary) Status() string

Status returns the session status.

func (HandoffSummary) Summary

func (h HandoffSummary) Summary() string

Summary returns the session summary text.

func (HandoffSummary) TotalEvents

func (h HandoffSummary) TotalEvents() int

TotalEvents returns the total event count.

func (HandoffSummary) Workspace

func (h HandoffSummary) Workspace() domtypes.Workspace

Workspace returns the workspace.

type HookDeliveryInput added in v0.31.0

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

HookDeliveryInput is host-normalized delivery evidence carried from a hook adapter to the event/session usecase. NativeID is empty when the host does not expose a stable delivery identifier; callers must not invent one from body equality.

func HookDeliveryFromContext added in v0.31.0

func HookDeliveryFromContext(ctx context.Context) (HookDeliveryInput, bool)

HookDeliveryFromContext returns host-normalized delivery input when present.

func HookDeliveryInputOf added in v0.31.0

func HookDeliveryInputOf(nativeID, rawWorkspace string) HookDeliveryInput

HookDeliveryInputOf normalizes the delivery ID while preserving raw host workspace evidence byte-for-byte.

func (HookDeliveryInput) NativeID added in v0.31.0

func (i HookDeliveryInput) NativeID() string

NativeID returns the host-native stable delivery identifier.

func (HookDeliveryInput) RawWorkspace added in v0.31.0

func (i HookDeliveryInput) RawWorkspace() string

RawWorkspace returns the unnormalized host workspace evidence.

type ImportedMemoryCandidate added in v0.7.0

type ImportedMemoryCandidate struct {
	MemoryType   domtypes.MemoryType
	Scope        domtypes.MemoryScope
	Fact         string
	EvidenceRefs []domtypes.EvidenceRef
	ArtifactRefs []domtypes.ArtifactRef
	// SourcePath is the absolute path of the source file the fact was parsed
	// from. It is used for dedupe — re-runs that point at the same file must
	// not double-insert candidates even when the bullet line number changed.
	SourcePath string
}

ImportedMemoryCandidate represents a single durable-memory candidate that was parsed out of a host-native source (for example a Codex MEMORY.md file). It is the stable value object the import usecase consumes — the source adapter has already resolved a scope and attached provenance refs, and the usecase only has to sanitize, dedupe, and persist the candidate.

type LogRedaction added in v0.8.0

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

LogRedaction holds redaction settings for event logging via EventUsecase.Log. It mirrors AuditRedaction for the Audit path so every log-ingest surface (CLI `traceary log`, transcript hook, MCP add_log) carries the same policy shape and the usecase implementation can apply redaction once on behalf of all callers.

The zero value is intentionally a pass-through: no extra patterns, matching today's behaviour for non-transcript kinds.

func (LogRedaction) ExtraRedactPatterns added in v0.8.0

func (r LogRedaction) ExtraRedactPatterns() []string

ExtraRedactPatterns returns additional redaction regex patterns.

func (LogRedaction) StructuredRules added in v0.10.0

func (r LogRedaction) StructuredRules() []redaction.RuleConfig

StructuredRules returns configured structured redaction rules.

type LogRedactionBuilder added in v0.8.0

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

LogRedactionBuilder builds a LogRedaction value.

func NewLogRedactionBuilder added in v0.8.0

func NewLogRedactionBuilder() *LogRedactionBuilder

NewLogRedactionBuilder starts building an empty LogRedaction.

func (*LogRedactionBuilder) Build added in v0.8.0

func (b *LogRedactionBuilder) Build() LogRedaction

Build finalizes and returns the LogRedaction.

func (*LogRedactionBuilder) ExtraRedactPatterns added in v0.8.0

func (b *LogRedactionBuilder) ExtraRedactPatterns(patterns []string) *LogRedactionBuilder

ExtraRedactPatterns sets additional redaction regex patterns.

func (*LogRedactionBuilder) StructuredRules added in v0.10.0

func (b *LogRedactionBuilder) StructuredRules(rules []redaction.RuleConfig) *LogRedactionBuilder

StructuredRules sets structured redaction rules.

type MemoryActivationApplyAction added in v0.12.0

type MemoryActivationApplyAction string

MemoryActivationApplyAction summarizes the observable filesystem outcome of a non-dry-run activation.

const (
	// MemoryActivationApplyCreated means the activation target file was created.
	MemoryActivationApplyCreated MemoryActivationApplyAction = "created"
	// MemoryActivationApplyUpdated means an existing activation target changed.
	MemoryActivationApplyUpdated MemoryActivationApplyAction = "updated"
	// MemoryActivationApplyNoop means the activation target was already current.
	MemoryActivationApplyNoop MemoryActivationApplyAction = "noop"
)

func (MemoryActivationApplyAction) String added in v0.12.0

String returns the canonical string form.

type MemoryActivationApplyResult added in v0.12.0

type MemoryActivationApplyResult struct {
	Target         MemoryBridgeTarget
	TargetPath     string
	Scopes         []domtypes.MemoryScope
	Action         MemoryActivationApplyAction
	Existing       bool
	ActivatedCount int
	HostContext    *MemoryActivationComponent
	ExternalMemory *MemoryActivationComponent
}

MemoryActivationApplyResult reports the effect of writing accepted memories into a host-native activation target.

For two-file targets (Claude / Gemini) the top-level Action is the aggregated pair action per the v0.13 ADR (created when either file was created, updated when at least one file changed and none was created, otherwise noop). The per-file HostContext / ExternalMemory components carry the underlying action and path so callers can render the apply summary independently for each file.

type MemoryActivationComponent added in v0.13.0

type MemoryActivationComponent struct {
	Path     string
	Existing bool
	Markdown string
	Diff     string
	Action   MemoryActivationApplyAction
	State    MemoryActivationStatusState
	Message  string
}

MemoryActivationComponent is the per-file plan inside a two-file activation pair (host context stub + external memory file). Single-file targets do not populate this type; two-file targets populate one MemoryActivationComponent per file so callers see the planned content, status, and diff for each file independently.

type MemoryActivationCriteria added in v0.12.0

type MemoryActivationCriteria struct {
	Target        MemoryBridgeTarget
	Root          string
	Path          string
	Scopes        []domtypes.MemoryScope
	IncludeGlobal bool
	Diff          bool
}

MemoryActivationCriteria describes a dry-run host activation plan. The planner resolves a target file and renders the content, but it never writes to disk; later write-side usecases consume the same target contract.

type MemoryActivationPlan added in v0.12.0

type MemoryActivationPlan struct {
	Target         MemoryBridgeTarget
	TargetPath     string
	Scopes         []domtypes.MemoryScope
	Markdown       string
	Existing       bool
	Diff           string
	ActivatedCount int
	HostContext    *MemoryActivationComponent
	ExternalMemory *MemoryActivationComponent
}

MemoryActivationPlan is the resolved dry-run output for a host-native activation. Markdown is the content that would be written to TargetPath.

For two-file targets (Claude / Gemini) the top-level fields describe the host context file so codex JSON consumers continue to see the same shape; component-level details for both files are exposed through HostContext and ExternalMemory so callers that understand the pair contract can render per-file diffs and apply paths.

type MemoryActivationStatusResult added in v0.12.0

type MemoryActivationStatusResult struct {
	Target         MemoryBridgeTarget
	TargetPath     string
	Scopes         []domtypes.MemoryScope
	State          MemoryActivationStatusState
	Existing       bool
	ActivatedCount int
	Message        string
	HostContext    *MemoryActivationComponent
	ExternalMemory *MemoryActivationComponent
}

MemoryActivationStatusResult is the read-only activation health view used by `memory activate --status` and doctor.

For two-file targets the top-level State is the aggregated pair state per the v0.13 ADR (invalid > missing > stale > in_sync), and the per-file HostContext / ExternalMemory components carry the underlying state and path so doctor can give actionable remediation without reparsing files.

type MemoryActivationStatusState added in v0.12.0

type MemoryActivationStatusState string

MemoryActivationStatusState describes whether the host-native file reflects the currently accepted Traceary memories.

const (
	// MemoryActivationStatusMissing means the target file or managed block is absent.
	MemoryActivationStatusMissing MemoryActivationStatusState = "missing"
	// MemoryActivationStatusStale means the managed block differs from current accepted memories.
	MemoryActivationStatusStale MemoryActivationStatusState = "stale"
	// MemoryActivationStatusInSync means the managed block matches current accepted memories.
	MemoryActivationStatusInSync MemoryActivationStatusState = "in_sync"
	// MemoryActivationStatusInvalid means the target cannot be safely interpreted.
	MemoryActivationStatusInvalid MemoryActivationStatusState = "invalid"
)

func (MemoryActivationStatusState) String added in v0.12.0

String returns the canonical string form.

type MemoryBridgeImportCriteria added in v0.7.0

type MemoryBridgeImportCriteria struct {
	Target            MemoryBridgeTarget
	Path              string
	Markdown          string
	WorkspaceFallback domtypes.Workspace
}

MemoryBridgeImportCriteria carries the inputs to the instruction-file import usecase. Target picks the marker format, Path / Markdown are the raw source (exactly one of them is consumed by the usecase so the CLI can stream either a file or an in-memory buffer). WorkspaceFallback is applied when a bullet does not carry a scope hint of its own.

type MemoryBridgeImportResult added in v0.7.0

type MemoryBridgeImportResult struct {
	Imported              []MemoryDetails
	SkippedDuplicateCount int
	SkippedRejectedCount  int
	Warnings              []string
}

MemoryBridgeImportResult reports the outcome of one import run and reuses MemoryImportResult's shape so downstream consumers (CLI, documentation, telemetry) do not have to branch between the Codex memory import surface and the instruction-file surface.

type MemoryBridgeTarget added in v0.7.0

type MemoryBridgeTarget string

MemoryBridgeTarget names a host-native instruction file (CLAUDE.md, AGENTS.md, GEMINI.md) that the bridge export and import usecases translate to and from. Keeping the target set small and explicit means the usecase can pick the right markdown template without the CLI having to hand-wave host-specific conventions.

const (
	// MemoryBridgeTargetClaude targets Claude Code's CLAUDE.md instructions.
	MemoryBridgeTargetClaude MemoryBridgeTarget = "claude"
	// MemoryBridgeTargetCodex targets Codex's AGENTS.md instructions.
	MemoryBridgeTargetCodex MemoryBridgeTarget = "codex"
	// MemoryBridgeTargetGemini targets Gemini CLI's GEMINI.md instructions.
	MemoryBridgeTargetGemini MemoryBridgeTarget = "gemini"
)

func MemoryBridgeTargetOf added in v0.7.0

func MemoryBridgeTargetOf(value string) (MemoryBridgeTarget, bool)

MemoryBridgeTargetOf validates and returns a MemoryBridgeTarget.

func (MemoryBridgeTarget) String added in v0.7.0

func (t MemoryBridgeTarget) String() string

String returns the canonical string form.

type MemoryDecayCriteria added in v0.28.0

type MemoryDecayCriteria struct {
	OlderThan     time.Duration
	Limit         int
	Apply         bool
	Dedupe        bool
	IncludeHidden bool
	Workspace     domtypes.Optional[domtypes.Workspace]
	Now           time.Time
}

MemoryDecayCriteria configures a decay run.

type MemoryDecayResult added in v0.28.0

type MemoryDecayResult struct {
	ExpiredIDs     []string
	SupersededIDs  []string
	Skipped        map[string]int
	RemainingAfter int
	Applied        bool
	OlderThan      time.Duration
	Scanned        int
}

MemoryDecayResult is the outcome of a decay dry-run or apply.

type MemoryDetails added in v0.5.0

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

MemoryDetails holds a MemorySummary plus traceable refs.

func MemoryDetailsFrom added in v0.5.0

func MemoryDetailsFrom(memory *model.Memory) (MemoryDetails, error)

MemoryDetailsFrom creates MemoryDetails from a Memory aggregate.

func MemoryDetailsOf added in v0.5.0

func MemoryDetailsOf(summary MemorySummary, evidenceRefs []domtypes.EvidenceRef, artifactRefs []domtypes.ArtifactRef) MemoryDetails

MemoryDetailsOf creates MemoryDetails from a summary and refs.

func (MemoryDetails) ArtifactRefs added in v0.5.0

func (d MemoryDetails) ArtifactRefs() []domtypes.ArtifactRef

ArtifactRefs returns the related artifact refs.

func (MemoryDetails) EvidenceRefs added in v0.5.0

func (d MemoryDetails) EvidenceRefs() []domtypes.EvidenceRef

EvidenceRefs returns the supporting evidence refs.

func (MemoryDetails) Summary added in v0.5.0

func (d MemoryDetails) Summary() MemorySummary

Summary returns the memory summary.

type MemoryDistillCriteria added in v0.12.0

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

MemoryDistillCriteria describes an explicit operator distillation of one or more candidate memories into a new accepted memory.

func MemoryDistillCriteriaOf added in v0.12.0

func MemoryDistillCriteriaOf(
	fromIDs []domtypes.MemoryID,
	memoryType domtypes.MemoryType,
	scope domtypes.MemoryScope,
	fact string,
	confidence domtypes.Optional[domtypes.Confidence],
	source domtypes.MemorySource,
	replace MemoryDistillReplace,
) MemoryDistillCriteria

MemoryDistillCriteriaOf creates distillation criteria.

func (MemoryDistillCriteria) Confidence added in v0.12.0

Confidence returns the accepted confidence override.

func (MemoryDistillCriteria) Fact added in v0.12.0

func (c MemoryDistillCriteria) Fact() string

Fact returns the operator-provided distilled fact.

func (MemoryDistillCriteria) FromIDs added in v0.12.0

func (c MemoryDistillCriteria) FromIDs() []domtypes.MemoryID

FromIDs returns the source candidate IDs.

func (MemoryDistillCriteria) MemoryType added in v0.12.0

func (c MemoryDistillCriteria) MemoryType() domtypes.MemoryType

MemoryType returns the accepted memory type to create.

func (MemoryDistillCriteria) Replace added in v0.12.0

Replace returns how source candidates should be handled.

func (MemoryDistillCriteria) Scope added in v0.12.0

Scope returns the accepted memory scope to create.

func (MemoryDistillCriteria) Source added in v0.12.0

Source returns the source attribution for the accepted memory.

type MemoryDistillReplace added in v0.12.0

type MemoryDistillReplace string

MemoryDistillReplace controls what happens to source candidates after distillation creates the accepted memory.

const (
	// MemoryDistillReplaceKeep leaves source candidates unchanged after distillation.
	MemoryDistillReplaceKeep MemoryDistillReplace = "keep"
	// MemoryDistillReplaceReject rejects source candidates after distillation.
	MemoryDistillReplaceReject MemoryDistillReplace = "reject"
	// MemoryDistillReplaceSupersede marks source candidates as superseded after distillation.
	MemoryDistillReplaceSupersede MemoryDistillReplace = "supersede"
)

func (MemoryDistillReplace) String added in v0.12.0

func (r MemoryDistillReplace) String() string

String returns the stable CLI / JSON value.

type MemoryDistillResult added in v0.12.0

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

MemoryDistillResult reports the accepted memory and resulting source states.

func MemoryDistillResultOf added in v0.12.0

func MemoryDistillResultOf(distilled MemoryDetails, sources []MemorySummary, replace MemoryDistillReplace) MemoryDistillResult

MemoryDistillResultOf creates a distillation result.

func (MemoryDistillResult) Distilled added in v0.12.0

func (r MemoryDistillResult) Distilled() MemoryDetails

Distilled returns the accepted memory created by distillation.

func (MemoryDistillResult) Replace added in v0.12.0

Replace returns the source replacement policy that was applied.

func (MemoryDistillResult) Sources added in v0.12.0

func (r MemoryDistillResult) Sources() []MemorySummary

Sources returns source candidate summaries after replacement handling.

type MemoryExportCriteria added in v0.7.0

type MemoryExportCriteria struct {
	Target MemoryBridgeTarget
	Scopes []domtypes.MemoryScope
	// IncludeGlobal adds the global scope when Scopes is non-empty.
	IncludeGlobal bool
}

MemoryExportCriteria is the input to the export usecase. An empty scope exports every accepted memory. Callers that pass explicit workspace scopes can set IncludeGlobal to add the global memory scope beside the workspace filter.

type MemoryExportResult added in v0.7.0

type MemoryExportResult struct {
	Target   MemoryBridgeTarget
	Scopes   []domtypes.MemoryScope
	Markdown string
	// ExportedCount tracks the number of accepted memories included in
	// the Markdown output so operators can sanity-check the volume and
	// JSON consumers can drive their own "nothing to do" guards.
	ExportedCount int
}

MemoryExportResult carries the serialized markdown emitted by an export run so the CLI / MCP layer can write it to disk or return it as JSON without the usecase having to reach into the filesystem itself.

type MemoryExtractionCriteria added in v0.5.0

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

MemoryExtractionCriteria describes how to extract candidate durable memories from existing session/history signals.

func (MemoryExtractionCriteria) CandidateLimit added in v0.5.0

func (c MemoryExtractionCriteria) CandidateLimit() int

CandidateLimit returns the maximum number of candidates to persist.

func (MemoryExtractionCriteria) EventLimit added in v0.5.0

func (c MemoryExtractionCriteria) EventLimit() int

EventLimit returns the maximum number of recent events to inspect per kind.

func (MemoryExtractionCriteria) SessionID added in v0.5.0

SessionID returns the target session ID.

func (MemoryExtractionCriteria) Workspace added in v0.5.0

Workspace returns the target workspace.

type MemoryExtractionCriteriaBuilder added in v0.5.0

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

MemoryExtractionCriteriaBuilder builds MemoryExtractionCriteria values.

func NewMemoryExtractionCriteriaBuilder added in v0.5.0

func NewMemoryExtractionCriteriaBuilder() *MemoryExtractionCriteriaBuilder

NewMemoryExtractionCriteriaBuilder starts a criteria builder with sensible defaults.

func (*MemoryExtractionCriteriaBuilder) Build added in v0.5.0

Build finalizes the criteria.

func (*MemoryExtractionCriteriaBuilder) CandidateLimit added in v0.5.0

CandidateLimit sets the maximum number of extracted candidates.

func (*MemoryExtractionCriteriaBuilder) EventLimit added in v0.5.0

EventLimit sets the per-kind event inspection limit.

func (*MemoryExtractionCriteriaBuilder) SessionID added in v0.5.0

SessionID sets the target session ID.

func (*MemoryExtractionCriteriaBuilder) Workspace added in v0.5.0

Workspace sets the target workspace.

type MemoryExtractionDebugReport added in v0.11.2

type MemoryExtractionDebugReport struct {
	SessionID domtypes.SessionID
	Workspace domtypes.Workspace
	Segments  []MemoryExtractionSegmentDecision
}

MemoryExtractionDebugReport explains how durable-memory extraction evaluated each inspected signal segment. It is intentionally read-only: callers use it for dogfooding and false-negative analysis without creating candidates.

type MemoryExtractionSegmentDecision added in v0.11.2

type MemoryExtractionSegmentDecision struct {
	Text              string
	Client            domtypes.Client
	EventKind         domtypes.EventKind
	SourceHook        string
	MemoryType        domtypes.MemoryType
	Features          []string
	Score             int
	Decision          string
	Reason            string
	EvidenceRefs      []domtypes.EvidenceRef
	ArtifactRefs      []domtypes.ArtifactRef
	LowQualityReasons []string
}

MemoryExtractionSegmentDecision captures the classifier features and final extraction decision for one normalized signal segment.

type MemoryHygieneApplied added in v0.7.0

type MemoryHygieneApplied struct {
	MemoryID   string
	Kind       MemoryHygieneSuggestionKind
	Transition string
	Details    MemoryDetails
}

MemoryHygieneApplied describes one memory that transitioned because of an apply run. Kind / Transition tell the reviewer exactly what the usecase did so they can re-inspect the store later.

type MemoryHygieneApplyCriteria added in v0.7.0

type MemoryHygieneApplyCriteria struct {
	MemoryIDs               []string
	StalenessThreshold      time.Duration
	Now                     time.Time
	IncludeHiddenCandidates bool
}

MemoryHygieneApplyCriteria carries the inputs to the apply path. Ids reference memories the caller already saw in a Scan result; the usecase re-runs the scan to make sure the transition still applies.

IncludeHiddenCandidates mirrors the scan flag so an apply targeting a previously-hidden candidate id still finds the suggestion when the re-scan runs. Without it, the re-scan would miss the row and the apply would fail with "no current hygiene suggestion".

type MemoryHygieneApplyFailure added in v0.7.0

type MemoryHygieneApplyFailure struct {
	MemoryID string
	Error    string
}

MemoryHygieneApplyFailure reports per-id errors so the caller can retry only the tail that failed.

type MemoryHygieneApplyResult added in v0.7.0

type MemoryHygieneApplyResult struct {
	Applied  []MemoryHygieneApplied
	Failures []MemoryHygieneApplyFailure
}

MemoryHygieneApplyResult mirrors the inbox batch output shape so both surfaces expose the same processed / failure breakdown.

type MemoryHygieneScanCriteria added in v0.7.0

type MemoryHygieneScanCriteria struct {
	Scopes                  []domtypes.MemoryScope
	StalenessThreshold      time.Duration
	SimilarityThreshold     float64
	Now                     time.Time
	IncludeHiddenCandidates bool
}

MemoryHygieneScanCriteria carries the inputs the hygiene scanner consumes. Scopes default to every scope when empty; the staleness threshold controls the expiry suggestion window and falls back to a usecase default when zero. SimilarityThreshold tunes the supersede_candidate detector — 0 uses the usecase default (0.6).

IncludeHiddenCandidates expands the candidate-noise pass to include extracted-hidden rows (low-quality auto-extractions kept for audit). Without it the scan only inspects visible candidates so the default view matches what the operator sees in the inbox.

type MemoryHygieneScanResult added in v0.7.0

type MemoryHygieneScanResult struct {
	Suggestions                   []MemoryHygieneSuggestion
	RedactionHitCount             int
	ExpiryCandidateCount          int
	DuplicateCount                int
	SupersedeCandidateCount       int
	ValidityOverlapSupersedeCount int
	LowQualityCandidateCount      int
}

MemoryHygieneScanResult summarises a single scan run. Suggestions keeps the list so JSON consumers get a stable shape regardless of which category was populated; the counts mirror what the CLI renders as a human-readable summary.

type MemoryHygieneSuggestion added in v0.7.0

type MemoryHygieneSuggestion struct {
	MemoryID            domtypes.MemoryID
	Kind                MemoryHygieneSuggestionKind
	Reason              string
	Fact                string
	SanitizedFact       string
	DuplicateMemoryID   domtypes.MemoryID
	ReplacementMemoryID domtypes.MemoryID
	ReplacementFact     string
	Similarity          float64
	Scope               domtypes.MemoryScope
	UpdatedAt           time.Time
	Status              domtypes.MemoryStatus
	Source              domtypes.MemorySource
	QualityReasons      []string
}

MemoryHygieneSuggestion is the serializable view of a single scan hit. SanitizedFact is populated for redaction hits so the apply path can propose a supersede with the masked content; DuplicateMemoryID is set on duplicate hits so the reader sees both sides of the pair; ReplacementMemoryID and ReplacementFact are set on supersede_candidate hits so the apply path knows which memory becomes the replacement. Similarity is the computed word-Jaccard score (0.0-1.0) — zero on everything except supersede_candidate.

Status / Source are populated for low_quality_candidate suggestions so the reviewer can confirm the row is still a candidate (and which extraction source produced it) before approving the apply path. QualityReasons enumerates the deterministic noise markers that classified the candidate as low-quality — the same vocabulary the extractor diagnostics expose (#857).

type MemoryHygieneSuggestionKind added in v0.7.0

type MemoryHygieneSuggestionKind string

MemoryHygieneSuggestionKind names the reason a memory was surfaced by the hygiene scan. Keeping the enumeration small means the CLI and MCP output can branch on a single field without reimplementing the scanner logic on the read side.

const (
	// MemoryHygieneSuggestionRedactionHit flags an accepted memory whose
	// sanitized fact differs from the stored fact, meaning the current
	// audit redaction rules would mask content that the stored row still
	// exposes.
	MemoryHygieneSuggestionRedactionHit MemoryHygieneSuggestionKind = "redaction_hit"
	// MemoryHygieneSuggestionExpiryCandidate flags an accepted memory
	// whose updated_at is older than the hygiene staleness threshold, so
	// an operator may want to expire it.
	MemoryHygieneSuggestionExpiryCandidate MemoryHygieneSuggestionKind = "expiry_candidate"
	// MemoryHygieneSuggestionDuplicate flags two accepted memories that
	// share the same scope and fact text, so one should supersede or
	// expire the other to keep the store tidy.
	MemoryHygieneSuggestionDuplicate MemoryHygieneSuggestionKind = "duplicate"
	// MemoryHygieneSuggestionSupersedeCandidate flags two accepted
	// memories that share a scope and a meaningful word overlap (word
	// Jaccard >= defaultSupersedeSimilarityThreshold) but carry
	// different text. The newer memory is suggested as the replacement;
	// the CLI apply path supersedes the older memory with the newer
	// memory's content so the store converges on a single entry.
	MemoryHygieneSuggestionSupersedeCandidate MemoryHygieneSuggestionKind = "supersede_candidate"
	// MemoryHygieneSuggestionValidityOverlapSupersede flags two accepted
	// memories that share (scope, type) and have overlapping temporal
	// validity windows (valid_from/valid_to) while carrying facts that
	// differ above the similarity threshold. The older memory is
	// superseded by the newer one on apply, and the apply path keeps
	// scope / type / refs so the retrieval surface stays consistent.
	// Unlike SupersedeCandidate this detector is gated by window
	// overlap: memories with disjoint validity windows are treated as
	// separate historical facts.
	MemoryHygieneSuggestionValidityOverlapSupersede MemoryHygieneSuggestionKind = "validity_overlap_supersede"
	// MemoryHygieneSuggestionLowQualityCandidate flags a status=candidate
	// memory whose fact text matches the deterministic low-quality
	// classifier (#857). The apply path rejects the candidate so the
	// inbox view stays focused on durable signals; accepted memories are
	// never touched. The suggestion only fires for status=candidate, and
	// extracted-hidden rows are inspected only when the caller opts in
	// via MemoryHygieneScanCriteria.IncludeHiddenCandidates so the
	// default scan stays predictable.
	MemoryHygieneSuggestionLowQualityCandidate MemoryHygieneSuggestionKind = "low_quality_candidate"
)

type MemoryImportResult added in v0.7.0

type MemoryImportResult struct {
	// Imported is the set of newly persisted candidate memories.
	Imported []MemoryDetails
	// SkippedDuplicateCount is the number of candidates that were already
	// represented in the durable-memory store (same scope + source path +
	// sanitized fact) and were therefore intentionally not re-created.
	SkippedDuplicateCount int
	// SkippedRejectedCount is the number of candidates that matched an
	// existing memory whose current status is rejected/superseded/expired.
	// The import path refuses to resurrect them, so they are counted
	// separately to help the operator understand why no new row appeared.
	SkippedRejectedCount int
	// Warnings carries non-fatal parser or sanitizer messages that should
	// surface in the CLI output but do not stop the run.
	Warnings []string
}

MemoryImportResult summarises a single run of the Codex memory import usecase. Counts are reported per category so the CLI can render a human-friendly summary and `--json` consumers can track drift across runs without replaying the full candidate list.

type MemoryListCriteria added in v0.5.0

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

MemoryListCriteria holds filter parameters for memory listing. Zero-value fields are ignored unless documented otherwise.

func (MemoryListCriteria) AsOf added in v0.8.0

AsOf returns the point-in-time at which validity should be evaluated. When present, a memory matches only if validFrom <= AsOf and (validTo is null or validTo > AsOf). The zero value (None) means "use the current wall clock at query time".

func (MemoryListCriteria) IncludeExpiredByValidity added in v0.8.0

func (c MemoryListCriteria) IncludeExpiredByValidity() bool

IncludeExpiredByValidity returns true when the caller asked to bypass the validity-window filter and return memories whose validTo is in the past as well. Defaults to false so the common case ("give me memories that are still valid right now") is the default.

func (MemoryListCriteria) Limit added in v0.5.0

func (c MemoryListCriteria) Limit() int

Limit returns the maximum number of results.

func (MemoryListCriteria) MemoryTypes added in v0.5.0

func (c MemoryListCriteria) MemoryTypes() []domtypes.MemoryType

MemoryTypes returns the memory type filters.

func (MemoryListCriteria) Offset added in v0.5.0

func (c MemoryListCriteria) Offset() int

Offset returns the result offset.

func (MemoryListCriteria) RememberIntentPriority added in v0.12.0

func (c MemoryListCriteria) RememberIntentPriority() bool

RememberIntentPriority reports whether prioritized inbox source rows should be returned ahead of other rows in the result set. The flag is honoured at the query layer so pagination (--limit/--offset) is consistent with the displayed order. Used by the inbox view; default is false.

func (MemoryListCriteria) Scopes added in v0.5.0

Scopes returns the typed scope filters.

func (MemoryListCriteria) Sources added in v0.7.0

Sources returns the memory source filters.

func (MemoryListCriteria) Statuses added in v0.5.0

func (c MemoryListCriteria) Statuses() []domtypes.MemoryStatus

Statuses returns the lifecycle status filters.

func (MemoryListCriteria) UpdatedAfter added in v0.16.0

func (c MemoryListCriteria) UpdatedAfter() domtypes.Optional[time.Time]

UpdatedAfter returns an optional updated_at lower bound.

func (MemoryListCriteria) UpdatedBefore added in v0.16.0

func (c MemoryListCriteria) UpdatedBefore() domtypes.Optional[time.Time]

UpdatedBefore returns an optional updated_at upper bound.

type MemoryListCriteriaBuilder added in v0.5.0

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

MemoryListCriteriaBuilder builds a MemoryListCriteria value.

func NewMemoryListCriteriaBuilder added in v0.5.0

func NewMemoryListCriteriaBuilder(limit int) *MemoryListCriteriaBuilder

NewMemoryListCriteriaBuilder starts building with the given limit.

func (*MemoryListCriteriaBuilder) AsOf added in v0.8.0

AsOf sets the point-in-time at which validity windows are evaluated. Zero values are ignored.

func (*MemoryListCriteriaBuilder) Build added in v0.5.0

Build finalizes and returns the MemoryListCriteria.

func (*MemoryListCriteriaBuilder) IncludeExpiredByValidity added in v0.8.0

func (b *MemoryListCriteriaBuilder) IncludeExpiredByValidity(include bool) *MemoryListCriteriaBuilder

IncludeExpiredByValidity toggles whether memories whose validTo is in the past are included in results. Default is false.

func (*MemoryListCriteriaBuilder) MemoryType added in v0.5.0

MemoryType appends a memory type filter.

func (*MemoryListCriteriaBuilder) MemoryTypes added in v0.5.0

MemoryTypes replaces the memory type filters.

func (*MemoryListCriteriaBuilder) Offset added in v0.5.0

Offset sets the number of results to skip.

func (*MemoryListCriteriaBuilder) RememberIntentPriority added in v0.12.0

func (b *MemoryListCriteriaBuilder) RememberIntentPriority(priority bool) *MemoryListCriteriaBuilder

RememberIntentPriority toggles whether prioritized inbox source rows should be returned ahead of other rows in the result set. The flag is honoured at the query layer so pagination is consistent with the displayed order. Default is false.

func (*MemoryListCriteriaBuilder) Scope added in v0.5.0

Scope appends a typed scope filter.

func (*MemoryListCriteriaBuilder) Scopes added in v0.5.0

Scopes replaces the typed scope filters.

func (*MemoryListCriteriaBuilder) Source added in v0.7.0

Source appends a memory source filter.

func (*MemoryListCriteriaBuilder) Sources added in v0.7.0

Sources replaces the memory source filters.

func (*MemoryListCriteriaBuilder) Status added in v0.5.0

Status appends a lifecycle status filter.

func (*MemoryListCriteriaBuilder) Statuses added in v0.5.0

Statuses replaces the lifecycle status filters.

func (*MemoryListCriteriaBuilder) UpdatedAfter added in v0.16.0

func (b *MemoryListCriteriaBuilder) UpdatedAfter(updatedAfter time.Time) *MemoryListCriteriaBuilder

UpdatedAfter filters rows whose updated_at is later than or equal to the supplied timestamp. Zero values are ignored.

func (*MemoryListCriteriaBuilder) UpdatedBefore added in v0.16.0

func (b *MemoryListCriteriaBuilder) UpdatedBefore(updatedBefore time.Time) *MemoryListCriteriaBuilder

UpdatedBefore filters rows whose updated_at is earlier than or equal to the supplied timestamp. Zero values are ignored.

type MemoryRetrievalPreset added in v0.8.0

type MemoryRetrievalPreset string

MemoryRetrievalPreset names a canonical retrieval shape over durable memory. Presets pre-populate a MemoryListCriteriaBuilder with the filters that match a specific operator scenario (resume / review / incident), and the caller can still layer explicit filters on top.

const (
	// MemoryRetrievalPresetResume surfaces memories operators want when
	// picking up where a session left off: accepted memories ordered
	// newest-first, no type restriction so recent lessons /
	// constraints / preferences all surface together.
	MemoryRetrievalPresetResume MemoryRetrievalPreset = "resume"

	// MemoryRetrievalPresetReview focuses on long-lived "what did we
	// decide" knowledge: only accepted decisions and constraints, no
	// preferences or one-off lessons.
	MemoryRetrievalPresetReview MemoryRetrievalPreset = "review"

	// MemoryRetrievalPresetIncident surfaces what an operator needs to
	// know when a failure just happened: accepted lessons and
	// constraints (the "what to avoid" axis) plus decisions that might
	// explain why a contested path exists.
	MemoryRetrievalPresetIncident MemoryRetrievalPreset = "incident"
)

func KnownMemoryRetrievalPresets added in v0.8.0

func KnownMemoryRetrievalPresets() []MemoryRetrievalPreset

KnownMemoryRetrievalPresets returns the exhaustive list of built-in presets, in the order CLI help and docs should render them.

func MemoryRetrievalPresetOf added in v0.8.0

func MemoryRetrievalPresetOf(value string) (MemoryRetrievalPreset, error)

MemoryRetrievalPresetOf parses a free-form string into a known preset. Empty input returns "" (no preset applied) so callers can pass a user-supplied flag value through without special-casing.

func (MemoryRetrievalPreset) ApplyMemoryTypeFiltersToMemoryListCriteriaBuilder added in v0.16.0

func (p MemoryRetrievalPreset) ApplyMemoryTypeFiltersToMemoryListCriteriaBuilder(builder *MemoryListCriteriaBuilder) *MemoryListCriteriaBuilder

ApplyMemoryTypeFiltersToMemoryListCriteriaBuilder applies only the preset's type restrictions, leaving lifecycle status untouched. This lets review-oriented surfaces ask for candidate memories in a separate section while preserving the same resume / review / incident memory type shape as the trusted accepted section.

func (MemoryRetrievalPreset) ApplyToMemoryListCriteriaBuilder added in v0.8.0

func (p MemoryRetrievalPreset) ApplyToMemoryListCriteriaBuilder(builder *MemoryListCriteriaBuilder) *MemoryListCriteriaBuilder

ApplyToMemoryListCriteriaBuilder pre-populates the builder with the preset's default filters. Explicit filters the caller sets after calling this method override the preset's defaults — the preset is purely a convenience starting point, not a ceiling.

Design choices:

  • `resume` does not restrict memoryTypes because the scenario is "what was I working on" — preferences and lessons are as useful as decisions. It only pins statuses=[accepted].
  • `review` narrows to decision + constraint because those are the types operators expect to reread.
  • `incident` includes lesson + constraint + decision so the "what did we learn" / "what must not happen" / "why is this state here" axes all surface together.

Callers pass a MemoryListCriteriaBuilder to keep the dependency direction domain-free; no MemoryListCriteria allocation is returned directly because the caller typically still needs to chain Limit(), Scopes(), AsOf(), etc.

func (MemoryRetrievalPreset) ApplyToMemorySearchCriteriaBuilder added in v0.8.0

func (p MemoryRetrievalPreset) ApplyToMemorySearchCriteriaBuilder(builder *MemorySearchCriteriaBuilder) *MemorySearchCriteriaBuilder

ApplyToMemorySearchCriteriaBuilder is the search-side counterpart to ApplyToMemoryListCriteriaBuilder. Same defaults, same override semantics.

func (MemoryRetrievalPreset) String added in v0.8.0

func (p MemoryRetrievalPreset) String() string

String returns the canonical name of the preset.

type MemorySearchCriteria added in v0.5.0

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

MemorySearchCriteria holds filter parameters for full-text memory search.

func (MemorySearchCriteria) AsOf added in v0.8.0

AsOf returns the point-in-time at which validity windows are evaluated. See MemoryListCriteria.AsOf for semantics.

func (MemorySearchCriteria) IncludeExpiredByValidity added in v0.8.0

func (c MemorySearchCriteria) IncludeExpiredByValidity() bool

IncludeExpiredByValidity returns true when the caller asked to bypass the validity-window filter. See MemoryListCriteria.IncludeExpiredByValidity.

func (MemorySearchCriteria) Limit added in v0.5.0

func (c MemorySearchCriteria) Limit() int

Limit returns the maximum number of results.

func (MemorySearchCriteria) MemoryTypes added in v0.5.0

func (c MemorySearchCriteria) MemoryTypes() []domtypes.MemoryType

MemoryTypes returns the memory type filters.

func (MemorySearchCriteria) Offset added in v0.5.0

func (c MemorySearchCriteria) Offset() int

Offset returns the result offset.

func (MemorySearchCriteria) Query added in v0.5.0

func (c MemorySearchCriteria) Query() string

Query returns the search query.

func (MemorySearchCriteria) Scopes added in v0.5.0

Scopes returns the typed scope filters.

func (MemorySearchCriteria) Sources added in v0.11.0

Sources returns the memory source filters.

func (MemorySearchCriteria) Statuses added in v0.5.0

Statuses returns the lifecycle status filters.

type MemorySearchCriteriaBuilder added in v0.5.0

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

MemorySearchCriteriaBuilder builds a MemorySearchCriteria value.

func NewMemorySearchCriteriaBuilder added in v0.5.0

func NewMemorySearchCriteriaBuilder(limit int) *MemorySearchCriteriaBuilder

NewMemorySearchCriteriaBuilder starts building with the given limit.

func (*MemorySearchCriteriaBuilder) AsOf added in v0.8.0

AsOf sets the point-in-time at which validity windows are evaluated. Zero values are ignored.

func (*MemorySearchCriteriaBuilder) Build added in v0.5.0

Build finalizes and returns the MemorySearchCriteria.

func (*MemorySearchCriteriaBuilder) IncludeExpiredByValidity added in v0.8.0

func (b *MemorySearchCriteriaBuilder) IncludeExpiredByValidity(include bool) *MemorySearchCriteriaBuilder

IncludeExpiredByValidity toggles whether memories whose validTo is in the past are included in results. Default is false.

func (*MemorySearchCriteriaBuilder) MemoryType added in v0.5.0

MemoryType appends a memory type filter.

func (*MemorySearchCriteriaBuilder) MemoryTypes added in v0.5.0

MemoryTypes replaces the memory type filters.

func (*MemorySearchCriteriaBuilder) Offset added in v0.5.0

Offset sets the result offset.

func (*MemorySearchCriteriaBuilder) Query added in v0.5.0

Query sets the search query string.

func (*MemorySearchCriteriaBuilder) Scope added in v0.5.0

Scope appends a typed scope filter.

func (*MemorySearchCriteriaBuilder) Scopes added in v0.5.0

Scopes replaces the typed scope filters.

func (*MemorySearchCriteriaBuilder) Source added in v0.11.0

Source appends a memory source filter.

func (*MemorySearchCriteriaBuilder) Sources added in v0.11.0

Sources replaces the memory source filters.

func (*MemorySearchCriteriaBuilder) Status added in v0.5.0

Status appends a lifecycle status filter.

func (*MemorySearchCriteriaBuilder) Statuses added in v0.5.0

Statuses replaces the lifecycle status filters.

type MemoryStatusCounts added in v0.20.0

type MemoryStatusCounts struct {
	Accepted  int
	Candidate int
}

MemoryStatusCounts holds the true per-status durable-memory row counts, independent of any list scan limit. It backs the reliability pane's candidate/accepted totals when the bounded summary scan is saturated (see topReliabilityMemoryScanLimit).

type MemorySummary added in v0.5.0

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

MemorySummary holds read-side information about a single durable memory.

func MemorySummaryFrom added in v0.5.0

func MemorySummaryFrom(memory *model.Memory) (MemorySummary, error)

MemorySummaryFrom creates a MemorySummary from a Memory aggregate.

func MemorySummaryOf added in v0.5.0

func MemorySummaryOf(
	memoryID domtypes.MemoryID,
	memoryType domtypes.MemoryType,
	scope domtypes.MemoryScope,
	fact string,
	status domtypes.MemoryStatus,
	confidence domtypes.Confidence,
	source domtypes.MemorySource,
	supersedes domtypes.Optional[domtypes.MemoryID],
	expiresAt domtypes.Optional[time.Time],
	validFrom time.Time,
	validTo domtypes.Optional[time.Time],
	createdAt time.Time,
	updatedAt time.Time,
) (MemorySummary, error)

MemorySummaryOf creates a MemorySummary. validFrom must be non-zero; post-migration callers can default to createdAt when they have no more specific value. validTo stays optional so open-ended validity remains the default.

func (MemorySummary) Confidence added in v0.5.0

func (s MemorySummary) Confidence() domtypes.Confidence

Confidence returns the memory confidence.

func (MemorySummary) CreatedAt added in v0.5.0

func (s MemorySummary) CreatedAt() time.Time

CreatedAt returns when the memory was created.

func (MemorySummary) ExpiresAt added in v0.5.0

func (s MemorySummary) ExpiresAt() domtypes.Optional[time.Time]

ExpiresAt returns the expiry timestamp, when present.

func (MemorySummary) Fact added in v0.5.0

func (s MemorySummary) Fact() string

Fact returns the distilled fact.

func (MemorySummary) MemoryID added in v0.5.0

func (s MemorySummary) MemoryID() domtypes.MemoryID

MemoryID returns the memory ID.

func (MemorySummary) MemoryType added in v0.5.0

func (s MemorySummary) MemoryType() domtypes.MemoryType

MemoryType returns the memory type.

func (MemorySummary) Scope added in v0.5.0

Scope returns the memory scope.

func (MemorySummary) Source added in v0.5.0

func (s MemorySummary) Source() domtypes.MemorySource

Source returns the memory source attribution.

func (MemorySummary) Status added in v0.5.0

func (s MemorySummary) Status() domtypes.MemoryStatus

Status returns the memory lifecycle status.

func (MemorySummary) Supersedes added in v0.5.0

Supersedes returns the superseded memory ID, when present.

func (MemorySummary) UpdatedAt added in v0.5.0

func (s MemorySummary) UpdatedAt() time.Time

UpdatedAt returns when the memory was last updated.

func (MemorySummary) ValidFrom added in v0.8.0

func (s MemorySummary) ValidFrom() time.Time

ValidFrom returns the start of the content validity window.

func (MemorySummary) ValidTo added in v0.8.0

func (s MemorySummary) ValidTo() domtypes.Optional[time.Time]

ValidTo returns the end of the content validity window, when present.

type OneShotRepairApplyParams added in v0.31.0

type OneShotRepairApplyParams struct {
	Repair     OneShotRepairParams
	BackupPath string
}

OneShotRepairApplyParams requires a rollback snapshot for a write operation.

type OneShotRepairCandidate added in v0.31.0

type OneShotRepairCandidate struct {
	SessionID         domtypes.SessionID          `json:"session_id"`
	StoredRuntimeMode domtypes.RuntimeMode        `json:"stored_runtime_mode,omitempty"`
	ProposedReason    domtypes.TerminalReason     `json:"proposed_terminal_reason"`
	CompletedAt       time.Time                   `json:"completed_at"`
	LatestActivityAt  time.Time                   `json:"latest_activity_at,omitempty"`
	EvidenceSource    OneShotRepairEvidenceSource `json:"evidence_source"`
	EvidenceRef       string                      `json:"evidence_ref"`
	Eligible          bool                        `json:"eligible"`
	Applied           bool                        `json:"applied"`
	Decision          string                      `json:"decision"`
}

OneShotRepairCandidate explains the decision for one evidence entry.

type OneShotRepairEvidenceEntry added in v0.31.0

type OneShotRepairEvidenceEntry struct {
	SessionID      domtypes.SessionID
	RuntimeMode    domtypes.RuntimeMode
	TerminalReason domtypes.TerminalReason
	CompletedAt    time.Time
	EvidenceSource OneShotRepairEvidenceSource
	EvidenceRef    string
}

OneShotRepairEvidenceEntry is one operator-supplied terminal attestation.

type OneShotRepairEvidenceSource added in v0.31.0

type OneShotRepairEvidenceSource string

OneShotRepairEvidenceSource identifies the authoritative process-exit record supplied by the operator. These values never include transcript inference.

const (
	// OneShotRepairEvidenceSupervisedProcess is emitted by Traceary's process supervisor.
	OneShotRepairEvidenceSupervisedProcess OneShotRepairEvidenceSource = "supervised_process_exit"
	// OneShotRepairEvidenceCodexExec identifies an observed Codex exec process exit.
	OneShotRepairEvidenceCodexExec OneShotRepairEvidenceSource = "codex_exec_exit"
	// OneShotRepairEvidenceBatchRunner identifies a batch runner's per-child exit record.
	OneShotRepairEvidenceBatchRunner OneShotRepairEvidenceSource = "batch_runner_exit"
	// OneShotRepairEvidenceOperatorAttested identifies an explicit operator attestation.
	OneShotRepairEvidenceOperatorAttested OneShotRepairEvidenceSource = "operator_attested_process_exit"
)

type OneShotRepairParams added in v0.31.0

type OneShotRepairParams struct {
	Entries      []OneShotRepairEvidenceEntry
	EvidenceHash string
	StaleAfter   time.Duration
	Now          time.Time
}

OneShotRepairParams defines one evidence-backed preview or apply operation.

type OneShotRepairResult added in v0.31.0

type OneShotRepairResult struct {
	EvidenceHash string                   `json:"evidence_hash"`
	ApplyMode    bool                     `json:"apply_mode"`
	Before       OneShotRepairStats       `json:"before"`
	After        OneShotRepairStats       `json:"after"`
	Candidates   []OneShotRepairCandidate `json:"candidates"`
}

OneShotRepairResult is the complete explainable outcome of one run.

func (OneShotRepairResult) AppliedCount added in v0.31.0

func (r OneShotRepairResult) AppliedCount() int

AppliedCount returns the number of terminal transitions committed by this run.

type OneShotRepairStats added in v0.31.0

type OneShotRepairStats struct {
	ActiveCount    int `json:"active_count"`
	StaleCount     int `json:"stale_count"`
	CompletedCount int `json:"completed_count"`
	FailedCount    int `json:"failed_count"`
}

OneShotRepairStats reports lifecycle counts across the store snapshot.

type RawBodyApplyResult added in v0.31.0

type RawBodyApplyResult struct {
	PlanID         string
	CandidateCount int
	PrunedCount    int
	AlreadyPruned  int
}

RawBodyApplyResult reports an idempotent plan application.

type RawBodyCandidate added in v0.31.0

type RawBodyCandidate struct {
	EventID     string
	CreatedAt   time.Time
	StoredBytes int
	BodySHA256  string
}

RawBodyCandidate identifies one exact persisted event-body version.

type RawBodyRecoveryBody added in v0.31.0

type RawBodyRecoveryBody struct {
	Candidate RawBodyCandidate
	Body      string
}

RawBodyRecoveryBody contains one verified body used only at the executor boundary.

type RawBodyRestoreResult added in v0.31.0

type RawBodyRestoreResult struct {
	PlanID          string
	CandidateCount  int
	RestoredCount   int
	AlreadyRestored int
}

RawBodyRestoreResult reports an idempotent recovery operation.

type RawBodyRetentionSnapshot added in v0.31.0

type RawBodyRetentionSnapshot struct {
	DatabaseIdentity  string
	SQLiteUserVersion int
	MigrationDigest   string
	SnapshotAt        time.Time
	Candidates        []RawBodyCandidate
	ExcludedActive    []string
}

RawBodyRetentionSnapshot is the body-safe result of a read-only planner scan.

type RecentCommandSummary added in v0.31.0

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

RecentCommandSummary is a body-safe handoff projection with enough provenance for consumers to decide whether explicit detail retrieval is necessary.

func RecentCommandSummaryOf added in v0.31.0

func RecentCommandSummaryOf(
	eventID domtypes.EventID,
	summary string,
	responseTruncated bool,
	bodyExtent EventBodyExtent,
	createdAt time.Time,
) (RecentCommandSummary, error)

RecentCommandSummaryOf creates a structured recent-command projection.

func (RecentCommandSummary) BodyExtent added in v0.31.0

func (s RecentCommandSummary) BodyExtent() EventBodyExtent

BodyExtent returns persisted body size and truncation facts.

func (RecentCommandSummary) CreatedAt added in v0.31.0

func (s RecentCommandSummary) CreatedAt() time.Time

CreatedAt returns the event timestamp.

func (RecentCommandSummary) EventID added in v0.31.0

EventID returns the event identity.

func (RecentCommandSummary) ResponseTruncated added in v0.31.0

func (s RecentCommandSummary) ResponseTruncated() bool

ResponseTruncated reports whether the handoff response omitted stored body content.

func (RecentCommandSummary) ReturnedBytes added in v0.31.0

func (s RecentCommandSummary) ReturnedBytes() int

ReturnedBytes returns the UTF-8 byte count included in Summary.

func (RecentCommandSummary) Summary added in v0.31.0

func (s RecentCommandSummary) Summary() string

Summary returns the body-safe, single-line command summary.

type ReplayBundle added in v0.8.0

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

ReplayBundle is the cross-aggregate result returned by ReplayUsecase. It carries the sessions (with their per-session events), the memory panel scoped to those sessions' workspaces, a timeline of recent work blocks (same shape as `traceary timeline`), and a failure hotspot ranking of command_executed events with non-zero exit code. Presentation callers render the replay HTML from this snapshot without re-querying the store.

func ReplayBundleOf added in v0.8.0

func ReplayBundleOf(
	generatedAt time.Time,
	sessions []ReplayBundleSession,
	memories []MemorySummary,
	timelineBlocks []TimelineBlock,
	failureHotspots []ReplayFailureHotspot,
) ReplayBundle

ReplayBundleOf creates a ReplayBundle and defensively copies its slices so the presentation caller cannot mutate the usecase's working set after it returns.

func (ReplayBundle) FailureHotspots added in v0.8.0

func (b ReplayBundle) FailureHotspots() []ReplayFailureHotspot

FailureHotspots returns the failure-hotspot ranking in descending count order. Mutating the returned slice does not affect the bundle.

func (ReplayBundle) GeneratedAt added in v0.8.0

func (b ReplayBundle) GeneratedAt() time.Time

GeneratedAt returns the wall-clock time the bundle was assembled.

func (ReplayBundle) Memories added in v0.8.0

func (b ReplayBundle) Memories() []MemorySummary

Memories returns the memory panel in bundle order. The slice is a copy so the caller can mutate it safely.

func (ReplayBundle) Sessions added in v0.8.0

func (b ReplayBundle) Sessions() []ReplayBundleSession

Sessions returns the per-session slice. Mutating the returned slice does not affect the bundle.

func (ReplayBundle) TimelineBlocks added in v0.8.0

func (b ReplayBundle) TimelineBlocks() []TimelineBlock

TimelineBlocks returns the recent work blocks. Mutating the returned slice does not affect the bundle.

type ReplayBundleSession added in v0.8.0

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

ReplayBundleSession pairs a session summary with the events loaded for it inside the replay bundle. The event list is already capped at ReplayCriteria.EventsPerSession.

func ReplayBundleSessionOf added in v0.8.0

func ReplayBundleSessionOf(summary SessionSummary, events []*model.Event) ReplayBundleSession

ReplayBundleSessionOf creates a ReplayBundleSession pairing a summary with its event list.

func (ReplayBundleSession) Events added in v0.8.0

func (s ReplayBundleSession) Events() []*model.Event

Events returns a copy of the events loaded for this session.

func (ReplayBundleSession) Summary added in v0.8.0

func (s ReplayBundleSession) Summary() SessionSummary

Summary returns the session summary inside a ReplayBundleSession.

type ReplayCriteria added in v0.8.0

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

ReplayCriteria holds the inputs the replay usecase consumes when it assembles a cross-aggregate bundle for a browser-viewable HTML export. Zero values fall back to sensible defaults at the usecase layer so presentation callers do not need to know the defaults.

func (ReplayCriteria) EventsPerSession added in v0.8.0

func (c ReplayCriteria) EventsPerSession() int

EventsPerSession returns the cap applied to each session's event list.

func (ReplayCriteria) HotspotLimit added in v0.8.0

func (c ReplayCriteria) HotspotLimit() int

HotspotLimit returns the maximum number of failure hotspots to include. Values <= 0 instruct the usecase to skip the hotspot panel entirely.

func (ReplayCriteria) HotspotLookback added in v0.8.0

func (c ReplayCriteria) HotspotLookback() time.Duration

HotspotLookback returns the lookback window used to source failure events. Zero falls back to the usecase default (last 7 days).

func (ReplayCriteria) MemoryAsOf added in v0.8.0

func (c ReplayCriteria) MemoryAsOf() domtypes.Optional[time.Time]

MemoryAsOf returns the point-in-time used to evaluate memory validity windows. None means "use the current wall clock at query time".

func (ReplayCriteria) MemoryLimit added in v0.8.0

func (c ReplayCriteria) MemoryLimit() int

MemoryLimit returns the cap applied to the durable-memory panel. Any value <= 0 asks the usecase to skip the memory panel entirely; a positive value caps the row count returned.

func (ReplayCriteria) SessionLimit added in v0.8.0

func (c ReplayCriteria) SessionLimit() int

SessionLimit returns the maximum number of recent sessions to load.

func (ReplayCriteria) TimelineGapSeconds added in v0.8.0

func (c ReplayCriteria) TimelineGapSeconds() int

TimelineGapSeconds returns the idle-gap threshold (in seconds) used to segment events into work blocks. 0 falls back to the usecase default (15 minutes).

func (ReplayCriteria) TimelineLimit added in v0.8.0

func (c ReplayCriteria) TimelineLimit() int

TimelineLimit returns the maximum number of timeline blocks to include. Values <= 0 instruct the usecase to skip the timeline panel entirely.

type ReplayCriteriaBuilder added in v0.8.0

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

ReplayCriteriaBuilder constructs a ReplayCriteria.

func NewReplayCriteriaBuilder added in v0.8.0

func NewReplayCriteriaBuilder(sessionLimit, eventsPerSession, memoryLimit int) *ReplayCriteriaBuilder

NewReplayCriteriaBuilder starts building with the three session-side caps required by the replay export.

func (*ReplayCriteriaBuilder) Build added in v0.8.0

Build returns the finalized ReplayCriteria value.

func (*ReplayCriteriaBuilder) HotspotLimit added in v0.8.0

func (b *ReplayCriteriaBuilder) HotspotLimit(value int) *ReplayCriteriaBuilder

HotspotLimit sets the maximum number of failure hotspots. Values <= 0 skip the panel.

func (*ReplayCriteriaBuilder) HotspotLookback added in v0.8.0

func (b *ReplayCriteriaBuilder) HotspotLookback(value time.Duration) *ReplayCriteriaBuilder

HotspotLookback sets the lookback window for the failure hotspot query. Zero falls back to the usecase default.

func (*ReplayCriteriaBuilder) MemoryAsOf added in v0.8.0

func (b *ReplayCriteriaBuilder) MemoryAsOf(value time.Time) *ReplayCriteriaBuilder

MemoryAsOf sets the timestamp used to evaluate memory validity windows. Zero values are ignored so the replay defaults to "as of now".

func (*ReplayCriteriaBuilder) TimelineGapSeconds added in v0.8.0

func (b *ReplayCriteriaBuilder) TimelineGapSeconds(value int) *ReplayCriteriaBuilder

TimelineGapSeconds sets the idle-gap threshold. 0 falls back to the usecase default.

func (*ReplayCriteriaBuilder) TimelineLimit added in v0.8.0

func (b *ReplayCriteriaBuilder) TimelineLimit(value int) *ReplayCriteriaBuilder

TimelineLimit sets the maximum number of timeline blocks. Values <= 0 skip the panel.

type ReplayFailureHotspot added in v0.8.0

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

ReplayFailureHotspot clusters non-zero-exit-code command_executed events by normalized command prefix (first whitespace-delimited token) within a workspace, so operators can see where the failures pile up at a glance. Count is the number of failure events in the cluster and LastOccurredAt is the most recent of those events.

func ReplayFailureHotspotOf added in v0.8.0

func ReplayFailureHotspotOf(command, workspace string, count int, lastOccurredAt time.Time) ReplayFailureHotspot

ReplayFailureHotspotOf creates a ReplayFailureHotspot value.

func (ReplayFailureHotspot) Command added in v0.8.0

func (h ReplayFailureHotspot) Command() string

Command returns the normalized command prefix the hotspot clusters around (for example "go" for any `go test` / `go vet` failure).

func (ReplayFailureHotspot) Count added in v0.8.0

func (h ReplayFailureHotspot) Count() int

Count returns the number of failure events in the cluster.

func (ReplayFailureHotspot) LastOccurredAt added in v0.8.0

func (h ReplayFailureHotspot) LastOccurredAt() time.Time

LastOccurredAt returns the most recent failure timestamp in the cluster.

func (ReplayFailureHotspot) Workspace added in v0.8.0

func (h ReplayFailureHotspot) Workspace() string

Workspace returns the workspace the hotspot was observed in. Empty when the event did not carry a workspace.

type ReportAggregation added in v0.31.0

type ReportAggregation struct {
	Coverage  ReportCoverage      `json:"coverage" jsonschema:"complete only when all aggregate sources are complete"`
	PageSize  int                 `json:"page_size" jsonschema:"internal database page size"`
	ResultCap int                 `json:"result_cap,omitempty" jsonschema:"caller-requested per-source row cap; omitted means unlimited"`
	Sources   ReportSourceExtents `json:"sources"`
}

ReportAggregation describes overall and per-source aggregate completeness.

type ReportCommandOutput added in v0.31.0

type ReportCommandOutput struct {
	Command       string   `json:"command"`
	Count         int      `json:"count"`
	FailedCount   int      `json:"failed_count"`
	FailureRate   *float64 `json:"failure_rate,omitempty"`
	SampleEventID string   `json:"sample_event_id,omitempty"`
}

ReportCommandOutput is one normalized command aggregate.

type ReportCommandRecord added in v0.31.0

type ReportCommandRecord struct {
	EventID       domtypes.EventID
	Client        domtypes.Client
	Agent         domtypes.Agent
	SessionID     domtypes.SessionID
	Workspace     domtypes.Workspace
	Wrapper       domtypes.Optional[domtypes.CommandName]
	CommandName   domtypes.CommandName
	ExitCode      domtypes.Optional[int]
	Failed        bool
	FailureReason domtypes.CommandFailureReason
	CreatedAt     time.Time
}

ReportCommandRecord is the body-free read model used to aggregate command audit outcomes for a report.

func (ReportCommandRecord) EffectiveFailureReason added in v0.31.0

func (r ReportCommandRecord) EffectiveFailureReason() domtypes.CommandFailureReason

EffectiveFailureReason returns a reportable reason without inferring from text. Legacy non-zero exit codes can be identified structurally; other legacy failures remain unknown.

func (ReportCommandRecord) IsFailure added in v0.31.0

func (r ReportCommandRecord) IsFailure() bool

IsFailure applies the compatibility rule for report aggregation. An explicit zero exit code is always success; known reasons are authoritative; legacy unknown rows fall back to their persisted failed/non-zero evidence.

type ReportCommandRow added in v0.31.0

type ReportCommandRow struct {
	Command       string
	Count         int
	FailedCount   int
	FailureRate   float64
	SampleEventID string
}

ReportCommandRow contains one normalized executable aggregate.

type ReportCommandSummary added in v0.31.0

type ReportCommandSummary struct {
	FailureTotal     int
	FailuresByClient map[string]int
	FailuresByReason map[string]int
	FailureSamples   []string
	TopCommands      []ReportCommandRow
	FailureLoops     []ReportFailureLoop
}

ReportCommandSummary is the body-free command portion of a report.

type ReportCoverage added in v0.31.0

type ReportCoverage string

ReportCoverage identifies whether an aggregate covers the full requested filter or an explicitly capped prefix.

const (
	// ReportCoverageComplete means all matching rows were aggregated.
	ReportCoverageComplete ReportCoverage = "complete"
	// ReportCoveragePartial means result_cap excluded matching rows.
	ReportCoveragePartial ReportCoverage = "partial"
)

type ReportCoverageRow added in v0.31.0

type ReportCoverageRow struct {
	Client                       string   `json:"client"`
	Sessions                     int      `json:"sessions"`
	WithPrompt                   int      `json:"with_prompt"`
	WithTranscript               int      `json:"with_transcript"`
	WithCommand                  int      `json:"with_command"`
	PromptTranscriptMissing      int      `json:"prompt_transcript_missing"`
	PromptTranscriptMissingRatio *float64 `json:"prompt_transcript_missing_ratio,omitempty"`
}

ReportCoverageRow is one client-grouped capture coverage aggregate.

type ReportCriteria added in v0.31.0

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

ReportCriteria is the validated, provider-neutral input shared by CLI and MCP report surfaces.

func ReportCriteriaFrom added in v0.31.0

func ReportCriteriaFrom(
	requestedFrom, requestedTo, timezone string,
	snapshotAt time.Time,
	workspace domtypes.Workspace,
	client domtypes.Client,
	pageSize, resultCap int,
) (ReportCriteria, error)

ReportCriteriaFrom validates one report request. Both omitted bounds select the default seven-day window while preserving the omitted requested values.

func (ReportCriteria) Client added in v0.31.0

func (c ReportCriteria) Client() domtypes.Client

Client returns the optional client filter.

func (ReportCriteria) Interval added in v0.31.0

func (c ReportCriteria) Interval() RequestedInterval

Interval returns the resolved half-open report interval.

func (ReportCriteria) PageSize added in v0.31.0

func (c ReportCriteria) PageSize() int

PageSize returns the internal database page size.

func (ReportCriteria) ResultCap added in v0.31.0

func (c ReportCriteria) ResultCap() int

ResultCap returns the per-source row cap, or zero for full aggregation.

func (ReportCriteria) Workspace added in v0.31.0

func (c ReportCriteria) Workspace() domtypes.Workspace

Workspace returns the optional workspace filter.

type ReportFailureLoop added in v0.31.0

type ReportFailureLoop struct {
	Command        string
	Workspace      string
	Agent          string
	Count          int
	SampleEventIDs []string
}

ReportFailureLoop identifies a repeated failure for one command identity.

type ReportFailureLoopOutput added in v0.31.0

type ReportFailureLoopOutput struct {
	Command        string   `json:"command"`
	Workspace      string   `json:"workspace,omitempty"`
	Agent          string   `json:"agent,omitempty"`
	Count          int      `json:"count"`
	SampleEventIDs []string `json:"sample_event_ids"`
}

ReportFailureLoopOutput describes one repeated command failure group.

type ReportFailures added in v0.31.0

type ReportFailures struct {
	Total    int            `json:"total"`
	ByClient map[string]int `json:"by_client"`
	ByReason map[string]int `json:"by_reason"`
	Samples  []string       `json:"sample_event_ids"`
}

ReportFailures summarizes failed command audits.

type ReportPeriod added in v0.31.0

type ReportPeriod struct {
	From                   string `json:"from"`
	To                     string `json:"to"`
	RequestedFrom          string `json:"requested_from"`
	RequestedTo            string `json:"requested_to"`
	EffectiveFromInclusive string `json:"effective_from_inclusive"`
	EffectiveToExclusive   string `json:"effective_to_exclusive"`
	Timezone               string `json:"timezone"`
	SnapshotAt             string `json:"snapshot_at"`
	FromDateOnly           bool   `json:"from_date_only"`
	ToDateOnly             bool   `json:"to_date_only"`
}

ReportPeriod preserves requested bounds and exposes their resolved interval.

type ReportSessionRecord added in v0.31.0

type ReportSessionRecord struct {
	Client       domtypes.Client
	StartedAt    time.Time
	TotalEvents  int
	CommandCount int
}

ReportSessionRecord is the body-free session projection required by report aggregation.

type ReportSessionRow added in v0.31.0

type ReportSessionRow struct {
	Client       string `json:"client"`
	Sessions     int    `json:"sessions"`
	TotalEvents  int    `json:"total_events"`
	CommandCount int    `json:"command_count"`
}

ReportSessionRow is one client-grouped session aggregate.

type ReportSnapshot added in v0.31.0

type ReportSnapshot struct {
	Period           ReportPeriod              `json:"period"`
	Aggregation      ReportAggregation         `json:"aggregation"`
	Workspace        string                    `json:"workspace,omitempty"`
	ClientFilter     string                    `json:"client,omitempty"`
	Sessions         []ReportSessionRow        `json:"sessions"`
	CaptureCoverage  []ReportCoverageRow       `json:"capture_coverage"`
	Failures         ReportFailures            `json:"failures"`
	TopCommands      []ReportCommandOutput     `json:"top_commands"`
	FailureLoops     []ReportFailureLoopOutput `json:"failure_loops,omitempty"`
	Usage            ReportUsageSnapshot       `json:"usage"`
	EventScanCount   int                       `json:"event_scan_count"`
	SessionScanCount int                       `json:"session_scan_count"`
	UsageScanCount   int                       `json:"usage_scan_count"`
}

ReportSnapshot is the shared CLI/MCP report response.

type ReportSourceExtent added in v0.31.0

type ReportSourceExtent struct {
	Coverage           ReportCoverage `json:"coverage" jsonschema:"complete when the full filter was scanned; partial when result_cap truncated the source"`
	ObservedCount      int            `json:"observed_count" jsonschema:"rows included in this aggregate"`
	PageSize           int            `json:"page_size" jsonschema:"internal database page size"`
	ResultCap          int            `json:"result_cap,omitempty" jsonschema:"caller-requested per-source row cap; omitted means unlimited"`
	ResponseTruncated  bool           `json:"response_truncated" jsonschema:"whether rows beyond result_cap were excluded"`
	TruncationReason   string         `json:"truncation_reason,omitempty" jsonschema:"result_cap when response_truncated is true"`
	ObservedEarliestAt string         `json:"observed_earliest_at,omitempty" jsonschema:"earliest included row timestamp (RFC3339Nano)"`
	ObservedLatestAt   string         `json:"observed_latest_at,omitempty" jsonschema:"latest included row timestamp (RFC3339Nano)"`
}

ReportSourceExtent describes the returned portion of one aggregate source. It mirrors response-truncation provenance: a partial source names the cap that cut the response and the observed time range.

func ReportSourceExtentOf added in v0.31.0

func ReportSourceExtentOf(observedAt []time.Time, pageSize, resultCap int, truncated bool) (ReportSourceExtent, error)

ReportSourceExtentOf creates validated extent metadata from the included row timestamps. Callers pass only returned rows, not the sentinel row used to detect truncation.

type ReportSourceExtents added in v0.31.0

type ReportSourceExtents struct {
	Sessions ReportSourceExtent `json:"sessions"`
	Events   ReportSourceExtent `json:"events"`
	Commands ReportSourceExtent `json:"commands"`
	Usage    ReportSourceExtent `json:"usage"`
}

ReportSourceExtents groups provenance for each aggregate source.

type ReportUsageAggregateRow added in v0.32.0

type ReportUsageAggregateRow struct {
	Provider          string               `json:"provider,omitempty"`
	Engine            string               `json:"engine"`
	Model             string               `json:"model,omitempty"`
	Role              string               `json:"role,omitempty"`
	RoleAvailability  string               `json:"role_availability"`
	Repository        string               `json:"repository,omitempty"`
	TicketRef         string               `json:"ticket,omitempty"`
	PullRequest       *int64               `json:"pull_request,omitempty"`
	BatchID           string               `json:"batch,omitempty"`
	Round             *int64               `json:"round,omitempty"`
	RoundAvailability string               `json:"round_availability"`
	Observations      int                  `json:"observations"`
	Accounted         int                  `json:"accounted_observations"`
	Excluded          int                  `json:"excluded_observations"`
	InputTokens       ReportUsageMetric    `json:"input_tokens"`
	CachedInputTokens ReportUsageMetric    `json:"cached_input_tokens"`
	CacheWriteTokens  ReportUsageMetric    `json:"cache_write_input_tokens"`
	OutputTokens      ReportUsageMetric    `json:"output_tokens"`
	ReasoningTokens   ReportUsageMetric    `json:"reasoning_output_tokens"`
	TotalTokens       ReportUsageMetric    `json:"total_tokens"`
	CostUnavailable   int                  `json:"cost_unavailable_observations"`
	Costs             []ReportUsageCostRow `json:"costs"`
	TerminalCodes     map[string]int       `json:"terminal_classifications"`
}

ReportUsageAggregateRow is one comparable provider/run-attribution group. Role and round remain explicitly unavailable until their authoritative values are persisted.

type ReportUsageCostRow added in v0.32.0

type ReportUsageCostRow struct {
	Origin            string `json:"origin" jsonschema:"provider_reported or estimated"`
	Currency          string `json:"currency"`
	PriceTableVersion string `json:"price_table_version,omitempty"`
	Observations      int    `json:"observations"`
	AmountMicros      int64  `json:"amount_micros"`
}

ReportUsageCostRow keeps provider-reported and estimated amounts separate.

type ReportUsageMetric added in v0.32.0

type ReportUsageMetric struct {
	KnownObservations       int   `json:"known_observations"`
	UnavailableObservations int   `json:"unavailable_observations"`
	Sum                     int64 `json:"sum"`
}

ReportUsageMetric aggregates one usage dimension without treating an unavailable value as numeric zero.

type ReportUsageRecord added in v0.32.0

type ReportUsageRecord struct {
	ObservationID   string
	ObservedAt      time.Time
	Engine          string
	Provider        string
	Model           string
	Accounting      domtypes.UsageAccounting
	TerminalCode    domtypes.UsageTerminalCode
	Counters        domtypes.UsageCounters
	Cost            domtypes.UsageCost
	RunHost         string
	RunID           string
	Repository      string
	TicketRef       string
	PullRequest     domtypes.Optional[int64]
	BatchID         string
	PacketBytes     domtypes.Optional[int64]
	ToolOutputBytes domtypes.Optional[int64]
}

ReportUsageRecord is one body-free finalized usage projection loaded under the report snapshot. Role, round, and wall time are intentionally absent because the durable schema does not currently record them.

type ReportUsageRunAggregateRow added in v0.32.0

type ReportUsageRunAggregateRow struct {
	Engine            string               `json:"engine"`
	Role              string               `json:"role,omitempty"`
	RoleAvailability  string               `json:"role_availability"`
	Repository        string               `json:"repository,omitempty"`
	TicketRef         string               `json:"ticket,omitempty"`
	PullRequest       *int64               `json:"pull_request,omitempty"`
	BatchID           string               `json:"batch,omitempty"`
	Round             *int64               `json:"round,omitempty"`
	RoundAvailability string               `json:"round_availability"`
	Runs              int                  `json:"runs"`
	PacketBytes       ReportUsageRunMetric `json:"packet_bytes"`
	ToolOutputBytes   ReportUsageRunMetric `json:"tool_output_bytes"`
	WallTimeMS        ReportUsageRunMetric `json:"wall_time_ms"`
}

ReportUsageRunAggregateRow reports immutable run facts separately from provider/model token groups so one run cannot multiply packet or tool bytes when it carries multiple usage observations.

type ReportUsageRunMetric added in v0.32.0

type ReportUsageRunMetric struct {
	KnownRuns       int   `json:"known_runs"`
	UnavailableRuns int   `json:"unavailable_runs"`
	Sum             int64 `json:"sum"`
}

ReportUsageRunMetric aggregates immutable run facts exactly once per run.

type ReportUsageSnapshot added in v0.32.0

type ReportUsageSnapshot struct {
	Aggregates []ReportUsageAggregateRow    `json:"aggregates"`
	Runs       []ReportUsageRunAggregateRow `json:"runs"`
}

ReportUsageSnapshot combines observation and run aggregates from the same database snapshot.

type ReportWindow added in v0.31.0

type ReportWindow struct {
	Sessions []ReportSessionRecord
	Events   []EventMetadata
	Commands []ReportCommandRecord
	Usage    []ReportUsageRecord
	Extents  ReportSourceExtents
}

ReportWindow is the raw, body-free snapshot returned by report storage.

type RequestedInterval added in v0.31.0

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

RequestedInterval preserves the caller-facing interval while exposing one effective half-open UTC range for every query surface. Date-only bounds are interpreted in Timezone; RFC3339 bounds are exact instants.

func RequestedIntervalFrom added in v0.31.0

func RequestedIntervalFrom(requestedFrom, requestedTo, timezone string, snapshotAt time.Time) (RequestedInterval, error)

RequestedIntervalFrom resolves caller-facing bounds into a half-open UTC interval. An omitted upper bound uses snapshotAt when it is non-zero.

func (RequestedInterval) EffectiveFromInclusive added in v0.31.0

func (i RequestedInterval) EffectiveFromInclusive() time.Time

EffectiveFromInclusive returns the resolved inclusive UTC lower bound.

func (RequestedInterval) EffectiveToExclusive added in v0.31.0

func (i RequestedInterval) EffectiveToExclusive() time.Time

EffectiveToExclusive returns the resolved exclusive UTC upper bound.

func (RequestedInterval) FromIsDateOnly added in v0.31.0

func (i RequestedInterval) FromIsDateOnly() bool

FromIsDateOnly reports whether the lower bound was a calendar date.

func (RequestedInterval) HasRequestedFrom added in v0.31.0

func (i RequestedInterval) HasRequestedFrom() bool

HasRequestedFrom reports whether the caller supplied a lower bound.

func (RequestedInterval) HasRequestedTo added in v0.31.0

func (i RequestedInterval) HasRequestedTo() bool

HasRequestedTo reports whether the caller supplied an upper bound.

func (RequestedInterval) RequestedFrom added in v0.31.0

func (i RequestedInterval) RequestedFrom() string

RequestedFrom returns the trimmed caller-supplied lower bound.

func (RequestedInterval) RequestedTo added in v0.31.0

func (i RequestedInterval) RequestedTo() string

RequestedTo returns the trimmed caller-supplied upper bound.

func (RequestedInterval) SnapshotAt added in v0.31.0

func (i RequestedInterval) SnapshotAt() time.Time

SnapshotAt returns the UTC snapshot supplied during resolution.

func (RequestedInterval) Timezone added in v0.31.0

func (i RequestedInterval) Timezone() string

Timezone returns the IANA timezone used for date-only bounds.

func (RequestedInterval) ToIsDateOnly added in v0.31.0

func (i RequestedInterval) ToIsDateOnly() bool

ToIsDateOnly reports whether the upper bound was a calendar date.

func (RequestedInterval) WithDefaultFrom added in v0.31.0

func (i RequestedInterval) WithDefaultFrom(fallback time.Time) (RequestedInterval, error)

WithDefaultFrom applies fallback as the effective lower bound only when the caller omitted the lower bound. The requested value remains empty so output can distinguish an explicit bound from a command-provided default window.

type RetentionCanonicalPayload added in v0.31.0

type RetentionCanonicalPayload struct {
	SchemaVersion        string                   `json:"schema_version"`
	CreatedAt            string                   `json:"created_at"`
	SnapshotAt           string                   `json:"snapshot_at"`
	Source               RetentionPlanSource      `json:"source"`
	Policy               RetentionPlanPolicy      `json:"policy"`
	ClassResults         []RetentionClassResult   `json:"class_results"`
	Candidates           []RetentionPlanCandidate `json:"candidates"`
	Exclusions           []RetentionPlanExclusion `json:"exclusions"`
	RecoveryRequirements []RetentionRecoveryPoint `json:"recovery_requirements"`
	Phases               []RetentionPlanPhase     `json:"phases"`
}

RetentionCanonicalPayload is the hashed portion of retention-plan/v1.

type RetentionCeilingResult added in v0.31.0

type RetentionCeilingResult struct {
	Ceiling   string          `json:"ceiling"`
	Status    string          `json:"status"`
	Current   RetentionExtent `json:"current"`
	Projected RetentionExtent `json:"projected"`
}

RetentionCeilingResult reports current and projected status for one ceiling.

type RetentionClassResult added in v0.31.0

type RetentionClassResult struct {
	Class    string                   `json:"class"`
	Status   string                   `json:"status"`
	Ceilings []RetentionCeilingResult `json:"ceilings"`
}

RetentionClassResult reports the AND-reduced status of one retention class.

type RetentionExtent added in v0.31.0

type RetentionExtent struct {
	Availability string `json:"availability"`
	Bytes        string `json:"bytes,omitempty"`
}

RetentionExtent distinguishes known byte values from unknown extents.

type RetentionPlan added in v0.31.0

type RetentionPlan struct {
	PlanID           string                    `json:"plan_id"`
	CanonicalPayload RetentionCanonicalPayload `json:"canonical_payload"`
	Display          RetentionPlanDisplay      `json:"display,omitempty"`
}

RetentionPlan is the reviewed JSON envelope consumed by apply/restore.

type RetentionPlanBatch added in v0.31.0

type RetentionPlanBatch struct {
	Ordinal             string   `json:"ordinal"`
	CandidateIdentities []string `json:"candidate_identities"`
}

RetentionPlanBatch groups ordered candidate identities for one transaction.

type RetentionPlanCandidate added in v0.31.0

type RetentionPlanCandidate struct {
	Class             string          `json:"class"`
	IdentityKind      string          `json:"identity_kind"`
	DatabaseIdentity  string          `json:"database_identity"`
	RootID            string          `json:"root_id"`
	RelativePath      string          `json:"relative_path"`
	Timestamp         string          `json:"timestamp"`
	CandidateIdentity string          `json:"candidate_identity"`
	LogicalExtent     RetentionExtent `json:"logical_extent"`
	AllocatedExtent   RetentionExtent `json:"allocated_extent"`
	Reasons           []string        `json:"reasons"`
}

RetentionPlanCandidate is one exact reviewed database or file identity.

type RetentionPlanDisplay added in v0.31.0

type RetentionPlanDisplay struct {
	Summary string `json:"summary,omitempty"`
}

RetentionPlanDisplay contains non-authoritative operator-facing fields.

type RetentionPlanExclusion added in v0.31.0

type RetentionPlanExclusion struct {
	Reason         string `json:"reason"`
	StableIdentity string `json:"stable_identity"`
}

RetentionPlanExclusion records one stable identity excluded from apply.

type RetentionPlanPhase added in v0.31.0

type RetentionPlanPhase struct {
	Phase        string               `json:"phase"`
	Batches      []RetentionPlanBatch `json:"batches"`
	OrderedSteps []string             `json:"ordered_steps"`
}

RetentionPlanPhase records ordered execution steps for one retention phase.

type RetentionPlanPolicy added in v0.31.0

type RetentionPlanPolicy struct {
	Ceilings []RetentionPolicyCeiling `json:"ceilings"`
}

RetentionPlanPolicy records the configured ceilings used by the planner.

type RetentionPlanRoot added in v0.31.0

type RetentionPlanRoot struct {
	RootID      string `json:"root_id"`
	Fingerprint string `json:"fingerprint"`
}

RetentionPlanRoot identifies one reviewed filesystem root without exposing it.

type RetentionPlanSource added in v0.31.0

type RetentionPlanSource struct {
	DatabaseIdentity  string              `json:"database_identity"`
	SQLiteUserVersion int                 `json:"sqlite_user_version"`
	MigrationDigest   string              `json:"migration_digest"`
	Roots             []RetentionPlanRoot `json:"roots"`
}

RetentionPlanSource identifies the exact source store and reviewed roots.

type RetentionPolicyCeiling added in v0.31.0

type RetentionPolicyCeiling struct {
	Class   string `json:"class"`
	Ceiling string `json:"ceiling"`
	Value   string `json:"value"`
}

RetentionPolicyCeiling records one class-specific policy ceiling.

type RetentionRecoveryPoint added in v0.31.0

type RetentionRecoveryPoint struct {
	Generation     string `json:"generation"`
	Digest         string `json:"digest"`
	RootID         string `json:"root_id"`
	RelativePath   string `json:"relative_path"`
	CoverageDigest string `json:"coverage_digest"`
	State          string `json:"state"`
}

RetentionRecoveryPoint pins the verified recovery artifact required by apply.

type SessionListCriteria

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

SessionListCriteria holds filter parameters for session listing. Zero-value fields are ignored (no filter applied).

func (SessionListCriteria) ActiveOnly added in v0.10.0

func (c SessionListCriteria) ActiveOnly() bool

ActiveOnly reports whether only active sessions should be returned.

func (SessionListCriteria) Agent

Agent returns the agent filter.

func (SessionListCriteria) Client

func (c SessionListCriteria) Client() domtypes.Client

Client returns the client filter.

func (SessionListCriteria) From

From returns the lower bound of the time range (inclusive).

func (SessionListCriteria) Label

func (c SessionListCriteria) Label() string

Label returns the session label filter.

func (SessionListCriteria) Limit

func (c SessionListCriteria) Limit() int

Limit returns the maximum number of results to return.

func (SessionListCriteria) Offset

func (c SessionListCriteria) Offset() int

Offset returns the number of results to skip before returning matches.

func (SessionListCriteria) SessionID

func (c SessionListCriteria) SessionID() domtypes.SessionID

SessionID returns the session ID filter.

func (SessionListCriteria) To

To returns the upper bound of the time range (exclusive).

func (SessionListCriteria) Workspace

func (c SessionListCriteria) Workspace() domtypes.Workspace

Workspace returns the workspace filter.

type SessionListCriteriaBuilder

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

SessionListCriteriaBuilder builds a SessionListCriteria value.

func NewSessionListCriteriaBuilder

func NewSessionListCriteriaBuilder(limit int) *SessionListCriteriaBuilder

NewSessionListCriteriaBuilder starts building with the given limit. Limit is required; other fields are optional.

func (*SessionListCriteriaBuilder) ActiveOnly added in v0.10.0

func (b *SessionListCriteriaBuilder) ActiveOnly(activeOnly bool) *SessionListCriteriaBuilder

ActiveOnly restricts the list to active sessions when set to true.

func (*SessionListCriteriaBuilder) Agent

Agent sets the agent filter.

func (*SessionListCriteriaBuilder) Build

Build finalizes and returns the SessionListCriteria.

func (*SessionListCriteriaBuilder) Client

Client sets the client filter.

func (*SessionListCriteriaBuilder) From

From sets the lower bound of the time range (inclusive).

func (*SessionListCriteriaBuilder) Label

Label sets the session label filter.

func (*SessionListCriteriaBuilder) Offset

Offset sets the number of results to skip before returning matches.

func (*SessionListCriteriaBuilder) SessionID

SessionID sets the session ID filter.

func (*SessionListCriteriaBuilder) To

To sets the upper bound of the time range (exclusive).

func (*SessionListCriteriaBuilder) Workspace

Workspace sets the workspace filter.

type SessionLookupCriteria

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

SessionLookupCriteria holds filter parameters for single-session lookup (active session, latest session). Zero-value fields are ignored (no filter applied).

func (SessionLookupCriteria) ActiveOnly

func (c SessionLookupCriteria) ActiveOnly() bool

ActiveOnly reports whether only active sessions should be considered.

func (SessionLookupCriteria) Agent

Agent returns the agent filter.

func (SessionLookupCriteria) Client

Client returns the client filter.

func (SessionLookupCriteria) Workspace

Workspace returns the workspace filter.

type SessionLookupCriteriaBuilder

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

SessionLookupCriteriaBuilder builds a SessionLookupCriteria value.

func NewSessionLookupCriteriaBuilder

func NewSessionLookupCriteriaBuilder() *SessionLookupCriteriaBuilder

NewSessionLookupCriteriaBuilder starts building an empty SessionLookupCriteria.

func (*SessionLookupCriteriaBuilder) ActiveOnly

ActiveOnly restricts the lookup to active sessions when set to true.

func (*SessionLookupCriteriaBuilder) Agent

Agent sets the agent filter.

func (*SessionLookupCriteriaBuilder) Build

Build finalizes and returns the SessionLookupCriteria.

func (*SessionLookupCriteriaBuilder) Client

Client sets the client filter.

func (*SessionLookupCriteriaBuilder) Workspace

Workspace sets the workspace filter.

type SessionModel added in v0.26.1

type SessionModel string

SessionModel is a host-reported model identifier attached to a SessionSummary. Empty means the host did not report a model.

type SessionSummary

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

SessionSummary holds aggregated information about a single session.

func SessionSummaryOf

func SessionSummaryOf(
	sessionID domtypes.SessionID,
	workspace domtypes.Workspace,
	startedAt time.Time,
	endedAt domtypes.Optional[time.Time],
	status string,
	totalEvents int,
	commandCount int,
	agents []string,
	label string,
	summary string,
	parentSessionID domtypes.SessionID,
	spawnMetadata ...any,
) SessionSummary

SessionSummaryOf creates a SessionSummary.

func (SessionSummary) Agents

func (s SessionSummary) Agents() []string

Agents returns the list of agents that participated.

func (SessionSummary) Client added in v0.10.0

func (s SessionSummary) Client() domtypes.Client

Client returns the recording client.

func (SessionSummary) CommandCount

func (s SessionSummary) CommandCount() int

CommandCount returns the number of command_executed events.

func (SessionSummary) EndedAt

func (s SessionSummary) EndedAt() domtypes.Optional[time.Time]

EndedAt returns when the session ended.

func (SessionSummary) Label

func (s SessionSummary) Label() string

Label returns the user-assigned label.

func (SessionSummary) LatestEventAt added in v0.10.0

func (s SessionSummary) LatestEventAt() time.Time

LatestEventAt returns the latest recorded event timestamp in the session.

func (SessionSummary) LatestEventID added in v0.21.0

func (s SessionSummary) LatestEventID() domtypes.EventID

LatestEventID returns the identifier of the latest recorded event in the session, or empty when the session has no events. It is the retrieval hint for fetching the full body explicitly via `traceary show <event_id>`.

func (SessionSummary) LatestEventKind added in v0.10.3

func (s SessionSummary) LatestEventKind() domtypes.EventKind

LatestEventKind returns the kind of the latest recorded event in the session.

func (SessionSummary) LatestEventMessage added in v0.10.3

func (s SessionSummary) LatestEventMessage() string

LatestEventMessage returns the plain-text message of the latest recorded event in the session.

func (SessionSummary) Model added in v0.26.1

func (s SessionSummary) Model() string

Model returns the host-reported model identifier, or empty when unavailable.

func (SessionSummary) ParentSessionID

func (s SessionSummary) ParentSessionID() domtypes.SessionID

ParentSessionID returns the parent session ID.

func (SessionSummary) SessionID

func (s SessionSummary) SessionID() domtypes.SessionID

SessionID returns the session ID.

func (SessionSummary) SpawnEventID added in v0.10.0

func (s SessionSummary) SpawnEventID() domtypes.EventID

SpawnEventID returns the event that spawned this session, or empty if unknown.

func (SessionSummary) SpawnOrder added in v0.10.0

func (s SessionSummary) SpawnOrder() domtypes.Optional[int]

SpawnOrder returns this child session's sibling order when available.

func (SessionSummary) StartedAt

func (s SessionSummary) StartedAt() time.Time

StartedAt returns when the session started.

func (SessionSummary) Status

func (s SessionSummary) Status() string

Status returns the session status (active, stale, ended, ended_with_late_events).

func (SessionSummary) SubagentKind added in v0.10.0

func (s SessionSummary) SubagentKind() string

SubagentKind returns the kind of subagent spawn, or empty for top-level sessions.

func (SessionSummary) Summary

func (s SessionSummary) Summary() string

Summary returns the session summary text.

func (SessionSummary) TotalEvents

func (s SessionSummary) TotalEvents() int

TotalEvents returns the total number of events in the session.

func (SessionSummary) Workspace

func (s SessionSummary) Workspace() domtypes.Workspace

Workspace returns the workspace.

type SessionSummaryLatestEvent added in v0.10.3

type SessionSummaryLatestEvent struct {
	ID      domtypes.EventID
	Kind    domtypes.EventKind
	Message string
}

SessionSummaryLatestEvent carries latest-event metadata for SessionSummaryOf.

func SessionSummaryLatestEventOf added in v0.10.3

func SessionSummaryLatestEventOf(id domtypes.EventID, kind domtypes.EventKind, message string) SessionSummaryLatestEvent

SessionSummaryLatestEventOf creates latest-event metadata for SessionSummaryOf.

type StaleMemoryListCriteria added in v0.15.0

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

StaleMemoryListCriteria holds the filters for read-side stale-memory lists.

func (StaleMemoryListCriteria) AsOf added in v0.15.0

AsOf returns the evaluation time for validity-window checks.

func (StaleMemoryListCriteria) Limit added in v0.15.0

func (c StaleMemoryListCriteria) Limit() int

Limit returns the maximum number of rows to return.

func (StaleMemoryListCriteria) Offset added in v0.15.0

func (c StaleMemoryListCriteria) Offset() int

Offset returns the number of rows to skip after ordering.

func (StaleMemoryListCriteria) Scopes added in v0.15.0

Scopes returns the typed scope filters.

type StaleMemoryListCriteriaBuilder added in v0.15.0

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

StaleMemoryListCriteriaBuilder builds stale-memory list criteria.

func NewStaleMemoryListCriteriaBuilder added in v0.15.0

func NewStaleMemoryListCriteriaBuilder(limit int) *StaleMemoryListCriteriaBuilder

NewStaleMemoryListCriteriaBuilder starts building with the given limit.

func (*StaleMemoryListCriteriaBuilder) AsOf added in v0.15.0

AsOf sets the evaluation time for validity-window checks.

func (*StaleMemoryListCriteriaBuilder) Build added in v0.15.0

Build finalizes the criteria.

func (*StaleMemoryListCriteriaBuilder) Offset added in v0.15.0

Offset sets the number of rows to skip.

func (*StaleMemoryListCriteriaBuilder) Scope added in v0.15.0

Scope appends a typed scope filter.

func (*StaleMemoryListCriteriaBuilder) Scopes added in v0.15.0

Scopes replaces the typed scope filters.

type StaleMemoryListResult added in v0.15.0

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

StaleMemoryListResult carries a paged stale-memory result plus the total stale count before LIMIT/OFFSET are applied.

func StaleMemoryListResultOf added in v0.15.0

func StaleMemoryListResultOf(count int, items []StaleMemoryRow) (StaleMemoryListResult, error)

StaleMemoryListResultOf creates a stale-memory list result.

func (StaleMemoryListResult) Count added in v0.15.0

func (r StaleMemoryListResult) Count() int

Count returns the total stale-memory count before paging.

func (StaleMemoryListResult) Items added in v0.15.0

Items returns the paged stale-memory rows.

type StaleMemoryReason added in v0.15.0

type StaleMemoryReason string

StaleMemoryReason explains why a durable-memory row should be surfaced in the operator-facing stale-memory pane.

const (
	// StaleMemoryReasonExpired covers memories whose lifecycle status is
	// expired or whose content-validity window has already closed.
	StaleMemoryReasonExpired StaleMemoryReason = "expired"
	// StaleMemoryReasonSuperseded covers memories that have been replaced but
	// still exist in the local store for audit / pruning.
	StaleMemoryReasonSuperseded StaleMemoryReason = "superseded"
	// StaleMemoryReasonOverlap covers memories that are part of a deterministic
	// dedupe overlap hygiene hit.
	StaleMemoryReasonOverlap StaleMemoryReason = "overlap"
)

func StaleMemoryReasonFrom added in v0.15.0

func StaleMemoryReasonFrom(value string) (StaleMemoryReason, error)

StaleMemoryReasonFrom validates a serialized stale-memory reason.

func (StaleMemoryReason) String added in v0.15.0

func (r StaleMemoryReason) String() string

String returns the serialized reason value.

type StaleMemoryRow added in v0.15.0

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

StaleMemoryRow is the read-side row rendered by the stale-memory top pane.

func StaleMemoryRowOf added in v0.15.0

func StaleMemoryRowOf(summary MemorySummary, reason StaleMemoryReason) (StaleMemoryRow, error)

StaleMemoryRowOf creates a stale-memory row from an existing memory summary.

func (StaleMemoryRow) Reason added in v0.15.0

func (r StaleMemoryRow) Reason() StaleMemoryReason

Reason returns the staleness reason.

func (StaleMemoryRow) Summary added in v0.15.0

func (r StaleMemoryRow) Summary() MemorySummary

Summary returns the durable-memory summary for this stale row.

type StoreArchiveCreateParams added in v0.28.0

type StoreArchiveCreateParams struct {
	OutputPath        string
	Before            time.Time
	KeepDays          int
	Target            GarbageCollectionTarget
	DryRun            bool
	DeleteAfterVerify bool
	Passphrase        []byte
	ToolVersion       string
	SourceDBPath      string
}

StoreArchiveCreateParams configures archive create / archive-then-gc.

type StoreArchiveRestoreResult added in v0.28.0

type StoreArchiveRestoreResult struct {
	DryRun         bool
	Inserted       int
	Skipped        int
	Conflicts      int
	TotalInArchive int
}

StoreArchiveRestoreResult is the outcome of restore.

type StoreArchiveResult added in v0.28.0

type StoreArchiveResult struct {
	DryRun             bool
	Path               string
	Tables             []StoreArchiveTableCount
	TotalRows          int
	DeletedCount       int
	Verified           bool
	DeletedAfterVerify bool
}

StoreArchiveResult is the outcome of create (and optional delete).

type StoreArchiveTableCount added in v0.28.0

type StoreArchiveTableCount struct {
	Name     string
	RowCount int
}

StoreArchiveTableCount is per-table row counts in a plan or package.

type TimelineBlock

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

TimelineBlock represents a contiguous work block separated by idle gaps. It holds block-level aggregates plus a per-workspace breakdown.

func TimelineBlockOf

func TimelineBlockOf(
	blockStart time.Time,
	blockEnd time.Time,
	eventCount int,
	agents []string,
	workspaceBreakdown []TimelineWorkspaceBreakdown,
) TimelineBlock

TimelineBlockOf creates a TimelineBlock.

func (TimelineBlock) Agents

func (b TimelineBlock) Agents() []string

Agents returns the agents involved.

func (TimelineBlock) BlockEnd

func (b TimelineBlock) BlockEnd() time.Time

BlockEnd returns when the block ended.

func (TimelineBlock) BlockStart

func (b TimelineBlock) BlockStart() time.Time

BlockStart returns when the block started.

func (TimelineBlock) EventCount

func (b TimelineBlock) EventCount() int

EventCount returns the number of events in the block.

func (TimelineBlock) Kinds

func (b TimelineBlock) Kinds() []string

Kinds returns the union of kinds seen across every workspace in the block, preserving each workspace's kind ordering.

func (TimelineBlock) WorkspaceBreakdown added in v0.6.1

func (b TimelineBlock) WorkspaceBreakdown() []TimelineWorkspaceBreakdown

WorkspaceBreakdown returns per-workspace activity inside the block.

func (TimelineBlock) Workspaces

func (b TimelineBlock) Workspaces() []string

Workspaces returns the distinct workspaces involved in the block, derived from the workspace breakdown for backward compatibility with callers that only need the workspace list.

type TimelineCriteria

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

TimelineCriteria holds filter parameters for work timeline block listing. Zero-value fields are ignored (no filter applied).

func (TimelineCriteria) From

func (c TimelineCriteria) From() time.Time

From returns the lower bound of the time range (inclusive).

func (TimelineCriteria) GapSeconds

func (c TimelineCriteria) GapSeconds() int

GapSeconds returns the idle gap threshold in seconds.

func (TimelineCriteria) Limit

func (c TimelineCriteria) Limit() int

Limit returns the maximum number of blocks to return.

func (TimelineCriteria) To

func (c TimelineCriteria) To() time.Time

To returns the upper bound of the time range (exclusive).

func (TimelineCriteria) Workspace

func (c TimelineCriteria) Workspace() domtypes.Workspace

Workspace returns the workspace filter.

type TimelineCriteriaBuilder

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

TimelineCriteriaBuilder builds a TimelineCriteria value.

func NewTimelineCriteriaBuilder

func NewTimelineCriteriaBuilder(limit int) *TimelineCriteriaBuilder

NewTimelineCriteriaBuilder starts building with the given limit. Limit is required; other fields are optional.

func (*TimelineCriteriaBuilder) Build

Build finalizes and returns the TimelineCriteria.

func (*TimelineCriteriaBuilder) From

From sets the lower bound of the time range (inclusive).

func (*TimelineCriteriaBuilder) GapSeconds

func (b *TimelineCriteriaBuilder) GapSeconds(gapSeconds int) *TimelineCriteriaBuilder

GapSeconds sets the idle gap threshold in seconds.

func (*TimelineCriteriaBuilder) To

To sets the upper bound of the time range (exclusive).

func (*TimelineCriteriaBuilder) Workspace

Workspace sets the workspace filter.

type TimelineWorkspaceBreakdown added in v0.6.1

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

TimelineWorkspaceBreakdown captures per-workspace activity inside a timeline block. It is always nested under a TimelineBlock.

func TimelineWorkspaceBreakdownOf added in v0.6.1

func TimelineWorkspaceBreakdownOf(
	workspace string,
	eventCount int,
	kinds []string,
	agents []string,
	summary string,
	summarySource TimelineWorkspaceBreakdownSummarySource,
) TimelineWorkspaceBreakdown

TimelineWorkspaceBreakdownOf creates a TimelineWorkspaceBreakdown.

func (TimelineWorkspaceBreakdown) Agents added in v0.8.0

func (b TimelineWorkspaceBreakdown) Agents() []string

Agents returns the distinct agents that produced events for this workspace inside the block (#654).

func (TimelineWorkspaceBreakdown) EventCount added in v0.6.1

func (b TimelineWorkspaceBreakdown) EventCount() int

EventCount returns the number of events attributed to this workspace.

func (TimelineWorkspaceBreakdown) Kinds added in v0.6.1

func (b TimelineWorkspaceBreakdown) Kinds() []string

Kinds returns the kinds observed for this workspace inside the block.

func (TimelineWorkspaceBreakdown) Summary added in v0.6.1

func (b TimelineWorkspaceBreakdown) Summary() string

Summary returns the short activity summary for this workspace.

func (TimelineWorkspaceBreakdown) SummarySource added in v0.6.1

SummarySource returns which event kind the summary was derived from.

func (TimelineWorkspaceBreakdown) Workspace added in v0.6.1

func (b TimelineWorkspaceBreakdown) Workspace() string

Workspace returns the workspace identifier.

type TimelineWorkspaceBreakdownSummarySource added in v0.6.1

type TimelineWorkspaceBreakdownSummarySource string

TimelineWorkspaceBreakdownSummarySource identifies which event kind the workspace activity summary was derived from. Consumers can disambiguate between user-intent (prompt), agent-report (compact_summary), and the kind-count fallback.

const (
	// TimelineSummarySourceCompactSummary means the summary came from a
	// compact_summary event body recorded for this workspace in the block.
	TimelineSummarySourceCompactSummary TimelineWorkspaceBreakdownSummarySource = "compact_summary"
	// TimelineSummarySourcePrompt means the summary came from the first
	// prompt event body recorded for this workspace in the block.
	TimelineSummarySourcePrompt TimelineWorkspaceBreakdownSummarySource = "prompt"
	// TimelineSummarySourceTranscript means the summary came from the
	// first transcript event body recorded for this workspace in the
	// block (assistant-reasoning signal, introduced with #606).
	TimelineSummarySourceTranscript TimelineWorkspaceBreakdownSummarySource = "transcript"
	// TimelineSummarySourceKindCounts means no summary event was available
	// and the renderer should fall back to the kind-count line.
	TimelineSummarySourceKindCounts TimelineWorkspaceBreakdownSummarySource = "kind_counts"
)

type WorkingState added in v0.5.0

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

WorkingState captures structured working-memory signals for handoff and context resumption without persisting a separate aggregate.

func WorkingStateOf added in v0.5.0

func WorkingStateOf(sessionSummary string, compactSummary string) WorkingState

WorkingStateOf creates a WorkingState from session and compact summary signals.

func (WorkingState) CombinedSummary added in v0.5.0

func (w WorkingState) CombinedSummary() string

CombinedSummary returns a single-line summary suitable for compatibility handoff surfaces.

func (WorkingState) CompactSummary added in v0.5.0

func (w WorkingState) CompactSummary() string

CompactSummary returns the latest compact-summary signal extracted from event history.

func (WorkingState) SessionSummary added in v0.5.0

func (w WorkingState) SessionSummary() string

SessionSummary returns the session-end or operator-authored summary signal.

type WorkspaceAliasSummary added in v0.31.0

type WorkspaceAliasSummary struct {
	SessionID  string    `json:"session_id"`
	Workspace  string    `json:"workspace"`
	ReviewedAt time.Time `json:"reviewed_at"`
	ReviewedBy string    `json:"reviewed_by"`
	Note       string    `json:"note,omitempty"`
}

WorkspaceAliasSummary is the read-side projection of a reviewed alias.

type WorkspaceConflictSample added in v0.31.0

type WorkspaceConflictSample struct {
	EventID    string `json:"event_id"`
	SessionID  string `json:"session_id"`
	Client     string `json:"client"`
	SourceHook string `json:"source_hook"`
}

WorkspaceConflictSample is a body-free pointer for operator review.

type WorkspaceIdentityCoverage added in v0.31.0

type WorkspaceIdentityCoverage struct {
	EventCount       int     `json:"event_count"`
	CoveredEvents    int     `json:"covered_events"`
	MissingEvents    int     `json:"missing_events"`
	CoverageRate     float64 `json:"coverage_rate"`
	ObservationCount int     `json:"observation_count"`
}

WorkspaceIdentityCoverage reports current-event primary-observation coverage.

type WorkspaceIdentityReport added in v0.31.0

type WorkspaceIdentityReport struct {
	Coverage        WorkspaceIdentityCoverage       `json:"coverage"`
	Sources         []WorkspaceIdentitySourceReport `json:"sources"`
	ConflictSamples []WorkspaceConflictSample       `json:"conflict_samples"`
	Aliases         []WorkspaceAliasSummary         `json:"aliases"`
}

WorkspaceIdentityReport contains body-free identity diagnostics.

type WorkspaceIdentitySourceReport added in v0.31.0

type WorkspaceIdentitySourceReport struct {
	Client                 string                      `json:"client"`
	SourceHook             string                      `json:"source_hook"`
	ObservationCount       int                         `json:"observation_count"`
	Relationships          WorkspaceRelationshipCounts `json:"relationships"`
	IngestedConflictCount  int                         `json:"ingested_conflict_count"`
	KnownRelationshipCount int                         `json:"known_relationship_count"`
	ConflictRate           float64                     `json:"conflict_rate"`
	DeliveryAttemptCount   int                         `json:"delivery_attempt_count"`
	RuntimeAttemptCount    int                         `json:"runtime_attempt_count"`
	BackfilledAttemptCount int                         `json:"backfilled_attempt_count"`
	AcceptedDeliveryCount  int                         `json:"accepted_delivery_count"`
	IdentityConflictCount  int                         `json:"identity_conflict_count"`
	ExactRedeliveryCount   int                         `json:"exact_redelivery_count"`
	ExactRedeliveryRate    float64                     `json:"exact_redelivery_rate"`
}

WorkspaceIdentitySourceReport groups attribution and delivery facts by host/hook.

type WorkspaceRelationshipCounts added in v0.31.0

type WorkspaceRelationshipCounts struct {
	Exact         int `json:"exact"`
	Descendant    int `json:"descendant"`
	Ancestor      int `json:"ancestor"`
	ExplicitAlias int `json:"explicit_alias"`
	Conflict      int `json:"conflict"`
	Unknown       int `json:"unknown"`
}

WorkspaceRelationshipCounts is a fixed projection of current relationship facts.

Jump to

Keyboard shortcuts

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