@jjanczur/tyran 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,7 +11,7 @@
11
11
  {
12
12
  "name": "tyran",
13
13
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
14
- "version": "0.1.8",
14
+ "version": "0.1.9",
15
15
  "source": "./",
16
16
  "author": {
17
17
  "name": "Jacek Janczura",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tyran",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "A task conductor for Claude Code: multi-agent orchestration with an enforced evidence contract, repo-specific learning, and update-safe local evolution.",
5
5
  "author": {
6
6
  "name": "Jacek Janczura",
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.9 — 2026-08-13
4
+
5
+ ### One layout for an initiative's files
6
+
7
+ The core disagreed with itself about where an initiative's files live:
8
+ `agents/retro.md` read `PLAN.md`/`NOTES.md` and wrote `RETRO.md` under
9
+ `.tyran/initiatives/<slug>/`, and iron rule 7 put leases there too — while
10
+ every mechanical consumer (journal, projections, doctor, the hooks) reads
11
+ `.tyran/state/<slug>/`, which is also where real installs put those files.
12
+ Everything now names `state/`; leases move to `.tyran/state/<slug>/locks/`,
13
+ already covered by the `.tyran/state/**` AUTO rule. The template keeps the
14
+ `.tyran/initiatives/*/locks/**` rule as a dated legacy alias for installs
15
+ adopted at ≤ 0.1.8, and `doctor --state` reports a leftover legacy directory
16
+ (`state-legacy-initiatives-dir`).
17
+
18
+ Because `state/` is committed and leases must not be, `scan-repo` (and so
19
+ `/tyran:setup`) now seeds a create-only `.tyran/.gitignore` excluding
20
+ `state/*/locks/`, and doctor warns when lease files are tracked anyway
21
+ (`lease-file-tracked`).
22
+
23
+ ### The knowledge store gets its missing reader
24
+
25
+ `.tyran/knowledge/` had a writer (the retrospective), a schema, and no
26
+ reader — the loop was write-only, and the measured cost was a 137 KB store
27
+ nothing consumed. `scripts/knowledge.mjs brief` (also `npx @jjanczur/tyran
28
+ knowledge brief`) selects entries whose `applies_to` globs intersect a
29
+ story's predicted files, ranks by confidence, cuts to a character budget
30
+ with an explicit omission line, and prints a block the conductor pastes
31
+ verbatim into a handoff — item (8) of the handoff contract. Reports owe a
32
+ verdict on the entry ids they received; the retrospective folds the verdicts
33
+ into the `used`/`helpful`/`outdated_reports` counters at close. Oversized
34
+ entries (over 4 000 characters) now draw a `knowledge-entry-oversized`
35
+ doctor warning, because one document-sized entry crowds out every other
36
+ entry a budgeted brief would have carried.
37
+
3
38
  ## 0.1.8 — 2026-08-08
4
39
 
5
40
  ### The secrets gate scanned everything except what the command published
package/README.md CHANGED
@@ -253,7 +253,11 @@ echo "wrong branch — hold everything" > .tyran/STOP
253
253
  tunes Tyran's own playbook, through an anti-bloat filter with four
254
254
  questions, a hard cap of three edits per retrospective, and a stated
255
255
  preference for deleting rules over adding them — so *"I changed nothing"*
256
- is a correct outcome, and so is declining the retro entirely. **You are
256
+ is a correct outcome, and so is declining the retro entirely. What was
257
+ learned reaches the agent that needs it: every handoff carries a budgeted
258
+ **knowledge brief** of the entries that apply to the files at hand, and
259
+ each agent's report grades the entries it received, so the store is
260
+ pruned on evidence. **You are
257
261
  never blocked twice**, whichever you choose. This is a gate rather than a
258
262
  sentence in a skill because the retro is the step most easily skipped: it
259
263
  happens after the merge, when the interesting part is over.
@@ -355,9 +359,9 @@ Published on npm as [`@jjanczur/tyran`](https://www.npmjs.com/package/@jjanczur/
355
359
  command stays `tyran` either way; only the registry name is scoped, the same
356
360
  pattern as `@angular/cli` giving you `ng`. `bin/tyran.mjs` exposes the same
357
361
  scripts the plugin's hooks and skills already call — `doctor`, `scan-repo`,
358
- `tiers`, `journal`, `schema`, `stop-check`, `scan-control-chars`,
359
- `desc-budget` — for a shell or a CI job with no Claude Code session. Zero
360
- dependencies; `--help` lists them.
362
+ `tiers`, `journal`, `schema`, `knowledge`, `stop-check`,
363
+ `scan-control-chars`, `desc-budget` — for a shell or a CI job with no Claude
364
+ Code session. Zero dependencies; `--help` lists them.
361
365
 
362
366
  ```bash
363
367
  npx @jjanczur/tyran doctor --hooks # is any gate installed but unable to fire?
@@ -55,6 +55,8 @@ commits and anything written to disk are in English.**
55
55
  after a `git fetch` run immediately beforehand; a stale remote once
56
56
  turned a correct proof into a false accusation.
57
57
  7. **Final report:** what was done · test and validation output · what the
58
- optimization pass changed · branch or PR · premises you corrected · open
59
- doubts. The open doubts are worth more than the summary; do not tidy them
60
- away.
58
+ optimization pass changed · branch or PR · premises you corrected · a
59
+ verdict on every knowledge-brief entry id in your handoff (helped, wrong,
60
+ or unused — the retrospective folds these into the store's counters) ·
61
+ open doubts. The open doubts are worth more than the summary; do not tidy
62
+ them away.
package/agents/retro.md CHANGED
@@ -12,7 +12,7 @@ to disk is in English.**
12
12
 
13
13
  ## Inputs, in this order
14
14
 
15
- 1. `.tyran/initiatives/<slug>/PLAN.md` (the ledger — what went smoothly, what
15
+ 1. `.tyran/state/<slug>/PLAN.md` (the ledger — what went smoothly, what
16
16
  came back) and `NOTES.md` (decisions, deviations, the agents' signals about
17
17
  the process itself).
18
18
  2. The agents' reports from this initiative: corrected premises, escalations,
@@ -64,6 +64,12 @@ next retro relitigating the same idea.
64
64
  - **Scripts and harnesses** worth reusing — gates, comparators, probes,
65
65
  report generators. A one-off harness from an initiative either becomes a
66
66
  general tool or gets deleted; do not leave dead files behind.
67
+ - **Knowledge upkeep:** fold the reports' knowledge-brief verdicts into the
68
+ entries' counters (the fold procedure lives in `skills/retro/SKILL.md`,
69
+ step 3 — one home, not two), and retire or split entries
70
+ `doctor --state` flags as `knowledge-entry-oversized`. An entry whose
71
+ counters say it stopped earning its keep is a deletion candidate, which
72
+ satisfies the deletion preference.
67
73
  - **Documentation that pays forward:** the repo's detected configuration,
68
74
  protocols, runbooks. **Every initiative should leave the repo better
69
75
  described than it found it** — that is the part that makes each next
@@ -78,7 +84,7 @@ behaviour visible to users of the product.
78
84
  ## Product
79
85
 
80
86
  1. The implemented changes — surgical, each with its reason.
81
- 2. `.tyran/initiatives/<slug>/RETRO.md`: what worked (keep it) · what failed
87
+ 2. `.tyran/state/<slug>/RETRO.md`: what worked (keep it) · what failed
82
88
  (with the cost) · **implemented** · **rejected and why** · candidates for
83
89
  later.
84
90
  3. A five-line report for the conductor: candidates, implemented, rejected,
package/bin/tyran.mjs CHANGED
@@ -68,6 +68,10 @@ export const COMMANDS = {
68
68
  'schema.mjs',
69
69
  'Validate .tyran/ config, knowledge, and policy files against their schemas.',
70
70
  ],
71
+ knowledge: [
72
+ 'knowledge.mjs',
73
+ 'Select the knowledge entries that apply to a set of paths and print a paste-ready brief for a handoff.',
74
+ ],
71
75
  'stop-check': [
72
76
  'stop-check.mjs',
73
77
  'Check the .tyran/STOP operator brake that halts a running initiative before its next spawn or merge.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jjanczur/tyran",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "Command-line scripts for the Tyran task conductor (doctor, journal, schema, and repo tooling) for CI and terminals outside Claude Code. Installing this package does NOT install the Claude Code plugin — add that separately with `/plugin marketplace add jjanczur/tyran` inside Claude Code.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -36,7 +36,7 @@
36
36
  * dead writes no state to be inconsistent with.
37
37
  */
38
38
  import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
39
- import { join, dirname, resolve } from 'node:path';
39
+ import { join, dirname, resolve, basename } from 'node:path';
40
40
  import { fileURLToPath } from 'node:url';
41
41
  import { checkHooks, DEFAULT_PLUGIN_ROOT } from './hooks-check.mjs';
42
42
  import { readJournal, validateJournal, pairSpawns, tail } from './journal.mjs';
@@ -48,7 +48,7 @@ import {
48
48
  PROGRESS_FILE,
49
49
  STATE_FILE,
50
50
  } from './project.mjs';
51
- import { classifyPath, normalizePath, validateFile, MANDATORY_KERNEL_PATHS } from './schema.mjs';
51
+ import { classifyPath, normalizePath, validateFile, knowledgeWarnings, MANDATORY_KERNEL_PATHS } from './schema.mjs';
52
52
  import { gitRunner } from './scan-repo.mjs';
53
53
 
54
54
  /** Severity order is also the report order. `info` never fails the check. */
@@ -176,6 +176,7 @@ export const SEVERITY_BY_CODE = Object.freeze(
176
176
  'knowledge-invalid': 'error',
177
177
  'knowledge-unreadable': 'error',
178
178
  'knowledge-not-a-directory': 'warning',
179
+ 'knowledge-entry-oversized': 'warning',
179
180
  // Not `info`, which is what it was: with `.tyran/` on disk and no policy
180
181
  // under it the gate refuses every write in the repository. A severity that
181
182
  // does not fail the check reports a locked-out repo as a note.
@@ -193,6 +194,8 @@ export const SEVERITY_BY_CODE = Object.freeze(
193
194
  'state-not-a-directory': 'error',
194
195
  'state-unreadable': 'error',
195
196
  'state-stray-file': 'warning',
197
+ 'state-legacy-initiatives-dir': 'warning',
198
+ 'lease-file-tracked': 'warning',
196
199
  }),
197
200
  );
198
201
 
@@ -1001,12 +1004,31 @@ function policyFindings(path, repoRoot) {
1001
1004
  * evidence that a file is untracked, and reporting it as such would fire on
1002
1005
  * every temp directory and every fresh `git init`.
1003
1006
  */
1004
- export function untrackedTyranDir(repoRoot, run) {
1007
+ export function untrackedTyranDir(repoRoot, run, tyranDirName = '.tyran') {
1005
1008
  if (run(['rev-parse', '--is-inside-work-tree']).trim() !== 'true') return null;
1006
1009
  // `ls-files` over the directory: any tracked file under it means the tree
1007
1010
  // travels with a worktree, which is the property being checked. Asking about
1008
1011
  // config.yaml alone would pass a repo that committed only the policy.
1009
- return run(['ls-files', '--', '.tyran']).trim() === '';
1012
+ // The pathspec is parameterized the same way trackedLeaseFiles' is, so a
1013
+ // --dir naming anything but `.tyran` cannot make the two checks contradict
1014
+ // each other about what git tracks.
1015
+ return run(['ls-files', '--', tyranDirName]).trim() === '';
1016
+ }
1017
+
1018
+ /**
1019
+ * Lease files committed to git. A lease records who holds a worktree or a
1020
+ * heavy slot RIGHT NOW; committing one makes every parallel merge conflict on
1021
+ * state that was stale the moment it was written, and a checkout resurrects
1022
+ * it as a phantom holder. Filtered in JS rather than via a wildcard pathspec
1023
+ * — git's pathspec globbing is exactly the kind of subtlety this tool exists
1024
+ * to not depend on. Returns [] when git cannot answer: "not a git repository"
1025
+ * is not evidence that a lease is tracked.
1026
+ */
1027
+ export function trackedLeaseFiles(run, tyranDirName = '.tyran') {
1028
+ const listing = run(['ls-files', '--', tyranDirName]);
1029
+ if (listing === '') return [];
1030
+ const lease = /\/(?:state|initiatives)\/[^/]+\/locks\//;
1031
+ return listing.split('\n').filter((line) => line !== '' && lease.test(line));
1010
1032
  }
1011
1033
 
1012
1034
  export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAULT_STALE_HOURS, run = null } = {}) {
@@ -1038,7 +1060,8 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1038
1060
  checked.push('config.yaml: absent');
1039
1061
  }
1040
1062
 
1041
- const untracked = untrackedTyranDir(repoRoot, run ?? gitRunner(repoRoot));
1063
+ const gitRun = run ?? gitRunner(repoRoot);
1064
+ const untracked = untrackedTyranDir(repoRoot, gitRun, basename(root));
1042
1065
  if (untracked === true) {
1043
1066
  findings.push(
1044
1067
  finding(
@@ -1055,7 +1078,22 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1055
1078
 
1056
1079
  const knowledge = yamlFilesIn(join(dir, 'knowledge'), 'knowledge');
1057
1080
  findings.push(...knowledge.findings);
1058
- for (const file of knowledge.files) findings.push(...checkSchemaFile('knowledge', file).findings);
1081
+ for (const file of knowledge.files) {
1082
+ const schemaResult = checkSchemaFile('knowledge', file);
1083
+ findings.push(...schemaResult.findings);
1084
+ // Advisory, on files that already validate: an oversized entry is legal,
1085
+ // it just crowds every budgeted brief it appears in.
1086
+ for (const warning of knowledgeWarnings(schemaResult.doc)) {
1087
+ findings.push(
1088
+ finding(
1089
+ 'knowledge-entry-oversized',
1090
+ show(file),
1091
+ warning,
1092
+ `node scripts/knowledge.mjs brief '**' --dir ${sq(join(dir, 'knowledge'))} # shows what a budgeted brief keeps`,
1093
+ ),
1094
+ );
1095
+ }
1096
+ }
1059
1097
  checked.push(`knowledge/: ${knowledge.files.length} file(s)`);
1060
1098
 
1061
1099
  const policies = yamlFilesIn(join(dir, 'policies'), 'policies');
@@ -1110,6 +1148,36 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1110
1148
  initiatives.length === 0 ? 'state/: no initiatives' : `state/: ${initiatives.join(', ')}`,
1111
1149
  );
1112
1150
 
1151
+ const legacyDir = join(dir, 'initiatives');
1152
+ if (isDirectory(legacyDir)) {
1153
+ findings.push(
1154
+ finding(
1155
+ 'state-legacy-initiatives-dir',
1156
+ show(legacyDir),
1157
+ 'legacy layout — initiative files (PLAN.md, NOTES.md, RETRO.md, locks/) live under ' +
1158
+ 'state/<initiative>/ since 0.1.9. Mechanical consumers read only state/, so anything ' +
1159
+ 'kept here is invisible to the projections, the retrospective and the session summary',
1160
+ `ls -la ${sq(legacyDir)} # relocate the contents by hand, one initiative directory at a time, into ${sq(join(dir, 'state'))} — see docs/journal.md`,
1161
+ ),
1162
+ );
1163
+ }
1164
+ checked.push(`initiatives/ (legacy): ${isDirectory(legacyDir) ? 'PRESENT' : 'absent'}`);
1165
+
1166
+ const trackedLeases = trackedLeaseFiles(gitRun, basename(root));
1167
+ if (trackedLeases.length > 0) {
1168
+ findings.push(
1169
+ finding(
1170
+ 'lease-file-tracked',
1171
+ show(trackedLeases[0]) + (trackedLeases.length > 1 ? ` (+${trackedLeases.length - 1} more)` : ''),
1172
+ `${trackedLeases.length} lease file(s) committed to git — a lease records who holds a resource ` +
1173
+ 'RIGHT NOW, so a committed one conflicts on every parallel merge and resurrects as a phantom ' +
1174
+ 'holder on every checkout',
1175
+ `git ls-files -- ${sq(basename(root))} # list them; keep 'state/*/locks/' in .tyran/.gitignore and un-track the files by hand — see docs/configuration.md`,
1176
+ ),
1177
+ );
1178
+ }
1179
+ checked.push(`lease files tracked by git: ${trackedLeases.length}`);
1180
+
1113
1181
  return summarize(dir, findings, checked);
1114
1182
  }
1115
1183
 
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * knowledge — the READER for `.tyran/knowledge/`.
4
+ *
5
+ * The knowledge store had a writer (the retrospective) and a schema, and no
6
+ * reader: nothing put a learned fact in front of the agent about to need it,
7
+ * so the loop was write-only and the file grew without pressure. Measured on
8
+ * a real install: 137 KB, 31 entries, and the largest single entry 13 KB —
9
+ * nothing that size can be pasted into a handoff, so in practice nothing was.
10
+ *
11
+ * `brief` closes the loop: select the entries whose `applies_to` globs
12
+ * intersect the paths a story is about to touch (`ticket.created`'s
13
+ * `files_predicted` is the intended source), rank by confidence, cut to a
14
+ * character budget, and print a Markdown block ready to paste VERBATIM into a
15
+ * handoff. Entry ids are part of the output on purpose — the agent's report
16
+ * owes a verdict on them (helped / wrong / unused), which is what the
17
+ * retrospective folds into the `used`/`helpful`/`outdated_reports` counters.
18
+ *
19
+ * The budget is the design, not a safety valve: it is the pressure that keeps
20
+ * entries scoped. An entry with `applies_to: ['**']` and a page of prose
21
+ * crowds out eight useful ones, VISIBLY — and the omission line names the
22
+ * cost. Omission is never silent.
23
+ *
24
+ * Selection is symmetric on purpose: `applies_to` holds globs and the inputs
25
+ * are often globs too (`files_predicted` may say `src/lib/**`), so an entry
26
+ * matches when either side's glob matches the other side as a literal. One
27
+ * line of generosity instead of a second glob engine.
28
+ *
29
+ * CLI:
30
+ * node knowledge.mjs brief [<path>...] [--dir .tyran/knowledge]
31
+ * [--kinds fact,convention,gotcha,command,decision]
32
+ * [--limit N] [--budget CHARS] [--json]
33
+ * Exit: 0 briefed (including "no matches") · 1 invalid knowledge file · 2 usage/IO
34
+ */
35
+ import { existsSync, readdirSync, statSync, realpathSync } from 'node:fs';
36
+ import { join, resolve } from 'node:path';
37
+ import { fileURLToPath } from 'node:url';
38
+ import { validateFile, globMatches, normalizePath, KNOWLEDGE_KINDS } from './schema.mjs';
39
+ import { escapeInvisible, jsonEscapeInvisible } from './invisible.mjs';
40
+
41
+ export const DEFAULT_DIR = join('.tyran', 'knowledge');
42
+ export const DEFAULT_BUDGET = 4000;
43
+
44
+ class UsageError extends Error {}
45
+
46
+ /** Untrusted YAML value on its way into a terminal or a handoff: one line, visible. */
47
+ function clean(value) {
48
+ return escapeInvisible(String(value)).replace(/\s+/g, ' ').trim();
49
+ }
50
+
51
+ /** The knowledge files of a directory, sorted for determinism. */
52
+ export function knowledgeFiles(dir) {
53
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return [];
54
+ return readdirSync(dir)
55
+ .filter((name) => /\.ya?ml$/i.test(name))
56
+ .sort()
57
+ .map((name) => join(dir, name));
58
+ }
59
+
60
+ /**
61
+ * Load every entry of every knowledge file, or report the files that fail
62
+ * validation. Returns `{entries, invalid}` where `invalid` is
63
+ * `[{file, errors}]` — an invalid file is a LOUD result, never a silent skip:
64
+ * a brief that quietly dropped a file would read as "nothing to know".
65
+ */
66
+ export function loadEntries(dir) {
67
+ const entries = [];
68
+ const invalid = [];
69
+ for (const file of knowledgeFiles(dir)) {
70
+ const result = validateFile('knowledge', file);
71
+ if (!result.ok) {
72
+ invalid.push({ file, errors: result.errors });
73
+ continue;
74
+ }
75
+ for (const entry of result.doc.entries) entries.push({ ...entry, file });
76
+ }
77
+ return { entries, invalid };
78
+ }
79
+
80
+ /** Does this entry apply to any of the given repo paths? */
81
+ export function entryMatches(entry, paths) {
82
+ const globs = Array.isArray(entry.applies_to) ? entry.applies_to.filter((g) => typeof g === 'string') : [];
83
+ if (globs.length === 0) return true; // no applies_to = repo-global by schema
84
+ return globs.some((glob) => paths.some((path) => globMatches(glob, path) || globMatches(path, glob)));
85
+ }
86
+
87
+ /**
88
+ * Select and rank: kind filter, path intersection, confidence descending with
89
+ * file order breaking ties. No clock and no randomness — the same store and
90
+ * the same paths produce the same brief, byte for byte.
91
+ */
92
+ export function selectEntries(entries, { paths = [], kinds = null, limit = Infinity } = {}) {
93
+ const ranked = entries
94
+ .map((entry, index) => ({ entry, index }))
95
+ .filter(({ entry }) => kinds === null || kinds.includes(entry.kind))
96
+ .filter(({ entry }) => (paths.length === 0 ? !Array.isArray(entry.applies_to) || entry.applies_to.length === 0 : entryMatches(entry, paths)))
97
+ .sort((a, b) => (b.entry.confidence - a.entry.confidence) || (a.index - b.index))
98
+ .map(({ entry }) => entry);
99
+ const selected = ranked.slice(0, Math.max(0, limit));
100
+ return { selected, matched: ranked.length, limited: ranked.length - selected.length };
101
+ }
102
+
103
+ function entryLine(entry) {
104
+ const applies = Array.isArray(entry.applies_to) && entry.applies_to.length > 0
105
+ ? ` _(applies to: ${entry.applies_to.map(clean).join(', ')})_`
106
+ : '';
107
+ return `- **[${clean(entry.id)}]** (${clean(entry.kind)}, ${entry.confidence}) ${clean(entry.text)}${applies}`;
108
+ }
109
+
110
+ /**
111
+ * The paste-ready Markdown block. Entries are cut at `budget` characters;
112
+ * anything cut — by budget or by `--limit` — is counted in an explicit
113
+ * trailing line. `matched` is the pre-limit match count.
114
+ */
115
+ export function renderBrief(selected, matched, { budget = DEFAULT_BUDGET, dir = DEFAULT_DIR, limited = 0 } = {}) {
116
+ if (matched === 0) return `### Knowledge brief (${clean(dir)}) — no matching entries\n`;
117
+ const lines = [];
118
+ let used = 0;
119
+ let kept = 0;
120
+ for (const entry of selected) {
121
+ const line = entryLine(entry);
122
+ // Budget is charged in CODEPOINTS, the same unit knowledgeWarnings
123
+ // measures entries in — an oversize warning that predicted a different
124
+ // quantity than the budget spends would under-measure exactly the thing
125
+ // it exists to predict.
126
+ const cost = Array.from(line).length + 1;
127
+ if (used + cost > budget && kept > 0) break;
128
+ lines.push(line);
129
+ used += cost;
130
+ kept += 1;
131
+ }
132
+ const header = `### Knowledge brief (${clean(dir)}, ${kept} of ${matched} entr${matched === 1 ? 'y' : 'ies'})`;
133
+ const byBudget = selected.length - kept;
134
+ const parts = [];
135
+ // Each cut names its own remedy — an omission line telling the reader to
136
+ // raise a budget that did not do the cutting is a remedy that cannot work.
137
+ if (limited > 0) parts.push(`${limited} by --limit`);
138
+ if (byBudget > 0) parts.push(`${byBudget} by the ${budget}-codepoint budget`);
139
+ const omitted = matched - kept;
140
+ const tail = omitted > 0
141
+ ? [`_${omitted} matching entr${omitted === 1 ? 'y' : 'ies'} omitted (${parts.join(', ')}) — ${limited > 0 ? 'raise --limit' : 'raise --budget'} or narrow the paths._`]
142
+ : [];
143
+ return [header, ...lines, ...tail].join('\n') + '\n';
144
+ }
145
+
146
+ // ---------------------------------------------------------------- CLI
147
+
148
+ const VALUE_FLAGS = ['dir', 'kinds', 'limit', 'budget'];
149
+ const BOOLEAN_FLAGS = ['json'];
150
+
151
+ function parseArgs(argv) {
152
+ const flags = { dir: DEFAULT_DIR, kinds: null, limit: Infinity, budget: DEFAULT_BUDGET, json: false };
153
+ const paths = [];
154
+ for (let i = 0; i < argv.length; i += 1) {
155
+ const arg = argv[i];
156
+ if (!arg.startsWith('--')) {
157
+ paths.push(arg);
158
+ continue;
159
+ }
160
+ const name = arg.slice(2);
161
+ if (BOOLEAN_FLAGS.includes(name)) {
162
+ flags[name] = true;
163
+ } else if (VALUE_FLAGS.includes(name)) {
164
+ const value = argv[i + 1];
165
+ if (value === undefined || value.startsWith('--')) {
166
+ throw new UsageError(`flag --${name} needs a value`);
167
+ }
168
+ flags[name] = value;
169
+ i += 1;
170
+ } else {
171
+ throw new UsageError(`unknown flag --${name}`);
172
+ }
173
+ }
174
+ if (flags.kinds !== null) {
175
+ flags.kinds = String(flags.kinds).split(',').map((k) => k.trim()).filter((k) => k !== '');
176
+ const bad = flags.kinds.filter((k) => !KNOWLEDGE_KINDS.includes(k));
177
+ if (bad.length > 0) {
178
+ throw new UsageError(`unknown kind(s) ${bad.join(', ')} — valid: ${KNOWLEDGE_KINDS.join(' | ')}`);
179
+ }
180
+ }
181
+ for (const numeric of ['limit', 'budget']) {
182
+ if (typeof flags[numeric] === 'string') {
183
+ const n = Number(flags[numeric]);
184
+ if (!Number.isFinite(n) || n <= 0) throw new UsageError(`--${numeric} must be a positive number`);
185
+ flags[numeric] = n;
186
+ }
187
+ }
188
+ return { flags, paths };
189
+ }
190
+
191
+ function main() {
192
+ const [command, ...rest] = process.argv.slice(2);
193
+ const usage = 'usage: knowledge.mjs brief [<path>...] [--dir <knowledge-dir>] [--kinds k,k] [--limit N] [--budget CHARS] [--json]';
194
+ if (command !== 'brief') {
195
+ console.error(usage);
196
+ process.exit(2);
197
+ }
198
+ let parsed;
199
+ try {
200
+ parsed = parseArgs(rest);
201
+ } catch (error) {
202
+ if (!(error instanceof UsageError)) throw error;
203
+ console.error(`knowledge: ${error.message}`);
204
+ console.error(usage);
205
+ process.exit(2);
206
+ }
207
+ const { flags, paths } = parsed;
208
+ const dir = resolve(flags.dir);
209
+ if (!existsSync(dir)) {
210
+ console.log(`### Knowledge brief — no knowledge directory at ${escapeInvisible(flags.dir)}\n`);
211
+ process.exitCode = 0;
212
+ return;
213
+ }
214
+ if (!statSync(dir).isDirectory()) {
215
+ // Absence is a fact worth an explicit line; a FILE where a directory
216
+ // belongs is a mistake, and exit 0 here would let an automated handoff
217
+ // silently carry an empty brief that claims the store was consulted.
218
+ console.error(`knowledge: --dir ${escapeInvisible(flags.dir)} is not a directory`);
219
+ process.exitCode = 2;
220
+ return;
221
+ }
222
+
223
+ const normalized = paths.map((p) => normalizePath(p) ?? p);
224
+ const { entries, invalid } = loadEntries(dir);
225
+ if (invalid.length > 0) {
226
+ for (const { file, errors } of invalid) {
227
+ console.error(`knowledge: INVALID ${escapeInvisible(file)}`);
228
+ for (const e of errors) console.error(` - ${escapeInvisible(String(e))}`);
229
+ }
230
+ console.error('knowledge: refusing to brief from a store that does not validate — a partial brief reads as a complete one');
231
+ process.exitCode = 1;
232
+ return;
233
+ }
234
+
235
+ const { selected, matched, limited } = selectEntries(entries, { paths: normalized, kinds: flags.kinds, limit: flags.limit });
236
+ if (flags.json) {
237
+ const payload = selected.map(({ id, kind, confidence, text, applies_to, file }) => ({
238
+ id, kind, confidence, text, applies_to: applies_to ?? [], file,
239
+ }));
240
+ console.log(jsonEscapeInvisible(JSON.stringify(payload, null, 2)));
241
+ process.exitCode = 0;
242
+ return;
243
+ }
244
+ // exitCode, never process.exit(): exit() does not wait for stdout to
245
+ // drain, and a large brief into a pipe would be TRUNCATED at the exact
246
+ // moment it matters most (a big store, an automated consumer).
247
+ process.stdout.write(renderBrief(selected, matched, { budget: flags.budget, dir: flags.dir, limited }));
248
+ process.exitCode = 0;
249
+ }
250
+
251
+ function canonicalPath(path) {
252
+ const abs = resolve(path);
253
+ try {
254
+ return realpathSync(abs);
255
+ } catch {
256
+ return abs;
257
+ }
258
+ }
259
+
260
+ function isMainModule(moduleUrl) {
261
+ if (!process.argv[1]) return false;
262
+ return canonicalPath(process.argv[1]) === canonicalPath(fileURLToPath(moduleUrl));
263
+ }
264
+
265
+ if (isMainModule(import.meta.url)) main();
@@ -508,6 +508,36 @@ 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
+ const STATE_GITIGNORE_BODY =
513
+ '# Runtime files, never history. Leases record who holds a worktree or a\n' +
514
+ '# heavy slot RIGHT NOW; committing one makes every parallel merge conflict\n' +
515
+ '# on state that was stale the moment it was written.\n' +
516
+ 'state/*/locks/\n';
517
+
518
+ /**
519
+ * Create-only write of `.tyran/.gitignore` excluding lease files. A nested
520
+ * gitignore rather than a line in the host's, because `.tyran/` is committed
521
+ * and travels into every worktree — the exclusion has to travel with it.
522
+ * Returns `{ path, status: 'created' | 'present' }`; never overwrites, so an
523
+ * operator's own additions survive re-running setup.
524
+ */
525
+ export function ensureStateGitignore(repoRoot) {
526
+ const root = resolve(repoRoot);
527
+ const path = join(root, ...STATE_GITIGNORE_PATH.split('/'));
528
+ if (existsSync(path)) return { path, status: 'present' };
529
+ try {
530
+ mkdirSync(dirname(path), { recursive: true });
531
+ writeFileSync(path, STATE_GITIGNORE_BODY);
532
+ } catch (error) {
533
+ throw new BootstrapError(
534
+ `could not write ${escapeInvisible(path)}: ${error.message}`,
535
+ 'check the directory permissions; re-running this command is safe',
536
+ );
537
+ }
538
+ return { path, status: 'created' };
539
+ }
540
+
511
541
  function main() {
512
542
  const args = process.argv.slice(2);
513
543
  const flag = (name, fallback) => {
@@ -531,6 +561,10 @@ function main() {
531
561
  ? `scan-repo: created ${escapeInvisible(seeded.path)} from the shipped template`
532
562
  : `scan-repo: ${escapeInvisible(seeded.path)} already exists — left untouched`,
533
563
  );
564
+ const ignored = seedStateGitignore(dir);
565
+ if (ignored.status === 'created') {
566
+ console.error(`scan-repo: created ${escapeInvisible(ignored.path)} (lease files stay out of history)`);
567
+ }
534
568
  return;
535
569
  }
536
570
 
@@ -547,6 +581,10 @@ function main() {
547
581
  if (seeded.status === 'created') {
548
582
  console.error(`scan-repo: created ${escapeInvisible(seeded.path)} from the shipped template`);
549
583
  }
584
+ const ignored = seedStateGitignore(dir);
585
+ if (ignored.status === 'created') {
586
+ console.error(`scan-repo: created ${escapeInvisible(ignored.path)} (lease files stay out of history)`);
587
+ }
550
588
  }
551
589
  try {
552
590
  mkdirSync(dirname(path), { recursive: true });
@@ -572,6 +610,23 @@ function seedPolicy(dir) {
572
610
  }
573
611
  }
574
612
 
613
+ /**
614
+ * `ensureStateGitignore`, with a BootstrapError turned into exit 2. Both call
615
+ * sites run this AFTER `seedPolicy` on purpose: it creates `.tyran/` when
616
+ * absent, and `.tyran/` without a policy under it is the state that refuses
617
+ * every subsequent write.
618
+ */
619
+ function seedStateGitignore(dir) {
620
+ try {
621
+ return ensureStateGitignore(dir);
622
+ } catch (error) {
623
+ if (!(error instanceof BootstrapError)) throw error;
624
+ console.error(`scan-repo: ${error.message}`);
625
+ console.error(`scan-repo: ${error.remedy}`);
626
+ process.exit(2);
627
+ }
628
+ }
629
+
575
630
  function canonicalPath(path) {
576
631
  const abs = resolve(path);
577
632
  try {
@@ -203,6 +203,36 @@ export function validateKnowledge(doc) {
203
203
  return errors;
204
204
  }
205
205
 
206
+ /**
207
+ * The size above which a knowledge entry stops being a brief-able fact and
208
+ * starts being a document. `knowledge.mjs brief` selects entries into a
209
+ * character budget; one 10 KB entry crowds out eight useful ones, visibly.
210
+ */
211
+ export const KNOWLEDGE_ENTRY_MAX_CHARS = 4000;
212
+
213
+ /**
214
+ * Advisory findings on a knowledge file that already validates. A separate
215
+ * export rather than more `validateKnowledge` errors on purpose: a warning
216
+ * must never flip `ok` for the existing consumers (validateFile, doctor, CI
217
+ * template validation), or every install with one wordy entry goes red.
218
+ */
219
+ export function knowledgeWarnings(doc) {
220
+ if (!isPlainObject(doc) || !Array.isArray(doc.entries)) return [];
221
+ const warnings = [];
222
+ doc.entries.forEach((entry, i) => {
223
+ if (!isPlainObject(entry) || typeof entry.text !== 'string') return;
224
+ const size = Array.from(entry.text).length;
225
+ if (size > KNOWLEDGE_ENTRY_MAX_CHARS) {
226
+ const id = isNonEmptyString(entry.id) ? entry.id : `entries[${i}]`;
227
+ warnings.push(
228
+ `${id}: text is ${size} characters (max ${KNOWLEDGE_ENTRY_MAX_CHARS} before it crowds a brief) — ` +
229
+ 'split it, or move the bulk into a doc and keep the pointer here',
230
+ );
231
+ }
232
+ });
233
+ return warnings;
234
+ }
235
+
206
236
  /**
207
237
  * Paths that MUST be classified KERNEL. A policy that downgrades any of
208
238
  * these would let the self-improvement loop disable its own enforcement,
@@ -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
@@ -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
@@ -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