@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,161 @@
1
+ import type { DefinitionGraph } from "./model";
2
+
3
+ export interface ErrorObservation {
4
+ eventId: string;
5
+ project: string;
6
+ issueId?: string;
7
+ title: string;
8
+ issueUrl?: string;
9
+ commit?: string;
10
+ matchReason?: string;
11
+ at?: string;
12
+ elementId?: string;
13
+ basis: "source" | "component" | "unassigned";
14
+ }
15
+ export interface ErrorHeat {
16
+ counts?: ErrorCount[];
17
+ accounting?: {
18
+ total: number;
19
+ source: number;
20
+ related: number;
21
+ projects: { project: string; total: number | null }[];
22
+ samplePartial: boolean;
23
+ classificationPartial: boolean;
24
+ };
25
+ warnings?: import("./sentry").SentryProjectWarning[];
26
+ fetchedAt: string;
27
+ period: string;
28
+ window?: import("./time-window").TimeWindow;
29
+ partial: boolean;
30
+ events: ErrorObservation[];
31
+ cells: Record<string, { source: number; related: number; intensity: number }>;
32
+ unassigned: number;
33
+ }
34
+ /** Aggregate occurrences are not synthetic event IDs or extrapolated event samples. */
35
+ export interface ErrorCount {
36
+ project: string;
37
+ count: number;
38
+ elementId?: string;
39
+ basis: "source" | "component" | "unassigned";
40
+ reason?: string;
41
+ }
42
+ /** Each event contributes once to its owner and once to each ancestor, never to siblings. */
43
+ export function errorHeat(
44
+ graph: DefinitionGraph,
45
+ observations: ErrorObservation[],
46
+ partial = false,
47
+ counts?: ErrorCount[],
48
+ ): ErrorHeat {
49
+ const byId = new Map(graph.elements.map((node) => [node.id, node]));
50
+ const seen = new Set<string>(),
51
+ events: ErrorObservation[] = [],
52
+ cells: ErrorHeat["cells"] = {};
53
+ for (const event of observations) {
54
+ const key = `${event.project}:${event.eventId}`;
55
+ if (seen.has(key)) continue;
56
+ seen.add(key);
57
+ const owner =
58
+ event.elementId &&
59
+ byId.get(graph.aliases?.[event.elementId] || event.elementId);
60
+ const record = owner
61
+ ? { ...event, elementId: owner.id }
62
+ : { ...event, elementId: undefined, basis: "unassigned" as const };
63
+ events.push(record);
64
+ }
65
+ let unassigned = 0,
66
+ source = 0,
67
+ related = 0;
68
+ for (const row of counts || events.map((event) => ({ ...event, count: 1 }))) {
69
+ if (!Number.isSafeInteger(row.count) || row.count < 0)
70
+ throw Error("Invalid Sentry occurrence count");
71
+ const owner =
72
+ row.elementId &&
73
+ byId.get(graph.aliases?.[row.elementId] || row.elementId);
74
+ if (!owner || row.basis === "unassigned") {
75
+ unassigned += row.count;
76
+ continue;
77
+ }
78
+ if (row.basis === "source") source += row.count;
79
+ else related += row.count;
80
+ let current: DefinitionGraph["elements"][number] | undefined = owner;
81
+ const ancestors = new Set<string>();
82
+ while (current && !ancestors.has(current.id)) {
83
+ ancestors.add(current.id);
84
+ const cell = (cells[current.id] ||= {
85
+ source: 0,
86
+ related: 0,
87
+ intensity: 0,
88
+ });
89
+ if (row.basis === "source") cell.source += row.count;
90
+ else if (row.basis === "component") cell.related += row.count;
91
+ current = current.parent ? byId.get(current.parent) : undefined;
92
+ }
93
+ }
94
+ const maximum = Math.max(
95
+ 1,
96
+ ...Object.entries(cells)
97
+ .filter(([id]) => id !== graph.id)
98
+ .map(([, cell]) => cell.source + cell.related),
99
+ );
100
+ for (const cell of Object.values(cells))
101
+ cell.intensity = Math.min(1, (cell.source + cell.related) / maximum);
102
+ return {
103
+ fetchedAt: new Date().toISOString(),
104
+ period: "14d",
105
+ partial,
106
+ events,
107
+ cells,
108
+ unassigned,
109
+ ...(counts
110
+ ? {
111
+ counts,
112
+ accounting: {
113
+ total: source + related + unassigned,
114
+ source,
115
+ related,
116
+ projects: [],
117
+ samplePartial: false,
118
+ classificationPartial: false,
119
+ },
120
+ }
121
+ : {}),
122
+ };
123
+ }
124
+
125
+ /** Group only provider issue identities; unrelated ungrouped events remain separate. */
126
+ export function groupErrors(events: ErrorObservation[]) {
127
+ const groups = new Map<
128
+ string,
129
+ {
130
+ key: string;
131
+ title: string;
132
+ project: string;
133
+ issueId?: string;
134
+ issueUrl?: string;
135
+ events: ErrorObservation[];
136
+ }
137
+ >();
138
+ for (const event of events) {
139
+ const key = `${event.project}:${event.issueId || "event:" + event.eventId}`;
140
+ const group = groups.get(key) || {
141
+ key,
142
+ title: event.title,
143
+ project: event.project,
144
+ issueId: event.issueId,
145
+ issueUrl: event.issueUrl,
146
+ events: [],
147
+ };
148
+ group.events.push(event);
149
+ groups.set(key, group);
150
+ }
151
+ return [...groups.values()]
152
+ .map((group) => ({
153
+ ...group,
154
+ events: group.events.sort(
155
+ (a, b) => (Date.parse(b.at || "") || 0) - (Date.parse(a.at || "") || 0),
156
+ ),
157
+ }))
158
+ .sort(
159
+ (a, b) => b.events.length - a.events.length || a.key.localeCompare(b.key),
160
+ );
161
+ }
@@ -0,0 +1,94 @@
1
+ import type { DefinitionGraph, ExecutionEvidence } from "./model";
2
+
3
+ const record = (value: unknown): Record<string, unknown> =>
4
+ value !== null && typeof value === "object" && !Array.isArray(value)
5
+ ? (value as Record<string, unknown>)
6
+ : {};
7
+ /** Project a real materialized session document. Never infer a call path from a terminal status. */
8
+ export function inspectJob(
9
+ document: unknown,
10
+ jobId: string,
11
+ graph: DefinitionGraph,
12
+ ): ExecutionEvidence {
13
+ const doc = record(document),
14
+ jobs = record(record(doc.jobs).byId),
15
+ job = record(jobs[jobId]);
16
+ if (!Object.keys(job).length)
17
+ throw new Error(`Job not found in session document: ${jobId}`);
18
+ const metadata = record(job.metadata),
19
+ diagnostics = record(metadata.diagnostics),
20
+ intent = record(job.startIntent);
21
+ const failures = (
22
+ Array.isArray(diagnostics.failures) ? diagnostics.failures : []
23
+ ).map((value) => {
24
+ const f = record(value);
25
+ return {
26
+ code: String(f.code || "Unknown"),
27
+ origin: String(f.origin || "unknown"),
28
+ commit: String(f.commit || "unknown"),
29
+ };
30
+ });
31
+ const pending = record(metadata.pendingInvocations);
32
+ const unresolved = Object.entries(pending)
33
+ .filter(([, value]) => record(value).readOnly !== true)
34
+ .map(([id, value]) => ({
35
+ operationId: String(record(value).operationId || id),
36
+ commit: "unknown" as const,
37
+ reason:
38
+ "Outstanding mutation recorded in the session; its outcome is not established by job status.",
39
+ }));
40
+ const resolutions = new Set(
41
+ (Array.isArray(diagnostics.resolutions) ? diagnostics.resolutions : []).map(
42
+ (value) => record(value).operationId,
43
+ ),
44
+ );
45
+ for (const value of Array.isArray(diagnostics.failures)
46
+ ? diagnostics.failures
47
+ : []) {
48
+ const failure = record(value),
49
+ id = failure.operationId;
50
+ if (
51
+ failure.commit === "unknown" &&
52
+ typeof id === "string" &&
53
+ !resolutions.has(id) &&
54
+ !unresolved.some((item) => item.operationId === id)
55
+ )
56
+ unresolved.push({
57
+ operationId: id,
58
+ commit: "unknown",
59
+ reason: "Failure diagnostics record an unresolved commit outcome.",
60
+ });
61
+ }
62
+ const observations: ExecutionEvidence["observations"] = [];
63
+ const jobNode = graph.elements.find(
64
+ (n) => n.source?.symbol === "handleJobSubmitRpc",
65
+ );
66
+ if (jobNode)
67
+ observations.push({
68
+ elementId: jobNode.id,
69
+ label: `Persisted job record: ${String(job.status || "unknown")}. Submission call itself was not traced.`,
70
+ confidence: "recorded",
71
+ });
72
+ // Evidence records state, not fabricated traversal of all the nodes that could have run.
73
+ return {
74
+ schema: "fractal.evidence.v1",
75
+ jobId,
76
+ status: String(job.status || "unknown"),
77
+ runtime:
78
+ typeof metadata.jobRuntime === "string" ? metadata.jobRuntime : undefined,
79
+ startIntent:
80
+ typeof intent.state === "string"
81
+ ? {
82
+ state: intent.state,
83
+ attempt: typeof intent.attempt === "number" ? intent.attempt : 0,
84
+ }
85
+ : undefined,
86
+ unresolved,
87
+ failures,
88
+ observations,
89
+ definitionRevision:
90
+ typeof metadata.fractalDefinitionRevision === "string"
91
+ ? metadata.fractalDefinitionRevision
92
+ : undefined,
93
+ };
94
+ }
@@ -0,0 +1,378 @@
1
+ import { displayName } from "./display-name";
2
+ import type { FactoryModel, FactoryAttachments } from "./factory-model";
3
+ import type { DefinitionGraph, SourceRef } from "./model";
4
+ function digest(value: string) {
5
+ let hash = BigInt("14695981039346656037");
6
+ for (const byte of new TextEncoder().encode(value))
7
+ hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * BigInt("1099511628211"));
8
+ return hash.toString(16).padStart(16, "0");
9
+ }
10
+
11
+ /** Compatibility projection only. The v2 model retains interface/member semantics. */
12
+ export function factoryGraph(
13
+ model: FactoryModel,
14
+ base?: DefinitionGraph,
15
+ ): DefinitionGraph {
16
+ if (model.diagnostics.length)
17
+ throw new Error(
18
+ model.diagnostics
19
+ .map((d) => `${d.file}:${d.line}: ${d.message}`)
20
+ .join("\n"),
21
+ );
22
+ const graph: DefinitionGraph = base
23
+ ? structuredClone(base)
24
+ : {
25
+ schema: "fractal.definition.v1",
26
+ id: "factory",
27
+ revision: "",
28
+ generatedAt: "compiled",
29
+ scope: "Annotated factory",
30
+ elements: [
31
+ {
32
+ id: "factory",
33
+ label: "Factory",
34
+ kind: "block",
35
+ provenance: "declared",
36
+ },
37
+ ],
38
+ connections: [],
39
+ tests: [],
40
+ failures: [],
41
+ gaps: [],
42
+ };
43
+ // Reviewed inventories describe product areas, not executable control flow.
44
+ // Retire their handwritten process internals when source declarations take over.
45
+ const declaredIds = new Set(
46
+ [...model.blocks, ...model.interfaces, ...model.methods].map(
47
+ (item) => item.id,
48
+ ),
49
+ );
50
+ const processIds = new Set(model.processes.map((item) => item.blockId));
51
+ const oldById = new Map(graph.elements.map((item) => [item.id, item]));
52
+ // Incremental adoption: an ID names a logical area, never a source folder.
53
+ // Keep unowned declarations inside the nearest existing inventory block.
54
+ // An explicit typed parent always wins; no parallel parent/child registry.
55
+ const inventoryParent = (id: string) =>
56
+ [...oldById.values()]
57
+ .filter(
58
+ (node) =>
59
+ kept.has(node.id) &&
60
+ id.startsWith(`${node.id}/`) &&
61
+ ![
62
+ "resource",
63
+ "artifact",
64
+ "method",
65
+ "operation",
66
+ "interface",
67
+ ].includes(node.kind),
68
+ )
69
+ .sort((a, b) => b.id.length - a.id.length)[0]?.id;
70
+ const inProcess = (id: string) => {
71
+ const seen = new Set<string>();
72
+ while (id && !seen.has(id)) {
73
+ if (processIds.has(id)) return true;
74
+ seen.add(id);
75
+ id = oldById.get(id)?.parent || "";
76
+ }
77
+ return false;
78
+ };
79
+ // A reviewed leaf may describe the exact method now supplied by an annotation.
80
+ // Collapse only unambiguous matches inside the same logical owner; never infer
81
+ // ownership from a file alone or replace a capability group with its helper.
82
+ const ownedBy = (id: string, owner: string) => {
83
+ const seen = new Set<string>();
84
+ while (id && !seen.has(id)) {
85
+ if (id === owner) return true;
86
+ seen.add(id);
87
+ id = oldById.get(id)?.parent || "";
88
+ }
89
+ return false;
90
+ };
91
+ const adopted = new Map<string, string>();
92
+ for (const node of graph.elements) {
93
+ if (
94
+ node.kind !== "method" ||
95
+ node.provenance === "declared" ||
96
+ declaredIds.has(node.id) ||
97
+ graph.elements.some((child) => child.parent === node.id)
98
+ )
99
+ continue;
100
+ const candidates = model.methods.filter(
101
+ (method) =>
102
+ method.source.file === node.source?.file &&
103
+ ownedBy(node.parent || "", method.blockId) &&
104
+ (node.source?.symbol === method.name ||
105
+ new RegExp(
106
+ "\\b" +
107
+ method.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") +
108
+ "\\s*\\(",
109
+ ).test(node.source?.symbol || "")),
110
+ );
111
+ if (candidates.length === 1) {
112
+ const method = candidates[0],
113
+ process = model.processes.find((p) => p.entryMethodId === method.id);
114
+ adopted.set(node.id, process?.blockId || method.id);
115
+ }
116
+ }
117
+ graph.aliases = { ...graph.aliases, ...Object.fromEntries(adopted) };
118
+ graph.elements = graph.elements.filter(
119
+ (item) =>
120
+ (!inProcess(item.id) || declaredIds.has(item.id)) &&
121
+ !adopted.has(item.id),
122
+ );
123
+ graph.connections = graph.connections.map((edge) => ({
124
+ ...edge,
125
+ source: adopted.get(edge.source) || edge.source,
126
+ target: adopted.get(edge.target) || edge.target,
127
+ }));
128
+ graph.tests = graph.tests.map((test) => ({
129
+ ...test,
130
+ targets: [...new Set(test.targets.map((id) => adopted.get(id) || id))],
131
+ }));
132
+ const kept = new Set([
133
+ ...graph.elements.map((item) => item.id),
134
+ ...declaredIds,
135
+ ]);
136
+ graph.connections = graph.connections.filter(
137
+ (edge) =>
138
+ !edge.path &&
139
+ kept.has(edge.source) &&
140
+ kept.has(edge.target) &&
141
+ !(
142
+ edge.id.startsWith("flow:") &&
143
+ (inProcess(edge.source) || inProcess(edge.target))
144
+ ),
145
+ );
146
+ graph.tests = graph.tests
147
+ .map((test) => ({
148
+ ...test,
149
+ targets: test.targets.filter((id) => kept.has(id)),
150
+ }))
151
+ .filter((test) => test.targets.length);
152
+ const put = (element: DefinitionGraph["elements"][number]) => {
153
+ element.definitionRevision = model.revision;
154
+ const index = graph.elements.findIndex((node) => node.id === element.id);
155
+ if (index < 0) graph.elements.push(element);
156
+ else
157
+ graph.elements[index] = {
158
+ ...graph.elements[index],
159
+ ...element,
160
+ sources: [
161
+ ...(element.sources || (element.source ? [element.source] : [])),
162
+ ...(graph.elements[index].sources || []).filter(
163
+ (source) => source.scope === "file",
164
+ ),
165
+ ].filter(
166
+ (source, at, all) =>
167
+ all.findIndex(
168
+ (other) => JSON.stringify(other) === JSON.stringify(source),
169
+ ) === at,
170
+ ),
171
+ description: element.description ?? graph.elements[index].description,
172
+ parent: element.parent || graph.elements[index].parent,
173
+ };
174
+ };
175
+ const attach = (
176
+ id: string,
177
+ attachments: FactoryAttachments,
178
+ source: SourceRef,
179
+ ) => {
180
+ for (const file of attachments.tests) {
181
+ const testId = `attachment:${id}:${file}`;
182
+ if (!graph.tests.some((test) => test.id === testId))
183
+ graph.tests.push({
184
+ id: testId,
185
+ name: file,
186
+ source: { ...source, file, line: 1 },
187
+ targets: [id],
188
+ association: "attachment",
189
+ status: "not_run",
190
+ });
191
+ }
192
+ };
193
+ for (const block of model.blocks) {
194
+ const existing = graph.elements.find((node) => node.id === block.id);
195
+ const label =
196
+ block.label === block.id.split("/").at(-1)
197
+ ? existing?.label || block.label
198
+ : block.label;
199
+ const entry = model.methods.find((method) =>
200
+ model.processes.some(
201
+ (process) =>
202
+ process.blockId === block.id && process.entryMethodId === method.id,
203
+ ),
204
+ );
205
+ put({
206
+ id: block.id,
207
+ label,
208
+ parent:
209
+ block.parent ||
210
+ existing?.parent ||
211
+ inventoryParent(block.id) ||
212
+ (block.id !== graph.id ? graph.id : undefined),
213
+ kind: model.processes.some((process) => process.blockId === block.id)
214
+ ? "process"
215
+ : "block",
216
+ provenance: "declared",
217
+ source: block.source,
218
+ sources: [block.source],
219
+ description: block.attachments.description,
220
+ attachments: block.attachments,
221
+ ...(entry
222
+ ? {
223
+ signature: entry.signature,
224
+ contract: {
225
+ id: block.id,
226
+ input: {
227
+ language: "typescript",
228
+ args: entry.contract.args,
229
+ typeSources: entry.contract.typeSources,
230
+ runtimeValidation: entry.contract.runtimeValidation,
231
+ },
232
+ output: { language: "typescript", type: entry.contract.result },
233
+ },
234
+ }
235
+ : {}),
236
+ });
237
+ attach(block.id, block.attachments, block.source);
238
+ }
239
+ for (const api of model.interfaces) {
240
+ const previous = `${api.blockId}::${api.name}`;
241
+ if (api.id !== previous) {
242
+ graph.aliases = { ...graph.aliases, [previous]: api.id };
243
+ for (const method of model.methods.filter(
244
+ (method) => method.interfaceId === api.id,
245
+ ))
246
+ graph.aliases[`${previous}#${method.name}`] = method.id;
247
+ }
248
+ put({
249
+ id: api.id,
250
+ // A source inventory may supply the prefix owner during incremental
251
+ // adoption. With a smaller inventory, use its nearest known owner rather
252
+ // than emitting an orphan or manufacturing intermediate blocks.
253
+ parent: kept.has(api.blockId)
254
+ ? api.blockId
255
+ : inventoryParent(api.id) || graph.id,
256
+ kind: "interface",
257
+ label:
258
+ api.label ||
259
+ api.name
260
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
261
+ .replace(/^./, (letter) => letter.toUpperCase()),
262
+ provenance: "declared",
263
+ source: api.source,
264
+ sources: [api.source],
265
+ attachments: api.attachments,
266
+ description: api.attachments.description,
267
+ contract: {
268
+ id: api.id,
269
+ input: {
270
+ language: "typescript",
271
+ members: model.methods
272
+ .filter((method) => method.interfaceId === api.id)
273
+ .map((method) => ({ name: method.name, ...method.contract })),
274
+ },
275
+ },
276
+ });
277
+ attach(api.id, api.attachments, api.source);
278
+ }
279
+ for (const method of model.methods) {
280
+ // A process entry is the implementation of its process box, not an extra method box.
281
+ const processEntry = model.processes.some(
282
+ (process) => process.entryMethodId === method.id,
283
+ );
284
+ if (processEntry && !method.interfaceId) continue;
285
+ if (processEntry && method.interfaceId)
286
+ graph.connections.push({
287
+ id: `interface-entry:${method.id}`,
288
+ source: method.id,
289
+ target: method.blockId,
290
+ relation: "exposes",
291
+ label: method.name,
292
+ provenance: "declared",
293
+ sourceRef: method.source,
294
+ });
295
+ put({
296
+ id: method.id,
297
+ parent: method.interfaceId || method.blockId,
298
+ kind: "method",
299
+ label: method.label || displayName(method.name),
300
+ provenance: "declared",
301
+ source: method.source,
302
+ sources: [method.source],
303
+ signature: method.endpoint
304
+ ? `${method.endpoint.method} ${method.endpoint.path}`
305
+ : method.signature,
306
+ ...(processEntry ? { implementationBlock: method.blockId } : {}),
307
+ contract: {
308
+ id: method.id,
309
+ input: {
310
+ language: "typescript",
311
+ ...(method.endpoint ? { endpoint: method.endpoint } : {}),
312
+ args: method.contract.args,
313
+ typeSources: method.contract.typeSources,
314
+ runtimeValidation: method.contract.runtimeValidation,
315
+ },
316
+ output: { language: "typescript", type: method.contract.result },
317
+ },
318
+ attachments: method.attachments,
319
+ });
320
+ attach(method.id, method.attachments, method.source);
321
+ }
322
+ for (const dependency of model.dependencies) {
323
+ const id = `call-site:${dependency.source}->${dependency.target}:${dependency.at.file}:${dependency.at.line}:${dependency.relation || "calls"}:${dependency.label || ""}`;
324
+ if (!graph.connections.some((edge) => edge.id === id))
325
+ graph.connections.push({
326
+ id,
327
+ source: dependency.source,
328
+ target: dependency.target,
329
+ relation: dependency.relation || "calls",
330
+ label:
331
+ dependency.label ||
332
+ graph.elements.find((node) => node.id === dependency.target)?.label ||
333
+ dependency.target,
334
+ provenance: "source",
335
+ sourceRef: dependency.at,
336
+ ...(dependency.transport ? { transport: dependency.transport } : {}),
337
+ ...(dependency.via?.length
338
+ ? { sources: [...dependency.via, dependency.at] }
339
+ : {}),
340
+ ...(dependency.exchange ? { exchange: dependency.exchange } : {}),
341
+ ...(dependency.displayLabel
342
+ ? { displayLabel: dependency.displayLabel }
343
+ : {}),
344
+ });
345
+ }
346
+ // A bootstrap capability can be broader than the declared caller. Prefer the
347
+ // exact compiled owner for each identical call site, retaining uncovered sites.
348
+ const covered = new Set(
349
+ model.dependencies.map(
350
+ (edge) =>
351
+ `${edge.target}:${edge.at.file}:${edge.at.line}:${edge.relation || "calls"}`,
352
+ ),
353
+ );
354
+ graph.connections = graph.connections.flatMap((edge) => {
355
+ if (!edge.id.startsWith("source:")) return [edge];
356
+ const refs = edge.sources || (edge.sourceRef ? [edge.sourceRef] : []);
357
+ const remaining = refs.filter(
358
+ (ref) =>
359
+ !covered.has(`${edge.target}:${ref.file}:${ref.line}:${edge.relation}`),
360
+ );
361
+ if (remaining.length === refs.length) return [edge];
362
+ return remaining.length
363
+ ? [{ ...edge, sourceRef: remaining[0], sources: remaining }]
364
+ : [];
365
+ });
366
+ graph.gaps.push(...(model.interactionGaps || []));
367
+ // Call sites are explicitly source evidence; actual traversal comes only from traces.
368
+ graph.revision = digest(
369
+ JSON.stringify({
370
+ elements: graph.elements,
371
+ connections: graph.connections,
372
+ tests: graph.tests,
373
+ failures: graph.failures,
374
+ gaps: graph.gaps,
375
+ }),
376
+ ).slice(0, 16);
377
+ return graph;
378
+ }
@@ -0,0 +1,73 @@
1
+ import type { SourceRef } from "./model";
2
+
3
+ export interface FactoryAttachments {
4
+ benchmarks?: string[];
5
+ docs: string[];
6
+ tests: string[];
7
+ description?: string;
8
+ /** A policy is enforced by its runtime function, not by a descriptive label. */
9
+ auth?: { symbol: string; source: SourceRef };
10
+ }
11
+ export interface FactoryBlock {
12
+ inputLabel?: string;
13
+ eventLabel?: string;
14
+ id: string;
15
+ label: string;
16
+ parent?: string;
17
+ source: SourceRef;
18
+ attachments: FactoryAttachments;
19
+ }
20
+ export interface FactoryInterface {
21
+ id: string;
22
+ blockId: string;
23
+ name: string;
24
+ label?: string;
25
+ source: SourceRef;
26
+ attachments: FactoryAttachments;
27
+ methods: string[];
28
+ }
29
+ export interface FactoryMethod {
30
+ label?: string;
31
+ endpoint?: { method: string; path: string };
32
+ id: string;
33
+ blockId: string;
34
+ interfaceId?: string;
35
+ name: string;
36
+ source: SourceRef;
37
+ signature: string;
38
+ contract: {
39
+ args: { name: string; type: string; optional: boolean; rest: boolean }[];
40
+ result: string;
41
+ /** Fingerprinted type dependencies; these files are not owned executable code. */
42
+ typeSources?: SourceRef[];
43
+ /** Type information is not a claim that a runtime validator exists. */
44
+ runtimeValidation: boolean;
45
+ };
46
+ attachments: FactoryAttachments;
47
+ }
48
+ export interface FactoryProcess {
49
+ blockId: string;
50
+ entryMethodId: string;
51
+ }
52
+ export interface FactoryModel {
53
+ schema: "fractal.factory.v2";
54
+ revision: string;
55
+ blocks: FactoryBlock[];
56
+ interfaces: FactoryInterface[];
57
+ methods: FactoryMethod[];
58
+ processes: FactoryProcess[];
59
+ /** Source-backed interactions. Helpers retain their evidence without becoming boxes. */
60
+ dependencies: {
61
+ source: string;
62
+ target: string;
63
+ at: SourceRef;
64
+ relation?: "calls" | "renders" | "callbacks" | "delegates" | "exposes";
65
+ label?: string;
66
+ displayLabel?: string;
67
+ transport?: string;
68
+ via?: SourceRef[];
69
+ exchange?: { inputs: { name: string; type: string }[]; output?: string };
70
+ }[];
71
+ interactionGaps?: { source: SourceRef; expression: string; reason: string }[];
72
+ diagnostics: { file: string; line: number; message: string }[];
73
+ }