@granular-software/fractory 0.0.0-stage → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +28 -2
  3. package/dist/activity-volume.d.ts +18 -0
  4. package/dist/activity-volume.js +94 -0
  5. package/dist/annotations.d.ts +122 -0
  6. package/dist/annotations.js +304 -0
  7. package/dist/benchmark-cli.d.ts +1 -0
  8. package/dist/benchmark-cli.js +95 -0
  9. package/dist/benchmark-worker.d.ts +2 -0
  10. package/dist/benchmark-worker.js +22 -0
  11. package/dist/benchmarks.d.ts +19 -0
  12. package/dist/benchmarks.js +414 -0
  13. package/dist/bin.d.ts +2 -0
  14. package/dist/bin.js +63 -0
  15. package/dist/block-cli.d.ts +1 -0
  16. package/dist/block-cli.js +88 -0
  17. package/dist/block-documents.d.ts +35 -0
  18. package/dist/block-documents.js +84 -0
  19. package/dist/change-impact.d.ts +55 -0
  20. package/dist/change-impact.js +223 -0
  21. package/dist/check-source.d.ts +2 -0
  22. package/dist/check-source.js +66 -0
  23. package/dist/checks-model.d.ts +64 -0
  24. package/dist/checks-model.js +36 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +359 -0
  27. package/dist/code-model.d.ts +38 -0
  28. package/dist/code-model.js +94 -0
  29. package/dist/code-store.d.ts +9 -0
  30. package/dist/code-store.js +79 -0
  31. package/dist/compare-artifact.d.ts +6 -0
  32. package/dist/compare-artifact.js +277 -0
  33. package/dist/compare.d.ts +81 -0
  34. package/dist/compare.js +291 -0
  35. package/dist/compiler.d.ts +10 -0
  36. package/dist/compiler.js +1240 -0
  37. package/dist/compose.d.ts +9 -0
  38. package/dist/compose.js +72 -0
  39. package/dist/core.d.ts +87 -0
  40. package/dist/core.js +207 -0
  41. package/dist/coverage-cli.d.ts +1 -0
  42. package/dist/coverage-cli.js +42 -0
  43. package/dist/declaration-sources.d.ts +3 -0
  44. package/dist/declaration-sources.js +51 -0
  45. package/dist/declared-graph.d.ts +3 -0
  46. package/dist/declared-graph.js +67 -0
  47. package/dist/display-name.d.ts +2 -0
  48. package/dist/display-name.js +8 -0
  49. package/dist/error-heat.d.ts +58 -0
  50. package/dist/error-heat.js +96 -0
  51. package/dist/evidence.d.ts +3 -0
  52. package/dist/evidence.js +68 -0
  53. package/dist/factory-graph.d.ts +7 -0
  54. package/dist/factory-graph.js +389 -0
  55. package/dist/factory-model.d.ts +111 -0
  56. package/dist/factory-model.js +1 -0
  57. package/dist/git-code.d.ts +47 -0
  58. package/dist/git-code.js +352 -0
  59. package/dist/git-refs.d.ts +4 -0
  60. package/dist/git-refs.js +37 -0
  61. package/dist/history-activity.d.ts +4 -0
  62. package/dist/history-activity.js +129 -0
  63. package/dist/history-churn.d.ts +36 -0
  64. package/dist/history-churn.js +302 -0
  65. package/dist/history-git.d.ts +21 -0
  66. package/dist/history-git.js +125 -0
  67. package/dist/history-ledger.d.ts +43 -0
  68. package/dist/history-ledger.js +450 -0
  69. package/dist/history-ownership.d.ts +10 -0
  70. package/dist/history-ownership.js +75 -0
  71. package/dist/history-source.d.ts +13 -0
  72. package/dist/history-source.js +100 -0
  73. package/dist/integrations-cli.d.ts +2 -0
  74. package/dist/integrations-cli.js +159 -0
  75. package/dist/interface-map.d.ts +15 -0
  76. package/dist/interface-map.js +125 -0
  77. package/dist/issue-cache.d.ts +9 -0
  78. package/dist/issue-cache.js +68 -0
  79. package/dist/issue-cli.d.ts +1 -0
  80. package/dist/issue-cli.js +89 -0
  81. package/dist/issue-links.d.ts +15 -0
  82. package/dist/issue-links.js +125 -0
  83. package/dist/linear-issues.d.ts +19 -0
  84. package/dist/linear-issues.js +124 -0
  85. package/dist/local-runtime.d.ts +8 -0
  86. package/dist/local-runtime.js +59 -0
  87. package/dist/map-activity.d.ts +73 -0
  88. package/dist/map-activity.js +234 -0
  89. package/dist/map-model.d.ts +5 -0
  90. package/dist/map-model.js +166 -0
  91. package/dist/map-quality.d.ts +20 -0
  92. package/dist/map-quality.js +61 -0
  93. package/dist/mapping-coverage.d.ts +87 -0
  94. package/dist/mapping-coverage.js +404 -0
  95. package/dist/model.d.ts +186 -0
  96. package/dist/model.js +66 -0
  97. package/dist/operation-benchmark-worker.d.ts +2 -0
  98. package/dist/operation-benchmark-worker.js +60 -0
  99. package/dist/operation-benchmark.d.ts +29 -0
  100. package/dist/operation-benchmark.js +1 -0
  101. package/dist/otel-metrics.d.ts +21 -0
  102. package/dist/otel-metrics.js +146 -0
  103. package/dist/performance-model.d.ts +185 -0
  104. package/dist/performance-model.js +396 -0
  105. package/dist/product-map.d.ts +71 -0
  106. package/dist/product-map.js +197 -0
  107. package/dist/provider-access.cjs +207 -0
  108. package/dist/provider-access.d.cts +14 -0
  109. package/dist/public-boundaries.d.ts +13 -0
  110. package/dist/public-boundaries.js +115 -0
  111. package/dist/reports-cli.d.ts +1 -0
  112. package/dist/reports-cli.js +111 -0
  113. package/dist/reports-model.d.ts +27 -0
  114. package/dist/reports-model.js +39 -0
  115. package/dist/reports.d.ts +23 -0
  116. package/dist/reports.js +223 -0
  117. package/dist/repository-map.d.ts +22 -0
  118. package/dist/repository-map.js +153 -0
  119. package/dist/resource-cache.d.ts +17 -0
  120. package/dist/resource-cache.js +65 -0
  121. package/dist/review-cli.d.ts +19 -0
  122. package/dist/review-cli.js +224 -0
  123. package/dist/review.d.ts +48 -0
  124. package/dist/review.js +289 -0
  125. package/dist/runtime-metrics.d.ts +26 -0
  126. package/dist/runtime-metrics.js +290 -0
  127. package/dist/scope.d.ts +14 -0
  128. package/dist/scope.js +168 -0
  129. package/dist/sentry-activity.d.ts +39 -0
  130. package/dist/sentry-activity.js +174 -0
  131. package/dist/sentry.d.ts +130 -0
  132. package/dist/sentry.js +369 -0
  133. package/dist/service-release.d.ts +16 -0
  134. package/dist/service-release.js +14 -0
  135. package/dist/setup-cli.d.ts +2 -0
  136. package/dist/setup-cli.js +52 -0
  137. package/dist/setup-kit.cjs +163 -0
  138. package/dist/setup-kit.d.cts +32 -0
  139. package/dist/source-index.d.ts +37 -0
  140. package/dist/source-index.js +170 -0
  141. package/dist/source-review-git.d.ts +7 -0
  142. package/dist/source-review-git.js +105 -0
  143. package/dist/source-review.d.ts +18 -0
  144. package/dist/source-review.js +573 -0
  145. package/dist/telemetry.d.ts +17 -0
  146. package/dist/telemetry.js +51 -0
  147. package/dist/time-window.d.ts +9 -0
  148. package/dist/time-window.js +35 -0
  149. package/dist/trace-evidence.d.ts +23 -0
  150. package/dist/trace-evidence.js +55 -0
  151. package/dist/trace-model.d.ts +26 -0
  152. package/dist/trace-model.js +1 -0
  153. package/dist/tracing.d.ts +44 -0
  154. package/dist/tracing.js +123 -0
  155. package/dist/work-check.d.ts +18 -0
  156. package/dist/work-check.js +115 -0
  157. package/dist/work-cli.d.ts +1 -0
  158. package/dist/work-cli.js +176 -0
  159. package/dist/work-context.d.ts +59 -0
  160. package/dist/work-context.js +594 -0
  161. package/dist/work-intents.d.ts +6 -0
  162. package/dist/work-intents.js +140 -0
  163. package/dist/work-items.d.ts +58 -0
  164. package/dist/work-items.js +86 -0
  165. package/dist/work-lock-check.d.ts +12 -0
  166. package/dist/work-lock-check.js +339 -0
  167. package/dist/work-locks.d.ts +10 -0
  168. package/dist/work-locks.js +98 -0
  169. package/dist/work-model.d.ts +119 -0
  170. package/dist/work-model.js +310 -0
  171. package/dist/work-review-git.d.ts +8 -0
  172. package/dist/work-review-git.js +111 -0
  173. package/dist/work-review.d.ts +26 -0
  174. package/dist/work-review.js +426 -0
  175. package/dist/work-switcher-model.d.ts +43 -0
  176. package/dist/work-switcher-model.js +79 -0
  177. package/dist/work-switcher.d.ts +6 -0
  178. package/dist/work-switcher.js +171 -0
  179. package/dist/working-cli.d.ts +1 -0
  180. package/dist/working-cli.js +33 -0
  181. package/dist/working-code.d.ts +74 -0
  182. package/dist/working-code.js +421 -0
  183. package/dist/workspace-notes.d.ts +71 -0
  184. package/dist/workspace-notes.js +177 -0
  185. package/dist/workspace-tests.d.ts +21 -0
  186. package/dist/workspace-tests.js +573 -0
  187. package/package.json +547 -4
  188. package/src/activity-volume.ts +149 -0
  189. package/src/annotations.ts +485 -0
  190. package/src/benchmark-cli.ts +118 -0
  191. package/src/benchmark-worker.ts +22 -0
  192. package/src/benchmarks.ts +493 -0
  193. package/src/bin.ts +54 -0
  194. package/src/block-cli.ts +106 -0
  195. package/src/block-documents.ts +117 -0
  196. package/src/change-impact.ts +280 -0
  197. package/src/check-source.ts +82 -0
  198. package/src/checks-model.ts +108 -0
  199. package/src/cli.ts +440 -0
  200. package/src/code-model.ts +159 -0
  201. package/src/code-store.ts +98 -0
  202. package/src/compare-artifact.ts +314 -0
  203. package/src/compare.ts +440 -0
  204. package/src/compiler.ts +1512 -0
  205. package/src/compose.ts +94 -0
  206. package/src/core.ts +361 -0
  207. package/src/coverage-cli.ts +52 -0
  208. package/src/declaration-sources.ts +69 -0
  209. package/src/declared-graph.ts +75 -0
  210. package/src/display-name.ts +8 -0
  211. package/src/error-heat.ts +161 -0
  212. package/src/evidence.ts +94 -0
  213. package/src/factory-graph.ts +462 -0
  214. package/src/factory-model.ts +82 -0
  215. package/src/git-code.ts +461 -0
  216. package/src/git-refs.ts +43 -0
  217. package/src/history-activity.ts +146 -0
  218. package/src/history-churn.ts +416 -0
  219. package/src/history-git.ts +163 -0
  220. package/src/history-ledger.ts +636 -0
  221. package/src/history-ownership.ts +116 -0
  222. package/src/history-source.ts +117 -0
  223. package/src/integrations-cli.ts +187 -0
  224. package/src/interface-map.ts +166 -0
  225. package/src/issue-cache.ts +96 -0
  226. package/src/issue-cli.ts +137 -0
  227. package/src/issue-links.ts +153 -0
  228. package/src/linear-issues.ts +154 -0
  229. package/src/local-runtime.ts +70 -0
  230. package/src/map-activity.ts +309 -0
  231. package/src/map-model.ts +213 -0
  232. package/src/map-quality.ts +66 -0
  233. package/src/mapping-coverage.ts +570 -0
  234. package/src/model.ts +228 -0
  235. package/src/operation-benchmark-worker.ts +60 -0
  236. package/src/operation-benchmark.ts +28 -0
  237. package/src/otel-metrics.ts +176 -0
  238. package/src/performance-model.ts +575 -0
  239. package/src/product-map.ts +271 -0
  240. package/src/provider-access.cjs +207 -0
  241. package/src/provider-access.d.cts +14 -0
  242. package/src/public-boundaries.ts +143 -0
  243. package/src/reports-cli.ts +125 -0
  244. package/src/reports-model.ts +73 -0
  245. package/src/reports.ts +276 -0
  246. package/src/repository-map.ts +191 -0
  247. package/src/resource-cache.ts +76 -0
  248. package/src/review-cli.ts +256 -0
  249. package/src/review.ts +376 -0
  250. package/src/runtime-metrics.ts +386 -0
  251. package/src/scope.ts +192 -0
  252. package/src/sentry-activity.ts +234 -0
  253. package/src/sentry.ts +545 -0
  254. package/src/service-release.ts +18 -0
  255. package/src/setup-cli.ts +58 -0
  256. package/src/setup-kit.cjs +163 -0
  257. package/src/setup-kit.d.cts +32 -0
  258. package/src/source-index.ts +208 -0
  259. package/src/source-review-git.ts +131 -0
  260. package/src/source-review.ts +736 -0
  261. package/src/telemetry.ts +68 -0
  262. package/src/time-window.ts +51 -0
  263. package/src/trace-evidence.ts +80 -0
  264. package/src/trace-model.ts +26 -0
  265. package/src/tracing.ts +165 -0
  266. package/src/work-check.ts +149 -0
  267. package/src/work-cli.ts +229 -0
  268. package/src/work-context.ts +753 -0
  269. package/src/work-intents.ts +196 -0
  270. package/src/work-items.ts +151 -0
  271. package/src/work-lock-check.ts +549 -0
  272. package/src/work-locks.ts +108 -0
  273. package/src/work-model.ts +466 -0
  274. package/src/work-review-git.ts +130 -0
  275. package/src/work-review.ts +573 -0
  276. package/src/work-switcher-model.ts +121 -0
  277. package/src/work-switcher.ts +191 -0
  278. package/src/working-cli.ts +38 -0
  279. package/src/working-code.ts +582 -0
  280. package/src/workspace-notes.ts +203 -0
  281. package/src/workspace-tests.ts +654 -0
  282. package/toolkit/GUIDE.md +354 -0
  283. package/toolkit/SKILL.md +142 -0
  284. package/toolkit/bin/fractory +2 -0
  285. package/toolkit/build.json +1 -0
@@ -0,0 +1,753 @@
1
+ import {
2
+ mapFromArtifacts,
3
+ repositoryMapConfiguration,
4
+ parseMapConfiguration,
5
+ } from "./repository-map";
6
+ /** Local work contexts. Git refs are read without checkout; only explicit create adds a worktree. */
7
+ import { createHash, randomUUID } from "node:crypto";
8
+ import {
9
+ existsSync,
10
+ mkdirSync,
11
+ readFileSync,
12
+ readdirSync,
13
+ realpathSync,
14
+ renameSync,
15
+ writeFileSync,
16
+ rmSync,
17
+ } from "node:fs";
18
+ import { join, resolve } from "node:path";
19
+ import { execFileSync } from "node:child_process";
20
+ import { readGit, resolveComparisonRef, comparisonMergeBase } from "./git-refs";
21
+ import {
22
+ normalizeWorkScope,
23
+ validateProposals,
24
+ proposalConnectionError,
25
+ type WorkContext,
26
+ type WorkPlan,
27
+ type WorkTarget,
28
+ } from "./work-model";
29
+ import type { DefinitionGraph } from "./model";
30
+ import { checkedPath } from "./workspace-notes";
31
+ import { logicalMap } from "./map-model";
32
+ import { intentEvidence, workIntentStates } from "./work-intents";
33
+ import { validateLocks, lockBrief } from "./work-locks";
34
+ import type { WorkLock } from "./work-model";
35
+
36
+ const uuid = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
37
+ const hash = (value: string) =>
38
+ createHash("sha256").update(value).digest("hex");
39
+ const identity = (path: string) => hash(path).slice(0, 20);
40
+ export function workDirectory(root: string) {
41
+ return join(
42
+ realpathSync(
43
+ resolve(root, readGit(root, ["rev-parse", "--git-common-dir"]).trim()),
44
+ ),
45
+ "fractory",
46
+ "work",
47
+ );
48
+ }
49
+ function writeJSON(file: string, value: unknown) {
50
+ const temporary = `${file}.${randomUUID()}.tmp`;
51
+ writeFileSync(temporary, JSON.stringify(value, null, 2) + "\n", {
52
+ flag: "wx",
53
+ mode: 0o600,
54
+ });
55
+ renameSync(temporary, file);
56
+ }
57
+ export function mainReference(root: string) {
58
+ for (const ref of ["origin/main", "main", "origin/master", "master"])
59
+ try {
60
+ return { ref, commit: resolveComparisonRef(root, ref) };
61
+ } catch {}
62
+ let symbolic = "HEAD";
63
+ try {
64
+ symbolic = readGit(root, ["symbolic-ref", "--quiet", "HEAD"])
65
+ .trim()
66
+ .replace(/^refs\/heads\//, "");
67
+ } catch {}
68
+ return { ref: symbolic, commit: resolveComparisonRef(root, symbolic) };
69
+ }
70
+ export function gitWorkTargets(root: string): WorkTarget[] {
71
+ const current = realpathSync(root);
72
+ const entries = readGit(root, ["worktree", "list", "--porcelain", "-z"])
73
+ .split("\0\0")
74
+ .filter(Boolean);
75
+ return entries.flatMap((entry) => {
76
+ const lines = entry.split("\0").filter(Boolean);
77
+ const path = lines.find((line) => line.startsWith("worktree "))?.slice(9);
78
+ if (!path || !existsSync(path) || lines.includes("bare")) return [];
79
+ const canonical = realpathSync(path);
80
+ const branch =
81
+ lines
82
+ .find((line) => line.startsWith("branch "))
83
+ ?.slice(7)
84
+ .replace(/^refs\/heads\//, "") || "Detached checkout";
85
+ return [
86
+ {
87
+ id: `tree-${identity(canonical)}`,
88
+ title:
89
+ branch === "Detached checkout"
90
+ ? `Local worktree · ${canonical.split("/").at(-2)}`
91
+ : branch,
92
+ branch,
93
+ path: canonical,
94
+ current: canonical === current,
95
+ managed: false,
96
+ head: lines.find((line) => line.startsWith("HEAD "))?.slice(5) || "",
97
+ },
98
+ ];
99
+ });
100
+ }
101
+ interface RegistryEntry {
102
+ id: string;
103
+ root: string;
104
+ planFile: string;
105
+ baselineFile: string;
106
+ }
107
+ function registry(
108
+ root: string,
109
+ id: string,
110
+ known?: { directory: string; targets: WorkTarget[] },
111
+ ): RegistryEntry {
112
+ if (!uuid.test(id)) throw Error("Unknown work context.");
113
+ const value = JSON.parse(
114
+ readFileSync(
115
+ checkedPath(known?.directory || workDirectory(root), `${id}.json`),
116
+ "utf8",
117
+ ),
118
+ ) as RegistryEntry;
119
+ if (
120
+ value.id !== id ||
121
+ value.planFile !== `docs/fractory/work/${id}.json` ||
122
+ value.baselineFile !== `${id}.map.json`
123
+ )
124
+ throw Error("Invalid work context registry.");
125
+ const target = (known?.targets || gitWorkTargets(root)).find(
126
+ (tree) => tree.path === value.root,
127
+ );
128
+ if (!target)
129
+ throw Error(
130
+ "This worktree is no longer available. Return to Main or choose another worktree.",
131
+ );
132
+ return value;
133
+ }
134
+ export function readWorkPlan(
135
+ root: string,
136
+ id: string,
137
+ known?: { directory: string; targets: WorkTarget[] },
138
+ ) {
139
+ const entry = registry(root, id, known);
140
+ const file = checkedPath(entry.root, entry.planFile);
141
+ const body = readFileSync(file, "utf8");
142
+ if (Buffer.byteLength(body) > 512000)
143
+ throw Error("The work plan exceeds its read budget.");
144
+ const plan = JSON.parse(body) as WorkPlan;
145
+ if (
146
+ plan.schema !== "fractory.work.v1" ||
147
+ plan.id !== id ||
148
+ !Array.isArray(plan.scope) ||
149
+ plan.scope.some((id) => typeof id !== "string") ||
150
+ (plan.excluded !== undefined &&
151
+ (!Array.isArray(plan.excluded) ||
152
+ plan.excluded.some((id) => typeof id !== "string"))) ||
153
+ (plan.locks !== undefined &&
154
+ (!Array.isArray(plan.locks) ||
155
+ plan.locks.length > 500 ||
156
+ new Set(plan.locks.map((l) => l?.target)).size !== plan.locks.length ||
157
+ plan.locks.some(
158
+ (lock) =>
159
+ !lock ||
160
+ typeof lock.target !== "string" ||
161
+ !["subtree", "contract"].includes(lock.kind) ||
162
+ (lock.note !== undefined &&
163
+ (typeof lock.note !== "string" || lock.note.length > 4000)),
164
+ )))
165
+ )
166
+ throw Error("Invalid work plan.");
167
+ return { entry, plan, revision: hash(body) };
168
+ }
169
+ export function workBaseline(root: string, id: string): DefinitionGraph {
170
+ const entry = registry(root, id);
171
+ return JSON.parse(
172
+ readFileSync(checkedPath(workDirectory(root), entry.baselineFile), "utf8"),
173
+ );
174
+ }
175
+ export function listWorkContexts(root: string) {
176
+ const targets = gitWorkTargets(root);
177
+ const directory = workDirectory(root);
178
+ let files: string[] = [];
179
+ try {
180
+ files = readdirSync(directory)
181
+ .filter((file) => uuid.test(file.replace(/\.json$/, "")))
182
+ .slice(0, 500);
183
+ } catch {}
184
+ for (const file of files) {
185
+ try {
186
+ const { entry, plan } = readWorkPlan(root, file.replace(/\.json$/, ""), {
187
+ directory,
188
+ targets,
189
+ });
190
+ const target = targets.find((tree) => tree.path === entry.root);
191
+ if (target) {
192
+ target.id = plan.id;
193
+ target.title = plan.title;
194
+ target.managed = true;
195
+ target.scope = plan.scope;
196
+ target.plannedAt = plan.createdAt;
197
+ target.pullRequest = plan.pullRequest;
198
+ }
199
+ } catch {
200
+ /* Missing worktrees stay in Git's own list, never guessed from a stale path. */
201
+ }
202
+ }
203
+ const branches = readGit(root, [
204
+ "for-each-ref",
205
+ "--format=%(refname:short)%00%(objectname)",
206
+ "refs/heads/",
207
+ ])
208
+ .trim()
209
+ .split("\n")
210
+ .filter(Boolean);
211
+ for (const item of branches) {
212
+ const [branch, head] = item.split("\0");
213
+ if (!targets.some((tree) => tree.branch === branch))
214
+ targets.push({
215
+ id: `branch-${identity(branch)}`,
216
+ branch,
217
+ title: branch,
218
+ head,
219
+ current: false,
220
+ managed: false,
221
+ });
222
+ }
223
+ return targets;
224
+ }
225
+ export function resolveWorkContext(root: string, id = "main"): WorkContext {
226
+ const main = mainReference(root);
227
+ if (id === "main")
228
+ return {
229
+ id,
230
+ mode: "main",
231
+ title: "Main",
232
+ branch: main.ref,
233
+ root: realpathSync(root),
234
+ head: main.commit,
235
+ baseRef: main.ref,
236
+ baseCommit: main.commit,
237
+ mapBasis: "committed",
238
+ hasCheckout: false,
239
+ };
240
+ if (uuid.test(id)) {
241
+ const { entry, plan, revision } = readWorkPlan(root, id);
242
+ const head = resolveComparisonRef(entry.root, "HEAD");
243
+ let copied = false;
244
+ if (plan.bootstrapRevision)
245
+ try {
246
+ copied =
247
+ JSON.parse(
248
+ readFileSync(checkedPath(entry.root, "fractory.json"), "utf8"),
249
+ ).revision === plan.bootstrapRevision;
250
+ } catch {}
251
+ return {
252
+ id,
253
+ mode: "work",
254
+ title: plan.title,
255
+ branch: plan.branch,
256
+ root: entry.root,
257
+ head,
258
+ baseRef: plan.baseRef,
259
+ baseCommit: plan.baseCommit,
260
+ plan,
261
+ revision,
262
+ mapBasis: copied ? "baseline" : "checkout",
263
+ hasCheckout: true,
264
+ notice: copied
265
+ ? "Structure copied from the reviewed map. Compile this worktree to verify its code references."
266
+ : undefined,
267
+ };
268
+ }
269
+ const targets = listWorkContexts(root);
270
+ const raw = gitWorkTargets(root).find((tree) => tree.id === id);
271
+ const adopted =
272
+ raw && targets.find((tree) => tree.path === raw.path && tree.managed);
273
+ if (adopted) return resolveWorkContext(root, adopted.id);
274
+ const target = targets.find((tree) => tree.id === id);
275
+ if (!target) throw Error("Unknown branch or worktree.");
276
+ return {
277
+ id,
278
+ mode: "branch",
279
+ title: target.title,
280
+ branch: target.branch,
281
+ root: target.path || realpathSync(root),
282
+ head: target.head,
283
+ baseRef: main.ref,
284
+ baseCommit: comparisonMergeBase(root, main.commit, target.head),
285
+ mapBasis: target.path ? "checkout" : "committed",
286
+ hasCheckout: !!target.path,
287
+ notice: target.path
288
+ ? undefined
289
+ : "This branch has no local worktree. Open it read-only, or start a worktree to develop it.",
290
+ };
291
+ }
292
+
293
+ const immutableMaps = new Map<string, Promise<DefinitionGraph | null>>();
294
+ export async function readFactoryMap(
295
+ root: string,
296
+ ref?: string,
297
+ ): Promise<DefinitionGraph | null> {
298
+ if (!ref) return readFactoryMapUncached(root);
299
+ const commit = resolveComparisonRef(root, ref),
300
+ key = `${realpathSync(root)}:${commit}:${JSON.stringify(repositoryMapConfiguration(root))}`;
301
+ let pending = immutableMaps.get(key);
302
+ if (!pending) {
303
+ pending = readFactoryMapUncached(root, commit);
304
+ immutableMaps.set(key, pending);
305
+ if (immutableMaps.size > 24)
306
+ immutableMaps.delete(immutableMaps.keys().next().value!);
307
+ void pending.catch(() => immutableMaps.delete(key));
308
+ }
309
+ return pending;
310
+ }
311
+ async function readFactoryMapUncached(
312
+ root: string,
313
+ ref?: string,
314
+ ): Promise<DefinitionGraph | null> {
315
+ const text = (file: string) => {
316
+ try {
317
+ return ref
318
+ ? readGit(root, ["show", `${resolveComparisonRef(root, ref)}:${file}`])
319
+ : readFileSync(checkedPath(root, file), "utf8");
320
+ } catch {
321
+ return undefined;
322
+ }
323
+ };
324
+ const configuration = text("fractory.config.json");
325
+ const graph = mapFromArtifacts(
326
+ configuration
327
+ ? parseMapConfiguration(configuration)
328
+ : repositoryMapConfiguration(root),
329
+ text,
330
+ );
331
+ if (!graph) return null;
332
+ if (
333
+ graph.schema !== "fractal.definition.v1" ||
334
+ !graph.id ||
335
+ !Array.isArray(graph.elements) ||
336
+ !Array.isArray(graph.connections)
337
+ )
338
+ throw Error("Invalid factory map.");
339
+ return logicalMap(graph);
340
+ }
341
+
342
+ export async function createWorkContext(
343
+ root: string,
344
+ graph: DefinitionGraph,
345
+ input: {
346
+ title: string;
347
+ scope: string[];
348
+ excluded?: string[];
349
+ branch?: string;
350
+ from?: string;
351
+ fromName?: string;
352
+ },
353
+ ) {
354
+ const title = input.title.trim();
355
+ if (!title || title.length > 120 || /[\x00-\x1f]/.test(title))
356
+ throw Error("Give the work a short name.");
357
+ if (!input.scope.length) throw Error("Select at least one block.");
358
+ const { scope, excluded } = normalizeWorkScope(
359
+ graph,
360
+ input.scope,
361
+ input.excluded,
362
+ );
363
+ const id = randomUUID();
364
+ const main = mainReference(root);
365
+ const from = input.from
366
+ ? resolveComparisonRef(root, input.from)
367
+ : main.commit;
368
+ if (!/^[a-f0-9]{40,64}$/.test(from))
369
+ throw Error(`Invalid base commit: ${JSON.stringify(main)} at ${root}`);
370
+ const slug =
371
+ title
372
+ .toLowerCase()
373
+ .normalize("NFKD")
374
+ .replace(/[^a-z0-9]+/g, "-")
375
+ .replace(/^-|-$/g, "")
376
+ .slice(0, 48) || "work";
377
+ const branch = input.branch || `codex/${slug}-${id.slice(0, 6)}`;
378
+ if (!/^codex\/[a-zA-Z0-9][a-zA-Z0-9/_-]{0,100}$/.test(branch))
379
+ throw Error("Use a codex/ branch name without spaces.");
380
+ readGit(root, ["check-ref-format", `refs/heads/${branch}`]);
381
+ const path = checkedPath(
382
+ root,
383
+ `.fractal/worktrees/${slug}-${id.slice(0, 6)}`,
384
+ true,
385
+ );
386
+ if (existsSync(path)) throw Error("The worktree destination already exists.");
387
+ mkdirSync(join(root, ".fractal/worktrees"), { recursive: true });
388
+ execFileSync(
389
+ "git",
390
+ [
391
+ "-c",
392
+ "core.hooksPath=/dev/null",
393
+ "-c",
394
+ "core.fsmonitor=false",
395
+ "worktree",
396
+ "add",
397
+ "-b",
398
+ branch,
399
+ "--",
400
+ path,
401
+ from,
402
+ ],
403
+ {
404
+ cwd: root,
405
+ timeout: 60000,
406
+ maxBuffer: 2 * 1024 * 1024,
407
+ stdio: ["ignore", "pipe", "pipe"],
408
+ },
409
+ );
410
+ const plan: WorkPlan = {
411
+ schema: "fractory.work.v1",
412
+ id,
413
+ title,
414
+ branch,
415
+ baseRef: input.fromName || input.from || main.ref,
416
+ baseCommit: from,
417
+ createdAt: new Date().toISOString(),
418
+ scope,
419
+ ...(excluded.length ? { excluded } : {}),
420
+ proposals: [],
421
+ };
422
+ const planFile = `docs/fractory/work/${id}.json`;
423
+ mkdirSync(join(path, "docs/fractory/work"), { recursive: true });
424
+ // A supplied reviewed map is explicit when the base revision predates mapping.
425
+ if (!(await readFactoryMap(path))) {
426
+ plan.bootstrapRevision = graph.revision;
427
+ writeJSON(checkedPath(path, "fractory.json", true), {
428
+ ...graph,
429
+ codeRevision: undefined,
430
+ });
431
+ }
432
+ writeJSON(checkedPath(path, planFile, true), plan);
433
+ // Carry only the Fractory skill, without copying credentials or other agents' settings.
434
+ for (const file of [
435
+ ".agents/skills/fractory/SKILL.md",
436
+ ".agents/skills/fractory/references/fractory-guide.md",
437
+ ])
438
+ try {
439
+ if (existsSync(checkedPath(path, file, true))) continue;
440
+ const body = readFileSync(checkedPath(root, file), "utf8");
441
+ if (Buffer.byteLength(body) > 128000) continue;
442
+ const destination = checkedPath(path, file, true);
443
+ mkdirSync(resolve(destination, ".."), { recursive: true });
444
+ writeFileSync(destination, body, { flag: "wx", mode: 0o600 });
445
+ } catch {
446
+ /* The portable app/CLI skill remains available when the repo has none. */
447
+ }
448
+ const directory = workDirectory(root);
449
+ mkdirSync(directory, { recursive: true });
450
+ writeJSON(checkedPath(directory, `${id}.map.json`, true), graph);
451
+ writeJSON(checkedPath(directory, `${id}.json`, true), {
452
+ id,
453
+ root: realpathSync(path),
454
+ planFile,
455
+ baselineFile: `${id}.map.json`,
456
+ } satisfies RegistryEntry);
457
+ return resolveWorkContext(root, id);
458
+ }
459
+
460
+ /** Attach a plan to an existing registered Git checkout. No checkout, branch creation or code copy. */
461
+ export async function adoptWorkContext(
462
+ root: string,
463
+ targetId: string,
464
+ graph: DefinitionGraph,
465
+ input: { scope: string[]; excluded?: string[]; title?: string },
466
+ ) {
467
+ const target =
468
+ gitWorkTargets(root).find((tree) => tree.id === targetId) ||
469
+ listWorkContexts(root).find((tree) => tree.id === targetId);
470
+ if (!target?.path)
471
+ throw Error("Open an existing worktree before planning changes.");
472
+ if (!input.scope.length) throw Error("Select at least one block.");
473
+ const { scope, excluded } = normalizeWorkScope(
474
+ graph,
475
+ input.scope,
476
+ input.excluded,
477
+ );
478
+ const existing = listWorkContexts(root).find(
479
+ (tree) => tree.path === target.path && tree.managed,
480
+ );
481
+ if (existing) return resolveWorkContext(root, existing.id);
482
+ const directory = workDirectory(root);
483
+ mkdirSync(directory, { recursive: true });
484
+ const lock = join(directory, `adopt-${identity(target.path)}.lock`);
485
+ try {
486
+ mkdirSync(lock);
487
+ } catch {
488
+ throw Error("This worktree is being prepared. Retry in a moment.");
489
+ }
490
+ try {
491
+ const already = listWorkContexts(root).find(
492
+ (tree) => tree.path === target.path && tree.managed,
493
+ );
494
+ if (already) return resolveWorkContext(root, already.id);
495
+ const main = mainReference(root),
496
+ id = randomUUID();
497
+ const baseCommit = comparisonMergeBase(root, main.commit, target.head);
498
+ const baseline = (await readFactoryMap(target.path, baseCommit)) || graph;
499
+ if (resolveComparisonRef(target.path, "HEAD") !== target.head)
500
+ throw Error("The worktree advanced while its plan was prepared. Retry.");
501
+ const title = (input.title || target.title).trim();
502
+ if (!title || title.length > 120 || /[\x00-\x1f]/.test(title))
503
+ throw Error("Give the work a short name.");
504
+ const plan: WorkPlan = {
505
+ schema: "fractory.work.v1",
506
+ id,
507
+ title,
508
+ branch: target.branch,
509
+ baseRef: main.ref,
510
+ baseCommit,
511
+ createdAt: new Date().toISOString(),
512
+ scope,
513
+ ...(excluded.length ? { excluded } : {}),
514
+ proposals: [],
515
+ };
516
+ const planFile = `docs/fractory/work/${id}.json`;
517
+ mkdirSync(checkedPath(target.path, "docs/fractory/work", true), {
518
+ recursive: true,
519
+ });
520
+ writeJSON(checkedPath(target.path, planFile, true), plan);
521
+ writeJSON(checkedPath(directory, `${id}.map.json`, true), baseline);
522
+ writeJSON(checkedPath(directory, `${id}.json`, true), {
523
+ id,
524
+ root: target.path,
525
+ planFile,
526
+ baselineFile: `${id}.map.json`,
527
+ } satisfies RegistryEntry);
528
+ return resolveWorkContext(root, id);
529
+ } finally {
530
+ rmSync(lock, { recursive: true, force: true });
531
+ }
532
+ }
533
+
534
+ export function updateWorkPlan(
535
+ root: string,
536
+ id: string,
537
+ graph: DefinitionGraph,
538
+ input: {
539
+ revision: string;
540
+ proposals?: unknown;
541
+ scope?: string[];
542
+ excluded?: string[];
543
+ locks?: WorkLock[];
544
+ pullRequest?: WorkPlan["pullRequest"];
545
+ },
546
+ snapshot?: WorkContext,
547
+ ) {
548
+ const current = readWorkPlan(root, id);
549
+ if (input.revision !== current.revision)
550
+ throw Error("This plan changed. Reload it before saving.");
551
+ const plan: WorkPlan = {
552
+ ...current.plan,
553
+ ...(input.locks !== undefined
554
+ ? { locks: validateLocks(graph, input.locks, current.plan.locks) }
555
+ : {}),
556
+ proposals:
557
+ input.proposals === undefined
558
+ ? current.plan.proposals
559
+ : validateProposals(graph, input.proposals, current.plan.proposals),
560
+ ...(input.scope !== undefined || input.excluded !== undefined
561
+ ? normalizeWorkScope(
562
+ graph,
563
+ input.scope ?? current.plan.scope,
564
+ input.excluded ?? current.plan.excluded,
565
+ )
566
+ : {}),
567
+ };
568
+ if (input.pullRequest) {
569
+ const url = new URL(input.pullRequest.url);
570
+ if (
571
+ url.protocol !== "https:" ||
572
+ url.username ||
573
+ url.password ||
574
+ !/^\/[^/]+\/[^/]+\/pull\/\d+$/.test(url.pathname)
575
+ )
576
+ throw Error("Choose a pull-request URL.");
577
+ plan.pullRequest = {
578
+ url: url.href,
579
+ title: String(input.pullRequest.title).slice(0, 200),
580
+ };
581
+ }
582
+ writeJSON(checkedPath(current.entry.root, current.entry.planFile), plan);
583
+ // A caller that just resolved this checkout need not rescan Git and every
584
+ // worktree again to return a plan-only edit. The file revision still guards writes.
585
+ if (snapshot?.id === id && snapshot.root === current.entry.root)
586
+ return { ...snapshot, plan, revision: readWorkPlan(root, id).revision };
587
+ return resolveWorkContext(root, id);
588
+ }
589
+
590
+ /** Explicit confirmation, with evidence read from this checkout and the pinned baseline. */
591
+ export function updateWorkIntent(
592
+ root: string,
593
+ id: string,
594
+ graph: DefinitionGraph,
595
+ input: {
596
+ revision: string;
597
+ proposal: string;
598
+ status: "planned" | "done" | "dropped";
599
+ implementation?: string;
600
+ },
601
+ ) {
602
+ const current = readWorkPlan(root, id);
603
+ if (input.revision !== current.revision)
604
+ throw Error("This plan changed. Reload it before saving.");
605
+ if (!["planned", "done", "dropped"].includes(input.status))
606
+ throw Error("Choose Planned, Done or Dropped.");
607
+ const p = current.plan.proposals.find((p) => p.id === input.proposal);
608
+ if (!p) throw Error("This intention is no longer in the plan.");
609
+ const next = { ...p };
610
+ if (input.implementation !== undefined) {
611
+ const valid = (
612
+ p.kind === "connection"
613
+ ? graph.connections
614
+ : p.kind === "block"
615
+ ? graph.elements
616
+ : [...graph.elements, ...graph.connections]
617
+ ).some((n) => n.id === input.implementation && n.provenance !== "proposed");
618
+ if (!valid) throw Error("Choose an actual mapped block or connection.");
619
+ next.implementation = input.implementation;
620
+ }
621
+ delete next.outcome;
622
+ if (input.status !== "planned")
623
+ next.outcome = {
624
+ status: input.status,
625
+ checkedAt: new Date().toISOString(),
626
+ ...(input.status === "done"
627
+ ? {
628
+ evidence: intentEvidence(
629
+ current.entry.root,
630
+ graph,
631
+ next,
632
+ workBaseline(root, id),
633
+ ),
634
+ }
635
+ : {}),
636
+ };
637
+ const dropped = new Set(input.status === "dropped" ? [next.id] : []);
638
+ if (next.kind === "block" && dropped.size) {
639
+ for (
640
+ let i = 0, changed = true;
641
+ changed && i < current.plan.proposals.length;
642
+ i++
643
+ ) {
644
+ changed = false;
645
+ for (const p of current.plan.proposals)
646
+ if (
647
+ !dropped.has(p.id) &&
648
+ p.outcome?.status !== "done" &&
649
+ [p.parent, p.source, p.target].some((id) => id && dropped.has(id))
650
+ ) {
651
+ dropped.add(p.id);
652
+ changed = true;
653
+ }
654
+ }
655
+ }
656
+ return updateWorkPlan(root, id, graph, {
657
+ revision: current.revision,
658
+ proposals: current.plan.proposals.map((p) =>
659
+ p.id === next.id
660
+ ? next
661
+ : dropped.has(p.id)
662
+ ? {
663
+ ...p,
664
+ outcome: {
665
+ status: "dropped" as const,
666
+ checkedAt: next.outcome!.checkedAt,
667
+ },
668
+ }
669
+ : next.kind === "block" &&
670
+ input.status === "done" &&
671
+ next.implementation &&
672
+ p.kind === "annotation" &&
673
+ p.target === next.id &&
674
+ !p.implementation
675
+ ? { ...p, implementation: next.implementation }
676
+ : p,
677
+ ),
678
+ });
679
+ }
680
+
681
+ export function workDeepLink(root: string, id: string) {
682
+ const url = new URL("fractory://open");
683
+ url.searchParams.set(
684
+ "repo",
685
+ gitWorkTargets(root)[0]?.path || realpathSync(root),
686
+ );
687
+ url.searchParams.set("work", id);
688
+ return url.href;
689
+ }
690
+ export function workHandoff(context: WorkContext, graph: DefinitionGraph) {
691
+ const plan = context.plan;
692
+ const states = workIntentStates(
693
+ context.root,
694
+ graph,
695
+ plan,
696
+ plan ? workBaseline(context.root, context.id) : undefined,
697
+ );
698
+ const labels = new Map([
699
+ ...graph.elements.map((node) => [node.id, node.label] as const),
700
+ ...(plan?.proposals
701
+ .filter((p) => p.kind === "block" || p.kind === "connection")
702
+ .map((p) => [p.id, p.label] as const) || []),
703
+ ]);
704
+ return [
705
+ `# ${context.title}`,
706
+ "",
707
+ context.mode === "branch" && context.mapBasis === "committed"
708
+ ? "No local worktree exists for this branch. Create one before editing; do not treat the repository checkout as this branch."
709
+ : `Worktree: ${context.root}`,
710
+ `Branch: ${context.branch}`,
711
+ `Base: ${context.baseRef} (${context.baseCommit})`,
712
+ "",
713
+ "For a local worktree, work in that exact directory. Preserve unrelated edits. Run fractory work check before committing and report any outside, shared or unassigned changes. Recompile the map after changing code. Proposed blocks and links are instructions, not implemented behavior.",
714
+ "",
715
+ "## Scope",
716
+ ...(plan?.scope || []).map(
717
+ (id) => `- ${labels.get(id) || id} (${id}), including nested blocks`,
718
+ ),
719
+ "",
720
+ ...(plan?.excluded?.length
721
+ ? [
722
+ "Excluded subtrees:",
723
+ ...plan.excluded.map((id) => `- ${labels.get(id) || id} (${id})`),
724
+ "Explicit selections nested inside an excluded subtree remain included.",
725
+ "",
726
+ ]
727
+ : []),
728
+ ...lockBrief(graph, plan?.locks || []),
729
+ "## Intended changes",
730
+ "Connections enter public interfaces. A plain box or internal method is not a valid external destination; preserve the request while choosing its real public contract.",
731
+ ...(plan?.proposals || []).map(
732
+ (p) =>
733
+ `- [${states[p.id]?.status === "changed" ? "needs recheck" : states[p.id]?.status || "planned"}] ${p.kind === "annotation" ? "comment" : p.kind}: ${p.label || labels.get(p.target || "") || p.target} [${p.id}]${p.resolved ? " [resolved]" : ""}${p.kind === "annotation" && p.target ? `; attached to ${labels.get(p.target) || p.target} (${p.target})` : ""}${p.parent ? `; inside ${labels.get(p.parent) || p.parent}` : ""}${p.source ? `; ${labels.get(p.source) || p.source} → ${labels.get(p.target!) || p.target}` : ""}${p.change ? `; ${p.change}` : ""}${p.implementation ? `; implementation: ${labels.get(p.implementation) || p.implementation} (${p.implementation})` : ""}\n ${p.note}`,
734
+ ),
735
+ "",
736
+ ...(plan?.proposals.flatMap((proposal) => {
737
+ const issue =
738
+ !proposal.implementation &&
739
+ proposalConnectionError(graph, plan, proposal);
740
+ return issue
741
+ ? [
742
+ `Connection ${proposal.label || proposal.id} needs an interface target: ${issue}`,
743
+ ]
744
+ : [];
745
+ }) || []),
746
+ "Continue planned items and items needing recheck. Done and dropped items remain recorded; do not implement them again without reopening them. Done is an explicit confirmation with a source fingerprint, not a test result.",
747
+ ...(plan?.pullRequest ? [`Pull request: ${plan.pullRequest.url}`] : []),
748
+ `Check: fractory work check ${context.id} --root ${JSON.stringify(context.root)}`,
749
+ `Factory: ${workDeepLink(context.root, context.id)}`,
750
+ "",
751
+ "The plan describes intended changes, not existing code. The scope check reports out-of-scope, shared and unassigned files; it is not a sandbox or merge protection. Compile the map and run the block's actual tests to verify the implementation.",
752
+ ].join("\n");
753
+ }