Files
callstack__agent-device/docs/adr/README.md
Michał Pierzchała 152894cce2 docs(adr): rules-first ADR restructure + ADR 0017 proposal (unified event journal) (#1399)
* docs(adr): rules-first restructure of 0012/0014/0016, drop completed migration logs

ADR 0012 alone was 42% of the ADR corpus by bytes; consulting it cost ~28k
tokens of mostly process history. Restructure per the new shape convention
(added to the ADR README): Status + a normative 'Rules at a glance' first so
a reader can stop after ~50 lines, rationale and refuted alternatives kept
below the fold, and completed migration plans/landing tables deleted — git
history is the archive.

- 0012: delete migration plan/progress; fix the Status section that still
  claimed #1235 unimplemented against its own landing table; demote the
  2026-07-10 evidence audit to the end (still cited by the decisions).
- 0014: same; the accepted Android blocking-dialog-recovery evidence gap and
  its covering fixture tests move into Status so the waiver survives.
- 0016: verified implemented; rules summary added (nothing was history).

No rule's meaning changed; edits are reorganization plus stale-status fixes.

* docs(adr): propose ADR 0017 — unified request event journal

Apply ADR 0008's registry thesis to events. Inventory (2026-07-24) found four
parallel event vocabularies — ~155 stringly-typed diagnostics phases, the
session events.ndjson, the progress wire stream, and the replay timing trace
(one of its two writers unredacted) — with consumers coupled to emit sites by
string: agent-cost counts runner round-trips by matching two phase names.

Proposal: an EVENT_CATALOG in contracts making every kind a typed,
trait-carrying declaration; the diagnostics scope becomes the single journal
append point; every consumer becomes an explicitly registered sink; all
existing file/wire formats stay byte-compatible behind golden fixtures.
Explicitly rejects pub-sub and event sourcing. Status: Proposed — not indexed
in the ADR README until accepted.

* docs(adr): revise ADR 0017 per architecture review

Address all five review findings and adopt both requested judgments:

- P1 out-of-request events: finalizeRepairTeardown records a synthesized
  close during idle-reap/daemon-shutdown with no live request; a
  request-scoped-only journal would silently drop it. Added an explicit
  session-scoped teardown scope model (fatal-scope precedent) and rejected
  the ambient-fallback alternative.
- P1 redaction vs byte-compat: progress stays unredacted on its own channel;
  the replay-trace unredacted->redacted change is now a declared, intentional
  compatibility change with its own fixture update, not smuggled under a
  byte-compat claim.
- P1 per-attempt trace routing: sinks with dynamic destinations read
  scope-bound routing context (logPath-rebind precedent); drop-when-unbound
  semantics; sink ordering/isolation/flush contract made normative.
- P2 progress typing: progress streaming removed from the journal entirely -
  it is a transport-owned output port (ordering, disconnect-as-cancellation,
  closed typed union); mirror emits noted as the future opt-in shape.
- P2 completeness check: orphan detection is now a static source scan in the
  layering-lint style; runtime unit-suite observation explicitly rejected.

Also per review: catalog keys are internal identities; sinks map to legacy
wire discriminators, which are never automatically canonical. Migration plan
reduced to 4 steps.

* docs(adr): ADR 0017 — fork, never rebind, for per-attempt trace routing

Review found a blocking concurrency flaw in the revised routing design:
sharded test attempts run concurrently (Promise.allSettled in
runReplayTestShards) under one inherited AsyncLocalStorage request scope, so
mutable scope rebinding would let one attempt overwrite or clear another's
replay-timing destination after an await — cross-writing or dropping events.

Replace rebinding with a journal fork primitive: journal.fork(bindings, fn)
runs fn in a new ALS scope object sharing the parent's buffer/phaseCounts/
envelope/sinks but carrying frozen routing bindings. Each attempt wraps its
work (including nested replay dispatch) in a fork binding its own trace
path; the binding dies with the fork, so no clearing step exists to race.
Existing updateDiagnosticsScope rebinds stay confined to sequential request
setup, pre-fan-out. Validation gains a concurrent-shard regression proving
each replay-timing.ndjson contains only its own attempt's events.

* docs(adr): ADR 0017 — scope identity on the envelope for future exporter sinks

Reserve the one shape decision an OTel-style exporter would otherwise force
a retrofit for: every scope (request, teardown, fork) carries scopeId, forks
record parentScopeId, both ride the event envelope. Forks already form a
tree, so an exporter sink can emit parent-child spans from envelope fields
alone. Cross-process correlation stays requestId; a traceparent-style meta
field is additive under ADR 0006 and deferred. No exporter in this ADR.

* docs(adr): address re-review — renumber to 0018, full fork isolation, 0016 record-as

1. Renumber the proposal 0017 -> 0018: main now carries accepted ADR 0017
   (parameterized recorded inputs, #1369); branch rebased onto it.
2. Fork contract strengthened: forks clone EVERY mutable scope field
   (envelope, logPath, routing bindings) and own their event buffer; only
   the sink list and the request-global phaseCounts tally are shared.
   Verified in code: nested dispatch creates child execution scopes
   (request-router.ts:257) whose updateDiagnosticsScope rebinds
   session/logPath mid-flight, so a shared mutable envelope would
   cross-route debug/session-log events between concurrent shards even with
   frozen trace bindings. updateDiagnosticsScope now specified as mutating
   only the innermost scope. The regression now covers all three routed
   outputs (replay-timing, per-request diagnostics ndjson, events.ndjson).
3. 0016 rules summary updated for shipped #1348: sensitive fills use
   fill --record-as <VAR> (ADR 0017); unparameterized fill/type stays
   literal (body sections already updated by #1369's merge).

* docs(adr): ADR 0018 — name the usage sink as first consumer, privacy by construction

The motivating consumer is opt-in usage analytics over agent behavior:
command frequencies, typed failure codes, and outcome sequences that trip
agents (consecutive snapshots, screenshot-after-snapshot). Decision 4 pins
its discipline now, before any exporter exists: an allowlist-by-construction
UsageRecord schema whose every field draws from a registry-enumerated
vocabulary (command names, ADR 0010 error codes, flag names, durations,
hashed session + sequence number) — positionals, selectors, labels, fill
text, and error messages are unrepresentable by type, not redacted.
Anti-pattern detection is downstream analysis over the stream, never
emission-side logic; the sink itself is a follow-up after migration step 3.
Adds the matching invariant and a schema gate to validation.
2026-07-25 14:03:03 +02:00

3.7 KiB

ADR index — read this when…

ADR Read when you touch…
0001 Provider-First Integration Scenarios integration testing strategy, provider transcripts, the scenario harness
0002 Persistent Platform Helper Sessions helper process lifecycle, keep-alive semantics
0003 Daemon Command Registry daemon routing, request-policy traits
0004 iOS Snapshot Backend Strategy snapshot capture plans, backend fallbacks, quality verdicts
0005 iOS Runner Interaction Lifecycle XCTest runner sessions, leases, adoption, idle-stop
0006 Daemon RPC Protocol Version remote daemon HTTP/JSON-RPC compatibility
0007 Remote Device Leases leases, tenancy, provider-owned devices
0008 Command Descriptor Registry adding/changing a command, any surface projection (CLI/MCP/client/batch), timeout policy
0009 Apple Platform Consolidation Apple platform family, apple/appleOs axes, the apple-leak guard
0010 Error system conventions error codes, hints, normalizeError, typed error signals
0011 Interaction Guarantee Contract interaction dispatch paths, fast paths, guards, the guarantee matrix, parity tables
0012 Interactive Replay replay healing/--update, diagnostic resolution disclosure, bounded .ad target-binding evidence, bounded divergence wire/error handling, plan-bound replay-only --from semantics, and agent-supervised re-record repair ("heal-by-doing")
0013 Unified Gesture Plans gesture API/routing, contact topology, multi-touch geometry, native pointer injection, two-finger pan
0014 Session Ref-Frame Lifetime ref authorization epochs, complete/partial issuance, pre-side-effect expiration, replay/batch compatibility, and cross-platform stale-mutation policy
0015 Direct Maestro Compatibility Engine Maestro YAML parsing/execution, compatibility observation policy, conformance, performance gates, gesture integration
0016 Active-Session Script Publication publishing an armed open-to-destination .ad script without closing its live session
0017 Parameterized Recorded Inputs safely authoring sensitive fill inputs as ${VAR} placeholders across recording, replay, and repair

ADRs record why; the registries and gates they describe are the living source of truth — when prose and a registry disagree, the registry wins and the ADR needs a follow-up.

Shape conventions, so consulting an ADR stays cheap:

  • Normative rules first, terse. Status, then a "Rules at a glance" summary a reader can stop after; full contracts and rationale below it.
  • Rationale and refuted alternatives stay in the ADR — they are what stops re-litigating settled ideas — but below the fold.
  • Process history is deleted once complete, not archived in-file. Migration plans, per-step landing tables, and point-in-time status change-logs go to git history; the Status section keeps one line saying so plus any accepted, still-relevant waiver or evidence gap.
  • Once a rule is gate-enforced, the ADR keeps the why and points at the gate rather than restating the rule's details.