@elecnix/bellwether 0.1.2 → 0.1.3
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/README.md +56 -6
- package/dist/cli.js +2 -1
- package/dist/core/adopt.js +59 -0
- package/dist/core/brief.js +61 -0
- package/dist/core/child-lock.js +84 -0
- package/dist/core/classifier.js +38 -4
- package/dist/core/herdr-client.js +24 -10
- package/dist/core/inactivity.js +31 -0
- package/dist/core/label.js +7 -0
- package/dist/core/machine.js +134 -0
- package/dist/core/mcp-config.js +47 -0
- package/dist/core/outbox.js +72 -7
- package/dist/core/paths.js +14 -0
- package/dist/core/registry.js +40 -4
- package/dist/core/report.js +48 -3
- package/dist/core/resume.js +210 -0
- package/dist/core/retire.js +416 -0
- package/dist/core/send.js +17 -0
- package/dist/core/spawn-resume.js +96 -0
- package/dist/core/spawn.js +140 -42
- package/dist/core/startup-dialogs.js +120 -0
- package/dist/core/transcript.js +8 -0
- package/dist/core/types.js +2 -1
- package/dist/core/watcher.js +317 -89
- package/dist/daemon/client.js +90 -8
- package/dist/daemon/main.js +6 -0
- package/dist/daemon/protocol.js +17 -3
- package/dist/daemon/server.js +1 -1
- package/dist/daemon/service.js +8 -4
- package/dist/integrations/claude/channel.js +17 -5
- package/dist/integrations/pi/extension.js +5 -3
- package/dist/integrations/tools.js +135 -41
- package/package.json +4 -4
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// Retirement: a child asks to be retired, and the daemon cleans up after it.
|
|
2
|
+
//
|
|
3
|
+
// The request runs while the child is alive, so it can tell the child which
|
|
4
|
+
// checks pass now. It writes the intent on the child record and removes
|
|
5
|
+
// nothing. The daemon does the cleaning once herdr reports the pane gone,
|
|
6
|
+
// because the daemon already holds the registry, watches every pane and
|
|
7
|
+
// outlives every child. No other process takes part.
|
|
8
|
+
//
|
|
9
|
+
// The cleanup removes nothing until every condition holds, records its outcome
|
|
10
|
+
// on the child record, and appends one line to retire.log. Each step checks the
|
|
11
|
+
// state it leaves behind, so a daemon restarted part of the way through
|
|
12
|
+
// finishes the job without doing any step twice.
|
|
13
|
+
import { execFile } from 'node:child_process';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { LOCAL_HOST, hostOf } from './machine.js';
|
|
17
|
+
import { bellwetherHome } from './paths.js';
|
|
18
|
+
import { childOfCaller } from './report.js';
|
|
19
|
+
import { readParent, updateChild } from './registry.js';
|
|
20
|
+
export const RETIRE_TOOL = 'request_retirement';
|
|
21
|
+
/** A request refused outright: nothing is written, and the error says why. */
|
|
22
|
+
export class RetireRefused extends Error {
|
|
23
|
+
constructor(message) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = 'RetireRefused';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** The one log line per outcome, beside the daemon's own state. */
|
|
29
|
+
export function retireLogPath() {
|
|
30
|
+
return path.join(bellwetherHome(), 'retire.log');
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The bounds no request and no cleanup may cross: a child this daemon did not
|
|
34
|
+
* spawn, a child on another host, a child with no working directory. Returns
|
|
35
|
+
* the refusal, or undefined when the child is in bounds.
|
|
36
|
+
*/
|
|
37
|
+
function outOfBounds(child) {
|
|
38
|
+
if (child.origin === 'adopt')
|
|
39
|
+
return `${child.name} was adopted, not spawned by Bellwether, so Bellwether never removes its worktree. Remove it by hand with \`git worktree remove\` once its work is safe.`;
|
|
40
|
+
if (hostOf(child) !== LOCAL_HOST)
|
|
41
|
+
return `${child.name} runs on machine ${hostOf(child)}, and this daemon only cleans up after children on its own machine. Remove the worktree on ${hostOf(child)} by hand.`;
|
|
42
|
+
if (!child.cwd)
|
|
43
|
+
return `${child.name} has no working directory on its record, so there is no worktree to retire.`;
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
function mainRefusal(worktree, why) {
|
|
47
|
+
return `${worktree} is the repository's main worktree (${why}), and Bellwether never removes a main worktree, whoever asks. Nothing was written. Work in a worktree of your own to be retired with it.`;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The child-facing request. It runs the checks it can run while the child is
|
|
51
|
+
* alive, writes `retireRequestedAt` and the intent on the child record, and
|
|
52
|
+
* returns one line per check. It removes nothing.
|
|
53
|
+
*/
|
|
54
|
+
export async function requestRetirement(caller, ops, reason) {
|
|
55
|
+
if (!caller.childId) {
|
|
56
|
+
throw new RetireRefused(`${RETIRE_TOOL} needs a child id, and this session sent none: its environment carries no BELLWETHER_CHILD, so it is not a child Bellwether spawned. Nothing was written.`);
|
|
57
|
+
}
|
|
58
|
+
const found = childOfCaller(caller);
|
|
59
|
+
if (!found)
|
|
60
|
+
throw new RetireRefused(`${RETIRE_TOOL} was called for child id ${caller.childId}, which no registry on this machine holds, so there is nothing to retire. Nothing was written.`);
|
|
61
|
+
const { parent, child } = found;
|
|
62
|
+
const bounds = outOfBounds(child);
|
|
63
|
+
if (bounds)
|
|
64
|
+
throw new RetireRefused(`${bounds} Nothing was written.`);
|
|
65
|
+
const facts = await ops.inspect(child.cwd);
|
|
66
|
+
if ('error' in facts)
|
|
67
|
+
throw new RetireRefused(`${child.cwd} is not a git worktree Bellwether can retire: ${facts.error}. Nothing was written.`);
|
|
68
|
+
if (facts.main)
|
|
69
|
+
throw new RetireRefused(mainRefusal(facts.worktree, facts.main));
|
|
70
|
+
if (!facts.branch)
|
|
71
|
+
throw new RetireRefused(`${facts.worktree} has no branch checked out (detached HEAD at ${facts.head.slice(0, 12)}), so Bellwether cannot tell whether its work is safe. Check out a branch, then ask again. Nothing was written.`);
|
|
72
|
+
const passed = [];
|
|
73
|
+
const failing = [];
|
|
74
|
+
const dirty = await ops.dirty(facts.worktree);
|
|
75
|
+
(dirty.length ? failing : passed).push(dirty.length ? `the worktree has ${dirty.length} uncommitted path(s): ${dirty.slice(0, 5).join(', ')}` : 'the worktree is clean');
|
|
76
|
+
const stashes = await ops.stashes(facts.repo, facts.branch);
|
|
77
|
+
(stashes.length ? failing : passed).push(stashes.length ? `${stashes.length} stash entr${stashes.length === 1 ? 'y' : 'ies'} on ${facts.branch}` : 'no stash on the branch');
|
|
78
|
+
const safety = await ops.safety({ repo: facts.repo, worktree: facts.worktree, branch: facts.branch, defaultBranch: facts.defaultBranch });
|
|
79
|
+
(safety.safe ? passed : failing).push(safety.how);
|
|
80
|
+
const intent = { worktree: facts.worktree, repo: facts.repo, branch: facts.branch, head: facts.head, ...(facts.defaultBranch ? { defaultBranch: facts.defaultBranch } : {}), ...(reason ? { reason } : {}) };
|
|
81
|
+
const now = new Date().toISOString();
|
|
82
|
+
updateChild(parent.id, child.id, (entry) => {
|
|
83
|
+
// A child resumed after an earlier retirement asks afresh.
|
|
84
|
+
if (entry.retireOutcome)
|
|
85
|
+
clearRetirement(entry);
|
|
86
|
+
entry.retireRequestedAt ??= now;
|
|
87
|
+
entry.retireIntent = intent;
|
|
88
|
+
});
|
|
89
|
+
const lines = [`Retirement requested for ${child.name}: ${facts.worktree} on branch ${facts.branch}. Nothing has been removed.`];
|
|
90
|
+
lines.push(`Passed now: ${passed.length ? passed.join('; ') : 'none'}.`);
|
|
91
|
+
if (failing.length)
|
|
92
|
+
lines.push(`Failing now: ${failing.join('; ')}. Fix these before you exit, or the daemon will refuse and leave everything in place.`);
|
|
93
|
+
lines.push('After your pane is gone, the daemon checks again that the pane and tab are gone, that the worktree is not a main worktree, is clean and has no stash, that the work is safe, and that no process works inside it. Only then does it remove the worktree and delete the branch.');
|
|
94
|
+
lines.push('Close your tab to finish.');
|
|
95
|
+
return lines.join('\n');
|
|
96
|
+
}
|
|
97
|
+
/** Drop every retirement field, for a child that is brought back. */
|
|
98
|
+
export function clearRetirement(child) {
|
|
99
|
+
delete child.retireRequestedAt;
|
|
100
|
+
delete child.retireIntent;
|
|
101
|
+
delete child.retireStage;
|
|
102
|
+
delete child.retiredAt;
|
|
103
|
+
delete child.retireOutcome;
|
|
104
|
+
delete child.retireReason;
|
|
105
|
+
}
|
|
106
|
+
/** Whether a child has asked to be retired and the cleanup has not finished. */
|
|
107
|
+
export function retirementPending(child) {
|
|
108
|
+
return Boolean(child.retireRequestedAt && !child.retireOutcome);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The daemon's cleanup for one child that asked to be retired. It runs after
|
|
112
|
+
* the watcher marks the child exited, and again when a daemon starts, so an
|
|
113
|
+
* unfinished retirement finishes. A child still alive is left alone.
|
|
114
|
+
*/
|
|
115
|
+
export async function reapChild(parentId, childId, deps) {
|
|
116
|
+
const log = deps.log ?? (() => { });
|
|
117
|
+
const child = readParent(parentId)?.children.find((entry) => entry.id === childId);
|
|
118
|
+
if (!child || !retirementPending(child))
|
|
119
|
+
return { outcome: 'skipped' };
|
|
120
|
+
if (!child.exitedAt)
|
|
121
|
+
return { outcome: 'skipped' };
|
|
122
|
+
const refuse = (reason) => {
|
|
123
|
+
finish(parentId, child, 'refused', reason);
|
|
124
|
+
log(`retire ${child.name}: refused: ${reason}`);
|
|
125
|
+
return { outcome: 'refused', reason };
|
|
126
|
+
};
|
|
127
|
+
const bounds = outOfBounds(child);
|
|
128
|
+
if (bounds)
|
|
129
|
+
return refuse(`out of bounds: ${bounds}`);
|
|
130
|
+
const intent = child.retireIntent;
|
|
131
|
+
if (!intent)
|
|
132
|
+
return refuse(`no intent: the record of ${child.name} asks for retirement but names no worktree, so nothing was touched. Ask again from a live child.`);
|
|
133
|
+
// 1. The pane and the tab are gone from herdr.
|
|
134
|
+
let live;
|
|
135
|
+
try {
|
|
136
|
+
live = await deps.paneOrTabLive(child);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
const reason = `herdr could not be asked whether pane ${child.paneId} is gone (${String(error)}); the retirement waits for the next exit event or daemon start`;
|
|
140
|
+
log(`retire ${child.name}: ${reason}`);
|
|
141
|
+
return { outcome: 'pending', reason };
|
|
142
|
+
}
|
|
143
|
+
if (live) {
|
|
144
|
+
const reason = `pane ${child.paneId} or tab ${child.tabId ?? '?'} is still in herdr; the retirement waits until both are gone`;
|
|
145
|
+
log(`retire ${child.name}: ${reason}`);
|
|
146
|
+
return { outcome: 'pending', reason };
|
|
147
|
+
}
|
|
148
|
+
const { ops } = deps;
|
|
149
|
+
const worktreeDone = child.retireStage === 'worktree-removed' || child.retireStage === 'branch-deleted' || !(await ops.worktreeExists(intent.repo, intent.worktree));
|
|
150
|
+
if (!worktreeDone) {
|
|
151
|
+
// 2. Not a main worktree, the same one the child asked about, clean, no stash.
|
|
152
|
+
const facts = await ops.inspect(intent.worktree);
|
|
153
|
+
if ('error' in facts)
|
|
154
|
+
return refuse(`condition 2 (worktree): ${intent.worktree} is no longer a git worktree Bellwether can read: ${facts.error}. Look at it by hand.`);
|
|
155
|
+
if (facts.main)
|
|
156
|
+
return refuse(`condition 2 (main worktree): ${mainRefusal(facts.worktree, facts.main)}`);
|
|
157
|
+
if (path.resolve(facts.worktree) !== path.resolve(intent.worktree) || path.resolve(facts.repo) !== path.resolve(intent.repo)) {
|
|
158
|
+
return refuse(`condition 2 (worktree): ${intent.worktree} now belongs to ${facts.repo} at ${facts.worktree}, not the worktree the child asked about. Nothing was touched; look at it by hand.`);
|
|
159
|
+
}
|
|
160
|
+
if (facts.branch !== intent.branch)
|
|
161
|
+
return refuse(`condition 2 (branch): ${intent.worktree} has ${facts.branch ?? 'a detached HEAD'} checked out, not ${intent.branch}, which the child asked to retire. Nothing was touched; look at it by hand.`);
|
|
162
|
+
const dirty = await ops.dirty(intent.worktree);
|
|
163
|
+
if (dirty.length)
|
|
164
|
+
return refuse(`condition 2 (clean): ${intent.worktree} has ${dirty.length} uncommitted path(s): ${dirty.slice(0, 5).join(', ')}. Commit or discard them, then remove it with \`git worktree remove ${intent.worktree}\`.`);
|
|
165
|
+
const stashes = await ops.stashes(intent.repo, intent.branch);
|
|
166
|
+
if (stashes.length)
|
|
167
|
+
return refuse(`condition 2 (stash): ${stashes.length} stash entr${stashes.length === 1 ? 'y' : 'ies'} on ${intent.branch} (${stashes[0]}). Apply or drop them, then remove the worktree by hand.`);
|
|
168
|
+
}
|
|
169
|
+
// 3. The work is safe. Checked again after the worktree is gone, because the
|
|
170
|
+
// branch is deleted only when it holds nothing that exists nowhere else.
|
|
171
|
+
const branchLeft = child.retireStage !== 'branch-deleted' && (await ops.branchExists(intent.repo, intent.branch));
|
|
172
|
+
if (branchLeft) {
|
|
173
|
+
const safety = await ops.safety({ repo: intent.repo, worktree: worktreeDone ? undefined : intent.worktree, branch: intent.branch, defaultBranch: intent.defaultBranch });
|
|
174
|
+
if (!safety.safe)
|
|
175
|
+
return refuse(`condition 3 (work is safe): ${safety.how}. Merge the branch, or push it and merge or close its pull request, then remove the worktree and the branch by hand.`);
|
|
176
|
+
}
|
|
177
|
+
// 4. No process works inside the path. A shell can take a moment to leave
|
|
178
|
+
// after its pane exits, so look a few times before refusing.
|
|
179
|
+
if (!worktreeDone) {
|
|
180
|
+
const tries = (deps.busyRetries ?? 3) + 1;
|
|
181
|
+
let pids = [];
|
|
182
|
+
for (let attempt = 0; attempt < tries; attempt += 1) {
|
|
183
|
+
pids = await ops.busy(intent.worktree);
|
|
184
|
+
if (pids === undefined || pids.length === 0)
|
|
185
|
+
break;
|
|
186
|
+
if (attempt < tries - 1)
|
|
187
|
+
await new Promise((resolve) => setTimeout(resolve, deps.busyDelayMs ?? 500));
|
|
188
|
+
}
|
|
189
|
+
if (pids === undefined)
|
|
190
|
+
return refuse(`condition 4 (no process inside): this machine offers neither /proc nor lsof, so Bellwether cannot tell whether a process works in ${intent.worktree}. Check by hand, then remove it.`);
|
|
191
|
+
if (pids.length)
|
|
192
|
+
return refuse(`condition 4 (no process inside): process(es) ${pids.join(', ')} have their working directory in ${intent.worktree}. Stop them, then remove the worktree by hand.`);
|
|
193
|
+
}
|
|
194
|
+
// 5. Remove, delete, verify. Each stage is written as it completes, so a
|
|
195
|
+
// restart skips what is done.
|
|
196
|
+
try {
|
|
197
|
+
if (!worktreeDone) {
|
|
198
|
+
await ops.removeWorktree(intent.repo, intent.worktree);
|
|
199
|
+
updateChild(parentId, child.id, (entry) => {
|
|
200
|
+
entry.retireStage = 'worktree-removed';
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
if (branchLeft)
|
|
204
|
+
await ops.deleteBranch(intent.repo, intent.branch);
|
|
205
|
+
updateChild(parentId, child.id, (entry) => {
|
|
206
|
+
entry.retireStage = 'branch-deleted';
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
return refuse(`condition 5 (removal): git refused: ${error.message.trim()}. Look at ${intent.worktree} and branch ${intent.branch} by hand.`);
|
|
211
|
+
}
|
|
212
|
+
const pathLeft = (await ops.worktreeExists(intent.repo, intent.worktree)) || fs.existsSync(intent.worktree);
|
|
213
|
+
const branchStill = await ops.branchExists(intent.repo, intent.branch);
|
|
214
|
+
if (pathLeft || branchStill) {
|
|
215
|
+
return refuse(`condition 5 (verify): after removal ${[pathLeft ? `${intent.worktree} still exists` : '', branchStill ? `branch ${intent.branch} still exists` : ''].filter(Boolean).join(' and ')}. Remove what is left by hand.`);
|
|
216
|
+
}
|
|
217
|
+
finish(parentId, child, 'removed');
|
|
218
|
+
log(`retire ${child.name}: removed ${intent.worktree} and branch ${intent.branch}`);
|
|
219
|
+
return { outcome: 'removed' };
|
|
220
|
+
}
|
|
221
|
+
/** Record the outcome on the child record first, then append the log line. */
|
|
222
|
+
function finish(parentId, child, outcome, reason) {
|
|
223
|
+
const at = new Date().toISOString();
|
|
224
|
+
updateChild(parentId, child.id, (entry) => {
|
|
225
|
+
entry.retiredAt = at;
|
|
226
|
+
entry.retireOutcome = outcome;
|
|
227
|
+
if (reason)
|
|
228
|
+
entry.retireReason = reason;
|
|
229
|
+
else
|
|
230
|
+
delete entry.retireReason;
|
|
231
|
+
});
|
|
232
|
+
const line = { at, parent: parentId, child: child.id, name: child.name, outcome, worktree: child.retireIntent?.worktree, branch: child.retireIntent?.branch, ...(reason ? { reason } : {}) };
|
|
233
|
+
fs.mkdirSync(path.dirname(retireLogPath()), { recursive: true });
|
|
234
|
+
fs.appendFileSync(retireLogPath(), `${JSON.stringify(line)}\n`);
|
|
235
|
+
}
|
|
236
|
+
/** Run a command without a shell, without a prompt, and never throw on a non-zero exit. */
|
|
237
|
+
export const runCommand = (command, args, cwd) => new Promise((resolve) => {
|
|
238
|
+
execFile(command, args, { cwd, timeout: 30_000, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GH_PROMPT_DISABLED: '1', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' } }, (error, stdout, stderr) => {
|
|
239
|
+
const code = error ? (typeof error.code === 'number' ? (error.code) : 127) : 0;
|
|
240
|
+
resolve({ code, stdout: String(stdout), stderr: String(stderr) || (error && code === 127 ? error.message : '') });
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
function realpath(dir) {
|
|
244
|
+
try {
|
|
245
|
+
return fs.realpathSync(dir);
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return path.resolve(dir);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function inside(candidate, dir) {
|
|
252
|
+
return candidate === dir || candidate.startsWith(`${dir}${path.sep}`);
|
|
253
|
+
}
|
|
254
|
+
/** The retirement operations on the real git, gh and process table. */
|
|
255
|
+
export function realRetireOps(options = {}) {
|
|
256
|
+
const run = options.run ?? runCommand;
|
|
257
|
+
const proc = 'proc' in options ? options.proc : fs.existsSync('/proc/self/cwd') ? '/proc' : undefined;
|
|
258
|
+
const git = (repo, args) => run('git', [`--git-dir=${repo}`, ...args]);
|
|
259
|
+
const gitIn = (dir, args) => run('git', ['-C', dir, ...args]);
|
|
260
|
+
const defaultBranchOf = async (repo) => {
|
|
261
|
+
const head = await git(repo, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']);
|
|
262
|
+
if (head.code === 0 && head.stdout.trim())
|
|
263
|
+
return head.stdout.trim();
|
|
264
|
+
for (const ref of ['origin/main', 'origin/master', 'main', 'master']) {
|
|
265
|
+
const remote = ref.startsWith('origin/');
|
|
266
|
+
const found = await git(repo, ['show-ref', '--verify', '--quiet', remote ? `refs/remotes/${ref}` : `refs/heads/${ref}`]);
|
|
267
|
+
if (found.code === 0)
|
|
268
|
+
return ref;
|
|
269
|
+
}
|
|
270
|
+
return undefined;
|
|
271
|
+
};
|
|
272
|
+
const listWorktrees = async (repo) => {
|
|
273
|
+
const listed = await git(repo, ['worktree', 'list', '--porcelain']);
|
|
274
|
+
if (listed.code !== 0)
|
|
275
|
+
return [];
|
|
276
|
+
const entries = [];
|
|
277
|
+
for (const block of listed.stdout.split('\n\n')) {
|
|
278
|
+
const lines = block.split('\n');
|
|
279
|
+
const where = lines.find((line) => line.startsWith('worktree '))?.slice('worktree '.length);
|
|
280
|
+
if (!where)
|
|
281
|
+
continue;
|
|
282
|
+
const branch = lines.find((line) => line.startsWith('branch '))?.slice('branch refs/heads/'.length);
|
|
283
|
+
entries.push({ path: realpath(where), ...(branch ? { branch } : {}), bare: lines.includes('bare') });
|
|
284
|
+
}
|
|
285
|
+
return entries;
|
|
286
|
+
};
|
|
287
|
+
return {
|
|
288
|
+
async inspect(dir) {
|
|
289
|
+
if (!fs.existsSync(dir))
|
|
290
|
+
return { error: `${dir} does not exist` };
|
|
291
|
+
const top = await gitIn(dir, ['rev-parse', '--show-toplevel']);
|
|
292
|
+
if (top.code !== 0)
|
|
293
|
+
return { error: top.stderr.trim() || 'git rev-parse failed' };
|
|
294
|
+
const worktree = realpath(top.stdout.trim());
|
|
295
|
+
const dirs = await gitIn(worktree, ['rev-parse', '--absolute-git-dir', '--git-common-dir', 'HEAD']);
|
|
296
|
+
if (dirs.code !== 0)
|
|
297
|
+
return { error: dirs.stderr.trim() || 'git rev-parse failed' };
|
|
298
|
+
const [gitDir = '', common = '', head = ''] = dirs.stdout.trim().split('\n');
|
|
299
|
+
const repo = realpath(path.resolve(worktree, common));
|
|
300
|
+
const branchRun = await gitIn(worktree, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
301
|
+
const branch = branchRun.code === 0 ? branchRun.stdout.trim() : undefined;
|
|
302
|
+
const defaultBranch = await defaultBranchOf(repo);
|
|
303
|
+
const defaultName = defaultBranch?.replace(/^origin\//, '');
|
|
304
|
+
const worktrees = await listWorktrees(repo);
|
|
305
|
+
let main;
|
|
306
|
+
if (realpath(gitDir) === repo)
|
|
307
|
+
main = 'its git directory is the repository itself';
|
|
308
|
+
else if (worktrees[0] && !worktrees[0].bare && worktrees[0].path === worktree)
|
|
309
|
+
main = 'git lists it first';
|
|
310
|
+
else if (branch && defaultName && branch === defaultName)
|
|
311
|
+
main = `it has the default branch ${defaultName} checked out`;
|
|
312
|
+
else if (['main', 'master'].includes(path.basename(worktree)))
|
|
313
|
+
main = `it is named ${path.basename(worktree)}`;
|
|
314
|
+
return { worktree, repo, head, ...(branch ? { branch } : {}), ...(defaultBranch ? { defaultBranch } : {}), ...(main ? { main } : {}) };
|
|
315
|
+
},
|
|
316
|
+
async dirty(worktree) {
|
|
317
|
+
const status = await gitIn(worktree, ['status', '--porcelain', '--untracked-files=all']);
|
|
318
|
+
if (status.code !== 0)
|
|
319
|
+
return [`git status failed: ${status.stderr.trim()}`];
|
|
320
|
+
return status.stdout.split('\n').filter((line) => line.trim());
|
|
321
|
+
},
|
|
322
|
+
async stashes(repo, branch) {
|
|
323
|
+
const list = await git(repo, ['stash', 'list', '--format=%gs']);
|
|
324
|
+
if (list.code !== 0)
|
|
325
|
+
return [];
|
|
326
|
+
return list.stdout.split('\n').filter((line) => line.startsWith(`WIP on ${branch}:`) || line.startsWith(`On ${branch}:`));
|
|
327
|
+
},
|
|
328
|
+
async safety({ repo, worktree, branch, defaultBranch }) {
|
|
329
|
+
const tip = await git(repo, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]);
|
|
330
|
+
if (tip.code !== 0)
|
|
331
|
+
return { safe: false, how: `branch ${branch} does not exist in ${repo}` };
|
|
332
|
+
const sha = tip.stdout.trim();
|
|
333
|
+
const base = defaultBranch ?? (await defaultBranchOf(repo));
|
|
334
|
+
if (base) {
|
|
335
|
+
const ancestor = await git(repo, ['merge-base', '--is-ancestor', sha, base]);
|
|
336
|
+
if (ancestor.code === 0)
|
|
337
|
+
return { safe: true, how: `branch ${branch} is merged into ${base}` };
|
|
338
|
+
}
|
|
339
|
+
const pr = await run('gh', ['pr', 'list', '--head', branch, '--state', 'all', '--json', 'number,state,headRefOid', '--limit', '20'], worktree && fs.existsSync(worktree) ? worktree : repo);
|
|
340
|
+
if (pr.code !== 0)
|
|
341
|
+
return { safe: false, how: `branch ${branch} is not merged into ${base ?? 'a default branch'}, and gh could not list its pull requests (${(pr.stderr || pr.stdout).trim().split('\n')[0]})` };
|
|
342
|
+
let prs = [];
|
|
343
|
+
try {
|
|
344
|
+
prs = JSON.parse(pr.stdout);
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
prs = [];
|
|
348
|
+
}
|
|
349
|
+
const pushed = prs.filter((entry) => entry.headRefOid === sha);
|
|
350
|
+
const settled = pushed.find((entry) => entry.state === 'MERGED' || entry.state === 'CLOSED');
|
|
351
|
+
if (settled)
|
|
352
|
+
return { safe: true, how: `branch ${branch} is pushed and pull request #${settled.number} is ${settled.state.toLowerCase()}` };
|
|
353
|
+
const open = pushed.find((entry) => entry.state === 'OPEN');
|
|
354
|
+
if (open)
|
|
355
|
+
return { safe: false, how: `branch ${branch} is pushed but pull request #${open.number} is still open` };
|
|
356
|
+
return { safe: false, how: `branch ${branch} is not merged into ${base ?? 'a default branch'}, and no merged or closed pull request has its tip ${sha.slice(0, 12)}, so its work may exist nowhere else` };
|
|
357
|
+
},
|
|
358
|
+
async busy(dir) {
|
|
359
|
+
const target = realpath(dir);
|
|
360
|
+
if (proc) {
|
|
361
|
+
const pids = [];
|
|
362
|
+
let entries;
|
|
363
|
+
try {
|
|
364
|
+
entries = fs.readdirSync(proc);
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
return undefined;
|
|
368
|
+
}
|
|
369
|
+
for (const entry of entries) {
|
|
370
|
+
if (!/^\d+$/.test(entry))
|
|
371
|
+
continue;
|
|
372
|
+
try {
|
|
373
|
+
if (inside(fs.readlinkSync(path.join(proc, entry, 'cwd')), target))
|
|
374
|
+
pids.push(Number(entry));
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
// A process that left, or one this user cannot read.
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return pids;
|
|
381
|
+
}
|
|
382
|
+
const lsof = await run('lsof', ['-n', '-P', '-w', '-d', 'cwd', '-Fpn']);
|
|
383
|
+
if (lsof.code === 127)
|
|
384
|
+
return undefined;
|
|
385
|
+
const pids = [];
|
|
386
|
+
let pid = 0;
|
|
387
|
+
for (const line of lsof.stdout.split('\n')) {
|
|
388
|
+
if (line.startsWith('p'))
|
|
389
|
+
pid = Number(line.slice(1));
|
|
390
|
+
else if (line.startsWith('n') && inside(line.slice(1), target))
|
|
391
|
+
pids.push(pid);
|
|
392
|
+
}
|
|
393
|
+
return pids;
|
|
394
|
+
},
|
|
395
|
+
async worktreeExists(repo, worktree) {
|
|
396
|
+
const target = realpath(worktree);
|
|
397
|
+
if (fs.existsSync(worktree))
|
|
398
|
+
return true;
|
|
399
|
+
return (await listWorktrees(repo)).some((entry) => entry.path === target || entry.path === path.resolve(worktree));
|
|
400
|
+
},
|
|
401
|
+
async branchExists(repo, branch) {
|
|
402
|
+
return (await git(repo, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`])).code === 0;
|
|
403
|
+
},
|
|
404
|
+
async removeWorktree(repo, worktree) {
|
|
405
|
+
const removed = await git(repo, ['worktree', 'remove', worktree]);
|
|
406
|
+
if (removed.code !== 0)
|
|
407
|
+
throw new Error(removed.stderr.trim() || `git worktree remove exited ${removed.code}`);
|
|
408
|
+
await git(repo, ['worktree', 'prune']);
|
|
409
|
+
},
|
|
410
|
+
async deleteBranch(repo, branch) {
|
|
411
|
+
const deleted = await git(repo, ['branch', '-D', branch]);
|
|
412
|
+
if (deleted.code !== 0)
|
|
413
|
+
throw new Error(deleted.stderr.trim() || `git branch -D exited ${deleted.code}`);
|
|
414
|
+
},
|
|
415
|
+
};
|
|
416
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Prompting a live child. agent_send and a spawn that finds its resume target
|
|
2
|
+
// alive both go through here, so a blocked child gets the same answer from each.
|
|
3
|
+
import { HerdrApiError } from './herdr-client.js';
|
|
4
|
+
/** Submit a prompt to a child's pane, or return the dialog that blocks it. */
|
|
5
|
+
export async function promptChild(herdr, child, text) {
|
|
6
|
+
try {
|
|
7
|
+
await herdr.agentPrompt(child.paneId, text);
|
|
8
|
+
return `Prompted ${child.name}.`;
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
if (error instanceof HerdrApiError && child.lastStatus === 'blocked') {
|
|
12
|
+
const dialog = await herdr.paneRead({ paneId: child.paneId, source: 'detection', lines: 30 }).catch(() => '');
|
|
13
|
+
return `herdr refused the prompt because ${child.name} is blocked. The dialog:\n${dialog.trim()}\n\nReply with agent_send keys, for example ["enter"] or ["down","enter"].`;
|
|
14
|
+
}
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// A spawn with a resume target acts as a message that resumes. The caller says
|
|
2
|
+
// what it wants to tell a child, and this decides how it gets there: a child
|
|
3
|
+
// whose session herdr still shows gets the prompt as an ordinary message, and a
|
|
4
|
+
// child herdr no longer knows comes back in a new tab with its session's resume
|
|
5
|
+
// flag, under the same child id. herdr decides which, not the registry, because
|
|
6
|
+
// the registry can be stale. One lock per child covers the decision and the
|
|
7
|
+
// resume, so two callers bring a child back once.
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { withChildLock } from './child-lock.js';
|
|
10
|
+
import { LOCAL_HOST, hostOf } from './machine.js';
|
|
11
|
+
import { readParent, updateChild } from './registry.js';
|
|
12
|
+
import { findResumable, holdsSession, resumeArgs, resumeChild, sessionOf } from './resume.js';
|
|
13
|
+
import { herdrLink } from './spawn.js';
|
|
14
|
+
import { promptChild } from './send.js';
|
|
15
|
+
function sessionTarget(value) {
|
|
16
|
+
return { value, kind: value.includes('/') ? 'path' : 'id' };
|
|
17
|
+
}
|
|
18
|
+
function paneLabel(pane) {
|
|
19
|
+
return `pane ${pane.paneId}${pane.name ? ` (${pane.name})` : ''}`;
|
|
20
|
+
}
|
|
21
|
+
export async function spawnResume(clientFor, parentId, request, signal) {
|
|
22
|
+
const first = readParent(parentId);
|
|
23
|
+
if (!first)
|
|
24
|
+
throw new Error(`No Bellwether registry for ${parentId}.`);
|
|
25
|
+
const known = findResumable(first, request.target);
|
|
26
|
+
const host = known ? hostOf(known) : (request.host ?? LOCAL_HOST);
|
|
27
|
+
const client = await clientFor(host);
|
|
28
|
+
const key = known ? known.id : `session-${path.basename(request.target, '.jsonl')}`;
|
|
29
|
+
const label = known ? `${known.name} (child ${known.id})` : `Session ${request.target}`;
|
|
30
|
+
return withChildLock(key, label, `resume of ${request.target}`, async () => {
|
|
31
|
+
// Read the registry again under the lock: a caller that held it before
|
|
32
|
+
// this one may have just brought the child back.
|
|
33
|
+
const record = readParent(parentId) ?? first;
|
|
34
|
+
const panes = await client.agentList(signal);
|
|
35
|
+
const options = { prompt: request.prompt, model: request.model, args: request.args, focus: request.focus, startupTimeoutMs: request.startupTimeoutMs, redrawMs: request.redrawMs };
|
|
36
|
+
if (!known) {
|
|
37
|
+
const wanted = sessionTarget(request.target);
|
|
38
|
+
const live = panes.find((pane) => pane.agent && (pane.paneId === request.target || pane.name === request.target || holdsSession(pane, wanted)));
|
|
39
|
+
if (live) {
|
|
40
|
+
throw new Error(`"${request.target}" is alive in ${paneLabel(live)} on ${host}, but it is not a child of this session, and Bellwether sends input only to panes this session started. Adopt it with agent_adopt, then call agent_spawn with resume again to message it.`);
|
|
41
|
+
}
|
|
42
|
+
if (!request.kind) {
|
|
43
|
+
throw new Error(`"${request.target}" is neither a child of this session nor a live session on ${host}. Call agent_list to see this session's children, or pass kind (claude or pi) with resume to reopen a session id no child ran.`);
|
|
44
|
+
}
|
|
45
|
+
resumeArgs(request.kind, wanted);
|
|
46
|
+
const resumed = await resumeChild(client, record, { session: wanted, kind: request.kind, name: request.name, cwd: request.cwd, host }, options, signal);
|
|
47
|
+
return { action: 'resumed', child: resumed.child, session: resumed.session, link: resumed.link };
|
|
48
|
+
}
|
|
49
|
+
const child = record.children.find((entry) => entry.id === known.id) ?? known;
|
|
50
|
+
const session = sessionOf(child);
|
|
51
|
+
const holder = session ? panes.find((pane) => holdsSession(pane, session)) : undefined;
|
|
52
|
+
if (holder && holder.paneId === child.paneId) {
|
|
53
|
+
// Alive where this session put it: the prompt is an ordinary message.
|
|
54
|
+
let corrected;
|
|
55
|
+
if (child.exitedAt) {
|
|
56
|
+
corrected = `The registry marked ${child.name} exited, but herdr shows its session ${session?.value} in its own pane ${child.paneId}, so Bellwether cleared the exit and treated it as alive.`;
|
|
57
|
+
updateChild(parentId, child.id, (entry) => {
|
|
58
|
+
delete entry.exitedAt;
|
|
59
|
+
delete entry.exitCode;
|
|
60
|
+
});
|
|
61
|
+
delete child.exitedAt;
|
|
62
|
+
}
|
|
63
|
+
const reply = request.prompt ? await promptChild(client, child, request.prompt) : `${child.name} is alive in pane ${child.paneId}, and there was no prompt to send.`;
|
|
64
|
+
return { action: 'messaged', child, reply, link: herdrLink('pane', child.paneId), corrected };
|
|
65
|
+
}
|
|
66
|
+
if (holder) {
|
|
67
|
+
// The session runs, but in a pane this session did not start for it.
|
|
68
|
+
throw new Error(`${child.name} (child ${child.id}) has its session ${session?.value} alive in ${paneLabel(holder)}, but this session last ran it in pane ${child.paneId}${child.exitedAt ? ' and the registry marked it exited' : ''}. Bellwether sends input only to panes this session started, so it neither messaged that pane nor opened a second copy. Adopt pane ${holder.paneId} with agent_adopt to take it over, or close that pane and call agent_spawn with resume again.`);
|
|
69
|
+
}
|
|
70
|
+
if (!session) {
|
|
71
|
+
// With no session, herdr cannot say which conversation is the child's.
|
|
72
|
+
// A running record whose pane still holds an agent of its kind is the
|
|
73
|
+
// only case Bellwether can still trust.
|
|
74
|
+
const own = panes.find((pane) => pane.paneId === child.paneId && pane.agent === child.kind);
|
|
75
|
+
if (!child.exitedAt && own) {
|
|
76
|
+
const reply = request.prompt ? await promptChild(client, child, request.prompt) : `${child.name} is alive in pane ${child.paneId}, and there was no prompt to send.`;
|
|
77
|
+
return { action: 'messaged', child, reply, link: herdrLink('pane', child.paneId) };
|
|
78
|
+
}
|
|
79
|
+
resumeArgs(child.kind, { value: '', kind: 'id' });
|
|
80
|
+
throw new Error(`${child.name} (child ${child.id}) has no recorded session, and herdr shows no running agent this session can tie to it in pane ${child.paneId}, so there is no conversation to reopen. Pass resume with the session id and kind to reopen it as a new child, or call agent_spawn without resume for a fresh one.`);
|
|
81
|
+
}
|
|
82
|
+
// herdr has no pane for the session: the child is retired.
|
|
83
|
+
resumeArgs(child.kind, session);
|
|
84
|
+
let corrected;
|
|
85
|
+
if (!child.exitedAt) {
|
|
86
|
+
corrected = `The registry still listed ${child.name} as running in pane ${child.paneId}, but herdr shows no pane holding its session ${session.value}, so Bellwether treated it as retired and resumed it.`;
|
|
87
|
+
const at = new Date().toISOString();
|
|
88
|
+
updateChild(parentId, child.id, (entry) => {
|
|
89
|
+
entry.exitedAt = at;
|
|
90
|
+
});
|
|
91
|
+
child.exitedAt = at;
|
|
92
|
+
}
|
|
93
|
+
const resumed = await resumeChild(client, record, { child }, options, signal);
|
|
94
|
+
return { action: 'resumed', child: resumed.child, session: resumed.session, link: resumed.link, corrected };
|
|
95
|
+
});
|
|
96
|
+
}
|