Plan: One always-on diagnostics stream for the gadhs packages
Closes: #484. Relates to: #483, #482. Branch: feat/diagnostics. Status: Done (2026-10-26) — implemented as planned, with the errata below
Design
The problem
Two runs aborted on 2026-10-26 with nobody pressing Escape (#483), and nothing recorded why. Everything the packages log is opt-in: debugLog in packages/pi-modes/debug-log.ts writes only when GADHS_PI_MODES_DEBUG names a file, and pi-remote’s twin (packages/pi-remote/state.ts, GADHS_PI_REMOTE_DEBUG) likewise. pi itself has no logging facility, and console.error is unusable under the TUI. The review log (pi-permission-system’s) is always on but records adjudication only. So a rare bug leaves no trail, and the next one will not either.
The ~75 existing debugLog call sites (pi-modes, and pi-workflow through the bridge, packages/pi-modes/session-wiring.ts bridgeFor) are the right events; they are dark. The fix is the sink, not the sites.
Decisions
-
Always on, bounded. The stream writes by default to
<agentDir>/gadhs-diagnostics/log.jsonl, mode 0600 in a 0700 directory, and rotates once tolog.jsonl.1when it passes 4 MiB (pi-remote’slink.logpattern,packages/pi-remote/index.tslifecycleLogger, with a larger cap). A bounded file answers debug-log.ts’s "silent growing file" objection; a path of our own answers its "unreadable by the agent" one, which was about pi-permission-system’s directory. -
GADHS_PI_DIAGNOSTICSreplaces both env vars.offdisables; any other value is an explicit path, which is what tests and bug hunts use.GADHS_PI_MODES_DEBUGandGADHS_PI_REMOTE_DEBUGare retired, not aliased (pre-1.0). The vitest base config (vitest.config.ts) setsGADHS_PI_DIAGNOSTICS: "off"in place of blanking the old var. -
Scrubbed on write. Every string value in a record passes a token-shape scrub before serialisation: the ten shapes of
packages/pi-workflow/redact.tsSECRET_PATTERNS(PEM block,NAME=valuesecret lines, AWS, GitHub, GitLab, Slack, Google, Anthropic, OpenAI keys, JWT), replaced by[REDACTED <kind>]. ADR-004 forbids pi-modes importing pi-workflow, so the list is copied into pi-modes, and a contract test in pi-modes readspackages/pi-workflow/redact.tsfrom disk and fails when the two lists differ (the same cross-package readingpackages/pi-modes/test/subagent-gate.test.tsdoes for agent files). -
Never content. No typed text, paste bodies, prompts, file contents, tool output or tokens, in any record. The new input record keeps control sequences only (below). Existing events already carry only ids, names, reasons and command lines; the scrub covers the command lines.
-
One stream, stamped. Every record carries
ts,pid,startedandcwd(SESSION_STAMP,packages/pi-modes/judge.ts), pluseventand the caller’s details; the review log is already keyed this way, so the two can be joined by eye. -
Before the session opens, a ring. Events logged before
session_startsuppliesagentDir(judge registration, config loading) go to an in-memory ring of 200 and are flushed when the stream opens. A process that never opens it writes nothing, which is what keeps the test suites quiet with no env var at all;offis belt and braces. -
Readers.
/diag [n](pi-modes) prints the lastnrecords (default 20) compactly and the file’s path, so a human or a peer agent can paste them into a bug report. No new allow rule for the agent reading the path: an out-of-tree read goes to the judge as any other, and this session’s experience (alink.logread queued for the human) is acceptable for now; a rule is a follow-up if the asks get tedious. No repository task verb:/diagandgrepon the path cover it.
The facility: packages/pi-modes/diagnostics.ts
Replaces debug-log.ts; the export keeps its name and signature so the ~75 sites and the bridge member change nothing beyond the import path (ten pi-modes files import ./debug-log.ts; each becomes ./diagnostics.ts). packages/pi-modes/package.json gains an export "./diagnostics": "./diagnostics.ts", the way ./status and ./title are exported, so pi-remote can import it.
-
debugLog(event, details): scrub, stamp, then write to the explicit path (GADHS_PI_DIAGNOSTICS), else the opened default path, else the ring.offdrops. A write failure is swallowed (a broken log must never break the session it observes), as today. -
openDiagnostics(agentDir): resolves the default path, creates the directory, flushes the ring. Called fromsession_startinsession-wiring.ts. Idempotent; a second call with anotheragentDir(session replacement) switches the path. -
rotateIfLarge(path):renameSyncto.1pastROTATE_BYTES(4 MiB), checked on each write bystatSyncof the open path (cheap at this volume; a counter every N writes is premature). -
scrubStrings(value): deep, strings only, arrays and plain objects walked, other values untouched. Patterns inDIAG_SECRET_PATTERNS, with the kind names of pi-workflow’s list. -
tailDiagnostics(path, n): the lastnlines, parsed, for/diag.
pi-remote’s state.ts debugLog and DEBUG_ENV are deleted; index.ts imports debugLog from @gadhs/pi-modes/diagnostics (pi-remote already depends on @gadhs/pi-modes), and the extension.test.ts case that exercised the old function ("debugLog writes JSONL only when the env names a file…", line 230) is deleted with it, its property now asserted by pi-modes' own tests. lifecycleLogger keeps link.log as is: it is pi-remote’s own routing record, read by its pairing flow.
tools/consumer-sim.mjs sets GADHS_PI_MODES_DEBUG (lines 271, 372) and reads the file to prove the extension loaded; it sets GADHS_PI_DIAGNOSTICS to the same temp path instead, and the assertion is unchanged.
pi’s events used: agent_settled with aborted: boolean and onTerminalInput are declared in node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/types.d.ts (AgentSettledEvent, line ~801; onTerminalInput, line ~82; pi 1.4.0). isKittyProtocolActive is exported by @earendil-works/pi-tui (dist/index.d.ts, line 23), which pi-modes already imports from (pending-widget.ts, plan-tools.ts).
The records the aborts needed
run.settled (session-wiring): on agent_settled (AgentSettledEvent { aborted }, pi ≥ 1.4), one record: aborted, ms since the run’s agent_start, stopReason and errorMessage of the last assistant message, turns. A small RunLedger class (in diagnostics.ts) holds those: started() on agent_start, saw(message) from the message_end hook already in session-wiring (onMessageEnd, which today reads only the role and usage; it additionally hands assistant messages to the ledger), settled(aborted) returns the record. On an aborted run it adds input: the ring below, and sinceEscapeMs / sinceCtrlCMs: the time since the last Escape or Ctrl+C in it, or absent. This is the record that says whether an abort followed a keypress.
The control-input ring (packages/pi-modes/input-ring.ts): a listener on ctx.ui.onTerminalInput, registered beside the focus listener in session-wiring.ts (the mouse-tail guard shows the pattern, packages/pi-modes/mouse-tail.ts), returning undefined so every chunk passes on untouched. It keeps the last 32 entries of { at, kind, seq? } where:
-
a chunk that is one C0 byte (
< 0x20, or0x7f) iskind: "ctrl"withseqas its caret name (^[,^C); -
a chunk starting with ESC and at most 24 bytes is
kind: "esc"withseqverbatim minus the ESC ([I,[<35;40;12M,[A), except a bracketed paste ([200~), which iskind: "paste"withlenand no body; -
anything else is
kind: "text"withlenonly. Never the bytes.
The ring is memory only; it is written once, inside an aborted run.settled, and never otherwise.
remote.abort (pi-remote commands.ts, the abort case of payloadOutcome): one record through the CommandReply.log the dispatcher already holds (handleCommand, line ~137, which calls payloadOutcome(cmd, ctx, host, origin); payloadOutcome gains the reply parameter), with the origin device, before ctx.abort(). The one programmatic abort we own becomes visible.
session.start (session-wiring, on open): version of pi-modes, pi version (getPackageDir-adjacent, as title.ts reads it), model, mode, hasUI, term (TERM), ssh (SSH_TTY set), mux (TMUX/STY/ZELLIJ set), kitty (isKittyProtocolActive() from @earendil-works/pi-tui, which pi-modes already imports from). The facts every bug report asks for, once per session. No env values beyond TERM.
/diag
Registered in command-wiring.ts beside /mode and /gadhs-reset. /diag shows the last 20 records as HH:MM:SS event k=v … lines (details flattened, strings truncated at 80 characters, the stamp fields omitted) and the path; /diag 50 shows 50; /diag path shows only the path. Nothing is written by the command.
Fail modes
The stream observes; it never decides. So every failure here is fail-silent: the session is unaffected and the record is lost, and the plan says so for each. Nothing fails open or closed, because nothing is gated on it.
-
No agent dir yet (a logged event at module load): the ring holds it; nothing is lost up to 200 events, and older ones fall off oldest first (silent, bounded).
-
The directory cannot be created or the file not written (read-only home, full disk): the write is dropped, the session unaffected, as today (silent).
/diagsays "no diagnostics at <path>" rather than throwing. -
GADHS_PI_DIAGNOSTICSnames a path in a directory that does not exist: dropped, the same rule; the explicit path is the operator’s (silent). -
Rotation fails (
.1locked on Windows): the rename error is swallowed and the file keeps growing until the next successful rotation; the cap is a target, not a guarantee (silent, unbounded until then). -
Two pi processes share the agent dir: both append to one file;
pidandstartedtell them apart, as in the review log. Interleaved partial lines are possible under concurrent appends;tailDiagnosticsskips lines that do not parse (silent per line). -
No UI (
hasUIfalse, a helper or a remote-driven session): no input ring is registered;run.settledcarries noinput(by design, not a failure).
Scope
In
-
packages/pi-modes/diagnostics.ts(new, replacesdebug-log.ts),input-ring.ts(new),session-wiring.ts(open on start;run.settled;session.start; the ring’s listener),command-wiring.ts(/diag),judge.tsordiagnostics.ts(SESSION_STAMPhome),index.tswiring. -
packages/pi-remote/state.ts(drop itsdebugLog),index.ts(import),commands.ts(remote.abort). -
vitest.config.ts:GADHS_PI_DIAGNOSTICS: "off". The three test files that setGADHS_PI_MODES_DEBUG(packages/pi-modes/test/command-wiring.test.ts,context-budget-boundary.test.ts,wiring-lifecycle.test.ts) set the new var. -
tools/consumer-sim.mjs: the new env var, same temp path. -
Tests, each with its category:
-
Contract: the scrub’s pattern list equals
packages/pi-workflow/redact.tsSECRET_PATTERNS(read from disk); the record shape (ts,pid,started,cwd,event, details) is what/diagand a reader parse. -
Unit (
diagnostics.test.ts): the scrub redacts each of the ten shapes and leaves other strings and non-strings alone; the ring holds before open and flushes on open in order and drops the oldest past 200;offwrites nothing; an explicit path wins over the opened one; rotation renames past the cap; a write failure (no such directory) does not throw;tailDiagnosticsreturns the lastnand skips an unparsable line. -
Unit (
input-ring.test.ts): a C0 byte, an ESC sequence, a paste and text are classified as specified; text and paste bodies never appear; the ring holds 32. -
Wiring (
wiring-lifecycle.test.ts, against the fake pi harness):session_startopens the stream and writessession.start;run.settledon an aborted run carries the ring andsinceEscapeMs, and on a completed run neither; the listener returnsundefinedfor every chunk. -
Wiring (pi-remote
extension.test.ts): theabortcommand writesremote.abortbeforectx.abort()runs; the olddebugLogcase is deleted. -
Command (
command-wiring.test.ts):/diagshows the tail and the path,/diag pathonly the path, and says so when there is no file. -
Mutation check: the scrub, the ring bound, the
offswitch, the rotation threshold and the input classifier each get a mutant, killed before the MR.
-
-
Docs: a
Diagnosticssection on the modes page (replacing theGADHS_PI_MODES_DEBUGbullet and the env mention near the dialog timing), the architecture page’s bridge table row and the "opt-in diagnostic stream" line, the local-dev, testing and tuning mentions of the old var, pi-modes' README line, pi-remote’s doc mention ofGADHS_PI_REMOTE_DEBUGif any. CHANGELOGAdded(the stream, the records,/diag) andChanged(the env vars retired). -
Delivery: one MR,
Closes #484; after merge, the merge SHA on the issue. A note on #483 that the next abort’srun.settleddecides between an input-side cause and a programmatic one, once the release carrying this is installed. -
Release: the next
@gadhs/piminor (pi-modes and pi-remote move; the retired env vars go in the release note’sChanged).
Out
-
#482 (an aborted run lapses a /pending approval): its own fix and MR.
-
The terminal-generic Escape handling discussed on #483: designed only once a cause is shown.
-
An allow rule for the agent reading the diagnostics path; a repository
task diagnosticsverb; a bus so pi-vertex or pi-agents can emit without a dependency; shipping diagnostics anywhere off the box. Each an issue when wanted. -
Any change to the review log or to
task verdicts.
Erratum (2026-10-26): remote.abort calls the shared debugLog directly; dispatch holds no CommandReply, and threading one through would widen two signatures for the same stream.
Erratum (2026-10-26): the RunLedger is fed by its own message_end handler in registerDiagnostics, not through onMessageEnd, which stays the helper ledger’s alone. An aborted run.settled also records kitty, since pi negotiates the protocol asynchronously and it may not yet be on at session.start.
Erratum (2026-10-26): the wiring tests are in test/session-wiring.test.ts, against registerDiagnostics (exported for them), not test/wiring-lifecycle.test.ts. SESSION_STAMP moved to diagnostics.ts, so pi-remote’s import does not drag in the judge.
Erratum (2026-10-26): the mutation check covered 20 mutants, all killed. The off mutant first survived, because "holds nothing" was never asserted; a test now checks that a record logged while off never reaches the file once the stream is turned back on.