@jjanczur/tyran 0.1.25 → 0.1.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/board.mjs CHANGED
@@ -46,6 +46,8 @@ import { renderBoardError, renderBoardHtml } from './board-html.mjs';
46
46
  import { COST_SCHEMA, costJson, costReport } from './cost.mjs';
47
47
  import { SettingsError, applyPolicyClass, applySetting, readSettings } from './settings.mjs';
48
48
  import { checkStopAt } from './stop-check.mjs';
49
+ import { runState } from './overnight.mjs';
50
+ import { answerOne, answerProblem, classify, openAsks, partitionAsks, reRender, sortAsks } from './answer.mjs';
49
51
 
50
52
  export const BOARD_HTML_FILE = 'board.html';
51
53
 
@@ -66,8 +68,15 @@ export function readInitiativeBoards(tyranDir) {
66
68
  let names;
67
69
  try {
68
70
  names = readdirSync(stateDir).sort();
69
- } catch {
70
- return { initiatives: [], errors: [] };
71
+ } catch (err) {
72
+ // ENOENT is the legitimate fresh-repo case: setup has run, no initiative
73
+ // exists yet, and an empty board is the right answer. Anything else —
74
+ // EACCES, ENOTDIR, EIO — means we cannot TELL whether there is work here,
75
+ // and returning "no initiatives" for that is the board saying all is well
76
+ // about a directory it could not open. It is also what `--dir` pointed at
77
+ // the repo root instead of at `.tyran` looks like.
78
+ if (err?.code === 'ENOENT') return { initiatives: [], errors: [] };
79
+ return { initiatives: [], errors: [{ name: 'state', error: `${err?.code ?? 'unreadable'} reading ${join(basename(resolve(tyranDir)), 'state')}` }] };
71
80
  }
72
81
  const dirs = names.filter((name) => {
73
82
  try {
@@ -87,7 +96,17 @@ export function readInitiativeBoards(tyranDir) {
87
96
  const warned = [];
88
97
  for (const name of dirs) {
89
98
  const journal = join(stateDir, name, 'journal.jsonl');
90
- if (!existsSync(journal)) continue;
99
+ // "there is no journal here" and "I cannot tell whether there is a journal
100
+ // here" are different facts, and `existsSync` returns false for both. An
101
+ // initiative in an unreadable directory used to vanish from the board with
102
+ // nothing said — the totals simply went down by one.
103
+ try {
104
+ statSync(journal);
105
+ } catch (err) {
106
+ if (err?.code === 'ENOENT') continue;
107
+ errors.push({ name, error: `${err?.code ?? 'unreadable'} reading ${join('state', name, 'journal.jsonl')}` });
108
+ continue;
109
+ }
91
110
  try {
92
111
  const state = fold(readJournal(journal));
93
112
  // PARTIAL damage, which the guard below cannot see. That guard fires only
@@ -118,7 +137,17 @@ export function readInitiativeBoards(tyranDir) {
118
137
  // where an initiative's journal lives (ADR-21).
119
138
  initiatives.push({ name, journal, state, board: boardOf(state), files: initiativeFiles(tyranDir, name) });
120
139
  } catch (err) {
121
- errors.push({ name, error: String(err?.message ?? err) });
140
+ // The CODE and a repo-relative path, never the raw message. A Node fs
141
+ // error carries the absolute path, which means a home directory and a
142
+ // username — and this string is written into `board.json`, a committed
143
+ // artefact compared byte for byte, so it also made `--check` fail on any
144
+ // other machine.
145
+ errors.push({
146
+ name,
147
+ error: err?.code
148
+ ? `${err.code} reading ${join('state', name, 'journal.jsonl')}`
149
+ : String(err?.message ?? err),
150
+ });
122
151
  }
123
152
  }
124
153
  return { initiatives, errors, warned };
@@ -204,14 +233,25 @@ export function crossBoard({ initiatives, errors, warned = [], stop = null }) {
204
233
  for (const card of board.lanes.get(lane)) lanes[lane].push({ ...card, init: name });
205
234
  }
206
235
  }
207
- asks.sort((a, b) => String(a.since ?? '').localeCompare(String(b.since ?? '')));
236
+ // The SAME rule the answer sheet uses, imported rather than restated: the
237
+ // sheet and the page are two renderings of one queue, and two orderings
238
+ // would make an operator answer them in different sequences depending on
239
+ // which surface they happened to open (ADR-21).
240
+ const ordered = sortAsks(asks);
241
+ asks.length = 0;
242
+ asks.push(...ordered);
208
243
  // Stalest FIRST. Rendering agents in the order the journals happened to spawn
209
244
  // them puts the one that has said nothing for six hours anywhere at all,
210
245
  // including last — and the whole reason the strip carries a last-signal time
211
246
  // is that the silent agent is the one worth looking at. `last_signal` is an
212
247
  // ISO string from the journal, so ascending string order IS ascending time;
213
248
  // an agent with no signal at all sorts to the front, where it belongs.
214
- agents.sort((a, b) => String(a.last_signal ?? '').localeCompare(String(b.last_signal ?? '')));
249
+ // Sorted on EVIDENCE where there is any, falling back to the signal. An
250
+ // agent that has shown nothing for three hours belongs at the top even if it
251
+ // has been saying "working" every four minutes the whole time — which is
252
+ // exactly the case the old signal-only sort put last.
253
+ agents.sort((a, b) =>
254
+ String(a.last_evidence ?? a.since ?? '').localeCompare(String(b.last_evidence ?? b.since ?? '')));
215
255
  // Newest first: an error from four days ago is history, the one from ten
216
256
  // minutes ago is the reason you opened this page.
217
257
  logged.sort((a, b) => String(b.ts ?? '').localeCompare(String(a.ts ?? '')));
@@ -297,6 +337,9 @@ export function renderCrossMd(payload) {
297
337
  parts.push(`- **${inline(a.question ?? `(no question recorded — gate ${a.kind})`)}**\n`);
298
338
  if (a.recommendation != null) parts.push(` - recommendation: ${inline(a.recommendation)}\n`);
299
339
  if (a.default != null) parts.push(` - default: ${inline(a.default)}\n`);
340
+ if (a.blocks != null && a.blocks.count > 0) {
341
+ parts.push(` - blocks ${a.blocks.count} ticket(s): ${a.blocks.ids.map((id) => inline(id)).join(', ')}\n`);
342
+ }
300
343
  parts.push(` - ${inline(a.init)}${a.ticket != null ? ` · \`${inline(a.ticket)}\`` : ''} · since ${inline(a.since)}\n`);
301
344
  }
302
345
 
@@ -383,8 +426,13 @@ function readJsonBody(req) {
383
426
  req.on('data', (chunk) => {
384
427
  size += chunk.length;
385
428
  if (size > MAX_BODY_BYTES) {
386
- reject(new SettingsError('request body is too large'));
387
- req.destroy();
429
+ // Reject, but do NOT destroy the socket: the route's 400 is written on
430
+ // the next tick, and tearing the connection down first meant the
431
+ // client saw a network error instead of the sentence explaining what
432
+ // was wrong. Pausing stops us reading the rest without discarding the
433
+ // channel the answer goes out on.
434
+ req.pause();
435
+ reject(new SettingsError(`request body is larger than ${MAX_BODY_BYTES} bytes`));
388
436
  return;
389
437
  }
390
438
  chunks.push(chunk);
@@ -434,6 +482,47 @@ const sendJson = (res, status, body) => {
434
482
  res.end(JSON.stringify(body) + '\n');
435
483
  };
436
484
 
485
+ /**
486
+ * Answer one open question, from the page instead of from a terminal.
487
+ *
488
+ * The request supplies exactly two things: WHICH ask, and the operator's own
489
+ * words. Everything else — the question, the recorded default, the ticket, the
490
+ * gate id — is read back out of the journal, which is the same guarantee
491
+ * `answer apply` makes about its sheet: nothing you type can change what was
492
+ * asked. The append itself is `answerOne`, unchanged and unwrapped, so the
493
+ * lock, the re-check and the decision-before-gate ordering are the ones the
494
+ * CLI already uses.
495
+ */
496
+ function handleAnswer(dir, body) {
497
+ const kind = String(body.kind ?? '');
498
+ const init = String(body.init ?? '');
499
+ const text = typeof body.answer === 'string' ? body.answer : '';
500
+
501
+ const { asks } = openAsks(dir);
502
+ const { answerable } = partitionAsks(asks);
503
+ const ask = answerable.find((a) => a.kind === kind && a.init === init);
504
+ if (ask === undefined) {
505
+ throw new SettingsError(
506
+ `no open question "${kind}" in "${init}" — it may have been answered in a terminal since this page loaded. Reload.`,
507
+ );
508
+ }
509
+ const trimmed = text.trim();
510
+ const problem = answerProblem(trimmed);
511
+ if (problem !== null) throw new SettingsError(`that answer ${problem}`);
512
+
513
+ const verdict = classify(trimmed, ask);
514
+ if (verdict.mode === 'open') throw new SettingsError(verdict.why ?? 'nothing to record');
515
+ const outcome = answerOne(ask, verdict);
516
+ if (outcome.skipped !== undefined) throw new SettingsError(outcome.skipped);
517
+
518
+ // A board still showing an answered question is worse than one that never
519
+ // showed it. Re-render before replying, so the reload the page does next is
520
+ // already correct.
521
+ reRender(dir, new Map([[ask.init, ask.journal]]));
522
+ console.log(`board: answered ${ask.init}/${ask.kind} (${verdict.mode}) -> decision ${outcome.decision}`);
523
+ return { ok: true, kind: ask.kind, init: ask.init, mode: verdict.mode, decision: outcome.decision, recorded: verdict.text };
524
+ }
525
+
437
526
  /**
438
527
  * Apply one edit and write it, or change nothing and say why.
439
528
  *
@@ -450,6 +539,16 @@ function handleSettingsWrite(dir, route, body) {
450
539
  route === 'config'
451
540
  ? applySetting(dir, String(body.id ?? ''), body.value, confirm)
452
541
  : applyPolicyClass(dir, body.path === null || body.path === undefined ? null : String(body.path), String(body.class ?? ''), confirm);
542
+ // Compare-and-swap. `applySetting` reads the whole file and computes a whole
543
+ // replacement, so a second writer between the read and the write would have
544
+ // its change silently discarded — and both writers would report success.
545
+ // In-process that cannot interleave (this handler is one synchronous block),
546
+ // but two boards on one directory, or a board and a terminal, are ordinary.
547
+ if (readFileSync(applied.file, 'utf8') !== applied.before_text) {
548
+ throw new SettingsError(
549
+ `${applied.file} changed underneath this edit — something else wrote it while the page was open. Nothing was written; reload and try again.`,
550
+ );
551
+ }
453
552
  writeAtomic(applied.file, applied.text);
454
553
  // The operator's terminal is the audit trail. A change made from a web page
455
554
  // that left no trace anywhere a person looks is how a settings screen turns
@@ -502,6 +601,21 @@ function main() {
502
601
  console.error(`board: no such directory ${dir}`);
503
602
  process.exit(2);
504
603
  }
604
+ // `--dir` wants the `.tyran` directory, and pointing it at the repo root
605
+ // instead is the obvious typo. Since the renderer creates `state/` where it
606
+ // is told to, that typo used to succeed silently: a `state/` directory
607
+ // appearing in the project root, and an empty board reporting that all is
608
+ // well about a repo whose real journals sit one level down. Any ONE of these
609
+ // three is enough to recognise a Tyran directory, including a freshly set up
610
+ // one that has no initiative yet.
611
+ const looksLikeTyran = ['state', 'config.yaml', 'policies'].some((name) => existsSync(join(dir, name)));
612
+ if (!looksLikeTyran) {
613
+ console.error(
614
+ `board: ${dir} does not look like a .tyran directory — it has no state/, config.yaml or policies/. ` +
615
+ 'Point --dir at .tyran itself (run /tyran:setup first if this repo has not adopted Tyran).',
616
+ );
617
+ process.exit(2);
618
+ }
505
619
  const outDir = join(dir, 'state');
506
620
 
507
621
  if (flags.serve) {
@@ -534,12 +648,26 @@ function main() {
534
648
  // `board.json` would break the byte-exact `--check` contract. Over
535
649
  // `file://` the fetch fails and the tab says how to open the board
536
650
  // with a server, which is the honest answer.
651
+ // The MACHINE-LOCAL half of "is this run supposed to be running".
652
+ // `.tyran/STOP` is committed and travels in the artefact; the pause
653
+ // marker, the resume watcher and the usage sidecar are gitignored and
654
+ // different on every machine, so they are served — the same split, and
655
+ // the same argument, spend already makes.
656
+ if (req.url === '/run.json') {
657
+ try {
658
+ sendJson(res, 200, { schema: 1, ...runState(resolve(dir, '..')) });
659
+ } catch (err) {
660
+ // A run-state failure must never take the board down with it.
661
+ sendJson(res, 503, { schema: 1, error: String(err?.message ?? err) });
662
+ }
663
+ return;
664
+ }
537
665
  if (req.url === '/settings.json') {
538
666
  sendJson(res, 200, { ...readSettings(dir), writable: flags.write });
539
667
  return;
540
668
  }
541
- if (req.url === '/settings/config' || req.url === '/settings/policy') {
542
- const route = req.url.slice('/settings/'.length);
669
+ if (req.url === '/settings/config' || req.url === '/settings/policy' || req.url === '/answer') {
670
+ const route = req.url === '/answer' ? 'answer' : req.url.slice('/settings/'.length);
543
671
  if (req.method !== 'POST') {
544
672
  sendJson(res, 405, { ok: false, error: 'this route takes POST' });
545
673
  return;
@@ -550,6 +678,10 @@ function main() {
550
678
  // that and editing the autonomy policy through it is the difference
551
679
  // this flag exists to make. The refusal names the flag, because a
552
680
  // 403 an operator cannot act on is just a bug report.
681
+ // One flag for every route that writes. Answering a question and
682
+ // editing the autonomy policy are different acts, but they are the
683
+ // same decision for the operator: whether this board may change the
684
+ // repository at all.
553
685
  if (!flags.write) {
554
686
  sendJson(res, 403, {
555
687
  ok: false,
@@ -562,7 +694,7 @@ function main() {
562
694
  return;
563
695
  }
564
696
  readJsonBody(req)
565
- .then((body) => sendJson(res, 200, handleSettingsWrite(dir, route, body)))
697
+ .then((body) => sendJson(res, 200, route === 'answer' ? handleAnswer(dir, body) : handleSettingsWrite(dir, route, body)))
566
698
  .catch((err) => {
567
699
  const known = err instanceof SettingsError;
568
700
  if (!known) console.error(`board: settings write failed: ${String(err?.message ?? err)}`);
@@ -186,6 +186,60 @@ export function scheduleDecision(marker, { forceResume = false } = {}) {
186
186
 
187
187
  // --------------------------------------------------------------- plumbing
188
188
 
189
+ /**
190
+ * The machine-local run state, for a reader that only wants to LOOK at it.
191
+ *
192
+ * Composed here rather than in the board, because these three files and the
193
+ * rules for reading them are this module's business: the marker says whether a
194
+ * pause is live, the resume state says whether a watcher is still breathing,
195
+ * and the sidecar says how full the window was when it was last written. All
196
+ * three are gitignored and different on every machine, which is why the board
197
+ * SERVES this rather than embedding it — the same argument spend makes.
198
+ *
199
+ * Everything is read defensively: a missing, oversized or unparseable file is
200
+ * simply absent. This answers a question about the run; it must never be the
201
+ * reason nobody can see the board.
202
+ */
203
+ export function runState(repo, nowMs = Date.now()) {
204
+ const marker = readSmallJson(join(repo, MARKER_RELPATH));
205
+ const resume = readSmallJson(join(repo, RESUME_STATE_RELPATH));
206
+ const sidecar = readSmallJson(join(repo, SIDECAR_RELPATH));
207
+ const resumeAtMs = marker?.resume_at ? Date.parse(marker.resume_at) : NaN;
208
+ return {
209
+ paused: marker === null ? null : {
210
+ since: typeof marker.paused_at === 'string' ? marker.paused_at : null,
211
+ window: typeof marker.window === 'string' ? marker.window : null,
212
+ used_percentage: typeof marker.used_percentage === 'number' ? marker.used_percentage : null,
213
+ resume_at: typeof marker.resume_at === 'string' ? marker.resume_at : null,
214
+ // A marker whose resume time has passed while a watcher was supposed to
215
+ // act on it is the shape of a dead watcher, and it reads as an ordinary
216
+ // pause unless something says otherwise.
217
+ overdue: Number.isFinite(resumeAtMs) && resumeAtMs < nowMs,
218
+ wait: Number.isFinite(resumeAtMs) ? humanWait(resumeAtMs - nowMs) : null,
219
+ },
220
+ watcher: resume === null ? null : {
221
+ state: typeof resume.state === 'string' ? resume.state : null,
222
+ alive: watcherAlive(resume, nowMs),
223
+ resume_at: typeof resume.resume_at === 'string' ? resume.resume_at : null,
224
+ },
225
+ usage: sidecar === null ? null : {
226
+ written_at: typeof sidecar.written_at === 'string' ? sidecar.written_at : null,
227
+ stale: !(typeof sidecar.written_at === 'string' && nowMs - Date.parse(sidecar.written_at) < SIDECAR_FRESH_MS),
228
+ five_hour: pickWindow(sidecar.five_hour),
229
+ seven_day: pickWindow(sidecar.seven_day),
230
+ },
231
+ };
232
+ }
233
+
234
+ /** Numbers and an ISO string only — never a free payload string from a hook. */
235
+ function pickWindow(w) {
236
+ if (w === null || typeof w !== 'object') return null;
237
+ return {
238
+ used_percentage: typeof w.used_percentage === 'number' ? w.used_percentage : null,
239
+ resets_at: typeof w.resets_at === 'string' ? w.resets_at : null,
240
+ };
241
+ }
242
+
189
243
  function readSmallJson(path) {
190
244
  try {
191
245
  if (!existsSync(path) || statSync(path).size > 64 * 1024) return null;
@@ -205,6 +205,21 @@ function clearBlockageBy(state, agent) {
205
205
  }
206
206
 
207
207
  /** A `review`/`merge` settles the ticket for EVERY agent blocked on it. */
208
+ /**
209
+ * Record that an agent SHOWED something, as opposed to said something.
210
+ *
211
+ * Newest wins, and only ever moves forward: events arrive in journal order, but
212
+ * a hand-edited file need not be monotonic, and an older evidence event must
213
+ * not make an agent look staler than the board already knows it is.
214
+ */
215
+ function noteEvidence(state, agent, kind, ts) {
216
+ if (agent == null) return;
217
+ const key = String(agent);
218
+ const prev = state.evidenceByAgent.get(key);
219
+ if (prev !== undefined && String(prev.ts ?? '') > String(ts ?? '')) return;
220
+ state.evidenceByAgent.set(key, { kind, ts });
221
+ }
222
+
208
223
  function clearBlockagesOn(state, ticketId) {
209
224
  for (const [key, blockage] of state.blockages) {
210
225
  // A ticketless blockage is keyed to its agent and belongs to no ticket —
@@ -264,6 +279,13 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
264
279
  ambiguousAgents: [],
265
280
  // agent name -> latest self-reported signal (last one wins)
266
281
  progressByAgent: new Map(),
282
+ // What an agent has SHOWN, as opposed to what it has said. A `progress`
283
+ // event is a heartbeat an agent emits at will; the events here each carry
284
+ // a work product — a report with its evidence[], a finding with its proof,
285
+ // a review or a merge on the agent's ticket. An agent looping without
286
+ // achieving anything can keep `progressByAgent` perfectly fresh, and used
287
+ // to sort to the BOTTOM of a strip ordered by staleness.
288
+ evidenceByAgent: new Map(),
267
289
  // agent name -> that agent's open blockage, the ticket inside the value.
268
290
  //
269
291
  // Keyed by AGENT and not by ticket, because one agent has at most one live
@@ -412,6 +434,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
412
434
  break;
413
435
  }
414
436
  case 'report': {
437
+ noteEvidence(state, data.agent ?? actor, 'report', ts);
415
438
  // A report that pairSpawns matched to a spawn has already been applied
416
439
  // to that spawn's row above — this branch only has to render what
417
440
  // pairing left over, so the two never compute the same thing twice.
@@ -458,6 +481,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
458
481
  break;
459
482
  }
460
483
  case 'finding':
484
+ noteEvidence(state, actor, 'finding', ts);
461
485
  state.findings.push({
462
486
  id: data.id ?? null,
463
487
  area: data.area ?? null,
@@ -520,6 +544,7 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
520
544
  // and the same correlator closes what that spawn left behind. Without
521
545
  // it a reviewer's ticketless blockage outlived its own review with no
522
546
  // later event that could ever clear it.
547
+ noteEvidence(state, data.by ?? actor, 'review', ts);
523
548
  if (data.by != null) closeAgent(state, data.by);
524
549
  break;
525
550
  }
@@ -631,7 +656,16 @@ export const LANES = Object.freeze([
631
656
  'done',
632
657
  ]);
633
658
 
634
- const APPROVING_RE = /^approv|^lgtm$|^pass/i;
659
+ /**
660
+ * A review verdict that counts as an approval.
661
+ *
662
+ * Exported because `tiers.mjs` counts FAILED attempts on a ticket to decide
663
+ * whether to escalate, and "did this attempt fail" must not have two answers
664
+ * (ADR-21). Note the asymmetry this creates, stated because someone will meet
665
+ * it: the pattern was written for lane assignment, so "approved with nits"
666
+ * reads as an approval and "looks fine" does not.
667
+ */
668
+ export const APPROVING_RE = /^approv|^lgtm$|^pass/i;
635
669
 
636
670
  /**
637
671
  * The kanban view of a folded state. PURE and clock-free: every timestamp is
@@ -658,10 +692,45 @@ export function boardOf(state) {
658
692
  (g) => PAUSED_RE.test(g.kind) && !GATE_PASS.has(String(g.result ?? '').toLowerCase()),
659
693
  ) ?? null;
660
694
 
695
+ // What each open question is HOLDING UP.
696
+ //
697
+ // `deps` is resolved forward everywhere else — a ticket is ready when its
698
+ // dependencies are merged — and the reverse direction was never computed, so
699
+ // a queue of nine questions sorted by age alone put the one gating six
700
+ // tickets wherever it happened to fall. The walk is transitive and skips
701
+ // merged tickets, which are not held up by anything.
702
+ //
703
+ // Only when the initiative declares deps at all: on a journal that records
704
+ // none, every ask would report "blocks 0", and an absence rendered as a
705
+ // measurement is worse than saying nothing.
706
+ const declaresDeps = state.ticketList.some((x) => Array.isArray(x.deps) && x.deps.length > 0);
707
+ const dependents = new Map();
708
+ if (declaresDeps) {
709
+ for (const x of state.ticketList) {
710
+ for (const d of Array.isArray(x.deps) ? x.deps.map(String) : []) {
711
+ dependents.set(d, [...(dependents.get(d) ?? []), x.id]);
712
+ }
713
+ }
714
+ }
715
+ const blockedBy = (ticket) => {
716
+ if (!declaresDeps || ticket == null) return null;
717
+ const seen = new Set();
718
+ const queue = [String(ticket)];
719
+ while (queue.length > 0) {
720
+ for (const next of dependents.get(queue.shift()) ?? []) {
721
+ if (seen.has(next) || mergedIds.has(next)) continue;
722
+ seen.add(next);
723
+ queue.push(next);
724
+ }
725
+ }
726
+ return { count: seen.size, ids: [...seen].sort(naturalCompare) };
727
+ };
728
+
661
729
  const asks = [];
662
730
  for (const g of state.openGates) {
663
731
  if (WAITING_RE.test(String(g.result ?? ''))) {
664
732
  asks.push({
733
+ blocks: blockedBy(g.ticket),
665
734
  kind: g.kind,
666
735
  ticket: g.ticket ?? null,
667
736
  question: g.question ?? null,
@@ -731,6 +800,7 @@ export function boardOf(state) {
731
800
  .filter((a) => a.status === 'running')
732
801
  .map((a) => {
733
802
  const signal = state.progressByAgent.get(a.agent) ?? null;
803
+ const evidence = state.evidenceByAgent.get(a.agent) ?? null;
734
804
  return {
735
805
  agent: a.agent,
736
806
  role: a.role,
@@ -739,6 +809,17 @@ export function boardOf(state) {
739
809
  detail: signal?.detail ?? null,
740
810
  next: signal?.next ?? null,
741
811
  last_signal: signal?.ts ?? a.spawnTs,
812
+ // What it has SHOWN. Null until it shows something, which is the
813
+ // ordinary state of an agent that has just started — the strip says
814
+ // "nothing yet" rather than implying silence.
815
+ last_evidence: evidence?.ts ?? null,
816
+ evidence_kind: evidence?.kind ?? null,
817
+ // When it started. An agent that has shown nothing is stale from its
818
+ // SPAWN, not from the last thing it said — without this an agent
819
+ // chattering every four minutes and producing nothing outranks one
820
+ // that produced something twenty minutes ago, which is the exact
821
+ // inversion the evidence split exists to correct.
822
+ since: a.spawnTs,
742
823
  };
743
824
  });
744
825
 
@@ -290,7 +290,13 @@ export function allSettings() {
290
290
  function resolvePath(doc, path) {
291
291
  let node = doc;
292
292
  for (const segment of path) {
293
- if (node === null || typeof node !== 'object') return null;
293
+ // The REQUESTED path, never null. `limits:` is optional in a valid config
294
+ // — every install set up before it existed has none — and returning null
295
+ // here fed `readAt`'s `for (const segment of path)` an unusable value, so
296
+ // the whole Settings tab died with "path is not iterable" and every write
297
+ // became an HTTP 500. Handing the path back lets the absent-key branch do
298
+ // its job: `present: false`, and a control that says so.
299
+ if (node === null || typeof node !== 'object') return path;
294
300
  node = node[segment];
295
301
  }
296
302
  if (node !== null && typeof node === 'object' && !Array.isArray(node) && 'value' in node) {
@@ -473,7 +479,7 @@ export function applySetting(tyranDir, id, value, confirm = null) {
473
479
  if (errors.length > 0) {
474
480
  throw new SettingsError(`that change makes the config invalid, so nothing was written:\n ${errors.join('\n ')}`);
475
481
  }
476
- return { file, path, before, after: next, text };
482
+ return { file, path, before, after: next, text, before_text: loaded.text };
477
483
  }
478
484
 
479
485
  /**
@@ -538,5 +544,5 @@ export function applyPolicyClass(tyranDir, rulePath, klass, confirm = null) {
538
544
  if (errors.length > 0) {
539
545
  throw new SettingsError(`that change makes the policy invalid, so nothing was written:\n ${errors.join('\n ')}`);
540
546
  }
541
- return { file, path, before, after: klass, text };
547
+ return { file, path, before, after: klass, text, before_text: loaded.text };
542
548
  }