@jjanczur/tyran 0.1.8 → 0.1.10

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.
@@ -508,6 +508,74 @@ export function ensureAutonomyPolicy(repoRoot, { templatePath = policyTemplatePa
508
508
  return { path, status: 'created' };
509
509
  }
510
510
 
511
+ export const STATE_GITIGNORE_PATH = '.tyran/.gitignore';
512
+ export const STATE_GITIGNORE_LINES = Object.freeze([
513
+ 'state/*/locks/',
514
+ 'state/paused-until.json',
515
+ 'state/resume.json',
516
+ 'state/resume.log',
517
+ 'state/usage.json',
518
+ ]);
519
+ const STATE_GITIGNORE_BODY =
520
+ '# Runtime files, never history. Leases record who holds a worktree or a\n' +
521
+ '# heavy slot RIGHT NOW; committing one makes every parallel merge conflict\n' +
522
+ '# on state that was stale the moment it was written. The overnight files\n' +
523
+ '# are machine-local by nature: another clone has a different watcher pid,\n' +
524
+ '# a different telemetry stream, and no business inheriting this one\'s pause.\n' +
525
+ `${STATE_GITIGNORE_LINES.join('\n')}\n`;
526
+
527
+ /**
528
+ * Seed `.tyran/.gitignore` excluding runtime files. A nested gitignore rather
529
+ * than a line in the host's, because `.tyran/` is committed and travels into
530
+ * every worktree — the exclusion has to travel with it. An existing file gains
531
+ * any managed line it lacks, APPENDED at the end (matched by exact trimmed
532
+ * line): create-only seeding left every 0.1.9 install without the overnight
533
+ * exclusions, and the wind-down checklist's `git add .tyran/state` then
534
+ * committed a machine-local pause marker that every clone inherited. Existing
535
+ * content — operator additions included — is never reordered or rewritten,
536
+ * and a `!`-negated managed line is an operator decision this never reverses.
537
+ * Returns `{ path, status: 'created' | 'updated' | 'present' | 'unreadable' }`.
538
+ */
539
+ export function ensureStateGitignore(repoRoot) {
540
+ const root = resolve(repoRoot);
541
+ const path = join(root, ...STATE_GITIGNORE_PATH.split('/'));
542
+ if (existsSync(path)) {
543
+ let existing;
544
+ try {
545
+ existing = readFileSync(path, 'utf8');
546
+ } catch {
547
+ // A directory or unreadable file at this path is the operator's to
548
+ // resolve; crashing the scan over an ignore nicety helps nobody.
549
+ return { path, status: 'unreadable' };
550
+ }
551
+ const have = new Set(existing.split('\n').map((line) => line.trim()));
552
+ // `!line` is the operator explicitly TRACKING that file; appending the
553
+ // plain line after it would win by last-match and silently reverse them.
554
+ const missing = STATE_GITIGNORE_LINES.filter((line) => !have.has(line) && !have.has(`!${line}`));
555
+ if (missing.length === 0) return { path, status: 'present' };
556
+ try {
557
+ const glue = existing === '' || existing.endsWith('\n') ? '' : '\n';
558
+ writeFileSync(path, `${existing}${glue}${missing.join('\n')}\n`);
559
+ } catch (error) {
560
+ throw new BootstrapError(
561
+ `could not write ${escapeInvisible(path)}: ${error.message}`,
562
+ 'check the directory permissions; re-running this command is safe',
563
+ );
564
+ }
565
+ return { path, status: 'updated' };
566
+ }
567
+ try {
568
+ mkdirSync(dirname(path), { recursive: true });
569
+ writeFileSync(path, STATE_GITIGNORE_BODY);
570
+ } catch (error) {
571
+ throw new BootstrapError(
572
+ `could not write ${escapeInvisible(path)}: ${error.message}`,
573
+ 'check the directory permissions; re-running this command is safe',
574
+ );
575
+ }
576
+ return { path, status: 'created' };
577
+ }
578
+
511
579
  function main() {
512
580
  const args = process.argv.slice(2);
513
581
  const flag = (name, fallback) => {
@@ -531,6 +599,7 @@ function main() {
531
599
  ? `scan-repo: created ${escapeInvisible(seeded.path)} from the shipped template`
532
600
  : `scan-repo: ${escapeInvisible(seeded.path)} already exists — left untouched`,
533
601
  );
602
+ reportStateGitignore(seedStateGitignore(dir));
534
603
  return;
535
604
  }
536
605
 
@@ -547,6 +616,7 @@ function main() {
547
616
  if (seeded.status === 'created') {
548
617
  console.error(`scan-repo: created ${escapeInvisible(seeded.path)} from the shipped template`);
549
618
  }
619
+ reportStateGitignore(seedStateGitignore(dir));
550
620
  }
551
621
  try {
552
622
  mkdirSync(dirname(path), { recursive: true });
@@ -572,6 +642,34 @@ function seedPolicy(dir) {
572
642
  }
573
643
  }
574
644
 
645
+ /** A silent line only when nothing changed — every other shape is reported. */
646
+ function reportStateGitignore({ path, status }) {
647
+ if (status === 'created') {
648
+ console.error(`scan-repo: created ${escapeInvisible(path)} (lease files stay out of history)`);
649
+ } else if (status === 'updated') {
650
+ console.error(`scan-repo: updated ${escapeInvisible(path)} (appended missing runtime exclusions)`);
651
+ } else if (status === 'unreadable') {
652
+ console.error(`scan-repo: could not read ${escapeInvisible(path)} — runtime exclusions were NOT updated`);
653
+ }
654
+ }
655
+
656
+ /**
657
+ * `ensureStateGitignore`, with a BootstrapError turned into exit 2. Both call
658
+ * sites run this AFTER `seedPolicy` on purpose: it creates `.tyran/` when
659
+ * absent, and `.tyran/` without a policy under it is the state that refuses
660
+ * every subsequent write.
661
+ */
662
+ function seedStateGitignore(dir) {
663
+ try {
664
+ return ensureStateGitignore(dir);
665
+ } catch (error) {
666
+ if (!(error instanceof BootstrapError)) throw error;
667
+ console.error(`scan-repo: ${error.message}`);
668
+ console.error(`scan-repo: ${error.remedy}`);
669
+ process.exit(2);
670
+ }
671
+ }
672
+
575
673
  function canonicalPath(path) {
576
674
  const abs = resolve(path);
577
675
  try {
@@ -68,7 +68,7 @@ export function validateConfig(doc) {
68
68
  const errors = [];
69
69
  if (!isPlainObject(doc)) return ['config must be a mapping'];
70
70
 
71
- const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths'];
71
+ const known = ['profile', 'autonomy', 'tiers', 'validation', 'shared_zones', 'budget', 'main_writable_paths', 'limits'];
72
72
  for (const key of Object.keys(doc)) {
73
73
  if (!known.includes(key)) errors.push(`${key}: unknown top-level key`);
74
74
  }
@@ -145,9 +145,70 @@ export function validateConfig(doc) {
145
145
  }
146
146
  }
147
147
 
148
+ // Overnight mode: usage-limit pause/resume. Optional; absent = feature off.
149
+ // Operator-written policy, never scanner-inferred — no provenance wrapper.
150
+ if ('limits' in doc) {
151
+ if (!isPlainObject(doc.limits)) errors.push('limits: must be a mapping');
152
+ else {
153
+ const limits = doc.limits;
154
+ if (!LIMITS_MODES.includes(limits.mode)) {
155
+ errors.push(`limits.mode: required, one of ${LIMITS_MODES.join(' | ')}`);
156
+ }
157
+ // Floor of 50 catches the classic footgun: 0.97 (a fraction pasted where
158
+ // a percent belongs) would otherwise pause on the first tool call of
159
+ // every session.
160
+ for (const key of ['pause_at_percent', 'weekly_pause_at_percent']) {
161
+ if (key in limits && (typeof limits[key] !== 'number' || limits[key] < 50 || limits[key] > 100)) {
162
+ errors.push(`limits.${key}: must be a number in [50, 100]`);
163
+ }
164
+ }
165
+ if ('wait_max_hours' in limits && (typeof limits.wait_max_hours !== 'number' || limits.wait_max_hours <= 0 || limits.wait_max_hours > 24)) {
166
+ errors.push('limits.wait_max_hours: must be a number in (0, 24]');
167
+ }
168
+ if ('long_wait' in limits && !LIMITS_LONG_WAIT.includes(limits.long_wait)) {
169
+ errors.push(`limits.long_wait: must be one of ${LIMITS_LONG_WAIT.join(' | ')}`);
170
+ }
171
+ if ('resume_margin_minutes' in limits && (typeof limits.resume_margin_minutes !== 'number' || limits.resume_margin_minutes <= 0 || limits.resume_margin_minutes > 240)) {
172
+ errors.push('limits.resume_margin_minutes: must be a number in (0, 240]');
173
+ }
174
+ const knownLimits = ['mode', 'pause_at_percent', 'weekly_pause_at_percent', 'wait_max_hours', 'long_wait', 'resume_margin_minutes'];
175
+ for (const key of Object.keys(limits)) {
176
+ if (!knownLimits.includes(key)) errors.push(`limits.${key}: unknown key`);
177
+ }
178
+ }
179
+ }
180
+
148
181
  return errors;
149
182
  }
150
183
 
184
+ export const LIMITS_MODES = Object.freeze(['off', 'warn', 'pause']);
185
+ export const LIMITS_LONG_WAIT = Object.freeze(['hold', 'resume']);
186
+
187
+ /**
188
+ * The limits block with defaults applied — the ONE place the defaults AND the
189
+ * accepted ranges live. `doc` is a parsed config (or null); an absent or
190
+ * invalid block is `off`. A value outside validateConfig's range is treated
191
+ * as absent (the default applies): the gate must never ENFORCE a value the
192
+ * schema rejects — `pause_at_percent: 0.97` enforced verbatim is a permanent
193
+ * false pause, the exact footgun the validator's floor of 50 exists to catch.
194
+ */
195
+ export function limitsOf(doc) {
196
+ const limits = isPlainObject(doc) && isPlainObject(doc.limits) ? doc.limits : {};
197
+ const mode = LIMITS_MODES.includes(limits.mode) ? limits.mode : 'off';
198
+ const inRange = (value, min, max, { minExclusive = false } = {}) =>
199
+ typeof value === 'number' && Number.isFinite(value) && (minExclusive ? value > min : value >= min) && value <= max;
200
+ return {
201
+ mode,
202
+ pause_at_percent: inRange(limits.pause_at_percent, 50, 100) ? limits.pause_at_percent : 97,
203
+ weekly_pause_at_percent:
204
+ inRange(limits.weekly_pause_at_percent, 50, 100) ? limits.weekly_pause_at_percent : 97,
205
+ wait_max_hours: inRange(limits.wait_max_hours, 0, 24, { minExclusive: true }) ? limits.wait_max_hours : 5,
206
+ long_wait: LIMITS_LONG_WAIT.includes(limits.long_wait) ? limits.long_wait : 'hold',
207
+ resume_margin_minutes:
208
+ inRange(limits.resume_margin_minutes, 0, 240, { minExclusive: true }) ? limits.resume_margin_minutes : 5,
209
+ };
210
+ }
211
+
151
212
  /**
152
213
  * Validate a knowledge file: `entries:` list of learned facts.
153
214
  * Schema adapted from the best pattern found in the wild (metaswarm):
@@ -203,6 +264,36 @@ export function validateKnowledge(doc) {
203
264
  return errors;
204
265
  }
205
266
 
267
+ /**
268
+ * The size above which a knowledge entry stops being a brief-able fact and
269
+ * starts being a document. `knowledge.mjs brief` selects entries into a
270
+ * character budget; one 10 KB entry crowds out eight useful ones, visibly.
271
+ */
272
+ export const KNOWLEDGE_ENTRY_MAX_CHARS = 4000;
273
+
274
+ /**
275
+ * Advisory findings on a knowledge file that already validates. A separate
276
+ * export rather than more `validateKnowledge` errors on purpose: a warning
277
+ * must never flip `ok` for the existing consumers (validateFile, doctor, CI
278
+ * template validation), or every install with one wordy entry goes red.
279
+ */
280
+ export function knowledgeWarnings(doc) {
281
+ if (!isPlainObject(doc) || !Array.isArray(doc.entries)) return [];
282
+ const warnings = [];
283
+ doc.entries.forEach((entry, i) => {
284
+ if (!isPlainObject(entry) || typeof entry.text !== 'string') return;
285
+ const size = Array.from(entry.text).length;
286
+ if (size > KNOWLEDGE_ENTRY_MAX_CHARS) {
287
+ const id = isNonEmptyString(entry.id) ? entry.id : `entries[${i}]`;
288
+ warnings.push(
289
+ `${id}: text is ${size} characters (max ${KNOWLEDGE_ENTRY_MAX_CHARS} before it crowds a brief) — ` +
290
+ 'split it, or move the bulk into a doc and keep the pointer here',
291
+ );
292
+ }
293
+ });
294
+ return warnings;
295
+ }
296
+
206
297
  /**
207
298
  * Paths that MUST be classified KERNEL. A policy that downgrades any of
208
299
  * these would let the self-improvement loop disable its own enforcement,
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * statusline — tees the platform's rate-limit telemetry into the sidecar the
4
+ * usage gate reads.
5
+ *
6
+ * Measured on Claude Code 2.1.197: the PreToolUse hook payload does NOT carry
7
+ * `rate_limits` (recorded in hooks/HOOK-CONTRACT-MEASURED.md), so the ONLY
8
+ * place a session's subscription usage is programmatically visible is the
9
+ * statusline JSON — which a plugin cannot install; the operator registers this
10
+ * command in their user settings (`/tyran:setup` prints the snippet). Each
11
+ * time the statusline fires, this writes `.tyran/state/usage.json`
12
+ * atomically; the usage gate treats a sidecar older than its staleness window
13
+ * as absent and fails open.
14
+ *
15
+ * Trust boundary: the payload is platform-produced but this writer is
16
+ * deliberately a filter, not a copier — ONLY finite numbers and a
17
+ * shape-validated session id reach the sidecar, never free strings, so
18
+ * nothing downstream has to sanitize what it reads back.
19
+ *
20
+ * A statusline is a UI element: it must never break the UI. Every failure
21
+ * path exits 0, silently. `--sidecar-only` prints nothing at all, so an
22
+ * operator with an existing statusline can tee the platform's JSON payload
23
+ * into this writer BEFORE their own statusline consumes it:
24
+ * tee >(node .../statusline.mjs --sidecar-only) | existing-statusline.sh
25
+ * The order matters: this writer parses the platform payload, and what an
26
+ * existing statusline emits is a rendered display line, not JSON — teeing
27
+ * after it would silently never update the sidecar.
28
+ *
29
+ * CLI: node statusline.mjs [--sidecar-only] # payload on stdin
30
+ * Exit: always 0
31
+ */
32
+ import { existsSync, mkdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
33
+ import { join, resolve } from 'node:path';
34
+
35
+ export const SIDECAR_RELPATH = join('.tyran', 'state', 'usage.json');
36
+ const MAX_INPUT_BYTES = 1024 * 1024;
37
+ const SESSION_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
38
+
39
+ /** Own-property read on a prototype-free view of foreign JSON. */
40
+ function field(obj, name) {
41
+ return obj !== null && typeof obj === 'object' && Object.prototype.hasOwnProperty.call(obj, name)
42
+ ? obj[name]
43
+ : undefined;
44
+ }
45
+
46
+ function finiteNumber(value) {
47
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
48
+ }
49
+
50
+ /** One rate-limit window ({used_percentage, resets_at}) — numbers only. */
51
+ function windowOf(node) {
52
+ if (node === null || typeof node !== 'object') return null;
53
+ const used = finiteNumber(field(node, 'used_percentage'));
54
+ const resets = finiteNumber(field(node, 'resets_at'));
55
+ if (used === null && resets === null) return null;
56
+ const out = {};
57
+ if (used !== null) out.used_percentage = used;
58
+ if (resets !== null) out.resets_at = resets;
59
+ return out;
60
+ }
61
+
62
+ /**
63
+ * The sidecar document, or null when the payload carries nothing usable.
64
+ * `now` is injected so tests are deterministic.
65
+ */
66
+ export function sidecarOf(payload, nowIso) {
67
+ if (payload === null || typeof payload !== 'object') return null;
68
+ const limits = field(payload, 'rate_limits');
69
+ const fiveHour = windowOf(field(limits, 'five_hour'));
70
+ const sevenDay = windowOf(field(limits, 'seven_day'));
71
+ if (fiveHour === null && sevenDay === null) return null;
72
+ const doc = { written_at: nowIso };
73
+ const sessionId = field(payload, 'session_id');
74
+ if (typeof sessionId === 'string' && SESSION_ID_RE.test(sessionId)) doc.session_id = sessionId;
75
+ if (fiveHour !== null) doc.five_hour = fiveHour;
76
+ if (sevenDay !== null) doc.seven_day = sevenDay;
77
+ return doc;
78
+ }
79
+
80
+ /** Where the repo is, per the payload; last resort is the process cwd. */
81
+ export function repoRootOf(payload, cwd = process.cwd()) {
82
+ const workspace = field(payload, 'workspace');
83
+ for (const candidate of [field(workspace, 'project_dir'), field(workspace, 'current_dir'), field(payload, 'cwd')]) {
84
+ if (typeof candidate === 'string' && candidate !== '' && existsSync(candidate)) return candidate;
85
+ }
86
+ return cwd;
87
+ }
88
+
89
+ /** Atomic create-or-replace: temp in the same directory, then rename. */
90
+ export function writeSidecar(root, doc) {
91
+ const target = join(resolve(root), SIDECAR_RELPATH);
92
+ const dir = join(resolve(root), '.tyran', 'state');
93
+ if (!existsSync(join(resolve(root), '.tyran'))) return false; // not a Tyran repo — write nothing
94
+ mkdirSync(dir, { recursive: true });
95
+ const temp = join(dir, `.usage-${process.pid}.tmp`);
96
+ writeFileSync(temp, JSON.stringify(doc, null, 2) + '\n');
97
+ renameSync(temp, target);
98
+ return true;
99
+ }
100
+
101
+ /** The one visible line. Only numbers formatted here — nothing foreign. */
102
+ export function statusLineOf(doc) {
103
+ const parts = [];
104
+ const fmt = (label, w) => {
105
+ if (!w) return;
106
+ let text = `${label}`;
107
+ if (typeof w.used_percentage === 'number') text += ` ${Math.round(w.used_percentage)}%`;
108
+ if (typeof w.resets_at === 'number') {
109
+ const at = new Date(w.resets_at * 1000);
110
+ if (!Number.isNaN(at.getTime())) {
111
+ text += ` resets ${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`;
112
+ }
113
+ }
114
+ parts.push(text);
115
+ };
116
+ fmt('5h', doc.five_hour);
117
+ fmt('7d', doc.seven_day);
118
+ return parts.join(' · ');
119
+ }
120
+
121
+ async function readStdin(limit = MAX_INPUT_BYTES) {
122
+ const chunks = [];
123
+ let size = 0;
124
+ for await (const chunk of process.stdin) {
125
+ size += chunk.length;
126
+ if (size > limit) return null;
127
+ chunks.push(chunk);
128
+ }
129
+ return Buffer.concat(chunks).toString('utf8');
130
+ }
131
+
132
+ async function main() {
133
+ const sidecarOnly = process.argv.includes('--sidecar-only');
134
+ try {
135
+ const raw = await readStdin();
136
+ if (raw === null) return;
137
+ const payload = JSON.parse(raw);
138
+ const doc = sidecarOf(payload, new Date().toISOString());
139
+ if (doc === null) return;
140
+ writeSidecar(repoRootOf(payload), doc);
141
+ if (!sidecarOnly) process.stdout.write(statusLineOf(doc) + '\n');
142
+ } catch {
143
+ // A statusline that breaks the UI is worse than one that says nothing.
144
+ }
145
+ }
146
+
147
+ import { fileURLToPath } from 'node:url';
148
+ import { realpathSync } from 'node:fs';
149
+ function canonicalPath(path) {
150
+ const abs = resolve(path);
151
+ try {
152
+ return realpathSync(abs);
153
+ } catch {
154
+ return abs;
155
+ }
156
+ }
157
+ function isMainModule(moduleUrl) {
158
+ if (!process.argv[1]) return false;
159
+ return canonicalPath(process.argv[1]) === canonicalPath(fileURLToPath(moduleUrl));
160
+ }
161
+ if (isMainModule(import.meta.url)) await main();
@@ -58,6 +58,14 @@ confidence, its provenance, and the paths it applies to. The counters
58
58
  retire an entry that stopped earning its keep — knowledge that only ever
59
59
  grows is a context tax with a good story attached.
60
60
 
61
+ **Fold the counters from the agents' reports.** Every handoff carried a
62
+ knowledge brief with entry ids, and every report owes a verdict on them.
63
+ Increment `used` for each id that was handed off, `helpful` for the ids
64
+ reported as having helped, `outdated_reports` for the ids reported wrong —
65
+ here, at close, in the one place licensed to write these files. Keep entries
66
+ under the size `doctor --state` warns about (`knowledge-entry-oversized`,
67
+ 4 000 codepoints); an oversized entry crowds every brief it matches.
68
+
61
69
  Write what a competent newcomer would get wrong, not what the code already
62
70
  says. "The test suite takes 9 minutes, so do not run it per file" is worth an
63
71
  entry. "This is a Next.js app" is not: the next agent can see that.
@@ -166,7 +166,7 @@ open one.
166
166
  chasing you instead of reading reports.
167
167
  2. **Fresh context per task.** Handoffs are SELF-CONTAINED; the agent
168
168
  disappears afterwards. Never ask the operator to compact. **Every handoff
169
- carries seven things:** (1) the role and one story, one goal; (2) paths to
169
+ carries eight things:** (1) the role and one story, one goal; (2) paths to
170
170
  the files of record; (3) the iron rules copied VERBATIM, not linked;
171
171
  (4) the lease protocol (rule 7); (5) the **evidence contract** — the report
172
172
  must contain raw command output (exit codes, `X passed / Y failed`); a
@@ -185,7 +185,12 @@ open one.
185
185
  premises of this handoff in the code — and
186
186
  premises about DATA by measuring the real thing read-only: a field being in
187
187
  the schema is not the same as the field being in the data. Correct a wrong
188
- premise and report the correction EXPLICITLY"; (7) when to escalate.
188
+ premise and report the correction EXPLICITLY"; (7) when to escalate;
189
+ (8) the **knowledge brief** — the output of
190
+ `node "${CLAUDE_PLUGIN_ROOT}/scripts/knowledge.mjs" brief <files the story will touch>`
191
+ pasted VERBATIM, entry ids included. The report owes a verdict on those ids
192
+ — helped, wrong, or unused — which the retrospective folds into the
193
+ entries' counters.
189
194
  3. **Quality gates.** Review is done by an agent who is NOT the author — when
190
195
  that is impossible (a limit, an outage), you spot-check AND the ledger
191
196
  carries an explicit **"NO INDEPENDENT REVIEW"** stamp; staying quiet about
@@ -305,13 +310,17 @@ open one.
305
310
  Siblings of the checkout (`../<repo>-<slug>`) sidestep it, whatever
306
311
  convention the repo already had.
307
312
  - **Leases are files.** Every worktree and every heavy slot has
308
- `.tyran/initiatives/<slug>/locks/<resource>.lease` holding holder,
309
- purpose, story and expiry. A handoff BEGINS by taking the lease — an
310
- existing unexpired lease means the agent refuses to start and reports —
311
- and ENDS by releasing it. Assigning slots from your own memory is
312
- forbidden: the lead's memory is the least reliable store in the system.
313
+ `.tyran/state/<slug>/locks/<resource>.lease` holding holder,
314
+ purpose, story and expiry — covered by the `.tyran/state/**` AUTO rule,
315
+ kept out of history by `.tyran/.gitignore`. An install adopted before
316
+ 0.1.9 has no such file — seed it before the first merge commit with
317
+ `node ${CLAUDE_PLUGIN_ROOT}/scripts/scan-repo.mjs --dir . --ensure-policy`
318
+ (create-only; it never overwrites an operator's own). A handoff BEGINS by taking the
319
+ lease — an existing unexpired lease means the agent refuses to start and
320
+ reports — and ENDS by releasing it. Assigning slots from your own memory
321
+ is forbidden: the lead's memory is the least reliable store in the system.
313
322
  If the policy gate refuses the lease write — an install whose repo-local
314
- `autonomy.yaml` predates the `locks/**` AUTO rule — fall back to
323
+ `autonomy.yaml` predates that rule — fall back to
315
324
  `lease.acquired`/`lease.released` events in the journal, same holder,
316
325
  purpose and expiry, conductor-written, rather than working unleased.
317
326
  - **Preflight a heavy slot** on acquisition: check free disk against a
@@ -364,3 +373,12 @@ open one.
364
373
  a lease still held by an agent that has already reported. An orphaned lease
365
374
  blocks the next initiative from a resource nobody is using, and the person
366
375
  who hits it has no way to know it is stale.
376
+ - **A usage-gate refusal is a wind-down order, not an obstacle.** Near the
377
+ subscription window the gate refuses everything except checkpointing;
378
+ its refusal text IS the checklist — follow it verbatim, in order, then
379
+ stop. Never route around the allowlist: the point of pausing at 97% is
380
+ that the last 3% pays for a clean checkpoint instead of a corpse. The
381
+ scheduler resumes the session after the reset (or notifies and holds on a
382
+ long, weekly-shaped wait — `docs/overnight.md`); a resumed session starts
383
+ from the `usage-limit-pause` checkpoint and first closes the open
384
+ usage-limit gate with `result: passed`.
@@ -118,6 +118,11 @@ reason is the one failure mode of this whole setup that is **silent**:
118
118
  git add .tyran && git commit -m "chore: adopt Tyran"
119
119
  ```
120
120
 
121
+ The scan also seeded `.tyran/.gitignore` (excluding `state/*/locks/`), so this
122
+ `git add` stays clean: lease files record who holds a resource RIGHT NOW, and a
123
+ committed lease conflicts on every parallel merge. Commit the `.gitignore`
124
+ with the rest.
125
+
121
126
  `git worktree add` does not carry untracked files. Tyran's parallel model is
122
127
  worktrees, so an uncommitted `.tyran/` means every worktree the conductor
123
128
  creates has no config and no policy — and a repo with no `.tyran/` is a repo
@@ -130,3 +135,23 @@ Until it is committed there is a second hazard worth naming in your report: an
130
135
  agent that runs `git add -A` on a story branch sweeps the untracked `.tyran/`
131
136
  into that branch, and a four-way parallel run ends with four conflicting
132
137
  copies of the config. Stage explicit paths until this commit exists.
138
+
139
+ ## 7. Offer overnight mode — and say plainly what the operator must do
140
+
141
+ Overnight mode (`docs/overnight.md`) pauses autonomous work near the
142
+ subscription usage limit and resumes after the window resets. It is OFF by
143
+ default because its telemetry is a statusline the plugin cannot install:
144
+ `.claude/settings.json` in user scope is the operator's file, and the policy
145
+ gate refuses agents writing the in-repo one — so print the snippet with the
146
+ plugin path RESOLVED and let the human paste it:
147
+
148
+ ```json
149
+ { "statusLine": { "type": "command",
150
+ "command": "node <resolved-plugin-root>/scripts/statusline.mjs" } }
151
+ ```
152
+
153
+ Then show the `limits:` block to enable (`mode: 'pause'` — quoted, bare
154
+ `off`/`on` are YAML booleans) and note that `doctor --state` reports
155
+ `limit-telemetry-missing` if the pause is configured while the statusline is
156
+ not installed. Do not attempt the settings write yourself; the refusal is
157
+ the boundary working.
@@ -15,14 +15,18 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/journal.mjs" open-spawns "$J"
15
15
 
16
16
  Then report, in this order and no longer than a screen:
17
17
 
18
- 1. The progress line: `PROGRESS: NN% · X/Y tickets · phase: <name> · last merge: <sha>`.
19
- 2. **Agents with no report yet** — the ones from `open-spawns`. Say how long
18
+ 1. If `.tyran/state/paused-until.json` exists, the pause comes FIRST: which
19
+ window, when it resumes, and `node "${CLAUDE_PLUGIN_ROOT}/scripts/overnight.mjs" status`
20
+ output. Everything below it is context for a session that is deliberately
21
+ not working.
22
+ 2. The progress line: `PROGRESS: NN% · X/Y tickets · phase: <name> · last merge: <sha>`.
23
+ 3. **Agents with no report yet** — the ones from `open-spawns`. Say how long
20
24
  each has been open. An agent that has been running for an hour is the most
21
25
  useful thing on this screen and the easiest to overlook.
22
- 3. Open gates, and who is waiting on whom.
23
- 4. Any lease released by someone who did not hold it. The projection surfaces
26
+ 4. Open gates, and who is waiting on whom.
27
+ 5. Any lease released by someone who did not hold it. The projection surfaces
24
28
  these; they mean two agents believed they owned the same worktree.
25
- 5. The resume steps from the last checkpoint.
29
+ 6. The resume steps from the last checkpoint.
26
30
 
27
31
  If there is no journal, say exactly that and suggest `/tyran:setup`. Do not
28
32
  reconstruct a status from the git log — a plausible status is worse than none,
@@ -42,3 +42,23 @@ validation:
42
42
 
43
43
  # Files multiple agents may touch: append-only, serialized by the conductor.
44
44
  shared_zones: []
45
+
46
+ # Overnight mode — pause autonomous work near the subscription usage limits
47
+ # and resume after the window resets (docs/overnight.md). Requires the
48
+ # operator-installed statusline helper (scripts/statusline.mjs), which is the
49
+ # only place the platform exposes usage telemetry; without it the gate is
50
+ # silent and doctor says so.
51
+ #
52
+ # mode: off | warn | pause warn surfaces, never denies; pause winds down
53
+ # wait_max_hours: 5 reset further away than this = a LONG pause:
54
+ # notify and hold rather than silently waiting
55
+ # days (the weekly window). Within it: schedule
56
+ # the resume and say when.
57
+ # long_wait: hold | resume what the scheduler does beyond wait_max_hours
58
+ limits:
59
+ mode: 'off' # quoted — bare off is YAML for false
60
+ pause_at_percent: 97
61
+ weekly_pause_at_percent: 97
62
+ wait_max_hours: 5
63
+ long_wait: hold
64
+ resume_margin_minutes: 5
@@ -28,31 +28,27 @@ rules:
28
28
  class: AUTO
29
29
  reason: repo-specific skills, gated by a passing activation test
30
30
 
31
+ # This rule also covers the lease files at `.tyran/state/<slug>/locks/`.
32
+ # Leases are runtime, never history: `.tyran/.gitignore` (seeded by
33
+ # scan-repo.mjs) excludes `state/*/locks/`, so the blast radius of a bad
34
+ # write is a stale lock file, cleared by deleting it.
31
35
  - path: .tyran/state/**
32
36
  class: AUTO
33
37
  reason: the execution journal is append-only and written by the conductor itself
34
38
 
35
- # Measured on a real initiative: iron rule 7 says "a handoff BEGINS by taking
36
- # the lease" and ENDS by releasing it — but leases live under
37
- # `.tyran/initiatives/<slug>/locks/`, which matched NO rule here, so it fell
38
- # through to `default: GATED`. A subagent is ALWAYS unsupervised, and
39
- # `verdictForClass(GATED, unsupervised)` denies unconditionally. So the lease
40
- # protocol the conductor skill mandates could not be satisfied by any
41
- # implementer, in any repo, under the shipped template — the agent either
42
- # reported the refusal (correct, and what happened) or quietly worked without
43
- # the lease, which is the failure mode leases exist to prevent. The conductor
44
- # had to write every lease itself, which puts the record of who holds a
45
- # resource in the one place iron rule 7 says it must not live: the lead.
46
- #
47
- # AUTO is the safe class here precisely because these are not history: the
48
- # repo's own .gitignore excludes `.tyran/initiatives/*/locks/`, so nothing
49
- # under it is version-controlled and the blast radius of a bad write is a
50
- # stale lock file, cleared by deleting it. Scoped to `locks/` deliberately
51
- # rather than all of `.tyran/initiatives/**`, so anything else that comes to
52
- # live under an initiative keeps the stricter default.
39
+ # LEGACY ALIAS, kept 2026-08 for installs adopted at <= 0.1.8, whose leases
40
+ # live under `.tyran/initiatives/<slug>/locks/`. The canonical layout since
41
+ # 0.1.9 is `.tyran/state/<slug>/locks/`, covered by the `.tyran/state/**`
42
+ # rule above; `doctor --state` reports a leftover `.tyran/initiatives/`
43
+ # directory. The measured incident that produced this rule: leases matched
44
+ # NO rule, fell through to `default: GATED`, and `verdictForClass(GATED,
45
+ # unsupervised)` denies unconditionally — so no implementer in any repo
46
+ # could satisfy the take-your-own-lease protocol of iron rule 7, and the
47
+ # conductor had to write every lease itself, putting the record of who
48
+ # holds a resource in the one place rule 7 says it must not live: the lead.
53
49
  - path: .tyran/initiatives/*/locks/**
54
50
  class: AUTO
55
- reason: runtime worktree and heavy-slot leases, gitignored and not history; GATED denies every subagent unconditionally, which makes the take-your-own-lease protocol of iron rule 7 unsatisfiable
51
+ reason: legacy lease location for installs adopted at <= 0.1.8; GATED denies every subagent unconditionally, which makes the take-your-own-lease protocol of iron rule 7 unsatisfiable
56
52
 
57
53
  # Was GATED. The cost was measured on a real install: setup had inferred
58
54
  # `pnpm test`, which in that repo is bare `vitest` — it never exits, so every