@jjanczur/tyran 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,7 +11,7 @@
11
11
  {
12
12
  "name": "tyran",
13
13
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
14
- "version": "0.1.12",
14
+ "version": "0.1.14",
15
15
  "source": "./",
16
16
  "author": {
17
17
  "name": "Jacek Janczura",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tyran",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
5
5
  "author": {
6
6
  "name": "Jacek Janczura",
package/CHANGELOG.md CHANGED
@@ -1,5 +1,138 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.14 — 2026-08-14
4
+
5
+ ### The repository remembers what went wrong — and eventually writes it into law
6
+
7
+ Tyran had three places a lesson could land and not one of them answered *how
8
+ often*. A journal `finding` dies with its initiative, correctly: it is that
9
+ run's discovery. A `.tyran/knowledge/` entry says what an agent must know
10
+ before touching a path. `CLAUDE.md` is law. Recurrence was counted nowhere, so
11
+ "this has burned us three times" was something a human had to remember, and on
12
+ the fourth time it was argued from scratch.
13
+
14
+ `MISTAKES.md` at your repository root is the store that was missing: what
15
+ happened, the root cause, the consequence, the prevention — newest first, plain
16
+ prose, yours to edit. The retrospective is its only writer, and it writes an
17
+ entry only for a breakage the initiative actually paid for. Every entry carries
18
+ a **signature**, and the signature is the whole point: the model decides
19
+ whether two failures are the *same* failure, and `scripts/mistakes.mjs`
20
+ (`add` · `repeats` · `promote`) does the counting.
21
+
22
+ **Three open entries under one signature** graduate the lesson into
23
+ `.tyran/knowledge/`, where every handoff touching those paths already delivers
24
+ it. **Five, still recurring after the knowledge entry shipped**, is evidence
25
+ the delivered rule was not enough — the strongest argument for law there is —
26
+ and at five `mistakes.mjs promote --law` **writes the rule into your
27
+ `CLAUDE.md`**. Not a proposal, not a queue: an autonomous write, between
28
+ `<!-- tyran:rules start -->` and `<!-- tyran:rules end -->` and never a byte
29
+ outside those markers. The line names the rule, its signature and the dated
30
+ entries that earned it; a `decision` event records the act; `--dry-run` prints
31
+ the line and writes nothing. You say no by deleting the line — the entries are
32
+ already at status `law`, so nothing puts it back. A fence that is absent is
33
+ appended once at the end, with its heading, and existing prose is never
34
+ reflowed; a fence that is malformed is refused by name, with nothing written.
35
+
36
+ The safety story is a boundary rather than a sentence. The shipped policy now
37
+ classes `CLAUDE.md` as **GATED**, which bans the hand and not the mechanism: a
38
+ subagent's free-hand `Write` is denied, while the script that demands five
39
+ recorded occurrences passes. Until this rule, the gate was silent on repo-root
40
+ files — its governed namespace is `.tyran/`, `.claude/` and the enforcement
41
+ scripts — so a subagent could rewrite the law it was bound by and nothing had
42
+ an opinion. An explicit rule outranks that namespace test, which is why one
43
+ line is enough. Seeding has always been create-only, so existing installs keep
44
+ their own policy untouched.
45
+
46
+ Seeding `MISTAKES.md` is create-only too, and **deleting the file is the whole
47
+ opt-out** — no knob for a file you can remove. `doctor --state` grew three
48
+ codes, 54 → **57**: `mistakes-repeat-unpromoted` (info — a lesson has earned
49
+ promotion), `mistakes-unreadable` (warning), and `claude-md-fence-missing`
50
+ (info — entries claim `law` but no fence exists to hold the rule). An absent
51
+ ledger is never a finding.
52
+
53
+ Stated rather than discovered: `MISTAKES.md` is **authored, not a byte-checked
54
+ projection**. A projection would report a hand edit as drift and destroy it on
55
+ the next render, and a human correcting a wrong root cause is the most valuable
56
+ edit this file will ever get. The cost is that nothing compares it to the
57
+ journal, so it can drift. Every entry cites its initiative and the event id
58
+ that proves it, which makes drift auditable by a human and **not** enforced by
59
+ a gate — a weaker guarantee than the projections carry, and both docs surfaces
60
+ say so instead of leaving you to assume parity.
61
+
62
+ This repository ships its own `MISTAKES.md`, five entries, one of them earned
63
+ during this release: the control-character write-guard refused an edit twice
64
+ because the editing tool turns `\uXXXX` escape text into the character itself,
65
+ so a regex class typed as escapes reached disk as raw C0 and bidi codepoints.
66
+ The guard was working; the author was the attacker.
67
+
68
+ ### Keep the machine awake while the watcher waits
69
+
70
+ The overnight resume watcher's whole job is to be asleep for hours, which is
71
+ exactly the interval a laptop chooses to suspend in — and a suspended machine
72
+ takes the watcher and the network with it. `limits.keep_awake` (a real boolean,
73
+ default `false`) wraps the wait in a system-sleep inhibitor: `caffeinate -is`
74
+ on macOS, `systemd-inhibit --what=idle:sleep` on Linux. **Never `caffeinate
75
+ -d`**: that blocks the display sleep and with it the screen lock, and a machine
76
+ left running overnight that never locks is a security regression. The inhibitor
77
+ is released on every exit path including `SIGINT` and `SIGTERM`, an unsupported
78
+ platform degrades to a no-op instead of refusing to wait, and
79
+ `overnight.mjs schedule` tells you which way the knob is set — as a warning,
80
+ never a refusal.
81
+
82
+ ### Measured
83
+
84
+ `node --test "tests/**/*.test.mjs"`: **1133 unit tests, 0 failures** — 34 of
85
+ them new in `tests/unit/mistakes.test.mjs` (the entry format, the counting
86
+ thresholds, the fence, and every refusal), 11 in `keepawake.test.mjs`.
87
+ `scan-control-chars`: clean over 185 tracked text files. The skill description
88
+ budget is unchanged at **4352 / 5000** — this release adds no skill and no
89
+ agent.
90
+
91
+ ## 0.1.13 — 2026-08-13
92
+
93
+ ### Six concurrent decisions, two ids
94
+
95
+ `append` took the write lock; issuing the `D-<n>` or `F-<n>` a caller omitted
96
+ happened before it, in the CLI. Issuing an id is read-compute-write, so every
97
+ concurrent writer read the same journal, computed the same next number, and
98
+ then serialized on the lock to write it. Measured on a fresh journal, seven
99
+ runs of six simultaneous `decision` appends: **1 to 4 distinct ids for 6
100
+ events**, and in the worst run all six carried the same id. Ids are how the
101
+ ledger references itself — "see D-2" —
102
+ in a file that is never rewritten, so every collision is ambiguous
103
+ permanently: neither `validate` nor the projections can say which `D-2` a
104
+ later event meant, and the premise of the whole design is many agents writing
105
+ one ledger at once.
106
+
107
+ The id is now issued inside the lock, from the snapshot that call has already
108
+ read for the timestamp clamp and the spawn guard — no second read per append,
109
+ which a long journal would pay for on every event. The contract is unchanged:
110
+ an explicit `data.id` still wins, `"id":""` is still treated as absent, and
111
+ only `decision` and `finding` are issued one. The same six-process race now
112
+ measures 6 distinct ids for 6 events, and eight genuinely concurrent
113
+ processes pin it in the suite.
114
+
115
+ The exported `append()` moved with the CLI, not behind it: before this release
116
+ a `decision` without `data.id` was rejected outright — `invalid event: data.id
117
+ is required for ev "decision"` — so every programmatic caller had to compute an
118
+ id first and then carry it across exactly the gap this release closes. Omitting
119
+ `data.id` is now the safe call rather than an error.
120
+
121
+ What is atomic is exactly the ids `append` ISSUES — `decision` and `finding`,
122
+ where `data.id` was omitted or empty: two of those, concurrent, can no longer
123
+ be handed one number. Nothing else moved. `next-id` previews a value while
124
+ holding nothing, so an id read there and appended later still loses to any
125
+ writer that appended in between — both journal doc surfaces say so, and a
126
+ caller that can let `append` issue the id should. An explicit `data.id` is
127
+ written verbatim and stays the caller's to keep unique: a journal whose three
128
+ `decision` events all carry `D-2` validates `ok`. `ticket.created` is
129
+ deliberately outside the issued set — a ticket id comes from the plan, which
130
+ numbers its own stories — so there is no atomic path for a `T-` id at all, and
131
+ `skills/run/SKILL.md` now says the conductor is the single writer for ticket
132
+ creation. And an id at or past 2^53 saturates `max+1`: seeded with
133
+ `D-9007199254740992`, `append` issues that same number to every decision after
134
+ it, and a 400-digit id yields `D-Infinity` — arithmetic byte-identical to the
135
+ previous release, named here rather than changed here.
3
136
  ## 0.1.12 — 2026-08-13
4
137
 
5
138
  ### The board: every ticket in a lane, every question in front of you
package/README.md CHANGED
@@ -443,6 +443,11 @@ underlying script does.
443
443
  - [x] Read-only dashboard: the kanban board — `BOARD.md`/`board.json` next to
444
444
  every journal, one cross-initiative `board.html` in the landing page's
445
445
  own palette, refreshed on every subagent stop, plus `board.mjs --serve`
446
+ - [x] The mistakes ledger: `MISTAKES.md` at your repo root — what went wrong
447
+ here and how often — where three occurrences of one signature graduate a
448
+ lesson into `.tyran/knowledge/` and five write a rule into your
449
+ `CLAUDE.md`, inside Tyran's own fence — see
450
+ [docs/self-improvement.md](docs/self-improvement.md)
446
451
 
447
452
  ## Where this came from
448
453
 
package/agents/retro.md CHANGED
@@ -21,6 +21,10 @@ to disk is in English.**
21
21
  --ev finding`) — the claims agents recorded WITH proof, mid-run. Promote
22
22
  the recurring ones into `.tyran/knowledge/` through the filter below; the
23
23
  rest die with the initiative, which is correct.
24
+ Alongside them, `MISTAKES.md` at the repository root — the durable record of
25
+ what has gone WRONG here, newest first. You are its only writer: read it
26
+ before you decide anything, so a candidate that has already burned this repo
27
+ repeatedly is recognised as evidence rather than argued about again.
24
28
  3. `git log` for the initiative: reverts, fixes of your own regressions,
25
29
  repeated phases.
26
30
  4. The current state of `skills/`, `agents/`, `scripts/` and the docs — **so
@@ -69,11 +73,22 @@ next retro relitigating the same idea.
69
73
  report generators. A one-off harness from an initiative either becomes a
70
74
  general tool or gets deleted; do not leave dead files behind.
71
75
  - **Knowledge upkeep:** fold the reports' knowledge-brief verdicts into the
72
- entries' counters (the fold procedure lives in `skills/retro/SKILL.md`,
73
- step 3 — one home, not two), and retire or split entries
76
+ entries' counters (the fold procedure lives in `skills/retro/SKILL.md`, under
77
+ "Write down what is true about THIS repo" — one home, not two), and retire or
78
+ split entries
74
79
  `doctor --state` flags as `knowledge-entry-oversized`. An entry whose
75
80
  counters say it stopped earning its keep is a deletion candidate, which
76
81
  satisfies the deletion preference.
82
+ - **The mistakes ledger:** append an entry to `MISTAKES.md` for every breakage
83
+ this initiative actually paid for — what happened, the root cause, the
84
+ consequence, the prevention — and give it a **signature** you reuse for the
85
+ same failure rather than a near-synonym, because the signature is what makes
86
+ recurrence countable. Then promote what recurred: `mistakes.mjs repeats` says
87
+ which signatures crossed a graduation threshold and what each one has earned
88
+ — a `.tyran/knowledge/` entry, or a line you write into the `tyran:rules`
89
+ fence of the host `CLAUDE.md`. A discovery is not a mistake; if nothing
90
+ broke, write nothing. The procedure is the step of `skills/retro/SKILL.md`
91
+ that folds breakages into `MISTAKES.md` — one home, not two.
77
92
  - **Documentation that pays forward:** the repo's detected configuration,
78
93
  protocols, runbooks. **Every initiative should leave the repo better
79
94
  described than it found it** — that is the part that makes each next
package/bin/tyran.mjs CHANGED
@@ -72,6 +72,10 @@ export const COMMANDS = {
72
72
  'knowledge.mjs',
73
73
  'Select the knowledge entries that apply to a set of paths and print a paste-ready brief for a handoff.',
74
74
  ],
75
+ mistakes: [
76
+ 'mistakes.mjs',
77
+ "Append to the repository's MISTAKES.md, count recurring signatures, and promote a recurring one into CLAUDE.md.",
78
+ ],
75
79
  overnight: [
76
80
  'overnight.mjs',
77
81
  'Schedule and run the usage-limit resume watcher: wait for the window reset, then resume the paused session.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "Command-line scripts for the Tyran task conductor (doctor, journal, schema, and repo tooling) for CI and terminals outside Claude Code. Installing this package does NOT install the Claude Code plugin — add that separately with `/plugin marketplace add jjanczur/tyran` inside Claude Code.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -52,6 +52,7 @@ import {
52
52
  } from './project.mjs';
53
53
  import { classifyPath, normalizePath, validateFile, knowledgeWarnings, MANDATORY_KERNEL_PATHS } from './schema.mjs';
54
54
  import { gitRunner } from './scan-repo.mjs';
55
+ import { parseMistakes, countSignatures, fenceState, KNOWLEDGE_THRESHOLD, MISTAKES_FILE, CLAUDE_MD_FILE } from './mistakes.mjs';
55
56
 
56
57
  /** Severity order is also the report order. `info` never fails the check. */
57
58
  export const SEVERITIES = Object.freeze(['error', 'warning', 'info']);
@@ -200,6 +201,17 @@ export const SEVERITY_BY_CODE = Object.freeze(
200
201
  'state-stray-file': 'warning',
201
202
  'state-legacy-initiatives-dir': 'warning',
202
203
  'lease-file-tracked': 'warning',
204
+ // the mistakes ledger. `mistakes-unreadable` is a WARNING, not the `error`
205
+ // that `knowledge-unreadable` and `config-unreadable` carry: nothing
206
+ // mechanical consumes MISTAKES.md at write time, so an unreadable one
207
+ // degrades learning without stopping work, and exiting 1 on it would be a
208
+ // false alarm about a repository that is fine. The other two are `info`
209
+ // for the same reason `spawn-open` is: a warning would go red on every
210
+ // healthy repo between a breakage and its next retro, and a check that is
211
+ // red during normal operation is a check people learn to skip.
212
+ 'mistakes-unreadable': 'warning',
213
+ 'mistakes-repeat-unpromoted': 'info',
214
+ 'claude-md-fence-missing': 'info',
203
215
  // overnight mode
204
216
  'limit-pause-active': 'info',
205
217
  'limit-pause-stale': 'warning',
@@ -1113,6 +1125,98 @@ export function trackedLeaseFiles(run, tyranDirName = '.tyran') {
1113
1125
  return listing.split('\n').filter((line) => line !== '' && lease.test(line));
1114
1126
  }
1115
1127
 
1128
+ /**
1129
+ * The mistakes ledger at the repository root: is it readable, has a lesson
1130
+ * earned promotion, and can a promoted rule actually land?
1131
+ *
1132
+ * ABSENCE PRODUCES NO FINDING AT ALL. Deleting the file is the documented
1133
+ * opt-out, and a tool that nags about a file you deliberately removed is a
1134
+ * tool you disable. The `checked` line still records what was looked at, so
1135
+ * "nothing was said about it" and "it is not there" stay distinguishable.
1136
+ *
1137
+ * `parseMistakes` is imported rather than re-implemented: the entry shape is
1138
+ * owned by `mistakes.mjs`, the same discipline doctor already follows for
1139
+ * `validateKnowledge` and `pairSpawns` (ADR-18).
1140
+ */
1141
+ export function mistakesFindings(repoRoot) {
1142
+ const path = join(repoRoot, MISTAKES_FILE);
1143
+ if (!existsSync(path)) return { findings: [], checked: `${MISTAKES_FILE}: absent` };
1144
+
1145
+ let parsed;
1146
+ try {
1147
+ parsed = parseMistakes(readFileSync(path, 'utf8'));
1148
+ } catch (err) {
1149
+ return {
1150
+ findings: [
1151
+ finding(
1152
+ 'mistakes-unreadable',
1153
+ show(path),
1154
+ `the mistakes ledger could not be read or parsed (${errText(err)}) — nothing in it was counted`,
1155
+ `ls -la ${sq(path)} # this file is prose, not a projection: open it and repair it by hand`,
1156
+ ),
1157
+ ],
1158
+ checked: `${MISTAKES_FILE}: UNREADABLE`,
1159
+ };
1160
+ }
1161
+
1162
+ const findings = [];
1163
+ const rows = countSignatures(parsed.entries);
1164
+ for (const row of rows) {
1165
+ if (row.open < KNOWLEDGE_THRESHOLD) continue;
1166
+ findings.push(
1167
+ finding(
1168
+ 'mistakes-repeat-unpromoted',
1169
+ show(path),
1170
+ `\`${show(row.signature)}\` has ${row.open} open entries (${show(row.dates.join(', '))}) — ` +
1171
+ 'a failure that recurred this often is evidence a rule is missing, not a coincidence',
1172
+ `node scripts/mistakes.mjs repeats --file ${sq(path)} --threshold ${KNOWLEDGE_THRESHOLD} # then /tyran:retro promotes them into .tyran/knowledge/`,
1173
+ ),
1174
+ );
1175
+ }
1176
+
1177
+ // A law entry says a rule was earned; the fence is where such a rule lives.
1178
+ // Info in both directions: a repo whose law predates the fence is fine, and
1179
+ // a repo that has never promoted anything must never see this at all.
1180
+ const lawEntries = parsed.entries.filter((entry) => entry.statusKind === 'law').length;
1181
+ if (lawEntries > 0) {
1182
+ const claudePath = join(repoRoot, CLAUDE_MD_FILE);
1183
+ let state = { start: null, problem: null };
1184
+ let claudeExists = existsSync(claudePath);
1185
+ if (claudeExists) {
1186
+ try {
1187
+ state = fenceState(readFileSync(claudePath, 'utf8'));
1188
+ } catch {
1189
+ claudeExists = false;
1190
+ }
1191
+ }
1192
+ if (!claudeExists || state.problem !== null || state.start === null) {
1193
+ // The two branches fail differently, so they say different things: a
1194
+ // missing fence is written by the next promotion (writeRuleToFence
1195
+ // creates it), a malformed one refuses every promotion until it is
1196
+ // repaired by hand.
1197
+ const why = state.problem !== null
1198
+ ? `the tyran:rules fence is malformed (${show(state.problem)}) — ` +
1199
+ 'the next promotion cannot land where an earned rule is supposed to live'
1200
+ : `${CLAUDE_MD_FILE} carries no tyran:rules fence — ` +
1201
+ 'the earned rule is not in force in any session';
1202
+ findings.push(
1203
+ finding(
1204
+ 'claude-md-fence-missing',
1205
+ show(claudePath),
1206
+ `${lawEntries} entr${lawEntries === 1 ? 'y' : 'ies'} in ${MISTAKES_FILE} ` +
1207
+ `claim${lawEntries === 1 ? 's' : ''} status \`law\`, and ${why}`,
1208
+ `node scripts/mistakes.mjs repeats --file ${sq(path)} # see docs/self-improvement.md for the fence`,
1209
+ ),
1210
+ );
1211
+ }
1212
+ }
1213
+
1214
+ return {
1215
+ findings,
1216
+ checked: `${MISTAKES_FILE}: ${parsed.entries.length} entries, ${rows.length} signatures`,
1217
+ };
1218
+ }
1219
+
1116
1220
  /** The repo-global overnight runtime files that legally live at state/ level. */
1117
1221
  /** The cross-initiative board artefacts board.mjs writes at state/ level. */
1118
1222
  export const CROSS_BOARD_FILES = Object.freeze(['BOARD.md', 'board.json', 'board.html']);
@@ -1379,6 +1483,10 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1379
1483
  }
1380
1484
  checked.push(`initiatives/ (legacy): ${isDirectory(legacyDir) ? 'PRESENT' : 'absent'}`);
1381
1485
 
1486
+ const mistakes = mistakesFindings(repoRoot);
1487
+ findings.push(...mistakes.findings);
1488
+ checked.push(mistakes.checked);
1489
+
1382
1490
  findings.push(...overnightFindings(dir, { now, configDoc }));
1383
1491
  checked.push('overnight: checked');
1384
1492
 
@@ -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;