@jjanczur/tyran 0.1.10 → 0.1.12

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.
@@ -0,0 +1,352 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * board — the cross-initiative kanban view.
4
+ *
5
+ * `project.mjs` renders one initiative's BOARD.md/board.json next to its
6
+ * journal; this tool folds EVERY journal under `.tyran/state/` into one
7
+ * board — the answer to "what is going on" that previously required opening
8
+ * one file per initiative (measured install: 31). Three artefacts, all
9
+ * GENERATED, all under `state/` where the AUTO policy class already covers
10
+ * them:
11
+ *
12
+ * .tyran/state/BOARD.md the agent/git surface
13
+ * .tyran/state/board.json schema 1, for tooling
14
+ * .tyran/state/board.html the page an operator stares at (board-html.mjs)
15
+ *
16
+ * Determinism carries over from the projection layer: no clock (the page
17
+ * shows the newest event ts as "as of"), byte-identical reruns, invisibles
18
+ * escaped never removed, `--check` compares bytes. An unreadable journal is a
19
+ * visible error entry, never a crash — a board that omits a broken
20
+ * initiative reads as "all is well" exactly when it is not.
21
+ *
22
+ * CLI:
23
+ * node board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>]]
24
+ * Exit: 0 ok · 1 drift (--check) · 2 usage/IO
25
+ */
26
+ import { existsSync, readdirSync, statSync, readFileSync } from 'node:fs';
27
+ import { createServer } from 'node:http';
28
+ import { join, resolve } from 'node:path';
29
+ import { realpathSync } from 'node:fs';
30
+ import { fileURLToPath } from 'node:url';
31
+ import { readJournal } from './journal.mjs';
32
+ import {
33
+ BOARD_FILE,
34
+ BOARD_JSON_FILE,
35
+ LANES,
36
+ boardOf,
37
+ checkFile,
38
+ fold,
39
+ inline,
40
+ writeAllAtomic,
41
+ } from './project.mjs';
42
+ import { jsonEscapeInvisible } from './invisible.mjs';
43
+ import { renderBoardHtml } from './board-html.mjs';
44
+
45
+ export const BOARD_HTML_FILE = 'board.html';
46
+
47
+ /** Same ceiling as the evidence gate's journal locator — a deliberate
48
+ * duplicate: scripts must not import from hook files (direction is
49
+ * hooks -> scripts), and the constant is one number with one meaning. */
50
+ export const MAX_INITIATIVES = 64;
51
+
52
+ const GENERATED_MD_HEADER =
53
+ '<!-- GENERATED by tyran scripts/board.mjs - DO NOT EDIT. Source of truth: the journals under .tyran/state/ -->\n' +
54
+ '<!-- Regenerate: node scripts/board.mjs --dir <.tyran> -->\n';
55
+
56
+ class UsageError extends Error {}
57
+
58
+ /** Every initiative folded to its board; failures become visible entries. */
59
+ export function readInitiativeBoards(tyranDir) {
60
+ const stateDir = join(tyranDir, 'state');
61
+ let names;
62
+ try {
63
+ names = readdirSync(stateDir).sort();
64
+ } catch {
65
+ return { initiatives: [], errors: [] };
66
+ }
67
+ const dirs = names.filter((name) => {
68
+ try {
69
+ return statSync(join(stateDir, name)).isDirectory();
70
+ } catch {
71
+ return false;
72
+ }
73
+ });
74
+ if (dirs.length > MAX_INITIATIVES) {
75
+ throw new UsageError(
76
+ `${dirs.length} initiative directories under ${stateDir} — the ceiling is ${MAX_INITIATIVES}. ` +
77
+ 'Archive closed initiatives out of state/ before rendering a board over them.',
78
+ );
79
+ }
80
+ const initiatives = [];
81
+ const errors = [];
82
+ for (const name of dirs) {
83
+ const journal = join(stateDir, name, 'journal.jsonl');
84
+ if (!existsSync(journal)) continue;
85
+ try {
86
+ const state = fold(readJournal(journal));
87
+ // `readJournal` does NOT throw on unparseable content — it returns zero
88
+ // events and counts the damage — so the catch below never sees a corrupt
89
+ // journal. Without this guard a damaged file renders as an initiative
90
+ // with nothing wrong, which is the one output this board must never
91
+ // produce. Same condition the CLI and the refresh probe refuse on.
92
+ if (state.total === 0 && (state.corruptLines + state.malformed > 0 || state.truncatedTail)) {
93
+ const damage = [
94
+ state.corruptLines > 0 ? `${state.corruptLines} corrupt line(s)` : null,
95
+ state.malformed > 0 ? `${state.malformed} non-object line(s)` : null,
96
+ state.truncatedTail ? 'a truncated final line' : null,
97
+ ].filter(Boolean).join(', ');
98
+ errors.push({ name, error: `0 readable events and ${damage} — the journal is damaged` });
99
+ continue;
100
+ }
101
+ initiatives.push({ name, state, board: boardOf(state) });
102
+ } catch (err) {
103
+ errors.push({ name, error: String(err?.message ?? err) });
104
+ }
105
+ }
106
+ return { initiatives, errors };
107
+ }
108
+
109
+ /** Pure merge of per-initiative boards into the one payload. */
110
+ export function crossBoard({ initiatives, errors }) {
111
+ const asks = [];
112
+ const agents = [];
113
+ const paused = [];
114
+ const lanes = Object.fromEntries(LANES.map((lane) => [lane, []]));
115
+ let merged = 0;
116
+ let tickets = 0;
117
+ let asOf = null;
118
+
119
+ for (const { name, state, board } of initiatives) {
120
+ merged += state.merged;
121
+ tickets += state.ticketList.length;
122
+ if (state.lastTs !== null && (asOf === null || state.lastTs > asOf)) asOf = state.lastTs;
123
+ for (const a of board.asks) asks.push({ ...a, init: name });
124
+ for (const a of board.agents) agents.push({ ...a, init: name });
125
+ if (board.paused !== null) paused.push({ ...board.paused, init: name });
126
+ for (const lane of LANES) {
127
+ for (const card of board.lanes.get(lane)) lanes[lane].push({ ...card, init: name });
128
+ }
129
+ }
130
+ asks.sort((a, b) => String(a.since ?? '').localeCompare(String(b.since ?? '')));
131
+
132
+ return {
133
+ schema: 1,
134
+ as_of: asOf,
135
+ totals: {
136
+ initiatives: initiatives.length,
137
+ agents: agents.length,
138
+ merged,
139
+ tickets,
140
+ percent: tickets === 0 ? 0 : Math.round((merged / tickets) * 100),
141
+ },
142
+ paused,
143
+ asks,
144
+ agents,
145
+ lanes,
146
+ errors,
147
+ };
148
+ }
149
+
150
+ export function crossJson(payload) {
151
+ return jsonEscapeInvisible(JSON.stringify(payload, null, 2)) + '\n';
152
+ }
153
+
154
+ export function renderCrossMd(payload) {
155
+ const parts = [GENERATED_MD_HEADER, '# BOARD — all initiatives\n\n'];
156
+ const t = payload.totals;
157
+ parts.push(
158
+ `**${t.agents} agent(s) running across ${t.initiatives} initiative(s) · ` +
159
+ `${t.merged}/${t.tickets} tickets merged (${t.percent}%) · as of ${inline(payload.as_of)}**\n`,
160
+ );
161
+ for (const p of payload.paused) {
162
+ parts.push(`\n**PAUSED** — ${inline(p.init)}: gate ${inline(p.kind)} (${inline(p.result)}) since ${inline(p.since)}\n`);
163
+ }
164
+ for (const e of payload.errors) {
165
+ parts.push(`\n**UNREADABLE** — ${inline(e.name)}: ${inline(e.error)}\n`);
166
+ }
167
+
168
+ parts.push('\n## Waiting on you\n\n');
169
+ if (payload.asks.length === 0) parts.push('_none — the agents have what they need_\n');
170
+ for (const a of payload.asks) {
171
+ parts.push(`- **${inline(a.question ?? `(no question recorded — gate ${a.kind})`)}**\n`);
172
+ if (a.recommendation != null) parts.push(` - recommendation: ${inline(a.recommendation)}\n`);
173
+ if (a.default != null) parts.push(` - default: ${inline(a.default)}\n`);
174
+ parts.push(` - ${inline(a.init)}${a.ticket != null ? ` · \`${inline(a.ticket)}\`` : ''} · since ${inline(a.since)}\n`);
175
+ }
176
+
177
+ parts.push('\n## Agents\n\n');
178
+ if (payload.agents.length === 0) parts.push('_none running_\n');
179
+ for (const a of payload.agents) {
180
+ parts.push(
181
+ `- \`${inline(a.agent)}\` (${inline(a.role)}) — ${inline(a.init)}` +
182
+ `${a.ticket != null ? ` · \`${inline(a.ticket)}\`` : ''} · ${inline(a.state)}` +
183
+ `${a.detail != null ? ` — ${inline(a.detail)}` : ''} · last signal ${inline(a.last_signal)}\n`,
184
+ );
185
+ }
186
+
187
+ for (const lane of LANES) {
188
+ const cards = payload.lanes[lane];
189
+ parts.push(`\n## ${lane} (${cards.length})\n\n`);
190
+ if (cards.length === 0) {
191
+ parts.push('_none_\n');
192
+ continue;
193
+ }
194
+ for (const c of cards) {
195
+ parts.push(
196
+ `- \`${inline(c.id)}\`${c.title ? ` — ${inline(c.title)}` : ''} _(${inline(c.init)})_` +
197
+ `${c.agents.length > 0 ? ` — ${inline(c.agents)}` : ''}` +
198
+ `${c.annotation ? ` — ${inline(c.annotation)}` : ''}\n`,
199
+ );
200
+ }
201
+ }
202
+ return parts.join('');
203
+ }
204
+
205
+ export function renderAll(tyranDir) {
206
+ const payload = crossBoard(readInitiativeBoards(tyranDir));
207
+ const json = crossJson(payload);
208
+ return {
209
+ payload,
210
+ files: {
211
+ [BOARD_FILE]: renderCrossMd(payload),
212
+ [BOARD_JSON_FILE]: json,
213
+ [BOARD_HTML_FILE]: renderBoardHtml(json.trimEnd()),
214
+ },
215
+ };
216
+ }
217
+
218
+ // ------------------------------------------------------------------- CLI
219
+
220
+ const BOOLEAN_FLAGS = ['check', 'serve'];
221
+ const VALUE_FLAGS = ['dir', 'port'];
222
+
223
+ function parseArgs(argv) {
224
+ const flags = { dir: '.tyran', port: 4173, check: false, serve: false };
225
+ for (let i = 0; i < argv.length; i += 1) {
226
+ const arg = argv[i];
227
+ if (!arg.startsWith('--')) throw new UsageError(`unexpected argument "${arg}"`);
228
+ const name = arg.slice(2);
229
+ if (BOOLEAN_FLAGS.includes(name)) flags[name] = true;
230
+ else if (VALUE_FLAGS.includes(name)) {
231
+ const value = argv[i + 1];
232
+ if (value === undefined) throw new UsageError(`flag --${name} needs a value`);
233
+ flags[name] = name === 'port' ? Number(value) : value;
234
+ i += 1;
235
+ } else throw new UsageError(`unknown flag --${name}`);
236
+ }
237
+ if (!Number.isInteger(flags.port) || flags.port <= 0 || flags.port > 65535) {
238
+ throw new UsageError('--port must be an integer in (0, 65535]');
239
+ }
240
+ return flags;
241
+ }
242
+
243
+ function main() {
244
+ let flags;
245
+ try {
246
+ flags = parseArgs(process.argv.slice(2));
247
+ } catch (err) {
248
+ if (!(err instanceof UsageError)) throw err;
249
+ console.error(`board: ${err.message}`);
250
+ console.error('usage: board.mjs [--dir <.tyran>] [--check] [--serve [--port <n>]]');
251
+ process.exit(2);
252
+ }
253
+ const dir = resolve(flags.dir);
254
+ if (!existsSync(dir)) {
255
+ console.error(`board: no such directory ${dir}`);
256
+ process.exit(2);
257
+ }
258
+ const outDir = join(dir, 'state');
259
+
260
+ if (flags.serve) {
261
+ // Read-only, loopback-only, re-rendered per request so it is always
262
+ // fresh. No filesystem path is ever derived from the URL.
263
+ const server = createServer((req, res) => {
264
+ try {
265
+ // Binding to loopback is not enough on its own: any web page the
266
+ // operator visits can resolve its own hostname to 127.0.0.1 and read
267
+ // this board — which carries journal content from foreign
268
+ // repositories — straight out of the browser (DNS rebinding). A
269
+ // browser cannot forge the Host header, so pinning it to the literal
270
+ // loopback names closes that path.
271
+ const host = String(req.headers.host ?? '').replace(/:\d+$/, '');
272
+ if (host !== '127.0.0.1' && host !== 'localhost' && host !== '[::1]') {
273
+ res.writeHead(403, { 'content-type': 'text/plain' });
274
+ res.end('forbidden: this board answers to 127.0.0.1 only\n');
275
+ return;
276
+ }
277
+ const { files } = renderAll(dir);
278
+ if (req.url === '/' || req.url === '/index.html') {
279
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
280
+ res.end(files[BOARD_HTML_FILE]);
281
+ } else if (req.url === '/board.json') {
282
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
283
+ res.end(files[BOARD_JSON_FILE]);
284
+ } else {
285
+ res.writeHead(404, { 'content-type': 'text/plain' });
286
+ res.end('not found\n');
287
+ }
288
+ } catch (err) {
289
+ res.writeHead(500, { 'content-type': 'text/plain' });
290
+ res.end(`board render failed: ${String(err?.message ?? err)}\n`);
291
+ }
292
+ });
293
+ // A busy port is an ordinary operator mistake, not a crash worth a stack
294
+ // trace over.
295
+ server.on('error', (err) => {
296
+ console.error(
297
+ err?.code === 'EADDRINUSE'
298
+ ? `board: port ${flags.port} is already in use — pass --port <n> for another`
299
+ : `board: could not serve: ${String(err?.message ?? err)}`,
300
+ );
301
+ process.exitCode = 2;
302
+ });
303
+ server.listen(flags.port, '127.0.0.1', () => {
304
+ console.log(`board: serving http://127.0.0.1:${flags.port}/ (read-only; Ctrl-C to stop)`);
305
+ });
306
+ return;
307
+ }
308
+
309
+ let rendered;
310
+ try {
311
+ rendered = renderAll(dir);
312
+ } catch (err) {
313
+ console.error(`board: ${err.message}`);
314
+ process.exit(2);
315
+ }
316
+
317
+ if (flags.check) {
318
+ let drift = 0;
319
+ for (const [name, content] of Object.entries(rendered.files)) {
320
+ const verdict = checkFile(join(outDir, name), content);
321
+ if (!verdict.ok) {
322
+ drift++;
323
+ console.error(`board: drift: ${join(outDir, name)} — ${verdict.reason}`);
324
+ }
325
+ }
326
+ if (drift > 0) {
327
+ console.error(`board: regenerate with: node scripts/board.mjs --dir ${dir}`);
328
+ process.exit(1);
329
+ }
330
+ console.log(`board: projections up to date (3 files in ${outDir})`);
331
+ return;
332
+ }
333
+
334
+ writeAllAtomic(Object.entries(rendered.files).map(([name, content]) => [join(outDir, name), content]));
335
+ for (const name of Object.keys(rendered.files)) console.log(`wrote ${join(outDir, name)}`);
336
+ }
337
+
338
+ function canonicalPath(path) {
339
+ const abs = resolve(path);
340
+ try {
341
+ return realpathSync(abs);
342
+ } catch {
343
+ return abs;
344
+ }
345
+ }
346
+
347
+ function isMainModule(moduleUrl) {
348
+ if (!process.argv[1]) return false;
349
+ return canonicalPath(process.argv[1]) === canonicalPath(fileURLToPath(moduleUrl));
350
+ }
351
+
352
+ if (isMainModule(import.meta.url)) main();
@@ -45,6 +45,8 @@ import {
45
45
  inline,
46
46
  naturalCompare,
47
47
  renderProjections,
48
+ BOARD_FILE,
49
+ BOARD_JSON_FILE,
48
50
  PROGRESS_FILE,
49
51
  STATE_FILE,
50
52
  } from './project.mjs';
@@ -154,6 +156,7 @@ export const SEVERITY_BY_CODE = Object.freeze(
154
156
  // spawns
155
157
  'spawn-open': 'info',
156
158
  'spawn-stale': 'warning',
159
+ 'spawn-blocked': 'warning',
157
160
  'spawn-duplicate': 'warning',
158
161
  'spawn-orphan-report': 'warning',
159
162
  'agent-name-unusable': 'warning',
@@ -169,6 +172,7 @@ export const SEVERITY_BY_CODE = Object.freeze(
169
172
  'projection-blocked': 'warning',
170
173
  'projection-failed': 'error',
171
174
  'projection-unreadable': 'error',
175
+ 'board-absent': 'info',
172
176
  // configuration
173
177
  'config-missing': 'info',
174
178
  'config-invalid': 'error',
@@ -674,14 +678,50 @@ function closeSpawnHint(journalPath, init, agent) {
674
678
  : `node scripts/journal.mjs close-spawn ${sq(journalPath)} ${sq(slug)} ${sq(agent)} --reason "<why>"`;
675
679
  }
676
680
 
681
+ /** How long a self-reported `blocked` may stand before it is a finding. */
682
+ export const DEFAULT_BLOCKED_HOURS = 1;
683
+
684
+ /** The latest `progress` signal per agent, from the raw events. */
685
+ function lastSignals(events) {
686
+ const signals = new Map();
687
+ for (const e of events) {
688
+ if (e?.ev === 'progress' && typeof e?.data?.agent === 'string') {
689
+ signals.set(e.data.agent, { state: e.data.state ?? null, detail: e.data.detail ?? null, ts: e.ts ?? null });
690
+ }
691
+ }
692
+ return signals;
693
+ }
694
+
677
695
  function spawnFindings(journalPath, at, dirName, events, reference, staleHours) {
678
696
  const findings = [];
679
697
  const { open } = pairSpawns(events);
698
+ const signals = lastSignals(events);
680
699
  for (const agent of sortedNames(open.keys())) {
681
700
  for (const spawn of open.get(agent)) {
682
701
  const age = reference === null ? null : hoursBetween(spawn.ts, reference);
683
702
  const where = `${show(spawn.data.ticket ?? 'no ticket')}, role ${show(spawn.data.role)}`;
684
- if (age !== null && age >= staleHours) {
703
+ // `lastSignals` is keyed by agent NAME, and ADR-18 permits a name to be
704
+ // re-spawned once its previous spawn is closed — so the latest signal
705
+ // under this name may belong to an incarnation that has already
706
+ // reported, whose blockage the report cleared. Only a signal emitted
707
+ // during THIS spawn describes the agent running now; a pair that cannot
708
+ // be ordered (a hand-edited timestamp) is not evidence either.
709
+ const latest = signals.get(agent) ?? null;
710
+ const sinceSpawn = latest === null ? null : hoursBetween(spawn.ts, latest.ts);
711
+ const signal = sinceSpawn !== null && sinceSpawn >= 0 ? latest : null;
712
+ const blockedHours =
713
+ signal?.state === 'blocked' && reference !== null ? hoursBetween(signal.ts, reference) : null;
714
+ if (blockedHours !== null && blockedHours >= DEFAULT_BLOCKED_HOURS) {
715
+ findings.push(
716
+ finding(
717
+ 'spawn-blocked',
718
+ at,
719
+ `agent "${show(agent)}" reported itself BLOCKED ${blockedHours.toFixed(1)} h of journal time ago ` +
720
+ `(${show(signal.detail ?? 'no detail')}) and nothing has cleared it. ${where}`,
721
+ closeSpawnHint(journalPath, spawn.init ?? dirName, agent),
722
+ ),
723
+ );
724
+ } else if (age !== null && age >= staleHours) {
685
725
  findings.push(
686
726
  finding(
687
727
  'spawn-stale',
@@ -697,7 +737,9 @@ function spawnFindings(journalPath, at, dirName, events, reference, staleHours)
697
737
  finding(
698
738
  'spawn-open',
699
739
  at,
700
- `agent "${show(agent)}" is still working (spawned ${show(spawn.ts)}). ${where}`,
740
+ `agent "${show(agent)}" is still working (spawned ${show(spawn.ts)})` +
741
+ (signal ? ` — last signal ${show(signal.state)} at ${show(signal.ts)}` : '') +
742
+ `. ${where}`,
701
743
  ),
702
744
  );
703
745
  }
@@ -864,6 +906,41 @@ function projectionFindings(journalPath, dir, at, read) {
864
906
  ),
865
907
  );
866
908
  }
909
+ // The board pair rides the same projection contract, with its own absent
910
+ // code: every install older than the board feature has neither file, and
911
+ // that must stay info — a check that fails on upgrade day gets deleted.
912
+ const boardNames = [BOARD_FILE, BOARD_JSON_FILE];
913
+ const boardPresent = boardNames.filter((name) => existsSync(join(dir, name)));
914
+ if (boardPresent.length === 0) {
915
+ findings.push(
916
+ finding(
917
+ 'board-absent',
918
+ show(dir),
919
+ `no ${BOARD_FILE} / ${BOARD_JSON_FILE} yet — regenerating the projections creates them`,
920
+ regenerate,
921
+ ),
922
+ );
923
+ return findings;
924
+ }
925
+ for (const name of boardNames) {
926
+ const path = join(dir, name);
927
+ if (!boardPresent.includes(name)) {
928
+ findings.push(
929
+ finding('projection-missing', show(path), `${name} is missing while ${boardPresent[0]} exists — a projection run stopped half way`, regenerate),
930
+ );
931
+ continue;
932
+ }
933
+ let result;
934
+ try {
935
+ result = checkFile(path, files[name]);
936
+ } catch (err) {
937
+ findings.push(finding('projection-unreadable', show(path), `cannot read the projection (${errText(err)})`));
938
+ continue;
939
+ }
940
+ if (!result.ok) {
941
+ findings.push(finding('projection-drift', show(path), `${name} does not match the journal (${result.reason})`, regenerate));
942
+ }
943
+ }
867
944
  return findings;
868
945
  }
869
946
 
@@ -1037,6 +1114,9 @@ export function trackedLeaseFiles(run, tyranDirName = '.tyran') {
1037
1114
  }
1038
1115
 
1039
1116
  /** The repo-global overnight runtime files that legally live at state/ level. */
1117
+ /** The cross-initiative board artefacts board.mjs writes at state/ level. */
1118
+ export const CROSS_BOARD_FILES = Object.freeze(['BOARD.md', 'board.json', 'board.html']);
1119
+
1040
1120
  export const OVERNIGHT_RUNTIME_FILES = Object.freeze([
1041
1121
  'paused-until.json',
1042
1122
  'resume.json',
@@ -1265,6 +1345,7 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1265
1345
  // live at the state/ level by design (repo-global, machine-local,
1266
1346
  // gitignored) and are checked by overnightFindings instead.
1267
1347
  if (OVERNIGHT_RUNTIME_FILES.includes(name)) continue;
1348
+ if (CROSS_BOARD_FILES.includes(name)) continue; // generated by board.mjs at this level, by design
1268
1349
  findings.push(
1269
1350
  finding(
1270
1351
  'state-stray-file',
@@ -40,12 +40,15 @@ export const EVENT_TYPES = Object.freeze([
40
40
  'init.created',
41
41
  'plan.accepted',
42
42
  'ticket.created',
43
+ 'ticket.status',
43
44
  'spawn',
44
45
  'report',
46
+ 'progress',
45
47
  'gate',
46
48
  'review',
47
49
  'merge',
48
50
  'decision',
51
+ 'finding',
49
52
  'lease.acquired',
50
53
  'lease.released',
51
54
  'checkpoint',
@@ -58,17 +61,20 @@ export const EVENT_TYPES = Object.freeze([
58
61
  * prefix to issue it under. `ticket.created` is deliberately absent: a ticket
59
62
  * id comes from the plan, which numbers its own stories.
60
63
  */
61
- export const ID_ISSUED_FOR = Object.freeze(Object.assign(Object.create(null), { decision: 'D' }));
64
+ export const ID_ISSUED_FOR = Object.freeze(Object.assign(Object.create(null), { decision: 'D', finding: 'F' }));
62
65
 
63
66
  /** Per-type required keys inside `data` (data may always carry extra keys). */
64
67
  export const DATA_REQUIRED = Object.freeze({
65
68
  'ticket.created': ['id'],
69
+ 'ticket.status': ['ticket', 'column'],
66
70
  spawn: ['agent', 'role'],
67
71
  report: ['agent', 'verdict'],
72
+ progress: ['agent', 'state'],
68
73
  gate: ['kind', 'result'],
69
74
  review: ['ticket', 'verdict', 'by'],
70
75
  merge: ['ticket', 'sha'],
71
76
  decision: ['id', 'text'],
77
+ finding: ['area', 'claim'],
72
78
  'lease.acquired': ['resource', 'holder'],
73
79
  'lease.released': ['resource', 'holder'],
74
80
  checkpoint: ['phase', 'next_steps'],
@@ -76,6 +82,30 @@ export const DATA_REQUIRED = Object.freeze({
76
82
  error: ['class'],
77
83
  });
78
84
 
85
+ /**
86
+ * Closed VALUE sets inside `data`, for the same reason the event set is
87
+ * closed: an unknown value must be a loud rejection at append time, not a
88
+ * surprise in a projection. Hard errors are safe here because both types are
89
+ * new — no legacy journal can retroactively fail `validate`.
90
+ *
91
+ * `ticket.status.column` is deliberately NARROW: only the lanes no lifecycle
92
+ * event can ever derive. Anything broader would be a second source of truth
93
+ * against the derived board (`done` is what `merge` means; an override saying
94
+ * so would let the two disagree).
95
+ */
96
+ export const DATA_ENUMS = Object.freeze({
97
+ progress: Object.freeze({ state: Object.freeze(['started', 'working', 'blocked', 'unblocked']) }),
98
+ 'ticket.status': Object.freeze({ column: Object.freeze(['blocked', 'waiting-operator', 'parked']) }),
99
+ });
100
+
101
+ /**
102
+ * Free-text keys with a size ceiling, in codepoints. REJECTED at append,
103
+ * never truncated — the journal does not silently shorten anything. Long
104
+ * material belongs in NOTES.md with a reference here. `validateJournal`
105
+ * reports historical oversizes as warnings only (no retroactive errors).
106
+ */
107
+ export const CAPPED_DATA_KEYS = Object.freeze({ detail: 2000, claim: 2000, proof: 2000 });
108
+
79
109
  /**
80
110
  * A journal-derived value on its way into a HUMAN-READABLE MESSAGE.
81
111
  *
@@ -130,10 +160,37 @@ export function validateEvent(event) {
130
160
  errors.push(`data.id must be a string for ev "${q(event.ev)}" (got ${typeof event.data.id})`);
131
161
  }
132
162
  }
163
+ const enums = DATA_ENUMS[event.ev];
164
+ if (enums) {
165
+ for (const [key, allowed] of Object.entries(enums)) {
166
+ if (key in event.data && !allowed.includes(event.data[key])) {
167
+ // Name the whole set, same as the closed event set above: the agent
168
+ // recovering from this error has no other source of truth.
169
+ errors.push(
170
+ `data.${q(key)} "${q(event.data[key])}" is not valid for ev "${q(event.ev)}" — valid: ${allowed.join(', ')}`,
171
+ );
172
+ }
173
+ }
174
+ }
133
175
  }
134
176
  return errors;
135
177
  }
136
178
 
179
+ /**
180
+ * The oversize problem of one capped data key, or null. Codepoints, not
181
+ * UTF-16 units, same as every other length rule in this repo.
182
+ */
183
+ export function cappedKeyProblem(data) {
184
+ if (data === null || typeof data !== 'object') return null;
185
+ for (const [key, cap] of Object.entries(CAPPED_DATA_KEYS)) {
186
+ const value = data[key];
187
+ if (typeof value === 'string' && Array.from(value).length > cap) {
188
+ return `data.${key} is ${Array.from(value).length} codepoints (cap ${cap}) — put the full text in NOTES.md and reference it here`;
189
+ }
190
+ }
191
+ return null;
192
+ }
193
+
137
194
  // -------------------------------------------------- spawn ↔ report pairing
138
195
 
139
196
  /**
@@ -410,7 +467,10 @@ function appendUnderLock(file, event, preread = null) {
410
467
  if (errors.length > 0) {
411
468
  throw new Error('invalid event: ' + errors.join('; '));
412
469
  }
413
- if (stamped.ev === 'spawn' || stamped.ev === 'report') {
470
+ if (stamped.ev === 'spawn' || stamped.ev === 'report' || stamped.ev === 'progress') {
471
+ // `progress` joins the guard because data.agent is how a signal attaches
472
+ // to the agent row in the fold — a non-canonical name would silently
473
+ // fail to attach rather than error anywhere.
414
474
  const problem = agentNameProblem(stamped.data.agent);
415
475
  if (problem) {
416
476
  throw new Error(
@@ -419,6 +479,10 @@ function appendUnderLock(file, event, preread = null) {
419
479
  );
420
480
  }
421
481
  }
482
+ {
483
+ const oversize = cappedKeyProblem(stamped.data);
484
+ if (oversize) throw new Error(`invalid event: ${oversize}`);
485
+ }
422
486
  if (stamped.ev === 'spawn') {
423
487
  // ADR-18: refuse a second OPEN spawn for one agent name. Same lock as the
424
488
  // write, same read as the clamp — a check outside the lock would let two
@@ -556,6 +620,13 @@ export function validateJournal(file) {
556
620
  for (const [raw, problem] of badNames) {
557
621
  warnings.push(`unusable data.agent ${q(raw)}: ${problem} — excluded from spawn↔report pairing`);
558
622
  }
623
+ // Historical oversizes are warnings, never errors: the cap is enforced at
624
+ // append time, and a hand-edited file must stay visible without turning a
625
+ // whole journal's `validate` red retroactively.
626
+ events.forEach((e, i) => {
627
+ const oversize = cappedKeyProblem(e?.data);
628
+ if (oversize) warnings.push(`event ${i + 1}: ${oversize}`);
629
+ });
559
630
  return { ok: errors.length === 0, errors, warnings, count: events.length, truncatedTail };
560
631
  }
561
632