@granular-software/fractory 0.0.0-stage → 0.1.24

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 (273) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +28 -2
  3. package/dist/activity-volume.d.ts +18 -0
  4. package/dist/activity-volume.js +94 -0
  5. package/dist/annotations.d.ts +118 -0
  6. package/dist/annotations.js +304 -0
  7. package/dist/benchmark-cli.d.ts +1 -0
  8. package/dist/benchmark-cli.js +95 -0
  9. package/dist/benchmark-worker.d.ts +2 -0
  10. package/dist/benchmark-worker.js +22 -0
  11. package/dist/benchmarks.d.ts +19 -0
  12. package/dist/benchmarks.js +414 -0
  13. package/dist/bin.d.ts +2 -0
  14. package/dist/bin.js +63 -0
  15. package/dist/block-cli.d.ts +1 -0
  16. package/dist/block-cli.js +88 -0
  17. package/dist/block-documents.d.ts +35 -0
  18. package/dist/block-documents.js +84 -0
  19. package/dist/change-impact.d.ts +55 -0
  20. package/dist/change-impact.js +223 -0
  21. package/dist/check-source.d.ts +2 -0
  22. package/dist/check-source.js +66 -0
  23. package/dist/checks-model.d.ts +64 -0
  24. package/dist/checks-model.js +36 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +359 -0
  27. package/dist/code-model.d.ts +38 -0
  28. package/dist/code-model.js +94 -0
  29. package/dist/code-store.d.ts +9 -0
  30. package/dist/code-store.js +79 -0
  31. package/dist/compare-artifact.d.ts +6 -0
  32. package/dist/compare-artifact.js +277 -0
  33. package/dist/compare.d.ts +81 -0
  34. package/dist/compare.js +291 -0
  35. package/dist/compiler.d.ts +10 -0
  36. package/dist/compiler.js +1083 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +86 -0
  40. package/dist/core.js +206 -0
  41. package/dist/coverage-cli.d.ts +1 -0
  42. package/dist/coverage-cli.js +42 -0
  43. package/dist/declaration-sources.d.ts +3 -0
  44. package/dist/declaration-sources.js +51 -0
  45. package/dist/declared-graph.d.ts +3 -0
  46. package/dist/declared-graph.js +66 -0
  47. package/dist/display-name.d.ts +2 -0
  48. package/dist/display-name.js +8 -0
  49. package/dist/error-heat.d.ts +58 -0
  50. package/dist/error-heat.js +96 -0
  51. package/dist/evidence.d.ts +3 -0
  52. package/dist/evidence.js +68 -0
  53. package/dist/factory-graph.d.ts +4 -0
  54. package/dist/factory-graph.js +318 -0
  55. package/dist/factory-model.d.ts +97 -0
  56. package/dist/factory-model.js +1 -0
  57. package/dist/git-code.d.ts +47 -0
  58. package/dist/git-code.js +352 -0
  59. package/dist/git-refs.d.ts +4 -0
  60. package/dist/git-refs.js +37 -0
  61. package/dist/history-activity.d.ts +4 -0
  62. package/dist/history-activity.js +129 -0
  63. package/dist/history-churn.d.ts +36 -0
  64. package/dist/history-churn.js +302 -0
  65. package/dist/history-git.d.ts +21 -0
  66. package/dist/history-git.js +125 -0
  67. package/dist/history-ledger.d.ts +43 -0
  68. package/dist/history-ledger.js +450 -0
  69. package/dist/history-ownership.d.ts +10 -0
  70. package/dist/history-ownership.js +75 -0
  71. package/dist/history-source.d.ts +13 -0
  72. package/dist/history-source.js +100 -0
  73. package/dist/integrations-cli.d.ts +2 -0
  74. package/dist/integrations-cli.js +159 -0
  75. package/dist/issue-cache.d.ts +9 -0
  76. package/dist/issue-cache.js +68 -0
  77. package/dist/issue-cli.d.ts +1 -0
  78. package/dist/issue-cli.js +89 -0
  79. package/dist/issue-links.d.ts +15 -0
  80. package/dist/issue-links.js +125 -0
  81. package/dist/linear-issues.d.ts +19 -0
  82. package/dist/linear-issues.js +124 -0
  83. package/dist/local-runtime.d.ts +8 -0
  84. package/dist/local-runtime.js +59 -0
  85. package/dist/map-activity.d.ts +73 -0
  86. package/dist/map-activity.js +234 -0
  87. package/dist/map-model.d.ts +5 -0
  88. package/dist/map-model.js +166 -0
  89. package/dist/map-quality.d.ts +14 -0
  90. package/dist/map-quality.js +56 -0
  91. package/dist/mapping-coverage.d.ts +87 -0
  92. package/dist/mapping-coverage.js +404 -0
  93. package/dist/model.d.ts +182 -0
  94. package/dist/model.js +66 -0
  95. package/dist/operation-benchmark-worker.d.ts +2 -0
  96. package/dist/operation-benchmark-worker.js +60 -0
  97. package/dist/operation-benchmark.d.ts +29 -0
  98. package/dist/operation-benchmark.js +1 -0
  99. package/dist/otel-metrics.d.ts +21 -0
  100. package/dist/otel-metrics.js +146 -0
  101. package/dist/performance-model.d.ts +185 -0
  102. package/dist/performance-model.js +396 -0
  103. package/dist/product-map.d.ts +69 -0
  104. package/dist/product-map.js +168 -0
  105. package/dist/provider-access.cjs +207 -0
  106. package/dist/provider-access.d.cts +14 -0
  107. package/dist/reports-cli.d.ts +1 -0
  108. package/dist/reports-cli.js +111 -0
  109. package/dist/reports-model.d.ts +27 -0
  110. package/dist/reports-model.js +39 -0
  111. package/dist/reports.d.ts +23 -0
  112. package/dist/reports.js +223 -0
  113. package/dist/repository-map.d.ts +22 -0
  114. package/dist/repository-map.js +151 -0
  115. package/dist/resource-cache.d.ts +17 -0
  116. package/dist/resource-cache.js +65 -0
  117. package/dist/review-cli.d.ts +19 -0
  118. package/dist/review-cli.js +224 -0
  119. package/dist/review.d.ts +48 -0
  120. package/dist/review.js +289 -0
  121. package/dist/runtime-metrics.d.ts +26 -0
  122. package/dist/runtime-metrics.js +290 -0
  123. package/dist/scope.d.ts +12 -0
  124. package/dist/scope.js +94 -0
  125. package/dist/sentry-activity.d.ts +39 -0
  126. package/dist/sentry-activity.js +174 -0
  127. package/dist/sentry.d.ts +130 -0
  128. package/dist/sentry.js +369 -0
  129. package/dist/service-release.d.ts +16 -0
  130. package/dist/service-release.js +14 -0
  131. package/dist/setup-cli.d.ts +2 -0
  132. package/dist/setup-cli.js +52 -0
  133. package/dist/setup-kit.cjs +163 -0
  134. package/dist/setup-kit.d.cts +32 -0
  135. package/dist/source-index.d.ts +37 -0
  136. package/dist/source-index.js +166 -0
  137. package/dist/source-review-git.d.ts +7 -0
  138. package/dist/source-review-git.js +103 -0
  139. package/dist/source-review.d.ts +16 -0
  140. package/dist/source-review.js +493 -0
  141. package/dist/telemetry.d.ts +17 -0
  142. package/dist/telemetry.js +51 -0
  143. package/dist/time-window.d.ts +9 -0
  144. package/dist/time-window.js +35 -0
  145. package/dist/trace-evidence.d.ts +23 -0
  146. package/dist/trace-evidence.js +55 -0
  147. package/dist/trace-model.d.ts +26 -0
  148. package/dist/trace-model.js +1 -0
  149. package/dist/tracing.d.ts +44 -0
  150. package/dist/tracing.js +123 -0
  151. package/dist/work-check.d.ts +17 -0
  152. package/dist/work-check.js +110 -0
  153. package/dist/work-cli.d.ts +1 -0
  154. package/dist/work-cli.js +148 -0
  155. package/dist/work-context.d.ts +57 -0
  156. package/dist/work-context.js +568 -0
  157. package/dist/work-intents.d.ts +6 -0
  158. package/dist/work-intents.js +140 -0
  159. package/dist/work-items.d.ts +58 -0
  160. package/dist/work-items.js +86 -0
  161. package/dist/work-model.d.ts +110 -0
  162. package/dist/work-model.js +261 -0
  163. package/dist/work-review-git.d.ts +8 -0
  164. package/dist/work-review-git.js +111 -0
  165. package/dist/work-review.d.ts +26 -0
  166. package/dist/work-review.js +426 -0
  167. package/dist/work-switcher-model.d.ts +43 -0
  168. package/dist/work-switcher-model.js +79 -0
  169. package/dist/work-switcher.d.ts +6 -0
  170. package/dist/work-switcher.js +171 -0
  171. package/dist/working-cli.d.ts +1 -0
  172. package/dist/working-cli.js +33 -0
  173. package/dist/working-code.d.ts +74 -0
  174. package/dist/working-code.js +421 -0
  175. package/dist/workspace-notes.d.ts +71 -0
  176. package/dist/workspace-notes.js +177 -0
  177. package/dist/workspace-tests.d.ts +21 -0
  178. package/dist/workspace-tests.js +573 -0
  179. package/package.json +547 -4
  180. package/src/activity-volume.ts +149 -0
  181. package/src/annotations.ts +481 -0
  182. package/src/benchmark-cli.ts +118 -0
  183. package/src/benchmark-worker.ts +22 -0
  184. package/src/benchmarks.ts +493 -0
  185. package/src/bin.ts +54 -0
  186. package/src/block-cli.ts +106 -0
  187. package/src/block-documents.ts +117 -0
  188. package/src/change-impact.ts +280 -0
  189. package/src/check-source.ts +82 -0
  190. package/src/checks-model.ts +108 -0
  191. package/src/cli.ts +440 -0
  192. package/src/code-model.ts +159 -0
  193. package/src/code-store.ts +98 -0
  194. package/src/compare-artifact.ts +314 -0
  195. package/src/compare.ts +440 -0
  196. package/src/compiler.ts +1326 -0
  197. package/src/compose.ts +94 -0
  198. package/src/core.ts +357 -0
  199. package/src/coverage-cli.ts +52 -0
  200. package/src/declaration-sources.ts +69 -0
  201. package/src/declared-graph.ts +74 -0
  202. package/src/display-name.ts +8 -0
  203. package/src/error-heat.ts +161 -0
  204. package/src/evidence.ts +94 -0
  205. package/src/factory-graph.ts +378 -0
  206. package/src/factory-model.ts +73 -0
  207. package/src/git-code.ts +461 -0
  208. package/src/git-refs.ts +43 -0
  209. package/src/history-activity.ts +146 -0
  210. package/src/history-churn.ts +416 -0
  211. package/src/history-git.ts +163 -0
  212. package/src/history-ledger.ts +636 -0
  213. package/src/history-ownership.ts +116 -0
  214. package/src/history-source.ts +117 -0
  215. package/src/integrations-cli.ts +187 -0
  216. package/src/issue-cache.ts +96 -0
  217. package/src/issue-cli.ts +137 -0
  218. package/src/issue-links.ts +153 -0
  219. package/src/linear-issues.ts +154 -0
  220. package/src/local-runtime.ts +70 -0
  221. package/src/map-activity.ts +309 -0
  222. package/src/map-model.ts +213 -0
  223. package/src/map-quality.ts +61 -0
  224. package/src/mapping-coverage.ts +570 -0
  225. package/src/model.ts +221 -0
  226. package/src/operation-benchmark-worker.ts +60 -0
  227. package/src/operation-benchmark.ts +28 -0
  228. package/src/otel-metrics.ts +176 -0
  229. package/src/performance-model.ts +575 -0
  230. package/src/product-map.ts +236 -0
  231. package/src/provider-access.cjs +207 -0
  232. package/src/provider-access.d.cts +14 -0
  233. package/src/reports-cli.ts +125 -0
  234. package/src/reports-model.ts +73 -0
  235. package/src/reports.ts +276 -0
  236. package/src/repository-map.ts +189 -0
  237. package/src/resource-cache.ts +76 -0
  238. package/src/review-cli.ts +256 -0
  239. package/src/review.ts +376 -0
  240. package/src/runtime-metrics.ts +386 -0
  241. package/src/scope.ts +103 -0
  242. package/src/sentry-activity.ts +234 -0
  243. package/src/sentry.ts +545 -0
  244. package/src/service-release.ts +18 -0
  245. package/src/setup-cli.ts +58 -0
  246. package/src/setup-kit.cjs +163 -0
  247. package/src/setup-kit.d.cts +32 -0
  248. package/src/source-index.ts +205 -0
  249. package/src/source-review-git.ts +129 -0
  250. package/src/source-review.ts +637 -0
  251. package/src/telemetry.ts +68 -0
  252. package/src/time-window.ts +51 -0
  253. package/src/trace-evidence.ts +80 -0
  254. package/src/trace-model.ts +26 -0
  255. package/src/tracing.ts +165 -0
  256. package/src/work-check.ts +143 -0
  257. package/src/work-cli.ts +195 -0
  258. package/src/work-context.ts +713 -0
  259. package/src/work-intents.ts +196 -0
  260. package/src/work-items.ts +151 -0
  261. package/src/work-model.ts +400 -0
  262. package/src/work-review-git.ts +130 -0
  263. package/src/work-review.ts +573 -0
  264. package/src/work-switcher-model.ts +121 -0
  265. package/src/work-switcher.ts +191 -0
  266. package/src/working-cli.ts +38 -0
  267. package/src/working-code.ts +582 -0
  268. package/src/workspace-notes.ts +203 -0
  269. package/src/workspace-tests.ts +654 -0
  270. package/toolkit/GUIDE.md +305 -0
  271. package/toolkit/SKILL.md +131 -0
  272. package/toolkit/bin/fractory +2 -0
  273. package/toolkit/build.json +1 -0
@@ -0,0 +1,637 @@
1
+ import { displayName } from "./display-name";
2
+ /** Supplement a reviewed logical map with source-backed capabilities.
3
+ * This is a source association map, never a captured historical contract or runtime trace.
4
+ * The adapter supplies immutable blobs (Git) or current files; no application is executed.
5
+ */
6
+ import { createHash } from "node:crypto";
7
+ import { posix } from "node:path";
8
+ import ts from "typescript";
9
+ import type { DefinitionGraph, Element, SourceRef } from "./model";
10
+ export interface SourceArea {
11
+ id: string;
12
+ parent: string;
13
+ /** Retain a source namespace when its logical parts are regrouped. */
14
+ identityRoot?: string;
15
+ label: string;
16
+ description: string;
17
+ kind?: "block" | "interface";
18
+ /** False records module ownership only; annotated interactions remain authoritative. */
19
+ discoverMethods?: boolean;
20
+ matches: (file: string) => boolean;
21
+ /** Explicit import aliases supplied by the repository adapter; never guessed. */
22
+ aliases?: Record<string, string>;
23
+ }
24
+ const hash = (text: string) => createHash("sha256").update(text).digest("hex");
25
+ const isTest = (file: string) =>
26
+ /\.(?:test|spec|vitest)\.[cm]?[jt]sx?$/.test(file);
27
+ export function sourceReviewMap(
28
+ definition: DefinitionGraph,
29
+ files: Map<string, string>,
30
+ areas: SourceArea[],
31
+ revision?: string,
32
+ ): DefinitionGraph {
33
+ const graph = structuredClone(definition);
34
+ const areaIds = new Set(areas.map((area) => area.id));
35
+ const discoveredAreas = new Set(
36
+ areas
37
+ .filter((area) => area.discoverMethods !== false)
38
+ .map((area) => area.id),
39
+ );
40
+ // Rebuild this adapter's contribution, rather than accumulating stale leaves/edges
41
+ // when a generated inventory is supplemented again at another revision.
42
+ graph.elements = graph.elements.filter(
43
+ (n) =>
44
+ !(
45
+ n.provenance === "source" &&
46
+ (discoveredAreas.has(n.id) ||
47
+ (/\/[a-f0-9]{12}$/.test(n.id) &&
48
+ discoveredAreas.has(n.parent || "")) ||
49
+ (areaIds.has(n.id) &&
50
+ n.source?.scope === "file" &&
51
+ n.sources?.every((source) => source.scope === "file")))
52
+ ),
53
+ );
54
+ graph.elements = graph.elements.map((node) =>
55
+ !areaIds.has(node.id)
56
+ ? node
57
+ : {
58
+ ...node,
59
+ ...(node.source?.scope === "file" ? { source: undefined } : {}),
60
+ ...(node.sources
61
+ ? {
62
+ sources: node.sources.filter(
63
+ (source) => source.scope !== "file",
64
+ ),
65
+ }
66
+ : {}),
67
+ },
68
+ );
69
+ const retainedIds = new Set(graph.elements.map((n) => n.id));
70
+ graph.connections = graph.connections.filter(
71
+ (c) =>
72
+ !c.id.startsWith("source:") &&
73
+ retainedIds.has(c.source) &&
74
+ retainedIds.has(c.target),
75
+ );
76
+ graph.tests = graph.tests.filter((t) => !t.id.startsWith("source-test:"));
77
+ const owners = new Map<string, string>();
78
+ const refs = new Map<string, SourceRef>();
79
+ const parsed = new Map<string, ts.SourceFile>();
80
+ const byId = new Map(graph.elements.map((n) => [n.id, n]));
81
+ for (const node of graph.elements)
82
+ for (const source of node.sources || (node.source ? [node.source] : []))
83
+ if (files.has(source.file)) owners.set(source.file, node.id);
84
+ const active = new Set<string>();
85
+ const methods = new Map<string, string>();
86
+ for (const [file, text] of files) {
87
+ if (!/\.[cm]?[jt]sx?$/.test(file)) continue;
88
+ const area = areas.find((a) => a.matches(file));
89
+ const source: SourceRef = {
90
+ file,
91
+ line: 1,
92
+ digest: hash(text).slice(0, 16),
93
+ };
94
+ refs.set(file, source);
95
+ const ast = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
96
+ parsed.set(file, ast);
97
+ if (!area || isTest(file)) continue;
98
+ const owner = area.id;
99
+ active.add(owner);
100
+ owners.set(file, owner);
101
+ let node = byId.get(owner);
102
+ if (!node) {
103
+ node = {
104
+ id: area.id,
105
+ parent: area.parent,
106
+ label: area.label,
107
+ description: area.description,
108
+ kind: area.kind || "block",
109
+ provenance: "source",
110
+ sources: [],
111
+ };
112
+ graph.elements.push(node);
113
+ byId.set(node.id, node);
114
+ }
115
+ node.sources = [
116
+ ...(node.sources || []).filter(
117
+ (s) => s.file !== file || s.scope !== "file",
118
+ ),
119
+ { ...source, scope: "file" },
120
+ ];
121
+ node.source ||= { ...source, scope: "file" };
122
+ // Exported callable leaves are discovered, not maintained in another method list.
123
+ if (area.discoverMethods === false) continue;
124
+ for (const statement of ast.statements) {
125
+ if (
126
+ !ts.canHaveModifiers(statement) ||
127
+ !ts
128
+ .getModifiers(statement)
129
+ ?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
130
+ )
131
+ continue;
132
+ const exports: {
133
+ symbol: string;
134
+ declaration:
135
+ | ts.FunctionDeclaration
136
+ | ts.FunctionExpression
137
+ | ts.ArrowFunction;
138
+ options?: ts.Expression;
139
+ }[] = [];
140
+ if (
141
+ ts.isFunctionDeclaration(statement) &&
142
+ statement.name &&
143
+ statement.body
144
+ )
145
+ exports.push({ symbol: statement.name.text, declaration: statement });
146
+ if (ts.isVariableStatement(statement))
147
+ for (const variable of statement.declarationList.declarations) {
148
+ if (!ts.isIdentifier(variable.name) || !variable.initializer)
149
+ continue;
150
+ const value = variable.initializer;
151
+ if (ts.isArrowFunction(value) || ts.isFunctionExpression(value))
152
+ exports.push({ symbol: variable.name.text, declaration: value });
153
+ else if (
154
+ ts.isCallExpression(value) &&
155
+ ts.isCallExpression(value.expression) &&
156
+ ts.isIdentifier(value.expression.expression) &&
157
+ value.arguments[0] &&
158
+ (ts.isFunctionExpression(value.arguments[0]) ||
159
+ ts.isArrowFunction(value.arguments[0]))
160
+ ) {
161
+ const imported = ast.statements.some(
162
+ (item) =>
163
+ ts.isImportDeclaration(item) &&
164
+ ts.isStringLiteral(item.moduleSpecifier) &&
165
+ ["@granular-software/fractal/annotations", "@granular-software/fractory/annotations"].includes(item.moduleSpecifier.text) &&
166
+ item.importClause?.namedBindings &&
167
+ ts.isNamedImports(item.importClause.namedBindings) &&
168
+ item.importClause.namedBindings.elements.some(
169
+ (name) =>
170
+ name.name.text ===
171
+ (
172
+ value.expression as ts.CallExpression
173
+ ).expression.getText(ast) &&
174
+ ["Method", "Process", "Block"].includes(
175
+ name.propertyName?.text || name.name.text,
176
+ ),
177
+ ),
178
+ );
179
+ if (imported)
180
+ exports.push({
181
+ symbol: variable.name.text,
182
+ declaration: value.arguments[0],
183
+ options: value.expression.arguments[1],
184
+ });
185
+ }
186
+ }
187
+ for (const { symbol, declaration, options } of exports) {
188
+ const ref = {
189
+ ...source,
190
+ line:
191
+ ast.getLineAndCharacterOfPosition(declaration.getStart(ast)).line +
192
+ 1,
193
+ symbol: declaration.name?.getText(ast) || symbol,
194
+ };
195
+ const id = `${area.identityRoot || area.id}/${hash(file + ":" + symbol).slice(0, 12)}`;
196
+ methods.set(file + ":" + symbol, id);
197
+ if (
198
+ statement.modifiers?.some(
199
+ (modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword,
200
+ )
201
+ )
202
+ methods.set(file + ":default", id);
203
+ const configuredDescription =
204
+ options && ts.isObjectLiteralExpression(options)
205
+ ? options.properties.find(
206
+ (item) =>
207
+ ts.isPropertyAssignment(item) &&
208
+ item.name.getText(ast) === "description",
209
+ )
210
+ : undefined;
211
+ const descriptionText =
212
+ configuredDescription &&
213
+ ts.isPropertyAssignment(configuredDescription) &&
214
+ ts.isStringLiteral(configuredDescription.initializer)
215
+ ? configuredDescription.initializer.text
216
+ : undefined;
217
+ const documentation = ts
218
+ .getJSDocCommentsAndTags(statement)
219
+ .find((node) => node.kind === ts.SyntaxKind.JSDoc) as
220
+ | ts.JSDoc
221
+ | undefined;
222
+ const docs =
223
+ typeof documentation?.comment === "string"
224
+ ? documentation.comment.trim()
225
+ : documentation?.comment
226
+ ?.map((part) => part.text)
227
+ .join("")
228
+ .trim();
229
+ const method: Element = {
230
+ id,
231
+ parent: area.id,
232
+ label: displayName(symbol),
233
+ kind: "method",
234
+ provenance: "source",
235
+ source: ref,
236
+ signature: declaration
237
+ .getText(ast)
238
+ .slice(
239
+ 0,
240
+ declaration.body!.getStart(ast) - declaration.getStart(ast),
241
+ )
242
+ .trim(),
243
+ description: descriptionText || docs || undefined,
244
+ };
245
+ if (!byId.has(id)) {
246
+ graph.elements.push(method);
247
+ byId.set(id, method);
248
+ }
249
+ }
250
+ }
251
+ }
252
+ // Materialize only ancestors of capabilities whose files actually exist at this revision.
253
+ for (let pending = true; pending; ) {
254
+ pending = false;
255
+ for (const area of areas)
256
+ if (active.has(area.id) && !byId.has(area.parent)) {
257
+ const parent = areas.find((a) => a.id === area.parent);
258
+ if (!parent)
259
+ throw Error(`Source area has no logical parent: ${area.parent}`);
260
+ const node: Element = {
261
+ id: parent.id,
262
+ parent: parent.parent,
263
+ label: parent.label,
264
+ kind: parent.kind || "block",
265
+ description: parent.description,
266
+ provenance: "source",
267
+ };
268
+ graph.elements.push(node);
269
+ byId.set(node.id, node);
270
+ active.add(node.id);
271
+ pending = true;
272
+ }
273
+ }
274
+ const resolveImport = (file: string, spec: string) => {
275
+ const aliases = areas.find(area => area.matches(file))?.aliases || {};
276
+ const alias = Object.keys(aliases).sort((a,b)=>b.length-a.length).find(prefix => spec.startsWith(prefix));
277
+ const base = spec.startsWith(".")
278
+ ? posix.normalize(posix.join(posix.dirname(file), spec))
279
+ : alias ? posix.normalize(aliases[alias] + spec.slice(alias.length)) : undefined;
280
+ if (!base) return;
281
+ return [
282
+ base,
283
+ base.replace(/\.js$/, ".ts"),
284
+ base + ".ts",
285
+ base + ".tsx",
286
+ base + "/index.ts",
287
+ base + "/index.tsx",
288
+ ].find((f) => files.has(f));
289
+ };
290
+ // Bind lexical symbols without loading dependencies or executing code. A local
291
+ // parameter named like an import must not become a fabricated cross-block call.
292
+ const host = ts.createCompilerHost({ noLib: true, noResolve: true });
293
+ const clean = (path: string) => path.replace(/^\//, "");
294
+ host.getCurrentDirectory = () => "/";
295
+ host.getSourceFile = (file) => parsed.get(clean(file));
296
+ host.fileExists = (file) => parsed.has(clean(file));
297
+ host.readFile = (file) => files.get(clean(file));
298
+ const checker = ts
299
+ .createProgram([...parsed.keys()], { noLib: true, noResolve: true }, host)
300
+ .getTypeChecker();
301
+ const connections = new Map<string, DefinitionGraph["connections"][number]>();
302
+ const enclosingOwner = (node: ts.Node, file: string, fallback: string) => {
303
+ let current: ts.Node | undefined = node.parent;
304
+ while (current) {
305
+ if (ts.isFunctionDeclaration(current) && current.name) {
306
+ const owner = methods.get(file + ":" + current.name.text);
307
+ if (owner) return owner;
308
+ }
309
+ current = current.parent;
310
+ }
311
+ return fallback;
312
+ };
313
+ const link = (
314
+ file: string,
315
+ node: ts.Node,
316
+ from: string,
317
+ to: string,
318
+ relation: DefinitionGraph["connections"][number]["relation"],
319
+ label: string,
320
+ transport: string,
321
+ ) => {
322
+ if (from === to) return;
323
+ const ref = {
324
+ ...refs.get(file)!,
325
+ line:
326
+ node.getSourceFile().getLineAndCharacterOfPosition(node.getStart())
327
+ .line + 1,
328
+ symbol: node.getText().split("\n")[0],
329
+ };
330
+ const id = `source:${from}:${to}:${relation}`;
331
+ const existing = connections.get(id);
332
+ if (existing) existing.sources!.push(ref);
333
+ else
334
+ connections.set(id, {
335
+ id,
336
+ source: from,
337
+ target: to,
338
+ relation,
339
+ label: displayName(label),
340
+ transport,
341
+ provenance: "source",
342
+ sourceRef: ref,
343
+ sources: [ref],
344
+ });
345
+ };
346
+ const nextRoutes = new Map<string, string>();
347
+ const nextRoots = new Set<string>();
348
+ for (const [file, ast] of parsed) {
349
+ const match = file.match(
350
+ /^(.*?)(?:src\/)?app(\/api\/.*)\/route\.[cm]?[jt]s$/,
351
+ );
352
+ if (!match) continue;
353
+ for (const method of [
354
+ "GET",
355
+ "POST",
356
+ "PUT",
357
+ "PATCH",
358
+ "DELETE",
359
+ "HEAD",
360
+ "OPTIONS",
361
+ ]) {
362
+ const target = methods.get(file + ":" + method);
363
+ if (target) {
364
+ nextRoots.add(match[1]);
365
+ nextRoutes.set(match[1] + " " + method + " " + match[2], target);
366
+ }
367
+ }
368
+ }
369
+ for (const [file, ast] of parsed) {
370
+ const sourceOwner = owners.get(file);
371
+ const discoverInteractions =
372
+ areas.find((area) => area.matches(file))?.discoverMethods !== false;
373
+ const testTargets = new Set<string>();
374
+ if (
375
+ sourceOwner &&
376
+ active.has(sourceOwner) &&
377
+ discoverInteractions &&
378
+ !isTest(file)
379
+ ) {
380
+ // Same-file exported calls and JSX were previously invisible. Resolve the
381
+ // actual lexical declaration; matching a name alone would invent links.
382
+ const visitLocal = (node: ts.Node) => {
383
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
384
+ const target = checker.getSymbolAtLocation(
385
+ node.expression,
386
+ )?.valueDeclaration;
387
+ if (
388
+ target &&
389
+ ts.isFunctionDeclaration(target) &&
390
+ target.getSourceFile() === ast &&
391
+ target.name
392
+ ) {
393
+ const id = methods.get(file + ":" + target.name.text);
394
+ if (id)
395
+ link(
396
+ file,
397
+ node,
398
+ enclosingOwner(node, file, sourceOwner),
399
+ id,
400
+ "calls",
401
+ node.expression.text,
402
+ "JavaScript call",
403
+ );
404
+ }
405
+ // Same-origin Next routes: require a literal path and a known HTTP
406
+ // method, and reject shadowed fetches or spread/unknown options.
407
+ if (
408
+ node.expression.text === "fetch" &&
409
+ !checker.getSymbolAtLocation(node.expression)?.declarations
410
+ ?.length &&
411
+ node.arguments[0] &&
412
+ ts.isStringLiteral(node.arguments[0])
413
+ ) {
414
+ const init = node.arguments[1];
415
+ let method: string | undefined = !init ? "GET" : undefined;
416
+ if (
417
+ init &&
418
+ ts.isObjectLiteralExpression(init) &&
419
+ !init.properties.some(ts.isSpreadAssignment)
420
+ ) {
421
+ const field = init.properties.find(
422
+ (p) => p.name?.getText().replace(/['"]/g, "") === "method",
423
+ );
424
+ method = !field
425
+ ? "GET"
426
+ : ts.isPropertyAssignment(field) &&
427
+ ts.isStringLiteral(field.initializer)
428
+ ? field.initializer.text.toUpperCase()
429
+ : undefined;
430
+ }
431
+ const route =
432
+ method &&
433
+ nextRoutes.get(
434
+ [...nextRoots]
435
+ .sort((a, b) => b.length - a.length)
436
+ .find(
437
+ (root) =>
438
+ file.startsWith(root + "src/") ||
439
+ file.startsWith(root + "app/"),
440
+ ) +
441
+ " " +
442
+ method +
443
+ " " +
444
+ node.arguments[0].text.split("?")[0],
445
+ );
446
+ if (route)
447
+ link(
448
+ file,
449
+ node,
450
+ enclosingOwner(node, file, sourceOwner),
451
+ route,
452
+ "calls",
453
+ method + " " + node.arguments[0].text.split("?")[0],
454
+ "HTTP",
455
+ );
456
+ }
457
+ }
458
+ ts.forEachChild(node, visitLocal);
459
+ };
460
+ visitLocal(ast);
461
+ }
462
+ for (const statement of ast.statements) {
463
+ if (
464
+ !ts.isImportDeclaration(statement) ||
465
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
466
+ statement.importClause?.isTypeOnly
467
+ )
468
+ continue;
469
+ const targetFile = resolveImport(file, statement.moduleSpecifier.text);
470
+ const target = targetFile && owners.get(targetFile);
471
+ if (!target) continue;
472
+ if (isTest(file)) {
473
+ testTargets.add(target);
474
+ continue;
475
+ }
476
+ if (!sourceOwner || !active.has(sourceOwner) || !discoverInteractions)
477
+ continue;
478
+ const ref = {
479
+ ...refs.get(file)!,
480
+ line:
481
+ ast.getLineAndCharacterOfPosition(statement.getStart(ast)).line + 1,
482
+ };
483
+ const imports = statement.importClause?.namedBindings;
484
+ const names =
485
+ imports && ts.isNamedImports(imports)
486
+ ? imports.elements
487
+ .filter((e) => !e.isTypeOnly)
488
+ .map((e) => e.name.text)
489
+ : [];
490
+ if (imports && ts.isNamedImports(imports) && !names.length) continue;
491
+ const called = new Set<string>();
492
+ const visit = (node: ts.Node) => {
493
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
494
+ const name = ts.isIdentifier(node.tagName) ? node.tagName : undefined;
495
+ const named =
496
+ name && imports && ts.isNamedImports(imports)
497
+ ? imports.elements.find(
498
+ (e) =>
499
+ !e.isTypeOnly &&
500
+ checker.getSymbolAtLocation(e.name) ===
501
+ checker.getSymbolAtLocation(name),
502
+ )
503
+ : undefined;
504
+ const defaultName = statement.importClause?.name;
505
+ const isDefault = !!(
506
+ name &&
507
+ defaultName &&
508
+ checker.getSymbolAtLocation(defaultName) ===
509
+ checker.getSymbolAtLocation(name)
510
+ );
511
+ if (named || isDefault) {
512
+ const targetMethod = methods.get(
513
+ targetFile +
514
+ ":" +
515
+ (isDefault
516
+ ? "default"
517
+ : named!.propertyName?.text || named!.name.text),
518
+ );
519
+ link(
520
+ file,
521
+ node,
522
+ enclosingOwner(node, file, sourceOwner),
523
+ targetMethod || target,
524
+ "renders",
525
+ name!.text,
526
+ "React props",
527
+ );
528
+ called.add(name!.text);
529
+ }
530
+ }
531
+ if (
532
+ ts.isCallExpression(node) &&
533
+ ts.isIdentifier(node.expression) &&
534
+ names.includes(node.expression.text) &&
535
+ imports &&
536
+ ts.isNamedImports(imports) &&
537
+ imports.elements.some(
538
+ (e) =>
539
+ e.name.text === (node.expression as ts.Identifier).text &&
540
+ checker.getSymbolAtLocation(e.name) ===
541
+ checker.getSymbolAtLocation(node.expression),
542
+ )
543
+ ) {
544
+ called.add(node.expression.text);
545
+ const imported =
546
+ imports && ts.isNamedImports(imports)
547
+ ? imports.elements.find(
548
+ (e) =>
549
+ e.name.text === (node.expression as ts.Identifier).text,
550
+ )
551
+ : undefined;
552
+ const targetMethod = methods.get(
553
+ targetFile +
554
+ ":" +
555
+ (imported?.propertyName?.text || node.expression.text),
556
+ );
557
+ let enclosing: ts.Node | undefined = node.parent;
558
+ while (enclosing && !ts.isFunctionDeclaration(enclosing))
559
+ enclosing = enclosing.parent;
560
+ const sourceMethod =
561
+ enclosing && ts.isFunctionDeclaration(enclosing) && enclosing.name
562
+ ? methods.get(file + ":" + enclosing.name.text)
563
+ : undefined;
564
+ const from = sourceMethod || sourceOwner,
565
+ to = targetMethod || target;
566
+ if (from !== to) {
567
+ const id = `source:${from}:${to}:calls`;
568
+ const callRef = {
569
+ ...refs.get(file)!,
570
+ line:
571
+ ast.getLineAndCharacterOfPosition(node.expression.getStart(ast))
572
+ .line + 1,
573
+ symbol: node.expression.text,
574
+ };
575
+ const previous = connections.get(id);
576
+ if (previous) previous.sources!.push(callRef);
577
+ else
578
+ connections.set(id, {
579
+ id,
580
+ source: from,
581
+ target: to,
582
+ relation: "calls",
583
+ label: displayName(node.expression.text),
584
+ provenance: "source",
585
+ sourceRef: callRef,
586
+ sources: [callRef],
587
+ transport: "JavaScript call",
588
+ });
589
+ }
590
+ }
591
+ ts.forEachChild(node, visit);
592
+ };
593
+ visit(ast);
594
+ // Exact callable edges already project to their logical parents on the map.
595
+ if (called.size || sourceOwner === target) continue;
596
+ const relation = called.size ? "calls" : "requires";
597
+ const id = `source:${sourceOwner}:${target}:${relation}`;
598
+ const previous = connections.get(id);
599
+ if (previous) previous.sources!.push(ref);
600
+ else
601
+ connections.set(id, {
602
+ id,
603
+ source: sourceOwner,
604
+ target,
605
+ relation,
606
+ label: called.size
607
+ ? [...called].map(displayName).slice(0, 3).join(" · ")
608
+ : "Imports implementation",
609
+ provenance: "source",
610
+ sourceRef: ref,
611
+ sources: [ref],
612
+ transport: "JavaScript module",
613
+ });
614
+ }
615
+ if (testTargets.size && !graph.tests.some((t) => t.source.file === file))
616
+ graph.tests.push({
617
+ id: `source-test:${file}`,
618
+ name: posix.basename(file),
619
+ source: refs.get(file)!,
620
+ targets: [...testTargets],
621
+ association: "imports",
622
+ status: "not_run",
623
+ });
624
+ }
625
+ graph.connections.push(...connections.values());
626
+ graph.revision = hash(
627
+ JSON.stringify({
628
+ base: definition.revision,
629
+ revision,
630
+ elements: graph.elements,
631
+ connections: graph.connections,
632
+ tests: graph.tests,
633
+ }),
634
+ );
635
+ graph.codeRevision = revision;
636
+ return graph;
637
+ }
@@ -0,0 +1,68 @@
1
+ /** Node/Cloudflare nodejs_compat host adapter. The annotation SDK itself stays portable. */
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import {
4
+ installFactoryHost,
5
+ type FactoryFrame,
6
+ type FactoryEvent,
7
+ } from "./annotations";
8
+ import { commitFromRelease } from "./code-model";
9
+
10
+ interface MetricOptions {
11
+ attributes: Record<string, string>;
12
+ }
13
+ export function installFactoryTelemetry(options: {
14
+ service: string;
15
+ context?: () => unknown;
16
+ codeRevision?: () => string | undefined;
17
+ count(name: string, value: number, options: MetricOptions): void;
18
+ distribution(
19
+ name: string,
20
+ value: number,
21
+ options: MetricOptions & { unit: string },
22
+ ): void;
23
+ /** Detailed traces can be sampled independently of aggregate counters. */
24
+ trace?: (event: FactoryEvent) => void;
25
+ metrics?: (event: FactoryEvent) => void;
26
+ }) {
27
+ const scope = new AsyncLocalStorage<FactoryFrame>();
28
+ return installFactoryHost({
29
+ current: () => scope.getStore(),
30
+ run: (frame, execute) => scope.run(frame, execute),
31
+ context: options.context,
32
+ codeRevision: () => commitFromRelease(options.codeRevision?.()),
33
+ emit(event) {
34
+ try {
35
+ options.metrics?.(event);
36
+ } catch {
37
+ /* aggregate metrics never affect execution */
38
+ }
39
+ const attributes = {
40
+ service: options.service,
41
+ block: event.blockId,
42
+ interface: event.interfaceId || "",
43
+ method: event.method,
44
+ outcome: event.status,
45
+ };
46
+ try {
47
+ options.count(`fractal.boundary.${event.status}`, 1, { attributes });
48
+ } catch {
49
+ /* independent sink */
50
+ }
51
+ if (event.durationMs !== undefined) {
52
+ try {
53
+ options.distribution("fractal.boundary.duration", event.durationMs, {
54
+ attributes,
55
+ unit: "millisecond",
56
+ });
57
+ } catch {
58
+ /* independent sink */
59
+ }
60
+ }
61
+ try {
62
+ options.trace?.(event);
63
+ } catch {
64
+ /* observational */
65
+ }
66
+ },
67
+ });
68
+ }