@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,159 @@
1
+ import { connect } from "node:net";
2
+ import { existsSync, readFileSync, lstatSync, realpathSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
+ import { discovery } from "./provider-access.cjs";
7
+ const providers = ["github", "sentry", "linear"];
8
+ function argument(args, name) {
9
+ const i = args.indexOf(name);
10
+ if (i < 0)
11
+ return undefined;
12
+ if (!args[i + 1] || args[i + 1].startsWith("--"))
13
+ throw Error(name + " needs a value.");
14
+ return args[i + 1];
15
+ }
16
+ export async function agentRequest(request) {
17
+ const directory = process.env.FRACTORY_AGENT_DATA_DIR ||
18
+ join(homedir(), "Library/Application Support/Fractory");
19
+ const file = join(directory, "agent-bridge.json");
20
+ if (!existsSync(file) &&
21
+ process.platform === "darwin" &&
22
+ !process.env.FRACTORY_AGENT_DATA_DIR) {
23
+ execFileSync("open", ["-a", "Fractory"], {
24
+ stdio: "ignore",
25
+ timeout: 5000,
26
+ });
27
+ for (let n = 0; n < 50 && !existsSync(file); n++)
28
+ await new Promise((r) => setTimeout(r, 100));
29
+ }
30
+ const secure = (name) => {
31
+ const s = lstatSync(name);
32
+ if (s.isSymbolicLink() ||
33
+ (s.mode & 0o077) !== 0 ||
34
+ (process.getuid && s.uid !== process.getuid()))
35
+ throw Error("The Fractory agent bridge must be private to your account.");
36
+ };
37
+ if (!existsSync(file))
38
+ throw Error("Open Fractory once, then retry. Its local credential bridge is not running.");
39
+ secure(file);
40
+ const bridge = JSON.parse(readFileSync(file, "utf8"));
41
+ secure(bridge.socket);
42
+ if (bridge.version !== 1 ||
43
+ typeof bridge.nonce !== "string" ||
44
+ bridge.socket !== join(directory, "agent.sock"))
45
+ throw Error("Invalid Fractory agent bridge.");
46
+ return await new Promise((resolve, reject) => {
47
+ const socket = connect(bridge.socket);
48
+ let data = "";
49
+ socket.setTimeout(25000, () => {
50
+ socket.destroy();
51
+ reject(Error("Fractory did not respond. Reopen the app and retry."));
52
+ });
53
+ socket.on("connect", () => socket.write(JSON.stringify({ ...request, nonce: bridge.nonce }) + "\n"));
54
+ socket.on("error", () => reject(Error("Could not reach Fractory. Reopen the app and retry.")));
55
+ socket.on("data", (chunk) => {
56
+ data += chunk.toString();
57
+ if (data.length > 65536) {
58
+ socket.destroy();
59
+ reject(Error("Invalid bridge response."));
60
+ return;
61
+ }
62
+ if (!data.includes("\n"))
63
+ return;
64
+ socket.end();
65
+ try {
66
+ const result = JSON.parse(data.split("\n")[0]);
67
+ if (!result.ok)
68
+ reject(Error(result.error));
69
+ else
70
+ resolve(result.data);
71
+ }
72
+ catch {
73
+ reject(Error("Invalid bridge response."));
74
+ }
75
+ });
76
+ });
77
+ }
78
+ export async function runIntegrations(args) {
79
+ if (args.includes("--help") || args.length === 1)
80
+ return `fractory integrations status [--root PATH]
81
+ fractory integrations connect github|sentry|linear|all [--auto] [--login] [--root PATH]
82
+ fractory integrations connect PROVIDER --token-stdin [provider options]
83
+ fractory integrations check PROVIDER|all [--root PATH]
84
+ fractory integrations disconnect PROVIDER [--root PATH]
85
+ Options: --repository owner/repo, --org sentry-org, --projects slug,slug, --workspace-id ID.
86
+ Existing logins and allowed repository environment values are discovered automatically. GitHub and Sentry --login use official browser authorization. Linear without a credential returns an agent authorization task. Agents can send acquired credentials over stdin; secrets are never accepted as command arguments or printed. Credentials are verified and stored by the running Mac app in encrypted, per-repository settings. No credentials enter Git.`;
87
+ if (args.includes("--token"))
88
+ throw Error("Do not put tokens in command arguments. Use --token-stdin with an agent-owned pipe.");
89
+ const root = realpathSync(resolve(argument(args, "--root") || process.cwd()));
90
+ const action = args[1];
91
+ if (!["status", "connect", "check", "disconnect"].includes(action))
92
+ throw Error("Choose status, connect, check or disconnect.");
93
+ if (action === "status")
94
+ return JSON.stringify(await agentRequest({ op: "status", root }), null, 2);
95
+ const selected = args[2];
96
+ if (selected !== "all" && !providers.includes(selected))
97
+ throw Error("Choose github, sentry, linear or all.");
98
+ if ((args.includes("--token-stdin") || action === "disconnect") &&
99
+ selected === "all")
100
+ throw Error("Choose one provider for this action.");
101
+ let secret;
102
+ if (args.includes("--token-stdin")) {
103
+ if (process.stdin.isTTY)
104
+ throw Error("This option expects an agent-owned pipe, not an interactive paste.");
105
+ secret = readFileSync(0, "utf8").trim();
106
+ if (!secret || secret.length > 16000 || /[\r\n\0]/.test(secret))
107
+ throw Error("Expected one credential on stdin.");
108
+ }
109
+ const known = discovery(root);
110
+ const results = [];
111
+ for (const provider of selected === "all"
112
+ ? providers
113
+ : [selected]) {
114
+ try {
115
+ const value = {
116
+ ...Object.fromEntries(Object.entries(known[provider]).filter(([, value]) => value !== undefined)),
117
+ ...(secret ? { token: secret } : {}),
118
+ ...Object.fromEntries([
119
+ ["repository", argument(args, "--repository")],
120
+ ["org", argument(args, "--org")],
121
+ ["projects", argument(args, "--projects")],
122
+ ["workspaceId", argument(args, "--workspace-id")],
123
+ ].filter(([, v]) => v)),
124
+ };
125
+ if (args.includes("--login") &&
126
+ action === "connect" &&
127
+ provider !== "linear") {
128
+ const result = spawnSync(provider === "github" ? "gh" : "sentry", provider === "github"
129
+ ? ["auth", "login", "--hostname", "github.com", "--web"]
130
+ : ["auth", "login", "--read-only"], { stdio: "inherit", timeout: 300000 });
131
+ if (result.error || result.status !== 0)
132
+ throw Error("Browser authorization did not finish. The agent should check that the official provider CLI is installed and retry.");
133
+ value.mode = "cli";
134
+ delete value.token;
135
+ }
136
+ results.push({
137
+ provider,
138
+ ...(await agentRequest({ op: action, root, provider, value })),
139
+ });
140
+ }
141
+ catch (e) {
142
+ process.exitCode = 1;
143
+ results.push({
144
+ provider,
145
+ status: "needs-attention",
146
+ message: e instanceof Error ? e.message : "Connection failed.",
147
+ ...(provider === "linear"
148
+ ? {
149
+ agentAction: "Use the browser to verify the intended Linear workspace and authorize read access. Acquire a read-only credential, then pipe it to fractory integrations connect linear --token-stdin. Do not ask the user to copy a key or put it in chat. A Codex connector login is not an exportable Fractory credential.",
150
+ authorizationUrl: "https://linear.app/settings/account/security",
151
+ }
152
+ : {
153
+ agentAction: `Complete ${provider} browser authorization with fractory integrations connect ${provider} --login, then retry the read check.`,
154
+ }),
155
+ });
156
+ }
157
+ }
158
+ return JSON.stringify({ repository: root, results }, null, 2);
159
+ }
@@ -0,0 +1,9 @@
1
+ import type { LinearWorkIssue } from "./work-items.js";
2
+ export interface IssueCache {
3
+ schema: "fractal.linear-cache.v1";
4
+ workspaceId: string;
5
+ issues: LinearWorkIssue[];
6
+ }
7
+ export declare function readIssueCache(file: string, workspaceId: string): LinearWorkIssue[];
8
+ /** Observational cache only. The Git-versioned registry is the authoritative relation. */
9
+ export declare function recordIssues(file: string, workspaceId: string, incoming: LinearWorkIssue[], unavailable?: string[]): LinearWorkIssue[];
@@ -0,0 +1,68 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, renameSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { normalizeLinearIssue } from "./linear-issues.js";
5
+ export function readIssueCache(file, workspaceId) {
6
+ try {
7
+ const raw = readFileSync(file, "utf8");
8
+ if (raw.length > 2_000_000)
9
+ throw Error("Issue cache exceeds its limit");
10
+ const value = JSON.parse(raw);
11
+ if (value.schema !== "fractal.linear-cache.v1" ||
12
+ value.workspaceId !== workspaceId ||
13
+ !Array.isArray(value.issues) ||
14
+ value.issues.length > 500)
15
+ throw Error("Invalid issue cache or workspace");
16
+ return value.issues.map((issue) => {
17
+ if (typeof issue.checkedAt !== "string")
18
+ throw Error("Recorded status lacks its observation timestamp");
19
+ return normalizeLinearIssue(issue, issue.checkedAt);
20
+ });
21
+ }
22
+ catch (error) {
23
+ if (error.code === "ENOENT")
24
+ return [];
25
+ throw error;
26
+ }
27
+ }
28
+ /** Observational cache only. The Git-versioned registry is the authoritative relation. */
29
+ export function recordIssues(file, workspaceId, incoming, unavailable = []) {
30
+ if (incoming.length > 500)
31
+ throw Error("Linear status cache supports at most 500 incoming issues");
32
+ let previous = [];
33
+ try {
34
+ previous = readIssueCache(file, workspaceId);
35
+ }
36
+ catch {
37
+ /* A successful provider read can replace a corrupt or other-workspace observational cache. */
38
+ }
39
+ const absent = new Set(unavailable);
40
+ const issues = new Map(previous
41
+ .filter((issue) => !absent.has(issue.id) && !absent.has(issue.identifier))
42
+ .map((issue) => [issue.id, issue]));
43
+ for (const value of incoming) {
44
+ if (typeof value.checkedAt !== "string")
45
+ throw Error("Recorded status requires an observation timestamp");
46
+ const issue = normalizeLinearIssue(value, value.checkedAt), prior = issues.get(issue.id);
47
+ if (!prior ||
48
+ Date.parse(issue.updatedAt) > Date.parse(prior.updatedAt) ||
49
+ (issue.updatedAt === prior.updatedAt &&
50
+ Date.parse(issue.checkedAt) >= Date.parse(prior.checkedAt)))
51
+ issues.set(issue.id, issue);
52
+ }
53
+ // Exact lookups must not eventually fill the cache and disable every future refresh.
54
+ const incomingIds = new Set(incoming.map((issue) => issue.id));
55
+ const retained = [...issues.values()]
56
+ .sort((a, b) => Number(incomingIds.has(b.id)) - Number(incomingIds.has(a.id)) ||
57
+ Date.parse(b.checkedAt) - Date.parse(a.checkedAt))
58
+ .slice(0, 500);
59
+ mkdirSync(dirname(file), { recursive: true });
60
+ const temp = file + "." + randomUUID() + ".tmp";
61
+ writeFileSync(temp, JSON.stringify({
62
+ schema: "fractal.linear-cache.v1",
63
+ workspaceId,
64
+ issues: retained,
65
+ }, null, 2) + "\n", { mode: 0o600 });
66
+ renameSync(temp, file);
67
+ return retained;
68
+ }
@@ -0,0 +1 @@
1
+ export declare function runIssues(args: string[]): Promise<string>;
@@ -0,0 +1,89 @@
1
+ import { join, resolve } from "node:path";
2
+ import { readFileSync } from "node:fs";
3
+ import { readIssueLinks, saveIssueLink } from "./issue-links.js";
4
+ import { readIssueCache, recordIssues } from "./issue-cache.js";
5
+ import { normalizeLinearIssue, LinearIssuesReader } from "./linear-issues.js";
6
+ import { workItems, issueReference } from "./work-items.js";
7
+ export async function runIssues(args) {
8
+ const option = (flag) => {
9
+ const index = args.indexOf(flag);
10
+ return index < 0 ? undefined : args[index + 1];
11
+ };
12
+ const root = resolve(option("--root") || process.cwd()), file = join(root, "fractal.issues.json"), cache = join(root, ".fractal/linear-issues.json");
13
+ const { registry, revision } = readIssueLinks(file);
14
+ if (args.includes("--help"))
15
+ return "fractal issues [list|link|unlink|import|sync] [--root path]\nlink --issue GRA-123 --block <id> [--block <id> ...] --graph graph.json\nunlink --issue GRA-123\nimport --file verified-linear-export.json\nsync uses FRACTAL_LINEAR_API_KEY or LINEAR_API_KEY (read-only).";
16
+ const command = args[1] || "list";
17
+ if (command === "link" || command === "unlink") {
18
+ const key = issueReference(option("--issue") || "").key;
19
+ const blocks = args.flatMap((arg, index) => arg === "--block" ? [args[index + 1]] : []);
20
+ let known = new Set();
21
+ if (command === "link") {
22
+ const graph = JSON.parse(readFileSync(resolve(root, option("--graph") || "fractory.json"), "utf8"));
23
+ known = new Set([
24
+ graph.id,
25
+ ...graph.elements.map((block) => block.id),
26
+ ]);
27
+ if (!blocks.length)
28
+ throw Error("Choose at least one --block");
29
+ }
30
+ const metadata = registry.workspace?.id
31
+ ? readIssueCache(cache, registry.workspace.id).find((issue) => issue.id === key || issue.identifier === key)
32
+ : undefined;
33
+ const prior = registry.links.find((link) => link.issue === key ||
34
+ link.identifier === key ||
35
+ link.issue === metadata?.id);
36
+ const ref = issueReference(option("--issue"));
37
+ if (ref.workspace &&
38
+ registry.workspace?.url &&
39
+ new URL(registry.workspace.url).pathname !== "/" + ref.workspace)
40
+ throw Error("Issue belongs to another workspace");
41
+ if (command === "unlink" && !prior)
42
+ throw Error("Issue has no saved links");
43
+ return JSON.stringify(saveIssueLink(file, revision, {
44
+ issue: metadata?.id || prior?.issue || key,
45
+ identifier: metadata?.identifier || prior?.identifier,
46
+ blocks: command === "unlink" ? [] : blocks,
47
+ }, known), null, 2);
48
+ }
49
+ if (command === "import" || command === "sync") {
50
+ if (!registry.workspace?.id)
51
+ throw Error("Set workspace.id in fractal.issues.json first");
52
+ let issues;
53
+ if (command === "import") {
54
+ const data = JSON.parse(readFileSync(resolve(root, option("--file") || ""), "utf8"));
55
+ if (data.workspaceId !== registry.workspace.id ||
56
+ !Array.isArray(data.issues) ||
57
+ data.issues.length > 500)
58
+ throw Error("Import must match the configured workspace and contain up to 500 issues");
59
+ issues = data.issues.map((issue) => {
60
+ const checkedAt = issue.checkedAt || data.checkedAt;
61
+ if (typeof checkedAt !== "string")
62
+ throw Error("Include the actual checkedAt timestamp from the Linear read");
63
+ return normalizeLinearIssue(issue, checkedAt);
64
+ });
65
+ for (const issue of issues)
66
+ if (new URL(issue.url).pathname.split("/")[1] !==
67
+ new URL(registry.workspace.url).pathname.split("/")[1])
68
+ throw Error("Imported issue belongs to a different workspace");
69
+ }
70
+ else {
71
+ const token = process.env.FRACTAL_LINEAR_API_KEY || process.env.LINEAR_API_KEY;
72
+ if (!token)
73
+ throw Error("Configure a read-only Linear credential to refresh status");
74
+ issues = await new LinearIssuesReader(token, registry.workspace.id).issues(registry.links.map((link) => link.issue));
75
+ }
76
+ recordIssues(cache, registry.workspace.id, issues);
77
+ return `Recorded ${issues.length} issue statuses; no Linear issues were modified.`;
78
+ }
79
+ if (command !== "list")
80
+ throw Error("Unknown issues command. Use fractal issues --help");
81
+ const items = workItems(registry, registry.workspace?.id ? readIssueCache(cache, registry.workspace.id) : []);
82
+ return JSON.stringify({
83
+ revision,
84
+ workspace: registry.workspace,
85
+ items: option("--block")
86
+ ? items.filter((item) => item.blocks.includes(option("--block")))
87
+ : items,
88
+ }, null, 2);
89
+ }
@@ -0,0 +1,15 @@
1
+ import { type IssueLinks } from "./work-items.js";
2
+ export declare class IssueLinkConflict extends Error {
3
+ }
4
+ export declare function readIssueLinks(file: string): {
5
+ registry: IssueLinks;
6
+ revision: string;
7
+ };
8
+ export declare function saveIssueLink(file: string, expectedRevision: string, input: {
9
+ issue: string;
10
+ identifier?: string;
11
+ blocks: string[];
12
+ }, knownBlocks: ReadonlySet<string>): {
13
+ registry: IssueLinks;
14
+ revision: string;
15
+ };
@@ -0,0 +1,125 @@
1
+ /** Tiny Git-versionable link registry; Linear retains ownership of issue metadata/status. */
2
+ import { readFileSync, writeFileSync, renameSync, unlinkSync, lstatSync, mkdirSync, } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { issueReference } from "./work-items.js";
6
+ const empty = { schema: "fractal.issues.v1", links: [] };
7
+ export class IssueLinkConflict extends Error {
8
+ }
9
+ export function readIssueLinks(file) {
10
+ let raw;
11
+ try {
12
+ if (lstatSync(file).isSymbolicLink())
13
+ throw Error("Issue link registry must not be a symlink");
14
+ raw = readFileSync(file, "utf8");
15
+ }
16
+ catch (error) {
17
+ if (error.code !== "ENOENT")
18
+ throw error;
19
+ raw = JSON.stringify(empty);
20
+ }
21
+ if (raw.length > 256_000)
22
+ throw Error("Issue link registry exceeds its size limit");
23
+ const value = JSON.parse(raw);
24
+ if (value.schema !== "fractal.issues.v1" ||
25
+ !Array.isArray(value.links) ||
26
+ value.links.length > 500)
27
+ throw Error("Invalid issue link registry");
28
+ const ids = new Set();
29
+ if (value.workspace) {
30
+ const url = new URL(value.workspace.url);
31
+ if (url.origin !== "https://linear.app" ||
32
+ url.username ||
33
+ url.password ||
34
+ url.search ||
35
+ url.hash ||
36
+ url.pathname.split("/").filter(Boolean).length !== 1)
37
+ throw Error("Invalid Linear workspace URL");
38
+ }
39
+ for (const link of value.links) {
40
+ const key = issueReference(link.issue).key;
41
+ if (key !== link.issue ||
42
+ ids.has(key) ||
43
+ !Array.isArray(link.blocks) ||
44
+ !link.blocks.length ||
45
+ link.blocks.length > 64 ||
46
+ link.blocks.some((b) => typeof b !== "string" || !b || b.length > 400) ||
47
+ new Set(link.blocks).size !== link.blocks.length)
48
+ throw Error("Invalid or duplicate issue link");
49
+ if (link.identifier &&
50
+ issueReference(link.identifier).key !== link.identifier)
51
+ throw Error("Invalid issue identifier");
52
+ for (const alias of new Set([
53
+ key,
54
+ ...(link.identifier ? [link.identifier] : []),
55
+ ])) {
56
+ if (ids.has(alias))
57
+ throw Error("Duplicate issue alias");
58
+ ids.add(alias);
59
+ }
60
+ }
61
+ return {
62
+ registry: value,
63
+ revision: createHash("sha256").update(raw).digest("hex"),
64
+ };
65
+ }
66
+ export function saveIssueLink(file, expectedRevision, input, knownBlocks) {
67
+ if (!/^[a-f0-9]{64}$/.test(expectedRevision))
68
+ throw new IssueLinkConflict("Reload issue links before saving");
69
+ mkdirSync(dirname(file), { recursive: true });
70
+ const lock = file + ".lock";
71
+ let owned = false;
72
+ try {
73
+ try {
74
+ writeFileSync(lock, "", { flag: "wx", mode: 0o600 });
75
+ owned = true;
76
+ }
77
+ catch (error) {
78
+ if (error.code === "EEXIST")
79
+ throw new IssueLinkConflict("Another writer holds the issue-link lock; retry when it finishes");
80
+ throw error;
81
+ }
82
+ const current = readIssueLinks(file);
83
+ if (current.revision !== expectedRevision)
84
+ throw new IssueLinkConflict("Issue links changed. Reload before saving so another edit is not overwritten");
85
+ const key = issueReference(input.issue).key, identifier = input.identifier
86
+ ? issueReference(input.identifier).key
87
+ : undefined;
88
+ if (!Array.isArray(input.blocks) ||
89
+ input.blocks.length > 64 ||
90
+ input.blocks.some((b) => typeof b !== "string"))
91
+ throw Error("Choose up to 64 blocks");
92
+ const prior = current.registry.links.find((l) => l.issue === key ||
93
+ l.identifier === key ||
94
+ (identifier && (l.identifier === identifier || l.issue === identifier)));
95
+ const blocks = [...new Set(input.blocks)].sort();
96
+ for (const block of blocks)
97
+ if (!knownBlocks.has(block) && !prior?.blocks.includes(block))
98
+ throw Error("Unknown block: " + block);
99
+ const links = current.registry.links.filter((l) => l !== prior);
100
+ const savedKey = prior?.identifier === key ? prior.issue : key;
101
+ const savedIdentifier = identifier || prior?.identifier;
102
+ if (blocks.length)
103
+ links.push({
104
+ issue: savedKey,
105
+ ...(savedIdentifier ? { identifier: savedIdentifier } : {}),
106
+ blocks,
107
+ });
108
+ const value = {
109
+ ...current.registry,
110
+ links: links.sort((a, b) => (a.identifier || a.issue).localeCompare(b.identifier || b.issue)),
111
+ };
112
+ writeFileSync(lock, JSON.stringify(value, null, 2) + "\n");
113
+ readIssueLinks(lock);
114
+ renameSync(lock, file);
115
+ owned = false;
116
+ return readIssueLinks(file);
117
+ }
118
+ finally {
119
+ if (owned)
120
+ try {
121
+ unlinkSync(lock);
122
+ }
123
+ catch { }
124
+ }
125
+ }
@@ -0,0 +1,19 @@
1
+ import { type LinearWorkIssue } from "./work-items.js";
2
+ export declare function normalizeLinearIssue(raw: any, checkedAt?: string): LinearWorkIssue;
3
+ export declare class LinearIssuesReader {
4
+ private token;
5
+ private workspaceId?;
6
+ private fetcher;
7
+ constructor(token: string, workspaceId?: string | undefined, fetcher?: typeof fetch);
8
+ /** Explicit, bounded title search. Never used to assign ownership automatically. */
9
+ search(query: string): Promise<{
10
+ issues: LinearWorkIssue[];
11
+ more: boolean;
12
+ }>;
13
+ issues(references: string[]): Promise<LinearWorkIssue[]>;
14
+ /** Refresh every permitted registry link; unavailable issues are explicit, not old successes. */
15
+ issueResults(references: string[]): Promise<{
16
+ issues: LinearWorkIssue[];
17
+ unavailable: string[];
18
+ }>;
19
+ }
@@ -0,0 +1,124 @@
1
+ import { issueReference } from "./work-items.js";
2
+ export function normalizeLinearIssue(raw, checkedAt = new Date().toISOString()) {
3
+ const id = raw.uuid || raw.id, identifier = raw.identifier || raw.id;
4
+ if (!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id || "") ||
5
+ !/^[A-Z][A-Z0-9]{0,15}-[1-9][0-9]{0,9}$/.test(identifier || "") ||
6
+ typeof raw.title !== "string" ||
7
+ raw.title.length > 1000)
8
+ throw Error("Invalid Linear issue metadata");
9
+ const url = issueReference(raw.url);
10
+ if (url.key !== identifier)
11
+ throw Error("Linear issue URL does not match its identifier");
12
+ const state = raw.state || { name: raw.status, type: raw.statusType };
13
+ if (typeof state?.name !== "string" ||
14
+ typeof state?.type !== "string" ||
15
+ !Number.isFinite(Date.parse(raw.updatedAt)) ||
16
+ !Number.isFinite(Date.parse(checkedAt)))
17
+ throw Error("Issue status or timestamps unavailable");
18
+ return {
19
+ id,
20
+ identifier,
21
+ title: raw.title,
22
+ url: url.url,
23
+ state: { name: state.name.slice(0, 100), type: state.type.slice(0, 40) },
24
+ updatedAt: raw.updatedAt,
25
+ checkedAt,
26
+ ...(raw.archivedAt ? { archivedAt: raw.archivedAt } : {}),
27
+ };
28
+ }
29
+ export class LinearIssuesReader {
30
+ token;
31
+ workspaceId;
32
+ fetcher;
33
+ constructor(token, workspaceId, fetcher = fetch) {
34
+ this.token = token;
35
+ this.workspaceId = workspaceId;
36
+ this.fetcher = fetcher;
37
+ }
38
+ /** Explicit, bounded title search. Never used to assign ownership automatically. */
39
+ async search(query) {
40
+ const term = query.trim();
41
+ if (term.length < 3 || term.length > 120)
42
+ throw Error("Search with 3–120 characters");
43
+ const response = await this.fetcher("https://api.linear.app/graphql", {
44
+ method: "POST",
45
+ headers: {
46
+ "content-type": "application/json",
47
+ Authorization: this.token,
48
+ },
49
+ body: JSON.stringify({
50
+ query: `query FractalIssueSearch($term: String!) {
51
+ organization { id }
52
+ issues(first: 20, filter: { title: { containsIgnoreCase: $term } }) {
53
+ nodes { id identifier title url updatedAt archivedAt state { name type } }
54
+ pageInfo { hasNextPage }
55
+ }
56
+ }`,
57
+ variables: { term },
58
+ }),
59
+ signal: AbortSignal.timeout(10000),
60
+ });
61
+ if (response.status === 429)
62
+ throw Error("Linear rate limit reached; retry later");
63
+ if (!response.ok)
64
+ throw Error("Linear search failed (" + response.status + ")");
65
+ const body = await response.json();
66
+ if (body.errors?.length ||
67
+ !Array.isArray(body.data?.issues?.nodes) ||
68
+ !body.data?.organization?.id)
69
+ throw Error("Linear returned incomplete search results");
70
+ if (this.workspaceId && body.data.organization.id !== this.workspaceId)
71
+ throw Error("Linear credential belongs to a different workspace");
72
+ const checkedAt = new Date().toISOString();
73
+ return {
74
+ issues: body.data.issues.nodes.map((issue) => normalizeLinearIssue(issue, checkedAt)),
75
+ more: !!body.data.issues.pageInfo?.hasNextPage,
76
+ };
77
+ }
78
+ async issues(references) {
79
+ return (await this.issueResults(references)).issues;
80
+ }
81
+ /** Refresh every permitted registry link; unavailable issues are explicit, not old successes. */
82
+ async issueResults(references) {
83
+ const keys = [...new Set(references.map((ref) => issueReference(ref).key))];
84
+ if (keys.length > 500)
85
+ throw Error("Refresh up to 500 linked issues at a time");
86
+ const result = [];
87
+ const unavailable = [];
88
+ for (let start = 0; start < keys.length; start += 25) {
89
+ const refs = keys.slice(start, start + 25), definitions = refs.map((_, i) => `$id${i}: String!`).join(","), queries = refs
90
+ .map((_, i) => `i${i}: issue(id:$id${i}) { id identifier title url updatedAt archivedAt state { name type } }`)
91
+ .join("\n");
92
+ const checkedAt = new Date().toISOString();
93
+ const response = await this.fetcher("https://api.linear.app/graphql", {
94
+ method: "POST",
95
+ headers: {
96
+ "content-type": "application/json",
97
+ Authorization: this.token,
98
+ },
99
+ body: JSON.stringify({
100
+ query: `query FractalIssues(${definitions}) { organization { id } ${queries} }`,
101
+ variables: Object.fromEntries(refs.map((ref, i) => ["id" + i, ref])),
102
+ }),
103
+ signal: AbortSignal.timeout(10000),
104
+ });
105
+ if (response.status === 429)
106
+ throw Error("Linear rate limit reached; recorded status remains available");
107
+ if (!response.ok)
108
+ throw Error("Linear status refresh failed (" + response.status + ")");
109
+ const body = await response.json();
110
+ if (!body.data?.organization?.id ||
111
+ body.errors?.some((error) => !/^i\d+$/.test(String(error.path?.[0] || ""))))
112
+ throw Error("Linear returned incomplete issue data; recorded status remains available");
113
+ if (this.workspaceId && body.data.organization.id !== this.workspaceId)
114
+ throw Error("Linear credential belongs to a different workspace");
115
+ for (let i = 0; i < refs.length; i++)
116
+ if (body.data["i" + i] &&
117
+ !body.errors?.some((error) => error.path?.[0] === "i" + i))
118
+ result.push(normalizeLinearIssue(body.data["i" + i], checkedAt));
119
+ else
120
+ unavailable.push(refs[i]);
121
+ }
122
+ return { issues: result, unavailable };
123
+ }
124
+ }
@@ -0,0 +1,8 @@
1
+ /** A desktop backend is a local workspace even when its UI is production-built.
2
+ * This is a capability flag, not authentication: every desktop request must also
3
+ * present the per-launch session and exact loopback host. */
4
+ export declare function desktopRuntime(env?: Record<string, string | undefined>): boolean;
5
+ export declare function localRepositoryRuntime(env?: Record<string, string | undefined>): boolean;
6
+ export declare function desktopRequestAllowed(headers: Pick<Headers, "get">, env?: Record<string, string | undefined>): boolean;
7
+ /** Explicit loopback-only web development; packaged builds always require their session. */
8
+ export declare function developmentRequestAllowed(headers: Pick<Headers, "get">, env?: Record<string, string | undefined>): boolean;