@christang/keel 5.182.0 → 5.183.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.182.0",
3
+ "version": "5.183.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.182.0 -->
1
+ <!-- keel:start version=5.183.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.182.0",
3
+ "version": "5.183.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.182.0",
9
+ "version": "5.183.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.182.0",
5
+ "version": "5.183.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.182.0",
3
+ "version": "5.183.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.182.0",
3
+ "version": "5.183.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",
@@ -51,8 +51,8 @@ REQUIRED_SCRIPTS = [
51
51
  "scripts/validate_plugin.py",
52
52
  ]
53
53
 
54
- PACKAGE_VERSION = "5.182.0"
55
- PROTOCOL_VERSION = "5.182.0"
54
+ PACKAGE_VERSION = "5.183.0"
55
+ PROTOCOL_VERSION = "5.183.0"
56
56
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
57
57
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
58
58
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -8420,6 +8420,191 @@ def validate_shift_start_desktop_scenario() -> int:
8420
8420
  return 0
8421
8421
 
8422
8422
 
8423
+ # A claude for the hand-over's host contract (#408): `agents --json` from a rows
8424
+ # file, `stop` that drops the row's status and pid at once and ends the process
8425
+ # a second later (`late`) or never (`never`), as measured on 2.1.304 (row 0.32 s,
8426
+ # return 0.98 s, exit 3.2 s), `rm` that logs whether that process was still
8427
+ # running, and a new session for `--bg`.
8428
+ HANDOVER_CONTRACT_FAKE = """#!/usr/bin/env python3
8429
+ import json, os, subprocess, sys
8430
+ agents, calls, mode = os.environ['FAKE_AGENTS'], os.environ['FAKE_CALLS'], os.environ.get('FAKE_STOP_MODE', 'late')
8431
+ argv = sys.argv[1:]
8432
+ def running(pid):
8433
+ try:
8434
+ os.kill(pid, 0)
8435
+ except OSError:
8436
+ return False
8437
+ return True
8438
+ rows = json.loads(open(agents).read())
8439
+ record = {'argv': argv}
8440
+ if argv[:1] == ['rm']:
8441
+ gone = [row for row in rows if row['id'] == argv[1]]
8442
+ record['alive'] = bool(gone) and bool(gone[0].get('_pid')) and running(gone[0]['_pid'])
8443
+ rows = [row for row in rows if row['id'] != argv[1]]
8444
+ open(calls, 'a').write(json.dumps(record) + '\\n')
8445
+ if argv[:2] == ['agents', '--json']:
8446
+ print(json.dumps([{k: v for k, v in row.items() if not k.startswith('_')} for row in rows])); sys.exit(0)
8447
+ if argv[:1] == ['stop']:
8448
+ for row in rows:
8449
+ if row['id'] == argv[1] and 'status' in row:
8450
+ pid = row.pop('pid', None); row.pop('status', None); row['state'] = 'stopped'; row['_pid'] = pid
8451
+ if pid and mode == 'late':
8452
+ subprocess.Popen(['sh', '-c', f'sleep 1; kill {pid}'], start_new_session=True,
8453
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
8454
+ open(agents, 'w').write(json.dumps(rows)); print('stopped ' + argv[1]); sys.exit(0)
8455
+ if argv[:1] == ['--bg']:
8456
+ rows.append({'kind': 'background', 'name': 'verify', 'sessionId': 'newsess1-0000-0000-0000-000000000000', 'id': 'newsess1',
8457
+ 'status': 'busy', 'state': 'working', 'pid': os.getpid(), 'cwd': os.getcwd(), 'startedAt': 1792600000000})
8458
+ open(agents, 'w').write(json.dumps(rows)); print('backgrounded · newsess1 · verify'); sys.exit(0)
8459
+ open(agents, 'w').write(json.dumps(rows)); print('ok')
8460
+ """
8461
+
8462
+
8463
+ def detached_sleeper() -> int:
8464
+ """A process that is not this one's child, so a kill reaps it instead of leaving a zombie."""
8465
+ return int(subprocess.run(["sh", "-c", "sleep 600 >/dev/null 2>&1 & echo $!"], text=True,
8466
+ capture_output=True, check=True).stdout.strip())
8467
+
8468
+
8469
+ def validate_shift_cli_removes_after_exit_scenario() -> int:
8470
+ """Issue #408: a hand-over never removes a session whose process still runs.
8471
+
8472
+ Measured on Claude Code 2.1.304 (2026-10-21): after `claude stop` the row
8473
+ loses `status` and `pid` at 0.32 s, the command returns at 0.98 s, and the
8474
+ process exits about 3.2 s in. Since #418 the session just handed over is
8475
+ removed by default, so the removal waits for the process the note recorded.
8476
+ """
8477
+ label = "shift-cli-removes-after-exit:"
8478
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
8479
+ for mode in ("late", "never"):
8480
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408a-") as raw:
8481
+ base = Path(raw)
8482
+ rtl, verify, env, _ = shift_scratch(base)
8483
+ agents, calls, fake, config = base / "agents.json", base / "calls.jsonl", base / "fake-claude", base / "claude"
8484
+ write_text(fake, HANDOVER_CONTRACT_FAKE)
8485
+ fake.chmod(0o755)
8486
+ write_text(config / "projects" / host_project_name(verify) / f"{OLD}.jsonl",
8487
+ json.dumps({"type": "user", "message": {"role": "user", "content": "carry on"}}) + "\n")
8488
+ process = detached_sleeper()
8489
+ try:
8490
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
8491
+ "status": "idle", "state": "done", "pid": process, "cwd": str(verify),
8492
+ "startedAt": 1792500000000}]))
8493
+ calls.write_text("")
8494
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config), "FAKE_AGENTS": str(agents),
8495
+ "FAKE_CALLS": str(calls), "FAKE_STOP_MODE": mode, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1",
8496
+ "KEEL_SHIFT_EXIT_WAIT_MS": "5000" if mode == "late" else "1500"}
8497
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(process)}
8498
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R030", env=cli_env)
8499
+ if readied.returncode != 0:
8500
+ report(f"{label} ready --wake failed: {readied.stderr!r}")
8501
+ return 1
8502
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
8503
+ removals = [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
8504
+ status = run_keel(rtl, "shift", "status", env=env).stdout
8505
+ if mode == "late":
8506
+ if [r["argv"][1] for r in removals] != [OLD[:8]]:
8507
+ report(f"{label} the hand-over did not remove the session just handed over once its process exited: {removals!r}")
8508
+ return 1
8509
+ if removals[0]["alive"]:
8510
+ report(f"{label} `claude rm` of the session just handed over ran while its process was still running.")
8511
+ return 1
8512
+ else:
8513
+ if removals:
8514
+ report(f"{label} a session whose process never exited was removed: {removals!r}")
8515
+ return 1
8516
+ if f"claude attach {OLD[:8]}" not in status:
8517
+ report(f"{label} shift status does not say the old session is kept for `claude attach`: {status!r}")
8518
+ return 1
8519
+ finally:
8520
+ with contextlib.suppress(OSError):
8521
+ os.kill(process, signal.SIGKILL)
8522
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
8523
+ report(f"{label} the scenario registry does not include it.")
8524
+ return 1
8525
+ report(f"{label.rstrip(':')} scenario passed.")
8526
+ return 0
8527
+
8528
+
8529
+ def validate_shift_cli_names_host_failure_scenario() -> int:
8530
+ """Issue #408: a hand-off the host cannot be asked about says why it waits."""
8531
+ label = "shift-cli-names-host-failure:"
8532
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
8533
+ for case, needle in (("missing", "claude was not found"), ("garbled", "agents --json")):
8534
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408b-") as raw:
8535
+ base = Path(raw)
8536
+ rtl, verify, env, _ = shift_scratch(base)
8537
+ claude = base / "no-claude"
8538
+ if case == "garbled":
8539
+ write_text(claude, "#!/bin/sh\necho 'not a list'\n")
8540
+ claude.chmod(0o755)
8541
+ env = {**env, "KEEL_CLAUDE": str(claude), "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
8542
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8543
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R031", env=cli_env)
8544
+ if readied.returncode != 0:
8545
+ report(f"{label} ready --wake failed ({case}): {readied.stderr!r}")
8546
+ return 1
8547
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
8548
+ status = run_keel(rtl, "shift", "status", env=env).stdout
8549
+ if "pending" not in status:
8550
+ report(f"{label} the hand-off is no longer pending ({case}): {status!r}")
8551
+ return 1
8552
+ if needle not in status:
8553
+ report(f"{label} shift status does not name why the hand-off waits ({case}, expected {needle!r}): {status!r}")
8554
+ return 1
8555
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
8556
+ report(f"{label} the scenario registry does not include it.")
8557
+ return 1
8558
+ report(f"{label.rstrip(':')} scenario passed.")
8559
+ return 0
8560
+
8561
+
8562
+ def validate_tick_retries_failed_wake_scenario() -> int:
8563
+ """Issue #408: a tick retries a failed wake a bounded number of times.
8564
+
8565
+ A tick marked the role woken whether or not the resume worked, so one
8566
+ failure was never retried; a removed session is not tried again either.
8567
+ """
8568
+ label = "tick-retries-failed-wake:"
8569
+ for case in ("failing", "removed"):
8570
+ with tempfile.TemporaryDirectory(prefix="keel-tick-408c-") as raw:
8571
+ base = Path(raw)
8572
+ rtl, verify, env, _ = shift_scratch(base)
8573
+ calls = base / "calls.jsonl"
8574
+ fake = base / "fake-claude"
8575
+ listed = "['sess-verify-1']" if case == "failing" else "['other-0000']"
8576
+ write_text(fake, "#!/usr/bin/env python3\nimport json, sys\n"
8577
+ f"open({str(calls)!r}, 'a').write(json.dumps(sys.argv[1:]) + '\\n')\n"
8578
+ "if sys.argv[1:3] == ['agents', '--json']:\n"
8579
+ f" print(json.dumps([{{'kind': 'background', 'sessionId': s, 'id': s[:8]}} for s in {listed}])); sys.exit(0)\n"
8580
+ "if sys.argv[1:2] == ['--bg']:\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n")
8581
+ fake.chmod(0o755)
8582
+ env = {**env, "KEEL_CLAUDE": str(fake)}
8583
+ dead = subprocess.Popen(["true"])
8584
+ dead.wait()
8585
+ chat_session_start(verify, env, "sess-verify-1", dead.pid)
8586
+ run_keel(rtl, "chat", "dm", "verify", "rerun R032", env=env)
8587
+ for _ in range(4):
8588
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
8589
+ made = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
8590
+ resumes = [call for call in made if call[:2] == ["--bg", "--resume"]]
8591
+ lookups = [call for call in made if call[:2] == ["agents", "--json"]]
8592
+ if case == "failing" and len(resumes) != 3:
8593
+ report(f"{label} four ticks tried a failing resume {len(resumes)} times, not 3.")
8594
+ return 1
8595
+ if case == "removed" and resumes:
8596
+ report(f"{label} a removed session was resumed: {resumes!r}")
8597
+ return 1
8598
+ if case == "removed" and len(lookups) != 1:
8599
+ report(f"{label} four ticks looked up a removed session {len(lookups)} times, not once.")
8600
+ return 1
8601
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
8602
+ report(f"{label} the scenario registry does not include it.")
8603
+ return 1
8604
+ report(f"{label.rstrip(':')} scenario passed.")
8605
+ return 0
8606
+
8607
+
8423
8608
  def validate_shift_cli_self_shift_scenario() -> int:
8424
8609
  """Issues #357 and #388 on the CLI (owner, 2026-10-19): hand over, promptly, and retire.
8425
8610
 
@@ -8472,8 +8657,7 @@ def validate_shift_cli_self_shift_scenario() -> int:
8472
8657
  "if argv[:1] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8473
8658
  "print('stopped')\n")
8474
8659
  fake.chmod(0o755)
8475
- env = {**env, "KEEL_CLAUDE": str(fake), "KEEL_SHIFT_HANDOVER_POLL_MS": "200", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "20000",
8476
- "KEEL_SHIFT_RENAME_WAIT_MS": "1500"}
8660
+ env = {**env, "KEEL_CLAUDE": str(fake), "KEEL_SHIFT_HANDOVER_POLL_MS": "200", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "20000"}
8477
8661
  # With the waiter given no time, a hand-over is the tick's alone.
8478
8662
  tick_only = {**env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
8479
8663
  cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
@@ -8674,9 +8858,12 @@ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
8674
8858
  " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8675
8859
  "open(agents, 'w').write(json.dumps(rows)); print('ok'); sys.exit(0)\n")
8676
8860
  fake.chmod(0o755)
8677
- env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config_dir), "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1",
8678
- "KEEL_SHIFT_RENAME_WAIT_MS": "200", "KEEL_SHIFT_STOP_WAIT_MS": "200"}
8679
- cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8861
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config_dir), "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
8862
+ # The process the note records has exited by the time the hand-over removes the session,
8863
+ # as on the host; #408 makes the removal wait for it.
8864
+ exited = subprocess.Popen(["true"])
8865
+ exited.wait()
8866
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(exited.pid)}
8680
8867
  roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
8681
8868
  bound = {role: path for path, role in roles.items()}
8682
8869
 
@@ -42362,6 +42549,9 @@ SCENARIOS: tuple = (
42362
42549
  ("shift-self-wake", validate_shift_self_wake_scenario),
42363
42550
  ("shift-cli-self-shift", validate_shift_cli_self_shift_scenario),
42364
42551
  ("shift-cli-keeps-old-sessions", validate_shift_cli_keeps_old_sessions_scenario),
42552
+ ("shift-cli-removes-after-exit", validate_shift_cli_removes_after_exit_scenario),
42553
+ ("shift-cli-names-host-failure", validate_shift_cli_names_host_failure_scenario),
42554
+ ("tick-retries-failed-wake", validate_tick_retries_failed_wake_scenario),
42365
42555
  ("owner-language", validate_owner_language_scenario),
42366
42556
  ("owner-language-after-tools", validate_owner_language_after_tools_scenario),
42367
42557
  ("shift-history", validate_shift_history_scenario),
@@ -238,6 +238,9 @@ function resumeCli(entry) {
238
238
  cwd: entry.worktree || undefined, encoding: "utf8",
239
239
  });
240
240
  const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
241
+ if (result.error && result.error.code === "ENOENT") {
242
+ return { ok: false, output: "claude was not found; put it on PATH or name it with KEEL_CLAUDE" };
243
+ }
241
244
  return { ok: !result.error && result.status === 0, output: result.error ? result.error.message : output };
242
245
  }
243
246
 
package/src/core/shift.js CHANGED
@@ -513,14 +513,55 @@ function finished(row) {
513
513
  return row.status === "idle";
514
514
  }
515
515
 
516
- function listAgents(claude) {
517
- const listed = spawnSync(claude, ["agents", "--json", "--all"], { encoding: "utf8" });
516
+ // Every host call in the hand-over is bounded (#408 D2): a hung `claude` must
517
+ // not hold the waiter or the tick.
518
+ function hostTimeout() {
519
+ return envMs("KEEL_SHIFT_HOST_TIMEOUT_MS", 60 * 1000);
520
+ }
521
+
522
+ // Why a host call did not answer, in words the owner can act on.
523
+ function hostTrouble(result, what) {
524
+ if (result.error && result.error.code === "ENOENT") return "claude was not found; put it on PATH or name it with KEEL_CLAUDE";
525
+ if (result.error && result.error.code === "ETIMEDOUT") return `\`${what}\` timed out after ${hostTimeout() / 1000} s`;
526
+ if (result.error) return `\`${what}\` failed: ${result.error.message}`;
527
+ return `\`${what}\` printed no session list (exit ${result.status})`;
528
+ }
529
+
530
+ function queryAgents(claude) {
531
+ const listed = spawnSync(claude, ["agents", "--json", "--all"], { encoding: "utf8", timeout: hostTimeout() });
518
532
  try {
519
533
  const parsed = JSON.parse(listed.stdout);
520
- return listed.status === 0 && Array.isArray(parsed) ? parsed : null;
534
+ if (!listed.error && listed.status === 0 && Array.isArray(parsed)) return { rows: parsed, why: null };
521
535
  } catch {
522
- return null;
536
+ // not a list
523
537
  }
538
+ return { rows: null, why: hostTrouble(listed, "claude agents --json --all") };
539
+ }
540
+
541
+ function listAgents(claude) {
542
+ return queryAgents(claude).rows;
543
+ }
544
+
545
+ function processRunning(pid) {
546
+ if (!Number.isInteger(pid) || pid <= 1) return false;
547
+ try {
548
+ process.kill(pid, 0);
549
+ return true;
550
+ } catch (error) {
551
+ return error.code === "EPERM";
552
+ }
553
+ }
554
+
555
+ // `claude stop` returns before the process exits (#395; on 2.1.304 the row
556
+ // loses its status at 0.32 s, stop returns at 0.98 s, the process exits at
557
+ // about 3.2 s), so a removal waits for the process the note recorded.
558
+ function waitForExit(pid, limitMs) {
559
+ const deadline = Date.now() + limitMs;
560
+ while (processRunning(pid)) {
561
+ if (Date.now() >= deadline) return false;
562
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
563
+ }
564
+ return true;
524
565
  }
525
566
 
526
567
  // Stop the old session; `claude stop` keeps its conversation. It is not resumed:
@@ -528,7 +569,7 @@ function listAgents(claude) {
528
569
  // its claude.ai title back over a rename (#399 F1, F2). The new session carries
529
570
  // a name of its own instead.
530
571
  function retire(claude, entry, row) {
531
- if (row.state !== "stopped") spawnSync(claude, ["stop", row.id || entry.session.slice(0, 8)], { encoding: "utf8" });
572
+ if (row.state !== "stopped") spawnSync(claude, ["stop", row.id || entry.session.slice(0, 8)], { encoding: "utf8", timeout: hostTimeout() });
532
573
  }
533
574
 
534
575
  // The new session's name: the role and its local start time (#399 D1), which
@@ -582,8 +623,14 @@ function removeOldSessions(claude, where, entry, keep) {
582
623
  .sort((a, b) => (Number(b.row.startedAt) || 0) - (Number(a.row.startedAt) || 0));
583
624
  const removed = [];
584
625
  for (const { row, transcript } of old.slice(keep)) {
626
+ // Never a session whose process still runs (#408 D1): the one just handed
627
+ // over gets a bounded wait for the process its note recorded; any other
628
+ // still running is left for the next hand-over.
629
+ const handedOver = row.sessionId === entry.session;
630
+ const pid = Number(handedOver ? entry.pid : row.pid);
631
+ if (handedOver ? !waitForExit(pid, envMs("KEEL_SHIFT_EXIT_WAIT_MS", 15 * 1000)) : processRunning(pid)) continue;
585
632
  if (transcript && !keptCopyOf(where, entry.role, transcript)) continue;
586
- const gone = spawnSync(claude, ["rm", row.id || row.sessionId.slice(0, 8)], { encoding: "utf8" });
633
+ const gone = spawnSync(claude, ["rm", row.id || row.sessionId.slice(0, 8)], { encoding: "utf8", timeout: hostTimeout() });
587
634
  if (!gone.error && gone.status === 0) removed.push(row.id || row.sessionId.slice(0, 8));
588
635
  }
589
636
  return removed;
@@ -624,15 +671,29 @@ function handOver(where, only = null) {
624
671
  const claude = process.env.KEEL_CLAUDE || "claude";
625
672
  const pending = handOffs(where).filter((entry) => entry.state === "pending" && (!only || entry.role === only));
626
673
  if (!pending.length) return [];
627
- const sessions = listAgents(claude);
628
- // A listing that failed says nothing about the old session: wait for the next step.
629
- if (!sessions) return [];
674
+ const queried = queryAgents(claude);
675
+ const sessions = queried.rows;
676
+ // A listing that failed says nothing about the old session: wait for the next
677
+ // step, and say why on the entry, which status and the patrol show (#408 D2).
678
+ if (!sessions) {
679
+ for (const queuedEntry of pending) {
680
+ const entry = store.readJsonFile(queueFile(where, queuedEntry.role));
681
+ if (entry && entry.state === "pending" && entry.waiting_on !== queried.why) {
682
+ store.writeJsonAtomic(where, queueFile(where, entry.role), { ...entry, waiting_on: queried.why });
683
+ }
684
+ }
685
+ return [];
686
+ }
630
687
  const done = [];
631
688
  for (const queued of pending) {
632
689
  const ran = withHandOverLock(where, queued.role, () => {
633
690
  const entry = store.readJsonFile(queueFile(where, queued.role));
634
691
  if (!entry || entry.state !== "pending") return null;
635
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
+ }
636
697
  if (!finished(row)) return null;
637
698
  // `stop`, `attach` and `logs` take the 8-character job id, not the full
638
699
  // session id (`No job matching`, measured 2026-10-19).
@@ -641,7 +702,7 @@ function handOver(where, only = null) {
641
702
  const mode = declared.permissionMode;
642
703
  const name = sessionName(entry.role);
643
704
  const started = spawnSync(claude, ["--bg", "-n", name, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
644
- cwd: entry.worktree, encoding: "utf8",
705
+ cwd: entry.worktree, encoding: "utf8", timeout: hostTimeout(),
645
706
  });
646
707
  const output = `${started.stdout || ""}`;
647
708
  if (!started.error && started.status === 0) {
@@ -650,7 +711,7 @@ function handOver(where, only = null) {
650
711
  entry.removed = removeOldSessions(claude, where, entry, declared.keepOldSessions);
651
712
  if (declared.message) entry.notice = declared.message;
652
713
  } else {
653
- const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
714
+ const reason = started.error ? hostTrouble(started, "claude --bg") : String(started.stderr || output).trim().split(/\r?\n/).pop();
654
715
  Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
655
716
  }
656
717
  store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
@@ -689,7 +750,8 @@ function waitForHandOver(where, role) {
689
750
  function describeHandOff(entry) {
690
751
  const tail = entry.state === "delivered"
691
752
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}${entry.new_name ? ` "${entry.new_name}"` : ""}`
692
- : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}` : "pending: waits for the session to go idle";
753
+ : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}`
754
+ : entry.waiting_on ? `pending: cannot ask the host — ${entry.waiting_on}` : "pending: waits for the session to go idle";
693
755
  // An entry from before #399 recorded whether the old session's rename showed.
694
756
  const renamed = entry.state === "delivered" && "renamed" in entry ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
695
757
  const removed = (entry.removed || []).length ? `; older sessions removed from \`claude agents\` (transcripts kept by Keel): ${entry.removed.join(", ")}` : "";
@@ -705,7 +767,8 @@ function describeHandOff(entry) {
705
767
  function handOffRisks(where, now = Date.now()) {
706
768
  return handOffs(where).filter((entry) => entry.state === "failed"
707
769
  || (entry.state === "pending" && now - Date.parse(entry.requested_at) > 15 * 60 * 1000))
708
- .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}` : ` since ${entry.requested_at}`}; see \`keel shift status\``);
770
+ .map((entry) => `${entry.role}'s CLI hand-off ${entry.state}${entry.error ? `: ${entry.error}` : ` since ${entry.requested_at}`}`
771
+ + `${entry.waiting_on ? ` (${entry.waiting_on})` : ""}; see \`keel shift status\``);
709
772
  }
710
773
 
711
774
  // --- the one-shot wake (#293) -------------------------------------------------------
package/src/core/tick.js CHANGED
@@ -57,7 +57,12 @@ function wakeEnded(where, state) {
57
57
  const newest = waiting[waiting.length - 1];
58
58
  if (!newest || (state.woken[role] && state.woken[role] >= newest)) continue;
59
59
  const resumed = notice.resumeCli(entry);
60
- state.woken[role] = newest;
60
+ // Marked woken only once it worked, the session is gone, or three tries
61
+ // failed for this record (#408 D3); a newer record starts the count again.
62
+ const before = (state.wake_attempts || {})[role];
63
+ const count = before && before.record === newest ? before.count + 1 : 1;
64
+ state.wake_attempts = { ...(state.wake_attempts || {}), [role]: { record: newest, count } };
65
+ if (resumed.ok || resumed.removed || count >= 3) state.woken[role] = newest;
61
66
  woken.push({ role, session: entry.session, record: newest, ok: resumed.ok, output: resumed.output });
62
67
  }
63
68
  return woken;
@@ -68,7 +73,9 @@ function tick(where, now = new Date()) {
68
73
  const wakeState = readState(where);
69
74
  result.woken = wakeEnded(where, wakeState);
70
75
  result.handedOver = require("./shift").handOver(where);
71
- if (result.woken.length) store.writeJsonAtomic(where, stateFile(where), { ...readState(where), woken: wakeState.woken });
76
+ if (result.woken.length) {
77
+ store.writeJsonAtomic(where, stateFile(where), { ...readState(where), woken: wakeState.woken, wake_attempts: wakeState.wake_attempts });
78
+ }
72
79
  const found = patrolWorktree(where);
73
80
  if (!found.worktree) {
74
81
  result.patrol = { ran: false, why: found.why };