@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,116 @@
1
+ import { join } from "node:path";
2
+ import { loadCode } from "./code-store";
3
+ import type { CodeSnapshot } from "./code-model";
4
+ import type { DefinitionGraph } from "./model";
5
+ import {
6
+ repositoryMapPaths,
7
+ repositoryMapConfiguration,
8
+ mapFromArtifacts,
9
+ parseMapConfiguration,
10
+ } from "./repository-map";
11
+ import type { FactoryModel } from "./factory-model";
12
+ import { historyBlobs } from "./history-git";
13
+ export interface HistoricalOwnership {
14
+ graph: DefinitionGraph;
15
+ snapshot?: CodeSnapshot;
16
+ }
17
+ /** Read exact-revision artifacts when present. Missing history is never replaced with today's graph. */
18
+ export async function historicalOwnership(
19
+ root: string,
20
+ revisions: string[],
21
+ archive = join(root, ".fractal"),
22
+ ) {
23
+ const result = new Map<string, HistoricalOwnership>(),
24
+ missing: string[] = [];
25
+ for (const commit of new Set(revisions)) {
26
+ const saved = loadCode(archive, commit);
27
+ if (saved) result.set(commit, { graph: saved.graph, snapshot: saved });
28
+ else missing.push(commit);
29
+ }
30
+ const fallback = repositoryMapConfiguration(root);
31
+ const configs = await historyBlobs(
32
+ root,
33
+ missing.map((commit) => `${commit}:fractory.config.json`),
34
+ );
35
+ const configurations = new Map(
36
+ missing.map((commit) => {
37
+ const text = configs.get(`${commit}:fractory.config.json`);
38
+ try {
39
+ return [commit, text ? parseMapConfiguration(text) : fallback] as const;
40
+ } catch {
41
+ return [commit, {}] as const;
42
+ }
43
+ }),
44
+ );
45
+ const objects = await historyBlobs(
46
+ root,
47
+ missing.flatMap((commit) =>
48
+ repositoryMapPaths(root, configurations.get(commit)).map(
49
+ (path) => `${commit}:${path}`,
50
+ ),
51
+ ),
52
+ );
53
+ const composed = new Map<string, DefinitionGraph>();
54
+ for (const commit of missing) {
55
+ const configuration = configurations.get(commit)!;
56
+ const texts = repositoryMapPaths(root, configuration).map((path) =>
57
+ objects.get(`${commit}:${path}`),
58
+ );
59
+ try {
60
+ let graph: DefinitionGraph | undefined;
61
+ const key = JSON.stringify(configuration) + texts.join("\0");
62
+ if (composed.has(key)) graph = composed.get(key);
63
+ else
64
+ graph =
65
+ mapFromArtifacts(configuration, (path) =>
66
+ objects.get(`${commit}:${path}`),
67
+ ) || undefined;
68
+ if (
69
+ graph?.schema === "fractal.definition.v1" &&
70
+ Array.isArray(graph.elements) &&
71
+ graph.elements.some((node) => node.id === graph!.id)
72
+ ) {
73
+ composed.set(key, graph);
74
+ result.set(commit, { graph });
75
+ }
76
+ } catch {
77
+ /* Invalid/missing artifacts are unavailable, not inferred historical ownership. */
78
+ }
79
+ }
80
+ return result;
81
+ }
82
+
83
+ /** A coarse association lands on a logical block, never on a guessed leaf method. */
84
+ export function fileAssociations(graph: DefinitionGraph) {
85
+ const byId = new Map(graph.elements.map((node) => [node.id, node]));
86
+ const ancestors = (id: string) => {
87
+ const ids: string[] = [],
88
+ seen = new Set<string>();
89
+ let node = byId.get(id);
90
+ while (node && !seen.has(node.id)) {
91
+ seen.add(node.id);
92
+ ids.push(node.id);
93
+ node = byId.get(node.parent || "");
94
+ }
95
+ return ids;
96
+ };
97
+ const candidates = new Map<string, string[]>();
98
+ for (const node of graph.elements)
99
+ for (const ref of node.sources || (node.source ? [node.source] : [])) {
100
+ const id =
101
+ ancestors(node.implementationBlock || node.id).find((id) =>
102
+ ["block", "system", "factory", "deployment"].includes(
103
+ byId.get(id)!.kind,
104
+ ),
105
+ ) || graph.id;
106
+ candidates.set(ref.file, [...(candidates.get(ref.file) || []), id]);
107
+ }
108
+ return new Map(
109
+ [...candidates].map(([file, ids]) => [
110
+ file,
111
+ ancestors(ids[0]).find((id) =>
112
+ ids.every((other) => ancestors(other).includes(id)),
113
+ )!,
114
+ ]),
115
+ );
116
+ }
@@ -0,0 +1,117 @@
1
+ /** Resolve the history branch without checking out, fetching or scanning files. */
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ const execute = promisify(execFile);
5
+ export type HistorySourceMode = "default" | "checkout";
6
+ export interface HistorySource {
7
+ mode: HistorySourceMode | "revision";
8
+ label: string;
9
+ commit: string;
10
+ options: { value: HistorySourceMode; label: string; description: string }[];
11
+ }
12
+ export function historySourceMode(value: string | null): HistorySourceMode {
13
+ if (value && value !== "default" && value !== "checkout")
14
+ throw Error("Choose the default branch or the current checkout.");
15
+ return value === "checkout" ? "checkout" : "default";
16
+ }
17
+ export async function resolveHistorySource(
18
+ root: string,
19
+ mode: HistorySourceMode = "default",
20
+ revision?: string,
21
+ ): Promise<HistorySource> {
22
+ const git = async (args: string[]) =>
23
+ (
24
+ await execute("git", args, {
25
+ cwd: root,
26
+ encoding: "utf8",
27
+ timeout: 8000,
28
+ maxBuffer: 256 * 1024,
29
+ env: {
30
+ ...process.env,
31
+ GIT_OPTIONAL_LOCKS: "0",
32
+ GIT_TERMINAL_PROMPT: "0",
33
+ },
34
+ })
35
+ ).stdout.trim();
36
+ const resolve = async (ref: string) => {
37
+ const sha = await git([
38
+ "rev-parse",
39
+ "--verify",
40
+ "--end-of-options",
41
+ ref + "^{commit}",
42
+ ]);
43
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha))
44
+ throw Error("No commit at this history source.");
45
+ return sha;
46
+ };
47
+ if (revision) {
48
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(revision))
49
+ throw Error("Expected a full commit SHA.");
50
+ return {
51
+ mode: "revision",
52
+ label: revision.slice(0, 8),
53
+ commit: revision,
54
+ options: [],
55
+ };
56
+ }
57
+ const [head, current, remoteHeads] = await Promise.all([
58
+ resolve("HEAD"),
59
+ git(["symbolic-ref", "--quiet", "HEAD"]).catch(() => ""),
60
+ git([
61
+ "for-each-ref",
62
+ "--count=1000",
63
+ "--format=%(refname)%00%(symref)",
64
+ "refs/remotes",
65
+ ]).catch(() => ""),
66
+ ]);
67
+ const remotes = remoteHeads.split("\n").map((row) => row.split("\0"));
68
+ const preferred =
69
+ remotes.find(([ref]) => ref === "refs/remotes/origin/HEAD")?.[1] ||
70
+ remotes.find(([ref, target]) => ref.endsWith("/HEAD") && target)?.[1];
71
+ const candidates = [
72
+ ...new Set(
73
+ [
74
+ preferred,
75
+ "refs/remotes/origin/main",
76
+ "refs/remotes/origin/master",
77
+ ...remotes
78
+ .filter(([ref]) => /\/(main|master)$/.test(ref))
79
+ .map(([ref]) => ref),
80
+ "refs/heads/main",
81
+ "refs/heads/master",
82
+ ].filter((ref): ref is string => !!ref),
83
+ ),
84
+ ];
85
+ let branch = "",
86
+ anchor = head;
87
+ for (const candidate of candidates) {
88
+ try {
89
+ anchor = await resolve(candidate);
90
+ branch = candidate;
91
+ break;
92
+ } catch {}
93
+ }
94
+ const label = (ref: string) => ref.replace(/^refs\/(heads|remotes)\//, "");
95
+ const checkout = current
96
+ ? label(current)
97
+ : `Detached HEAD · ${head.slice(0, 8)}`;
98
+ const options: HistorySource["options"] = [
99
+ {
100
+ value: "default",
101
+ label: branch ? label(branch) : checkout,
102
+ description: branch ? "Default branch · local Git" : "Current checkout",
103
+ },
104
+ ];
105
+ if ((branch && branch !== current) || mode === "checkout")
106
+ options.push({
107
+ value: "checkout",
108
+ label: checkout,
109
+ description: "Current checkout",
110
+ });
111
+ return {
112
+ mode,
113
+ label: mode === "checkout" ? checkout : options[0].label,
114
+ commit: mode === "checkout" ? head : anchor,
115
+ options,
116
+ };
117
+ }
@@ -0,0 +1,187 @@
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"] as const;
8
+ function argument(args: string[], name: string) {
9
+ const i = args.indexOf(name);
10
+ if (i < 0) return undefined;
11
+ if (!args[i + 1] || args[i + 1].startsWith("--"))
12
+ throw Error(name + " needs a value.");
13
+ return args[i + 1];
14
+ }
15
+ export async function agentRequest(request: Record<string, unknown>) {
16
+ const directory =
17
+ process.env.FRACTORY_AGENT_DATA_DIR ||
18
+ join(homedir(), "Library/Application Support/Fractory");
19
+ const file = join(directory, "agent-bridge.json");
20
+ if (
21
+ !existsSync(file) &&
22
+ process.platform === "darwin" &&
23
+ !process.env.FRACTORY_AGENT_DATA_DIR
24
+ ) {
25
+ execFileSync("open", ["-a", "Fractory"], {
26
+ stdio: "ignore",
27
+ timeout: 5000,
28
+ });
29
+ for (let n = 0; n < 50 && !existsSync(file); n++)
30
+ await new Promise((r) => setTimeout(r, 100));
31
+ }
32
+ const secure = (name: string) => {
33
+ const s = lstatSync(name);
34
+ if (
35
+ s.isSymbolicLink() ||
36
+ (s.mode & 0o077) !== 0 ||
37
+ (process.getuid && s.uid !== process.getuid())
38
+ )
39
+ throw Error("The Fractory agent bridge must be private to your account.");
40
+ };
41
+ if (!existsSync(file))
42
+ throw Error(
43
+ "Open Fractory once, then retry. Its local credential bridge is not running.",
44
+ );
45
+ secure(file);
46
+ const bridge = JSON.parse(readFileSync(file, "utf8"));
47
+ secure(bridge.socket);
48
+ if (
49
+ bridge.version !== 1 ||
50
+ typeof bridge.nonce !== "string" ||
51
+ bridge.socket !== join(directory, "agent.sock")
52
+ )
53
+ throw Error("Invalid Fractory agent bridge.");
54
+ return await new Promise<any>((resolve, reject) => {
55
+ const socket = connect(bridge.socket);
56
+ let data = "";
57
+ socket.setTimeout(25000, () => {
58
+ socket.destroy();
59
+ reject(Error("Fractory did not respond. Reopen the app and retry."));
60
+ });
61
+ socket.on("connect", () =>
62
+ socket.write(JSON.stringify({ ...request, nonce: bridge.nonce }) + "\n"),
63
+ );
64
+ socket.on("error", () =>
65
+ reject(Error("Could not reach Fractory. Reopen the app and retry.")),
66
+ );
67
+ socket.on("data", (chunk) => {
68
+ data += chunk.toString();
69
+ if (data.length > 65536) {
70
+ socket.destroy();
71
+ reject(Error("Invalid bridge response."));
72
+ return;
73
+ }
74
+ if (!data.includes("\n")) return;
75
+ socket.end();
76
+ try {
77
+ const result = JSON.parse(data.split("\n")[0]);
78
+ if (!result.ok) reject(Error(result.error));
79
+ else resolve(result.data);
80
+ } catch {
81
+ reject(Error("Invalid bridge response."));
82
+ }
83
+ });
84
+ });
85
+ }
86
+ export async function runIntegrations(args: string[]) {
87
+ if (args.includes("--help") || args.length === 1)
88
+ return `fractory integrations status [--root PATH]
89
+ fractory integrations connect github|sentry|linear|all [--auto] [--login] [--root PATH]
90
+ fractory integrations connect PROVIDER --token-stdin [provider options]
91
+ fractory integrations check PROVIDER|all [--root PATH]
92
+ fractory integrations disconnect PROVIDER [--root PATH]
93
+ Options: --repository owner/repo, --org sentry-org, --projects slug,slug, --workspace-id ID.
94
+ 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.`;
95
+ if (args.includes("--token"))
96
+ throw Error(
97
+ "Do not put tokens in command arguments. Use --token-stdin with an agent-owned pipe.",
98
+ );
99
+ const root = realpathSync(resolve(argument(args, "--root") || process.cwd()));
100
+ const action = args[1];
101
+ if (!["status", "connect", "check", "disconnect"].includes(action))
102
+ throw Error("Choose status, connect, check or disconnect.");
103
+ if (action === "status")
104
+ return JSON.stringify(await agentRequest({ op: "status", root }), null, 2);
105
+ const selected = args[2];
106
+ if (selected !== "all" && !providers.includes(selected as any))
107
+ throw Error("Choose github, sentry, linear or all.");
108
+ if (
109
+ (args.includes("--token-stdin") || action === "disconnect") &&
110
+ selected === "all"
111
+ )
112
+ throw Error("Choose one provider for this action.");
113
+ let secret;
114
+ if (args.includes("--token-stdin")) {
115
+ if (process.stdin.isTTY)
116
+ throw Error(
117
+ "This option expects an agent-owned pipe, not an interactive paste.",
118
+ );
119
+ secret = readFileSync(0, "utf8").trim();
120
+ if (!secret || secret.length > 16000 || /[\r\n\0]/.test(secret))
121
+ throw Error("Expected one credential on stdin.");
122
+ }
123
+ const known = discovery(root);
124
+ const results = [];
125
+ for (const provider of selected === "all"
126
+ ? providers
127
+ : [selected as (typeof providers)[number]]) {
128
+ try {
129
+ const value: Record<string, string> = {
130
+ ...Object.fromEntries(
131
+ Object.entries(known[provider]).filter(
132
+ ([, value]) => value !== undefined,
133
+ ),
134
+ ),
135
+ ...(secret ? { token: secret } : {}),
136
+ ...Object.fromEntries(
137
+ [
138
+ ["repository", argument(args, "--repository")],
139
+ ["org", argument(args, "--org")],
140
+ ["projects", argument(args, "--projects")],
141
+ ["workspaceId", argument(args, "--workspace-id")],
142
+ ].filter(([, v]) => v),
143
+ ),
144
+ };
145
+ if (
146
+ args.includes("--login") &&
147
+ action === "connect" &&
148
+ provider !== "linear"
149
+ ) {
150
+ const result = spawnSync(
151
+ provider === "github" ? "gh" : "sentry",
152
+ provider === "github"
153
+ ? ["auth", "login", "--hostname", "github.com", "--web"]
154
+ : ["auth", "login", "--read-only"],
155
+ { stdio: "inherit", timeout: 300000 },
156
+ );
157
+ if (result.error || result.status !== 0)
158
+ throw Error(
159
+ "Browser authorization did not finish. The agent should check that the official provider CLI is installed and retry.",
160
+ );
161
+ value.mode = "cli";
162
+ delete value.token;
163
+ }
164
+ results.push({
165
+ provider,
166
+ ...(await agentRequest({ op: action, root, provider, value })),
167
+ });
168
+ } catch (e) {
169
+ process.exitCode = 1;
170
+ results.push({
171
+ provider,
172
+ status: "needs-attention",
173
+ message: e instanceof Error ? e.message : "Connection failed.",
174
+ ...(provider === "linear"
175
+ ? {
176
+ agentAction:
177
+ "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.",
178
+ authorizationUrl: "https://linear.app/settings/account/security",
179
+ }
180
+ : {
181
+ agentAction: `Complete ${provider} browser authorization with fractory integrations connect ${provider} --login, then retry the read check.`,
182
+ }),
183
+ });
184
+ }
185
+ }
186
+ return JSON.stringify({ repository: root, results }, null, 2);
187
+ }
@@ -0,0 +1,96 @@
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";
5
+ import type { LinearWorkIssue } from "./work-items";
6
+ export interface IssueCache {
7
+ schema: "fractal.linear-cache.v1";
8
+ workspaceId: string;
9
+ issues: LinearWorkIssue[];
10
+ }
11
+ export function readIssueCache(
12
+ file: string,
13
+ workspaceId: string,
14
+ ): LinearWorkIssue[] {
15
+ try {
16
+ const raw = readFileSync(file, "utf8");
17
+ if (raw.length > 2_000_000) throw Error("Issue cache exceeds its limit");
18
+ const value = JSON.parse(raw) as IssueCache;
19
+ if (
20
+ value.schema !== "fractal.linear-cache.v1" ||
21
+ value.workspaceId !== workspaceId ||
22
+ !Array.isArray(value.issues) ||
23
+ value.issues.length > 500
24
+ )
25
+ throw Error("Invalid issue cache or workspace");
26
+ return value.issues.map((issue) => {
27
+ if (typeof issue.checkedAt !== "string")
28
+ throw Error("Recorded status lacks its observation timestamp");
29
+ return normalizeLinearIssue(issue, issue.checkedAt);
30
+ });
31
+ } catch (error: any) {
32
+ if (error.code === "ENOENT") return [];
33
+ throw error;
34
+ }
35
+ }
36
+ /** Observational cache only. The Git-versioned registry is the authoritative relation. */
37
+ export function recordIssues(
38
+ file: string,
39
+ workspaceId: string,
40
+ incoming: LinearWorkIssue[],
41
+ unavailable: string[] = [],
42
+ ) {
43
+ if (incoming.length > 500)
44
+ throw Error("Linear status cache supports at most 500 incoming issues");
45
+ let previous: LinearWorkIssue[] = [];
46
+ try {
47
+ previous = readIssueCache(file, workspaceId);
48
+ } catch {
49
+ /* A successful provider read can replace a corrupt or other-workspace observational cache. */
50
+ }
51
+ const absent = new Set(unavailable);
52
+ const issues = new Map(
53
+ previous
54
+ .filter((issue) => !absent.has(issue.id) && !absent.has(issue.identifier))
55
+ .map((issue) => [issue.id, issue]),
56
+ );
57
+ for (const value of incoming) {
58
+ if (typeof value.checkedAt !== "string")
59
+ throw Error("Recorded status requires an observation timestamp");
60
+ const issue = normalizeLinearIssue(value, value.checkedAt),
61
+ prior = issues.get(issue.id);
62
+ if (
63
+ !prior ||
64
+ Date.parse(issue.updatedAt) > Date.parse(prior.updatedAt) ||
65
+ (issue.updatedAt === prior.updatedAt &&
66
+ Date.parse(issue.checkedAt) >= Date.parse(prior.checkedAt))
67
+ )
68
+ issues.set(issue.id, issue);
69
+ }
70
+ // Exact lookups must not eventually fill the cache and disable every future refresh.
71
+ const incomingIds = new Set(incoming.map((issue) => issue.id));
72
+ const retained = [...issues.values()]
73
+ .sort(
74
+ (a, b) =>
75
+ Number(incomingIds.has(b.id)) - Number(incomingIds.has(a.id)) ||
76
+ Date.parse(b.checkedAt) - Date.parse(a.checkedAt),
77
+ )
78
+ .slice(0, 500);
79
+ mkdirSync(dirname(file), { recursive: true });
80
+ const temp = file + "." + randomUUID() + ".tmp";
81
+ writeFileSync(
82
+ temp,
83
+ JSON.stringify(
84
+ {
85
+ schema: "fractal.linear-cache.v1",
86
+ workspaceId,
87
+ issues: retained,
88
+ },
89
+ null,
90
+ 2,
91
+ ) + "\n",
92
+ { mode: 0o600 },
93
+ );
94
+ renameSync(temp, file);
95
+ return retained;
96
+ }
@@ -0,0 +1,137 @@
1
+ import { join, resolve } from "node:path";
2
+ import { readFileSync } from "node:fs";
3
+ import { readIssueLinks, saveIssueLink } from "./issue-links";
4
+ import { readIssueCache, recordIssues } from "./issue-cache";
5
+ import { normalizeLinearIssue, LinearIssuesReader } from "./linear-issues";
6
+ import { workItems, issueReference } from "./work-items";
7
+ export async function runIssues(args: string[]) {
8
+ const option = (flag: string) => {
9
+ const index = args.indexOf(flag);
10
+ return index < 0 ? undefined : args[index + 1];
11
+ };
12
+ const root = resolve(option("--root") || process.cwd()),
13
+ file = join(root, "fractal.issues.json"),
14
+ cache = join(root, ".fractal/linear-issues.json");
15
+ const { registry, revision } = readIssueLinks(file);
16
+ if (args.includes("--help"))
17
+ 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).";
18
+ const command = args[1] || "list";
19
+ if (command === "link" || command === "unlink") {
20
+ const key = issueReference(option("--issue") || "").key;
21
+ const blocks = args.flatMap((arg, index) =>
22
+ arg === "--block" ? [args[index + 1]] : [],
23
+ );
24
+ let known = new Set<string>();
25
+ if (command === "link") {
26
+ const graph = JSON.parse(
27
+ readFileSync(
28
+ resolve(
29
+ root,
30
+ option("--graph") || "fractory.json",
31
+ ),
32
+ "utf8",
33
+ ),
34
+ );
35
+ known = new Set([
36
+ graph.id,
37
+ ...graph.elements.map((block: { id: string }) => block.id),
38
+ ]);
39
+ if (!blocks.length) throw Error("Choose at least one --block");
40
+ }
41
+ const metadata = registry.workspace?.id
42
+ ? readIssueCache(cache, registry.workspace.id).find(
43
+ (issue) => issue.id === key || issue.identifier === key,
44
+ )
45
+ : undefined;
46
+ const prior = registry.links.find(
47
+ (link) =>
48
+ link.issue === key ||
49
+ link.identifier === key ||
50
+ link.issue === metadata?.id,
51
+ );
52
+ const ref = issueReference(option("--issue")!);
53
+ if (
54
+ ref.workspace &&
55
+ registry.workspace?.url &&
56
+ new URL(registry.workspace.url).pathname !== "/" + ref.workspace
57
+ )
58
+ throw Error("Issue belongs to another workspace");
59
+ if (command === "unlink" && !prior) throw Error("Issue has no saved links");
60
+ return JSON.stringify(
61
+ saveIssueLink(
62
+ file,
63
+ revision,
64
+ {
65
+ issue: metadata?.id || prior?.issue || key,
66
+ identifier: metadata?.identifier || prior?.identifier,
67
+ blocks: command === "unlink" ? [] : blocks,
68
+ },
69
+ known,
70
+ ),
71
+ null,
72
+ 2,
73
+ );
74
+ }
75
+ if (command === "import" || command === "sync") {
76
+ if (!registry.workspace?.id)
77
+ throw Error("Set workspace.id in fractal.issues.json first");
78
+ let issues;
79
+ if (command === "import") {
80
+ const data = JSON.parse(
81
+ readFileSync(resolve(root, option("--file") || ""), "utf8"),
82
+ );
83
+ if (
84
+ data.workspaceId !== registry.workspace.id ||
85
+ !Array.isArray(data.issues) ||
86
+ data.issues.length > 500
87
+ )
88
+ throw Error(
89
+ "Import must match the configured workspace and contain up to 500 issues",
90
+ );
91
+ issues = data.issues.map((issue: any) => {
92
+ const checkedAt = issue.checkedAt || data.checkedAt;
93
+ if (typeof checkedAt !== "string")
94
+ throw Error(
95
+ "Include the actual checkedAt timestamp from the Linear read",
96
+ );
97
+ return normalizeLinearIssue(issue, checkedAt);
98
+ });
99
+ for (const issue of issues)
100
+ if (
101
+ new URL(issue.url).pathname.split("/")[1] !==
102
+ new URL(registry.workspace.url).pathname.split("/")[1]
103
+ )
104
+ throw Error("Imported issue belongs to a different workspace");
105
+ } else {
106
+ const token =
107
+ process.env.FRACTAL_LINEAR_API_KEY || process.env.LINEAR_API_KEY;
108
+ if (!token)
109
+ throw Error(
110
+ "Configure a read-only Linear credential to refresh status",
111
+ );
112
+ issues = await new LinearIssuesReader(
113
+ token,
114
+ registry.workspace.id,
115
+ ).issues(registry.links.map((link) => link.issue));
116
+ }
117
+ recordIssues(cache, registry.workspace.id, issues);
118
+ return `Recorded ${issues.length} issue statuses; no Linear issues were modified.`;
119
+ }
120
+ if (command !== "list")
121
+ throw Error("Unknown issues command. Use fractal issues --help");
122
+ const items = workItems(
123
+ registry,
124
+ registry.workspace?.id ? readIssueCache(cache, registry.workspace.id) : [],
125
+ );
126
+ return JSON.stringify(
127
+ {
128
+ revision,
129
+ workspace: registry.workspace,
130
+ items: option("--block")
131
+ ? items.filter((item) => item.blocks.includes(option("--block")!))
132
+ : items,
133
+ },
134
+ null,
135
+ 2,
136
+ );
137
+ }