@christang/keel 5.180.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.180.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,4 +1,4 @@
1
- <!-- keel:start version=5.180.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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.180.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.180.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.180.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.180.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.180.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.180.0"
55
- PROTOCOL_VERSION = "5.180.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)
@@ -41971,6 +42162,10 @@ SCENARIOS: tuple = (
41971
42162
  ("two-live-sessions-on-one-role", validate_two_live_sessions_on_one_role_scenario),
41972
42163
  ("chat-role-rename", validate_chat_role_rename_scenario),
41973
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),
41974
42169
  ("chat-ack", validate_chat_ack_scenario),
41975
42170
  ("coordinator-patrol", validate_coordinator_patrol_scenario),
41976
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
  };