@jjanczur/tyran 0.1.11 → 0.1.13

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';
@@ -170,6 +172,7 @@ export const SEVERITY_BY_CODE = Object.freeze(
170
172
  'projection-blocked': 'warning',
171
173
  'projection-failed': 'error',
172
174
  'projection-unreadable': 'error',
175
+ 'board-absent': 'info',
173
176
  // configuration
174
177
  'config-missing': 'info',
175
178
  'config-invalid': 'error',
@@ -903,6 +906,41 @@ function projectionFindings(journalPath, dir, at, read) {
903
906
  ),
904
907
  );
905
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
+ }
906
944
  return findings;
907
945
  }
908
946
 
@@ -1076,6 +1114,9 @@ export function trackedLeaseFiles(run, tyranDirName = '.tyran') {
1076
1114
  }
1077
1115
 
1078
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
+
1079
1120
  export const OVERNIGHT_RUNTIME_FILES = Object.freeze([
1080
1121
  'paused-until.json',
1081
1122
  'resume.json',
@@ -1304,6 +1345,7 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1304
1345
  // live at the state/ level by design (repo-global, machine-local,
1305
1346
  // gitignored) and are checked by overnightFindings instead.
1306
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
1307
1349
  findings.push(
1308
1350
  finding(
1309
1351
  'state-stray-file',
@@ -122,6 +122,14 @@ export const CAPPED_DATA_KEYS = Object.freeze({ detail: 2000, claim: 2000, proof
122
122
  */
123
123
  const q = (value) => escapeInvisible(String(value));
124
124
 
125
+ /**
126
+ * A `data` payload of the shape the envelope requires. Arrays are excluded on
127
+ * purpose: they are objects to `typeof`, they accept string properties, and
128
+ * anything that ADDS a key to one would turn a rejected event into a written
129
+ * one of a shape the caller never wrote.
130
+ */
131
+ const isDataObject = (data) => typeof data === 'object' && data !== null && !Array.isArray(data);
132
+
125
133
  /** Validate a single event object. Returns [] when valid, else error strings. */
126
134
  export function validateEvent(event) {
127
135
  const errors = [];
@@ -143,7 +151,7 @@ export function validateEvent(event) {
143
151
  if (typeof event.actor !== 'string' || event.actor.length === 0) {
144
152
  errors.push('actor must be a non-empty string');
145
153
  }
146
- if (typeof event.data !== 'object' || event.data === null || Array.isArray(event.data)) {
154
+ if (!isDataObject(event.data)) {
147
155
  errors.push('data must be a JSON object (may be empty)');
148
156
  } else if (DATA_REQUIRED[event.ev]) {
149
157
  for (const key of DATA_REQUIRED[event.ev]) {
@@ -463,6 +471,31 @@ function appendUnderLock(file, event, preread = null) {
463
471
  if (lastTs && Date.parse(ts) < Date.parse(lastTs)) ts = lastTs;
464
472
  }
465
473
  const stamped = { ...event, ts };
474
+ // An id the caller omitted is ISSUED, not demanded — and issued HERE, from
475
+ // the same snapshot this write is about to extend. Issuing one is
476
+ // read-compute-write, so anywhere outside the lock every concurrent writer
477
+ // reads the same journal, computes the same "next" number, and then queues up
478
+ // to write it: measured over seven runs, six concurrent `decision` appends
479
+ // against one journal issued between 1 and 4 distinct ids for 6 events.
480
+ // Nothing detects that later — history is append-only, so "see D-2" stays
481
+ // ambiguous forever.
482
+ //
483
+ // `skills/run/SKILL.md` is emphatic that IDs never come from memory, because
484
+ // after a compaction memory hands out the same number twice — and `append`
485
+ // once REJECTED a missing `data.id`, leaving the conductor to remember a
486
+ // separate `next-id` call. Measured in the field: 12 decision IDs
487
+ // hand-assigned from memory in one initiative, which is the exact failure the
488
+ // rule names, with nothing objecting. A rule in prose loses to a mechanism
489
+ // that makes the mistake impossible.
490
+ //
491
+ // An explicit id still wins — but `"id":""` is not explicit: a conductor
492
+ // recovering from next-id's usage error supplied exactly that, three times,
493
+ // and the ledger kept three permanently blank ids nothing can reference.
494
+ const issuePrefix = ID_ISSUED_FOR[stamped.ev];
495
+ if (issuePrefix !== undefined && isDataObject(stamped.data) && (stamped.data.id === undefined || stamped.data.id === '')) {
496
+ // a fresh object: the `data` the caller passed in stays the caller's
497
+ stamped.data = { ...stamped.data, id: nextIdFrom(read().events, issuePrefix) };
498
+ }
466
499
  const errors = validateEvent(stamped);
467
500
  if (errors.length > 0) {
468
501
  throw new Error('invalid event: ' + errors.join('; '));
@@ -506,6 +539,9 @@ function appendUnderLock(file, event, preread = null) {
506
539
  *
507
540
  * `spawn` additionally must not duplicate an agent name that is still open
508
541
  * (ADR-18) — see `duplicateSpawnMessage` for how to get unstuck.
542
+ *
543
+ * Returns the event as written, including any `data.id` issued for it: the
544
+ * CLI prints that, and it is the only place the issued id is reported.
509
545
  */
510
546
  export function append(file, event) {
511
547
  mkdirSync(dirname(resolve(file)), { recursive: true });
@@ -631,14 +667,15 @@ export function validateJournal(file) {
631
667
  }
632
668
 
633
669
  /**
634
- * Next free ID for a prefix, derived from the journal — never from memory.
635
- * Scans data.id fields shaped `<PREFIX>-<number>` and returns max+1.
670
+ * Next free ID for a prefix, over events already read. Separate from `nextId`
671
+ * only so the locked append path can issue an id from the snapshot it is
672
+ * holding: re-reading the file there would be a second full read on every
673
+ * append, which a long journal pays for on every event.
636
674
  */
637
- export function nextId(file, prefix) {
675
+ function nextIdFrom(events, prefix) {
638
676
  if (!/^[A-Za-z][A-Za-z0-9]*$/.test(prefix)) {
639
677
  throw new Error(`invalid id prefix "${prefix}" — use letters/digits, starting with a letter`);
640
678
  }
641
- const { events } = readJournal(file);
642
679
  let max = 0;
643
680
  const re = new RegExp(`^${prefix}-(\\d+)$`);
644
681
  for (const e of events) {
@@ -648,6 +685,19 @@ export function nextId(file, prefix) {
648
685
  return `${prefix}-${max + 1}`;
649
686
  }
650
687
 
688
+ /**
689
+ * Next free ID for a prefix, derived from the journal — never from memory.
690
+ * Scans data.id fields shaped `<PREFIX>-<number>` and returns max+1.
691
+ *
692
+ * A PREVIEW, not a reservation: nothing is written and no lock is held, so an
693
+ * id read here and appended later collides with any writer that appended in
694
+ * between. `append` issues ids under its own write lock; a caller that can
695
+ * let it do so has no window at all.
696
+ */
697
+ export function nextId(file, prefix) {
698
+ return nextIdFrom(readJournal(file).events, prefix);
699
+ }
700
+
651
701
  /** Latest checkpoint + still-open leases — the resume surface. */
652
702
  export function tail(file) {
653
703
  const { events } = readJournal(file);
@@ -744,23 +794,9 @@ function main() {
744
794
  const [file, ev, init] = rest;
745
795
  if (!file || !ev || !init) throw new UsageError();
746
796
  const data = flags.data ? JSON.parse(flags.data) : {};
747
- // An id the caller omitted is ISSUED, not demanded.
748
- //
749
- // `skills/run/SKILL.md` is emphatic that IDs never come from memory,
750
- // because after a compaction memory hands out the same number twice —
751
- // and then `append` REJECTED a missing `data.id` and left the conductor
752
- // to remember a separate `next-id` call. Measured in the field: 12
753
- // decision IDs hand-assigned from memory in one initiative, which is
754
- // the exact failure the rule names, with nothing objecting.
755
- //
756
- // A rule in prose loses to a mechanism that makes the mistake
757
- // impossible. This is that mechanism, and an explicit id still wins —
758
- // but `"id":""` is not explicit: a conductor recovering from next-id's
759
- // usage error supplied exactly that, three times, and the ledger kept
760
- // three permanently blank ids nothing can reference.
761
- if (ID_ISSUED_FOR[ev] !== undefined && (data.id === undefined || data.id === '')) {
762
- data.id = nextId(file, ID_ISSUED_FOR[ev]);
763
- }
797
+ // An omitted id is issued by `append`, inside its write lock, and comes
798
+ // back on the event this prints — issuing one out here would be outside
799
+ // that lock, which is where concurrent writers hand out one id twice.
764
800
  const written = append(file, { ev, init, actor: flags.actor ?? 'conductor', data });
765
801
  console.log(emit(written));
766
802
  return;