@christang/keel 5.161.0 → 5.163.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.161.0",
3
+ "version": "5.163.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.161.0 -->
1
+ <!-- keel:start version=5.163.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.
package/bin/keel.js CHANGED
@@ -2314,12 +2314,30 @@ function runDoctor(options) {
2314
2314
  printFastPrePushSurface(repo);
2315
2315
  printSourceRepoCliResolution(repo);
2316
2316
  printChatRoleDrift(repo);
2317
+ printLaunchdJobs();
2317
2318
 
2318
2319
  return authorizationOk ? checkStatus : 1;
2319
2320
  }
2320
2321
 
2321
2322
  // Chat role bindings that drifted from where sessions run (#301 D3). Nothing
2322
2323
  // is printed without a chat store that binds roles.
2324
+ // A launchd job that names a node an upgrade removed fails silently every
2325
+ // interval (#387); the report does not change doctor's exit status, since the
2326
+ // job belongs to the machine and not to this repository.
2327
+ function printLaunchdJobs() {
2328
+ const jobs = require("../src/core/launchd").inspectJobs();
2329
+ if (!jobs.length) return;
2330
+ const gone = jobs.filter((job) => !job.exists);
2331
+ for (const job of gone) {
2332
+ printDoctorLine(
2333
+ "launchd",
2334
+ "problem",
2335
+ `${job.name} runs ${job.program || "no program"}, which does not exist; re-create it with \`${job.recreate}\``
2336
+ );
2337
+ }
2338
+ if (!gone.length) printDoctorLine("launchd", "ok", `${jobs.length} dev.keel job${jobs.length === 1 ? "" : "s"}, each naming a node that exists`);
2339
+ }
2340
+
2323
2341
  function printChatRoleDrift(repo) {
2324
2342
  let where = null;
2325
2343
  try {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.161.0",
3
+ "version": "5.163.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.161.0",
9
+ "version": "5.163.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.161.0",
5
+ "version": "5.163.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.161.0",
3
+ "version": "5.163.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.161.0",
3
+ "version": "5.163.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",
@@ -49,8 +49,8 @@ REQUIRED_SCRIPTS = [
49
49
  "scripts/validate_plugin.py",
50
50
  ]
51
51
 
52
- PACKAGE_VERSION = "5.161.0"
53
- PROTOCOL_VERSION = "5.161.0"
52
+ PACKAGE_VERSION = "5.163.0"
53
+ PROTOCOL_VERSION = "5.163.0"
54
54
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
55
55
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
56
56
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -3365,6 +3365,90 @@ def validate_patrol_next_scenario() -> int:
3365
3365
  return 0
3366
3366
 
3367
3367
 
3368
+ def validate_launchd_stable_node_scenario() -> int:
3369
+ """Issue #387: a launchd job must name a node that outlives `brew upgrade`.
3370
+
3371
+ `keel tick task` printed `process.execPath`, Homebrew's versioned Cellar
3372
+ path, which is gone after an upgrade; launchd then fails silently every
3373
+ interval. The jobs now name the `node` on PATH that is the same binary (the
3374
+ symlink the package manager keeps current), leave plugin cache directories
3375
+ out of PATH, and `keel --doctor` reports a job whose node no longer exists.
3376
+ """
3377
+ label = "launchd-stable-node:"
3378
+ with tempfile.TemporaryDirectory(prefix="keel-launchd-387-") as raw:
3379
+ base = Path(raw)
3380
+ rtl, cx, env, _ = chat_wake_scratch(base)
3381
+ real = os.path.realpath(shutil.which("node") or "node")
3382
+ versioned = base / "cellar" / "node" / "9.9.9" / "bin"
3383
+ versioned.mkdir(parents=True)
3384
+ (versioned / "node").symlink_to(real)
3385
+ stable = base / "bin"
3386
+ stable.mkdir()
3387
+ (stable / "node").symlink_to(versioned / "node")
3388
+ cache = base / "home" / ".claude" / "plugins" / "cache" / "keel-marketplace" / "keel" / "5.149.0" / "bin"
3389
+ cache.mkdir(parents=True)
3390
+ path = os.pathsep.join([str(cache), str(stable), os.environ.get("PATH", "")])
3391
+ env = {**env, "PATH": path}
3392
+ write_text(rtl / "openspec/specs/.keep", "")
3393
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 60m\n runner: tick\n")
3394
+ subprocess.run(["git", "add", "-A"], cwd=rtl, check=True, capture_output=True)
3395
+ subprocess.run(["git", "commit", "-q", "-m", "tick"], cwd=rtl, check=True, capture_output=True)
3396
+
3397
+ def keel(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3398
+ return subprocess.run([str(stable / "node"), str(ROOT / "bin" / "keel.js"), *args], cwd=cwd, env=env,
3399
+ text=True, capture_output=True, check=False)
3400
+
3401
+ def program(plist: str) -> str:
3402
+ return (re.search(r"<key>ProgramArguments</key>\s*<array>\s*<string>(.*?)</string>", plist, re.S) or [None, ""])[1]
3403
+
3404
+ def path_of(plist: str) -> str:
3405
+ return (re.search(r"<key>PATH</key>\s*<string>(.*?)</string>", plist, re.S) or [None, ""])[1]
3406
+
3407
+ task = keel(rtl, "tick", "task")
3408
+ if task.returncode != 0:
3409
+ report(f"{label} keel tick task failed: {task.stderr!r}")
3410
+ return 1
3411
+ if program(task.stdout) != str(stable / "node"):
3412
+ report(f"{label} the tick job names the versioned node: {program(task.stdout)!r}, not {str(stable / 'node')!r}")
3413
+ return 1
3414
+ if str(stable) not in path_of(task.stdout).split(os.pathsep) or "plugins/cache" in path_of(task.stdout):
3415
+ report(f"{label} the tick job's PATH is not the stable directories without the plugin cache: {path_of(task.stdout)!r}")
3416
+ return 1
3417
+
3418
+ added = keel(cx, "chat", "wake", "add")
3419
+ plists = sorted((base / "agents").glob("dev.keel.chat-wake.*.plist"))
3420
+ if added.returncode != 0 or len(plists) != 1:
3421
+ report(f"{label} keel chat wake add wrote {len(plists)} LaunchAgents: {(added.stdout + added.stderr).strip()!r}")
3422
+ return 1
3423
+ waker = plists[0].read_text(encoding="utf-8")
3424
+ if program(waker) != str(stable / "node"):
3425
+ report(f"{label} the chat waker's LaunchAgent names the versioned node: {program(waker)!r}")
3426
+ return 1
3427
+ if "plugins/cache" in path_of(waker):
3428
+ report(f"{label} the chat waker's LaunchAgent keeps a plugin cache directory in PATH: {path_of(waker)!r}")
3429
+ return 1
3430
+
3431
+ gone = base / "Cellar" / "node" / "0.0.0" / "bin" / "node"
3432
+ broken = base / "agents" / "dev.keel.tick.x.plist"
3433
+ broken.write_text(task.stdout[task.stdout.index("<?xml"):task.stdout.index("</plist>") + 8].replace(str(stable / "node"), str(gone)), encoding="utf-8")
3434
+ problem = keel(rtl, "--doctor")
3435
+ line = next((l for l in problem.stdout.splitlines() if l.startswith("launchd: problem")), "")
3436
+ for needle in ("dev.keel.tick.x.plist", str(gone), "keel tick task"):
3437
+ if needle not in line:
3438
+ report(f"{label} doctor does not name {needle!r} for a job whose node is gone: {problem.stdout!r}")
3439
+ return 1
3440
+ broken.write_text(broken.read_text(encoding="utf-8").replace(str(gone), str(stable / "node")), encoding="utf-8")
3441
+ fine = keel(rtl, "--doctor")
3442
+ if "launchd: ok" not in fine.stdout or "launchd: problem" in fine.stdout:
3443
+ report(f"{label} doctor does not report ok once the node exists: {fine.stdout!r}")
3444
+ return 1
3445
+ if "launchd-stable-node" not in {name for name, _ in SCENARIOS}:
3446
+ report(f"{label} scenario is not registered.")
3447
+ return 1
3448
+ report("launchd-stable-node scenario passed.")
3449
+ return 0
3450
+
3451
+
3368
3452
  def validate_tick_runs_due_patrol_scenario() -> int:
3369
3453
  """The owner's CLI waker (2026-10-19, #356): `keel tick` runs the patrol when due.
3370
3454
 
@@ -8077,49 +8161,84 @@ def validate_shift_start_desktop_scenario() -> int:
8077
8161
 
8078
8162
 
8079
8163
  def validate_shift_cli_self_shift_scenario() -> int:
8080
- """Issue #357 on the CLI (owner, 2026-10-19): stop the old session, start a new one.
8164
+ """Issues #357 and #388 on the CLI (owner, 2026-10-19): hand over, promptly, and retire.
8081
8165
 
8082
8166
  A CLI session cannot clear itself. `keel shift ready --wake` there queues
8083
- the hand-off; `keel tick` waits until the old session is idle, stops it
8084
- (kept: `claude attach` reopens it), and starts a new session in the role's
8085
- worktree that runs `keel shift resume`. `keel shift status` shows the
8086
- queue, and a failed start is a patrol risk.
8167
+ the hand-off and leaves a waiter that, once the old session has finished,
8168
+ retires it (stop, rename by resuming it with `/rename`, stop) and starts a
8169
+ new session in the role's worktree that runs `keel shift resume`. `keel
8170
+ tick` carries out a queued hand-off too, and the two start one session. A
8171
+ session that is busy, or blocked on a question (idle, but its job state is
8172
+ still `working`), is left alone. `keel shift status` shows the queue, and a
8173
+ failed start is a patrol risk.
8087
8174
  """
8088
8175
  label = "shift-cli-self-shift:"
8089
8176
  OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
8090
8177
  with tempfile.TemporaryDirectory(prefix="keel-shift-357-") as raw:
8091
8178
  base = Path(raw)
8092
8179
  rtl, verify, env, _ = shift_scratch(base)
8093
- calls, agents, fail = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start"
8180
+ calls, agents, fail, norename = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start", base / "no-rename"
8094
8181
  fake = base / "fake-claude"
8182
+ # The fake answers with the shapes measured on Claude Code 2.1.303: a live row has `status` and `state`; a stopped one has `state: stopped` and no `status`.
8095
8183
  write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
8096
- f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd()}}) + '\\n')\n"
8097
- f"if sys.argv[1:3] == ['agents', '--json']:\n print(open({str(agents)!r}).read()); sys.exit(0)\n"
8098
- f"if sys.argv[1:2] == ['--bg'] and os.path.exists({str(fail)!r}):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
8099
- "if sys.argv[1:2] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8184
+ f"agents, fail, norename = {str(agents)!r}, {str(fail)!r}, {str(norename)!r}\n"
8185
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd(), 'claude_env': sorted(k for k in os.environ if k.startswith('CLAUDE'))}}) + '\\n')\n"
8186
+ "argv = sys.argv[1:]\n"
8187
+ "if argv[:2] == ['agents', '--json']:\n print(open(agents).read()); sys.exit(0)\n"
8188
+ "rows = json.loads(open(agents).read())\n"
8189
+ "if argv[:1] == ['stop']:\n"
8190
+ " for row in rows:\n if row['id'] == argv[1]:\n row.pop('status', None); row['state'] = 'stopped'\n"
8191
+ " open(agents, 'w').write(json.dumps(rows)); print('stopped ' + argv[1]); sys.exit(0)\n"
8192
+ "if argv[:2] == ['--bg', '--resume']:\n"
8193
+ " for row in rows:\n if row['sessionId'] == argv[2] and not os.path.exists(norename):\n row['name'] = argv[3].split(None, 1)[1]\n"
8194
+ " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · ' + argv[2][:8]); sys.exit(0)\n"
8195
+ "if argv[:1] == ['--bg'] and os.path.exists(fail):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
8196
+ "if argv[:1] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
8100
8197
  "print('stopped')\n")
8101
8198
  fake.chmod(0o755)
8102
- env = {**env, "KEEL_CLAUDE": str(fake)}
8199
+ env = {**env, "KEEL_CLAUDE": str(fake), "KEEL_SHIFT_HANDOVER_POLL_MS": "200", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "20000",
8200
+ "KEEL_SHIFT_RENAME_WAIT_MS": "1500"}
8201
+ # With the waiter given no time, a hand-over is the tick's alone.
8202
+ tick_only = {**env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
8103
8203
  cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
8204
+ queue = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue"
8104
8205
 
8105
- def agents_status(status: str) -> None:
8106
- # The measured shape: `sessionId` is the full id, `id` the job id `stop` and `attach` take.
8107
- agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
8108
- "pid": os.getpid(), "status": status, "cwd": str(verify)}]))
8206
+ def agents_row(status: str | None, state: str, name: str = "verify") -> None:
8207
+ row = {"kind": "background", "name": name, "sessionId": OLD, "id": OLD[:8], "pid": os.getpid(), "state": state, "cwd": str(verify)}
8208
+ if status:
8209
+ row["status"] = status
8210
+ agents.write_text(json.dumps([row]))
8211
+
8212
+ def rows() -> list[dict]:
8213
+ return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
8109
8214
 
8110
- def made(kind: str) -> list[dict]:
8111
- rows = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
8112
- return [r for r in rows if (r["argv"][:1] == ["stop"] if kind == "stop" else r["argv"][:1] == ["--bg"])]
8215
+ def acted() -> list[list[str]]:
8216
+ return [r["argv"] for r in rows() if r["argv"][:2] != ["agents", "--json"]]
8217
+
8218
+ def starts() -> list[dict]:
8219
+ return [r for r in rows() if r["argv"][:1] == ["--bg"] and "--resume" not in r["argv"]]
8113
8220
 
8114
8221
  def tick() -> subprocess.CompletedProcess[str]:
8115
- return run_keel(verify, "tick", "--repo", str(rtl), env=env)
8222
+ return run_keel(verify, "tick", "--repo", str(rtl), env=tick_only)
8223
+
8224
+ def status_text() -> str:
8225
+ return run_keel(rtl, "shift", "status", env=env).stdout
8226
+
8227
+ def wait_for(condition, seconds: float = 10.0) -> bool:
8228
+ deadline = time.time() + seconds
8229
+ while time.time() < deadline:
8230
+ if condition():
8231
+ return True
8232
+ time.sleep(0.2)
8233
+ return condition()
8116
8234
 
8235
+ agents_row("busy", "working")
8117
8236
  readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R012", env=cli_env)
8118
8237
  if readied.returncode != 0:
8119
8238
  report(f"{label} ready --wake in a CLI session failed: {readied.stdout!r} {readied.stderr!r}")
8120
8239
  return 1
8121
- if "keel tick" not in readied.stdout:
8122
- report(f"{label} ready --wake in a CLI session does not say keel tick will hand over: {readied.stdout!r}")
8240
+ if "claude attach" not in readied.stdout or "--wake" in readied.stderr:
8241
+ report(f"{label} ready --wake in a CLI session does not say how the old session is reopened: {readied.stdout!r}")
8123
8242
  return 1
8124
8243
  note = next((mailbox_common_dir(rtl) / "keel-chat" / "shift").glob("verify.md"), None)
8125
8244
  if not note:
@@ -8129,58 +8248,100 @@ def validate_shift_cli_self_shift_scenario() -> int:
8129
8248
  report(f"{label} the note does not record the CLI session.")
8130
8249
  return 1
8131
8250
 
8132
- agents_status("busy")
8133
- tick()
8134
- if made("stop"):
8135
- report(f"{label} a tick stopped the old session while it was busy: {made('stop')!r}")
8251
+ # A busy session, and one blocked on a question, are left alone.
8252
+ time.sleep(1.0)
8253
+ if acted():
8254
+ report(f"{label} the hand-over acted while the old session was busy: {acted()!r}")
8136
8255
  return 1
8137
- if made("start"):
8138
- report(f"{label} a tick started a session while the old one was busy: {made('start')!r}")
8256
+ if "pending" not in status_text():
8257
+ report(f"{label} shift status does not show the pending hand-off: {status_text()!r}")
8139
8258
  return 1
8140
- status = run_keel(rtl, "shift", "status", env=env).stdout
8141
- if "pending" not in status:
8142
- report(f"{label} shift status does not show the pending hand-off: {status!r}")
8259
+ agents_row("idle", "working")
8260
+ time.sleep(1.0)
8261
+ if acted():
8262
+ report(f"{label} the hand-over cut off a session blocked on a question (idle, state working): {acted()!r}")
8143
8263
  return 1
8144
8264
 
8145
- agents_status("idle")
8146
- tick()
8147
- stops, starts = made("stop"), made("start")
8148
- if [s["argv"] for s in stops] != [["stop", OLD[:8]]]:
8149
- report(f"{label} the idle old session was not stopped once: {stops!r}")
8150
- return 1
8151
- if len(starts) != 1:
8152
- report(f"{label} the new session was not started once: {starts!r}")
8265
+ # Finished: the waiter retires it and starts the next, with no tick.
8266
+ agents_row("idle", "done")
8267
+ if not wait_for(lambda: len(starts()) >= 1):
8268
+ report(f"{label} the waiter did not hand over without a tick: {acted()!r}")
8153
8269
  return 1
8154
- if starts[0]["argv"][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]:
8155
- report(f"{label} the new session was not started as --bg -n verify --permission-mode auto: {starts!r}")
8270
+ order = acted()
8271
+ shifted = re.compile(r"^/rename verify · shifted \d{4}-\d{2}-\d{2} \d{2}:\d{2}$")
8272
+ if (order[0] != ["stop", OLD[:8]] or order[1][:3] != ["--bg", "--resume", OLD] or len(order[1]) != 4
8273
+ or not shifted.match(order[1][3]) or order[2] != ["stop", OLD[:8]] or order[3][:5] != ["--bg", "-n", "verify", "--permission-mode", "auto"]
8274
+ or len(order) != 4):
8275
+ report(f"{label} the old session was not retired as stop, rename-by-resume, stop, then the new start: {order!r}")
8156
8276
  return 1
8157
- if "keel shift resume" not in starts[0]["argv"][-1]:
8158
- report(f"{label} the new session's prompt does not name keel shift resume: {starts[0]['argv']!r}")
8277
+ if "keel shift resume" not in order[3][-1] or "--resume" in order[3]:
8278
+ report(f"{label} the new session does not start fresh with a keel shift resume prompt: {order[3]!r}")
8159
8279
  return 1
8160
- if "--resume" in starts[0]["argv"]:
8161
- report(f"{label} the new session resumes an old one instead of starting fresh: {starts[0]['argv']!r}")
8280
+ if os.path.realpath(starts()[0]["cwd"]) != os.path.realpath(verify):
8281
+ report(f"{label} the new session started in {starts()[0]['cwd']}, not verify's worktree.")
8162
8282
  return 1
8163
- if os.path.realpath(starts[0]["cwd"]) != os.path.realpath(verify):
8164
- report(f"{label} the new session started in {starts[0]['cwd']}, not verify's worktree.")
8283
+ leaked = [r for r in rows() if r["claude_env"]]
8284
+ if leaked:
8285
+ report(f"{label} a claude the hand-over ran inherited the old session's {leaked[0]['claude_env']!r}.")
8165
8286
  return 1
8166
- status = run_keel(rtl, "shift", "status", env=env).stdout
8167
- for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}"):
8168
- if needle not in status:
8169
- report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {status!r}")
8287
+ text = status_text()
8288
+ for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}", "shifted"):
8289
+ if needle not in text:
8290
+ report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {text!r}")
8170
8291
  return 1
8171
8292
  tick()
8172
- if len(made("start")) != 1:
8293
+ if len(starts()) != 1 or len(acted()) != 4:
8294
+ report(f"{label} a tick after the hand-over acted again: {acted()!r}")
8295
+ return 1
8296
+
8297
+ # The tick and the waiter start one session: a fresh lock holds the tick off.
8298
+ calls.write_text("")
8299
+ agents_row("idle", "done")
8300
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R014", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8301
+ lock = queue / "verify.lock"
8302
+ write_text(lock, "held")
8303
+ tick()
8304
+ if acted():
8305
+ report(f"{label} a tick acted while another hand-over held the lock: {acted()!r}")
8306
+ return 1
8307
+ lock.unlink()
8308
+ tick()
8309
+ if len(starts()) != 1:
8310
+ report(f"{label} the tick did not start one session once the lock was gone: {acted()!r}")
8311
+ return 1
8312
+ tick()
8313
+ if len(starts()) != 1:
8173
8314
  report(f"{label} a second tick started another session.")
8174
8315
  return 1
8175
8316
 
8317
+ # A rename that never shows is recorded, and the new session still starts.
8318
+ calls.write_text("")
8319
+ agents_row("idle", "done")
8320
+ write_text(norename, "x")
8321
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R015", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8322
+ ticked = tick()
8323
+ text = status_text()
8324
+ if len(starts()) != 1:
8325
+ report(f"{label} a rename that did not show stopped the new session from starting: {acted()!r} {ticked.stderr!r}")
8326
+ return 1
8327
+ if "delivered" not in text:
8328
+ report(f"{label} a rename that did not show kept the hand-off from being delivered: {text!r}")
8329
+ return 1
8330
+ if "rename not shown" not in text:
8331
+ report(f"{label} shift status does not say the rename did not show: {text!r}")
8332
+ return 1
8333
+ norename.unlink()
8334
+
8176
8335
  # A start that fails stays visible and is a patrol risk.
8177
- fail.write_text("x")
8178
- run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env=cli_env)
8336
+ calls.write_text("")
8337
+ agents_row("idle", "done")
8338
+ write_text(fail, "x")
8339
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
8179
8340
  tick()
8180
- status = run_keel(rtl, "shift", "status", env=env).stdout
8341
+ text = status_text()
8181
8342
  for needle in ("failed", "Workspace not trusted"):
8182
- if needle not in status:
8183
- report(f"{label} a failed start does not show {needle!r}: {status!r}")
8343
+ if needle not in text:
8344
+ report(f"{label} a failed start does not show {needle!r}: {text!r}")
8184
8345
  return 1
8185
8346
  patrolled = run_keel(rtl, "patrol", env=env).stdout
8186
8347
  if not re.search(r"risk: .*verify.*hand-off", patrolled):
@@ -42714,6 +42875,7 @@ SCENARIOS: tuple = (
42714
42875
  ("patrol-since-last", validate_patrol_since_last_scenario),
42715
42876
  ("patrol-next", validate_patrol_next_scenario),
42716
42877
  ("tick-runs-due-patrol", validate_tick_runs_due_patrol_scenario),
42878
+ ("launchd-stable-node", validate_launchd_stable_node_scenario),
42717
42879
  ("patrol-exit-says-who-acts", validate_patrol_exit_says_who_acts_scenario),
42718
42880
  ("patrol-nudge", validate_patrol_nudge_scenario),
42719
42881
  ("patrol-escalate", validate_patrol_escalate_scenario),
@@ -125,8 +125,9 @@ function xml(text) {
125
125
 
126
126
  function plistText() {
127
127
  const cli = path.resolve(__dirname, "..", "..", "..", "bin", "keel.js");
128
- const args = [process.execPath, cli, "chat", "bridge", "run"];
129
- const environment = { PATH: process.env.PATH || "/usr/bin:/bin:/usr/sbin:/sbin" };
128
+ const { stableNode, launchdPath } = require("../launchd");
129
+ const args = [stableNode(), cli, "chat", "bridge", "run"];
130
+ const environment = { PATH: launchdPath(process.env.PATH) };
130
131
  if (process.env.KEEL_HOME) environment.KEEL_HOME = process.env.KEEL_HOME;
131
132
  if (process.env.KEEL_CHAT_MACHINE) environment.KEEL_CHAT_MACHINE = process.env.KEEL_CHAT_MACHINE;
132
133
  const log = path.join(bridgeDir(), "bridge.log");
@@ -125,8 +125,9 @@ function xml(text) {
125
125
 
126
126
  function plistText(label, worktree, signal) {
127
127
  const cli = path.resolve(__dirname, "..", "..", "..", "bin", "keel.js");
128
- const args = [process.execPath, cli, "chat", "wake", "run", "--once", "--worktree", worktree];
129
- const environment = { PATH: process.env.PATH || "/usr/bin:/bin:/usr/sbin:/sbin" };
128
+ const { stableNode, launchdPath } = require("../launchd");
129
+ const args = [stableNode(), cli, "chat", "wake", "run", "--once", "--worktree", worktree];
130
+ const environment = { PATH: launchdPath(process.env.PATH) };
130
131
  for (const key of ["KEEL_HOME", "KEEL_CHAT_CODEX"]) {
131
132
  if (process.env[key]) environment[key] = process.env[key];
132
133
  }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+
3
+ // What the LaunchAgents Keel prints or writes (`keel tick task`, `keel chat
4
+ // wake add`, the chat bridge) name, so that they outlive a package upgrade
5
+ // (#387). A launchd job runs long after the shell that rendered it.
6
+ const fs = require("fs");
7
+ const os = require("os");
8
+ const path = require("path");
9
+
10
+ // `process.execPath` is the binary's real location, which `brew upgrade` moves
11
+ // (`/opt/homebrew/Cellar/node/<version>/bin/node`). The `node` a person types is
12
+ // the symlink the manager keeps current, so a name on PATH that resolves to this
13
+ // same binary is the one to write; when none does, the real path is all there is.
14
+ function stableNode(env = process.env) {
15
+ const exec = process.execPath;
16
+ let real;
17
+ try {
18
+ real = fs.realpathSync(exec);
19
+ } catch {
20
+ return exec;
21
+ }
22
+ for (const dir of String(env.PATH || "").split(path.delimiter)) {
23
+ if (!dir) continue;
24
+ const candidate = path.join(dir, "node");
25
+ try {
26
+ if (fs.realpathSync(candidate) === real) return candidate;
27
+ } catch {
28
+ // not on this directory
29
+ }
30
+ }
31
+ return exec;
32
+ }
33
+
34
+ // A Claude plugin cache directory belongs to one release (`…/keel/5.149.0/bin`)
35
+ // and is stale after the next update. The jobs call node and keel.js by
36
+ // absolute path, so nothing in it is needed.
37
+ const PLUGIN_CACHE = /[\\/]\.claude[\\/]plugins[\\/]cache[\\/]/;
38
+
39
+ function launchdPath(value) {
40
+ const text = value || "/usr/bin:/bin:/usr/sbin:/sbin";
41
+ return text.split(path.delimiter).filter((dir) => dir && !PLUGIN_CACHE.test(`${dir}${path.sep}`)).join(path.delimiter);
42
+ }
43
+
44
+ function agentsDir() {
45
+ return process.env.KEEL_CHAT_LAUNCH_AGENTS_DIR || path.join(os.homedir(), "Library", "LaunchAgents");
46
+ }
47
+
48
+ const RECREATE = [
49
+ [/^dev\.keel\.tick\./, "keel tick task"],
50
+ [/^dev\.keel\.chat-wake\./, "keel chat wake add"],
51
+ [/^dev\.keel\.chat-bridge/, "keel chat bridge install"],
52
+ ];
53
+
54
+ // Each `dev.keel.*` LaunchAgent with the program it runs and whether that exists.
55
+ function inspectJobs() {
56
+ let names = [];
57
+ try {
58
+ names = fs.readdirSync(agentsDir()).filter((name) => /^dev\.keel\..*\.plist$/.test(name)).sort();
59
+ } catch {
60
+ return [];
61
+ }
62
+ return names.map((name) => {
63
+ let text = "";
64
+ try {
65
+ text = fs.readFileSync(path.join(agentsDir(), name), "utf8");
66
+ } catch {
67
+ // unreadable: reported as no program below
68
+ }
69
+ const match = text.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/);
70
+ const program = match ? match[1].replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&") : null;
71
+ const recreate = (RECREATE.find(([pattern]) => pattern.test(name)) || [null, "the command that wrote it"])[1];
72
+ return { name, program, exists: Boolean(program) && fs.existsSync(program), recreate };
73
+ });
74
+ }
75
+
76
+ module.exports = { stableNode, launchdPath, inspectJobs };
package/src/core/shift.js CHANGED
@@ -475,14 +475,16 @@ function ready(where, options) {
475
475
  store.writeRecord(where, { group: todo.group, kind: "done", from: role, target: todo.id });
476
476
  }
477
477
  }
478
- // A CLI session cannot clear itself: `keel tick` stops it once idle and
479
- // starts the next (#357 D1), so nothing waits for a clear.
478
+ // A CLI session cannot clear itself: its hand-over stops it once it has
479
+ // finished and starts the next (#357 D1), so nothing waits for a clear. A
480
+ // waiter carries it out within seconds; `keel tick` stays as the fallback (#388 D1).
480
481
  const queued = options.wake && cli ? queueHandOff(where, role, cli) : null;
481
- const waiter = options.wake && !queued ? armWake(where, role, since) : null;
482
+ const waiter = options.wake && !queued ? armWake(where, role, since) : queued ? armHandOver(where, role) : null;
482
483
  return { role: role || null, note, closed: open.map((todo) => todo.id), waiter, queued, startedBy: role ? null : options.forceReason, desktop, pid, cli, worktree: where.worktree };
483
484
  }
484
485
 
485
486
  // --- the CLI hand-off queue (#357) --------------------------------------------------
487
+ // `ready --wake` queues an entry; the waiter it leaves and `keel tick` both carry it out (#388).
486
488
 
487
489
  function queueFile(where, role) {
488
490
  return path.join(shiftDir(where), "queue", `${role}.json`);
@@ -501,50 +503,146 @@ function handOffs(where) {
501
503
 
502
504
  const SHIFT_START_TEXT = (role) => `${role}: your new shift starts now. Run keel context, then keel shift resume.`;
503
505
 
504
- // One step of the waker (#357 D2): a busy old session waits; an idle or gone
505
- // one is stopped (kept: \`claude attach\` reopens it) and a new session starts.
506
- function handOver(where) {
507
- const { readShiftDeclaration } = require("./config");
508
- const claude = process.env.KEEL_CLAUDE || "claude";
509
- const pending = handOffs(where).filter((entry) => entry.state === "pending");
510
- if (!pending.length) return [];
511
- const listed = spawnSync(claude, ["agents", "--json"], { encoding: "utf8" });
512
- let sessions = [];
506
+ // The old session has finished when it is gone, or is not busy and its job
507
+ // state is not a turn in progress: a session blocked on a question to the owner
508
+ // reads `idle` with state `working`, and stopping it cuts the conversation off (#388).
509
+ function finished(row) {
510
+ if (!row) return true;
511
+ if (row.status === "busy") return false;
512
+ return !row.state || ["done", "idle", "stopped"].includes(row.state);
513
+ }
514
+
515
+ function listAgents(claude) {
516
+ const listed = spawnSync(claude, ["agents", "--json", "--all"], { encoding: "utf8" });
517
+ try {
518
+ const parsed = JSON.parse(listed.stdout);
519
+ return listed.status === 0 && Array.isArray(parsed) ? parsed : null;
520
+ } catch {
521
+ return null;
522
+ }
523
+ }
524
+
525
+ // Stop the old session, give it a name that says it shifted, stop it again. The
526
+ // rename is a resume with `/rename` and no other flag, which keeps the session id
527
+ // and shows in `claude agents` (measured 2026-10-19); it is best effort (#388 D4).
528
+ function retire(claude, entry, row) {
529
+ const id = row.id || entry.session.slice(0, 8);
530
+ if (row.state !== "stopped") spawnSync(claude, ["stop", id], { encoding: "utf8" });
531
+ const stamp = store.isoLocal(new Date()).slice(0, 16).replace("T", " ");
532
+ const name = `${entry.role} · shifted ${stamp}`;
533
+ spawnSync(claude, ["--bg", "--resume", entry.session, `/rename ${name}`], { encoding: "utf8", cwd: row.cwd || entry.worktree });
534
+ const deadline = Date.now() + envMs("KEEL_SHIFT_RENAME_WAIT_MS", 30000);
535
+ const pause = new Int32Array(new SharedArrayBuffer(4));
536
+ let shown = false;
537
+ for (;;) {
538
+ const now = (listAgents(claude) || []).find((item) => item && item.sessionId === entry.session);
539
+ shown = Boolean(now && now.name === name);
540
+ if (shown || Date.now() >= deadline) break;
541
+ Atomics.wait(pause, 0, 0, 500);
542
+ }
543
+ spawnSync(claude, ["stop", id], { encoding: "utf8" });
544
+ return shown ? name : null;
545
+ }
546
+
547
+ // One runner at a time per role (#388 D2): the waiter and the tick both carry
548
+ // hand-overs out, and a lock younger than two minutes is the other's.
549
+ function withHandOverLock(where, role, fn) {
550
+ const file = path.join(shiftDir(where), "queue", `${role}.lock`);
513
551
  try {
514
- sessions = JSON.parse(listed.stdout);
552
+ if (Date.now() - fs.statSync(file).mtimeMs > 2 * 60 * 1000) fs.unlinkSync(file);
515
553
  } catch {
516
- sessions = [];
554
+ // no lock yet
555
+ }
556
+ let fd;
557
+ try {
558
+ fd = fs.openSync(file, "wx");
559
+ } catch {
560
+ return null;
561
+ }
562
+ try {
563
+ return fn();
564
+ } finally {
565
+ fs.closeSync(fd);
566
+ try {
567
+ fs.unlinkSync(file);
568
+ } catch {
569
+ // already gone
570
+ }
517
571
  }
572
+ }
573
+
574
+ // One step of the waker (#357 D2): a busy or unfinished old session waits; a
575
+ // finished or gone one is retired (kept: \`claude attach\` reopens it) and a new
576
+ // session starts. `only` limits the step to one role (the waiter's).
577
+ function handOver(where, only = null) {
578
+ const { readShiftDeclaration } = require("./config");
579
+ const claude = process.env.KEEL_CLAUDE || "claude";
580
+ const pending = handOffs(where).filter((entry) => entry.state === "pending" && (!only || entry.role === only));
581
+ if (!pending.length) return [];
582
+ const sessions = listAgents(claude);
583
+ // A listing that failed says nothing about the old session: wait for the next step.
584
+ if (!sessions) return [];
518
585
  const done = [];
519
- for (const entry of pending) {
520
- const row = (Array.isArray(sessions) ? sessions : []).find((item) => item && item.sessionId === entry.session);
521
- if (row && row.status === "busy") continue;
522
- // `stop`, `attach` and `logs` take the 8-character job id, not the full
523
- // session id (`No job matching`, measured 2026-10-19).
524
- if (row) spawnSync(claude, ["stop", row.id || entry.session.slice(0, 8)], { encoding: "utf8" });
525
- const mode = readShiftDeclaration(entry.worktree).permissionMode;
526
- const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
527
- cwd: entry.worktree, encoding: "utf8",
586
+ for (const queued of pending) {
587
+ const ran = withHandOverLock(where, queued.role, () => {
588
+ const entry = store.readJsonFile(queueFile(where, queued.role));
589
+ if (!entry || entry.state !== "pending") return null;
590
+ const row = sessions.find((item) => item && item.sessionId === entry.session);
591
+ if (!finished(row)) return null;
592
+ // `stop`, `attach` and `logs` take the 8-character job id, not the full
593
+ // session id (`No job matching`, measured 2026-10-19).
594
+ if (row) entry.renamed = retire(claude, entry, row);
595
+ const mode = readShiftDeclaration(entry.worktree).permissionMode;
596
+ const started = spawnSync(claude, ["--bg", "-n", entry.role, "--permission-mode", mode, SHIFT_START_TEXT(entry.role)], {
597
+ cwd: entry.worktree, encoding: "utf8",
598
+ });
599
+ const output = `${started.stdout || ""}`;
600
+ if (!started.error && started.status === 0) {
601
+ const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
602
+ Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
603
+ } else {
604
+ const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
605
+ Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
606
+ }
607
+ store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
608
+ return entry;
528
609
  });
529
- const output = `${started.stdout || ""}`;
530
- if (!started.error && started.status === 0) {
531
- const id = (output.match(/backgrounded\s*·\s*(\S+)/) || [])[1] || null;
532
- Object.assign(entry, { state: "delivered", delivered_at: store.isoLocal(new Date()), new_session: id });
533
- } else {
534
- const reason = started.error ? started.error.message : String(started.stderr || output).trim().split(/\r?\n/).pop();
535
- Object.assign(entry, { state: "failed", failed_at: store.isoLocal(new Date()), error: reason || `exited ${started.status}` });
536
- }
537
- store.writeJsonAtomic(where, queueFile(where, entry.role), entry);
538
- done.push(entry);
610
+ if (ran) done.push(ran);
539
611
  }
540
612
  return done;
541
613
  }
542
614
 
615
+ // `ready --wake` on the CLI leaves this waiter (#388 D1). Its working directory
616
+ // is `/`, so `check` never counts it, and its environment has none of the old
617
+ // session's `CLAUDE*` variables, which the claude it starts must not inherit.
618
+ function armHandOver(where, role) {
619
+ const keel = path.resolve(__dirname, "..", "..", "bin", "keel.js");
620
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("CLAUDE")));
621
+ const child = spawn(process.execPath, [keel, "shift", "handover-wait", "--role", role, "--repo", where.worktree],
622
+ { detached: true, stdio: "ignore", cwd: path.parse(where.worktree).root, env });
623
+ child.unref();
624
+ return child.pid;
625
+ }
626
+
627
+ function waitForHandOver(where, role) {
628
+ const poll = envMs("KEEL_SHIFT_HANDOVER_POLL_MS", 3000);
629
+ const deadline = Date.now() + envMs("KEEL_SHIFT_HANDOVER_TIMEOUT_MS", 2 * 60 * 60 * 1000);
630
+ const step = () => {
631
+ const entry = store.readJsonFile(queueFile(where, role));
632
+ if (!entry || entry.state !== "pending" || Date.now() > deadline) return;
633
+ handOver(where, role);
634
+ setTimeout(step, poll);
635
+ };
636
+ // `ready` has just run, so the session is still finishing its turn: look first after one interval.
637
+ setTimeout(step, poll);
638
+ }
639
+
543
640
  function describeHandOff(entry) {
544
641
  const tail = entry.state === "delivered"
545
642
  ? `delivered ${entry.delivered_at} as session ${entry.new_session || "(id not printed)"}`
546
643
  : entry.state === "failed" ? `failed ${entry.failed_at}: ${entry.error}` : "pending: waits for the session to go idle";
547
- return `- ${entry.role}: ${tail}; requested ${entry.requested_at}; old session kept, reopen it with \`claude attach ${entry.session.slice(0, 8)}\``;
644
+ const renamed = entry.state === "delivered" ? (entry.renamed ? `; old session renamed "${entry.renamed}"` : "; rename not shown") : "";
645
+ return `- ${entry.role}: ${tail}${renamed}; requested ${entry.requested_at}; old session kept, reopen it with \`claude attach ${entry.session.slice(0, 8)}\``;
548
646
  }
549
647
 
550
648
  // A failed hand-off, or one pending past 15 minutes, is the patrol's risk (#357 D4).
@@ -995,9 +1093,9 @@ const CLEAR_HINT = [
995
1093
  // or — without a chat role — the person who opens it.
996
1094
  function clearHint(result) {
997
1095
  if (result.queued) {
998
- return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session is idle, "
999
- + `\`keel tick\` stops it — its conversation is kept, \`claude attach ${result.cli.session.slice(0, 8)}\` reopens it — and starts a new session `
1000
- + `in ${result.worktree} that runs \`keel shift resume\`. \`keel shift status\` shows the hand-off.`;
1096
+ return "This is a Claude Code CLI session, which cannot clear itself (#357). End your turn now: once this session has finished, "
1097
+ + `a waiter stops it and renames it — its conversation is kept, \`claude attach ${result.cli.session.slice(0, 8)}\` reopens it — and starts a new session `
1098
+ + `in ${result.worktree} that runs \`keel shift resume\`; \`keel tick\` does the same if the waiter is gone. \`keel shift status\` shows the hand-off.`;
1001
1099
  }
1002
1100
  let last;
1003
1101
  if (!result.role) last = `Without a chat role nothing wakes the new session; ${result.startedBy} — tell it to run \`keel shift resume\`.`;
@@ -1100,6 +1198,13 @@ function runShift(argv) {
1100
1198
  waitForWake(where, options.role, options.since);
1101
1199
  return 0;
1102
1200
  }
1201
+ case "handover-wait": {
1202
+ // Internal: the detached waiter `ready --wake` spawns in a CLI session.
1203
+ if (!options.role) throw new ShiftError("keel shift handover-wait needs --role.");
1204
+ store.checkName(options.role, "Role");
1205
+ waitForHandOver(where, options.role);
1206
+ return 0;
1207
+ }
1103
1208
  case "start": {
1104
1209
  if (!rest[0]) throw new ShiftError("keel shift start needs the role.");
1105
1210
  const { record, body, desktop } = start(where, rest[0], rest.slice(1).join(" "));
package/src/core/tick.js CHANGED
@@ -9,6 +9,7 @@ const os = require("os");
9
9
  const path = require("path");
10
10
  const { spawnSync } = require("child_process");
11
11
  const store = require("./chat/store");
12
+ const { stableNode, launchdPath } = require("./launchd");
12
13
 
13
14
  const USAGE = "keel tick [--repo <path>] [--json] one model-free step: run the patrol when it is due\n"
14
15
  + " keel tick task [--json] [--repo <path>] print the launchd job that calls it";
@@ -126,7 +127,7 @@ function task(where) {
126
127
  if (!found.worktree) throw new TickError(found.why);
127
128
  const label = `dev.keel.tick.${where.project.replace(/[^A-Za-z0-9.-]/g, "-")}`;
128
129
  const logs = path.join(where.root, "tick");
129
- const args = [process.execPath, KEEL, "tick", "--repo", found.worktree];
130
+ const args = [stableNode(), KEEL, "tick", "--repo", found.worktree];
130
131
  const plist = [
131
132
  '<?xml version="1.0" encoding="UTF-8"?>',
132
133
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -135,7 +136,7 @@ function task(where) {
135
136
  " <key>Label</key>", ` <string>${xml(label)}</string>`,
136
137
  " <key>ProgramArguments</key>", " <array>", ...args.map((arg) => ` <string>${xml(arg)}</string>`), " </array>",
137
138
  " <key>WorkingDirectory</key>", ` <string>${xml(found.worktree)}</string>`,
138
- " <key>EnvironmentVariables</key>", " <dict>", " <key>PATH</key>", ` <string>${xml(process.env.PATH || "")}</string>`, " </dict>",
139
+ " <key>EnvironmentVariables</key>", " <dict>", " <key>PATH</key>", ` <string>${xml(launchdPath(process.env.PATH))}</string>`, " </dict>",
139
140
  " <key>StartInterval</key>", ` <integer>${INTERVAL_SECONDS}</integer>`,
140
141
  " <key>StandardOutPath</key>", ` <string>${xml(path.join(logs, "tick.log"))}</string>`,
141
142
  " <key>StandardErrorPath</key>", ` <string>${xml(path.join(logs, "tick.err"))}</string>`,