cyc-stack 0.0.0-stage → 0.6.0

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.
Files changed (112) hide show
  1. package/.agents/plugins/marketplace.json +12 -0
  2. package/.claude-plugin/marketplace.json +14 -0
  3. package/.claude-plugin/plugin.json +17 -0
  4. package/.codex-plugin/plugin.json +33 -0
  5. package/.cursor-plugin/marketplace.json +13 -0
  6. package/.cursor-plugin/plugin.json +19 -0
  7. package/INSTALL.md +108 -0
  8. package/LICENSE +21 -0
  9. package/README.md +359 -2
  10. package/bin/cyc.mjs +285 -0
  11. package/catalog/playbooks.json +20 -0
  12. package/docs/README.md +30 -0
  13. package/docs/assets/cyc-method-library.svg +39 -0
  14. package/docs/assets/cyc-overview.svg +44 -0
  15. package/docs/assets/cyc-readme-banner-mobile.svg +31 -0
  16. package/docs/assets/cyc-readme-banner.svg +39 -0
  17. package/docs/assets/cyc-workflow-diagram.svg +415 -0
  18. package/docs/code-quality.md +42 -0
  19. package/docs/context.md +40 -0
  20. package/docs/cyc-method-map.md +58 -0
  21. package/docs/cyc-workflow.md +188 -0
  22. package/docs/engineering/code-standards.md +103 -0
  23. package/docs/engineering/domain-design.md +81 -0
  24. package/docs/engineering/failure-handling.md +99 -0
  25. package/docs/impact-analysis.md +70 -0
  26. package/docs/installation.md +196 -0
  27. package/docs/onboarding-recovery.md +75 -0
  28. package/docs/principles.md +49 -0
  29. package/docs/project-tools.md +108 -0
  30. package/docs/response-standard.md +202 -0
  31. package/docs/runtime.md +247 -0
  32. package/docs/skill-contract.md +70 -0
  33. package/docs/skill-craft.md +23 -0
  34. package/docs/validation.md +39 -0
  35. package/docs/work-assessments.md +102 -0
  36. package/hooks/claude.json +10 -0
  37. package/hooks/codex.json +28 -0
  38. package/hooks/cursor.json +8 -0
  39. package/methods/cyc-build/SKILL.md +65 -0
  40. package/methods/cyc-build/references/file-writes.md +11 -0
  41. package/methods/cyc-challenge/SKILL.md +48 -0
  42. package/methods/cyc-context/SKILL.md +76 -0
  43. package/methods/cyc-context/references/evidence.md +27 -0
  44. package/methods/cyc-context/references/templates.md +54 -0
  45. package/methods/cyc-context/scripts/evidence.mjs +61 -0
  46. package/methods/cyc-correct/SKILL.md +43 -0
  47. package/methods/cyc-deliver/SKILL.md +52 -0
  48. package/methods/cyc-design/SKILL.md +50 -0
  49. package/methods/cyc-design/frontend-design/SKILL.md +43 -0
  50. package/methods/cyc-design/frontend-design/references/color.md +77 -0
  51. package/methods/cyc-design/frontend-design/references/craft-rules.md +61 -0
  52. package/methods/cyc-design/frontend-design/references/decision-sheet.md +110 -0
  53. package/methods/cyc-design/frontend-design/references/experience-review.md +58 -0
  54. package/methods/cyc-design/frontend-design/references/generic-tells.md +76 -0
  55. package/methods/cyc-design/frontend-design/references/layout-archetypes.md +188 -0
  56. package/methods/cyc-design/frontend-design/references/reference-standards.md +38 -0
  57. package/methods/cyc-design/frontend-design/references/typography.md +51 -0
  58. package/methods/cyc-design/frontend-design/references/ux-foundations.md +45 -0
  59. package/methods/cyc-design/frontend-design/references/visual-material.md +42 -0
  60. package/methods/cyc-error-ledger/SKILL.md +53 -0
  61. package/methods/cyc-error-ledger/references/entry-format.md +38 -0
  62. package/methods/cyc-explore/SKILL.md +41 -0
  63. package/methods/cyc-frame/SKILL.md +49 -0
  64. package/methods/cyc-impact/SKILL.md +64 -0
  65. package/methods/cyc-reflect/SKILL.md +48 -0
  66. package/methods/cyc-remember/SKILL.md +53 -0
  67. package/methods/cyc-scout/SKILL.md +67 -0
  68. package/methods/cyc-setup/SKILL.md +60 -0
  69. package/methods/cyc-teach/SKILL.md +40 -0
  70. package/methods/cyc-understand/SKILL.md +40 -0
  71. package/methods/cyc-understand/references/diagnose.md +53 -0
  72. package/methods/cyc-verify/SKILL.md +84 -0
  73. package/methods/cyc-verify/references/recipe.md +53 -0
  74. package/package.json +93 -4
  75. package/plugin.json +40 -0
  76. package/rules/cyc-delivery.mdc +33 -0
  77. package/scripts/baseline-worker.mjs +10 -0
  78. package/scripts/catalog.mjs +29 -0
  79. package/scripts/check-response.mjs +13 -0
  80. package/scripts/claude-project-hook.mjs +12 -0
  81. package/scripts/context-review.mjs +600 -0
  82. package/scripts/host-activation.mjs +66 -0
  83. package/scripts/install.mjs +387 -0
  84. package/scripts/onboarding.mjs +110 -0
  85. package/scripts/packet.mjs +107 -0
  86. package/scripts/project-tools.mjs +196 -0
  87. package/scripts/recovery.mjs +66 -0
  88. package/scripts/response-gate.mjs +105 -0
  89. package/scripts/response-hook.mjs +237 -0
  90. package/scripts/response-mode.mjs +12 -0
  91. package/scripts/run-gate.mjs +264 -0
  92. package/scripts/runtime.mjs +1723 -0
  93. package/scripts/source-hash-worker.mjs +5 -0
  94. package/scripts/source-snapshot.mjs +405 -0
  95. package/scripts/test-output.mjs +258 -0
  96. package/scripts/work-review.mjs +257 -0
  97. package/skills/cyc/SKILL.md +130 -0
  98. package/skills/cyc/references/playbooks/bug-fix.md +13 -0
  99. package/skills/cyc/references/playbooks/evaluate.md +13 -0
  100. package/skills/cyc/references/playbooks/experience.md +7 -0
  101. package/skills/cyc/references/playbooks/explore.md +9 -0
  102. package/skills/cyc/references/playbooks/feature.md +14 -0
  103. package/skills/cyc/references/playbooks/handoff.md +11 -0
  104. package/skills/cyc/references/playbooks/investigation.md +7 -0
  105. package/skills/cyc/references/playbooks/performance.md +7 -0
  106. package/skills/cyc/references/playbooks/plan.md +11 -0
  107. package/skills/cyc/references/playbooks/refactor.md +12 -0
  108. package/skills/cyc/references/playbooks/reflect.md +11 -0
  109. package/skills/cyc/references/playbooks/resume.md +11 -0
  110. package/skills/cyc/references/playbooks/review.md +9 -0
  111. package/skills/cyc/references/playbooks/teach.md +11 -0
  112. package/skills/cyc/references/playbooks/verify.md +7 -0
@@ -0,0 +1,600 @@
1
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join, relative, resolve } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { readRun } from './runtime.mjs';
6
+ import { contextLinks } from './project-tools.mjs';
7
+
8
+ // Component context docs under docs/context/ and their quality check. A doc is for one component,
9
+ // in a fixed AI-readable layout, and the index (the table of contents) carries enough per component
10
+ // that a task can read the index plus the matched docs instead of every doc. `review` proposes
11
+ // doc updates from completed controller runs and `--write` applies them; `lint` checks the rules
12
+ // below and the index's freshness against Git; `measure` counts what the index path costs to read.
13
+
14
+ export const contextFolder = 'docs/context';
15
+ export const indexName = `${contextFolder}/INDEX.md`;
16
+ const reservedDocs = new Set(['INDEX.md', 'error-ledger.md', 'verify-recipe.md']);
17
+ const docFileName = /^[a-z][a-z0-9-]*\.md$/;
18
+ const dateText = /\d{4}-\d{2}-\d{2}/;
19
+ const runIdText = /[A-Za-z0-9][A-Za-z0-9._-]{3,}/;
20
+ const hashText = /(?:sha256:)?[0-9a-f]{7,64}/;
21
+ const lastChangeLine = new RegExp(`^Last changed by AI: (?:none recorded|(${dateText.source}) · run (${runIdText.source}) · files: (.+))$`);
22
+ const historyHeading = new RegExp(`^### (${dateText.source}) · run (${runIdText.source})(?: · (.*))?$`);
23
+ const lessonLine = new RegExp(`^- (${dateText.source}) · ([^:]+): (.+)$`);
24
+ const fileItem = new RegExp(`^\`?([^\`@\\s]+)\`?@(${hashText.source})$`);
25
+ const sectionOrder = ['Current view', 'Lessons', 'History'];
26
+ export const maxDocLines = 300;
27
+
28
+ // Each rule is named in a lint issue so the fix is clear. They are structure rules only: a doc can
29
+ // pass every one and still be wrong about the component.
30
+ export const rules = {
31
+ name: `The file name is kebab-case (${docFileName.source}); INDEX.md, error-ledger.md and verify-recipe.md are not component docs.`,
32
+ title: 'The first non-empty line is the only H1, naming the one component the doc covers.',
33
+ covers: 'A "Covers:" line lists one or more project-relative path patterns (comma-separated, forward slashes, no parent segments).',
34
+ 'last-change': 'A "Last changed by AI:" line reads "none recorded" or "<YYYY-MM-DD> · run <id> · files: <paths>".',
35
+ sections: `The H2 sections are exactly ${sectionOrder.map(name => `"## ${name}"`).join(', ')}, once each, in that order.`,
36
+ 'current-view': 'Current view has prose and no <placeholder> left from the template.',
37
+ 'lesson-dated': 'Every line under Lessons is a bullet "- <YYYY-MM-DD> · <source>: <lesson>".',
38
+ 'history-entry': 'Every History entry heads with "### <YYYY-MM-DD> · run <id>", newest first, and nothing but entries appears under History.',
39
+ evidence: 'Every History entry has a "**Files:**" line listing each file as path@<sha256 or commit>.',
40
+ 'last-change-current': 'The "Last changed by AI" line names the newest History entry.',
41
+ size: `The doc has at most ${maxDocLines} lines; consolidate older entries past that.`,
42
+ 'toc-columns': 'The index table has Component (or Area), Covers, Doc (or Record), Last AI change and Lessons columns.',
43
+ 'toc-link': 'Every index Doc link resolves to an existing file.',
44
+ 'toc-unindexed': 'Every component doc in docs/context/ has exactly one index row.',
45
+ 'toc-covers': 'An index row\'s Covers equals its doc\'s Covers line.',
46
+ 'toc-last-change': 'An index row\'s Last AI change starts with the doc\'s last-change date and run.',
47
+ 'toc-lessons': 'An index row\'s Lessons cell starts with the doc\'s lesson count.',
48
+ 'stale-against-git': 'A covered path was committed after the doc\'s last commit, so the doc may describe code that has changed.'
49
+ };
50
+
51
+ const text = value => typeof value === 'string' && value.trim().length > 0;
52
+ const oneLine = (value, max = 160) => {
53
+ const line = String(value ?? '').replace(/\s+/g, ' ').replaceAll('|', '\\|').trim();
54
+ return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;
55
+ };
56
+ const shortRun = id => String(id).slice(0, 8);
57
+ const day = iso => String(iso ?? '').slice(0, 10);
58
+ const fileName = path => path.split('/').at(-1);
59
+ const isComponentDoc = path => !!path && dirname(path) === contextFolder && docFileName.test(fileName(path)) && !reservedDocs.has(fileName(path));
60
+
61
+ export function canonicalPattern(pattern, { patterns = true } = {}) {
62
+ const value = String(pattern ?? '').trim().replaceAll('`', '');
63
+ if (!value || /[\\:\0]/.test(value) || (!patterns && /[*?]/.test(value)) || /[\[\]{}]/.test(value) || value.split('/').some(p => !p || p === '.' || p === '..')) throw Error(`Use canonical project-relative ${patterns ? 'patterns' : 'paths'}: ${value || pattern}`);
64
+ return value;
65
+ }
66
+
67
+ // The same pattern language as cyc investigate (project-tools.mjs): literal paths and directories,
68
+ // *, ** and ?; "all" covers everything. Kept compatible so the index means one thing to both.
69
+ export function matches(pattern, path) {
70
+ if (pattern === 'all') pattern = '**';
71
+ canonicalPattern(pattern); canonicalPattern(path, { patterns: false });
72
+ let regex = '';
73
+ for (let i = 0; i < pattern.length; i++) {
74
+ if (pattern[i] === '*' && pattern[i + 1] === '*') { i++; if (pattern[i + 1] === '/') { i++; regex += '(?:.*/)?'; } else regex += '.*'; }
75
+ else if (pattern[i] === '*') regex += '[^/]*';
76
+ else if (pattern[i] === '?') regex += '[^/]';
77
+ else regex += pattern[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
78
+ }
79
+ const prefix = pattern.split(/[?*]/)[0].replace(/\/$/, '');
80
+ return new RegExp(`^${regex}$`).test(path) || (prefix && (prefix === path || prefix.startsWith(path + '/'))) || (!/[?*]/.test(pattern) && path.startsWith(pattern + '/'));
81
+ }
82
+ const covered = (covers, path) => covers.some(pattern => { try { return matches(pattern, path); } catch { return false; } });
83
+
84
+ function local(root, path) {
85
+ canonicalPattern(path, { patterns: false });
86
+ let current = root;
87
+ for (const part of path.split('/')) {
88
+ current = join(current, part);
89
+ try { if (lstatSync(current).isSymbolicLink()) throw Error(`Linked path is not supported: ${path}`); }
90
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
91
+ }
92
+ return current;
93
+ }
94
+ const read = (root, path) => readFileSync(local(root, path), 'utf8').replace(/^/, '').replaceAll('\r\n', '\n');
95
+ function atomicWrite(path, content) {
96
+ const temporary = `${path}.${randomUUID()}.tmp`;
97
+ writeFileSync(temporary, content);
98
+ renameSync(temporary, path);
99
+ }
100
+
101
+ // ---------------------------------------------------------------- component docs
102
+
103
+ export function parseDoc(source, name = 'doc.md') {
104
+ const lines = source.replace(/^/, '').replaceAll('\r\n', '\n').split('\n');
105
+ const issues = [];
106
+ const issue = (rule, message, line) => issues.push({ rule, message, ...(line !== undefined ? { line: line + 1 } : {}) });
107
+ if (!docFileName.test(name) || reservedDocs.has(name)) issue('name', `${name} is not a component doc name.`);
108
+ const h1 = lines.map((line, index) => [line, index]).filter(([line]) => /^# /.test(line));
109
+ const firstText = lines.findIndex(line => line.trim());
110
+ if (h1.length !== 1 || h1[0][1] !== firstText) issue('title', h1.length === 1 ? 'The H1 must be the first non-empty line.' : `Expected one H1, found ${h1.length}.`, h1[0]?.[1]);
111
+ const title = h1.length ? h1[0][0].slice(2).trim() : null;
112
+ const coversIndex = lines.findIndex(line => /^Covers:/.test(line));
113
+ let covers = [];
114
+ if (coversIndex === -1) issue('covers', 'Missing "Covers:" line.');
115
+ else {
116
+ try {
117
+ covers = lines[coversIndex].slice('Covers:'.length).split(',').map(p => canonicalPattern(p));
118
+ if (!covers.length) throw Error('Covers lists no pattern.');
119
+ } catch (error) { issue('covers', error.message, coversIndex); covers = []; }
120
+ }
121
+ const lastIndex = lines.findIndex(line => /^Last changed by AI:/.test(line));
122
+ let lastChange = null;
123
+ if (lastIndex === -1) issue('last-change', 'Missing "Last changed by AI:" line.');
124
+ else {
125
+ const match = lines[lastIndex].match(lastChangeLine);
126
+ if (!match) issue('last-change', `Unreadable line: ${lines[lastIndex]}`, lastIndex);
127
+ else lastChange = match[1] ? { date: match[1], run: match[2], files: match[3].split(',').map(p => p.trim().replaceAll('`', '')).filter(Boolean) } : 'none recorded';
128
+ }
129
+ const h2 = lines.map((line, index) => [line, index]).filter(([line]) => /^## /.test(line));
130
+ const names = h2.map(([line]) => line.slice(3).trim());
131
+ if (names.join('\n') !== sectionOrder.join('\n')) issue('sections', `Found sections: ${names.map(n => `"## ${n}"`).join(', ') || 'none'}.`);
132
+ const section = name => {
133
+ const at = h2.findIndex(([line]) => line.slice(3).trim() === name);
134
+ if (at === -1) return null;
135
+ const start = h2[at][1] + 1, end = at + 1 < h2.length ? h2[at + 1][1] : lines.length;
136
+ return { start, lines: lines.slice(start, end) };
137
+ };
138
+ const view = section('Current view');
139
+ if (view) {
140
+ if (!view.lines.some(line => line.trim())) issue('current-view', 'Current view is empty.', view.start);
141
+ const placeholder = view.lines.findIndex(line => /^\s*<[^>]*>\s*$/.test(line));
142
+ if (placeholder !== -1) issue('current-view', 'Current view still has a template placeholder.', view.start + placeholder);
143
+ }
144
+ const lessons = [];
145
+ const lessonSection = section('Lessons');
146
+ for (const [offset, line] of (lessonSection?.lines ?? []).entries()) {
147
+ if (!line.trim()) continue;
148
+ const match = line.match(lessonLine);
149
+ if (!match) { issue('lesson-dated', `Not a dated lesson bullet: ${oneLine(line, 80)}`, lessonSection.start + offset); continue; }
150
+ lessons.push({ date: match[1], source: match[2], text: match[3], line: lessonSection.start + offset + 1 });
151
+ }
152
+ const history = [];
153
+ const historySection = section('History');
154
+ if (historySection) {
155
+ let entry = null;
156
+ for (const [offset, line] of historySection.lines.entries()) {
157
+ const at = historySection.start + offset;
158
+ if (/^### /.test(line)) {
159
+ const match = line.match(historyHeading);
160
+ if (!match) { issue('history-entry', `Unreadable entry heading: ${oneLine(line, 80)}`, at); entry = null; continue; }
161
+ entry = { date: match[1], run: match[2], title: match[3] ?? '', line: at + 1, files: [], hasFiles: false };
162
+ history.push(entry);
163
+ continue;
164
+ }
165
+ if (!entry) { if (line.trim()) issue('history-entry', 'Text under History outside an entry.', at); continue; }
166
+ if (/^\*\*Files:\*\*/.test(line)) {
167
+ entry.hasFiles = true;
168
+ for (const item of line.slice('**Files:**'.length).split(',').map(s => s.trim()).filter(Boolean)) {
169
+ const match = item.match(fileItem);
170
+ if (!match) { issue('evidence', `File item needs path@hash: ${oneLine(item, 80)}`, at); continue; }
171
+ entry.files.push({ path: match[1], hash: match[2] });
172
+ }
173
+ }
174
+ }
175
+ for (const item of history) if (!item.hasFiles || !item.files.length) issue('evidence', `Entry ${item.date} · run ${item.run} lists no files.`, item.line - 1);
176
+ for (let i = 1; i < history.length; i++) if (history[i].date > history[i - 1].date) { issue('history-entry', 'Entries are not newest first.', history[i].line - 1); break; }
177
+ if (history.length && lastChange !== null) {
178
+ const newest = history[0];
179
+ if (lastChange === 'none recorded' || lastChange.run !== newest.run || lastChange.date !== newest.date) issue('last-change-current', `Newest entry is ${newest.date} · run ${newest.run}.`, lastIndex);
180
+ }
181
+ }
182
+ if (lines.length > maxDocLines) issue('size', `${lines.length} lines.`);
183
+ return { name, title, covers, lastChange, lessons, history, lines: lines.length, issues };
184
+ }
185
+
186
+ export function listDocs(root) {
187
+ const folder = local(root, contextFolder);
188
+ if (!existsSync(folder)) return [];
189
+ return readdirSync(folder).filter(name => name.endsWith('.md') && !reservedDocs.has(name) && lstatSync(join(folder, name)).isFile()).sort();
190
+ }
191
+
192
+ export function lintDoc(root, path) {
193
+ const parsed = parseDoc(read(root, path), fileName(path));
194
+ return { path, ok: !parsed.issues.length, ...parsed };
195
+ }
196
+
197
+ // ---------------------------------------------------------------- the index (table of contents)
198
+
199
+ const columnAliases = { component: ['component', 'area'], covers: ['covers'], doc: ['doc', 'record'], lastChange: ['last ai change'], lessons: ['lessons'] };
200
+
201
+ export function parseIndex(source) {
202
+ const lines = source.replace(/^/, '').replaceAll('\r\n', '\n').split('\n');
203
+ const table = { header: null, headerLine: -1, separatorLine: -1, columns: {}, rows: [], lines };
204
+ for (const [index, line] of lines.entries()) {
205
+ if (!/^\s*\|/.test(line)) { if (table.header && table.rows.length) break; table.header = null; continue; }
206
+ const cells = line.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map(c => c.trim().replaceAll('\\|', '|'));
207
+ if (!table.header) {
208
+ if (!cells.some(c => c.toLowerCase() === 'covers')) continue;
209
+ table.header = cells; table.headerLine = index;
210
+ for (const [key, aliases] of Object.entries(columnAliases)) table.columns[key] = cells.findIndex(c => aliases.includes(c.toLowerCase()));
211
+ continue;
212
+ }
213
+ if (cells.every(c => /^:?-+:?$/.test(c))) { table.separatorLine = index; continue; }
214
+ if (cells.length !== table.header.length) { table.rows.push({ line: index, malformed: true, cells }); continue; }
215
+ const cell = key => table.columns[key] >= 0 ? cells[table.columns[key]] : '';
216
+ const links = contextLinks(cell('doc'));
217
+ const link = cell('doc').match(/\[[^\]]+\]\(([^)#]+)[^)]*\)/);
218
+ table.rows.push({ line: index, cells, component: cell('component'), covers: cell('covers').replaceAll('`', '').split(',').map(p => p.trim()).filter(Boolean), docText: cell('doc'), links, link: link ? decodeURIComponent(link[1]) : null, lastChange: cell('lastChange'), lessons: cell('lessons') });
219
+ }
220
+ return table;
221
+ }
222
+
223
+ function resolveLink(root, link) {
224
+ if (!link || /^[a-z]+:/i.test(link)) return null;
225
+ return relative(root, resolve(dirname(local(root, indexName)), link)).replaceAll('\\', '/');
226
+ }
227
+
228
+ const git = (root, args, timeout = 5000) => spawnSync('git', ['--no-optional-locks', '-C', root, ...args], { encoding: 'utf8', windowsHide: true, timeout, maxBuffer: 16 * 1024 * 1024 });
229
+
230
+ function gitAvailable(root) {
231
+ const result = git(root, ['rev-parse', '--is-inside-work-tree']);
232
+ return result.status === 0 && result.stdout.trim() === 'true';
233
+ }
234
+ const pathspec = pattern => pattern === 'all' ? '.' : /[?*]/.test(pattern) ? `:(glob)${pattern}` : pattern;
235
+
236
+ // Freshness against Git: the doc's last commit against the last commit that touched a covered path.
237
+ // Same commit, or the doc committed later, is fresh. Uncommitted edits to covered paths are reported
238
+ // as dirty, never as stale: they have no commit yet, and the doc may be edited in the same change.
239
+ export function docFreshness(root, docPath, covers) {
240
+ if (!gitAvailable(root)) return { status: 'unknown', reason: 'Not a Git checkout; freshness was not compared.' };
241
+ const last = args => { const r = git(root, ['log', '-1', '--format=%H%x09%cI%x09%s', ...args]); if (r.status !== 0) throw Error(r.stderr.trim() || 'git log failed'); const [commit, date, subject] = r.stdout.trim().split('\t'); return commit ? { commit, date, subject } : null; };
242
+ let doc, coveredCommit;
243
+ try {
244
+ doc = last(['--', docPath]);
245
+ coveredCommit = covers.length ? last(['--', ...covers.map(pathspec)]) : null;
246
+ } catch (error) { return { status: 'unknown', reason: error.message }; }
247
+ const dirty = covers.length ? git(root, ['status', '--porcelain', '--', ...covers.map(pathspec)]) : { status: 0, stdout: '' };
248
+ const dirtyPaths = dirty.status === 0 ? dirty.stdout.split('\n').filter(Boolean).map(line => line.slice(3).trim()) : [];
249
+ if (!doc) return { status: 'uncommitted', reason: 'The doc has no commit yet.', coveredCommit, dirtyPaths };
250
+ if (!coveredCommit) return { status: 'fresh', docCommit: doc, coveredCommit: null, dirtyPaths };
251
+ // The doc's commit being an ancestor of the covered commit is decisive; dates only break a tie
252
+ // across branches, and two commits in the same second compare equal by date.
253
+ const later = coveredCommit.commit !== doc.commit && (git(root, ['merge-base', '--is-ancestor', doc.commit, coveredCommit.commit]).status === 0 || coveredCommit.date > doc.date);
254
+ if (later) return { status: 'stale', docCommit: doc, coveredCommit, dirtyPaths };
255
+ return { status: dirtyPaths.length ? 'dirty' : 'fresh', docCommit: doc, coveredCommit, dirtyPaths };
256
+ }
257
+
258
+ export function lintIndex(root, { git: checkGit = true } = {}) {
259
+ const issues = [];
260
+ const issue = (rule, message, line) => issues.push({ rule, message, ...(line !== undefined ? { line: line + 1 } : {}) });
261
+ const exists = existsSync(local(root, indexName));
262
+ const docs = listDocs(root);
263
+ const freshness = [];
264
+ if (!exists) {
265
+ if (docs.length) issue('toc-unindexed', `${indexName} is missing; ${docs.length} component doc(s) have no row.`);
266
+ return { path: indexName, exists, ok: !issues.length, rows: [], issues, freshness };
267
+ }
268
+ const table = parseIndex(read(root, indexName));
269
+ if (!table.header) { issue('toc-columns', 'No table with a Covers column.'); return { path: indexName, exists, ok: false, rows: [], issues, freshness }; }
270
+ for (const [key, index] of Object.entries(table.columns)) if (index === -1) issue('toc-columns', `Missing column ${columnAliases[key].join(' or ')}.`, table.headerLine);
271
+ const seen = new Map();
272
+ const rows = [];
273
+ for (const row of table.rows) {
274
+ if (row.malformed) { issue('toc-columns', 'Malformed row (cell count differs from the header).', row.line); continue; }
275
+ const docPath = resolveLink(root, row.link);
276
+ const entry = { line: row.line + 1, component: row.component, covers: row.covers, doc: docPath, componentDoc: false };
277
+ rows.push(entry);
278
+ if (!docPath) { if (row.docText && !row.link) issue('toc-link', `No link in the Doc cell: ${oneLine(row.docText, 60)}`, row.line); continue; }
279
+ if (!existsSync(local(root, docPath))) { issue('toc-link', `${docPath} does not exist.`, row.line); continue; }
280
+ if (!isComponentDoc(docPath)) continue;
281
+ entry.componentDoc = true;
282
+ if (seen.has(docPath)) issue('toc-unindexed', `${docPath} has more than one row (first at line ${seen.get(docPath) + 1}).`, row.line);
283
+ seen.set(docPath, row.line);
284
+ const parsed = lintDoc(root, docPath);
285
+ entry.docIssues = parsed.issues.length;
286
+ if ([...parsed.covers].sort().join(',') !== [...row.covers].sort().join(',')) issue('toc-covers', `Row covers [${row.covers.join(', ')}] but ${docPath} covers [${parsed.covers.join(', ')}].`, row.line);
287
+ const expectLast = parsed.lastChange && parsed.lastChange !== 'none recorded' ? `${parsed.lastChange.date} · run ${shortRun(parsed.lastChange.run)}` : 'none recorded';
288
+ if (table.columns.lastChange >= 0 && !row.lastChange.startsWith(expectLast)) issue('toc-last-change', `Row says "${oneLine(row.lastChange, 60)}", the doc says "${expectLast}".`, row.line);
289
+ const expectLessons = parsed.lessons.length ? String(parsed.lessons.length) : 'none';
290
+ if (table.columns.lessons >= 0 && !(row.lessons === expectLessons || row.lessons.startsWith(`${expectLessons} `))) issue('toc-lessons', `Row says "${oneLine(row.lessons, 60)}", the doc has ${parsed.lessons.length} lesson(s).`, row.line);
291
+ if (checkGit) {
292
+ const fresh = docFreshness(root, docPath, parsed.covers);
293
+ freshness.push({ doc: docPath, ...fresh });
294
+ if (fresh.status === 'stale') issue('stale-against-git', `${docPath}: ${fresh.coveredCommit.commit.slice(0, 7)} (${day(fresh.coveredCommit.date)}, ${oneLine(fresh.coveredCommit.subject, 60)}) touched covered paths after the doc's last commit ${fresh.docCommit.commit.slice(0, 7)} (${day(fresh.docCommit.date)}).`, row.line);
295
+ }
296
+ }
297
+ for (const name of docs) if (!seen.has(`${contextFolder}/${name}`)) issue('toc-unindexed', `${contextFolder}/${name} has no index row.`);
298
+ return { path: indexName, exists, ok: !issues.length, rows, issues, freshness };
299
+ }
300
+
301
+ const docSummary = result => ({ path: result.path, ok: result.ok, issues: result.issues, lines: result.lines, lessons: result.lessons.length, history: result.history.length });
302
+
303
+ export function lintContext(root, { doc, git: checkGit = true } = {}) {
304
+ root = realpathSync(root);
305
+ if (doc) {
306
+ const result = lintDoc(root, doc.replaceAll('\\', '/'));
307
+ return { ok: result.ok, docs: [docSummary(result)], rules, note: 'Structure rules only: a passing doc can still be wrong about its component.' };
308
+ }
309
+ const docs = listDocs(root).map(name => docSummary(lintDoc(root, `${contextFolder}/${name}`)));
310
+ const index = lintIndex(root, { git: checkGit });
311
+ return { ok: docs.every(d => d.ok) && index.ok, index: { path: index.path, exists: index.exists, ok: index.ok, issues: index.issues, freshness: index.freshness }, docs, rules, note: 'Structure and freshness rules only: a passing doc can still be wrong about its component, and a fresh doc is one whose covered paths have no later commit, not one that is correct.' };
312
+ }
313
+
314
+ // ---------------------------------------------------------------- run records
315
+
316
+ export function completedRuns(root) {
317
+ const folder = local(root, '.cyc/runs');
318
+ if (!existsSync(folder)) return [];
319
+ return readdirSync(folder).filter(name => existsSync(join(folder, name, 'state.json'))).flatMap(id => {
320
+ try { const state = readRun(root, id); return state.status === 'complete' ? [state] : []; }
321
+ catch { return []; }
322
+ });
323
+ }
324
+
325
+ function ledgerEntriesFor(root, state) {
326
+ const entries = [];
327
+ for (const path of new Set([state.projectLedgerPath, state.ledgerPath].filter(Boolean))) {
328
+ let source;
329
+ try { source = read(root, path); } catch { continue; }
330
+ let current = null;
331
+ for (const line of source.split('\n')) {
332
+ const heading = line.match(/^## (\S+)/);
333
+ if (heading) { current = { id: heading[1], title: oneLine(line.slice(3 + heading[1].length).replace(/^\s*\u00B7\s*/, ''), 120), path, mentions: false }; entries.push(current); continue; }
334
+ if (current && line.includes(state.id)) current.mentions = true;
335
+ }
336
+ }
337
+ return entries.filter(e => e.mentions).map(({ id, title, path }) => ({ id, title, path }));
338
+ }
339
+
340
+ // What a component doc entry needs, read from the run's own record: nothing here is invented, and
341
+ // a field the run did not record is said to be missing.
342
+ export function runRecord(root, state) {
343
+ const passed = stage => state.handoffs.findLast(h => h.stage === stage && h.status === 'passed');
344
+ const build = state.handoffs.filter(h => h.stage === 'build' && h.status === 'passed');
345
+ const deliver = passed('deliver'), verify = passed('verify');
346
+ const final = deliver ?? verify ?? build.at(-1);
347
+ const complete = state.history.find(h => h.type === 'complete');
348
+ const completedAt = complete?.time ?? final?.recordedAt ?? state.startedAt;
349
+ const date = day(completedAt);
350
+ const files = (final?.artifacts ?? []).map(({ path, sha256 }) => ({ path, sha256 }));
351
+ const learning = deliver?.assessment?.learning, errors = deliver?.assessment?.errorHistory;
352
+ const retries = state.history.filter(h => h.type === 'retry' && text(h.reason)).map(h => h.reason);
353
+ const failed = state.handoffs.filter(h => h.status === 'failed').map(h => h.summary);
354
+ const proof = state.testProof;
355
+ const exemption = verify?.assessment?.testProof;
356
+ const checks = (state.verification?.results ?? []).map(r => `${r.id} ${r.passed ? 'passed' : 'failed'} (exit ${r.exitCode})`);
357
+ const decisiveCheck = exemption?.status === 'exempt' ? `No test proof (exempt): ${oneLine(exemption.reason, 200)}`
358
+ : proof?.claim ? oneLine(proof.claim, 240)
359
+ : proof?.verdict ? oneLine(proof.verdict.split(/(?<=\.)\s/)[0], 240)
360
+ : 'No test proof recorded.';
361
+ const ledger = ledgerEntriesFor(root, state);
362
+ const lessons = [];
363
+ if (learning?.status === 'recorded' && text(learning.reason)) lessons.push(oneLine(learning.reason, 400));
364
+ if (errors?.status === 'recorded' && text(errors.reason)) lessons.push(oneLine(errors.reason, 400));
365
+ for (const reason of retries) lessons.push(`Retry: ${oneLine(reason, 400)}`);
366
+ for (const entry of ledger) lessons.push(`Ledger ${entry.id}: ${entry.title}`);
367
+ const contextDocs = deliver?.contextDocs ?? files.map(f => f.path).filter(p => p.startsWith(`${contextFolder}/`) && p.endsWith('.md'));
368
+ return { runId: state.id, date, completedAt, goal: state.goal, playbook: state.playbook, status: state.status, session: state.session ?? null, files,
369
+ changed: build.map(h => oneLine(h.summary.replace(/^Built: /, ''), 400)),
370
+ learning: learning ? { status: learning.status, reason: oneLine(learning.reason, 400), artifacts: learning.artifacts ?? [] } : null,
371
+ errorHistory: errors ? { status: errors.status, reason: oneLine(errors.reason, 400), artifacts: errors.artifacts ?? [] } : null,
372
+ retries, failedHandoffs: failed, failures: state.failures ?? 0, ledgerEntries: ledger, decisiveCheck, checks, lessons: [...new Set(lessons)], contextDocs };
373
+ }
374
+
375
+ function entryMarkdown(record, files) {
376
+ const learned = record.lessons.length ? record.lessons.join(' ') : 'No reusable learning recorded for this run.';
377
+ return [
378
+ `### ${record.date} · run ${record.runId} · ${oneLine(record.goal, 100)}`,
379
+ `**Changed:** ${record.changed.join(' ') || 'No Build summary recorded.'}`,
380
+ `**Learned:** ${learned}`,
381
+ `**Decisive check:** ${record.decisiveCheck}${record.checks.length ? ` Checks: ${record.checks.join(', ')}.` : ''}`,
382
+ `**Files:** ${files.map(f => `${f.path}@sha256:${f.sha256.slice(0, 12)}`).join(', ')}`
383
+ ].join('\n');
384
+ }
385
+ const lessonBullets = record => record.lessons.map(lesson => `- ${record.date} · run ${shortRun(record.runId)}: ${lesson}`);
386
+
387
+ // ---------------------------------------------------------------- review: propose and write
388
+
389
+ function componentsOf(root) {
390
+ const exists = existsSync(local(root, indexName));
391
+ const table = exists ? parseIndex(read(root, indexName)) : { rows: [] };
392
+ const components = table.rows.filter(row => !row.malformed).flatMap(row => (row.links.length ? row.links : [null]).map(link => {
393
+ const doc = resolveLink(root, link);
394
+ return { component: row.component, covers: row.covers, doc, inFolder: isComponentDoc(doc) };
395
+ }));
396
+ return { exists, components };
397
+ }
398
+
399
+ function recordedRuns(root, docs) {
400
+ const runs = new Map();
401
+ for (const name of docs) {
402
+ const parsed = parseDoc(read(root, `${contextFolder}/${name}`), name);
403
+ for (const entry of parsed.history) runs.set(entry.run, [...(runs.get(entry.run) ?? []), `${contextFolder}/${name}`]);
404
+ }
405
+ return runs;
406
+ }
407
+
408
+ function newDocSource(title, covers) {
409
+ return `# ${title}\n\nCovers: ${covers.join(', ')}\n\nLast changed by AI: none recorded\n\n## Current view\n\n<Write what the code cannot tell a reader: the invariant, its writers and readers, the adopted decisions and the known dead ends.>\n\n## Lessons\n\n## History\n`;
410
+ }
411
+
412
+ // Insert the entry under History and the lessons under Lessons, newest first, and set the
413
+ // last-change line. The Current view is the author's; it is never edited here.
414
+ export function applyEntry(source, { entry, lessons, lastChange }) {
415
+ const lines = source.replaceAll('\r\n', '\n').split('\n');
416
+ const at = name => lines.findIndex(line => line === `## ${name}`);
417
+ const history = at('History'), lessonsAt = at('Lessons'), last = lines.findIndex(line => /^Last changed by AI:/.test(line));
418
+ if (history === -1 || lessonsAt === -1 || last === -1) throw Error('The doc lacks the fixed layout (Last changed by AI line, ## Lessons, ## History); fix it with cyc context lint before writing to it.');
419
+ const entryDate = entry.split('\n')[0].match(historyHeading)?.[1];
420
+ const existing = lines.flatMap((line, index) => index > history && historyHeading.test(line) ? [{ index, date: line.match(historyHeading)[1] }] : []);
421
+ const insertion = existing.find(item => item.date <= entryDate)?.index ?? (existing.length ? lines.length : history + 1);
422
+ lines.splice(insertion, 0, '', ...entry.split('\n'), '');
423
+ if (lessons.length) {
424
+ const bullets = lines.flatMap((line, index) => index > lessonsAt && index < at('History') && lessonLine.test(line) ? [{ index, date: line.match(lessonLine)[1] }] : []);
425
+ const lessonDate = lessons[0].match(lessonLine)?.[1];
426
+ const first = bullets.find(item => item.date <= lessonDate)?.index ?? (bullets.length ? at('History') : lessonsAt + 1);
427
+ lines.splice(first, 0, '', ...lessons);
428
+ }
429
+ // Catching up an older missing run must not relabel a newer current view.
430
+ if (!existing.length || entryDate >= existing[0].date) lines[last] = lastChange;
431
+ return `${lines.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\n*$/, '')}\n`;
432
+ }
433
+
434
+ function indexCells(root, docPath) {
435
+ const parsed = parseDoc(read(root, docPath), fileName(docPath));
436
+ const last = parsed.lastChange && parsed.lastChange !== 'none recorded' ? `${parsed.lastChange.date} · run ${shortRun(parsed.lastChange.run)}${parsed.history[0]?.title ? ` · ${oneLine(parsed.history[0].title, 80)}` : ''}` : 'none recorded';
437
+ const lessons = parsed.lessons.length ? `${parsed.lessons.length} · latest: ${oneLine(parsed.lessons[0].text, 80)}` : 'none';
438
+ return { parsed, last, lessons };
439
+ }
440
+
441
+ function refreshIndex(root) {
442
+ const table = parseIndex(read(root, indexName));
443
+ if (!table.header) throw Error(`${indexName} has no table with a Covers column.`);
444
+ const lines = table.lines;
445
+ const columns = { ...table.columns };
446
+ const width = table.header.length;
447
+ const added = [];
448
+ for (const [key, label] of [['lastChange', 'Last AI change'], ['lessons', 'Lessons']]) if (columns[key] === -1) { columns[key] = width + added.length; added.push(label); }
449
+ const render = cells => `| ${cells.map(c => c.replaceAll('|', '\\|')).join(' | ')} |`;
450
+ if (added.length) {
451
+ lines[table.headerLine] = render([...table.header, ...added]);
452
+ if (table.separatorLine >= 0) lines[table.separatorLine] = render([...Array(width + added.length)].map(() => '---'));
453
+ }
454
+ const seen = new Set();
455
+ for (const row of table.rows) {
456
+ if (row.malformed) continue;
457
+ const docPath = resolveLink(root, row.link);
458
+ const cells = [...row.cells, ...added.map(() => '')];
459
+ if (isComponentDoc(docPath) && existsSync(local(root, docPath))) {
460
+ seen.add(docPath);
461
+ const { parsed, last, lessons } = indexCells(root, docPath);
462
+ if (parsed.covers.length) cells[columns.covers] = parsed.covers.join(', ');
463
+ cells[columns.lastChange] = last; cells[columns.lessons] = lessons;
464
+ }
465
+ lines[row.line] = render(cells);
466
+ }
467
+ const lastRow = table.rows.length ? table.rows.at(-1).line : table.separatorLine;
468
+ const appended = [];
469
+ for (const name of listDocs(root)) {
470
+ const docPath = `${contextFolder}/${name}`;
471
+ if (seen.has(docPath)) continue;
472
+ const { parsed, last, lessons } = indexCells(root, docPath);
473
+ const cells = [...Array(width + added.length)].map(() => '');
474
+ if (columns.component >= 0) cells[columns.component] = parsed.title ?? name;
475
+ cells[columns.covers] = parsed.covers.join(', ');
476
+ cells[columns.doc] = `[${parsed.title ?? name}](${name})`;
477
+ cells[columns.lastChange] = last; cells[columns.lessons] = lessons;
478
+ appended.push(render(cells));
479
+ }
480
+ lines.splice(lastRow + 1, 0, ...appended);
481
+ atomicWrite(local(root, indexName), `${lines.join('\n').replace(/\n*$/, '')}\n`);
482
+ return { addedColumns: added, addedRows: appended.length };
483
+ }
484
+
485
+ export function reviewContext(root, { run, since, all = false, write = false, newDoc } = {}) {
486
+ root = realpathSync(root);
487
+ if (newDoc !== undefined && (!docFileName.test(`${newDoc}.md`) || reservedDocs.has(`${newDoc}.md`))) throw Error(`--new needs a kebab-case component name (${docFileName.source} without .md).`);
488
+ if (since !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(since)) throw Error('--since needs YYYY-MM-DD.');
489
+ const { exists, components } = componentsOf(root);
490
+ const docs = listDocs(root);
491
+ const recorded = recordedRuns(root, docs);
492
+ let states;
493
+ if (run) {
494
+ const state = readRun(root, run);
495
+ if (state.status !== 'complete') throw Error(`Run ${run} is ${state.status}; context proposals come from completed runs.`);
496
+ states = [state];
497
+ } else states = completedRuns(root);
498
+ const records = states.map(state => runRecord(root, state)).filter(record => !since || record.date >= since).sort((a, b) => a.completedAt.localeCompare(b.completedAt) || a.runId.localeCompare(b.runId));
499
+ const proposals = [];
500
+ const unmappedAll = new Map();
501
+ for (const record of records) {
502
+ const perComponent = new Map();
503
+ const unmapped = [];
504
+ const retained = new Set([...record.contextDocs, ...(record.learning?.artifacts ?? []), ...(record.errorHistory?.artifacts ?? [])]);
505
+ for (const file of record.files) {
506
+ let mapped = false;
507
+ for (const component of components) {
508
+ if (!covered(component.covers, file.path)) continue;
509
+ mapped = true;
510
+ const key = component.doc ?? component.component;
511
+ if (!perComponent.has(key)) perComponent.set(key, { ...component, files: [] });
512
+ perComponent.get(key).files.push(file);
513
+ }
514
+ if (!mapped && !retained.has(file.path)) unmapped.push(file);
515
+ }
516
+ const proposal = { runId: record.runId, date: record.date, goal: record.goal, playbook: record.playbook, contextDocsTouched: record.contextDocs,
517
+ components: [...perComponent.values()].map(component => {
518
+ const alreadyRecorded = (recorded.get(record.runId) ?? []).includes(component.doc);
519
+ const touched = !!component.doc && (record.contextDocs.includes(component.doc) || (record.learning?.artifacts ?? []).includes(component.doc));
520
+ return { component: component.component, doc: component.doc, writable: component.inFolder, touched, alreadyRecorded, shouldHaveBeenTouched: !touched && component.inFolder, files: component.files, entry: entryMarkdown(record, component.files), lessons: lessonBullets(record) };
521
+ }),
522
+ unmapped, lessons: record.lessons, decisiveCheck: record.decisiveCheck, learning: record.learning, errorHistory: record.errorHistory, ledgerEntries: record.ledgerEntries };
523
+ // A run is caught up only when every writable component has its entry and no changed file
524
+ // remains unmapped. Explicit --run/--all keep the complete diagnostic view.
525
+ if (!run && !all && recorded.has(record.runId) && !unmapped.length && !proposal.components.some(component => component.writable && !component.alreadyRecorded)) continue;
526
+ if (unmapped.length && newDoc) {
527
+ const path = `${contextFolder}/${newDoc}.md`;
528
+ proposal.newDoc = { path, covers: unmapped.map(f => f.path), entry: entryMarkdown(record, unmapped), lessons: lessonBullets(record), exists: existsSync(local(root, path)) };
529
+ }
530
+ for (const file of unmapped) unmappedAll.set(file.path, [...(unmappedAll.get(file.path) ?? []), record.runId]);
531
+ proposals.push(proposal);
532
+ }
533
+ const result = { ok: true, index: { path: indexName, exists, components: components.length, componentDocs: docs.length }, runs: proposals, unmappedFiles: [...unmappedAll].map(([path, runs]) => ({ path, runs })), written: null,
534
+ note: write ? 'Entries were appended from the runs\' own records; the Current view of each doc is yours to update. Review the diff before committing.' : 'Read-only proposal from completed run records: nothing was written. Add --write to append these entries and refresh the index; --new NAME creates a doc for unmapped files.' };
535
+ if (!write) return result;
536
+ const written = [];
537
+ for (const proposal of proposals) {
538
+ for (const component of proposal.components) {
539
+ if (!component.writable || component.alreadyRecorded) continue;
540
+ const source = read(root, component.doc);
541
+ const parsed = parseDoc(source, fileName(component.doc));
542
+ const blocking = parsed.issues.filter(i => ['sections', 'last-change', 'title'].includes(i.rule));
543
+ if (blocking.length) { written.push({ doc: component.doc, runId: proposal.runId, written: false, reason: `Fix first: ${blocking.map(i => `${i.rule} (${i.message})`).join('; ')}` }); continue; }
544
+ const lastChange = `Last changed by AI: ${proposal.date} · run ${proposal.runId} · files: ${component.files.map(f => f.path).join(', ')}`;
545
+ atomicWrite(local(root, component.doc), applyEntry(source, { entry: component.entry, lessons: component.lessons, lastChange }));
546
+ recorded.set(proposal.runId, [...(recorded.get(proposal.runId) ?? []), component.doc]);
547
+ written.push({ doc: component.doc, runId: proposal.runId, written: true });
548
+ }
549
+ if (proposal.newDoc) {
550
+ const { path, covers, entry, lessons } = proposal.newDoc;
551
+ const title = newDoc.split('-').map((w, i) => i ? w : w[0].toUpperCase() + w.slice(1)).join(' ');
552
+ const source = existsSync(local(root, path)) ? read(root, path) : newDocSource(title, covers);
553
+ if (parseDoc(source, `${newDoc}.md`).history.some(e => e.run === proposal.runId)) continue;
554
+ atomicWrite(local(root, path), applyEntry(source, { entry, lessons, lastChange: `Last changed by AI: ${proposal.date} · run ${proposal.runId} · files: ${covers.join(', ')}` }));
555
+ written.push({ doc: path, runId: proposal.runId, written: true, created: !proposal.newDoc.exists });
556
+ }
557
+ }
558
+ let index = null;
559
+ if (written.some(w => w.written)) {
560
+ if (!existsSync(local(root, indexName))) atomicWrite(local(root, indexName), '# Context index\n\nRead the index, then the docs whose Covers match the paths you are about to change.\n\n| Component | Covers | Doc | Last AI change | Lessons |\n| --- | --- | --- | --- | --- |\n');
561
+ index = refreshIndex(root);
562
+ }
563
+ const lint = lintContext(root, { git: false });
564
+ return { ...result, written, indexRefreshed: index, lint: { ok: lint.ok, index: lint.index.issues, docs: lint.docs.filter(d => !d.ok).map(d => ({ path: d.path, issues: d.issues })) } };
565
+ }
566
+
567
+ // ---------------------------------------------------------------- measure: what the index path costs
568
+
569
+ const codePoints = value => [...value].length;
570
+ const tokensEstimate = chars => Math.round(chars / 4);
571
+
572
+ export function measureContext(root, { paths = [], run } = {}) {
573
+ root = realpathSync(root);
574
+ if (!Array.isArray(paths)) throw Error('Paths must be an array.');
575
+ const { exists, components } = componentsOf(root);
576
+ if (!exists) throw Error(`${indexName} does not exist; nothing to measure.`);
577
+ const size = path => { const source = read(root, path); return { path, bytes: Buffer.byteLength(source), chars: codePoints(source) }; };
578
+ const sum = items => items.reduce((total, item) => ({ bytes: total.bytes + item.bytes, chars: total.chars + item.chars }), { bytes: 0, chars: 0 });
579
+ const folder = local(root, contextFolder);
580
+ const allDocs = readdirSync(folder).filter(name => name.endsWith('.md') && lstatSync(join(folder, name)).isFile()).sort().map(name => size(`${contextFolder}/${name}`));
581
+ if (run) {
582
+ const state = readRun(root, run);
583
+ const final = state.handoffs.findLast(h => ['deliver', 'verify', 'build'].includes(h.stage) && h.status === 'passed');
584
+ paths = [...new Set([...paths, ...(final?.artifacts ?? []).map(a => a.path)])];
585
+ }
586
+ for (const path of paths) canonicalPattern(path, { patterns: false });
587
+ const matchedDocs = new Set(components.filter(c => c.doc && existsSync(local(root, c.doc)) && paths.some(path => covered(c.covers, path))).map(c => c.doc));
588
+ matchedDocs.delete(indexName);
589
+ const tocPathFiles = [size(indexName), ...[...matchedDocs].sort().map(size)];
590
+ const tocPath = sum(tocPathFiles), all = sum(allDocs);
591
+ const runRecords = completedRuns(root).map(state => {
592
+ const files = [`.cyc/runs/${state.id}/state.json`, `.cyc/runs/${state.id}/review.md`].filter(path => existsSync(local(root, path))).map(size);
593
+ return { runId: state.id, ...sum(files) };
594
+ });
595
+ const sorted = [...runRecords].sort((a, b) => a.chars - b.chars);
596
+ const median = sorted.length ? sorted[Math.floor(sorted.length / 2)].chars : null;
597
+ return { ok: true, paths, tocPath: { files: tocPathFiles, ...tocPath, approxTokens: tokensEstimate(tocPath.chars) }, allDocs: { files: allDocs.length, ...all, approxTokens: tokensEstimate(all.chars) },
598
+ runRecords: { runs: runRecords.length, ...sum(runRecords), approxTokens: tokensEstimate(sum(runRecords).chars), medianChars: median, medianApproxTokens: median === null ? null : tokensEstimate(median) },
599
+ note: 'Characters are Unicode code points; approxTokens divides by 4, a rough estimate, no tokenizer was run. Run records are the controller\'s state.json and review.md, not the chat transcript, which this tool cannot see. A smaller read is not evidence that the next task succeeds with it.' };
600
+ }