@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,125 @@
1
+ import { readRepositoryMap } from "./repository-map";
2
+ import { listWorkContexts, workDeepLink } from "./work-context";
3
+ import { realpathSync } from "node:fs";
4
+ import { existsSync, readFileSync, statSync } from "node:fs";
5
+ import { execFileSync } from "node:child_process";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { createReport, listReports, markReport, readReport } from "./reports";
8
+ import { reportsForBlock } from "./reports-model";
9
+ import type { DefinitionGraph } from "./model";
10
+
11
+ export async function runReports(args: string[]) {
12
+ if (args.includes("--help"))
13
+ return "fractory reports [list] [--block ID] [--unread]\nfractory reports create --block ID [--block ID ...] --title TITLE (--file report.md | --stdin) [--author LABEL]\nfractory reports show REPORT_ID\nfractory reports open REPORT_ID\nfractory reports read REPORT_ID\nfractory reports unread REPORT_ID\nUse --root PATH from another directory. Reports are versioned Markdown; read status stays local. Showing a report does not mark it read.";
14
+ const value = (name: string) => {
15
+ const index = args.indexOf(name);
16
+ if (index < 0) return undefined;
17
+ if (!args[index + 1] || args[index + 1].startsWith("--"))
18
+ throw Error(`${name} needs a value.`);
19
+ return args[index + 1];
20
+ };
21
+ let root = resolve(value("--root") || process.cwd());
22
+ if (!value("--root"))
23
+ while (
24
+ !existsSync(join(root, ".git")) &&
25
+ !existsSync(join(root, "fractory.json")) &&
26
+ dirname(root) !== root
27
+ )
28
+ root = dirname(root);
29
+ const action = args[1]?.startsWith("--") ? "list" : args[1] || "list";
30
+ const reportURL = (report: { blocks: string[]; id: string }) => {
31
+ let link = `fractory://open?repo=${encodeURIComponent(root)}`;
32
+ try {
33
+ const context = listWorkContexts(root).find(
34
+ (t) => t.path === realpathSync(root),
35
+ );
36
+ link = workDeepLink(root, context?.id || "main");
37
+ } catch {
38
+ /* Offline report fixtures still produce a repository link. */
39
+ }
40
+ const url = new URL(link);
41
+ url.searchParams.set("block", report.blocks[0]);
42
+ url.searchParams.set("inspect", report.blocks[0]);
43
+ url.searchParams.set("workspace", "reports");
44
+ url.searchParams.set("report", report.id);
45
+ return url.href;
46
+ };
47
+ if (["show", "read", "unread", "open"].includes(action)) {
48
+ const id = args[2];
49
+ if (!id || id.startsWith("--"))
50
+ throw Error("Choose a report ID from fractory reports list.");
51
+ const report = readReport(root, id);
52
+ if (action === "open") {
53
+ const url = reportURL(report);
54
+ execFileSync("open", [url], { stdio: "ignore", timeout: 5000 });
55
+ return url;
56
+ }
57
+ return JSON.stringify(
58
+ action === "show"
59
+ ? report
60
+ : markReport(root, id, report.revision, action === "read"),
61
+ null,
62
+ 2,
63
+ );
64
+ }
65
+ if (!["list", "create"].includes(action))
66
+ throw Error(`Unknown reports command: ${action}`);
67
+ const graph = readRepositoryMap(root);
68
+ if (!graph)
69
+ throw Error("No Fractory map in this repository. Run fractory setup.");
70
+ if (action === "list") {
71
+ const view = listReports(root);
72
+ const reports = value("--block")
73
+ ? reportsForBlock(graph, view.reports, value("--block")!)
74
+ : view.reports;
75
+ return JSON.stringify(
76
+ {
77
+ ...view,
78
+ reports: args.includes("--unread")
79
+ ? reports.filter((report) => report.unread)
80
+ : reports,
81
+ },
82
+ null,
83
+ 2,
84
+ );
85
+ }
86
+ const blocks = args.flatMap((arg, index) =>
87
+ arg === "--block" ? [args[index + 1]] : [],
88
+ );
89
+ if (blocks.some((block) => !block || block.startsWith("--")))
90
+ throw Error("--block needs a block ID.");
91
+ const file = value("--file"),
92
+ stdin = args.includes("--stdin");
93
+ if ((!file && !stdin) || (file && stdin))
94
+ throw Error("Supply Markdown with either --file PATH or --stdin.");
95
+ if (stdin && process.stdin.isTTY)
96
+ throw Error("Pipe Markdown to --stdin, or use --file PATH.");
97
+ let body: string;
98
+ if (file) {
99
+ const path = resolve(process.cwd(), file),
100
+ stat = statSync(path);
101
+ if (!stat.isFile() || stat.size > 128000)
102
+ throw Error("Supply a Markdown file below 128 KB.");
103
+ body = readFileSync(path, "utf8");
104
+ } else {
105
+ const chunks: Buffer[] = [];
106
+ let size = 0;
107
+ for await (const chunk of process.stdin) {
108
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
109
+ size += buffer.length;
110
+ if (size > 128000) throw Error("Keep this report below 128 KB.");
111
+ chunks.push(buffer);
112
+ }
113
+ body = Buffer.concat(chunks).toString("utf8");
114
+ }
115
+ const report = createReport(root, graph, {
116
+ title: value("--title") || "",
117
+ blocks,
118
+ body,
119
+ author: value("--author"),
120
+ });
121
+ const url = reportURL(report);
122
+ if (args.includes("--open"))
123
+ execFileSync("open", [url], { stdio: "ignore", timeout: 5000 });
124
+ return JSON.stringify({ ...report, url }, null, 2);
125
+ }
@@ -0,0 +1,73 @@
1
+ import type { DefinitionGraph } from "./model";
2
+
3
+ export interface ReportMetadata {
4
+ schema: "fractory.report.v1";
5
+ id: string;
6
+ title: string;
7
+ blocks: string[];
8
+ createdAt: string;
9
+ author?: string;
10
+ codeRevision?: string;
11
+ }
12
+ export interface BlockReport extends ReportMetadata {
13
+ file: string;
14
+ revision: string;
15
+ unread: boolean;
16
+ }
17
+ export interface ReportDocument extends BlockReport {
18
+ body: string;
19
+ }
20
+ export interface ReportsView {
21
+ reports: BlockReport[];
22
+ warnings: string[];
23
+ }
24
+
25
+ export function resolvedReportBlock(graph: DefinitionGraph, id: string) {
26
+ const seen = new Set<string>();
27
+ while (graph.aliases && Object.hasOwn(graph.aliases, id) && typeof graph.aliases[id] === "string" && !seen.has(id)) {
28
+ seen.add(id);
29
+ id = graph.aliases[id];
30
+ }
31
+ return id;
32
+ }
33
+
34
+ /** A multi-target report contributes once to each ancestor, including the root. */
35
+ export function reportBlocks(
36
+ graph: DefinitionGraph,
37
+ report: Pick<BlockReport, "blocks">,
38
+ ) {
39
+ const byId = new Map(graph.elements.map((node) => [node.id, node]));
40
+ const owners = new Set<string>();
41
+ // The repository inbox must also retain reports whose target was removed.
42
+ // Their tree placement stays explicitly Unassigned, never a guessed leaf.
43
+ if (byId.has(graph.id)) owners.add(graph.id);
44
+ for (const target of report.blocks) {
45
+ let id: string | undefined = resolvedReportBlock(graph, target);
46
+ const seen = new Set<string>();
47
+ while (id && byId.has(id) && !seen.has(id)) {
48
+ seen.add(id);
49
+ owners.add(id);
50
+ id = byId.get(id)!.parent;
51
+ }
52
+ }
53
+ return owners;
54
+ }
55
+ export function unreadReportCounts(
56
+ graph: DefinitionGraph,
57
+ reports: BlockReport[],
58
+ ) {
59
+ const counts: Record<string, number> = Object.create(null);
60
+ for (const report of reports)
61
+ if (report.unread)
62
+ for (const id of reportBlocks(graph, report))
63
+ counts[id] = (counts[id] || 0) + 1;
64
+ return counts;
65
+ }
66
+ export function reportsForBlock(
67
+ graph: DefinitionGraph,
68
+ reports: BlockReport[],
69
+ block: string,
70
+ ) {
71
+ const id = resolvedReportBlock(graph, block);
72
+ return reports.filter((report) => reportBlocks(graph, report).has(id));
73
+ }
package/src/reports.ts ADDED
@@ -0,0 +1,276 @@
1
+ import { readGit } from "./git-refs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { execFileSync } from "node:child_process";
4
+ import {
5
+ existsSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ readFileSync,
9
+ readdirSync,
10
+ renameSync,
11
+ unlinkSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import type { DefinitionGraph } from "./model";
16
+ import {
17
+ checkedPath,
18
+ noteRevision,
19
+ WorkspaceConflict,
20
+ } from "./workspace-notes";
21
+ import {
22
+ resolvedReportBlock,
23
+ type BlockReport,
24
+ type ReportDocument,
25
+ type ReportMetadata,
26
+ type ReportsView,
27
+ } from "./reports-model";
28
+
29
+ const directory = "docs/fractory/reports";
30
+ const limit = 128_000;
31
+ const validId =
32
+ /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
33
+ const cache = new Map<
34
+ string,
35
+ { stamp: string; metadata: ReportMetadata; revision: string }
36
+ >();
37
+ function reportFile(id: string) {
38
+ if (!validId.test(id)) throw Error("Choose a valid report ID.");
39
+ return `${directory}/${id}.md`;
40
+ }
41
+ function receiptFile(id: string) {
42
+ reportFile(id);
43
+ return `.fractal/reports/read/${id}.json`;
44
+ }
45
+ function atomic(root: string, file: string, body: string) {
46
+ const path = checkedPath(root, file, true);
47
+ mkdirSync(dirname(path), { recursive: true });
48
+ checkedPath(root, file, true);
49
+ const temp = join(dirname(path), `.fractory-${randomUUID()}.tmp`);
50
+ try {
51
+ writeFileSync(temp, body, { flag: "wx", mode: 0o600 });
52
+ renameSync(temp, path);
53
+ } finally {
54
+ if (existsSync(temp)) unlinkSync(temp);
55
+ }
56
+ }
57
+ function parse(
58
+ text: string,
59
+ id: string,
60
+ ): { metadata: ReportMetadata; body: string } {
61
+ // Standard Markdown front matter with a JSON/YAML flow mapping. Reports do
62
+ // not need a new parser dependency or an additional registry of bindings.
63
+ const match = /^---\r?\nfractory: ([^\r\n]+)\r?\n---\r?\n/.exec(text);
64
+ if (!match) throw Error("Missing Fractory report front matter.");
65
+ const metadata = JSON.parse(match[1]) as ReportMetadata;
66
+ if (
67
+ metadata.schema !== "fractory.report.v1" ||
68
+ metadata.id !== id ||
69
+ !validId.test(metadata.id) ||
70
+ typeof metadata.title !== "string" ||
71
+ !metadata.title.trim() ||
72
+ metadata.title.length > 160 ||
73
+ !Array.isArray(metadata.blocks) ||
74
+ !metadata.blocks.length ||
75
+ metadata.blocks.some(
76
+ (block) => typeof block !== "string" || !block || block.length > 4096,
77
+ ) ||
78
+ typeof metadata.createdAt !== "string" ||
79
+ !Number.isFinite(Date.parse(metadata.createdAt)) ||
80
+ (metadata.author !== undefined &&
81
+ (typeof metadata.author !== "string" || metadata.author.length > 100)) ||
82
+ (metadata.codeRevision !== undefined &&
83
+ !/^[a-f0-9]{40,64}$/.test(metadata.codeRevision))
84
+ )
85
+ throw Error("Invalid Fractory report metadata.");
86
+ return { metadata, body: text.slice(match[0].length) };
87
+ }
88
+ function readRevision(root: string, id: string) {
89
+ const path = checkedPath(root, receiptFile(id), true);
90
+ if (!existsSync(path)) return undefined;
91
+ try {
92
+ const value = JSON.parse(readFileSync(path, "utf8"));
93
+ return typeof value.revision === "string" ? value.revision : undefined;
94
+ } catch {
95
+ return undefined;
96
+ }
97
+ }
98
+ function summary(root: string, id: string): BlockReport {
99
+ const file = reportFile(id),
100
+ path = checkedPath(root, file);
101
+ const stat = lstatSync(path);
102
+ if (!stat.isFile() || stat.size > limit)
103
+ throw Error("Report must be a Markdown file below 128 KB.");
104
+ const stamp = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
105
+ let entry = cache.get(path);
106
+ if (!entry || entry.stamp !== stamp) {
107
+ const text = readFileSync(path, "utf8");
108
+ entry = {
109
+ stamp,
110
+ metadata: parse(text, id).metadata,
111
+ revision: noteRevision(text),
112
+ };
113
+ cache.set(path, entry);
114
+ if (cache.size > 2048) cache.delete(cache.keys().next().value!);
115
+ }
116
+ return {
117
+ ...entry.metadata,
118
+ file,
119
+ revision: entry.revision,
120
+ unread: readRevision(root, id) !== entry.revision,
121
+ };
122
+ }
123
+ export function listReports(root: string, ref?: string): ReportsView {
124
+ if (ref) {
125
+ const reports: BlockReport[] = [],
126
+ warnings: string[] = [];
127
+ for (const file of readGit(root, [
128
+ "ls-tree",
129
+ "-r",
130
+ "--name-only",
131
+ ref,
132
+ "--",
133
+ directory,
134
+ ])
135
+ .trim()
136
+ .split("\n")
137
+ .filter(Boolean)) {
138
+ try {
139
+ const id = file.split("/").at(-1)!.replace(/\.md$/, ""),
140
+ { body, ...report } = readReport(root, id, ref);
141
+ reports.push(report);
142
+ } catch (e) {
143
+ warnings.push(`${file}: unreadable report`);
144
+ }
145
+ }
146
+ return {
147
+ reports: reports.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
148
+ warnings,
149
+ };
150
+ }
151
+ const path = checkedPath(root, directory, true);
152
+ if (!existsSync(path)) return { reports: [], warnings: [] };
153
+ const reports: BlockReport[] = [],
154
+ warnings: string[] = [];
155
+ for (const file of readdirSync(path).sort()) {
156
+ if (!file.endsWith(".md")) continue;
157
+ const id = file.slice(0, -3);
158
+ try {
159
+ reports.push(summary(root, id));
160
+ } catch (error) {
161
+ warnings.push(
162
+ `${file}: ${error instanceof Error ? error.message : "Unreadable report"}`,
163
+ );
164
+ }
165
+ }
166
+ reports.sort(
167
+ (a, b) =>
168
+ b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id),
169
+ );
170
+ return { reports, warnings };
171
+ }
172
+ export function readReport(
173
+ root: string,
174
+ id: string,
175
+ ref?: string,
176
+ ): ReportDocument {
177
+ if (ref) {
178
+ const file = reportFile(id),
179
+ text = readGit(root, ["show", `${ref}:${file}`]);
180
+ if (Buffer.byteLength(text) > limit)
181
+ throw Error("Report exceeds read budget.");
182
+ const { metadata, body } = parse(text, id),
183
+ revision = noteRevision(text);
184
+ return {
185
+ ...metadata,
186
+ file,
187
+ revision,
188
+ body,
189
+ unread: readRevision(root, id) !== revision,
190
+ };
191
+ }
192
+ const file = reportFile(id),
193
+ path = checkedPath(root, file);
194
+ const stat = lstatSync(path);
195
+ if (!stat.isFile() || stat.size > limit)
196
+ throw Error("Report must be a Markdown file below 128 KB.");
197
+ const text = readFileSync(path, "utf8");
198
+ if (Buffer.byteLength(text) > limit)
199
+ throw Error("Keep this report below 128 KB.");
200
+ const { metadata, body } = parse(text, id),
201
+ revision = noteRevision(text);
202
+ return {
203
+ ...metadata,
204
+ file,
205
+ revision,
206
+ unread: readRevision(root, id) !== revision,
207
+ body,
208
+ };
209
+ }
210
+ export function createReport(
211
+ root: string,
212
+ graph: DefinitionGraph,
213
+ input: { title: string; blocks: string[]; body: string; author?: string },
214
+ ) {
215
+ if (
216
+ !input.title.trim() ||
217
+ input.title.length > 160 ||
218
+ /[\r\n\0]/.test(input.title)
219
+ )
220
+ throw Error("Use a report title of 1–160 characters.");
221
+ if (!input.body.trim()) throw Error("Write the report’s Markdown content.");
222
+ if (
223
+ input.author !== undefined &&
224
+ (input.author.length > 100 || /[\r\n\0]/.test(input.author))
225
+ )
226
+ throw Error("Use a short author label.");
227
+ const blocks = [
228
+ ...new Set(input.blocks.map((id) => resolvedReportBlock(graph, id))),
229
+ ];
230
+ if (
231
+ !blocks.length ||
232
+ blocks.some((id) => !graph.elements.some((node) => node.id === id))
233
+ )
234
+ throw Error("Attach this report to at least one existing block ID.");
235
+ let codeRevision: string | undefined;
236
+ try {
237
+ codeRevision = execFileSync("git", ["rev-parse", "HEAD"], {
238
+ cwd: root,
239
+ encoding: "utf8",
240
+ stdio: ["ignore", "pipe", "ignore"],
241
+ timeout: 2000,
242
+ }).trim();
243
+ } catch {}
244
+ const metadata: ReportMetadata = {
245
+ schema: "fractory.report.v1",
246
+ id: randomUUID(),
247
+ title: input.title.trim(),
248
+ blocks,
249
+ createdAt: new Date().toISOString(),
250
+ ...(input.author ? { author: input.author } : {}),
251
+ ...(codeRevision ? { codeRevision } : {}),
252
+ };
253
+ const body = `---\nfractory: ${JSON.stringify(metadata)}\n---\n\n${input.body.trim()}\n`;
254
+ if (Buffer.byteLength(body) > limit)
255
+ throw Error("Keep this report below 128 KB.");
256
+ atomic(root, reportFile(metadata.id), body);
257
+ return readReport(root, metadata.id);
258
+ }
259
+ export function markReport(
260
+ root: string,
261
+ id: string,
262
+ revision: string,
263
+ read: boolean,
264
+ ref?: string,
265
+ ) {
266
+ const report = readReport(root, id, ref);
267
+ if (report.revision !== revision)
268
+ throw new WorkspaceConflict(
269
+ "This report changed. Read its latest version before marking it read.",
270
+ );
271
+ const file = receiptFile(id),
272
+ path = checkedPath(root, file, true);
273
+ if (read) atomic(root, file, JSON.stringify({ revision }));
274
+ else if (existsSync(path)) unlinkSync(path);
275
+ return { ...report, unread: !read };
276
+ }
@@ -0,0 +1,191 @@
1
+ /** Repository-owned mapping configuration. Fractory ships no product map or provider rules. */
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import type { DefinitionGraph } from "./model";
5
+ import type { FactoryModel } from "./factory-model";
6
+ import type { SentryAreaRule } from "./sentry";
7
+ import { composeDefinitions } from "./compose";
8
+ import { factoryGraph } from "./factory-graph";
9
+ import { captureCommit, resolveCommit } from "./git-code";
10
+ import { execFileSync } from "node:child_process";
11
+
12
+ export interface RepositoryMapConfiguration {
13
+ /** Optional compatibility with repositories which generate several map artifacts. */
14
+ map?: {
15
+ base: string;
16
+ mounts?: Array<{ file: string; at: string; root: string }>;
17
+ annotations?: string;
18
+ };
19
+ sentryAreas?: SentryAreaRule[];
20
+ }
21
+ function repositoryFile(file: string) {
22
+ if (
23
+ !file ||
24
+ file.startsWith("/") ||
25
+ /[\\\r\n\0]/.test(file) ||
26
+ file.split("/").some((p) => p === "..")
27
+ )
28
+ throw Error("Map configuration must use repository-relative paths.");
29
+ return file;
30
+ }
31
+ export function repositoryMapConfiguration(
32
+ root: string,
33
+ ): RepositoryMapConfiguration {
34
+ let path = join(root, "fractory.config.json");
35
+ if (!existsSync(path)) {
36
+ // A linked worktree can predate an uncommitted repository configuration.
37
+ // Share only its primary checkout's rules, proven by Git's own inventory.
38
+ // The map/source blobs themselves are still read from the selected checkout.
39
+ try {
40
+ const primary = execFileSync(
41
+ "git",
42
+ ["worktree", "list", "--porcelain", "-z"],
43
+ {
44
+ cwd: root,
45
+ encoding: "utf8",
46
+ stdio: ["ignore", "pipe", "ignore"],
47
+ timeout: 5000,
48
+ maxBuffer: 1024 * 1024,
49
+ },
50
+ )
51
+ .split("\0")
52
+ .find((line) => line.startsWith("worktree "))
53
+ ?.slice(9);
54
+ if (!primary || realpathSync(primary) === realpathSync(root)) return {};
55
+ path = join(primary, "fractory.config.json");
56
+ } catch {
57
+ return {};
58
+ }
59
+ }
60
+ if (!existsSync(path)) return {};
61
+ return parseMapConfiguration(readFileSync(path, "utf8"));
62
+ }
63
+ export function parseMapConfiguration(
64
+ text: string,
65
+ ): RepositoryMapConfiguration {
66
+ const config = JSON.parse(text) as RepositoryMapConfiguration;
67
+ if (config.map) {
68
+ repositoryFile(config.map.base);
69
+ for (const mount of config.map.mounts || []) repositoryFile(mount.file);
70
+ if (config.map.annotations) repositoryFile(config.map.annotations);
71
+ }
72
+ return config;
73
+ }
74
+ export function repositoryMapPaths(
75
+ root: string,
76
+ configuration = repositoryMapConfiguration(root),
77
+ ) {
78
+ const map = configuration.map;
79
+ return [
80
+ ...new Set([
81
+ "fractory.json",
82
+ ...(map
83
+ ? [
84
+ map.base,
85
+ ...(map.mounts || []).map((m) => m.file),
86
+ ...(map.annotations ? [map.annotations] : []),
87
+ ]
88
+ : []),
89
+ ]),
90
+ ];
91
+ }
92
+ export function mapFromArtifacts(
93
+ config: RepositoryMapConfiguration,
94
+ read: (file: string) => string | undefined,
95
+ ): DefinitionGraph | null {
96
+ const canonical = read("fractory.json");
97
+ if (canonical) return JSON.parse(canonical);
98
+ const map = config.map;
99
+ if (!map) return null;
100
+ const base = read(map.base);
101
+ if (!base) return null;
102
+ const mounts = [];
103
+ for (const mount of map.mounts || []) {
104
+ const value = read(mount.file);
105
+ if (!value) return null;
106
+ mounts.push({
107
+ at: mount.at,
108
+ root: mount.root,
109
+ definition: JSON.parse(value) as DefinitionGraph,
110
+ });
111
+ }
112
+ const graph = composeDefinitions(JSON.parse(base), mounts);
113
+ const annotations = map.annotations && read(map.annotations);
114
+ return annotations
115
+ ? factoryGraph(JSON.parse(annotations) as FactoryModel, graph, {
116
+ legacySnapshot: true,
117
+ })
118
+ : graph;
119
+ }
120
+ export function readRepositoryMap(root: string): DefinitionGraph | null {
121
+ return mapFromArtifacts(repositoryMapConfiguration(root), (file) => {
122
+ try {
123
+ return readFileSync(join(root, repositoryFile(file)), "utf8");
124
+ } catch (error) {
125
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
126
+ throw error;
127
+ }
128
+ });
129
+ }
130
+ /** Uses maps and source blobs from the exact revision; never today's ownership. */
131
+ export function captureRepositoryCommit(
132
+ root: string,
133
+ ref: string,
134
+ definition?: string,
135
+ ) {
136
+ const commit = resolveCommit(root, ref);
137
+ let canonical = !!definition;
138
+ if (!canonical) {
139
+ try {
140
+ execFileSync("git", ["cat-file", "-e", `${commit}:fractory.json`], {
141
+ cwd: root,
142
+ stdio: "ignore",
143
+ });
144
+ canonical = true;
145
+ } catch {
146
+ /* Older multi-artifact map. */
147
+ }
148
+ }
149
+ if (canonical)
150
+ return captureCommit(
151
+ root,
152
+ commit,
153
+ [repositoryFile(definition || "fractory.json")],
154
+ ([graph]) => graph,
155
+ );
156
+ let historicalConfiguration: string | undefined;
157
+ try {
158
+ historicalConfiguration = execFileSync(
159
+ "git",
160
+ ["show", `${commit}:fractory.config.json`],
161
+ {
162
+ cwd: root,
163
+ encoding: "utf8",
164
+ stdio: ["ignore", "pipe", "ignore"],
165
+ maxBuffer: 1024 * 1024,
166
+ },
167
+ );
168
+ } catch {
169
+ /* Repositories predating this configuration use the current legacy artifact locations. */
170
+ }
171
+ const config = historicalConfiguration
172
+ ? parseMapConfiguration(historicalConfiguration)
173
+ : repositoryMapConfiguration(root);
174
+ const map = config.map;
175
+ if (!map) throw Error("No factory map captured at this revision.");
176
+ return captureCommit(
177
+ root,
178
+ commit,
179
+ [map.base, ...(map.mounts || []).map((m) => m.file)],
180
+ (graphs) =>
181
+ composeDefinitions(
182
+ graphs[0],
183
+ (map.mounts || []).map((m, i) => ({
184
+ at: m.at,
185
+ root: m.root,
186
+ definition: graphs[i + 1],
187
+ })),
188
+ ),
189
+ map.annotations,
190
+ );
191
+ }