@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,87 @@
1
+ import ts from "typescript";
2
+ import type { DefinitionGraph } from "./model.js";
3
+ export declare const COVERAGE_FILE = "fractory.coverage.json";
4
+ export interface CoverageItem {
5
+ id: string;
6
+ file: string;
7
+ start: number;
8
+ end: number;
9
+ lines: number;
10
+ label: string;
11
+ preview: string;
12
+ digest: string;
13
+ excluded: boolean;
14
+ exclusionReason?: string;
15
+ exclusionScope?: "file";
16
+ }
17
+ export interface MappingCoverage {
18
+ checkedAt: string;
19
+ revision: string | null;
20
+ total: number;
21
+ mapped: number;
22
+ mappedDeclarations: number;
23
+ mappedBlockSource: number;
24
+ missing: number;
25
+ excluded: number;
26
+ percent: number | null;
27
+ files: number;
28
+ items: CoverageItem[];
29
+ expiredExclusions: number;
30
+ omitted: {
31
+ reason: string;
32
+ files: number;
33
+ }[];
34
+ warnings: {
35
+ file: string;
36
+ reason: string;
37
+ }[];
38
+ sourceWarnings: {
39
+ elementId: string;
40
+ file: string;
41
+ reason: string;
42
+ }[];
43
+ }
44
+ export declare function omittedSource(file: string): string | undefined;
45
+ /** Count physical lines with language tokens, excluding comments and blank lines. */
46
+ export declare function sourceLines(text: string, file: string, syntax?: ts.SourceFile): {
47
+ lines: string[];
48
+ code: number[];
49
+ };
50
+ /** Read Git's tracked and non-ignored untracked inventory; never import or execute repo code. */
51
+ export declare function mappingCoverage(root: string, graph: DefinitionGraph): Promise<MappingCoverage>;
52
+ export declare function coverageSummary(report: MappingCoverage): {
53
+ missingRegions: number;
54
+ excludedRegions: number;
55
+ checkedAt: string;
56
+ revision: string | null;
57
+ total: number;
58
+ mapped: number;
59
+ mappedDeclarations: number;
60
+ mappedBlockSource: number;
61
+ missing: number;
62
+ excluded: number;
63
+ percent: number | null;
64
+ files: number;
65
+ expiredExclusions: number;
66
+ omitted: {
67
+ reason: string;
68
+ files: number;
69
+ }[];
70
+ warnings: {
71
+ file: string;
72
+ reason: string;
73
+ }[];
74
+ sourceWarnings: {
75
+ elementId: string;
76
+ file: string;
77
+ reason: string;
78
+ }[];
79
+ };
80
+ export declare function coverageSource(root: string, item: CoverageItem, offset?: number): Promise<{
81
+ file: string;
82
+ start: number;
83
+ end: number;
84
+ body: string;
85
+ more: boolean;
86
+ }>;
87
+ export declare function saveCoverageExclusion(root: string, report: MappingCoverage, id: string | string[], excluded: boolean, revision: string | null): void;
@@ -0,0 +1,404 @@
1
+ /** Source ownership coverage, never test coverage or proof of architectural correctness. */
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import { createHash } from "node:crypto";
5
+ import { readFile, lstat } from "node:fs/promises";
6
+ import { existsSync, readFileSync, lstatSync, writeFileSync, renameSync, unlinkSync, openSync, closeSync, } from "node:fs";
7
+ import ts from "typescript";
8
+ import { indexSources, sourceDigest } from "./source-index.js";
9
+ import { checkedPath, WorkspaceConflict } from "./workspace-notes.js";
10
+ const execute = promisify(execFile);
11
+ const hash = (text) => createHash("sha256").update(text).digest("hex");
12
+ export const COVERAGE_FILE = "fractory.coverage.json";
13
+ function readExclusions(root) {
14
+ const path = checkedPath(root, COVERAGE_FILE, true);
15
+ if (!existsSync(path))
16
+ return {
17
+ revision: null,
18
+ exclusions: [],
19
+ files: [],
20
+ };
21
+ if (lstatSync(path).size > 1_000_000)
22
+ throw Error("Coverage exclusions exceed the 1 MB limit");
23
+ const text = readFileSync(path, "utf8");
24
+ if (Buffer.byteLength(text) > 1_000_000)
25
+ throw Error("Coverage exclusions exceed the 1 MB limit");
26
+ const value = JSON.parse(text);
27
+ if (value.schema !== "fractory.coverage.v1" ||
28
+ !Array.isArray(value.exclusions) ||
29
+ (value.files !== undefined &&
30
+ (!Array.isArray(value.files) ||
31
+ value.files.some((item) => !item ||
32
+ typeof item.file !== "string" ||
33
+ !/^[a-f0-9]{64}$/.test(item.digest) ||
34
+ typeof item.reason !== "string" ||
35
+ !item.reason.trim() ||
36
+ item.reason.length > 500))) ||
37
+ value.exclusions.some((item) => !item ||
38
+ !/^[a-f0-9]{64}$/.test(item.id) ||
39
+ typeof item.file !== "string" ||
40
+ !Number.isSafeInteger(item.start) ||
41
+ !Number.isSafeInteger(item.end) ||
42
+ typeof item.digest !== "string"))
43
+ throw Error("Invalid fractory.coverage.json");
44
+ return {
45
+ revision: hash(text),
46
+ exclusions: value.exclusions,
47
+ files: (value.files || []),
48
+ };
49
+ }
50
+ const sourceExtension = /\.(?:[cm]?[jt]sx?)$/i;
51
+ const otherSource = /\.(?:py|go|rs|java|kt|swift|rb|php|vue|svelte|c|cc|cpp|h|cs|ex|exs|scala|sh|sql)$/i;
52
+ export function omittedSource(file) {
53
+ if (/(^|\/)\.backups?(\/|$)/.test(file))
54
+ return "Backup copies";
55
+ if (!sourceExtension.test(file))
56
+ return otherSource.test(file)
57
+ ? "Other source languages (not measured)"
58
+ : "Non-source files";
59
+ if (/(^|\/)(node_modules|vendor|dist|build|out|\.next[^/]*|\.git|\.fractal|coverage)(\/|$)/.test(file))
60
+ return "Dependencies and build output";
61
+ if (/(^|\/)(generated|__generated__)(\/|$)|\.(generated|gen|d)\.[cm]?[jt]sx?$/.test(file))
62
+ return "Generated code and type declarations";
63
+ if (/(^|\/)(__tests__|__mocks__|test|tests|e2e|fixtures)(\/|$)|\.(test|spec|vitest|bench|stories)\.[cm]?[jt]sx?$/.test(file))
64
+ return "Tests, fixtures and stories";
65
+ return undefined;
66
+ }
67
+ /** Count physical lines with language tokens, excluding comments and blank lines. */
68
+ export function sourceLines(text, file, syntax = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false)) {
69
+ const lines = text.split(/\r?\n/);
70
+ const code = new Set();
71
+ const visit = (node) => {
72
+ if (node.kind === ts.SyntaxKind.EndOfFileToken ||
73
+ (node.kind >= ts.SyntaxKind.FirstJSDocNode &&
74
+ node.kind <= ts.SyntaxKind.LastJSDocNode))
75
+ return;
76
+ const children = node.getChildren(syntax);
77
+ if (children.length) {
78
+ for (const child of children)
79
+ visit(child);
80
+ return;
81
+ }
82
+ if (node.getWidth(syntax) === 0)
83
+ return;
84
+ const start = syntax.getLineAndCharacterOfPosition(node.getStart(syntax)).line + 1;
85
+ const end = syntax.getLineAndCharacterOfPosition(node.getEnd() - 1).line + 1;
86
+ for (let line = start; line <= end; line++)
87
+ if (lines[line - 1]?.trim())
88
+ code.add(line);
89
+ };
90
+ visit(syntax);
91
+ return { lines, code: [...code].sort((a, b) => a - b) };
92
+ }
93
+ const fileCache = new Map();
94
+ function measureFile(file, text, graph) {
95
+ const owners = graph.elements.flatMap((node) => {
96
+ const sources = (node.sources || (node.source ? [node.source] : [])).filter((ref) => ref.file === file);
97
+ return sources.length ? [{ ...node, source: sources[0], sources }] : [];
98
+ });
99
+ const key = hash(file +
100
+ sourceDigest(text) +
101
+ JSON.stringify(owners.map((node) => [node.id, node.sources])));
102
+ const cached = fileCache.get(key);
103
+ if (cached)
104
+ return cached;
105
+ // Strict freshness: moved or changed declarations remain missing until the map is refreshed.
106
+ const indexed = owners.length
107
+ ? indexSources({ ...graph, elements: owners }, () => text)
108
+ : { files: {}, gaps: [] };
109
+ const ranges = indexed.files[file]?.ranges || [];
110
+ const syntax = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false);
111
+ const { lines, code } = sourceLines(text, file, syntax);
112
+ const covered = new Set();
113
+ const declarations = new Set();
114
+ for (const range of ranges)
115
+ for (let line = range.start; line <= range.end; line++) {
116
+ covered.add(line);
117
+ if (range.basis !== "file")
118
+ declarations.add(line);
119
+ }
120
+ const missing = code.filter((line) => !covered.has(line));
121
+ // Split at top-level declarations as well as mapped boundaries, so a missing
122
+ // function can be dismissed without excluding the rest of a shared file.
123
+ const boundaries = new Set();
124
+ if (missing.length) {
125
+ for (const node of syntax.statements) {
126
+ if (ts.isImportDeclaration(node) ||
127
+ ts.isImportEqualsDeclaration(node) ||
128
+ (ts.isExpressionStatement(node) &&
129
+ ts.isStringLiteral(node.expression) &&
130
+ /^use (client|server|strict)$/.test(node.expression.text)))
131
+ continue;
132
+ boundaries.add(syntax.getLineAndCharacterOfPosition(node.getStart(syntax)).line + 1);
133
+ if (ts.isClassDeclaration(node))
134
+ for (const member of node.members)
135
+ boundaries.add(syntax.getLineAndCharacterOfPosition(member.getStart(syntax)).line +
136
+ 1);
137
+ }
138
+ }
139
+ const groups = [];
140
+ let group;
141
+ for (const line of code) {
142
+ if (covered.has(line)) {
143
+ group = undefined;
144
+ continue;
145
+ }
146
+ if (!group || boundaries.has(line)) {
147
+ group = [];
148
+ groups.push(group);
149
+ }
150
+ group.push(line);
151
+ }
152
+ const items = groups.map((group) => {
153
+ const start = group[0], end = group.at(-1);
154
+ const body = lines.slice(start - 1, end).join("\n");
155
+ const digest = hash(body);
156
+ const firstLine = lines
157
+ .slice(start - 1, end)
158
+ .find((line) => line.trim())
159
+ ?.trim()
160
+ .slice(0, 140) || "Source region";
161
+ const label = /^(import\b|["']use (client|server|strict)["'])/.test(firstLine)
162
+ ? "Module setup"
163
+ : firstLine;
164
+ return {
165
+ id: hash(file + "\0" + start + ":" + end + "\0" + digest),
166
+ file,
167
+ start,
168
+ end,
169
+ lines: group.length,
170
+ label,
171
+ digest,
172
+ preview: lines.slice(start - 1, Math.min(end, start + 7)).join("\n"),
173
+ excluded: false,
174
+ };
175
+ });
176
+ const result = {
177
+ total: code.length,
178
+ mapped: code.length - missing.length,
179
+ mappedDeclarations: code.filter((line) => declarations.has(line)).length,
180
+ mappedBlockSource: code.filter((line) => covered.has(line) && !declarations.has(line)).length,
181
+ items,
182
+ sourceWarnings: indexed.gaps,
183
+ };
184
+ fileCache.set(key, result);
185
+ if (fileCache.size > 3000)
186
+ fileCache.delete(fileCache.keys().next().value);
187
+ return result;
188
+ }
189
+ /** Read Git's tracked and non-ignored untracked inventory; never import or execute repo code. */
190
+ export async function mappingCoverage(root, graph) {
191
+ const { stdout } = await execute("git", [
192
+ "-c",
193
+ "core.fsmonitor=false",
194
+ "ls-files",
195
+ "--cached",
196
+ "--others",
197
+ "--exclude-standard",
198
+ "-z",
199
+ ], {
200
+ cwd: root,
201
+ encoding: "utf8",
202
+ timeout: 15000,
203
+ maxBuffer: 16 * 1024 * 1024,
204
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
205
+ });
206
+ const paths = [...new Set(stdout.split("\0").filter(Boolean))].sort();
207
+ const saved = readExclusions(root), exclusions = new Set(saved.exclusions.map((item) => item.id));
208
+ const discardedFiles = new Map(saved.files.map((item) => [item.file, item]));
209
+ const activeDiscardedFiles = new Set();
210
+ const report = {
211
+ checkedAt: new Date().toISOString(),
212
+ revision: saved.revision,
213
+ total: 0,
214
+ mapped: 0,
215
+ mappedDeclarations: 0,
216
+ mappedBlockSource: 0,
217
+ missing: 0,
218
+ excluded: 0,
219
+ percent: null,
220
+ files: 0,
221
+ items: [],
222
+ expiredExclusions: 0,
223
+ omitted: [],
224
+ warnings: [],
225
+ sourceWarnings: [],
226
+ };
227
+ const omitted = new Map();
228
+ let bytes = 0;
229
+ for (const file of paths) {
230
+ const reason = omittedSource(file);
231
+ if (reason) {
232
+ omitted.set(reason, (omitted.get(reason) || 0) + 1);
233
+ continue;
234
+ }
235
+ if (report.files >= 15000)
236
+ throw Error("Coverage exceeds the 15,000 source-file scan limit");
237
+ try {
238
+ const path = checkedPath(root, file);
239
+ const stat = await lstat(path);
240
+ if (!stat.isFile())
241
+ continue;
242
+ if (stat.size > 2 * 1024 * 1024) {
243
+ report.warnings.push({
244
+ file,
245
+ reason: "Source exceeds the 2 MB per-file limit",
246
+ });
247
+ continue;
248
+ }
249
+ bytes += stat.size;
250
+ if (bytes > 150 * 1024 * 1024)
251
+ throw Error("Coverage exceeds the 150 MB source scan limit");
252
+ const text = await readFile(path, "utf8");
253
+ if (/^\s*(?:\/\/|\/\*|\*)[^\n]*(@generated|auto-generated|automatically generated|Code generated.*DO NOT EDIT)/im.test(text.slice(0, 1200))) {
254
+ omitted.set("Generated code and type declarations", (omitted.get("Generated code and type declarations") || 0) + 1);
255
+ continue;
256
+ }
257
+ const measured = measureFile(file, text, graph);
258
+ report.files++;
259
+ report.total += measured.total;
260
+ report.mapped += measured.mapped;
261
+ report.mappedDeclarations += measured.mappedDeclarations;
262
+ report.mappedBlockSource += measured.mappedBlockSource;
263
+ report.sourceWarnings.push(...measured.sourceWarnings);
264
+ const fileExclusion = discardedFiles.get(file);
265
+ const discarded = !!fileExclusion && fileExclusion.digest === hash(text);
266
+ if (discarded && measured.items.length)
267
+ activeDiscardedFiles.add(file);
268
+ for (const item of measured.items) {
269
+ const excluded = discarded || exclusions.has(item.id);
270
+ report.items.push({
271
+ ...item,
272
+ excluded,
273
+ ...(discarded
274
+ ? {
275
+ exclusionReason: fileExclusion.reason,
276
+ exclusionScope: "file",
277
+ }
278
+ : {}),
279
+ });
280
+ if (excluded)
281
+ report.excluded += item.lines;
282
+ else
283
+ report.missing += item.lines;
284
+ }
285
+ }
286
+ catch (error) {
287
+ if (error instanceof Error && error.message.includes("source scan limit"))
288
+ throw error;
289
+ report.warnings.push({
290
+ file,
291
+ reason: "Source unavailable or linked outside the repository",
292
+ });
293
+ }
294
+ }
295
+ const active = new Set(report.items.map((item) => item.id));
296
+ report.expiredExclusions =
297
+ saved.exclusions.filter((item) => !active.has(item.id)).length +
298
+ saved.files.filter((item) => !activeDiscardedFiles.has(item.file)).length;
299
+ report.omitted = [...omitted].map(([reason, files]) => ({ reason, files }));
300
+ report.percent =
301
+ report.mapped + report.missing
302
+ ? (report.mapped / (report.mapped + report.missing)) * 100
303
+ : null;
304
+ const declaredFiles = new Set(graph.elements.flatMap((node) => (node.sources || (node.source ? [node.source] : [])).map((source) => source.file)));
305
+ const missingByFile = new Map();
306
+ for (const item of report.items)
307
+ if (!item.excluded)
308
+ missingByFile.set(item.file, (missingByFile.get(item.file) || 0) + item.lines);
309
+ // Help complete known areas first; never invent logical ownership for missing code.
310
+ report.items.sort((a, b) => Number(declaredFiles.has(b.file)) - Number(declaredFiles.has(a.file)) ||
311
+ (missingByFile.get(b.file) || 0) - (missingByFile.get(a.file) || 0) ||
312
+ a.file.localeCompare(b.file) ||
313
+ b.lines - a.lines ||
314
+ a.start - b.start);
315
+ return report;
316
+ }
317
+ export function coverageSummary(report) {
318
+ const { items, ...summary } = report;
319
+ return {
320
+ ...summary,
321
+ missingRegions: items.filter((item) => !item.excluded).length,
322
+ excludedRegions: items.filter((item) => item.excluded).length,
323
+ };
324
+ }
325
+ export async function coverageSource(root, item, offset = 0) {
326
+ const path = checkedPath(root, item.file);
327
+ if ((await lstat(path)).size > 2 * 1024 * 1024)
328
+ throw Error("Source exceeds the 2 MB per-file limit");
329
+ const lines = (await readFile(path, "utf8")).split(/\r?\n/);
330
+ if (hash(lines.slice(item.start - 1, item.end).join("\n")) !== item.digest)
331
+ throw new WorkspaceConflict("This code changed. Refresh coverage before inspecting it.");
332
+ const start = item.start + offset, end = Math.min(item.end, start + 199);
333
+ return {
334
+ file: item.file,
335
+ start,
336
+ end,
337
+ body: lines.slice(start - 1, end).join("\n"),
338
+ more: end < item.end,
339
+ };
340
+ }
341
+ export function saveCoverageExclusion(root, report, id, excluded, revision) {
342
+ const ids = new Set(Array.isArray(id) ? id : [id]);
343
+ const items = report.items.filter((item) => ids.has(item.id));
344
+ if (!items.length || items.length !== ids.size)
345
+ throw new WorkspaceConflict("This source region changed. Refresh coverage first.");
346
+ const lock = checkedPath(root, COVERAGE_FILE + ".lock", true);
347
+ let handle;
348
+ try {
349
+ handle = openSync(lock, "wx", 0o600);
350
+ }
351
+ catch {
352
+ throw new WorkspaceConflict("Coverage exclusions are being saved. Try again.");
353
+ }
354
+ const path = checkedPath(root, COVERAGE_FILE, true), temporary = checkedPath(root, `.fractory-coverage-${crypto.randomUUID()}.tmp`, true);
355
+ try {
356
+ const current = readExclusions(root);
357
+ if (current.revision !== revision)
358
+ throw new WorkspaceConflict("Coverage exclusions changed. Refresh before saving.");
359
+ const sources = new Map();
360
+ for (const item of items) {
361
+ if (!sources.has(item.file))
362
+ sources.set(item.file, readFileSync(checkedPath(root, item.file), "utf8").split(/\r?\n/));
363
+ const source = sources
364
+ .get(item.file)
365
+ .slice(item.start - 1, item.end)
366
+ .join("\n");
367
+ if (hash(source) !== item.digest)
368
+ throw new WorkspaceConflict("This code changed. Refresh coverage before saving.");
369
+ }
370
+ // Expired entries are removed on the next explicit save, never during a read.
371
+ const active = new Set(report.items.map((entry) => entry.id));
372
+ const exclusions = current.exclusions.filter((entry) => !ids.has(entry.id) && active.has(entry.id));
373
+ const files = current.files.filter((entry) => hasActiveFileDiscard(report, entry.file) &&
374
+ (excluded || !items.some((item) => item.file === entry.file)));
375
+ if (excluded)
376
+ for (const item of items)
377
+ exclusions.push({
378
+ id: item.id,
379
+ file: item.file,
380
+ start: item.start,
381
+ end: item.end,
382
+ digest: item.digest,
383
+ at: new Date().toISOString(),
384
+ });
385
+ const body = JSON.stringify({
386
+ schema: "fractory.coverage.v1",
387
+ exclusions,
388
+ ...(files.length ? { files } : {}),
389
+ }, null, 2) + "\n";
390
+ if (Buffer.byteLength(body) > 1_000_000)
391
+ throw Error("Coverage exclusions exceed the 1 MB limit. Restore old exclusions before adding more.");
392
+ writeFileSync(temporary, body, { flag: "wx", mode: 0o600 });
393
+ renameSync(temporary, path);
394
+ }
395
+ finally {
396
+ closeSync(handle);
397
+ unlinkSync(lock);
398
+ if (existsSync(temporary))
399
+ unlinkSync(temporary);
400
+ }
401
+ }
402
+ function hasActiveFileDiscard(report, file) {
403
+ return report.items.some((item) => item.file === file && item.exclusionScope === "file");
404
+ }
@@ -0,0 +1,182 @@
1
+ /** A definition graph is separate from execution evidence. No payloads or credentials belong here. */
2
+ export type ElementKind = "factory" | "deployment" | "system" | "interface" | "process" | "method" | "block" | "operation" | "resource" | "artifact";
3
+ export type Provenance = "declared" | "source" | "inferred" | "observed" | "proposed";
4
+ /** The four logical shapes. Older snapshots may still contain the legacy kinds above. */
5
+ export type LogicalKind = "block" | "interface" | "method" | "process";
6
+ export interface SourceRef {
7
+ /** Explicit implementation-module ownership; does not claim a method boundary. */
8
+ scope?: "file";
9
+ file: string;
10
+ line: number;
11
+ symbol?: string;
12
+ digest: string;
13
+ }
14
+ export interface ResourceAttachment {
15
+ id: string;
16
+ label: string;
17
+ description?: string;
18
+ source?: SourceRef;
19
+ sources?: SourceRef[];
20
+ provenance?: Provenance;
21
+ /** Existing dependency evidence, retained when an older resource node is folded away. */
22
+ connections?: Connection[];
23
+ }
24
+ export interface FlowArtifact {
25
+ id: string;
26
+ label: string;
27
+ description?: string;
28
+ source?: SourceRef;
29
+ sources?: SourceRef[];
30
+ provenance?: Provenance;
31
+ }
32
+ export interface Element {
33
+ id: string;
34
+ label: string;
35
+ kind: ElementKind;
36
+ parent?: string;
37
+ provenance: Provenance;
38
+ /** Original definition fingerprint when mounted in a larger factory. */
39
+ definitionRevision?: string;
40
+ source?: SourceRef;
41
+ sources?: SourceRef[];
42
+ hosting?: string;
43
+ externalBoundaries?: string[];
44
+ signature?: string;
45
+ contract?: {
46
+ id: string;
47
+ input?: unknown;
48
+ output?: unknown;
49
+ };
50
+ description?: string;
51
+ attachments?: import("./factory-model.js").FactoryAttachments;
52
+ /** An interface entry can expose a process while source ownership stays on that process. */
53
+ implementationBlock?: string;
54
+ resources?: ResourceAttachment[];
55
+ /** Known outputs; only mapped transfers get a wire on the canvas. */
56
+ outputs?: FlowArtifact[];
57
+ }
58
+ export type Relation = "exposes" | "flows" | "calls" | "renders" | "callbacks" | "delegates" | "resumes" | "requires" | "reads" | "writes" | "produces" | "loads";
59
+ export interface Connection {
60
+ id: string;
61
+ source: string;
62
+ target: string;
63
+ relation: Relation;
64
+ label: string;
65
+ displayLabel?: string;
66
+ provenance: Provenance;
67
+ sourceRef?: SourceRef;
68
+ sources?: SourceRef[];
69
+ transport?: string;
70
+ exchange?: {
71
+ inputs: {
72
+ name: string;
73
+ type: string;
74
+ }[];
75
+ output?: string;
76
+ };
77
+ bidirectional?: boolean;
78
+ condition?: string;
79
+ path?: "failure" | "retry";
80
+ overview?: boolean;
81
+ artifacts?: FlowArtifact[];
82
+ /** Original transfers grouped onto one visible wire. Presentation only. */
83
+ members?: Connection[];
84
+ }
85
+ export interface Verification {
86
+ id: string;
87
+ name: string;
88
+ source: SourceRef;
89
+ targets: string[];
90
+ association: "imports" | "contract-reference" | "attachment";
91
+ status: "not_run";
92
+ }
93
+ export interface DefinitionGraph {
94
+ schema: "fractal.definition.v1";
95
+ id: string;
96
+ revision: string;
97
+ /** Full source commit, when a build artifact proves it. Distinct from definition shape. */
98
+ codeRevision?: string;
99
+ generatedAt: string;
100
+ scope: string;
101
+ basis?: "repository-review";
102
+ supportingAreas?: {
103
+ name: string;
104
+ paths: string[];
105
+ scope: string;
106
+ }[];
107
+ elements: Element[];
108
+ connections: Connection[];
109
+ tests: Verification[];
110
+ failures: {
111
+ operationId: string;
112
+ source: SourceRef;
113
+ kind: "throw" | "catch";
114
+ description: string;
115
+ }[];
116
+ gaps: {
117
+ source: SourceRef;
118
+ expression: string;
119
+ reason: string;
120
+ }[];
121
+ /** Presentation redirects for resource/artifact IDs from older snapshots and activity links. */
122
+ aliases?: Record<string, string>;
123
+ }
124
+ export interface ExecutionEvidence {
125
+ schema: "fractal.evidence.v1";
126
+ jobId: string;
127
+ status: string;
128
+ runtime?: string;
129
+ startIntent?: {
130
+ state: string;
131
+ attempt: number;
132
+ };
133
+ unresolved: {
134
+ operationId: string;
135
+ commit: "unknown";
136
+ reason: string;
137
+ }[];
138
+ failures: {
139
+ code: string;
140
+ origin: string;
141
+ commit: string;
142
+ }[];
143
+ observations: {
144
+ elementId: string;
145
+ label: string;
146
+ confidence: "recorded";
147
+ }[];
148
+ definitionRevision?: string;
149
+ }
150
+ /** Lift a connection to the nearest visible ancestor, preserving its original identity. */
151
+ export declare function projectGraph(graph: DefinitionGraph, expanded: ReadonlySet<string>): {
152
+ nodes: Element[];
153
+ edges: {
154
+ source: string;
155
+ target: string;
156
+ originalSource: string;
157
+ originalTarget: string;
158
+ id: string;
159
+ relation: Relation;
160
+ label: string;
161
+ displayLabel?: string;
162
+ provenance: Provenance;
163
+ sourceRef?: SourceRef;
164
+ sources?: SourceRef[];
165
+ transport?: string;
166
+ exchange?: {
167
+ inputs: {
168
+ name: string;
169
+ type: string;
170
+ }[];
171
+ output?: string;
172
+ };
173
+ bidirectional?: boolean;
174
+ condition?: string;
175
+ path?: "failure" | "retry";
176
+ overview?: boolean;
177
+ artifacts?: FlowArtifact[];
178
+ /** Original transfers grouped onto one visible wire. Presentation only. */
179
+ members?: Connection[];
180
+ }[];
181
+ };
182
+ export declare function relatedTests(graph: DefinitionGraph, elementId: string): Verification[];