@jjanczur/tyran 0.1.33 → 0.1.34

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.
@@ -11,7 +11,7 @@
11
11
  {
12
12
  "name": "tyran",
13
13
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
14
- "version": "0.1.33",
14
+ "version": "0.1.34",
15
15
  "source": "./",
16
16
  "author": {
17
17
  "name": "Jacek Janczura",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tyran",
3
- "version": "0.1.33",
3
+ "version": "0.1.34",
4
4
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
5
5
  "author": {
6
6
  "name": "Jacek Janczura",
package/CHANGELOG.md CHANGED
@@ -1,5 +1,87 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.34 — 2026-08-17
4
+
5
+ ### The dashboard starts itself
6
+
7
+ The board was reachable only by a human typing a command that never returns.
8
+ On every install where nobody typed it, each projection Tyran writes was
9
+ generated and read by no one.
10
+
11
+ `board.mjs --serve` blocks forever, which is right for an operator at a prompt
12
+ and fatal for everything else. Setup's "turn the dashboard on" step handed an
13
+ **agent** that command: measured, still listening three seconds after spawn
14
+ with nothing to return — so the tool call sat until the platform's timeout and
15
+ setup's remaining steps (validate, report, ask for the `.tyran/` commit)
16
+ silently never ran.
17
+
18
+ ```bash
19
+ node scripts/board.mjs --dir .tyran --detach --write # returns; prints the URL
20
+ node scripts/board.mjs --dir .tyran --status # where is it?
21
+ node scripts/board.mjs --dir .tyran --stop
22
+ ```
23
+
24
+ `--detach` is the same server, waited on only until it answers. A new `board:`
25
+ block in `.tyran/config.yaml` defaults `autostart: true`, so every session
26
+ brings the board up if it is not already running and prints the URL in its
27
+ opening summary. `limits:` defaults off because off is *inert*; a board that
28
+ never starts is not.
29
+
30
+ **Liveness is an HTTP question, never a recorded pid.** `/health.json` names
31
+ the `.tyran` directory it serves, and a caller believes it only if that
32
+ directory is its own. Both halves are load-bearing: a pid written by one
33
+ process and read by another is dead before it is read and, once the OS
34
+ recycles the number, names a stranger — while probing only the *port* finds a
35
+ **different repository's** board (same program, same route) and concludes this
36
+ one is already up, so it never starts. Ports walk 4173–4182, so several repos
37
+ each get their own.
38
+
39
+ `TYRAN_NO_BOARD=1` turns it off machine-wide, for CI: an automated run clones a
40
+ repository whose committed config says `autostart: true`, has no browser and no
41
+ operator, and a detached server started by a build outlives the build.
42
+
43
+ ### The commit, the reviewer and the model reach the card
44
+
45
+ Measured across **387 real journals and 1799 lane cards**: 1243 carried a merge
46
+ sha and 1074 a review verdict that no surface displayed.
47
+
48
+ Nothing looked broken because the **lane encoded them** — `done` means merged,
49
+ `changes-requested` means a non-approving review. The board was right, and
50
+ could not show its work. Selecting a card now shows the commit, the reviewer
51
+ and when, plus an **Execution** table: agent, model, start, verdict. That last
52
+ column is the half of "what did this cost me" the Spend tab cannot answer —
53
+ Spend gives dollars per ticket, this gives what was spawned to earn them.
54
+
55
+ The worst real `board.json` grows 57 KiB → 84 KiB. `BOARD.md` is byte-unchanged.
56
+
57
+ **Upgrading: one expected `--check` drift**, the same shape as 0.1.33's. Cards
58
+ gain `review`, `merge` and `execution`, so a `board.json` committed by an
59
+ earlier version no longer matches. Clear it with one regenerate:
60
+
61
+ ```bash
62
+ node scripts/board.mjs --dir .tyran # then commit the three artefacts
63
+ ```
64
+
65
+ `doctor --state` is silent about it; the only surface is an explicit `--check`.
66
+
67
+ ### A feature deliberately not shipped, and the measurement that killed it
68
+
69
+ While specifying a `spawn-silent` doctor finding — an open agent that has
70
+ never said anything — the count came first. Across 388 real journals the
71
+ `progress` event appears **once**, against an instruction in
72
+ `agents/implementer.md` asking for four per story (roughly 6000 expected
73
+ against 1532 spawns).
74
+
75
+ So `spawn-silent` would fire on 100% of open spawns: the always-on warning
76
+ `SEVERITY_BY_CODE` already refuses by name. It is not shipped.
77
+
78
+ Agents are not ignoring the journal — 5302 gates and 4585 decisions — and not
79
+ ignoring that file: the `lease.acquired` instruction one bullet above produced
80
+ 434 events. Four shipped features rest on the dead event and are inert on every
81
+ real install: `spawn-blocked`, the `blocked` lane, the agent chip's state, and
82
+ the signal half of "signal is not evidence". `NOTES-REQUESTS.md` §11 records
83
+ three options and the measurement that would decide between them.
84
+
3
85
  ## 0.1.33 — 2026-08-17
4
86
 
5
87
  ### The board was hiding what its own journal already knew
package/README.md CHANGED
@@ -309,7 +309,7 @@ enforces the cap (4352 of 5000 characters). What each one assumes, when it
309
309
  fires and who invokes it, is in
310
310
  [skills and agents](https://jjanczur.github.io/tyran/skills/); the prompts
311
311
  themselves are in [`skills/`](skills/) and [`agents/`](agents/). Behind all of
312
- it: 1535 unit tests, run with `node --test "tests/**/*.test.mjs"`.
312
+ it: 1569 unit tests, run with `node --test "tests/**/*.test.mjs"`.
313
313
 
314
314
  ## Documentation
315
315
 
@@ -26,6 +26,9 @@ import { checkHooks } from '../../scripts/hooks-check.mjs';
26
26
  import { readJournal } from '../../scripts/journal.mjs';
27
27
  import { SESSION_ID_RE } from '../../scripts/overnight.mjs';
28
28
  import { fold, inlinePlain, progressLine } from '../../scripts/project.mjs';
29
+ import { findLiveServer, startDetachedNoWait, urlFor } from '../../scripts/board-daemon.mjs';
30
+ import { boardSettings } from '../../scripts/schema.mjs';
31
+ import { parse as parseYaml } from '../../scripts/yaml-lite.mjs';
29
32
  import { field, main, runProbe } from './hook-io.mjs';
30
33
 
31
34
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -169,14 +172,18 @@ function rows(list, render) {
169
172
  * 120 characters under the platform's hard ceiling. Escaping first means the
170
173
  * length fitBudget sees is the length that ships.
171
174
  */
172
- export function renderContext({ repoRoot, initiatives, doctor, hardware, nowIso, pause = null }) {
173
- if (initiatives.length === 0 && pause === null) return '';
175
+ export function renderContext({ repoRoot, initiatives, doctor, hardware, nowIso, pause = null, board = null }) {
176
+ if (initiatives.length === 0 && pause === null && board === null) return '';
174
177
  const lines = [
175
178
  '## Tyran state (injected by the session-start probe)',
176
179
  '',
177
180
  `Repo: ${inlinePlain(repoRoot)} · as of ${inlinePlain(nowIso)}`,
178
181
  `Machine: ${inlinePlain(hardware)}`,
179
182
  ];
183
+ // In the HEADER for the same reason the pause notice is: `fitBudget` drops
184
+ // whole sections from the END, and the URL is the one line a reader wants
185
+ // from a repo with enough state to overflow the budget.
186
+ if (board !== null) lines.push(renderBoardLine(board));
180
187
  // The pause notice lives in the HEADER, before any `### ` section, because
181
188
  // fitBudget always keeps the preamble and drops sections from the end — a
182
189
  // paused session must never lose the one line that says why it is paused.
@@ -401,6 +408,71 @@ export function recordConductor(stateDir, input, { now = new Date(), cwd = null
401
408
  }
402
409
  }
403
410
 
411
+ /**
412
+ * Start the dashboard, if it is not already up and the repo has not said no.
413
+ *
414
+ * This is the step that makes the board something an install HAS rather than
415
+ * something an operator remembers to run. Before it, the board was reached
416
+ * only by typing a command that holds a terminal, so on any install where
417
+ * nobody typed it every projection Tyran writes existed and nothing ever
418
+ * displayed them.
419
+ *
420
+ * Three properties, each of which the obvious implementation gets wrong:
421
+ *
422
+ * - it does NOT wait. `startDetachedNoWait` spawns and returns. This probe's
423
+ * whole budget is 4 s, already shared with doctor, and confirming a
424
+ * convenience would cost the user their session summary on a slow machine.
425
+ * The next session finds the server through `findLiveServer` and says so.
426
+ * - it asks whether one is running FIRST, over HTTP, scoped to this
427
+ * directory — so repeated sessions, `resume` and `compact` do not stack up
428
+ * servers, and another repo's board is never mistaken for this one's.
429
+ * - every failure is silent and returns a state, never an exception: a probe
430
+ * may not cost a session (ADR-22).
431
+ *
432
+ * Returns what to tell the reader, or null to say nothing at all.
433
+ */
434
+ export async function ensureBoard(stateDir, { settings = null, find = findLiveServer, start = startDetachedNoWait, env = process.env } = {}) {
435
+ try {
436
+ // A machine-wide off switch, above the per-repo config. CI is the case
437
+ // that needs it: an automated run has no browser, no operator and no
438
+ // interest in a dashboard, but it does clone repositories whose committed
439
+ // config says `autostart: true` — and a detached server started by a
440
+ // build outlives the build. Also the honest way for this repository's own
441
+ // end-to-end tests to run the real hook without leaking a server per test.
442
+ if (env.TYRAN_NO_BOARD === '1') return null;
443
+ const board = settings ?? boardSettings(readConfigDoc(stateDir));
444
+ if (board.autostart === false) return null;
445
+ const live = await find(stateDir, board.port);
446
+ if (live !== null) return { running: true, port: live.port, url: urlFor(live.port) };
447
+ // The port it actually chose, not the one asked for: with several repos
448
+ // open at once the preferred one is routinely taken, and printing a URL
449
+ // that belongs to a different repository's board is worse than silence.
450
+ const chosen = await start(stateDir, { port: board.port, write: board.write });
451
+ return chosen === null ? null : { running: false, port: chosen, url: urlFor(chosen) };
452
+ } catch {
453
+ return null; // a dashboard that could not start is not worth a failed session
454
+ }
455
+ }
456
+
457
+ /** This repo's config, parsed, or null — every failure reads as "no config". */
458
+ function readConfigDoc(stateDir) {
459
+ try {
460
+ const path = join(stateDir, 'config.yaml');
461
+ if (!existsSync(path)) return null;
462
+ return parseYaml(readFileSync(path, 'utf8'));
463
+ } catch {
464
+ return null;
465
+ }
466
+ }
467
+
468
+ /** One line telling the operator where the board is. */
469
+ export function renderBoardLine(board) {
470
+ if (board === null) return '';
471
+ return board.running
472
+ ? `Dashboard: ${inlinePlain(board.url)}`
473
+ : `Dashboard: starting at ${inlinePlain(board.url)} (give it a moment)`;
474
+ }
475
+
404
476
  /** The pause marker, if one is active. Garbage reads as absent. */
405
477
  export function readPauseMarker(stateDir) {
406
478
  try {
@@ -413,7 +485,19 @@ export function readPauseMarker(stateDir) {
413
485
  }
414
486
  }
415
487
 
416
- export async function buildContext({ input, now = new Date(), env = process.env, health = hookHealth } = {}) {
488
+ /**
489
+ * `ensure` is injectable and that is not a testing nicety — it is the seam
490
+ * that keeps a test suite from spawning servers.
491
+ *
492
+ * Every call of this function against a directory that has a `.tyran/` starts
493
+ * a detached board for it, and a test's temp directory is a NEW directory
494
+ * every time, so the idempotence that makes this safe in a real repo (one
495
+ * repo, one board) does not apply: each run leaves another live server behind
496
+ * it. Measured after adding autostart without this parameter — ten orphaned
497
+ * servers holding ports 4173-4182, the entire search span, which then made an
498
+ * unrelated test fail because no port was left to bind.
499
+ */
500
+ export async function buildContext({ input, now = new Date(), env = process.env, health = hookHealth, ensure = ensureBoard } = {}) {
417
501
  // Said even in a repository that has nothing to do with Tyran: the claim
418
502
  // being corrected is about the PLUGIN the user installed, not about this
419
503
  // project's state, and a user whose gates are dead needs to hear it in the
@@ -425,6 +509,7 @@ export async function buildContext({ input, now = new Date(), env = process.env,
425
509
  if (!existsSync(stateDir)) return fitBudget(warning); // not a Tyran repo — but a dead gate still counts
426
510
  recordConductor(stateDir, input, { now, cwd: repoRoot });
427
511
  const nowIso = now.toISOString();
512
+ const board = await ensure(stateDir);
428
513
  return fitBudget(
429
514
  warning +
430
515
  renderContext({
@@ -434,6 +519,7 @@ export async function buildContext({ input, now = new Date(), env = process.env,
434
519
  hardware: hardwareLine(),
435
520
  nowIso,
436
521
  pause: readPauseMarker(stateDir),
522
+ board,
437
523
  }),
438
524
  );
439
525
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.33",
3
+ "version": "0.1.34",
4
4
  "description": "Command-line scripts for the Tyran task conductor (doctor, journal, schema, and repo tooling) for CI and terminals outside Claude Code. Installing this package does NOT install the Claude Code plugin — add that separately with `/plugin marketplace add jjanczur/tyran` inside Claude Code.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -0,0 +1,412 @@
1
+ /**
2
+ * board-daemon — the part of `board.mjs --serve` that lets it be STARTED by
3
+ * something other than a human with a spare terminal.
4
+ *
5
+ * `--serve` blocks forever, which is correct for an operator who typed it and
6
+ * fatal for everything else. Setup's "turn the dashboard on" step handed an
7
+ * AGENT that command: the board came up, the agent's tool call then sat on it
8
+ * until the platform's timeout, and setup's remaining steps — validate,
9
+ * report, ask for the `.tyran/` commit — never ran. Measured: still listening
10
+ * three seconds after spawn, with nothing to return to the caller.
11
+ *
12
+ * So this module owns starting a server the caller does not have to wait for,
13
+ * and the harder half of that: knowing whether one is ALREADY running.
14
+ *
15
+ * THE LIVENESS CONTRACT, because a pid is the obvious answer and the wrong
16
+ * one. `session-start.mjs` states the general case — a pid recorded by a
17
+ * short-lived process is dead before anyone reads it, and once the OS recycles
18
+ * the number it names a stranger. A board that trusted its own record would
19
+ * therefore report "already running" about somebody else's process and never
20
+ * start. Liveness here is an HTTP question instead:
21
+ *
22
+ * 1. GET `/health.json` on the port,
23
+ * 2. and believe it only if it names THIS `.tyran` directory.
24
+ *
25
+ * Both halves are load-bearing. Without (1) a recycled pid is a false
26
+ * positive; without (2) the board of a DIFFERENT repository — same program,
27
+ * same route, same shape — answers and this one silently never starts, which
28
+ * is the failure mode of every "is my dev server up" check that only probes a
29
+ * port. The recorded pid is kept for exactly one job, `--stop`, where a stale
30
+ * one costs a refusal rather than a wrong answer.
31
+ *
32
+ * Everything is best-effort by construction. A caller that cannot start a
33
+ * board still has a working repository, so no function here throws on a
34
+ * failure to reach the network, the filesystem or a child process.
35
+ */
36
+ import { spawn as spawnProcess } from 'node:child_process';
37
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
38
+ import { get as httpGet } from 'node:http';
39
+ import { connect as netConnect } from 'node:net';
40
+ import { dirname, join, resolve } from 'node:path';
41
+ import { fileURLToPath } from 'node:url';
42
+
43
+ /** Where the running server records itself, relative to `.tyran`. */
44
+ export const SERVER_RECORD_FILE = 'board-server.json';
45
+ export const SERVER_RECORD_RELPATH = join('state', SERVER_RECORD_FILE);
46
+
47
+ /** Bumped when the record's shape changes; an older one reads as absent. */
48
+ export const SERVER_RECORD_SCHEMA = 1;
49
+
50
+ /** The route that answers the liveness question above. */
51
+ export const HEALTH_ROUTE = '/health.json';
52
+
53
+ /**
54
+ * How many ports to try from the preferred one.
55
+ *
56
+ * One board per repository, and people work in several repositories at once,
57
+ * so "the port is busy" is the ordinary case rather than an error. Ten is
58
+ * enough for any plausible number of simultaneous repos and small enough that
59
+ * an exhausted search is fast.
60
+ */
61
+ export const PORT_SEARCH_SPAN = 10;
62
+
63
+ /**
64
+ * A probe budget, not a timeout in the usual sense: this runs inside the
65
+ * SessionStart hook, whose whole deadline is 4 s and which already spends
66
+ * half of it on doctor. A loopback server either answers in single-digit
67
+ * milliseconds or is not there.
68
+ */
69
+ export const PROBE_TIMEOUT_MS = 400;
70
+
71
+ /** How long `--detach` waits for the child to answer before reporting. */
72
+ export const START_DEADLINE_MS = 5000;
73
+
74
+ const POLL_INTERVAL_MS = 100;
75
+
76
+ const HERE = dirname(fileURLToPath(import.meta.url));
77
+ const BOARD_SCRIPT = join(HERE, 'board.mjs');
78
+
79
+ export function serverRecordPath(dir) {
80
+ return join(dir, SERVER_RECORD_RELPATH);
81
+ }
82
+
83
+ /**
84
+ * The record, or null. Garbage, a wrong schema and an unreadable file are all
85
+ * "no record" — this file is a convenience, and a caller that crashed on a
86
+ * half-written one would be worse than the problem it solves.
87
+ */
88
+ export function readServerRecord(dir) {
89
+ try {
90
+ const path = serverRecordPath(dir);
91
+ if (!existsSync(path)) return null;
92
+ const doc = JSON.parse(readFileSync(path, 'utf8'));
93
+ if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) return null;
94
+ if (doc.schema !== SERVER_RECORD_SCHEMA) return null;
95
+ return doc;
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /** Atomic, same rename dance as every other runtime file Tyran writes. */
102
+ export function writeServerRecord(dir, record) {
103
+ try {
104
+ const target = serverRecordPath(dir);
105
+ mkdirSync(dirname(target), { recursive: true });
106
+ const temp = join(dirname(target), `.board-server-${process.pid}.tmp`);
107
+ writeFileSync(temp, `${JSON.stringify({ schema: SERVER_RECORD_SCHEMA, ...record }, null, 2)}\n`);
108
+ renameSync(temp, target);
109
+ return true;
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+
115
+ export function removeServerRecord(dir) {
116
+ try {
117
+ rmSync(serverRecordPath(dir), { force: true });
118
+ return true;
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * GET `/health.json` on one port. Resolves to the parsed document, or null for
126
+ * every failure — closed port, wrong program, timeout, unparseable body.
127
+ *
128
+ * The body is capped: this asks an arbitrary local port a question, and the
129
+ * thing that answers is not necessarily a board. A megabyte of response to a
130
+ * health probe is not a health response, and reading it in full would let any
131
+ * process on loopback decide how much memory this one spends.
132
+ */
133
+ export function probeHealth(port, { timeoutMs = PROBE_TIMEOUT_MS, request = httpGet } = {}) {
134
+ return new Promise((resolvePromise) => {
135
+ let settled = false;
136
+ const done = (value) => {
137
+ if (settled) return;
138
+ settled = true;
139
+ resolvePromise(value);
140
+ };
141
+ let req;
142
+ try {
143
+ req = request(
144
+ { host: '127.0.0.1', port, path: HEALTH_ROUTE, headers: { host: `127.0.0.1:${port}` } },
145
+ (res) => {
146
+ if (res.statusCode !== 200) {
147
+ res.resume();
148
+ done(null);
149
+ return;
150
+ }
151
+ let body = '';
152
+ res.setEncoding('utf8');
153
+ res.on('data', (chunk) => {
154
+ body += chunk;
155
+ if (body.length > 8192) {
156
+ req.destroy();
157
+ done(null);
158
+ }
159
+ });
160
+ res.on('end', () => {
161
+ try {
162
+ const doc = JSON.parse(body);
163
+ done(doc !== null && typeof doc === 'object' && doc.tyran_board === true ? doc : null);
164
+ } catch {
165
+ done(null);
166
+ }
167
+ });
168
+ res.on('error', () => done(null));
169
+ },
170
+ );
171
+ } catch {
172
+ done(null);
173
+ return;
174
+ }
175
+ req.on('error', () => done(null));
176
+ req.setTimeout?.(timeoutMs, () => {
177
+ req.destroy();
178
+ done(null);
179
+ });
180
+ });
181
+ }
182
+
183
+ /** Two directories are the same board when they resolve to the same path. */
184
+ function sameDir(a, b) {
185
+ try {
186
+ return resolve(String(a)) === resolve(String(b));
187
+ } catch {
188
+ return false;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Is a board for THIS directory already answering — and on which port?
194
+ *
195
+ * The recorded port is tried first because it is nearly always right and one
196
+ * probe is the whole cost. The span is then swept so that a server whose
197
+ * record was lost (a `git clean`, a crash between listen and write) is still
198
+ * found rather than duplicated.
199
+ */
200
+ export async function findLiveServer(dir, preferredPort, { probe = probeHealth } = {}) {
201
+ const record = readServerRecord(dir);
202
+ const ports = [];
203
+ if (record !== null && Number.isInteger(record.port)) ports.push(record.port);
204
+ for (let i = 0; i < PORT_SEARCH_SPAN; i += 1) {
205
+ const port = preferredPort + i;
206
+ if (!ports.includes(port)) ports.push(port);
207
+ }
208
+ for (const port of ports) {
209
+ const health = await probe(port);
210
+ if (health !== null && sameDir(health.dir, dir)) return { port, health };
211
+ }
212
+ return null;
213
+ }
214
+
215
+ /**
216
+ * Is anything at all listening on this port?
217
+ *
218
+ * A TCP connect, because the health probe CANNOT answer this. `probeHealth`
219
+ * returns null for "nothing is there" and for "something is there and it is
220
+ * not a board" alike, and a caller that reads that null as "free" will bind a
221
+ * port already in use. Measured exactly that way: an unrelated local server
222
+ * on the port answered `/health.json` with `not a board`, the health probe
223
+ * reported null, the port was declared free, the child died on EADDRINUSE,
224
+ * and `--detach` spent its whole 5 s deadline before reporting a failure that
225
+ * was knowable in one millisecond.
226
+ */
227
+ export function isPortFree(port, { timeoutMs = PROBE_TIMEOUT_MS, connect = netConnect } = {}) {
228
+ return new Promise((resolvePromise) => {
229
+ let settled = false;
230
+ const done = (value) => {
231
+ if (settled) return;
232
+ settled = true;
233
+ resolvePromise(value);
234
+ };
235
+ let socket;
236
+ try {
237
+ socket = connect({ host: '127.0.0.1', port });
238
+ } catch {
239
+ done(true); // could not even try to connect — treat as free and let bind decide
240
+ return;
241
+ }
242
+ socket.setTimeout?.(timeoutMs);
243
+ socket.on('connect', () => { socket.destroy(); done(false); });
244
+ socket.on('timeout', () => { socket.destroy(); done(true); });
245
+ socket.on('error', () => { socket.destroy?.(); done(true); }); // ECONNREFUSED — nothing there
246
+ });
247
+ }
248
+
249
+ /**
250
+ * The first port this board may take: one that is genuinely free, or one it
251
+ * already owns. A port held by ANY other program — another repository's
252
+ * board, or something with no opinion about Tyran at all — is skipped rather
253
+ * than fought over.
254
+ *
255
+ * The order of the two probes is deliberate. Ownership is asked FIRST because
256
+ * a board of ours answering is the case worth reusing, and only then is the
257
+ * cheaper "is anything there" question used to tell free from foreign.
258
+ *
259
+ * Returns null when the whole span is occupied — a real condition to report,
260
+ * not one to paper over by binding somewhere unpredictable.
261
+ */
262
+ export async function pickPort(dir, preferred, { probe = probeHealth, free = isPortFree } = {}) {
263
+ for (let i = 0; i < PORT_SEARCH_SPAN; i += 1) {
264
+ const port = preferred + i;
265
+ const health = await probe(port);
266
+ if (health !== null && sameDir(health.dir, dir)) return { port, reuse: true };
267
+ if (health !== null) continue; // a board, but not ours
268
+ if (await free(port)) return { port, reuse: false };
269
+ }
270
+ return null;
271
+ }
272
+
273
+ /**
274
+ * Start a server nobody has to wait for, and wait just long enough to be able
275
+ * to say whether it worked.
276
+ *
277
+ * `detached` + `stdio: 'ignore'` + `unref()` is what actually severs it from
278
+ * the caller: without all three the child keeps the parent's event loop or its
279
+ * pipes alive and the caller blocks anyway — which is the bug this file
280
+ * exists to fix, reintroduced one flag at a time.
281
+ *
282
+ * The CHILD writes the record, not this function, and that ordering is the
283
+ * point: it writes from inside its own `listen` callback, so a record exists
284
+ * only for a server that actually bound a port. A parent writing it first
285
+ * would be recording an intention.
286
+ */
287
+ export async function startDetached(
288
+ dir,
289
+ { port, write = true, open = false, transcripts = [], spawn = spawnProcess, probe = probeHealth, deadlineMs = START_DEADLINE_MS, sleep = defaultSleep } = {},
290
+ ) {
291
+ const existing = await findLiveServer(dir, port, { probe });
292
+ if (existing !== null) {
293
+ return { started: false, reused: true, port: existing.port, url: urlFor(existing.port), pid: existing.health.pid ?? null };
294
+ }
295
+ const chosen = await pickPort(dir, port, { probe });
296
+ if (chosen === null) {
297
+ return {
298
+ started: false,
299
+ reused: false,
300
+ error:
301
+ `ports ${port}-${port + PORT_SEARCH_SPAN - 1} are all in use by other programs — ` +
302
+ 'pass --port <n> to start somewhere else',
303
+ };
304
+ }
305
+ const args = [BOARD_SCRIPT, '--dir', dir, '--serve', '--port', String(chosen.port)];
306
+ if (write) args.push('--write');
307
+ if (open) args.push('--open');
308
+ for (const t of transcripts) args.push('--transcripts', t);
309
+ let child;
310
+ try {
311
+ child = spawn(process.execPath, args, { stdio: 'ignore', detached: true });
312
+ child.on?.('error', () => { /* reported by the health probe below, not by a throw */ });
313
+ child.unref?.();
314
+ } catch (err) {
315
+ return { started: false, reused: false, error: `could not spawn the board: ${String(err?.message ?? err)}` };
316
+ }
317
+ // Poll rather than trust the spawn: a child that exits immediately (a bad
318
+ // --dir, a port that raced) is indistinguishable from a healthy one at
319
+ // spawn time, and reporting a URL nothing answers is worse than an error.
320
+ const deadline = deadlineMs;
321
+ for (let waited = 0; waited < deadline; waited += POLL_INTERVAL_MS) {
322
+ await sleep(POLL_INTERVAL_MS);
323
+ const health = await probe(chosen.port);
324
+ if (health !== null && sameDir(health.dir, dir)) {
325
+ return { started: true, reused: false, port: chosen.port, url: urlFor(chosen.port), pid: health.pid ?? child.pid ?? null };
326
+ }
327
+ }
328
+ return { started: false, reused: false, error: `the board did not answer on port ${chosen.port} within ${deadline} ms` };
329
+ }
330
+
331
+ /**
332
+ * Start one without waiting for it to ANSWER — for callers on a hook's budget.
333
+ *
334
+ * Everything the polling version buys (a URL known to answer, a real pid, an
335
+ * error when the child died) is given up here on purpose: `SessionStart` has
336
+ * a 4 s deadline it shares with doctor, and spending seconds of it confirming
337
+ * a convenience would cost the user their session summary. The next session
338
+ * finds the server through `findLiveServer` and reports it then.
339
+ *
340
+ * What is NOT given up is choosing a port that can actually be bound. Skipping
341
+ * that would make the caller spawn a child onto an occupied port, where it
342
+ * dies on EADDRINUSE with `stdio: 'ignore'` — no output, no exit code anyone
343
+ * reads, and a board that never starts on EVERY session, silently, for as long
344
+ * as the other program holds the port. Port selection costs two immediate
345
+ * ECONNREFUSEDs in the normal case, which the budget can afford; being wrong
346
+ * here costs the whole feature.
347
+ *
348
+ * Returns the chosen port, or null if nothing was started.
349
+ */
350
+ export async function startDetachedNoWait(
351
+ dir,
352
+ { port, write = true, transcripts = [], spawn = spawnProcess, probe = probeHealth, free = isPortFree } = {},
353
+ ) {
354
+ const chosen = await pickPort(dir, port, { probe, free });
355
+ if (chosen === null) return null;
356
+ const args = [BOARD_SCRIPT, '--dir', dir, '--serve', '--port', String(chosen.port)];
357
+ if (write) args.push('--write');
358
+ for (const t of transcripts) args.push('--transcripts', t);
359
+ try {
360
+ const child = spawn(process.execPath, args, { stdio: 'ignore', detached: true });
361
+ child.on?.('error', () => { /* nothing to report to; the next session probes */ });
362
+ child.unref?.();
363
+ return chosen.port;
364
+ } catch {
365
+ return null;
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Stop the recorded server.
371
+ *
372
+ * The pid is only trusted this far because the cost of being wrong is bounded
373
+ * and visible: the health probe runs FIRST, so a pid is signalled only when a
374
+ * board for this directory is genuinely answering on the recorded port. That
375
+ * closes the recycled-pid window to the case where a stranger inherited the
376
+ * pid AND a real board answers AND the record is stale — at which point the
377
+ * kill fails or hits the board, never an unrelated process by luck alone.
378
+ */
379
+ export async function stopServer(dir, { probe = probeHealth, kill = process.kill.bind(process) } = {}) {
380
+ const record = readServerRecord(dir);
381
+ if (record === null) return { stopped: false, reason: 'no board server is recorded for this directory' };
382
+ const health = await probe(record.port);
383
+ if (health === null || !sameDir(health.dir, dir)) {
384
+ removeServerRecord(dir);
385
+ return { stopped: false, reason: `nothing is answering on port ${record.port} — cleared the stale record` };
386
+ }
387
+ const pid = health.pid ?? record.pid;
388
+ if (!Number.isInteger(pid)) return { stopped: false, reason: 'the running board did not report a pid' };
389
+ try {
390
+ kill(pid, 'SIGTERM');
391
+ } catch (err) {
392
+ return { stopped: false, reason: `could not signal pid ${pid}: ${String(err?.message ?? err)}` };
393
+ }
394
+ removeServerRecord(dir);
395
+ return { stopped: true, pid, port: record.port };
396
+ }
397
+
398
+ export function urlFor(port) {
399
+ return `http://127.0.0.1:${port}/`;
400
+ }
401
+
402
+ /**
403
+ * NOT unref'd, and that is the whole function.
404
+ *
405
+ * An unref'd timer does not hold the event loop open, so `--detach` drained
406
+ * its loop and exited between the spawn and the first poll — reporting
407
+ * nothing at all about a server that then started fine half a second later.
408
+ * The command looked instantaneous and successful and printed no URL.
409
+ */
410
+ function defaultSleep(ms) {
411
+ return new Promise((r) => { setTimeout(r, ms); });
412
+ }
@@ -135,6 +135,12 @@ h3{font-family:var(--font);color:var(--heading);font-size:.85rem;margin:1.1rem 0
135
135
  .file .fname{color:var(--steel-bright);font-family:var(--mono);font-weight:600;min-width:6rem}
136
136
  .file code{color:var(--muted);font-size:.72rem;word-break:break-all}
137
137
 
138
+ /* ---- what actually ran on a ticket ---- */
139
+ .runs{width:100%;border-collapse:collapse;margin-top:.3rem;font-size:.74rem;display:block;overflow-x:auto}
140
+ .runs th{text-align:left;color:var(--muted);font-weight:600;padding:.2rem .5rem .2rem 0;border-bottom:1px solid var(--hairline);white-space:nowrap}
141
+ .runs td{padding:.22rem .5rem .22rem 0;border-bottom:1px solid var(--hairline);vertical-align:top}
142
+ .runs td:first-child{font-family:var(--mono);color:var(--steel-bright)}
143
+
138
144
  /* ---- lanes ---- */
139
145
  .lanes{display:grid;grid-template-columns:repeat(auto-fill,minmax(15rem,1fr));gap:.6rem;align-items:start}
140
146
  .lane{background:var(--bg-sunken);border:1px solid var(--hairline-soft);border-radius:var(--radius);padding:.55rem}
@@ -731,6 +737,16 @@ if (data.schema !== 1) {
731
737
  // a ticket had come back and never why, which is the one thing the card is
732
738
  // opened for.
733
739
  row('reported', card.report_text);
740
+ // The two lifecycle facts the lane could only imply: which commit a
741
+ // merged ticket became, and who wrote the review that sent it back.
742
+ if (card.review) {
743
+ row('review', card.review.verdict + (card.review.by ? ' by ' + card.review.by : '')
744
+ + (card.review.ts ? ' · ' + ago(card.review.ts) : ''));
745
+ }
746
+ if (card.merge) {
747
+ row('merged', (card.merge.sha || 'no sha') + (card.merge.mode ? ' (' + card.merge.mode + ')' : '')
748
+ + (card.merge.ts ? ' · ' + ago(card.merge.ts) : ''));
749
+ }
734
750
  row('last event', card.since ? ago(card.since) + ' (' + card.since + ')' : null);
735
751
  if (cost) {
736
752
  var hit = (cost.by_ticket || []).filter(function (r) { return r.ticket === card.id; })[0];
@@ -739,6 +755,30 @@ if (data.schema !== 1) {
739
755
  row('spend', costError);
740
756
  }
741
757
  box.appendChild(dl);
758
+ // What actually ran on this ticket: agent, model, when, verdict. A table
759
+ // rather than more dl rows, because the interesting reading is DOWN a
760
+ // column — three implementers on one ticket, or the same story reopened
761
+ // on a bigger model — and that comparison is what a list of prose rows
762
+ // makes impossible.
763
+ var runs = card.execution || [];
764
+ if (runs.length > 0) {
765
+ box.appendChild(el('div', 'dt', 'Execution'));
766
+ var tbl = el('table', 'runs');
767
+ var head = el('tr');
768
+ ['agent', 'model', 'started', 'verdict'].forEach(function (h) { head.appendChild(el('th', null, h)); });
769
+ tbl.appendChild(head);
770
+ runs.forEach(function (r) {
771
+ var tr = el('tr');
772
+ tr.appendChild(el('td', null, r.agent + (r.role ? ' (' + r.role + ')' : '')));
773
+ // A spawn that named no model is a real state, not a gap to hide: it
774
+ // means the conductor let the platform default decide.
775
+ tr.appendChild(el('td', null, r.model || '—'));
776
+ tr.appendChild(el('td', null, r.started ? ago(r.started) : '—'));
777
+ tr.appendChild(el('td', null, r.verdict || (r.ended ? 'no verdict' : 'running')));
778
+ tbl.appendChild(tr);
779
+ });
780
+ box.appendChild(tbl);
781
+ }
742
782
  // The files this initiative ACTUALLY has, listed by the server after an
743
783
  // existsSync — never a fixed list of what a well-run initiative ought to
744
784
  // contain. Paths, not links: the board serves three URLs and derives a
package/scripts/board.mjs CHANGED
@@ -21,8 +21,13 @@
21
21
  *
22
22
  * CLI:
23
23
  * node board.mjs [--dir <.tyran>] [--check]
24
- * [--serve [--port <n>] [--write] [--open] [--transcripts <dir>]...]
25
- * Exit: 0 ok · 1 drift (--check) · 2 usage/IO
24
+ * [--serve|--detach [--port <n>] [--write] [--open] [--transcripts <dir>]...]
25
+ * [--status] [--stop]
26
+ * Exit: 0 ok · 1 drift (--check), or no server (--status/--stop) · 2 usage/IO
27
+ *
28
+ * `--serve` holds the terminal; `--detach` starts the same server, waits only
29
+ * until it answers, and returns. Anything that is not a human with a spare
30
+ * terminal wants the second one — see board-daemon.mjs.
26
31
  */
27
32
  import { existsSync, readdirSync, statSync, readFileSync } from 'node:fs';
28
33
  import { createServer } from 'node:http';
@@ -50,9 +55,22 @@ import { SettingsError, applyPolicyClass, applySetting, readSettings } from './s
50
55
  import { checkStopAt } from './stop-check.mjs';
51
56
  import { runState } from './overnight.mjs';
52
57
  import { answerOne, answerProblem, classify, openAsks, partitionAsks, reRender, sortAsks } from './answer.mjs';
58
+ import {
59
+ HEALTH_ROUTE,
60
+ PORT_SEARCH_SPAN,
61
+ findLiveServer,
62
+ removeServerRecord,
63
+ startDetached,
64
+ stopServer,
65
+ urlFor,
66
+ writeServerRecord,
67
+ } from './board-daemon.mjs';
53
68
 
54
69
  export const BOARD_HTML_FILE = 'board.html';
55
70
 
71
+ /** How often a served board checks that it still has a directory to serve. */
72
+ export const DIR_WATCHDOG_MS = 60_000;
73
+
56
74
  /**
57
75
  * Open the served board in the operator's browser.
58
76
  *
@@ -645,14 +663,17 @@ function handleSettingsWrite(dir, route, body) {
645
663
 
646
664
  // ------------------------------------------------------------------- CLI
647
665
 
648
- const BOOLEAN_FLAGS = ['check', 'serve', 'write', 'open'];
666
+ const BOOLEAN_FLAGS = ['check', 'serve', 'write', 'open', 'detach', 'stop', 'status'];
649
667
  const VALUE_FLAGS = ['dir', 'port'];
650
668
  // Repeatable, unlike VALUE_FLAGS: sources are the union over every directory
651
669
  // given, exactly like cost.mjs's own `--transcripts`.
652
670
  const REPEATABLE_FLAGS = ['transcripts'];
653
671
 
654
672
  function parseArgs(argv) {
655
- const flags = { dir: '.tyran', port: 4173, check: false, serve: false, write: false, open: false, transcripts: [] };
673
+ const flags = {
674
+ dir: '.tyran', port: 4173, check: false, serve: false, write: false, open: false,
675
+ detach: false, stop: false, status: false, transcripts: [],
676
+ };
656
677
  for (let i = 0; i < argv.length; i += 1) {
657
678
  const arg = argv[i];
658
679
  if (!arg.startsWith('--')) throw new UsageError(`unexpected argument "${arg}"`);
@@ -684,25 +705,34 @@ function main() {
684
705
  if (!(err instanceof UsageError)) throw err;
685
706
  console.error(`board: ${err.message}`);
686
707
  console.error(
687
- 'usage: board.mjs [--dir <.tyran>] [--check] ' +
688
- '[--serve [--port <n>] [--write] [--transcripts <dir>]...]'
708
+ 'usage: board.mjs [--dir <.tyran>] [--check]\n' +
709
+ ' [--serve|--detach [--port <n>] [--write] [--open] [--transcripts <dir>]...]\n' +
710
+ ' [--status] [--stop]'
689
711
  );
690
712
  process.exit(2);
691
713
  }
692
- if (flags.write && !flags.serve) {
693
- console.error('board: --write only means anything with --serve (it is what the served page may edit)');
714
+ // `--detach` is `--serve` that returns. Every flag describing HOW to serve
715
+ // therefore has to accept either, or the detached form would refuse exactly
716
+ // the arguments it exists to be given.
717
+ const serving = flags.serve || flags.detach;
718
+ if (flags.serve && flags.detach) {
719
+ console.error('board: --serve and --detach are the same server, one holding the terminal and one not — pass one');
694
720
  process.exit(2);
695
721
  }
696
- if (flags.open && !flags.serve) {
722
+ if (flags.write && !serving) {
723
+ console.error('board: --write only means anything with --serve or --detach (it is what the served page may edit)');
724
+ process.exit(2);
725
+ }
726
+ if (flags.open && !serving) {
697
727
  // Same refusal as --write and --transcripts, for the same reason: there is
698
728
  // no URL to open without a server, and a flag that silently does nothing
699
729
  // reads as configuration.
700
- console.error('board: --open only means anything with --serve (there is no URL to open without it)');
730
+ console.error('board: --open only means anything with --serve or --detach (there is no URL to open without it)');
701
731
  process.exit(2);
702
732
  }
703
- if (flags.transcripts.length > 0 && !flags.serve) {
733
+ if (flags.transcripts.length > 0 && !serving) {
704
734
  console.error(
705
- 'board: --transcripts only means anything with --serve (it is what /cost.json reads instead of ' +
735
+ 'board: --transcripts only means anything with --serve or --detach (it is what /cost.json reads instead of ' +
706
736
  'the derived transcript directory)'
707
737
  );
708
738
  process.exit(2);
@@ -729,6 +759,63 @@ function main() {
729
759
  }
730
760
  const outDir = join(dir, 'state');
731
761
 
762
+ // ---- the three routes that talk ABOUT a server rather than being one ----
763
+ //
764
+ // All three are async, and `main` stays sync for everything else on
765
+ // purpose: the rendering path is the one every test and every hook drives,
766
+ // and making it return a promise would change the shape of a contract that
767
+ // has nothing to do with servers.
768
+ if (flags.status) {
769
+ findLiveServer(dir, flags.port).then((live) => {
770
+ if (live === null) {
771
+ console.log(
772
+ `board: no server is answering for ${dir} ` +
773
+ `(tried the recorded port, if any, then ${flags.port}-${flags.port + PORT_SEARCH_SPAN - 1}) — ` +
774
+ `start one with: node scripts/board.mjs --dir ${dir} --detach --write`,
775
+ );
776
+ process.exitCode = 1;
777
+ return;
778
+ }
779
+ console.log(
780
+ `board: serving ${urlFor(live.port)} (pid ${live.health.pid ?? '?'}; ` +
781
+ `${live.health.write ? 'Settings can edit config.yaml and autonomy.yaml' : 'read-only'})`,
782
+ );
783
+ });
784
+ return;
785
+ }
786
+ if (flags.stop) {
787
+ stopServer(dir).then((result) => {
788
+ if (result.stopped) {
789
+ console.log(`board: stopped the server on port ${result.port} (pid ${result.pid})`);
790
+ return;
791
+ }
792
+ console.error(`board: ${result.reason}`);
793
+ process.exitCode = 1;
794
+ });
795
+ return;
796
+ }
797
+ if (flags.detach) {
798
+ startDetached(dir, { port: flags.port, write: flags.write, open: flags.open, transcripts: flags.transcripts })
799
+ .then((result) => {
800
+ if (result.error) {
801
+ console.error(`board: ${result.error}`);
802
+ process.exitCode = 2;
803
+ return;
804
+ }
805
+ // "Already running" is a SUCCESS, and saying which one it is matters:
806
+ // this command is meant to be safe to run on every session start, so
807
+ // its ordinary outcome is that there was nothing to do.
808
+ console.log(
809
+ result.reused
810
+ ? `board: already serving ${result.url} (pid ${result.pid ?? '?'})`
811
+ : `board: serving ${result.url} (pid ${result.pid ?? '?'}; ` +
812
+ `${flags.write ? 'Settings can edit config.yaml and autonomy.yaml' : 'read-only'}; ` +
813
+ `stop it with: node scripts/board.mjs --dir ${dir} --stop)`,
814
+ );
815
+ });
816
+ return;
817
+ }
818
+
732
819
  if (flags.serve) {
733
820
  // Loopback-only, re-rendered per request so it is always fresh. No
734
821
  // filesystem path is ever derived from the URL.
@@ -764,6 +851,15 @@ function main() {
764
851
  // marker, the resume watcher and the usage sidecar are gitignored and
765
852
  // different on every machine, so they are served — the same split, and
766
853
  // the same argument, spend already makes.
854
+ // The liveness answer, and the ONLY reliable one. A caller asking
855
+ // "is a board already up for this repo" cannot use the recorded pid —
856
+ // see board-daemon.mjs for why — so it asks the server itself, and
857
+ // `dir` is what stops ANOTHER repository's board (same program, same
858
+ // route) from answering yes on this one's behalf.
859
+ if (req.url === HEALTH_ROUTE) {
860
+ sendJson(res, 200, { tyran_board: true, schema: 1, dir, pid: process.pid, port: flags.port, write: flags.write });
861
+ return;
862
+ }
767
863
  if (req.url === '/run.json') {
768
864
  try {
769
865
  sendJson(res, 200, { schema: 1, ...runState(resolve(dir, '..')) });
@@ -884,13 +980,46 @@ function main() {
884
980
  process.exitCode = 2;
885
981
  });
886
982
  server.listen(flags.port, '127.0.0.1', () => {
887
- const url = `http://127.0.0.1:${flags.port}/`;
983
+ const url = urlFor(flags.port);
984
+ // Written from INSIDE the listen callback, so the record only ever
985
+ // describes a server that actually bound a port — a record written
986
+ // before this point would be an intention, and `--stop` would signal
987
+ // whatever inherited the pid of a board that never started.
988
+ writeServerRecord(dir, { pid: process.pid, port: flags.port, url, write: flags.write, started_at: new Date().toISOString() });
888
989
  console.log(
889
990
  `board: serving ${url} ` +
890
991
  `(${flags.write ? 'Settings can edit config.yaml and autonomy.yaml' : 'read-only'}; Ctrl-C to stop)`,
891
992
  );
892
993
  if (flags.open) openInBrowser(url);
893
994
  });
995
+ // Clear the record on the way out, so the next caller does not have to
996
+ // probe a port to learn that this one is gone. Best-effort: a killed
997
+ // process runs none of this, which is exactly why the reader treats the
998
+ // record as a hint and the health probe as the answer.
999
+ const clear = () => { removeServerRecord(dir); };
1000
+ process.on('exit', clear);
1001
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
1002
+ process.on(signal, () => {
1003
+ clear();
1004
+ process.exit(0);
1005
+ });
1006
+ }
1007
+ // A board whose directory is gone is serving nothing, and nothing will
1008
+ // ever ask it to stop: `--stop` needs a `.tyran` to find the record in,
1009
+ // and the operator who deleted the checkout is not going to hunt a pid.
1010
+ // Detached servers are started automatically now, so "nobody ever stops
1011
+ // it" is the DEFAULT case rather than an unlucky one — a deleted worktree
1012
+ // otherwise leaves a process holding a port until the machine reboots.
1013
+ const watchdog = setInterval(() => {
1014
+ if (!existsSync(dir)) {
1015
+ clear();
1016
+ process.exit(0);
1017
+ }
1018
+ }, DIR_WATCHDOG_MS);
1019
+ // Unref'd so it is the SERVER that keeps this process alive, never the
1020
+ // timer: a watchdog that held the loop open would turn every exit path
1021
+ // above into a hang.
1022
+ watchdog.unref?.();
894
1023
  return;
895
1024
  }
896
1025
 
@@ -65,6 +65,7 @@ import { classifyPath, normalizePath, validateFile, knowledgeWarnings, MANDATORY
65
65
  import { auditEntries, loadEntries as loadKnowledgeEntries } from './knowledge.mjs';
66
66
  import { readPlatformUsage } from './usage-source.mjs';
67
67
  import { gitRunner } from './scan-repo.mjs';
68
+ import { SERVER_RECORD_FILE } from './board-daemon.mjs';
68
69
  import { parseMistakes, countSignatures, fenceState, KNOWLEDGE_THRESHOLD, MISTAKES_FILE, CLAUDE_MD_FILE } from './mistakes.mjs';
69
70
 
70
71
  /** Severity order is also the report order. `info` never fails the check. */
@@ -1613,7 +1614,17 @@ export function mistakesFindings(repoRoot, run = null) {
1613
1614
 
1614
1615
  /** The repo-global overnight runtime files that legally live at state/ level. */
1615
1616
  /** The cross-initiative board artefacts board.mjs writes at state/ level. */
1616
- export const CROSS_BOARD_FILES = Object.freeze(['BOARD.md', 'board.json', 'board.html']);
1617
+ export const CROSS_BOARD_FILES = Object.freeze([
1618
+ 'BOARD.md',
1619
+ 'board.json',
1620
+ 'board.html',
1621
+ // Not a projection like the three above — the running server's own record,
1622
+ // written from inside its listen callback and removed on the way out. It
1623
+ // sits at this level because the server serves the whole directory, and it
1624
+ // is machine-local for the same reason the overnight files are: another
1625
+ // clone has a different pid on a different port.
1626
+ SERVER_RECORD_FILE,
1627
+ ]);
1617
1628
 
1618
1629
  export const OVERNIGHT_RUNTIME_FILES = Object.freeze([
1619
1630
  'paused-until.json',
@@ -400,6 +400,17 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
400
400
  title: null,
401
401
  deps: null,
402
402
  agents: [],
403
+ // The same spawns as `agents`, by REFERENCE rather than by name, so a
404
+ // ticket can answer "what actually ran here" — which model, from when
405
+ // to when, ending in what verdict. `agents` stays a list of names
406
+ // because BOARD.md and the lane cards both read it as one.
407
+ //
408
+ // References, not copies, on purpose: the `report` fold mutates a
409
+ // spawn's status, verdict and reportTs after this push, and a copy
410
+ // taken at spawn time would freeze every run as `running` with no
411
+ // verdict — which is exactly the row an operator opens a finished
412
+ // ticket to read.
413
+ runs: [],
403
414
  report: null,
404
415
  review: null,
405
416
  merge: null,
@@ -482,7 +493,11 @@ export function fold({ events = [], truncatedTail = false, badLines = [] } = {})
482
493
  }
483
494
  }
484
495
  state.agents.push(agent);
485
- if (data.ticket != null) ticketOf(data.ticket, ts).agents.push(agent.agent);
496
+ if (data.ticket != null) {
497
+ const onTicket = ticketOf(data.ticket, ts);
498
+ onTicket.agents.push(agent.agent);
499
+ onTicket.runs.push(agent);
500
+ }
486
501
  break;
487
502
  }
488
503
  case 'report': {
@@ -909,6 +924,25 @@ export function boardOf(state, { staleHours = DEFAULT_STALE_HOURS } = {}) {
909
924
  // discarded at fold time, so the board could say a ticket had come back
910
925
  // and never why — the one thing the reader opens the card for.
911
926
  report_text: t.report?.text ?? null,
927
+ // The two lifecycle facts the LANE could only imply. `done` said a
928
+ // ticket was merged and never which commit; `changes-requested` said a
929
+ // review had come back and never who wrote it. Both are in the journal
930
+ // — `review` carries ticket/verdict/by and `merge` carries ticket/sha —
931
+ // and neither reached the one surface people open to ask.
932
+ review: t.review === null ? null : { verdict: t.review.verdict, by: t.review.by, ts: t.review.ts },
933
+ merge: t.merge === null ? null : { sha: t.merge.sha, mode: t.merge.mode, ts: t.merge.ts },
934
+ // What actually ran, in spawn order: which agent, on which model, from
935
+ // when to when, ending in what verdict. `worked_by` answers "who
936
+ // touched this"; this answers "what did it cost me and how did it go",
937
+ // which is the question a finished ticket is opened for.
938
+ execution: t.runs.map((a) => ({
939
+ agent: a.agent,
940
+ role: a.role,
941
+ model: a.model,
942
+ started: a.spawnTs,
943
+ ended: a.reportTs,
944
+ verdict: a.verdict,
945
+ })),
912
946
  annotation: annotations.length > 0 ? annotations.join(' · ') : null,
913
947
  });
914
948
  }
@@ -375,6 +375,17 @@ export function scanRepo(dir, { run = gitRunner(dir) } = {}) {
375
375
  resume_margin_minutes: 5,
376
376
  keep_awake: false,
377
377
  },
378
+ // The dashboard, ON. Written in full for the same reason `limits:` is —
379
+ // the Settings tab patches keys that exist and will not invent them — but
380
+ // with the opposite default, because the argument for OFF does not apply.
381
+ // `limits:` off is inert; a board that does not start means every
382
+ // projection Tyran writes is generated and never read by anyone.
383
+ board: {
384
+ autostart: true,
385
+ port: 4173,
386
+ write: true,
387
+ open: false,
388
+ },
378
389
  };
379
390
 
380
391
  const questions = [];
@@ -745,6 +756,9 @@ export const STATE_GITIGNORE_LINES = Object.freeze([
745
756
  // that was stale the moment it was written.
746
757
  'state/conductor.json',
747
758
  'state/ANSWERS.md',
759
+ // The running board's own record: a pid and a port, which name a process on
760
+ // THIS machine and a stranger anywhere else.
761
+ 'state/board-server.json',
748
762
  ]);
749
763
  const STATE_GITIGNORE_BODY =
750
764
  '# Runtime files, never history. Leases record who holds a worktree or a\n' +
@@ -68,7 +68,7 @@ export function validateConfig(doc) {
68
68
  const errors = [];
69
69
  if (!isPlainObject(doc)) return ['config must be a mapping'];
70
70
 
71
- const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths', 'limits', 'pricing', 'spend'];
71
+ const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths', 'limits', 'pricing', 'spend', 'board'];
72
72
  for (const key of Object.keys(doc)) {
73
73
  if (!known.includes(key)) errors.push(`${key}: unknown top-level key`);
74
74
  }
@@ -259,9 +259,59 @@ export function validateConfig(doc) {
259
259
  }
260
260
  }
261
261
 
262
+ // The dashboard's own switches. Absent means the DEFAULTS below apply, and
263
+ // those defaults are ON — the board is where everything Tyran does becomes
264
+ // legible, and an install that leaves it off is an install where none of it
265
+ // is. This block exists to turn it DOWN, which is why every key is optional.
266
+ if ('board' in doc) {
267
+ if (!isPlainObject(doc.board)) errors.push('board: must be a mapping');
268
+ else {
269
+ const board = doc.board;
270
+ for (const key of ['autostart', 'write', 'open']) {
271
+ if (key in board && typeof board[key] !== 'boolean') {
272
+ errors.push(`board.${key}: must be true or false (quote 'off'/'on' if you meant a string — bare ones are YAML booleans)`);
273
+ }
274
+ }
275
+ if ('port' in board) {
276
+ const port = board.port;
277
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
278
+ errors.push('board.port: must be an integer in (0, 65535]');
279
+ }
280
+ }
281
+ const knownBoard = ['autostart', 'port', 'write', 'open'];
282
+ for (const key of Object.keys(board)) {
283
+ if (!knownBoard.includes(key)) errors.push(`board.${key}: unknown key`);
284
+ }
285
+ }
286
+ }
287
+
262
288
  return errors;
263
289
  }
264
290
 
291
+ /**
292
+ * The board's settings, with the defaults applied.
293
+ *
294
+ * ONE function, because three callers need this answer — the session-start
295
+ * hook that autostarts, the setup skill's command, and doctor — and three
296
+ * copies of "default the port to 4173" is ADR-21 with a port number in it.
297
+ *
298
+ * `autostart` and `write` default TRUE. The board was previously reached only
299
+ * by a human typing a blocking command, which meant that on any install where
300
+ * nobody typed it, every projection Tyran writes existed and nothing read
301
+ * them. Defaulting off would preserve exactly that.
302
+ */
303
+ export const BOARD_DEFAULTS = Object.freeze({ autostart: true, port: 4173, write: true, open: false });
304
+
305
+ export function boardSettings(doc) {
306
+ const board = isPlainObject(doc) && isPlainObject(doc.board) ? doc.board : {};
307
+ return {
308
+ autostart: typeof board.autostart === 'boolean' ? board.autostart : BOARD_DEFAULTS.autostart,
309
+ port: Number.isInteger(board.port) && board.port > 0 && board.port <= 65535 ? board.port : BOARD_DEFAULTS.port,
310
+ write: typeof board.write === 'boolean' ? board.write : BOARD_DEFAULTS.write,
311
+ open: typeof board.open === 'boolean' ? board.open : BOARD_DEFAULTS.open,
312
+ };
313
+ }
314
+
265
315
  export const LIMITS_MODES = Object.freeze(['off', 'warn', 'pause']);
266
316
  export const LIMITS_LONG_WAIT = Object.freeze(['hold', 'resume']);
267
317
 
@@ -168,9 +168,16 @@ files on disk; the board is where any of it becomes legible, and it was the
168
168
  one thing installation never actually reached.
169
169
 
170
170
  ```bash
171
- node "${CLAUDE_PLUGIN_ROOT}/scripts/board.mjs" --dir .tyran --serve --write --open
171
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/board.mjs" --dir .tyran --detach --write --open
172
172
  ```
173
173
 
174
+ **`--detach`, never `--serve`.** They are the same server; `--serve` holds the
175
+ terminal until Ctrl-C, which is right for a human who typed it and fatal here
176
+ — an agent that runs it sits on the call until the platform's timeout, and
177
+ every step below this one silently never happens. That is what this step used
178
+ to do. `--detach` waits only until the board answers, prints the URL, and
179
+ returns; `--stop` ends it.
180
+
174
181
  `--open` launches their browser; `--write` is what makes the **Settings** tab
175
182
  able to edit `config.yaml` and the autonomy policy from the page. Tell them
176
183
  that tab exists and what it covers — profile, autonomy class, tiers,
@@ -178,8 +185,12 @@ validation commands, shared zones, overnight limits — because for someone who
178
185
  would rather not hand-edit YAML in their own repository, that tab is the
179
186
  entire configuration story and they will not guess it is there.
180
187
 
181
- It holds the terminal while it serves. Say so, and say that Ctrl-C stops it
182
- and the board is still there next time.
188
+ Say that they do not have to run this again: the scan wrote a `board:` block
189
+ with `autostart: true`, so every later session starts the board if it is not
190
+ already up, and prints the URL in its opening summary. Several repositories at
191
+ once each get their own — the port walks forward from 4173 when one is taken.
192
+ `node scripts/board.mjs --dir .tyran --status` says where it is; `--stop` ends
193
+ it; `autostart: false` in the config turns the whole thing off.
183
194
 
184
195
  ## 5. Validate and report
185
196
 
@@ -68,6 +68,24 @@ limits:
68
68
  resume_margin_minutes: 5
69
69
  keep_awake: false # a real boolean, so the bare-off trap above cannot apply
70
70
 
71
+ # The dashboard. Unlike everything above, this defaults ON: the board is where
72
+ # a journal, a projection and a spend report become something a person can
73
+ # read, and an install where nobody starts it is an install where none of that
74
+ # is ever seen. Set autostart: false to turn it down.
75
+ #
76
+ # autostart: true start it with the session, if it is not already up
77
+ # port: 4173 the first port tried; the next 9 are used if it is taken,
78
+ # so several repositories can each have their own board
79
+ # write: true lets the Settings tab edit config.yaml and the autonomy
80
+ # policy. false serves the same page read-only.
81
+ # open: false true also launches your browser on every session, which
82
+ # is a tab per session — the URL is printed either way.
83
+ board:
84
+ autostart: true
85
+ port: 4173
86
+ write: true
87
+ open: false
88
+
71
89
  # What a model costs, per MILLION tokens. Optional; absent means the spend
72
90
  # report counts tokens and shows no money, which is the honest default —
73
91
  # Tyran does not know what you pay. Operator-written from a vendor's price