@christang/keel 5.134.0 → 5.136.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/README.md CHANGED
@@ -242,9 +242,10 @@ session reads that restore as another session's request and stops to ask you. It
242
242
  session, so it takes no scope, and it covers no other session, no clear or archive, and no repository
243
243
  action.
244
244
 
245
- `self-shift` (#319) is its outgoing counterpart: the three steps `keel shift ready --wake` prints on
246
- the desktop app once the note is stored — create the one-shot wake task (which unarchives the
247
- session first if needed, #326), rename the session, clear it. Remote Control stays on (#324). It does not
245
+ `self-shift` (#319) is its outgoing counterpart: the four steps `keel shift ready --wake` prints on
246
+ the desktop app once the note is stored — create the wake task (which waits for the clear with
247
+ `keel shift await-clear`, then unarchives the session first if needed, #326), start it with
248
+ `run_scheduled_task`, rename the session, clear it. The shift takes well under a minute. Remote Control stays on (#324). It does not
248
249
  decide that a shift happens; that stays with the task-boundary rule and the coordinator. It takes no
249
250
  scope.
250
251
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.134.0 -->
1
+ <!-- keel:start version=5.136.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the only durable authority — never native memory, goals, or transcripts.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.134.0",
3
+ "version": "5.136.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.134.0",
9
+ "version": "5.136.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.134.0",
5
+ "version": "5.136.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.134.0",
3
+ "version": "5.136.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.134.0",
3
+ "version": "5.136.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",
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.134.0"
51
- PROTOCOL_VERSION = "5.134.0"
50
+ PACKAGE_VERSION = "5.136.0"
51
+ PROTOCOL_VERSION = "5.136.0"
52
52
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
53
53
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
54
54
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -6817,8 +6817,8 @@ def validate_self_shift_authorization_scenario() -> int:
6817
6817
  report(f"{label} a desktop ready --wake with self-shift declared does not say the steps are standing-authorized: {granted.stdout.strip()} {granted.stderr.strip()}")
6818
6818
  return 1
6819
6819
  # Three once the Remote Control step went (#324).
6820
- if "take these three steps now" not in granted.stdout:
6821
- report(f"{label} a desktop ready --wake with self-shift declared does not cover three steps: {granted.stdout.strip()}")
6820
+ if "take these four steps now" not in granted.stdout:
6821
+ report(f"{label} a desktop ready --wake with self-shift declared does not cover four steps: {granted.stdout.strip()}")
6822
6822
  return 1
6823
6823
  run_keel(verify, "shift", "resume", env=desktop)
6824
6824
 
@@ -6909,6 +6909,118 @@ def validate_shift_restore_authorization_scenario() -> int:
6909
6909
  return 0
6910
6910
 
6911
6911
 
6912
+ def validate_shift_await_clear_scenario() -> int:
6913
+ """`keel shift await-clear` returns once the outgoing process is gone.
6914
+
6915
+ The desktop wake starts at once and waits on it, so it can never land
6916
+ before the clear (D1, D2 of shift-desktop-wake-in-a-minute).
6917
+ """
6918
+ label = "shift-await-clear:"
6919
+ with tempfile.TemporaryDirectory(prefix="keel-shift-await-") as raw:
6920
+ base = Path(raw)
6921
+ _rtl, verify, env, _ = shift_scratch(base)
6922
+ # Reaped as soon as it exits, as the app reaps its session's process;
6923
+ # an unreaped zombie still answers kill(pid, 0).
6924
+ brief = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(1)"])
6925
+ reaper = threading.Thread(target=brief.wait)
6926
+ reaper.start()
6927
+ started = time.monotonic()
6928
+ gone = run_keel(verify, "shift", "await-clear", "--pid", str(brief.pid), "--timeout-ms", "15000", env=env)
6929
+ reaper.join()
6930
+ if gone.returncode != 0:
6931
+ report(f"{label} await-clear did not exit 0 once the process exited: {gone.returncode} {gone.stdout.strip()} {gone.stderr.strip()}")
6932
+ return 1
6933
+ if "cleared" not in gone.stdout:
6934
+ report(f"{label} await-clear did not say `cleared` once the process exited: {gone.stdout.strip()}")
6935
+ return 1
6936
+ if time.monotonic() - started > 10:
6937
+ report(f"{label} await-clear took more than 10 s to notice the process exited.")
6938
+ return 1
6939
+ live = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
6940
+ try:
6941
+ held = run_keel(verify, "shift", "await-clear", "--pid", str(live.pid), "--timeout-ms", "500", env=env)
6942
+ finally:
6943
+ live.kill()
6944
+ live.wait()
6945
+ if held.returncode != 1:
6946
+ report(f"{label} await-clear on a live process did not exit 1: {held.returncode} {held.stdout.strip()} {held.stderr.strip()}")
6947
+ return 1
6948
+ if "not cleared" not in held.stdout:
6949
+ report(f"{label} await-clear on a live process did not say `not cleared`: {held.stdout.strip()}")
6950
+ return 1
6951
+ desktop = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000", "CLAUDE_CODE_ENTRYPOINT": "claude-desktop",
6952
+ "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319", "KEEL_SHIFT_DESKTOP_PID": "4242"}
6953
+ armed = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R031", env=desktop)
6954
+ note = mailbox_common_dir(verify) / "keel-chat" / "shift" / "verify.md"
6955
+ if armed.returncode != 0:
6956
+ report(f"{label} a desktop ready --wake failed: {armed.stderr.strip()}")
6957
+ return 1
6958
+ if "Desktop process: 4242." not in note.read_text(encoding="utf-8"):
6959
+ report(f"{label} a desktop ready --wake does not record the desktop process.")
6960
+ return 1
6961
+ if "shift-await-clear" not in {name for name, _ in SCENARIOS}:
6962
+ report(f"{label} scenario is not registered.")
6963
+ return 1
6964
+ report("shift-await-clear scenario passed.")
6965
+ return 0
6966
+
6967
+
6968
+ def validate_shift_desktop_wake_overdue_scenario() -> int:
6969
+ """`keel shift status` flags a desktop note whose wake is overdue.
6970
+
6971
+ A wake task that never runs leaves no trace anywhere else; the waiting
6972
+ note with its recorded desktop session is the one place a coordinator or
6973
+ patrol can see it (D2 of shift-desktop-wake-confirm).
6974
+ """
6975
+ label = "shift-desktop-wake-overdue:"
6976
+ with tempfile.TemporaryDirectory(prefix="keel-shift-overdue-") as raw:
6977
+ base = Path(raw)
6978
+ _rtl, verify, env, _ = shift_scratch(base)
6979
+ env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000"}
6980
+ desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319"}
6981
+ armed = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R021", env=desktop)
6982
+ if armed.returncode != 0:
6983
+ report(f"{label} ready --wake on the desktop app failed: {armed.stderr.strip()}")
6984
+ return 1
6985
+ young = run_keel(verify, "shift", "status", env={**env, "KEEL_SHIFT_WAKE_OVERDUE_MS": "3600000"})
6986
+ if "overdue" in young.stdout:
6987
+ report(f"{label} a note written just now is already called overdue: {young.stdout.strip()}")
6988
+ return 1
6989
+ late = run_keel(verify, "shift", "status", env={**env, "KEEL_SHIFT_WAKE_OVERDUE_MS": "0"})
6990
+ for needle in ("overdue", "local_test-319", "list_task_runs", "send_message"):
6991
+ if needle not in late.stdout:
6992
+ report(f"{label} status past the overdue time does not name {needle}: {late.stdout.strip()}")
6993
+ return 1
6994
+ # Without the override the overdue time is three minutes (D4 of
6995
+ # shift-desktop-wake-in-a-minute).
6996
+ note = mailbox_common_dir(verify) / "keel-chat" / "shift" / "verify.md"
6997
+ for minutes, flagged in ((2, False), (4, True)):
6998
+ then = time.time() - minutes * 60
6999
+ os.utime(note, (then, then))
7000
+ row = run_keel(verify, "shift", "status", env=env)
7001
+ if ("overdue" in row.stdout) != flagged:
7002
+ report(f"{label} a desktop note written {minutes} minutes ago is {'not ' if flagged else ''}flagged overdue by default: {row.stdout.strip()}")
7003
+ return 1
7004
+ run_keel(verify, "shift", "resume", env=env)
7005
+ plain = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R022", env=env)
7006
+ if plain.returncode != 0:
7007
+ report(f"{label} ready --wake outside the desktop app failed: {plain.stderr.strip()}")
7008
+ return 1
7009
+ other = run_keel(verify, "shift", "status", env={**env, "KEEL_SHIFT_WAKE_OVERDUE_MS": "0"})
7010
+ if "overdue" in other.stdout:
7011
+ report(f"{label} a note with no desktop session is called overdue: {other.stdout.strip()}")
7012
+ return 1
7013
+ for relative, word in (("docs/shift-change.md", "overdue"), ("docs/shift-change.zh-CN.md", "超时")):
7014
+ if word not in (ROOT / relative).read_text(encoding="utf-8"):
7015
+ report(f"{label} {relative} does not say {word}.")
7016
+ return 1
7017
+ if "shift-desktop-wake-overdue" not in {name for name, _ in SCENARIOS}:
7018
+ report(f"{label} scenario is not registered.")
7019
+ return 1
7020
+ report("shift-desktop-wake-overdue scenario passed.")
7021
+ return 0
7022
+
7023
+
6912
7024
  def validate_shift_desktop_wake_scenario() -> int:
6913
7025
  """Issue #319: on the desktop app a clear starts no session until a prompt.
6914
7026
 
@@ -6922,7 +7034,8 @@ def validate_shift_desktop_wake_scenario() -> int:
6922
7034
  base = Path(raw)
6923
7035
  _rtl, verify, env, _ = shift_scratch(base)
6924
7036
  env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000"}
6925
- desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319"}
7037
+ # The pid is pinned so the scenario does not depend on running under a `claude` process (CI does not).
7038
+ desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319", "KEEL_SHIFT_DESKTOP_PID": "4242"}
6926
7039
  note = mailbox_common_dir(verify) / "keel-chat" / "shift" / "verify.md"
6927
7040
 
6928
7041
  armed = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R011", env=desktop)
@@ -6969,6 +7082,33 @@ def validate_shift_desktop_wake_scenario() -> int:
6969
7082
  if not look < armed.stdout.find("unarchive_session") < armed.stdout.find("send_message", look):
6970
7083
  report(f"{label} the wake does not check get_session, then unarchive_session, then send_message: {armed.stdout.strip()}")
6971
7084
  return 1
7085
+ # The wake starts at once and waits for the clear itself, so no minute
7086
+ # tick sits in the shift (D3 of shift-desktop-wake-in-a-minute).
7087
+ for needle in ("await-clear", "run_scheduled_task", "keel-shift-wake-verify",
7088
+ "mcp__scheduled-tasks__run_scheduled_task"):
7089
+ if needle not in armed.stdout:
7090
+ report(f"{label} the desktop clear hint does not name {needle}: {armed.stdout.strip()}")
7091
+ return 1
7092
+ for needle in ("fireAt", "three minutes"):
7093
+ if needle in armed.stdout:
7094
+ report(f"{label} the desktop clear hint still schedules the wake ({needle}): {armed.stdout.strip()}")
7095
+ return 1
7096
+ made = armed.stdout.find("create_scheduled_task")
7097
+ run = armed.stdout.find("run_scheduled_task", made + 1)
7098
+ if not made < run < armed.stdout.find("set_session_title", run) < armed.stdout.find("clear_session", run):
7099
+ report(f"{label} the desktop clear hint does not order create, run_scheduled_task, rename, clear: {armed.stdout.strip()}")
7100
+ return 1
7101
+ waits = armed.stdout.find("await-clear")
7102
+ if not waits < armed.stdout.find("get_session", waits) < armed.stdout.find("send_message", waits):
7103
+ report(f"{label} the wake does not await the clear before get_session and send_message: {armed.stdout.strip()}")
7104
+ return 1
7105
+ # The wake confirms delivery: anything but delivered or queued after the
7106
+ # archived retry is a failed wake the owner hears about (D1 of
7107
+ # shift-desktop-wake-confirm).
7108
+ for needle in ("PushNotification", "WAKE FAILED", "delivered"):
7109
+ if needle not in armed.stdout[armed.stdout.find("send_message"):]:
7110
+ report(f"{label} the desktop wake does not say {needle} after send_message: {armed.stdout.strip()}")
7111
+ return 1
6972
7112
  if "archived copy" in armed.stdout:
6973
7113
  report(f"{label} the desktop clear hint still says the rename tells an archived copy apart: {armed.stdout.strip()}")
6974
7114
  return 1
@@ -7016,7 +7156,8 @@ def validate_shift_desktop_wake_scenario() -> int:
7016
7156
  report(f"{label} {relative} still says {stale}.")
7017
7157
  return 1
7018
7158
  for needle in ("send_message", "set_remote_control", "set_session_title", "shift-restore",
7019
- "get_session", "unarchive_session"):
7159
+ "get_session", "unarchive_session", "PushNotification", "WAKE FAILED",
7160
+ "await-clear", "run_scheduled_task"):
7020
7161
  if needle not in text:
7021
7162
  report(f"{label} {relative} does not name {needle} for the desktop app.")
7022
7163
  return 1
@@ -40555,6 +40696,8 @@ SCENARIOS: tuple = (
40555
40696
  ("host-run-session", validate_host_run_session_scenario),
40556
40697
  ("shift-without-role", validate_shift_without_role_scenario),
40557
40698
  ("shift-desktop-wake", validate_shift_desktop_wake_scenario),
40699
+ ("shift-desktop-wake-overdue", validate_shift_desktop_wake_overdue_scenario),
40700
+ ("shift-await-clear", validate_shift_await_clear_scenario),
40558
40701
  ("shift-restore-authorization", validate_shift_restore_authorization_scenario),
40559
40702
  ("self-shift-authorization", validate_self_shift_authorization_scenario),
40560
40703
  ("resource-lock", validate_resource_lock_scenario),
package/src/core/shift.js CHANGED
@@ -29,6 +29,7 @@ const USAGE = [
29
29
  "keel shift start <role> [text] wake the cleared role to resume (once its note waits)",
30
30
  "keel shift resume [--role r] [--json] print and consume this role's note (--role: from an unbound worktree)",
31
31
  "keel shift status [--json] each role's shift state",
32
+ "keel shift await-clear --pid <pid> wait until a desktop session's process has exited (its clear); exit 1 after --timeout-ms",
32
33
  "keel shift history [role] [--grep t] a role's past transcripts and notes; --grep searches them (#304)",
33
34
  "Options: --repo <path>. See docs/shift-change.md.",
34
35
  ].join("\n");
@@ -373,6 +374,45 @@ function desktopSession() {
373
374
  return process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop" && id ? id : null;
374
375
  }
375
376
 
377
+ // The desktop session's Claude process: the nearest ancestor whose command's
378
+ // basename is `claude`. The app's clear stops it, which is what the wake
379
+ // waits for (D1 of shift-desktop-wake-in-a-minute).
380
+ function desktopProcess() {
381
+ const forced = Number(process.env.KEEL_SHIFT_DESKTOP_PID);
382
+ if (process.env.KEEL_SHIFT_DESKTOP_PID && Number.isInteger(forced) && forced > 0) return forced;
383
+ const table = processTable();
384
+ let pid = process.ppid;
385
+ for (let hops = 0; pid > 1 && hops < 32; hops += 1) {
386
+ const row = table.get(pid);
387
+ if (!row) return null;
388
+ // The app's path holds a space ("Application Support"), so match the
389
+ // executable's basename rather than split the command line.
390
+ if (/(?:^|\/)claude(?:\s|$)/.test(row.command)) return pid;
391
+ pid = row.ppid;
392
+ }
393
+ return null;
394
+ }
395
+
396
+ function alive(pid) {
397
+ try {
398
+ process.kill(pid, 0);
399
+ return true;
400
+ } catch (error) {
401
+ return error.code === "EPERM";
402
+ }
403
+ }
404
+
405
+ // Blocks until the process is gone or the limit passes (D2).
406
+ function awaitClear(pid, timeoutMs) {
407
+ const deadline = Date.now() + timeoutMs;
408
+ const pause = new Int32Array(new SharedArrayBuffer(4));
409
+ while (alive(pid)) {
410
+ if (Date.now() >= deadline) return false;
411
+ Atomics.wait(pause, 0, 0, 250);
412
+ }
413
+ return true;
414
+ }
415
+
376
416
  function ready(where, options) {
377
417
  const role = readyRole(where, options);
378
418
  if (options.wake && !role) {
@@ -395,11 +435,13 @@ function ready(where, options) {
395
435
  if (!text.trim()) throw new ShiftError("keel shift ready needs the shift note: give it as text, with --file, or on stdin.");
396
436
  const stamp = store.isoLocal(new Date());
397
437
  const desktop = desktopSession();
438
+ const pid = desktop ? desktopProcess() : null;
398
439
  const head = [
399
440
  `# Shift note: ${role || path.basename(where.worktree)}`,
400
441
  "",
401
442
  `Written ${stamp} in ${result.worktree}.`,
402
443
  desktop ? `Desktop session: ${desktop}.` : "",
444
+ desktop && pid ? `Desktop process: ${pid}.` : "",
403
445
  // A shift the role started itself; the patrol may nudge it to resume (#307 D4).
404
446
  options.wake ? "Self-initiated: this shift armed `keel shift ready --wake`." : "",
405
447
  !role ? `Started by hand: ${options.forceReason}.` : "",
@@ -422,7 +464,7 @@ function ready(where, options) {
422
464
  }
423
465
  }
424
466
  const waiter = options.wake ? armWake(where, role, since) : null;
425
- return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, startedBy: role ? null : options.forceReason, desktop, worktree: where.worktree };
467
+ return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, startedBy: role ? null : options.forceReason, desktop, pid, worktree: where.worktree };
426
468
  }
427
469
 
428
470
  // --- the one-shot wake (#293) -------------------------------------------------------
@@ -435,6 +477,12 @@ function ready(where, options) {
435
477
  const WAKE_SENDER = "keel-shift";
436
478
  const WAKE_SOURCES = new Set(["clear", "startup"]);
437
479
 
480
+ // Zero is a valid overdue time: it flags every desktop note at once.
481
+ function overdueMs() {
482
+ const value = Number(process.env.KEEL_SHIFT_WAKE_OVERDUE_MS);
483
+ return process.env.KEEL_SHIFT_WAKE_OVERDUE_MS && Number.isFinite(value) && value >= 0 ? value : 3 * 60 * 1000;
484
+ }
485
+
438
486
  function envMs(name, fallback) {
439
487
  const value = Number(process.env[name]);
440
488
  return Number.isFinite(value) && value > 0 ? value : fallback;
@@ -566,6 +614,12 @@ function status(where) {
566
614
  const stat = fs.statSync(path.join(folder, file));
567
615
  const row = entry(`${prefix}${file.slice(0, -3)}`);
568
616
  row.note = store.isoLocal(stat.mtime);
617
+ // A desktop wake that never ran leaves no trace but the waiting note
618
+ // (D2 of shift-desktop-wake-confirm).
619
+ const desktop = fs.readFileSync(path.join(folder, file), "utf8").match(/^Desktop session: (\S+)\.$/m);
620
+ if (desktop && Date.now() - stat.mtime.getTime() >= overdueMs()) {
621
+ row.overdueDesktop = desktop[1];
622
+ }
569
623
  if (prefix) {
570
624
  // The note's header names the worktree it was written in (#291 D6).
571
625
  const header = fs.readFileSync(path.join(folder, file), "utf8").match(/^Written \S+ in (.+)\.$/m);
@@ -708,6 +762,13 @@ function safeList(dir) {
708
762
  }
709
763
 
710
764
  function describe(row) {
765
+ const line = describeState(row);
766
+ if (!row.note || !row.overdueDesktop) return line;
767
+ return `${line}\n desktop wake overdue: nothing has resumed it; check the wake task's run with \`list_task_runs\`, `
768
+ + `and if it did not deliver, \`send_message\` session ${row.overdueDesktop} to run \`keel context\` and \`keel shift resume\``;
769
+ }
770
+
771
+ function describeState(row) {
711
772
  if (row.note && row.role.startsWith("worktree ")) {
712
773
  return `${row.role}: note waiting since ${row.note}; no chat role there, so tell the session in ${row.path || "that worktree"} to run \`keel shift resume\``;
713
774
  }
@@ -742,33 +803,41 @@ function clearHint(result) {
742
803
  let last;
743
804
  if (!result.role) last = `Without a chat role nothing wakes the new session; ${result.startedBy} — tell it to run \`keel shift resume\`.`;
744
805
  else if (result.waiter && result.desktop) {
745
- // Nothing starts a cleared desktop session but a prompt (#319 D3). A wake
746
- // that fires before the clear is queued, and the app then refuses the clear
747
- // to keep it, so rename and clear follow the task at once. Remote Control
748
- // stays on: the clear is accepted with it on, and turning it off waits for
749
- // a person's approval (#324 D1, D2 of shift-desktop-keep-remote-control).
806
+ // Nothing starts a cleared desktop session but a prompt (#319 D3). The app
807
+ // dispatches scheduled tasks once a minute, and a wake that lands before
808
+ // the clear gets it refused, so the wake starts at once and waits for the
809
+ // session's process to exit — the clear — before it sends (D3 of
810
+ // shift-desktop-wake-in-a-minute). Remote Control stays on (#324); the app's
811
+ // auto-archive can still take the cleared session, so the wake unarchives
812
+ // first (#326), and a send that does not deliver reaches the owner.
813
+ const task = `keel-shift-wake-${result.role}`;
814
+ const resumeText = `${result.role}: your new shift starts now. `
815
+ + "Run `keel context` and `keel shift resume`, then restore Remote Control and this session's title as `keel shift resume` says.";
750
816
  last = [
751
817
  "On the Claude desktop app a clear starts no session until a prompt arrives, so the waiter alone wakes nothing (#319). "
752
- + "Leave Remote Control on: the clear is accepted with it on, and the app reconnects it after the clear under a new address, which a remote viewer has to open (#324). Do these in order:",
753
- // The app's auto-archive can take the cleared, idle session before the
754
- // wake, on every PR it ever had; dismissing bound PRs did not stop it, so
755
- // the wake unarchives first (#326 D1, D2 of shift-desktop-unarchive-wake).
756
- "1. Create a one-shot scheduled task with the host's `create_scheduled_task`, firing about three minutes later, "
757
- + `whose prompt first calls \`get_session\` on session \`${result.desktop}\` and, when it reports the session archived, calls \`unarchive_session\` on it; `
758
- + `then calls \`send_message\` to it with: "${result.role}: your new shift starts now. `
759
- + "Run `keel context` and `keel shift resume`, then restore Remote Control and this session's title as `keel shift resume` says.\" "
760
- + "If that send is still refused because the session is archived, it unarchives it and sends once more, and it says which path it took. "
761
- + "The app's auto-archive can archive the cleared session before the wake (#326); unarchiving brings back its worktree. "
762
- + "A task that fires before the clear gets the clear refused, so take the next two steps at once.",
763
- `2. Rename this session with \`set_session_title\` (for example "${result.role} · shifted ${store.isoLocal(new Date()).slice(0, 16)}"), so it reads as between shifts until the woken session renames it back.`,
764
- '3. Call clear_session("self").',
765
- "Keel creates no task. Running unattended needs `mcp__ccd_session_mgmt__set_remote_control`, `mcp__ccd_session_mgmt__get_session` "
766
- + "and `mcp__ccd_session_mgmt__unarchive_session` in `permissions.allow`, "
818
+ + "Leave Remote Control on: the clear is accepted with it on, and the app reconnects it after the clear under a new address, which a remote viewer has to open (#324). "
819
+ + "The whole shift takes well under a minute. Do these in order, without pausing between them:",
820
+ result.pid
821
+ ? `1. Create the ad-hoc task \`${task}\` with the host's \`create_scheduled_task\` (or \`update_scheduled_task\` when it exists), with no \`cronExpression\` and no fire time, and \`notifyOnCompletion: false\`. Its prompt: `
822
+ + `"Run \`keel shift await-clear --pid ${result.pid}\` with Bash. If it exits 1, the session was not cleared: send nothing, call \`PushNotification\` naming session ${result.desktop}, and start your reply with \`WAKE FAILED\`. `
823
+ + `If it exits 0, call \`get_session\` on session \`${result.desktop}\` and, when it reports the session archived, call \`unarchive_session\` on it; `
824
+ + `then call \`send_message\` to it with: '${resumeText}' `
825
+ + "If that send is refused because the session is archived, unarchive it and send once more, and say which path you took. "
826
+ + "A send result of `delivered` or `queued` is a delivered wake; any other result after that retry is a failed wake: call `PushNotification` naming the session and the result, and start your reply with `WAKE FAILED`.\" "
827
+ + "The app's auto-archive can archive the cleared session before the wake (#326); unarchiving brings back its worktree."
828
+ : "1. Keel found no `claude` process above this one, so nothing can wait for the clear: after the clear, type into the new session.",
829
+ result.pid
830
+ ? `2. Start it at once with \`run_scheduled_task\` on \`${task}\`. The run waits for this session's clear itself, so starting it first is safe.`
831
+ : "2. There is no task to start.",
832
+ `3. Rename this session with \`set_session_title\` (for example "${result.role} · shifted ${store.isoLocal(new Date()).slice(0, 16)}"), so it reads as between shifts until the woken session renames it back.`,
833
+ '4. Call clear_session("self").',
834
+ "Keel creates no task. Running unattended needs `mcp__ccd_session_mgmt__set_remote_control`, `mcp__ccd_session_mgmt__get_session`, "
835
+ + "`mcp__ccd_session_mgmt__unarchive_session` and `mcp__scheduled-tasks__run_scheduled_task` in `permissions.allow`, "
767
836
  + "and `shift-restore` under `authorize:` in keel/config.yaml so the woken session does not stop to ask.",
768
837
  // The outgoing side's confirmation is the repository's to waive (#319).
769
838
  require("./config").readStandingAuthorization(result.worktree).scopes.has("self-shift")
770
- ? "Standing-authorized by `self-shift` in keel/config.yaml: take these three steps now, without asking."
771
- : "Declaring `self-shift` under authorize: in keel/config.yaml lets a session take these three steps without asking.",
839
+ ? "Standing-authorized by `self-shift` in keel/config.yaml: take these four steps now, without asking."
840
+ : "Declaring `self-shift` under authorize: in keel/config.yaml lets a session take these four steps without asking.",
772
841
  ].join("\n");
773
842
  } else if (result.waiter) {
774
843
  last = `The wake is armed: once ${result.role}'s next session starts (after a clear or a fresh start), it gets one message to run \`keel shift resume\`. The waiter gives up after two hours.`;
@@ -794,6 +863,8 @@ function runShift(argv) {
794
863
  else if (arg === "--role") options.role = argv[++index] || "";
795
864
  else if (arg === "--since") options.since = Number(argv[++index]);
796
865
  else if (arg === "--wake") options.wake = true;
866
+ else if (arg === "--pid") options.pid = Number(argv[++index]);
867
+ else if (arg === "--timeout-ms") options.timeoutMs = Number(argv[++index]);
797
868
  else if (arg === "--grep") options.grep = argv[++index] || "";
798
869
  else if (arg === "--help" || arg === "-h") {
799
870
  process.stdout.write(`${USAGE}\n`);
@@ -870,6 +941,15 @@ function runShift(argv) {
870
941
  out(result, renderHistory(result, options.grep));
871
942
  return options.grep && !result.segments.some((segment) => segment.matches.length) ? 1 : 0;
872
943
  }
944
+ case "await-clear": {
945
+ if (!Number.isInteger(options.pid) || options.pid <= 1) throw new ShiftError("keel shift await-clear needs --pid <the desktop session's process id>.");
946
+ const limit = Number.isFinite(options.timeoutMs) && options.timeoutMs >= 0 ? options.timeoutMs : 120000;
947
+ const cleared = awaitClear(options.pid, limit);
948
+ out({ pid: options.pid, cleared }, cleared
949
+ ? `cleared: process ${options.pid} has exited.`
950
+ : `not cleared: process ${options.pid} still runs after ${limit} ms.`);
951
+ return cleared ? 0 : 1;
952
+ }
873
953
  case "status": {
874
954
  const rows = status(where);
875
955
  out({ roles: rows }, rows.length ? rows.map(describe).join("\n") : "No shift change recorded.");
@@ -898,4 +978,5 @@ function waitingFor(repo) {
898
978
  return { note, since: store.isoLocal(fs.statSync(note).mtime) };
899
979
  }
900
980
 
901
- module.exports = { check, describe, runShift, shiftStatus: status, waitingFor };
981
+ module.exports = {
982
+ desktopProcess, check, describe, runShift, shiftStatus: status, waitingFor };