@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.
- 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__/bash-guard.test.d.ts +1 -0
- package/dist/core/__tests__/bash-guard.test.js +190 -0
- 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__/fixtures/fake-engine.d.ts +6 -0
- package/dist/core/__tests__/fixtures/fake-engine.js +51 -11
- 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-provider-retry.test.js +57 -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-guard.d.ts +6 -0
- package/dist/core/bash-guard.js +393 -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.d.ts +4 -0
- package/dist/core/runtime/broker/fault-retry.js +74 -6
- 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/shell-segments.d.ts +42 -0
- package/dist/core/shell-segments.js +169 -0
- package/dist/core/substrate/surface-match.d.ts +0 -9
- package/dist/core/substrate/surface-match.js +4 -160
- 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 -3
- package/dist/pi-extensions/canvas-bash-valve.js +75 -77
- package/dist/pi-extensions/canvas-inbox-watcher.js +0 -2
- package/package.json +1 -1
- package/runtime.lock.json +5 -5
|
@@ -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
|
+
}
|
|
@@ -21,6 +21,7 @@ import { resolve } from 'node:path';
|
|
|
21
21
|
import { getNode, updateNode } from './canvas/index.js';
|
|
22
22
|
import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
|
|
23
23
|
import { gitAsync } from './git.js';
|
|
24
|
+
import { proveBranchContained, upstreamTip } from './worktree-containment.js';
|
|
24
25
|
import { parseStatusPorcelain, planLandIntoCheckout, refDeleteTransactionStdin } from './worktree-landing.js';
|
|
25
26
|
import { WORKTREE_LOCK_WAIT_MS, checkoutPathForBranchInList, persistClosedWorktreeState, samePath, worktreeLockPathForCommonDir } from './worktree.js';
|
|
26
27
|
/** Escalating recheck interval, in minutes, indexed by consecutive refusal. The
|
|
@@ -101,95 +102,32 @@ function registeredCheckoutPath(porcelain, path, branch) {
|
|
|
101
102
|
}
|
|
102
103
|
return null;
|
|
103
104
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
async function containmentCandidates(cwd, wt) {
|
|
107
|
-
const candidates = [];
|
|
108
|
-
const localBaseRef = `refs/heads/${wt.base_ref}`;
|
|
109
|
-
const localBase = await revParseRef(cwd, localBaseRef);
|
|
110
|
-
if (localBase !== null)
|
|
111
|
-
candidates.push({ ref: localBaseRef, sha: localBase });
|
|
112
|
-
const upstream = await gitAsync(['rev-parse', '--symbolic-full-name', '--verify', `${wt.base_ref}@{upstream}`], cwd);
|
|
113
|
-
const upstreamRef = upstream.status === 0 && upstream.stdout.trim().startsWith('refs/')
|
|
114
|
-
? upstream.stdout.trim()
|
|
115
|
-
: `refs/remotes/origin/${wt.base_ref}`;
|
|
116
|
-
const upstreamSha = await revParseRef(cwd, upstreamRef);
|
|
117
|
-
if (upstreamSha !== null)
|
|
118
|
-
candidates.push({ ref: upstreamRef, sha: upstreamSha });
|
|
119
|
-
return candidates;
|
|
120
|
-
}
|
|
121
|
-
/** Does removing this branch lose content the candidate does not already have?
|
|
122
|
-
*
|
|
123
|
-
* The invariant is about CONTENT, not history. A rebase rewrites every SHA, so
|
|
124
|
-
* a fully-landed branch can look diverged; a squash-merge leaves no matching
|
|
125
|
-
* commit at all. An ancestry-only proof would refuse exactly the cases this
|
|
126
|
-
* sweep exists to clean up, so three layers run in increasing cost, and any one
|
|
127
|
-
* of them is sufficient:
|
|
128
|
-
*
|
|
129
|
-
* 1. ancestry — the tip is already reachable from the candidate.
|
|
130
|
-
* 2. patch identity — every commit not in the candidate by SHA has a
|
|
131
|
-
* patch-equivalent commit there (`git cherry`). The rebase case.
|
|
132
|
-
* 3. content no-op — merging the branch in would change nothing. The
|
|
133
|
-
* squash-merge case, and most remaining "looks bad but isn't" states.
|
|
134
|
-
*
|
|
135
|
-
* Only when all three fail does the branch genuinely carry unlanded content.
|
|
136
|
-
* Every layer fails CLOSED: a Git version without `merge-tree --write-tree`, an
|
|
137
|
-
* unreadable object, any non-zero exit — none of them prove anything, so the
|
|
138
|
-
* branch survives. */
|
|
139
|
-
async function proveContained(cwd, wt, branchSha) {
|
|
140
|
-
const candidates = await containmentCandidates(cwd, wt);
|
|
141
|
-
if (candidates.length === 0)
|
|
142
|
-
return null;
|
|
143
|
-
for (const candidate of candidates) {
|
|
144
|
-
if ((await gitAsync(['merge-base', '--is-ancestor', branchSha, candidate.sha], cwd)).status === 0) {
|
|
145
|
-
return { containingRef: candidate.ref, containingSha: candidate.sha, layer: 'ancestry' };
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
for (const candidate of candidates) {
|
|
149
|
-
const cherry = await gitAsync(['cherry', candidate.sha, branchSha], cwd);
|
|
150
|
-
if (cherry.status !== 0)
|
|
151
|
-
continue;
|
|
152
|
-
const lines = cherry.stdout.split('\n').map((l) => l.trim()).filter((l) => l !== '');
|
|
153
|
-
if (lines.every((line) => line.startsWith('-'))) {
|
|
154
|
-
return { containingRef: candidate.ref, containingSha: candidate.sha, layer: 'patch_identity' };
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
for (const candidate of candidates) {
|
|
158
|
-
const candidateTree = await revParseRef(cwd, `${candidate.sha}^{tree}`);
|
|
159
|
-
if (candidateTree === null)
|
|
160
|
-
continue;
|
|
161
|
-
const merged = await gitAsync(['merge-tree', '--write-tree', candidate.sha, branchSha], cwd);
|
|
162
|
-
if (merged.status !== 0)
|
|
163
|
-
continue; // conflict, or a Git too old for this flag
|
|
164
|
-
if (merged.stdout.split('\n')[0]?.trim() === candidateTree) {
|
|
165
|
-
return { containingRef: candidate.ref, containingSha: candidate.sha, layer: 'content_noop' };
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
return null;
|
|
169
|
-
}
|
|
105
|
+
// Content containment is shared with explicit close. A delivered branch is
|
|
106
|
+
// never rebased onto a local base merely because that base later diverged.
|
|
170
107
|
// Change detection
|
|
171
|
-
/** Base
|
|
172
|
-
* reads the same
|
|
173
|
-
* nothing that decided the refusal has moved. An unreadable checkout
|
|
174
|
-
* `null`, which never compares equal, so uncertainty always re-proves. */
|
|
108
|
+
/** Base, upstream, and branch tips plus checkout state as they are right now.
|
|
109
|
+
* A pass that reads the same values as the refusal that preceded it can stop
|
|
110
|
+
* there: nothing that decided the refusal has moved. An unreadable checkout
|
|
111
|
+
* records `null`, which never compares equal, so uncertainty always re-proves. */
|
|
175
112
|
async function observe(wt) {
|
|
176
113
|
const present = existsSync(wt.path);
|
|
177
114
|
const cwd = present ? wt.path : wt.repo_root;
|
|
178
115
|
const base = await revParseRef(cwd, `refs/heads/${wt.base_ref}`);
|
|
116
|
+
const upstream = await upstreamTip(cwd, wt.base_ref);
|
|
179
117
|
const branch = await revParseRef(cwd, `refs/heads/${wt.branch}`);
|
|
180
118
|
if (!present)
|
|
181
|
-
return { base, branch, checkout: 'absent' };
|
|
119
|
+
return { base, upstream: upstream?.sha ?? null, branch, checkout: 'absent' };
|
|
182
120
|
const head = await gitAsync(['rev-parse', 'HEAD'], wt.path);
|
|
183
121
|
const status = await gitAsync(['status', '--porcelain'], wt.path);
|
|
184
122
|
const checkout = head.status !== 0 || status.status !== 0
|
|
185
123
|
? null
|
|
186
124
|
: createHash('sha256').update(`${head.stdout.trim()}\n${status.stdout}`).digest('hex');
|
|
187
|
-
return { base, branch, checkout };
|
|
125
|
+
return { base, upstream: upstream?.sha ?? null, branch, checkout };
|
|
188
126
|
}
|
|
189
127
|
function sameObservation(a, b) {
|
|
190
128
|
if (a.checkout === null || b.checkout === null)
|
|
191
129
|
return false;
|
|
192
|
-
return a.base === b.base && a.branch === b.branch && a.checkout === b.checkout;
|
|
130
|
+
return a.base === b.base && a.upstream === b.upstream && a.branch === b.branch && a.checkout === b.checkout;
|
|
193
131
|
}
|
|
194
132
|
// Recording an unfinished pass
|
|
195
133
|
/** Persist why this pass did not finish, with the fingerprint it decided
|
|
@@ -336,13 +274,13 @@ export async function reconcileManagedWorktree(nodeId, guard, now = Date.now())
|
|
|
336
274
|
return { status: 'skipped', reason: 'already_reconciled' };
|
|
337
275
|
const cwd = existsSync(wt.path) ? wt.path : wt.repo_root;
|
|
338
276
|
if (!existsSync(cwd)) {
|
|
339
|
-
return
|
|
277
|
+
return finish(nodeId, wt, { status: 'refused', reason: 'repo_unavailable', detail: `neither the recorded checkout nor repository root exists, so ${wt.branch} cannot be proved absent` }, { base: null, upstream: null, branch: null, checkout: null }, now, guard);
|
|
340
278
|
}
|
|
341
279
|
const commonDir = await commonGitDirAsync(cwd);
|
|
342
280
|
if (commonDir === null) {
|
|
343
|
-
return finish(nodeId, wt, { status: 'failed', reason: 'git_dir_unreadable', detail: `could not resolve the git common dir from ${cwd}` }, { base: null, branch: null, checkout: null }, now, guard);
|
|
281
|
+
return finish(nodeId, wt, { status: 'failed', reason: 'git_dir_unreadable', detail: `could not resolve the git common dir from ${cwd}` }, { base: null, upstream: null, branch: null, checkout: null }, now, guard);
|
|
344
282
|
}
|
|
345
|
-
let observed = { base: null, branch: null, checkout: null };
|
|
283
|
+
let observed = { base: null, upstream: null, branch: null, checkout: null };
|
|
346
284
|
let outcome;
|
|
347
285
|
try {
|
|
348
286
|
outcome = await withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
|
|
@@ -412,7 +350,7 @@ async function concludeAbsentCheckout(nodeId, wt, observed, guard) {
|
|
|
412
350
|
if (elsewhere !== null) {
|
|
413
351
|
return { status: 'refused', reason: 'branch_checked_out_elsewhere', detail: `${wt.branch} is checked out at ${elsewhere}` };
|
|
414
352
|
}
|
|
415
|
-
const proof = await
|
|
353
|
+
const proof = await proveBranchContained(admin, wt, observed.branch);
|
|
416
354
|
if (proof === null) {
|
|
417
355
|
return { status: 'refused', reason: 'unlanded_work', detail: `${wt.branch} carries content no base or upstream ref contains; its checkout is already gone, so the branch is the only copy` };
|
|
418
356
|
}
|
|
@@ -477,7 +415,7 @@ async function reconcilePresentCheckout(nodeId, wt, guard) {
|
|
|
477
415
|
// is preserved, never deleted, unlike the ordinary path below.
|
|
478
416
|
return persistComplete(nodeId, wt, guard);
|
|
479
417
|
}
|
|
480
|
-
let proof = await
|
|
418
|
+
let proof = await proveBranchContained(wt.path, wt, branchSha);
|
|
481
419
|
let stash;
|
|
482
420
|
if (proof === null && wt.land_intent !== undefined) {
|
|
483
421
|
const landed = await finishBlockedLand(wt, list.stdout, guard);
|
|
@@ -485,7 +423,7 @@ async function reconcilePresentCheckout(nodeId, wt, guard) {
|
|
|
485
423
|
return landed.ineligible === true ? NODE_REVIVED : { status: 'refused', reason: 'land_blocked', detail: landed.detail };
|
|
486
424
|
branchSha = landed.landedSha;
|
|
487
425
|
stash = landed.stash;
|
|
488
|
-
proof = await
|
|
426
|
+
proof = await proveBranchContained(wt.path, wt, branchSha);
|
|
489
427
|
}
|
|
490
428
|
if (proof === null) {
|
|
491
429
|
return { status: 'refused', reason: 'unlanded_work', detail: `${wt.branch} carries commits its base does not contain, and this node never asked to land them` };
|
package/dist/core/worktree.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export declare function managedWorktreesRoot(): string;
|
|
|
14
14
|
export declare function managedWorktreePath(nodeId: string): string;
|
|
15
15
|
export declare function hasOpenManagedWorktree(node: NodeMeta | null | undefined): boolean;
|
|
16
16
|
export declare function openManagedWorktreeForNode(nodeId: string): ManagedWorktree | null;
|
|
17
|
+
export declare function isManagedWorktreeBase(repoRoot: string): boolean;
|
|
17
18
|
/** Shared parse for a `git worktree list --porcelain` blob already in hand —
|
|
18
19
|
* callers that must not throw on a read failure (an absent-path proof that
|
|
19
20
|
* needs to fail closed rather than error) call `gitSync` themselves and pass
|
package/dist/core/worktree.js
CHANGED
|
@@ -51,7 +51,7 @@ function repoRootFor(cwd) {
|
|
|
51
51
|
}
|
|
52
52
|
return result.stdout.trim();
|
|
53
53
|
}
|
|
54
|
-
function isManagedWorktreeBase(repoRoot) {
|
|
54
|
+
export function isManagedWorktreeBase(repoRoot) {
|
|
55
55
|
const path = relative(canonicalPath(managedWorktreesRoot()), canonicalPath(repoRoot));
|
|
56
56
|
return path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path);
|
|
57
57
|
}
|
|
@@ -49,15 +49,17 @@ test('a Unix socket bind failure rejects readiness and releases daemon ownership
|
|
|
49
49
|
assert.equal(existsSync(pidfile), false, 'failed readiness removes the pidfile mirror');
|
|
50
50
|
assert.equal(existsSync(socketPath), true, 'the pre-existing directory was never mistaken for a serving socket');
|
|
51
51
|
assert.match(readFileSync(join(canvasHome, 'crtrd.log'), 'utf8'), /api\.server\.failed/, 'the bind failure is recorded for cold-start diagnostics');
|
|
52
|
+
rmSync(socketPath, { recursive: true, force: true });
|
|
52
53
|
writeFileSync(pidfile, String(process.pid));
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
existing_pid: process.pid,
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
54
|
+
try {
|
|
55
|
+
const result = await spawnDaemon();
|
|
56
|
+
assert.deepEqual({ started: result.started, existing_pid: result.existing_pid, running: result.running, serving: result.serving }, { started: false, existing_pid: process.pid, running: true, serving: false }, 'a live owner with an unavailable socket remains in place');
|
|
57
|
+
assert.match(result.probe_error ?? '', /ENOENT|ECONNREFUSED/, 'the result retains the actual failed probe');
|
|
58
|
+
process.kill(process.pid, 0);
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
rmSync(pidfile, { force: true });
|
|
62
|
+
}
|
|
61
63
|
const retryClaim = claimDaemonOwnership('post-api-bind-failure');
|
|
62
64
|
assert.equal(retryClaim.claimed, true, 'failed readiness releases the authoritative ownership claim');
|
|
63
65
|
if (retryClaim.claimed) {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
import { test, before, after } from 'node:test';
|
|
27
27
|
import assert from 'node:assert/strict';
|
|
28
28
|
import { spawnSync } from 'node:child_process';
|
|
29
|
-
import { statSync, existsSync, readFileSync, mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
29
|
+
import { chmodSync, statSync, existsSync, readFileSync, mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
30
30
|
import { tmpdir } from 'node:os';
|
|
31
31
|
import { join, dirname } from 'node:path';
|
|
32
32
|
import WebSocket from 'ws';
|
|
@@ -133,6 +133,45 @@ test('A2: POST /nodes boots a live broker; GET /nodes/{id} shows active + live p
|
|
|
133
133
|
assert.ok(meta?.pi_pid != null && isPidAlive(meta.pi_pid), 'row records a live broker pid');
|
|
134
134
|
assert.ok(existsSync(h.brokerSock(id)), 'view.sock exists for the live broker');
|
|
135
135
|
});
|
|
136
|
+
function installBlockedStartHook(nodeId) {
|
|
137
|
+
const root = join(h.agentHome, '.crouter', 'plugins', `blocked-start-${nodeId}`);
|
|
138
|
+
const started = join(root, 'started');
|
|
139
|
+
const release = join(root, 'release');
|
|
140
|
+
mkdirSync(join(root, '.crouter-plugin'), { recursive: true });
|
|
141
|
+
writeFileSync(join(root, '.crouter-plugin', 'plugin.json'), JSON.stringify({
|
|
142
|
+
name: `blocked-start-${nodeId}`,
|
|
143
|
+
version: '0.1.0',
|
|
144
|
+
description: 'message acknowledgment fixture',
|
|
145
|
+
hooks: 'hooks.json',
|
|
146
|
+
hookExecutable: 'bin/hook.js',
|
|
147
|
+
}));
|
|
148
|
+
writeFileSync(join(root, 'hooks.json'), JSON.stringify({
|
|
149
|
+
schemaVersion: 2,
|
|
150
|
+
lifecycle: [{ event: 'node:start', phase: 'on', op: 'block', description: 'block target launch', effects: ['waits for test release'] }],
|
|
151
|
+
}));
|
|
152
|
+
const executable = join(root, 'bin', 'hook.js');
|
|
153
|
+
mkdirSync(join(root, 'bin'), { recursive: true });
|
|
154
|
+
writeFileSync(executable, `#!/usr/bin/env node
|
|
155
|
+
const { existsSync, writeFileSync } = require('node:fs');
|
|
156
|
+
let input = '';
|
|
157
|
+
process.stdin.on('data', (chunk) => { input += chunk; });
|
|
158
|
+
process.stdin.on('end', () => {
|
|
159
|
+
const request = JSON.parse(input);
|
|
160
|
+
if (request.node.id !== ${JSON.stringify(nodeId)}) {
|
|
161
|
+
process.stdout.write(JSON.stringify({ protocolVersion: 1, ok: true }));
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
writeFileSync(${JSON.stringify(started)}, 'started');
|
|
165
|
+
const timer = setInterval(() => {
|
|
166
|
+
if (!existsSync(${JSON.stringify(release)})) return;
|
|
167
|
+
clearInterval(timer);
|
|
168
|
+
process.stdout.write(JSON.stringify({ protocolVersion: 1, ok: true }));
|
|
169
|
+
}, 10);
|
|
170
|
+
});
|
|
171
|
+
`);
|
|
172
|
+
chmodSync(executable, 0o755);
|
|
173
|
+
return { started, release };
|
|
174
|
+
}
|
|
136
175
|
// A3 — POST .../messages appends inbox.jsonl; POST .../reports {tier:'final'}
|
|
137
176
|
// writes the report, notifies subscribers, transitions the row
|
|
138
177
|
test('A3: messages append inbox.jsonl; final report writes + notifies subscriber + transitions row', async () => {
|
|
@@ -153,6 +192,36 @@ test('A3: messages append inbox.jsonl; final report writes + notifies subscriber
|
|
|
153
192
|
assert.equal(h.node(B)?.status, 'done', 'row status is done after final');
|
|
154
193
|
await assert.rejects(() => client.pushReport(B, { tier: 'final', delivery_tier: 'deferred', body: 'invalid tiered final' }), (error) => error instanceof ApiError && error.code === 'usage' && error.message === 'delivery_tier is only valid for update reports', 'the API rejects a delivery tier on final before it can alter final delivery');
|
|
155
194
|
});
|
|
195
|
+
test('A3b: a durable send acknowledges while the lifecycle tick is blocked launching its idle target', async () => {
|
|
196
|
+
const target = h.fabricateBrokerNode({ lifecycle: 'resident', status: 'idle', intent: 'idle-release' });
|
|
197
|
+
const hook = installBlockedStartHook(target);
|
|
198
|
+
const inboxFile = inboxPath(target);
|
|
199
|
+
const before = countLines(inboxFile);
|
|
200
|
+
const sending = client.sendMessage(target, { body: 'wake after durable acknowledgment' });
|
|
201
|
+
let tick;
|
|
202
|
+
try {
|
|
203
|
+
await h.waitFor(() => countLines(inboxFile) === before + 1, { label: 'durable inbox append' });
|
|
204
|
+
assert.equal(h.node(target)?.cycles ?? 0, 0, 'the send has not launched the target');
|
|
205
|
+
tick = h.tick();
|
|
206
|
+
await h.waitFor(() => existsSync(hook.started), { label: 'blocked lifecycle launch' });
|
|
207
|
+
const acknowledged = await Promise.race([
|
|
208
|
+
sending,
|
|
209
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('durable send waited for recipient launch')), 500)),
|
|
210
|
+
]);
|
|
211
|
+
assert.equal(acknowledged.delivered, true, 'the API acknowledges the durable append');
|
|
212
|
+
assert.equal(acknowledged.revived, false, 'the response honestly reports no synchronous revive');
|
|
213
|
+
assert.equal(countLines(inboxFile), before + 1, 'exactly one inbox entry is durable while launch is blocked');
|
|
214
|
+
writeFileSync(hook.release, 'release');
|
|
215
|
+
await tick;
|
|
216
|
+
assert.equal(h.node(target)?.cycles, 1, 'the one queued entry drove lifecycle revival');
|
|
217
|
+
assert.equal(countLines(inboxFile), before + 1, 'revival did not append a second inbox entry');
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
if (!existsSync(hook.release))
|
|
221
|
+
writeFileSync(hook.release, 'release');
|
|
222
|
+
await tick;
|
|
223
|
+
}
|
|
224
|
+
});
|
|
156
225
|
// A4 — WS attach reconstructs the same settled broker snapshot as a direct
|
|
157
226
|
// ViewSocketClient; ?revive=0 on a dormant node → 409 without launching a broker
|
|
158
227
|
test('A4a: WS attach welcome.snapshot is byte-identical to a direct ViewSocketClient snapshot', async () => {
|
|
@@ -59,7 +59,7 @@ async function handleStop(ctx) {
|
|
|
59
59
|
throw new ApiError(404, 'job_not_found', `background job ${jobId} for ${nodeId} is no longer running`, { log_path: stopped.logPath });
|
|
60
60
|
}
|
|
61
61
|
if (stopped.kind === 'not-stoppable') {
|
|
62
|
-
throw new ApiError(409, 'job_not_stoppable', `job ${jobId} recorded no process
|
|
62
|
+
throw new ApiError(409, 'job_not_stoppable', `job ${jobId} recorded no trusted process identity`, { log_path: stopped.logPath });
|
|
63
63
|
}
|
|
64
64
|
// Match `crtr node bash kill`: retire the job, then send an urgent durable
|
|
65
65
|
// notice to the owning node. The terminal path sends that notice through the
|
|
@@ -16,6 +16,7 @@ import { appendSituationalContext, formatSituationalProse } from '../../../core/
|
|
|
16
16
|
import { formatDataCard } from '../../../shared/generated-context.js';
|
|
17
17
|
import { hasNoNaturalCycle } from '../../../core/runtime/revive-all.js';
|
|
18
18
|
import { recordPendingParkActivity } from '../../park-pending.js';
|
|
19
|
+
import { wantsExecution } from '../../reconcilers/node-lifecycle/wants-execution.js';
|
|
19
20
|
import { hasFreshGroundState } from '../../../core/runtime/revive.js';
|
|
20
21
|
import { notFound, usage } from '../../../core/errors.js';
|
|
21
22
|
import { InputError } from '../../../core/io.js';
|
|
@@ -355,13 +356,14 @@ async function handleMessage(ctx) {
|
|
|
355
356
|
// owes a thaw; consume its deadline when that durable future wake arrives.
|
|
356
357
|
if (entry.tier !== 'deferred' || meta.frozen_at !== null)
|
|
357
358
|
cancelCronsOnWake(id);
|
|
358
|
-
// A wake-capable
|
|
359
|
-
//
|
|
360
|
-
//
|
|
361
|
-
//
|
|
359
|
+
// A wake-capable entry for an active or idle target is admitted by the
|
|
360
|
+
// lifecycle tick. Reopen delivery preserves this handler's synchronous wake
|
|
361
|
+
// authority; a terminal-lifecycle row also needs it because it has no later
|
|
362
|
+
// natural cycle to consume the entry.
|
|
362
363
|
let revived = false;
|
|
363
364
|
let frozen = false;
|
|
364
|
-
|
|
365
|
+
const needsSynchronousWake = req.reopen || current.lifecycle === 'terminal' || !wantsExecution(current);
|
|
366
|
+
if (needsSynchronousWake && entry.tier !== 'deferred' && !paused && !isBrokerLive(current)) {
|
|
365
367
|
try {
|
|
366
368
|
// The entry is already durable, so a wake denied for capacity is only
|
|
367
369
|
// delayed: the row freezes and the tick relaunches it — at which point
|