@north-light/crouter 0.3.302 → 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.
Files changed (85) hide show
  1. package/dist/api/__tests__/integration/client.test.js +37 -36
  2. package/dist/api/client.d.ts +32 -55
  3. package/dist/api/client.js +102 -98
  4. package/dist/api/dto/messages.d.ts +6 -5
  5. package/dist/api/errors.d.ts +3 -0
  6. package/dist/api/errors.js +10 -0
  7. package/dist/api/index.d.ts +1 -1
  8. package/dist/api/index.js +1 -1
  9. package/dist/builtin-memory/internal/plugins.md +1 -1
  10. package/dist/clients/attach/viewer.js +532 -532
  11. package/dist/commands/__tests__/seam/daemon-status.test.d.ts +1 -0
  12. package/dist/commands/__tests__/seam/daemon-status.test.js +29 -0
  13. package/dist/commands/api-client.d.ts +3 -3
  14. package/dist/commands/api-client.js +3 -3
  15. package/dist/commands/memory/read.js +2 -1
  16. package/dist/commands/node/bash.js +6 -6
  17. package/dist/commands/node/message.js +3 -3
  18. package/dist/commands/sys/daemon.js +11 -13
  19. package/dist/core/__tests__/bash-guard.test.d.ts +1 -0
  20. package/dist/core/__tests__/bash-guard.test.js +190 -0
  21. package/dist/core/__tests__/broker-stream-watchdog-floor.test.js +0 -2
  22. package/dist/core/__tests__/daemon-boot.test.js +1 -1
  23. package/dist/core/__tests__/fixtures/fake-engine.d.ts +6 -0
  24. package/dist/core/__tests__/fixtures/fake-engine.js +51 -11
  25. package/dist/core/__tests__/helpers/harness.d.ts +2 -0
  26. package/dist/core/__tests__/helpers/harness.js +9 -0
  27. package/dist/core/__tests__/integration/worktree-land.test.js +50 -0
  28. package/dist/core/__tests__/integration/worktree-reap.test.js +184 -5
  29. package/dist/core/__tests__/parse-argv-stdin-secret.test.js +14 -0
  30. package/dist/core/__tests__/seam/broker-attach-stream.test.js +13 -0
  31. package/dist/core/__tests__/seam/broker-provider-retry.test.js +57 -0
  32. package/dist/core/__tests__/seam/broker-startup-diagnostics.test.d.ts +1 -0
  33. package/dist/core/__tests__/seam/broker-startup-diagnostics.test.js +82 -0
  34. package/dist/core/bash-guard.d.ts +6 -0
  35. package/dist/core/bash-guard.js +393 -0
  36. package/dist/core/bash-jobs.d.ts +20 -8
  37. package/dist/core/bash-jobs.js +40 -21
  38. package/dist/core/canvas/types.d.ts +4 -2
  39. package/dist/core/command.js +1 -1
  40. package/dist/core/fault-classifier.d.ts +1 -1
  41. package/dist/core/runtime/broker/event-projection.d.ts +0 -3
  42. package/dist/core/runtime/broker/event-projection.js +2 -15
  43. package/dist/core/runtime/broker/fault-retry.d.ts +4 -0
  44. package/dist/core/runtime/broker/fault-retry.js +74 -6
  45. package/dist/core/runtime/broker-persona-guidance.js +12 -0
  46. package/dist/core/runtime/broker.js +0 -5
  47. package/dist/core/runtime/fault.js +1 -1
  48. package/dist/core/runtime/host.js +10 -1
  49. package/dist/core/runtime/spawn.js +5 -6
  50. package/dist/core/shell-segments.d.ts +42 -0
  51. package/dist/core/shell-segments.js +169 -0
  52. package/dist/core/substrate/surface-match.d.ts +0 -9
  53. package/dist/core/substrate/surface-match.js +4 -160
  54. package/dist/core/worktree-close.d.ts +4 -0
  55. package/dist/core/worktree-close.js +225 -0
  56. package/dist/core/worktree-containment.d.ts +14 -0
  57. package/dist/core/worktree-containment.js +48 -0
  58. package/dist/core/worktree-mutation-async.d.ts +13 -0
  59. package/dist/core/worktree-mutation-async.js +281 -0
  60. package/dist/core/worktree-sweep.js +17 -79
  61. package/dist/core/worktree.d.ts +1 -0
  62. package/dist/core/worktree.js +1 -1
  63. package/dist/daemon/__tests__/integration/api-startup-readiness.test.js +10 -8
  64. package/dist/daemon/api/__tests__/seam/api-server.test.js +70 -1
  65. package/dist/daemon/api/handlers/bash-jobs.js +1 -1
  66. package/dist/daemon/api/handlers/messages.js +7 -5
  67. package/dist/daemon/api/handlers/reports.js +3 -2
  68. package/dist/daemon/api/handlers/worktree.js +7 -6
  69. package/dist/daemon/fleet.d.ts +1 -1
  70. package/dist/daemon/fleet.js +30 -12
  71. package/dist/daemon/manage.d.ts +8 -5
  72. package/dist/daemon/manage.js +63 -40
  73. package/dist/daemon/reconcilers/managed-worktree-sweep.js +12 -0
  74. package/dist/daemon/reconcilers/node-lifecycle/tick.d.ts +0 -6
  75. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -13
  76. package/dist/daemon/reconcilers/node-lifecycle/wants-execution.d.ts +5 -0
  77. package/dist/daemon/reconcilers/node-lifecycle/wants-execution.js +11 -0
  78. package/dist/pi-extensions/__tests__/canvas-context-intro.test.js +83 -0
  79. package/dist/pi-extensions/__tests__/integration/canvas-bash-valve.test.d.ts +1 -0
  80. package/dist/pi-extensions/__tests__/integration/canvas-bash-valve.test.js +133 -0
  81. package/dist/pi-extensions/canvas-bash-valve.d.ts +2 -3
  82. package/dist/pi-extensions/canvas-bash-valve.js +75 -77
  83. package/dist/pi-extensions/canvas-inbox-watcher.js +0 -2
  84. package/package.json +1 -1
  85. package/runtime.lock.json +5 -5
@@ -10,6 +10,7 @@
10
10
  // container (its owning repo dir for `read`, its canonical routing anchor for
11
11
  // `memory-read`).
12
12
  import { basename, isAbsolute, matchesGlob, relative, sep } from 'node:path';
13
+ import { commandSegments, stripHeredocs } from '../shell-segments.js';
13
14
  import { CRTR_DIR_NAME } from '../../types.js';
14
15
  import { realpathOrSelf } from '../fs-utils.js';
15
16
  import { evalCondition } from '../predicate.js';
@@ -102,129 +103,6 @@ export function matchesMemoryReadEntry(entry, routingAnchor, subject, name) {
102
103
  return false;
103
104
  return entry.match.some((g) => memoryReadGlobMatches(g, routingAnchor, name));
104
105
  }
105
- /** Split a command into shell segments on unquoted `;`, newline, `&&`, `||`,
106
- * and `|`. A single `&`, subshell parentheses, and backticks are left inside
107
- * their segment — this is a best-effort guardrail, not a shell parser.
108
- * Heredoc bodies are a separate pre-match concern (see `stripHeredocs`). */
109
- function splitCommandSegments(command) {
110
- const segments = [];
111
- let current = '';
112
- let quote = null;
113
- let escaped = false;
114
- const finish = () => {
115
- segments.push(current);
116
- current = '';
117
- };
118
- for (let i = 0; i < command.length; i += 1) {
119
- const ch = command[i];
120
- if (escaped) {
121
- current += ch;
122
- escaped = false;
123
- continue;
124
- }
125
- if (ch === '\\' && quote !== "'") {
126
- current += ch;
127
- escaped = true;
128
- continue;
129
- }
130
- if (quote !== null) {
131
- current += ch;
132
- if (ch === quote)
133
- quote = null;
134
- continue;
135
- }
136
- if (ch === "'" || ch === '"') {
137
- current += ch;
138
- quote = ch;
139
- continue;
140
- }
141
- if (ch === '\n' || ch === ';') {
142
- finish();
143
- continue;
144
- }
145
- if ((ch === '&' || ch === '|') && command[i + 1] === ch) {
146
- finish();
147
- i += 1;
148
- continue;
149
- }
150
- if (ch === '|') {
151
- finish();
152
- continue;
153
- }
154
- current += ch;
155
- }
156
- finish();
157
- return segments;
158
- }
159
- /** Tokenize one segment into shell words, marking quoted spans opaque. */
160
- function tokenizeCommandSegment(segment) {
161
- const tokens = [];
162
- let text = '';
163
- let opaque = false;
164
- let started = false;
165
- let quote = null;
166
- let escaped = false;
167
- const finish = () => {
168
- if (started)
169
- tokens.push({ text, opaque });
170
- text = '';
171
- opaque = false;
172
- started = false;
173
- };
174
- for (let i = 0; i < segment.length; i += 1) {
175
- const ch = segment[i];
176
- if (escaped) {
177
- text += ch;
178
- started = true;
179
- escaped = false;
180
- continue;
181
- }
182
- if (ch === '\\' && quote !== "'") {
183
- escaped = true;
184
- started = true;
185
- continue;
186
- }
187
- if (quote !== null) {
188
- started = true;
189
- if (ch === quote) {
190
- quote = null;
191
- }
192
- else {
193
- text += ch;
194
- }
195
- continue;
196
- }
197
- if (ch === "'" || ch === '"') {
198
- quote = ch;
199
- opaque = true;
200
- started = true;
201
- continue;
202
- }
203
- if (/\s/.test(ch)) {
204
- finish();
205
- continue;
206
- }
207
- text += ch;
208
- started = true;
209
- }
210
- if (escaped)
211
- text += '\\';
212
- finish();
213
- return tokens;
214
- }
215
- /** Every non-empty command segment as its env-stripped token list: leading
216
- * `VAR=value` assignments are dropped so `tokens[0]` is the executable. */
217
- function commandSegments(command) {
218
- return splitCommandSegments(command)
219
- .map(tokenizeCommandSegment)
220
- .map((tokens) => {
221
- let first = 0;
222
- while (first < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[first].text))
223
- first += 1;
224
- return tokens.slice(first);
225
- })
226
- .filter((tokens) => tokens.length > 0);
227
- }
228
106
  function commandGlobPattern(glob) {
229
107
  const words = glob.trim().split(/\s+/);
230
108
  if (words.length === 1 && words[0] === '')
@@ -275,7 +153,9 @@ function commandGlobMatches(glob, command) {
275
153
  const pattern = commandGlobPattern(glob);
276
154
  if (pattern === null)
277
155
  return false;
278
- return commandSegments(command).some((tokens) => segmentMatches(pattern, tokens));
156
+ return commandSegments(command)
157
+ .filter(({ tokens }) => tokens.length > 0)
158
+ .some(({ tokens }) => segmentMatches(pattern, tokens));
279
159
  }
280
160
  /** Does a `command` entry fit the executed command string? */
281
161
  export function matchesCommandEntry(entry, subject, command) {
@@ -283,42 +163,6 @@ export function matchesCommandEntry(entry, subject, command) {
283
163
  return false;
284
164
  return entry.match.some((g) => commandGlobMatches(g, command));
285
165
  }
286
- const HEREDOC_OPEN = /<<(-?)\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\2/g;
287
- /** Remove heredoc BODIES (the stdin data between `<<DELIM` and its closing
288
- * `DELIM` line) from a command before it is matched. The opening line is kept
289
- * — `crtr push final <<'EOF'` is still a real `push final` invocation — but the
290
- * body lines, which are data fed on stdin and never executed as commands, are
291
- * dropped. Without this a doc-writing command whose body merely MENTIONS a
292
- * matched invocation would have its whole call held. Post-execution `command`
293
- * delivery does not need this (a spurious late injection costs a paragraph);
294
- * a `pre-command` block costs the agent a turn, so it does. */
295
- export function stripHeredocs(command) {
296
- const lines = command.split('\n');
297
- const out = [];
298
- let i = 0;
299
- while (i < lines.length) {
300
- const line = lines[i];
301
- out.push(line);
302
- i += 1;
303
- // Every heredoc opened on this line, left to right; their bodies stack and
304
- // are consumed in that order.
305
- const delims = [];
306
- HEREDOC_OPEN.lastIndex = 0;
307
- let m;
308
- while ((m = HEREDOC_OPEN.exec(line)) !== null)
309
- delims.push({ name: m[3], dash: m[1] === '-' });
310
- for (const d of delims) {
311
- while (i < lines.length) {
312
- // `<<-` strips leading TABS from the body and the closing delimiter.
313
- const probe = d.dash ? lines[i].replace(/^\t+/, '') : lines[i];
314
- i += 1;
315
- if (probe === d.name)
316
- break; // closing delimiter line — drop it, stop
317
- }
318
- }
319
- }
320
- return out.join('\n');
321
- }
322
166
  /** Does a `pre-command` entry fit a command that is ABOUT to run? The same
323
167
  * glob machinery `command` uses — one matcher, one semantics — applied to the
324
168
  * command with its heredoc bodies stripped. Subshell parentheses, backticks,
@@ -0,0 +1,4 @@
1
+ import { type CloseManagedWorktreeResult } from './worktree.js';
2
+ /** Async daemon executor for explicit close. The lock wait and every Git
3
+ * subprocess yield to the daemon event loop. */
4
+ export declare function closeManagedWorktreeAsync(nodeId: string): Promise<CloseManagedWorktreeResult>;
@@ -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>;