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,888 @@
1
+ /**
2
+ * Use cases from entry points (spec recovery 0.2, task SR-E2; design §1.2).
3
+ *
4
+ * Per module, find the entry points and turn each into a `UseCase`, grouped
5
+ * into areas (the `##` headings of the module's spec.md):
6
+ *
7
+ * - **routes** — HTTP route registrations (`runtime_registrations`, every
8
+ * language circle-ir registers: Express, Fastify, Koa, Hono, Flask,
9
+ * FastAPI, axum, actix, …), verb calls on other routers (`users.get('/x', h)`),
10
+ * Nest decorators (0.1 TS sources, `ts-rule-sources.ts`), Spring / JAX-RS
11
+ * annotations (0.1 Java evidence, `evidence-extractor.ts`), tRPC procedures;
12
+ * mount prefixes (`app.route('/billing', billing)`, `app.use('/x', router)`)
13
+ * are followed across the module's files through relative imports;
14
+ * - **cli** — commander / yargs `.command('name')`, click commands,
15
+ * Spring Shell `@ShellMethod`, picocli `@Command`;
16
+ * - **handler** — the Cloudflare Worker `fetch` export, domain event
17
+ * listeners (`bus.on('order.created', h)`, Spring `@EventListener`);
18
+ * - **queue** — Worker `queue` export, BullMQ `new Worker('q', h)`, Bull
19
+ * `queue.process('q', h)`, kafkajs `consumer.run`, amqplib `channel.consume`,
20
+ * celery tasks, Spring `@KafkaListener` / `@RabbitListener` / `@JmsListener` / `@SqsListener`;
21
+ * - **cron** — Worker `scheduled` export, `cron.schedule`, `schedule.scheduleJob`,
22
+ * `new CronJob`, Spring `@Scheduled`;
23
+ * - **file routes** (`file-routes.ts`) — Next.js app and pages routers,
24
+ * TanStack Router `createFileRoute`, Remix / React Router 7 flat routes,
25
+ * SvelteKit `+page` / `+server`, route config objects (method `PAGE`, or
26
+ * the exported verb); `'use server'` exports as handlers (method `ACTION`);
27
+ * - **public-api** — for a library (a module with none of the above), its
28
+ * public surface (`library-surface.ts`): one row per surface area (package
29
+ * subpath, or the directory a root-entry export is declared in), with
30
+ * counts and the key exported names, not one use case per function.
31
+ *
32
+ * Area = the first meaningful route segment (`/api/v1/billing/…` → Billing),
33
+ * the tRPC router key, the command or topic group (`db:migrate` → Db), or the
34
+ * directory under the entry layer (`src/routes/billing/…`, `jobs/sweep.ts`).
35
+ *
36
+ * Domain rules: the guard and throw facts of 0.1 (`extractTsRuleFacts`) inside
37
+ * the handler and the same-file functions it calls, with the 0.1 rule text, so
38
+ * a rule keeps its 0.1 `ruleKey`. Layer mechanics (request plumbing, auth
39
+ * tokens, headers, env and config, parsing) are dropped here: they belong in
40
+ * principles.md (SR-E3), not in a use case.
41
+ *
42
+ * Facts only from circle-ir's IR; source text is read only at line numbers
43
+ * circle-ir gives (to confirm a Worker handler's name on its function's first
44
+ * line, as 0.1 confirms `throw`). Pure: no I/O, no model.
45
+ */
46
+ import { createHash } from 'node:crypto';
47
+ import * as path from 'node:path';
48
+ import { extractEvidence } from './evidence-extractor.js';
49
+ import { computeRuleKey, staticProvenance } from './provenance.js';
50
+ import { appDirRoute, fileRouteEntries, fileRouteSignals, routerConfigEntries, serverActionEntries } from './file-routes.js';
51
+ import { keyNames, librarySurface } from './library-surface.js';
52
+ import { extractTsRuleFacts, isTsOrJs, joinRoute } from './ts-rule-sources.js';
53
+ const INLINE = '<inline>';
54
+ /** Build and tool config (`vite.config.ts`, `wrangler.config.js`) is not an entry layer. */
55
+ const CONFIG_FILE = /(^|\/)[\w.-]+\.config\.[cm]?[jt]s$/;
56
+ const TEST_FILE = /(^|\/)(__tests__|__mocks__|tests?|spec|e2e|fixtures?)\/|\.(test|spec|e2e|tp)\.[cm]?[jt]sx?$|(^|\/)test\.[jt]s$|Test\.java$|_test\.(go|py)$/;
57
+ const VERBS = {
58
+ get: 'GET', post: 'POST', put: 'PUT', delete: 'DELETE', del: 'DELETE', patch: 'PATCH',
59
+ head: 'HEAD', options: 'OPTIONS', all: 'ANY',
60
+ };
61
+ function functions(ir) {
62
+ const out = [];
63
+ for (const t of ir.types ?? []) {
64
+ for (const m of t.methods ?? []) {
65
+ out.push({
66
+ symbol: t.name === '<module>' ? m.name : `${t.name}.${m.name}`,
67
+ name: m.name, start: m.start_line, end: m.end_line, annotations: m.annotations ?? [],
68
+ });
69
+ }
70
+ }
71
+ return out;
72
+ }
73
+ /**
74
+ * The span of the function whose CFG entry block starts on `line` (an inline
75
+ * arrow or function expression), at or after `minColumn`. The matching exit
76
+ * is found by balancing entry/exit blocks, so nested functions do not cut it short.
77
+ */
78
+ function cfgFunctionAt(ir, line, minColumn = 0) {
79
+ const blocks = ir.cfg?.blocks ?? [];
80
+ const i = blocks.findIndex(b => b.type === 'entry' && b.start_line === line && (b.start_column ?? 0) >= minColumn);
81
+ if (i < 0)
82
+ return undefined;
83
+ let depth = 0;
84
+ let end = line;
85
+ for (let j = i; j < blocks.length; j++) {
86
+ const b = blocks[j];
87
+ end = Math.max(end, b.end_line);
88
+ if (b.type === 'entry')
89
+ depth++;
90
+ else if (b.type === 'exit' && --depth === 0)
91
+ return { start: line, end: Math.max(end, b.end_line) };
92
+ }
93
+ return { start: line, end };
94
+ }
95
+ /** Each CFG function: its entry line and span. */
96
+ function cfgFunctions(ir) {
97
+ const out = [];
98
+ for (const b of ir.cfg?.blocks ?? []) {
99
+ if (b.type !== 'entry')
100
+ continue;
101
+ const s = cfgFunctionAt(ir, b.start_line, b.start_column ?? 0);
102
+ if (s && !out.some(o => o.start === s.start && o.end === s.end))
103
+ out.push(s);
104
+ }
105
+ return out;
106
+ }
107
+ function byName(fns, name, line) {
108
+ if (!name)
109
+ return undefined;
110
+ const bare = name.replace(/^this\./, '');
111
+ const named = fns.filter(f => f.name === bare || f.symbol === bare);
112
+ if (line !== undefined) {
113
+ const at = named.find(f => f.start <= line && line <= f.end);
114
+ if (at)
115
+ return at;
116
+ }
117
+ return named[0];
118
+ }
119
+ function lit(a) {
120
+ if (!a)
121
+ return undefined;
122
+ if (a.literal != null)
123
+ return a.literal;
124
+ const m = (a.expression ?? '').trim().match(/^(['"`])([^'"`$\\]*)\1$/);
125
+ return m ? m[2] : undefined;
126
+ }
127
+ function ident(a) {
128
+ if (!a || a.literal != null)
129
+ return undefined;
130
+ const e = (a.expression ?? '').trim();
131
+ return /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)?$/.test(e) ? e : undefined;
132
+ }
133
+ /** The handler for a call-registered entry: a named function, or the inline function on the call's line. */
134
+ function handlerFor(ir, fns, arg, line) {
135
+ const name = ident(arg);
136
+ const f = byName(fns, name);
137
+ if (f)
138
+ return { symbol: f.symbol, span: { start: f.start, end: f.end } };
139
+ // An imported handler: named, anchored on the registration line (its body is in another file).
140
+ if (name && (ir.imports ?? []).some(i => (i.alias ?? i.imported_name) === name.split('.')[0]))
141
+ return { symbol: name, span: { start: line, end: line } };
142
+ const inline = cfgFunctionAt(ir, line);
143
+ if (inline)
144
+ return { span: inline };
145
+ // An expression-bodied arrow has no CFG: the argument's text says it is a function.
146
+ if (isFunctionText(arg?.expression))
147
+ return { span: { start: line, end: line }, inline: true };
148
+ return { span: { start: line, end: line } };
149
+ }
150
+ function isFunctionText(e) {
151
+ const t = (e ?? '').trim();
152
+ return /^(async\s+)?(function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/.test(t);
153
+ }
154
+ // ─── Entry sources ───────────────────────────────────────────────────
155
+ function routeEntries(sf, fns) {
156
+ const { file, ir, code } = sf;
157
+ const out = [];
158
+ const lines = new Set();
159
+ for (const r of ir.runtime_registrations ?? []) {
160
+ const handler = r.handler?.name ? byName(fns, r.handler.name, r.handler.line) : undefined;
161
+ const span = handler
162
+ ? { start: handler.start, end: handler.end }
163
+ : cfgFunctionAt(ir, r.handler?.line ?? r.registrar.line, r.handler?.column ?? 0) ?? { start: r.registrar.line, end: r.registrar.line };
164
+ const base = { file, symbol: handler?.symbol, span, site: r.registrar.line };
165
+ if (r.kind === 'http_route') {
166
+ const verb = VERBS[String(r.registrar?.method ?? '').toLowerCase()] ?? (isTsOrJs(ir.meta.language) ? undefined : String(r.registrar.method || 'ANY').toUpperCase());
167
+ if (!verb)
168
+ continue;
169
+ lines.add(r.registrar.line);
170
+ out.push({ ...base, kind: 'route', method: verb, path: r.path ?? undefined, mountable: true });
171
+ }
172
+ else if (r.framework === 'click') {
173
+ out.push({ ...base, kind: 'cli', path: r.path ?? r.handler?.name?.replace(/_/g, '-') ?? undefined });
174
+ }
175
+ else if (r.framework === 'celery') {
176
+ out.push({ ...base, kind: 'queue', path: r.path ?? r.handler?.name ?? undefined });
177
+ }
178
+ else if (r.kind === 'event_listener' && r.path && isDomainEvent(r.registrar.receiver, r.path)) {
179
+ out.push({ ...base, kind: 'handler', method: 'EVENT', path: r.path });
180
+ }
181
+ }
182
+ // Verb calls circle-ir did not register (another router object: `users.get('/:id', h)`).
183
+ for (const c of ir.calls ?? []) {
184
+ const verb = VERBS[c.method_name];
185
+ const line = c.location?.line;
186
+ if (!verb || !line || lines.has(line) || !c.receiver || !/^[A-Za-z_$][\w$]*$/.test(c.receiver))
187
+ continue;
188
+ const p = lit(c.arguments?.[0]);
189
+ if (!p || !p.startsWith('/') || (c.arguments?.length ?? 0) < 2)
190
+ continue;
191
+ // The last argument must be a handler: a function of this file or an inline function.
192
+ const h = handlerFor(ir, fns, c.arguments[c.arguments.length - 1], line);
193
+ if (!h.symbol && !h.inline && h.span.end === h.span.start)
194
+ continue;
195
+ lines.add(line);
196
+ out.push({ kind: 'route', file, method: verb, path: p, symbol: h.symbol, span: h.span, site: line, mountable: true });
197
+ }
198
+ // Decorator routes (Nest), from the 0.1 TS sources.
199
+ if (isTsOrJs(ir.meta.language)) {
200
+ for (const r of extractTsRuleFacts(file, code, ir).routes) {
201
+ if (r.framework !== 'decorator')
202
+ continue;
203
+ out.push({ kind: 'route', file, method: r.verb, path: r.path, symbol: r.handlerSymbol, span: { start: r.startLine, end: r.endLine } });
204
+ }
205
+ }
206
+ else {
207
+ // Spring / JAX-RS, from the 0.1 Java annotation evidence.
208
+ for (const e of extractEvidence(file, code, ir).publicAPI) {
209
+ if (e.lineStart === undefined)
210
+ continue;
211
+ out.push({
212
+ kind: 'route', file, method: e.method, path: joinRoute(e.path),
213
+ symbol: e.ownerType ? `${e.ownerType}.${e.handler}` : e.handler,
214
+ span: { start: e.lineStart, end: e.lineEnd ?? e.lineStart },
215
+ });
216
+ }
217
+ }
218
+ return out;
219
+ }
220
+ const RUNTIME_EVENTS = new Set(['error', 'close', 'end', 'data', 'finish', 'open', 'drain', 'listening', 'connection',
221
+ 'connect', 'disconnect', 'message', 'request', 'upgrade', 'exit', 'SIGINT', 'SIGTERM', 'SIGHUP', 'uncaughtException',
222
+ 'unhandledRejection', 'beforeExit', 'warning', 'ready', 'timeout', 'response', 'abort', 'load', 'click', 'change',
223
+ 'input', 'submit', 'keydown', 'keyup', 'resize', 'scroll', 'DOMContentLoaded']);
224
+ const RUNTIME_RECEIVERS = /^(process|req|res|request|response|stream|socket|ws|server|window|document|el|element|child|proc|emitter\.process)$/;
225
+ function isDomainEvent(receiver, event) {
226
+ return !RUNTIME_EVENTS.has(event) && !RUNTIME_RECEIVERS.test(receiver) && /[.:/]|^[a-z]+[A-Z_-]/.test(event);
227
+ }
228
+ const CLI_RECEIVER = /\b(program|cli|yargs|commander|cmd|command|app)\b|Command\(\)/i;
229
+ function callEntries(sf, fns) {
230
+ const { file, ir } = sf;
231
+ const out = [];
232
+ const calls = ir.calls ?? [];
233
+ for (const c of calls) {
234
+ const line = c.location?.line;
235
+ if (!line)
236
+ continue;
237
+ const args = c.arguments ?? [];
238
+ const m = c.method_name;
239
+ const recv = c.receiver ?? '';
240
+ // commander / yargs: `.command('deploy <env>')`.
241
+ if (m === 'command' && recv) {
242
+ const name = lit(args[0])?.trim().split(/\s+/)[0];
243
+ if (!name || name.startsWith('/') || name.startsWith('$'))
244
+ continue;
245
+ const action = calls.find(a => a.method_name === 'action' && a.location?.line === line && (a.receiver ?? '').includes(`command(`));
246
+ const viaAction = action !== undefined || calls.some(a => a.method_name === 'action' && (a.receiver ?? '').includes(`command('${lit(args[0])}'`));
247
+ if (!viaAction && !CLI_RECEIVER.test(recv) && args.length < 3)
248
+ continue;
249
+ const handlerArg = action?.arguments?.[0] ?? (args.length >= 4 ? args[3] : undefined);
250
+ const h = handlerFor(ir, fns, handlerArg, line);
251
+ out.push({ kind: 'cli', file, path: name, symbol: h.symbol, span: h.span, site: line });
252
+ continue;
253
+ }
254
+ // Domain event listeners not registered by circle-ir: `bus.on('order.created', h)`.
255
+ if ((m === 'on' || m === 'addListener' || m === 'subscribe' || m === 'once') && recv && args.length >= 2) {
256
+ const ev = lit(args[0]);
257
+ if (!ev || !isDomainEvent(recv, ev))
258
+ continue;
259
+ if ((ir.runtime_registrations ?? []).some(r => r.registrar.line === line))
260
+ continue;
261
+ const h = handlerFor(ir, fns, args[args.length - 1], line);
262
+ if (!h.symbol && !h.inline && h.span.end === h.span.start)
263
+ continue;
264
+ out.push({ kind: 'handler', file, method: 'EVENT', path: ev, symbol: h.symbol, span: h.span, site: line });
265
+ continue;
266
+ }
267
+ // node-cron / node-schedule / croner.
268
+ if ((m === 'schedule' && /cron/i.test(recv)) || (m === 'scheduleJob' && recv) || ((m === 'CronJob' || m === 'Cron') && !recv)) {
269
+ const expr = lit(args[0]);
270
+ if (!expr || !/^[\d*/,\-?LW#@a-z ]+$/i.test(expr))
271
+ continue;
272
+ const h = handlerFor(ir, fns, args[1], line);
273
+ out.push({ kind: 'cron', file, path: expr, symbol: h.symbol, span: h.span, site: line });
274
+ continue;
275
+ }
276
+ // BullMQ `new Worker('q', fn)` (not a web Worker on a script path).
277
+ if (m === 'Worker' && !recv && args.length >= 2) {
278
+ const q = lit(args[0]);
279
+ if (!q || /[./]/.test(q.slice(0, 2)) || /\.(m?js|ts)$/.test(q))
280
+ continue;
281
+ const h = handlerFor(ir, fns, args[1], line);
282
+ out.push({ kind: 'queue', file, path: q, symbol: h.symbol, span: h.span, site: line });
283
+ continue;
284
+ }
285
+ // Bull `queue.process('name', fn)`; amqplib `channel.consume('q', fn)`.
286
+ if ((m === 'process' && recv && recv !== 'process' && /queue/i.test(recv)) || (m === 'consume' && /chan|channel|ch\b|amqp|rabbit/i.test(recv))) {
287
+ const q = lit(args[0]);
288
+ const fnArg = q !== undefined ? args[1] : args[0];
289
+ const h = handlerFor(ir, fns, fnArg, line);
290
+ out.push({ kind: 'queue', file, path: q ?? recv, symbol: h.symbol, span: h.span, site: line });
291
+ continue;
292
+ }
293
+ // kafkajs `consumer.run({ eachMessage })`; topics from `consumer.subscribe({ topic })`.
294
+ if (m === 'run' && /consumer/i.test(recv) && /each(Message|Batch)/.test(args[0]?.expression ?? '')) {
295
+ const sub = calls.find(s => s.method_name === 'subscribe' && s.receiver === recv);
296
+ const topic = (sub?.arguments?.[0]?.expression ?? '').match(/topics?\s*:\s*\[?\s*(['"`])([^'"`]+)\1/)?.[2];
297
+ out.push({ kind: 'queue', file, path: topic ?? recv, span: cfgFunctionAt(ir, line) ?? { start: line, end: line }, site: line });
298
+ }
299
+ }
300
+ return out;
301
+ }
302
+ /**
303
+ * tRPC: each `.query` / `.mutation` / `.subscription` on a procedure builder,
304
+ * named by its key in the enclosing `router({ … })` object (nested routers
305
+ * give `invoice.create`). The router's argument text comes from the IR.
306
+ */
307
+ function trpcEntries(sf, fns) {
308
+ const { file, ir } = sf;
309
+ const calls = ir.calls ?? [];
310
+ const routers = calls.filter(c => (c.method_name === 'router' || c.method_name === 'createTRPCRouter') && /^\s*\{/.test(c.arguments?.[0]?.expression ?? ''));
311
+ if (routers.length === 0)
312
+ return [];
313
+ const out = [];
314
+ for (const c of calls) {
315
+ const kind = c.method_name;
316
+ if (!(kind === 'query' || kind === 'mutation' || kind === 'subscription') || !/[Pp]rocedure\b/.test(c.receiver ?? ''))
317
+ continue;
318
+ const line = c.location?.line;
319
+ if (!line)
320
+ continue;
321
+ const name = procedureName(routers, line);
322
+ if (!name)
323
+ continue;
324
+ const h = handlerFor(ir, fns, c.arguments?.[0], line);
325
+ out.push({
326
+ kind: 'route', file, method: kind.toUpperCase(), path: name,
327
+ // Area: the top router key, else the router's file under the entry layer (`routers/finding.ts`).
328
+ area: name.includes('.') ? name.split('.')[0] : directoryArea(file, ''),
329
+ symbol: h.symbol, span: h.span, site: line,
330
+ });
331
+ }
332
+ return out;
333
+ }
334
+ /** The dotted key path of the procedure on `line` within the router object literals. */
335
+ function procedureName(routers, line) {
336
+ // Innermost router holding the line names the last key; outer routers prefix it.
337
+ const holding = routers
338
+ .map(r => ({ r, start: r.location.line, text: r.arguments[0].expression ?? '' }))
339
+ .filter(x => x.start <= line && line < x.start + x.text.split('\n').length)
340
+ .sort((a, b) => b.start - a.start);
341
+ const parts = [];
342
+ let target = line;
343
+ for (const h of holding) {
344
+ const key = keyAtLine(h.text, target - h.start);
345
+ if (!key)
346
+ break;
347
+ parts.unshift(key);
348
+ target = h.start;
349
+ }
350
+ return parts.length ? parts.join('.') : undefined;
351
+ }
352
+ /** The top-level key of an object literal whose value starts on (or spans) `offset` lines into `text`. */
353
+ function keyAtLine(text, offset) {
354
+ let depth = 0;
355
+ let quote;
356
+ let lineNo = 0;
357
+ let key;
358
+ let keyLine = -1;
359
+ let token = '';
360
+ for (let i = 0; i < text.length; i++) {
361
+ const ch = text[i];
362
+ if (ch === '\n')
363
+ lineNo++;
364
+ if (lineNo > offset && key !== undefined && keyLine <= offset)
365
+ return key;
366
+ if (quote) {
367
+ if (ch === '\\')
368
+ i++;
369
+ else if (ch === quote)
370
+ quote = undefined;
371
+ continue;
372
+ }
373
+ // Comments: skip to the end of the line or of the block (an apostrophe in a comment is not a quote).
374
+ if (ch === '/' && text[i + 1] === '/') {
375
+ const nl = text.indexOf('\n', i);
376
+ i = (nl < 0 ? text.length : nl) - 1;
377
+ continue;
378
+ }
379
+ if (ch === '/' && text[i + 1] === '*') {
380
+ const close = text.indexOf('*/', i + 2);
381
+ const end = close < 0 ? text.length : close + 1;
382
+ for (let j = i; j < end; j++)
383
+ if (text[j] === '\n')
384
+ lineNo++;
385
+ i = end;
386
+ continue;
387
+ }
388
+ if (ch === "'" || ch === '"' || ch === '`') {
389
+ quote = ch;
390
+ continue;
391
+ }
392
+ if (ch === '{' || ch === '(' || ch === '[') {
393
+ depth++;
394
+ token = '';
395
+ continue;
396
+ }
397
+ if (ch === '}' || ch === ')' || ch === ']') {
398
+ depth--;
399
+ token = '';
400
+ continue;
401
+ }
402
+ if (depth === 1) {
403
+ if (ch === ':' && /^[A-Za-z_$][\w$]*$/.test(token.trim())) {
404
+ if (lineNo > offset)
405
+ return key;
406
+ key = token.trim();
407
+ keyLine = lineNo;
408
+ token = '';
409
+ continue;
410
+ }
411
+ if (ch === ',') {
412
+ token = '';
413
+ continue;
414
+ }
415
+ token += ch;
416
+ }
417
+ }
418
+ return keyLine <= offset ? key : undefined;
419
+ }
420
+ const WORKER_TYPES = /\b(ExecutionContext|ScheduledController|ScheduledEvent|MessageBatch|ForwardableEmailMessage|ExportedHandler)\b/;
421
+ const WORKER_HANDLERS = {
422
+ fetch: { kind: 'handler', method: 'FETCH' },
423
+ scheduled: { kind: 'cron', method: 'SCHEDULED' },
424
+ queue: { kind: 'queue', method: 'QUEUE' },
425
+ email: { kind: 'handler', method: 'EMAIL' },
426
+ };
427
+ /**
428
+ * Cloudflare Worker exports (`export default { fetch, scheduled, queue }`):
429
+ * circle-ir has no declaration for an object literal's methods, so each CFG
430
+ * function whose first line names a Worker handler is one, in a Worker entry
431
+ * file or when the line carries a Workers type.
432
+ */
433
+ function workerEntries(sf, isEntry) {
434
+ const { file, ir, code } = sf;
435
+ if (!isTsOrJs(ir.meta.language))
436
+ return [];
437
+ const lines = code.split('\n');
438
+ const out = [];
439
+ const classSpans = (ir.types ?? []).filter(t => t.name !== '<module>').map(t => ({ start: t.start_line, end: t.end_line }));
440
+ for (const s of cfgFunctions(ir)) {
441
+ const text = lines[s.start - 1] ?? '';
442
+ const m = text.match(/^\s*(?:async\s+)?(fetch|scheduled|queue|email)\s*\(/);
443
+ if (!m)
444
+ continue;
445
+ if (classSpans.some(c => c.start <= s.start && s.start <= c.end))
446
+ continue; // Durable Object / class method
447
+ if (!isEntry && !WORKER_TYPES.test(text))
448
+ continue;
449
+ const h = WORKER_HANDLERS[m[1]];
450
+ out.push({ kind: h.kind, file, method: h.method, symbol: m[1], span: s, area: 'Worker' });
451
+ }
452
+ return out;
453
+ }
454
+ /** Java / Kotlin annotations: listeners, schedules, shell commands. */
455
+ function annotationEntries(sf) {
456
+ const { file, ir } = sf;
457
+ if (isTsOrJs(ir.meta.language))
458
+ return [];
459
+ const out = [];
460
+ const arg = (a, ...keys) => {
461
+ for (const k of keys) {
462
+ const m = a.match(new RegExp(`\\b${k}\\s*=\\s*\\{?\\s*"([^"]+)"`));
463
+ if (m)
464
+ return m[1];
465
+ }
466
+ return a.match(/\(\s*\{?\s*"([^"]+)"/)?.[1];
467
+ };
468
+ for (const t of ir.types ?? []) {
469
+ const owner = t.name === '<module>' ? undefined : t.name;
470
+ const clsCommand = (t.annotations ?? []).map(a => a.replace(/^@/, '')).find(a => /^Command\b/.test(a));
471
+ if (clsCommand) {
472
+ const run = t.methods.find(m => m.name === 'call' || m.name === 'run');
473
+ const span = run ? { start: run.start_line, end: run.end_line } : { start: t.start_line, end: t.end_line };
474
+ out.push({ kind: 'cli', file, path: arg(clsCommand, 'name') ?? t.name, symbol: run ? `${t.name}.${run.name}` : t.name, span });
475
+ }
476
+ for (const m of t.methods ?? []) {
477
+ const symbol = owner ? `${owner}.${m.name}` : m.name;
478
+ const span = { start: m.start_line, end: m.end_line };
479
+ for (const raw of m.annotations ?? []) {
480
+ const a = raw.replace(/^@/, '');
481
+ const name = a.replace(/\(.*$/s, '').trim();
482
+ if (name === 'Scheduled')
483
+ out.push({ kind: 'cron', file, symbol, span, path: arg(a, 'cron', 'fixedRate', 'fixedDelay', 'fixedRateString', 'fixedDelayString') ?? a.match(/(fixed\w+)\s*=\s*(\d+)/)?.slice(1).join('=') ?? 'scheduled' });
484
+ else if (/^(KafkaListener|RabbitListener|JmsListener|SqsListener|StreamListener|KafkaHandler)$/.test(name))
485
+ out.push({ kind: 'queue', file, symbol, span, path: arg(a, 'topics', 'queues', 'destination', 'value') ?? symbol });
486
+ else if (name === 'EventListener' || name === 'TransactionalEventListener')
487
+ out.push({ kind: 'handler', file, symbol, span, method: 'EVENT', path: arg(a, 'classes', 'value') ?? m.parameters?.[0]?.type ?? symbol });
488
+ else if (name === 'ShellMethod' || name === 'Command')
489
+ out.push({ kind: 'cli', file, symbol, span, path: arg(a, 'key', 'name', 'command') ?? m.name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() });
490
+ }
491
+ }
492
+ }
493
+ return out;
494
+ }
495
+ // ─── Mount prefixes (Hono `app.route`, Express `app.use`) ────────────
496
+ function resolveImport(from, spec, known) {
497
+ if (!spec.startsWith('.'))
498
+ return undefined;
499
+ const base = path.posix.normalize(path.posix.join(path.posix.dirname(from), spec)).replace(/\.(m?js|cjs)$/, '');
500
+ for (const ext of ['', '.ts', '.tsx', '.js', '.mjs', '.jsx', '/index.ts', '/index.tsx', '/index.js']) {
501
+ if (known.has(base + ext))
502
+ return base + ext;
503
+ }
504
+ return undefined;
505
+ }
506
+ /** target file → the prefixes it is mounted under (transitively; a file mounted nowhere has none). */
507
+ function mountPrefixes(files) {
508
+ const known = new Set(files.map(f => f.file));
509
+ const edges = [];
510
+ for (const sf of files) {
511
+ const imports = sf.ir.imports ?? [];
512
+ for (const c of sf.ir.calls ?? []) {
513
+ if (c.method_name !== 'route' && c.method_name !== 'use' && c.method_name !== 'register')
514
+ continue;
515
+ const prefix = lit(c.arguments?.[0]);
516
+ const target = ident(c.arguments?.[1]);
517
+ if (!prefix?.startsWith('/') || !target)
518
+ continue;
519
+ const imp = imports.find(i => (i.alias ?? i.imported_name) === target);
520
+ const to = imp?.from_package ? resolveImport(sf.file, imp.from_package, known) : undefined;
521
+ if (to && to !== sf.file)
522
+ edges.push({ from: sf.file, to, prefix });
523
+ }
524
+ }
525
+ const memo = new Map();
526
+ const visit = (file, seen) => {
527
+ if (memo.has(file))
528
+ return memo.get(file);
529
+ const incoming = edges.filter(e => e.to === file && !seen.has(e.from));
530
+ const out = [];
531
+ for (const e of incoming) {
532
+ const parents = visit(e.from, new Set([...seen, file]));
533
+ for (const p of parents.length ? parents : [''])
534
+ out.push(joinRoute(p, e.prefix));
535
+ }
536
+ const uniq = [...new Set(out)].sort();
537
+ memo.set(file, uniq);
538
+ return uniq;
539
+ };
540
+ const result = new Map();
541
+ for (const f of known) {
542
+ const p = visit(f, new Set());
543
+ if (p.length)
544
+ result.set(f, p);
545
+ }
546
+ return result;
547
+ }
548
+ // ─── Areas and titles ────────────────────────────────────────────────
549
+ const ENTRY_LAYER_DIRS = new Set(['routes', 'route', 'routers', 'router', 'api', 'apis', 'controllers', 'controller', 'handlers',
550
+ 'handler', 'commands', 'command', 'cmd', 'cli', 'jobs', 'job', 'cron', 'crons', 'tasks', 'workers', 'worker', 'consumers',
551
+ 'consumer', 'queues', 'queue', 'listeners', 'subscribers', 'events', 'trpc', 'procedures', 'endpoints', 'functions', 'lambdas', 'resources', 'web', 'rest', 'actions']);
552
+ const GENERIC_SEGMENTS = /^(api|apis|rest|rpc|trpc|v\d+(\.\d+)?|internal|public|private|admin-api|_?next)$/i;
553
+ const FILE_SUFFIX = /\.(controller|controllers|routes?|router|handlers?|resource|endpoint|api|command|cmd|job|cron|consumer|worker|listener|procedures?)$/i;
554
+ function words(s) {
555
+ return s.replace(/([a-z\d])([A-Z])/g, '$1 $2').replace(/[-_.:]+/g, ' ').trim();
556
+ }
557
+ function areaName(s) {
558
+ const w = words(s).toLowerCase();
559
+ return w ? w.charAt(0).toUpperCase() + w.slice(1) : 'General';
560
+ }
561
+ /** The first route segment that is not `api`, a version, a parameter or a one-letter prefix (`/r/:repoId/runs` → runs). */
562
+ function routeArea(p) {
563
+ for (const seg of p.split('/')) {
564
+ const clean = seg.replace(/[*?+]+$/, '');
565
+ if (!clean || clean.length < 2 || GENERIC_SEGMENTS.test(clean) || /^[:{*[<(]/.test(clean) || clean.startsWith('$'))
566
+ continue;
567
+ return clean;
568
+ }
569
+ return undefined;
570
+ }
571
+ /** The directory (or file stem) right under the entry layer, relative to the module root. */
572
+ function directoryArea(file, moduleRoot) {
573
+ const rel = moduleRoot && file.startsWith(moduleRoot + '/') ? file.slice(moduleRoot.length + 1) : file;
574
+ const parts = rel.split('/');
575
+ const stem = (f) => f.replace(/\.[^.]+$/, '').replace(FILE_SUFFIX, '');
576
+ for (let i = 0; i < parts.length - 1; i++) {
577
+ if (!ENTRY_LAYER_DIRS.has(parts[i].toLowerCase()))
578
+ continue;
579
+ const next = i + 1 < parts.length - 1 ? parts[i + 1] : stem(parts[parts.length - 1]);
580
+ if (next && next !== 'index' && !ENTRY_LAYER_DIRS.has(next.toLowerCase()))
581
+ return next;
582
+ }
583
+ return undefined;
584
+ }
585
+ const KIND_AREA = {
586
+ route: 'Http', cli: 'Commands', handler: 'Handlers', queue: 'Queues', cron: 'Scheduled jobs', 'public-api': 'Api',
587
+ };
588
+ function areaOf(f, moduleRoot) {
589
+ if (f.area)
590
+ return areaName(f.area);
591
+ let key;
592
+ if (f.kind === 'route' && f.path)
593
+ key = routeArea(f.path);
594
+ else if ((f.kind === 'cli' || f.kind === 'queue' || f.kind === 'handler') && f.path && /[:. /]/.test(f.path))
595
+ key = f.path.split(/[:. /]/).find(Boolean);
596
+ key ??= directoryArea(f.file, moduleRoot);
597
+ if (!key && f.kind === 'public-api') {
598
+ const rel = moduleRoot && f.file.startsWith(moduleRoot + '/') ? f.file.slice(moduleRoot.length + 1) : f.file;
599
+ const dirs = rel.split('/').slice(0, -1).filter(d => d !== 'src' && d !== 'lib');
600
+ key = dirs[0] ?? rel.split('/').pop().replace(/\.[^.]+$/, '').replace(/^index$/, '');
601
+ }
602
+ // JVM: the package's last segment (`acme/billing/RefundController.java` → billing).
603
+ if (!key && /\.(java|kt|scala)$/.test(f.file)) {
604
+ const dir = f.file.split('/').slice(-2, -1)[0];
605
+ if (dir && !/^(java|kotlin|scala|main|src)$/.test(dir))
606
+ key = dir;
607
+ }
608
+ if (!key && f.kind === 'route' && f.symbol?.includes('.'))
609
+ key = f.symbol.split('.')[0].replace(/(Controller|Resource|Router|Handler|Api)$/, '');
610
+ return key ? areaName(key) : KIND_AREA[f.kind];
611
+ }
612
+ const GENERIC_HANDLER = /^(handler|handle|default|anonymous|index|main|run|call|execute|fetch|scheduled|queue|email|process|<inline>)$/i;
613
+ function titleOf(f) {
614
+ const member = f.symbol?.split('.').pop();
615
+ const trigger = triggerOf(f);
616
+ if (member && !GENERIC_HANDLER.test(member)) {
617
+ const w = words(member).toLowerCase();
618
+ return `${w.charAt(0).toUpperCase()}${w.slice(1)} (${trigger})`;
619
+ }
620
+ return trigger;
621
+ }
622
+ function triggerOf(f) {
623
+ switch (f.kind) {
624
+ case 'route': return [f.method, f.path ?? `in ${f.symbol ?? INLINE}`].filter(Boolean).join(' ');
625
+ case 'cli': return `command ${f.path ?? f.symbol ?? INLINE}`;
626
+ case 'cron': return f.method === 'SCHEDULED' ? 'Worker scheduled' : `schedule ${f.path ?? f.symbol ?? INLINE}`;
627
+ case 'queue': return f.method === 'QUEUE' ? 'Worker queue' : `consume ${f.path ?? f.symbol ?? INLINE}`;
628
+ case 'handler': return f.method === 'EVENT' ? `on ${f.path}` : f.method === 'ACTION' ? `action ${f.symbol ?? INLINE}` : `Worker ${(f.method ?? 'handler').toLowerCase()}`;
629
+ case 'public-api': return `${f.symbol}()`;
630
+ }
631
+ }
632
+ // ─── Domain rules ────────────────────────────────────────────────────
633
+ /**
634
+ * Layer mechanics, not domain: request plumbing, auth tokens and sessions,
635
+ * headers, content types and parsing, env and config, transport failures.
636
+ * A rule that also names one of the use case's domain words stays domain
637
+ * ("only admins can refund" on a refund route).
638
+ */
639
+ const MECHANIC = /\b(req|request|res|response|headers?|c\.req|ctx\.req|process\.env|env|config|token|jwt|bearer|session|cookie|csrf|cors|signature|api[-_ ]?key|content[-_ ]type|json|parse|body|unauthori[sz]ed|unauthenticated|not authenticated|authentication|auth|rate[-_ ]?limit|timeout|member(ship)?|organi[sz]ation|tenant|db|database|method not allowed|not implemented|internal|typeof|instanceof|undefined|null)\b/i;
640
+ /** Always mechanics, whatever else the rule names: transport status, config and env. */
641
+ const STRONG_MECHANIC = /\b(res|response)\.(status|statusText|ok)\b|\bstatus(Text|Code)?\b|\bSSE\b|\bECONN\w*|\bnetwork\b|\bprocess\.env\b|\benv\.[A-Z_]+|\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b|\bConfig(uration)?Error\b|\bnot configured\b|\b(ctx|c)\.(req|env)\b|\b\w*[Ff]eature(Enabled|Flag|On)\w*\(/;
642
+ const GENERIC_ERROR = /^(Error|TypeError|RangeError|HttpException|HTTPException|TRPCError|RuntimeException|Exception|IllegalStateException)$/;
643
+ const STOP = new Set(['get', 'set', 'post', 'put', 'patch', 'delete', 'handle', 'handler', 'api', 'v1', 'v2', 'id', 'index', 'by', 'the', 'a', 'an', 'to', 'for', 'of', 'on', 'in', 'all', 'one', 'find', 'list', 'route', 'controller', 'service', 'query', 'mutation', 'command', 'worker']);
644
+ function domainWords(f, area) {
645
+ const src = [f.path ?? '', f.symbol ?? '', area].join(' ');
646
+ const out = new Set();
647
+ for (const w of words(src).toLowerCase().split(/[^a-z0-9]+/)) {
648
+ if (w.length < 3 || STOP.has(w))
649
+ continue;
650
+ out.add(w);
651
+ if (w.endsWith('s'))
652
+ out.add(w.slice(0, -1));
653
+ }
654
+ return out;
655
+ }
656
+ function namesDomain(text, vocab) {
657
+ return words(text).toLowerCase().split(/[^a-z0-9]+/).some(w => vocab.has(w) || (w.endsWith('s') && vocab.has(w.slice(0, -1))));
658
+ }
659
+ /** A throw fact's message: a string literal, or the `message:` of an object argument (tRPC). */
660
+ function messageOf(t) {
661
+ if (!t.message)
662
+ return undefined;
663
+ if (!t.message.trim().startsWith('{'))
664
+ return t.message;
665
+ return t.message.match(/\bmessage\s*:\s*(['"`])([^'"`]*)\1/)?.[2];
666
+ }
667
+ function isDomainRule(t, vocab) {
668
+ const msg = messageOf(t);
669
+ if (!t.condition && !msg && GENERIC_ERROR.test(t.errorType))
670
+ return false;
671
+ const text = [t.condition ?? '', msg ?? '', t.errorType].join(' ');
672
+ if (STRONG_MECHANIC.test(text))
673
+ return false;
674
+ if (MECHANIC.test(text) && !namesDomain([msg ?? '', t.condition ?? ''].join(' '), vocab))
675
+ return false;
676
+ return true;
677
+ }
678
+ /** The 0.1 rule for a throw fact (same text and derivation as `spec-generator`, so the ruleKey matches). */
679
+ function ruleFor(t) {
680
+ const msg = messageOf(t);
681
+ const who = t.symbol ?? 'The module';
682
+ const what = msg ? `${t.errorType}("${msg}")` : t.errorType;
683
+ const paths = [{ file: t.file, symbol: t.symbol, startLine: t.line, endLine: t.line, role: 'anchor' }];
684
+ if (t.condition && t.conditionLine !== undefined && t.conditionLine !== t.line) {
685
+ paths.push({ file: t.file, symbol: t.symbol, startLine: t.conditionLine, endLine: t.conditionLine, role: 'evidence' });
686
+ }
687
+ const req = t.condition
688
+ ? { id: '', description: `${who} shall reject with ${what} when ${t.condition}`, category: 'functional', priority: 'must', tested: false, provenance: staticProvenance('guard', 'corroborated', paths) }
689
+ : { id: '', description: `${who} may throw ${what}`, category: 'functional', priority: 'should', tested: false, provenance: staticProvenance('throw', 'corroborated', paths) };
690
+ req.ruleKey = computeRuleKey(req);
691
+ return req;
692
+ }
693
+ // ─── Server-action areas and library-surface rows ────────────────────
694
+ /** A server action's area: its app-router route, else its directory under the entry layer, else its file stem. */
695
+ function actionArea(file, moduleRoot) {
696
+ const route = appDirRoute(file, moduleRoot);
697
+ const key = (route && routeArea(route)) ?? directoryArea(file, moduleRoot)
698
+ ?? file.split('/').pop().replace(/\.[^.]+$/, '').replace(/^(index|actions?|server)$/, '');
699
+ return key ? areaName(key) : 'Actions';
700
+ }
701
+ /**
702
+ * One public-surface row: anchored on the entry (barrel) line, with every
703
+ * exported declaration as evidence and the domain rules inside them.
704
+ */
705
+ function surfaceUseCase(g, moduleName, throwsByFile, rulesByKey) {
706
+ const area = g.key ? areaName(g.key) : 'Root';
707
+ const id = `uc-${createHash('sha256').update([moduleName ?? '', 'public-api', 'surface', g.key].join('\u0000')).digest('hex').slice(0, 16)}`;
708
+ const names = keyNames(g);
709
+ const count = (k) => g.exports.filter(e => e.kind === k).length;
710
+ const surface = {
711
+ subpaths: [...g.subpaths], exports: g.exports.length,
712
+ functions: count('function'), classes: count('class'), types: count('type'), other: count('other'),
713
+ names, reexports: [...g.reexports],
714
+ };
715
+ const codePaths = [{ file: g.entryFile, ...(names[0] ? { symbol: names[0] } : {}), startLine: g.entryLine, endLine: g.entryLine, role: 'anchor' }];
716
+ for (const e of g.exports) {
717
+ if (!e.declared)
718
+ continue;
719
+ if (codePaths.some(p => p.file === e.file && p.startLine === e.start && p.symbol === e.name))
720
+ continue;
721
+ codePaths.push({ file: e.file, symbol: e.name, startLine: e.start, endLine: e.end, role: 'evidence' });
722
+ }
723
+ // Domain rules inside the exported functions and classes.
724
+ const vocab = new Set();
725
+ for (const w of words([g.key, ...g.exports.map(e => e.name)].join(' ')).toLowerCase().split(/[^a-z0-9]+/)) {
726
+ if (w.length < 3 || STOP.has(w))
727
+ continue;
728
+ vocab.add(w);
729
+ if (w.endsWith('s'))
730
+ vocab.add(w.slice(0, -1));
731
+ }
732
+ const refs = [];
733
+ for (const e of g.exports) {
734
+ if (!e.declared)
735
+ continue;
736
+ for (const t of throwsByFile.get(e.file) ?? []) {
737
+ if (t.line < e.start || t.line > e.end || !isDomainRule(t, vocab))
738
+ continue;
739
+ const rule = ruleFor(t);
740
+ const key = rule.ruleKey;
741
+ if (!rulesByKey.has(key))
742
+ rulesByKey.set(key, rule);
743
+ if (!refs.includes(key))
744
+ refs.push(key);
745
+ }
746
+ }
747
+ const head = names.length ? `${names.join(', ')}${g.exports.length > names.length ? ', …' : ''}` : g.reexports.join(', ');
748
+ return {
749
+ id, ...(moduleName ? { module: moduleName } : {}), area,
750
+ title: `${g.exports.length} export(s)${head ? `: ${head}` : ''}`,
751
+ entry: { kind: 'public-api', symbol: names[0] ?? g.key ?? '', file: g.entryFile, ...(g.subpaths.length ? { path: g.subpaths.join(' ') } : {}) },
752
+ codePaths, ruleRefs: refs, surface,
753
+ };
754
+ }
755
+ // ─── Main ────────────────────────────────────────────────────────────
756
+ function useCaseId(moduleName, f) {
757
+ const trigger = f.kind === 'public-api' ? `${f.file}#${f.symbol}` : `${f.method ?? ''} ${f.path ?? ''}#${f.path ? '' : `${f.file}#${f.symbol ?? f.span.start}`}`;
758
+ const h = createHash('sha256').update([moduleName ?? '', f.kind, trigger].join('\u0000')).digest('hex');
759
+ return `uc-${h.slice(0, 16)}`;
760
+ }
761
+ export function extractUseCases(files, opts = {}) {
762
+ const moduleRoot = opts.module?.root && opts.module.root !== '.' ? opts.module.root.replace(/\/+$/, '') : '';
763
+ const src = files
764
+ .filter(f => !TEST_FILE.test(f.file) && !CONFIG_FILE.test(f.file) && (!moduleRoot || f.file.startsWith(moduleRoot + '/')))
765
+ .sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));
766
+ const workerSet = new Set(opts.workerEntries ?? []);
767
+ const mounts = mountPrefixes(src);
768
+ const fnsByFile = new Map();
769
+ const throwsByFile = new Map();
770
+ let found = [];
771
+ const signals = fileRouteSignals(src);
772
+ for (const sf of src) {
773
+ const fns = functions(sf.ir);
774
+ fnsByFile.set(sf.file, fns);
775
+ throwsByFile.set(sf.file, extractTsRuleFacts(sf.file, sf.code, sf.ir).throws);
776
+ const here = [...routeEntries(sf, fns), ...callEntries(sf, fns), ...trpcEntries(sf, fns), ...workerEntries(sf, workerSet.has(sf.file)), ...annotationEntries(sf)];
777
+ if (isTsOrJs(sf.ir.meta.language)) {
778
+ // File-system routes and route config: area = first route segment.
779
+ for (const r of [...fileRouteEntries(sf, fns, moduleRoot, signals), ...routerConfigEntries(sf)]) {
780
+ here.push({ ...r, area: routeArea(r.path ?? '') ?? 'Home' });
781
+ }
782
+ for (const a of serverActionEntries(sf, fns))
783
+ here.push({ ...a, area: actionArea(a.file, moduleRoot) });
784
+ }
785
+ // A route in a file mounted under a prefix is served at prefix + path.
786
+ const prefixes = mounts.get(sf.file);
787
+ for (const f of here) {
788
+ if (f.kind === 'route' && f.mountable && f.path && prefixes?.length) {
789
+ for (const p of prefixes)
790
+ found.push({ ...f, path: joinRoute(p, f.path) });
791
+ }
792
+ else
793
+ found.push(f);
794
+ }
795
+ }
796
+ const mode = opts.publicApi ?? 'auto';
797
+ const surface = mode === 'always' || (mode === 'auto' && found.length === 0)
798
+ ? librarySurface(src.filter(sf => isTsOrJs(sf.ir.meta.language)), { moduleRoot, manifest: opts.manifest })
799
+ : [];
800
+ // Same route registered by two sources (runtime registration and decorator): keep one.
801
+ found = found.filter((f, i) => found.findIndex(g => g.kind === f.kind && g.file === f.file && g.method === f.method && g.path === f.path && g.span.start === f.span.start) === i);
802
+ const byId = new Map();
803
+ const rulesByKey = new Map();
804
+ for (const f of found) {
805
+ const area = areaOf(f, moduleRoot);
806
+ const id = useCaseId(opts.module?.name, f);
807
+ const anchor = { file: f.file, symbol: f.symbol, startLine: f.span.start, endLine: f.span.end, role: 'anchor' };
808
+ const paths = [anchor];
809
+ if (f.site !== undefined && (f.site < f.span.start || f.site > f.span.end)) {
810
+ paths.push({ file: f.file, startLine: f.site, endLine: f.site, role: 'evidence' });
811
+ }
812
+ // The handler and the same-file functions it calls (one hop).
813
+ const fns = fnsByFile.get(f.file) ?? [];
814
+ const spans = [f.span];
815
+ const ir = src.find(s => s.file === f.file).ir;
816
+ for (const c of ir.calls ?? []) {
817
+ const line = c.location?.line ?? 0;
818
+ if (c.receiver != null || line < f.span.start || line > f.span.end)
819
+ continue;
820
+ const callee = fns.find(fn => fn.name === c.method_name && !(fn.start <= line && line <= fn.end));
821
+ if (callee && !spans.some(s => s.start === callee.start)) {
822
+ spans.push({ start: callee.start, end: callee.end });
823
+ paths.push({ file: f.file, symbol: callee.symbol, startLine: callee.start, endLine: callee.end, role: 'evidence' });
824
+ }
825
+ }
826
+ const vocab = domainWords(f, area);
827
+ const refs = [];
828
+ for (const t of throwsByFile.get(f.file) ?? []) {
829
+ if (!spans.some(s => s.start <= t.line && t.line <= s.end) || !isDomainRule(t, vocab))
830
+ continue;
831
+ const rule = ruleFor(t);
832
+ const key = rule.ruleKey;
833
+ if (!rulesByKey.has(key))
834
+ rulesByKey.set(key, rule);
835
+ if (!refs.includes(key))
836
+ refs.push(key);
837
+ }
838
+ const existing = byId.get(id);
839
+ if (existing) {
840
+ for (const p of paths)
841
+ if (!existing.codePaths.some(q => q.file === p.file && q.startLine === p.startLine && q.symbol === p.symbol))
842
+ existing.codePaths.push(p);
843
+ for (const r of refs)
844
+ if (!existing.ruleRefs.includes(r))
845
+ existing.ruleRefs.push(r);
846
+ continue;
847
+ }
848
+ const entry = {
849
+ kind: f.kind, symbol: f.symbol ?? INLINE, file: f.file,
850
+ ...(f.method ? { method: f.method } : {}),
851
+ ...(f.path ? { path: f.path } : {}),
852
+ };
853
+ byId.set(id, {
854
+ id, ...(opts.module ? { module: opts.module.name } : {}),
855
+ area, title: titleOf(f), entry, codePaths: paths, ruleRefs: refs,
856
+ });
857
+ }
858
+ for (const g of surface) {
859
+ const u = surfaceUseCase(g, opts.module?.name, throwsByFile, rulesByKey);
860
+ if (!byId.has(u.id))
861
+ byId.set(u.id, u);
862
+ }
863
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
864
+ const sortKey = (u) => `${u.entry.kind}\u0000${u.entry.path ?? ''}\u0000${u.entry.method ?? ''}\u0000${u.entry.file}\u0000${u.entry.symbol}`;
865
+ const useCases = [...byId.values()].sort((a, b) => cmp(a.area, b.area) || cmp(sortKey(a), sortKey(b)));
866
+ const rules = [];
867
+ for (const u of useCases) {
868
+ for (const k of u.ruleRefs) {
869
+ const r = rulesByKey.get(k);
870
+ if (r && !rules.includes(r))
871
+ rules.push(r);
872
+ }
873
+ }
874
+ rules.forEach((r, i) => { r.id = `REQ-${String(i + 1).padStart(3, '0')}`; });
875
+ const areas = [];
876
+ for (const u of useCases) {
877
+ const a = areas.find(x => x.area === u.area);
878
+ if (a)
879
+ a.useCaseIds.push(u.id);
880
+ else
881
+ areas.push({ area: u.area, useCaseIds: [u.id] });
882
+ }
883
+ const counts = { route: 0, cli: 0, handler: 0, queue: 0, cron: 0, 'public-api': 0 };
884
+ for (const u of useCases)
885
+ counts[u.entry.kind]++;
886
+ return { useCases, rules, areas, counts };
887
+ }
888
+ //# sourceMappingURL=use-cases.js.map