circle-ir-ai 4.34.0 → 4.35.2

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 (100) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/agents/mastra/workflow.d.ts +9 -0
  3. package/dist/agents/mastra/workflow.d.ts.map +1 -1
  4. package/dist/agents/mastra/workflow.js +12 -3
  5. package/dist/agents/mastra/workflow.js.map +1 -1
  6. package/dist/grid/index.d.ts +9 -0
  7. package/dist/grid/index.d.ts.map +1 -1
  8. package/dist/grid/index.js +19 -5
  9. package/dist/grid/index.js.map +1 -1
  10. package/dist/selectors/detect.d.ts +2 -0
  11. package/dist/selectors/detect.d.ts.map +1 -1
  12. package/dist/selectors/detect.js +1 -1
  13. package/dist/selectors/detect.js.map +1 -1
  14. package/dist/spec-gap/analyzer.js +30 -4
  15. package/dist/spec-gap/analyzer.js.map +1 -1
  16. package/dist/specifica/environment/diff.d.ts.map +1 -1
  17. package/dist/specifica/environment/diff.js +10 -2
  18. package/dist/specifica/environment/diff.js.map +1 -1
  19. package/dist/specifica/environment/index.d.ts +20 -3
  20. package/dist/specifica/environment/index.d.ts.map +1 -1
  21. package/dist/specifica/environment/index.js +40 -10
  22. package/dist/specifica/environment/index.js.map +1 -1
  23. package/dist/specifica/environment/merge.d.ts +12 -0
  24. package/dist/specifica/environment/merge.d.ts.map +1 -1
  25. package/dist/specifica/environment/merge.js +29 -6
  26. package/dist/specifica/environment/merge.js.map +1 -1
  27. package/dist/specifica/environment/read-ci.d.ts.map +1 -1
  28. package/dist/specifica/environment/read-ci.js +3 -2
  29. package/dist/specifica/environment/read-ci.js.map +1 -1
  30. package/dist/specifica/environment/read-compose.d.ts +17 -0
  31. package/dist/specifica/environment/read-compose.d.ts.map +1 -0
  32. package/dist/specifica/environment/read-compose.js +96 -0
  33. package/dist/specifica/environment/read-compose.js.map +1 -0
  34. package/dist/specifica/environment/read-docker.js +2 -2
  35. package/dist/specifica/environment/read-docker.js.map +1 -1
  36. package/dist/specifica/environment/read-dotenv.js +3 -3
  37. package/dist/specifica/environment/read-dotenv.js.map +1 -1
  38. package/dist/specifica/environment/read-wrangler.js +2 -2
  39. package/dist/specifica/environment/read-wrangler.js.map +1 -1
  40. package/dist/specifica/environment/secrets.d.ts +17 -2
  41. package/dist/specifica/environment/secrets.d.ts.map +1 -1
  42. package/dist/specifica/environment/secrets.js +67 -12
  43. package/dist/specifica/environment/secrets.js.map +1 -1
  44. package/dist/specifica/environment/write.d.ts +24 -1
  45. package/dist/specifica/environment/write.d.ts.map +1 -1
  46. package/dist/specifica/environment/write.js +183 -73
  47. package/dist/specifica/environment/write.js.map +1 -1
  48. package/dist/specifica/file-routes.d.ts +89 -0
  49. package/dist/specifica/file-routes.d.ts.map +1 -0
  50. package/dist/specifica/file-routes.js +374 -0
  51. package/dist/specifica/file-routes.js.map +1 -0
  52. package/dist/specifica/generator.d.ts.map +1 -1
  53. package/dist/specifica/generator.js +124 -2
  54. package/dist/specifica/generator.js.map +1 -1
  55. package/dist/specifica/index.d.ts +4 -1
  56. package/dist/specifica/index.d.ts.map +1 -1
  57. package/dist/specifica/index.js +4 -1
  58. package/dist/specifica/index.js.map +1 -1
  59. package/dist/specifica/layering.d.ts +140 -0
  60. package/dist/specifica/layering.d.ts.map +1 -0
  61. package/dist/specifica/layering.js +365 -0
  62. package/dist/specifica/layering.js.map +1 -0
  63. package/dist/specifica/learned-diff.d.ts +15 -1
  64. package/dist/specifica/learned-diff.d.ts.map +1 -1
  65. package/dist/specifica/learned-diff.js +63 -21
  66. package/dist/specifica/learned-diff.js.map +1 -1
  67. package/dist/specifica/learned-tree.d.ts +4 -0
  68. package/dist/specifica/learned-tree.d.ts.map +1 -1
  69. package/dist/specifica/learned-tree.js.map +1 -1
  70. package/dist/specifica/level-design.d.ts +170 -0
  71. package/dist/specifica/level-design.d.ts.map +1 -0
  72. package/dist/specifica/level-design.js +1253 -0
  73. package/dist/specifica/level-design.js.map +1 -0
  74. package/dist/specifica/library-surface.d.ts +62 -0
  75. package/dist/specifica/library-surface.d.ts.map +1 -0
  76. package/dist/specifica/library-surface.js +348 -0
  77. package/dist/specifica/library-surface.js.map +1 -0
  78. package/dist/specifica/modules.d.ts +37 -0
  79. package/dist/specifica/modules.d.ts.map +1 -0
  80. package/dist/specifica/modules.js +536 -0
  81. package/dist/specifica/modules.js.map +1 -0
  82. package/dist/specifica/spec-tree.d.ts +150 -0
  83. package/dist/specifica/spec-tree.d.ts.map +1 -0
  84. package/dist/specifica/spec-tree.js +689 -0
  85. package/dist/specifica/spec-tree.js.map +1 -0
  86. package/dist/specifica/tree-types.d.ts +228 -0
  87. package/dist/specifica/tree-types.d.ts.map +1 -0
  88. package/dist/specifica/tree-types.js +35 -0
  89. package/dist/specifica/tree-types.js.map +1 -0
  90. package/dist/specifica/tree-writer.d.ts +133 -0
  91. package/dist/specifica/tree-writer.d.ts.map +1 -0
  92. package/dist/specifica/tree-writer.js +402 -0
  93. package/dist/specifica/tree-writer.js.map +1 -0
  94. package/dist/specifica/types.d.ts +40 -0
  95. package/dist/specifica/types.d.ts.map +1 -1
  96. package/dist/specifica/use-cases.d.ts +80 -0
  97. package/dist/specifica/use-cases.d.ts.map +1 -0
  98. package/dist/specifica/use-cases.js +888 -0
  99. package/dist/specifica/use-cases.js.map +1 -0
  100. package/package.json +1 -1
@@ -0,0 +1,689 @@
1
+ /**
2
+ * Spec recovery 0.2 integration: build the learned Specifica tree for a
3
+ * directory (techspec `spec-recovery/.specifica/0.2/design.md` §1–§2).
4
+ *
5
+ * detectModules (SR-E1) → per level (repository, each module):
6
+ * use cases (SR-E2) → layer classification (SR-E3: domain → spec, layers
7
+ * → one line per layer in principles, shared lines lifted to the parent)
8
+ * → spec.md (use cases grouped by area, domain rules only)
9
+ * → design.md (SR-E4) → principles.md (layer lines + learned conventions)
10
+ * → environment.md at the root (existing learner) → tasks.md empty
11
+ * → writeSpecTree (SR-E5).
12
+ *
13
+ * Size (spec §2 rule 3, default pending Eyal's confirmation): a spec.md that
14
+ * does not fit ~100 lines first drops the per-rule `from:` lines (rules.json
15
+ * keeps every code path), then lists one table row per area with its use
16
+ * cases; rules that still do not fit are counted and stay in rules.json. A
17
+ * package is never split into modules (Eyal's rule); too many areas merge into
18
+ * one "Other areas" row.
19
+ *
20
+ * Model arm (opt-in, `skipLLM` false): one call per level may phrase use-case
21
+ * sentences and principle lines from the deterministic facts only. Each
22
+ * phrase is keyed to a use case id or a layer that the static arm found;
23
+ * anything else in the answer is dropped, so the model never adds a module,
24
+ * a use case or a rule. Phrases are shown as `suggested · llm: <model>`. The
25
+ * static arm produces the complete tree alone.
26
+ *
27
+ * Deterministic on the static arm: inputs sorted, no timestamps; same source
28
+ * and engine version → same bytes and rule keys.
29
+ */
30
+ import * as fs from 'fs';
31
+ import * as path from 'path';
32
+ import { createHash } from 'node:crypto';
33
+ import { detectModules } from './modules.js';
34
+ import { extractUseCases } from './use-cases.js';
35
+ import { classifyRules, formatLayerLines, layerName, liftSharedLines, summarizeLevel, } from './layering.js';
36
+ import { generateLevelDesigns } from './level-design.js';
37
+ import { generateFallbackSpec } from './spec-generator.js';
38
+ import { aggregateEvidence } from './evidence-aggregator.js';
39
+ import { generatePrinciples } from './principles-generator.js';
40
+ import { assignRuleKeys, formatProvenanceLine, relativizeProvenance, summarizeProvenance, SPEC_PROVENANCE_SCHEME } from './provenance.js';
41
+ import { DEFAULT_SPEC_VERSION, resolveSpecVersion } from './learned-tree.js';
42
+ import { flattenLevels, levelFilePaths, moduleLevelPath, normalizeMarkdown, writeSpecTree } from './tree-writer.js';
43
+ import { ENVIRONMENT_FOLDER_FILES, LEVEL_LINE_BUDGET } from './tree-types.js';
44
+ // ─── Helpers ─────────────────────────────────────────────────────────
45
+ /** Not product code: tests, fixtures, benchmark corpora, examples. Their entry points are not the product's use cases. */
46
+ const TEST_FILE = /(^|\/)(__tests__|__mocks__|tests?|spec|e2e|fixtures?|benchmarks?|testcode|testdata|examples?|samples?)\/|\.(test|spec|e2e|tp)\.[cm]?[jt]sx?$|(^|\/)test\.[jt]s$|Test\.java$|_test\.(go|py)$/;
47
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
48
+ function isUnder(root, rel) {
49
+ return root === '' || rel === root || rel.startsWith(`${root}/`);
50
+ }
51
+ /** The deepest module that contains `rel`, or undefined (repository level). */
52
+ function ownerOf(rel, modules) {
53
+ let best;
54
+ for (const m of modules)
55
+ if (isUnder(m.root, rel) && (!best || m.root.length > best.root.length))
56
+ best = m;
57
+ return best;
58
+ }
59
+ function readText(p) {
60
+ try {
61
+ return fs.readFileSync(p, 'utf-8');
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ }
67
+ /** Direct dependencies a level's manifest declares (npm, Cargo, Go). */
68
+ export function manifestDependencies(projectRoot, root) {
69
+ const dir = path.join(projectRoot, root || '.');
70
+ const out = [];
71
+ const pkg = readText(path.join(dir, 'package.json'));
72
+ if (pkg) {
73
+ try {
74
+ const j = JSON.parse(pkg);
75
+ for (const n of Object.keys({ ...(j.dependencies ?? {}), ...(j.peerDependencies ?? {}) }))
76
+ out.push({ name: n, ecosystem: 'npm' });
77
+ }
78
+ catch { /* not JSON */ }
79
+ }
80
+ const cargo = readText(path.join(dir, 'Cargo.toml'));
81
+ if (cargo) {
82
+ const sec = /^\[(?:workspace\.)?dependencies\]\s*$([\s\S]*?)(?=^\[|$(?![\s\S]))/m.exec(cargo)?.[1] ?? '';
83
+ for (const line of sec.split('\n')) {
84
+ const m = /^\s*([A-Za-z0-9_-]+)\s*=/.exec(line);
85
+ if (m)
86
+ out.push({ name: m[1], ecosystem: 'cargo' });
87
+ }
88
+ }
89
+ const gomod = readText(path.join(dir, 'go.mod'));
90
+ if (gomod) {
91
+ for (const m of gomod.matchAll(/^\s*(?:require\s+)?([a-z0-9.-]+\.[a-z]+\/[^\s]+)\s+v[\d.]+/gm))
92
+ out.push({ name: m[1], ecosystem: 'golang' });
93
+ }
94
+ const seen = new Set();
95
+ return out.filter(d => (seen.has(d.name) ? false : (seen.add(d.name), true))).sort((a, b) => cmp(a.name, b.name));
96
+ }
97
+ const LANG_ECOSYSTEM = {
98
+ typescript: 'npm', javascript: 'npm', python: 'pypi', rust: 'cargo', go: 'golang', java: 'maven',
99
+ };
100
+ function fileDependencies(files) {
101
+ const out = {};
102
+ for (const f of files) {
103
+ const eco = LANG_ECOSYSTEM[f.evidence.language];
104
+ const deps = f.evidence.imports
105
+ .map(i => i.module)
106
+ .filter(m => m && !m.startsWith('.') && !m.startsWith('/'))
107
+ .map(m => (m.startsWith('@') ? m.split('/').slice(0, 2).join('/') : m.startsWith('node:') ? m : m.split('/')[0]));
108
+ out[f.rel] = [...new Set(deps)].sort().map(name => ({ name, ...(eco ? { ecosystem: eco } : {}) }));
109
+ }
110
+ return out;
111
+ }
112
+ /** Worker entry files: the `main` of each wrangler config inside the level. */
113
+ function workerEntryFiles(projectRoot, files) {
114
+ const dirs = new Set(['']);
115
+ for (const f of files) {
116
+ const parts = f.rel.split('/');
117
+ for (let i = 1; i < parts.length; i++)
118
+ dirs.add(parts.slice(0, i).join('/'));
119
+ }
120
+ const out = new Set();
121
+ for (const d of [...dirs].sort()) {
122
+ for (const name of ['wrangler.toml', 'wrangler.json', 'wrangler.jsonc']) {
123
+ const text = readText(path.join(projectRoot, d, name));
124
+ if (!text)
125
+ continue;
126
+ const main = /^\s*main\s*=\s*["']([^"']+)["']/m.exec(text)?.[1] ?? /"main"\s*:\s*"([^"]+)"/.exec(text)?.[1];
127
+ if (main)
128
+ out.add(path.posix.normalize(path.posix.join(d, main)));
129
+ }
130
+ }
131
+ return [...out].sort();
132
+ }
133
+ /** The level's parsed `package.json` (its `exports` name a library's entry files), if any. */
134
+ function readManifest(projectRoot, sourceRoot) {
135
+ const text = readText(path.join(projectRoot, sourceRoot, 'package.json'));
136
+ if (!text)
137
+ return undefined;
138
+ try {
139
+ return JSON.parse(text);
140
+ }
141
+ catch {
142
+ return undefined;
143
+ }
144
+ }
145
+ /** The repository's display name: its manifest name, else its folder. */
146
+ function repoName(projectRoot) {
147
+ const pkg = readText(path.join(projectRoot, 'package.json'));
148
+ if (pkg) {
149
+ try {
150
+ const n = JSON.parse(pkg).name;
151
+ if (n)
152
+ return n;
153
+ }
154
+ catch { /* ignore */ }
155
+ }
156
+ return path.basename(path.resolve(projectRoot));
157
+ }
158
+ function hashKey(prefix, ...parts) {
159
+ return `${prefix}-${createHash('sha256').update(parts.join('\u0000')).digest('hex').slice(0, 20)}`;
160
+ }
161
+ function cell(s) {
162
+ return s.replace(/\|/g, '\\|').replace(/\n/g, ' ');
163
+ }
164
+ function oneLine(s, max = 200) {
165
+ const t = s.replace(/\s+/g, ' ').trim();
166
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
167
+ }
168
+ function lineCount(text) {
169
+ const t = normalizeMarkdown(text);
170
+ return t ? t.replace(/\n$/, '').split('\n').length : 0;
171
+ }
172
+ // ─── spec.md ─────────────────────────────────────────────────────────
173
+ const MODEL_MARK = (model) => `_(suggested · llm: ${model})_`;
174
+ function anchorOf(u) {
175
+ const a = u.codePaths[0];
176
+ return a ? `\`${a.file}:${a.startLine}\`` : `\`${u.entry.file}\``;
177
+ }
178
+ function triggerOf(u) {
179
+ const e = u.entry;
180
+ if (e.kind === 'route')
181
+ return [e.method, e.path ?? `in ${e.symbol}`].filter(Boolean).join(' ');
182
+ if (e.kind === 'public-api')
183
+ return u.surface ? `${u.area} (${u.surface.exports} exports)` : `${e.symbol}()`;
184
+ return [e.method, e.path ?? e.symbol].filter(Boolean).join(' ');
185
+ }
186
+ function ruleLine(r, indent, withFrom) {
187
+ const priority = r.priority === 'must' ? '**MUST**' : r.priority === 'should' ? 'SHOULD' : 'COULD';
188
+ // A quoted condition can span lines in the code; a rule is always one line here.
189
+ const out = [`${indent}- [ ] **${r.id}**: ${priority} ${oneLine(r.description, 240)}`];
190
+ if (withFrom && r.provenance)
191
+ out.push(`${indent} - ${formatProvenanceLine(r.provenance)}${r.ruleKey ? ` · ${r.ruleKey}` : ''}`);
192
+ return out;
193
+ }
194
+ function specHeader(inp, areas, ruleCount) {
195
+ const out = [`# Spec — ${inp.title}`, ''];
196
+ out.push('> Learned from code: use cases from entry points, grouped by area, and the domain rules behind them. Layer rules (L1–L8) are one line each in principles.md. Review before promoting a rule to intent.', '');
197
+ out.push(`${inp.useCases.length} use case(s) in ${areas.length} area(s) · ${ruleCount} domain rule(s).`, '');
198
+ if (inp.childNote)
199
+ out.push(inp.childNote, '');
200
+ return out;
201
+ }
202
+ function areasOf(useCases) {
203
+ const out = [];
204
+ for (const u of useCases)
205
+ if (!out.includes(u.area))
206
+ out.push(u.area);
207
+ return out;
208
+ }
209
+ function useCaseLine(u, inp) {
210
+ const said = inp.phrases.get(u.id);
211
+ const phrase = said && inp.model ? `: ${said} ${MODEL_MARK(inp.model)}` : '';
212
+ return `- ${u.title}${phrase} — ${anchorOf(u)}`;
213
+ }
214
+ /** `12 (8 fn · 2 classes · 2 types)`. */
215
+ function surfaceCount(s) {
216
+ const parts = [
217
+ s.functions ? `${s.functions} fn` : '', s.classes ? `${s.classes} class${s.classes === 1 ? '' : 'es'}` : '',
218
+ s.types ? `${s.types} type${s.types === 1 ? '' : 's'}` : '', s.other ? `${s.other} other` : '',
219
+ ].filter(Boolean);
220
+ return parts.length > 1 ? `${s.exports} (${parts.join(' · ')})` : parts.length === 1 ? parts[0] : s.exports ? `${s.exports}` : '—';
221
+ }
222
+ /**
223
+ * A library: one table row per surface area (what it exports, counted, with
224
+ * the key names and the entry line), then the domain rules. Over the budget,
225
+ * the smallest areas merge into one row.
226
+ */
227
+ function renderSurfaceSpec(inp, mode, budget) {
228
+ const all = [...inp.rules.values(), ...inp.otherRules];
229
+ const rows = inp.useCases;
230
+ const total = rows.reduce((n, u) => n + (u.surface?.exports ?? 0), 0);
231
+ const out = [`# Spec — ${inp.title}`, ''];
232
+ out.push('> Learned from code: a library, described by its public surface — one row per surface area (package subpath, or the folder its exports are declared in) — and the domain rules inside it. Layer rules (L1–L8) are one line each in principles.md. Review before promoting a rule to intent.', '');
233
+ out.push(`${rows.length} surface area(s) · ${total} export(s) · ${all.length} domain rule(s).`, '');
234
+ if (inp.childNote)
235
+ out.push(inp.childNote, '');
236
+ out.push('## Public surface', '', '| Area | Exported from | Exports | Key names | Rules |', '|---|---|---|---|---|');
237
+ const maxRows = Math.max(5, Math.floor(budget * 0.45));
238
+ let kept = rows;
239
+ let merged = [];
240
+ if (rows.length > maxRows) {
241
+ const bySize = [...rows].sort((x, y) => (y.surface?.exports ?? 0) - (x.surface?.exports ?? 0) || cmp(x.area, y.area));
242
+ const keep = new Set(bySize.slice(0, maxRows - 1).map(r => r.id));
243
+ kept = rows.filter(r => keep.has(r.id));
244
+ merged = rows.filter(r => !keep.has(r.id));
245
+ }
246
+ for (const u of kept) {
247
+ const s = u.surface;
248
+ const names = s.names.map(n => `\`${n}\``).join(', ') + (s.exports > s.names.length ? ', …' : '');
249
+ const whole = s.reexports.length ? `${names ? '; ' : ''}all of ${s.reexports.map(p => `\`${p}\``).join(', ')}` : '';
250
+ const from = s.subpaths.length ? s.subpaths.map(p => `\`${p}\``).join(', ') : '—';
251
+ out.push(`| ${cell(u.area)} | ${cell(from)} | ${surfaceCount(s)} | ${cell(names + whole)} — ${anchorOf(u)} | ${u.ruleRefs.length} |`);
252
+ }
253
+ if (merged.length > 0) {
254
+ const n = merged.reduce((t, u) => t + (u.surface?.exports ?? 0), 0);
255
+ const r = merged.reduce((t, u) => t + u.ruleRefs.length, 0);
256
+ out.push(`| Other areas (${merged.length}) | — | ${n} | ${cell(merged.slice(0, 8).map(u => u.area).join(', '))}${merged.length > 8 ? ', …' : ''} | ${r} |`);
257
+ }
258
+ out.push('');
259
+ if (all.length > 0) {
260
+ out.push('## Domain rules', '');
261
+ const per = mode === 'full' ? 2 : 1;
262
+ const room = Math.max(0, budget - out.length - 2);
263
+ const fit = Math.min(all.length, Math.floor(room / per));
264
+ for (const r of all.slice(0, fit))
265
+ out.push(...ruleLine(r, '', mode === 'full'));
266
+ if (fit < all.length)
267
+ out.push(`- +${all.length - fit} more domain rule(s) in rules.json.`);
268
+ out.push('');
269
+ }
270
+ return out.join('\n');
271
+ }
272
+ function renderSpec(inp, mode, budget) {
273
+ if (inp.useCases.length > 0 && inp.useCases.every(u => u.surface))
274
+ return renderSurfaceSpec(inp, mode, budget);
275
+ const areas = areasOf(inp.useCases);
276
+ const shown = new Set();
277
+ const out = specHeader(inp, areas, inp.rules.size + inp.otherRules.length);
278
+ if (inp.useCases.length === 0)
279
+ out.push('No entry points found at this level.', '');
280
+ for (const area of areas) {
281
+ out.push(`## ${area}`, '');
282
+ for (const u of inp.useCases.filter(x => x.area === area)) {
283
+ out.push(useCaseLine(u, inp));
284
+ for (const k of u.ruleRefs) {
285
+ const r = inp.rules.get(k);
286
+ if (!r || shown.has(k))
287
+ continue;
288
+ shown.add(k);
289
+ out.push(...ruleLine(r, ' ', mode === 'full'));
290
+ }
291
+ }
292
+ out.push('');
293
+ }
294
+ if (inp.otherRules.length > 0) {
295
+ out.push('## Other domain rules', '');
296
+ const room = Math.max(0, budget - out.length - 2);
297
+ const per = mode === 'full' ? 2 : 1;
298
+ const fit = Math.min(inp.otherRules.length, Math.floor(room / per));
299
+ for (const r of inp.otherRules.slice(0, fit))
300
+ out.push(...ruleLine(r, '', mode === 'full'));
301
+ if (fit < inp.otherRules.length)
302
+ out.push(`- +${inp.otherRules.length - fit} more domain rule(s) in rules.json.`);
303
+ out.push('');
304
+ }
305
+ return out.join('\n');
306
+ }
307
+ /**
308
+ * Compact: one table row per area with its use cases, then as many domain
309
+ * rules as fit. Over ~budget rows, the smallest areas merge into one row.
310
+ */
311
+ function renderSpecCompact(inp, budget) {
312
+ const areas = areasOf(inp.useCases);
313
+ const all = [...inp.rules.values(), ...inp.otherRules];
314
+ const out = specHeader(inp, areas, all.length);
315
+ out.push('Too many use cases for one page: one row per area; every rule with its code paths is in rules.json.', '');
316
+ out.push('## Use cases by area', '', '| Area | Use cases | Domain rules |', '|---|---|---|');
317
+ const rows = areas.map(a => {
318
+ const ucs = inp.useCases.filter(u => u.area === a);
319
+ const rules = new Set(ucs.flatMap(u => u.ruleRefs)).size;
320
+ return { area: a, ucs, rules };
321
+ });
322
+ const maxRows = Math.max(5, Math.floor(budget * 0.45));
323
+ let kept = rows;
324
+ let merged = [];
325
+ if (rows.length > maxRows) {
326
+ const bySize = [...rows].sort((x, y) => y.ucs.length - x.ucs.length || cmp(x.area, y.area));
327
+ const keep = new Set(bySize.slice(0, maxRows - 1).map(r => r.area));
328
+ kept = rows.filter(r => keep.has(r.area));
329
+ merged = rows.filter(r => !keep.has(r.area));
330
+ }
331
+ const MAX_LISTED = 6;
332
+ for (const r of kept) {
333
+ const list = r.ucs.slice(0, MAX_LISTED).map(u => `\`${triggerOf(u)}\``).join(', ') + (r.ucs.length > MAX_LISTED ? `, +${r.ucs.length - MAX_LISTED} more` : '');
334
+ out.push(`| ${cell(r.area)} (${r.ucs.length}) | ${cell(list)} | ${r.rules} |`);
335
+ }
336
+ if (merged.length > 0) {
337
+ const n = merged.reduce((s, r) => s + r.ucs.length, 0);
338
+ const rules = merged.reduce((s, r) => s + r.rules, 0);
339
+ out.push(`| Other areas (${merged.length}) | ${n} use case(s): ${cell(merged.slice(0, 8).map(r => r.area).join(', '))}${merged.length > 8 ? ', …' : ''} | ${rules} |`);
340
+ }
341
+ out.push('');
342
+ if (all.length > 0) {
343
+ out.push('## Domain rules', '');
344
+ const room = Math.max(0, budget - out.length - 2);
345
+ const fit = Math.min(all.length, room);
346
+ for (const r of all.slice(0, fit))
347
+ out.push(...ruleLine(r, '', false));
348
+ if (fit < all.length)
349
+ out.push(`- +${all.length - fit} more domain rule(s) in rules.json.`);
350
+ out.push('');
351
+ }
352
+ return out.join('\n');
353
+ }
354
+ function fitSpec(inp, budget) {
355
+ const full = renderSpec(inp, 'full', budget);
356
+ if (lineCount(full) <= budget)
357
+ return { text: full, mode: 'full' };
358
+ const brief = renderSpec(inp, 'brief', budget);
359
+ if (lineCount(brief) <= budget)
360
+ return { text: brief, mode: 'brief' };
361
+ return { text: renderSpecCompact(inp, budget), mode: 'compact' };
362
+ }
363
+ function renderPrinciples(title, isRepo, summaries, conventions, phrases, model, budget) {
364
+ const out = [`# Principles — ${title}`, ''];
365
+ out.push(isRepo
366
+ ? '> Learned from code. One line per layer of the engine grid (L1–L8) present here; a line every module shares sits here, not in the modules. Domain rules are in spec.md.'
367
+ : '> Learned from code. One line per layer of the engine grid (L1–L8) at this module; lines shared with the repository are in the repository principles.md. Domain rules are in spec.md.', '');
368
+ out.push('## Layers', '');
369
+ const lines = formatLayerLines(summaries);
370
+ if (lines.length === 0)
371
+ out.push(isRepo ? 'No layer rules found.' : 'Nothing beyond the repository principles.');
372
+ summaries.forEach((s, i) => {
373
+ const said = phrases.get(s.layer);
374
+ out.push(said && model ? `${lines[i]} — ${said} ${MODEL_MARK(model)}` : lines[i]);
375
+ });
376
+ out.push('');
377
+ if (conventions.length > 0) {
378
+ out.push('## Conventions', '');
379
+ const room = Math.max(0, budget - out.length - 2);
380
+ for (const c of conventions.slice(0, Math.min(room, 10)))
381
+ out.push(`- ${c.text} (${c.category}; ${c.adherence}; ${c.confidence})`);
382
+ out.push('');
383
+ }
384
+ return out.join('\n');
385
+ }
386
+ const PRINCIPLE_CATEGORY_LABEL = {
387
+ error_handling: 'error handling', logging: 'logging', auth: 'auth', validation: 'validation', naming: 'naming',
388
+ caching: 'caching', metrics: 'metrics', performance: 'performance', security: 'security', other: 'other',
389
+ };
390
+ async function conventionsOf(files, projectRoot) {
391
+ const evidence = files.map(f => f.extended).filter((e) => !!e);
392
+ if (evidence.length === 0)
393
+ return [];
394
+ const r = await generatePrinciples({ evidence, clusters: [], irResults: [], sourcePath: projectRoot }, { enableLLM: false });
395
+ return r.principles.principles
396
+ .map(p => ({
397
+ key: hashKey('pr1', p.value.category, p.value.description),
398
+ category: PRINCIPLE_CATEGORY_LABEL[p.value.category] ?? p.value.category,
399
+ text: oneLine(p.value.description),
400
+ confidence: p.confidence,
401
+ adherence: `${p.value.adherenceCount}/${p.value.totalApplicable}`,
402
+ }))
403
+ .sort((a, b) => cmp(a.category, b.category) || cmp(a.text, b.text));
404
+ }
405
+ async function buildLevelWork(opts, name, levelPath, sourceRoot, module, files) {
406
+ const projectRoot = opts.projectRoot;
407
+ // SR-E2: use cases and the domain rules behind each.
408
+ const prodFiles = files.filter(f => !TEST_FILE.test(f.rel));
409
+ const ucFiles = prodFiles.map(f => ({ file: f.rel, code: f.code, ir: f.ir }));
410
+ const uc = extractUseCases(ucFiles, {
411
+ ...(module ? { module: { name: module.name, root: module.root } } : {}),
412
+ workerEntries: workerEntryFiles(projectRoot, files),
413
+ manifest: readManifest(projectRoot, sourceRoot),
414
+ });
415
+ // 0.1 static rules over the level's own non-test files: the layer candidates
416
+ // (taint pairs, guards and throws outside handlers, declared API).
417
+ let staticRules = [];
418
+ if (prodFiles.length > 0) {
419
+ const agg = aggregateEvidence({ name, files: prodFiles.map(f => f.abs), evidence: prodFiles.map(f => f.evidence), confidence: 1, clusteringMethod: 'package' });
420
+ const spec = generateFallbackSpec(agg);
421
+ relativizeProvenance(spec, projectRoot, path.relative);
422
+ // Same keys as the 0.1 path and as the use-case rules below (stable ids first).
423
+ if (opts.attachStableIds)
424
+ await opts.attachStableIds(spec, projectRoot);
425
+ assignRuleKeys(spec);
426
+ staticRules = spec.requirements.filter(r => r.provenance?.derivation !== 'method-inventory');
427
+ }
428
+ // Stable ids on the use-case rules, keys recomputed and references remapped.
429
+ if (opts.attachStableIds && uc.rules.length > 0) {
430
+ const spec = { title: name, summary: '', requirements: uc.rules, edgeCases: [], errorScenarios: [] };
431
+ const before = uc.rules.map(r => r.ruleKey);
432
+ await opts.attachStableIds(spec, projectRoot);
433
+ assignRuleKeys(spec);
434
+ const remap = new Map(before.map((k, i) => [k, uc.rules[i].ruleKey]));
435
+ for (const u of uc.useCases)
436
+ u.ruleRefs = u.ruleRefs.map(k => remap.get(k) ?? k);
437
+ }
438
+ const conventions = await conventionsOf(prodFiles, projectRoot);
439
+ // SR-E3: classify everything the level knows; domain → spec, layers → principles.
440
+ const toInput = (r) => ({
441
+ ruleKey: r.ruleKey, description: r.description, derivation: r.provenance?.derivation, codePaths: r.provenance?.codePaths,
442
+ });
443
+ const ucKeys = new Set(uc.rules.map(r => r.ruleKey));
444
+ // A guard or throw inside a use case's code that SR-E2 did not keep is a
445
+ // layer mechanic by SR-E2's test (request plumbing, auth, config): it is
446
+ // classified without the level's domain terms, so it can only land on a
447
+ // layer, or be dropped — never in spec.md.
448
+ const spans = uc.useCases.flatMap(u => u.codePaths.map(p => ({ file: p.file, start: p.startLine, end: p.endLine })));
449
+ const inUseCase = (r) => {
450
+ const a = r.provenance?.codePaths.find(p => p.role === 'anchor');
451
+ return !!a && spans.some(s => s.file === a.file && s.start <= a.startLine && a.startLine <= s.end);
452
+ };
453
+ const isCheck = (r) => r.provenance?.derivation === 'guard' || r.provenance?.derivation === 'throw';
454
+ const notUc = staticRules.filter(r => !ucKeys.has(r.ruleKey));
455
+ const mechanics = notUc.filter(r => isCheck(r) && inUseCase(r));
456
+ const extra = notUc.filter(r => !mechanics.includes(r));
457
+ const mechanicDecisions = classifyRules(mechanics.map(toInput), { fileDependencies: fileDependencies(files) })
458
+ .filter(d => d.layer !== 'domain');
459
+ const inputs = [
460
+ ...uc.rules.map(toInput),
461
+ ...extra.map(toInput),
462
+ ...conventions.map(c => ({ ruleKey: c.key, description: c.text, principleCategory: Object.keys(PRINCIPLE_CATEGORY_LABEL).find(k => PRINCIPLE_CATEGORY_LABEL[k] === c.category) ?? 'other' })),
463
+ ];
464
+ const decisions = [
465
+ ...classifyRules(inputs, { useCases: uc.useCases, fileDependencies: fileDependencies(files) }),
466
+ ...mechanicDecisions,
467
+ ];
468
+ const layerOf = new Map(decisions.map(d => [d.ruleKey, d.layer]));
469
+ const domainUc = uc.rules.filter(r => layerOf.get(r.ruleKey) === 'domain');
470
+ const domainKeys = new Set(domainUc.map(r => r.ruleKey));
471
+ for (const u of uc.useCases)
472
+ u.ruleRefs = u.ruleRefs.filter(k => domainKeys.has(k));
473
+ // Domain guards and throws not under any entry point (a service's own checks).
474
+ const otherRules = extra.filter(r => layerOf.get(r.ruleKey) === 'domain' && (r.provenance?.derivation === 'guard' || r.provenance?.derivation === 'throw'));
475
+ const summaries = summarizeLevel({ decisions, dependencies: manifestDependencies(projectRoot, module?.root ?? '') });
476
+ return {
477
+ name, path: levelPath, sourceRoot, ...(module ? { module } : {}), files,
478
+ useCases: uc.useCases, domainRules: domainUc, otherRules, decisions, summaries, conventions,
479
+ };
480
+ }
481
+ /** Number rules REQ-001… in the order the spec shows them, as `SpecMdContent`. */
482
+ function numberRules(w) {
483
+ const byKey = new Map();
484
+ const ordered = [];
485
+ const domain = new Map(w.domainRules.map(r => [r.ruleKey, r]));
486
+ for (const u of w.useCases) {
487
+ for (const k of u.ruleRefs) {
488
+ const r = domain.get(k);
489
+ if (r && !byKey.has(k)) {
490
+ byKey.set(k, r);
491
+ ordered.push(r);
492
+ }
493
+ }
494
+ }
495
+ const other = w.otherRules.filter(r => !byKey.has(r.ruleKey));
496
+ const all = [...ordered, ...other].map((r, i) => ({ ...r, id: `REQ-${String(i + 1).padStart(3, '0')}` }));
497
+ const numbered = new Map(all.map(r => [r.ruleKey, r]));
498
+ for (const k of [...byKey.keys()])
499
+ byKey.set(k, numbered.get(k));
500
+ return { rules: all, byKey, other: other.map(r => numbered.get(r.ruleKey)) };
501
+ }
502
+ async function phraseLevel(phraser, w, byKey, summaries) {
503
+ const none = { useCases: new Map(), layers: new Map() };
504
+ if (!phraser || (w.useCases.length === 0 && summaries.length === 0))
505
+ return none;
506
+ const input = {
507
+ level: w.name,
508
+ useCases: w.useCases.slice(0, 60).map(u => ({
509
+ id: u.id, area: u.area, title: u.title, trigger: triggerOf(u),
510
+ rules: u.ruleRefs.map(k => byKey.get(k)?.description).filter((d) => !!d).slice(0, 5),
511
+ })),
512
+ layers: summaries.map(s => ({ layer: s.layer, name: layerName(s.layer), facts: s.text })),
513
+ };
514
+ let out = null;
515
+ try {
516
+ out = await phraser.phrase(input);
517
+ }
518
+ catch {
519
+ out = null;
520
+ }
521
+ if (!out)
522
+ return none;
523
+ const ucIds = new Set(input.useCases.map(u => u.id));
524
+ const layerIds = new Set(input.layers.map(l => l.layer));
525
+ const clean = (s) => (typeof s === 'string' ? oneLine(s.replace(/[`|]/g, "'"), 160) : '');
526
+ for (const p of out.useCases ?? []) {
527
+ const s = clean(p?.sentence);
528
+ if (p && ucIds.has(p.id) && s)
529
+ none.useCases.set(p.id, s);
530
+ }
531
+ for (const p of out.layers ?? []) {
532
+ const s = clean(p?.line);
533
+ if (p && layerIds.has(p.layer) && s)
534
+ none.layers.set(p.layer, s);
535
+ }
536
+ return none;
537
+ }
538
+ /**
539
+ * Build the learned tree in memory. Levels: the repository, and one per
540
+ * module (workspace package or service) inside the scanned directory.
541
+ */
542
+ export async function buildSpecTree(opts) {
543
+ const projectRoot = path.resolve(opts.projectRoot);
544
+ const budget = opts.budget ?? LEVEL_LINE_BUDGET;
545
+ const scanRel = path.relative(projectRoot, path.resolve(opts.scanRoot ?? projectRoot)).split(path.sep).join('/');
546
+ const scan = scanRel === '' || scanRel === '.' ? '' : scanRel;
547
+ const files = [...opts.files].sort((a, b) => cmp(a.rel, b.rel));
548
+ const all = detectModules(projectRoot).modules;
549
+ // Modules inside the scanned directory, or the one module the scan sits in.
550
+ const modules = all.filter(m => isUnder(scan, m.root) || isUnder(m.root, scan));
551
+ const byLevel = new Map();
552
+ for (const f of files) {
553
+ const key = ownerOf(f.rel, modules)?.root ?? '';
554
+ byLevel.set(key, [...(byLevel.get(key) ?? []), f]);
555
+ }
556
+ const version = resolveSpecVersion(projectRoot) || DEFAULT_SPEC_VERSION;
557
+ const name = repoName(projectRoot);
558
+ const repoWork = await buildLevelWork({ ...opts, projectRoot }, name, '', '.', undefined, byLevel.get('') ?? []);
559
+ const moduleWork = [];
560
+ for (const m of modules) {
561
+ moduleWork.push(await buildLevelWork({ ...opts, projectRoot }, m.name, moduleLevelPath(m.name), m.root, m, byLevel.get(m.root) ?? []));
562
+ }
563
+ // Lift layer lines every module shares to the repository.
564
+ const lifted = liftSharedLines({
565
+ name, summaries: repoWork.summaries,
566
+ children: moduleWork.map(w => ({ name: w.name, summaries: w.summaries, children: [] })),
567
+ });
568
+ repoWork.summaries = lifted.summaries;
569
+ moduleWork.forEach((w, i) => { w.summaries = lifted.children[i].summaries; });
570
+ // SR-E4: design.md per level, one read for all levels.
571
+ const designs = generateLevelDesigns(projectRoot, modules.map(m => ({ name: m.name, root: m.root, ...(m.declaredName ? { declaredName: m.declaredName } : {}) })), { maxLines: budget });
572
+ const allConventions = repoWork.conventions.length > 0 || moduleWork.length === 0
573
+ ? repoWork.conventions
574
+ : await conventionsOf(files.filter(f => !TEST_FILE.test(f.rel)), projectRoot);
575
+ const levels = [];
576
+ const toLevel = async (w, isRepo) => {
577
+ const { rules, byKey, other } = numberRules(w);
578
+ const phrased = await phraseLevel(opts.phraser, w, byKey, w.summaries);
579
+ const model = opts.phraser?.model;
580
+ const childNote = isRepo && moduleWork.length > 0
581
+ ? `Modules: ${moduleWork.map(m => `\`${m.name}\``).join(', ')} — each has its own spec.md under \`modules/<name>/\`.`
582
+ : undefined;
583
+ const { text: spec, mode } = fitSpec({ title: w.name, useCases: w.useCases, rules: byKey, otherRules: other, phrases: phrased.useCases, ...(model ? { model } : {}), ...(childNote ? { childNote } : {}) }, budget);
584
+ const principles = renderPrinciples(w.name, isRepo, w.summaries, isRepo ? allConventions : [], phrased.layers, model, budget);
585
+ const design = designs.get(w.sourceRoot) ?? designs.get('.') ?? '';
586
+ const specContent = { title: w.name, summary: '', requirements: rules, edgeCases: [], errorScenarios: [] };
587
+ const sidecar = {
588
+ scheme: SPEC_PROVENANCE_SCHEME,
589
+ tree: 'learned',
590
+ module: w.name,
591
+ version,
592
+ spec: '',
593
+ requirements: rules,
594
+ metadata: {
595
+ generator: 'circle-ir-ai/specifica',
596
+ version: opts.engineVersion,
597
+ model: 'static-generation',
598
+ filesAnalyzed: w.files.length,
599
+ provenance: summarizeProvenance(specContent),
600
+ ...(opts.subject ? { subject: opts.subject } : {}),
601
+ sourceRoot: w.sourceRoot,
602
+ ...(model && (phrased.useCases.size + phrased.layers.size > 0) ? { phrasedBy: `llm: ${model}` } : {}),
603
+ },
604
+ };
605
+ const level = {
606
+ level: isRepo ? 'repo' : 'module',
607
+ path: w.path,
608
+ name: w.name,
609
+ sourceRoot: w.sourceRoot,
610
+ version,
611
+ files: {
612
+ principles,
613
+ ...(isRepo && opts.environmentFolder
614
+ ? { environmentFolder: opts.environmentFolder }
615
+ : isRepo && opts.environment !== undefined ? { environment: opts.environment } : {}),
616
+ spec,
617
+ design,
618
+ tasks: '',
619
+ },
620
+ rules: sidecar,
621
+ modules: [],
622
+ };
623
+ levels.push({
624
+ level, useCases: w.useCases, domainRules: rules, layerDecisions: w.decisions, files: w.files.map(f => f.rel),
625
+ specMode: mode, phrased: { useCases: phrased.useCases.size, layers: phrased.layers.size },
626
+ });
627
+ return level;
628
+ };
629
+ const tree = await toLevel(repoWork, true);
630
+ for (const w of moduleWork)
631
+ tree.modules.push(await toLevel(w, false));
632
+ return { tree, levels, modules };
633
+ }
634
+ /** Per-level line counts of the four markdown files (smoke report). */
635
+ export function treeLineCounts(tree) {
636
+ return flattenLevels(tree).map(l => ({
637
+ level: l.level === 'repo' ? '(repository)' : l.path,
638
+ principles: lineCount(l.files.principles),
639
+ ...(l.files.environment !== undefined ? { environment: lineCount(l.files.environment) } : {}),
640
+ ...(l.files.environmentFolder
641
+ ? { environmentFolder: Object.fromEntries(ENVIRONMENT_FOLDER_FILES.map(f => [f, lineCount(l.files.environmentFolder[f])])) }
642
+ : {}),
643
+ spec: lineCount(l.files.spec),
644
+ design: lineCount(l.files.design),
645
+ tasks: lineCount(l.files.tasks),
646
+ }));
647
+ }
648
+ /** Build and write; returns what was written. */
649
+ export async function generateSpecTree(opts) {
650
+ const built = await buildSpecTree(opts);
651
+ const write = writeSpecTree(opts.projectRoot, built.tree, { learnedDir: opts.learnedDir, explicitOutputDir: opts.explicitOutputDir });
652
+ return { ...built, write };
653
+ }
654
+ export { levelFilePaths };
655
+ // ─── Model arm ───────────────────────────────────────────────────────
656
+ /**
657
+ * The model phraser: one `chatJSON` call per level, given only the
658
+ * deterministic facts (use-case titles, triggers, rule texts, layer lines).
659
+ * The answer is keyed back to those ids; anything else is dropped by
660
+ * `phraseLevel`. Any failure → `null` (the level stays static).
661
+ */
662
+ export function llmTreePhraser(model, specModel) {
663
+ return {
664
+ model,
665
+ async phrase(input) {
666
+ const { getAxLLMClient } = await import('../llm/ax-client.js');
667
+ const { getDefaultLLMConfig } = await import('../llm/config.js');
668
+ let cfg;
669
+ if (specModel) {
670
+ const d = getDefaultLLMConfig();
671
+ cfg = { phases: { ...d.phases, enrichment: { ...d.phases.enrichment, model: specModel, temperature: 0.2, maxTokens: 4000 } } };
672
+ }
673
+ const client = getAxLLMClient(cfg);
674
+ const system = 'You rephrase facts recovered from source code into short plain-English lines for a specification. Use only the facts given. Never add a use case, a rule, a layer, a module or a technology that is not in the input. Answer with JSON only.';
675
+ const user = [
676
+ `Level: ${input.level}`,
677
+ 'Facts (JSON):',
678
+ JSON.stringify({ useCases: input.useCases, layers: input.layers }),
679
+ '',
680
+ 'Return {"useCases":[{"id":"<id from the input>","sentence":"<one sentence: what the user can do, from the title, trigger and rules>"}],',
681
+ ' "layers":[{"layer":"<L1..L8 from the input>","line":"<one short sentence summarising that layer\'s facts>"}]}.',
682
+ 'Keep each sentence under 25 words. Reuse ids exactly. Omit anything you cannot phrase from the facts.',
683
+ ].join('\n');
684
+ const r = await client.chatJSON(system, user, 'enrichment');
685
+ return r && typeof r === 'object' ? r : null;
686
+ },
687
+ };
688
+ }
689
+ //# sourceMappingURL=spec-tree.js.map