docs/internal/incident.md

Incident-only audit writers

internal/incident and ez-agent-ruby/lib/ez_agent/incident.rb own the internal Go and Ruby tombstone writers. They do not change the daemon's JSONL protocol, SQLite schema, recovery decisions, normal logging, or exception handling. Instrumentation owners choose the incident and record the decisions and outcomes. Create one recorder per process before storage initialization. Constructors and site registration do no filesystem I/O. Healthy execution creates no audit file or directory and starts no audit worker.

Go API

go
1// Use the existing service resolution. Do not invent another config path.
2audit, err := incident.New(config.StateDir(), "service", incident.Options{})
3if err != nil { /* fixed registration/config error; do not log raw errors */ }
4site, err := audit.Register("pkg/service/service.go:Run:1", "startup", "")
5if err != nil { /* fix invalid/duplicate static site registration */ }
6
7audit.Breadcrumb(site, incident.Started, incident.Observe, incident.Data{})
8// Only on a critical failure, not ordinary user cancellation:
9audit.Incident(site, incident.Timeout, incident.Stop,
10 incident.Data{DurationMS: 5000, BudgetMS: 5000})
11audit.Breadcrumb(site, incident.Decision, incident.Retry, incident.Data{Attempt: 1})
12ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
13defer cancel()
14audit.Flush(ctx)
15audit.Close(ctx)

Exact exported interface:

  • New(stateDir, component string, options Options) (*Recorder, error). stateDir is the application directory, including ez-agent, not its parent. Service callers pass config.StateDir(). A connected client may instead pass the existing acknowledged StateDir. State-directory validation and creation are deferred until an incident so breadcrumbs are available before storage.
  • (*Recorder).Register(identity, operation, comment string) (*Site, error).
  • (*Recorder).Breadcrumb(*Site, Event, Outcome, Data) bool.
  • (*Recorder).Incident(*Site, Event, Outcome, Data) bool.
  • (*Recorder).Flush(context.Context) bool and Close(context.Context) bool.
  • (*Recorder).Status() Status, with Dropped, Invalid uint64; Failed bool.
  • Options{OpenWriter func() (io.WriteCloser, error)} is a test seam. Leave it nil in production. The worker alone opens, writes, and closes the sink. The sink must implement unbuffered writes or make each successful write visible.

Data has string fields LeafID, TurnID, RequestID, OperationID and int64 fields DurationMS, BudgetMS, Attempt, Pending. Zero values are omitted. Event and outcome constants correspond to the exact schema values below, using Go PascalCase, for example CleanupFailed, ProviderTemporary, Continue.

Ruby API

ruby
1require "ez_agent/incident"
2
3audit = EzAgent::Incident::Recorder.new(component: "ruby_workflow")
4site = audit.register("ez-agent-ruby/lib/ez_agent/workflow/evaluator.rb:eval:1",
5 operation: "evaluation")
6audit.breadcrumb(site, event: :started)
7audit.incident(site, event: :timeout, outcome: :stop,
8 data: {duration_ms: 5000, budget_ms: 5000})
9audit.breadcrumb(site, event: :decision, outcome: :retry, data: {attempt: 1})
10audit.flush(timeout: 0.1)
11audit.close(timeout: 0.1)

Exact interface:

  • EzAgent::Incident.state_dir(env: ENV) resolves XDG_STATE_HOME/ez-agent, falling back to $HOME/.local/state/ez-agent, like Go config.StateDir(). If HOME is unavailable, its relative fallback fails closed at disk creation. This deliberately does not use XDG_DATA_HOME, where the Ruby launcher keeps its installation metadata. It does not read config or auth files.
  • Recorder.new(component:, state_dir: Incident.state_dir, open_writer: nil). Pass an acknowledged service state directory when available. open_writer is the equivalent test seam, returning an unbuffered write/close sink.
  • register(identity, operation:, comment: "") returns an opaque site token.
  • breadcrumb(site, event:, outcome: :observe, data: {}) -> boolean.
  • incident(site, event:, outcome:, data: {}) -> boolean.
  • flush(timeout: 0.1) -> boolean, close(timeout: 0.1) -> boolean. Timeouts are finite nonnegative seconds.
  • status -> {dropped: Integer, invalid: Integer, failed: boolean}.

Ruby data uses the schema's symbol keys and plain String/Integer values. Events and outcomes are symbols. Unknown keys, exception objects, floats, string keys, string subclasses, invalid encodings, and unapproved string values are rejected. Component, registration labels, and ID strings are copied and frozen before validation. The recorder retains those exact validated snapshots, using one identity snapshot for both the site token and registration key. Later mutation of caller-owned strings cannot change accepted evidence. The recorder never calls exception message, inspect, or backtrace. Requiring this library does not load API or Workflow or connect to a daemon.

Common JSONL schema v1

One JSON object per line, with no raw message field:

FieldMeaning
vInteger 1
timeUTC RFC3339 timestamp of the event
pidProcess ID
componentFixed component label below
kindbreadcrumb, incident, repeat, or limit
siteExplicit repository-relative file:function[:index]
operationFixed operation label below
eventFixed structured event below
outcomeFixed decision/outcome below
commentOptional fixed comment below
dataObject containing only the allowlisted fields below
count1 for ordinary events; additional suppressed occurrences for repeats
droppedOptional cumulative count of discarded events/breadcrumbs
last_timeRepeat summary's last occurrence timestamp, otherwise absent
budgetOnly on limit: routine or total, identifying the exhausted allowance

Both writers emit these same names and types. Object key order, timestamp fraction precision, and omitted numeric zero fields are not significant. repeat retains the original site's event, outcome, data, and time, and adds last_time. Count is additional occurrences, excluding the first emitted event.

Allowed labels:

  • Components: service, cli, tui, builtin, configurator, ruby, ruby_api, ruby_workflow, provider, test.
  • Operations: startup, shutdown, storage, request, evaluation, replay, provider, cleanup, transport, callback, workflow. Selected callpoints also use these fixed human-readable descriptions in the same field. Both writers accept exactly this additional allowlist:
    • Workflow: read workflow control state, monitor workflow completion, reconcile workflow name, evaluate prepared workflow, prepare workflow operation, execute workflow worker, execute workflow control, settle unexpected worker exit, settle unreachable workflow operation, persist workflow command output, launch workflow command, materialize workflow root.
    • Service requests: read leaf statistics, rename leaf, admit leaf prompt, abort leaf work.
    • Service startup: prepare service state, load service configuration, listen on service socket, open service database, clean temporary sessions, repair session storage, vacuum session storage, reconcile interrupted leaves, start service server. These are registration constants, not runtime strings or a stack trace.
  • Events: started, completed, decision, timeout, unexpected, invariant, cleanup_failed, cleanup_slow, replay_ambiguous, provider_temporary. The writer alone emits budget_exhausted on kind: limit.
  • Outcomes: observe, continue, retry, stop, cancel, recover, reuse, fail, success, wait.
  • Comments: omitted/empty, deadline exceeded, unexpected failure, cleanup incomplete, recovery uncertain, temporary provider failure, invariant violated.

Data allowlist:

  • leaf_id: repository leaf format l_ plus exactly 12 lowercase hex digits.
  • turn_id: repository turn format t_ plus exactly 12 lowercase hex digits.
  • request_id: repository RPC format rpc_ plus exactly 16 lowercase hex digits for Go RPCs or 32 for Ruby RPCs. Both writers accept both RPC lengths.
  • These three fields also accept lowercase canonical UUIDs or 16 through 64 unprefixed lowercase hex digits. operation_id accepts only those UUID/hex forms. Prefixes are field-specific; for example a turn ID is not a leaf ID. Only pass actual machine correlation IDs, never arbitrary wire strings, display names, or workflow keys. Omit other formats; do not sanitize arbitrary text until it passes validation. There is no automatic hashing or stringifying.
  • duration_ms, budget_ms, attempt, pending: integers in [0, 2^53-1].

Site identities must be static repository-relative .go or .rb locations, up to 160 ASCII bytes. No absolute paths, empty/dot/dot-dot path components, or backslashes. Functions allow ASCII letters/digits/underscore/dot/!/?. An optional index is 1 through 9999. Registration rejects duplicates within a recorder, over 256 sites, and registration after close. Reuse the returned token at that callpoint; another recorder's token is rejected. Owners must choose unique indices for separate decisions in one function, not derive identities from runtime names. Registration validates shape without consulting storage.

Unique registry entries alone do not establish unique callpoints. Workflow's source regression counts the emission statements using each entry and checks their owning file and method. A shared reporting helper delegates the selected caller's site; it is not another callpoint. Fixed cleanup-stage selectors may choose among their registered indices, but another emission statement cannot reuse one of those sites. Selected Workflow mappings are documented in the Workflow error reference.

Never pass raw errors, panic values, exception objects, commands, prompts, responses, user/provider/model names, provider bodies, headers, credentials, native thinking, arbitrary class names, or unrestricted paths. This schema has no stack field. Use a registered location and a fixed event category instead. Extend this internal allowlist deliberately with corresponding tests and docs when another typed category is needed, rather than adding a generic string map.

Bounds and delivery semantics

The fixed bounds exported in both languages are 32 in-memory breadcrumbs, 64 queued requests, 256 registered sites, 512 disk records, 256 KiB per file, and 2048 bytes per JSONL line. The first incident request can carry the cold breadcrumb ring plus its triggering incident, at most 33 records. All later queued event requests carry one record. The one worker holds at most one such batch, one previous record, and scalar repeat counters. Old ring entries, saturated requests, and records beyond the disk allowance increase dropped. Invalid input increases invalid, creates no incident, and never enters the queue. Status contains numbers and a failure bit, not error text. Accepted input returns true, which is not a persistence guarantee.

Before the first incident, breadcrumbs stay in the cold ring. Healthy flush or close does not deliver that ring or create a sink. The first incident snapshots it and activates the single worker. Once hot, all breadcrumbs enqueue promptly, including started phases and successful, failed, or cancelled completion outcomes following an error. They do not wait for another incident. Explicit flush delivers previously accepted hot records and repeat summaries; close drains them even if its caller-bounded wait expires.

Nondecision breadcrumbs and decisions with outcomes observe, continue, or success use the routine allowance, capped at 128 records and 64 KiB including its limit marker. Ordinary cold context also uses that allowance. Incidents and decisions with other outcomes share the remaining total budget. Nonroutine decisions retain protected treatment even when delivered from the cold ring. Routine requests cannot use the final 16 queue slots; incidents and nonroutine decisions can. This protects later rare errors and retry/recovery/stop decisions from routine traffic, not from a saturated queue of other critical requests or flush barriers. Nonroutine decisions before the first incident remain in memory and never start the worker themselves. Hot completion outcomes use the routine allowance, so routine exhaustion or queue saturation can still discard them. Flush and close deliver accepted work subject to these limits; they do not bypass budgets. After routine exhaustion, later incidents and nonroutine decisions still retain the reserved disk and queue capacity. There is no causal-correlation table or unbounded promise to retain every later successful outcome.

Repeated consecutive events at the same site, kind, event, outcome, and data emit once, then a counted summary on a change, explicit flush, or close. event: decision is never repeat-suppressed, but remains subject to queue and disk limits. Changed outcomes, IDs, budgets, and attempts remain distinct. Repeat summaries use the allowance of their original record. Pending repeat counts, the ring, and queued work can be lost on sudden process death.

Each disk allowance reserves space for an explicit limit record. budget: routine stops routine output only; budget: total stops all output. At most one of each is written, with total exhaustion taking precedence if both limits are reached together. There is no rewriting, truncation, rotation, deletion, periodic reset, or replacement worker/file. The displaced record or repeat summary adds its full occurrence count to dropped. The marker has count: 1 and includes that updated dropped total. Its outcome: stop describes the audit budget, not a decision to stop useful work. Later losses are visible through Status, not additional disk lines.

This is useful for a 24-hour process with rare incidents, not a 24-hour retention guarantee. Routine traffic can consume no more than its allowance, leaving at least 384 record slots and 192 KiB for critical evidence before any critical usage, including the final total-limit marker. Sustained incidents, nonroutine decisions, or repeated explicit flushes of error summaries can still exhaust that finite remainder. New errors after total exhaustion are counted as drops; this recorder never opens a second file to escape the bound. New recorders are process/component lifecycle objects, not a retention service.

Only the first incident starts one worker and lazily opens a unique file. Normal emit calls do no filesystem I/O and do not wait for a sink. Locks protect bounded bookkeeping only. A failing sink disables or discards further output; Go worker panics and Ruby worker exceptions are contained without formatting payloads. Ruby worker-creation ThreadError is also contained without inspecting the exception; it marks the recorder failed, counts the discarded breadcrumb/ incident batch, and makes that incident return false. Later incidents do not retry worker creation. Queue saturation is nonfatal. On the first sink failure, the recorder attempts one fixed warning:

text
1ez-agent: incident audit unavailable; continuing without audit output

On Linux this uses an independent nonblocking stderr descriptor only if it is a pipe, socket, or character device. A full/unavailable stderr silently loses the warning. Regular files receive nothing; no normal log is created, no error text is included, stderr's existing flags are unchanged, and warning failure does not retry or report itself. Unsupported platforms omit this warning. There is no retry spawning or alternate audit destination. A blocked sink can retain at most one worker and its bounded queue per recorder. Do not create a recorder per request or per leaf.

Flush processes previously accepted records and pending repeat summaries. Close is idempotent, rejects future events, and requests a background drain. Both have caller-bounded waits. Close continues draining if that wait expires. Healthy flush/close creates no worker or file. True means the barrier/drain completed with no sink failure, not that there were no drops. Check Status for loss. No fsync guarantee is made, and callers must never make service, model, cleanup, or recovery success depend on audit success.

Disk safety and scope

Files live under <resolved stateDir>/audit, with names tombstone-<UTC timestamp>-<PID>-<component>-<random suffix>.jsonl. The writers use O_EXCL exclusive creation, O_APPEND writes, mode 0600, and mode 0700 for new directories. State and audit directories must be owned by the effective UID and exactly 0700, with no sticky/set-ID bits. A current-user-owned ancestor may be group-writable, such as /workspace and installation/state parents at 0775, but not world-writable. Root-owned nonsticky ancestors must not be group- or world-writable. The existing allowance for root-owned sticky ancestors such as /tmp is unchanged. The caller-selected state directory and its ancestors may be symlinks. Writers resolve the longest existing state-path prefix without creating directories, then validate the resolved path under the same owner and mode rules. Missing descendants are created only after validating their parents. Foreign-owned or unsafe resolved directories and symlinks at the managed audit directory are rejected. Writers never chmod existing directories. Only the exclusively created log has its permissions set to exactly 0600. Construction, registration, status inspection, healthy flush, and healthy close do no filesystem work and cannot create directories or a tombstone.

Production disk creation currently supports Linux. Go uses no-follow openat/mkdirat and held directory descriptors. Ruby uses no-follow opens anchored to held descriptors through /proc/self/fd; Linux procfs must be available. Other platforms fail closed on the worker, without blocking useful work. Permission or path failures have the same nonfatal behavior. The writers never reopen an existing tombstone. After state-path resolution, each child is opened no-follow relative to its held parent descriptor, then checked through that child's descriptor before use. A symlink substituted during this walk is rejected, not followed. File creation is anchored to the validated audit descriptor, and subsequent writes use the original file descriptor. Renaming an already opened ancestor or substituting a symlink cannot redirect these operations through a new pathname. A group member able to rename an ancestor cannot read or enter the effective- user-owned 0700 state/audit directory, replace its children, or read the 0600 log. A foreign-owned replacement fails validation instead of receiving payload.

Ancestor rename/removal can still hide the directory from its expected pathname or prevent later traversal. That availability denial is outside this payload confidentiality boundary. The writer does not lock ancestors, restore paths, or claim that a pathname names the same inode before it is first opened. Same-UID attackers and privileged administrators are outside this boundary. Tests use private synthetic state directories beneath user-owned 0775 ancestors matching the installation layout, never the actual inherited state directory.

Service instrumentation belongs to the core unit. Ruby API/Workflow callpoints belong to their later unit. These writers alone do not install panic handlers, interpret timeouts, persist replay state, or change cancellation/retry policy. Tests are internal/incident/*_test.go and ez-agent-ruby/test/incident_test.rb. Workflow callpoint regressions and Go/Ruby operation-allowlist parity live in ez-agent-ruby/test/workflow_readiness_test.rb; selected service registration coverage lives in pkg/service/audit_test.go.