@jjanczur/tyran 0.1.13 → 0.1.15

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,896 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * answer — the operator's sitting: one sheet of every open question, one fold
4
+ * back into the journals.
5
+ *
6
+ * An ask is a `gate` whose `kind` IS its id (`Q-<n>`), raised by
7
+ * `journal.mjs ask`. `render` writes every open one across every initiative
8
+ * into `.tyran/state/ANSWERS.md`; the operator types under the `answer:`
9
+ * lines; `apply` folds each answer back as a `decision` + a closing
10
+ * `gate result: answered`, decision first, and re-renders the projections and
11
+ * the board.
12
+ *
13
+ * Three properties this file exists to hold:
14
+ *
15
+ * - **Every value written comes out of the JOURNAL, never out of the sheet.**
16
+ * The sheet is an inbox. A tampered one can change WHICH asks close and
17
+ * WHAT the operator said, and nothing else — it cannot forge a question, a
18
+ * default, a ticket or an id.
19
+ * - **Parsing is all-or-nothing.** One unreadable block and nothing at all is
20
+ * appended. A per-block skip would record eleven answers and silently drop
21
+ * the twelfth, and the operator would never learn which. This is why the
22
+ * heading DETECTOR is wider than the heading GRAMMAR: a heading that lost
23
+ * its space is a refusal with a line number, never context quietly
24
+ * appended to the previous answer.
25
+ * - **Decision before gate.** A crash between the two leaves a visible orphan
26
+ * decision, which is re-appliable; the reverse leaves a closed question
27
+ * whose answer was never written down, which is silent loss.
28
+ * - **One writer per ask.** The re-read that says "this ask is still open"
29
+ * and the two appends share ONE lock, so two `apply` runs on one sheet
30
+ * cannot both close the same question — an append-only ledger keeps both
31
+ * decisions forever.
32
+ *
33
+ * It discovers nothing of its own: initiatives come from `board.mjs`, appends
34
+ * go through `journal.mjs`, re-rendering through `project.mjs` and
35
+ * `board.mjs`, liveness and the resume argv from `overnight.mjs`.
36
+ *
37
+ * `ANSWERS.md` is GENERATED and then HAND-EDITED, so it is deliberately NOT in
38
+ * the byte-exact `--check` set: byte-equality is not a property a file the
39
+ * operator types into can have.
40
+ *
41
+ * CLI:
42
+ * node answer.mjs render [--dir <.tyran>] [--force]
43
+ * node answer.mjs apply [--dir <.tyran>] [--dry-run] [--resume]
44
+ * Exit: 0 ok · 1 nothing is waiting on you · 2 usage, IO, a sheet that did
45
+ * not parse, or a sheet with answers already typed into it
46
+ */
47
+ import { spawn } from 'node:child_process';
48
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmdirSync, statSync } from 'node:fs';
49
+ import { dirname, join, resolve } from 'node:path';
50
+ import { fileURLToPath } from 'node:url';
51
+
52
+ import { readInitiativeBoards, renderAll } from './board.mjs';
53
+ import { append, ASK_KIND_RE, CAPPED_DATA_KEYS, readJournal } from './journal.mjs';
54
+ import { formatCodePoint, invisibleProblem } from './invisible.mjs';
55
+ import { resumeArgv, SESSION_ID_RE } from './overnight.mjs';
56
+ import { inlinePlain, naturalCompare, projectFile, WAITING_RE, writeAllAtomic, writeAtomic } from './project.mjs';
57
+
58
+ /** The sheet, and the session record `apply --resume` reads. Both under
59
+ * `state/`, which is already the AUTO policy class on every install. */
60
+ export const ANSWERS_FILE = 'ANSWERS.md';
61
+ export const CONDUCTOR_FILE = 'conductor.json';
62
+
63
+ /** The answer's ceiling is the journal's, imported rather than restated: a
64
+ * pre-flight that disagreed with `append` would refuse the 9th answer of a
65
+ * sitting after writing the 8th. */
66
+ export const MAX_ANSWER = CAPPED_DATA_KEYS.answer;
67
+
68
+ /** Longest answer excerpt in the report line. */
69
+ const REPORT_EXCERPT = 60;
70
+
71
+ /** The heading's tail on an ask with nothing recorded to fall back to. Part of
72
+ * the grammar, so `render` and `parseSheet` cannot spell it differently. */
73
+ const NO_DEFAULT_SUFFIX = ' · no default recorded';
74
+
75
+ /**
76
+ * The GRAMMAR. `$1` is the ask id (the gate kind), `$2` is the initiative
77
+ * directory — captured to the end of the line rather than to the first space,
78
+ * so a directory named `pay ments` round-trips instead of rendering a sheet
79
+ * `apply` can never accept. Trailing blanks are the editor's, not the
80
+ * operator's.
81
+ */
82
+ export const BLOCK_RE = new RegExp(`^## (Q-\\d+) · (.+?)(?:${NO_DEFAULT_SUFFIX})?[ \\t]*$`);
83
+
84
+ /**
85
+ * The DETECTOR, deliberately wider than the grammar: every line the operator
86
+ * could have MEANT as a heading. `##Q-2 · p`, `### Q-2 · p`, ` ## Q-2 · p` and
87
+ * a tab-indented one are all typos an editor makes; matched here, each is a
88
+ * refusal naming its line, and unmatched each would be ordinary context
89
+ * appended to the PREVIOUS answer — one decision carrying two questions, the
90
+ * second ask still open, exit 0.
91
+ */
92
+ const HEADING_RE = /^(?:## |[ \t]*#{1,6}[ \t]*Q-\d)/;
93
+
94
+ /**
95
+ * An ask's identity across initiatives. Ask ids are minted per journal, so
96
+ * `Q-1` in `payments` and `Q-1` in `docs-site` are two different questions and
97
+ * both must be answerable in one sitting.
98
+ */
99
+ const keyOf = (init, kind) => `${init} :: ${kind}`;
100
+
101
+ const GENERATED_HEADER = `<!-- GENERATED by tyran scripts/answer.mjs — the \`answer:\` lines are the only thing you edit.
102
+ When you are done: node scripts/answer.mjs apply --dir .tyran
103
+
104
+ blank accept the recorded default, verbatim, as the decision
105
+ - leave it open; ask me again next time
106
+ text your answer, in your own words — everything down to the next \`## \` is it
107
+
108
+ Questions with NO recorded default come first: those are the only ones where
109
+ saying nothing has no safe outcome. The question, the default, the ticket and
110
+ the id are read back out of the journal when you apply, so nothing you type
111
+ can change what was asked. One line is structure rather than content: the
112
+ \`## Q-<n> · <initiative>\` heading PICKS which question your answer closes —
113
+ leave it alone, or your answer is filed against a different ask. -->
114
+ `;
115
+
116
+ class UsageError extends Error {}
117
+ class IOError extends Error {}
118
+
119
+ // ------------------------------------------------------------- discovery
120
+
121
+ /**
122
+ * Every open ask, across every initiative, with the journal that owns it.
123
+ *
124
+ * The queue is `boardOf`'s, not a second derivation: an ask is an open gate
125
+ * whose result matches the board's waiting rule, and this file must close
126
+ * exactly what the board shows.
127
+ */
128
+ export function openAsks(tyranDir) {
129
+ const { initiatives, errors } = readInitiativeBoards(tyranDir);
130
+ const asks = [];
131
+ for (const { name, journal, board } of initiatives) {
132
+ for (const ask of board.asks) asks.push({ ...ask, init: name, journal });
133
+ }
134
+ // `inits` is every initiative that EXISTS, not every one that still has a
135
+ // question open: "payments has no open ask any more" and "there is no
136
+ // payments" send the operator to opposite fixes, and the second sitting on
137
+ // an already-applied sheet hits exactly that fork.
138
+ return { asks: sortAsks(asks), inits: initiatives.map((i) => i.name), errors };
139
+ }
140
+
141
+ /**
142
+ * No recorded default FIRST — those are the only questions where saying
143
+ * nothing has no safe outcome. Then oldest first: a question that has stood
144
+ * for four days is the one costing an initiative its progress. The last two
145
+ * keys make the order total, so the sheet is stable across renders.
146
+ */
147
+ export function sortAsks(asks) {
148
+ return [...asks].sort(
149
+ (a, b) =>
150
+ Number(a.default != null) - Number(b.default != null) ||
151
+ String(a.since ?? '').localeCompare(String(b.since ?? '')) ||
152
+ naturalCompare(a.init, b.init) ||
153
+ naturalCompare(a.kind, b.kind),
154
+ );
155
+ }
156
+
157
+ // --------------------------------------------------------------- render
158
+
159
+ /**
160
+ * Which open asks this sheet can carry, and why the rest cannot.
161
+ *
162
+ * Two shapes cannot round-trip through the grammar, and rendering either as a
163
+ * block would be worse than not rendering it: parsing is all-or-nothing, so
164
+ * ONE heading the parser refuses makes every other answer in the sitting
165
+ * unappliable, and re-rendering reproduces it forever.
166
+ *
167
+ * - A gate `kind` that is not `Q-<n>`. 0.1.9-0.1.14 raised the
168
+ * waiting-on-operator lane with kinds of the conductor's own choosing, and
169
+ * those journals are still on disk; `journal.mjs append` still accepts one.
170
+ * - An initiative whose directory name does not survive one line of Markdown
171
+ * (a newline or a tab in it, longer than the cell cap, invisibles). The
172
+ * heading is the SELECTOR, and a folded or truncated name selects nothing.
173
+ *
174
+ * Both are listed on the sheet, read-only, with the command that closes them.
175
+ */
176
+ export function partitionAsks(asks) {
177
+ const answerable = [];
178
+ const unanswerable = [];
179
+ for (const a of asks) {
180
+ if (!ASK_KIND_RE.test(String(a.kind ?? ''))) {
181
+ unanswerable.push({ ask: a, why: 'its gate kind is not `Q-<n>`, so no heading can select it' });
182
+ } else if (inlinePlain(a.init) !== a.init || String(a.init).endsWith(NO_DEFAULT_SUFFIX)) {
183
+ unanswerable.push({ ask: a, why: 'the initiative directory name does not survive one line of Markdown' });
184
+ } else {
185
+ answerable.push(a);
186
+ }
187
+ }
188
+ return { answerable, unanswerable };
189
+ }
190
+
191
+ /**
192
+ * The read-only list. ABOVE the blocks, because everything before the first
193
+ * heading is context and nothing here can be swallowed into an answer; and
194
+ * with no `#` on any line, because the heading detector would otherwise read
195
+ * one of these as a block the grammar then refuses.
196
+ */
197
+ function unanswerableNote(unanswerable) {
198
+ if (unanswerable.length === 0) return '';
199
+ const lines = [
200
+ `\n> ${unanswerable.length} open ask(s) cannot be answered here — read-only, listed so the queue is honest.`,
201
+ '> Close each from its own journal: node scripts/journal.mjs append <journal> gate <initiative>',
202
+ "> --data '{\"kind\":\"<kind>\",\"result\":\"answered\",\"answer\":\"<what you decided>\"}'",
203
+ ];
204
+ for (const { ask, why } of unanswerable) {
205
+ lines.push(`> ${inlinePlain(ask.init)} · ${inlinePlain(ask.kind)} — ${why}`);
206
+ lines.push(`> journal: ${inlinePlain(ask.journal ?? '(unknown)')}`);
207
+ lines.push(`> question: ${inlinePlain(ask.question ?? '(no question recorded)')}`);
208
+ }
209
+ return `${lines.join('\n')}\n`;
210
+ }
211
+
212
+ /**
213
+ * The sheet. Every journal-derived value goes through `inlinePlain`, which is
214
+ * the repo's one answer to "is this safe to show a human": it escapes
215
+ * invisibles and folds the value onto ONE line. The folding is load-bearing
216
+ * here and not merely cosmetic — a question carrying a newline plus
217
+ * `## Q-99 · other` would otherwise open a second parseable block inside its
218
+ * own sheet, and an agent would be writing the operator's ballot.
219
+ *
220
+ * Every journal-derived line carries a `- <field>: ` prefix for the same
221
+ * reason: an unprefixed question that itself began `answer:` would hijack its
222
+ * own block's answer line, and a blank answer — "take the recorded default" —
223
+ * would reach the ledger as an operator decision in the question author's
224
+ * words. Question text is agent-supplied, and the ledger is append-only.
225
+ *
226
+ * The initiative goes into the heading RAW, which is safe only because
227
+ * `partitionAsks` has already dropped every name `inlinePlain` would alter:
228
+ * the heading is the selector, so it must carry the directory's real name.
229
+ */
230
+ export function renderSheet(asks) {
231
+ const { answerable, unanswerable } = partitionAsks(asks);
232
+ const parts = [
233
+ GENERATED_HEADER,
234
+ '\n',
235
+ `# ${answerable.length} question${answerable.length === 1 ? '' : 's'} waiting on you\n`,
236
+ unanswerableNote(unanswerable),
237
+ ];
238
+ for (const a of answerable) {
239
+ parts.push(`\n## ${a.kind} · ${a.init}${a.default == null ? NO_DEFAULT_SUFFIX : ''}\n`);
240
+ parts.push(`- question: ${inlinePlain(a.question ?? '(no question recorded)')}\n`);
241
+ if (a.recommendation != null) parts.push(`- recommendation: ${inlinePlain(a.recommendation)}\n`);
242
+ if (a.default != null) parts.push(`- default: ${inlinePlain(a.default)}\n`);
243
+ if (a.ticket != null) parts.push(`- ticket: ${inlinePlain(a.ticket)}\n`);
244
+ parts.push(`- since: ${inlinePlain(a.since)}\n`);
245
+ parts.push('answer:\n');
246
+ }
247
+ return parts.join('');
248
+ }
249
+
250
+ // ---------------------------------------------------------------- parse
251
+
252
+ /** The sheet's lines, one trailing CR dropped. The file is GENERATED and then
253
+ * hand-edited, so its line endings are the operator's editor's: a CRLF sheet
254
+ * must not fail with a codepoint offset nobody can act on. */
255
+ const sheetLines = (text) => String(text).split('\n').map((l) => (l.endsWith('\r') ? l.slice(0, -1) : l));
256
+
257
+ /**
258
+ * The grammar, deliberately dumber than YAML: one heading regex, one
259
+ * `answer:` line, everything else ignored.
260
+ *
261
+ * Returns `{ blocks, errors }`. A non-empty `errors` means NOTHING is
262
+ * appended — the caller must not apply a subset. A line that LOOKS like a
263
+ * heading (`HEADING_RE`) but does not parse (`BLOCK_RE`) is an error rather
264
+ * than ignored context: a mistyped heading is exactly how a sitting would
265
+ * half-apply, and the operator would have no way to see which answer went
266
+ * missing.
267
+ */
268
+ export function parseSheet(text) {
269
+ const lines = sheetLines(text);
270
+ const blocks = [];
271
+ const errors = [];
272
+ const seen = new Map();
273
+ let current = null;
274
+
275
+ const close = () => {
276
+ if (current === null) return;
277
+ if (current.answerLine === null) {
278
+ errors.push(
279
+ `line ${current.line}: block "${current.kind} · ${current.init}" has no \`answer:\` line — ` +
280
+ 'every block needs one, even when the answer is blank',
281
+ );
282
+ } else {
283
+ blocks.push({
284
+ kind: current.kind,
285
+ init: current.init,
286
+ line: current.line,
287
+ answerLine: current.answerLine,
288
+ answer: current.parts.join('\n').trim(),
289
+ });
290
+ }
291
+ current = null;
292
+ };
293
+
294
+ lines.forEach((line, i) => {
295
+ const number = i + 1;
296
+ if (HEADING_RE.test(line)) {
297
+ close();
298
+ const m = BLOCK_RE.exec(line);
299
+ if (m === null) {
300
+ errors.push(
301
+ `line ${number}: heading is not \`## Q-<n> · <initiative>\` — ` +
302
+ 'regenerate the sheet with: node scripts/answer.mjs render',
303
+ );
304
+ return;
305
+ }
306
+ const key = keyOf(m[2], m[1]);
307
+ const first = seen.get(key);
308
+ if (first !== undefined) {
309
+ errors.push(`line ${number}: ${m[1]} · ${m[2]} appears twice (first at line ${first}) — which one is your answer?`);
310
+ return;
311
+ }
312
+ seen.set(key, number);
313
+ current = { kind: m[1], init: m[2], line: number, answerLine: null, parts: [] };
314
+ return;
315
+ }
316
+ if (current === null) return; // everything before the first block is context
317
+ if (current.answerLine === null) {
318
+ if (/^answer:/.test(line)) {
319
+ current.answerLine = number;
320
+ current.parts.push(line.slice('answer:'.length));
321
+ }
322
+ return; // any other line inside a block is context
323
+ }
324
+ current.parts.push(line);
325
+ });
326
+ close();
327
+ return { blocks, errors };
328
+ }
329
+
330
+ /**
331
+ * What one answer means. `-` is the sentinel for "ask me again"; blank takes
332
+ * the recorded default; blank with no default recorded leaves the question
333
+ * open, because there is nothing to record.
334
+ */
335
+ export function classify(answer, ask) {
336
+ if (answer === '-') return { mode: 'open', why: 'you typed "-"' };
337
+ if (answer === '') {
338
+ if (ask.default == null) return { mode: 'open', why: 'blank, and no default is recorded' };
339
+ return { mode: 'default', text: String(ask.default) };
340
+ }
341
+ return { mode: 'answered', text: answer };
342
+ }
343
+
344
+ /**
345
+ * A RECORDED DEFAULT that `append` would refuse. A blank answer writes the
346
+ * default verbatim, so the value this sitting appends is one the sheet never
347
+ * carried: checking only what the operator typed lets a 2500-codepoint default
348
+ * throw BETWEEN the decision and its gate, leaving an orphan decision, the
349
+ * rest of the sheet unprocessed and the projections stale.
350
+ *
351
+ * Only the ceiling, not the invisibility rules `answerProblem` also applies:
352
+ * the default is a JOURNAL value being echoed back verbatim, not sheet text.
353
+ */
354
+ export function defaultProblem(text) {
355
+ const cps = Array.from(text);
356
+ return cps.length > MAX_ANSWER ? `is ${cps.length} codepoints (cap ${MAX_ANSWER})` : null;
357
+ }
358
+
359
+ /** An answer that `append` would refuse, checked BEFORE the first append so a
360
+ * sitting cannot half-apply. LF is fine; bidi and zero-width are not. */
361
+ export function answerProblem(answer) {
362
+ const cps = Array.from(answer);
363
+ if (cps.length > MAX_ANSWER) {
364
+ return `is ${cps.length} codepoints (cap ${MAX_ANSWER}) — shorten it, or put the long form in NOTES.md and reference it`;
365
+ }
366
+ let offset = 0;
367
+ for (const ch of cps) {
368
+ const cp = ch.codePointAt(0);
369
+ const problem = invisibleProblem(cp);
370
+ if (problem !== null) return `carries ${formatCodePoint(cp)} at codepoint offset ${offset} (${problem})`;
371
+ offset += 1;
372
+ }
373
+ return null;
374
+ }
375
+
376
+ // ---------------------------------------------------------------- apply
377
+
378
+ /**
379
+ * The two events one answered ask produces, in the order they must be
380
+ * written. Pure, so the ordering guarantee is testable without a filesystem.
381
+ *
382
+ * `decision.text` carries the `Q-<n>: ` prefix because `STATE.md`'s decisions
383
+ * table has no ask column — without the prefix the decision is unfindable
384
+ * from the question. `answer_mode` records whether the operator typed it or
385
+ * accepted the recorded default: a default accepted is still a decision.
386
+ *
387
+ * `ticket` comes from the ASK, which came from the journal. Nothing here may
388
+ * come from the sheet.
389
+ */
390
+ export function eventsFor(ask, verdict, decisionId = null) {
391
+ const decision = {
392
+ ev: 'decision',
393
+ init: ask.init,
394
+ actor: 'operator',
395
+ data: {
396
+ text: `${ask.kind}: ${verdict.mode === 'default' ? '(default accepted) ' : ''}${verdict.text}`,
397
+ ask: ask.kind,
398
+ ...(ask.ticket != null ? { ticket: String(ask.ticket) } : {}),
399
+ },
400
+ };
401
+ const gate = {
402
+ ev: 'gate',
403
+ init: ask.init,
404
+ actor: 'operator',
405
+ data: {
406
+ kind: ask.kind,
407
+ result: 'answered',
408
+ ...(ask.ticket != null ? { ticket: String(ask.ticket) } : {}),
409
+ answer: verdict.text,
410
+ answer_mode: verdict.mode === 'default' ? 'default' : 'operator',
411
+ decision: decisionId,
412
+ via: ANSWERS_FILE,
413
+ },
414
+ };
415
+ return { decision, gate };
416
+ }
417
+
418
+ /** The sheet's blocks, matched against the journal's open asks. Every
419
+ * mismatch is collected, so one run names every problem at once. */
420
+ function resolveBlocks(blocks, asks, initNames) {
421
+ const index = new Map(asks.map((a) => [keyOf(a.init, a.kind), a]));
422
+ const inits = new Set(initNames);
423
+ const errors = [];
424
+ const resolved = [];
425
+ for (const block of blocks) {
426
+ const ask = index.get(keyOf(block.init, block.kind));
427
+ if (ask === undefined) {
428
+ errors.push(
429
+ inits.has(block.init)
430
+ ? `line ${block.line}: ${block.kind} is not an open ask in "${inlinePlain(block.init)}" — it was answered ` +
431
+ 'or never existed. Re-render the sheet: node scripts/answer.mjs render'
432
+ : `line ${block.line}: "${inlinePlain(block.init)}" is not an initiative with an open ask under .tyran/state/`,
433
+ );
434
+ continue;
435
+ }
436
+ // Classify FIRST: the value this run will write is the verdict's, and for
437
+ // a blank answer that value is the recorded default, which the sheet does
438
+ // not carry. Checking `block.answer` alone passes every blank.
439
+ const verdict = classify(block.answer, ask);
440
+ if (verdict.mode === 'answered') {
441
+ const problem = answerProblem(verdict.text);
442
+ if (problem !== null) {
443
+ errors.push(`line ${block.answerLine}: the answer to ${block.kind} ${problem}`);
444
+ continue;
445
+ }
446
+ } else if (verdict.mode === 'default') {
447
+ const problem = defaultProblem(verdict.text);
448
+ if (problem !== null) {
449
+ errors.push(
450
+ `line ${block.answerLine}: the recorded default for ${block.kind} ${problem} — ` +
451
+ 'a blank answer would write it verbatim, so type a shorter answer of your own instead',
452
+ );
453
+ continue;
454
+ }
455
+ }
456
+ resolved.push({ ask, block, verdict });
457
+ }
458
+ return { resolved, errors };
459
+ }
460
+
461
+ /**
462
+ * The sitting's own cross-process lock, one directory per journal.
463
+ *
464
+ * `append` locks per EVENT, which serializes bytes and nothing else: two
465
+ * `apply` runs on one sheet each read the queue, each see the ask open, and
466
+ * each write a decision and a closing gate — every question answered twice,
467
+ * forever, in a file that cannot be corrected. This lock spans the re-read and
468
+ * both appends, the shape `journal.mjs closeSpawn` already uses.
469
+ *
470
+ * A SEPARATE lock dir from `append`'s on purpose: taking that one here would
471
+ * deadlock against the append it wraps.
472
+ */
473
+ function withSittingLock(journal, fn) {
474
+ const lockDir = `${canonicalPath(journal)}.answer.lock`;
475
+ const deadline = Date.now() + 5000;
476
+ for (;;) {
477
+ try {
478
+ mkdirSync(lockDir, { recursive: false });
479
+ break;
480
+ } catch (err) {
481
+ if (err.code !== 'EEXIST') throw err;
482
+ try {
483
+ // A crashed run leaves the directory behind; 10s is far longer than a
484
+ // sitting's two appends and far shorter than an operator's patience.
485
+ if (Date.now() - statSync(lockDir).mtimeMs > 10_000) {
486
+ rmdirSync(lockDir);
487
+ continue;
488
+ }
489
+ } catch {
490
+ continue; // the lock vanished between checks — retry immediately
491
+ }
492
+ if (Date.now() > deadline) throw new IOError(`another apply is holding ${lockDir}`);
493
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
494
+ }
495
+ }
496
+ try {
497
+ return fn();
498
+ } finally {
499
+ rmdirSync(lockDir);
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Is this ask still open, according to the journal on disk RIGHT NOW?
505
+ *
506
+ * `fold` keys gates by kind with last-write-wins, so the LAST gate carrying
507
+ * the kind is the one the board reads — the same rule, not a second one.
508
+ * Called under `withSittingLock`: the value of this check is entirely in it
509
+ * being inseparable from the append that follows.
510
+ */
511
+ export function askState(journal, kind) {
512
+ let last = null;
513
+ for (const e of readJournal(journal).events) {
514
+ if (e?.ev === 'gate' && String(e?.data?.kind ?? '') === kind) last = e;
515
+ }
516
+ if (last === null) return { open: false, why: 'no gate carrying it is in the journal any more' };
517
+ if (WAITING_RE.test(String(last.data?.result ?? ''))) return { open: true };
518
+ return {
519
+ open: false,
520
+ why: `another run closed it at ${inlinePlain(last.ts)} (result: ${inlinePlain(last.data?.result)})`,
521
+ };
522
+ }
523
+
524
+ /**
525
+ * Fold the sheet back into the journals. Appends nothing when anything at all
526
+ * is wrong, and nothing at all when `dryRun` is set.
527
+ *
528
+ * The queue it matches against is the ANSWERABLE half of the board's: an ask
529
+ * the grammar cannot round-trip is reported, never matched, so one legacy gate
530
+ * cannot make every other initiative's answers unappliable.
531
+ */
532
+ export function applySheet(tyranDir, sheetText, { dryRun = false } = {}) {
533
+ const { asks, inits, errors: readErrors } = openAsks(tyranDir);
534
+ const { answerable, unanswerable } = partitionAsks(asks);
535
+ if (answerable.length === 0) {
536
+ return { ok: false, empty: true, errors: [], results: [], unanswerable, readErrors };
537
+ }
538
+ const base = { results: [], open: answerable.length, unanswerable, readErrors };
539
+
540
+ const parsed = parseSheet(sheetText);
541
+ if (parsed.blocks.length === 0 && parsed.errors.length === 0) {
542
+ return {
543
+ ok: false,
544
+ errors: ['no `## Q-<n> · <initiative>` block in the sheet — regenerate it: node scripts/answer.mjs render'],
545
+ ...base,
546
+ };
547
+ }
548
+ const matched = resolveBlocks(parsed.blocks, answerable, inits);
549
+ const errors = [...parsed.errors, ...matched.errors];
550
+ if (errors.length > 0) return { ok: false, errors, ...base };
551
+
552
+ const results = [];
553
+ const touched = new Map();
554
+ for (const { ask, verdict } of matched.resolved) {
555
+ if (verdict.mode === 'open' || dryRun) {
556
+ results.push({ ask, verdict, decision: null });
557
+ continue;
558
+ }
559
+ const outcome = sittingOutcome(ask, verdict);
560
+ if (outcome.skipped !== undefined) {
561
+ results.push({ ask, verdict, decision: null, skipped: outcome.skipped });
562
+ continue;
563
+ }
564
+ touched.set(ask.init, ask.journal);
565
+ results.push({ ask, verdict, decision: outcome.decision });
566
+ }
567
+ return { ok: true, errors: [], ...base, results, touched, dryRun };
568
+ }
569
+
570
+ /** One ask's two appends, or the reason nothing was written for it. A lock
571
+ * this run could not take is reported like any other unwritten ask: the run
572
+ * that holds it is writing the same sitting, and a thrown error here would
573
+ * abandon the asks after this one without saying so. */
574
+ function sittingOutcome(ask, verdict) {
575
+ try {
576
+ return withSittingLock(ask.journal, () => {
577
+ const state = askState(ask.journal, ask.kind);
578
+ if (!state.open) return { skipped: state.why };
579
+ // Decision FIRST, and its id is issued by `append` under the journal's own
580
+ // write lock — computing one out here would be the race that lock closes.
581
+ const written = append(ask.journal, eventsFor(ask, verdict).decision);
582
+ const id = written.data.id;
583
+ append(ask.journal, eventsFor(ask, verdict, id).gate);
584
+ return { decision: id };
585
+ });
586
+ } catch (err) {
587
+ if (!(err instanceof IOError)) throw err;
588
+ return { skipped: err.message };
589
+ }
590
+ }
591
+
592
+ /** Re-render every touched initiative AND the cross board. A board left stale
593
+ * is a board that still shows a question that has been answered. */
594
+ export function reRender(tyranDir, touched) {
595
+ const written = [];
596
+ for (const [name, journal] of [...touched].sort((a, b) => naturalCompare(a[0], b[0]))) {
597
+ const { files } = projectFile(journal);
598
+ const dir = dirname(journal);
599
+ writeAllAtomic(Object.entries(files).map(([file, content]) => [join(dir, file), content]));
600
+ written.push({ dir, files: Object.keys(files), init: name });
601
+ }
602
+ const cross = renderAll(tyranDir);
603
+ const stateDir = join(tyranDir, 'state');
604
+ writeAllAtomic(Object.entries(cross.files).map(([file, content]) => [join(stateDir, file), content]));
605
+ written.push({ dir: stateDir, files: Object.keys(cross.files), init: null });
606
+ return written;
607
+ }
608
+
609
+ // ----------------------------------------------------------- the conductor
610
+
611
+ /** The session record the SessionStart probe writes. Garbage reads as absent. */
612
+ export function readConductor(tyranDir) {
613
+ try {
614
+ const path = join(tyranDir, 'state', CONDUCTOR_FILE);
615
+ if (!existsSync(path) || statSync(path).size > 64 * 1024) return null;
616
+ const doc = JSON.parse(readFileSync(path, 'utf8'));
617
+ return doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : null;
618
+ } catch {
619
+ return null;
620
+ }
621
+ }
622
+
623
+ /**
624
+ * How long a recorded `started_at` still counts as "a session announced itself
625
+ * here". `SessionStart` fires on startup, resume and compact, so a fresh stamp
626
+ * is evidence one is around; a stale one is evidence of NOTHING, since a
627
+ * conductor three days into an initiative has an old stamp.
628
+ */
629
+ export const ANNOUNCED_FRESH_MS = 30 * 60 * 1000;
630
+
631
+ /**
632
+ * What to say — and whether to spawn — about the session that will act on
633
+ * these answers. Two conductors on one journal is a hazard this repo has
634
+ * already paid for once.
635
+ *
636
+ * `conductor.json` carries NO liveness signal (see `recordConductor`): a hook
637
+ * process can only observe its own pid, which is dead before anyone reads it
638
+ * and later names a stranger. So this reads `started_at` in ONE direction —
639
+ * recent enough, and no spawn, because a session announced itself and would
640
+ * pick the answers up on its own. An old stamp licenses nothing by itself:
641
+ * the only thing that authorizes a spawn is the operator typing `--resume`.
642
+ * Absent evidence is UNKNOWN, never "it is dead".
643
+ */
644
+ export function resumePlan(conductor, { resume = false, now = Date.now() } = {}) {
645
+ const sessionId = typeof conductor?.session_id === 'string' ? conductor.session_id : null;
646
+ if (sessionId === null || !SESSION_ID_RE.test(sessionId)) return { action: 'none' };
647
+ const announced = Date.parse(String(conductor?.started_at ?? ''));
648
+ if (Number.isFinite(announced) && now - announced >= 0 && now - announced <= ANNOUNCED_FRESH_MS) {
649
+ return { action: 'announced', sessionId, since: String(conductor.started_at) };
650
+ }
651
+ return { action: resume ? 'spawn' : 'offer', sessionId };
652
+ }
653
+
654
+ // --------------------------------------------------------------- reporting
655
+
656
+ function excerpt(text) {
657
+ const s = inlinePlain(text);
658
+ const cps = Array.from(s);
659
+ return cps.length > REPORT_EXCERPT ? cps.slice(0, REPORT_EXCERPT - 1).join('') + '…' : s;
660
+ }
661
+
662
+ export function reportLines(result) {
663
+ const counts = { answered: 0, default: 0, open: 0, skipped: 0 };
664
+ for (const r of result.results) counts[r.skipped === undefined ? r.verdict.mode : 'skipped'] += 1;
665
+ const lines = [
666
+ `answer: ${result.open} open · ${counts.answered} answered · ${counts.default} defaulted · ${counts.open} left open` +
667
+ // Only when it happened: a counter that is 0 in every ordinary sitting
668
+ // teaches the operator to stop reading the line.
669
+ (counts.skipped > 0 ? ` · ${counts.skipped} already closed` : '') +
670
+ (result.dryRun ? ' (--dry-run: nothing was appended)' : ''),
671
+ '',
672
+ ];
673
+ const width = (pick) => Math.max(0, ...result.results.map((r) => inlinePlain(pick(r)).length));
674
+ const kindWidth = width((r) => r.ask.kind);
675
+ const initWidth = width((r) => r.ask.init);
676
+ for (const r of result.results) {
677
+ const mode = r.skipped === undefined ? r.verdict.mode : 'skipped';
678
+ const verdict =
679
+ mode === 'skipped' ? 'not written' : mode === 'open' ? 'left open ' : mode === 'default' ? 'default ' : 'answered ';
680
+ const tail =
681
+ mode === 'skipped'
682
+ ? `(${r.skipped})`
683
+ : mode === 'open'
684
+ ? `(${r.verdict.why})`
685
+ : `"${excerpt(r.verdict.text)}"${r.decision === null ? '' : ` ${r.decision}`}`;
686
+ lines.push(
687
+ ` ${inlinePlain(r.ask.kind).padEnd(kindWidth)} ${inlinePlain(r.ask.init).padEnd(initWidth)} ${verdict} ${tail}`,
688
+ );
689
+ }
690
+ return lines;
691
+ }
692
+
693
+ function conductorLines(plan, answered) {
694
+ if (plan.action === 'announced') {
695
+ return [
696
+ `a conductor session announced itself at ${inlinePlain(plan.since)} — nothing is spawned.`,
697
+ ' If it is still running it will pick these up on its next loop. If it is not:',
698
+ ` claude --resume ${plan.sessionId} "Answers landed for ${answered.join(', ')}"`,
699
+ ];
700
+ }
701
+ if (plan.action === 'none') {
702
+ return [
703
+ 'no conductor session id is recorded in .tyran/state/conductor.json.',
704
+ ' Start one and it will read the answers out of the journal: /tyran',
705
+ ];
706
+ }
707
+ return [
708
+ 'no conductor session has announced itself recently — conductor.json records no liveness signal,',
709
+ ' so whether one is running is not knowable from here. To put the swarm back on it:',
710
+ ` claude --resume ${plan.sessionId} "Answers landed for ${answered.join(', ')}"`,
711
+ ' (or re-run apply with --resume and this command will do it)',
712
+ ];
713
+ }
714
+
715
+ // ------------------------------------------------------------------- CLI
716
+
717
+ const BOOLEAN_FLAGS = ['dry-run', 'resume', 'force'];
718
+ const VALUE_FLAGS = ['dir'];
719
+
720
+ export function parseArgs(argv) {
721
+ const flags = { dir: '.tyran' };
722
+ const rest = [];
723
+ for (let i = 0; i < argv.length; i += 1) {
724
+ const arg = argv[i];
725
+ if (!arg.startsWith('--')) {
726
+ rest.push(arg);
727
+ continue;
728
+ }
729
+ const name = arg.slice(2);
730
+ if (BOOLEAN_FLAGS.includes(name)) flags[name] = true;
731
+ else if (VALUE_FLAGS.includes(name)) {
732
+ const value = argv[i + 1];
733
+ if (value === undefined || value.startsWith('--')) throw new UsageError(`flag --${name} needs a value`);
734
+ flags[name] = value;
735
+ i += 1;
736
+ } else throw new UsageError(`unknown flag --${name}`);
737
+ }
738
+ if (rest.length > 1) throw new UsageError(`unexpected extra argument "${rest[1]}"`);
739
+ return { verb: rest[0] ?? null, flags };
740
+ }
741
+
742
+ const USAGE =
743
+ 'usage: answer.mjs render [--dir <.tyran>] [--force]\n' +
744
+ ' answer.mjs apply [--dir <.tyran>] [--dry-run] [--resume]';
745
+
746
+ /**
747
+ * Answers already typed into the sheet on disk, for asks that are STILL OPEN.
748
+ *
749
+ * `render` overwrites the sheet, and doctor's fix string for every open ask
750
+ * sends the operator to `render` — so re-rendering to see a new question would
751
+ * silently destroy twenty minutes of typing. Answers for asks that are already
752
+ * closed are not typing at risk: they are in the ledger.
753
+ */
754
+ export function typedAnswers(text, openKeys) {
755
+ const { blocks } = parseSheet(text);
756
+ const typed = blocks
757
+ .filter((b) => b.answer !== '' && openKeys.has(keyOf(b.init, b.kind)))
758
+ .map((b) => `${b.kind} · ${inlinePlain(b.init)}`);
759
+ if (typed.length > 0) return typed;
760
+ // A sheet whose headings the operator broke parses into NO block at all —
761
+ // the answers typed under them are still theirs, and which asks they belong
762
+ // to is exactly what cannot be known here.
763
+ if (blocks.length === 0 && sheetLines(text).some((l) => /^answer:[ \t]*\S/.test(l))) {
764
+ return ['(an answer under a heading that does not parse)'];
765
+ }
766
+ return [];
767
+ }
768
+
769
+ function doRender(tyranDir, sheetPath, flags) {
770
+ const { asks, errors } = openAsks(tyranDir);
771
+ for (const e of errors) console.error(`answer: unreadable initiative ${inlinePlain(e.name)}: ${inlinePlain(e.error)}`);
772
+ const { answerable, unanswerable } = partitionAsks(asks);
773
+ for (const { ask, why } of unanswerable) {
774
+ console.error(`answer: ${inlinePlain(ask.init)} · ${inlinePlain(ask.kind)} cannot be answered through the sheet — ${why}`);
775
+ }
776
+ if (answerable.length === 0) {
777
+ console.error('answer: nothing is waiting on you');
778
+ process.exit(1);
779
+ }
780
+ if (flags.force !== true && existsSync(sheetPath)) {
781
+ const openKeys = new Set(answerable.map((a) => keyOf(a.init, a.kind)));
782
+ const typed = typedAnswers(readFileSync(sheetPath, 'utf8'), openKeys);
783
+ if (typed.length > 0) {
784
+ console.error(`answer: ${sheetPath} already has ${typed.length} answer(s) typed into it: ${typed.join(', ')}`);
785
+ console.error(` apply them first: node scripts/answer.mjs apply --dir ${tyranDir}`);
786
+ console.error(' or discard them and start the sitting again: add --force');
787
+ process.exit(2);
788
+ }
789
+ }
790
+ mkdirSync(dirname(sheetPath), { recursive: true });
791
+ writeAtomic(sheetPath, renderSheet(asks));
792
+ console.log(`answer: wrote ${sheetPath} — ${answerable.length} question(s) waiting on you`);
793
+ console.log(` fill the \`answer:\` lines, then: node scripts/answer.mjs apply --dir ${tyranDir}`);
794
+ const noDefault = answerable.filter((a) => a.default == null).length;
795
+ if (noDefault > 0) {
796
+ console.log(` ${noDefault} of them have no recorded default and come first — blank leaves those open.`);
797
+ }
798
+ }
799
+
800
+ function doApply(tyranDir, sheetPath, flags) {
801
+ if (!existsSync(sheetPath)) {
802
+ throw new IOError(`no sheet at ${sheetPath} — write one first: node scripts/answer.mjs render --dir ${tyranDir}`);
803
+ }
804
+ const result = applySheet(tyranDir, readFileSync(sheetPath, 'utf8'), { dryRun: flags['dry-run'] === true });
805
+ for (const e of result.readErrors ?? []) {
806
+ console.error(`answer: unreadable initiative ${inlinePlain(e.name)}: ${inlinePlain(e.error)}`);
807
+ }
808
+ for (const { ask, why } of result.unanswerable ?? []) {
809
+ console.error(`answer: ${inlinePlain(ask.init)} · ${inlinePlain(ask.kind)} cannot be answered through the sheet — ${why}`);
810
+ }
811
+ if (result.empty) {
812
+ console.error('answer: nothing is waiting on you');
813
+ process.exit(1);
814
+ }
815
+ if (!result.ok) {
816
+ for (const e of result.errors) console.error(`answer: ${sheetPath}: ${e}`);
817
+ console.error(
818
+ `answer: nothing was appended — the sheet is applied whole or not at all (${result.errors.length} problem(s))`,
819
+ );
820
+ process.exit(2);
821
+ }
822
+
823
+ const lines = reportLines(result);
824
+ // An ask another run closed while this one was parsing is not this run's to
825
+ // announce: it wrote nothing for it.
826
+ const closed = result.results.filter((r) => r.verdict.mode !== 'open' && r.skipped === undefined);
827
+ const acted = !result.dryRun && closed.length > 0;
828
+ if (acted) {
829
+ lines.push('', 're-rendered');
830
+ for (const { dir, files } of reRender(tyranDir, result.touched)) lines.push(` ${dir}/{${files.join(',')}}`);
831
+ }
832
+ const plan = resumePlan(readConductor(tyranDir), { resume: flags.resume === true });
833
+ const answered = closed.map((r) => r.ask.kind);
834
+ if (acted) lines.push('', ...conductorLines(plan, answered));
835
+ console.log(lines.join('\n'));
836
+
837
+ if (acted && plan.action === 'spawn') {
838
+ // Never through a shell: the argv is the whole command, and the session id
839
+ // was shape-checked before it became one of its elements.
840
+ const argv = resumeArgv(plan.sessionId, `Answers landed for ${answered.join(', ')} — read the journal tail and continue.`);
841
+ const child = spawn(argv[0], argv.slice(1), {
842
+ cwd: dirname(resolve(tyranDir)),
843
+ detached: true,
844
+ stdio: 'ignore',
845
+ shell: false,
846
+ });
847
+ child.on('error', (err) => console.error(`answer: could not resume the session: ${err.message}`));
848
+ child.unref();
849
+ console.log(`answer: resumed session ${plan.sessionId} (pid ${child.pid ?? '?'})`);
850
+ }
851
+ }
852
+
853
+ function main() {
854
+ let parsed;
855
+ try {
856
+ parsed = parseArgs(process.argv.slice(2));
857
+ } catch (err) {
858
+ console.error(`answer: ${err.message}`);
859
+ console.error(USAGE);
860
+ process.exit(2);
861
+ }
862
+ const tyranDir = resolve(parsed.flags.dir);
863
+ const sheetPath = join(tyranDir, 'state', ANSWERS_FILE);
864
+ try {
865
+ if (!existsSync(tyranDir)) throw new IOError(`no such directory ${tyranDir}`);
866
+ if (parsed.verb === 'render') return doRender(tyranDir, sheetPath, parsed.flags);
867
+ if (parsed.verb === 'apply') return doApply(tyranDir, sheetPath, parsed.flags);
868
+ // A verb-less invocation NEVER guesses. This command writes to the ledger,
869
+ // and an invocation that sometimes writes and sometimes does not is what a
870
+ // tired operator gets wrong at 23:00.
871
+ console.error(USAGE);
872
+ console.error(`answer: ${openAsks(tyranDir).asks.length} question(s) waiting on you — say \`render\` or \`apply\``);
873
+ process.exit(2);
874
+ } catch (err) {
875
+ console.error(`answer: ${err.message}`);
876
+ if (err instanceof UsageError) console.error(USAGE);
877
+ process.exit(2);
878
+ }
879
+ }
880
+
881
+ /** See journal.mjs — both sides canonicalized, or a symlinked path no-ops. */
882
+ function canonicalPath(path) {
883
+ const abs = resolve(path);
884
+ try {
885
+ return realpathSync(abs);
886
+ } catch {
887
+ return abs;
888
+ }
889
+ }
890
+
891
+ function isMainModule(moduleUrl) {
892
+ if (!process.argv[1]) return false;
893
+ return canonicalPath(process.argv[1]) === canonicalPath(fileURLToPath(moduleUrl));
894
+ }
895
+
896
+ if (isMainModule(import.meta.url)) main();