@christang/keel 5.182.0 → 5.184.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.
@@ -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 };