@north-light/crouter 0.3.303 → 0.3.304
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.
- package/dist/api/__tests__/integration/client.test.js +37 -36
- package/dist/api/client.d.ts +32 -55
- package/dist/api/client.js +102 -98
- package/dist/api/dto/messages.d.ts +6 -5
- package/dist/api/errors.d.ts +3 -0
- package/dist/api/errors.js +10 -0
- package/dist/api/index.d.ts +1 -1
- package/dist/api/index.js +1 -1
- package/dist/builtin-memory/internal/plugins.md +1 -1
- package/dist/clients/attach/viewer.js +532 -532
- package/dist/commands/__tests__/seam/daemon-status.test.d.ts +1 -0
- package/dist/commands/__tests__/seam/daemon-status.test.js +29 -0
- package/dist/commands/api-client.d.ts +3 -3
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/memory/read.js +2 -1
- package/dist/commands/node/bash.js +6 -6
- package/dist/commands/node/message.js +3 -3
- package/dist/commands/sys/daemon.js +11 -13
- package/dist/core/__tests__/broker-stream-watchdog-floor.test.js +0 -2
- package/dist/core/__tests__/daemon-boot.test.js +1 -1
- package/dist/core/__tests__/helpers/harness.d.ts +2 -0
- package/dist/core/__tests__/helpers/harness.js +9 -0
- package/dist/core/__tests__/integration/worktree-land.test.js +50 -0
- package/dist/core/__tests__/integration/worktree-reap.test.js +184 -5
- package/dist/core/__tests__/parse-argv-stdin-secret.test.js +14 -0
- package/dist/core/__tests__/seam/broker-attach-stream.test.js +13 -0
- package/dist/core/__tests__/seam/broker-startup-diagnostics.test.d.ts +1 -0
- package/dist/core/__tests__/seam/broker-startup-diagnostics.test.js +82 -0
- package/dist/core/bash-jobs.d.ts +20 -8
- package/dist/core/bash-jobs.js +40 -21
- package/dist/core/canvas/types.d.ts +4 -2
- package/dist/core/command.js +1 -1
- package/dist/core/fault-classifier.d.ts +1 -1
- package/dist/core/runtime/broker/event-projection.d.ts +0 -3
- package/dist/core/runtime/broker/event-projection.js +2 -15
- package/dist/core/runtime/broker/fault-retry.js +8 -0
- package/dist/core/runtime/broker-persona-guidance.js +12 -0
- package/dist/core/runtime/broker.js +0 -5
- package/dist/core/runtime/fault.js +1 -1
- package/dist/core/runtime/host.js +10 -1
- package/dist/core/runtime/spawn.js +5 -6
- package/dist/core/worktree-close.d.ts +4 -0
- package/dist/core/worktree-close.js +225 -0
- package/dist/core/worktree-containment.d.ts +14 -0
- package/dist/core/worktree-containment.js +48 -0
- package/dist/core/worktree-mutation-async.d.ts +13 -0
- package/dist/core/worktree-mutation-async.js +281 -0
- package/dist/core/worktree-sweep.js +17 -79
- package/dist/core/worktree.d.ts +1 -0
- package/dist/core/worktree.js +1 -1
- package/dist/daemon/__tests__/integration/api-startup-readiness.test.js +10 -8
- package/dist/daemon/api/__tests__/seam/api-server.test.js +70 -1
- package/dist/daemon/api/handlers/bash-jobs.js +1 -1
- package/dist/daemon/api/handlers/messages.js +7 -5
- package/dist/daemon/api/handlers/reports.js +3 -2
- package/dist/daemon/api/handlers/worktree.js +7 -6
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +30 -12
- package/dist/daemon/manage.d.ts +8 -5
- package/dist/daemon/manage.js +63 -40
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +12 -0
- package/dist/daemon/reconcilers/node-lifecycle/tick.d.ts +0 -6
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -13
- package/dist/daemon/reconcilers/node-lifecycle/wants-execution.d.ts +5 -0
- package/dist/daemon/reconcilers/node-lifecycle/wants-execution.js +11 -0
- package/dist/pi-extensions/__tests__/canvas-context-intro.test.js +83 -0
- package/dist/pi-extensions/__tests__/integration/canvas-bash-valve.test.d.ts +1 -0
- package/dist/pi-extensions/__tests__/integration/canvas-bash-valve.test.js +133 -0
- package/dist/pi-extensions/canvas-bash-valve.d.ts +2 -0
- package/dist/pi-extensions/canvas-bash-valve.js +73 -43
- package/dist/pi-extensions/canvas-inbox-watcher.js +0 -2
- package/package.json +1 -1
- package/runtime.lock.json +5 -5
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { getNode, updateNode } from './canvas/index.js';
|
|
4
|
+
import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
|
|
5
|
+
import { gitAsync } from './git.js';
|
|
6
|
+
import { proveBranchContained } from './worktree-containment.js';
|
|
7
|
+
import { concludeAbsentManagedWorktreeAsync } from './worktree-mutation-async.js';
|
|
8
|
+
import { parseStatusPorcelain, planLandIntoCheckout } from './worktree-landing.js';
|
|
9
|
+
import { WORKTREE_LOCK_WAIT_MS, checkoutPathForBranchInList, missingWorktreeRecoveryHint, persistClosedWorktreeState, samePath, worktreeLockPathForCommonDir, WorktreeError } from './worktree.js';
|
|
10
|
+
import { shellQuote } from '../shared/shell-quote.js';
|
|
11
|
+
function detailOf(result) {
|
|
12
|
+
return (result.stderr.trim() || result.stdout.trim()).trim();
|
|
13
|
+
}
|
|
14
|
+
async function runGit(cwd, args, code, next) {
|
|
15
|
+
const result = await gitAsync(args, cwd);
|
|
16
|
+
if (result.status !== 0)
|
|
17
|
+
throw new WorktreeError(code, `git ${args.join(' ')} failed`, next, detailOf(result));
|
|
18
|
+
return result.stdout.trim();
|
|
19
|
+
}
|
|
20
|
+
async function commonGitDir(cwd) {
|
|
21
|
+
const output = await runGit(cwd, ['rev-parse', '--git-common-dir'], 'git_common_dir_failed', 'Inspect the repository git metadata, then retry.');
|
|
22
|
+
return realpathSync(resolve(cwd, output));
|
|
23
|
+
}
|
|
24
|
+
async function resolveLandableBase(cwd, baseRef) {
|
|
25
|
+
const ref = `refs/heads/${baseRef}`;
|
|
26
|
+
const exists = await gitAsync(['show-ref', '--verify', '--quiet', ref], cwd);
|
|
27
|
+
if (exists.status === 1 && exists.executionFailed !== true) {
|
|
28
|
+
throw new WorktreeError('missing_base_branch', `managed worktree base '${baseRef}' does not name an existing local branch`, 'The base must be a local branch that landing can fast-forward — freshen your local branch from origin first (rebase-not-merge), then base on it.');
|
|
29
|
+
}
|
|
30
|
+
if (exists.status !== 0) {
|
|
31
|
+
const execution = exists.processError === undefined ? '' : `\nprocess error: ${exists.processError}`;
|
|
32
|
+
throw new WorktreeError('base_branch_inspection_failed', `could not inspect local base branch '${baseRef}' (git show-ref exited with status ${exists.status})`, 'Inspect the repository and its Git metadata, then retry.', `status: ${exists.status}\nstderr: ${exists.stderr.trim() || '<empty>'}${execution}`);
|
|
33
|
+
}
|
|
34
|
+
return runGit(cwd, ['rev-parse', '--verify', ref], 'base_branch_resolve_failed', 'Inspect the local base branch, then retry.');
|
|
35
|
+
}
|
|
36
|
+
async function rebaseInProgress(cwd) {
|
|
37
|
+
for (const path of ['rebase-merge', 'rebase-apply']) {
|
|
38
|
+
const gitPath = await runGit(cwd, ['rev-parse', '--git-path', path], 'git_path_failed', 'Inspect the worktree manually, then retry.');
|
|
39
|
+
if (existsSync(gitPath))
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
async function registeredWorktree(cwd, path, branch) {
|
|
45
|
+
const list = await gitAsync(['worktree', 'list', '--porcelain'], cwd);
|
|
46
|
+
if (list.status !== 0)
|
|
47
|
+
return false;
|
|
48
|
+
let current = null;
|
|
49
|
+
for (const line of list.stdout.split('\n')) {
|
|
50
|
+
if (line.startsWith('worktree '))
|
|
51
|
+
current = line.slice('worktree '.length).trim();
|
|
52
|
+
else if (current !== null && samePath(current, path) && line === `branch refs/heads/${branch}`)
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
function deferredCleanupResult(wt) {
|
|
58
|
+
return {
|
|
59
|
+
worktree_removed: false,
|
|
60
|
+
worktree_remove_error: `cleanup pending: the caller checkout at ${wt.path} remains intact. After its node exits, run \`git -C ${shellQuote(wt.repo_root)} worktree remove ${shellQuote(wt.path)}\` after confirming it is safe to delete.`,
|
|
61
|
+
branch_deleted: false,
|
|
62
|
+
branch_delete_error: `cleanup pending: local branch ${wt.branch} remains checked out at ${wt.path}; delete it only after that checkout is removed and its landed commit is still contained in ${wt.base_ref}.`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function recordBlockedLandIntent(nodeId, blocked) {
|
|
66
|
+
const current = getNode(nodeId)?.managed_worktree;
|
|
67
|
+
if (current === undefined || current === null || current.state !== 'open')
|
|
68
|
+
return;
|
|
69
|
+
const { sweep: _sweep, ...retained } = current;
|
|
70
|
+
updateNode(nodeId, { managed_worktree: { ...retained, land_intent: { at: new Date().toISOString(), blocked } } });
|
|
71
|
+
}
|
|
72
|
+
async function dropStashIfStillTip(cwd, stashSha) {
|
|
73
|
+
const tip = await gitAsync(['rev-parse', '--verify', '--quiet', 'refs/stash'], cwd);
|
|
74
|
+
if (tip.status === 0 && tip.stdout.trim() === stashSha)
|
|
75
|
+
await gitAsync(['stash', 'drop'], cwd);
|
|
76
|
+
}
|
|
77
|
+
async function landIntoBaseCheckout(baseCheckout, branch, baseSha, landedSha) {
|
|
78
|
+
const status = await gitAsync(['status', '--porcelain'], baseCheckout);
|
|
79
|
+
if (status.status !== 0)
|
|
80
|
+
return { ok: false, detail: detailOf(status) };
|
|
81
|
+
const diff = await gitAsync(['diff', '--name-only', baseSha, landedSha], baseCheckout);
|
|
82
|
+
if (diff.status !== 0)
|
|
83
|
+
return { ok: false, detail: detailOf(diff) };
|
|
84
|
+
const incoming = diff.stdout.split('\n').map((line) => line.trim()).filter((line) => line !== '');
|
|
85
|
+
const plan = planLandIntoCheckout(parseStatusPorcelain(status.stdout), incoming);
|
|
86
|
+
if (plan.kind === 'refuse')
|
|
87
|
+
return { ok: false, detail: `untracked files in ${baseCheckout} would be overwritten by the incoming commits: ${plan.collisions.join(', ')}` };
|
|
88
|
+
const merge = async () => {
|
|
89
|
+
const result = await gitAsync(['merge', '--ff-only', landedSha], baseCheckout);
|
|
90
|
+
return result.status === 0 ? { ok: true } : { ok: false, detail: detailOf(result) };
|
|
91
|
+
};
|
|
92
|
+
if (plan.kind === 'direct')
|
|
93
|
+
return merge();
|
|
94
|
+
const before = await gitAsync(['rev-parse', '--verify', '--quiet', 'refs/stash'], baseCheckout);
|
|
95
|
+
const beforeSha = before.status === 0 ? before.stdout.trim() : null;
|
|
96
|
+
const pushed = await gitAsync(['stash', 'push', '--message', `crtr landing ${branch}`], baseCheckout);
|
|
97
|
+
if (pushed.status !== 0)
|
|
98
|
+
return { ok: false, detail: detailOf(pushed) };
|
|
99
|
+
const after = await gitAsync(['rev-parse', '--verify', '--quiet', 'refs/stash'], baseCheckout);
|
|
100
|
+
const stashSha = after.status === 0 ? after.stdout.trim() : null;
|
|
101
|
+
if (stashSha === null || stashSha === beforeSha)
|
|
102
|
+
return merge();
|
|
103
|
+
const landed = await merge();
|
|
104
|
+
if (!landed.ok) {
|
|
105
|
+
if ((await gitAsync(['stash', 'apply', stashSha], baseCheckout)).status === 0)
|
|
106
|
+
await dropStashIfStillTip(baseCheckout, stashSha);
|
|
107
|
+
return landed;
|
|
108
|
+
}
|
|
109
|
+
if ((await gitAsync(['stash', 'apply', stashSha], baseCheckout)).status === 0) {
|
|
110
|
+
await dropStashIfStillTip(baseCheckout, stashSha);
|
|
111
|
+
return { ok: true };
|
|
112
|
+
}
|
|
113
|
+
await gitAsync(['reset', '--hard', landedSha], baseCheckout);
|
|
114
|
+
return { ok: true, stash: `local changes in ${baseCheckout} conflicted with the landed commits and were PRESERVED as stash ${stashSha}; nothing was lost. Re-apply them with \`git -C ${shellQuote(baseCheckout)} stash apply ${stashSha}\` and resolve the conflict.` };
|
|
115
|
+
}
|
|
116
|
+
async function closeLocked(nodeId) {
|
|
117
|
+
const node = getNode(nodeId);
|
|
118
|
+
if (node === null)
|
|
119
|
+
throw new WorktreeError('unknown_node', `unknown node: ${nodeId}`, 'Run this from a live node, or pass a real node id once that command supports it.');
|
|
120
|
+
const wt = node?.managed_worktree?.state === 'open' ? node.managed_worktree : null;
|
|
121
|
+
if (wt === null)
|
|
122
|
+
throw new WorktreeError('no_managed_worktree', `node ${nodeId} has no open managed worktree`, 'Nothing to close for this node.');
|
|
123
|
+
if (!existsSync(wt.path))
|
|
124
|
+
throw new WorktreeError('worktree_missing', `managed worktree path is missing: ${wt.path}`, missingWorktreeRecoveryHint(wt));
|
|
125
|
+
if (await rebaseInProgress(wt.path))
|
|
126
|
+
throw new WorktreeError('rebase_in_progress', 'this managed worktree is mid-rebase', `Resolve conflicts in ${wt.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);
|
|
127
|
+
const status = await runGit(wt.path, ['status', '--porcelain'], 'status_failed', 'Inspect the worktree manually, then retry.');
|
|
128
|
+
if (status !== '')
|
|
129
|
+
throw new WorktreeError('dirty_worktree', 'managed worktree has uncommitted changes', `Commit the work in ${wt.path}, then rerun \`crtr node worktree close\`.`);
|
|
130
|
+
const branch = await runGit(wt.path, ['rev-parse', '--abbrev-ref', 'HEAD'], 'branch_check_failed', 'Inspect the worktree manually, then retry.');
|
|
131
|
+
const head = await runGit(wt.path, ['rev-parse', 'HEAD'], 'landed_sha_failed', 'Inspect the worktree checkout manually, then rerun `crtr node worktree close`.');
|
|
132
|
+
if (branch !== wt.branch) {
|
|
133
|
+
const recorded = await gitAsync(['show-ref', '--verify', '--quiet', `refs/heads/${wt.branch}`], wt.path);
|
|
134
|
+
if (recorded.status === 0 || branch === 'HEAD' || !(await registeredWorktree(wt.repo_root, wt.path, branch))) {
|
|
135
|
+
throw new WorktreeError('wrong_branch', `managed worktree is not on its recorded branch (expected ${wt.branch}, found ${branch === 'HEAD' ? 'detached HEAD' : branch})`, `Inspect ${wt.path}, then rerun \`crtr node worktree close\`.`);
|
|
136
|
+
}
|
|
137
|
+
if (await proveBranchContained(wt.path, wt, head) === null) {
|
|
138
|
+
throw new WorktreeError('branch_moved_unlanded', `managed worktree's recorded branch ${wt.branch} no longer exists; its checkout is now on ${branch} at ${head}, which carries content local base branch '${wt.base_ref}' does not yet contain`, `Land or push ${branch} through its own workflow before closing.`);
|
|
139
|
+
}
|
|
140
|
+
const commonDir = await commonGitDir(wt.path);
|
|
141
|
+
if (!(await registeredWorktree(wt.repo_root, wt.path, branch)) || (await runGit(wt.path, ['rev-parse', '--abbrev-ref', 'HEAD'], 'branch_check_failed', 'Inspect the worktree manually, then retry.')) !== branch || (await runGit(wt.path, ['rev-parse', 'HEAD'], 'branch_check_failed', 'Inspect the worktree manually, then retry.')) !== head) {
|
|
142
|
+
throw new WorktreeError('wrong_branch', `managed worktree at ${wt.path} changed while closing`, `Inspect ${wt.path}, then rerun \`crtr node worktree close\`.`);
|
|
143
|
+
}
|
|
144
|
+
persistClosedWorktreeState(nodeId, { ...wt, disposal: { observed_branch: branch, observed_sha: head, common_dir: commonDir, authorized: new Date().toISOString() } }, 'pending');
|
|
145
|
+
return { node_id: nodeId, branch, worktree_path: wt.path, landed_sha: head, ...deferredCleanupResult(wt), branch_delete_error: `${branch} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.` };
|
|
146
|
+
}
|
|
147
|
+
// Decide whether landing remains before resolving a destination. A diverged
|
|
148
|
+
// local base cannot replay history that the recorded upstream already has.
|
|
149
|
+
if (await proveBranchContained(wt.path, wt, head) !== null) {
|
|
150
|
+
persistClosedWorktreeState(nodeId, wt, 'pending');
|
|
151
|
+
return { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, landed_sha: head, ...deferredCleanupResult(wt) };
|
|
152
|
+
}
|
|
153
|
+
let baseSha;
|
|
154
|
+
try {
|
|
155
|
+
baseSha = await resolveLandableBase(wt.path, wt.base_ref);
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
if (!(error instanceof WorktreeError) || error.code !== 'missing_base_branch' || head !== wt.base_sha)
|
|
159
|
+
throw error;
|
|
160
|
+
persistClosedWorktreeState(nodeId, wt, 'pending');
|
|
161
|
+
return { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, landed_sha: wt.base_sha, ...deferredCleanupResult(wt) };
|
|
162
|
+
}
|
|
163
|
+
const rebase = await gitAsync(['rebase', baseSha], wt.path);
|
|
164
|
+
if (rebase.status !== 0)
|
|
165
|
+
throw new WorktreeError('rebase_failed', `rebase onto local base branch '${wt.base_ref}' did not complete`, `Resolve conflicts in ${wt.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`, detailOf(rebase));
|
|
166
|
+
const landedSha = await runGit(wt.path, ['rev-parse', 'HEAD'], 'landed_sha_failed', 'Inspect the worktree checkout manually, then rerun `crtr node worktree close`.');
|
|
167
|
+
const blocked = (message, next, detail) => {
|
|
168
|
+
recordBlockedLandIntent(nodeId, message);
|
|
169
|
+
return new WorktreeError('land_base_failed', message, next, detail);
|
|
170
|
+
};
|
|
171
|
+
const fastForward = await gitAsync(['merge-base', '--is-ancestor', baseSha, landedSha], wt.path);
|
|
172
|
+
if (fastForward.status !== 0)
|
|
173
|
+
throw blocked(`rebased worktree is not a fast-forward of local base branch '${wt.base_ref}'`, 'Ask the user how to land this managed worktree.', detailOf(fastForward));
|
|
174
|
+
const list = await runGit(wt.path, ['worktree', 'list', '--porcelain'], 'worktree_list_failed', 'Inspect the repository worktrees manually, then retry.');
|
|
175
|
+
const baseCheckout = checkoutPathForBranchInList(list, wt.base_ref);
|
|
176
|
+
let stashNote;
|
|
177
|
+
if (baseCheckout !== null) {
|
|
178
|
+
const checkoutHead = await gitAsync(['rev-parse', 'HEAD'], baseCheckout);
|
|
179
|
+
if (checkoutHead.status !== 0 || checkoutHead.stdout.trim() !== baseSha)
|
|
180
|
+
throw blocked(`local base branch '${wt.base_ref}' changed while this worktree was closing`, `Reconcile the base checkout at ${baseCheckout}, then rerun \`crtr node worktree close\`.`, checkoutHead.status !== 0 ? detailOf(checkoutHead) : `expected ${baseSha}, found ${checkoutHead.stdout.trim()}`);
|
|
181
|
+
const landed = await landIntoBaseCheckout(baseCheckout, wt.branch, baseSha, landedSha);
|
|
182
|
+
if (!landed.ok)
|
|
183
|
+
throw blocked(`could not fast-forward local base branch '${wt.base_ref}' to this worktree`, `Local base branch '${wt.base_ref}' is checked out at ${baseCheckout} in a state that blocks a fast-forward.`, landed.detail);
|
|
184
|
+
stashNote = landed.stash;
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
const update = await gitAsync(['update-ref', `refs/heads/${wt.base_ref}`, landedSha, baseSha], wt.path);
|
|
188
|
+
if (update.status !== 0)
|
|
189
|
+
throw blocked(`could not fast-forward local base branch '${wt.base_ref}' to this worktree`, 'Ask the user how to land this managed worktree.', detailOf(update));
|
|
190
|
+
}
|
|
191
|
+
persistClosedWorktreeState(nodeId, wt, 'pending');
|
|
192
|
+
return { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, landed_sha: landedSha, ...deferredCleanupResult(wt), ...(stashNote === undefined ? {} : { base_checkout_stash: stashNote }) };
|
|
193
|
+
}
|
|
194
|
+
/** Async daemon executor for explicit close. The lock wait and every Git
|
|
195
|
+
* subprocess yield to the daemon event loop. */
|
|
196
|
+
export async function closeManagedWorktreeAsync(nodeId) {
|
|
197
|
+
const wt = getNode(nodeId)?.managed_worktree;
|
|
198
|
+
if (wt === undefined || wt === null || wt.state !== 'open')
|
|
199
|
+
return closeLocked(nodeId);
|
|
200
|
+
if (!existsSync(wt.path)) {
|
|
201
|
+
const conclusion = await concludeAbsentManagedWorktreeAsync(nodeId);
|
|
202
|
+
if (conclusion !== null) {
|
|
203
|
+
return {
|
|
204
|
+
node_id: nodeId,
|
|
205
|
+
branch: conclusion.dropped.branch,
|
|
206
|
+
worktree_path: conclusion.dropped.worktree_path,
|
|
207
|
+
landed_sha: conclusion.landedSha,
|
|
208
|
+
worktree_removed: true,
|
|
209
|
+
branch_deleted: conclusion.dropped.branch_deleted,
|
|
210
|
+
...(conclusion.dropped.branch_delete_error === undefined ? {} : { branch_delete_error: conclusion.dropped.branch_delete_error }),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const current = getNode(nodeId)?.managed_worktree;
|
|
215
|
+
if (current === undefined || current === null || current.state !== 'open')
|
|
216
|
+
return closeLocked(nodeId);
|
|
217
|
+
const cwd = existsSync(current.path) ? current.path : current.repo_root;
|
|
218
|
+
const commonDir = await commonGitDir(cwd);
|
|
219
|
+
return withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), () => closeLocked(nodeId), {
|
|
220
|
+
// Leave room for the API handler to serialize the typed refusal before its
|
|
221
|
+
// 30s client socket deadline.
|
|
222
|
+
timeoutMs: Math.min(WORKTREE_LOCK_WAIT_MS, 25_000),
|
|
223
|
+
timeoutError: () => new WorktreeError('worktree_lock_timeout', `timed out waiting to create a managed worktree in ${commonDir}`, 'Wait for the other managed-worktree operation to finish, then retry.'),
|
|
224
|
+
});
|
|
225
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ManagedWorktree } from './canvas/index.js';
|
|
2
|
+
export interface BranchContainmentProof {
|
|
3
|
+
containingRef: string;
|
|
4
|
+
containingSha: string;
|
|
5
|
+
}
|
|
6
|
+
/** Resolve the base branch's configured upstream, or its origin fallback. */
|
|
7
|
+
export declare function upstreamTip(cwd: string, baseRef: string): Promise<{
|
|
8
|
+
ref: string;
|
|
9
|
+
sha: string;
|
|
10
|
+
} | null>;
|
|
11
|
+
/** Prove that a recorded base or its upstream already carries a branch's
|
|
12
|
+
* committed content. This is the one decision point for explicit close and
|
|
13
|
+
* sweep cleanup: destination resolution happens only when this returns null. */
|
|
14
|
+
export declare function proveBranchContained(cwd: string, wt: Pick<ManagedWorktree, 'base_ref'>, branchSha: string): Promise<BranchContainmentProof | null>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { gitAsync } from './git.js';
|
|
2
|
+
async function revParseRef(cwd, ref) {
|
|
3
|
+
const result = await gitAsync(['rev-parse', '--verify', '--quiet', ref], cwd);
|
|
4
|
+
return result.status === 0 ? result.stdout.trim() : null;
|
|
5
|
+
}
|
|
6
|
+
/** Resolve the base branch's configured upstream, or its origin fallback. */
|
|
7
|
+
export async function upstreamTip(cwd, baseRef) {
|
|
8
|
+
const upstream = await gitAsync(['rev-parse', '--symbolic-full-name', '--verify', `${baseRef}@{upstream}`], cwd);
|
|
9
|
+
const ref = upstream.status === 0 && upstream.stdout.trim().startsWith('refs/')
|
|
10
|
+
? upstream.stdout.trim()
|
|
11
|
+
: `refs/remotes/origin/${baseRef}`;
|
|
12
|
+
const sha = await revParseRef(cwd, ref);
|
|
13
|
+
return sha === null ? null : { ref, sha };
|
|
14
|
+
}
|
|
15
|
+
/** Prove that a recorded base or its upstream already carries a branch's
|
|
16
|
+
* committed content. This is the one decision point for explicit close and
|
|
17
|
+
* sweep cleanup: destination resolution happens only when this returns null. */
|
|
18
|
+
export async function proveBranchContained(cwd, wt, branchSha) {
|
|
19
|
+
const candidates = [];
|
|
20
|
+
const localBaseRef = `refs/heads/${wt.base_ref}`;
|
|
21
|
+
const localBase = await revParseRef(cwd, localBaseRef);
|
|
22
|
+
if (localBase !== null)
|
|
23
|
+
candidates.push({ ref: localBaseRef, sha: localBase });
|
|
24
|
+
const upstream = await upstreamTip(cwd, wt.base_ref);
|
|
25
|
+
if (upstream !== null)
|
|
26
|
+
candidates.push(upstream);
|
|
27
|
+
for (const candidate of candidates) {
|
|
28
|
+
if ((await gitAsync(['merge-base', '--is-ancestor', branchSha, candidate.sha], cwd)).status === 0)
|
|
29
|
+
return { containingRef: candidate.ref, containingSha: candidate.sha };
|
|
30
|
+
}
|
|
31
|
+
for (const candidate of candidates) {
|
|
32
|
+
const cherry = await gitAsync(['cherry', candidate.sha, branchSha], cwd);
|
|
33
|
+
if (cherry.status !== 0)
|
|
34
|
+
continue;
|
|
35
|
+
const lines = cherry.stdout.split('\n').map((line) => line.trim()).filter((line) => line !== '');
|
|
36
|
+
if (lines.every((line) => line.startsWith('-')))
|
|
37
|
+
return { containingRef: candidate.ref, containingSha: candidate.sha };
|
|
38
|
+
}
|
|
39
|
+
for (const candidate of candidates) {
|
|
40
|
+
const candidateTree = await revParseRef(cwd, `${candidate.sha}^{tree}`);
|
|
41
|
+
if (candidateTree === null)
|
|
42
|
+
continue;
|
|
43
|
+
const merged = await gitAsync(['merge-tree', '--write-tree', candidate.sha, branchSha], cwd);
|
|
44
|
+
if (merged.status === 0 && merged.stdout.split('\n')[0]?.trim() === candidateTree)
|
|
45
|
+
return { containingRef: candidate.ref, containingSha: candidate.sha };
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type ManagedWorktree } from './canvas/index.js';
|
|
2
|
+
import { type AbandonManagedWorktreeResult, type AutoDroppedWorktree } from './worktree.js';
|
|
3
|
+
export declare function rollbackManagedWorktreeAsync(wt: ManagedWorktree): Promise<void>;
|
|
4
|
+
export declare function createManagedWorktreeAsync(cwd: string, nodeId: string, baseRef?: string): Promise<ManagedWorktree>;
|
|
5
|
+
export interface AbsentWorktreeConclusion {
|
|
6
|
+
dropped: AutoDroppedWorktree;
|
|
7
|
+
landedSha: string;
|
|
8
|
+
}
|
|
9
|
+
/** Conclude an absent checkout only from the same branch-delivery proof used by
|
|
10
|
+
* push-final and explicit close. */
|
|
11
|
+
export declare function concludeAbsentManagedWorktreeAsync(nodeId: string): Promise<AbsentWorktreeConclusion | null>;
|
|
12
|
+
export declare function autoDropCleanManagedWorktreeAsync(nodeId: string): Promise<AutoDroppedWorktree | null>;
|
|
13
|
+
export declare function abandonManagedWorktreeAsync(nodeId: string, by: string): Promise<AbandonManagedWorktreeResult>;
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { getNode, updateNode } from './canvas/index.js';
|
|
4
|
+
import { isPidAlive } from './canvas/pid.js';
|
|
5
|
+
import { CONFIG_FILE, CRTR_DIR_NAME, STATE_FILE } from '../types.js';
|
|
6
|
+
import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
|
|
7
|
+
import { gitAsync } from './git.js';
|
|
8
|
+
import { WORKTREE_LOCK_WAIT_MS, checkoutPathForBranchInList, isManagedWorktreeBase, managedWorktreePath, persistClosedWorktreeState, worktreeLockPathForCommonDir, WorktreeError } from './worktree.js';
|
|
9
|
+
import { proveBranchContained } from './worktree-containment.js';
|
|
10
|
+
import { refDeleteTransactionStdin } from './worktree-landing.js';
|
|
11
|
+
const LOCK_WAIT_MS = Math.min(WORKTREE_LOCK_WAIT_MS, 25_000);
|
|
12
|
+
function detailOf(result) { return (result.stderr.trim() || result.stdout.trim()).trim(); }
|
|
13
|
+
async function runGit(cwd, args, code, next) {
|
|
14
|
+
const result = await gitAsync(args, cwd);
|
|
15
|
+
if (result.status !== 0)
|
|
16
|
+
throw new WorktreeError(code, `git ${args.join(' ')} failed`, next, detailOf(result));
|
|
17
|
+
return result.stdout.trim();
|
|
18
|
+
}
|
|
19
|
+
async function commonGitDir(cwd) {
|
|
20
|
+
return realpathSync(resolve(cwd, await runGit(cwd, ['rev-parse', '--git-common-dir'], 'git_common_dir_failed', 'Inspect the repository git metadata, then retry.')));
|
|
21
|
+
}
|
|
22
|
+
async function withRepositoryLock(cwd, action) {
|
|
23
|
+
const commonDir = await commonGitDir(cwd);
|
|
24
|
+
return withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), action, {
|
|
25
|
+
timeoutMs: LOCK_WAIT_MS,
|
|
26
|
+
timeoutError: () => new WorktreeError('worktree_lock_timeout', `timed out waiting to create a managed worktree in ${commonDir}`, 'Wait for the other managed-worktree operation to finish, then retry.'),
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async function resolveLandableBase(cwd, baseRef) {
|
|
30
|
+
const ref = `refs/heads/${baseRef}`;
|
|
31
|
+
const exists = await gitAsync(['show-ref', '--verify', '--quiet', ref], cwd);
|
|
32
|
+
if (exists.status === 1 && exists.executionFailed !== true)
|
|
33
|
+
throw new WorktreeError('missing_base_branch', `managed worktree base '${baseRef}' does not name an existing local branch`, 'The base must be a local branch that landing can fast-forward — freshen your local branch from origin first (rebase-not-merge), then base on it.');
|
|
34
|
+
if (exists.status !== 0)
|
|
35
|
+
throw new WorktreeError('base_branch_inspection_failed', `could not inspect local base branch '${baseRef}' (git show-ref exited with status ${exists.status})`, 'Inspect the repository and its Git metadata, then retry.', `status: ${exists.status}\nstderr: ${exists.stderr.trim() || '<empty>'}`);
|
|
36
|
+
return runGit(cwd, ['rev-parse', '--verify', ref], 'base_branch_resolve_failed', 'Inspect the local base branch, then retry.');
|
|
37
|
+
}
|
|
38
|
+
function seedExclude(repoRoot, commonDir) {
|
|
39
|
+
try {
|
|
40
|
+
const path = join(commonDir, 'info', 'exclude');
|
|
41
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
42
|
+
let current = '';
|
|
43
|
+
try {
|
|
44
|
+
current = readFileSync(path, 'utf8');
|
|
45
|
+
}
|
|
46
|
+
catch { /* first write */ }
|
|
47
|
+
const patterns = [`/${CRTR_DIR_NAME}/${CONFIG_FILE}`, `/${CRTR_DIR_NAME}/${STATE_FILE}`];
|
|
48
|
+
if (patterns.every((pattern) => current.split('\n').map((line) => line.trim()).includes(pattern)))
|
|
49
|
+
return;
|
|
50
|
+
writeFileSync(path, `${current}${current !== '' && !current.endsWith('\n') ? '\n' : ''}# crtr: exclude crtr's own untracked project-scope bookkeeping (auto-added at managed-worktree creation)\n${patterns.filter((pattern) => !current.split('\n').map((line) => line.trim()).includes(pattern)).join('\n')}\n`);
|
|
51
|
+
}
|
|
52
|
+
catch { /* cosmetic only */ }
|
|
53
|
+
}
|
|
54
|
+
export async function rollbackManagedWorktreeAsync(wt) {
|
|
55
|
+
await withRepositoryLock(wt.repo_root, async () => {
|
|
56
|
+
const branch = await gitAsync(['rev-parse', '--verify', `refs/heads/${wt.branch}`], wt.repo_root);
|
|
57
|
+
if (branch.status !== 0 || branch.stdout.trim() !== wt.base_sha)
|
|
58
|
+
return;
|
|
59
|
+
const list = await gitAsync(['worktree', 'list', '--porcelain'], wt.repo_root);
|
|
60
|
+
if (list.status !== 0)
|
|
61
|
+
return;
|
|
62
|
+
if (list.stdout.split('\n').some((line) => line.trim() === `branch refs/heads/${wt.branch}`)) {
|
|
63
|
+
if ((await gitAsync(['worktree', 'remove', '--force', wt.path], wt.repo_root)).status !== 0)
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
else if (existsSync(wt.path)) {
|
|
67
|
+
try {
|
|
68
|
+
rmSync(wt.path, { recursive: true, force: true });
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
await gitAsync(['update-ref', '-d', `refs/heads/${wt.branch}`, wt.base_sha], wt.repo_root);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main') {
|
|
78
|
+
const repoRoot = await runGit(cwd, ['rev-parse', '--show-toplevel'], 'not_git_repo', 'Pass --cwd <real repo> pointing inside a git repository.');
|
|
79
|
+
if (isManagedWorktreeBase(repoRoot)) {
|
|
80
|
+
throw new WorktreeError('managed_worktree_base', `cwd ${repoRoot} is a managed worktree and cannot be used as a managed worktree base`, 'Pass --cwd <real repo> pointing at the repository’s primary checkout.');
|
|
81
|
+
}
|
|
82
|
+
const commonDir = await commonGitDir(repoRoot);
|
|
83
|
+
return withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
|
|
84
|
+
const baseSha = await resolveLandableBase(repoRoot, baseRef);
|
|
85
|
+
const path = managedWorktreePath(nodeId);
|
|
86
|
+
const branch = `crtr/${nodeId}`;
|
|
87
|
+
if (existsSync(path))
|
|
88
|
+
throw new WorktreeError('worktree_path_exists', `managed worktree path already exists: ${path}`, 'Remove the stale path or choose a fresh node id.');
|
|
89
|
+
if ((await gitAsync(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], repoRoot)).status === 0)
|
|
90
|
+
throw new WorktreeError('worktree_branch_exists', `managed worktree branch already exists: ${branch}`, 'Remove the stale branch or choose a fresh node id.');
|
|
91
|
+
const wt = { state: 'open', path, branch, repo_root: repoRoot, base_ref: baseRef, base_sha: baseSha, created: new Date().toISOString() };
|
|
92
|
+
await runGit(repoRoot, ['branch', branch, baseSha], 'worktree_branch_create_failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.');
|
|
93
|
+
const added = await gitAsync(['worktree', 'add', path, branch], repoRoot);
|
|
94
|
+
if (added.status !== 0) {
|
|
95
|
+
await gitAsync(['update-ref', '-d', `refs/heads/${branch}`, baseSha], repoRoot);
|
|
96
|
+
throw new WorktreeError('worktree_add_failed', 'git worktree add failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.', detailOf(added));
|
|
97
|
+
}
|
|
98
|
+
seedExclude(repoRoot, commonDir);
|
|
99
|
+
return wt;
|
|
100
|
+
}, { timeoutMs: LOCK_WAIT_MS, timeoutError: () => new WorktreeError('worktree_lock_timeout', `timed out waiting to create a managed worktree in ${commonDir}`, 'Wait for the other managed-worktree operation to finish, then retry.') });
|
|
101
|
+
}
|
|
102
|
+
async function cleanTip(wt) {
|
|
103
|
+
if (wt.state !== 'open' || !existsSync(wt.path))
|
|
104
|
+
return null;
|
|
105
|
+
const branch = await gitAsync(['rev-parse', '--abbrev-ref', 'HEAD'], wt.path);
|
|
106
|
+
const status = await gitAsync(['status', '--porcelain'], wt.path);
|
|
107
|
+
const head = await gitAsync(['rev-parse', 'HEAD'], wt.path);
|
|
108
|
+
if (branch.status !== 0 || branch.stdout.trim() !== wt.branch || status.status !== 0 || status.stdout.trim() !== '' || head.status !== 0)
|
|
109
|
+
return null;
|
|
110
|
+
const gitPath = await gitAsync(['rev-parse', '--git-path', 'rebase-merge'], wt.path);
|
|
111
|
+
if (gitPath.status !== 0 || existsSync(gitPath.stdout.trim()))
|
|
112
|
+
return null;
|
|
113
|
+
return head.stdout.trim();
|
|
114
|
+
}
|
|
115
|
+
async function containedInLocalBase(wt, head) {
|
|
116
|
+
try {
|
|
117
|
+
const base = await resolveLandableBase(wt.path, wt.base_ref);
|
|
118
|
+
return (await gitAsync(['merge-base', '--is-ancestor', head, base], wt.path)).status === 0;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (error instanceof WorktreeError && error.code === 'missing_base_branch' && head === wt.base_sha)
|
|
122
|
+
return true;
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function deferred(wt) {
|
|
127
|
+
return { node_id: '', branch: wt.branch, worktree_path: wt.path, worktree_removed: false, worktree_remove_error: `cleanup pending: the caller checkout at ${wt.path} remains intact.`, branch_deleted: false, branch_delete_error: `cleanup pending: local branch ${wt.branch} remains checked out at ${wt.path}.` };
|
|
128
|
+
}
|
|
129
|
+
/** A missing checkout can be concluded only when its branch is already gone,
|
|
130
|
+
* or the recorded base or its upstream contains the branch and it has no other
|
|
131
|
+
* checkout. */
|
|
132
|
+
async function proveAbsentPathManagedWorktree(wt) {
|
|
133
|
+
if (wt.state !== 'open' || existsSync(wt.path))
|
|
134
|
+
return null;
|
|
135
|
+
const branchRef = `refs/heads/${wt.branch}`;
|
|
136
|
+
const branchExists = await gitAsync(['show-ref', '--verify', '--quiet', branchRef], wt.repo_root);
|
|
137
|
+
if (branchExists.status === 1 && branchExists.executionFailed !== true)
|
|
138
|
+
return { branchSha: null };
|
|
139
|
+
if (branchExists.status !== 0)
|
|
140
|
+
return null;
|
|
141
|
+
const branch = await gitAsync(['rev-parse', '--verify', branchRef], wt.repo_root);
|
|
142
|
+
if (branch.status !== 0)
|
|
143
|
+
return null;
|
|
144
|
+
const branchSha = branch.stdout.trim();
|
|
145
|
+
const worktreeList = await gitAsync(['worktree', 'list', '--porcelain'], wt.repo_root);
|
|
146
|
+
if (worktreeList.status !== 0 || checkoutPathForBranchInList(worktreeList.stdout, wt.branch) !== null)
|
|
147
|
+
return null;
|
|
148
|
+
const containment = await proveBranchContained(wt.repo_root, wt, branchSha);
|
|
149
|
+
return containment === null ? null : { branchSha, containment };
|
|
150
|
+
}
|
|
151
|
+
async function autoDropAbsentPathManagedWorktreeLocked(nodeId, wt, proof) {
|
|
152
|
+
if (existsSync(wt.path))
|
|
153
|
+
return null;
|
|
154
|
+
if (proof.branchSha === null) {
|
|
155
|
+
persistClosedWorktreeState(nodeId, wt, 'complete');
|
|
156
|
+
return { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, worktree_removed: true, branch_deleted: true };
|
|
157
|
+
}
|
|
158
|
+
if (proof.containment === undefined)
|
|
159
|
+
return null;
|
|
160
|
+
// `update-ref` bypasses Git's checked-out-branch protection. A person can
|
|
161
|
+
// add a worktree after the list above, so the delivered branch stays intact:
|
|
162
|
+
// its containment proof concludes this node without risking that checkout.
|
|
163
|
+
persistClosedWorktreeState(nodeId, wt, 'complete');
|
|
164
|
+
return { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, worktree_removed: true, branch_deleted: false, branch_delete_error: `local branch ${wt.branch} is delivered but retained because its checkout status can change outside crtr's repository lock.` };
|
|
165
|
+
}
|
|
166
|
+
/** Conclude an absent checkout only from the same branch-delivery proof used by
|
|
167
|
+
* push-final and explicit close. */
|
|
168
|
+
export async function concludeAbsentManagedWorktreeAsync(nodeId) {
|
|
169
|
+
const wt = getNode(nodeId)?.managed_worktree;
|
|
170
|
+
if (wt === undefined || wt === null || wt.state !== 'open' || existsSync(wt.path))
|
|
171
|
+
return null;
|
|
172
|
+
if (await proveAbsentPathManagedWorktree(wt) === null)
|
|
173
|
+
return null;
|
|
174
|
+
return withRepositoryLock(wt.repo_root, async () => {
|
|
175
|
+
const locked = getNode(nodeId)?.managed_worktree;
|
|
176
|
+
if (locked === undefined || locked === null || locked.state !== 'open')
|
|
177
|
+
return null;
|
|
178
|
+
const proof = await proveAbsentPathManagedWorktree(locked);
|
|
179
|
+
if (proof === null)
|
|
180
|
+
return null;
|
|
181
|
+
const dropped = await autoDropAbsentPathManagedWorktreeLocked(nodeId, locked, proof);
|
|
182
|
+
return dropped === null ? null : { dropped, landedSha: proof.branchSha ?? locked.base_sha };
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
export async function autoDropCleanManagedWorktreeAsync(nodeId) {
|
|
186
|
+
const wt = getNode(nodeId)?.managed_worktree;
|
|
187
|
+
if (wt === undefined || wt === null || wt.state !== 'open')
|
|
188
|
+
return null;
|
|
189
|
+
if (!existsSync(wt.path))
|
|
190
|
+
return (await concludeAbsentManagedWorktreeAsync(nodeId))?.dropped ?? null;
|
|
191
|
+
const initial = await cleanTip(wt);
|
|
192
|
+
if (initial === null || !(await containedInLocalBase(wt, initial)))
|
|
193
|
+
return null;
|
|
194
|
+
return withRepositoryLock(wt.path, async () => {
|
|
195
|
+
const locked = getNode(nodeId)?.managed_worktree;
|
|
196
|
+
if (locked === undefined || locked === null || locked.state !== 'open')
|
|
197
|
+
return null;
|
|
198
|
+
const head = await cleanTip(locked);
|
|
199
|
+
if (head === null || head !== initial || !(await containedInLocalBase(locked, head)))
|
|
200
|
+
return null;
|
|
201
|
+
persistClosedWorktreeState(nodeId, locked, 'pending');
|
|
202
|
+
return { ...deferred(locked), node_id: nodeId };
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
async function rebaseInProgress(cwd) {
|
|
206
|
+
for (const path of ['rebase-merge', 'rebase-apply']) {
|
|
207
|
+
const result = await gitAsync(['rev-parse', '--git-path', path], cwd);
|
|
208
|
+
if (result.status !== 0 || existsSync(result.stdout.trim()))
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
213
|
+
function persistAbandoned(nodeId, wt, tip, at, by, branch = wt.branch) {
|
|
214
|
+
updateNode(nodeId, { cwd: wt.repo_root, managed_worktree: { ...wt, state: 'abandoned', abandoned: { branch, tip_sha: tip, at, by } } });
|
|
215
|
+
}
|
|
216
|
+
export async function abandonManagedWorktreeAsync(nodeId, by) {
|
|
217
|
+
const wt = getNode(nodeId)?.managed_worktree;
|
|
218
|
+
if (wt === undefined || wt === null || wt.state !== 'open')
|
|
219
|
+
throw new WorktreeError('no_managed_worktree', `node ${nodeId} has no open managed worktree`, 'Nothing to abandon for this node.');
|
|
220
|
+
return withRepositoryLock(wt.path, async () => {
|
|
221
|
+
const node = getNode(nodeId);
|
|
222
|
+
const current = node?.managed_worktree;
|
|
223
|
+
if (node === null || current === undefined || current === null || current.state !== 'open')
|
|
224
|
+
throw new WorktreeError('no_managed_worktree', `node ${nodeId} has no open managed worktree`, 'Nothing to abandon for this node.');
|
|
225
|
+
if (node.status === 'active' || node.status === 'idle' || isPidAlive(node.pi_pid))
|
|
226
|
+
throw new WorktreeError('node_running', `node ${nodeId} is still running`, 'Stop the node before abandoning its managed worktree.');
|
|
227
|
+
if (!existsSync(current.path))
|
|
228
|
+
throw new WorktreeError('worktree_missing', `managed worktree path is missing: ${current.path}`, 'Inspect the branch and worktree registration, then retry.');
|
|
229
|
+
const branch = await runGit(current.path, ['rev-parse', '--abbrev-ref', 'HEAD'], 'branch_check_failed', 'Inspect the worktree manually, then retry.');
|
|
230
|
+
const recorded = await gitAsync(['show-ref', '--verify', '--quiet', `refs/heads/${current.branch}`], current.path);
|
|
231
|
+
if (branch !== current.branch) {
|
|
232
|
+
if (recorded.status === 0 || branch === 'HEAD')
|
|
233
|
+
throw new WorktreeError('wrong_branch', `managed worktree is not on its recorded branch (expected ${current.branch}, found ${branch === 'HEAD' ? 'detached HEAD' : branch})`, `Inspect ${current.path}, then rerun \`crtr node worktree abandon\`.`);
|
|
234
|
+
if (await rebaseInProgress(current.path) || (await runGit(current.path, ['status', '--porcelain'], 'status_failed', 'Inspect the worktree manually, then retry.')) !== '')
|
|
235
|
+
throw new WorktreeError('dirty_worktree', 'managed worktree has uncommitted changes', `Commit or stash them in ${current.path}, then rerun \`crtr node worktree abandon\`.`);
|
|
236
|
+
const tip = await runGit(current.path, ['rev-parse', 'HEAD'], 'abandon_tip_failed', 'Inspect the worktree manually, then retry.');
|
|
237
|
+
await runGit(current.repo_root, ['worktree', 'remove', current.path], 'worktree_remove_failed', 'Inspect the worktree manually, then retry.');
|
|
238
|
+
const at = new Date().toISOString();
|
|
239
|
+
persistAbandoned(nodeId, current, tip, at, by, branch);
|
|
240
|
+
return { node_id: nodeId, branch, tip_sha: tip, worktree_path: current.path, branch_deleted: false };
|
|
241
|
+
}
|
|
242
|
+
const head = await runGit(current.path, ['rev-parse', 'HEAD'], 'abandon_tip_failed', 'Inspect the branch manually, then retry.');
|
|
243
|
+
let cleanBase = null;
|
|
244
|
+
try {
|
|
245
|
+
const base = await resolveLandableBase(current.path, current.base_ref);
|
|
246
|
+
if ((await gitAsync(['merge-base', '--is-ancestor', head, base], current.path)).status === 0)
|
|
247
|
+
cleanBase = base;
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
if (!(error instanceof WorktreeError) || error.code !== 'missing_base_branch' || head !== current.base_sha)
|
|
251
|
+
throw error;
|
|
252
|
+
cleanBase = current.base_sha;
|
|
253
|
+
}
|
|
254
|
+
const at = new Date().toISOString();
|
|
255
|
+
const status = await runGit(current.path, ['status', '--porcelain'], 'status_failed', 'Inspect the worktree manually, then retry.');
|
|
256
|
+
if (cleanBase !== null && head === current.base_sha) {
|
|
257
|
+
const tree = await runGit(current.repo_root, ['rev-parse', `${head}^{tree}`], 'abandon_tree_failed', 'Inspect the branch manually, then retry.');
|
|
258
|
+
const marker = await runGit(current.repo_root, ['-c', 'user.name=crtr-abandon', '-c', 'user.email=crtr-abandon@localhost', 'commit-tree', tree, '-p', head, '-m', 'crtr-abandon', '-m', `Crtr-Abandon: ${nodeId} ${at}`], 'abandon_commit_failed', 'Inspect the branch manually, then retry.');
|
|
259
|
+
await runGit(current.repo_root, ['update-ref', `refs/heads/${current.branch}`, marker, head], 'abandon_marker_failed', 'The branch changed while abandon was starting; inspect the worktree, then retry.');
|
|
260
|
+
await runGit(current.repo_root, ['worktree', 'remove', current.path], 'worktree_remove_failed', 'Inspect the worktree manually, then retry.');
|
|
261
|
+
const deleted = await gitAsync(['update-ref', '--stdin'], current.repo_root, refDeleteTransactionStdin(current.branch, marker, `refs/heads/${current.base_ref}`, cleanBase));
|
|
262
|
+
if (deleted.status === 0) {
|
|
263
|
+
persistClosedWorktreeState(nodeId, current, 'complete');
|
|
264
|
+
return { node_id: nodeId, branch: current.branch, tip_sha: marker, worktree_path: current.path, branch_deleted: true };
|
|
265
|
+
}
|
|
266
|
+
persistAbandoned(nodeId, current, marker, at, by);
|
|
267
|
+
return { node_id: nodeId, branch: current.branch, tip_sha: marker, worktree_path: current.path, branch_deleted: false };
|
|
268
|
+
}
|
|
269
|
+
if (!await rebaseInProgress(current.path) && status === '') {
|
|
270
|
+
await runGit(current.repo_root, ['worktree', 'remove', current.path], 'worktree_remove_failed', 'Inspect the worktree manually, then retry.');
|
|
271
|
+
persistAbandoned(nodeId, current, head, at, by);
|
|
272
|
+
return { node_id: nodeId, branch: current.branch, tip_sha: head, worktree_path: current.path, branch_deleted: false };
|
|
273
|
+
}
|
|
274
|
+
await runGit(current.path, ['add', '--all'], 'abandon_stage_failed', 'Inspect the worktree manually, then retry.');
|
|
275
|
+
await runGit(current.path, ['-c', 'user.name=crtr-abandon', '-c', 'user.email=crtr-abandon@localhost', 'commit', '--allow-empty', '-m', 'crtr-abandon', '-m', `Crtr-Abandon: ${nodeId} ${at}`], 'abandon_commit_failed', 'Inspect the worktree manually, then retry.');
|
|
276
|
+
const tip = await runGit(current.path, ['rev-parse', 'HEAD'], 'abandon_tip_failed', 'Inspect the branch manually, then retry.');
|
|
277
|
+
await runGit(current.repo_root, ['worktree', 'remove', current.path], 'worktree_remove_failed', 'Inspect the worktree manually, then retry.');
|
|
278
|
+
persistAbandoned(nodeId, current, tip, at, by);
|
|
279
|
+
return { node_id: nodeId, branch: current.branch, tip_sha: tip, worktree_path: current.path, branch_deleted: false };
|
|
280
|
+
});
|
|
281
|
+
}
|