@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,59 @@
1
+ import { type WorkContext, type WorkPlan, type WorkTarget } from "./work-model.js";
2
+ import type { DefinitionGraph } from "./model.js";
3
+ import type { WorkLock } from "./work-model.js";
4
+ export declare function workDirectory(root: string): string;
5
+ export declare function mainReference(root: string): {
6
+ ref: string;
7
+ commit: string;
8
+ };
9
+ export declare function gitWorkTargets(root: string): WorkTarget[];
10
+ interface RegistryEntry {
11
+ id: string;
12
+ root: string;
13
+ planFile: string;
14
+ baselineFile: string;
15
+ }
16
+ export declare function readWorkPlan(root: string, id: string, known?: {
17
+ directory: string;
18
+ targets: WorkTarget[];
19
+ }): {
20
+ entry: RegistryEntry;
21
+ plan: WorkPlan;
22
+ revision: string;
23
+ };
24
+ export declare function workBaseline(root: string, id: string): DefinitionGraph;
25
+ export declare function listWorkContexts(root: string): WorkTarget[];
26
+ export declare function resolveWorkContext(root: string, id?: string): WorkContext;
27
+ export declare function readFactoryMap(root: string, ref?: string): Promise<DefinitionGraph | null>;
28
+ export declare function createWorkContext(root: string, graph: DefinitionGraph, input: {
29
+ title: string;
30
+ scope: string[];
31
+ excluded?: string[];
32
+ branch?: string;
33
+ from?: string;
34
+ fromName?: string;
35
+ }): Promise<WorkContext>;
36
+ /** Attach a plan to an existing registered Git checkout. No checkout, branch creation or code copy. */
37
+ export declare function adoptWorkContext(root: string, targetId: string, graph: DefinitionGraph, input: {
38
+ scope: string[];
39
+ excluded?: string[];
40
+ title?: string;
41
+ }): Promise<WorkContext>;
42
+ export declare function updateWorkPlan(root: string, id: string, graph: DefinitionGraph, input: {
43
+ revision: string;
44
+ proposals?: unknown;
45
+ scope?: string[];
46
+ excluded?: string[];
47
+ locks?: WorkLock[];
48
+ pullRequest?: WorkPlan["pullRequest"];
49
+ }, snapshot?: WorkContext): WorkContext;
50
+ /** Explicit confirmation, with evidence read from this checkout and the pinned baseline. */
51
+ export declare function updateWorkIntent(root: string, id: string, graph: DefinitionGraph, input: {
52
+ revision: string;
53
+ proposal: string;
54
+ status: "planned" | "done" | "dropped";
55
+ implementation?: string;
56
+ }): WorkContext;
57
+ export declare function workDeepLink(root: string, id: string): string;
58
+ export declare function workHandoff(context: WorkContext, graph: DefinitionGraph): string;
59
+ export {};
@@ -0,0 +1,594 @@
1
+ import { mapFromArtifacts, repositoryMapConfiguration, parseMapConfiguration, } from "./repository-map.js";
2
+ /** Local work contexts. Git refs are read without checkout; only explicit create adds a worktree. */
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, writeFileSync, rmSync, } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import { execFileSync } from "node:child_process";
7
+ import { readGit, resolveComparisonRef, comparisonMergeBase } from "./git-refs.js";
8
+ import { normalizeWorkScope, validateProposals, proposalConnectionError, } from "./work-model.js";
9
+ import { checkedPath } from "./workspace-notes.js";
10
+ import { logicalMap } from "./map-model.js";
11
+ import { intentEvidence, workIntentStates } from "./work-intents.js";
12
+ import { validateLocks, lockBrief } from "./work-locks.js";
13
+ const uuid = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
14
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
15
+ const identity = (path) => hash(path).slice(0, 20);
16
+ export function workDirectory(root) {
17
+ return join(realpathSync(resolve(root, readGit(root, ["rev-parse", "--git-common-dir"]).trim())), "fractory", "work");
18
+ }
19
+ function writeJSON(file, value) {
20
+ const temporary = `${file}.${randomUUID()}.tmp`;
21
+ writeFileSync(temporary, JSON.stringify(value, null, 2) + "\n", {
22
+ flag: "wx",
23
+ mode: 0o600,
24
+ });
25
+ renameSync(temporary, file);
26
+ }
27
+ export function mainReference(root) {
28
+ for (const ref of ["origin/main", "main", "origin/master", "master"])
29
+ try {
30
+ return { ref, commit: resolveComparisonRef(root, ref) };
31
+ }
32
+ catch { }
33
+ let symbolic = "HEAD";
34
+ try {
35
+ symbolic = readGit(root, ["symbolic-ref", "--quiet", "HEAD"])
36
+ .trim()
37
+ .replace(/^refs\/heads\//, "");
38
+ }
39
+ catch { }
40
+ return { ref: symbolic, commit: resolveComparisonRef(root, symbolic) };
41
+ }
42
+ export function gitWorkTargets(root) {
43
+ const current = realpathSync(root);
44
+ const entries = readGit(root, ["worktree", "list", "--porcelain", "-z"])
45
+ .split("\0\0")
46
+ .filter(Boolean);
47
+ return entries.flatMap((entry) => {
48
+ const lines = entry.split("\0").filter(Boolean);
49
+ const path = lines.find((line) => line.startsWith("worktree "))?.slice(9);
50
+ if (!path || !existsSync(path) || lines.includes("bare"))
51
+ return [];
52
+ const canonical = realpathSync(path);
53
+ const branch = lines
54
+ .find((line) => line.startsWith("branch "))
55
+ ?.slice(7)
56
+ .replace(/^refs\/heads\//, "") || "Detached checkout";
57
+ return [
58
+ {
59
+ id: `tree-${identity(canonical)}`,
60
+ title: branch === "Detached checkout"
61
+ ? `Local worktree · ${canonical.split("/").at(-2)}`
62
+ : branch,
63
+ branch,
64
+ path: canonical,
65
+ current: canonical === current,
66
+ managed: false,
67
+ head: lines.find((line) => line.startsWith("HEAD "))?.slice(5) || "",
68
+ },
69
+ ];
70
+ });
71
+ }
72
+ function registry(root, id, known) {
73
+ if (!uuid.test(id))
74
+ throw Error("Unknown work context.");
75
+ const value = JSON.parse(readFileSync(checkedPath(known?.directory || workDirectory(root), `${id}.json`), "utf8"));
76
+ if (value.id !== id ||
77
+ value.planFile !== `docs/fractory/work/${id}.json` ||
78
+ value.baselineFile !== `${id}.map.json`)
79
+ throw Error("Invalid work context registry.");
80
+ const target = (known?.targets || gitWorkTargets(root)).find((tree) => tree.path === value.root);
81
+ if (!target)
82
+ throw Error("This worktree is no longer available. Return to Main or choose another worktree.");
83
+ return value;
84
+ }
85
+ export function readWorkPlan(root, id, known) {
86
+ const entry = registry(root, id, known);
87
+ const file = checkedPath(entry.root, entry.planFile);
88
+ const body = readFileSync(file, "utf8");
89
+ if (Buffer.byteLength(body) > 512000)
90
+ throw Error("The work plan exceeds its read budget.");
91
+ const plan = JSON.parse(body);
92
+ if (plan.schema !== "fractory.work.v1" ||
93
+ plan.id !== id ||
94
+ !Array.isArray(plan.scope) ||
95
+ plan.scope.some((id) => typeof id !== "string") ||
96
+ (plan.excluded !== undefined &&
97
+ (!Array.isArray(plan.excluded) ||
98
+ plan.excluded.some((id) => typeof id !== "string"))) ||
99
+ (plan.locks !== undefined &&
100
+ (!Array.isArray(plan.locks) ||
101
+ plan.locks.length > 500 ||
102
+ new Set(plan.locks.map((l) => l?.target)).size !== plan.locks.length ||
103
+ plan.locks.some((lock) => !lock ||
104
+ typeof lock.target !== "string" ||
105
+ !["subtree", "contract"].includes(lock.kind) ||
106
+ (lock.note !== undefined &&
107
+ (typeof lock.note !== "string" || lock.note.length > 4000))))))
108
+ throw Error("Invalid work plan.");
109
+ return { entry, plan, revision: hash(body) };
110
+ }
111
+ export function workBaseline(root, id) {
112
+ const entry = registry(root, id);
113
+ return JSON.parse(readFileSync(checkedPath(workDirectory(root), entry.baselineFile), "utf8"));
114
+ }
115
+ export function listWorkContexts(root) {
116
+ const targets = gitWorkTargets(root);
117
+ const directory = workDirectory(root);
118
+ let files = [];
119
+ try {
120
+ files = readdirSync(directory)
121
+ .filter((file) => uuid.test(file.replace(/\.json$/, "")))
122
+ .slice(0, 500);
123
+ }
124
+ catch { }
125
+ for (const file of files) {
126
+ try {
127
+ const { entry, plan } = readWorkPlan(root, file.replace(/\.json$/, ""), {
128
+ directory,
129
+ targets,
130
+ });
131
+ const target = targets.find((tree) => tree.path === entry.root);
132
+ if (target) {
133
+ target.id = plan.id;
134
+ target.title = plan.title;
135
+ target.managed = true;
136
+ target.scope = plan.scope;
137
+ target.plannedAt = plan.createdAt;
138
+ target.pullRequest = plan.pullRequest;
139
+ }
140
+ }
141
+ catch {
142
+ /* Missing worktrees stay in Git's own list, never guessed from a stale path. */
143
+ }
144
+ }
145
+ const branches = readGit(root, [
146
+ "for-each-ref",
147
+ "--format=%(refname:short)%00%(objectname)",
148
+ "refs/heads/",
149
+ ])
150
+ .trim()
151
+ .split("\n")
152
+ .filter(Boolean);
153
+ for (const item of branches) {
154
+ const [branch, head] = item.split("\0");
155
+ if (!targets.some((tree) => tree.branch === branch))
156
+ targets.push({
157
+ id: `branch-${identity(branch)}`,
158
+ branch,
159
+ title: branch,
160
+ head,
161
+ current: false,
162
+ managed: false,
163
+ });
164
+ }
165
+ return targets;
166
+ }
167
+ export function resolveWorkContext(root, id = "main") {
168
+ const main = mainReference(root);
169
+ if (id === "main")
170
+ return {
171
+ id,
172
+ mode: "main",
173
+ title: "Main",
174
+ branch: main.ref,
175
+ root: realpathSync(root),
176
+ head: main.commit,
177
+ baseRef: main.ref,
178
+ baseCommit: main.commit,
179
+ mapBasis: "committed",
180
+ hasCheckout: false,
181
+ };
182
+ if (uuid.test(id)) {
183
+ const { entry, plan, revision } = readWorkPlan(root, id);
184
+ const head = resolveComparisonRef(entry.root, "HEAD");
185
+ let copied = false;
186
+ if (plan.bootstrapRevision)
187
+ try {
188
+ copied =
189
+ JSON.parse(readFileSync(checkedPath(entry.root, "fractory.json"), "utf8")).revision === plan.bootstrapRevision;
190
+ }
191
+ catch { }
192
+ return {
193
+ id,
194
+ mode: "work",
195
+ title: plan.title,
196
+ branch: plan.branch,
197
+ root: entry.root,
198
+ head,
199
+ baseRef: plan.baseRef,
200
+ baseCommit: plan.baseCommit,
201
+ plan,
202
+ revision,
203
+ mapBasis: copied ? "baseline" : "checkout",
204
+ hasCheckout: true,
205
+ notice: copied
206
+ ? "Structure copied from the reviewed map. Compile this worktree to verify its code references."
207
+ : undefined,
208
+ };
209
+ }
210
+ const targets = listWorkContexts(root);
211
+ const raw = gitWorkTargets(root).find((tree) => tree.id === id);
212
+ const adopted = raw && targets.find((tree) => tree.path === raw.path && tree.managed);
213
+ if (adopted)
214
+ return resolveWorkContext(root, adopted.id);
215
+ const target = targets.find((tree) => tree.id === id);
216
+ if (!target)
217
+ throw Error("Unknown branch or worktree.");
218
+ return {
219
+ id,
220
+ mode: "branch",
221
+ title: target.title,
222
+ branch: target.branch,
223
+ root: target.path || realpathSync(root),
224
+ head: target.head,
225
+ baseRef: main.ref,
226
+ baseCommit: comparisonMergeBase(root, main.commit, target.head),
227
+ mapBasis: target.path ? "checkout" : "committed",
228
+ hasCheckout: !!target.path,
229
+ notice: target.path
230
+ ? undefined
231
+ : "This branch has no local worktree. Open it read-only, or start a worktree to develop it.",
232
+ };
233
+ }
234
+ const immutableMaps = new Map();
235
+ export async function readFactoryMap(root, ref) {
236
+ if (!ref)
237
+ return readFactoryMapUncached(root);
238
+ const commit = resolveComparisonRef(root, ref), key = `${realpathSync(root)}:${commit}:${JSON.stringify(repositoryMapConfiguration(root))}`;
239
+ let pending = immutableMaps.get(key);
240
+ if (!pending) {
241
+ pending = readFactoryMapUncached(root, commit);
242
+ immutableMaps.set(key, pending);
243
+ if (immutableMaps.size > 24)
244
+ immutableMaps.delete(immutableMaps.keys().next().value);
245
+ void pending.catch(() => immutableMaps.delete(key));
246
+ }
247
+ return pending;
248
+ }
249
+ async function readFactoryMapUncached(root, ref) {
250
+ const text = (file) => {
251
+ try {
252
+ return ref
253
+ ? readGit(root, ["show", `${resolveComparisonRef(root, ref)}:${file}`])
254
+ : readFileSync(checkedPath(root, file), "utf8");
255
+ }
256
+ catch {
257
+ return undefined;
258
+ }
259
+ };
260
+ const configuration = text("fractory.config.json");
261
+ const graph = mapFromArtifacts(configuration
262
+ ? parseMapConfiguration(configuration)
263
+ : repositoryMapConfiguration(root), text);
264
+ if (!graph)
265
+ return null;
266
+ if (graph.schema !== "fractal.definition.v1" ||
267
+ !graph.id ||
268
+ !Array.isArray(graph.elements) ||
269
+ !Array.isArray(graph.connections))
270
+ throw Error("Invalid factory map.");
271
+ return logicalMap(graph);
272
+ }
273
+ export async function createWorkContext(root, graph, input) {
274
+ const title = input.title.trim();
275
+ if (!title || title.length > 120 || /[\x00-\x1f]/.test(title))
276
+ throw Error("Give the work a short name.");
277
+ if (!input.scope.length)
278
+ throw Error("Select at least one block.");
279
+ const { scope, excluded } = normalizeWorkScope(graph, input.scope, input.excluded);
280
+ const id = randomUUID();
281
+ const main = mainReference(root);
282
+ const from = input.from
283
+ ? resolveComparisonRef(root, input.from)
284
+ : main.commit;
285
+ if (!/^[a-f0-9]{40,64}$/.test(from))
286
+ throw Error(`Invalid base commit: ${JSON.stringify(main)} at ${root}`);
287
+ const slug = title
288
+ .toLowerCase()
289
+ .normalize("NFKD")
290
+ .replace(/[^a-z0-9]+/g, "-")
291
+ .replace(/^-|-$/g, "")
292
+ .slice(0, 48) || "work";
293
+ const branch = input.branch || `codex/${slug}-${id.slice(0, 6)}`;
294
+ if (!/^codex\/[a-zA-Z0-9][a-zA-Z0-9/_-]{0,100}$/.test(branch))
295
+ throw Error("Use a codex/ branch name without spaces.");
296
+ readGit(root, ["check-ref-format", `refs/heads/${branch}`]);
297
+ const path = checkedPath(root, `.fractal/worktrees/${slug}-${id.slice(0, 6)}`, true);
298
+ if (existsSync(path))
299
+ throw Error("The worktree destination already exists.");
300
+ mkdirSync(join(root, ".fractal/worktrees"), { recursive: true });
301
+ execFileSync("git", [
302
+ "-c",
303
+ "core.hooksPath=/dev/null",
304
+ "-c",
305
+ "core.fsmonitor=false",
306
+ "worktree",
307
+ "add",
308
+ "-b",
309
+ branch,
310
+ "--",
311
+ path,
312
+ from,
313
+ ], {
314
+ cwd: root,
315
+ timeout: 60000,
316
+ maxBuffer: 2 * 1024 * 1024,
317
+ stdio: ["ignore", "pipe", "pipe"],
318
+ });
319
+ const plan = {
320
+ schema: "fractory.work.v1",
321
+ id,
322
+ title,
323
+ branch,
324
+ baseRef: input.fromName || input.from || main.ref,
325
+ baseCommit: from,
326
+ createdAt: new Date().toISOString(),
327
+ scope,
328
+ ...(excluded.length ? { excluded } : {}),
329
+ proposals: [],
330
+ };
331
+ const planFile = `docs/fractory/work/${id}.json`;
332
+ mkdirSync(join(path, "docs/fractory/work"), { recursive: true });
333
+ // A supplied reviewed map is explicit when the base revision predates mapping.
334
+ if (!(await readFactoryMap(path))) {
335
+ plan.bootstrapRevision = graph.revision;
336
+ writeJSON(checkedPath(path, "fractory.json", true), {
337
+ ...graph,
338
+ codeRevision: undefined,
339
+ });
340
+ }
341
+ writeJSON(checkedPath(path, planFile, true), plan);
342
+ // Carry only the Fractory skill, without copying credentials or other agents' settings.
343
+ for (const file of [
344
+ ".agents/skills/fractory/SKILL.md",
345
+ ".agents/skills/fractory/references/fractory-guide.md",
346
+ ])
347
+ try {
348
+ if (existsSync(checkedPath(path, file, true)))
349
+ continue;
350
+ const body = readFileSync(checkedPath(root, file), "utf8");
351
+ if (Buffer.byteLength(body) > 128000)
352
+ continue;
353
+ const destination = checkedPath(path, file, true);
354
+ mkdirSync(resolve(destination, ".."), { recursive: true });
355
+ writeFileSync(destination, body, { flag: "wx", mode: 0o600 });
356
+ }
357
+ catch {
358
+ /* The portable app/CLI skill remains available when the repo has none. */
359
+ }
360
+ const directory = workDirectory(root);
361
+ mkdirSync(directory, { recursive: true });
362
+ writeJSON(checkedPath(directory, `${id}.map.json`, true), graph);
363
+ writeJSON(checkedPath(directory, `${id}.json`, true), {
364
+ id,
365
+ root: realpathSync(path),
366
+ planFile,
367
+ baselineFile: `${id}.map.json`,
368
+ });
369
+ return resolveWorkContext(root, id);
370
+ }
371
+ /** Attach a plan to an existing registered Git checkout. No checkout, branch creation or code copy. */
372
+ export async function adoptWorkContext(root, targetId, graph, input) {
373
+ const target = gitWorkTargets(root).find((tree) => tree.id === targetId) ||
374
+ listWorkContexts(root).find((tree) => tree.id === targetId);
375
+ if (!target?.path)
376
+ throw Error("Open an existing worktree before planning changes.");
377
+ if (!input.scope.length)
378
+ throw Error("Select at least one block.");
379
+ const { scope, excluded } = normalizeWorkScope(graph, input.scope, input.excluded);
380
+ const existing = listWorkContexts(root).find((tree) => tree.path === target.path && tree.managed);
381
+ if (existing)
382
+ return resolveWorkContext(root, existing.id);
383
+ const directory = workDirectory(root);
384
+ mkdirSync(directory, { recursive: true });
385
+ const lock = join(directory, `adopt-${identity(target.path)}.lock`);
386
+ try {
387
+ mkdirSync(lock);
388
+ }
389
+ catch {
390
+ throw Error("This worktree is being prepared. Retry in a moment.");
391
+ }
392
+ try {
393
+ const already = listWorkContexts(root).find((tree) => tree.path === target.path && tree.managed);
394
+ if (already)
395
+ return resolveWorkContext(root, already.id);
396
+ const main = mainReference(root), id = randomUUID();
397
+ const baseCommit = comparisonMergeBase(root, main.commit, target.head);
398
+ const baseline = (await readFactoryMap(target.path, baseCommit)) || graph;
399
+ if (resolveComparisonRef(target.path, "HEAD") !== target.head)
400
+ throw Error("The worktree advanced while its plan was prepared. Retry.");
401
+ const title = (input.title || target.title).trim();
402
+ if (!title || title.length > 120 || /[\x00-\x1f]/.test(title))
403
+ throw Error("Give the work a short name.");
404
+ const plan = {
405
+ schema: "fractory.work.v1",
406
+ id,
407
+ title,
408
+ branch: target.branch,
409
+ baseRef: main.ref,
410
+ baseCommit,
411
+ createdAt: new Date().toISOString(),
412
+ scope,
413
+ ...(excluded.length ? { excluded } : {}),
414
+ proposals: [],
415
+ };
416
+ const planFile = `docs/fractory/work/${id}.json`;
417
+ mkdirSync(checkedPath(target.path, "docs/fractory/work", true), {
418
+ recursive: true,
419
+ });
420
+ writeJSON(checkedPath(target.path, planFile, true), plan);
421
+ writeJSON(checkedPath(directory, `${id}.map.json`, true), baseline);
422
+ writeJSON(checkedPath(directory, `${id}.json`, true), {
423
+ id,
424
+ root: target.path,
425
+ planFile,
426
+ baselineFile: `${id}.map.json`,
427
+ });
428
+ return resolveWorkContext(root, id);
429
+ }
430
+ finally {
431
+ rmSync(lock, { recursive: true, force: true });
432
+ }
433
+ }
434
+ export function updateWorkPlan(root, id, graph, input, snapshot) {
435
+ const current = readWorkPlan(root, id);
436
+ if (input.revision !== current.revision)
437
+ throw Error("This plan changed. Reload it before saving.");
438
+ const plan = {
439
+ ...current.plan,
440
+ ...(input.locks !== undefined
441
+ ? { locks: validateLocks(graph, input.locks, current.plan.locks) }
442
+ : {}),
443
+ proposals: input.proposals === undefined
444
+ ? current.plan.proposals
445
+ : validateProposals(graph, input.proposals, current.plan.proposals),
446
+ ...(input.scope !== undefined || input.excluded !== undefined
447
+ ? normalizeWorkScope(graph, input.scope ?? current.plan.scope, input.excluded ?? current.plan.excluded)
448
+ : {}),
449
+ };
450
+ if (input.pullRequest) {
451
+ const url = new URL(input.pullRequest.url);
452
+ if (url.protocol !== "https:" ||
453
+ url.username ||
454
+ url.password ||
455
+ !/^\/[^/]+\/[^/]+\/pull\/\d+$/.test(url.pathname))
456
+ throw Error("Choose a pull-request URL.");
457
+ plan.pullRequest = {
458
+ url: url.href,
459
+ title: String(input.pullRequest.title).slice(0, 200),
460
+ };
461
+ }
462
+ writeJSON(checkedPath(current.entry.root, current.entry.planFile), plan);
463
+ // A caller that just resolved this checkout need not rescan Git and every
464
+ // worktree again to return a plan-only edit. The file revision still guards writes.
465
+ if (snapshot?.id === id && snapshot.root === current.entry.root)
466
+ return { ...snapshot, plan, revision: readWorkPlan(root, id).revision };
467
+ return resolveWorkContext(root, id);
468
+ }
469
+ /** Explicit confirmation, with evidence read from this checkout and the pinned baseline. */
470
+ export function updateWorkIntent(root, id, graph, input) {
471
+ const current = readWorkPlan(root, id);
472
+ if (input.revision !== current.revision)
473
+ throw Error("This plan changed. Reload it before saving.");
474
+ if (!["planned", "done", "dropped"].includes(input.status))
475
+ throw Error("Choose Planned, Done or Dropped.");
476
+ const p = current.plan.proposals.find((p) => p.id === input.proposal);
477
+ if (!p)
478
+ throw Error("This intention is no longer in the plan.");
479
+ const next = { ...p };
480
+ if (input.implementation !== undefined) {
481
+ const valid = (p.kind === "connection"
482
+ ? graph.connections
483
+ : p.kind === "block"
484
+ ? graph.elements
485
+ : [...graph.elements, ...graph.connections]).some((n) => n.id === input.implementation && n.provenance !== "proposed");
486
+ if (!valid)
487
+ throw Error("Choose an actual mapped block or connection.");
488
+ next.implementation = input.implementation;
489
+ }
490
+ delete next.outcome;
491
+ if (input.status !== "planned")
492
+ next.outcome = {
493
+ status: input.status,
494
+ checkedAt: new Date().toISOString(),
495
+ ...(input.status === "done"
496
+ ? {
497
+ evidence: intentEvidence(current.entry.root, graph, next, workBaseline(root, id)),
498
+ }
499
+ : {}),
500
+ };
501
+ const dropped = new Set(input.status === "dropped" ? [next.id] : []);
502
+ if (next.kind === "block" && dropped.size) {
503
+ for (let i = 0, changed = true; changed && i < current.plan.proposals.length; i++) {
504
+ changed = false;
505
+ for (const p of current.plan.proposals)
506
+ if (!dropped.has(p.id) &&
507
+ p.outcome?.status !== "done" &&
508
+ [p.parent, p.source, p.target].some((id) => id && dropped.has(id))) {
509
+ dropped.add(p.id);
510
+ changed = true;
511
+ }
512
+ }
513
+ }
514
+ return updateWorkPlan(root, id, graph, {
515
+ revision: current.revision,
516
+ proposals: current.plan.proposals.map((p) => p.id === next.id
517
+ ? next
518
+ : dropped.has(p.id)
519
+ ? {
520
+ ...p,
521
+ outcome: {
522
+ status: "dropped",
523
+ checkedAt: next.outcome.checkedAt,
524
+ },
525
+ }
526
+ : next.kind === "block" &&
527
+ input.status === "done" &&
528
+ next.implementation &&
529
+ p.kind === "annotation" &&
530
+ p.target === next.id &&
531
+ !p.implementation
532
+ ? { ...p, implementation: next.implementation }
533
+ : p),
534
+ });
535
+ }
536
+ export function workDeepLink(root, id) {
537
+ const url = new URL("fractory://open");
538
+ url.searchParams.set("repo", gitWorkTargets(root)[0]?.path || realpathSync(root));
539
+ url.searchParams.set("work", id);
540
+ return url.href;
541
+ }
542
+ export function workHandoff(context, graph) {
543
+ const plan = context.plan;
544
+ const states = workIntentStates(context.root, graph, plan, plan ? workBaseline(context.root, context.id) : undefined);
545
+ const labels = new Map([
546
+ ...graph.elements.map((node) => [node.id, node.label]),
547
+ ...(plan?.proposals
548
+ .filter((p) => p.kind === "block" || p.kind === "connection")
549
+ .map((p) => [p.id, p.label]) || []),
550
+ ]);
551
+ return [
552
+ `# ${context.title}`,
553
+ "",
554
+ context.mode === "branch" && context.mapBasis === "committed"
555
+ ? "No local worktree exists for this branch. Create one before editing; do not treat the repository checkout as this branch."
556
+ : `Worktree: ${context.root}`,
557
+ `Branch: ${context.branch}`,
558
+ `Base: ${context.baseRef} (${context.baseCommit})`,
559
+ "",
560
+ "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.",
561
+ "",
562
+ "## Scope",
563
+ ...(plan?.scope || []).map((id) => `- ${labels.get(id) || id} (${id}), including nested blocks`),
564
+ "",
565
+ ...(plan?.excluded?.length
566
+ ? [
567
+ "Excluded subtrees:",
568
+ ...plan.excluded.map((id) => `- ${labels.get(id) || id} (${id})`),
569
+ "Explicit selections nested inside an excluded subtree remain included.",
570
+ "",
571
+ ]
572
+ : []),
573
+ ...lockBrief(graph, plan?.locks || []),
574
+ "## Intended changes",
575
+ "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.",
576
+ ...(plan?.proposals || []).map((p) => `- [${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}`),
577
+ "",
578
+ ...(plan?.proposals.flatMap((proposal) => {
579
+ const issue = !proposal.implementation &&
580
+ proposalConnectionError(graph, plan, proposal);
581
+ return issue
582
+ ? [
583
+ `Connection ${proposal.label || proposal.id} needs an interface target: ${issue}`,
584
+ ]
585
+ : [];
586
+ }) || []),
587
+ "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.",
588
+ ...(plan?.pullRequest ? [`Pull request: ${plan.pullRequest.url}`] : []),
589
+ `Check: fractory work check ${context.id} --root ${JSON.stringify(context.root)}`,
590
+ `Factory: ${workDeepLink(context.root, context.id)}`,
591
+ "",
592
+ "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.",
593
+ ].join("\n");
594
+ }
@@ -0,0 +1,6 @@
1
+ import type { Connection, DefinitionGraph, Element } from "./model.js";
2
+ import type { WorkIntentState, WorkPlan, WorkProposal } from "./work-model.js";
3
+ export declare function intentTarget(graph: DefinitionGraph, proposal: WorkProposal): "" | Connection | Element | undefined;
4
+ /** No fuzzy match: an agent/developer chooses the implementation identity explicitly. */
5
+ export declare function intentEvidence(root: string, graph: DefinitionGraph, proposal: WorkProposal, baseline?: DefinitionGraph): string;
6
+ export declare function workIntentStates(root: string, graph: DefinitionGraph, plan?: WorkPlan, baseline?: DefinitionGraph): Record<string, WorkIntentState>;