@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,163 @@
1
+ /** Shared setup metadata and skill installation. Never executes repository code. */
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+ const { execFileSync } = require("node:child_process");
5
+ const { randomUUID } = require("node:crypto");
6
+ const quote = (value) => "'" + String(value).replaceAll("'", "'\\''") + "'";
7
+ let toolsCache;
8
+ function probe(command, args) {
9
+ try {
10
+ return {
11
+ available: true,
12
+ version: execFileSync(command, args, {
13
+ encoding: "utf8",
14
+ timeout: 3000,
15
+ stdio: ["ignore", "pipe", "pipe"],
16
+ })
17
+ .trim()
18
+ .split("\n")[0],
19
+ };
20
+ } catch {
21
+ return { available: false };
22
+ }
23
+ }
24
+ function rootPath(root) {
25
+ const repository = fs.realpathSync(path.resolve(root));
26
+ if (!fs.existsSync(path.join(repository, ".git")))
27
+ throw Error("Choose the root of a Git repository.");
28
+ return repository;
29
+ }
30
+ function skillStatus(root) {
31
+ const file = path.join(root, ".agents/skills/fractory/SKILL.md");
32
+ try {
33
+ if (fs.lstatSync(file).isSymbolicLink())
34
+ return { installed: false, file, managed: false };
35
+ const body = fs.readFileSync(file, "utf8");
36
+ return {
37
+ installed: !!body.trim(),
38
+ file,
39
+ managed: body.includes("<!-- fractory-managed-skill -->"),
40
+ };
41
+ } catch {
42
+ return { installed: false, file, managed: false };
43
+ }
44
+ }
45
+ function installSkill(root, directory) {
46
+ root = rootPath(root);
47
+ // Do not follow repository-controlled links when installing tooling.
48
+ for (const suffix of [
49
+ ".agents",
50
+ ".agents/skills",
51
+ ".agents/skills/fractory",
52
+ ".agents/skills/fractory/references",
53
+ ]) {
54
+ const folder = path.join(root, suffix);
55
+ if (fs.existsSync(folder)) {
56
+ if (
57
+ fs.lstatSync(folder).isSymbolicLink() ||
58
+ !fs.lstatSync(folder).isDirectory()
59
+ )
60
+ throw Error(
61
+ "The Fractory skill directory must be a real folder, not a link.",
62
+ );
63
+ } else fs.mkdirSync(folder);
64
+ }
65
+ const status = skillStatus(root);
66
+ if (fs.existsSync(status.file) && fs.lstatSync(status.file).isSymbolicLink())
67
+ throw Error("Skill files must not be symbolic links.");
68
+ const write = (file, body) => {
69
+ if (fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink())
70
+ throw Error("Skill files must not be symbolic links.");
71
+ if (fs.existsSync(file) && fs.readFileSync(file, "utf8") === body) return;
72
+ const temporary = file + "." + randomUUID() + ".tmp";
73
+ try {
74
+ fs.writeFileSync(temporary, body, { flag: "wx", mode: 0o644 });
75
+ fs.renameSync(temporary, file);
76
+ } finally {
77
+ fs.rmSync(temporary, { force: true });
78
+ }
79
+ };
80
+ const source = fs.readFileSync(path.join(directory, "SKILL.md"), "utf8");
81
+ // Preserve a team's custom skill; install the complete updated reference beside it.
82
+ if (!status.installed || status.managed) write(status.file, source);
83
+ write(
84
+ path.join(root, ".agents/skills/fractory/references/fractory-guide.md"),
85
+ fs.readFileSync(path.join(directory, "GUIDE.md"), "utf8"),
86
+ );
87
+ return {
88
+ ...skillStatus(root),
89
+ updated: !status.installed || status.managed,
90
+ preserved: status.installed && !status.managed,
91
+ };
92
+ }
93
+ function setupInfo(root, directory, version = "development") {
94
+ const repository = rootPath(root),
95
+ guideFile = path.join(directory, "GUIDE.md"),
96
+ cli = path.join(directory, "bin/fractory");
97
+ const guide = fs.readFileSync(guideFile, "utf8");
98
+ let mapped = false,
99
+ mapError;
100
+ if (fs.existsSync(path.join(repository, "fractory.json"))) {
101
+ try {
102
+ const map = JSON.parse(
103
+ fs.readFileSync(path.join(repository, "fractory.json"), "utf8"),
104
+ );
105
+ mapped =
106
+ map.schema === "fractal.definition.v1" &&
107
+ Array.isArray(map.elements) &&
108
+ map.elements.some((n) => n.id === map.id) &&
109
+ ["connections", "tests", "gaps", "failures"].every((k) =>
110
+ Array.isArray(map[k]),
111
+ );
112
+ if (!mapped) mapError = "fractory.json is not a generated Fractory map.";
113
+ } catch {
114
+ mapError =
115
+ "The map could not be read. Ask your agent to check and regenerate it.";
116
+ }
117
+ } else mapped = mapAvailable(repository);
118
+ if (!toolsCache)
119
+ toolsCache = {
120
+ git: probe("git", ["--version"]),
121
+ bun: probe("bun", ["--version"]),
122
+ node: probe("node", ["--version"]),
123
+ gh: probe("gh", ["--version"]),
124
+ };
125
+ const prompts = {
126
+ explore:
127
+ "$fractory Explain this repository’s main blocks and how they connect.",
128
+ connect: "$fractory Connect GitHub, Sentry and Linear for this repository.",
129
+ map: "$fractory Map this product from its code, with logical blocks, real connections, docs and tests. Open it in Fractory.",
130
+ };
131
+ const prompt = `${prompts.map}\n\nRepository: ${JSON.stringify(repository)}\nCLI: ${quote(cli)}\nRead: .agents/skills/fractory/references/fractory-guide.md`;
132
+ return {
133
+ repository,
134
+ name: path.basename(repository),
135
+ version,
136
+ mapped,
137
+ mapError,
138
+ tools: toolsCache,
139
+ cli,
140
+ cliAvailable: fs.existsSync(cli),
141
+ guide,
142
+ prompt,
143
+ prompts,
144
+ skill: skillStatus(repository),
145
+ };
146
+ }
147
+ function mapAvailable(root) {
148
+ if (fs.existsSync(path.join(root, "fractory.json"))) return true;
149
+ try {
150
+ let configuration = path.join(root, "fractory.config.json");
151
+ if (!fs.existsSync(configuration)) {
152
+ const primary = require("node:child_process").execFileSync("git", ["worktree", "list", "--porcelain", "-z"], {cwd:root,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:5000}).split("\0").find(line => line.startsWith("worktree "))?.slice(9);
153
+ if (!primary) return false;
154
+ configuration = path.join(primary, "fractory.config.json");
155
+ }
156
+ const config = JSON.parse(fs.readFileSync(configuration,"utf8"));
157
+ if (!config.map?.base) return false;
158
+ const files = [config.map.base, ...(config.map.mounts || []).map(m => m.file), ...(config.map.annotations ? [config.map.annotations] : [])];
159
+ return files.every(file => typeof file === "string" && !path.isAbsolute(file) && !/[\\\r\n\0]/.test(file) && !file.split("/").includes("..") && fs.existsSync(path.join(root,file)));
160
+ } catch { return false; }
161
+ }
162
+
163
+ module.exports = { setupInfo, installSkill, skillStatus, quote, mapAvailable };
@@ -0,0 +1,32 @@
1
+ export interface SkillStatus {
2
+ installed: boolean;
3
+ file: string;
4
+ managed: boolean;
5
+ updated?: boolean;
6
+ preserved?: boolean;
7
+ error?: string;
8
+ }
9
+ export function quote(value: unknown): string;
10
+ export function skillStatus(root: string): SkillStatus;
11
+ export function installSkill(root: string, directory: string): SkillStatus;
12
+ export function setupInfo(
13
+ root: string,
14
+ directory: string,
15
+ version?: string,
16
+ ): {
17
+ repository: string;
18
+ name: string;
19
+ version: string;
20
+ mapped: boolean;
21
+ mapError?: string;
22
+ tools: Record<
23
+ "git" | "bun" | "node" | "gh",
24
+ { available: boolean; version?: string }
25
+ >;
26
+ cli: string;
27
+ cliAvailable: boolean;
28
+ guide: string;
29
+ prompt: string;
30
+ prompts: Record<"explore" | "connect" | "map", string>;
31
+ skill: SkillStatus;
32
+ };
@@ -0,0 +1,208 @@
1
+ import ts from "typescript";
2
+ import { createHash } from "node:crypto";
3
+ import type { DefinitionGraph, SourceRef } from "./model";
4
+ import type { CodeSnapshot } from "./code-model";
5
+
6
+ export const sourceDigest = (text: string) =>
7
+ createHash("sha256").update(text).digest("hex").slice(0, 16);
8
+ const safeFile = (file: string) =>
9
+ !file.startsWith("/") &&
10
+ !file.split(/[\\/]/).includes("..") &&
11
+ !file.includes("\0");
12
+
13
+ /** Cheap freshness validation. Read each referenced file once; never rebase or bless a changed reference. */
14
+ export function staleSourceRefs(
15
+ refs: readonly SourceRef[],
16
+ read: (file: string) => string | undefined,
17
+ ) {
18
+ const files = new Map<
19
+ string,
20
+ { text: string | undefined; digest?: string; lines?: string[] }
21
+ >();
22
+ const gaps: { file: string; line: number; reason: string }[] = [];
23
+ for (const ref of refs) {
24
+ if (!safeFile(ref.file))
25
+ throw new Error("Source paths must be repository relative");
26
+ if (!files.has(ref.file)) {
27
+ const text = read(ref.file);
28
+ files.set(ref.file, {
29
+ text,
30
+ ...(text === undefined
31
+ ? {}
32
+ : { digest: sourceDigest(text), lines: text.split(/\r?\n/) }),
33
+ });
34
+ }
35
+ const file = files.get(ref.file)!;
36
+ const reason =
37
+ file.text === undefined
38
+ ? "Source file unavailable"
39
+ : file.digest !== ref.digest
40
+ ? "Source changed since review"
41
+ : !file.lines?.[ref.line - 1]?.includes(ref.symbol || "")
42
+ ? "Source anchor moved or disappeared"
43
+ : undefined;
44
+ if (reason) gaps.push({ file: ref.file, line: ref.line, reason });
45
+ }
46
+ return gaps;
47
+ }
48
+
49
+ /** Parse only source files named by the definition, once each. Never execute application code. */
50
+ export function indexSources(
51
+ graph: DefinitionGraph,
52
+ read: (file: string) => string | undefined,
53
+ cache?: {
54
+ get: (key: string) =>
55
+ | {
56
+ ranges: CodeSnapshot["files"][string]["ranges"];
57
+ gaps: CodeSnapshot["gaps"];
58
+ }
59
+ | undefined;
60
+ put: (
61
+ key: string,
62
+ value: {
63
+ ranges: CodeSnapshot["files"][string]["ranges"];
64
+ gaps: CodeSnapshot["gaps"];
65
+ },
66
+ ) => void;
67
+ },
68
+ options: { resolveUniqueAnchors?: boolean } = {},
69
+ ) {
70
+ const files: CodeSnapshot["files"] = {},
71
+ gaps: CodeSnapshot["gaps"] = [];
72
+ const refs = new Map<string, { elementId: string; ref: SourceRef }[]>();
73
+ for (const element of graph.elements) {
74
+ for (const ref of element.sources ||
75
+ (element.source ? [element.source] : [])) {
76
+ // A public signature points to its implementation for contract review,
77
+ // but does not own the body or the rest of an enclosing class/file.
78
+ if (ref.scope === "contract") continue;
79
+ if (!safeFile(ref.file))
80
+ throw new Error("Source paths must be repository relative");
81
+ const list = refs.get(ref.file) || [];
82
+ list.push({ elementId: element.id, ref });
83
+ refs.set(ref.file, list);
84
+ }
85
+ }
86
+ for (const [file, owners] of refs) {
87
+ const text = read(file);
88
+ if (text === undefined) {
89
+ for (const o of owners)
90
+ gaps.push({
91
+ elementId: o.elementId,
92
+ file,
93
+ reason: "Source file unavailable",
94
+ });
95
+ continue;
96
+ }
97
+ const digest = sourceDigest(text);
98
+ const key = createHash("sha256")
99
+ .update(JSON.stringify({ version: 5, file, digest, owners, options }))
100
+ .digest("hex");
101
+ const saved = cache?.get(key);
102
+ if (saved) {
103
+ files[file] = { digest, ranges: saved.ranges };
104
+ gaps.push(...saved.gaps);
105
+ continue;
106
+ }
107
+ const gapStart = gaps.length;
108
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
109
+ const nodes: ts.Node[] = [];
110
+ const visit = (node: ts.Node) => {
111
+ if (
112
+ (ts.isStatement(node) && !ts.isBlock(node)) ||
113
+ ts.isFunctionDeclaration(node) ||
114
+ ts.isMethodDeclaration(node) ||
115
+ ts.isClassDeclaration(node) ||
116
+ ts.isVariableDeclaration(node) ||
117
+ ts.isExpressionStatement(node) ||
118
+ ts.isPropertyDeclaration(node)
119
+ )
120
+ nodes.push(node);
121
+ ts.forEachChild(node, visit);
122
+ };
123
+ visit(sf);
124
+ const ranges: CodeSnapshot["files"][string]["ranges"] = [];
125
+ for (const { elementId, ref } of owners) {
126
+ const shifted =
127
+ digest !== ref.digest &&
128
+ options.resolveUniqueAnchors &&
129
+ ref.symbol &&
130
+ text.indexOf(ref.symbol) >= 0 &&
131
+ text.indexOf(ref.symbol, text.indexOf(ref.symbol) + ref.symbol.length) <
132
+ 0;
133
+ if (digest !== ref.digest) {
134
+ gaps.push({
135
+ elementId,
136
+ file,
137
+ reason: "Source changed since this definition was reviewed",
138
+ });
139
+ if (!shifted) continue;
140
+ }
141
+ if (ref.scope === "file") {
142
+ if (ref.line !== 1 || ref.symbol) {
143
+ gaps.push({
144
+ elementId,
145
+ file,
146
+ reason: "Invalid whole-module source reference",
147
+ });
148
+ continue;
149
+ }
150
+ ranges.push({
151
+ elementId,
152
+ start: 1,
153
+ end: sf.getLineStarts().length,
154
+ basis: "file",
155
+ });
156
+ continue;
157
+ }
158
+ const anchorLine = shifted
159
+ ? sf.getLineAndCharacterOfPosition(text.indexOf(ref.symbol!)).line + 1
160
+ : ref.line;
161
+ if (anchorLine < 1 || anchorLine > sf.getLineStarts().length) {
162
+ gaps.push({ elementId, file, reason: "Source line unavailable" });
163
+ continue;
164
+ }
165
+ const offset = sf.getPositionOfLineAndCharacter(anchorLine - 1, 0);
166
+ const lineEnd = sf.getLineStarts()[anchorLine] ?? text.length;
167
+ const indentation = Math.max(0, text.slice(offset, lineEnd).search(/\S/));
168
+ const position = shifted
169
+ ? text.indexOf(ref.symbol!)
170
+ : ref.symbol
171
+ ? text.indexOf(ref.symbol, offset)
172
+ : offset + indentation;
173
+ // An anchor must occur on the reviewed line; never move it silently to another occurrence.
174
+ if (
175
+ position < 0 ||
176
+ (!shifted &&
177
+ sf.getLineAndCharacterOfPosition(position).line + 1 !== ref.line)
178
+ ) {
179
+ gaps.push({
180
+ elementId,
181
+ file,
182
+ reason: "Reviewed source anchor unavailable",
183
+ });
184
+ continue;
185
+ }
186
+ const node = nodes
187
+ .filter((n) => n.getStart(sf) <= position && n.getEnd() > position)
188
+ .sort(
189
+ (a, b) => a.getEnd() - a.getStart(sf) - (b.getEnd() - b.getStart(sf)),
190
+ )[0];
191
+ const start = node
192
+ ? sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1
193
+ : anchorLine;
194
+ const end = node
195
+ ? sf.getLineAndCharacterOfPosition(node.getEnd() - 1).line + 1
196
+ : anchorLine;
197
+ ranges.push({
198
+ elementId,
199
+ start,
200
+ end,
201
+ basis: shifted ? "anchor" : node ? "syntax" : "anchor",
202
+ });
203
+ }
204
+ files[file] = { digest, ranges };
205
+ cache?.put(key, { ranges, gaps: gaps.slice(gapStart) });
206
+ }
207
+ return { files, gaps };
208
+ }
@@ -0,0 +1,131 @@
1
+ /** Bounded source reads. Git blobs are read in batches; no checkout or compiler process. */
2
+ import { execFileSync } from "node:child_process";
3
+ import { readFileSync, realpathSync, statSync } from "node:fs";
4
+ import { resolve, sep } from "node:path";
5
+ import { readGit, resolveComparisonRef } from "./git-refs";
6
+ import type { DefinitionGraph } from "./model";
7
+ import { sourceReviewMap, type SourceArea } from "./source-review";
8
+ export function readMapSources(
9
+ root: string,
10
+ definition: DefinitionGraph,
11
+ areas: SourceArea[],
12
+ ref?: string,
13
+ ) {
14
+ const revision = ref ? resolveComparisonRef(root, ref) : undefined;
15
+ const paths = (
16
+ revision
17
+ ? readGit(root, ["ls-tree", "-r", "--name-only", "-z", revision])
18
+ : readGit(root, [
19
+ "ls-files",
20
+ "--cached",
21
+ "--others",
22
+ "--exclude-standard",
23
+ "-z",
24
+ ])
25
+ )
26
+ .split("\0")
27
+ .filter(Boolean);
28
+ const known = new Set([
29
+ ...definition.elements.flatMap((n) =>
30
+ (n.sources || (n.source ? [n.source] : [])).map((s) => s.file),
31
+ ),
32
+ ...definition.tests.map((test) => test.source.file),
33
+ ]);
34
+ const selected = [
35
+ ...new Set(
36
+ paths.filter(
37
+ (p) =>
38
+ /\.[cm]?[jt]sx?$/.test(p) &&
39
+ !/[\n\r]/.test(p) &&
40
+ !p.startsWith("/") &&
41
+ !p.split("/").includes("..") &&
42
+ (known.has(p) ||
43
+ areas.some((a) => a.matches(p)) ||
44
+ (/\.(?:test|spec|vitest)\.[cm]?[jt]sx?$/.test(p) &&
45
+ areas.some((area) =>
46
+ area.matches(
47
+ p
48
+ .replace(/\/(?:__tests__|tests|test)\//g, "/")
49
+ .replace(/\.(?:test|spec|vitest)(\.[cm]?[jt]sx?)$/, "$1"),
50
+ ),
51
+ ))),
52
+ ),
53
+ ),
54
+ ].sort();
55
+ if (selected.length > 2500)
56
+ throw Error(
57
+ "Source review exceeded 2,500 files; narrow the capability rules.",
58
+ );
59
+ const files = new Map<string, string>();
60
+ let bytes = 0;
61
+ for (let at = 0; at < selected.length; at += 64) {
62
+ const batch = selected.slice(at, at + 64);
63
+ if (revision) {
64
+ const output = execFileSync("git", ["cat-file", "--batch"], {
65
+ cwd: root,
66
+ input: batch.map((p) => `${revision}:${p}\n`).join(""),
67
+ timeout: 15000,
68
+ maxBuffer: 16 * 1024 * 1024,
69
+ });
70
+ let offset = 0;
71
+ for (const file of batch) {
72
+ const end = output.indexOf(10, offset);
73
+ if (end < 0) throw Error("Incomplete Git source batch");
74
+ const header = output.subarray(offset, end).toString();
75
+ offset = end + 1;
76
+ if (header.endsWith(" missing")) continue;
77
+ const [, type, sizeText] = header.split(" "),
78
+ size = Number(sizeText);
79
+ if (
80
+ type !== "blob" ||
81
+ !Number.isSafeInteger(size) ||
82
+ size < 0 ||
83
+ offset + size > output.length
84
+ )
85
+ throw Error("Invalid Git source blob");
86
+ if (size <= 1024 * 1024)
87
+ files.set(file, output.subarray(offset, offset + size).toString());
88
+ offset += size + 1;
89
+ bytes += size;
90
+ }
91
+ } else {
92
+ const base = realpathSync(root);
93
+ for (const file of batch)
94
+ try {
95
+ const absolute = realpathSync(resolve(root, file));
96
+ if (
97
+ !absolute.startsWith(base + sep) ||
98
+ statSync(absolute).size > 1024 * 1024
99
+ )
100
+ continue;
101
+ const text = readFileSync(absolute, "utf8");
102
+ bytes += Buffer.byteLength(text);
103
+ files.set(file, text);
104
+ } catch {
105
+ /* Missing working-tree sources are not silently invented. */
106
+ }
107
+ }
108
+ if (bytes > 32 * 1024 * 1024)
109
+ throw Error("Source review exceeded its 32MB read budget.");
110
+ }
111
+ return { files, revision };
112
+ }
113
+ const revisions = new Map<string, DefinitionGraph>();
114
+ export function revisionSourceMap(
115
+ root: string,
116
+ definition: DefinitionGraph,
117
+ areas: SourceArea[],
118
+ ref: string,
119
+ ) {
120
+ const revision = resolveComparisonRef(root, ref),
121
+ key = `${root}:${definition.revision}:${revision}`;
122
+ const cached = revisions.get(key);
123
+ if (cached) return cached;
124
+ const source = readMapSources(root, definition, areas, revision);
125
+ const graph = sourceReviewMap(definition, source.files, areas, revision, {
126
+ legacySnapshot: true,
127
+ });
128
+ revisions.set(key, graph);
129
+ if (revisions.size > 4) revisions.delete(revisions.keys().next().value!);
130
+ return graph;
131
+ }