@granular-software/fractory 0.0.0-stage → 0.1.24

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 (273) 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 +118 -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 +1083 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +86 -0
  40. package/dist/core.js +206 -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 +66 -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 +4 -0
  54. package/dist/factory-graph.js +318 -0
  55. package/dist/factory-model.d.ts +97 -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/issue-cache.d.ts +9 -0
  76. package/dist/issue-cache.js +68 -0
  77. package/dist/issue-cli.d.ts +1 -0
  78. package/dist/issue-cli.js +89 -0
  79. package/dist/issue-links.d.ts +15 -0
  80. package/dist/issue-links.js +125 -0
  81. package/dist/linear-issues.d.ts +19 -0
  82. package/dist/linear-issues.js +124 -0
  83. package/dist/local-runtime.d.ts +8 -0
  84. package/dist/local-runtime.js +59 -0
  85. package/dist/map-activity.d.ts +73 -0
  86. package/dist/map-activity.js +234 -0
  87. package/dist/map-model.d.ts +5 -0
  88. package/dist/map-model.js +166 -0
  89. package/dist/map-quality.d.ts +14 -0
  90. package/dist/map-quality.js +56 -0
  91. package/dist/mapping-coverage.d.ts +87 -0
  92. package/dist/mapping-coverage.js +404 -0
  93. package/dist/model.d.ts +182 -0
  94. package/dist/model.js +66 -0
  95. package/dist/operation-benchmark-worker.d.ts +2 -0
  96. package/dist/operation-benchmark-worker.js +60 -0
  97. package/dist/operation-benchmark.d.ts +29 -0
  98. package/dist/operation-benchmark.js +1 -0
  99. package/dist/otel-metrics.d.ts +21 -0
  100. package/dist/otel-metrics.js +146 -0
  101. package/dist/performance-model.d.ts +185 -0
  102. package/dist/performance-model.js +396 -0
  103. package/dist/product-map.d.ts +69 -0
  104. package/dist/product-map.js +168 -0
  105. package/dist/provider-access.cjs +207 -0
  106. package/dist/provider-access.d.cts +14 -0
  107. package/dist/reports-cli.d.ts +1 -0
  108. package/dist/reports-cli.js +111 -0
  109. package/dist/reports-model.d.ts +27 -0
  110. package/dist/reports-model.js +39 -0
  111. package/dist/reports.d.ts +23 -0
  112. package/dist/reports.js +223 -0
  113. package/dist/repository-map.d.ts +22 -0
  114. package/dist/repository-map.js +151 -0
  115. package/dist/resource-cache.d.ts +17 -0
  116. package/dist/resource-cache.js +65 -0
  117. package/dist/review-cli.d.ts +19 -0
  118. package/dist/review-cli.js +224 -0
  119. package/dist/review.d.ts +48 -0
  120. package/dist/review.js +289 -0
  121. package/dist/runtime-metrics.d.ts +26 -0
  122. package/dist/runtime-metrics.js +290 -0
  123. package/dist/scope.d.ts +12 -0
  124. package/dist/scope.js +94 -0
  125. package/dist/sentry-activity.d.ts +39 -0
  126. package/dist/sentry-activity.js +174 -0
  127. package/dist/sentry.d.ts +130 -0
  128. package/dist/sentry.js +369 -0
  129. package/dist/service-release.d.ts +16 -0
  130. package/dist/service-release.js +14 -0
  131. package/dist/setup-cli.d.ts +2 -0
  132. package/dist/setup-cli.js +52 -0
  133. package/dist/setup-kit.cjs +163 -0
  134. package/dist/setup-kit.d.cts +32 -0
  135. package/dist/source-index.d.ts +37 -0
  136. package/dist/source-index.js +166 -0
  137. package/dist/source-review-git.d.ts +7 -0
  138. package/dist/source-review-git.js +103 -0
  139. package/dist/source-review.d.ts +16 -0
  140. package/dist/source-review.js +493 -0
  141. package/dist/telemetry.d.ts +17 -0
  142. package/dist/telemetry.js +51 -0
  143. package/dist/time-window.d.ts +9 -0
  144. package/dist/time-window.js +35 -0
  145. package/dist/trace-evidence.d.ts +23 -0
  146. package/dist/trace-evidence.js +55 -0
  147. package/dist/trace-model.d.ts +26 -0
  148. package/dist/trace-model.js +1 -0
  149. package/dist/tracing.d.ts +44 -0
  150. package/dist/tracing.js +123 -0
  151. package/dist/work-check.d.ts +17 -0
  152. package/dist/work-check.js +110 -0
  153. package/dist/work-cli.d.ts +1 -0
  154. package/dist/work-cli.js +148 -0
  155. package/dist/work-context.d.ts +57 -0
  156. package/dist/work-context.js +568 -0
  157. package/dist/work-intents.d.ts +6 -0
  158. package/dist/work-intents.js +140 -0
  159. package/dist/work-items.d.ts +58 -0
  160. package/dist/work-items.js +86 -0
  161. package/dist/work-model.d.ts +110 -0
  162. package/dist/work-model.js +261 -0
  163. package/dist/work-review-git.d.ts +8 -0
  164. package/dist/work-review-git.js +111 -0
  165. package/dist/work-review.d.ts +26 -0
  166. package/dist/work-review.js +426 -0
  167. package/dist/work-switcher-model.d.ts +43 -0
  168. package/dist/work-switcher-model.js +79 -0
  169. package/dist/work-switcher.d.ts +6 -0
  170. package/dist/work-switcher.js +171 -0
  171. package/dist/working-cli.d.ts +1 -0
  172. package/dist/working-cli.js +33 -0
  173. package/dist/working-code.d.ts +74 -0
  174. package/dist/working-code.js +421 -0
  175. package/dist/workspace-notes.d.ts +71 -0
  176. package/dist/workspace-notes.js +177 -0
  177. package/dist/workspace-tests.d.ts +21 -0
  178. package/dist/workspace-tests.js +573 -0
  179. package/package.json +547 -4
  180. package/src/activity-volume.ts +149 -0
  181. package/src/annotations.ts +481 -0
  182. package/src/benchmark-cli.ts +118 -0
  183. package/src/benchmark-worker.ts +22 -0
  184. package/src/benchmarks.ts +493 -0
  185. package/src/bin.ts +54 -0
  186. package/src/block-cli.ts +106 -0
  187. package/src/block-documents.ts +117 -0
  188. package/src/change-impact.ts +280 -0
  189. package/src/check-source.ts +82 -0
  190. package/src/checks-model.ts +108 -0
  191. package/src/cli.ts +440 -0
  192. package/src/code-model.ts +159 -0
  193. package/src/code-store.ts +98 -0
  194. package/src/compare-artifact.ts +314 -0
  195. package/src/compare.ts +440 -0
  196. package/src/compiler.ts +1326 -0
  197. package/src/compose.ts +94 -0
  198. package/src/core.ts +357 -0
  199. package/src/coverage-cli.ts +52 -0
  200. package/src/declaration-sources.ts +69 -0
  201. package/src/declared-graph.ts +74 -0
  202. package/src/display-name.ts +8 -0
  203. package/src/error-heat.ts +161 -0
  204. package/src/evidence.ts +94 -0
  205. package/src/factory-graph.ts +378 -0
  206. package/src/factory-model.ts +73 -0
  207. package/src/git-code.ts +461 -0
  208. package/src/git-refs.ts +43 -0
  209. package/src/history-activity.ts +146 -0
  210. package/src/history-churn.ts +416 -0
  211. package/src/history-git.ts +163 -0
  212. package/src/history-ledger.ts +636 -0
  213. package/src/history-ownership.ts +116 -0
  214. package/src/history-source.ts +117 -0
  215. package/src/integrations-cli.ts +187 -0
  216. package/src/issue-cache.ts +96 -0
  217. package/src/issue-cli.ts +137 -0
  218. package/src/issue-links.ts +153 -0
  219. package/src/linear-issues.ts +154 -0
  220. package/src/local-runtime.ts +70 -0
  221. package/src/map-activity.ts +309 -0
  222. package/src/map-model.ts +213 -0
  223. package/src/map-quality.ts +61 -0
  224. package/src/mapping-coverage.ts +570 -0
  225. package/src/model.ts +221 -0
  226. package/src/operation-benchmark-worker.ts +60 -0
  227. package/src/operation-benchmark.ts +28 -0
  228. package/src/otel-metrics.ts +176 -0
  229. package/src/performance-model.ts +575 -0
  230. package/src/product-map.ts +236 -0
  231. package/src/provider-access.cjs +207 -0
  232. package/src/provider-access.d.cts +14 -0
  233. package/src/reports-cli.ts +125 -0
  234. package/src/reports-model.ts +73 -0
  235. package/src/reports.ts +276 -0
  236. package/src/repository-map.ts +189 -0
  237. package/src/resource-cache.ts +76 -0
  238. package/src/review-cli.ts +256 -0
  239. package/src/review.ts +376 -0
  240. package/src/runtime-metrics.ts +386 -0
  241. package/src/scope.ts +103 -0
  242. package/src/sentry-activity.ts +234 -0
  243. package/src/sentry.ts +545 -0
  244. package/src/service-release.ts +18 -0
  245. package/src/setup-cli.ts +58 -0
  246. package/src/setup-kit.cjs +163 -0
  247. package/src/setup-kit.d.cts +32 -0
  248. package/src/source-index.ts +205 -0
  249. package/src/source-review-git.ts +129 -0
  250. package/src/source-review.ts +637 -0
  251. package/src/telemetry.ts +68 -0
  252. package/src/time-window.ts +51 -0
  253. package/src/trace-evidence.ts +80 -0
  254. package/src/trace-model.ts +26 -0
  255. package/src/tracing.ts +165 -0
  256. package/src/work-check.ts +143 -0
  257. package/src/work-cli.ts +195 -0
  258. package/src/work-context.ts +713 -0
  259. package/src/work-intents.ts +196 -0
  260. package/src/work-items.ts +151 -0
  261. package/src/work-model.ts +400 -0
  262. package/src/work-review-git.ts +130 -0
  263. package/src/work-review.ts +573 -0
  264. package/src/work-switcher-model.ts +121 -0
  265. package/src/work-switcher.ts +191 -0
  266. package/src/working-cli.ts +38 -0
  267. package/src/working-code.ts +582 -0
  268. package/src/workspace-notes.ts +203 -0
  269. package/src/workspace-tests.ts +654 -0
  270. package/toolkit/GUIDE.md +305 -0
  271. package/toolkit/SKILL.md +131 -0
  272. package/toolkit/bin/fractory +2 -0
  273. package/toolkit/build.json +1 -0
@@ -0,0 +1,207 @@
1
+ /** Fixed read-only provider checks. Never return credential material or provider error bodies. */
2
+ const { execFileSync } = require("node:child_process");
3
+ const { readFileSync } = require("node:fs");
4
+ const { join } = require("node:path");
5
+ const { homedir } = require("node:os");
6
+ const { parseEnv } = require("node:util");
7
+ function command(binary, args) {
8
+ return execFileSync(binary, args, {
9
+ encoding: "utf8",
10
+ timeout: 15000,
11
+ maxBuffer: 1024 * 1024,
12
+ stdio: ["ignore", "pipe", "pipe"],
13
+ }).trim();
14
+ }
15
+ function discovery(root, env = process.env) {
16
+ const values = { ...env };
17
+ for (const file of [
18
+ ".env",
19
+ ".env.local",
20
+ ])
21
+ try {
22
+ for (const [key, value] of Object.entries(
23
+ parseEnv(readFileSync(join(root, file), "utf8")),
24
+ ))
25
+ if (
26
+ /^(FRACTAL_(GITHUB_(TOKEN|REPOSITORY)|SENTRY_(TOKEN|ORG|PROJECTS)|LINEAR_(API_KEY|WORKSPACE_ID|WORKSPACE_URL))|SENTRY_(AUTH_TOKEN|ORG|PROJECT)|LINEAR_API_KEY|GH_TOKEN|GITHUB_TOKEN)$/.test(
27
+ key,
28
+ )
29
+ )
30
+ values[key] = value;
31
+ } catch (e) {
32
+ if (e.code !== "ENOENT")
33
+ throw Error("Could not read repository integration settings.");
34
+ }
35
+ let repository = values.FRACTAL_GITHUB_REPOSITORY;
36
+ if (!repository)
37
+ try {
38
+ const remote = command("git", [
39
+ "-C",
40
+ root,
41
+ "remote",
42
+ "get-url",
43
+ "origin",
44
+ ]);
45
+ repository = remote.match(
46
+ /(?:github\.com[:/])([\w.-]+\/[\w.-]+?)(?:\.git)?$/,
47
+ )?.[1];
48
+ } catch {}
49
+ let sentry = values.FRACTAL_SENTRY_TOKEN || values.SENTRY_AUTH_TOKEN;
50
+ if (!sentry)
51
+ try {
52
+ sentry = readFileSync(join(homedir(), ".sentryclirc"), "utf8").match(
53
+ /\[auth\][\s\S]*?^token\s*=\s*(\S+)/m,
54
+ )?.[1];
55
+ } catch {}
56
+ return {
57
+ github: {
58
+ token:
59
+ values.FRACTAL_GITHUB_TOKEN || values.GH_TOKEN || values.GITHUB_TOKEN,
60
+ repository,
61
+ },
62
+ sentry: {
63
+ token: sentry,
64
+ org: values.FRACTAL_SENTRY_ORG || values.SENTRY_ORG,
65
+ projects: values.FRACTAL_SENTRY_PROJECTS || values.SENTRY_PROJECT,
66
+ },
67
+ linear: {
68
+ token: values.FRACTAL_LINEAR_API_KEY || values.LINEAR_API_KEY,
69
+ workspaceId: values.FRACTAL_LINEAR_WORKSPACE_ID,
70
+ workspaceUrl: values.FRACTAL_LINEAR_WORKSPACE_URL,
71
+ },
72
+ };
73
+ }
74
+ async function checkProvider(provider, input, fetcher = fetch) {
75
+ const config = { ...input };
76
+ if (provider === "github" && config.mode === "cli") {
77
+ try {
78
+ config.token = command("gh", [
79
+ "auth",
80
+ "token",
81
+ "--hostname",
82
+ "github.com",
83
+ ]);
84
+ } catch {
85
+ throw Error(
86
+ "GitHub authorization required. Run fractory integrations connect github --login.",
87
+ );
88
+ }
89
+ }
90
+ if (provider === "sentry" && config.mode === "cli") {
91
+ try {
92
+ config.token = command("sentry", ["auth", "token"]);
93
+ } catch {
94
+ throw Error(
95
+ "Sentry authorization required. Run fractory integrations connect sentry --login.",
96
+ );
97
+ }
98
+ }
99
+ if (!config.token)
100
+ throw Error(
101
+ "No credential found. The agent must complete provider authorization.",
102
+ );
103
+ const request = async (url, body) => {
104
+ let response;
105
+ try {
106
+ response = await fetcher(url, {
107
+ method: body ? "POST" : "GET",
108
+ headers: {
109
+ Authorization:
110
+ provider === "linear" ? config.token : `Bearer ${config.token}`,
111
+ "Content-Type": "application/json",
112
+ Accept: "application/json",
113
+ },
114
+ ...(body ? { body: JSON.stringify(body) } : {}),
115
+ redirect: "error",
116
+ signal: AbortSignal.timeout(15000),
117
+ });
118
+ } catch {
119
+ throw Error(
120
+ `${provider} could not be reached. Check the network and retry.`,
121
+ );
122
+ }
123
+ if (!response.ok)
124
+ throw Error(
125
+ `${provider} access check failed (HTTP ${response.status}). Credentials were not saved.`,
126
+ );
127
+ const json = await response.json();
128
+ if (json.errors)
129
+ throw Error(
130
+ `${provider} rejected the read request. Check the account and read permissions.`,
131
+ );
132
+ return json;
133
+ };
134
+ let account;
135
+ if (provider === "github") {
136
+ if (!/^[\w.-]+\/[\w.-]+$/.test(config.repository || ""))
137
+ throw Error("Choose the GitHub repository with --repository owner/repo.");
138
+ const repo = await request(
139
+ "https://api.github.com/repos/" + config.repository,
140
+ );
141
+ if (repo.full_name?.toLowerCase() !== config.repository.toLowerCase())
142
+ throw Error("GitHub returned a different repository.");
143
+ await request(
144
+ "https://api.github.com/repos/" +
145
+ config.repository +
146
+ "/pulls?state=open&per_page=1",
147
+ );
148
+ account = repo.full_name;
149
+ } else if (provider === "sentry") {
150
+ if (config.org && !/^[\w.-]+$/.test(config.org))
151
+ throw Error("Invalid Sentry organization.");
152
+ if (!config.org) {
153
+ const orgs = await request("https://sentry.io/api/0/organizations/");
154
+ if (orgs.length !== 1)
155
+ throw Error("Choose a Sentry organization with --org.");
156
+ config.org = orgs[0].slug;
157
+ }
158
+ const projects = await request(
159
+ "https://sentry.io/api/0/organizations/" + config.org + "/projects/",
160
+ );
161
+ const chosen = (config.projects || "")
162
+ .split(",")
163
+ .map((s) => s.trim())
164
+ .filter(Boolean);
165
+ if (chosen.some((p) => !projects.some((x) => x.slug === p || x.id === p)))
166
+ throw Error(
167
+ "A selected Sentry project is not accessible to this account.",
168
+ );
169
+ if (!chosen.length)
170
+ throw Error(
171
+ "Choose this repository’s Sentry projects with --projects slug,slug.",
172
+ );
173
+ await request(
174
+ "https://sentry.io/api/0/projects/" +
175
+ config.org +
176
+ "/" +
177
+ projects.find((p) => p.slug === chosen[0] || p.id === chosen[0]).slug +
178
+ "/issues/?limit=1&statsPeriod=24h",
179
+ );
180
+ config.projects = chosen.join(",");
181
+ account = config.org;
182
+ } else if (provider === "linear") {
183
+ const data = (
184
+ await request("https://api.linear.app/graphql", {
185
+ query:
186
+ "query FractoryAccess { viewer { id name } organization { id name urlKey } issues(first: 1) { nodes { id } } }",
187
+ })
188
+ ).data;
189
+ if (!data?.organization?.id)
190
+ throw Error("Linear did not return a workspace.");
191
+ if (config.workspaceId && config.workspaceId !== data.organization.id)
192
+ throw Error("This credential belongs to a different Linear workspace.");
193
+ config.workspaceId = data.organization.id;
194
+ config.workspaceUrl = "https://linear.app/" + data.organization.urlKey;
195
+ account = data.organization.name;
196
+ } else throw Error("Unsupported integration.");
197
+ if (config.mode === "cli") delete config.token;
198
+ else config.mode = "token";
199
+ return {
200
+ value: Object.fromEntries(
201
+ Object.entries(config).filter(([, v]) => typeof v === "string"),
202
+ ),
203
+ account,
204
+ checkedAt: new Date().toISOString(),
205
+ };
206
+ }
207
+ module.exports = { discovery, checkProvider };
@@ -0,0 +1,14 @@
1
+ export type Provider = "github" | "sentry" | "linear";
2
+ export function discovery(
3
+ root: string,
4
+ env?: NodeJS.ProcessEnv,
5
+ ): Record<Provider, Record<string, string | undefined>>;
6
+ export function checkProvider(
7
+ provider: Provider,
8
+ input: Record<string, string>,
9
+ fetcher?: typeof fetch,
10
+ ): Promise<{
11
+ value: Record<string, string>;
12
+ account: string;
13
+ checkedAt: string;
14
+ }>;
@@ -0,0 +1 @@
1
+ export declare function runReports(args: string[]): Promise<string>;
@@ -0,0 +1,111 @@
1
+ import { readRepositoryMap } from "./repository-map.js";
2
+ import { listWorkContexts, workDeepLink } from "./work-context.js";
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.js";
8
+ import { reportsForBlock } from "./reports-model.js";
9
+ export async function runReports(args) {
10
+ if (args.includes("--help"))
11
+ 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.";
12
+ const value = (name) => {
13
+ const index = args.indexOf(name);
14
+ if (index < 0)
15
+ return undefined;
16
+ if (!args[index + 1] || args[index + 1].startsWith("--"))
17
+ throw Error(`${name} needs a value.`);
18
+ return args[index + 1];
19
+ };
20
+ let root = resolve(value("--root") || process.cwd());
21
+ if (!value("--root"))
22
+ while (!existsSync(join(root, ".git")) &&
23
+ !existsSync(join(root, "fractory.json")) &&
24
+ dirname(root) !== root)
25
+ root = dirname(root);
26
+ const action = args[1]?.startsWith("--") ? "list" : args[1] || "list";
27
+ const reportURL = (report) => {
28
+ let link = `fractory://open?repo=${encodeURIComponent(root)}`;
29
+ try {
30
+ const context = listWorkContexts(root).find((t) => t.path === realpathSync(root));
31
+ link = workDeepLink(root, context?.id || "main");
32
+ }
33
+ catch {
34
+ /* Offline report fixtures still produce a repository link. */
35
+ }
36
+ const url = new URL(link);
37
+ url.searchParams.set("block", report.blocks[0]);
38
+ url.searchParams.set("inspect", report.blocks[0]);
39
+ url.searchParams.set("workspace", "reports");
40
+ url.searchParams.set("report", report.id);
41
+ return url.href;
42
+ };
43
+ if (["show", "read", "unread", "open"].includes(action)) {
44
+ const id = args[2];
45
+ if (!id || id.startsWith("--"))
46
+ throw Error("Choose a report ID from fractory reports list.");
47
+ const report = readReport(root, id);
48
+ if (action === "open") {
49
+ const url = reportURL(report);
50
+ execFileSync("open", [url], { stdio: "ignore", timeout: 5000 });
51
+ return url;
52
+ }
53
+ return JSON.stringify(action === "show"
54
+ ? report
55
+ : markReport(root, id, report.revision, action === "read"), null, 2);
56
+ }
57
+ if (!["list", "create"].includes(action))
58
+ throw Error(`Unknown reports command: ${action}`);
59
+ const graph = readRepositoryMap(root);
60
+ if (!graph)
61
+ throw Error("No Fractory map in this repository. Run fractory setup.");
62
+ if (action === "list") {
63
+ const view = listReports(root);
64
+ const reports = value("--block")
65
+ ? reportsForBlock(graph, view.reports, value("--block"))
66
+ : view.reports;
67
+ return JSON.stringify({
68
+ ...view,
69
+ reports: args.includes("--unread")
70
+ ? reports.filter((report) => report.unread)
71
+ : reports,
72
+ }, null, 2);
73
+ }
74
+ const blocks = args.flatMap((arg, index) => arg === "--block" ? [args[index + 1]] : []);
75
+ if (blocks.some((block) => !block || block.startsWith("--")))
76
+ throw Error("--block needs a block ID.");
77
+ const file = value("--file"), stdin = args.includes("--stdin");
78
+ if ((!file && !stdin) || (file && stdin))
79
+ throw Error("Supply Markdown with either --file PATH or --stdin.");
80
+ if (stdin && process.stdin.isTTY)
81
+ throw Error("Pipe Markdown to --stdin, or use --file PATH.");
82
+ let body;
83
+ if (file) {
84
+ const path = resolve(process.cwd(), file), stat = statSync(path);
85
+ if (!stat.isFile() || stat.size > 128000)
86
+ throw Error("Supply a Markdown file below 128 KB.");
87
+ body = readFileSync(path, "utf8");
88
+ }
89
+ else {
90
+ const chunks = [];
91
+ let size = 0;
92
+ for await (const chunk of process.stdin) {
93
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
94
+ size += buffer.length;
95
+ if (size > 128000)
96
+ throw Error("Keep this report below 128 KB.");
97
+ chunks.push(buffer);
98
+ }
99
+ body = Buffer.concat(chunks).toString("utf8");
100
+ }
101
+ const report = createReport(root, graph, {
102
+ title: value("--title") || "",
103
+ blocks,
104
+ body,
105
+ author: value("--author"),
106
+ });
107
+ const url = reportURL(report);
108
+ if (args.includes("--open"))
109
+ execFileSync("open", [url], { stdio: "ignore", timeout: 5000 });
110
+ return JSON.stringify({ ...report, url }, null, 2);
111
+ }
@@ -0,0 +1,27 @@
1
+ import type { DefinitionGraph } from "./model.js";
2
+ export interface ReportMetadata {
3
+ schema: "fractory.report.v1";
4
+ id: string;
5
+ title: string;
6
+ blocks: string[];
7
+ createdAt: string;
8
+ author?: string;
9
+ codeRevision?: string;
10
+ }
11
+ export interface BlockReport extends ReportMetadata {
12
+ file: string;
13
+ revision: string;
14
+ unread: boolean;
15
+ }
16
+ export interface ReportDocument extends BlockReport {
17
+ body: string;
18
+ }
19
+ export interface ReportsView {
20
+ reports: BlockReport[];
21
+ warnings: string[];
22
+ }
23
+ export declare function resolvedReportBlock(graph: DefinitionGraph, id: string): string;
24
+ /** A multi-target report contributes once to each ancestor, including the root. */
25
+ export declare function reportBlocks(graph: DefinitionGraph, report: Pick<BlockReport, "blocks">): Set<string>;
26
+ export declare function unreadReportCounts(graph: DefinitionGraph, reports: BlockReport[]): Record<string, number>;
27
+ export declare function reportsForBlock(graph: DefinitionGraph, reports: BlockReport[], block: string): BlockReport[];
@@ -0,0 +1,39 @@
1
+ export function resolvedReportBlock(graph, id) {
2
+ const seen = new Set();
3
+ while (graph.aliases && Object.hasOwn(graph.aliases, id) && typeof graph.aliases[id] === "string" && !seen.has(id)) {
4
+ seen.add(id);
5
+ id = graph.aliases[id];
6
+ }
7
+ return id;
8
+ }
9
+ /** A multi-target report contributes once to each ancestor, including the root. */
10
+ export function reportBlocks(graph, report) {
11
+ const byId = new Map(graph.elements.map((node) => [node.id, node]));
12
+ const owners = new Set();
13
+ // The repository inbox must also retain reports whose target was removed.
14
+ // Their tree placement stays explicitly Unassigned, never a guessed leaf.
15
+ if (byId.has(graph.id))
16
+ owners.add(graph.id);
17
+ for (const target of report.blocks) {
18
+ let id = resolvedReportBlock(graph, target);
19
+ const seen = new Set();
20
+ while (id && byId.has(id) && !seen.has(id)) {
21
+ seen.add(id);
22
+ owners.add(id);
23
+ id = byId.get(id).parent;
24
+ }
25
+ }
26
+ return owners;
27
+ }
28
+ export function unreadReportCounts(graph, reports) {
29
+ const counts = Object.create(null);
30
+ for (const report of reports)
31
+ if (report.unread)
32
+ for (const id of reportBlocks(graph, report))
33
+ counts[id] = (counts[id] || 0) + 1;
34
+ return counts;
35
+ }
36
+ export function reportsForBlock(graph, reports, block) {
37
+ const id = resolvedReportBlock(graph, block);
38
+ return reports.filter((report) => reportBlocks(graph, report).has(id));
39
+ }
@@ -0,0 +1,23 @@
1
+ import type { DefinitionGraph } from "./model.js";
2
+ import { type ReportDocument, type ReportsView } from "./reports-model.js";
3
+ export declare function listReports(root: string, ref?: string): ReportsView;
4
+ export declare function readReport(root: string, id: string, ref?: string): ReportDocument;
5
+ export declare function createReport(root: string, graph: DefinitionGraph, input: {
6
+ title: string;
7
+ blocks: string[];
8
+ body: string;
9
+ author?: string;
10
+ }): ReportDocument;
11
+ export declare function markReport(root: string, id: string, revision: string, read: boolean, ref?: string): {
12
+ unread: boolean;
13
+ body: string;
14
+ file: string;
15
+ revision: string;
16
+ schema: "fractory.report.v1";
17
+ id: string;
18
+ title: string;
19
+ blocks: string[];
20
+ createdAt: string;
21
+ author?: string;
22
+ codeRevision?: string;
23
+ };
@@ -0,0 +1,223 @@
1
+ import { readGit } from "./git-refs.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { checkedPath, noteRevision, WorkspaceConflict, } from "./workspace-notes.js";
7
+ import { resolvedReportBlock, } from "./reports-model.js";
8
+ const directory = "docs/fractory/reports";
9
+ const limit = 128_000;
10
+ const validId = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
11
+ const cache = new Map();
12
+ function reportFile(id) {
13
+ if (!validId.test(id))
14
+ throw Error("Choose a valid report ID.");
15
+ return `${directory}/${id}.md`;
16
+ }
17
+ function receiptFile(id) {
18
+ reportFile(id);
19
+ return `.fractal/reports/read/${id}.json`;
20
+ }
21
+ function atomic(root, file, body) {
22
+ const path = checkedPath(root, file, true);
23
+ mkdirSync(dirname(path), { recursive: true });
24
+ checkedPath(root, file, true);
25
+ const temp = join(dirname(path), `.fractory-${randomUUID()}.tmp`);
26
+ try {
27
+ writeFileSync(temp, body, { flag: "wx", mode: 0o600 });
28
+ renameSync(temp, path);
29
+ }
30
+ finally {
31
+ if (existsSync(temp))
32
+ unlinkSync(temp);
33
+ }
34
+ }
35
+ function parse(text, id) {
36
+ // Standard Markdown front matter with a JSON/YAML flow mapping. Reports do
37
+ // not need a new parser dependency or an additional registry of bindings.
38
+ const match = /^---\r?\nfractory: ([^\r\n]+)\r?\n---\r?\n/.exec(text);
39
+ if (!match)
40
+ throw Error("Missing Fractory report front matter.");
41
+ const metadata = JSON.parse(match[1]);
42
+ if (metadata.schema !== "fractory.report.v1" ||
43
+ metadata.id !== id ||
44
+ !validId.test(metadata.id) ||
45
+ typeof metadata.title !== "string" ||
46
+ !metadata.title.trim() ||
47
+ metadata.title.length > 160 ||
48
+ !Array.isArray(metadata.blocks) ||
49
+ !metadata.blocks.length ||
50
+ metadata.blocks.some((block) => typeof block !== "string" || !block || block.length > 4096) ||
51
+ typeof metadata.createdAt !== "string" ||
52
+ !Number.isFinite(Date.parse(metadata.createdAt)) ||
53
+ (metadata.author !== undefined &&
54
+ (typeof metadata.author !== "string" || metadata.author.length > 100)) ||
55
+ (metadata.codeRevision !== undefined &&
56
+ !/^[a-f0-9]{40,64}$/.test(metadata.codeRevision)))
57
+ throw Error("Invalid Fractory report metadata.");
58
+ return { metadata, body: text.slice(match[0].length) };
59
+ }
60
+ function readRevision(root, id) {
61
+ const path = checkedPath(root, receiptFile(id), true);
62
+ if (!existsSync(path))
63
+ return undefined;
64
+ try {
65
+ const value = JSON.parse(readFileSync(path, "utf8"));
66
+ return typeof value.revision === "string" ? value.revision : undefined;
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ }
72
+ function summary(root, id) {
73
+ const file = reportFile(id), path = checkedPath(root, file);
74
+ const stat = lstatSync(path);
75
+ if (!stat.isFile() || stat.size > limit)
76
+ throw Error("Report must be a Markdown file below 128 KB.");
77
+ const stamp = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
78
+ let entry = cache.get(path);
79
+ if (!entry || entry.stamp !== stamp) {
80
+ const text = readFileSync(path, "utf8");
81
+ entry = {
82
+ stamp,
83
+ metadata: parse(text, id).metadata,
84
+ revision: noteRevision(text),
85
+ };
86
+ cache.set(path, entry);
87
+ if (cache.size > 2048)
88
+ cache.delete(cache.keys().next().value);
89
+ }
90
+ return {
91
+ ...entry.metadata,
92
+ file,
93
+ revision: entry.revision,
94
+ unread: readRevision(root, id) !== entry.revision,
95
+ };
96
+ }
97
+ export function listReports(root, ref) {
98
+ if (ref) {
99
+ const reports = [], warnings = [];
100
+ for (const file of readGit(root, [
101
+ "ls-tree",
102
+ "-r",
103
+ "--name-only",
104
+ ref,
105
+ "--",
106
+ directory,
107
+ ])
108
+ .trim()
109
+ .split("\n")
110
+ .filter(Boolean)) {
111
+ try {
112
+ const id = file.split("/").at(-1).replace(/\.md$/, ""), { body, ...report } = readReport(root, id, ref);
113
+ reports.push(report);
114
+ }
115
+ catch (e) {
116
+ warnings.push(`${file}: unreadable report`);
117
+ }
118
+ }
119
+ return {
120
+ reports: reports.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
121
+ warnings,
122
+ };
123
+ }
124
+ const path = checkedPath(root, directory, true);
125
+ if (!existsSync(path))
126
+ return { reports: [], warnings: [] };
127
+ const reports = [], warnings = [];
128
+ for (const file of readdirSync(path).sort()) {
129
+ if (!file.endsWith(".md"))
130
+ continue;
131
+ const id = file.slice(0, -3);
132
+ try {
133
+ reports.push(summary(root, id));
134
+ }
135
+ catch (error) {
136
+ warnings.push(`${file}: ${error instanceof Error ? error.message : "Unreadable report"}`);
137
+ }
138
+ }
139
+ reports.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id));
140
+ return { reports, warnings };
141
+ }
142
+ export function readReport(root, id, ref) {
143
+ if (ref) {
144
+ const file = reportFile(id), text = readGit(root, ["show", `${ref}:${file}`]);
145
+ if (Buffer.byteLength(text) > limit)
146
+ throw Error("Report exceeds read budget.");
147
+ const { metadata, body } = parse(text, id), revision = noteRevision(text);
148
+ return {
149
+ ...metadata,
150
+ file,
151
+ revision,
152
+ body,
153
+ unread: readRevision(root, id) !== revision,
154
+ };
155
+ }
156
+ const file = reportFile(id), path = checkedPath(root, file);
157
+ const stat = lstatSync(path);
158
+ if (!stat.isFile() || stat.size > limit)
159
+ throw Error("Report must be a Markdown file below 128 KB.");
160
+ const text = readFileSync(path, "utf8");
161
+ if (Buffer.byteLength(text) > limit)
162
+ throw Error("Keep this report below 128 KB.");
163
+ const { metadata, body } = parse(text, id), revision = noteRevision(text);
164
+ return {
165
+ ...metadata,
166
+ file,
167
+ revision,
168
+ unread: readRevision(root, id) !== revision,
169
+ body,
170
+ };
171
+ }
172
+ export function createReport(root, graph, input) {
173
+ if (!input.title.trim() ||
174
+ input.title.length > 160 ||
175
+ /[\r\n\0]/.test(input.title))
176
+ throw Error("Use a report title of 1–160 characters.");
177
+ if (!input.body.trim())
178
+ throw Error("Write the report’s Markdown content.");
179
+ if (input.author !== undefined &&
180
+ (input.author.length > 100 || /[\r\n\0]/.test(input.author)))
181
+ throw Error("Use a short author label.");
182
+ const blocks = [
183
+ ...new Set(input.blocks.map((id) => resolvedReportBlock(graph, id))),
184
+ ];
185
+ if (!blocks.length ||
186
+ blocks.some((id) => !graph.elements.some((node) => node.id === id)))
187
+ throw Error("Attach this report to at least one existing block ID.");
188
+ let codeRevision;
189
+ try {
190
+ codeRevision = execFileSync("git", ["rev-parse", "HEAD"], {
191
+ cwd: root,
192
+ encoding: "utf8",
193
+ stdio: ["ignore", "pipe", "ignore"],
194
+ timeout: 2000,
195
+ }).trim();
196
+ }
197
+ catch { }
198
+ const metadata = {
199
+ schema: "fractory.report.v1",
200
+ id: randomUUID(),
201
+ title: input.title.trim(),
202
+ blocks,
203
+ createdAt: new Date().toISOString(),
204
+ ...(input.author ? { author: input.author } : {}),
205
+ ...(codeRevision ? { codeRevision } : {}),
206
+ };
207
+ const body = `---\nfractory: ${JSON.stringify(metadata)}\n---\n\n${input.body.trim()}\n`;
208
+ if (Buffer.byteLength(body) > limit)
209
+ throw Error("Keep this report below 128 KB.");
210
+ atomic(root, reportFile(metadata.id), body);
211
+ return readReport(root, metadata.id);
212
+ }
213
+ export function markReport(root, id, revision, read, ref) {
214
+ const report = readReport(root, id, ref);
215
+ if (report.revision !== revision)
216
+ throw new WorkspaceConflict("This report changed. Read its latest version before marking it read.");
217
+ const file = receiptFile(id), path = checkedPath(root, file, true);
218
+ if (read)
219
+ atomic(root, file, JSON.stringify({ revision }));
220
+ else if (existsSync(path))
221
+ unlinkSync(path);
222
+ return { ...report, unread: !read };
223
+ }
@@ -0,0 +1,22 @@
1
+ import type { DefinitionGraph } from "./model.js";
2
+ import type { SentryAreaRule } from "./sentry.js";
3
+ export interface RepositoryMapConfiguration {
4
+ /** Optional compatibility with repositories which generate several map artifacts. */
5
+ map?: {
6
+ base: string;
7
+ mounts?: Array<{
8
+ file: string;
9
+ at: string;
10
+ root: string;
11
+ }>;
12
+ annotations?: string;
13
+ };
14
+ sentryAreas?: SentryAreaRule[];
15
+ }
16
+ export declare function repositoryMapConfiguration(root: string): RepositoryMapConfiguration;
17
+ export declare function parseMapConfiguration(text: string): RepositoryMapConfiguration;
18
+ export declare function repositoryMapPaths(root: string, configuration?: RepositoryMapConfiguration): string[];
19
+ export declare function mapFromArtifacts(config: RepositoryMapConfiguration, read: (file: string) => string | undefined): DefinitionGraph | null;
20
+ export declare function readRepositoryMap(root: string): DefinitionGraph | null;
21
+ /** Uses maps and source blobs from the exact revision; never today's ownership. */
22
+ export declare function captureRepositoryCommit(root: string, ref: string, definition?: string): import("./code-model.js").CodeSnapshot;