@jjanczur/tyran 0.1.13 → 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.
@@ -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,14 @@
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 { withKeepAwake } from './keepawake.mjs';
59
62
  import { limitsOf } from './schema.mjs';
60
63
  import { parse } from './yaml-lite.mjs';
61
64
  import { escapeInvisible } from './invisible.mjs';
@@ -281,6 +284,58 @@ function readLimitsFile(repo) {
281
284
  }
282
285
  }
283
286
 
287
+ /**
288
+ * Run ONE resume attempt to completion without blocking the event loop.
289
+ *
290
+ * `spawnSync` is the shorter shape and must not be used: a sync child parks
291
+ * the loop for the whole attempt — up to RESUME_ATTEMPT_TIMEOUT_MS, four
292
+ * times over — and no JS signal handler can run while it is parked. Two
293
+ * things depend on those handlers: `cancel`, the operator's documented
294
+ * handle, SIGTERMs the watcher and expects it to die; and keepawake's release
295
+ * runs from the same handler, so a sender that escalates to SIGKILL past its
296
+ * grace period orphans the inhibitor. Both are measured, in overnight.test.
297
+ *
298
+ * Resolves, never rejects: a missing binary arrives asynchronously as an
299
+ * 'error' event, and an unheard 'error' event is thrown from outside any
300
+ * try/catch the caller could have. Its `status: null` reads as "did not
301
+ * take", which is the babysitter's business, not an exception's.
302
+ */
303
+ export function runResume(argv, { cwd, timeoutMs = RESUME_ATTEMPT_TIMEOUT_MS, spawnFn = spawn } = {}) {
304
+ return new Promise((resolve) => {
305
+ let child;
306
+ try {
307
+ child = spawnFn(argv[0], argv.slice(1), {
308
+ cwd,
309
+ // Never a pipe: the output was captured and discarded before, and a
310
+ // buffered pipe would cap a long resume at maxBuffer instead.
311
+ stdio: 'ignore',
312
+ // The argv is the whole command. No shell, ever.
313
+ shell: false,
314
+ });
315
+ } catch {
316
+ resolve({ status: null, signal: null });
317
+ return;
318
+ }
319
+ let settled = false;
320
+ let timer = null;
321
+ const finish = (result) => {
322
+ if (settled) return;
323
+ settled = true;
324
+ if (timer !== null) clearTimeout(timer);
325
+ resolve(result);
326
+ };
327
+ timer = setTimeout(() => {
328
+ try {
329
+ child.kill('SIGTERM');
330
+ } catch {
331
+ /* it finished between the timer firing and this line */
332
+ }
333
+ }, timeoutMs);
334
+ child.on('error', () => finish({ status: null, signal: null }));
335
+ child.on('exit', (status, signal) => finish({ status, signal }));
336
+ });
337
+ }
338
+
284
339
  // ------------------------------------------------------------ subcommands
285
340
 
286
341
  function doSchedule(repo, flags) {
@@ -325,6 +380,19 @@ function doSchedule(repo, flags) {
325
380
  process.exit(1);
326
381
  }
327
382
 
383
+ // A warning, never a refusal: the operator is about to leave a machine
384
+ // waiting for hours, and whether it stays awake is their call to make with
385
+ // the risk named. Only on the watch path — a hold waits for nothing.
386
+ if (readLimitsFile(repo).keep_awake === true) {
387
+ console.log('overnight: keep-awake is on — the system stays awake while the watcher waits (the display and the screen lock are untouched).');
388
+ } else {
389
+ console.error(
390
+ 'overnight: keep-awake is OFF — if this machine sleeps before the reset, the watcher sleeps with it and the ' +
391
+ 'resume fires late or never. Set limits.keep_awake: true in .tyran/config.yaml to hold the SYSTEM awake ' +
392
+ 'while it waits; the display and the screen lock are untouched.',
393
+ );
394
+ }
395
+
328
396
  const logFd = openSync(join(repo, RESUME_LOG_RELPATH), 'a');
329
397
  const watcherArgv = [
330
398
  SELF,
@@ -366,6 +434,23 @@ async function doWait(repo, flags) {
366
434
  const prompt = typeof flags.prompt === 'string' ? flags.prompt : null;
367
435
  const cmd = typeof flags.cmd === 'string' ? flags.cmd : 'claude';
368
436
 
437
+ // The whole point of this process is to be asleep for hours, and a laptop
438
+ // that suspends during that window is the measured way an overnight run
439
+ // dies. The wrap covers the resume too: the resumed `claude -p` IS the
440
+ // overnight work, and a machine that suspends mid-session kills it.
441
+ //
442
+ // Opt-in, and released on every exit path including SIGTERM — which is what
443
+ // `cancel` sends. That release runs from a JS signal handler, so NOTHING
444
+ // inside this region may block the event loop: a sync child would defer the
445
+ // handler for its whole runtime and make `cancel` a no-op meanwhile. Hence
446
+ // runResume rather than spawnSync.
447
+ return withKeepAwake(
448
+ { enabled: readLimitsFile(repo).keep_awake === true, onNote: (message) => log(repo, message) },
449
+ () => runWaitLoop(repo, { chunkMs, backoffs, prompt, cmd }),
450
+ );
451
+ }
452
+
453
+ async function runWaitLoop(repo, { chunkMs, backoffs, prompt, cmd }) {
369
454
  for (;;) {
370
455
  const marker = readSmallJson(join(repo, MARKER_RELPATH));
371
456
  if (marker === null) {
@@ -455,7 +540,7 @@ async function doWait(repo, flags) {
455
540
  log(repo, `resuming attempt=${attempt + 1} argv=${argv[0]} session=${marker.session_id}`);
456
541
  writeStateFile(repo, { state: 'resuming', attempt: attempt + 1, at: new Date().toISOString() });
457
542
  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 });
543
+ const child = await runResume(argv, { cwd: repo });
459
544
  const eventsAfter = journalEventCount(journalPath);
460
545
  const took =
461
546
  eventsBefore === null || eventsAfter === null
@@ -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/',
@@ -600,6 +680,7 @@ function main() {
600
680
  : `scan-repo: ${escapeInvisible(seeded.path)} already exists — left untouched`,
601
681
  );
602
682
  reportStateGitignore(seedStateGitignore(dir));
683
+ reportMistakes(ensureMistakesFile(dir));
603
684
  return;
604
685
  }
605
686
 
@@ -618,6 +699,9 @@ function main() {
618
699
  }
619
700
  reportStateGitignore(seedStateGitignore(dir));
620
701
  }
702
+ // Unconditional, unlike the two above: MISTAKES.md is not under `.tyran/`,
703
+ // so `underTyranDir` has nothing to say about whether it should exist.
704
+ reportMistakes(ensureMistakesFile(dir));
621
705
  try {
622
706
  mkdirSync(dirname(path), { recursive: true });
623
707
  writeFileSync(path, renderConfig(result.config));
@@ -653,6 +737,22 @@ function reportStateGitignore({ path, status }) {
653
737
  }
654
738
  }
655
739
 
740
+ /**
741
+ * A file landing in someone's working tree unannounced is a bad way to meet a
742
+ * tool, and a file that FAILED to land silently is worse: the repository would
743
+ * simply never learn anything and nothing would say why.
744
+ */
745
+ function reportMistakes({ path, status, error }) {
746
+ if (status === 'created') {
747
+ console.error(
748
+ `scan-repo: created ${escapeInvisible(path)} — the repository's incident log ` +
749
+ '(delete it if you do not want one)',
750
+ );
751
+ } else if (status === 'failed') {
752
+ console.error(`scan-repo: could not create ${escapeInvisible(path)} (${escapeInvisible(String(error))}) — the scan continues`);
753
+ }
754
+ }
755
+
656
756
  /**
657
757
  * `ensureStateGitignore`, with a BootstrapError turned into exit 2. Both call
658
758
  * 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
 
@@ -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
@@ -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 -->
@@ -55,6 +55,10 @@ shared_zones: []
55
55
  # days (the weekly window). Within it: schedule
56
56
  # the resume and say when.
57
57
  # long_wait: hold | resume what the scheduler does beyond wait_max_hours
58
+ # keep_awake: false true holds the SYSTEM awake while the resume
59
+ # watcher waits — a laptop that suspends takes
60
+ # the watcher with it. Never the display: your
61
+ # screen lock is untouched.
58
62
  limits:
59
63
  mode: 'off' # quoted — bare off is YAML for false
60
64
  pause_at_percent: 97
@@ -62,3 +66,4 @@ limits:
62
66
  wait_max_hours: 5
63
67
  long_wait: hold
64
68
  resume_margin_minutes: 5
69
+ keep_awake: false # a real boolean, so the bare-off trap above cannot apply
@@ -70,6 +70,24 @@ rules:
70
70
  class: GATED
71
71
  reason: overriding a core agent freezes it at the version it was copied from
72
72
 
73
+ # Operator-owned prose, loaded into every session in this repository. The
74
+ # gate is otherwise SILENT at the repo root — the governed prefixes are
75
+ # `.tyran/`, `.claude/` and the enforcement-script directory, and a root file
76
+ # matches none of them — so without this rule a subagent could rewrite the law
77
+ # it is bound by and no gate would have an opinion. An explicit rule outranks
78
+ # the prefix test, which is why one line here is enough.
79
+ #
80
+ # It bans the HAND, not the mechanism. GATED denies a subagent
81
+ # unconditionally, so no agent free-hand rewrites this file with Write or
82
+ # Edit; `scripts/mistakes.mjs promote --law` still passes, because it is a
83
+ # Bash command and a repo-root file is not in the shell-protected globs.
84
+ # That asymmetry is the design: the law changes only through the mechanism
85
+ # that requires evidence — five recorded occurrences of one signature — and
86
+ # it changes only inside the `tyran:rules` fence.
87
+ - path: CLAUDE.md
88
+ class: GATED
89
+ reason: operator-owned prose loaded into every session; only mistakes.mjs writes it, and only inside its fence
90
+
73
91
  - path: .tyran/STOP
74
92
  class: KERNEL
75
93
  reason: the brake an operator uses to halt a running initiative; a loop that can clear its own stop signal has none