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,1253 @@
1
+ /**
2
+ * Level-scoped design.md (spec recovery 0.2, task SR-E4; techspec
3
+ * `services/cognium-engine/plans/spec-recovery/.specifica/0.2/design.md` §1.5).
4
+ *
5
+ * A learned tree has one design.md per level: the repository, and each module
6
+ * (workspace package or service). A level's design.md holds only that level's
7
+ *
8
+ * 1. **module map** — the child modules and how they map to each other:
9
+ * edges from imports across packages (and workspace manifest
10
+ * dependencies), HTTP / RPC clients matched to routes another module
11
+ * serves, queues (producer → consumer) and service bindings. A Mermaid
12
+ * flowchart plus a short table;
13
+ * 2. **constraints** — named validation schemas (zod, valibot, yup, Joi),
14
+ * DB table constraints (drizzle, Prisma) and limit / config-bound
15
+ * constants, from the files the level owns itself;
16
+ * 3. **state machines** — enum- or union-typed status fields and the
17
+ * transitions found in code (a status written by an update guarded by
18
+ * the current status), as Mermaid `stateDiagram-v2`.
19
+ *
20
+ * Scoping (Eyal, 19 Nov 2026): anything inside a child module belongs only to
21
+ * that child's design.md, never the parent's. A file belongs to the deepest
22
+ * module that contains it, else to the repository. A constraint belongs to
23
+ * its file's level. A state machine belongs to the module that declares its
24
+ * status type or enum, never to a parent: when several modules declare it,
25
+ * to the one the other declaring modules depend on (else the primary
26
+ * declaration's). Its transitions are drawn there wherever they are written,
27
+ * with a "written by" line naming the other modules and their sites; the
28
+ * parent shows at most the edge between them in its module map. Declarations
29
+ * with the same values join into one machine only across linked modules (one
30
+ * uses the other, or a third uses both); a write binds only to a machine
31
+ * declared in a module linked to its own.
32
+ *
33
+ * Deterministic and model-free: facts are read from source text with
34
+ * line-anchored patterns (TypeScript / JavaScript first), sorted, and every
35
+ * table row carries its `file:line`. No timestamps. A level's design.md stays
36
+ * near 100 lines; what does not fit is summarised in one line per section.
37
+ *
38
+ * Input is SR-E1's `Module[]` (`modules.ts`); a level is named by its source
39
+ * root (`.` for the repository, the module root otherwise, as
40
+ * `SpecLevel.sourceRoot`). `toTreeDesignFacts` gives the same facts in the
41
+ * shared `tree-types.ts` shapes for circle-pack's tree (SR-E6).
42
+ *
43
+ * This is separate from `design-generator.ts` (project-wide, fan-in based on
44
+ * feature clusters), which is unchanged; this writer is not wired into the
45
+ * generator yet.
46
+ */
47
+ import * as fs from 'fs';
48
+ import * as path from 'path';
49
+ import { LEVEL_LINE_BUDGET, } from './tree-types.js';
50
+ // ─── Source reading ──────────────────────────────────────────────────
51
+ const SKIP_DIRS = new Set([
52
+ 'node_modules', '.git', 'dist', 'build', 'out', 'coverage', '.next', '.turbo',
53
+ '.wrangler', '.cache', '.cognium', '.specifica', 'vendor', '.svelte-kit', '.output',
54
+ ]);
55
+ const CODE_EXT = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;
56
+ const TEST_FILE = /(\.|-)(test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)(__tests__|__mocks__|tests?|e2e|fixtures?)\//;
57
+ function walk(root, opts) {
58
+ const out = [];
59
+ const stack = [''];
60
+ while (stack.length > 0 && out.length < opts.maxFiles) {
61
+ const dir = stack.pop();
62
+ let entries;
63
+ try {
64
+ entries = fs.readdirSync(path.join(root, dir), { withFileTypes: true });
65
+ }
66
+ catch {
67
+ continue;
68
+ }
69
+ entries.sort((a, b) => (a.name < b.name ? 1 : a.name > b.name ? -1 : 0));
70
+ for (const e of entries) {
71
+ const rel = dir ? `${dir}/${e.name}` : e.name;
72
+ if (e.isDirectory()) {
73
+ if (!SKIP_DIRS.has(e.name))
74
+ stack.push(rel);
75
+ }
76
+ else if (e.isFile()) {
77
+ if (isWanted(rel))
78
+ out.push(rel);
79
+ }
80
+ }
81
+ }
82
+ return out.sort();
83
+ }
84
+ function isWanted(rel) {
85
+ const base = rel.slice(rel.lastIndexOf('/') + 1);
86
+ if (base === 'package.json' || /^wrangler\.(jsonc?|toml)$/.test(base))
87
+ return true;
88
+ if (base.endsWith('.prisma'))
89
+ return true;
90
+ if (base.endsWith('.d.ts'))
91
+ return false;
92
+ return CODE_EXT.test(base) && !TEST_FILE.test(rel);
93
+ }
94
+ /** Deepest module containing `rel`, '' when none. */
95
+ function ownerOf(rel, modulePaths) {
96
+ let best = '';
97
+ for (const m of modulePaths) {
98
+ if ((rel === m || rel.startsWith(m + '/')) && m.length > best.length)
99
+ best = m;
100
+ }
101
+ return best;
102
+ }
103
+ /** Parent level of a module path: the deepest other module containing it, else ''. */
104
+ function parentOf(m, modulePaths) {
105
+ let best = '';
106
+ for (const o of modulePaths) {
107
+ if (o !== m && m.startsWith(o + '/') && o.length > best.length)
108
+ best = o;
109
+ }
110
+ return best;
111
+ }
112
+ /** The child of `level` on the way down to `m` (m itself when it is a direct child); null when m is not under level. */
113
+ function childUnder(level, m, modulePaths) {
114
+ if (m === level)
115
+ return null;
116
+ if (level !== '' && !m.startsWith(level + '/'))
117
+ return null;
118
+ let cur = m;
119
+ for (;;) {
120
+ const p = parentOf(cur, modulePaths);
121
+ if (p === level)
122
+ return cur;
123
+ if (p === '' && level !== '')
124
+ return null;
125
+ if (p === '')
126
+ return null;
127
+ cur = p;
128
+ }
129
+ }
130
+ function isUnder(level, m) {
131
+ return level === '' || m === level || m.startsWith(level + '/');
132
+ }
133
+ function lineIndex(text) {
134
+ const starts = [0];
135
+ for (let i = 0; i < text.length; i++)
136
+ if (text.charCodeAt(i) === 10)
137
+ starts.push(i + 1);
138
+ return starts;
139
+ }
140
+ function lineAt(starts, idx) {
141
+ let lo = 0;
142
+ let hi = starts.length - 1;
143
+ while (lo < hi) {
144
+ const mid = (lo + hi + 1) >> 1;
145
+ if (starts[mid] <= idx)
146
+ lo = mid;
147
+ else
148
+ hi = mid - 1;
149
+ }
150
+ return lo + 1;
151
+ }
152
+ /** Index of the bracket closing the one at `open`, skipping strings and comments; -1 when unbalanced. */
153
+ function matchClose(text, open, limit = 20000) {
154
+ const pairs = { '(': ')', '{': '}', '[': ']' };
155
+ const stack = [];
156
+ const end = Math.min(text.length, open + limit);
157
+ for (let i = open; i < end; i++) {
158
+ const c = text[i];
159
+ if (c === '"' || c === "'" || c === '`') {
160
+ const q = c;
161
+ i++;
162
+ while (i < end && text[i] !== q) {
163
+ if (text[i] === '\\')
164
+ i++;
165
+ i++;
166
+ }
167
+ continue;
168
+ }
169
+ if (c === '/' && text[i + 1] === '/') {
170
+ while (i < end && text[i] !== '\n')
171
+ i++;
172
+ continue;
173
+ }
174
+ if (c === '/' && text[i + 1] === '*') {
175
+ const j = text.indexOf('*/', i + 2);
176
+ if (j < 0)
177
+ return -1;
178
+ i = j + 1;
179
+ continue;
180
+ }
181
+ if (pairs[c])
182
+ stack.push(pairs[c]);
183
+ else if (c === ')' || c === '}' || c === ']') {
184
+ if (stack.pop() !== c)
185
+ return -1;
186
+ if (stack.length === 0)
187
+ return i;
188
+ }
189
+ }
190
+ return -1;
191
+ }
192
+ function stringLiterals(s) {
193
+ return [...s.matchAll(/["'`]([\w.:/-]+)["'`]/g)].map(m => m[1]);
194
+ }
195
+ function stripJsonc(s) {
196
+ let out = '';
197
+ for (let i = 0; i < s.length; i++) {
198
+ const c = s[i];
199
+ if (c === '"') {
200
+ let j = i + 1;
201
+ while (j < s.length && s[j] !== '"') {
202
+ if (s[j] === '\\')
203
+ j++;
204
+ j++;
205
+ }
206
+ out += s.slice(i, j + 1);
207
+ i = j;
208
+ }
209
+ else if (c === '/' && s[i + 1] === '/') {
210
+ while (i < s.length && s[i] !== '\n')
211
+ i++;
212
+ out += '\n';
213
+ }
214
+ else if (c === '/' && s[i + 1] === '*') {
215
+ const j = s.indexOf('*/', i + 2);
216
+ i = j < 0 ? s.length : j + 1;
217
+ }
218
+ else
219
+ out += c;
220
+ }
221
+ return out.replace(/,(\s*[}\]])/g, '$1');
222
+ }
223
+ // ─── Module map facts ────────────────────────────────────────────────
224
+ const IMPORT_RE = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s+)["']([^"']+)["']/gm;
225
+ const ROUTE_RE = /\.(?:get|post|put|patch|delete|all|route|use|on)\(\s*(?:\[[^\]]*\]\s*,\s*)?["'`](\/[^"'`]*)["'`]/g;
226
+ const ENDPOINT_RE = /\bendpoint\s*:\s*["'`](\/[^"'`]*)["'`]/g;
227
+ const FETCH_RE = /\b(?:fetch|axios(?:\.(?:get|post|put|patch|delete|request))?|ky(?:\.(?:get|post|put|patch|delete))?|got|\$fetch|request)\(\s*["'`]([^"'`]+)["'`]/g;
228
+ const LINK_URL_RE = /\burl\s*:\s*["'`]([^"'`]+)["'`]/g;
229
+ const ENV_URL_RE = /\$\{\s*(?:[\w$]+\.)*([A-Z][A-Z0-9_]*(?:URL|HOST|ENDPOINT|BASE|ORIGIN|API))\s*\}/;
230
+ function routePrefix(p) {
231
+ const cut = p.search(/[:{*[(]/);
232
+ let lit = cut >= 0 ? p.slice(0, cut) : p;
233
+ lit = lit.replace(/\/+$/, '');
234
+ return lit;
235
+ }
236
+ /** A route prefix specific enough to attribute a client call to a module. */
237
+ function isSpecificPrefix(p) {
238
+ return p.split('/').filter(Boolean).length >= 1 && p.length >= 4 && !/^\/(api|v\d+)$/.test(p);
239
+ }
240
+ function readWrangler(rel, text) {
241
+ const out = { services: [], producers: [], consumers: [] };
242
+ if (rel.endsWith('.toml')) {
243
+ const name = /^\s*name\s*=\s*"([^"]+)"/m.exec(text);
244
+ if (name)
245
+ out.name = name[1];
246
+ let section = '';
247
+ for (const line of text.split('\n')) {
248
+ const sec = /^\s*\[\[?([\w.]+)\]\]?/.exec(line);
249
+ if (sec) {
250
+ section = sec[1];
251
+ continue;
252
+ }
253
+ const svc = /^\s*service\s*=\s*"([^"]+)"/.exec(line);
254
+ if (svc && section.endsWith('services'))
255
+ out.services.push(svc[1]);
256
+ const q = /^\s*queue\s*=\s*"([^"]+)"/.exec(line);
257
+ if (q && section.endsWith('producers'))
258
+ out.producers.push(q[1]);
259
+ if (q && section.endsWith('consumers'))
260
+ out.consumers.push(q[1]);
261
+ }
262
+ return out;
263
+ }
264
+ try {
265
+ const j = JSON.parse(stripJsonc(text));
266
+ const envs = [j, ...Object.values(j.env ?? {})];
267
+ if (typeof j.name === 'string')
268
+ out.name = j.name;
269
+ for (const e of envs) {
270
+ for (const s of e.services ?? [])
271
+ if (s?.service)
272
+ out.services.push(s.service);
273
+ const q = e.queues ?? {};
274
+ for (const p of q.producers ?? [])
275
+ if (p?.queue)
276
+ out.producers.push(p.queue);
277
+ for (const c of q.consumers ?? [])
278
+ if (c?.queue)
279
+ out.consumers.push(c.queue);
280
+ }
281
+ }
282
+ catch {
283
+ /* unreadable config: no facts */
284
+ }
285
+ return out;
286
+ }
287
+ // ─── Constraint facts ────────────────────────────────────────────────
288
+ const SCHEMA_RE = /^[ \t]*(?:export\s+)?(?:const|let)\s+(\w+)\s*(?::[^=\n]+)?=\s*(z|v|yup|Joi|t)\s*\.\s*(object|strictObject|enum|union|discriminatedUnion|array|string|number|picklist|variant)\s*\(/gm;
289
+ const INLINE_SCHEMA_RE = /\.(?:input|output|body|query|params)\(\s*(?:z|v)\s*\.\s*object\s*\(|zValidator\(\s*["'`]\w+["'`]\s*,/g;
290
+ const TABLE_RE = /^[ \t]*(?:export\s+)?const\s+(\w+)\s*=\s*(pgTable|mysqlTable|sqliteTable)\(\s*["'`](\w+)["'`]/gm;
291
+ const PRISMA_MODEL_RE = /^model\s+(\w+)\s*\{/gm;
292
+ const LIMIT_RE = /^[ \t]*(?:export\s+)?const\s+([A-Z][A-Z0-9_]*)\s*(?::[^=\n]+)?=\s*(-?[0-9][0-9_.]*(?:\s*[*/+]\s*[0-9][0-9_.]*)*)\s*(?:as const)?\s*;?\s*(?:\/\/.*)?$/gm;
293
+ const LIMIT_NAME = /(^|_)(MAX|MIN|LIMIT|LIMITS|TIMEOUT|TTL|RETRIES|RETRY|CAP|SIZE|BUDGET|THRESHOLD|QUOTA|WINDOW|BATCH|CONCURRENCY|DEPTH|LENGTH|LEN|MS|SECONDS|MINUTES|DAYS)(_|$)/;
294
+ function summariseSchema(body, kind) {
295
+ const parts = [];
296
+ if (kind === 'object' || kind === 'strictObject') {
297
+ // Fields at the first object level.
298
+ let depth = 0;
299
+ let fields = 0;
300
+ for (const line of body.split('\n')) {
301
+ // The body starts at the call's `(`, so the object's own keys sit at depth 2.
302
+ if (depth === 2 && /^\s*["']?[\w$]+["']?\s*:/.test(line))
303
+ fields++;
304
+ for (const c of line) {
305
+ if (c === '{' || c === '(' || c === '[')
306
+ depth++;
307
+ else if (c === '}' || c === ')' || c === ']')
308
+ depth--;
309
+ }
310
+ }
311
+ if (fields > 0)
312
+ parts.push(`${fields} field${fields === 1 ? '' : 's'}`);
313
+ }
314
+ else if (kind === 'enum' || kind === 'picklist') {
315
+ const vals = stringLiterals(body);
316
+ if (vals.length > 0)
317
+ parts.push(vals.slice(0, 6).join(' | ') + (vals.length > 6 ? ` +${vals.length - 6}` : ''));
318
+ }
319
+ else {
320
+ parts.push(kind);
321
+ }
322
+ const bounds = (body.match(/\.(?:min|max|length|gte|lte|gt|lt|minLength|maxLength|size)\(/g) ?? []).length;
323
+ if (bounds > 0)
324
+ parts.push(`${bounds} bound${bounds === 1 ? '' : 's'}`);
325
+ const fmts = [...new Set((body.match(/\.(email|url|uuid|cuid2?|ulid|datetime|date|ipv?[46]?|regex|int|positive|nonnegative|nonempty)\(/g) ?? [])
326
+ .map(s => s.slice(1, -1)))].sort();
327
+ if (fmts.length > 0)
328
+ parts.push(fmts.slice(0, 4).join(', '));
329
+ if (/\.(refine|superRefine|check)\(/.test(body))
330
+ parts.push('custom refine');
331
+ return parts.join('; ') || kind;
332
+ }
333
+ function summariseTable(body) {
334
+ const parts = [];
335
+ const nn = (body.match(/\.notNull\(\)/g) ?? []).length;
336
+ if (nn)
337
+ parts.push(`not null ×${nn}`);
338
+ const pk = (body.match(/\.primaryKey\(|\bprimaryKey\(\s*\{/g) ?? []).length;
339
+ if (pk)
340
+ parts.push('primary key');
341
+ const uq = (body.match(/\.unique\(\)|\buniqueIndex\(|\bunique\(/g) ?? []).length;
342
+ if (uq)
343
+ parts.push(`unique ×${uq}`);
344
+ const fks = [...new Set([...body.matchAll(/\.references\(\s*\(\)\s*(?::\s*\w+\s*)?=>\s*(\w+)\s*\./g)].map(m => m[1]))].sort();
345
+ if (fks.length)
346
+ parts.push(`FK → ${fks.slice(0, 4).join(', ')}${fks.length > 4 ? ` +${fks.length - 4}` : ''}`);
347
+ const en = (body.match(/\{\s*enum\s*:/g) ?? []).length;
348
+ if (en)
349
+ parts.push(`enum columns ×${en}`);
350
+ const ck = (body.match(/\bcheck\(/g) ?? []).length;
351
+ if (ck)
352
+ parts.push(`check ×${ck}`);
353
+ return parts.join(' · ') || 'columns only';
354
+ }
355
+ function summarisePrisma(body) {
356
+ const parts = [];
357
+ const id = (body.match(/@id\b|@@id\b/g) ?? []).length;
358
+ if (id)
359
+ parts.push('primary key');
360
+ const uq = (body.match(/@unique\b|@@unique\b/g) ?? []).length;
361
+ if (uq)
362
+ parts.push(`unique ×${uq}`);
363
+ const rel = [...new Set([...body.matchAll(/^\s*\w+\s+(\w+)\??\s+@relation/gm)].map(m => m[1]))].sort();
364
+ if (rel.length)
365
+ parts.push(`FK → ${rel.slice(0, 4).join(', ')}`);
366
+ return parts.join(' · ') || 'columns only';
367
+ }
368
+ // ─── State machine facts ─────────────────────────────────────────────
369
+ const STATE_WORD = /(status|state|phase|stage|lifecycle)$/i;
370
+ function fieldFromName(name) {
371
+ const m = /(status|state|phase|stage|lifecycle)(es|s)?$/i.exec(name.replace(/_/g, ''));
372
+ return m ? m[1].toLowerCase() : 'status';
373
+ }
374
+ function normField(f) {
375
+ const m = STATE_WORD.exec(f);
376
+ return m ? m[1].toLowerCase() : null;
377
+ }
378
+ function findDefinitions(f, starts, consts) {
379
+ const defs = [];
380
+ const t = f.text;
381
+ const push = (d) => {
382
+ const vals = [...new Set(d.values)];
383
+ if (vals.length >= 2 && vals.length <= 20)
384
+ defs.push({ ...d, values: vals, file: f.rel, owner: f.owner });
385
+ };
386
+ // type XStatus = "a" | "b"
387
+ for (const m of t.matchAll(/\btype\s+(\w*(?:Status|State|Phase|Stage))\s*=\s*((?:\s*\|?\s*["'][\w-]+["'])+)/g)) {
388
+ push({ name: m[1], field: fieldFromName(m[1]), values: stringLiterals(m[2]), line: lineAt(starts, m.index), rank: 0 });
389
+ }
390
+ // enum XStatus { A = "a", B }
391
+ for (const m of t.matchAll(/\benum\s+(\w*(?:Status|State|Phase|Stage))\s*\{([^}]*)\}/g)) {
392
+ const vals = m[2].split(',').map(s => s.trim()).filter(Boolean)
393
+ .map(s => /=\s*["']([\w-]+)["']/.exec(s)?.[1] ?? s.split(/\s*=/)[0].trim());
394
+ push({ name: m[1], field: fieldFromName(m[1]), values: vals, line: lineAt(starts, m.index), rank: 0 });
395
+ }
396
+ // const X_STATUSES = ["a", "b"] as const
397
+ for (const m of t.matchAll(/\bconst\s+(\w*(?:STATUS|STATE|PHASE|STAGE|Status|State|Phase|Stage)\w*)\s*(?::[^=\n]+)?=\s*\[([^\]]*)\]\s*as\s+const/g)) {
398
+ const vals = stringLiterals(m[2]);
399
+ consts.set(m[1], vals);
400
+ push({ name: m[1], field: fieldFromName(m[1]), values: vals, line: lineAt(starts, m.index), rank: 1 });
401
+ }
402
+ // pgEnum("run_status", ["a", "b"])
403
+ for (const m of t.matchAll(/\b(?:const\s+(\w+)\s*=\s*)?pgEnum\(\s*["'](\w+)["']\s*,\s*\[([^\]]*)\]/g)) {
404
+ if (!STATE_WORD.test(m[2]) && !(m[1] && STATE_WORD.test(m[1])))
405
+ continue;
406
+ push({ name: m[1] ?? m[2], field: fieldFromName(m[2]), values: stringLiterals(m[3]), line: lineAt(starts, m.index), rank: 1 });
407
+ }
408
+ return defs;
409
+ }
410
+ /** Column / field definitions (drizzle `text({ enum })`, zod `z.enum`), resolved against known consts. */
411
+ function findFieldDefinitions(f, starts, consts) {
412
+ const defs = [];
413
+ const t = f.text;
414
+ const tables = [];
415
+ for (const m of t.matchAll(TABLE_RE)) {
416
+ const open = m.index + m[0].indexOf(m[2] + '(') + m[2].length;
417
+ const close = matchClose(t, open);
418
+ tables.push({ name: m[1], start: m.index, end: close < 0 ? t.length : close });
419
+ }
420
+ const re = /\b(\w*(?:status|state|phase|stage|Status|State|Phase|Stage))\s*:\s*(?:text|varchar|char)\(\s*(?:["'][^"']*["']\s*,\s*)?\{[^}]*?\benum\s*:\s*(\[[^\]]*\]|\w+)/g;
421
+ for (const m of t.matchAll(re)) {
422
+ const ref = m[2];
423
+ const values = ref.startsWith('[') ? stringLiterals(ref) : consts.get(ref) ?? [];
424
+ if (values.length < 2)
425
+ continue;
426
+ const lineNo = lineAt(starts, m.index);
427
+ const lineText = f.lines[lineNo - 1] ?? '';
428
+ const tail = t.slice(m.index, Math.min(t.length, m.index + 300)).split('\n').slice(0, 2).join(' ');
429
+ const initial = /\.default\(\s*["']([\w-]+)["']\s*\)/.exec(tail)?.[1] ?? /\.default\(\s*["']([\w-]+)["']\s*\)/.exec(lineText)?.[1];
430
+ const table = tables.find(tb => m.index > tb.start && m.index < tb.end)?.name;
431
+ defs.push({
432
+ name: table ? `${table}.${m[1]}` : m[1],
433
+ field: normField(m[1]) ?? 'status',
434
+ values: [...new Set(values)],
435
+ initial: initial && values.includes(initial) ? initial : undefined,
436
+ file: f.rel,
437
+ line: lineNo,
438
+ owner: f.owner,
439
+ table,
440
+ rank: 2,
441
+ });
442
+ }
443
+ // type OrderStatus = (typeof ORDER_STATUSES)[number]
444
+ for (const m of t.matchAll(/\btype\s+(\w*(?:Status|State|Phase|Stage))\s*=\s*\(?\s*typeof\s+(\w+)\s*\)?\s*\[\s*number\s*\]/g)) {
445
+ const values = consts.get(m[2]) ?? [];
446
+ if (values.length < 2)
447
+ continue;
448
+ defs.push({
449
+ name: m[1], field: fieldFromName(m[1]), values: [...new Set(values)],
450
+ file: f.rel, line: lineAt(starts, m.index), owner: f.owner, rank: 0,
451
+ });
452
+ }
453
+ for (const m of t.matchAll(/\b(\w*(?:status|state|Status|State))\s*:\s*z\s*\.\s*enum\(\s*(\[[^\]]*\]|\w+)/g)) {
454
+ const ref = m[2];
455
+ const values = ref.startsWith('[') ? stringLiterals(ref) : consts.get(ref) ?? [];
456
+ if (values.length < 2)
457
+ continue;
458
+ const lineNo = lineAt(starts, m.index);
459
+ const initial = /\.default\(\s*["']([\w-]+)["']\s*\)/.exec(f.lines[lineNo - 1] ?? '')?.[1];
460
+ defs.push({
461
+ name: m[1], field: normField(m[1]) ?? 'status', values: [...new Set(values)],
462
+ initial: initial && values.includes(initial) ? initial : undefined,
463
+ file: f.rel, line: lineNo, owner: f.owner, rank: 3,
464
+ });
465
+ }
466
+ return defs;
467
+ }
468
+ const WRITE_CTX = /\.set\(\s*\{|\bupdate\w*\(|\bdata\s*:\s*\{|\$set\b|\bsetState\(|\bpatch\w*\(|\.update\(/;
469
+ const FN_START = /^\s*(?:export\s+)?(?:async\s+)?function\b|^\s*(?:public|private|protected)\s+(?:async\s+)?\w+\s*\(|^\s*\w+\s*:\s*\w*[Pp]rocedure\b|^\s*(?:it|test|describe)\(/;
470
+ function findWrites(f) {
471
+ const out = [];
472
+ const L = f.lines;
473
+ for (let i = 0; i < L.length; i++) {
474
+ const line = L[i];
475
+ // x.status = "done" | status: "done" inside an update
476
+ const re = /(?<![\w$])([A-Za-z_$][\w$]*)\s*(=|:)\s*["']([\w-]+)["'](?!\s*[|&])/g;
477
+ for (const m of line.matchAll(re)) {
478
+ const field = normField(m[1]);
479
+ if (!field)
480
+ continue;
481
+ const before = line.slice(0, m.index);
482
+ const after = line.slice(m.index + m[0].length);
483
+ if (m[2] === '=') {
484
+ // Only a member write (`run.status = "x"`) is a stored write; a local or a comparison is not.
485
+ if (!before.endsWith('.') || after.startsWith('='))
486
+ continue;
487
+ }
488
+ else {
489
+ // `status: "x"` only counts inside an update context (same line or the 3 above).
490
+ const ctx = L.slice(Math.max(0, i - 3), i + 1).join('\n');
491
+ if (!WRITE_CTX.test(ctx))
492
+ continue;
493
+ if (/\b(?:interface|type)\b/.test(ctx) || /\bwhere\b|\bfilter\b|\bfind\w*\(/.test(before))
494
+ continue;
495
+ }
496
+ const { froms, table } = guardsBefore(L, i, field);
497
+ out.push({ field, to: m[3], froms, file: f.rel, line: i + 1, owner: f.owner, table });
498
+ }
499
+ }
500
+ return out;
501
+ }
502
+ /** Status values the write is guarded by, from the lines before it in the same function. */
503
+ function guardsBefore(L, i, field) {
504
+ const froms = new Set();
505
+ let table;
506
+ const lo = Math.max(0, i - 14);
507
+ let switchVal;
508
+ for (let j = i; j >= lo; j--) {
509
+ const line = L[j];
510
+ if (!table) {
511
+ const up = /\.update\(\s*(?:[\w$]+\.)*([\w$]+)\s*\)/.exec(line) ?? /\bprisma\.([\w$]+)\.update/.exec(line);
512
+ if (up)
513
+ table = up[1];
514
+ }
515
+ // Comparisons on a stored field (`run.status === "x"`), not on a local such as `newStatus`.
516
+ for (const m of line.matchAll(/[\w$\]?)]\.([A-Za-z_$][\w$]*)\s*(===|==|!==|!=)\s*["']([\w-]+)["']|["']([\w-]+)["']\s*(===|==|!==|!=)\s*[\w$]+(?:\??\.[\w$]+)*\??\.([A-Za-z_$][\w$]*)\b/g)) {
517
+ const ident = m[1] ?? m[6];
518
+ const op = m[2] ?? m[5];
519
+ const val = m[3] ?? m[4];
520
+ if (normField(ident) !== field)
521
+ continue;
522
+ if (op.startsWith('!')) {
523
+ // `if (x.status !== "running") throw/return` → reached only from running.
524
+ const nxt = line + ' ' + (L[j + 1] ?? '');
525
+ if (/\b(throw|return|continue)\b/.test(nxt))
526
+ froms.add(val);
527
+ }
528
+ else
529
+ froms.add(val);
530
+ }
531
+ for (const m of line.matchAll(/\beq\(\s*[\w$.]*?\.([A-Za-z_$][\w$]*)\s*,\s*["']([\w-]+)["']\s*\)/g)) {
532
+ if (normField(m[1]) === field)
533
+ froms.add(m[2]);
534
+ }
535
+ for (const m of line.matchAll(/\binArray\(\s*[\w$.]*?\.([A-Za-z_$][\w$]*)\s*,\s*\[([^\]]*)\]/g)) {
536
+ if (normField(m[1]) === field)
537
+ for (const v of stringLiterals(m[2]))
538
+ froms.add(v);
539
+ }
540
+ if (switchVal === undefined && j < i) {
541
+ const c = /^\s*case\s+["']([\w-]+)["']\s*:/.exec(line);
542
+ if (c)
543
+ switchVal = c[1];
544
+ }
545
+ if (switchVal !== undefined) {
546
+ const s = /\bswitch\s*\(\s*[\w$]+(?:\??\.[\w$]+)*\??\.([A-Za-z_$][\w$]*)\s*\)/.exec(line);
547
+ if (s && normField(s[1]) === field) {
548
+ froms.add(switchVal);
549
+ switchVal = '';
550
+ }
551
+ }
552
+ if (j < i && FN_START.test(line))
553
+ break;
554
+ }
555
+ // A query builder's filter follows the write in the same chain:
556
+ // `.set({ status: "shipped" }).where(eq(t.status, "paid"))`.
557
+ for (let j = i + 1; j < Math.min(L.length, i + 4); j++) {
558
+ const line = L[j];
559
+ if (!/^\s*\.|\bwhere\b/.test(line))
560
+ break;
561
+ for (const m of line.matchAll(/\beq\(\s*[\w$.]*?\.([A-Za-z_$][\w$]*)\s*,\s*["']([\w-]+)["']\s*\)/g)) {
562
+ if (normField(m[1]) === field)
563
+ froms.add(m[2]);
564
+ }
565
+ for (const m of line.matchAll(/\binArray\(\s*[\w$.]*?\.([A-Za-z_$][\w$]*)\s*,\s*\[([^\]]*)\]/g)) {
566
+ if (normField(m[1]) === field)
567
+ for (const v of stringLiterals(m[2]))
568
+ froms.add(v);
569
+ }
570
+ }
571
+ return { froms: [...froms].sort(), table };
572
+ }
573
+ // ─── Fact collection ─────────────────────────────────────────────────
574
+ /**
575
+ * Read the repository once and collect every design fact, each placed at the
576
+ * level that owns it. `modules` is the flat list of all modules (any depth).
577
+ */
578
+ export function collectDesignFacts(repoRoot, modules, options = {}) {
579
+ const opts = {
580
+ maxLines: options.maxLines ?? LEVEL_LINE_BUDGET,
581
+ maxFileBytes: options.maxFileBytes ?? 512 * 1024,
582
+ maxFiles: options.maxFiles ?? 20000,
583
+ };
584
+ const mods = [...modules]
585
+ .map(m => ({ name: m.name, packageName: m.declaredName, path: m.root.replace(/\\/g, '/').replace(/^\.\/|\/+$/g, '') }))
586
+ .filter(m => m.path !== '' && m.path !== '.')
587
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
588
+ const paths = mods.map(m => m.path);
589
+ // Package names (from the manifest when the ref does not carry one) and manifest deps.
590
+ const byPackage = new Map();
591
+ const manifestDeps = new Map();
592
+ for (const m of mods) {
593
+ let pkg = {};
594
+ try {
595
+ pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, m.path, 'package.json'), 'utf8'));
596
+ }
597
+ catch {
598
+ /* not a node package */
599
+ }
600
+ const name = m.packageName ?? pkg.name;
601
+ if (name)
602
+ byPackage.set(name, m.path);
603
+ manifestDeps.set(m.path, Object.keys({ ...pkg.dependencies, ...pkg.peerDependencies }).sort());
604
+ }
605
+ const files = [];
606
+ for (const rel of walk(repoRoot, opts)) {
607
+ const abs = path.join(repoRoot, rel);
608
+ try {
609
+ if (fs.statSync(abs).size > opts.maxFileBytes)
610
+ continue;
611
+ const text = fs.readFileSync(abs, 'utf8');
612
+ files.push({ rel, text, lines: text.split('\n'), owner: ownerOf(rel, paths) });
613
+ }
614
+ catch {
615
+ /* unreadable: skip */
616
+ }
617
+ }
618
+ const edgeMap = new Map();
619
+ const addEdge = (from, to, kind, site, detail) => {
620
+ if (from === to)
621
+ return;
622
+ const key = `${from}\u0000${to}\u0000${kind}\u0000${detail ?? ''}`;
623
+ const e = edgeMap.get(key);
624
+ if (e)
625
+ e.count++;
626
+ else
627
+ edgeMap.set(key, { from, to, kind, detail, site, count: 1 });
628
+ };
629
+ const extMap = new Map();
630
+ const addExternal = (from, target, site) => {
631
+ const key = `${from}\u0000${target}`;
632
+ const e = extMap.get(key);
633
+ if (e)
634
+ e.count++;
635
+ else
636
+ extMap.set(key, { from, target, site, count: 1 });
637
+ };
638
+ // Manifest dependencies on workspace packages.
639
+ for (const m of mods) {
640
+ for (const dep of manifestDeps.get(m.path) ?? []) {
641
+ const to = byPackage.get(dep);
642
+ if (to)
643
+ addEdge(m.path, to, 'depends', `${m.path}/package.json:1`);
644
+ }
645
+ }
646
+ const routes = [];
647
+ const wrangler = new Map();
648
+ const constraints = [];
649
+ const inline = new Map();
650
+ const consts = new Map();
651
+ const defs = [];
652
+ const clientCalls = [];
653
+ const queueSites = [];
654
+ for (const f of files) {
655
+ const base = f.rel.slice(f.rel.lastIndexOf('/') + 1);
656
+ if (/^wrangler\.(jsonc?|toml)$/.test(base)) {
657
+ const w = readWrangler(f.rel, f.text);
658
+ const prev = wrangler.get(f.owner);
659
+ if (!prev)
660
+ wrangler.set(f.owner, w);
661
+ for (const q of w.producers)
662
+ queueSites.push({ owner: f.owner, name: q, role: 'producer', site: `${f.rel}:1` });
663
+ for (const q of w.consumers)
664
+ queueSites.push({ owner: f.owner, name: q, role: 'consumer', site: `${f.rel}:1` });
665
+ continue;
666
+ }
667
+ if (base === 'package.json')
668
+ continue;
669
+ const starts = lineIndex(f.text);
670
+ if (base.endsWith('.prisma')) {
671
+ for (const m of f.text.matchAll(PRISMA_MODEL_RE)) {
672
+ const open = m.index + m[0].length - 1;
673
+ const close = matchClose(f.text, open);
674
+ const body = f.text.slice(open, close < 0 ? undefined : close);
675
+ constraints.push({ kind: 'table', name: m[1], source: 'prisma', summary: summarisePrisma(body), file: f.rel, line: lineAt(starts, m.index), owner: f.owner });
676
+ }
677
+ continue;
678
+ }
679
+ // Imports across modules.
680
+ for (const m of f.text.matchAll(IMPORT_RE)) {
681
+ const spec = m[1];
682
+ let to;
683
+ if (spec.startsWith('.')) {
684
+ const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(f.rel), spec));
685
+ if (!resolved.startsWith('..'))
686
+ to = ownerOf(resolved, paths);
687
+ }
688
+ else {
689
+ const parts = spec.split('/');
690
+ const name = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
691
+ to = byPackage.get(name);
692
+ }
693
+ if (to !== undefined && to !== f.owner)
694
+ addEdge(f.owner, to, 'imports', `${f.rel}:${lineAt(starts, m.index)}`);
695
+ }
696
+ // Routes served.
697
+ for (const re of [ROUTE_RE, ENDPOINT_RE]) {
698
+ for (const m of f.text.matchAll(re)) {
699
+ const p = routePrefix(m[1]);
700
+ if (isSpecificPrefix(p))
701
+ routes.push({ owner: f.owner, prefix: p });
702
+ }
703
+ }
704
+ // HTTP / RPC clients.
705
+ const rpcFile = /\bcreateTRPC\w*|\bhttp(?:Batch)?Link\(|\bhc\s*</.test(f.text);
706
+ const clientRes = [[FETCH_RE, 'http']];
707
+ if (rpcFile)
708
+ clientRes.push([LINK_URL_RE, 'rpc']);
709
+ for (const [re, kind] of clientRes) {
710
+ for (const m of f.text.matchAll(re)) {
711
+ const raw = m[1];
712
+ const site = `${f.rel}:${lineAt(starts, m.index)}`;
713
+ const env = ENV_URL_RE.exec(raw);
714
+ if (env)
715
+ addExternal(f.owner, env[1], site);
716
+ const host = /^https?:\/\/([^/${}]+)/.exec(raw);
717
+ if (host && !/^(localhost|127\.|0\.0\.0\.0|\[::1\])/.test(host[1]))
718
+ addExternal(f.owner, host[1], site);
719
+ const p = raw.replace(/^https?:\/\/[^/]+/, '').replace(/^\$\{[^}]*\}/, '');
720
+ if (p.startsWith('/'))
721
+ clientCalls.push({ owner: f.owner, p: routePrefix(p) || p, site, kind });
722
+ }
723
+ }
724
+ // Queues in code (BullMQ-style).
725
+ for (const m of f.text.matchAll(/\bnew\s+(Queue|Worker)\(\s*["'`]([\w:.-]+)["'`]/g)) {
726
+ queueSites.push({ owner: f.owner, name: m[2], role: m[1] === 'Queue' ? 'producer' : 'consumer', site: `${f.rel}:${lineAt(starts, m.index)}` });
727
+ }
728
+ // Constraints (generated migration snapshots restate the schema; skipped).
729
+ const generated = /(^|\/)migrations?\//.test(f.rel);
730
+ for (const m of generated ? [] : f.text.matchAll(SCHEMA_RE)) {
731
+ if (m[2] === 't' && !/\bio-ts\b|from\s+["']io-ts/.test(f.text))
732
+ continue;
733
+ const open = f.text.indexOf('(', m.index + m[0].length - 1);
734
+ const close = matchClose(f.text, open);
735
+ const body = f.text.slice(open, close < 0 ? Math.min(f.text.length, open + 4000) : close + 1);
736
+ const lib = { z: 'zod', v: 'valibot', yup: 'yup', Joi: 'Joi', t: 'io-ts' }[m[2]];
737
+ constraints.push({ kind: 'schema', name: m[1], source: lib, summary: summariseSchema(body, m[3]), file: f.rel, line: lineAt(starts, m.index), owner: f.owner });
738
+ }
739
+ const inl = (f.text.match(INLINE_SCHEMA_RE) ?? []).length;
740
+ if (inl > 0) {
741
+ const e = inline.get(f.owner) ?? { count: 0, files: new Set() };
742
+ e.count += inl;
743
+ e.files.add(f.rel);
744
+ inline.set(f.owner, e);
745
+ }
746
+ for (const m of generated ? [] : f.text.matchAll(TABLE_RE)) {
747
+ const open = f.text.indexOf('(', m.index + m[1].length);
748
+ const close = matchClose(f.text, open);
749
+ const body = f.text.slice(open, close < 0 ? undefined : close + 1);
750
+ constraints.push({ kind: 'table', name: m[3], source: 'drizzle', summary: summariseTable(body), file: f.rel, line: lineAt(starts, m.index), owner: f.owner });
751
+ }
752
+ for (const m of generated ? [] : f.text.matchAll(LIMIT_RE)) {
753
+ if (!LIMIT_NAME.test(m[1]))
754
+ continue;
755
+ constraints.push({ kind: 'limit', name: m[1], source: 'const', summary: m[2].replace(/\s+/g, ' '), file: f.rel, line: lineAt(starts, m.index), owner: f.owner });
756
+ }
757
+ // State machine definitions.
758
+ defs.push(...findDefinitions(f, starts, consts));
759
+ }
760
+ // Column definitions resolve against consts from any file, so a second pass.
761
+ const writes = [];
762
+ for (const f of files) {
763
+ if (!CODE_EXT.test(f.rel))
764
+ continue;
765
+ const starts = lineIndex(f.text);
766
+ defs.push(...findFieldDefinitions(f, starts, consts));
767
+ writes.push(...findWrites(f));
768
+ }
769
+ // HTTP clients → the module serving the longest matching route prefix.
770
+ for (const c of clientCalls) {
771
+ let best;
772
+ for (const r of routes) {
773
+ if (r.owner === c.owner)
774
+ continue;
775
+ if (c.p === r.prefix || c.p.startsWith(r.prefix + '/')) {
776
+ if (!best || r.prefix.length > best.prefix.length || (r.prefix.length === best.prefix.length && r.owner < best.owner))
777
+ best = r;
778
+ }
779
+ }
780
+ if (best)
781
+ addEdge(c.owner, best.owner, c.kind, c.site, best.prefix);
782
+ }
783
+ // Queues: producer → consumer.
784
+ const qNames = [...new Set(queueSites.map(q => q.name))].sort();
785
+ for (const name of qNames) {
786
+ const prods = queueSites.filter(q => q.name === name && q.role === 'producer');
787
+ const cons = queueSites.filter(q => q.name === name && q.role === 'consumer');
788
+ for (const p of prods)
789
+ for (const c of cons)
790
+ addEdge(p.owner, c.owner, 'queue', p.site, name);
791
+ }
792
+ // Service bindings (wrangler `services`) → the module whose worker has that name.
793
+ const byWorker = new Map();
794
+ for (const [owner, w] of [...wrangler.entries()].sort())
795
+ if (w.name && !byWorker.has(w.name))
796
+ byWorker.set(w.name, owner);
797
+ for (const [owner, w] of [...wrangler.entries()].sort()) {
798
+ for (const s of w.services) {
799
+ const to = byWorker.get(s);
800
+ if (to !== undefined)
801
+ addEdge(owner, to, 'service', `${owner ? owner + '/' : ''}wrangler:1`, s);
802
+ else
803
+ addExternal(owner, `worker:${s}`, `${owner ? owner + '/' : ''}wrangler:1`);
804
+ }
805
+ }
806
+ // Modules may share a state machine when one links to the other, or when
807
+ // one module uses both (a type in a core package and the column in a db
808
+ // package that an api package joins); unrelated modules never do.
809
+ const out = new Map();
810
+ for (const e of edgeMap.values()) {
811
+ if (!out.has(e.from))
812
+ out.set(e.from, new Set());
813
+ out.get(e.from).add(e.to);
814
+ }
815
+ const dependsOn = (a, b) => out.get(a)?.has(b) === true;
816
+ const isRelated = (a, b) => {
817
+ if (a === b || out.get(a)?.has(b) || out.get(b)?.has(a))
818
+ return true;
819
+ for (const tos of out.values())
820
+ if (tos.has(a) && tos.has(b))
821
+ return true;
822
+ return false;
823
+ };
824
+ const machines = buildMachines(defs, writes, isRelated, dependsOn);
825
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
826
+ const edges = [...edgeMap.values()].sort((a, b) => cmp(a.from, b.from) || cmp(a.to, b.to) || cmp(a.kind, b.kind) || cmp(a.detail ?? '', b.detail ?? ''));
827
+ const external = [...extMap.values()].sort((a, b) => cmp(a.from, b.from) || cmp(a.target, b.target));
828
+ constraints.sort((a, b) => cmp(a.file, b.file) || a.line - b.line || cmp(a.name, b.name));
829
+ const inlineSchemas = new Map([...inline.entries()].sort().map(([k, v]) => [k, { count: v.count, files: v.files.size }]));
830
+ return { modules: mods, edges, external, constraints, inlineSchemas, machines, filesRead: files.length };
831
+ }
832
+ function buildMachines(defs, writes, isRelated, dependsOn) {
833
+ // One machine per (field, value set) within modules that are linked to each
834
+ // other; the same value set in two unrelated modules is two machines. A
835
+ // definition whose values are a strict subset of a linked one's with the
836
+ // same field is a view of it (a filter) and joins it.
837
+ const cmpDef = (a, b) => a.rank - b.rank || (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line);
838
+ const sorted = [...defs].sort(cmpDef);
839
+ const key = (d) => `${d.field}:${[...d.values].sort().join('|')}`;
840
+ const linked = (c, owner) => [...c.owners].some(o => isRelated(o, owner));
841
+ const clusters = [];
842
+ for (const d of sorted) {
843
+ const c = clusters.find(x => key(x) === key(d) && linked(x, d.owner));
844
+ if (c) {
845
+ c.defs.push(d);
846
+ c.owners.add(d.owner);
847
+ }
848
+ else
849
+ clusters.push({ field: d.field, values: d.values, defs: [d], owners: new Set([d.owner]) });
850
+ }
851
+ // Fold strict subsets into the smallest linked superset (largest sets first, so chains settle).
852
+ const bySize = [...clusters].sort((x, y) => x.values.length - y.values.length || (key(x) < key(y) ? -1 : 1));
853
+ const absorbed = new Set();
854
+ for (const c of bySize) {
855
+ const sup = bySize.find(o => o !== c && !absorbed.has(o) && o.field === c.field && o.values.length > c.values.length &&
856
+ c.values.every(v => o.values.includes(v)) && [...c.owners].some(ow => linked(o, ow)));
857
+ if (sup) {
858
+ sup.defs.push(...c.defs);
859
+ for (const o of c.owners)
860
+ sup.owners.add(o);
861
+ absorbed.add(c);
862
+ }
863
+ }
864
+ const drafts = clusters.filter(c => !absorbed.has(c)).map(c => ({
865
+ defs: [...c.defs].sort(cmpDef),
866
+ owners: c.owners,
867
+ field: c.field,
868
+ states: c.values,
869
+ transitions: new Map(),
870
+ unguarded: new Map(),
871
+ sites: [],
872
+ }));
873
+ for (const w of writes) {
874
+ // A write binds only to a machine declared in its own module or one it is linked to.
875
+ const cands = drafts.filter(d => d.field === w.field && d.states.includes(w.to) && [...d.owners].some(o => isRelated(o, w.owner)));
876
+ if (cands.length === 0)
877
+ continue;
878
+ let pick = cands;
879
+ if (pick.length > 1 && w.table) {
880
+ const byTable = pick.filter(d => d.defs.some(x => x.table === w.table));
881
+ if (byTable.length > 0)
882
+ pick = byTable;
883
+ }
884
+ if (pick.length > 1 && w.froms.length > 0) {
885
+ const byFrom = pick.filter(d => w.froms.every(f => d.states.includes(f)));
886
+ if (byFrom.length > 0)
887
+ pick = byFrom;
888
+ }
889
+ if (pick.length > 1) {
890
+ const near = pick.filter(d => d.defs.some(x => x.owner === w.owner));
891
+ if (near.length > 0)
892
+ pick = near;
893
+ }
894
+ const d = pick[0];
895
+ const froms = w.froms.filter(f => d.states.includes(f) && f !== w.to);
896
+ if (froms.length === 0) {
897
+ const k = `${w.to}`;
898
+ if (!d.unguarded.has(k))
899
+ d.unguarded.set(k, { to: w.to, file: w.file, line: w.line });
900
+ }
901
+ for (const f of froms) {
902
+ const k = `${f}\u0000${w.to}`;
903
+ if (!d.transitions.has(k))
904
+ d.transitions.set(k, { from: f, to: w.to, file: w.file, line: w.line });
905
+ }
906
+ d.sites.push({ level: w.owner, file: w.file, line: w.line });
907
+ }
908
+ const out = [];
909
+ for (const d of drafts) {
910
+ // The declaring module owns it. Several declaring modules: the one the
911
+ // others depend on (a db package's enum that an api re-exports), ties by
912
+ // declaration order (type before const before column before validator).
913
+ const declaring = [];
914
+ for (const x of d.defs)
915
+ if (!declaring.includes(x.owner))
916
+ declaring.push(x.owner);
917
+ const score = (o) => declaring.filter(x => x !== o && dependsOn(x, o)).length;
918
+ const owner = [...declaring].sort((a, b) => score(b) - score(a) || declaring.indexOf(a) - declaring.indexOf(b))[0];
919
+ const primary = d.defs.find(x => x.owner === owner) ?? d.defs[0];
920
+ const writtenBy = new Map();
921
+ for (const w of [...d.sites].sort((a, b) => (a.level < b.level ? -1 : a.level > b.level ? 1 : a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line))) {
922
+ if (w.level !== owner && !writtenBy.has(w.level))
923
+ writtenBy.set(w.level, w);
924
+ }
925
+ const initial = d.defs.find(x => x.initial)?.initial;
926
+ out.push({
927
+ name: primary.name,
928
+ field: d.field,
929
+ states: d.states,
930
+ initial,
931
+ aliases: [...new Set(d.defs.map(x => x.name))].filter(n => n !== primary.name).sort(),
932
+ definedAt: [primary, ...d.defs.filter(x => x !== primary)].map(x => ({ file: x.file, line: x.line })),
933
+ transitions: [...d.transitions.values()].sort((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : a.to < b.to ? -1 : a.to > b.to ? 1 : 0)),
934
+ unguarded: [...d.unguarded.values()].sort((a, b) => (a.to < b.to ? -1 : 1)),
935
+ owner,
936
+ writtenBy: [...writtenBy.values()],
937
+ });
938
+ }
939
+ return out.sort((a, b) => b.transitions.length - a.transitions.length || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
940
+ }
941
+ const BUDGETS = [
942
+ { edgesInDiagram: 30, tableRows: 14, constraints: 14, machines: 4, transitionsPerMachine: 12 },
943
+ { edgesInDiagram: 22, tableRows: 12, constraints: 10, machines: 3, transitionsPerMachine: 10 },
944
+ { edgesInDiagram: 16, tableRows: 10, constraints: 8, machines: 2, transitionsPerMachine: 8 },
945
+ { edgesInDiagram: 10, tableRows: 8, constraints: 5, machines: 2, transitionsPerMachine: 6 },
946
+ { edgesInDiagram: 6, tableRows: 6, constraints: 4, machines: 1, transitionsPerMachine: 6 },
947
+ ];
948
+ const KIND_LABEL = {
949
+ imports: 'imports', depends: 'depends', http: 'HTTP', rpc: 'RPC', queue: 'queue', service: 'service',
950
+ };
951
+ function edgeLabel(es) {
952
+ const kinds = new Set(es.map(e => e.kind));
953
+ // A manifest dependency is implied when the code imports it.
954
+ if (kinds.has('imports'))
955
+ kinds.delete('depends');
956
+ const parts = [];
957
+ for (const k of ['imports', 'depends', 'http', 'rpc', 'queue', 'service']) {
958
+ if (!kinds.has(k))
959
+ continue;
960
+ const details = [...new Set(es.filter(e => e.kind === k && e.detail).map(e => e.detail))].sort();
961
+ parts.push(details.length > 0 && k !== 'http' && k !== 'rpc' ? `${KIND_LABEL[k]} ${details.slice(0, 2).join(', ')}` : details.length > 0 ? `${KIND_LABEL[k]} ${details[0]}` : KIND_LABEL[k]);
962
+ }
963
+ return parts.join(', ');
964
+ }
965
+ /** The site to show for a link: a code site before a manifest line. */
966
+ function siteOf(es) {
967
+ return (es.find(e => e.kind !== 'depends') ?? es[0]).site;
968
+ }
969
+ function mmd(s) {
970
+ return s.replace(/"/g, "'").replace(/[|]/g, '/');
971
+ }
972
+ function cell(s) {
973
+ return s.replace(/\|/g, '\\|').replace(/\n/g, ' ');
974
+ }
975
+ function stateId(s) {
976
+ const id = s.replace(/[^A-Za-z0-9_]/g, '_');
977
+ return /^[0-9]/.test(id) ? `s_${id}` : id;
978
+ }
979
+ /**
980
+ * design.md for one level: `sourceRoot` `.` (or `''`) for the repository, else
981
+ * a module root. Only facts the level owns are written.
982
+ */
983
+ export function renderLevelDesign(facts, sourceRoot, options = {}) {
984
+ const maxLines = options.maxLines ?? LEVEL_LINE_BUDGET;
985
+ const level = levelKey(sourceRoot);
986
+ let last = '';
987
+ for (const b of BUDGETS) {
988
+ last = renderWithBudget(facts, level, b);
989
+ if (last.split('\n').length <= maxLines)
990
+ return last;
991
+ }
992
+ return last;
993
+ }
994
+ function renderWithBudget(facts, level, b) {
995
+ const paths = facts.modules.map(m => m.path);
996
+ const nameOf = (p) => (p === '' ? '(repository)' : facts.modules.find(m => m.path === p)?.name ?? p);
997
+ const self = level === '' ? undefined : facts.modules.find(m => m.path === level);
998
+ const children = facts.modules.filter(m => parentOf(m.path, paths) === level && m.path !== level);
999
+ const out = [];
1000
+ const title = level === '' ? 'Repository' : `Module \`${self?.name ?? level}\``;
1001
+ out.push(`# Design — ${title}`, '');
1002
+ out.push(`> Learned (deterministic, model-free). Level: \`${level === '' ? '.' : level}\`. Child modules are described in their own design.md.`, '');
1003
+ // 1. Module map.
1004
+ out.push('## Module map', '');
1005
+ // Lift each edge endpoint to this level's child (or self / outside).
1006
+ const lift = (m) => {
1007
+ if (m === level)
1008
+ return { id: level, inside: true };
1009
+ const c = childUnder(level, m, paths);
1010
+ if (c !== null)
1011
+ return { id: c, inside: true };
1012
+ return { id: m, inside: false };
1013
+ };
1014
+ const grouped = new Map();
1015
+ for (const e of facts.edges) {
1016
+ const fromIn = isUnder(level, e.from);
1017
+ const toIn = isUnder(level, e.to);
1018
+ if (!fromIn && !toIn)
1019
+ continue;
1020
+ const a = lift(e.from);
1021
+ const z = lift(e.to);
1022
+ if (a.id === z.id)
1023
+ continue;
1024
+ const k = `${a.id}\u0000${z.id}`;
1025
+ grouped.set(k, [...(grouped.get(k) ?? []), e]);
1026
+ }
1027
+ const pairs = [...grouped.entries()].sort((x, y) => (x[0] < y[0] ? -1 : 1));
1028
+ const ext = facts.external.filter(x => x.from === level || childUnder(level, x.from, paths) !== null);
1029
+ if (children.length === 0) {
1030
+ out.push('No child modules at this level.', '');
1031
+ const uses = pairs.filter(([k]) => k.split('\u0000')[0] === level);
1032
+ const usedBy = pairs.filter(([k]) => k.split('\u0000')[1] === level);
1033
+ if (uses.length + usedBy.length + ext.length === 0) {
1034
+ out.push('No links to other modules found.', '');
1035
+ }
1036
+ else {
1037
+ out.push('| Direction | Module | Through | First site |', '|---|---|---|---|');
1038
+ const rows = [];
1039
+ for (const [k, es] of uses)
1040
+ rows.push(`| uses | ${cell(nameOf(k.split('\u0000')[1]))} | ${cell(edgeLabel(es))} | \`${siteOf(es)}\` |`);
1041
+ for (const [k, es] of usedBy)
1042
+ rows.push(`| used by | ${cell(nameOf(k.split('\u0000')[0]))} | ${cell(edgeLabel(es))} | \`${siteOf(es)}\` |`);
1043
+ const extTargets = [...new Set(ext.map(x => x.target))].sort();
1044
+ for (const t of extTargets.slice(0, 4)) {
1045
+ const x = ext.find(y => y.target === t);
1046
+ rows.push(`| calls | ${cell(t)} (external) | HTTP | \`${x.site}\` |`);
1047
+ }
1048
+ out.push(...rows.slice(0, b.tableRows));
1049
+ if (rows.length > b.tableRows)
1050
+ out.push(`| … | +${rows.length - b.tableRows} more | | |`);
1051
+ if (extTargets.length > 4)
1052
+ out.push('', `Also calls ${extTargets.length - 4} more external service(s): ${extTargets.slice(4, 10).join(', ')}${extTargets.length > 10 ? ', …' : ''}.`);
1053
+ out.push('');
1054
+ }
1055
+ }
1056
+ else {
1057
+ const ids = new Map();
1058
+ const nodeLines = [];
1059
+ const node = (p, inside) => {
1060
+ if (ids.has(p))
1061
+ return ids.get(p);
1062
+ const id = `m${ids.size}`;
1063
+ ids.set(p, id);
1064
+ const label = p === level ? `${nameOf(p)} (own files)` : nameOf(p);
1065
+ nodeLines.push(inside ? ` ${id}["${mmd(label)}"]` : ` ${id}(["${mmd(label)} (outside)"])`);
1066
+ return id;
1067
+ };
1068
+ for (const c of children)
1069
+ node(c.path, true);
1070
+ const edgeLines = [];
1071
+ const ranked = [...pairs].sort((x, y) => {
1072
+ const ix = x[0].split('\u0000').every(p => p === level || children.some(c => c.path === p)) ? 0 : 1;
1073
+ const iy = y[0].split('\u0000').every(p => p === level || children.some(c => c.path === p)) ? 0 : 1;
1074
+ return ix - iy || (x[0] < y[0] ? -1 : 1);
1075
+ });
1076
+ for (const [k, es] of ranked.slice(0, b.edgesInDiagram)) {
1077
+ const [f, t] = k.split('\u0000');
1078
+ const fin = f === level || children.some(c => c.path === f);
1079
+ const tin = t === level || children.some(c => c.path === t);
1080
+ const a = node(f, fin);
1081
+ const z = node(t, tin);
1082
+ const arrow = fin && tin ? '-->' : '-.->';
1083
+ edgeLines.push(` ${a} ${arrow}|${mmd(edgeLabel(es))}| ${z}`);
1084
+ }
1085
+ out.push('```mermaid', 'flowchart LR', ...nodeLines, ...edgeLines, '```');
1086
+ if (pairs.length > b.edgesInDiagram)
1087
+ out.push('', `${pairs.length - b.edgesInDiagram} more link(s) not drawn.`);
1088
+ out.push('');
1089
+ out.push('| Module | Path | Uses | Used by |', '|---|---|---|---|');
1090
+ const rows = [];
1091
+ for (const c of children) {
1092
+ const uses = pairs.filter(([k]) => k.split('\u0000')[0] === c.path).map(([k]) => nameOf(k.split('\u0000')[1]));
1093
+ const usedBy = pairs.filter(([k]) => k.split('\u0000')[1] === c.path).map(([k]) => nameOf(k.split('\u0000')[0]));
1094
+ const fmt = (xs) => (xs.length === 0 ? '—' : xs.slice(0, 4).join(', ') + (xs.length > 4 ? ` +${xs.length - 4}` : ''));
1095
+ rows.push(`| ${cell(c.name)} | \`${c.path}\` | ${cell(fmt(uses))} | ${cell(fmt(usedBy))} |`);
1096
+ }
1097
+ out.push(...rows.slice(0, b.tableRows));
1098
+ if (rows.length > b.tableRows)
1099
+ out.push(`| … | +${rows.length - b.tableRows} more modules | | |`);
1100
+ const extTargets = [...new Set(ext.map(x => x.target))].sort();
1101
+ if (extTargets.length > 0)
1102
+ out.push('', `External services called: ${extTargets.slice(0, 8).map(t => `\`${t}\``).join(', ')}${extTargets.length > 8 ? `, +${extTargets.length - 8}` : ''}.`);
1103
+ out.push('');
1104
+ }
1105
+ // 2. Constraints owned by this level.
1106
+ out.push('## Constraints', '');
1107
+ const own = facts.constraints.filter(c => c.owner === level);
1108
+ const inl = facts.inlineSchemas.get(level);
1109
+ if (own.length === 0 && !inl) {
1110
+ out.push('None at this level.', '');
1111
+ }
1112
+ else {
1113
+ const order = { table: 0, schema: 1, limit: 2 };
1114
+ const sorted = [...own].sort((a, b) => order[a.kind] - order[b.kind] || (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line));
1115
+ if (sorted.length > 0) {
1116
+ out.push('| Constraint | Kind | Rule | From |', '|---|---|---|---|');
1117
+ for (const c of sorted.slice(0, b.constraints)) {
1118
+ const kind = c.kind === 'table' ? `DB table (${c.source})` : c.kind === 'schema' ? `schema (${c.source})` : 'limit';
1119
+ const rule = c.kind === 'limit' ? `= ${c.summary}` : c.summary;
1120
+ out.push(`| \`${cell(c.name)}\` | ${kind} | ${cell(rule)} | \`${c.file}:${c.line}\` |`);
1121
+ }
1122
+ const rest = sorted.slice(b.constraints);
1123
+ if (rest.length > 0) {
1124
+ const by = { table: 0, schema: 0, limit: 0 };
1125
+ for (const r of rest)
1126
+ by[r.kind]++;
1127
+ const files = new Set(rest.map(r => r.file)).size;
1128
+ out.push('', `+${rest.length} more (${by.table} tables, ${by.schema} schemas, ${by.limit} limits) in ${files} file(s).`);
1129
+ }
1130
+ }
1131
+ if (inl)
1132
+ out.push('', `Inline request validation: ${inl.count} handler input schema(s) in ${inl.files} file(s).`);
1133
+ out.push('');
1134
+ }
1135
+ // 3. State machines owned by this level.
1136
+ out.push('## State machines', '');
1137
+ const ms = facts.machines.filter(m => m.owner === level);
1138
+ if (ms.length === 0) {
1139
+ out.push('None at this level.');
1140
+ }
1141
+ else {
1142
+ for (const m of ms.slice(0, b.machines)) {
1143
+ const def = m.definedAt[0];
1144
+ const alias = m.aliases.length > 0 ? `; also \`${m.aliases.slice(0, 3).join('`, `')}\`` : '';
1145
+ out.push(`### \`${m.name}\` (field \`${m.field}\`)`, '');
1146
+ out.push(`${m.states.length} states, ${m.transitions.length} guarded transition(s) found. Defined at \`${def.file}:${def.line}\`${alias}.`, '');
1147
+ out.push('```mermaid', 'stateDiagram-v2');
1148
+ for (const s of m.states) {
1149
+ const id = stateId(s);
1150
+ if (id !== s)
1151
+ out.push(` state "${s}" as ${id}`);
1152
+ }
1153
+ if (m.initial)
1154
+ out.push(` [*] --> ${stateId(m.initial)}`);
1155
+ const shown = m.transitions.slice(0, b.transitionsPerMachine);
1156
+ const inDiagram = new Set(m.initial ? [m.initial] : []);
1157
+ for (const t of shown) {
1158
+ out.push(` ${stateId(t.from)} --> ${stateId(t.to)}`);
1159
+ inDiagram.add(t.from);
1160
+ inDiagram.add(t.to);
1161
+ }
1162
+ for (const s of m.states)
1163
+ if (!inDiagram.has(s))
1164
+ out.push(` ${stateId(s)}`);
1165
+ out.push('```', '');
1166
+ if (shown.length > 0) {
1167
+ const sites = shown.slice(0, 4).map(t => `${t.from}→${t.to} \`${t.file}:${t.line}\``);
1168
+ out.push(`Transitions from: ${sites.join('; ')}${shown.length > 4 ? '; …' : ''}.`);
1169
+ }
1170
+ if (m.transitions.length > shown.length)
1171
+ out.push(`+${m.transitions.length - shown.length} more transition(s).`);
1172
+ if (m.writtenBy.length > 0) {
1173
+ out.push(`Written by: ${m.writtenBy.slice(0, 5).map(w => `${nameOf(w.level)} \`${w.file}:${w.line}\``).join('; ')}${m.writtenBy.length > 5 ? `; +${m.writtenBy.length - 5} more` : ''}.`);
1174
+ }
1175
+ if (m.unguarded.length > 0) {
1176
+ out.push(`Written without a status guard: ${m.unguarded.slice(0, 4).map(u => `${u.to} \`${u.file}:${u.line}\``).join('; ')}${m.unguarded.length > 4 ? '; …' : ''}.`);
1177
+ }
1178
+ out.push('');
1179
+ }
1180
+ if (ms.length > b.machines) {
1181
+ out.push(`+${ms.length - b.machines} more: ${ms.slice(b.machines, b.machines + 6).map(m => `\`${m.name}\` (${m.states.length} states)`).join(', ')}${ms.length > b.machines + 6 ? ', …' : ''}.`);
1182
+ }
1183
+ }
1184
+ while (out.length > 0 && out[out.length - 1] === '')
1185
+ out.pop();
1186
+ return out.join('\n') + '\n';
1187
+ }
1188
+ /** '.' / '' / './x/' → the internal level key ('' for the repository). */
1189
+ function levelKey(sourceRoot) {
1190
+ const k = sourceRoot.replace(/\\/g, '/').replace(/^\.\/|\/+$/g, '');
1191
+ return k === '.' ? '' : k;
1192
+ }
1193
+ /**
1194
+ * design.md for every level, keyed by source root (`.` for the repository, the
1195
+ * module root otherwise; `SpecLevel.sourceRoot`). One read serves all levels.
1196
+ */
1197
+ export function generateLevelDesigns(repoRoot, modules, options = {}) {
1198
+ const facts = collectDesignFacts(repoRoot, modules, options);
1199
+ const out = new Map();
1200
+ out.set('.', renderLevelDesign(facts, '.', options));
1201
+ for (const m of facts.modules)
1202
+ out.set(m.path, renderLevelDesign(facts, m.path, options));
1203
+ return out;
1204
+ }
1205
+ /** design.md for one level (`sourceRoot` `.` for the repository). */
1206
+ export function generateLevelDesign(repoRoot, modules, sourceRoot, options = {}) {
1207
+ return renderLevelDesign(collectDesignFacts(repoRoot, modules, options), sourceRoot, options);
1208
+ }
1209
+ // ─── Shared tree shapes (tree-types.ts) ──────────────────────────────
1210
+ function sitePath(site) {
1211
+ const i = site.lastIndexOf(':');
1212
+ const line = Number(site.slice(i + 1)) || 1;
1213
+ return { file: site.slice(0, i), startLine: line, endLine: line, role: 'evidence' };
1214
+ }
1215
+ const TREE_EDGE_KIND = {
1216
+ imports: 'import', depends: 'dependency', http: 'http', rpc: 'call', queue: 'queue', service: 'call',
1217
+ };
1218
+ /**
1219
+ * The facts in `tree-types.ts` shapes, module references by `Module.name`
1220
+ * (undefined = repository level). Edges between the repository's own files and
1221
+ * a module use the repository name `.`.
1222
+ */
1223
+ export function toTreeDesignFacts(facts) {
1224
+ const nameOf = (p) => (p === '' ? '.' : facts.modules.find(m => m.path === p)?.name ?? p);
1225
+ const modOf = (p) => (p === '' ? undefined : nameOf(p));
1226
+ const edges = facts.edges.map(e => ({
1227
+ from: nameOf(e.from),
1228
+ to: nameOf(e.to),
1229
+ kind: TREE_EDGE_KIND[e.kind],
1230
+ ...(e.detail ? { label: e.kind === 'service' ? `service ${e.detail}` : e.detail } : {}),
1231
+ codePaths: [sitePath(e.site)],
1232
+ }));
1233
+ const stateMachines = facts.machines.map(m => {
1234
+ const d = m.definedAt[0];
1235
+ return {
1236
+ name: m.name,
1237
+ ...(modOf(m.owner) ? { module: modOf(m.owner) } : {}),
1238
+ states: m.states,
1239
+ transitions: [
1240
+ ...m.transitions.map(t => ({ from: t.from, to: t.to, codePath: { ...sitePath(`${t.file}:${t.line}`), role: 'anchor' } })),
1241
+ ...m.unguarded.map(u => ({ from: '*', to: u.to, codePath: { ...sitePath(`${u.file}:${u.line}`), role: 'anchor' } })),
1242
+ ],
1243
+ declaredAt: { file: d.file, startLine: d.line, endLine: d.line, role: 'anchor' },
1244
+ };
1245
+ });
1246
+ const constraints = facts.constraints.map(c => ({
1247
+ text: c.kind === 'limit' ? `${c.name} = ${c.summary}` : `${c.name} (${c.kind === 'table' ? `DB table, ${c.source}` : `schema, ${c.source}`}): ${c.summary}`,
1248
+ ...(modOf(c.owner) ? { module: modOf(c.owner) } : {}),
1249
+ codePaths: [{ file: c.file, startLine: c.line, endLine: c.line, role: 'anchor' }],
1250
+ }));
1251
+ return { edges, stateMachines, constraints };
1252
+ }
1253
+ //# sourceMappingURL=level-design.js.map