@christang/keel 5.179.0 → 5.181.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.179.0",
3
+ "version": "5.181.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",
package/README.md CHANGED
@@ -1003,7 +1003,7 @@ keel --init [--target <t>] [--dry-run] [--force-template-update]
1003
1003
  keel --install [--target <t>] [--dry-run] [--force-template-update] [--with-git-hooks]
1004
1004
  keel --check | --doctor [--target <t>]
1005
1005
  keel --uninstall | --clear [--target <t>] [--dry-run] # --clear is the same removal
1006
- keel --update [--dry-run] [--source <npm package or git spec>]
1006
+ keel --update [--dry-run] [--source <npm package or git spec>] [--adopt] # --adopt: restart idle background sessions on the new plugin
1007
1007
  keel --version | --help
1008
1008
 
1009
1009
  # OpenSpec, through the CLI Keel bundles
package/README.zh-CN.md CHANGED
@@ -846,7 +846,7 @@ keel --init [--target <t>] [--dry-run] [--force-template-update]
846
846
  keel --install [--target <t>] [--dry-run] [--force-template-update] [--with-git-hooks]
847
847
  keel --check | --doctor [--target <t>]
848
848
  keel --uninstall | --clear [--target <t>] [--dry-run] # --clear 是同一种移除
849
- keel --update [--dry-run] [--source <npm package or git spec>]
849
+ keel --update [--dry-run] [--source <npm package or git spec>] [--adopt] # --adopt:让空闲的后台会话重启到新插件上
850
850
  keel --version | --help
851
851
 
852
852
  # OpenSpec,通过 Keel 捆绑的 CLI 运行
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.179.0 -->
1
+ <!-- keel:start version=5.181.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the durable authority, and memory or transcripts may only inform.
package/bin/keel.js CHANGED
@@ -106,7 +106,7 @@ Usage:
106
106
  keel --install [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update] [--with-git-hooks]
107
107
  keel --clear [repo] [--target claude|codex|opencode] [--dry-run]
108
108
  keel --uninstall [repo] [--target claude|codex|opencode] [--dry-run]
109
- keel --update [--dry-run] [--source npm-package-or-git-spec]
109
+ keel --update [--dry-run] [--source npm-package-or-git-spec] [--adopt]
110
110
  keel --check [repo] [--target claude|codex|opencode]
111
111
  keel --doctor [repo] [--target claude|codex|opencode]
112
112
  keel --version
@@ -179,6 +179,7 @@ function parseArgs(argv) {
179
179
  forceTemplateUpdate: false,
180
180
  withGitHooks: false,
181
181
  updateSource: null,
182
+ adopt: false,
182
183
  help: false,
183
184
  version: false,
184
185
  change: null,
@@ -355,6 +356,10 @@ function parseArgs(argv) {
355
356
  parsed.withGitHooks = true;
356
357
  continue;
357
358
  }
359
+ if (arg === "--adopt") {
360
+ parsed.adopt = true;
361
+ continue;
362
+ }
358
363
  if (arg === "--target") {
359
364
  index += 1;
360
365
  if (index >= argv.length) {
@@ -987,7 +992,12 @@ function claudeKeel(executable) {
987
992
  const entry = (Array.isArray(listed) ? listed : [])
988
993
  .find((item) => item && typeof item.id === "string" && item.id.startsWith("keel@"));
989
994
  if (!entry) return null;
990
- return { id: entry.id, market: entry.id.slice("keel@".length), version: entry.version || null };
995
+ return {
996
+ id: entry.id,
997
+ market: entry.id.slice("keel@".length),
998
+ version: entry.version || null,
999
+ lastUpdated: entry.lastUpdated || null,
1000
+ };
991
1001
  }
992
1002
 
993
1003
  // The Codex marketplace needs only its catalog and the plugin it names; a
@@ -1378,11 +1388,106 @@ function runGlobalUpdate(options) {
1378
1388
  const results = [
1379
1389
  updateGlobalCli(options, npm, source),
1380
1390
  updateClaudePlugin(options, npm),
1391
+ adoptClaudeSessions(options),
1381
1392
  updateCodexPlugin(options),
1382
1393
  ];
1383
1394
  return results.every(Boolean) ? 0 : 1;
1384
1395
  }
1385
1396
 
1397
+ function waitForExit(pid, limitMs) {
1398
+ if (!Number.isInteger(pid) || pid <= 0) return true;
1399
+ const deadline = Date.now() + limitMs;
1400
+ for (;;) {
1401
+ try {
1402
+ process.kill(pid, 0);
1403
+ } catch {
1404
+ return true;
1405
+ }
1406
+ if (Date.now() >= deadline) return false;
1407
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
1408
+ }
1409
+ }
1410
+
1411
+ // A Claude background session keeps the plugin it loaded (#424). A hand-over
1412
+ // adopts the update, because it starts a new process; a session that does not
1413
+ // change shift stays on the old one. Each running background session started
1414
+ // before the installed plugin's `lastUpdated` is named, and with --adopt each
1415
+ // idle one is restarted: `claude stop`, a wait for its process to exit (a
1416
+ // resume before that starts a copy, #395), then `claude --bg --resume <id>`
1417
+ // with no prompt and no flag, which keeps its id and runs no turn (measured
1418
+ // 2026-10-21, Claude Code 2.1.304). A busy or waiting session, one under a
1419
+ // task's write guard, and the session running this are left.
1420
+ function adoptClaudeSessions(options) {
1421
+ const component = "claude sessions";
1422
+ const executable = process.env.KEEL_UPDATE_CLAUDE || "claude";
1423
+ if (options.dryRun) {
1424
+ if (options.adopt) {
1425
+ process.stdout.write("keel: would restart each idle background session started before the installed plugin: "
1426
+ + "claude stop <id>, then claude --bg --resume <session id>\n");
1427
+ }
1428
+ return true;
1429
+ }
1430
+ const plugin = claudeKeel(executable);
1431
+ const updatedAt = Date.parse((plugin && plugin.lastUpdated) || "");
1432
+ if (!plugin || plugin.failed || !Number.isFinite(updatedAt)) return true;
1433
+ const listed = hostQuery(executable, ["agents", "--json"]);
1434
+ const rows = !listed.failed && Array.isArray(listed.json) ? listed.json : null;
1435
+ if (!rows) {
1436
+ if (!options.adopt) return true;
1437
+ updateLine(component, "failed", `\`claude agents --json\` ${listed.failed || "listed no sessions"}, so none was adopted`);
1438
+ return false;
1439
+ }
1440
+ const own = process.env.CLAUDE_CODE_SESSION_ID || "";
1441
+ const older = rows.filter((row) => row && row.kind === "background" && row.status && row.sessionId
1442
+ && row.sessionId !== own && Number(row.startedAt) < updatedAt);
1443
+ if (older.length === 0) return true;
1444
+ const named = (row) => `${row.name || row.sessionId.slice(0, 8)} (${row.id || row.sessionId.slice(0, 8)})`;
1445
+ if (!options.adopt) {
1446
+ updateLine(component, "manual", `${older.length} started before the plugin was installed and still run the skills they loaded: `
1447
+ + `${older.map(named).join(", ")}; \`keel --update --adopt\` restarts the idle ones, and a shift change starts its new session on the installed plugin`);
1448
+ return true;
1449
+ }
1450
+ const adopted = [];
1451
+ const left = [];
1452
+ const failed = [];
1453
+ for (const row of older) {
1454
+ if (row.status !== "idle") {
1455
+ left.push(`${named(row)}, ${row.status}`);
1456
+ continue;
1457
+ }
1458
+ if (row.cwd && fs.existsSync(path.join(row.cwd, "keel", "guard.json"))) {
1459
+ left.push(`${named(row)}, under a task's write guard`);
1460
+ continue;
1461
+ }
1462
+ const stopped = hostRun(executable, ["stop", row.id || row.sessionId.slice(0, 8)]);
1463
+ if (stopped.error || stopped.status !== 0) {
1464
+ failed.push(`${named(row)}: \`claude stop\` ${hostFailure(stopped)}`);
1465
+ continue;
1466
+ }
1467
+ if (!waitForExit(Number(row.pid), 15 * 1000)) {
1468
+ failed.push(`${named(row)}: its process ${row.pid} was still running 15 s after \`claude stop\``);
1469
+ continue;
1470
+ }
1471
+ const resumed = spawnSync(executable, ["--bg", "--resume", row.sessionId], {
1472
+ encoding: "utf8",
1473
+ cwd: row.cwd && fs.existsSync(row.cwd) ? row.cwd : undefined,
1474
+ shell: process.platform === "win32",
1475
+ timeout: 60 * 1000,
1476
+ });
1477
+ if (resumed.error || resumed.status !== 0) {
1478
+ failed.push(`${named(row)}: \`claude --bg --resume\` ${hostFailure(resumed)}; \`claude attach ${row.id || row.sessionId.slice(0, 8)}\` reopens it`);
1479
+ continue;
1480
+ }
1481
+ adopted.push(named(row));
1482
+ }
1483
+ const parts = [];
1484
+ if (adopted.length) parts.push(`adopted ${adopted.join(", ")} — restarted on the installed plugin, same session, no turn run`);
1485
+ if (left.length) parts.push(`left ${left.join("; ")} — each adopts at its next shift change or another --adopt`);
1486
+ if (failed.length) parts.push(`could not adopt ${failed.join("; ")}`);
1487
+ updateLine(component, failed.length ? "failed" : "updated", parts.join("; "));
1488
+ return failed.length === 0;
1489
+ }
1490
+
1386
1491
  function runPython(script, args) {
1387
1492
  if (!fs.existsSync(script)) {
1388
1493
  process.stderr.write(`keel: missing packaged script: ${script}\n`);
@@ -2758,6 +2863,9 @@ function runAction(options) {
2758
2863
  if (options.withGitHooks && options.action !== "install") {
2759
2864
  fail("--with-git-hooks only applies to --install");
2760
2865
  }
2866
+ if (options.adopt && options.action !== "update") {
2867
+ fail("--adopt only applies to --update");
2868
+ }
2761
2869
 
2762
2870
  if (options.action === "openspec") {
2763
2871
  const openspec = findOpenSpecCommand();
@@ -3040,6 +3148,9 @@ function main() {
3040
3148
  return require("../src/core/agents").runAgents(process.argv.slice(3));
3041
3149
  }
3042
3150
  const options = parseArgs(process.argv.slice(2));
3151
+ if (options.adopt && options.action !== "update") {
3152
+ fail("--adopt only applies to --update");
3153
+ }
3043
3154
  if (options.help || (!options.action && !options.version)) {
3044
3155
  printHelp();
3045
3156
  return 0;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.179.0",
3
+ "version": "5.181.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.179.0",
9
+ "version": "5.181.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.179.0",
5
+ "version": "5.181.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.179.0",
3
+ "version": "5.181.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.179.0",
3
+ "version": "5.181.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",
@@ -51,8 +51,8 @@ REQUIRED_SCRIPTS = [
51
51
  "scripts/validate_plugin.py",
52
52
  ]
53
53
 
54
- PACKAGE_VERSION = "5.179.0"
55
- PROTOCOL_VERSION = "5.179.0"
54
+ PACKAGE_VERSION = "5.181.0"
55
+ PROTOCOL_VERSION = "5.181.0"
56
56
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
57
57
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
58
58
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -2201,7 +2201,7 @@ def mailbox_common_dir(repo: Path) -> Path:
2201
2201
  CHAT_ROLE_VARIABLES = ("KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE")
2202
2202
  # The desktop app's session markers (#319 D5): a run inside it must not change
2203
2203
  # what shift scenarios see.
2204
- DESKTOP_HOST_VARIABLES = ("CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_HOST_SESSION_ID")
2204
+ DESKTOP_HOST_VARIABLES = ("CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_HOST_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_PID")
2205
2205
 
2206
2206
 
2207
2207
  def chat_environment(**extra: str) -> dict[str, str]:
@@ -2498,6 +2498,195 @@ def validate_chat_mention_skips_code_scenario() -> int:
2498
2498
  return 0
2499
2499
 
2500
2500
 
2501
+ def host_project_name(directory: Path) -> str:
2502
+ """The host's project directory name for a working directory (Claude Code's sanitizing)."""
2503
+ return re.sub(r"[^A-Za-z0-9]", "-", os.path.realpath(directory))
2504
+
2505
+
2506
+ def chat_session_start(cwd: Path, env: dict, session: str, pid: int, source: str = "startup",
2507
+ transcript: Path | None = None) -> subprocess.CompletedProcess:
2508
+ payload = {"cwd": str(cwd), "hook_event_name": "SessionStart", "session_id": session, "source": source}
2509
+ if transcript is not None:
2510
+ payload["transcript_path"] = str(transcript)
2511
+ return subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=cwd, text=True,
2512
+ capture_output=True, check=False, input=json.dumps(payload),
2513
+ env={**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": session, "CLAUDE_PID": str(pid)})
2514
+
2515
+
2516
+ def chat_presence(rtl: Path, role: str) -> dict:
2517
+ path = mailbox_common_dir(rtl) / "keel-chat" / "presence" / f"{role}.json"
2518
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
2519
+
2520
+
2521
+ def chat_session_list(rtl: Path, role: str) -> dict:
2522
+ path = mailbox_common_dir(rtl) / "keel-chat" / "presence" / f"{role}.sessions.json"
2523
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
2524
+
2525
+
2526
+ def chat_session_record(rtl: Path, session: str) -> dict:
2527
+ path = mailbox_common_dir(rtl) / "keel-chat" / "sessions" / f"{session}.json"
2528
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
2529
+
2530
+
2531
+ def validate_chat_hook_follows_session_worktree_scenario() -> int:
2532
+ """Issue #415 (measured 2026-10-21): a resumed `claude --bg -w` session's
2533
+ SessionStart reports the directory it was launched from as `cwd`.
2534
+
2535
+ keel-maint-2, launched from the main checkout, was recorded as the main
2536
+ checkout's role (codex-issues) and watched its signal, so a message to
2537
+ keel-maint-2 did not wake it. The transcript stays in the host project
2538
+ directory of the worktree the session really runs in; the hook follows it.
2539
+ """
2540
+ label = "chat-hook-follows-session-worktree:"
2541
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415a-") as raw:
2542
+ base = Path(raw)
2543
+ rtl, verify, env = chat_scratch_group(base)
2544
+ chat_session_start(rtl, env, "sess-r", os.getpid())
2545
+ transcript = base / "claude" / "projects" / host_project_name(verify) / "sess-v.jsonl"
2546
+ started = chat_session_start(rtl, env, "sess-v", os.getpid(), source="resume", transcript=transcript)
2547
+ try:
2548
+ watched = json.loads(started.stdout)["hookSpecificOutput"]["watchPaths"]
2549
+ except (ValueError, KeyError, TypeError):
2550
+ report(f"{label} the resumed session's SessionStart printed no watch paths: {started.stdout!r} {started.stderr!r}")
2551
+ return 1
2552
+ if not any(path.endswith("/signal/verify") for path in watched) or any(path.endswith("/signal/rtl") for path in watched):
2553
+ report(f"{label} a session whose transcript is verify's watches {watched!r}, not verify's signal alone.")
2554
+ return 1
2555
+ verify_presence = chat_presence(rtl, "verify")
2556
+ if verify_presence.get("cli_session") != "sess-v" or os.path.realpath(verify_presence.get("cli_worktree") or "") != os.path.realpath(verify):
2557
+ report(f"{label} verify's presence does not record the resumed session in verify's worktree: {verify_presence!r}")
2558
+ return 1
2559
+ if chat_session_record(rtl, "sess-v").get("role") != "verify":
2560
+ report(f"{label} the resumed session's record names {chat_session_record(rtl, 'sess-v').get('role')!r}, not verify.")
2561
+ return 1
2562
+ if chat_presence(rtl, "rtl").get("cli_session") != "sess-r":
2563
+ report(f"{label} rtl's presence took the resumed session: {chat_presence(rtl, 'rtl')!r}")
2564
+ return 1
2565
+ if "sess-v" in chat_session_list(rtl, "rtl"):
2566
+ report(f"{label} rtl's session list took the resumed session: {chat_session_list(rtl, 'rtl')!r}")
2567
+ return 1
2568
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
2569
+ report(f"{label} the scenario registry does not include it.")
2570
+ return 1
2571
+ report(f"{label.rstrip(':')} scenario passed.")
2572
+ return 0
2573
+
2574
+
2575
+ def validate_chat_visitor_not_recorded_scenario() -> int:
2576
+ """Issue #415: a session that runs a keel command in another role's worktree
2577
+ is not that role's session, and a caller with no Claude session clears nothing."""
2578
+ label = "chat-visitor-not-recorded:"
2579
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415b-") as raw:
2580
+ base = Path(raw)
2581
+ rtl, verify, env = chat_scratch_group(base)
2582
+ chat_session_start(rtl, env, "sess-r", os.getpid())
2583
+ chat_session_start(verify, env, "sess-v", os.getpid())
2584
+ visitor = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-r", "CLAUDE_PID": str(os.getpid())}
2585
+ run_keel(verify, "chat", "unread", env=visitor)
2586
+ bare = {key: value for key, value in env.items() if not key.startswith("CLAUDE")}
2587
+ run_keel(verify, "chat", "unread", env=bare)
2588
+ # A session binding verify's worktree from elsewhere, on someone's behalf: its
2589
+ # transcript lies under rtl's project directory, so it is not recorded.
2590
+ config = base / "claude"
2591
+ write_text(config / "projects" / host_project_name(rtl) / "sess-r.jsonl", "{}\n")
2592
+ run_keel(verify, "chat", "role", "--set", "verify", env={**visitor, "CLAUDE_CONFIG_DIR": str(config)})
2593
+ presence = chat_presence(rtl, "verify")
2594
+ if presence.get("cli_session") != "sess-v" or os.path.realpath(presence.get("cli_worktree") or "") != os.path.realpath(verify):
2595
+ report(f"{label} a visiting or session-less keel command replaced verify's recorded session: {presence!r}")
2596
+ return 1
2597
+ if set(chat_session_list(rtl, "verify")) != {"sess-v"}:
2598
+ report(f"{label} verify's session list is {sorted(chat_session_list(rtl, 'verify'))!r}, not its own session alone.")
2599
+ return 1
2600
+ own = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-v", "CLAUDE_PID": str(os.getpid())}
2601
+ before = chat_presence(rtl, "verify").get("last_active")
2602
+ time.sleep(1.1)
2603
+ run_keel(verify, "chat", "unread", env=own)
2604
+ if chat_presence(rtl, "verify").get("last_active") == before:
2605
+ report(f"{label} verify's own session running a keel command no longer marks it active.")
2606
+ return 1
2607
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
2608
+ report(f"{label} the scenario registry does not include it.")
2609
+ return 1
2610
+ report(f"{label.rstrip(':')} scenario passed.")
2611
+ return 0
2612
+
2613
+
2614
+ def validate_chat_role_set_records_session_scenario() -> int:
2615
+ """Issue #415: `keel chat role --set` in the live session makes it the role's session.
2616
+
2617
+ keel-maint-2 bound its role after starting, and `keel chat wake now
2618
+ keel-maint-2` then found no session to resume.
2619
+ """
2620
+ label = "chat-role-set-records-session:"
2621
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415c-") as raw:
2622
+ base = Path(raw)
2623
+ rtl, _verify, env = chat_scratch_group(base)
2624
+ lane = chat_worktree(rtl, base / "lane")
2625
+ config = base / "claude"
2626
+ transcript = config / "projects" / host_project_name(lane) / "sess-3.jsonl"
2627
+ write_text(transcript, json.dumps({"type": "user", "message": {"role": "user", "content": "hi"}}) + "\n")
2628
+ env = {**env, "CLAUDE_CONFIG_DIR": str(config)}
2629
+ chat_session_start(lane, env, "sess-3", os.getpid(), transcript=transcript)
2630
+ bound = run_keel(lane, "chat", "role", "--set", "verify2",
2631
+ env={**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-3", "CLAUDE_PID": str(os.getpid())})
2632
+ if bound.returncode != 0:
2633
+ report(f"{label} role --set failed: {bound.stdout!r} {bound.stderr!r}")
2634
+ return 1
2635
+ presence = chat_presence(rtl, "verify2")
2636
+ if presence.get("cli_session") != "sess-3" or os.path.realpath(presence.get("cli_worktree") or "") != os.path.realpath(lane):
2637
+ report(f"{label} binding a role did not record the session that bound it: {presence!r}")
2638
+ return 1
2639
+ if chat_session_record(rtl, "sess-3").get("role") != "verify2":
2640
+ report(f"{label} the binding session's record names {chat_session_record(rtl, 'sess-3').get('role')!r}, not verify2.")
2641
+ return 1
2642
+ segments_file = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "segments" / "verify2.json"
2643
+ segments = json.loads(segments_file.read_text(encoding="utf-8")).get("segments", []) if segments_file.exists() else []
2644
+ if not segments or os.path.realpath(segments[-1].get("transcript", "")) != os.path.realpath(transcript):
2645
+ report(f"{label} verify2's current segment is not the binding session's transcript: {segments!r}")
2646
+ return 1
2647
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
2648
+ report(f"{label} the scenario registry does not include it.")
2649
+ return 1
2650
+ report(f"{label.rstrip(':')} scenario passed.")
2651
+ return 0
2652
+
2653
+
2654
+ def validate_chat_wake_skips_removed_session_scenario() -> int:
2655
+ """Issue #415: a role's recorded session that `claude rm` removed is not resumed."""
2656
+ label = "chat-wake-skips-removed-session:"
2657
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415d-") as raw:
2658
+ base = Path(raw)
2659
+ rtl, verify, env, _ = shift_scratch(base)
2660
+ calls = base / "claude-calls.jsonl"
2661
+ fake = base / "fake-claude"
2662
+ write_text(fake, "#!/usr/bin/env python3\nimport json, sys\n"
2663
+ f"open({str(calls)!r}, 'a').write(json.dumps(sys.argv[1:]) + '\\n')\n"
2664
+ "if sys.argv[1:3] == ['agents', '--json']:\n"
2665
+ " print(json.dumps([{'kind': 'background', 'sessionId': 'other-0000', 'id': 'other-00', 'cwd': '/tmp'}]))\n"
2666
+ "else:\n print('backgrounded · fake')\n")
2667
+ fake.chmod(0o755)
2668
+ env = {**env, "KEEL_CLAUDE": str(fake)}
2669
+ dead = subprocess.Popen(["true"])
2670
+ dead.wait()
2671
+ chat_session_start(verify, env, "sess-verify-1", dead.pid)
2672
+ woke = run_keel(rtl, "chat", "wake", "now", "verify", env=env)
2673
+ made = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2674
+ if any(call[:1] == ["--bg"] for call in made):
2675
+ report(f"{label} wake now resumed a session claude agents no longer lists: {made!r}")
2676
+ return 1
2677
+ if woke.returncode == 0:
2678
+ report(f"{label} wake now exits 0 for a session it could not resume: {woke.stdout!r}")
2679
+ return 1
2680
+ if "removed" not in (woke.stdout + woke.stderr):
2681
+ report(f"{label} wake now does not say the recorded session was removed: {woke.stdout!r} {woke.stderr!r}")
2682
+ return 1
2683
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
2684
+ report(f"{label} the scenario registry does not include it.")
2685
+ return 1
2686
+ report(f"{label.rstrip(':')} scenario passed.")
2687
+ return 0
2688
+
2689
+
2501
2690
  def validate_chat_wake_now_cli_scenario() -> int:
2502
2691
  """Issue #348 on the CLI (owner's CLI waker, 2026-10-19): one step wakes a role.
2503
2692
 
@@ -2528,7 +2717,9 @@ def validate_chat_wake_now_cli_scenario() -> int:
2528
2717
  input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": "sess-verify-1", "source": "startup"}))
2529
2718
 
2530
2719
  def made() -> list[dict]:
2531
- return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2720
+ # The resumes only: since #415 a wake first reads `claude agents --json --all`.
2721
+ calls_made = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2722
+ return [call for call in calls_made if call["argv"][:1] == ["--bg"]]
2532
2723
 
2533
2724
  start(dead.pid)
2534
2725
  posted = run_keel(rtl, "chat", "dm", "verify", "rerun R009", env=env)
@@ -25323,6 +25514,162 @@ process.exit(0);
25323
25514
  """
25324
25515
 
25325
25516
 
25517
+ # A claude for #424: the Keel plugin, the background sessions `agents --json`
25518
+ # lists, `stop` (which kills the row's process, as the host does a moment after
25519
+ # returning), and `--bg --resume`, which records whether the old process was
25520
+ # still alive when it ran.
25521
+ ADOPT_FAKE_CLAUDE = r"""const fs = require("fs");
25522
+ const args = process.argv.slice(2);
25523
+ const joined = args.join(" ");
25524
+ const statePath = process.env.FAKE_STATE;
25525
+ const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
25526
+ const save = () => fs.writeFileSync(statePath, JSON.stringify(state));
25527
+ fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify({ args, cwd: process.cwd() }) + "\n");
25528
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
25529
+ if (joined === "plugin list --json") {
25530
+ process.stdout.write(JSON.stringify([{ id: "keel@keel-marketplace", version: state.version,
25531
+ lastUpdated: state.lastUpdated }]));
25532
+ } else if (joined === "plugin update keel@keel-marketplace") {
25533
+ state.version = "5.1.0";
25534
+ save();
25535
+ } else if (joined === "agents --json") {
25536
+ process.stdout.write(JSON.stringify(state.rows));
25537
+ } else if (args[0] === "stop") {
25538
+ const row = state.rows.find((item) => item.id === args[1]);
25539
+ if (row) {
25540
+ setTimeout(() => { try { process.kill(row.pid, "SIGKILL"); } catch {} }, 300);
25541
+ delete row.status;
25542
+ save();
25543
+ }
25544
+ process.stdout.write(`stopped ${args[1]}\n`);
25545
+ setTimeout(() => process.exit(0), 400);
25546
+ return;
25547
+ } else if (args[0] === "--bg" && args[1] === "--resume") {
25548
+ const row = state.rows.find((item) => item.sessionId === args[2]);
25549
+ fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify({ resumed: args[2], oldAlive: row ? alive(row.pid) : null }) + "\n");
25550
+ if (row) { row.status = "idle"; row.startedAt = Date.now(); save(); }
25551
+ process.stdout.write(`backgrounded · ${args[2].slice(0, 8)} · resumed\n`);
25552
+ }
25553
+ process.exit(0);
25554
+ """
25555
+
25556
+
25557
+ def validate_update_adopts_idle_sessions_scenario() -> int:
25558
+ """Issue #424: a release reaches the running background sessions on request.
25559
+
25560
+ Each Claude background session keeps the plugin it loaded. A hand-over starts
25561
+ a new process, so it adopts the update; a session that does not change shift
25562
+ stays on the old one. Measured on 2026-10-21 (Claude Code 2.1.304), stop and
25563
+ resume with no prompt restarts it on the installed plugin without a turn.
25564
+ `--adopt` does that for the idle sessions started before the update, and
25565
+ leaves busy, guarded, and its own session alone.
25566
+ """
25567
+ label = "update-adopts-idle-sessions:"
25568
+ t0 = 1792540800000 # 2026-10-21T00:00:00Z, the update's lastUpdated
25569
+ with tempfile.TemporaryDirectory(prefix="keel-adopt-424-", ignore_cleanup_errors=True) as raw:
25570
+ tmp = Path(raw)
25571
+ fake = tmp / "fake-claude.js"
25572
+ write_text(fake, ADOPT_FAKE_CLAUDE)
25573
+ launcher = tmp / "fake-claude"
25574
+ write_text(launcher, f'#!/bin/sh\nexec node "{fake}" "$@"\n')
25575
+ launcher.chmod(0o755)
25576
+ npm_fake = tmp / "fake-npm.js"
25577
+ write_text(npm_fake, UPDATE_FAKE)
25578
+ npm = tmp / "fake-npm"
25579
+ write_text(npm, f'#!/bin/sh\nFAKE_HOST=npm exec node "{npm_fake}" "$@"\n')
25580
+ npm.chmod(0o755)
25581
+ guarded = tmp / "guarded"
25582
+ write_text(guarded / "keel" / "guard.json", "{}\n")
25583
+ sleepers: list[int] = []
25584
+
25585
+ def row(name: str, sid: str, status: str, started: int, cwd: Path) -> dict:
25586
+ # Not this process's child: a killed child stays a zombie until reaped,
25587
+ # and a zombie still answers kill(pid, 0), which a host process never does.
25588
+ pid = int(subprocess.run(["sh", "-c", "sleep 300 >/dev/null 2>&1 & echo $!"], text=True,
25589
+ capture_output=True, check=True).stdout.strip())
25590
+ sleepers.append(pid)
25591
+ return {"kind": "background", "name": name, "sessionId": sid, "id": sid[:8], "status": status,
25592
+ "state": "working", "pid": pid, "cwd": str(cwd), "startedAt": started}
25593
+
25594
+ def run(*extra: str) -> tuple[subprocess.CompletedProcess, list[dict]]:
25595
+ log = tmp / "log.jsonl"
25596
+ log.write_text("")
25597
+ rows = [
25598
+ row("lead · old idle", "aaaaaaaa-0000-0000-0000-000000000001", "idle", t0 - 3600000, tmp),
25599
+ row("verify · old busy", "bbbbbbbb-0000-0000-0000-000000000002", "busy", t0 - 3600000, tmp),
25600
+ row("rtl · old guarded", "cccccccc-0000-0000-0000-000000000003", "idle", t0 - 3600000, guarded),
25601
+ row("pm · fresh idle", "dddddddd-0000-0000-0000-000000000004", "idle", t0 + 3600000, tmp),
25602
+ row("maint · this session", "eeeeeeee-0000-0000-0000-000000000005", "busy", t0 - 3600000, tmp),
25603
+ ]
25604
+ (tmp / "state.json").write_text(json.dumps({"version": "5.0.0", "lastUpdated": "2026-10-21T00:00:00.000Z", "rows": rows}))
25605
+ env = dict(os.environ)
25606
+ env.update({"KEEL_UPDATE_NPM": str(npm), "KEEL_UPDATE_CLAUDE": str(launcher),
25607
+ "KEEL_UPDATE_CODEX": str(tmp / "no-codex"), "FAKE_LOG": str(log),
25608
+ "FAKE_STATE": str(tmp / "state.json"), "CLAUDE_CODE_SESSION_ID": rows[4]["sessionId"]})
25609
+ env.pop("KEEL_UPDATE_SOURCE", None)
25610
+ result = subprocess.run(["node", str(ROOT / "bin/keel.js"), "--update", *extra], cwd=tmp, env=env,
25611
+ text=True, capture_output=True, check=False, timeout=90)
25612
+ # The npm fake logs arrays to the same file; the claude fake logs objects.
25613
+ entries = [json.loads(line) for line in log.read_text().splitlines() if line.strip()]
25614
+ return result, [entry for entry in entries if isinstance(entry, dict)]
25615
+
25616
+ try:
25617
+ adopted, calls = run("--adopt")
25618
+ stops = [c["args"][1] for c in calls if c.get("args", [None])[0] == "stop"]
25619
+ resumes = [c for c in calls if c.get("args", [None])[:2] == ["--bg", "--resume"]]
25620
+ witnessed = [c for c in calls if "resumed" in c]
25621
+ line = next((l for l in adopted.stdout.splitlines() if l.startswith("keel update: claude sessions:")), "")
25622
+ if adopted.returncode != 0:
25623
+ report(f"{label} keel --update --adopt exited {adopted.returncode}: {adopted.stdout!r} {adopted.stderr!r}")
25624
+ return 1
25625
+ if stops != ["aaaaaaaa"]:
25626
+ report(f"{label} --adopt stopped {stops!r}, not only the idle session started before the update.")
25627
+ return 1
25628
+ if len(resumes) != 1 or resumes[0]["args"] != ["--bg", "--resume", "aaaaaaaa-0000-0000-0000-000000000001"]:
25629
+ report(f"{label} --adopt did not resume the stopped session with exactly `--bg --resume <id>`: {resumes!r}")
25630
+ return 1
25631
+ if resumes[0]["cwd"] != os.path.realpath(tmp) and resumes[0]["cwd"] != str(tmp):
25632
+ report(f"{label} the resume ran in {resumes[0]['cwd']!r}, not the session's worktree {str(tmp)!r}.")
25633
+ return 1
25634
+ if not witnessed or witnessed[0]["oldAlive"]:
25635
+ report(f"{label} the resume ran while the stopped session's process was still alive: {witnessed!r}")
25636
+ return 1
25637
+ for needle in ("adopted", "lead · old idle", "verify · old busy", "rtl · old guarded"):
25638
+ if needle not in line:
25639
+ report(f"{label} the claude sessions line does not name {needle!r}: {line!r}")
25640
+ return 1
25641
+ for absent in ("pm · fresh idle", "maint · this session"):
25642
+ if absent in line:
25643
+ report(f"{label} the claude sessions line names {absent!r}, which is not on an older plugin or is this session: {line!r}")
25644
+ return 1
25645
+
25646
+ named, calls = run()
25647
+ line = next((l for l in named.stdout.splitlines() if l.startswith("keel update: claude sessions:")), "")
25648
+ if any(c.get("args", [None])[0] == "stop" or c.get("args", [None])[:2] == ["--bg", "--resume"] for c in calls):
25649
+ report(f"{label} keel --update without --adopt stopped or resumed a session: {calls!r}")
25650
+ return 1
25651
+ for needle in ("lead · old idle", "verify · old busy", "rtl · old guarded", "keel --update --adopt"):
25652
+ if needle not in line:
25653
+ report(f"{label} without --adopt the claude sessions line does not name {needle!r}: {line!r}")
25654
+ return 1
25655
+ finally:
25656
+ for pid in sleepers:
25657
+ try:
25658
+ os.kill(pid, signal.SIGKILL)
25659
+ except ProcessLookupError:
25660
+ pass
25661
+ refused = subprocess.run(["node", str(ROOT / "bin/keel.js"), "--adopt"], cwd=ROOT, text=True,
25662
+ capture_output=True, check=False)
25663
+ if refused.returncode != 2:
25664
+ report(f"{label} --adopt outside --update exited {refused.returncode}, not 2: {refused.stderr!r}")
25665
+ return 1
25666
+ if label.rstrip(":") not in {name for name, _ in SCENARIOS}:
25667
+ report(f"{label} the scenario registry does not include it.")
25668
+ return 1
25669
+ report(f"{label.rstrip(':')} scenario passed.")
25670
+ return 0
25671
+
25672
+
25326
25673
  def validate_update_covers_installed_hosts_scenario() -> int:
25327
25674
  """Issue #204: one owner-run `keel --update` covers every installed component.
25328
25675
 
@@ -41773,6 +42120,7 @@ SCENARIOS: tuple = (
41773
42120
  ("update-host-query-timeout", validate_update_host_query_timeout_scenario),
41774
42121
  ("update-codex-from-disk", validate_update_codex_from_disk_scenario),
41775
42122
  ("update-registry-lag", validate_update_registry_lag_scenario),
42123
+ ("update-adopts-idle-sessions", validate_update_adopts_idle_sessions_scenario),
41776
42124
  ("refresh-covers-every-target", validate_refresh_covers_every_target_scenario),
41777
42125
  ("directory-branch-advances", validate_directory_branch_advances_scenario),
41778
42126
  ("release-notes-name-the-directory-branch", validate_release_notes_name_the_directory_branch_scenario),
@@ -41814,6 +42162,10 @@ SCENARIOS: tuple = (
41814
42162
  ("two-live-sessions-on-one-role", validate_two_live_sessions_on_one_role_scenario),
41815
42163
  ("chat-role-rename", validate_chat_role_rename_scenario),
41816
42164
  ("chat-wake-now-cli", validate_chat_wake_now_cli_scenario),
42165
+ ("chat-hook-follows-session-worktree", validate_chat_hook_follows_session_worktree_scenario),
42166
+ ("chat-visitor-not-recorded", validate_chat_visitor_not_recorded_scenario),
42167
+ ("chat-role-set-records-session", validate_chat_role_set_records_session_scenario),
42168
+ ("chat-wake-skips-removed-session", validate_chat_wake_skips_removed_session_scenario),
41817
42169
  ("chat-ack", validate_chat_ack_scenario),
41818
42170
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
41819
42171
  ("patrol-since-last", validate_patrol_since_last_scenario),
@@ -378,13 +378,15 @@ function dispatch(where, options) {
378
378
  }
379
379
  let role = store.currentRole(where);
380
380
  if (options.set !== null) role = store.setRole(where, options.set);
381
+ // The session that binds a role becomes its session (#415 D3).
382
+ const bound = options.set !== null && role ? notice.recordBinding(where, role) : null;
381
383
  if (options.alias !== null) {
382
384
  if (!role) throw new ChatError("Bind a role before adding an alias: `keel chat role --set <name>`.");
383
385
  store.addAlias(where, role, options.alias);
384
386
  }
385
387
  const aliases = role ? store.readMember(where.root, role).aliases : [];
386
388
  if (options.json) out(JSON.stringify({ role, aliases, worktree: where.worktree, store: where.root }));
387
- else out(role ? `Chat role: ${role}${aliases.length ? ` (aliases: ${aliases.join(", ")})` : ""}` : "This worktree has no chat role. Bind one with `keel chat role --set <name>`.");
389
+ else out(role ? `Chat role: ${role}${aliases.length ? ` (aliases: ${aliases.join(", ")})` : ""}${bound ? `\n${bound}` : ""}` : "This worktree has no chat role. Bind one with `keel chat role --set <name>`.");
388
390
  return 0;
389
391
  }
390
392
  case "group":
@@ -705,6 +707,7 @@ function runWake(cwd, options) {
705
707
  return 0;
706
708
  }
707
709
  const resumed = notice.resumeCli(entry);
710
+ if (resumed.removed) throw new ChatError(`${role}'s recorded CLI ${resumed.output}.`);
708
711
  out(`${resumed.ok ? "Resumed" : "Could not resume"} ${role}'s CLI session ${entry.session} in ${entry.worktree}.${resumed.output ? `\n${resumed.output}` : ""}`);
709
712
  return resumed.ok ? 0 : 1;
710
713
  }
@@ -747,7 +750,7 @@ function runChat(argv) {
747
750
  const where = store.requireLocation(cwd);
748
751
  migrateIfNeeded(where);
749
752
  const role = store.currentRole(where);
750
- if (role) notice.touchPresence(where, role);
753
+ if (role) notice.commandPresence(where, role);
751
754
  // Two live sessions on one role share its name and cursor (#369 D3).
752
755
  if (role && ["post", "dm", "todo", "unread", "read"].includes(options.positionals[0])) {
753
756
  const twins = notice.twinWarning(where, role);
@@ -215,6 +215,25 @@ const CLI_WAKE_PROMPT = "You have unread keel chat records; run keel context, th
215
215
  // and the prompt: any other flag starts a copy with a new session id.
216
216
  function resumeCli(entry) {
217
217
  const claude = process.env.KEEL_CLAUDE || "claude";
218
+ // A session `claude rm` removed is gone for good (#415 D4): when the host's
219
+ // list can be read and lacks it, nothing is resumed. An unreadable list
220
+ // resumes as before, since Keel cannot tell.
221
+ const listed = require("child_process").spawnSync(claude, ["agents", "--json", "--all"], {
222
+ encoding: "utf8", timeout: 30 * 1000,
223
+ });
224
+ try {
225
+ const rows = JSON.parse(listed.stdout);
226
+ if (!listed.error && listed.status === 0 && Array.isArray(rows)
227
+ && !rows.some((row) => row && row.sessionId === entry.session)) {
228
+ return {
229
+ ok: false,
230
+ removed: true,
231
+ output: `session ${entry.session} was removed: \`claude agents\` no longer lists it, so a new session must be started for the role in ${entry.worktree || "its worktree"}`,
232
+ };
233
+ }
234
+ } catch {
235
+ // Not a list: fall through and resume.
236
+ }
218
237
  const result = require("child_process").spawnSync(claude, ["--bg", "--resume", entry.session, CLI_WAKE_PROMPT], {
219
238
  cwd: entry.worktree || undefined, encoding: "utf8",
220
239
  });
@@ -506,6 +525,87 @@ function languageAfterTools(where, payload) {
506
525
  return { code: 0 };
507
526
  }
508
527
 
528
+ function realpathOf(file) {
529
+ try {
530
+ return fs.realpathSync(file);
531
+ } catch {
532
+ return path.resolve(file);
533
+ }
534
+ }
535
+
536
+ // The host's project directory name for a working directory.
537
+ function hostProjectName(directory) {
538
+ return directory.replace(/[^A-Za-z0-9]/g, "-");
539
+ }
540
+
541
+ // Where a hook's session runs (#415 D1). A resumed `claude --bg -w` session's
542
+ // SessionStart names the directory it was launched from as `cwd` (measured
543
+ // 2026-10-21, Claude Code 2.1.304), while its transcript stays in the host
544
+ // project directory of the worktree it runs in. When that names another
545
+ // worktree of this repository, the session is that worktree's.
546
+ function hookLocation(payload) {
547
+ const where = store.locate(payload.cwd || process.cwd());
548
+ const transcript = typeof payload.transcript_path === "string" ? payload.transcript_path : "";
549
+ if (!where || !path.isAbsolute(transcript)) return where;
550
+ const project = path.basename(path.dirname(transcript));
551
+ const named = (dir) => [dir, realpathOf(dir)].some((candidate) => hostProjectName(candidate) === project);
552
+ if (named(where.worktree)) return where;
553
+ const listed = require("child_process").spawnSync("git", ["worktree", "list", "--porcelain"], {
554
+ cwd: where.worktree, encoding: "utf8",
555
+ });
556
+ if (listed.error || listed.status !== 0) return where;
557
+ const match = String(listed.stdout).split("\n").filter((line) => line.startsWith("worktree "))
558
+ .map((line) => line.slice("worktree ".length)).find(named);
559
+ return (match && store.locate(match)) || where;
560
+ }
561
+
562
+ // A keel command touches the presence of the role bound to its worktree (#415
563
+ // D2). Only that role's own session — one whose record names the role — records
564
+ // itself there; a visiting session, or a caller with no Claude session, marks
565
+ // the role active and leaves its recorded session and session list as they are.
566
+ function commandPresence(where, role) {
567
+ const id = process.env.CLAUDE_CODE_SESSION_ID;
568
+ const file = id && /^[A-Za-z0-9._-]{1,128}$/.test(id) ? path.join(where.root, "sessions", `${id}.json`) : null;
569
+ if (file && fs.existsSync(file) && store.readJsonFile(file).role === role) {
570
+ touchPresence(where, role);
571
+ return;
572
+ }
573
+ const previous = store.readJsonFile(presenceFile(where, role));
574
+ if (!Object.keys(previous).length) return;
575
+ try {
576
+ store.writeJsonAtomic(where, presenceFile(where, role), { ...previous, state: "online", last_active: store.isoLocal(new Date()) });
577
+ } catch {
578
+ // Presence is a convenience: failing to record it must not fail a command.
579
+ }
580
+ }
581
+
582
+ // `keel chat role --set` inside a Claude Code session makes that session the
583
+ // role's (#415 D3): its record names the role, presence names it, and its
584
+ // transcript starts the role's current segment. Its hooks keep the watch list
585
+ // they were given at start. Returns a sentence for the user, or null.
586
+ function recordBinding(where, role) {
587
+ const id = process.env.CLAUDE_CODE_SESSION_ID;
588
+ if (!id || !/^[A-Za-z0-9._-]{1,128}$/.test(id)) return null;
589
+ // Only a session running in this worktree: its transcript is in this
590
+ // worktree's host project directory. A session binding the role from
591
+ // another worktree on someone's behalf is not recorded (#415 step 1).
592
+ const config = process.env.CLAUDE_CONFIG_DIR || path.join(require("os").homedir(), ".claude");
593
+ const transcript = [where.worktree, realpathOf(where.worktree)]
594
+ .map((dir) => path.join(config, "projects", hostProjectName(dir), `${id}.jsonl`))
595
+ .find((candidate) => fs.existsSync(candidate));
596
+ if (!transcript) return null;
597
+ const file = path.join(where.root, "sessions", `${id}.json`);
598
+ try {
599
+ rememberSession(where, role, file);
600
+ store.writeJsonAtomic(where, file, { ...store.readJsonFile(file), decided: true, host_run: false });
601
+ } catch {
602
+ return null;
603
+ }
604
+ touchPresence(where, role, "online", "claude-code", { source: "role-set" });
605
+ recordSegment(where, role, transcript);
606
+ return `Recorded this session (${id.slice(0, 8)}) as ${role}'s, so \`keel chat wake now ${role}\` resumes it.`;
607
+ }
608
+
509
609
  function hook(event, input, { mail = false } = {}) {
510
610
  if (!(event in HOST_EVENTS)) return { code: 0 };
511
611
  let payload = {};
@@ -517,7 +617,7 @@ function hook(event, input, { mail = false } = {}) {
517
617
  let where = null;
518
618
  let role = null;
519
619
  try {
520
- where = store.locate(payload.cwd || process.cwd());
620
+ where = hookLocation(payload);
521
621
  role = where ? store.currentRole(where) : null;
522
622
  } catch {
523
623
  role = null;
@@ -616,4 +716,6 @@ module.exports = {
616
716
  presenceOf,
617
717
  signalPath,
618
718
  touchPresence,
719
+ commandPresence,
720
+ recordBinding,
619
721
  };