@buffcore/cli 0.8.46 → 0.8.47

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 (187) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/commands/change-merge-remove.d.ts +9 -2
  3. package/dist/commands/change-merge-remove.js +27 -15
  4. package/dist/commands/design/check.d.ts +1 -1
  5. package/dist/commands/design/check.js +2 -1
  6. package/dist/commands/design/contract-size.d.ts +7 -0
  7. package/dist/commands/design/contract-size.js +47 -0
  8. package/dist/commands/design/tells.en.d.ts +2 -0
  9. package/dist/commands/design/tells.en.js +2 -0
  10. package/dist/commands/design/tells.es.js +2 -0
  11. package/dist/commands/extension/places-approval.d.ts +4 -0
  12. package/dist/commands/process-paths.d.ts +14 -0
  13. package/dist/commands/process-paths.js +90 -0
  14. package/dist/commands/prototype/ai-approval.d.ts +27 -0
  15. package/dist/commands/prototype/ai-approval.js +60 -0
  16. package/dist/commands/prototype/approver.d.ts +71 -0
  17. package/dist/commands/prototype/approver.js +168 -0
  18. package/dist/commands/prototype/critique-gate.d.ts +14 -0
  19. package/dist/commands/prototype/critique-gate.js +48 -0
  20. package/dist/commands/prototype/fence.d.ts +1 -0
  21. package/dist/commands/prototype/fence.js +12 -0
  22. package/dist/commands/prototype/final-approval-grant.js +18 -0
  23. package/dist/commands/prototype/final-approval.js +4 -1
  24. package/dist/commands/prototype/index.js +3 -0
  25. package/dist/commands/prototype/layout-hints.d.ts +34 -0
  26. package/dist/commands/prototype/layout-hints.js +194 -0
  27. package/dist/commands/prototype/layout-measure.d.ts +39 -0
  28. package/dist/commands/prototype/layout-measure.js +97 -0
  29. package/dist/commands/prototype/layout-words.d.ts +2 -0
  30. package/dist/commands/prototype/layout-words.js +11 -0
  31. package/dist/commands/prototype/layout.en.d.ts +6 -0
  32. package/dist/commands/prototype/layout.en.js +7 -0
  33. package/dist/commands/prototype/load-location.js +2 -3
  34. package/dist/commands/prototype/messages.en.d.ts +14 -0
  35. package/dist/commands/prototype/messages.en.js +15 -1
  36. package/dist/commands/prototype/messages.js +15 -1
  37. package/dist/commands/prototype/milestone-versions.d.ts +4 -0
  38. package/dist/commands/prototype/prune-command.d.ts +5 -0
  39. package/dist/commands/prototype/prune-command.js +25 -0
  40. package/dist/commands/prototype/prune-words.d.ts +1 -0
  41. package/dist/commands/prototype/prune-words.js +7 -0
  42. package/dist/commands/prototype/prune.d.ts +16 -0
  43. package/dist/commands/prototype/prune.en.d.ts +9 -0
  44. package/dist/commands/prototype/prune.en.js +9 -0
  45. package/dist/commands/prototype/prune.es.d.ts +2 -0
  46. package/dist/commands/prototype/prune.es.js +9 -0
  47. package/dist/commands/prototype/prune.js +140 -0
  48. package/dist/commands/prototype/reopen-messages.d.ts +9 -0
  49. package/dist/commands/prototype/reopen-messages.js +19 -0
  50. package/dist/commands/prototype/report.d.ts +14 -0
  51. package/dist/commands/prototype/report.js +5 -1
  52. package/dist/commands/prototype/scene-layout.d.ts +17 -0
  53. package/dist/commands/prototype/scene-layout.js +57 -0
  54. package/dist/commands/prototype/scene-ready.js +8 -2
  55. package/dist/commands/prototype/scene.d.ts +15 -2
  56. package/dist/commands/prototype/scene.js +54 -42
  57. package/dist/commands/prototype/selector-answer.d.ts +43 -0
  58. package/dist/commands/prototype/selector-answer.js +73 -0
  59. package/dist/commands/prototype/selector-misses.d.ts +19 -0
  60. package/dist/commands/prototype/selector-misses.js +78 -0
  61. package/dist/commands/prototype/selector-prompt.d.ts +23 -0
  62. package/dist/commands/prototype/selector-prompt.js +32 -0
  63. package/dist/commands/prototype/selector-run.d.ts +13 -0
  64. package/dist/commands/prototype/selector-run.js +113 -0
  65. package/dist/commands/prototype/selector.d.ts +54 -0
  66. package/dist/commands/prototype/selector.js +96 -0
  67. package/dist/commands/prototype/snapshot-ancestor.js +2 -0
  68. package/dist/commands/prototype/snapshot-bundle.d.ts +17 -3
  69. package/dist/commands/prototype/snapshot-bundle.js +69 -7
  70. package/dist/commands/prototype/snapshot-check-files.d.ts +2 -0
  71. package/dist/commands/prototype/snapshot-check-files.js +41 -0
  72. package/dist/commands/prototype/snapshot-command.d.ts +2 -0
  73. package/dist/commands/prototype/snapshot-command.js +3 -0
  74. package/dist/commands/prototype/snapshot-completion.d.ts +4 -0
  75. package/dist/commands/prototype/snapshot-completion.js +30 -2
  76. package/dist/commands/prototype/snapshot-dependencies.d.ts +23 -2
  77. package/dist/commands/prototype/snapshot-dependencies.js +120 -14
  78. package/dist/commands/prototype/snapshot-hashes.d.ts +7 -0
  79. package/dist/commands/prototype/snapshot-hashes.js +28 -0
  80. package/dist/commands/prototype/snapshot-inputs.d.ts +15 -6
  81. package/dist/commands/prototype/snapshot-inputs.js +140 -197
  82. package/dist/commands/prototype/snapshot-matrix.d.ts +58 -0
  83. package/dist/commands/prototype/snapshot-matrix.js +95 -0
  84. package/dist/commands/prototype/snapshot-metro-inputs.d.ts +8 -0
  85. package/dist/commands/prototype/snapshot-metro-inputs.js +81 -0
  86. package/dist/commands/prototype/snapshot-owners.d.ts +6 -2
  87. package/dist/commands/prototype/snapshot-owners.js +12 -3
  88. package/dist/commands/prototype/snapshot-progress-entry.d.ts +14 -0
  89. package/dist/commands/prototype/snapshot-progress-entry.js +85 -0
  90. package/dist/commands/prototype/snapshot-progress.d.ts +19 -2
  91. package/dist/commands/prototype/snapshot-progress.js +54 -102
  92. package/dist/commands/prototype/snapshot-registry.d.ts +14 -0
  93. package/dist/commands/prototype/snapshot-registry.js +121 -0
  94. package/dist/commands/prototype/snapshot-report.d.ts +4 -0
  95. package/dist/commands/prototype/snapshot-report.js +77 -12
  96. package/dist/commands/prototype/snapshot-requests.d.ts +13 -3
  97. package/dist/commands/prototype/snapshot-requests.js +68 -30
  98. package/dist/commands/prototype/snapshot-reuse.d.ts +6 -1
  99. package/dist/commands/prototype/snapshot-reuse.js +17 -7
  100. package/dist/commands/prototype/snapshot-scene-inputs.d.ts +30 -0
  101. package/dist/commands/prototype/snapshot-scene-inputs.js +210 -0
  102. package/dist/commands/prototype/snapshot-served-inputs.d.ts +3 -0
  103. package/dist/commands/prototype/snapshot-served-inputs.js +12 -0
  104. package/dist/commands/prototype/snapshot-server-record.d.ts +26 -0
  105. package/dist/commands/prototype/snapshot-server-record.js +135 -0
  106. package/dist/commands/prototype/snapshot-servers.d.ts +3 -1
  107. package/dist/commands/prototype/snapshot-servers.js +50 -2
  108. package/dist/commands/prototype/snapshot-setup.d.ts +3 -1
  109. package/dist/commands/prototype/snapshot-setup.js +2 -1
  110. package/dist/commands/prototype/snapshot-surface-inputs.d.ts +23 -0
  111. package/dist/commands/prototype/snapshot-surface-inputs.js +161 -0
  112. package/dist/commands/prototype/snapshot-vite-inputs.d.ts +22 -0
  113. package/dist/commands/prototype/snapshot-vite-inputs.js +209 -0
  114. package/dist/commands/prototype/snapshot.d.ts +5 -0
  115. package/dist/commands/prototype/snapshot.js +72 -10
  116. package/dist/commands/prototype/version-commands.d.ts +4 -0
  117. package/dist/commands/prototype/version-commands.js +36 -8
  118. package/dist/commands/prototype/versions.d.ts +28 -2
  119. package/dist/commands/prototype/versions.js +25 -1
  120. package/dist/commands/prototype/vite-fs-path.d.ts +4 -0
  121. package/dist/commands/prototype/vite-fs-path.js +15 -0
  122. package/dist/commands/remove-links.d.ts +6 -0
  123. package/dist/commands/remove-links.js +17 -0
  124. package/dist/commands/size-docs.d.ts +9 -0
  125. package/dist/commands/size-docs.en.d.ts +6 -0
  126. package/dist/commands/size-docs.en.js +6 -0
  127. package/dist/commands/size-docs.es.d.ts +2 -0
  128. package/dist/commands/size-docs.es.js +6 -0
  129. package/dist/commands/size-docs.js +28 -0
  130. package/dist/commands/size.d.ts +5 -2
  131. package/dist/commands/size.js +27 -9
  132. package/dist/commands/ui/approval-authority.d.ts +10 -2
  133. package/dist/commands/ui/approval-authority.js +1 -0
  134. package/dist/commands/ui/autopilot-ai-approve.d.ts +18 -0
  135. package/dist/commands/ui/autopilot-ai-approve.js +68 -0
  136. package/dist/commands/ui/autopilot-loop.js +5 -6
  137. package/dist/commands/ui/autopilot-merge.js +3 -0
  138. package/dist/commands/ui/autopilot.en.d.ts +23 -0
  139. package/dist/commands/ui/autopilot.en.js +23 -0
  140. package/dist/commands/ui/autopilot.es.d.ts +23 -0
  141. package/dist/commands/ui/autopilot.es.js +23 -0
  142. package/dist/commands/ui/chat/find.d.ts +2 -0
  143. package/dist/commands/ui/chat/find.js +13 -0
  144. package/dist/commands/ui/chat/fresh-codex.d.ts +39 -0
  145. package/dist/commands/ui/chat/fresh-codex.js +175 -0
  146. package/dist/commands/ui/chat/fresh-critique.js +13 -5
  147. package/dist/commands/ui/chat/fresh-launch.d.ts +19 -0
  148. package/dist/commands/ui/chat/fresh-launch.js +67 -11
  149. package/dist/commands/ui/chat/fresh-prompts.d.ts +2 -0
  150. package/dist/commands/ui/chat/fresh-prompts.js +2 -0
  151. package/dist/commands/ui/chat/fresh-secrets.d.ts +6 -0
  152. package/dist/commands/ui/chat/fresh-secrets.js +172 -0
  153. package/dist/commands/ui/chat/fresh.en.d.ts +1 -0
  154. package/dist/commands/ui/chat/fresh.en.js +2 -1
  155. package/dist/commands/ui/chat/fresh.es.d.ts +1 -0
  156. package/dist/commands/ui/chat/fresh.es.js +2 -1
  157. package/dist/commands/ui/chat/worktree.js +25 -5
  158. package/dist/commands/ui/index.js +3 -0
  159. package/dist/commands/ui/loop-approve.d.ts +30 -1
  160. package/dist/commands/ui/loop-approve.js +2 -2
  161. package/dist/commands/ui/merge-route.js +3 -0
  162. package/dist/commands/ui/places-change.d.ts +4 -0
  163. package/dist/commands/ui/prototype-main.d.ts +4 -0
  164. package/dist/commands/ui/reopen-route.d.ts +117 -0
  165. package/dist/commands/ui/reopen-route.js +97 -0
  166. package/dist/commands/ui/save-route.d.ts +2 -0
  167. package/dist/commands/ui/save-route.js +4 -0
  168. package/dist/commands/ui/studio-routes.js +2 -0
  169. package/dist/commands/ui/studio-state.d.ts +33 -0
  170. package/dist/commands/ui/studio-versions.d.ts +24 -0
  171. package/dist/commands/ui/worktrees.d.ts +1 -1
  172. package/dist/commands/ui/worktrees.js +19 -3
  173. package/dist/commands/worktree-sweep.d.ts +45 -0
  174. package/dist/commands/worktree-sweep.js +188 -0
  175. package/dist/commands/worktrees-command.d.ts +32 -0
  176. package/dist/commands/worktrees-command.en.d.ts +25 -0
  177. package/dist/commands/worktrees-command.en.js +55 -0
  178. package/dist/commands/worktrees-command.js +96 -0
  179. package/dist/main.js +2 -0
  180. package/dist/ui/page.js +82 -82
  181. package/docs/PROTOTYPE.md +6 -3
  182. package/docs/WORKBENCH.md +11 -6
  183. package/package.json +11 -11
  184. package/skills/ape-critique/SKILL.md +41 -6
  185. package/skills/ape-design-system/SKILL.md +3 -0
  186. package/skills/ape-plan-change/SKILL.md +6 -0
  187. package/skills/ape-prototype/SKILL.md +8 -4
@@ -0,0 +1,188 @@
1
+ // Which linked worktrees can go, and removing them. A worktree goes only when its branch is merged
2
+ // into main, nothing in it is uncommitted, and no studio turn or process holds its path; any doubt
3
+ // keeps it. Branches are never deleted. `ape worktrees` and the studio's sweep share this.
4
+ import { realpathSync } from 'node:fs';
5
+ import { isAbsolute, relative, resolve } from 'node:path';
6
+ import { defaultMergeTools, dirty } from './change-merge.js';
7
+ import { removeCheckout, removeWorktree } from './change-merge-remove.js';
8
+ import { mainCommit } from './main-ref.js';
9
+ import { pathsHeld, processPlaces } from './process-paths.js';
10
+ import { treeBusy } from './ui/chat/orphans.js';
11
+ import { ChatStore } from './ui/chat/store.js';
12
+ import { workingTree } from './ui/chat/worktree.js';
13
+ import { mergedBranches } from './ui/merged-branches.js';
14
+ /** Every linked worktree (`git worktree list --porcelain -z`), without the main working tree. */
15
+ export function linkedTrees(porcelain) {
16
+ const records = porcelain.split('\0\0').map((record) => record.split('\0').filter(Boolean));
17
+ return records.slice(1).flatMap((fields) => {
18
+ const path = fields.find((line) => line.startsWith('worktree '))?.slice(9);
19
+ if (!path || fields.includes('bare'))
20
+ return [];
21
+ const branch = fields.find((line) => line.startsWith('branch refs/heads/'))?.slice(18);
22
+ const head = fields.find((line) => line.startsWith('HEAD '))?.slice(5);
23
+ const change = branch && /^change\/(C-\d{3,})-[a-z0-9][a-z0-9-]*$/.exec(branch)?.[1];
24
+ return [
25
+ {
26
+ path,
27
+ ...(branch ? { branch } : {}),
28
+ ...(head ? { head } : {}),
29
+ ...(change ? { change } : {}),
30
+ ...(fields.some((line) => line === 'locked' || line.startsWith('locked '))
31
+ ? { locked: true }
32
+ : {}),
33
+ ...(fields.some((line) => line === 'prunable' || line.startsWith('prunable '))
34
+ ? { prunable: true }
35
+ : {}),
36
+ },
37
+ ];
38
+ });
39
+ }
40
+ const samePath = (a, b) => {
41
+ const norm = (path) => {
42
+ const plain = resolve(path).replaceAll('\\', '/');
43
+ return process.platform === 'win32' ? plain.toLowerCase() : plain;
44
+ };
45
+ return norm(a) === norm(b);
46
+ };
47
+ const isInside = (child, folder) => {
48
+ const rel = relative(resolve(folder), resolve(child));
49
+ return Boolean(rel) && !rel.startsWith('..') && !isAbsolute(rel);
50
+ };
51
+ /** A studio chat whose turn is running, or recorded as still holding the tree. */
52
+ async function studioHolds(store, root, path) {
53
+ for (const chat of store.all()) {
54
+ const tree = workingTree(root, chat);
55
+ if (!samePath(tree, path))
56
+ continue;
57
+ if (chat.state === 'running' || (await treeBusy(store, root, tree)))
58
+ return true;
59
+ }
60
+ return false;
61
+ }
62
+ /** The folders of `paths` a studio turn holds. */
63
+ export async function studioHeld(root, paths) {
64
+ const store = new ChatStore(root);
65
+ const held = new Set();
66
+ for (const path of paths)
67
+ if (await studioHolds(store, root, path))
68
+ held.add(path);
69
+ return held;
70
+ }
71
+ /** The studio's turns, then every process's command line and (where readable) working folder. */
72
+ export const defaultHolders = async (root, paths) => {
73
+ const held = await studioHeld(root, paths);
74
+ for (const path of pathsHeld(paths, await processPlaces()))
75
+ held.add(path);
76
+ // This process's own folder too: a worktree cannot be removed from inside it.
77
+ for (const path of paths)
78
+ if (samePath(path, process.cwd()) || isInside(process.cwd(), path))
79
+ held.add(path);
80
+ return held;
81
+ };
82
+ async function gitFolder(root, git) {
83
+ const common = await git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
84
+ return resolve(common.trim()).replaceAll('\\', '/').toLowerCase();
85
+ }
86
+ /** Each linked worktree's state, read only. Never throws; what cannot be read is `unknown`. */
87
+ export async function treeFacts(root, { git = defaultMergeTools.git, holders = defaultHolders } = {}) {
88
+ let trees;
89
+ try {
90
+ trees = linkedTrees(await git(root, ['worktree', 'list', '--porcelain', '-z']));
91
+ }
92
+ catch {
93
+ return [];
94
+ }
95
+ const [merged, inside] = await Promise.all([
96
+ mainCommit(root, git)
97
+ .then((main) => mergedBranches(main, (args) => git(root, args)))
98
+ .catch(() => undefined),
99
+ gitFolder(root, git).catch(() => undefined),
100
+ ]);
101
+ const facts = [];
102
+ for (const tree of trees)
103
+ facts.push({ ...tree, state: await stateOf(tree, git, merged, inside) });
104
+ const free = facts.filter((fact) => fact.state === 'merged').map((fact) => fact.path);
105
+ if (!free.length)
106
+ return facts;
107
+ const held = await holders(root, free).catch(() => new Set(free));
108
+ return facts.map((fact) => (held.has(fact.path) ? { ...fact, state: 'inUse' } : fact));
109
+ }
110
+ async function stateOf(tree, git, merged, gitDir) {
111
+ if (tree.prunable || !merged || !gitDir)
112
+ return 'unknown';
113
+ // A locked worktree, or a merge's own temporary checkout inside `.git`, is somebody's.
114
+ const where = resolve(tree.path).replaceAll('\\', '/').toLowerCase();
115
+ if (tree.locked || where.startsWith(`${gitDir}/`))
116
+ return 'inUse';
117
+ try {
118
+ if (await dirty(tree.path, git))
119
+ return 'dirty';
120
+ }
121
+ catch {
122
+ return 'unknown';
123
+ }
124
+ // Only a tip brought into main by a merge counts: a new branch still at main's tip is not merged.
125
+ return tree.branch && tree.head && merged.get(tree.branch) === tree.head ? 'merged' : 'unmerged';
126
+ }
127
+ const removalState = (reason) => reason === 'dirty' || reason === 'unmerged' ? reason : reason === 'busy' ? 'inUse' : 'unknown';
128
+ /** Remove each `merged` fact's worktree with the safe removal; the rest are returned unchanged. */
129
+ export async function removeMerged(root, facts, tools = defaultMergeTools) {
130
+ const out = [];
131
+ for (const fact of facts) {
132
+ if (fact.state !== 'merged') {
133
+ out.push(fact);
134
+ continue;
135
+ }
136
+ // A change's worktree goes under the merge lock, so no merge reads it meanwhile.
137
+ const result = fact.change
138
+ ? await removeWorktree(root, fact.change, { ...defaultMergeTools, ...tools })
139
+ : await removeCheckout(root, fact.path, tools).catch(() => ({ ok: false, reason: 'held' }));
140
+ out.push({ ...fact, state: result.ok ? 'removed' : removalState(result.reason) });
141
+ }
142
+ return out;
143
+ }
144
+ /** True when `path` is in `<root>/.ape/worktrees/`, by its real path. */
145
+ function studioTree(root, path) {
146
+ try {
147
+ const real = realpathSync.native(path);
148
+ return samePath(resolve(real, '..'), resolve(realpathSync.native(root), '.ape', 'worktrees'));
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ }
154
+ const kept = new Map();
155
+ const sweeping = new Map();
156
+ /** The last sweep's reason for keeping a merged worktree (in use, or its removal failed). */
157
+ export const keptAfterSweep = (root, path) => kept.get(resolve(root))?.get(path);
158
+ /**
159
+ * The studio's sweep of its own change worktrees (`.ape/worktrees/<change>`): each merged, clean,
160
+ * unused one is removed; the rest stay, and why is kept for the Work page. One at a time per root.
161
+ */
162
+ export function sweepStudio(root, holders = defaultHolders) {
163
+ const key = resolve(root);
164
+ const running = sweeping.get(key);
165
+ if (running)
166
+ return running;
167
+ const sweep = (async () => {
168
+ const facts = (await treeFacts(root, { holders })).filter((fact) => fact.change && studioTree(root, fact.path));
169
+ const after = await removeMerged(root, facts);
170
+ kept.set(key, new Map(after.flatMap((f) => f.state === 'removed' || f.state === 'merged' ? [] : [[f.path, f.state]])));
171
+ return after;
172
+ })()
173
+ .catch(() => [])
174
+ .finally(() => sweeping.delete(key));
175
+ sweeping.set(key, sweep);
176
+ return sweep;
177
+ }
178
+ const studios = new Set();
179
+ /** A running studio sweeps when it starts and after each merge (`sweepAfterMerge`). */
180
+ export function startSweeps(root) {
181
+ studios.add(resolve(root));
182
+ void sweepStudio(root);
183
+ }
184
+ /** After a merge went through: sweep, when this process runs the studio for `root`. */
185
+ export function sweepAfterMerge(root) {
186
+ if (studios.has(resolve(root)))
187
+ void sweepStudio(root);
188
+ }
@@ -0,0 +1,32 @@
1
+ import type { Command } from 'commander';
2
+ import { type Holders, type TreeFact } from './worktree-sweep.ts';
3
+ export interface WorktreesOptions {
4
+ json?: boolean;
5
+ size?: boolean;
6
+ }
7
+ export interface WorktreeLine {
8
+ path: string;
9
+ branch: string | null;
10
+ change: string | null;
11
+ state: TreeFact['state'];
12
+ /** Bytes on disk, with `--size`: links are counted as themselves and never followed. */
13
+ bytes?: number | null;
14
+ }
15
+ export interface WorktreesAnswer {
16
+ ok: boolean;
17
+ worktrees: WorktreeLine[];
18
+ error?: string;
19
+ }
20
+ /** Exit codes: 0 done (kept worktrees are not a failure), 1 a removal failed, 2 nothing could be read. */
21
+ declare const exitOf: (answer: WorktreesAnswer, cleaning: boolean) => 0 | 1 | 2;
22
+ /** Read (and with `clean`, remove) the worktrees of the repository at `root`. */
23
+ export declare function worktreesAnswer(root: string, { clean, size, holders }: {
24
+ clean?: boolean;
25
+ size?: boolean;
26
+ holders?: Holders;
27
+ }): Promise<WorktreesAnswer>;
28
+ /** The text a person reads. */
29
+ export declare function worktreesText(answer: WorktreesAnswer, cleaning: boolean): string;
30
+ /** `ape worktrees` and `ape worktrees clean` on the CLI's program. */
31
+ export declare function addWorktreesCommand(program: Command): void;
32
+ export { exitOf as worktreesExit };
@@ -0,0 +1,25 @@
1
+ import { mergeLocale } from './change-merge.en.ts';
2
+ export declare const en: {
3
+ 'worktrees.help': string;
4
+ 'worktrees.cleanHelp': string;
5
+ 'worktrees.json': string;
6
+ 'worktrees.size': string;
7
+ 'worktrees.none': string;
8
+ 'worktrees.count': string;
9
+ 'worktrees.unreadable': string;
10
+ 'worktrees.detached': string;
11
+ 'worktrees.state.merged': string;
12
+ 'worktrees.state.removed': string;
13
+ 'worktrees.state.unmerged': string;
14
+ 'worktrees.state.dirty': string;
15
+ 'worktrees.state.inUse': string;
16
+ 'worktrees.state.unknown': string;
17
+ 'worktrees.cleaned': string;
18
+ 'worktrees.kept': string;
19
+ 'worktrees.why.unmerged': string;
20
+ 'worktrees.why.dirty': string;
21
+ 'worktrees.why.inUse': string;
22
+ 'worktrees.why.unknown': string;
23
+ };
24
+ export declare const t: (key: keyof typeof en, values?: Record<string, unknown>) => string;
25
+ export declare const worktreesLocale: typeof mergeLocale;
@@ -0,0 +1,55 @@
1
+ import { createI18n } from '@buffcore/i18n';
2
+ import { mergeLocale } from './change-merge.en.js';
3
+ export const en = {
4
+ 'worktrees.help': "List this repository's worktrees and whether each can be removed",
5
+ 'worktrees.cleanHelp': 'Remove the worktrees that are merged into main, clean and unused; keep the rest and say why',
6
+ 'worktrees.json': 'as JSON, for tools and agents',
7
+ 'worktrees.size': 'add each worktree’s size on disk',
8
+ 'worktrees.none': 'No worktrees besides this checkout.',
9
+ 'worktrees.count': '{count, plural, one {# worktree} other {# worktrees}}',
10
+ 'worktrees.unreadable': 'The worktrees could not be read here. Run this inside a git checkout.',
11
+ 'worktrees.detached': '(no branch)',
12
+ 'worktrees.state.merged': 'merged and clean',
13
+ 'worktrees.state.removed': 'removed',
14
+ 'worktrees.state.unmerged': 'not merged',
15
+ 'worktrees.state.dirty': 'uncommitted work',
16
+ 'worktrees.state.inUse': 'in use',
17
+ 'worktrees.state.unknown': 'could not tell',
18
+ 'worktrees.cleaned': 'Removed {removed, plural, one {# worktree} other {# worktrees}}; kept {kept}. Branches stay.',
19
+ 'worktrees.kept': 'Kept {path}: {why}',
20
+ 'worktrees.why.unmerged': 'its branch is not merged into main.',
21
+ 'worktrees.why.dirty': 'it has uncommitted work.',
22
+ 'worktrees.why.inUse': 'a studio turn or a program is using it.',
23
+ 'worktrees.why.unknown': 'its state could not be read or it could not be removed safely.',
24
+ };
25
+ const messages = createI18n({
26
+ catalogs: [
27
+ {
28
+ en,
29
+ es: {
30
+ 'worktrees.help': 'Listar los árboles de trabajo del repositorio y si cada uno se puede quitar',
31
+ 'worktrees.cleanHelp': 'Quitar los árboles unidos a main, limpios y sin uso; conservar el resto y decir por qué',
32
+ 'worktrees.json': 'en JSON, para herramientas y agentes',
33
+ 'worktrees.size': 'añadir lo que ocupa cada árbol en disco',
34
+ 'worktrees.none': 'No hay árboles de trabajo además de este.',
35
+ 'worktrees.count': '{count, plural, one {# árbol de trabajo} other {# árboles de trabajo}}',
36
+ 'worktrees.unreadable': 'No se pudieron leer los árboles de trabajo aquí. Ejecútalo dentro de un repositorio git.',
37
+ 'worktrees.detached': '(sin rama)',
38
+ 'worktrees.state.merged': 'unido y limpio',
39
+ 'worktrees.state.removed': 'quitado',
40
+ 'worktrees.state.unmerged': 'sin unir',
41
+ 'worktrees.state.dirty': 'trabajo sin confirmar',
42
+ 'worktrees.state.inUse': 'en uso',
43
+ 'worktrees.state.unknown': 'no se sabe',
44
+ 'worktrees.cleaned': '{removed, plural, one {Se quitó # árbol} other {Se quitaron # árboles}}; se conservan {kept}. Las ramas se quedan.',
45
+ 'worktrees.kept': 'Se conserva {path}: {why}',
46
+ 'worktrees.why.unmerged': 'su rama no está unida a main.',
47
+ 'worktrees.why.dirty': 'tiene trabajo sin confirmar.',
48
+ 'worktrees.why.inUse': 'un turno del estudio o un programa lo está usando.',
49
+ 'worktrees.why.unknown': 'no se pudo leer su estado o no se pudo quitar con seguridad.',
50
+ },
51
+ },
52
+ ],
53
+ });
54
+ export const t = (key, values) => messages.t(mergeLocale(), key, values);
55
+ export const worktreesLocale = mergeLocale;
@@ -0,0 +1,96 @@
1
+ // `ape worktrees [clean] [--size] [--json]`: every linked worktree of this repository (the
2
+ // studio's and any other) and whether it can go; `clean` removes the merged, clean, unused ones.
3
+ import { lstat, readdir } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { findRoot } from '../project.js';
6
+ import { defaultMergeTools } from './change-merge.js';
7
+ import { removeMerged, treeFacts } from './worktree-sweep.js';
8
+ import { t, worktreesLocale } from './worktrees-command.en.js';
9
+ /** Exit codes: 0 done (kept worktrees are not a failure), 1 a removal failed, 2 nothing could be read. */
10
+ const exitOf = (answer, cleaning) => !answer.ok ? 2 : cleaning && answer.worktrees.some((w) => w.state === 'unknown') ? 1 : 0;
11
+ async function folderBytes(path) {
12
+ let total = 0;
13
+ for (const entry of await readdir(path, { withFileTypes: true })) {
14
+ const inner = join(path, entry.name);
15
+ if (entry.isDirectory())
16
+ total += await folderBytes(inner);
17
+ else
18
+ total += (await lstat(inner)).size;
19
+ }
20
+ return total;
21
+ }
22
+ const line = async (fact, size) => ({
23
+ path: fact.path,
24
+ branch: fact.branch ?? null,
25
+ change: fact.change ?? null,
26
+ state: fact.state,
27
+ ...(size && fact.state !== 'removed'
28
+ ? { bytes: await folderBytes(fact.path).catch(() => null) }
29
+ : {}),
30
+ });
31
+ /** Read (and with `clean`, remove) the worktrees of the repository at `root`. */
32
+ export async function worktreesAnswer(root, { clean = false, size = false, holders }) {
33
+ const facts = await treeFacts(root, holders ? { holders } : {});
34
+ // treeFacts answers [] when git cannot list the worktrees: tell that apart from "none".
35
+ if (!facts.length && !(await listable(root)))
36
+ return { ok: false, worktrees: [], error: t('worktrees.unreadable') };
37
+ const after = clean ? await removeMerged(root, facts) : facts;
38
+ return { ok: true, worktrees: await Promise.all(after.map((fact) => line(fact, size))) };
39
+ }
40
+ const listable = (root) => defaultMergeTools.git(root, ['worktree', 'list', '--porcelain', '-z']).then(() => true, () => false);
41
+ const megabytes = (bytes) => new Intl.NumberFormat(worktreesLocale(), {
42
+ style: 'unit',
43
+ unit: 'megabyte',
44
+ maximumFractionDigits: 0,
45
+ }).format(bytes / 1_000_000);
46
+ /** The text a person reads. */
47
+ export function worktreesText(answer, cleaning) {
48
+ if (!answer.ok)
49
+ return answer.error ?? t('worktrees.unreadable');
50
+ if (!answer.worktrees.length)
51
+ return t('worktrees.none');
52
+ const rows = answer.worktrees.map((w) => [
53
+ t(`worktrees.state.${w.state}`).padEnd(18),
54
+ (w.branch ?? t('worktrees.detached')).padEnd(28),
55
+ w.path,
56
+ typeof w.bytes === 'number' ? ` ${megabytes(w.bytes)}` : '',
57
+ ].join(' '));
58
+ const lines = [t('worktrees.count', { count: answer.worktrees.length }), ...rows];
59
+ if (!cleaning)
60
+ return lines.join('\n');
61
+ const kept = answer.worktrees.filter((w) => w.state !== 'removed');
62
+ const removed = answer.worktrees.length - kept.length;
63
+ lines.push('', t('worktrees.cleaned', { removed, kept: t('worktrees.count', { count: kept.length }) }), ...kept.map((w) => t('worktrees.kept', {
64
+ path: w.path,
65
+ why: t(`worktrees.why.${w.state === 'merged' ? 'unknown' : w.state}`),
66
+ })));
67
+ return lines.join('\n');
68
+ }
69
+ async function run(clean, options) {
70
+ let root;
71
+ try {
72
+ root = findRoot();
73
+ }
74
+ catch {
75
+ root = process.cwd();
76
+ }
77
+ const answer = await worktreesAnswer(root, { clean, size: Boolean(options.size) });
78
+ process.exitCode = exitOf(answer, clean);
79
+ process.stdout.write(options.json ? `${JSON.stringify(answer, null, 2)}\n` : `${worktreesText(answer, clean)}\n`);
80
+ }
81
+ /** `ape worktrees` and `ape worktrees clean` on the CLI's program. */
82
+ export function addWorktreesCommand(program) {
83
+ const worktrees = program
84
+ .command('worktrees')
85
+ .description(t('worktrees.help'))
86
+ .option('--size', t('worktrees.size'))
87
+ .option('--json', t('worktrees.json'))
88
+ .action((options) => run(false, options));
89
+ worktrees
90
+ .command('clean')
91
+ .description(t('worktrees.cleanHelp'))
92
+ .option('--size', t('worktrees.size'))
93
+ .option('--json', t('worktrees.json'))
94
+ .action((options) => run(true, options));
95
+ }
96
+ export { exitOf as worktreesExit };
package/dist/main.js CHANGED
@@ -42,6 +42,7 @@ import { addUiCommand } from './commands/ui/index.js';
42
42
  import { upgrade, upgradeT } from './commands/upgrade.js';
43
43
  import { addUploadsCommand } from './commands/uploads-orphans.js';
44
44
  import { addWhoCommand } from './commands/who.js';
45
+ import { addWorktreesCommand } from './commands/worktrees-command.js';
45
46
  import { BUFFCORE_RELEASE } from './version.js';
46
47
  const program = new Command('ape')
47
48
  .description('Build and run a product on BuffCore.')
@@ -148,6 +149,7 @@ addCatalogCommands(program);
148
149
  addServicesCommand(program);
149
150
  addAgentsCommand(program);
150
151
  addTurnCommand(program);
152
+ addWorktreesCommand(program);
151
153
  const lang = program.command('i18n').description('Translations');
152
154
  lang
153
155
  .command('check')