@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,450 @@
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 { indexSources } from "./source-index.js";
6
+ import { ownedIntervals } from "./history-churn.js";
7
+ import { checkedPath } from "./workspace-notes.js";
8
+ import { commitSha, historyGit, historyBlobs, parseChangeCommits, } from "./history-git.js";
9
+ import { historicalOwnership, fileAssociations, } from "./history-ownership.js";
10
+ const zero = () => ({ added: 0, deleted: 0 });
11
+ const keys = [
12
+ "historical",
13
+ "associated",
14
+ "unassigned",
15
+ "excluded",
16
+ ];
17
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
18
+ const metadata = new Map();
19
+ const indexCache = new Map();
20
+ const patchCache = new Map();
21
+ function limited(map, key, value, limit) {
22
+ map.set(key, value);
23
+ if (map.size > limit)
24
+ map.delete(map.keys().next().value);
25
+ return value;
26
+ }
27
+ export function historyMode(value) {
28
+ if (value && value !== "activity" && value !== "difference")
29
+ throw Error("Choose activity over time or difference between revisions.");
30
+ return value === "difference" ? "difference" : "activity";
31
+ }
32
+ /** Mainline changes count merges once against their first parent. A hard budget fails explicitly, never truncates totals. */
33
+ export async function historyCommits(root, window, anchor) {
34
+ if (!commitSha.test(anchor))
35
+ throw Error("Expected a resolved history commit");
36
+ const key = `${root}:${anchor}:${window.from}:${window.to}`;
37
+ let task = metadata.get(key);
38
+ if (!task) {
39
+ task = historyGit(root, [
40
+ "log",
41
+ "--first-parent",
42
+ "--diff-merges=first-parent",
43
+ "--root",
44
+ "--format=%x00%H%x00%P%x00%ct%x00%s",
45
+ "-z",
46
+ "--raw",
47
+ "--no-abbrev",
48
+ "--numstat",
49
+ "--no-renames",
50
+ `--since-as-filter=${window.from}`,
51
+ `--until=${new Date((Math.ceil(Date.parse(window.to) / 1000) - 1) * 1000).toISOString()}`,
52
+ "--max-count=10001",
53
+ anchor,
54
+ "--",
55
+ ]).then((buffer) => {
56
+ const records = parseChangeCommits(buffer.toString());
57
+ if (records.length > 10000)
58
+ throw Error("More than 10,000 mainline commits in this range. Choose a smaller period; totals were not truncated.");
59
+ const commits = records.filter((commit) => Date.parse(commit.at) >= Date.parse(window.from) &&
60
+ Date.parse(commit.at) < Date.parse(window.to));
61
+ if (commits.length > 10000)
62
+ throw Error("More than 10,000 mainline commits in this range. Choose a smaller period; totals were not truncated.");
63
+ return commits;
64
+ });
65
+ limited(metadata, key, task, 12);
66
+ task.catch(() => {
67
+ if (metadata.get(key) === task)
68
+ metadata.delete(key);
69
+ });
70
+ }
71
+ return task;
72
+ }
73
+ export function historyPolicyKey(root) {
74
+ try {
75
+ return hash(readFileSync(join(root, "fractory.coverage.json"), "utf8"));
76
+ }
77
+ catch {
78
+ return "none";
79
+ }
80
+ }
81
+ function decisions(root) {
82
+ try {
83
+ const text = readFileSync(join(root, "fractory.coverage.json"), "utf8");
84
+ if (Buffer.byteLength(text) > 1_000_000)
85
+ throw Error("Coverage policy exceeds its size limit");
86
+ const value = JSON.parse(text);
87
+ if (value.schema !== "fractory.coverage.v1")
88
+ return { files: [], exclusions: [] };
89
+ return {
90
+ files: (value.files || []),
91
+ exclusions: (value.exclusions || []),
92
+ };
93
+ }
94
+ catch {
95
+ return { files: [], exclusions: [] };
96
+ }
97
+ }
98
+ /** These named view exclusions are still included in repository totals and browseable by path. Other source languages stay unassigned, not excluded. */
99
+ export function historyExcludedReason(file) {
100
+ if (/(^|\/)(node_modules|vendor|dist|\.next|__generated__|generated|coverage)(\/|$)|\.(generated|gen|d)\.[cm]?[jt]sx?$/.test(file))
101
+ return "Dependencies and generated output";
102
+ if (/(^|\/)(__tests__|__mocks__|tests?|e2e|fixtures)(\/|$)|\.(test|spec|vitest|bench|stories)\.[cm]?[jt]sx?$/.test(file))
103
+ return "Tests, fixtures and benchmarks";
104
+ if (/(^|\/)(?:docs?|documentation)\/|\.(?:md|mdx|rst)$/i.test(file))
105
+ return "Documentation";
106
+ if (/(^|\/)(?:bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock)$/.test(file))
107
+ return "Dependency lockfiles";
108
+ }
109
+ function hunks(patch) {
110
+ return [
111
+ ...patch.matchAll(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm),
112
+ ].map((match) => ({
113
+ oldStart: +match[1],
114
+ oldCount: +(match[2] ?? 1),
115
+ newStart: +match[3],
116
+ newCount: +(match[4] ?? 1),
117
+ }));
118
+ }
119
+ export async function historyLedger(root, graph, window, anchor, mode = "activity", archive) {
120
+ const commits = await historyCommits(root, window, anchor);
121
+ const boundary = async (time) => (await historyGit(root, [
122
+ "rev-list",
123
+ "--first-parent",
124
+ "-1",
125
+ `--before=${new Date((Math.ceil(Date.parse(time) / 1000) - 1) * 1000).toISOString()}`,
126
+ anchor,
127
+ ]))
128
+ .toString()
129
+ .trim() || undefined;
130
+ const [base, head] = await Promise.all([
131
+ boundary(window.from),
132
+ boundary(window.to),
133
+ ]);
134
+ let changes = commits;
135
+ if (mode === "difference") {
136
+ const empty = !base && head
137
+ ? (await historyGit(root, ["hash-object", "-t", "tree", "--stdin"], ""))
138
+ .toString()
139
+ .trim()
140
+ : undefined;
141
+ const text = head && base !== head
142
+ ? (await historyGit(root, [
143
+ "diff",
144
+ "--no-ext-diff",
145
+ "--no-textconv",
146
+ "--no-renames",
147
+ "--raw",
148
+ "--no-abbrev",
149
+ "--numstat",
150
+ "-z",
151
+ base || empty,
152
+ head,
153
+ "--",
154
+ ])).toString()
155
+ : "";
156
+ const prefix = `\0${head || anchor}\0${base || ""}\0${Math.floor(Date.parse(window.to) / 1000)}\0Difference\0`;
157
+ changes = text ? parseChangeCommits(prefix + text) : [];
158
+ }
159
+ const revisions = [
160
+ ...new Set(changes
161
+ .flatMap((change) => [change.parent, change.commit])
162
+ .filter((id) => !!id)),
163
+ ];
164
+ const historical = await historicalOwnership(root, revisions, archive);
165
+ const currentFiles = fileAssociations(graph), policy = decisions(root);
166
+ const fullDiscards = new Map(policy.files.map((file) => [file.file, file]));
167
+ // Content-pinned decisions can be matched to Git blob IDs without downloading
168
+ // every past version of a discarded file. Changed/deleted decisions stay unassigned.
169
+ const approvedBlobs = new Map();
170
+ const objectFormat = (await historyGit(root, ["rev-parse", "--show-object-format"]))
171
+ .toString()
172
+ .trim();
173
+ if (!["sha1", "sha256"].includes(objectFormat))
174
+ throw Error("Unsupported Git object format");
175
+ const changedPaths = new Set(changes.flatMap((change) => change.files.map((file) => file.path)));
176
+ for (const decision of policy.files)
177
+ if (changedPaths.has(decision.file)) {
178
+ try {
179
+ const text = readFileSync(checkedPath(root, decision.file), "utf8");
180
+ if (Buffer.byteLength(text) <= 4 * 1024 * 1024 &&
181
+ hash(text) === decision.digest)
182
+ approvedBlobs.set(decision.file, createHash(objectFormat)
183
+ .update(`blob ${Buffer.byteLength(text)}\0`)
184
+ .update(text)
185
+ .digest("hex"));
186
+ }
187
+ catch {
188
+ /* An unavailable or changed discard is not applied to historical source. */
189
+ }
190
+ }
191
+ const regionDiscards = new Map();
192
+ for (const item of policy.exclusions)
193
+ regionDiscards.set(item.file, [
194
+ ...(regionDiscards.get(item.file) || []),
195
+ item,
196
+ ]);
197
+ const sourceObjects = new Set();
198
+ const historicalFiles = new WeakMap();
199
+ const fileIndex = (definition) => {
200
+ let files = historicalFiles.get(definition);
201
+ if (!files) {
202
+ files = fileAssociations(definition);
203
+ historicalFiles.set(definition, files);
204
+ }
205
+ return files;
206
+ };
207
+ for (const change of changes)
208
+ for (const file of change.files)
209
+ for (const [revision, blob] of [
210
+ [change.parent, file.beforeBlob],
211
+ [change.commit, file.afterBlob],
212
+ ]) {
213
+ if (!blob || /^0+$/.test(blob) || file.binary)
214
+ continue;
215
+ const owner = revision && historical.get(revision);
216
+ if ((owner &&
217
+ !owner.snapshot &&
218
+ !historyExcludedReason(file.path) &&
219
+ fileIndex(owner.graph).has(file.path)) ||
220
+ regionDiscards.has(file.path))
221
+ sourceObjects.add(blob);
222
+ }
223
+ const texts = await historyBlobs(root, [...sourceObjects]);
224
+ const result = {
225
+ mode,
226
+ base,
227
+ head,
228
+ totals: {
229
+ ...zero(),
230
+ files: new Set(changes.flatMap((change) => change.files.map((file) => file.path))).size,
231
+ binaryFiles: new Set(changes.flatMap((change) => change.files.filter((file) => file.binary).map((file) => file.path))).size,
232
+ commits: commits.length,
233
+ },
234
+ buckets: Object.fromEntries(keys.map((key) => [key, zero()])),
235
+ files: Object.fromEntries(keys.map((key) => [key, Object.create(null)])),
236
+ blocks: Object.create(null),
237
+ historicalRevisions: historical.size,
238
+ missingRevisions: revisions.length - historical.size,
239
+ commitOwners: Object.create(null),
240
+ };
241
+ const displayed = new Map(graph.elements.map((node) => [node.id, node]));
242
+ const ancestors = (id) => {
243
+ const ids = [], seen = new Set();
244
+ let node = displayed.get(id);
245
+ while (node && !seen.has(node.id)) {
246
+ seen.add(node.id);
247
+ ids.push(node.id);
248
+ node = displayed.get(node.parent || "");
249
+ }
250
+ return ids;
251
+ };
252
+ const displayOwner = (id, source) => {
253
+ const byId = new Map(source.elements.map((node) => [node.id, node])), seen = new Set();
254
+ let node = byId.get(id);
255
+ while (node && !seen.has(node.id)) {
256
+ seen.add(node.id);
257
+ const target = graph.aliases?.[node.id] || node.id;
258
+ if (displayed.has(target))
259
+ return target;
260
+ node = byId.get(node.parent || "");
261
+ }
262
+ };
263
+ function association(source, file) {
264
+ return fileIndex(source).get(file);
265
+ }
266
+ let activeCommit = "";
267
+ function add(file, side, count, bucket, reason, owner) {
268
+ if (!count && !file.binary)
269
+ return;
270
+ result.buckets[bucket][side] += count;
271
+ const entry = (result.files[bucket][file.path] ||= {
272
+ ...zero(),
273
+ reasons: [],
274
+ owners: [],
275
+ });
276
+ entry[side] += count;
277
+ if (file.binary)
278
+ entry.binary = true;
279
+ if (!entry.reasons.includes(reason))
280
+ entry.reasons.push(reason);
281
+ if (owner && !entry.owners.includes(owner))
282
+ entry.owners.push(owner);
283
+ if (owner)
284
+ for (const id of ancestors(owner)) {
285
+ const owners = (result.commitOwners[activeCommit] ||= []);
286
+ if (!owners.includes(id))
287
+ owners.push(id);
288
+ const cell = (result.blocks[id] ||= { ...zero(), associated: 0 });
289
+ cell[side] += count;
290
+ if (bucket === "associated")
291
+ cell.associated += count;
292
+ }
293
+ }
294
+ function ranges(owner, file, blob) {
295
+ if (!owner)
296
+ return [];
297
+ let ranges = owner.snapshot?.files[file.path]?.ranges;
298
+ if (!ranges && blob && texts.has(blob)) {
299
+ const elements = owner.graph.elements.filter((node) => (node.sources || (node.source ? [node.source] : [])).some((ref) => ref.file === file.path));
300
+ const key = hash(JSON.stringify([blob, file.path, elements]));
301
+ let indexed = indexCache.get(key);
302
+ if (!indexed)
303
+ indexed = limited(indexCache, key, indexSources({ ...owner.graph, elements }, (path) => path === file.path ? texts.get(blob) : undefined), 1000);
304
+ ranges = indexed.files[file.path]?.ranges;
305
+ }
306
+ return ownedIntervals(owner.graph, ranges || [])
307
+ .filter((part) => part.owners.length)
308
+ .flatMap((part) => {
309
+ const target = displayOwner(part.owners[0], owner.graph);
310
+ return target
311
+ ? [
312
+ {
313
+ start: part.start,
314
+ end: part.end,
315
+ owner: target,
316
+ bucket: "historical",
317
+ reason: target === part.owners[0]
318
+ ? "Ownership from this Git revision"
319
+ : "Historical owner rolled up to its surviving parent",
320
+ },
321
+ ]
322
+ : [];
323
+ });
324
+ }
325
+ function fallback(revision, path) {
326
+ const past = revision && historical.get(revision);
327
+ const source = past ? past.graph : graph;
328
+ const id = past ? association(source, path) : currentFiles.get(path);
329
+ const target = id && displayOwner(id, source);
330
+ return target
331
+ ? {
332
+ owner: target,
333
+ bucket: "associated",
334
+ reason: past
335
+ ? "File-level association from this revision; exact changed lines are not mapped"
336
+ : "Current-map file association; no historical ownership was captured",
337
+ }
338
+ : {
339
+ bucket: "unassigned",
340
+ reason: past
341
+ ? "No owner in this revision's map"
342
+ : "No historical map or current file association",
343
+ };
344
+ }
345
+ // Only historical indexes or pinned region exclusions need source hunks. Ordinary history uses numstat alone.
346
+ for (const change of changes)
347
+ for (const file of change.files) {
348
+ activeCommit = change.commit;
349
+ result.totals.added += file.added;
350
+ result.totals.deleted += file.deleted;
351
+ const oldOwner = change.parent && historical.get(change.parent), newOwner = historical.get(change.commit);
352
+ const before = ranges(oldOwner || undefined, file, file.beforeBlob), after = ranges(newOwner, file, file.afterBlob);
353
+ const explicit = fullDiscards.get(file.path);
354
+ const excluded = historyExcludedReason(file.path);
355
+ const pinned = (blob) => !!explicit && !!blob && approvedBlobs.get(file.path) === blob;
356
+ const exclusions = (blob) => !blob || !texts.has(blob)
357
+ ? []
358
+ : (regionDiscards.get(file.path) || [])
359
+ .filter((item) => hash(texts
360
+ .get(blob)
361
+ .split(/\r?\n/)
362
+ .slice(item.start - 1, item.end)
363
+ .join("\n")) === item.digest)
364
+ .map((item) => ({
365
+ start: item.start,
366
+ end: item.end,
367
+ bucket: "excluded",
368
+ reason: "Explicitly discarded source region; content fingerprint matches",
369
+ }));
370
+ const oldExclusions = exclusions(file.beforeBlob), newExclusions = exclusions(file.afterBlob);
371
+ let spans = [];
372
+ if (!file.binary &&
373
+ !excluded &&
374
+ ((!pinned(file.beforeBlob) &&
375
+ (before.length || oldExclusions.length)) ||
376
+ (!pinned(file.afterBlob) && (after.length || newExclusions.length)))) {
377
+ const empty = !change.parent
378
+ ? (await historyGit(root, ["hash-object", "-t", "tree", "--stdin"], ""))
379
+ .toString()
380
+ .trim()
381
+ : undefined;
382
+ const key = `${root}:${change.parent || "empty"}:${change.commit}:${file.path}`;
383
+ let patch = patchCache.get(key);
384
+ if (!patch)
385
+ patch = limited(patchCache, key, historyGit(root, [
386
+ "diff",
387
+ "--no-ext-diff",
388
+ "--no-textconv",
389
+ "--no-renames",
390
+ "--no-color",
391
+ "--unified=0",
392
+ change.parent || empty,
393
+ change.commit,
394
+ "--",
395
+ file.path,
396
+ ]).then((value) => hunks(value.toString())), 256);
397
+ spans = await patch;
398
+ }
399
+ for (const side of ["added", "deleted"]) {
400
+ const count = file[side], isOld = side === "deleted", revision = isOld ? change.parent : change.commit, blob = isOld ? file.beforeBlob : file.afterBlob;
401
+ if (excluded || pinned(blob)) {
402
+ add(file, side, count, "excluded", excluded || explicit.reason);
403
+ continue;
404
+ }
405
+ const candidates = [
406
+ ...(isOld ? oldExclusions : newExclusions),
407
+ ...(isOld ? before : after),
408
+ ];
409
+ let assigned = 0;
410
+ for (const hunk of spans) {
411
+ const start = isOld ? hunk.oldStart : hunk.newStart, length = isOld ? hunk.oldCount : hunk.newCount;
412
+ const points = [
413
+ ...new Set([
414
+ start,
415
+ start + length,
416
+ ...candidates.flatMap((part) => [
417
+ Math.max(start, part.start),
418
+ Math.min(start + length, part.end + 1),
419
+ ]),
420
+ ]),
421
+ ]
422
+ .filter((point) => point >= start && point <= start + length)
423
+ .sort((a, b) => a - b);
424
+ for (let i = 0; i < points.length - 1; i++) {
425
+ const part = candidates.find((part) => part.start <= points[i] && part.end >= points[i]);
426
+ if (part) {
427
+ const lines = points[i + 1] - points[i];
428
+ assigned += lines;
429
+ add(file, side, lines, part.bucket, part.reason, part.owner);
430
+ }
431
+ }
432
+ }
433
+ if (assigned > count)
434
+ throw Error("Git hunk accounting exceeded numstat; no totals were published");
435
+ if (count > assigned || file.binary) {
436
+ const target = fallback(revision, file.path);
437
+ add(file, side, count - assigned, target.bucket, target.reason, "owner" in target ? target.owner : undefined);
438
+ }
439
+ }
440
+ }
441
+ for (const side of ["added", "deleted"])
442
+ if (keys.reduce((sum, key) => sum + result.buckets[key][side], 0) !==
443
+ result.totals[side])
444
+ throw Error("Incomplete Git accounting; no totals were published");
445
+ const latestAt = commits[0]?.at ||
446
+ new Date(Number((await historyGit(root, ["show", "-s", "--format=%ct", anchor]))
447
+ .toString()
448
+ .trim()) * 1000).toISOString();
449
+ return { ledger: result, commits, latestAt };
450
+ }
@@ -0,0 +1,10 @@
1
+ import type { CodeSnapshot } from "./code-model.js";
2
+ import type { DefinitionGraph } from "./model.js";
3
+ export interface HistoricalOwnership {
4
+ graph: DefinitionGraph;
5
+ snapshot?: CodeSnapshot;
6
+ }
7
+ /** Read exact-revision artifacts when present. Missing history is never replaced with today's graph. */
8
+ export declare function historicalOwnership(root: string, revisions: string[], archive?: string): Promise<Map<string, HistoricalOwnership>>;
9
+ /** A coarse association lands on a logical block, never on a guessed leaf method. */
10
+ export declare function fileAssociations(graph: DefinitionGraph): Map<string, string>;
@@ -0,0 +1,75 @@
1
+ import { join } from "node:path";
2
+ import { loadCode } from "./code-store.js";
3
+ import { repositoryMapPaths, repositoryMapConfiguration, mapFromArtifacts, parseMapConfiguration, } from "./repository-map.js";
4
+ import { historyBlobs } from "./history-git.js";
5
+ /** Read exact-revision artifacts when present. Missing history is never replaced with today's graph. */
6
+ export async function historicalOwnership(root, revisions, archive = join(root, ".fractal")) {
7
+ const result = new Map(), missing = [];
8
+ for (const commit of new Set(revisions)) {
9
+ const saved = loadCode(archive, commit);
10
+ if (saved)
11
+ result.set(commit, { graph: saved.graph, snapshot: saved });
12
+ else
13
+ missing.push(commit);
14
+ }
15
+ const fallback = repositoryMapConfiguration(root);
16
+ const configs = await historyBlobs(root, missing.map((commit) => `${commit}:fractory.config.json`));
17
+ const configurations = new Map(missing.map((commit) => {
18
+ const text = configs.get(`${commit}:fractory.config.json`);
19
+ try {
20
+ return [commit, text ? parseMapConfiguration(text) : fallback];
21
+ }
22
+ catch {
23
+ return [commit, {}];
24
+ }
25
+ }));
26
+ const objects = await historyBlobs(root, missing.flatMap((commit) => repositoryMapPaths(root, configurations.get(commit)).map((path) => `${commit}:${path}`)));
27
+ const composed = new Map();
28
+ for (const commit of missing) {
29
+ const configuration = configurations.get(commit);
30
+ const texts = repositoryMapPaths(root, configuration).map((path) => objects.get(`${commit}:${path}`));
31
+ try {
32
+ let graph;
33
+ const key = JSON.stringify(configuration) + texts.join("\0");
34
+ if (composed.has(key))
35
+ graph = composed.get(key);
36
+ else
37
+ graph =
38
+ mapFromArtifacts(configuration, (path) => objects.get(`${commit}:${path}`)) || undefined;
39
+ if (graph?.schema === "fractal.definition.v1" &&
40
+ Array.isArray(graph.elements) &&
41
+ graph.elements.some((node) => node.id === graph.id)) {
42
+ composed.set(key, graph);
43
+ result.set(commit, { graph });
44
+ }
45
+ }
46
+ catch {
47
+ /* Invalid/missing artifacts are unavailable, not inferred historical ownership. */
48
+ }
49
+ }
50
+ return result;
51
+ }
52
+ /** A coarse association lands on a logical block, never on a guessed leaf method. */
53
+ export function fileAssociations(graph) {
54
+ const byId = new Map(graph.elements.map((node) => [node.id, node]));
55
+ const ancestors = (id) => {
56
+ const ids = [], seen = new Set();
57
+ let node = byId.get(id);
58
+ while (node && !seen.has(node.id)) {
59
+ seen.add(node.id);
60
+ ids.push(node.id);
61
+ node = byId.get(node.parent || "");
62
+ }
63
+ return ids;
64
+ };
65
+ const candidates = new Map();
66
+ for (const node of graph.elements)
67
+ for (const ref of node.sources || (node.source ? [node.source] : [])) {
68
+ const id = ancestors(node.implementationBlock || node.id).find((id) => ["block", "system", "factory", "deployment"].includes(byId.get(id).kind)) || graph.id;
69
+ candidates.set(ref.file, [...(candidates.get(ref.file) || []), id]);
70
+ }
71
+ return new Map([...candidates].map(([file, ids]) => [
72
+ file,
73
+ ancestors(ids[0]).find((id) => ids.every((other) => ancestors(other).includes(id))),
74
+ ]));
75
+ }
@@ -0,0 +1,13 @@
1
+ export type HistorySourceMode = "default" | "checkout";
2
+ export interface HistorySource {
3
+ mode: HistorySourceMode | "revision";
4
+ label: string;
5
+ commit: string;
6
+ options: {
7
+ value: HistorySourceMode;
8
+ label: string;
9
+ description: string;
10
+ }[];
11
+ }
12
+ export declare function historySourceMode(value: string | null): HistorySourceMode;
13
+ export declare function resolveHistorySource(root: string, mode?: HistorySourceMode, revision?: string): Promise<HistorySource>;
@@ -0,0 +1,100 @@
1
+ /** Resolve the history branch without checking out, fetching or scanning files. */
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ const execute = promisify(execFile);
5
+ export function historySourceMode(value) {
6
+ if (value && value !== "default" && value !== "checkout")
7
+ throw Error("Choose the default branch or the current checkout.");
8
+ return value === "checkout" ? "checkout" : "default";
9
+ }
10
+ export async function resolveHistorySource(root, mode = "default", revision) {
11
+ const git = async (args) => (await execute("git", args, {
12
+ cwd: root,
13
+ encoding: "utf8",
14
+ timeout: 8000,
15
+ maxBuffer: 256 * 1024,
16
+ env: {
17
+ ...process.env,
18
+ GIT_OPTIONAL_LOCKS: "0",
19
+ GIT_TERMINAL_PROMPT: "0",
20
+ },
21
+ })).stdout.trim();
22
+ const resolve = async (ref) => {
23
+ const sha = await git([
24
+ "rev-parse",
25
+ "--verify",
26
+ "--end-of-options",
27
+ ref + "^{commit}",
28
+ ]);
29
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha))
30
+ throw Error("No commit at this history source.");
31
+ return sha;
32
+ };
33
+ if (revision) {
34
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(revision))
35
+ throw Error("Expected a full commit SHA.");
36
+ return {
37
+ mode: "revision",
38
+ label: revision.slice(0, 8),
39
+ commit: revision,
40
+ options: [],
41
+ };
42
+ }
43
+ const [head, current, remoteHeads] = await Promise.all([
44
+ resolve("HEAD"),
45
+ git(["symbolic-ref", "--quiet", "HEAD"]).catch(() => ""),
46
+ git([
47
+ "for-each-ref",
48
+ "--count=1000",
49
+ "--format=%(refname)%00%(symref)",
50
+ "refs/remotes",
51
+ ]).catch(() => ""),
52
+ ]);
53
+ const remotes = remoteHeads.split("\n").map((row) => row.split("\0"));
54
+ const preferred = remotes.find(([ref]) => ref === "refs/remotes/origin/HEAD")?.[1] ||
55
+ remotes.find(([ref, target]) => ref.endsWith("/HEAD") && target)?.[1];
56
+ const candidates = [
57
+ ...new Set([
58
+ preferred,
59
+ "refs/remotes/origin/main",
60
+ "refs/remotes/origin/master",
61
+ ...remotes
62
+ .filter(([ref]) => /\/(main|master)$/.test(ref))
63
+ .map(([ref]) => ref),
64
+ "refs/heads/main",
65
+ "refs/heads/master",
66
+ ].filter((ref) => !!ref)),
67
+ ];
68
+ let branch = "", anchor = head;
69
+ for (const candidate of candidates) {
70
+ try {
71
+ anchor = await resolve(candidate);
72
+ branch = candidate;
73
+ break;
74
+ }
75
+ catch { }
76
+ }
77
+ const label = (ref) => ref.replace(/^refs\/(heads|remotes)\//, "");
78
+ const checkout = current
79
+ ? label(current)
80
+ : `Detached HEAD · ${head.slice(0, 8)}`;
81
+ const options = [
82
+ {
83
+ value: "default",
84
+ label: branch ? label(branch) : checkout,
85
+ description: branch ? "Default branch · local Git" : "Current checkout",
86
+ },
87
+ ];
88
+ if ((branch && branch !== current) || mode === "checkout")
89
+ options.push({
90
+ value: "checkout",
91
+ label: checkout,
92
+ description: "Current checkout",
93
+ });
94
+ return {
95
+ mode,
96
+ label: mode === "checkout" ? checkout : options[0].label,
97
+ commit: mode === "checkout" ? head : anchor,
98
+ options,
99
+ };
100
+ }
@@ -0,0 +1,2 @@
1
+ export declare function agentRequest(request: Record<string, unknown>): Promise<any>;
2
+ export declare function runIntegrations(args: string[]): Promise<string>;