@christang/keel 5.228.0 → 5.229.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
@@ -153,7 +153,10 @@ function liveProcesses(worktree) {
153
153
  // The keep-awake the session's host runs under it (#447 D1): its parent is
154
154
  // one of the checker's ancestors, the host process itself. Not init, which
155
155
  // every orphan has for a parent and every process for an ancestor.
156
- if (row.ppid > 1 && own.has(row.ppid) && HOST_KEEP_AWAKE.test(row.command)) continue;
156
+ // Linux subreapers can adopt an orphan into our ancestry. Its original
157
+ // process-group leader has exited; that does not make it our keep-awake.
158
+ const adoptedGroup = process.platform === "linux" && !table.has(row.pgid);
159
+ if (!adoptedGroup && row.ppid > 1 && own.has(row.ppid) && HOST_KEEP_AWAKE.test(row.command)) continue;
157
160
  found.push(row);
158
161
  }
159
162
  return found.sort((a, b) => a.pid - b.pid);
@@ -197,6 +200,36 @@ function check(where, role) {
197
200
  for (const line of local.out.split("\n").filter(Boolean)) items.push({ kind: "unpushed", detail: line });
198
201
  }
199
202
 
203
+ // What is only on this machine (#526 D16): a stash of this worktree's branch
204
+ // is this shift's to clear; the rest of the repository's local-only work is
205
+ // named, never counted, because it is not this session's.
206
+ const localOnly = [];
207
+ let synced = null;
208
+ try {
209
+ synced = require("./sync").status(where.worktree);
210
+ } catch {
211
+ synced = null;
212
+ }
213
+ if (synced) {
214
+ const here = git(where.worktree, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
215
+ const branch = here.ok ? here.out : null;
216
+ const checkedOut = new Set(require("./worktrees").listWorktrees(where.worktree).map((row) => row.branch).filter(Boolean));
217
+ for (const stash of synced.stashes) {
218
+ if (branch && stash.branch === branch) items.push({ kind: "stash", detail: `${stash.ref}: ${stash.subject}` });
219
+ else localOnly.push(`stash ${stash.ref}: ${stash.subject}`);
220
+ }
221
+ for (const row of synced.branches) {
222
+ if (!checkedOut.has(row.branch)) localOnly.push(`branch ${row.branch}: ${row.remote ? `${row.unpushed} unpushed commit(s)` : "no remote counterpart"}`);
223
+ }
224
+ for (const row of synced.worktrees) {
225
+ if (realpath(row.path) === where.worktree) continue;
226
+ localOnly.push(`worktree ${row.path}: ${row.missing ? "missing" : [row.dirty ? `${row.dirty} uncommitted or untracked path(s)` : "", row.localBranch ? `branch ${row.branch} not on the remote` : "", row.detachedUnpushed ? "detached head on no remote" : ""].filter(Boolean).join(", ")}`);
227
+ }
228
+ for (const line of localOnly) notes.push(`only on this machine, not counted: ${line}; \`keel sync status\` lists it with its fix`);
229
+ const held = heldBranchLock(where);
230
+ if (held) notes.push(`branch ${held.branch}: this device holds its lock (${held.lock.holder}, expires ${held.lock.expires}); \`keel shift ready\` releases it`);
231
+ }
232
+
200
233
  if (fs.existsSync(path.join(where.worktree, "keel", "guard.json"))) {
201
234
  if (guard.guardHolds(where.worktree)) {
202
235
  items.push({ kind: "task-in-progress", detail: "keel/guard.json: a task's write guard is still active; complete the task or clear the guard" });
@@ -250,7 +283,7 @@ function check(where, role) {
250
283
  // A pointer, never a loose item and never a deletion (#469 D5).
251
284
  const merged = role ? mergedBranchNote(where, role) : null;
252
285
  if (merged) notes.push(merged);
253
- return { ready: items.length === 0, worktree: where.worktree, role: role || null, items, notes };
286
+ return { ready: items.length === 0, worktree: where.worktree, role: role || null, items, notes, localOnly };
254
287
  }
255
288
 
256
289
  // How many of the role's task branches are merged and unused, pointing at
@@ -378,6 +411,110 @@ function readNoteText(options) {
378
411
  // when this worktree has none and that role has an open request. An unbound
379
412
  // worktree refuses to file under itself while role requests are open, since
380
413
  // such a note would answer none of them.
414
+ // The branch lock this device holds on the worktree's branch, as last
415
+ // fetched, under \`sync: lock: true\` (#526 D16); null otherwise.
416
+ function heldBranchLock(where) {
417
+ if (!require("./config").readSyncDeclaration(where.worktree).lock) return null;
418
+ const here = git(where.worktree, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
419
+ if (!here.ok || !here.out) return null;
420
+ const locks = require("./lock");
421
+ const sha = git(where.worktree, ["rev-parse", "--verify", "--quiet", `${locks.LOCK_PREFIX}${here.out}`]);
422
+ const lock = sha.ok ? locks.parseLock(where.worktree, sha.out) : null;
423
+ const device = locks.existingDeviceId(where);
424
+ if (!lock || lock.state !== "held" || !device || lock.device !== device) return null;
425
+ return { branch: here.out, lock };
426
+ }
427
+
428
+ // Releases the held branch lock with the note written once under
429
+ // shift-notes/ (#526 D9), then archives it. A failed release leaves nothing.
430
+ function releaseForShift(where, role, note) {
431
+ const held = heldBranchLock(where);
432
+ if (!held) return null;
433
+ const locks = require("./lock");
434
+ const device = locks.deviceId(where);
435
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
436
+ const relative = `shift-notes/${role || path.basename(where.worktree)}/${stamp}-${device}.md`;
437
+ const file = path.join(where.root, ...relative.split("/"));
438
+ fs.mkdirSync(path.dirname(file), { recursive: true });
439
+ fs.writeFileSync(file, note, { flag: "wx" });
440
+ let released;
441
+ try {
442
+ released = locks.releaseBranch(where, where.worktree, held.branch, { notePath: relative });
443
+ } catch (error) {
444
+ fs.rmSync(file, { force: true });
445
+ for (const dir of [path.dirname(file), path.dirname(path.dirname(file))]) {
446
+ try {
447
+ fs.rmdirSync(dir);
448
+ } catch {
449
+ // not empty, or already gone
450
+ }
451
+ }
452
+ throw new ShiftError(`the branch lock of ${held.branch} could not be released, so no note was stored: ${error.message}`);
453
+ }
454
+ let archived = null;
455
+ try {
456
+ archived = require("./chat/archive").sync(where);
457
+ } catch (error) {
458
+ archived = { error: error.message };
459
+ }
460
+ return {
461
+ branch: held.branch, head: released.lock.head, note: relative,
462
+ archived: archived && !archived.error ? { pushed: Boolean(archived.pushed), why: archived.reason || null } : { pushed: false, why: archived ? archived.error : null },
463
+ };
464
+ }
465
+
466
+ // \`keel shift resume\` is the takeover under \`sync: lock: true\` (#526 D14):
467
+ // the worktree's branch lock, else the latest lock this role last held, is
468
+ // taken after switching the worktree to that branch at the remote's tip.
469
+ function takeOver(where, role) {
470
+ if (!require("./config").readSyncDeclaration(where.worktree).lock) return null;
471
+ const cwd = where.worktree;
472
+ const dirty = git(cwd, ["status", "--porcelain=v1", "--untracked-files=all"]).out.split("\n").filter(Boolean).map((line) => line.slice(3));
473
+ if (dirty.length) throw new ShiftError(`${cwd} has uncommitted or untracked paths: ${dirty.join(", ")}; resume switches branches and discards nothing, so commit or move them first.`);
474
+ const remotes = git(cwd, ["remote"]).out.split("\n").filter(Boolean);
475
+ if (!remotes.length) return null;
476
+ const remote = remotes.includes("origin") ? "origin" : remotes[0];
477
+ const fetched = git(cwd, ["fetch", "--no-tags", "-q", remote, "+refs/keel/lock/*:refs/keel/lock/*"]);
478
+ if (!fetched.ok) throw new ShiftError(`cannot fetch the branch locks from ${remote}: ${fetched.err || fetched.out}`);
479
+ const locks = require("./lock");
480
+ const all = locks.branchLocks(where, cwd);
481
+ const here = git(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
482
+ const current = here.ok ? here.out : null;
483
+ const target = all.find((lock) => lock.branch === current)
484
+ || all.filter((lock) => role && locks.roleOf(lock.holder) === role).sort((x, y) => y.seq - x.seq)[0];
485
+ if (!target) return null;
486
+ const device = locks.existingDeviceId(where);
487
+ if (target.state === "held" && target.device !== device && locks.liveFor(target, Date.now(), locks.GRACE_MS)) {
488
+ throw new ShiftError(`branch ${target.branch} is held by ${target.holder} until ${target.expires}; nothing was switched or taken. `
489
+ + `Wait for its \`keel shift ready\`, or take it with \`keel lock acquire --branch ${target.branch} --break "<reason>"\`.`);
490
+ }
491
+ const branch = target.branch;
492
+ const tracking = git(cwd, ["fetch", "--no-tags", "-q", remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`]);
493
+ if (!tracking.ok) throw new ShiftError(`cannot fetch ${branch} from ${remote}: ${tracking.err || tracking.out}`);
494
+ const exists = git(cwd, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).ok;
495
+ const switched = branch === current ? { ok: true }
496
+ : exists ? git(cwd, ["switch", "-q", branch]) : git(cwd, ["switch", "-q", "-c", branch, "--track", `${remote}/${branch}`]);
497
+ if (!switched.ok) throw new ShiftError(`cannot switch to ${branch}: ${switched.err || switched.out}`);
498
+ const forward = git(cwd, ["merge", "-q", "--ff-only", `${remote}/${branch}`]);
499
+ if (!forward.ok) throw new ShiftError(`${branch} cannot fast-forward to ${remote}/${branch}: ${forward.err || forward.out}`);
500
+ let taken;
501
+ try {
502
+ taken = locks.acquireBranch(where, cwd, branch, {});
503
+ } catch (error) {
504
+ throw new ShiftError(`the branch lock of ${branch} could not be taken: ${error.message}`);
505
+ }
506
+ try {
507
+ require("./chat/archive").pull(where);
508
+ } catch {
509
+ // the note may already be here, or the archive be off; said below if absent
510
+ }
511
+ const notePath = target.note ? path.join(where.root, ...target.note.split("/")) : null;
512
+ return {
513
+ branch, head: git(cwd, ["rev-parse", "HEAD"]).out, from: target.holder, messages: taken.messages || [],
514
+ note: notePath && fs.existsSync(notePath) ? notePath : null, notePath: target.note || null,
515
+ };
516
+ }
517
+
381
518
  function readyRole(where, options) {
382
519
  const bound = store.currentRole(where);
383
520
  if (options.role) {
@@ -477,8 +614,11 @@ function ready(where, options) {
477
614
  if (!result.ready && !options.forceReason) {
478
615
  throw new ShiftError(`${renderCheck(result)}\nResolve these, or give --force-reason "<why they may stay>".`);
479
616
  }
480
- const text = readNoteText(options).replace(/\s+$/, "");
617
+ let text = readNoteText(options).replace(/\s+$/, "");
481
618
  if (!text.trim()) throw new ShiftError("keel shift ready needs the shift note: give it as text, with --file, or on stdin.");
619
+ // What stays on this machine goes into the note (#526 D16).
620
+ const leftHere = [...(result.localOnly || []), ...(options.forceReason ? result.items.map((item) => `${item.kind}: ${item.detail}`) : [])];
621
+ if (leftHere.length) text = `${text}\n\n## Not on the remote at hand-over\n\n${leftHere.map((line) => `- ${line}`).join("\n")}`;
482
622
  const stamp = store.isoLocal(new Date());
483
623
  const desktop = desktopSession();
484
624
  const pid = desktop ? desktopProcess() : null;
@@ -498,6 +638,9 @@ function ready(where, options) {
498
638
  options.forceReason && result.items.length ? `\nLeft as is (${options.forceReason}):\n${result.items.map((item) => `- ${item.kind}: ${item.detail}`).join("\n")}` : "",
499
639
  ].filter((line, index) => index < 2 || line !== "").concat("").join("\n");
500
640
  const note = ownNotePath(where, role);
641
+ // Under the lock, the hand-over is the lock changing hands (#526 D9): a
642
+ // release that fails stores no note at all.
643
+ const handed = releaseForShift(where, role, `${head}\n${text}\n`);
501
644
  writeFileAtomic(note, `${head}\n${text}\n`);
502
645
  // Requests are chat records; without a role there is none to close (D2).
503
646
  const open = role ? shiftRequests(where, role).filter((r) => r.open) : [];
@@ -517,7 +660,7 @@ function ready(where, options) {
517
660
  // waiter carries it out within seconds; `keel tick` stays as the fallback (#388 D1).
518
661
  const queued = options.wake && cli ? queueHandOff(where, role, cli) : null;
519
662
  const waiter = options.wake && !queued ? armWake(where, role, since) : queued ? armHandOver(where, role) : null;
520
- return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, queued, startedBy: role ? null : options.forceReason, desktop, pid, cli, worktree: where.worktree };
663
+ return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, queued, startedBy: role ? null : options.forceReason, desktop, pid, cli, worktree: where.worktree, handed };
521
664
  }
522
665
 
523
666
  // --- the CLI hand-off queue (#357) --------------------------------------------------
@@ -892,10 +1035,27 @@ function resolveShiftModel(worktree, declared) {
892
1035
  // finished or gone one is retired (stopped) and a new session starts. A claim
893
1036
  // left by a runner that died is settled, and a failed start is tried again
894
1037
  // (#408). `only` limits the step to one role (the waiter's).
1038
+ // A hand-over starts no session while another device holds the branch of the
1039
+ // role's worktree, by the last fetched lock (#526 D17); the entry says why.
1040
+ function waitsForLock(where, entry) {
1041
+ if (!entry.worktree || !require("./config").readSyncDeclaration(where.worktree).lock) return false;
1042
+ const here = git(entry.worktree, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1043
+ if (!here.ok || !here.out) return false;
1044
+ const locks = require("./lock");
1045
+ const sha = git(entry.worktree, ["rev-parse", "--verify", "--quiet", `${locks.LOCK_PREFIX}${here.out}`]);
1046
+ const lock = sha.ok ? locks.parseLock(entry.worktree, sha.out) : null;
1047
+ if (!lock || lock.state !== "held" || lock.device === locks.existingDeviceId(where) || !locks.liveFor(lock, Date.now(), locks.GRACE_MS)) return false;
1048
+ const why = `branch ${here.out} is held by ${lock.holder} until ${lock.expires}`;
1049
+ const current = store.readJsonFile(queueFile(where, entry.role));
1050
+ if (current && current.waiting_on !== why) store.writeJsonAtomic(where, queueFile(where, entry.role), { ...current, waiting_on: why });
1051
+ return true;
1052
+ }
1053
+
895
1054
  function handOver(where, only = null) {
896
1055
  const { readShiftDeclaration } = require("./config");
897
1056
  const claude = process.env.KEEL_CLAUDE || "claude";
898
- const queuedEntries = handOffs(where).filter((entry) => actionable(entry) && (!only || entry.role === only));
1057
+ const queuedEntries = handOffs(where).filter((entry) => actionable(entry) && (!only || entry.role === only))
1058
+ .filter((entry) => !waitsForLock(where, entry));
899
1059
  if (!queuedEntries.length) return [];
900
1060
  const queried = queryAgents(claude);
901
1061
  const sessions = queried.rows;
@@ -975,7 +1135,8 @@ function describeHandOff(entry) {
975
1135
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}${entry.new_name ? ` "${entry.new_name}"` : ""}${entry.model ? ` on model ${entry.model} (${entry.model_source})` : ""}`
976
1136
  : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}; ${retryNote(entry)}`
977
1137
  : entry.state === "starting" ? `starting since ${entry.starting_at} (attempt ${entry.attempts} of ${HANDOVER_ATTEMPTS})`
978
- : entry.waiting_on ? `pending: cannot ask the host — ${entry.waiting_on}` : "pending: waits for the session to go idle";
1138
+ : entry.waiting_on && /^branch .* is held by /.test(entry.waiting_on) ? `pending: ${entry.waiting_on}`
1139
+ : entry.waiting_on ? `pending: cannot ask the host — ${entry.waiting_on}` : "pending: waits for the session to go idle";
979
1140
  // An entry from before #399 recorded whether the old session's rename showed.
980
1141
  const renamed = entry.state === "delivered" && "renamed" in entry ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
981
1142
  const removed = (entry.removed || []).length ? `; older sessions removed from \`claude agents\` (transcripts kept by Keel): ${entry.removed.join(", ")}` : "";
@@ -1233,8 +1394,11 @@ function removeAtResume(where, role, text) {
1233
1394
 
1234
1395
  function resume(where, named = null) {
1235
1396
  const role = resumeRole(where, named);
1397
+ const taken = takeOver(where, role);
1398
+ // A note handed over on another machine arrives with the archive (#526 D14).
1399
+ if (taken && taken.note && !waitingNote(where, role)) writeFileAtomic(ownNotePath(where, role), fs.readFileSync(taken.note, "utf8"));
1236
1400
  const note = waitingNote(where, role);
1237
- if (!note) return { role: role || null, note: null, text: null };
1401
+ if (!note) return { role: role || null, note: null, text: null, taken };
1238
1402
  const text = fs.readFileSync(note, "utf8");
1239
1403
  const stamp = store.isoLocal(new Date()).replace(/[:+]/g, "");
1240
1404
  const history = path.join(shiftDir(where), "history", `${role || path.basename(note, ".md")}-${stamp}.md`);
@@ -1254,7 +1418,7 @@ function resume(where, named = null) {
1254
1418
  ? store.post(where, { group, text, refs: [REF] })
1255
1419
  : store.writeRecord(where, { group, kind: "message", from: role, refs: [REF], text })).id;
1256
1420
  }
1257
- return { role, note: history, text, told, removed: removeAtResume(where, role, text), waiting: role ? unstarted(where, role) : [], commits: noteCommits(where.worktree, text, knownSessionIds(where)), merged_branch: mergedBranch(where.worktree), fetched: lastFetch(where.worktree) };
1421
+ return { role, note: history, text, told, removed: removeAtResume(where, role, text), waiting: role ? unstarted(where, role) : [], commits: noteCommits(where.worktree, text, knownSessionIds(where)), merged_branch: mergedBranch(where.worktree), fetched: lastFetch(where.worktree), taken };
1258
1422
  }
1259
1423
 
1260
1424
  function status(where) {
@@ -1663,7 +1827,12 @@ function runShift(argv) {
1663
1827
  const result = ready(where, { ...options, text: rest.join(" ") });
1664
1828
  const whose = result.role || "this worktree (no chat role, so no request to close)";
1665
1829
  const hint = clearHint(result, where);
1666
- out({ ...result, clear: hint }, `Stored the shift note for ${whose} at ${result.note}${result.closed.length ? ` and closed ${result.closed.join(", ")}` : ""}.\n${hint}`);
1830
+ const handedText = result.handed
1831
+ ? `Released the branch lock of ${result.handed.branch} at ${String(result.handed.head || "none").slice(0, 8)} with the note ${result.handed.note}; `
1832
+ + (result.handed.archived.pushed ? "the chat archive carrying it was pushed.\n"
1833
+ : `the note stayed on this machine (${result.handed.archived.why || "the archive was not pushed"}).\n`)
1834
+ : "";
1835
+ out({ ...result, clear: hint }, `${handedText}Stored the shift note for ${whose} at ${result.note}${result.closed.length ? ` and closed ${result.closed.join(", ")}` : ""}.\n${hint}`);
1667
1836
  return 0;
1668
1837
  }
1669
1838
  case "wake-wait": {
@@ -1697,8 +1866,12 @@ function runShift(argv) {
1697
1866
  }
1698
1867
  case "resume": {
1699
1868
  const result = resume(where, options.role);
1869
+ const takenText = result.taken
1870
+ ? `Took over branch ${result.taken.branch} at ${result.taken.head.slice(0, 8)} from ${result.taken.from}.${result.taken.messages.length ? ` ${result.taken.messages.join(" ")}` : ""}`
1871
+ + `${result.taken.notePath && !result.taken.note ? ` Its note ${result.taken.notePath} is not here; run \`keel chat archive pull\` once the archive is pushed.` : ""}\n\n`
1872
+ : "";
1700
1873
  if (!result.note) {
1701
- out(result, `No shift note waits for ${result.role || "this worktree"}.`);
1874
+ out(result, `${takenText}No shift note waits for ${result.role || "this worktree"}.`);
1702
1875
  return 0;
1703
1876
  }
1704
1877
  // A new shift of the patrolling role re-creates its schedule (#260).
@@ -1734,7 +1907,7 @@ function runShift(argv) {
1734
1907
  const removed = (result.removed || []).length
1735
1908
  ? `\n\nRemoved old sessions from claude agents: ${result.removed.join(", ")}; \`keel shift history ${result.role} --show <id>\` prints each.`
1736
1909
  : "";
1737
- out(result, `${result.text.replace(/\s+$/, "")}${commits}${stale}\n\n(The note moved to ${result.note}.)${removed}${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}${remote}`);
1910
+ out(result, `${takenText}${result.text.replace(/\s+$/, "")}${commits}${stale}\n\n(The note moved to ${result.note}.)${removed}${still}${remind ? `\n\n${patrolReminder(patrol)}` : ""}${remote}`);
1738
1911
  return 0;
1739
1912
  }
1740
1913
  case "history": {