@christang/keel 5.184.0 → 5.185.0

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.184.0",
3
+ "version": "5.185.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.184.0 -->
1
+ <!-- keel:start version=5.185.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.184.0",
3
+ "version": "5.185.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.184.0",
9
+ "version": "5.185.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "^1.4.1"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.184.0",
5
+ "version": "5.185.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.184.0",
3
+ "version": "5.185.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.184.0",
3
+ "version": "5.185.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -35,10 +35,10 @@ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite
35
35
  os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
36
36
 
37
37
 
38
- PACKAGE_VERSION = "5.184.0"
38
+ PACKAGE_VERSION = "5.185.0"
39
39
 
40
40
 
41
- PROTOCOL_VERSION = "5.184.0"
41
+ PROTOCOL_VERSION = "5.185.0"
42
42
 
43
43
 
44
44
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
@@ -416,6 +416,8 @@ SCENARIOS: tuple = (
416
416
  ("shift-cli-removes-after-exit", shift.validate_shift_cli_removes_after_exit_scenario),
417
417
  ("shift-cli-names-host-failure", shift.validate_shift_cli_names_host_failure_scenario),
418
418
  ("tick-retries-failed-wake", shift.validate_tick_retries_failed_wake_scenario),
419
+ ("shift-cli-handover-claims-once", shift.validate_shift_cli_handover_claims_once_scenario),
420
+ ("shift-cli-retries-failed-handover", shift.validate_shift_cli_retries_failed_handover_scenario),
419
421
  ("owner-language", chat.validate_owner_language_scenario),
420
422
  ("owner-language-after-tools", chat.validate_owner_language_after_tools_scenario),
421
423
  ("shift-history", shift.validate_shift_history_scenario),
@@ -2672,6 +2672,198 @@ def validate_tick_retries_failed_wake_scenario() -> int:
2672
2672
  return 0
2673
2673
 
2674
2674
 
2675
+ HANDOVER_RETRY_FAKE = """#!/usr/bin/env python3
2676
+ import json, os, sys, time
2677
+ agents, calls = os.environ['FAKE_AGENTS'], os.environ['FAKE_CALLS']
2678
+ argv = sys.argv[1:]
2679
+ def load():
2680
+ return json.loads(open(agents).read())
2681
+ def save(rows):
2682
+ tmp = agents + '.' + str(os.getpid())
2683
+ open(tmp, 'w').write(json.dumps(rows)); os.replace(tmp, agents)
2684
+ open(calls, 'a').write(json.dumps({'argv': argv}) + '\\n')
2685
+ if argv[:2] == ['agents', '--json']:
2686
+ print(json.dumps([{k: v for k, v in row.items() if not k.startswith('_')} for row in load()])); sys.exit(0)
2687
+ if argv[:1] == ['stop']:
2688
+ rows = load()
2689
+ for row in rows:
2690
+ if row['id'] == argv[1] and 'status' in row:
2691
+ row.pop('status', None); pid = row.pop('pid', None); row['state'] = 'stopped'
2692
+ if pid:
2693
+ try:
2694
+ os.kill(pid, 9)
2695
+ except OSError:
2696
+ pass
2697
+ save(rows); print('stopped ' + argv[1]); sys.exit(0)
2698
+ if argv[:1] == ['--bg'] and '--resume' not in argv:
2699
+ failing = os.environ.get('FAKE_BG_FAILS', '0')
2700
+ count = os.environ['FAKE_CALLS'] + '.starts'
2701
+ made = int(open(count).read()) if os.path.exists(count) else 0
2702
+ open(count, 'w').write(str(made + 1))
2703
+ if failing == 'always' or made < int(failing):
2704
+ print('Workspace not trusted.', file=sys.stderr); sys.exit(1)
2705
+ new = 'newsess%d-0000-0000-0000-000000000000' % (made + 1)
2706
+ rows = load()
2707
+ rows.append({'kind': 'background', 'name': argv[2], 'sessionId': new, 'id': new[:8], 'status': 'busy', 'state': 'working',
2708
+ 'pid': os.getpid(), 'cwd': os.getcwd(), 'startedAt': int(time.time() * 1000)})
2709
+ save(rows)
2710
+ time.sleep(float(os.environ.get('FAKE_BG_SLEEP', '0')))
2711
+ print('backgrounded · ' + new[:8] + ' · ' + argv[2]); sys.exit(0)
2712
+ print('ok')
2713
+ """
2714
+
2715
+
2716
+ def handover_retry_scratch(base: Path, old: str) -> dict:
2717
+ """A verify hand-off queued from an idle CLI session, against HANDOVER_RETRY_FAKE."""
2718
+ rtl, verify, env, _ = shift_scratch(base)
2719
+ agents, calls, fake = base / "agents.json", base / "calls.jsonl", base / "fake-claude"
2720
+ write_text(fake, HANDOVER_RETRY_FAKE)
2721
+ fake.chmod(0o755)
2722
+ process = detached_sleeper()
2723
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify · 10-20 09:00", "sessionId": old, "id": old[:8],
2724
+ "status": "idle", "state": "done", "pid": process, "cwd": str(verify),
2725
+ "startedAt": 1792500000000}]))
2726
+ calls.write_text("")
2727
+ exited = subprocess.Popen(["true"])
2728
+ exited.wait()
2729
+ env = {**env, "KEEL_CLAUDE": str(fake), "FAKE_AGENTS": str(agents), "FAKE_CALLS": str(calls),
2730
+ "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1", "KEEL_SHIFT_EXIT_WAIT_MS": "500"}
2731
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": old, "CLAUDE_PID": str(exited.pid)}
2732
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R040", env=cli_env)
2733
+ if readied.returncode != 0:
2734
+ raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
2735
+ queue = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue" / "verify.json"
2736
+
2737
+ def starts() -> int:
2738
+ return sum(1 for line in calls.read_text().splitlines()
2739
+ if json.loads(line)["argv"][:1] == ["--bg"] and "--resume" not in json.loads(line)["argv"])
2740
+
2741
+ return {"rtl": rtl, "verify": verify, "env": env, "agents": agents, "calls": calls, "queue": queue,
2742
+ "starts": starts, "process": process,
2743
+ "tick": lambda extra=None: run_keel(verify, "tick", "--repo", str(rtl), env={**env, **(extra or {})}),
2744
+ "keel": ["node", str(ROOT / "bin" / "keel.js")]}
2745
+
2746
+
2747
+ def validate_shift_cli_handover_claims_once_scenario() -> int:
2748
+ """Issue #408, second loop: one pending hand-off starts one session.
2749
+
2750
+ Runners claim the entry as `starting` before any host call (D1). So two
2751
+ ticks and a waiter running at the same moment start one session. A runner
2752
+ killed after `claude --bg` listed the new session is settled by adopting
2753
+ that session, not by starting another (D2, D3).
2754
+ """
2755
+ label = "shift-cli-handover-claims-once:"
2756
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
2757
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408c-") as raw:
2758
+ s = handover_retry_scratch(Path(raw), OLD)
2759
+ try:
2760
+ race = {**s["env"], "FAKE_BG_SLEEP": "1", "KEEL_SHIFT_HANDOVER_POLL_MS": "50", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "8000"}
2761
+ runners = [subprocess.Popen([*s["keel"], "tick", "--repo", str(s["rtl"])], cwd=s["verify"], env=race,
2762
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(2)]
2763
+ runners.append(subprocess.Popen([*s["keel"], "shift", "handover-wait", "--role", "verify", "--repo", str(s["verify"])],
2764
+ cwd=s["verify"], env=race, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
2765
+ for runner in runners:
2766
+ runner.wait(timeout=60)
2767
+ entry = json.loads(s["queue"].read_text())
2768
+ if s["starts"]() != 1 or entry["state"] != "delivered":
2769
+ report(f"{label} two ticks and a waiter at once ran `claude --bg` {s['starts']()} times; the entry is {entry['state']}.")
2770
+ return 1
2771
+ finally:
2772
+ with contextlib.suppress(OSError):
2773
+ os.kill(s["process"], signal.SIGKILL)
2774
+
2775
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408d-") as raw:
2776
+ s = handover_retry_scratch(Path(raw), OLD)
2777
+ try:
2778
+ slow = {**s["env"], "FAKE_BG_SLEEP": "30"}
2779
+ runner = subprocess.Popen([*s["keel"], "tick", "--repo", str(s["rtl"])], cwd=s["verify"], env=slow,
2780
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
2781
+ deadline = time.time() + 20
2782
+ while s["starts"]() < 1 and time.time() < deadline:
2783
+ time.sleep(0.1)
2784
+ time.sleep(0.5)
2785
+ os.killpg(runner.pid, signal.SIGKILL)
2786
+ runner.wait()
2787
+ # The next tick comes minutes later, when any lock the dead runner left reads as stale.
2788
+ for lock in s["queue"].parent.glob("*.lock"):
2789
+ os.utime(lock, (time.time() - 600, time.time() - 600))
2790
+ s["tick"]()
2791
+ entry = json.loads(s["queue"].read_text())
2792
+ if s["starts"]() != 1:
2793
+ report(f"{label} a tick after the runner died mid-start ran `claude --bg` again: {s['starts']()} starts; the entry is {entry['state']}.")
2794
+ return 1
2795
+ if entry["state"] != "delivered" or not entry.get("adopted") or entry.get("new_session") != "newsess1":
2796
+ report(f"{label} the entry left by a runner that died mid-start was not delivered with the listed session: {entry!r}")
2797
+ return 1
2798
+ finally:
2799
+ with contextlib.suppress(OSError):
2800
+ os.kill(s["process"], signal.SIGKILL)
2801
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
2802
+ report(f"{label} the scenario registry does not include it.")
2803
+ return 1
2804
+ report(f"{label.rstrip(':')} scenario passed.")
2805
+ return 0
2806
+
2807
+
2808
+ def validate_shift_cli_retries_failed_handover_scenario() -> int:
2809
+ """Issue #408, second loop: a failed hand-off is retried within a bound (D4, D5).
2810
+
2811
+ The tick makes up to three start attempts per entry. After the last one,
2812
+ status and the patrol name `keel chat wake now <role>`. The tick does not
2813
+ retry when the old session runs again, or when the entry predates the
2814
+ attempt count.
2815
+ """
2816
+ label = "shift-cli-retries-failed-handover:"
2817
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
2818
+ for case in ("always", "third", "resumed", "legacy"):
2819
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408e-") as raw:
2820
+ s = handover_retry_scratch(Path(raw), OLD)
2821
+ try:
2822
+ fails = {"FAKE_BG_FAILS": "2" if case == "third" else "always"}
2823
+ s["tick"](fails)
2824
+ if case == "resumed":
2825
+ rows = json.loads(s["agents"].read_text())
2826
+ rows[0].update({"status": "idle", "state": "done", "pid": s["process"]})
2827
+ s["agents"].write_text(json.dumps(rows))
2828
+ if case == "legacy":
2829
+ entry = json.loads(s["queue"].read_text())
2830
+ entry.pop("attempts", None)
2831
+ s["queue"].write_text(json.dumps(entry))
2832
+ for _ in range(4 if case in ("always", "third") else 2):
2833
+ s["tick"](fails)
2834
+ entry = json.loads(s["queue"].read_text())
2835
+ status = run_keel(s["rtl"], "shift", "status", env=s["env"]).stdout
2836
+ if case == "always":
2837
+ if s["starts"]() != 3:
2838
+ report(f"{label} five ticks ran a failing `claude --bg` {s['starts']()} times, not 3.")
2839
+ return 1
2840
+ patrolled = run_keel(s["rtl"], "patrol", env=s["env"]).stdout
2841
+ if entry["state"] != "failed":
2842
+ report(f"{label} after three failed starts the entry is {entry['state']}, not failed.")
2843
+ return 1
2844
+ if "keel chat wake now verify" not in status:
2845
+ report(f"{label} after three failed starts, shift status does not name `keel chat wake now verify`: {status!r}")
2846
+ return 1
2847
+ if "keel chat wake now verify" not in patrolled:
2848
+ report(f"{label} after three failed starts, the patrol does not name `keel chat wake now verify`: {patrolled!r}")
2849
+ return 1
2850
+ elif case == "third":
2851
+ if s["starts"]() != 3 or entry["state"] != "delivered" or entry.get("new_session") != "newsess3":
2852
+ report(f"{label} a start that fails twice was not delivered on the third attempt: {s['starts']()} starts, {entry!r}")
2853
+ return 1
2854
+ elif s["starts"]() != 1 or entry["state"] != "failed":
2855
+ report(f"{label} a failed hand-off was retried although {'its old session runs again' if case == 'resumed' else 'it records no attempts'}: {s['starts']()} starts, {entry['state']}.")
2856
+ return 1
2857
+ finally:
2858
+ with contextlib.suppress(OSError):
2859
+ os.kill(s["process"], signal.SIGKILL)
2860
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
2861
+ report(f"{label} the scenario registry does not include it.")
2862
+ return 1
2863
+ report(f"{label.rstrip(':')} scenario passed.")
2864
+ return 0
2865
+
2866
+
2675
2867
  def validate_shift_cli_self_shift_scenario() -> int:
2676
2868
  """Issues #357 and #388 on the CLI (owner, 2026-10-19): hand over, promptly, and retire.
2677
2869
 
package/src/core/shift.js CHANGED
@@ -663,20 +663,94 @@ function withHandOverLock(where, role, fn) {
663
663
  }
664
664
  }
665
665
 
666
+ // A failed start is tried again this many times in all (#408 D4).
667
+ const HANDOVER_ATTEMPTS = 3;
668
+
669
+ // A claimed hand-over whose runner is gone, or that has outlived the bounded
670
+ // worst case of its host calls, is settled by another runner (#408 D2).
671
+ function runnerGone(entry, now = Date.now()) {
672
+ return !processRunning(Number(entry.runner_pid)) || !(now - Date.parse(entry.starting_at) <= 10 * 60 * 1000);
673
+ }
674
+
675
+ function actionable(entry) {
676
+ return entry.state === "pending"
677
+ || (entry.state === "starting" && runnerGone(entry))
678
+ || (entry.state === "failed" && Number.isInteger(entry.attempts) && entry.attempts < HANDOVER_ATTEMPTS);
679
+ }
680
+
681
+ // The session a claimed hand-over already started, if the host lists one (#408
682
+ // D3): named for the role, in its worktree, started since the claim.
683
+ function startedFor(entry, sessions) {
684
+ const since = Date.parse(entry.starting_at) - 5000;
685
+ const home = realpath(entry.worktree);
686
+ return sessions.find((row) => row && typeof row.name === "string" && row.name.startsWith(`${entry.role} · `)
687
+ && row.sessionId !== entry.session && Number(row.startedAt) >= since && row.cwd && realpath(row.cwd) === home) || null;
688
+ }
689
+
690
+ function deliver(claude, where, entry, id, name, adopted) {
691
+ const { readShiftDeclaration } = require("./config");
692
+ const declared = readShiftDeclaration(entry.worktree);
693
+ Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id, new_name: name });
694
+ for (const key of ["error", "failed_at", "runner_pid"]) delete entry[key];
695
+ if (adopted) entry.adopted = true;
696
+ entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
697
+ if (declared.message) entry.notice = declared.message;
698
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
699
+ return entry;
700
+ }
701
+
702
+ // Under the role's lock, decide what one entry needs, and claim it as
703
+ // `starting` before any host call, so the lock is held only for this (#408 D1):
704
+ // a runner acts only on an entry nobody has claimed.
705
+ function claim(where, queued, sessions) {
706
+ return withHandOverLock(where, queued.role, () => {
707
+ const entry = store.readJsonFile(queueFile(where, queued.role));
708
+ if (!entry || !actionable(entry)) return null;
709
+ const row = sessions.find((item) => item && item.sessionId === entry.session);
710
+ if (entry.waiting_on) {
711
+ delete entry.waiting_on;
712
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
713
+ }
714
+ if (entry.state === "starting") {
715
+ const started = startedFor(entry, sessions);
716
+ if (started) return { entry, adopt: started };
717
+ Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: "the hand-over runner stopped before the new session started" });
718
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
719
+ if (entry.attempts >= HANDOVER_ATTEMPTS) return null;
720
+ }
721
+ if (entry.state === "failed") {
722
+ // Someone resumed the old session: it is theirs now (#408 D4).
723
+ if (row && row.status) {
724
+ Object.assign(entry, { attempts: HANDOVER_ATTEMPTS, error: `${entry.error}; not retried: the old session is running again` });
725
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
726
+ return null;
727
+ }
728
+ const started = entry.starting_at && startedFor(entry, sessions);
729
+ if (started) return { entry, adopt: started };
730
+ } else if (!finished(row)) {
731
+ return null;
732
+ }
733
+ Object.assign(entry, { state: "starting", runner_pid: process.pid, starting_at: store.isoLocal(new Date()), attempts: (entry.attempts || 0) + 1 });
734
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
735
+ return { entry, row };
736
+ });
737
+ }
738
+
666
739
  // One step of the waker (#357 D2): a busy or unfinished old session waits; a
667
- // finished or gone one is retired (kept: \`claude attach\` reopens it) and a new
668
- // session starts. `only` limits the step to one role (the waiter's).
740
+ // finished or gone one is retired (stopped) and a new session starts. A claim
741
+ // left by a runner that died is settled, and a failed start is tried again
742
+ // (#408). `only` limits the step to one role (the waiter's).
669
743
  function handOver(where, only = null) {
670
744
  const { readShiftDeclaration } = require("./config");
671
745
  const claude = process.env.KEEL_CLAUDE || "claude";
672
- const pending = handOffs(where).filter((entry) => entry.state === "pending" && (!only || entry.role === only));
673
- if (!pending.length) return [];
746
+ const queuedEntries = handOffs(where).filter((entry) => actionable(entry) && (!only || entry.role === only));
747
+ if (!queuedEntries.length) return [];
674
748
  const queried = queryAgents(claude);
675
749
  const sessions = queried.rows;
676
750
  // A listing that failed says nothing about the old session: wait for the next
677
751
  // step, and say why on the entry, which status and the patrol show (#408 D2).
678
752
  if (!sessions) {
679
- for (const queuedEntry of pending) {
753
+ for (const queuedEntry of queuedEntries) {
680
754
  const entry = store.readJsonFile(queueFile(where, queuedEntry.role));
681
755
  if (entry && entry.state === "pending" && entry.waiting_on !== queried.why) {
682
756
  store.writeJsonAtomic(where, queueFile(where, entry.role), { ...entry, waiting_on: queried.why });
@@ -685,39 +759,33 @@ function handOver(where, only = null) {
685
759
  return [];
686
760
  }
687
761
  const done = [];
688
- for (const queued of pending) {
689
- const ran = withHandOverLock(where, queued.role, () => {
690
- const entry = store.readJsonFile(queueFile(where, queued.role));
691
- if (!entry || entry.state !== "pending") return null;
692
- const row = sessions.find((item) => item && item.sessionId === entry.session);
693
- if (entry.waiting_on) {
694
- delete entry.waiting_on;
695
- store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
696
- }
697
- if (!finished(row)) return null;
698
- // `stop`, `attach` and `logs` take the 8-character job id, not the full
699
- // session id (`No job matching`, measured 2026-10-19).
700
- if (row) retire(claude, entry, row);
701
- const declared = readShiftDeclaration(entry.worktree);
702
- const mode = declared.permissionMode;
703
- const name = sessionName(entry.role);
704
- const started = spawnSync(claude, ["--bg", "-n", name, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
705
- cwd: entry.worktree, encoding: "utf8", timeout: hostTimeout(),
706
- });
707
- const output = `${started.stdout || ""}`;
708
- if (!started.error && started.status === 0) {
709
- const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
710
- Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id, new_name: name });
711
- entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
712
- if (declared.message) entry.notice = declared.message;
713
- } else {
714
- const reason = started.error ? hostTrouble(started, "claude --bg") : String(started.stderr || output).trim().split(/\r?\n/).pop();
715
- Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
716
- }
717
- store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
718
- return entry;
762
+ for (const queued of queuedEntries) {
763
+ const claimed = claim(where, queued, sessions);
764
+ if (!claimed) continue;
765
+ const { entry, row, adopt } = claimed;
766
+ if (adopt) {
767
+ done.push(deliver(claude, where, entry, adopt.id || adopt.sessionId.slice(0, 8), adopt.name, true));
768
+ continue;
769
+ }
770
+ // `stop`, `attach` and `logs` take the 8-character job id, not the full
771
+ // session id (`No job matching`, measured 2026-10-19).
772
+ if (row) retire(claude, entry, row);
773
+ const mode = readShiftDeclaration(entry.worktree).permissionMode;
774
+ const name = sessionName(entry.role);
775
+ const started = spawnSync(claude, ["--bg", "-n", name, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
776
+ cwd: entry.worktree, encoding: "utf8", timeout: hostTimeout(),
719
777
  });
720
- if (ran) done.push(ran);
778
+ const output = `${started.stdout || ""}`;
779
+ if (!started.error && started.status === 0) {
780
+ const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
781
+ done.push(deliver(claude, where, entry, id, name, false));
782
+ } else {
783
+ const reason = started.error ? hostTrouble(started, "claude --bg") : String(started.stderr || output).trim().split(/\r?\n/).pop();
784
+ Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
785
+ delete entry.runner_pid;
786
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
787
+ done.push(entry);
788
+ }
721
789
  }
722
790
  return done;
723
791
  }
@@ -750,7 +818,8 @@ function waitForHandOver(where, role) {
750
818
  function describeHandOff(entry) {
751
819
  const tail = entry.state === "delivered"
752
820
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}${entry.new_name ? ` "${entry.new_name}"` : ""}`
753
- : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}`
821
+ : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}; ${retryNote(entry)}`
822
+ : entry.state === "starting" ? `starting since ${entry.starting_at} (attempt ${entry.attempts} of ${HANDOVER_ATTEMPTS})`
754
823
  : entry.waiting_on ? `pending: cannot ask the host — ${entry.waiting_on}` : "pending: waits for the session to go idle";
755
824
  // An entry from before #399 recorded whether the old session's rename showed.
756
825
  const renamed = entry.state === "delivered" && "renamed" in entry ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
@@ -763,11 +832,19 @@ function describeHandOff(entry) {
763
832
  return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; ${reopen}${removed}${notice}`;
764
833
  }
765
834
 
835
+ // What follows a failed start: the tick's next attempt, or, once none is left,
836
+ // the existing way to bring the role back (#408 D5).
837
+ function retryNote(entry) {
838
+ return Number.isInteger(entry.attempts) && entry.attempts < HANDOVER_ATTEMPTS
839
+ ? `attempt ${entry.attempts} of ${HANDOVER_ATTEMPTS}, the tick tries again`
840
+ : `resume the old session with \`keel chat wake now ${entry.role}\``;
841
+ }
842
+
766
843
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
767
844
  function handOffRisks(where, now = Date.now()) {
768
845
  return handOffs(where).filter((entry) => entry.state === "failed"
769
846
  || (entry.state === "pending" && now - Date.parse(entry.requested_at) > 15 * 60 * 1000))
770
- .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}` : ` since ${entry.requested_at}`}`
847
+ .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}; ${retryNote(entry)}` : ` since ${entry.requested_at}`}`
771
848
  + `${entry.waiting_on ? ` (${entry.waiting_on})` : ""}; see \`keel shift status\``);
772
849
  }
773
850