@christang/keel 5.183.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.
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