Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions templates/hooks/handoff-spawn.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
# Run by a session that hit the context cap (hooks/context-cap.sh tells it to),
# after it wrote its handoff. Starts the successor session in the background
# with Remote Control on, named "<this session's name> 2" (3, 4, ...), same
# model and effort, told to read the handoff. If that name is already used by any
# model, effort and permission mode, told to read the handoff. The permission
# mode must match: a session in another mode holds the orchestrator's messages
# (BOB-192). If that name is already used by any
# session (any state), the next free number is taken instead. [session-name] is needed only when
# this session has no title in its transcript. Once per session: a second call
# refuses, so the same work never runs in two sessions.
Expand Down Expand Up @@ -48,10 +50,10 @@ if ! AGENTS_JSON="$(claude agents --json --all)"; then
fi
export AGENTS_JSON

# name, successor name, model, start dir, from the transcript
# name, successor name, model, start dir, permission mode, from the transcript
read -r -d '' INFO < <(python3 - "$TRANSCRIPT" "$GIVEN_NAME" <<'PY'
import json, os, re, sys
custom = ai = model = cwd = ""
custom = ai = model = cwd = mode = ""
for line in open(sys.argv[1], errors="ignore"):
try:
d = json.loads(line)
Expand All @@ -66,6 +68,8 @@ for line in open(sys.argv[1], errors="ignore"):
model = d["message"]["model"]
if not cwd and d.get("cwd"):
cwd = d["cwd"]
if d.get("permissionMode"):
mode = d["permissionMode"]
name = (sys.argv[2] or custom or ai).strip()
if not name:
sys.exit("handoff-spawn: this session has no title; run it again with a short name: hooks/handoff-spawn.sh <handoff-file> \"<name>\"")
Expand All @@ -88,13 +92,15 @@ if not model or model.startswith("<"):
sys.exit("handoff-spawn: no model found in the transcript")
if not cwd:
sys.exit("handoff-spawn: no working directory found in the transcript")
print(name); print(nxt); print(model); print(cwd)
if not mode:
sys.exit("handoff-spawn: no permission mode found in the transcript")
print(name); print(nxt); print(model); print(cwd); print(mode)
PY
) || true
NAME="$(sed -n 1p <<<"$INFO")"; NEXT="$(sed -n 2p <<<"$INFO")"
MODEL="$(sed -n 3p <<<"$INFO")"; CWD="$(sed -n 4p <<<"$INFO")"
if [ -z "$CWD" ]; then
echo "handoff-spawn: could not read name, model and start dir from $TRANSCRIPT" >&2
MODEL="$(sed -n 3p <<<"$INFO")"; CWD="$(sed -n 4p <<<"$INFO")"; PMODE="$(sed -n 5p <<<"$INFO")"
if [ -z "$PMODE" ]; then
echo "handoff-spawn: could not read name, model, start dir and permission mode from $TRANSCRIPT" >&2
exit 1
fi

Expand All @@ -104,7 +110,7 @@ if [ -n "${CLAUDE_EFFORT:-}" ]; then EFFORT_ARGS=(--effort "$CLAUDE_EFFORT"); fi
PROMPT="You are taking over from the session \"$NAME\", which hit the context cap. Read $HANDOFF and continue from its next action. Do not redo finished work. Re-read other files only when the handoff points you at them."

cd "$CWD"
OUT="$(claude --bg --remote-control "$NEXT" -n "$NEXT" --model "$MODEL" ${EFFORT_ARGS[@]+"${EFFORT_ARGS[@]}"} "$PROMPT" 2>&1)"
OUT="$(claude --bg --remote-control "$NEXT" -n "$NEXT" --model "$MODEL" --permission-mode "$PMODE" ${EFFORT_ARGS[@]+"${EFFORT_ARGS[@]}"} "$PROMPT" 2>&1)"
BG_ID="$(sed -n 's/^backgrounded · \([0-9a-f]*\) · .*/\1/p' <<<"$OUT" | head -1)"
if [ -z "$BG_ID" ]; then
echo "handoff-spawn: claude --bg did not start a session:" >&2
Expand Down
28 changes: 25 additions & 3 deletions test/hooks/handoff-spawn.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// test/hooks/handoff-spawn.test.js — successor names never clash with a live or finished session (BOB-178).
// test/hooks/handoff-spawn.test.js — successor names never clash with a live or finished session (BOB-178);
// the successor runs in the parent's permission mode (BOB-192).
// Runs the real templates/hooks/handoff-spawn.sh against a stub `claude` on PATH and a temp HOME.
import fs from 'fs';
import os from 'os';
Expand All @@ -9,7 +10,7 @@ import { fileURLToPath } from 'url';
const SCRIPT = fileURLToPath(new URL('../../templates/hooks/handoff-spawn.sh', import.meta.url));
const SID = '11111111-2222-3333-4444-555555555555';

function run({ name, agents, agentsExit = 0 }) {
function run({ name, agents, agentsExit = 0, modes = ['bypassPermissions'] }) {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'handoff-spawn-'));
const bin = path.join(home, 'bin');
fs.mkdirSync(bin);
Expand All @@ -20,6 +21,7 @@ function run({ name, agents, agentsExit = 0 }) {
[
{ type: 'custom-title', customTitle: name },
{ type: 'assistant', cwd: home, message: { model: 'claude-test-1' } },
...modes.map((m) => ({ type: 'user', permissionMode: m })),
].map((d) => JSON.stringify(d)).join('\n') + '\n',
);
const handoff = path.join(home, 'handoff.md');
Expand Down Expand Up @@ -53,7 +55,7 @@ const list = (...names) => JSON.stringify(names.map((n, i) => ({ id: `a${i}`, na
test('no clash: successor is "<name> 2" and the marker line is unchanged', () => {
const r = run({ name: 'Lane', agents: list('Other') });
expect(r.status).toBe(0);
expect(r.spawned).toContain('--remote-control Lane 2 -n Lane 2 --model claude-test-1');
expect(r.spawned).toContain('--remote-control Lane 2 -n Lane 2 --model claude-test-1 --permission-mode bypassPermissions');
expect(r.marker).toBe('"Lane 2" (bg abc123, claude-test-1) from ' + r.marker.split(' from ')[1]);
expect(r.stdout).toContain('Handed off to "Lane 2" (bg abc123, claude-test-1).');
});
Expand Down Expand Up @@ -98,3 +100,23 @@ test.each([['not json {'], ['{"name":"Lane 2"}']])('bad session list %j exits 1
expect(r.spawned).toBe('');
expect(r.markerExists).toBe(false);
});

test('the successor takes the last permission mode in the transcript', () => {
const r = run({ name: 'Lane', agents: list('Other'), modes: ['auto', 'bypassPermissions'] });
expect(r.status).toBe(0);
expect(r.spawned).toContain('--permission-mode bypassPermissions');
});

test('an auto-mode parent hands off to an auto-mode successor', () => {
const r = run({ name: 'Lane', agents: list('Other'), modes: ['auto'] });
expect(r.status).toBe(0);
expect(r.spawned).toContain('--permission-mode auto');
});

test('a transcript with no permission mode exits 1 and spawns nothing', () => {
const r = run({ name: 'Lane', agents: list('Other'), modes: [] });
expect(r.status).toBe(1);
expect(r.stderr).toContain('no permission mode found in the transcript');
expect(r.spawned).toBe('');
expect(r.markerExists).toBe(false);
});
6 changes: 3 additions & 3 deletions test/lib/compaction-hooks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -281,11 +281,11 @@ describe('handoff-spawn refuses before starting anything', () => {
expect(fs.existsSync(path.join(tmp, 'claude-called'))).toBe(false);
});

test('starts "<name> 2" with the session model and records the marker', () => {
test('starts "<name> 2" with the session model and permission mode and records the marker', () => {
const proj = path.join(home, '.claude', 'projects', 'p');
fs.mkdirSync(proj, { recursive: true });
fs.writeFileSync(path.join(proj, 's1.jsonl'), [
{ type: 'custom-title', customTitle: 'Work' }, { cwd: tmp, ...prompt('hi') }, assistant(1),
{ type: 'custom-title', customTitle: 'Work' }, { cwd: tmp, permissionMode: 'bypassPermissions', ...prompt('hi') }, assistant(1),
].map(e => JSON.stringify(e)).join('\n') + '\n');
const bin = path.join(tmp, 'bin');
fs.mkdirSync(bin, { recursive: true });
Expand All @@ -294,7 +294,7 @@ describe('handoff-spawn refuses before starting anything', () => {
cwd: tmp, encoding: 'utf8', env: { ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}`, CLAUDE_CODE_SESSION_ID: 's1' },
});
expect(r.stdout).toContain('Handed off to "Work 2" (bg ab12, claude-x)');
expect(fs.readFileSync(path.join(tmp, 'claude-args'), 'utf8')).toContain('--remote-control Work 2 -n Work 2 --model claude-x');
expect(fs.readFileSync(path.join(tmp, 'claude-args'), 'utf8')).toContain('--remote-control Work 2 -n Work 2 --model claude-x --permission-mode bypassPermissions');
expect(fs.existsSync(path.join(home, '.bobby', 'hook-state', 's1.handoff'))).toBe(true);
});
});
Expand Down
Loading