@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,636 @@
1
+ /** Complete line accounting. Native Git supplies counts; ownership is evidence, never a file filter. */
2
+ import { createHash } from "node:crypto";
3
+ import { readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import type { DefinitionGraph } from "./model";
6
+ import type { TimeWindow } from "./time-window";
7
+ import type { CodeSnapshot } from "./code-model";
8
+ import { indexSources } from "./source-index";
9
+ import { ownedIntervals } from "./history-churn";
10
+ import { checkedPath } from "./workspace-notes";
11
+ import {
12
+ commitSha,
13
+ historyGit,
14
+ historyBlobs,
15
+ parseChangeCommits,
16
+ type GitChangeCommit,
17
+ type GitFileChange,
18
+ } from "./history-git";
19
+ import {
20
+ historicalOwnership,
21
+ fileAssociations,
22
+ type HistoricalOwnership,
23
+ } from "./history-ownership";
24
+ export type HistoryMode = "activity" | "difference";
25
+ export type HistoryBucket =
26
+ | "historical"
27
+ | "associated"
28
+ | "unassigned"
29
+ | "excluded";
30
+ export interface LineTotals {
31
+ added: number;
32
+ deleted: number;
33
+ }
34
+ export interface HistoryFileTotals extends LineTotals {
35
+ binary?: boolean;
36
+ reasons: string[];
37
+ owners: string[];
38
+ }
39
+ export interface HistoryLedger {
40
+ mode: HistoryMode;
41
+ base?: string;
42
+ head?: string;
43
+ totals: LineTotals & { files: number; binaryFiles: number; commits: number };
44
+ buckets: Record<HistoryBucket, LineTotals>;
45
+ files: Record<HistoryBucket, Record<string, HistoryFileTotals>>;
46
+ blocks: Record<string, LineTotals & { associated: number }>;
47
+ historicalRevisions: number;
48
+ missingRevisions: number;
49
+ commitOwners: Record<string, string[]>;
50
+ }
51
+ const zero = (): LineTotals => ({ added: 0, deleted: 0 });
52
+ const keys: HistoryBucket[] = [
53
+ "historical",
54
+ "associated",
55
+ "unassigned",
56
+ "excluded",
57
+ ];
58
+ const hash = (value: string) =>
59
+ createHash("sha256").update(value).digest("hex");
60
+ const metadata = new Map<string, Promise<GitChangeCommit[]>>();
61
+ const indexCache = new Map<string, ReturnType<typeof indexSources>>();
62
+ const patchCache = new Map<string, Promise<Hunk[]>>();
63
+ function limited<T>(map: Map<string, T>, key: string, value: T, limit: number) {
64
+ map.set(key, value);
65
+ if (map.size > limit) map.delete(map.keys().next().value!);
66
+ return value;
67
+ }
68
+ export function historyMode(value: string | null): HistoryMode {
69
+ if (value && value !== "activity" && value !== "difference")
70
+ throw Error("Choose activity over time or difference between revisions.");
71
+ return value === "difference" ? "difference" : "activity";
72
+ }
73
+ /** Mainline changes count merges once against their first parent. A hard budget fails explicitly, never truncates totals. */
74
+ export async function historyCommits(
75
+ root: string,
76
+ window: TimeWindow,
77
+ anchor: string,
78
+ ) {
79
+ if (!commitSha.test(anchor))
80
+ throw Error("Expected a resolved history commit");
81
+ const key = `${root}:${anchor}:${window.from}:${window.to}`;
82
+ let task = metadata.get(key);
83
+ if (!task) {
84
+ task = historyGit(root, [
85
+ "log",
86
+ "--first-parent",
87
+ "--diff-merges=first-parent",
88
+ "--root",
89
+ "--format=%x00%H%x00%P%x00%ct%x00%s",
90
+ "-z",
91
+ "--raw",
92
+ "--no-abbrev",
93
+ "--numstat",
94
+ "--no-renames",
95
+ `--since-as-filter=${window.from}`,
96
+ `--until=${new Date((Math.ceil(Date.parse(window.to) / 1000) - 1) * 1000).toISOString()}`,
97
+ "--max-count=10001",
98
+ anchor,
99
+ "--",
100
+ ]).then((buffer) => {
101
+ const records = parseChangeCommits(buffer.toString());
102
+ if (records.length > 10000)
103
+ throw Error(
104
+ "More than 10,000 mainline commits in this range. Choose a smaller period; totals were not truncated.",
105
+ );
106
+ const commits = records.filter(
107
+ (commit) =>
108
+ Date.parse(commit.at) >= Date.parse(window.from) &&
109
+ Date.parse(commit.at) < Date.parse(window.to),
110
+ );
111
+ if (commits.length > 10000)
112
+ throw Error(
113
+ "More than 10,000 mainline commits in this range. Choose a smaller period; totals were not truncated.",
114
+ );
115
+ return commits;
116
+ });
117
+ limited(metadata, key, task, 12);
118
+ task.catch(() => {
119
+ if (metadata.get(key) === task) metadata.delete(key);
120
+ });
121
+ }
122
+ return task;
123
+ }
124
+ export function historyPolicyKey(root: string) {
125
+ try {
126
+ return hash(readFileSync(join(root, "fractory.coverage.json"), "utf8"));
127
+ } catch {
128
+ return "none";
129
+ }
130
+ }
131
+ function decisions(root: string) {
132
+ try {
133
+ const text = readFileSync(join(root, "fractory.coverage.json"), "utf8");
134
+ if (Buffer.byteLength(text) > 1_000_000)
135
+ throw Error("Coverage policy exceeds its size limit");
136
+ const value = JSON.parse(text);
137
+ if (value.schema !== "fractory.coverage.v1")
138
+ return { files: [], exclusions: [] };
139
+ return {
140
+ files: (value.files || []) as {
141
+ file: string;
142
+ digest: string;
143
+ reason: string;
144
+ }[],
145
+ exclusions: (value.exclusions || []) as {
146
+ file: string;
147
+ start: number;
148
+ end: number;
149
+ digest: string;
150
+ }[],
151
+ };
152
+ } catch {
153
+ return { files: [], exclusions: [] };
154
+ }
155
+ }
156
+ /** These named view exclusions are still included in repository totals and browseable by path. Other source languages stay unassigned, not excluded. */
157
+ export function historyExcludedReason(file: string) {
158
+ if (
159
+ /(^|\/)(node_modules|vendor|dist|\.next|__generated__|generated|coverage)(\/|$)|\.(generated|gen|d)\.[cm]?[jt]sx?$/.test(
160
+ file,
161
+ )
162
+ )
163
+ return "Dependencies and generated output";
164
+ if (
165
+ /(^|\/)(__tests__|__mocks__|tests?|e2e|fixtures)(\/|$)|\.(test|spec|vitest|bench|stories)\.[cm]?[jt]sx?$/.test(
166
+ file,
167
+ )
168
+ )
169
+ return "Tests, fixtures and benchmarks";
170
+ if (/(^|\/)(?:docs?|documentation)\/|\.(?:md|mdx|rst)$/i.test(file))
171
+ return "Documentation";
172
+ if (
173
+ /(^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock)$/.test(
174
+ file,
175
+ )
176
+ )
177
+ return "Dependency lockfiles";
178
+ }
179
+ type Span = {
180
+ start: number;
181
+ end: number;
182
+ owner?: string;
183
+ bucket: HistoryBucket;
184
+ reason: string;
185
+ };
186
+ type Hunk = {
187
+ oldStart: number;
188
+ oldCount: number;
189
+ newStart: number;
190
+ newCount: number;
191
+ };
192
+ function hunks(patch: string) {
193
+ return [
194
+ ...patch.matchAll(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm),
195
+ ].map((match) => ({
196
+ oldStart: +match[1],
197
+ oldCount: +(match[2] ?? 1),
198
+ newStart: +match[3],
199
+ newCount: +(match[4] ?? 1),
200
+ }));
201
+ }
202
+
203
+ export async function historyLedger(
204
+ root: string,
205
+ graph: DefinitionGraph,
206
+ window: TimeWindow,
207
+ anchor: string,
208
+ mode: HistoryMode = "activity",
209
+ archive?: string,
210
+ ) {
211
+ const commits = await historyCommits(root, window, anchor);
212
+ const boundary = async (time: string) =>
213
+ (
214
+ await historyGit(root, [
215
+ "rev-list",
216
+ "--first-parent",
217
+ "-1",
218
+ `--before=${new Date((Math.ceil(Date.parse(time) / 1000) - 1) * 1000).toISOString()}`,
219
+ anchor,
220
+ ])
221
+ )
222
+ .toString()
223
+ .trim() || undefined;
224
+ const [base, head] = await Promise.all([
225
+ boundary(window.from),
226
+ boundary(window.to),
227
+ ]);
228
+ let changes = commits;
229
+ if (mode === "difference") {
230
+ const empty =
231
+ !base && head
232
+ ? (await historyGit(root, ["hash-object", "-t", "tree", "--stdin"], ""))
233
+ .toString()
234
+ .trim()
235
+ : undefined;
236
+ const text =
237
+ head && base !== head
238
+ ? (
239
+ await historyGit(root, [
240
+ "diff",
241
+ "--no-ext-diff",
242
+ "--no-textconv",
243
+ "--no-renames",
244
+ "--raw",
245
+ "--no-abbrev",
246
+ "--numstat",
247
+ "-z",
248
+ base || empty!,
249
+ head,
250
+ "--",
251
+ ])
252
+ ).toString()
253
+ : "";
254
+ const prefix = `\0${head || anchor}\0${base || ""}\0${Math.floor(Date.parse(window.to) / 1000)}\0Difference\0`;
255
+ changes = text ? parseChangeCommits(prefix + text) : [];
256
+ }
257
+ const revisions = [
258
+ ...new Set(
259
+ changes
260
+ .flatMap((change) => [change.parent, change.commit])
261
+ .filter((id): id is string => !!id),
262
+ ),
263
+ ];
264
+ const historical = await historicalOwnership(root, revisions, archive);
265
+ const currentFiles = fileAssociations(graph),
266
+ policy = decisions(root);
267
+ const fullDiscards = new Map(policy.files.map((file) => [file.file, file]));
268
+ // Content-pinned decisions can be matched to Git blob IDs without downloading
269
+ // every past version of a discarded file. Changed/deleted decisions stay unassigned.
270
+ const approvedBlobs = new Map<string, string>();
271
+ const objectFormat = (
272
+ await historyGit(root, ["rev-parse", "--show-object-format"])
273
+ )
274
+ .toString()
275
+ .trim();
276
+ if (!["sha1", "sha256"].includes(objectFormat))
277
+ throw Error("Unsupported Git object format");
278
+ const changedPaths = new Set(
279
+ changes.flatMap((change) => change.files.map((file) => file.path)),
280
+ );
281
+ for (const decision of policy.files)
282
+ if (changedPaths.has(decision.file)) {
283
+ try {
284
+ const text = readFileSync(checkedPath(root, decision.file), "utf8");
285
+ if (
286
+ Buffer.byteLength(text) <= 4 * 1024 * 1024 &&
287
+ hash(text) === decision.digest
288
+ )
289
+ approvedBlobs.set(
290
+ decision.file,
291
+ createHash(objectFormat)
292
+ .update(`blob ${Buffer.byteLength(text)}\0`)
293
+ .update(text)
294
+ .digest("hex"),
295
+ );
296
+ } catch {
297
+ /* An unavailable or changed discard is not applied to historical source. */
298
+ }
299
+ }
300
+ const regionDiscards = new Map<string, typeof policy.exclusions>();
301
+ for (const item of policy.exclusions)
302
+ regionDiscards.set(item.file, [
303
+ ...(regionDiscards.get(item.file) || []),
304
+ item,
305
+ ]);
306
+ const sourceObjects = new Set<string>();
307
+ const historicalFiles = new WeakMap<
308
+ DefinitionGraph,
309
+ ReturnType<typeof fileAssociations>
310
+ >();
311
+ const fileIndex = (definition: DefinitionGraph) => {
312
+ let files = historicalFiles.get(definition);
313
+ if (!files) {
314
+ files = fileAssociations(definition);
315
+ historicalFiles.set(definition, files);
316
+ }
317
+ return files;
318
+ };
319
+ for (const change of changes)
320
+ for (const file of change.files)
321
+ for (const [revision, blob] of [
322
+ [change.parent, file.beforeBlob],
323
+ [change.commit, file.afterBlob],
324
+ ] as const) {
325
+ if (!blob || /^0+$/.test(blob) || file.binary) continue;
326
+ const owner = revision && historical.get(revision);
327
+ if (
328
+ (owner &&
329
+ !owner.snapshot &&
330
+ !historyExcludedReason(file.path) &&
331
+ fileIndex(owner.graph).has(file.path)) ||
332
+ regionDiscards.has(file.path)
333
+ )
334
+ sourceObjects.add(blob);
335
+ }
336
+ const texts = await historyBlobs(root, [...sourceObjects]);
337
+ const result: HistoryLedger = {
338
+ mode,
339
+ base,
340
+ head,
341
+ totals: {
342
+ ...zero(),
343
+ files: new Set(
344
+ changes.flatMap((change) => change.files.map((file) => file.path)),
345
+ ).size,
346
+ binaryFiles: new Set(
347
+ changes.flatMap((change) =>
348
+ change.files.filter((file) => file.binary).map((file) => file.path),
349
+ ),
350
+ ).size,
351
+ commits: commits.length,
352
+ },
353
+ buckets: Object.fromEntries(
354
+ keys.map((key) => [key, zero()]),
355
+ ) as HistoryLedger["buckets"],
356
+ files: Object.fromEntries(
357
+ keys.map((key) => [key, Object.create(null)]),
358
+ ) as HistoryLedger["files"],
359
+ blocks: Object.create(null),
360
+ historicalRevisions: historical.size,
361
+ missingRevisions: revisions.length - historical.size,
362
+ commitOwners: Object.create(null),
363
+ };
364
+ const displayed = new Map(graph.elements.map((node) => [node.id, node]));
365
+ const ancestors = (id: string) => {
366
+ const ids: string[] = [],
367
+ seen = new Set<string>();
368
+ let node = displayed.get(id);
369
+ while (node && !seen.has(node.id)) {
370
+ seen.add(node.id);
371
+ ids.push(node.id);
372
+ node = displayed.get(node.parent || "");
373
+ }
374
+ return ids;
375
+ };
376
+ const displayOwner = (id: string, source: DefinitionGraph) => {
377
+ const byId = new Map(source.elements.map((node) => [node.id, node])),
378
+ seen = new Set<string>();
379
+ let node = byId.get(id);
380
+ while (node && !seen.has(node.id)) {
381
+ seen.add(node.id);
382
+ const target = graph.aliases?.[node.id] || node.id;
383
+ if (displayed.has(target)) return target;
384
+ node = byId.get(node.parent || "");
385
+ }
386
+ };
387
+ function association(source: DefinitionGraph, file: string) {
388
+ return fileIndex(source).get(file);
389
+ }
390
+ let activeCommit = "";
391
+ function add(
392
+ file: GitFileChange,
393
+ side: "added" | "deleted",
394
+ count: number,
395
+ bucket: HistoryBucket,
396
+ reason: string,
397
+ owner?: string,
398
+ ) {
399
+ if (!count && !file.binary) return;
400
+ result.buckets[bucket][side] += count;
401
+ const entry = (result.files[bucket][file.path] ||= {
402
+ ...zero(),
403
+ reasons: [],
404
+ owners: [],
405
+ });
406
+ entry[side] += count;
407
+ if (file.binary) entry.binary = true;
408
+ if (!entry.reasons.includes(reason)) entry.reasons.push(reason);
409
+ if (owner && !entry.owners.includes(owner)) entry.owners.push(owner);
410
+ if (owner)
411
+ for (const id of ancestors(owner)) {
412
+ const owners = (result.commitOwners[activeCommit] ||= []);
413
+ if (!owners.includes(id)) owners.push(id);
414
+ const cell = (result.blocks[id] ||= { ...zero(), associated: 0 });
415
+ cell[side] += count;
416
+ if (bucket === "associated") cell.associated += count;
417
+ }
418
+ }
419
+ function ranges(
420
+ owner: HistoricalOwnership | undefined,
421
+ file: GitFileChange,
422
+ blob?: string,
423
+ ): Span[] {
424
+ if (!owner) return [];
425
+ let ranges = owner.snapshot?.files[file.path]?.ranges;
426
+ if (!ranges && blob && texts.has(blob)) {
427
+ const elements = owner.graph.elements.filter((node) =>
428
+ (node.sources || (node.source ? [node.source] : [])).some(
429
+ (ref) => ref.file === file.path,
430
+ ),
431
+ );
432
+ const key = hash(JSON.stringify([blob, file.path, elements]));
433
+ let indexed = indexCache.get(key);
434
+ if (!indexed)
435
+ indexed = limited(
436
+ indexCache,
437
+ key,
438
+ indexSources({ ...owner.graph, elements }, (path) =>
439
+ path === file.path ? texts.get(blob) : undefined,
440
+ ),
441
+ 1000,
442
+ );
443
+ ranges = indexed.files[file.path]?.ranges;
444
+ }
445
+ return ownedIntervals(owner.graph, ranges || [])
446
+ .filter((part) => part.owners.length)
447
+ .flatMap((part) => {
448
+ const target = displayOwner(part.owners[0], owner.graph);
449
+ return target
450
+ ? [
451
+ {
452
+ start: part.start,
453
+ end: part.end,
454
+ owner: target,
455
+ bucket: "historical" as const,
456
+ reason:
457
+ target === part.owners[0]
458
+ ? "Ownership from this Git revision"
459
+ : "Historical owner rolled up to its surviving parent",
460
+ },
461
+ ]
462
+ : [];
463
+ });
464
+ }
465
+ function fallback(revision: string | undefined, path: string) {
466
+ const past = revision && historical.get(revision);
467
+ const source = past ? past.graph : graph;
468
+ const id = past ? association(source, path) : currentFiles.get(path);
469
+ const target = id && displayOwner(id, source);
470
+ return target
471
+ ? {
472
+ owner: target,
473
+ bucket: "associated" as const,
474
+ reason: past
475
+ ? "File-level association from this revision; exact changed lines are not mapped"
476
+ : "Current-map file association; no historical ownership was captured",
477
+ }
478
+ : {
479
+ bucket: "unassigned" as const,
480
+ reason: past
481
+ ? "No owner in this revision's map"
482
+ : "No historical map or current file association",
483
+ };
484
+ }
485
+ // Only historical indexes or pinned region exclusions need source hunks. Ordinary history uses numstat alone.
486
+ for (const change of changes)
487
+ for (const file of change.files) {
488
+ activeCommit = change.commit;
489
+ result.totals.added += file.added;
490
+ result.totals.deleted += file.deleted;
491
+ const oldOwner = change.parent && historical.get(change.parent),
492
+ newOwner = historical.get(change.commit);
493
+ const before = ranges(oldOwner || undefined, file, file.beforeBlob),
494
+ after = ranges(newOwner, file, file.afterBlob);
495
+ const explicit = fullDiscards.get(file.path);
496
+ const excluded = historyExcludedReason(file.path);
497
+ const pinned = (blob?: string) =>
498
+ !!explicit && !!blob && approvedBlobs.get(file.path) === blob;
499
+ const exclusions = (blob?: string): Span[] =>
500
+ !blob || !texts.has(blob)
501
+ ? []
502
+ : (regionDiscards.get(file.path) || [])
503
+ .filter(
504
+ (item) =>
505
+ hash(
506
+ texts
507
+ .get(blob)!
508
+ .split(/\r?\n/)
509
+ .slice(item.start - 1, item.end)
510
+ .join("\n"),
511
+ ) === item.digest,
512
+ )
513
+ .map((item) => ({
514
+ start: item.start,
515
+ end: item.end,
516
+ bucket: "excluded",
517
+ reason:
518
+ "Explicitly discarded source region; content fingerprint matches",
519
+ }));
520
+ const oldExclusions = exclusions(file.beforeBlob),
521
+ newExclusions = exclusions(file.afterBlob);
522
+ let spans: Hunk[] = [];
523
+ if (
524
+ !file.binary &&
525
+ !excluded &&
526
+ ((!pinned(file.beforeBlob) &&
527
+ (before.length || oldExclusions.length)) ||
528
+ (!pinned(file.afterBlob) && (after.length || newExclusions.length)))
529
+ ) {
530
+ const empty = !change.parent
531
+ ? (
532
+ await historyGit(
533
+ root,
534
+ ["hash-object", "-t", "tree", "--stdin"],
535
+ "",
536
+ )
537
+ )
538
+ .toString()
539
+ .trim()
540
+ : undefined;
541
+ const key = `${root}:${change.parent || "empty"}:${change.commit}:${file.path}`;
542
+ let patch = patchCache.get(key);
543
+ if (!patch)
544
+ patch = limited(
545
+ patchCache,
546
+ key,
547
+ historyGit(root, [
548
+ "diff",
549
+ "--no-ext-diff",
550
+ "--no-textconv",
551
+ "--no-renames",
552
+ "--no-color",
553
+ "--unified=0",
554
+ change.parent || empty!,
555
+ change.commit,
556
+ "--",
557
+ file.path,
558
+ ]).then((value) => hunks(value.toString())),
559
+ 256,
560
+ );
561
+ spans = await patch;
562
+ }
563
+ for (const side of ["added", "deleted"] as const) {
564
+ const count = file[side],
565
+ isOld = side === "deleted",
566
+ revision = isOld ? change.parent : change.commit,
567
+ blob = isOld ? file.beforeBlob : file.afterBlob;
568
+ if (excluded || pinned(blob)) {
569
+ add(file, side, count, "excluded", excluded || explicit!.reason);
570
+ continue;
571
+ }
572
+ const candidates = [
573
+ ...(isOld ? oldExclusions : newExclusions),
574
+ ...(isOld ? before : after),
575
+ ];
576
+ let assigned = 0;
577
+ for (const hunk of spans) {
578
+ const start = isOld ? hunk.oldStart : hunk.newStart,
579
+ length = isOld ? hunk.oldCount : hunk.newCount;
580
+ const points = [
581
+ ...new Set([
582
+ start,
583
+ start + length,
584
+ ...candidates.flatMap((part) => [
585
+ Math.max(start, part.start),
586
+ Math.min(start + length, part.end + 1),
587
+ ]),
588
+ ]),
589
+ ]
590
+ .filter((point) => point >= start && point <= start + length)
591
+ .sort((a, b) => a - b);
592
+ for (let i = 0; i < points.length - 1; i++) {
593
+ const part = candidates.find(
594
+ (part) => part.start <= points[i] && part.end >= points[i],
595
+ );
596
+ if (part) {
597
+ const lines = points[i + 1] - points[i];
598
+ assigned += lines;
599
+ add(file, side, lines, part.bucket, part.reason, part.owner);
600
+ }
601
+ }
602
+ }
603
+ if (assigned > count)
604
+ throw Error(
605
+ "Git hunk accounting exceeded numstat; no totals were published",
606
+ );
607
+ if (count > assigned || file.binary) {
608
+ const target = fallback(revision, file.path);
609
+ add(
610
+ file,
611
+ side,
612
+ count - assigned,
613
+ target.bucket,
614
+ target.reason,
615
+ "owner" in target ? target.owner : undefined,
616
+ );
617
+ }
618
+ }
619
+ }
620
+ for (const side of ["added", "deleted"] as const)
621
+ if (
622
+ keys.reduce((sum, key) => sum + result.buckets[key][side], 0) !==
623
+ result.totals[side]
624
+ )
625
+ throw Error("Incomplete Git accounting; no totals were published");
626
+ const latestAt =
627
+ commits[0]?.at ||
628
+ new Date(
629
+ Number(
630
+ (await historyGit(root, ["show", "-s", "--format=%ct", anchor]))
631
+ .toString()
632
+ .trim(),
633
+ ) * 1000,
634
+ ).toISOString();
635
+ return { ledger: result, commits, latestAt };
636
+ }