@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,582 @@
1
+ /** Read-only, bounded Git adapter for live edits. No compiler, source graph builder or application imports. */
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import { createHash } from "node:crypto";
5
+ import { realpath, lstat } from "node:fs/promises";
6
+ import { resolve } from "node:path";
7
+ const execute = promisify(execFile);
8
+ const identifier = (path: string) =>
9
+ createHash("sha256").update(path).digest("hex").slice(0, 20);
10
+ async function git(root: string, args: string[]) {
11
+ const { stdout } = await execute(
12
+ "git",
13
+ [
14
+ "--no-pager",
15
+ "-c",
16
+ "core.quotePath=false",
17
+ "-c",
18
+ "core.fsmonitor=false",
19
+ ...args,
20
+ ],
21
+ {
22
+ cwd: root,
23
+ encoding: "utf8",
24
+ timeout: 8_000,
25
+ maxBuffer: 2 * 1024 * 1024,
26
+ env: {
27
+ ...process.env,
28
+ GIT_OPTIONAL_LOCKS: "0",
29
+ GIT_LITERAL_PATHSPECS: "1",
30
+ },
31
+ },
32
+ );
33
+ return stdout;
34
+ }
35
+ export interface WorkingPath {
36
+ modifiedAt?: string;
37
+ /** Fingerprint of Git index metadata, not a source-content read. */
38
+ indexRevision?: string;
39
+ path: string;
40
+ index: string;
41
+ working: string;
42
+ kind: "file" | "directory" | "submodule";
43
+ untracked: boolean;
44
+ conflict: boolean;
45
+ originalPath?: string;
46
+ }
47
+ /** Exact saved files for a worktree review. No scan of sibling checkouts and no directory placeholders. */
48
+ export async function currentWorkingPaths(
49
+ root: string,
50
+ ): Promise<WorkingPath[]> {
51
+ const paths = parseWorkingStatus(
52
+ await git(root, [
53
+ "status",
54
+ "--porcelain=v2",
55
+ "-z",
56
+ "--untracked-files=all",
57
+ "--no-renames",
58
+ ]),
59
+ );
60
+ if (paths.length > 20000)
61
+ throw Error(
62
+ "This worktree exceeds the 20,000-file review budget; no partial comparison was returned.",
63
+ );
64
+ for (let at = 0; at < paths.length; at += 32)
65
+ await Promise.all(
66
+ paths.slice(at, at + 32).map(async (file) => {
67
+ try {
68
+ file.modifiedAt = (
69
+ await lstat(resolve(root, file.path))
70
+ ).mtime.toISOString();
71
+ } catch {}
72
+ }),
73
+ );
74
+ return paths;
75
+ }
76
+ export interface WorkingTree {
77
+ id: string;
78
+ path: string;
79
+ branch: string | null;
80
+ head: string | null;
81
+ current: boolean;
82
+ checkedAt: string | null;
83
+ locked: boolean;
84
+ unavailable?: string;
85
+ stale?: boolean;
86
+ changed: number | null;
87
+ staged: number | null;
88
+ unstaged: number | null;
89
+ conflicts: number | null;
90
+ untracked: number | null;
91
+ }
92
+ interface ScannedTree extends WorkingTree {
93
+ paths: WorkingPath[];
94
+ }
95
+ export interface WorkingOverview {
96
+ /** Complete attribution; the inspectable path list can remain bounded. */
97
+ mapping?: {
98
+ revision: string;
99
+ cells: Record<string, import("./map-activity").ActivityCell>;
100
+ unmapped: number;
101
+ };
102
+ checkedAt: string;
103
+ worktreesCheckedAt: string;
104
+ revision: string;
105
+ attribution: "worktree";
106
+ worktrees: WorkingTree[];
107
+ selected: string;
108
+ paths: WorkingPath[];
109
+ truncated: boolean;
110
+ omittedWorktrees: number;
111
+ }
112
+ export interface WorkingDetail {
113
+ path: string;
114
+ untracked: boolean;
115
+ conflict?: { stages: number[] };
116
+ members?: string[];
117
+ truncated: boolean;
118
+ layers: Array<{
119
+ layer: "staged" | "unstaged";
120
+ binary: boolean;
121
+ hunks: Array<{
122
+ beforeStart: number;
123
+ beforeCount: number;
124
+ afterStart: number;
125
+ afterCount: number;
126
+ }>;
127
+ }>;
128
+ }
129
+ export function parseWorkingStatus(output: string): WorkingPath[] {
130
+ const parts = output.split("\0"),
131
+ paths: WorkingPath[] = [];
132
+ for (let i = 0; i < parts.length; i++) {
133
+ const row = parts[i];
134
+ if (!row || row.startsWith("# ")) continue;
135
+ if (row.startsWith("? ")) {
136
+ const path = row.slice(2);
137
+ paths.push({
138
+ path,
139
+ index: ".",
140
+ working: ".",
141
+ kind: path.endsWith("/") ? "directory" : "file",
142
+ untracked: true,
143
+ conflict: false,
144
+ });
145
+ continue;
146
+ }
147
+ const fields = row.split(" "),
148
+ type = fields[0];
149
+ if (!["1", "2", "u"].includes(type)) continue;
150
+ const path = fields
151
+ .slice(type === "u" ? 10 : type === "2" ? 9 : 8)
152
+ .join(" ");
153
+ if (!path) throw Error("Incomplete Git status record");
154
+ paths.push({
155
+ path,
156
+ index: fields[1][0],
157
+ indexRevision: identifier(
158
+ fields.slice(type === "u" ? 7 : 6, type === "u" ? 10 : 8).join(" "),
159
+ ),
160
+ working: fields[1][1],
161
+ kind: fields[2].startsWith("S") ? "submodule" : "file",
162
+ untracked: false,
163
+ conflict: type === "u",
164
+ ...(type === "2" ? { originalPath: parts[++i] } : {}),
165
+ });
166
+ }
167
+ return paths;
168
+ }
169
+ async function trees(root: string) {
170
+ const current = await realpath(
171
+ (await git(root, ["rev-parse", "--show-toplevel"])).trim(),
172
+ );
173
+ const common = await realpath(
174
+ resolve(root, (await git(root, ["rev-parse", "--git-common-dir"])).trim()),
175
+ );
176
+ const records = (await git(root, ["worktree", "list", "--porcelain", "-z"]))
177
+ .split("\0\0")
178
+ .filter(Boolean);
179
+ return {
180
+ current,
181
+ common,
182
+ entries: records.flatMap((record) => {
183
+ const fields = record.split("\0"),
184
+ path = fields.find((v) => v.startsWith("worktree "))?.slice(9);
185
+ if (!path || fields.includes("bare")) return [];
186
+ return [
187
+ {
188
+ path,
189
+ head: fields.find((v) => v.startsWith("HEAD "))?.slice(5) || null,
190
+ branch:
191
+ fields
192
+ .find((v) => v.startsWith("branch "))
193
+ ?.slice(7)
194
+ .replace(/^refs\/heads\//, "") || null,
195
+ locked: fields.some((v) => v === "locked" || v.startsWith("locked ")),
196
+ prunable: fields.some(
197
+ (v) => v === "prunable" || v.startsWith("prunable "),
198
+ ),
199
+ },
200
+ ];
201
+ }),
202
+ };
203
+ }
204
+ type TreeEntry = Awaited<ReturnType<typeof trees>>["entries"][number];
205
+ async function scanOne(
206
+ tree: TreeEntry,
207
+ current: string,
208
+ common: string,
209
+ ): Promise<ScannedTree> {
210
+ let paths: WorkingPath[] = [],
211
+ unavailable: string | undefined,
212
+ currentTree = false;
213
+ try {
214
+ currentTree = (await realpath(tree.path)) === current;
215
+ if (tree.prunable) throw Error("prunable");
216
+ if (
217
+ (await realpath(
218
+ resolve(
219
+ tree.path,
220
+ (await git(tree.path, ["rev-parse", "--git-common-dir"])).trim(),
221
+ ),
222
+ )) !== common
223
+ )
224
+ throw Error("Worktree belongs to another repository");
225
+ const status = await git(tree.path, [
226
+ "status",
227
+ "--porcelain=v2",
228
+ "-z",
229
+ "--branch",
230
+ "--untracked-files=normal",
231
+ "--no-renames",
232
+ ]);
233
+ paths = parseWorkingStatus(status);
234
+ // Metadata only, bounded to the paths shown. A repeated edit to an already-dirty
235
+ // file must be visible without hashing source or compiling on each poll.
236
+ const shown = paths.slice(0, 500);
237
+ for (let at = 0; at < shown.length; at += 32)
238
+ await Promise.all(
239
+ shown.slice(at, at + 32).map(async (file) => {
240
+ if (file.path.startsWith("/") || file.path.split("/").includes(".."))
241
+ return;
242
+ try {
243
+ file.modifiedAt = (
244
+ await lstat(resolve(tree.path, file.path))
245
+ ).mtime.toISOString();
246
+ } catch {
247
+ /* A deletion has no mtime. */
248
+ }
249
+ }),
250
+ );
251
+ const headers = status.split("\0").filter((row) => row.startsWith("# "));
252
+ const oid = headers
253
+ .find((row) => row.startsWith("# branch.oid "))
254
+ ?.slice(13);
255
+ const branch = headers
256
+ .find((row) => row.startsWith("# branch.head "))
257
+ ?.slice(14);
258
+ tree = {
259
+ ...tree,
260
+ head: oid && oid !== "(initial)" ? oid : null,
261
+ branch: branch && branch !== "(detached)" ? branch : null,
262
+ };
263
+ } catch {
264
+ unavailable = "Checkout unavailable or Git status exceeded its read budget";
265
+ }
266
+ return {
267
+ id: identifier(tree.path),
268
+ path: tree.path,
269
+ branch: tree.branch,
270
+ head: tree.head && !/^0+$/.test(tree.head) ? tree.head : null,
271
+ current: currentTree,
272
+ checkedAt: new Date().toISOString(),
273
+ locked: tree.locked,
274
+ ...(unavailable ? { unavailable } : {}),
275
+ changed: unavailable ? null : paths.length,
276
+ staged: unavailable
277
+ ? null
278
+ : paths.filter((p) => !p.untracked && !p.conflict && p.index !== ".")
279
+ .length,
280
+ unstaged: unavailable
281
+ ? null
282
+ : paths.filter((p) => !p.untracked && !p.conflict && p.working !== ".")
283
+ .length,
284
+ conflicts: unavailable ? null : paths.filter((p) => p.conflict).length,
285
+ untracked: unavailable ? null : paths.filter((p) => p.untracked).length,
286
+ paths: unavailable ? [] : paths,
287
+ };
288
+ }
289
+ interface Scan {
290
+ checkedAt: string;
291
+ current: string;
292
+ common: string;
293
+ worktrees: ScannedTree[];
294
+ omittedWorktrees: number;
295
+ }
296
+ async function scan(root: string, previous?: Scan): Promise<Scan> {
297
+ const { current, common, entries } = await trees(root);
298
+ // Resolve only directory metadata so a symlinked current checkout is never excluded by the cap.
299
+ const currentPaths = new Set(
300
+ (
301
+ await Promise.all(
302
+ entries.map(async (e) => {
303
+ try {
304
+ return (await realpath(e.path)) === current ? e.path : undefined;
305
+ } catch {
306
+ return undefined;
307
+ }
308
+ }),
309
+ )
310
+ ).filter((p): p is string => !!p),
311
+ );
312
+ entries.sort(
313
+ (a, b) =>
314
+ Number(currentPaths.has(b.path)) - Number(currentPaths.has(a.path)),
315
+ );
316
+ const before = new Map(
317
+ previous?.worktrees.map((tree) => [tree.id, tree]) || [],
318
+ );
319
+ // Listing worktrees must not trigger a status walk of every checkout.
320
+ const result: ScannedTree[] = entries.slice(0, 128).map((tree) => {
321
+ const id = identifier(tree.path);
322
+ const head = tree.head && !/^0+$/.test(tree.head) ? tree.head : null;
323
+ const cached = before.get(id);
324
+ if (
325
+ cached &&
326
+ cached.head === head &&
327
+ cached.branch === tree.branch &&
328
+ !tree.prunable
329
+ )
330
+ return {
331
+ ...cached,
332
+ current: currentPaths.has(tree.path),
333
+ locked: tree.locked,
334
+ };
335
+ return {
336
+ id,
337
+ path: tree.path,
338
+ head,
339
+ branch: tree.branch,
340
+ locked: tree.locked,
341
+ current: currentPaths.has(tree.path),
342
+ checkedAt: null,
343
+ changed: null,
344
+ staged: null,
345
+ unstaged: null,
346
+ conflicts: null,
347
+ untracked: null,
348
+ paths: [],
349
+ ...(tree.prunable
350
+ ? { unavailable: "Checkout is no longer available" }
351
+ : {}),
352
+ };
353
+ });
354
+ return {
355
+ checkedAt: new Date().toISOString(),
356
+ current,
357
+ common,
358
+ worktrees: result,
359
+ omittedWorktrees: Math.max(0, entries.length - result.length),
360
+ };
361
+ }
362
+ const scans = new Map<
363
+ string,
364
+ { at: number; pending: boolean; value: Promise<Scan> }
365
+ >();
366
+ async function cachedScan(root: string, fresh: boolean) {
367
+ root = await realpath(root);
368
+ const existing = scans.get(root);
369
+ if (
370
+ existing &&
371
+ (existing.pending || (!fresh && Date.now() - existing.at < 30_000))
372
+ )
373
+ return existing.value;
374
+ const value = (async () => {
375
+ const previous = existing
376
+ ? await existing.value.catch(() => undefined)
377
+ : undefined;
378
+ return scan(root, previous);
379
+ })();
380
+ const entry = { at: Date.now(), pending: true, value };
381
+ scans.set(root, entry);
382
+ try {
383
+ return await value;
384
+ } catch (error) {
385
+ if (scans.get(root)?.value === value) scans.delete(root);
386
+ throw error;
387
+ } finally {
388
+ entry.pending = false;
389
+ entry.at = Date.now();
390
+ }
391
+ }
392
+ const activeReads = new Map<string, Promise<ScannedTree>>();
393
+ export async function workingOverview(
394
+ root: string,
395
+ options: {
396
+ worktree?: string;
397
+ fresh?: boolean;
398
+ allPaths?: boolean;
399
+ refreshSelected?: boolean;
400
+ } = {},
401
+ ): Promise<WorkingOverview> {
402
+ const value = await cachedScan(root, !!options.fresh);
403
+ let selected = options.worktree
404
+ ? value.worktrees.find((t) => t.id === options.worktree)
405
+ : value.worktrees.find((t) => t.current);
406
+ if (!selected) throw Error("Unknown repository worktree");
407
+ if (
408
+ options.fresh ||
409
+ options.refreshSelected ||
410
+ !selected.checkedAt ||
411
+ Date.now() - Date.parse(selected.checkedAt) > 2_000
412
+ ) {
413
+ const index = value.worktrees.indexOf(selected);
414
+ const key = value.common + "\0" + value.current + "\0" + selected.id;
415
+ let pending = activeReads.get(key);
416
+ if (!pending) {
417
+ pending = scanOne(
418
+ { ...selected, prunable: false },
419
+ value.current,
420
+ value.common,
421
+ );
422
+ activeReads.set(key, pending);
423
+ }
424
+ try {
425
+ selected = await pending;
426
+ } finally {
427
+ if (activeReads.get(key) === pending) activeReads.delete(key);
428
+ }
429
+ value.worktrees[index] = selected;
430
+ }
431
+ const selectedId = selected.id;
432
+ const worktrees = value.worktrees.map(({ paths, ...tree }) =>
433
+ tree.id !== selectedId &&
434
+ tree.checkedAt &&
435
+ Date.now() - Date.parse(tree.checkedAt) > 30_000
436
+ ? {
437
+ ...tree,
438
+ stale: true,
439
+ changed: null,
440
+ staged: null,
441
+ unstaged: null,
442
+ conflicts: null,
443
+ untracked: null,
444
+ }
445
+ : tree,
446
+ );
447
+ const paths = options.allPaths
448
+ ? selected.paths
449
+ : selected.paths.slice(0, 500);
450
+ return {
451
+ checkedAt: selected.checkedAt || value.checkedAt,
452
+ worktreesCheckedAt: value.checkedAt,
453
+ revision: identifier(JSON.stringify({ worktrees, paths })),
454
+ attribution: "worktree",
455
+ worktrees,
456
+ selected: selected.id,
457
+ paths,
458
+ truncated: selected.changed !== null && selected.changed > paths.length,
459
+ omittedWorktrees: value.omittedWorktrees,
460
+ };
461
+ }
462
+ function parseHunks(patch: string) {
463
+ return patch.split("\n").flatMap((line) => {
464
+ const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
465
+ return m
466
+ ? [
467
+ {
468
+ beforeStart: Number(m[1]),
469
+ beforeCount: Number(m[2] ?? 1),
470
+ afterStart: Number(m[3]),
471
+ afterCount: Number(m[4] ?? 1),
472
+ },
473
+ ]
474
+ : [];
475
+ });
476
+ }
477
+ export async function workingDetail(
478
+ root: string,
479
+ worktree: string,
480
+ file: string,
481
+ ): Promise<WorkingDetail> {
482
+ if (
483
+ !file ||
484
+ file.includes("\0") ||
485
+ file.startsWith("/") ||
486
+ file.split(/[\\/]/).includes("..")
487
+ )
488
+ throw Error("Expected a changed repository path");
489
+ const inventory = await trees(root),
490
+ tree = inventory.entries.find((t) => identifier(t.path) === worktree);
491
+ if (!tree || tree.prunable) throw Error("Unknown or unavailable worktree");
492
+ if (
493
+ (await realpath(
494
+ resolve(
495
+ tree.path,
496
+ (await git(tree.path, ["rev-parse", "--git-common-dir"])).trim(),
497
+ ),
498
+ )) !== inventory.common
499
+ )
500
+ throw Error("Worktree belongs to another repository");
501
+ const paths = parseWorkingStatus(
502
+ await git(tree.path, [
503
+ "status",
504
+ "--porcelain=v2",
505
+ "-z",
506
+ "--untracked-files=normal",
507
+ "--no-renames",
508
+ ]),
509
+ );
510
+ const path = paths.find((p) => p.path === file);
511
+ // An expanded untracked directory may contain this file; Git must confirm membership below.
512
+ const directory = paths.find(
513
+ (p) => p.untracked && p.kind === "directory" && file.startsWith(p.path),
514
+ );
515
+ if (!path && !directory)
516
+ throw Error("This path is no longer changed; refresh the working view");
517
+ if (path?.conflict) {
518
+ const records = (
519
+ await git(tree.path, ["ls-files", "--unmerged", "-z", "--", file])
520
+ )
521
+ .split("\0")
522
+ .filter(Boolean);
523
+ const stages = [
524
+ ...new Set(
525
+ records.map((record) => Number(record.split("\t")[0].split(" ")[2])),
526
+ ),
527
+ ]
528
+ .filter((stage) => [1, 2, 3].includes(stage))
529
+ .sort();
530
+ return {
531
+ path: file,
532
+ untracked: false,
533
+ conflict: { stages },
534
+ truncated: false,
535
+ layers: [],
536
+ };
537
+ }
538
+ if (path?.untracked || directory) {
539
+ const members = (
540
+ await git(tree.path, [
541
+ "ls-files",
542
+ "--others",
543
+ "--exclude-standard",
544
+ "-z",
545
+ "--",
546
+ file,
547
+ ])
548
+ )
549
+ .split("\0")
550
+ .filter(Boolean);
551
+ if (!members.length)
552
+ throw Error("This untracked path is no longer available");
553
+ return {
554
+ path: file,
555
+ untracked: true,
556
+ members: members.slice(0, 500),
557
+ truncated: members.length > 500,
558
+ layers: [],
559
+ };
560
+ }
561
+ const layers = await Promise.all(
562
+ (["staged", "unstaged"] as const).map(async (layer) => {
563
+ const patch = await git(tree.path, [
564
+ "diff",
565
+ ...(layer === "staged" ? ["--cached"] : []),
566
+ "--no-ext-diff",
567
+ "--no-textconv",
568
+ "--no-renames",
569
+ "--no-color",
570
+ "--unified=0",
571
+ "--",
572
+ file,
573
+ ]);
574
+ return {
575
+ layer,
576
+ binary: /^Binary files |^GIT binary patch/m.test(patch),
577
+ hunks: parseHunks(patch),
578
+ };
579
+ }),
580
+ );
581
+ return { path: file, untracked: false, truncated: false, layers };
582
+ }