@granular-software/fractory 0.0.0-stage → 0.1.25

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 (285) 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 +122 -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 +1240 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +87 -0
  40. package/dist/core.js +207 -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 +67 -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 +7 -0
  54. package/dist/factory-graph.js +389 -0
  55. package/dist/factory-model.d.ts +111 -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/interface-map.d.ts +15 -0
  76. package/dist/interface-map.js +125 -0
  77. package/dist/issue-cache.d.ts +9 -0
  78. package/dist/issue-cache.js +68 -0
  79. package/dist/issue-cli.d.ts +1 -0
  80. package/dist/issue-cli.js +89 -0
  81. package/dist/issue-links.d.ts +15 -0
  82. package/dist/issue-links.js +125 -0
  83. package/dist/linear-issues.d.ts +19 -0
  84. package/dist/linear-issues.js +124 -0
  85. package/dist/local-runtime.d.ts +8 -0
  86. package/dist/local-runtime.js +59 -0
  87. package/dist/map-activity.d.ts +73 -0
  88. package/dist/map-activity.js +234 -0
  89. package/dist/map-model.d.ts +5 -0
  90. package/dist/map-model.js +166 -0
  91. package/dist/map-quality.d.ts +20 -0
  92. package/dist/map-quality.js +61 -0
  93. package/dist/mapping-coverage.d.ts +87 -0
  94. package/dist/mapping-coverage.js +404 -0
  95. package/dist/model.d.ts +186 -0
  96. package/dist/model.js +66 -0
  97. package/dist/operation-benchmark-worker.d.ts +2 -0
  98. package/dist/operation-benchmark-worker.js +60 -0
  99. package/dist/operation-benchmark.d.ts +29 -0
  100. package/dist/operation-benchmark.js +1 -0
  101. package/dist/otel-metrics.d.ts +21 -0
  102. package/dist/otel-metrics.js +146 -0
  103. package/dist/performance-model.d.ts +185 -0
  104. package/dist/performance-model.js +396 -0
  105. package/dist/product-map.d.ts +71 -0
  106. package/dist/product-map.js +197 -0
  107. package/dist/provider-access.cjs +207 -0
  108. package/dist/provider-access.d.cts +14 -0
  109. package/dist/public-boundaries.d.ts +13 -0
  110. package/dist/public-boundaries.js +115 -0
  111. package/dist/reports-cli.d.ts +1 -0
  112. package/dist/reports-cli.js +111 -0
  113. package/dist/reports-model.d.ts +27 -0
  114. package/dist/reports-model.js +39 -0
  115. package/dist/reports.d.ts +23 -0
  116. package/dist/reports.js +223 -0
  117. package/dist/repository-map.d.ts +22 -0
  118. package/dist/repository-map.js +153 -0
  119. package/dist/resource-cache.d.ts +17 -0
  120. package/dist/resource-cache.js +65 -0
  121. package/dist/review-cli.d.ts +19 -0
  122. package/dist/review-cli.js +224 -0
  123. package/dist/review.d.ts +48 -0
  124. package/dist/review.js +289 -0
  125. package/dist/runtime-metrics.d.ts +26 -0
  126. package/dist/runtime-metrics.js +290 -0
  127. package/dist/scope.d.ts +14 -0
  128. package/dist/scope.js +168 -0
  129. package/dist/sentry-activity.d.ts +39 -0
  130. package/dist/sentry-activity.js +174 -0
  131. package/dist/sentry.d.ts +130 -0
  132. package/dist/sentry.js +369 -0
  133. package/dist/service-release.d.ts +16 -0
  134. package/dist/service-release.js +14 -0
  135. package/dist/setup-cli.d.ts +2 -0
  136. package/dist/setup-cli.js +52 -0
  137. package/dist/setup-kit.cjs +163 -0
  138. package/dist/setup-kit.d.cts +32 -0
  139. package/dist/source-index.d.ts +37 -0
  140. package/dist/source-index.js +170 -0
  141. package/dist/source-review-git.d.ts +7 -0
  142. package/dist/source-review-git.js +105 -0
  143. package/dist/source-review.d.ts +18 -0
  144. package/dist/source-review.js +573 -0
  145. package/dist/telemetry.d.ts +17 -0
  146. package/dist/telemetry.js +51 -0
  147. package/dist/time-window.d.ts +9 -0
  148. package/dist/time-window.js +35 -0
  149. package/dist/trace-evidence.d.ts +23 -0
  150. package/dist/trace-evidence.js +55 -0
  151. package/dist/trace-model.d.ts +26 -0
  152. package/dist/trace-model.js +1 -0
  153. package/dist/tracing.d.ts +44 -0
  154. package/dist/tracing.js +123 -0
  155. package/dist/work-check.d.ts +18 -0
  156. package/dist/work-check.js +115 -0
  157. package/dist/work-cli.d.ts +1 -0
  158. package/dist/work-cli.js +176 -0
  159. package/dist/work-context.d.ts +59 -0
  160. package/dist/work-context.js +594 -0
  161. package/dist/work-intents.d.ts +6 -0
  162. package/dist/work-intents.js +140 -0
  163. package/dist/work-items.d.ts +58 -0
  164. package/dist/work-items.js +86 -0
  165. package/dist/work-lock-check.d.ts +12 -0
  166. package/dist/work-lock-check.js +339 -0
  167. package/dist/work-locks.d.ts +10 -0
  168. package/dist/work-locks.js +98 -0
  169. package/dist/work-model.d.ts +119 -0
  170. package/dist/work-model.js +310 -0
  171. package/dist/work-review-git.d.ts +8 -0
  172. package/dist/work-review-git.js +111 -0
  173. package/dist/work-review.d.ts +26 -0
  174. package/dist/work-review.js +426 -0
  175. package/dist/work-switcher-model.d.ts +43 -0
  176. package/dist/work-switcher-model.js +79 -0
  177. package/dist/work-switcher.d.ts +6 -0
  178. package/dist/work-switcher.js +171 -0
  179. package/dist/working-cli.d.ts +1 -0
  180. package/dist/working-cli.js +33 -0
  181. package/dist/working-code.d.ts +74 -0
  182. package/dist/working-code.js +421 -0
  183. package/dist/workspace-notes.d.ts +71 -0
  184. package/dist/workspace-notes.js +177 -0
  185. package/dist/workspace-tests.d.ts +21 -0
  186. package/dist/workspace-tests.js +573 -0
  187. package/package.json +547 -4
  188. package/src/activity-volume.ts +149 -0
  189. package/src/annotations.ts +485 -0
  190. package/src/benchmark-cli.ts +118 -0
  191. package/src/benchmark-worker.ts +22 -0
  192. package/src/benchmarks.ts +493 -0
  193. package/src/bin.ts +54 -0
  194. package/src/block-cli.ts +106 -0
  195. package/src/block-documents.ts +117 -0
  196. package/src/change-impact.ts +280 -0
  197. package/src/check-source.ts +82 -0
  198. package/src/checks-model.ts +108 -0
  199. package/src/cli.ts +440 -0
  200. package/src/code-model.ts +159 -0
  201. package/src/code-store.ts +98 -0
  202. package/src/compare-artifact.ts +314 -0
  203. package/src/compare.ts +440 -0
  204. package/src/compiler.ts +1512 -0
  205. package/src/compose.ts +94 -0
  206. package/src/core.ts +361 -0
  207. package/src/coverage-cli.ts +52 -0
  208. package/src/declaration-sources.ts +69 -0
  209. package/src/declared-graph.ts +75 -0
  210. package/src/display-name.ts +8 -0
  211. package/src/error-heat.ts +161 -0
  212. package/src/evidence.ts +94 -0
  213. package/src/factory-graph.ts +462 -0
  214. package/src/factory-model.ts +82 -0
  215. package/src/git-code.ts +461 -0
  216. package/src/git-refs.ts +43 -0
  217. package/src/history-activity.ts +146 -0
  218. package/src/history-churn.ts +416 -0
  219. package/src/history-git.ts +163 -0
  220. package/src/history-ledger.ts +636 -0
  221. package/src/history-ownership.ts +116 -0
  222. package/src/history-source.ts +117 -0
  223. package/src/integrations-cli.ts +187 -0
  224. package/src/interface-map.ts +166 -0
  225. package/src/issue-cache.ts +96 -0
  226. package/src/issue-cli.ts +137 -0
  227. package/src/issue-links.ts +153 -0
  228. package/src/linear-issues.ts +154 -0
  229. package/src/local-runtime.ts +70 -0
  230. package/src/map-activity.ts +309 -0
  231. package/src/map-model.ts +213 -0
  232. package/src/map-quality.ts +66 -0
  233. package/src/mapping-coverage.ts +570 -0
  234. package/src/model.ts +228 -0
  235. package/src/operation-benchmark-worker.ts +60 -0
  236. package/src/operation-benchmark.ts +28 -0
  237. package/src/otel-metrics.ts +176 -0
  238. package/src/performance-model.ts +575 -0
  239. package/src/product-map.ts +271 -0
  240. package/src/provider-access.cjs +207 -0
  241. package/src/provider-access.d.cts +14 -0
  242. package/src/public-boundaries.ts +143 -0
  243. package/src/reports-cli.ts +125 -0
  244. package/src/reports-model.ts +73 -0
  245. package/src/reports.ts +276 -0
  246. package/src/repository-map.ts +191 -0
  247. package/src/resource-cache.ts +76 -0
  248. package/src/review-cli.ts +256 -0
  249. package/src/review.ts +376 -0
  250. package/src/runtime-metrics.ts +386 -0
  251. package/src/scope.ts +192 -0
  252. package/src/sentry-activity.ts +234 -0
  253. package/src/sentry.ts +545 -0
  254. package/src/service-release.ts +18 -0
  255. package/src/setup-cli.ts +58 -0
  256. package/src/setup-kit.cjs +163 -0
  257. package/src/setup-kit.d.cts +32 -0
  258. package/src/source-index.ts +208 -0
  259. package/src/source-review-git.ts +131 -0
  260. package/src/source-review.ts +736 -0
  261. package/src/telemetry.ts +68 -0
  262. package/src/time-window.ts +51 -0
  263. package/src/trace-evidence.ts +80 -0
  264. package/src/trace-model.ts +26 -0
  265. package/src/tracing.ts +165 -0
  266. package/src/work-check.ts +149 -0
  267. package/src/work-cli.ts +229 -0
  268. package/src/work-context.ts +753 -0
  269. package/src/work-intents.ts +196 -0
  270. package/src/work-items.ts +151 -0
  271. package/src/work-lock-check.ts +549 -0
  272. package/src/work-locks.ts +108 -0
  273. package/src/work-model.ts +466 -0
  274. package/src/work-review-git.ts +130 -0
  275. package/src/work-review.ts +573 -0
  276. package/src/work-switcher-model.ts +121 -0
  277. package/src/work-switcher.ts +191 -0
  278. package/src/working-cli.ts +38 -0
  279. package/src/working-code.ts +582 -0
  280. package/src/workspace-notes.ts +203 -0
  281. package/src/workspace-tests.ts +654 -0
  282. package/toolkit/GUIDE.md +354 -0
  283. package/toolkit/SKILL.md +142 -0
  284. package/toolkit/bin/fractory +2 -0
  285. package/toolkit/build.json +1 -0
@@ -0,0 +1,461 @@
1
+ /** Build/CLI adapter only. The Worker/browser matching core has no dependency on Git. */
2
+ import { execFileSync } from "node:child_process";
3
+ import { readGit as git } from "./git-refs";
4
+ export { resolveComparisonRef, comparisonMergeBase } from "./git-refs";
5
+ import { readFileSync, mkdirSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { createHash } from "node:crypto";
8
+ import type { DefinitionGraph } from "./model";
9
+ import { blockFiles, locateCode, type CodeSnapshot } from "./code-model";
10
+ import { indexSources } from "./source-index";
11
+ import { factoryGraph } from "./factory-graph";
12
+ import type { FactoryModel } from "./factory-model";
13
+ import { blockNoteFile } from "./workspace-notes";
14
+ import { relatedTests } from "./model";
15
+ import { graphIndex } from "./change-impact";
16
+
17
+ function attachments(
18
+ snapshot: Pick<CodeSnapshot, "graph">,
19
+ ): { file: string; kind: "notes" | "tests" | "auth"; elementId: string }[] {
20
+ const items: {
21
+ file: string;
22
+ kind: "notes" | "tests" | "auth";
23
+ elementId: string;
24
+ }[] = snapshot.graph.elements.flatMap((node) => [
25
+ ...[blockNoteFile(node.id), ...(node.attachments?.docs || [])].map(
26
+ (file) => ({
27
+ file: file.split("#")[0],
28
+ kind: "notes" as const,
29
+ elementId: node.id,
30
+ }),
31
+ ),
32
+ ...(node.attachments?.auth?.source
33
+ ? [
34
+ {
35
+ file: node.attachments.auth.source.file,
36
+ kind: "auth" as const,
37
+ elementId: node.id,
38
+ },
39
+ ]
40
+ : []),
41
+ ]);
42
+ items.push(
43
+ ...snapshot.graph.tests.flatMap((test) =>
44
+ test.targets.map((elementId) => ({
45
+ file: test.source.file,
46
+ kind: "tests" as const,
47
+ elementId,
48
+ })),
49
+ ),
50
+ );
51
+ return items;
52
+ }
53
+
54
+ export function resolveCommit(root: string, ref: string) {
55
+ if (!/^(?:HEAD(?:~\d{1,5}|\^\d?)?|[a-f0-9]{7,64})$/i.test(ref))
56
+ throw new Error("Use HEAD, HEAD~N, or a commit SHA");
57
+ return git(root, ["rev-parse", "--verify", `${ref}^{commit}`]).trim();
58
+ }
59
+ /** One bounded, null-delimited read. No similarity search or source execution. */
60
+ export function changedPaths(root: string, base: string, head: string) {
61
+ if (![base, head].every((ref) => /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(ref)))
62
+ throw Error("Expected resolved commits");
63
+ const parts = git(root, [
64
+ "diff",
65
+ "--no-ext-diff",
66
+ "--no-textconv",
67
+ "--no-renames",
68
+ "--raw",
69
+ "--no-abbrev",
70
+ "-z",
71
+ base,
72
+ head,
73
+ "--",
74
+ ]).split("\0");
75
+ const files: import("./review").FactoryFootprint["files"] = [];
76
+ for (let i = 0; i + 1 < parts.length; i += 2) {
77
+ const [, , before, after, status] = parts[i].split(" ");
78
+ files.push({
79
+ path: parts[i + 1],
80
+ status:
81
+ status === "A" ? "added" : status === "D" ? "removed" : "modified",
82
+ digest: `${before}:${after}`,
83
+ });
84
+ }
85
+ if (files.length > 20000) throw Error("PR footprint exceeds the path budget");
86
+ return files;
87
+ }
88
+ export function captureCode(
89
+ root: string,
90
+ graph: DefinitionGraph,
91
+ cacheDirectory?: string,
92
+ ): CodeSnapshot {
93
+ const baseCommit = resolveCommit(root, "HEAD");
94
+ let dirty = !!git(root, [
95
+ "status",
96
+ "--porcelain",
97
+ "--untracked-files=normal",
98
+ ]).trim();
99
+ if (cacheDirectory) mkdirSync(cacheDirectory, { recursive: true });
100
+ const indexed = indexSources(
101
+ graph,
102
+ (file) => {
103
+ try {
104
+ return readFileSync(join(root, file), "utf8");
105
+ } catch {
106
+ return undefined;
107
+ }
108
+ },
109
+ cacheDirectory
110
+ ? {
111
+ get: (key) => {
112
+ try {
113
+ return JSON.parse(
114
+ readFileSync(join(cacheDirectory, `${key}.json`), "utf8"),
115
+ );
116
+ } catch {
117
+ return undefined;
118
+ }
119
+ },
120
+ put: (key, value) =>
121
+ writeFileSync(
122
+ join(cacheDirectory, `${key}.json`),
123
+ JSON.stringify(value),
124
+ ),
125
+ }
126
+ : undefined,
127
+ { resolveUniqueAnchors: true },
128
+ );
129
+ // Catch a checkout or edit racing the capture. CI normally takes this fast clean path.
130
+ if (!dirty)
131
+ dirty =
132
+ resolveCommit(root, "HEAD") !== baseCommit ||
133
+ !!git(root, ["status", "--porcelain", "--untracked-files=normal"]).trim();
134
+ graph = { ...graph, codeRevision: dirty ? undefined : baseCommit };
135
+ const graphContent = { ...graph, generatedAt: "content" };
136
+ const id = createHash("sha256")
137
+ .update(
138
+ JSON.stringify({ baseCommit, dirty, graph: graphContent, ...indexed }),
139
+ )
140
+ .digest("hex");
141
+ return {
142
+ schema: "fractal.code.v1",
143
+ id,
144
+ commit: dirty ? null : baseCommit,
145
+ baseCommit,
146
+ capturedAt: new Date().toISOString(),
147
+ graph,
148
+ ...indexed,
149
+ };
150
+ }
151
+
152
+ export { saveCode, loadCode, codeTimeline } from "./code-store";
153
+
154
+ /** Two bounded cat-file batches; no checkout, source execution, or history scan. */
155
+ export function captureCommit(
156
+ root: string,
157
+ ref: string,
158
+ definitionFiles: string[],
159
+ compose: (definitions: DefinitionGraph[]) => DefinitionGraph,
160
+ annotationsFile?: string,
161
+ ): CodeSnapshot {
162
+ const commit = resolveCommit(root, ref);
163
+ const read = (paths: string[]) => {
164
+ if (
165
+ paths.some(
166
+ (path) =>
167
+ /[\r\n\0]/.test(path) ||
168
+ path.startsWith("/") ||
169
+ path.split(/[\\/]/).includes(".."),
170
+ )
171
+ )
172
+ throw new Error("Expected repository source paths");
173
+ const output = execFileSync("git", ["cat-file", "--batch"], {
174
+ cwd: root,
175
+ input: paths.map((path) => `${commit}:${path}\n`).join(""),
176
+ maxBuffer: 32 * 1024 * 1024,
177
+ timeout: 15_000,
178
+ stdio: ["pipe", "pipe", "pipe"],
179
+ });
180
+ const texts = new Map<string, string>();
181
+ let offset = 0;
182
+ for (const path of paths) {
183
+ const end = output.indexOf(10, offset);
184
+ if (end < 0) throw new Error("Incomplete Git object batch");
185
+ const header = output.subarray(offset, end).toString();
186
+ offset = end + 1;
187
+ if (header.endsWith(" missing")) continue;
188
+ const [, type, size] = header.split(" ");
189
+ if (type !== "blob" || !/^\d+$/.test(size))
190
+ throw new Error("Expected a Git source blob");
191
+ texts.set(
192
+ path,
193
+ output.subarray(offset, offset + Number(size)).toString(),
194
+ );
195
+ offset += Number(size) + 1;
196
+ }
197
+ return texts;
198
+ };
199
+ const definitions = read([
200
+ ...definitionFiles,
201
+ ...(annotationsFile ? [annotationsFile] : []),
202
+ ]);
203
+ const graphs = definitionFiles.map((file) => {
204
+ const text = definitions.get(file);
205
+ if (!text)
206
+ throw new Error(
207
+ "No captured definition at this commit; Fractal may not have been installed yet",
208
+ );
209
+ const graph = JSON.parse(text) as DefinitionGraph;
210
+ if (
211
+ graph.schema !== "fractal.definition.v1" ||
212
+ !Array.isArray(graph.elements)
213
+ )
214
+ throw new Error("Unsupported historical factory definition");
215
+ return graph;
216
+ });
217
+ const annotationText = annotationsFile && definitions.get(annotationsFile);
218
+ const annotations = annotationText
219
+ ? (JSON.parse(annotationText) as FactoryModel)
220
+ : undefined;
221
+ if (annotations && annotations.schema !== "fractal.factory.v2")
222
+ throw new Error("Unsupported historical annotation model");
223
+ const graph = {
224
+ ...(annotations
225
+ ? factoryGraph(annotations, compose(graphs), { legacySnapshot: true })
226
+ : compose(graphs)),
227
+ codeRevision: commit,
228
+ };
229
+ const paths = [
230
+ ...new Set(
231
+ graph.elements.flatMap((node) =>
232
+ (node.sources || (node.source ? [node.source] : [])).map(
233
+ (source) => source.file,
234
+ ),
235
+ ),
236
+ ),
237
+ ];
238
+ const texts = read(paths);
239
+ const indexed = indexSources(graph, (file) => texts.get(file), undefined, {
240
+ resolveUniqueAnchors: true,
241
+ });
242
+ const id = createHash("sha256")
243
+ .update(
244
+ JSON.stringify({
245
+ baseCommit: commit,
246
+ dirty: false,
247
+ graph: { ...graph, generatedAt: "content" },
248
+ ...indexed,
249
+ }),
250
+ )
251
+ .digest("hex");
252
+ return {
253
+ schema: "fractal.code.v1",
254
+ id,
255
+ commit,
256
+ baseCommit: commit,
257
+ capturedAt: git(root, ["show", "-s", "--format=%cI", commit]).trim(),
258
+ graph,
259
+ ...indexed,
260
+ };
261
+ }
262
+
263
+ export function codeHistory(
264
+ root: string,
265
+ snapshot: CodeSnapshot,
266
+ elementId: string,
267
+ limit = 20,
268
+ skip = 0,
269
+ ) {
270
+ if (!Number.isSafeInteger(skip) || skip < 0 || skip > 10000)
271
+ throw Error("History offset exceeds the read budget");
272
+ const { within } = graphIndex(snapshot.graph);
273
+ const paths = [
274
+ ...new Set([
275
+ ...blockFiles(snapshot, elementId),
276
+ ...attachments(snapshot)
277
+ .filter((item) => within(item.elementId, elementId))
278
+ .map((item) => item.file),
279
+ ...relatedTests(snapshot.graph, elementId).map(
280
+ (test) => test.source.file,
281
+ ),
282
+ ]),
283
+ ];
284
+ return readPathHistory(root, paths, snapshot.baseCommit, limit, skip);
285
+ }
286
+ export function definitionHistory(
287
+ root: string,
288
+ graph: DefinitionGraph,
289
+ elementId: string,
290
+ anchor: string,
291
+ limit = 30,
292
+ skip = 0,
293
+ ) {
294
+ if (!graph.elements.some((node) => node.id === elementId))
295
+ throw Error("Unknown block");
296
+ const { within } = graphIndex(graph);
297
+ const paths = [
298
+ ...new Set([
299
+ ...graph.elements
300
+ .filter((node) => within(node.id, elementId))
301
+ .flatMap((node) =>
302
+ (node.sources || (node.source ? [node.source] : [])).map(
303
+ (source) => source.file,
304
+ ),
305
+ ),
306
+ ...attachments({ graph })
307
+ .filter((item) => within(item.elementId, elementId))
308
+ .map((item) => item.file),
309
+ ...relatedTests(graph, elementId).map((test) => test.source.file),
310
+ ]),
311
+ ];
312
+ return readPathHistory(root, paths, anchor, limit, skip);
313
+ }
314
+ function readPathHistory(
315
+ root: string,
316
+ paths: string[],
317
+ anchor: string,
318
+ limit: number,
319
+ skip: number,
320
+ ) {
321
+ if (
322
+ !Number.isSafeInteger(skip) ||
323
+ skip < 0 ||
324
+ skip > 10000 ||
325
+ paths.length > 2000 ||
326
+ paths.join("").length > 200000
327
+ )
328
+ throw Error("History exceeds the read budget");
329
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(anchor))
330
+ throw Error("Expected a resolved history commit");
331
+ if (!paths.length) return [];
332
+ const log = git(root, [
333
+ "log",
334
+ `-n${Math.min(50, Math.max(1, limit))}`,
335
+ `--skip=${skip}`,
336
+ "--format=%H%x00%cI%x00%s",
337
+ "--no-renames",
338
+ anchor,
339
+ "--",
340
+ ...paths,
341
+ ]);
342
+ return log
343
+ .trim()
344
+ .split("\n")
345
+ .filter(Boolean)
346
+ .map((line) => {
347
+ const [commit, date, subject] = line.split("\0");
348
+ return { commit, date, subject, association: "mapped-files" as const };
349
+ });
350
+ }
351
+ export function codeChanges(
352
+ root: string,
353
+ before: CodeSnapshot,
354
+ after: CodeSnapshot,
355
+ ) {
356
+ if (!before.commit || !after.commit)
357
+ throw new Error("Diff matching requires two committed snapshots");
358
+ const paths = [
359
+ ...new Set([
360
+ ...Object.keys(before.files),
361
+ ...Object.keys(after.files),
362
+ ...[before, after].flatMap((snapshot) =>
363
+ snapshot.graph.connections.flatMap((edge) =>
364
+ edge.id.startsWith("call-site:")
365
+ ? (edge.sources || (edge.sourceRef ? [edge.sourceRef] : [])).map(
366
+ (source) => source.file,
367
+ )
368
+ : [],
369
+ ),
370
+ ),
371
+ ...[before, after].flatMap((snapshot) =>
372
+ attachments(snapshot).map((item) => item.file),
373
+ ),
374
+ ]),
375
+ ];
376
+ if (paths.length > 2000 || paths.join("").length > 200000)
377
+ throw Error("Comparison source paths exceed the read budget");
378
+ if (!paths.length) return [];
379
+ // No rename similarity search, text conversion, external diff, blame, or source reparse.
380
+ const patch = git(root, [
381
+ "diff",
382
+ "--no-ext-diff",
383
+ "--no-textconv",
384
+ "--no-renames",
385
+ "--no-color",
386
+ "--unified=0",
387
+ before.commit,
388
+ after.commit,
389
+ "--",
390
+ ...paths,
391
+ ]);
392
+ const associations = {
393
+ before: attachments(before),
394
+ after: attachments(after),
395
+ };
396
+ return matchPatch(patch, before, after).map((change) => ({
397
+ ...change,
398
+ attachments: associations[change.side].filter(
399
+ (item) => item.file === change.file,
400
+ ),
401
+ }));
402
+ }
403
+ export function matchPatch(
404
+ patch: string,
405
+ before: CodeSnapshot,
406
+ after: CodeSnapshot,
407
+ ) {
408
+ const result: {
409
+ side: "before" | "after";
410
+ file: string;
411
+ start: number;
412
+ count: number;
413
+ digest: string;
414
+ matches: ReturnType<typeof locateCode>[];
415
+ }[] = [];
416
+ let oldFile = "",
417
+ newFile = "";
418
+ const lines = patch.split("\n");
419
+ for (let index = 0; index < lines.length; index++) {
420
+ const line = lines[index];
421
+ if (line.startsWith("--- ")) oldFile = line.slice(4).replace(/^a\//, "");
422
+ else if (line.startsWith("+++ "))
423
+ newFile = line.slice(4).replace(/^b\//, "");
424
+ else {
425
+ const hunk = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
426
+ if (!hunk) continue;
427
+ let end = index + 1;
428
+ while (
429
+ end < lines.length &&
430
+ !lines[end].startsWith("@@ ") &&
431
+ !lines[end].startsWith("diff --git ")
432
+ )
433
+ end++;
434
+ const digest = createHash("sha256")
435
+ .update(lines.slice(index + 1, end).join("\n"))
436
+ .digest("hex");
437
+ for (const [side, file, start, count, snapshot] of [
438
+ ["before", oldFile, +hunk[1], +(hunk[2] ?? 1), before],
439
+ ["after", newFile, +hunk[3], +(hunk[4] ?? 1), after],
440
+ ] as const) {
441
+ if (!count || file === "/dev/null") continue;
442
+ // Query range boundaries, not every changed line; capture every intersecting owner.
443
+ const ranges = snapshot.files[file]?.ranges || [];
444
+ const points = new Set([
445
+ start,
446
+ ...ranges
447
+ .filter((r) => r.start < start + count && r.end >= start)
448
+ .flatMap((r) => [
449
+ Math.max(start, r.start),
450
+ ...(r.end + 1 < start + count ? [r.end + 1] : []),
451
+ ]),
452
+ ]);
453
+ const matches = [...points].map((point) =>
454
+ locateCode(snapshot, file, point),
455
+ );
456
+ result.push({ side, file, start, count, matches, digest });
457
+ }
458
+ }
459
+ }
460
+ return result;
461
+ }
@@ -0,0 +1,43 @@
1
+ /** Lightweight Git identity reads shared by review links and source adapters. */
2
+ import { execFileSync } from "node:child_process";
3
+ export function readGit(root: string, args: string[]) {
4
+ return execFileSync(
5
+ "git",
6
+ ["--no-pager", "-c", "core.quotePath=false", ...args],
7
+ {
8
+ cwd: root,
9
+ encoding: "utf8",
10
+ maxBuffer: 16 * 1024 * 1024,
11
+ timeout: 15_000,
12
+ env: {
13
+ ...process.env,
14
+ GIT_OPTIONAL_LOCKS: "0",
15
+ GIT_LITERAL_PATHSPECS: "1",
16
+ },
17
+ stdio: ["ignore", "pipe", "pipe"],
18
+ },
19
+ );
20
+ }
21
+ /** Resolve only local refs. No shell, fetch, revision ranges, paths or option arguments. */
22
+ export function resolveComparisonRef(root: string, ref: string) {
23
+ if (
24
+ !ref ||
25
+ ref.length > 180 ||
26
+ !/^[A-Za-z0-9][A-Za-z0-9._/~-]*(?:\^\d*)?$/.test(ref) ||
27
+ ref.includes("..") ||
28
+ ref.includes("//") ||
29
+ ref.endsWith(".lock")
30
+ )
31
+ throw Error("Use a local branch, tag, HEAD~N or commit SHA.");
32
+ return readGit(root, [
33
+ "rev-parse",
34
+ "--verify",
35
+ "--end-of-options",
36
+ `${ref}^{commit}`,
37
+ ]).trim();
38
+ }
39
+ export function comparisonMergeBase(root: string, base: string, head: string) {
40
+ if (![base, head].every((ref) => /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(ref)))
41
+ throw Error("Expected resolved commit identities");
42
+ return readGit(root, ["merge-base", base, head]).trim();
43
+ }
@@ -0,0 +1,146 @@
1
+ /** One bounded native Git read. No source parsing, snapshot generation or history database. */
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import type { HistorySample } from "./map-activity";
5
+ import { inTimeWindow, type TimeWindow } from "./time-window";
6
+ import { latestHistoryAt } from "./activity-volume";
7
+ const execute = promisify(execFile);
8
+ export function parseHistory(output: string): HistorySample["commits"] {
9
+ const fields = output.split("\0"),
10
+ commits: HistorySample["commits"] = [];
11
+ let i = 0;
12
+ while (i < fields.length) {
13
+ if (fields[i] !== "") throw Error("Invalid Git history record");
14
+ i++;
15
+ if (i === fields.length) break;
16
+ const commit = fields[i++],
17
+ timestamp = fields[i++],
18
+ subject = fields[i++];
19
+ if (
20
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit) ||
21
+ !/^\d+$/.test(timestamp) ||
22
+ subject === undefined
23
+ )
24
+ throw Error("Invalid Git commit metadata");
25
+ const files: string[] = [];
26
+ const changes: NonNullable<HistorySample["commits"][number]["changes"]> =
27
+ [];
28
+ let first = true;
29
+ while (i < fields.length && fields[i] !== "") {
30
+ const file = fields[i++];
31
+ const record = first && file.startsWith("\n") ? file.slice(1) : file;
32
+ const stat = /^(\d+|-)\t(\d+|-)\t([\s\S]+)$/.exec(record);
33
+ if (stat) {
34
+ files.push(stat[3]);
35
+ changes.push({
36
+ path: stat[3],
37
+ added: Number(stat[1]) || 0,
38
+ deleted: Number(stat[2]) || 0,
39
+ binary: stat[1] === "-",
40
+ });
41
+ } else files.push(record);
42
+ first = false;
43
+ }
44
+ commits.push({
45
+ commit,
46
+ at: new Date(Number(timestamp) * 1000).toISOString(),
47
+ subject,
48
+ files,
49
+ ...(changes.length ? { changes } : {}),
50
+ });
51
+ }
52
+ return commits;
53
+ }
54
+ export async function historyActivity(
55
+ root: string,
56
+ files: string[],
57
+ days: number,
58
+ commit = "HEAD",
59
+ window?: TimeWindow,
60
+ ): Promise<HistorySample> {
61
+ if (!window && ![0, 7, 30, 90].includes(days))
62
+ throw Error("Choose latest commits, or 7, 30 or 90 days");
63
+ if (commit !== "HEAD" && !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit))
64
+ throw Error("Expected a full commit SHA");
65
+ if (files.length > 1000 || files.join("").length > 128000)
66
+ throw Error("Mapped source exceeds the history read budget");
67
+ const checkedAt = new Date().toISOString();
68
+ let windowEnd = window?.to || checkedAt;
69
+ if (!window && commit !== "HEAD" && days) {
70
+ const { stdout } = await execute(
71
+ "git",
72
+ ["show", "-s", "--format=%ct", commit],
73
+ {
74
+ cwd: root,
75
+ encoding: "utf8",
76
+ timeout: 8000,
77
+ maxBuffer: 1024,
78
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
79
+ },
80
+ );
81
+ if (!/^\d+\s*$/.test(stdout))
82
+ throw Error("Cannot determine historical activity window");
83
+ windowEnd = new Date(Number(stdout.trim()) * 1000).toISOString();
84
+ }
85
+ if (!files.length)
86
+ return {
87
+ checkedAt,
88
+ days,
89
+ partial: false,
90
+ commits: [],
91
+ ...(window ? { windowStart: window.from, windowEnd: window.to } : {}),
92
+ };
93
+ const [{ stdout }, latestAt] = await Promise.all([
94
+ execute(
95
+ "git",
96
+ [
97
+ "--no-pager",
98
+ "-c",
99
+ "core.fsmonitor=false",
100
+ "log",
101
+ "--format=%x00%H%x00%ct%x00%s",
102
+ "-z",
103
+ "--numstat",
104
+ "--no-renames",
105
+ ...(window ? ["--first-parent"] : []),
106
+ ...(window || days
107
+ ? [
108
+ `--since-as-filter=${window?.from || new Date(Date.parse(windowEnd) - days * 86400000).toISOString()}`,
109
+ `--until=${windowEnd}`,
110
+ ]
111
+ : []),
112
+ "--max-count=201",
113
+ commit,
114
+ "--",
115
+ ...files,
116
+ ],
117
+ {
118
+ cwd: root,
119
+ encoding: "utf8",
120
+ timeout: 8000,
121
+ maxBuffer: 2 * 1024 * 1024,
122
+ env: {
123
+ ...process.env,
124
+ GIT_OPTIONAL_LOCKS: "0",
125
+ GIT_LITERAL_PATHSPECS: "1",
126
+ },
127
+ },
128
+ ),
129
+ latestHistoryAt(root, files, commit),
130
+ ]);
131
+ const commits = parseHistory(stdout);
132
+ return {
133
+ checkedAt,
134
+ latestAt,
135
+ windowEnd: window?.to || (days ? windowEnd : commits[0]?.at || checkedAt),
136
+ ...(window ? { windowStart: window.from } : {}),
137
+ ...(!window && !days && commits.length
138
+ ? { windowStart: commits[Math.min(commits.length, 200) - 1].at }
139
+ : {}),
140
+ days,
141
+ partial: commits.length > 200,
142
+ commits: commits
143
+ .slice(0, 200)
144
+ .filter((c) => !window || inTimeWindow(c.at, window)),
145
+ };
146
+ }