@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.
@@ -35,8 +35,8 @@
35
35
  * with no answer inside the state directory, because a plugin whose hooks are
36
36
  * dead writes no state to be inconsistent with.
37
37
  */
38
- import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
39
- import { join, dirname, resolve } from 'node:path';
38
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
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,13 @@ 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',
199
+ // overnight mode
200
+ 'limit-pause-active': 'info',
201
+ 'limit-pause-stale': 'warning',
202
+ 'limit-resume-watcher-dead': 'warning',
203
+ 'limit-telemetry-missing': 'warning',
196
204
  }),
197
205
  );
198
206
 
@@ -1001,12 +1009,154 @@ function policyFindings(path, repoRoot) {
1001
1009
  * evidence that a file is untracked, and reporting it as such would fire on
1002
1010
  * every temp directory and every fresh `git init`.
1003
1011
  */
1004
- export function untrackedTyranDir(repoRoot, run) {
1012
+ export function untrackedTyranDir(repoRoot, run, tyranDirName = '.tyran') {
1005
1013
  if (run(['rev-parse', '--is-inside-work-tree']).trim() !== 'true') return null;
1006
1014
  // `ls-files` over the directory: any tracked file under it means the tree
1007
1015
  // travels with a worktree, which is the property being checked. Asking about
1008
1016
  // config.yaml alone would pass a repo that committed only the policy.
1009
- return run(['ls-files', '--', '.tyran']).trim() === '';
1017
+ // The pathspec is parameterized the same way trackedLeaseFiles' is, so a
1018
+ // --dir naming anything but `.tyran` cannot make the two checks contradict
1019
+ // each other about what git tracks.
1020
+ return run(['ls-files', '--', tyranDirName]).trim() === '';
1021
+ }
1022
+
1023
+ /**
1024
+ * Lease files committed to git. A lease records who holds a worktree or a
1025
+ * heavy slot RIGHT NOW; committing one makes every parallel merge conflict on
1026
+ * state that was stale the moment it was written, and a checkout resurrects
1027
+ * it as a phantom holder. Filtered in JS rather than via a wildcard pathspec
1028
+ * — git's pathspec globbing is exactly the kind of subtlety this tool exists
1029
+ * to not depend on. Returns [] when git cannot answer: "not a git repository"
1030
+ * is not evidence that a lease is tracked.
1031
+ */
1032
+ export function trackedLeaseFiles(run, tyranDirName = '.tyran') {
1033
+ const listing = run(['ls-files', '--', tyranDirName]);
1034
+ if (listing === '') return [];
1035
+ const lease = /\/(?:state|initiatives)\/[^/]+\/locks\//;
1036
+ return listing.split('\n').filter((line) => line !== '' && lease.test(line));
1037
+ }
1038
+
1039
+ /** The repo-global overnight runtime files that legally live at state/ level. */
1040
+ export const OVERNIGHT_RUNTIME_FILES = Object.freeze([
1041
+ 'paused-until.json',
1042
+ 'resume.json',
1043
+ 'resume.log',
1044
+ 'usage.json',
1045
+ ]);
1046
+
1047
+ /**
1048
+ * Overnight-mode consistency: the pause marker, the resume watcher, and the
1049
+ * telemetry a configured gate depends on. Deterministic: staleness questions
1050
+ * are answered only against an explicit `now` (the SessionStart probe passes
1051
+ * one); without it a marker is reported as present, never as stale — doctor
1052
+ * never reads the wall clock.
1053
+ */
1054
+ export function overnightFindings(dir, { now = null, configDoc = null } = {}) {
1055
+ const findings = [];
1056
+ const referenceMs = now !== null ? Date.parse(now) : null;
1057
+ const markerPath = join(dir, 'state', 'paused-until.json');
1058
+ const resumePath = join(dir, 'state', 'resume.json');
1059
+ const sidecarPath = join(dir, 'state', 'usage.json');
1060
+
1061
+ const marker = readJsonIfSmall(markerPath);
1062
+ if (marker !== null) {
1063
+ const resumeAtMs = Date.parse(typeof marker.resume_at === 'string' ? marker.resume_at : '');
1064
+ const stale = referenceMs !== null && Number.isFinite(resumeAtMs) && resumeAtMs < referenceMs;
1065
+ if (stale) {
1066
+ findings.push(
1067
+ finding(
1068
+ 'limit-pause-stale',
1069
+ show(markerPath),
1070
+ `the pause marker's resume time (${show(marker.resume_at)}) has PASSED and the marker is still ` +
1071
+ 'here — the watcher died with the machine, or was never scheduled. Autonomous work stays ' +
1072
+ 'wound down until this is resolved; the usage gate also self-clears it on the next tool call',
1073
+ `node scripts/overnight.mjs status --dir ${sq(dirname(resolve(dir)))} # then schedule again, or let the gate self-clear`,
1074
+ ),
1075
+ );
1076
+ } else {
1077
+ findings.push(
1078
+ finding(
1079
+ 'limit-pause-active',
1080
+ show(markerPath),
1081
+ `paused on the ${show(marker.window)} usage window until ${show(marker.resume_at)}` +
1082
+ (marker.long_wait === true ? ' — a LONG pause; the scheduler holds unless told otherwise' : ''),
1083
+ ),
1084
+ );
1085
+ }
1086
+ }
1087
+
1088
+ // Outside the marker guard: the watcher unlinks the marker BEFORE spawning
1089
+ // the resume and never restores it, so a failed resume leaves resume.json
1090
+ // with no marker beside it.
1091
+ const resume = readJsonIfSmall(resumePath);
1092
+ if (resume !== null) {
1093
+ const waitingDead =
1094
+ resume.state === 'waiting' && !(Number.isInteger(resume.pid) && resume.pid > 0 && processAlive(resume.pid));
1095
+ if (waitingDead || resume.state === 'failed') {
1096
+ findings.push(
1097
+ finding(
1098
+ 'limit-resume-watcher-dead',
1099
+ show(resumePath),
1100
+ waitingDead
1101
+ ? `resume.json says a watcher is waiting (pid ${show(String(resume.pid))}) but no such process is alive — a reboot kills detached watchers`
1102
+ : `the last scheduled resume FAILED (${show(resume.reason ?? 'see resume.log')})`,
1103
+ // `schedule` needs the pause marker, and a failed resume has already
1104
+ // consumed it — the fix must be executable in the state that fires.
1105
+ marker !== null
1106
+ ? `node scripts/overnight.mjs schedule --dir ${sq(dirname(resolve(dir)))}`
1107
+ : `resume the session by hand (claude --resume; .tyran/state/resume.log names the attempt), then node scripts/overnight.mjs cancel --dir ${sq(dirname(resolve(dir)))} to reset the watcher state`,
1108
+ ),
1109
+ );
1110
+ }
1111
+ }
1112
+
1113
+ // A configured control that cannot see is the silent-absence class.
1114
+ const limits = knowsLimits(configDoc);
1115
+ if (limits !== null && limits.mode !== 'off') {
1116
+ const sidecar = readJsonIfSmall(sidecarPath);
1117
+ const writtenMs = sidecar !== null ? Date.parse(typeof sidecar.written_at === 'string' ? sidecar.written_at : '') : NaN;
1118
+ const ancient = referenceMs !== null && Number.isFinite(writtenMs) && referenceMs - writtenMs > 24 * 3600 * 1000;
1119
+ if (sidecar === null || ancient) {
1120
+ findings.push(
1121
+ finding(
1122
+ 'limit-telemetry-missing',
1123
+ show(sidecarPath),
1124
+ `limits.mode is "${show(limits.mode)}" but the usage telemetry sidecar is ${sidecar === null ? 'absent' : 'over a day old'} — ` +
1125
+ 'the gate fails open without it, so the configured pause protects nothing. The statusline ' +
1126
+ 'helper is operator-installed; see docs/overnight.md',
1127
+ `node scripts/statusline.mjs --sidecar-only # wired into the user-settings statusLine command`,
1128
+ ),
1129
+ );
1130
+ }
1131
+ }
1132
+ return findings;
1133
+ }
1134
+
1135
+ function readJsonIfSmall(path) {
1136
+ try {
1137
+ if (!existsSync(path) || statSync(path).size > 64 * 1024) return null;
1138
+ const doc = JSON.parse(readFileSync(path, 'utf8'));
1139
+ return doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : null;
1140
+ } catch {
1141
+ return null;
1142
+ }
1143
+ }
1144
+
1145
+ function processAlive(pid) {
1146
+ try {
1147
+ process.kill(pid, 0);
1148
+ return true;
1149
+ } catch {
1150
+ return false;
1151
+ }
1152
+ }
1153
+
1154
+ /** The limits block when the config carries a usable one, else null. */
1155
+ function knowsLimits(configDoc) {
1156
+ if (configDoc === null || typeof configDoc !== 'object') return null;
1157
+ const limits = configDoc.limits;
1158
+ if (limits === null || typeof limits !== 'object' || Array.isArray(limits)) return null;
1159
+ return typeof limits.mode === 'string' ? limits : null;
1010
1160
  }
1011
1161
 
1012
1162
  export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAULT_STALE_HOURS, run = null } = {}) {
@@ -1023,8 +1173,11 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1023
1173
  const checked = [];
1024
1174
 
1025
1175
  const configPath = join(dir, 'config.yaml');
1176
+ let configDoc = null;
1026
1177
  if (existsSync(configPath)) {
1027
- findings.push(...checkSchemaFile('config', configPath).findings);
1178
+ const configResult = checkSchemaFile('config', configPath);
1179
+ findings.push(...configResult.findings);
1180
+ configDoc = configResult.doc;
1028
1181
  checked.push('config.yaml: checked');
1029
1182
  } else {
1030
1183
  findings.push(
@@ -1038,7 +1191,8 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1038
1191
  checked.push('config.yaml: absent');
1039
1192
  }
1040
1193
 
1041
- const untracked = untrackedTyranDir(repoRoot, run ?? gitRunner(repoRoot));
1194
+ const gitRun = run ?? gitRunner(repoRoot);
1195
+ const untracked = untrackedTyranDir(repoRoot, gitRun, basename(root));
1042
1196
  if (untracked === true) {
1043
1197
  findings.push(
1044
1198
  finding(
@@ -1055,7 +1209,22 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1055
1209
 
1056
1210
  const knowledge = yamlFilesIn(join(dir, 'knowledge'), 'knowledge');
1057
1211
  findings.push(...knowledge.findings);
1058
- for (const file of knowledge.files) findings.push(...checkSchemaFile('knowledge', file).findings);
1212
+ for (const file of knowledge.files) {
1213
+ const schemaResult = checkSchemaFile('knowledge', file);
1214
+ findings.push(...schemaResult.findings);
1215
+ // Advisory, on files that already validate: an oversized entry is legal,
1216
+ // it just crowds every budgeted brief it appears in.
1217
+ for (const warning of knowledgeWarnings(schemaResult.doc)) {
1218
+ findings.push(
1219
+ finding(
1220
+ 'knowledge-entry-oversized',
1221
+ show(file),
1222
+ warning,
1223
+ `node scripts/knowledge.mjs brief '**' --dir ${sq(join(dir, 'knowledge'))} # shows what a budgeted brief keeps`,
1224
+ ),
1225
+ );
1226
+ }
1227
+ }
1059
1228
  checked.push(`knowledge/: ${knowledge.files.length} file(s)`);
1060
1229
 
1061
1230
  const policies = yamlFilesIn(join(dir, 'policies'), 'policies');
@@ -1092,6 +1261,10 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1092
1261
  for (const name of sortedNames(names)) {
1093
1262
  const path = join(stateDir, name);
1094
1263
  if (!isDirectory(path)) {
1264
+ // Named exemption, not a silent skip: the overnight runtime files
1265
+ // live at the state/ level by design (repo-global, machine-local,
1266
+ // gitignored) and are checked by overnightFindings instead.
1267
+ if (OVERNIGHT_RUNTIME_FILES.includes(name)) continue;
1095
1268
  findings.push(
1096
1269
  finding(
1097
1270
  'state-stray-file',
@@ -1110,6 +1283,39 @@ export function runStateChecks({ dir = '.tyran', now = null, staleHours = DEFAUL
1110
1283
  initiatives.length === 0 ? 'state/: no initiatives' : `state/: ${initiatives.join(', ')}`,
1111
1284
  );
1112
1285
 
1286
+ const legacyDir = join(dir, 'initiatives');
1287
+ if (isDirectory(legacyDir)) {
1288
+ findings.push(
1289
+ finding(
1290
+ 'state-legacy-initiatives-dir',
1291
+ show(legacyDir),
1292
+ 'legacy layout — initiative files (PLAN.md, NOTES.md, RETRO.md, locks/) live under ' +
1293
+ 'state/<initiative>/ since 0.1.9. Mechanical consumers read only state/, so anything ' +
1294
+ 'kept here is invisible to the projections, the retrospective and the session summary',
1295
+ `ls -la ${sq(legacyDir)} # relocate the contents by hand, one initiative directory at a time, into ${sq(join(dir, 'state'))} — see docs/journal.md`,
1296
+ ),
1297
+ );
1298
+ }
1299
+ checked.push(`initiatives/ (legacy): ${isDirectory(legacyDir) ? 'PRESENT' : 'absent'}`);
1300
+
1301
+ findings.push(...overnightFindings(dir, { now, configDoc }));
1302
+ checked.push('overnight: checked');
1303
+
1304
+ const trackedLeases = trackedLeaseFiles(gitRun, basename(root));
1305
+ if (trackedLeases.length > 0) {
1306
+ findings.push(
1307
+ finding(
1308
+ 'lease-file-tracked',
1309
+ show(trackedLeases[0]) + (trackedLeases.length > 1 ? ` (+${trackedLeases.length - 1} more)` : ''),
1310
+ `${trackedLeases.length} lease file(s) committed to git — a lease records who holds a resource ` +
1311
+ 'RIGHT NOW, so a committed one conflicts on every parallel merge and resurrects as a phantom ' +
1312
+ 'holder on every checkout',
1313
+ `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`,
1314
+ ),
1315
+ );
1316
+ }
1317
+ checked.push(`lease files tracked by git: ${trackedLeases.length}`);
1318
+
1113
1319
  return summarize(dir, findings, checked);
1114
1320
  }
1115
1321
 
@@ -650,7 +650,7 @@ export function shebangInterpreter(firstLine) {
650
650
  * also be reported as "no shebang", which would bury the finding that
651
651
  * actually says what to do.
652
652
  */
653
- function checkHookFile(path, where, { env }) {
653
+ function checkHookFile(path, where, { env, dispatcher = null }) {
654
654
  const findings = [];
655
655
  let stat;
656
656
  try {
@@ -688,6 +688,34 @@ function checkHookFile(path, where, { env }) {
688
688
  // and is the same on every machine. Raised in review as a CI hazard that
689
689
  // would have disarmed the mutant for this guard; measuring the bits removes
690
690
  // the dependency instead of hoping about the runner.
691
+ // A command of the form `node "<script>"` dispatches through the named
692
+ // interpreter, so neither the mode bits nor a shebang decide whether it can
693
+ // run — the file only has to exist and be readable, and `node` itself has
694
+ // to resolve. Registering this way is the sanctioned route for a hook file
695
+ // an agent authored: the policy gate refuses agent-run chmod on hook paths,
696
+ // deliberately, so the exec bit cannot be set from inside a session.
697
+ if (dispatcher !== null) {
698
+ if (!interpreterExists(dispatcher, env)) {
699
+ findings.push(
700
+ finding(
701
+ 'hook-interpreter-absent',
702
+ where,
703
+ `the command dispatches through "${q(dispatcher)}", which is not on PATH and is not an ` +
704
+ 'existing absolute path. The spawn fails in the non-blocking way, so the action proceeds.',
705
+ `command -v ${q(dispatcher)}`,
706
+ ),
707
+ );
708
+ }
709
+ try {
710
+ readFileSync(path, 'utf8');
711
+ } catch (err) {
712
+ findings.push(
713
+ finding('hook-file-unreadable', where, `cannot read the hook file (${q(err.code ?? err.message)})`),
714
+ );
715
+ }
716
+ return findings;
717
+ }
718
+
691
719
  let executable = (stat.mode & 0o111) !== 0;
692
720
  if (executable) {
693
721
  try {
@@ -1265,20 +1293,29 @@ export function checkHooks({ root = DEFAULT_PLUGIN_ROOT, env = process.env } = {
1265
1293
  );
1266
1294
  return;
1267
1295
  }
1268
- const program = substitute(lexed.argv[0] ?? '', vars);
1296
+ // `node "<script>"` dispatches through the interpreter: the SCRIPT is
1297
+ // the file to check, and mode bits/shebang stop being requirements
1298
+ // (checkHookFile handles that under `dispatcher`).
1299
+ let programWord = lexed.argv[0] ?? '';
1300
+ let dispatcher = null;
1301
+ if (substitute(programWord, vars) === 'node' && typeof lexed.argv[1] === 'string') {
1302
+ dispatcher = 'node';
1303
+ programWord = lexed.argv[1];
1304
+ }
1305
+ const program = substitute(programWord, vars);
1269
1306
  if (program === '' || /\$\{/.test(program)) {
1270
1307
  findings.push(
1271
1308
  finding(
1272
1309
  'hook-command-not-modellable',
1273
1310
  where,
1274
- `the command's program word "${q(lexed.argv[0] ?? '')}" still contains a variable this check ` +
1311
+ `the command's program word "${q(programWord)}" still contains a variable this check ` +
1275
1312
  'cannot resolve, so the file it names is unknown here.',
1276
1313
  ),
1277
1314
  );
1278
1315
  return;
1279
1316
  }
1280
1317
  const path = resolve(pluginRoot, program);
1281
- const fileFindings = checkHookFile(path, `${where} -> ${q(path)}`, { env });
1318
+ const fileFindings = checkHookFile(path, `${where} -> ${q(path)}`, { env, dispatcher });
1282
1319
  findings.push(...fileFindings);
1283
1320
 
1284
1321
  // Only cross-check the declared event when the file was readable —
@@ -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();