@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,570 @@
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 {
7
+ existsSync,
8
+ readFileSync,
9
+ lstatSync,
10
+ writeFileSync,
11
+ renameSync,
12
+ unlinkSync,
13
+ openSync,
14
+ closeSync,
15
+ } from "node:fs";
16
+ import ts from "typescript";
17
+ import type { DefinitionGraph } from "./model";
18
+ import { indexSources, sourceDigest } from "./source-index";
19
+ import { checkedPath, WorkspaceConflict } from "./workspace-notes";
20
+
21
+ const execute = promisify(execFile);
22
+ const hash = (text: string) => createHash("sha256").update(text).digest("hex");
23
+ export const COVERAGE_FILE = "fractory.coverage.json";
24
+ export interface CoverageItem {
25
+ id: string;
26
+ file: string;
27
+ start: number;
28
+ end: number;
29
+ lines: number;
30
+ label: string;
31
+ preview: string;
32
+ digest: string;
33
+ excluded: boolean;
34
+ exclusionReason?: string;
35
+ exclusionScope?: "file";
36
+ }
37
+ interface Exclusion {
38
+ id: string;
39
+ file: string;
40
+ start: number;
41
+ end: number;
42
+ digest: string;
43
+ at: string;
44
+ }
45
+ interface FileExclusion {
46
+ file: string;
47
+ digest: string;
48
+ reason: string;
49
+ at: string;
50
+ }
51
+ export interface MappingCoverage {
52
+ checkedAt: string;
53
+ revision: string | null;
54
+ total: number;
55
+ mapped: number;
56
+ mappedDeclarations: number;
57
+ mappedBlockSource: number;
58
+ missing: number;
59
+ excluded: number;
60
+ percent: number | null;
61
+ files: number;
62
+ items: CoverageItem[];
63
+ expiredExclusions: number;
64
+ omitted: { reason: string; files: number }[];
65
+ warnings: { file: string; reason: string }[];
66
+ sourceWarnings: { elementId: string; file: string; reason: string }[];
67
+ }
68
+ function readExclusions(root: string) {
69
+ const path = checkedPath(root, COVERAGE_FILE, true);
70
+ if (!existsSync(path))
71
+ return {
72
+ revision: null,
73
+ exclusions: [] as Exclusion[],
74
+ files: [] as FileExclusion[],
75
+ };
76
+ if (lstatSync(path).size > 1_000_000)
77
+ throw Error("Coverage exclusions exceed the 1 MB limit");
78
+ const text = readFileSync(path, "utf8");
79
+ if (Buffer.byteLength(text) > 1_000_000)
80
+ throw Error("Coverage exclusions exceed the 1 MB limit");
81
+ const value = JSON.parse(text);
82
+ if (
83
+ value.schema !== "fractory.coverage.v1" ||
84
+ !Array.isArray(value.exclusions) ||
85
+ (value.files !== undefined &&
86
+ (!Array.isArray(value.files) ||
87
+ value.files.some(
88
+ (item: FileExclusion) =>
89
+ !item ||
90
+ typeof item.file !== "string" ||
91
+ !/^[a-f0-9]{64}$/.test(item.digest) ||
92
+ typeof item.reason !== "string" ||
93
+ !item.reason.trim() ||
94
+ item.reason.length > 500,
95
+ ))) ||
96
+ value.exclusions.some(
97
+ (item: Exclusion) =>
98
+ !item ||
99
+ !/^[a-f0-9]{64}$/.test(item.id) ||
100
+ typeof item.file !== "string" ||
101
+ !Number.isSafeInteger(item.start) ||
102
+ !Number.isSafeInteger(item.end) ||
103
+ typeof item.digest !== "string",
104
+ )
105
+ )
106
+ throw Error("Invalid fractory.coverage.json");
107
+ return {
108
+ revision: hash(text),
109
+ exclusions: value.exclusions as Exclusion[],
110
+ files: (value.files || []) as FileExclusion[],
111
+ };
112
+ }
113
+ const sourceExtension = /\.(?:[cm]?[jt]sx?)$/i;
114
+ const otherSource =
115
+ /\.(?:py|go|rs|java|kt|swift|rb|php|vue|svelte|c|cc|cpp|h|cs|ex|exs|scala|sh|sql)$/i;
116
+ export function omittedSource(file: string): string | undefined {
117
+ if (/(^|\/)\.backups?(\/|$)/.test(file)) return "Backup copies";
118
+ if (!sourceExtension.test(file))
119
+ return otherSource.test(file)
120
+ ? "Other source languages (not measured)"
121
+ : "Non-source files";
122
+ if (
123
+ /(^|\/)(node_modules|vendor|dist|build|out|\.next[^/]*|\.git|\.fractal|coverage)(\/|$)/.test(
124
+ file,
125
+ )
126
+ )
127
+ return "Dependencies and build output";
128
+ if (
129
+ /(^|\/)(generated|__generated__)(\/|$)|\.(generated|gen|d)\.[cm]?[jt]sx?$/.test(
130
+ file,
131
+ )
132
+ )
133
+ return "Generated code and type declarations";
134
+ if (
135
+ /(^|\/)(__tests__|__mocks__|test|tests|e2e|fixtures)(\/|$)|\.(test|spec|vitest|bench|stories)\.[cm]?[jt]sx?$/.test(
136
+ file,
137
+ )
138
+ )
139
+ return "Tests, fixtures and stories";
140
+ return undefined;
141
+ }
142
+ /** Count physical lines with language tokens, excluding comments and blank lines. */
143
+ export function sourceLines(
144
+ text: string,
145
+ file: string,
146
+ syntax = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false),
147
+ ) {
148
+ const lines = text.split(/\r?\n/);
149
+ const code = new Set<number>();
150
+ const visit = (node: ts.Node) => {
151
+ if (
152
+ node.kind === ts.SyntaxKind.EndOfFileToken ||
153
+ (node.kind >= ts.SyntaxKind.FirstJSDocNode &&
154
+ node.kind <= ts.SyntaxKind.LastJSDocNode)
155
+ )
156
+ return;
157
+ const children = node.getChildren(syntax);
158
+ if (children.length) {
159
+ for (const child of children) visit(child);
160
+ return;
161
+ }
162
+ if (node.getWidth(syntax) === 0) return;
163
+ const start =
164
+ syntax.getLineAndCharacterOfPosition(node.getStart(syntax)).line + 1;
165
+ const end =
166
+ syntax.getLineAndCharacterOfPosition(node.getEnd() - 1).line + 1;
167
+ for (let line = start; line <= end; line++)
168
+ if (lines[line - 1]?.trim()) code.add(line);
169
+ };
170
+ visit(syntax);
171
+ return { lines, code: [...code].sort((a, b) => a - b) };
172
+ }
173
+ const fileCache = new Map<
174
+ string,
175
+ {
176
+ mapped: number;
177
+ mappedDeclarations: number;
178
+ mappedBlockSource: number;
179
+ total: number;
180
+ items: CoverageItem[];
181
+ sourceWarnings: MappingCoverage["sourceWarnings"];
182
+ }
183
+ >();
184
+ function measureFile(file: string, text: string, graph: DefinitionGraph) {
185
+ const owners = graph.elements.flatMap((node) => {
186
+ const sources = (node.sources || (node.source ? [node.source] : [])).filter(
187
+ (ref) => ref.file === file,
188
+ );
189
+ return sources.length ? [{ ...node, source: sources[0], sources }] : [];
190
+ });
191
+ const key = hash(
192
+ file +
193
+ sourceDigest(text) +
194
+ JSON.stringify(owners.map((node) => [node.id, node.sources])),
195
+ );
196
+ const cached = fileCache.get(key);
197
+ if (cached) return cached;
198
+ // Strict freshness: moved or changed declarations remain missing until the map is refreshed.
199
+ const indexed: Pick<import("./code-model").CodeSnapshot, "files" | "gaps"> =
200
+ owners.length
201
+ ? indexSources({ ...graph, elements: owners }, () => text)
202
+ : { files: {}, gaps: [] };
203
+ const ranges = indexed.files[file]?.ranges || [];
204
+ const syntax = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false);
205
+ const { lines, code } = sourceLines(text, file, syntax);
206
+ const covered = new Set<number>();
207
+ const declarations = new Set<number>();
208
+ for (const range of ranges)
209
+ for (let line = range.start; line <= range.end; line++) {
210
+ covered.add(line);
211
+ if (range.basis !== "file") declarations.add(line);
212
+ }
213
+ const missing = code.filter((line) => !covered.has(line));
214
+ // Split at top-level declarations as well as mapped boundaries, so a missing
215
+ // function can be dismissed without excluding the rest of a shared file.
216
+ const boundaries = new Set<number>();
217
+ if (missing.length) {
218
+ for (const node of syntax.statements) {
219
+ if (
220
+ ts.isImportDeclaration(node) ||
221
+ ts.isImportEqualsDeclaration(node) ||
222
+ (ts.isExpressionStatement(node) &&
223
+ ts.isStringLiteral(node.expression) &&
224
+ /^use (client|server|strict)$/.test(node.expression.text))
225
+ )
226
+ continue;
227
+ boundaries.add(
228
+ syntax.getLineAndCharacterOfPosition(node.getStart(syntax)).line + 1,
229
+ );
230
+ if (ts.isClassDeclaration(node))
231
+ for (const member of node.members)
232
+ boundaries.add(
233
+ syntax.getLineAndCharacterOfPosition(member.getStart(syntax)).line +
234
+ 1,
235
+ );
236
+ }
237
+ }
238
+ const groups: number[][] = [];
239
+ let group: number[] | undefined;
240
+ for (const line of code) {
241
+ if (covered.has(line)) {
242
+ group = undefined;
243
+ continue;
244
+ }
245
+ if (!group || boundaries.has(line)) {
246
+ group = [];
247
+ groups.push(group);
248
+ }
249
+ group.push(line);
250
+ }
251
+ const items = groups.map((group): CoverageItem => {
252
+ const start = group[0],
253
+ end = group.at(-1)!;
254
+ const body = lines.slice(start - 1, end).join("\n");
255
+ const digest = hash(body);
256
+ const firstLine =
257
+ lines
258
+ .slice(start - 1, end)
259
+ .find((line) => line.trim())
260
+ ?.trim()
261
+ .slice(0, 140) || "Source region";
262
+ const label = /^(import\b|["']use (client|server|strict)["'])/.test(
263
+ firstLine,
264
+ )
265
+ ? "Module setup"
266
+ : firstLine;
267
+ return {
268
+ id: hash(file + "\0" + start + ":" + end + "\0" + digest),
269
+ file,
270
+ start,
271
+ end,
272
+ lines: group.length,
273
+ label,
274
+ digest,
275
+ preview: lines.slice(start - 1, Math.min(end, start + 7)).join("\n"),
276
+ excluded: false,
277
+ };
278
+ });
279
+ const result = {
280
+ total: code.length,
281
+ mapped: code.length - missing.length,
282
+ mappedDeclarations: code.filter((line) => declarations.has(line)).length,
283
+ mappedBlockSource: code.filter(
284
+ (line) => covered.has(line) && !declarations.has(line),
285
+ ).length,
286
+ items,
287
+ sourceWarnings: indexed.gaps,
288
+ };
289
+ fileCache.set(key, result);
290
+ if (fileCache.size > 3000) fileCache.delete(fileCache.keys().next().value!);
291
+ return result;
292
+ }
293
+ /** Read Git's tracked and non-ignored untracked inventory; never import or execute repo code. */
294
+ export async function mappingCoverage(
295
+ root: string,
296
+ graph: DefinitionGraph,
297
+ ): Promise<MappingCoverage> {
298
+ const { stdout } = await execute(
299
+ "git",
300
+ [
301
+ "-c",
302
+ "core.fsmonitor=false",
303
+ "ls-files",
304
+ "--cached",
305
+ "--others",
306
+ "--exclude-standard",
307
+ "-z",
308
+ ],
309
+ {
310
+ cwd: root,
311
+ encoding: "utf8",
312
+ timeout: 15000,
313
+ maxBuffer: 16 * 1024 * 1024,
314
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
315
+ },
316
+ );
317
+ const paths = [...new Set(stdout.split("\0").filter(Boolean))].sort();
318
+ const saved = readExclusions(root),
319
+ exclusions = new Set(saved.exclusions.map((item) => item.id));
320
+ const discardedFiles = new Map(saved.files.map((item) => [item.file, item]));
321
+ const activeDiscardedFiles = new Set<string>();
322
+ const report: MappingCoverage = {
323
+ checkedAt: new Date().toISOString(),
324
+ revision: saved.revision,
325
+ total: 0,
326
+ mapped: 0,
327
+ mappedDeclarations: 0,
328
+ mappedBlockSource: 0,
329
+ missing: 0,
330
+ excluded: 0,
331
+ percent: null,
332
+ files: 0,
333
+ items: [],
334
+ expiredExclusions: 0,
335
+ omitted: [],
336
+ warnings: [],
337
+ sourceWarnings: [],
338
+ };
339
+ const omitted = new Map<string, number>();
340
+ let bytes = 0;
341
+ for (const file of paths) {
342
+ const reason = omittedSource(file);
343
+ if (reason) {
344
+ omitted.set(reason, (omitted.get(reason) || 0) + 1);
345
+ continue;
346
+ }
347
+ if (report.files >= 15000)
348
+ throw Error("Coverage exceeds the 15,000 source-file scan limit");
349
+ try {
350
+ const path = checkedPath(root, file);
351
+ const stat = await lstat(path);
352
+ if (!stat.isFile()) continue;
353
+ if (stat.size > 2 * 1024 * 1024) {
354
+ report.warnings.push({
355
+ file,
356
+ reason: "Source exceeds the 2 MB per-file limit",
357
+ });
358
+ continue;
359
+ }
360
+ bytes += stat.size;
361
+ if (bytes > 150 * 1024 * 1024)
362
+ throw Error("Coverage exceeds the 150 MB source scan limit");
363
+ const text = await readFile(path, "utf8");
364
+ if (
365
+ /^\s*(?:\/\/|\/\*|\*)[^\n]*(@generated|auto-generated|automatically generated|Code generated.*DO NOT EDIT)/im.test(
366
+ text.slice(0, 1200),
367
+ )
368
+ ) {
369
+ omitted.set(
370
+ "Generated code and type declarations",
371
+ (omitted.get("Generated code and type declarations") || 0) + 1,
372
+ );
373
+ continue;
374
+ }
375
+ const measured = measureFile(file, text, graph);
376
+ report.files++;
377
+ report.total += measured.total;
378
+ report.mapped += measured.mapped;
379
+ report.mappedDeclarations += measured.mappedDeclarations;
380
+ report.mappedBlockSource += measured.mappedBlockSource;
381
+ report.sourceWarnings.push(...measured.sourceWarnings);
382
+ const fileExclusion = discardedFiles.get(file);
383
+ const discarded = !!fileExclusion && fileExclusion.digest === hash(text);
384
+ if (discarded && measured.items.length) activeDiscardedFiles.add(file);
385
+ for (const item of measured.items) {
386
+ const excluded = discarded || exclusions.has(item.id);
387
+ report.items.push({
388
+ ...item,
389
+ excluded,
390
+ ...(discarded
391
+ ? {
392
+ exclusionReason: fileExclusion!.reason,
393
+ exclusionScope: "file" as const,
394
+ }
395
+ : {}),
396
+ });
397
+ if (excluded) report.excluded += item.lines;
398
+ else report.missing += item.lines;
399
+ }
400
+ } catch (error) {
401
+ if (error instanceof Error && error.message.includes("source scan limit"))
402
+ throw error;
403
+ report.warnings.push({
404
+ file,
405
+ reason: "Source unavailable or linked outside the repository",
406
+ });
407
+ }
408
+ }
409
+ const active = new Set(report.items.map((item) => item.id));
410
+ report.expiredExclusions =
411
+ saved.exclusions.filter((item) => !active.has(item.id)).length +
412
+ saved.files.filter((item) => !activeDiscardedFiles.has(item.file)).length;
413
+ report.omitted = [...omitted].map(([reason, files]) => ({ reason, files }));
414
+ report.percent =
415
+ report.mapped + report.missing
416
+ ? (report.mapped / (report.mapped + report.missing)) * 100
417
+ : null;
418
+ const declaredFiles = new Set(
419
+ graph.elements.flatMap((node) =>
420
+ (node.sources || (node.source ? [node.source] : [])).map(
421
+ (source) => source.file,
422
+ ),
423
+ ),
424
+ );
425
+ const missingByFile = new Map<string, number>();
426
+ for (const item of report.items)
427
+ if (!item.excluded)
428
+ missingByFile.set(
429
+ item.file,
430
+ (missingByFile.get(item.file) || 0) + item.lines,
431
+ );
432
+ // Help complete known areas first; never invent logical ownership for missing code.
433
+ report.items.sort(
434
+ (a, b) =>
435
+ Number(declaredFiles.has(b.file)) - Number(declaredFiles.has(a.file)) ||
436
+ (missingByFile.get(b.file) || 0) - (missingByFile.get(a.file) || 0) ||
437
+ a.file.localeCompare(b.file) ||
438
+ b.lines - a.lines ||
439
+ a.start - b.start,
440
+ );
441
+ return report;
442
+ }
443
+ export function coverageSummary(report: MappingCoverage) {
444
+ const { items, ...summary } = report;
445
+ return {
446
+ ...summary,
447
+ missingRegions: items.filter((item) => !item.excluded).length,
448
+ excludedRegions: items.filter((item) => item.excluded).length,
449
+ };
450
+ }
451
+ export async function coverageSource(
452
+ root: string,
453
+ item: CoverageItem,
454
+ offset = 0,
455
+ ) {
456
+ const path = checkedPath(root, item.file);
457
+ if ((await lstat(path)).size > 2 * 1024 * 1024)
458
+ throw Error("Source exceeds the 2 MB per-file limit");
459
+ const lines = (await readFile(path, "utf8")).split(/\r?\n/);
460
+ if (hash(lines.slice(item.start - 1, item.end).join("\n")) !== item.digest)
461
+ throw new WorkspaceConflict(
462
+ "This code changed. Refresh coverage before inspecting it.",
463
+ );
464
+ const start = item.start + offset,
465
+ end = Math.min(item.end, start + 199);
466
+ return {
467
+ file: item.file,
468
+ start,
469
+ end,
470
+ body: lines.slice(start - 1, end).join("\n"),
471
+ more: end < item.end,
472
+ };
473
+ }
474
+ export function saveCoverageExclusion(
475
+ root: string,
476
+ report: MappingCoverage,
477
+ id: string | string[],
478
+ excluded: boolean,
479
+ revision: string | null,
480
+ ) {
481
+ const ids = new Set(Array.isArray(id) ? id : [id]);
482
+ const items = report.items.filter((item) => ids.has(item.id));
483
+ if (!items.length || items.length !== ids.size)
484
+ throw new WorkspaceConflict(
485
+ "This source region changed. Refresh coverage first.",
486
+ );
487
+ const lock = checkedPath(root, COVERAGE_FILE + ".lock", true);
488
+ let handle: number;
489
+ try {
490
+ handle = openSync(lock, "wx", 0o600);
491
+ } catch {
492
+ throw new WorkspaceConflict(
493
+ "Coverage exclusions are being saved. Try again.",
494
+ );
495
+ }
496
+ const path = checkedPath(root, COVERAGE_FILE, true),
497
+ temporary = checkedPath(
498
+ root,
499
+ `.fractory-coverage-${crypto.randomUUID()}.tmp`,
500
+ true,
501
+ );
502
+ try {
503
+ const current = readExclusions(root);
504
+ if (current.revision !== revision)
505
+ throw new WorkspaceConflict(
506
+ "Coverage exclusions changed. Refresh before saving.",
507
+ );
508
+ const sources = new Map<string, string[]>();
509
+ for (const item of items) {
510
+ if (!sources.has(item.file))
511
+ sources.set(
512
+ item.file,
513
+ readFileSync(checkedPath(root, item.file), "utf8").split(/\r?\n/),
514
+ );
515
+ const source = sources
516
+ .get(item.file)!
517
+ .slice(item.start - 1, item.end)
518
+ .join("\n");
519
+ if (hash(source) !== item.digest)
520
+ throw new WorkspaceConflict(
521
+ "This code changed. Refresh coverage before saving.",
522
+ );
523
+ }
524
+ // Expired entries are removed on the next explicit save, never during a read.
525
+ const active = new Set(report.items.map((entry) => entry.id));
526
+ const exclusions = current.exclusions.filter(
527
+ (entry) => !ids.has(entry.id) && active.has(entry.id),
528
+ );
529
+ const files = current.files.filter(
530
+ (entry) =>
531
+ hasActiveFileDiscard(report, entry.file) &&
532
+ (excluded || !items.some((item) => item.file === entry.file)),
533
+ );
534
+ if (excluded)
535
+ for (const item of items)
536
+ exclusions.push({
537
+ id: item.id,
538
+ file: item.file,
539
+ start: item.start,
540
+ end: item.end,
541
+ digest: item.digest,
542
+ at: new Date().toISOString(),
543
+ });
544
+ const body =
545
+ JSON.stringify(
546
+ {
547
+ schema: "fractory.coverage.v1",
548
+ exclusions,
549
+ ...(files.length ? { files } : {}),
550
+ },
551
+ null,
552
+ 2,
553
+ ) + "\n";
554
+ if (Buffer.byteLength(body) > 1_000_000)
555
+ throw Error(
556
+ "Coverage exclusions exceed the 1 MB limit. Restore old exclusions before adding more.",
557
+ );
558
+ writeFileSync(temporary, body, { flag: "wx", mode: 0o600 });
559
+ renameSync(temporary, path);
560
+ } finally {
561
+ closeSync(handle);
562
+ unlinkSync(lock);
563
+ if (existsSync(temporary)) unlinkSync(temporary);
564
+ }
565
+ }
566
+ function hasActiveFileDiscard(report: MappingCoverage, file: string) {
567
+ return report.items.some(
568
+ (item) => item.file === file && item.exclusionScope === "file",
569
+ );
570
+ }