@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.
@@ -23,7 +23,9 @@
23
23
  * ## What the watcher defends against (measured platform facts)
24
24
  *
25
25
  * - Machine sleep: chunked sleeps re-read the wall clock; an overslept
26
- * laptop fires late, never never. Reboot kills the watcher — the marker
26
+ * laptop fires late, never never. Under `limits.keep_awake` it does not
27
+ * oversleep at all — the wait is wrapped in a system-sleep inhibitor
28
+ * (scripts/keepawake.mjs). Reboot still kills the watcher — the marker
27
29
  * then goes stale, doctor reports it, and the gate self-heals it.
28
30
  * - Blind resumed sessions: statuslines do not run under `claude -p`
29
31
  * (measured 2.1.197), so a resumed session has NO fresh telemetry. The
@@ -49,13 +51,15 @@
49
51
  * node overnight.mjs --wait [--dir <repo>] # internal (the watcher)
50
52
  * Exit: 0 ok/held · 1 refused (no marker, already scheduled, STOP) · 2 usage/IO
51
53
  */
52
- import { spawn, spawnSync, execFile } from 'node:child_process';
54
+ import { spawn, execFile } from 'node:child_process';
53
55
  import { existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
54
56
  import { join, resolve } from 'node:path';
55
57
  import { realpathSync } from 'node:fs';
56
58
  import { fileURLToPath } from 'node:url';
57
59
  import { checkStop } from './stop-check.mjs';
58
60
  import { readJournal } from './journal.mjs';
61
+ import { GATE_PASS } from './project.mjs';
62
+ import { withKeepAwake } from './keepawake.mjs';
59
63
  import { limitsOf } from './schema.mjs';
60
64
  import { parse } from './yaml-lite.mjs';
61
65
  import { escapeInvisible } from './invisible.mjs';
@@ -107,8 +111,9 @@ export function skipReason({ stopped, markerExists, journalEvents, pausedAtIso }
107
111
  // Only this pause's gate events count: a gate closed before pausedAt
108
112
  // belongs to an earlier cycle and says nothing about the current one.
109
113
  if (e?.ev === 'gate' && e?.data?.kind === 'usage-limit' && ts > pausedAt) {
110
- const result = String(e?.data?.result ?? '').toLowerCase();
111
- gateOpen = !['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered'].includes(result);
114
+ // The pass set is project.mjs's, imported: a copy here would let the
115
+ // watcher and the projection disagree about whether a gate is closed.
116
+ gateOpen = !GATE_PASS.has(String(e?.data?.result ?? '').toLowerCase());
112
117
  }
113
118
  if (e?.ev === 'checkpoint' && ts > pausedAt && e?.data?.phase !== 'usage-limit-pause') laterCheckpoint = true;
114
119
  }
@@ -281,6 +286,58 @@ function readLimitsFile(repo) {
281
286
  }
282
287
  }
283
288
 
289
+ /**
290
+ * Run ONE resume attempt to completion without blocking the event loop.
291
+ *
292
+ * `spawnSync` is the shorter shape and must not be used: a sync child parks
293
+ * the loop for the whole attempt — up to RESUME_ATTEMPT_TIMEOUT_MS, four
294
+ * times over — and no JS signal handler can run while it is parked. Two
295
+ * things depend on those handlers: `cancel`, the operator's documented
296
+ * handle, SIGTERMs the watcher and expects it to die; and keepawake's release
297
+ * runs from the same handler, so a sender that escalates to SIGKILL past its
298
+ * grace period orphans the inhibitor. Both are measured, in overnight.test.
299
+ *
300
+ * Resolves, never rejects: a missing binary arrives asynchronously as an
301
+ * 'error' event, and an unheard 'error' event is thrown from outside any
302
+ * try/catch the caller could have. Its `status: null` reads as "did not
303
+ * take", which is the babysitter's business, not an exception's.
304
+ */
305
+ export function runResume(argv, { cwd, timeoutMs = RESUME_ATTEMPT_TIMEOUT_MS, spawnFn = spawn } = {}) {
306
+ return new Promise((resolve) => {
307
+ let child;
308
+ try {
309
+ child = spawnFn(argv[0], argv.slice(1), {
310
+ cwd,
311
+ // Never a pipe: the output was captured and discarded before, and a
312
+ // buffered pipe would cap a long resume at maxBuffer instead.
313
+ stdio: 'ignore',
314
+ // The argv is the whole command. No shell, ever.
315
+ shell: false,
316
+ });
317
+ } catch {
318
+ resolve({ status: null, signal: null });
319
+ return;
320
+ }
321
+ let settled = false;
322
+ let timer = null;
323
+ const finish = (result) => {
324
+ if (settled) return;
325
+ settled = true;
326
+ if (timer !== null) clearTimeout(timer);
327
+ resolve(result);
328
+ };
329
+ timer = setTimeout(() => {
330
+ try {
331
+ child.kill('SIGTERM');
332
+ } catch {
333
+ /* it finished between the timer firing and this line */
334
+ }
335
+ }, timeoutMs);
336
+ child.on('error', () => finish({ status: null, signal: null }));
337
+ child.on('exit', (status, signal) => finish({ status, signal }));
338
+ });
339
+ }
340
+
284
341
  // ------------------------------------------------------------ subcommands
285
342
 
286
343
  function doSchedule(repo, flags) {
@@ -325,6 +382,19 @@ function doSchedule(repo, flags) {
325
382
  process.exit(1);
326
383
  }
327
384
 
385
+ // A warning, never a refusal: the operator is about to leave a machine
386
+ // waiting for hours, and whether it stays awake is their call to make with
387
+ // the risk named. Only on the watch path — a hold waits for nothing.
388
+ if (readLimitsFile(repo).keep_awake === true) {
389
+ console.log('overnight: keep-awake is on — the system stays awake while the watcher waits (the display and the screen lock are untouched).');
390
+ } else {
391
+ console.error(
392
+ 'overnight: keep-awake is OFF — if this machine sleeps before the reset, the watcher sleeps with it and the ' +
393
+ 'resume fires late or never. Set limits.keep_awake: true in .tyran/config.yaml to hold the SYSTEM awake ' +
394
+ 'while it waits; the display and the screen lock are untouched.',
395
+ );
396
+ }
397
+
328
398
  const logFd = openSync(join(repo, RESUME_LOG_RELPATH), 'a');
329
399
  const watcherArgv = [
330
400
  SELF,
@@ -366,6 +436,23 @@ async function doWait(repo, flags) {
366
436
  const prompt = typeof flags.prompt === 'string' ? flags.prompt : null;
367
437
  const cmd = typeof flags.cmd === 'string' ? flags.cmd : 'claude';
368
438
 
439
+ // The whole point of this process is to be asleep for hours, and a laptop
440
+ // that suspends during that window is the measured way an overnight run
441
+ // dies. The wrap covers the resume too: the resumed `claude -p` IS the
442
+ // overnight work, and a machine that suspends mid-session kills it.
443
+ //
444
+ // Opt-in, and released on every exit path including SIGTERM — which is what
445
+ // `cancel` sends. That release runs from a JS signal handler, so NOTHING
446
+ // inside this region may block the event loop: a sync child would defer the
447
+ // handler for its whole runtime and make `cancel` a no-op meanwhile. Hence
448
+ // runResume rather than spawnSync.
449
+ return withKeepAwake(
450
+ { enabled: readLimitsFile(repo).keep_awake === true, onNote: (message) => log(repo, message) },
451
+ () => runWaitLoop(repo, { chunkMs, backoffs, prompt, cmd }),
452
+ );
453
+ }
454
+
455
+ async function runWaitLoop(repo, { chunkMs, backoffs, prompt, cmd }) {
369
456
  for (;;) {
370
457
  const marker = readSmallJson(join(repo, MARKER_RELPATH));
371
458
  if (marker === null) {
@@ -455,7 +542,7 @@ async function doWait(repo, flags) {
455
542
  log(repo, `resuming attempt=${attempt + 1} argv=${argv[0]} session=${marker.session_id}`);
456
543
  writeStateFile(repo, { state: 'resuming', attempt: attempt + 1, at: new Date().toISOString() });
457
544
  notifyDesktop('Tyran: resuming', `The usage window has reset; resuming the paused session${init ? ` (${init})` : ''}.`);
458
- const child = spawnSync(argv[0], argv.slice(1), { cwd: repo, encoding: 'utf8', timeout: RESUME_ATTEMPT_TIMEOUT_MS });
545
+ const child = await runResume(argv, { cwd: repo });
459
546
  const eventsAfter = journalEventCount(journalPath);
460
547
  const took =
461
548
  eventsBefore === null || eventsAfter === null
@@ -41,8 +41,15 @@ const GENERATED_HEADER =
41
41
  '<!-- GENERATED by tyran scripts/project.mjs - DO NOT EDIT. Source of truth: journal.jsonl -->\n' +
42
42
  '<!-- Regenerate: node scripts/project.mjs <journal.jsonl> --out-dir <dir> -->\n';
43
43
 
44
- /** Gate results that count as closed. Anything else keeps the gate OPEN. */
45
- const GATE_PASS = new Set(['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered']);
44
+ /**
45
+ * Gate results that count as closed. Anything else keeps the gate OPEN.
46
+ *
47
+ * Exported because `overnight.skipReason` needs the same seven strings, and a
48
+ * hand-copied literal there is a second spelling of one rule (ADR-21): adding
49
+ * a pass result here while the watcher kept the old list would make it resume
50
+ * a session whose gate this module already considers closed.
51
+ */
52
+ export const GATE_PASS = new Set(['pass', 'passed', 'ok', 'green', 'approved', 'closed', 'answered']);
46
53
 
47
54
  /** A gate result that means "a human owes an answer" — the board's queue. */
48
55
  export const WAITING_RE = /^waiting[_-]?on[_-]?(operator|owner|human)$/i;
@@ -961,12 +968,17 @@ function renderState(state) {
961
968
  );
962
969
 
963
970
  parts.push('\n## Open gates\n\n');
971
+ // The Question column is what a resumed conductor reads. Without it this
972
+ // table says THAT the initiative is waiting on the operator and never what
973
+ // it asked, which costs a re-litigation of the question after every
974
+ // compaction. `fold` already carries it; ordinary gates render an em dash.
964
975
  parts.push(
965
976
  table(
966
- ['Gate', 'Latest result', 'At', 'Evidence'],
977
+ ['Gate', 'Latest result', 'Question', 'At', 'Evidence'],
967
978
  sortByKey(state.openGates, (g) => g.kind).map((g) => [
968
979
  inline(g.kind),
969
980
  inline(g.result),
981
+ inline(g.question),
970
982
  inline(g.ts),
971
983
  inline(g.evidence),
972
984
  ]),
@@ -319,6 +319,27 @@ export function detectAutonomy(dir, run = gitRunner(dir)) {
319
319
  );
320
320
  }
321
321
 
322
+ /**
323
+ * What the host `CLAUDE.md` says about the mistakes ledger, read-only.
324
+ *
325
+ * `present: false` deliberately produces NO question: Tyran does not create a
326
+ * CLAUDE.md for a repository that has none, and the seeded MISTAKES.md header
327
+ * carries the instruction itself, so the loop still closes without one.
328
+ */
329
+ export function detectClaudeMd(dir) {
330
+ const path = join(dir, CLAUDE_MD_PATH);
331
+ if (!existsSync(path)) return { path: CLAUDE_MD_PATH, present: false, hasMistakesPointer: false };
332
+ let text = '';
333
+ try {
334
+ text = readFileSync(path, 'utf8');
335
+ } catch {
336
+ // Unreadable is not absent, and it is not a reason to fail a scan: the
337
+ // only thing riding on this field is whether one question gets asked.
338
+ return { path: CLAUDE_MD_PATH, present: true, hasMistakesPointer: false };
339
+ }
340
+ return { path: CLAUDE_MD_PATH, present: true, hasMistakesPointer: text.includes(MISTAKES_PATH) };
341
+ }
342
+
322
343
  /** The whole scan. Returns `{config, languages, questions}`. */
323
344
  export function scanRepo(dir, { run = gitRunner(dir) } = {}) {
324
345
  const pkg = readPackageJson(dir);
@@ -326,6 +347,7 @@ export function scanRepo(dir, { run = gitRunner(dir) } = {}) {
326
347
  const validation = detectValidation(dir, pkg, manager?.value);
327
348
  const autonomy = detectAutonomy(dir, run);
328
349
  const languages = detectLanguages(dir, run);
350
+ const claudeMd = detectClaudeMd(dir);
329
351
 
330
352
  const config = {
331
353
  profile: 'balanced',
@@ -339,8 +361,16 @@ export function scanRepo(dir, { run = gitRunner(dir) } = {}) {
339
361
  if (autonomy.needs_confirmation) questions.push({ field: 'autonomy', asked: autonomy.source });
340
362
  if (validation.needs_confirmation) questions.push({ field: 'validation', asked: validation.source });
341
363
  if (manager?.needs_confirmation) questions.push({ field: 'package manager', asked: manager.source });
364
+ if (claudeMd.present && !claudeMd.hasMistakesPointer) {
365
+ questions.push({
366
+ field: 'CLAUDE.md pointer',
367
+ asked:
368
+ 'CLAUDE.md exists and does not mention MISTAKES.md — one line makes every session in this repo log ' +
369
+ 'its own mistakes, and only you can add it',
370
+ });
371
+ }
342
372
 
343
- return { config, languages, packageManager: manager, questions };
373
+ return { config, languages, packageManager: manager, claudeMd, questions };
344
374
  }
345
375
 
346
376
  /**
@@ -508,6 +538,56 @@ export function ensureAutonomyPolicy(repoRoot, { templatePath = policyTemplatePa
508
538
  return { path, status: 'created' };
509
539
  }
510
540
 
541
+ /**
542
+ * The repository's incident log, and the operator prose that can point at it.
543
+ * Both at the ROOT: a human, a reviewer on GitHub and a session that has never
544
+ * heard of Tyran all have to be able to find them.
545
+ */
546
+ export const MISTAKES_PATH = 'MISTAKES.md';
547
+ export const CLAUDE_MD_PATH = 'CLAUDE.md';
548
+
549
+ /** The shipped MISTAKES.md template, from this script's REAL location. */
550
+ export function mistakesTemplatePath() {
551
+ const self = canonicalPath(fileURLToPath(import.meta.url));
552
+ return join(dirname(self), '..', 'templates', MISTAKES_PATH);
553
+ }
554
+
555
+ /**
556
+ * Seed the repository's `MISTAKES.md` from the shipped template if it is
557
+ * absent. Returns `{ path, status: 'created' | 'present' | 'failed', error }`.
558
+ *
559
+ * Create-only, and that is the whole opt-out: a repository that does not want
560
+ * this file deletes it, and nothing here puts it back except an explicit
561
+ * re-run of setup. No config knob, because a knob for a file you can delete is
562
+ * a second way to say the same thing.
563
+ *
564
+ * Three deliberate differences from `ensureAutonomyPolicy`:
565
+ *
566
+ * - it lands at the repo ROOT, not under `.tyran/`, so it is called
567
+ * unconditionally rather than gated on `underTyranDir`;
568
+ * - a write failure is a REPORTED status, not a `BootstrapError`. An absent
569
+ * policy makes the gate refuse every write; an absent incident log breaks
570
+ * nothing. Refusing to configure a repository because its incident log
571
+ * could not be created would be the tail wagging the dog;
572
+ * - the header is shipped rather than authored on first use, because the
573
+ * parser depends on its shape and a header written by a model drifts.
574
+ */
575
+ export function ensureMistakesFile(repoRoot, { templatePath = mistakesTemplatePath() } = {}) {
576
+ const path = join(resolve(repoRoot), MISTAKES_PATH);
577
+ if (existsSync(path)) return { path, status: 'present', error: null };
578
+ try {
579
+ // `wx` and not a bare write: `existsSync` above answers about the past,
580
+ // and this file is a repository's incident history. The exclusive flag is
581
+ // what makes "create-only" true against a racing second setup rather than
582
+ // merely likely.
583
+ writeFileSync(path, readFileSync(templatePath, 'utf8'), { flag: 'wx' });
584
+ } catch (error) {
585
+ if (error.code === 'EEXIST') return { path, status: 'present', error: null };
586
+ return { path, status: 'failed', error: error.message };
587
+ }
588
+ return { path, status: 'created', error: null };
589
+ }
590
+
511
591
  export const STATE_GITIGNORE_PATH = '.tyran/.gitignore';
512
592
  export const STATE_GITIGNORE_LINES = Object.freeze([
513
593
  'state/*/locks/',
@@ -515,6 +595,12 @@ export const STATE_GITIGNORE_LINES = Object.freeze([
515
595
  'state/resume.json',
516
596
  'state/resume.log',
517
597
  'state/usage.json',
598
+ // The ask queue's two runtime files: a session id and a pid that mean
599
+ // nothing in another clone, and a sheet whose answers already live in the
600
+ // journal — committing either makes every parallel merge conflict on state
601
+ // that was stale the moment it was written.
602
+ 'state/conductor.json',
603
+ 'state/ANSWERS.md',
518
604
  ]);
519
605
  const STATE_GITIGNORE_BODY =
520
606
  '# Runtime files, never history. Leases record who holds a worktree or a\n' +
@@ -600,6 +686,7 @@ function main() {
600
686
  : `scan-repo: ${escapeInvisible(seeded.path)} already exists — left untouched`,
601
687
  );
602
688
  reportStateGitignore(seedStateGitignore(dir));
689
+ reportMistakes(ensureMistakesFile(dir));
603
690
  return;
604
691
  }
605
692
 
@@ -618,6 +705,9 @@ function main() {
618
705
  }
619
706
  reportStateGitignore(seedStateGitignore(dir));
620
707
  }
708
+ // Unconditional, unlike the two above: MISTAKES.md is not under `.tyran/`,
709
+ // so `underTyranDir` has nothing to say about whether it should exist.
710
+ reportMistakes(ensureMistakesFile(dir));
621
711
  try {
622
712
  mkdirSync(dirname(path), { recursive: true });
623
713
  writeFileSync(path, renderConfig(result.config));
@@ -653,6 +743,22 @@ function reportStateGitignore({ path, status }) {
653
743
  }
654
744
  }
655
745
 
746
+ /**
747
+ * A file landing in someone's working tree unannounced is a bad way to meet a
748
+ * tool, and a file that FAILED to land silently is worse: the repository would
749
+ * simply never learn anything and nothing would say why.
750
+ */
751
+ function reportMistakes({ path, status, error }) {
752
+ if (status === 'created') {
753
+ console.error(
754
+ `scan-repo: created ${escapeInvisible(path)} — the repository's incident log ` +
755
+ '(delete it if you do not want one)',
756
+ );
757
+ } else if (status === 'failed') {
758
+ console.error(`scan-repo: could not create ${escapeInvisible(path)} (${escapeInvisible(String(error))}) — the scan continues`);
759
+ }
760
+ }
761
+
656
762
  /**
657
763
  * `ensureStateGitignore`, with a BootstrapError turned into exit 2. Both call
658
764
  * sites run this AFTER `seedPolicy` on purpose: it creates `.tyran/` when
@@ -171,7 +171,13 @@ export function validateConfig(doc) {
171
171
  if ('resume_margin_minutes' in limits && (typeof limits.resume_margin_minutes !== 'number' || limits.resume_margin_minutes <= 0 || limits.resume_margin_minutes > 240)) {
172
172
  errors.push('limits.resume_margin_minutes: must be a number in (0, 240]');
173
173
  }
174
- const knownLimits = ['mode', 'pause_at_percent', 'weekly_pause_at_percent', 'wait_max_hours', 'long_wait', 'resume_margin_minutes'];
174
+ // Boolean only, and rejected rather than coerced: this knob spawns a
175
+ // process that changes the operator's machine, so a value nobody can
176
+ // read as a switch must be a complaint, not a guess.
177
+ if ('keep_awake' in limits && typeof limits.keep_awake !== 'boolean') {
178
+ errors.push('limits.keep_awake: must be true or false');
179
+ }
180
+ const knownLimits = ['mode', 'pause_at_percent', 'weekly_pause_at_percent', 'wait_max_hours', 'long_wait', 'resume_margin_minutes', 'keep_awake'];
175
181
  for (const key of Object.keys(limits)) {
176
182
  if (!knownLimits.includes(key)) errors.push(`limits.${key}: unknown key`);
177
183
  }
@@ -206,6 +212,9 @@ export function limitsOf(doc) {
206
212
  long_wait: LIMITS_LONG_WAIT.includes(limits.long_wait) ? limits.long_wait : 'hold',
207
213
  resume_margin_minutes:
208
214
  inRange(limits.resume_margin_minutes, 0, 240, { minExclusive: true }) ? limits.resume_margin_minutes : 5,
215
+ // Opt-in, strictly: anything that is not the boolean true is off. Nothing
216
+ // on any machine changes until an operator writes `keep_awake: true`.
217
+ keep_awake: limits.keep_awake === true,
209
218
  };
210
219
  }
211
220
 
package/scripts/tiers.mjs CHANGED
@@ -91,6 +91,12 @@ export const ROLE_TIERS = Object.freeze({
91
91
  acceptance: { eco: 'deep', balanced: 'top', full: 'top' },
92
92
  retro: { eco: 'work', balanced: 'work', full: 'deep' },
93
93
  bookkeeping: { eco: 'cheap', balanced: 'cheap', full: 'cheap' },
94
+ // ADVISORY. The conductor is the operator's own session, and no plugin can
95
+ // change a running session's model — so this row records the choice in the
96
+ // one file where model names may live and the CLI says out loud, on stderr,
97
+ // that it cannot enforce it. A row that silently did nothing would be worse
98
+ // than no row: it would read as configuration.
99
+ conductor: { eco: 'deep', balanced: 'top', full: 'top' },
94
100
  });
95
101
 
96
102
  /**
@@ -104,6 +110,9 @@ export const ROLE_TIERS = Object.freeze({
104
110
  export const ROLE_FLOOR = Object.freeze({
105
111
  'security-review': 'top',
106
112
  arbitration: 'top',
113
+ // One weak coordinator spends a whole team's budget on the wrong plan, and
114
+ // the floor is what `--profile eco --risk low` cannot shift out of.
115
+ conductor: 'deep',
107
116
  });
108
117
 
109
118
  export const ROLES = Object.freeze(Object.keys(ROLE_TIERS));
@@ -286,6 +295,14 @@ function main() {
286
295
  `"${escapeInvisible(role)}" has a floor that cannot be lowered`,
287
296
  );
288
297
  }
298
+ // STDERR, like every other note here: stdout is the resolved value and the
299
+ // skill parses it.
300
+ if (role === 'conductor') {
301
+ console.error(
302
+ 'tiers: `conductor` is ADVISORY. The conductor is your own session and no plugin can ' +
303
+ 'change its model mid-flight — this is the tier your config says it should be running.',
304
+ );
305
+ }
289
306
  console.error(`tiers: ${role} @ ${profile}/${risk} -> ${resolved.tier} · effort ${resolved.effort}`);
290
307
  if (field === 'json') console.log(JSON.stringify(resolved));
291
308
  else if (Object.hasOwn(resolved, field)) console.log(resolved[field]);
@@ -70,7 +70,86 @@ Write what a competent newcomer would get wrong, not what the code already
70
70
  says. "The test suite takes 9 minutes, so do not run it per file" is worth an
71
71
  entry. "This is a Next.js app" is not: the next agent can see that.
72
72
 
73
- ## 4. Report
73
+ ## 4. Fold what BROKE into `MISTAKES.md`, and promote what recurred
74
+
75
+ `.tyran/knowledge/` holds what an agent should know before touching a path;
76
+ `MISTAKES.md` at the repo root holds what has gone wrong here and **how often**.
77
+ Not two spellings of one store: the first is delivered into every handoff by
78
+ the knowledge brief, the second is the evidence that decides what deserves
79
+ delivering at all.
80
+
81
+ One entry per breakage this initiative genuinely paid for — a wasted agent
82
+ cycle, a bad merge, a rework wave. Not per discovery, and not per `finding`
83
+ event: most findings are good news.
84
+
85
+ ```bash
86
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/mistakes.mjs" add \
87
+ --signature worktree-missing-deps \
88
+ --what '...' --cause '...' --consequence '...' --prevention '...' \
89
+ --initiative "$INIT" --actor impl-t3 --proof F-12
90
+ ```
91
+
92
+ **The signature is the judgement, and the one part a script cannot do.** Reuse
93
+ the signature an earlier entry already used for the same failure; a
94
+ near-synonym resets the count to one and the lesson never graduates. Search the
95
+ file before you invent one. Then let the counting be mechanical:
96
+
97
+ ```bash
98
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/mistakes.mjs" repeats
99
+ ```
100
+
101
+ It prints one line per signature that has crossed a graduation threshold,
102
+ ending in what that signature has earned. Act on that recommendation — the
103
+ thresholds themselves, and why they are where they are, live in
104
+ `docs/self-improvement.md`.
105
+
106
+ - **`promote to .tyran/knowledge/`** — write the rule into
107
+ `.tyran/knowledge/<topic>.yaml`, scoped with `applies_to` so it reaches only
108
+ the agents it helps:
109
+
110
+ ```yaml
111
+ entries:
112
+ - id: K-12
113
+ kind: gotcha
114
+ text: 'Link the dependency directory into every new worktree before the handoff.'
115
+ confidence: 0.8
116
+ provenance:
117
+ - source: MISTAKES.md
118
+ reference: 'worktree-missing-deps — the open entries that earned it'
119
+ used: 0
120
+ helpful: 0
121
+ outdated_reports: 0
122
+ applies_to:
123
+ - 'scripts/**'
124
+ ```
125
+
126
+ `provenance` is a block sequence, never a flow mapping: `yaml-lite` refuses
127
+ `[{...}]`, and a knowledge file it cannot parse reaches no handoff at all.
128
+ Then `mistakes.mjs promote --signature <sig> --status knowledge:<id>`. Grep
129
+ `.tyran/knowledge/` for the signature first: an entry already carrying it
130
+ means this was promoted before and the status trailers were hand-edited away.
131
+ - **`promote to CLAUDE.md law` — it kept happening after the knowledge entry
132
+ shipped.** That is evidence the delivered rule was not enough, which is the
133
+ strongest case for law there is. Write it:
134
+
135
+ ```bash
136
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/mistakes.mjs" promote --signature <sig> \
137
+ --law --rule 'One imperative sentence.' --journal "$J" --init "$INIT"
138
+ ```
139
+
140
+ That edits the host `CLAUDE.md` between `<!-- tyran:rules start -->` and
141
+ `<!-- tyran:rules end -->` and no byte outside it, appends a `decision` event
142
+ naming the rule, the signature and the count, and refuses below the law
143
+ threshold or on a fence it cannot parse. `--dry-run` prints the line and
144
+ writes nothing. You do not wait for an approval: the operator meets the
145
+ change in the journal, the board and the diff, and says no by deleting the
146
+ line — a deleted rule does not come back.
147
+
148
+ Promotion never deletes an entry; it rewrites one status token. The entry is
149
+ the evidence that earned the rule. Nothing to add is a correct outcome here
150
+ too, and a common one: most initiatives break nothing that recurs.
151
+
152
+ ## 5. Report
74
153
 
75
154
  Five lines: candidates considered, implemented, rejected and why, what was
76
155
  deleted or merged, what is left for next time. Rejections are as valuable as
@@ -186,7 +186,12 @@ open one.
186
186
  - **Scout `DURABLE:` findings, you journal** as `finding` events — the
187
187
  required keys are `area` + `claim` (the area is the path or subsystem the
188
188
  scout's proof points at), plus that `proof` — scouts write nothing
189
- themselves. Implementers and reviewers append their own.
189
+ themselves. Implementers and reviewers append their own. An operator
190
+ CORRECTION — a premise you had wrong, a step they had to undo — is a
191
+ `finding` too, with `area: process`: it is the densest mistake signal
192
+ there is, and the retrospective is where it becomes a `MISTAKES.md`
193
+ entry. A correction that lives only in the chat log dies at the next
194
+ compaction.
190
195
  2. **Fresh context per task.** Handoffs are SELF-CONTAINED; the agent
191
196
  disappears afterwards. Never ask the operator to compact. **Every handoff
192
197
  carries eight things:** (1) the role and one story, one goal; (2) paths to
@@ -278,12 +283,33 @@ open one.
278
283
  (XL); product, visual and irreversible decisions, put in plain language
279
284
  with your recommendation; anything hard to undo or visible outside the
280
285
  repo. **"Shall I continue?" is forbidden.**
281
- **Every question to the operator lands in the journal before (or as) you
282
- ask it**: a `gate` event, `result: WAITING_ON_OPERATOR`, `data` carrying
283
- `question`, `recommendation`, `default` and `ticket` when it has one — a
284
- question that lives only in chat has to be re-litigated after every
285
- compaction. When answered, append the same `kind` with `result: answered`
286
- plus a `decision` recording the answer in the operator's words.
286
+ **Every question to the operator is raised with one command, and the
287
+ command mints its id:**
288
+ `node ${CLAUDE_PLUGIN_ROOT}/scripts/journal.mjs ask <abs-journal> <init>
289
+ --question '...' --recommendation '...' --default '...' [--ticket T-n]`.
290
+ It appends the `gate` — `kind: Q-<n>`, `result: WAITING_ON_OPERATOR` —
291
+ under the journal's write lock, so two agents asking in the same moment get
292
+ two ids rather than one. A question that lives only in chat has to be
293
+ re-litigated after every compaction; a question written as a bare `kind` of
294
+ your own invention collides with the next one that shares it, and the older
295
+ question is lost with nothing objecting anywhere.
296
+ - **Always record a `default`** — what ships if nobody ever answers. It is
297
+ what the operator accepts by leaving an answer blank, and it is the only
298
+ reason a queue of fifteen questions takes ten minutes instead of an hour.
299
+ An ask with no default is a question the operator must stop and think
300
+ about; spend that budget deliberately.
301
+ - **Do not park an asked ticket.** An ask that names a ticket already puts
302
+ it in the board's `waiting-operator` lane. A `ticket.status` override on
303
+ top of it **overrules** that lane and hides the question's own ticket —
304
+ measured in our own demo fixture, which showed `waiting-operator (0)`
305
+ while a question was open.
306
+ - **Never spin on an open ask.** Raise it, take the next schedulable
307
+ ticket, and let the operator answer in their own time. You do not close
308
+ it: `node ${CLAUDE_PLUGIN_ROOT}/scripts/answer.mjs apply` writes the
309
+ `decision` and the closing `gate` in the operator's own words. When the
310
+ operator answers you in chat instead, append that pair yourself — same
311
+ `kind`, `result: answered`, plus a `decision` whose text begins
312
+ `Q-<n>: ` — and say in your next report that you did.
287
313
  **Check the brake before every spawn and every merge:**
288
314
  `node ${CLAUDE_PLUGIN_ROOT}/scripts/stop-check.mjs` — exit 1 means the
289
315
  operator created `.tyran/STOP`. Halt, report where you got to, and do not
@@ -34,6 +34,13 @@ ever creates, never overwrites, and what it writes is the strictest template
34
34
  Tyran ships. Editing that file afterwards is human-only and stays so — the
35
35
  gate refuses `Write`, `Edit`, and any shell command that names the path.
36
36
 
37
+ It also seeds `MISTAKES.md` at the repository root: the durable record of what
38
+ has gone wrong here, which `/tyran:retro` appends to at close and reads before
39
+ it proposes anything. Create-only like the policy — and deleting it is the
40
+ whole opt-out, so a repository that does not want one simply removes it. Say
41
+ in your report that it appeared; a file landing in someone's working tree
42
+ unannounced is a bad way to meet a tool.
43
+
37
44
  If you find a repository already in the broken state — `.tyran/` present, no
38
45
  policy — this repairs it without touching anything else:
39
46
 
@@ -70,6 +77,19 @@ is a `staging` branch with CI. That looks like P2 — I release to staging on
70
77
  my own, production stays yours. Confirm, or say P1 and I only ever touch
71
78
  branches."
72
79
 
80
+ One flagged question is the `CLAUDE.md` pointer, and it is a question rather
81
+ than an edit on purpose. Tyran writes `CLAUDE.md` only inside its own
82
+ `tyran:rules` fence, and only through `mistakes.mjs promote --law`, which
83
+ demands five recorded occurrences of one signature; this line lives outside
84
+ that fence, so it is theirs to paste:
85
+
86
+ ```
87
+ Log mistakes in MISTAKES.md (what happened, root cause, prevention).
88
+ ```
89
+
90
+ That single line is what makes ordinary sessions — the ones Tyran does not
91
+ conduct at all — contribute evidence. Do not write it yourself.
92
+
73
93
  ## 4. Install the bare `/tyran` shortcut
74
94
 
75
95
  Plugin skills are namespaced, so the conductor is `/tyran:run`. Most people
@@ -115,9 +135,15 @@ End by asking for one commit of `.tyran/`. This is not tidiness, and the
115
135
  reason is the one failure mode of this whole setup that is **silent**:
116
136
 
117
137
  ```bash
118
- git add .tyran && git commit -m "chore: adopt Tyran"
138
+ git add .tyran
139
+ git add MISTAKES.md 2>/dev/null || true # absent if they took the opt-out
140
+ git commit -m "chore: adopt Tyran"
119
141
  ```
120
142
 
143
+ Two `git add` calls, not one: `git add` is atomic on an unmatched pathspec, so
144
+ naming a deleted `MISTAKES.md` alongside `.tyran` aborts the whole staging and
145
+ `&&` then eats the commit — the silent failure this step exists to prevent.
146
+
121
147
  The scan also seeded `.tyran/.gitignore` (excluding `state/*/locks/`), so this
122
148
  `git add` stays clean: lease files record who holds a resource RIGHT NOW, and a
123
149
  committed lease conflicts on every parallel merge. Commit the `.gitignore`
@@ -0,0 +1,39 @@
1
+ # Mistakes
2
+
3
+ What has gone wrong in this repository, what caused it, and what prevents it
4
+ next time. **Newest first.** This file is prose, not a generated artefact —
5
+ edit it by hand whenever a root cause here is wrong. Nothing overwrites it.
6
+
7
+ Every entry has the same five bullets:
8
+
9
+ ## <YYYY-MM-DD> — <one line: what broke, in a reader's words>
10
+
11
+ - **What happened:** the observable failure, not the diagnosis.
12
+ - **Root cause:** the mechanism. "I forgot" is not a root cause.
13
+ - **Consequence:** what it cost — time, a rework wave, a bad merge.
14
+ - **Prevention:** the rule that would have stopped it, imperative.
15
+ - **Signature:** `kebab-case-slug` · initiative `<slug>` · actor `<who>` · proof `<F-n>` · status `open`
16
+
17
+ The **signature** is what makes this more than a diary. Three entries under
18
+ one signature are evidence that a rule is missing, and the count is what
19
+ earns it:
20
+
21
+ node "${CLAUDE_PLUGIN_ROOT}/scripts/mistakes.mjs" repeats --threshold 3
22
+
23
+ Reuse an existing signature rather than inventing a near-synonym — a synonym
24
+ resets the count to one and the lesson never graduates.
25
+
26
+ **Status moves one way and never back.** `open` → `knowledge:<id>` (the rule
27
+ now ships in every handoff that touches those paths) → `law` (a rule Tyran
28
+ wrote into this repository's `CLAUDE.md`, inside its fence, once the failure
29
+ had recurred five times). Promotion never deletes an entry: the entry is the
30
+ evidence, and deleting it destroys the count that earned the rule. Disagree
31
+ with a promoted rule by deleting its line from the fence; it does not come
32
+ back.
33
+
34
+ If this repository has a `CLAUDE.md`, one line there closes the loop for
35
+ sessions that are not conducted by Tyran at all:
36
+
37
+ Log mistakes in MISTAKES.md (what happened, root cause, prevention).
38
+
39
+ <!-- entries below, newest first -->