@christang/keel 5.97.0 → 5.99.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -687,7 +687,7 @@ the brief, so `egress_deny` guards what is handed over, not what it can open.
687
687
 
688
688
  ## Group chat between sessions
689
689
 
690
- Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. Each member has its own unread state, and history is kept. Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention. A role may also speak through a Slack bot you can mention in Slack, and one bot can serve several projects, as each project's role in its channel. See [the Slack setup guide](docs/chat-slack-setup.md). The 5.83 `keel mail` commands keep working on direct groups.
690
+ Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. Each member has its own unread state, and history is kept. Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. Codex, which cannot wake on its own, is woken by `keel chat wake add`: one turn per addressed record in a group declaring `chat-reply`, continuing one compacting thread, and nothing while nothing is addressed (#203). Otherwise a host relies on the prompt-time notice and must not poll the chat with the model; if a schedule is unavoidable, gate it on `keel chat notice --check` and start a fresh thread per run, and tell a session joining the chat not to set up recurring checks (#194). With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention. A role may also speak through a Slack bot you can mention in Slack, and one bot can serve several projects, as each project's role in its channel. See [the Slack setup guide](docs/chat-slack-setup.md). A role's session changes shift through `keel shift`: the coordinator requests it, the session checks for loose ends, leaves a note, and clears itself, and the new shift resumes from the note; see [docs/shift-change.md](docs/shift-change.md). The 5.83 `keel mail` commands keep working on direct groups.
691
691
 
692
692
  ## Commands
693
693
 
package/README.zh-CN.md CHANGED
@@ -231,7 +231,7 @@ Keel 看不到对方在任务说明之外还读了什么,所以 `egress_deny`
231
231
 
232
232
  Codex 自己不会在闲着时醒来,可以在它的 worktree 里运行 `keel chat wake add`:在声明了 `chat-reply` 的群里,每条找它的消息启动一轮,接着同一个会自动压缩的线程,没人找时什么都不跑(#203)。其他宿主依靠下一次对话时的提醒,不要让模型定期检查群聊。确实需要定时检查时,先用 `keel chat notice --check` 把关,每次运行都开新线程;让会话加入群聊时,也要明确告诉它不要设置定时或循环检查(#194)。
233
233
 
234
- 每台电脑配一个 Slack App、跑一个桥接程序,同一批群就能实时连到其他电脑上的会话和你的手机;角色也可以通过 Slack bot 发言,在 Slack 里能直接 @ 它;一个 bot 可以服务多个项目,在每个项目的频道里代表那个项目的角色。聊天记录同时存在孤儿分支 `keel-chat` 上,不受 Slack 保留期限制。配置方法见 [Slack 配置说明](docs/chat-slack-setup.zh-CN.md)。5.83 的 `keel mail` 命令继续可用,消息存在私聊群里。
234
+ 每台电脑配一个 Slack App、跑一个桥接程序,同一批群就能实时连到其他电脑上的会话和你的手机;角色也可以通过 Slack bot 发言,在 Slack 里能直接 @ 它;一个 bot 可以服务多个项目,在每个项目的频道里代表那个项目的角色。聊天记录同时存在孤儿分支 `keel-chat` 上,不受 Slack 保留期限制。配置方法见 [Slack 配置说明](docs/chat-slack-setup.zh-CN.md)。角色会话用 `keel shift` 换班:协调者发起,会话自查收尾、留便条、清空自己,新的一班从便条接手,见 [docs/shift-change.zh-CN.md](docs/shift-change.zh-CN.md)。5.83 的 `keel mail` 命令继续可用,消息存在私聊群里。
235
235
 
236
236
  ## 命令参考
237
237
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.97.0 -->
1
+ <!-- keel:start version=5.99.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
@@ -106,6 +106,7 @@ Usage:
106
106
  keel mail role|send|list|read|hook [repo] ... (cross-host mailbox; see keel mail help)
107
107
  keel triage [repo] [--labels <l1,l2>] [--issue <n>] [--json]
108
108
  keel agents [name] [--repo path] [--json] (external model CLIs, read on demand; Keel launches none)
109
+ keel shift request|check|ready|start|resume|status ... (a role's shift change; see keel shift --help)
109
110
  keel openspec [args...]
110
111
  keel --init [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update]
111
112
  keel --install [repo] [--target claude|codex|opencode] [--dry-run] [--force-template-update] [--with-git-hooks]
@@ -2849,6 +2850,10 @@ function main() {
2849
2850
  if (process.argv[2] === "chat") {
2850
2851
  return require("../src/core/chat/cli").runChat(process.argv.slice(3));
2851
2852
  }
2853
+ // `keel shift` likewise: a coordinated shift change for a role's session.
2854
+ if (process.argv[2] === "shift") {
2855
+ return require("../src/core/shift").runShift(process.argv.slice(3));
2856
+ }
2852
2857
  // `keel agents` likewise: the external model CLI catalog (#219).
2853
2858
  if (process.argv[2] === "agents") {
2854
2859
  return require("../src/core/agents").runAgents(process.argv.slice(3));
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.97.0",
3
+ "version": "5.99.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.97.0",
9
+ "version": "5.99.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.97.0",
5
+ "version": "5.99.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.97.0",
3
+ "version": "5.99.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.97.0",
3
+ "version": "5.99.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",
@@ -445,6 +445,47 @@ function fallback(reason) {
445
445
  );
446
446
  }
447
447
 
448
+ // The git common directory of `cwd`, read from `.git` without spawning git.
449
+ function gitCommonDir(cwd) {
450
+ for (let dir = cwd; dir && dir !== path.dirname(dir); dir = path.dirname(dir)) {
451
+ const dotGit = path.join(dir, ".git");
452
+ let stat;
453
+ try {
454
+ stat = fs.statSync(dotGit);
455
+ } catch {
456
+ continue;
457
+ }
458
+ if (stat.isDirectory()) return dotGit;
459
+ const match = fs.readFileSync(dotGit, "utf8").match(/^gitdir:\s*(.+)$/m);
460
+ if (!match) return null;
461
+ const gitdir = path.resolve(dir, match[1].trim());
462
+ return /[\\/]worktrees[\\/][^\\/]+$/.test(gitdir) ? path.dirname(path.dirname(gitdir)) : gitdir;
463
+ }
464
+ return null;
465
+ }
466
+
467
+ // A repository without OpenSpec gets no projection, except a note from the
468
+ // previous shift (shift-without-role D3): checked on disk first, so the
469
+ // common case spawns nothing.
470
+ function shiftOnly(cwd) {
471
+ const common = gitCommonDir(cwd);
472
+ if (!common || !fs.existsSync(path.join(common, "keel-chat", "shift"))) return 0;
473
+ const result = runKeel(cwd, ["context", "--json"], keelCommand().command);
474
+ let context = null;
475
+ try {
476
+ context = JSON.parse(result.stdout);
477
+ } catch {
478
+ return 0;
479
+ }
480
+ if (!context || !context.shift || !context.shift.since) return 0;
481
+ const shift = `shift: your previous shift left a note (${context.shift.since}); run \`keel shift resume\` before anything else.`;
482
+ emit(
483
+ `Keel: ${shift} It authorizes nothing.`,
484
+ panel([`Keel: ${shift[0].toUpperCase()}${shift.slice(1)}`, DISPOSABLE])
485
+ );
486
+ return 0;
487
+ }
488
+
448
489
  function main() {
449
490
  const input = readStdin();
450
491
  const handed = handOff(__filename, input, 12000);
@@ -459,7 +500,7 @@ function main() {
459
500
  typeof event.cwd === "string" && event.cwd ? event.cwd : process.cwd();
460
501
 
461
502
  if (!fs.existsSync(path.join(cwd, "openspec"))) {
462
- return 0;
503
+ return shiftOnly(cwd);
463
504
  }
464
505
 
465
506
  const cli = keelCommand();
@@ -571,6 +612,12 @@ function main() {
571
612
  }
572
613
  const pointer = precedentPointer(cwd);
573
614
  if (pointer) lines.push(`- ${pointer}`);
615
+ // A note from the previous shift (shift-without-role D3), on every host.
616
+ if (context.shift && context.shift.since) {
617
+ const shift = `shift: your previous shift left a note (${context.shift.since}); run \`keel shift resume\` before anything else.`;
618
+ lines.push(`- ${shift}`);
619
+ human.splice(human.length - 1, 0, shift[0].toUpperCase() + shift.slice(1));
620
+ }
574
621
  lines.push(`- report this state ${DISCLOSURE}; it authorizes nothing.`);
575
622
  emit(lines.join("\n"), panel(human));
576
623
  return 0;
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.97.0"
51
- PROTOCOL_VERSION = "5.97.0"
50
+ PACKAGE_VERSION = "5.99.0"
51
+ PROTOCOL_VERSION = "5.99.0"
52
52
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
53
53
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
54
54
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -4457,6 +4457,255 @@ def validate_collected_feedback_is_recorded_scenario() -> int:
4457
4457
  return 0
4458
4458
 
4459
4459
 
4460
+ def validate_shift_change_scenario() -> int:
4461
+ """Owner's decision of 2026-10-05: a role's session changes shift through Keel.
4462
+
4463
+ The coordinator requests it, the role's readiness check names every loose
4464
+ end, `ready` stores the shift note outside the worktree and closes the
4465
+ request, `start` wakes the cleared role only once the note waits, the
4466
+ session-start notice points to the note, and `resume` consumes it.
4467
+ """
4468
+ label = "shift-change:"
4469
+ with tempfile.TemporaryDirectory(prefix="keel-shift-") as raw:
4470
+ base = Path(raw)
4471
+ rtl, verify, env = chat_scratch_group(base)
4472
+ remote = base / "remote.git"
4473
+ subprocess.run(["git", "init", "-q", "--bare", str(remote)], check=True)
4474
+ subprocess.run(["git", "remote", "add", "origin", str(remote)], cwd=rtl, check=True)
4475
+ for tree in (rtl, verify):
4476
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
4477
+ common = mailbox_common_dir(rtl) / "keel-chat"
4478
+ signal = common / "signal" / "verify"
4479
+
4480
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
4481
+ return run_keel(cwd, "shift", *args, env=env)
4482
+
4483
+ def notice() -> str:
4484
+ # The SessionStart projection, which every host runs (shift-without-role D3).
4485
+ session = run_session_start_hook(
4486
+ verify, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(verify)},
4487
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"', extra_env={k: v for k, v in env.items() if k.startswith("KEEL_")},
4488
+ )
4489
+ return session_start_context(session) or ""
4490
+
4491
+ size = signal.stat().st_size if signal.exists() else 0
4492
+ requested = shift(rtl, "request", "verify")
4493
+ if requested.returncode != 0:
4494
+ report(f"{label} keel shift request failed: {requested.stderr.strip()}")
4495
+ return 1
4496
+ request = [r for r in chat_records_with(rtl, "dm-rtl--verify", "shift") if "kind: todo" in r and "keel-shift" in r]
4497
+ if not request:
4498
+ report(f"{label} no keel-shift todo reached dm-rtl--verify: {requested.stdout.strip()}")
4499
+ return 1
4500
+ if "assignee: verify" not in request[0]:
4501
+ report(f"{label} the shift request is not assigned to verify:\n{request[0]}")
4502
+ return 1
4503
+ if not signal.exists():
4504
+ report(f"{label} the request created no signal file for verify.")
4505
+ return 1
4506
+ if signal.stat().st_size <= size:
4507
+ report(f"{label} the request did not touch verify's signal file.")
4508
+ return 1
4509
+ if shift(rtl, "start", "verify").returncode == 0:
4510
+ report(f"{label} keel shift start succeeded before verify was ready.")
4511
+ return 1
4512
+
4513
+ # Every kind of loose end at once.
4514
+ write_text(verify / "scratch.txt", "uncommitted\n")
4515
+ write_text(verify / "pushed-not.txt", "x\n")
4516
+ subprocess.run(["git", "add", "pushed-not.txt"], cwd=verify, check=True)
4517
+ subprocess.run(["git", "commit", "-q", "-m", "local only"], cwd=verify, check=True)
4518
+ write_text(verify / "keel" / "guard.json", "{}\n")
4519
+ temp_tree = Path(tempfile.gettempdir()) / f"keel-shift-tmp-{os.getpid()}"
4520
+ subprocess.run(["git", "worktree", "add", "-q", "--detach", str(temp_tree)], cwd=verify, check=True, capture_output=True)
4521
+ run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "Rerun the regression", env=env)
4522
+ # Its own session, as a job a session leaves behind would be: the check
4523
+ # skips its own command line's process group.
4524
+ sleeper = subprocess.Popen(["sleep", "60"], cwd=verify, start_new_session=True)
4525
+ try:
4526
+ checked = shift(verify, "check", "--json")
4527
+ if checked.returncode != 1:
4528
+ report(f"{label} keel shift check exited {checked.returncode} with loose ends present.")
4529
+ return 1
4530
+ text = checked.stdout
4531
+ for needle in ("scratch.txt", "local only", "guard.json", str(sleeper.pid), temp_tree.name, "Rerun the regression"):
4532
+ if needle not in text:
4533
+ report(f"{label} keel shift check does not name {needle!r}: {text.strip()[:600]}")
4534
+ return 1
4535
+ refused = shift(verify, "ready", "next: rerun R007")
4536
+ if refused.returncode == 0:
4537
+ report(f"{label} keel shift ready succeeded with loose ends present.")
4538
+ return 1
4539
+ if "scratch.txt" not in refused.stdout + refused.stderr:
4540
+ report(f"{label} the refused ready does not name the loose ends: {refused.stderr.strip()}")
4541
+ return 1
4542
+ if (common / "shift" / "verify.md").exists():
4543
+ report(f"{label} a refused ready stored a note.")
4544
+ return 1
4545
+ finally:
4546
+ sleeper.kill()
4547
+ sleeper.wait()
4548
+
4549
+ (verify / "scratch.txt").unlink()
4550
+ (verify / "keel" / "guard.json").unlink()
4551
+ subprocess.run(["git", "push", "-q"], cwd=verify, check=True, capture_output=True)
4552
+ subprocess.run(["git", "worktree", "remove", "--force", str(temp_tree)], cwd=verify, check=True)
4553
+ todo_id = next(r for r in chat_records_with(rtl, "soc", "Rerun the regression"))
4554
+ open_todo = re.search(r"^id: (\S+)", todo_id, re.M).group(1)
4555
+ run_keel(verify, "chat", "done", open_todo, env=env)
4556
+ run_keel(verify, "chat", "read", env=env)
4557
+ clean = shift(verify, "check")
4558
+ if clean.returncode != 0:
4559
+ report(f"{label} keel shift check is not ready on a clean worktree: {clean.stdout.strip()} {clean.stderr.strip()}")
4560
+ return 1
4561
+
4562
+ ready = shift(verify, "ready", "next: rerun R007 on 1b64e8c")
4563
+ if ready.returncode != 0:
4564
+ report(f"{label} keel shift ready failed on a clean worktree: {ready.stderr.strip()}")
4565
+ return 1
4566
+ note = common / "shift" / "verify.md"
4567
+ if not note.exists():
4568
+ report(f"{label} no shift note was stored at {note}.")
4569
+ return 1
4570
+ if "rerun R007 on 1b64e8c" not in note.read_text(encoding="utf-8"):
4571
+ report(f"{label} the stored shift note lacks the text given to ready.")
4572
+ return 1
4573
+ for needle in ("clear_session", "/clear"):
4574
+ if needle not in ready.stdout:
4575
+ report(f"{label} keel shift ready does not say how to clear the session ({needle!r}): {ready.stdout.strip()}")
4576
+ return 1
4577
+ reply = chat_records_with(rtl, "dm-rtl--verify", "done")
4578
+ if not reply:
4579
+ report(f"{label} ready did not reply done to the request.")
4580
+ return 1
4581
+ if "kind: done" not in "".join(chat_records_with(rtl, "dm-rtl--verify", "")):
4582
+ report(f"{label} the shift request was not closed.")
4583
+ return 1
4584
+
4585
+ status = shift(rtl, "status")
4586
+ if "verify: note waiting" not in status.stdout:
4587
+ report(f"{label} keel shift status does not list verify with a waiting note: {status.stdout.strip()}")
4588
+ return 1
4589
+ if "keel shift resume" not in notice():
4590
+ report(f"{label} the session-start notice does not point to the waiting note.")
4591
+ return 1
4592
+
4593
+ size = signal.stat().st_size
4594
+ started = shift(rtl, "start", "verify", "then pick up #157")
4595
+ if started.returncode != 0:
4596
+ report(f"{label} keel shift start failed after ready: {started.stderr.strip()}")
4597
+ return 1
4598
+ if not chat_records_with(rtl, "dm-rtl--verify", "keel shift resume"):
4599
+ report(f"{label} the cold-start message does not name keel shift resume.")
4600
+ return 1
4601
+ if signal.stat().st_size <= size:
4602
+ report(f"{label} the cold-start message did not touch verify's signal file.")
4603
+ return 1
4604
+
4605
+ resumed = shift(verify, "resume")
4606
+ if resumed.returncode != 0:
4607
+ report(f"{label} keel shift resume failed: {resumed.stderr.strip()}")
4608
+ return 1
4609
+ if "rerun R007 on 1b64e8c" not in resumed.stdout:
4610
+ report(f"{label} keel shift resume did not print the note: {resumed.stdout.strip()}")
4611
+ return 1
4612
+ if note.exists():
4613
+ report(f"{label} resume left the note waiting.")
4614
+ return 1
4615
+ if not list((common / "shift" / "history").glob("verify-*.md")):
4616
+ report(f"{label} resume did not keep the note in history.")
4617
+ return 1
4618
+ if not chat_records_with(rtl, "dm-rtl--verify", "on shift"):
4619
+ report(f"{label} resume did not tell the coordinator verify is on shift.")
4620
+ return 1
4621
+ if "keel shift resume" in notice():
4622
+ report(f"{label} the notice still points to a note already resumed.")
4623
+ return 1
4624
+ again = shift(verify, "resume")
4625
+ if "no shift note" not in again.stdout.lower():
4626
+ report(f"{label} a second resume does not say no note waits: {again.stdout.strip()} {again.stderr.strip()}")
4627
+ return 1
4628
+
4629
+ for relative in ("docs/shift-change.md", "docs/shift-change.zh-CN.md"):
4630
+ if not (ROOT / relative).exists():
4631
+ report(f"{label} {relative} is missing.")
4632
+ return 1
4633
+ for readme, guide in (("README.md", "docs/shift-change.md"), ("README.zh-CN.md", "docs/shift-change.zh-CN.md")):
4634
+ if guide not in (ROOT / readme).read_text(encoding="utf-8"):
4635
+ report(f"{label} {readme} does not link {guide}.")
4636
+ return 1
4637
+ if "shift-change" not in {name for name, _ in SCENARIOS}:
4638
+ report(f"{label} scenario is not registered.")
4639
+ return 1
4640
+ report("shift-change scenario passed.")
4641
+ return 0
4642
+
4643
+
4644
+ def validate_shift_without_role_scenario() -> int:
4645
+ """Owner's remark of 2026-10-05: a shift change needs no chat role.
4646
+
4647
+ In a worktree with no `keel chat` role, `ready` keeps the note per
4648
+ worktree, `keel context` and the SessionStart projection point to it
4649
+ without changing the context's status, and `resume` consumes it.
4650
+ """
4651
+ label = "shift-without-role:"
4652
+ with tempfile.TemporaryDirectory(prefix="keel-shift-norole-") as raw:
4653
+ base = Path(raw)
4654
+ repo = mailbox_repository(base / "solo")
4655
+ env = chat_environment()
4656
+ common = mailbox_common_dir(repo) / "keel-chat"
4657
+
4658
+ def context() -> dict:
4659
+ return chat_json(run_keel(repo, "context", "--json", env=env))
4660
+
4661
+ before = context().get("status")
4662
+ ready = run_keel(repo, "shift", "ready", "next: rerun R007", env=env)
4663
+ if ready.returncode != 0:
4664
+ report(f"{label} keel shift ready refused in a worktree without a chat role: {ready.stderr.strip()}")
4665
+ return 1
4666
+ notes = list((common / "shift" / "worktree").glob("*.md"))
4667
+ if len(notes) != 1:
4668
+ report(f"{label} ready kept {len(notes)} worktree notes under keel-chat/shift/worktree/, not one.")
4669
+ return 1
4670
+ text = run_keel(repo, "context", env=env).stdout
4671
+ if "keel shift resume" not in text:
4672
+ report(f"{label} keel context does not point to the waiting note: {text.strip()}")
4673
+ return 1
4674
+ if context().get("status") != before:
4675
+ report(f"{label} the waiting note changed the context status from {before!r} to {context().get('status')!r}.")
4676
+ return 1
4677
+ session = run_session_start_hook(
4678
+ repo, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(repo)},
4679
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
4680
+ )
4681
+ if "keel shift resume" not in (session_start_context(session) or ""):
4682
+ report(f"{label} the SessionStart projection does not point to the waiting note.")
4683
+ return 1
4684
+ resumed = run_keel(repo, "shift", "resume", env=env)
4685
+ if "rerun R007" not in resumed.stdout:
4686
+ report(f"{label} keel shift resume did not print the note: {resumed.stdout.strip()} {resumed.stderr.strip()}")
4687
+ return 1
4688
+ if notes[0].exists():
4689
+ report(f"{label} resume left the worktree note waiting.")
4690
+ return 1
4691
+ if not list((common / "shift" / "history").glob("*.md")):
4692
+ report(f"{label} resume did not keep the note in history.")
4693
+ return 1
4694
+ if "keel shift resume" in run_keel(repo, "context", env=env).stdout:
4695
+ report(f"{label} keel context still points to a note already resumed.")
4696
+ return 1
4697
+
4698
+ for relative, needle in (("docs/shift-change.md", "no chat role"), ("docs/shift-change.zh-CN.md", "不绑定聊天角色")):
4699
+ if needle not in (ROOT / relative).read_text(encoding="utf-8"):
4700
+ report(f"{label} {relative} does not say a chat role is optional ({needle!r}).")
4701
+ return 1
4702
+ if "shift-without-role" not in {name for name, _ in SCENARIOS}:
4703
+ report(f"{label} scenario is not registered.")
4704
+ return 1
4705
+ report("shift-without-role scenario passed.")
4706
+ return 0
4707
+
4708
+
4460
4709
  def validate_chat_archive_scenario() -> int:
4461
4710
  """Issue #187: chat history is archived to an orphan branch, never exposed.
4462
4711
 
@@ -36923,6 +37172,8 @@ SCENARIOS: tuple = (
36923
37172
  ("init-declares-plugin-auto-update", validate_init_declares_plugin_auto_update_scenario),
36924
37173
  ("context-names-the-protocol-refresh", validate_context_names_the_protocol_refresh_scenario),
36925
37174
  ("collected-feedback-is-recorded", validate_collected_feedback_is_recorded_scenario),
37175
+ ("shift-change", validate_shift_change_scenario),
37176
+ ("shift-without-role", validate_shift_without_role_scenario),
36926
37177
  ("init-never-downgrades-openspec", validate_init_never_downgrades_openspec_scenario),
36927
37178
  ("native-plugin-marketplaces", validate_native_plugin_marketplaces_scenario),
36928
37179
  ("native-plugin-install-matrix", validate_native_plugin_install_matrix_scenario),
@@ -715,6 +715,10 @@ function resolveContext(repo, options) {
715
715
 
716
716
  const protocol = protocolRefresh(repo, keelVersion(), authorization);
717
717
  if (protocol) context.protocol = protocol;
718
+ // A note from this worktree's previous shift (shift-without-role D3): a
719
+ // pointer for the new session, which changes no status or selection.
720
+ const shift = require("./shift").waitingFor(repo);
721
+ if (shift) context.shift = shift;
718
722
 
719
723
  // Set here rather than by the caller, so every consumer of the projection —
720
724
  // text, JSON, and any host reading it — carries the version without having
@@ -783,6 +787,10 @@ function protocolRefresh(repo, running, authorization) {
783
787
  };
784
788
  }
785
789
 
790
+ function shiftLine(shift) {
791
+ return `Shift: your previous shift left a note (${shift.since}); run \`keel shift resume\` before anything else`;
792
+ }
793
+
786
794
  function renderProtocol(protocol) {
787
795
  const head = `Protocol: ${protocol.file} is stamped ${protocol.stamped}, older than `
788
796
  + `Keel ${protocol.keel}; refresh with \`${protocol.command}\``;
@@ -859,6 +867,7 @@ function renderContext(result) {
859
867
  );
860
868
  }
861
869
  if (result.protocol) lines.push(renderProtocol(result.protocol));
870
+ if (result.shift) lines.push(shiftLine(result.shift));
862
871
  for (const reason of result.reasons) lines.push(`Reason: ${reason}`);
863
872
  for (const warning of result.warnings) lines.push(`Warning: ${warning}`);
864
873
  return `${lines.join("\n")}\n`;
@@ -0,0 +1,467 @@
1
+ "use strict";
2
+
3
+ // `keel shift`: a coordinated shift change for a role's session (owner's
4
+ // decision of 2026-10-05, shift-change D1-D7). The coordinator requests it,
5
+ // the outgoing session checks for loose ends and leaves a note, clears itself,
6
+ // and the new shift resumes from the note once the coordinator starts it.
7
+ //
8
+ // Each step is a chat record in the direct group between the coordinator and
9
+ // the role, so it wakes the right session and stays reviewable. The note is
10
+ // kept in the chat store, outside every worktree, from `ready` until `resume`:
11
+ // it is transient context for a cold start, never a follow-up owner and never
12
+ // read by `keel context`.
13
+
14
+ const fs = require("fs");
15
+ const os = require("os");
16
+ const path = require("path");
17
+ const { spawnSync } = require("child_process");
18
+ const store = require("./chat/store");
19
+
20
+ const REF = "keel-shift";
21
+ const USAGE = [
22
+ "keel shift request <role> [text] ask a role to change shift (wakes it)",
23
+ "keel shift check [--json] readiness check of this worktree; exit 1 if anything is loose",
24
+ "keel shift ready [text | --file f] store the shift note, close the request (refused while loose)",
25
+ " [--force-reason r] ...or state why the loose ends may stay",
26
+ "keel shift start <role> [text] wake the cleared role to resume (once its note waits)",
27
+ "keel shift resume [--json] print and consume this role's note",
28
+ "keel shift status [--json] each role's shift state",
29
+ "Options: --repo <path>. See docs/shift-change.md.",
30
+ ].join("\n");
31
+
32
+ class ShiftError extends Error {}
33
+
34
+ function git(cwd, args) {
35
+ const result = spawnSync("git", args, { cwd, encoding: "utf8" });
36
+ return { ok: result.status === 0, out: String(result.stdout || "").replace(/\s+$/, "") };
37
+ }
38
+
39
+ function realpath(file) {
40
+ try {
41
+ return fs.realpathSync(file);
42
+ } catch {
43
+ return path.resolve(file);
44
+ }
45
+ }
46
+
47
+ function inside(child, parent) {
48
+ return child === parent || child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep);
49
+ }
50
+
51
+ function shiftDir(where) {
52
+ return path.join(where.root, "shift");
53
+ }
54
+
55
+ function notePath(where, role) {
56
+ return path.join(shiftDir(where), `${role}.md`);
57
+ }
58
+
59
+ // A worktree with no chat role keeps its note per worktree (shift-without-role
60
+ // D1): its directory name for a reader, a hash of its path for uniqueness.
61
+ function worktreeNotePath(where) {
62
+ const id = require("crypto").createHash("sha256").update(where.worktree).digest("hex").slice(0, 8);
63
+ return path.join(shiftDir(where), "worktree", `${path.basename(where.worktree)}-${id}.md`);
64
+ }
65
+
66
+ // Where this worktree's note is written: the role's when it has one.
67
+ function ownNotePath(where, role) {
68
+ return role ? notePath(where, role) : worktreeNotePath(where);
69
+ }
70
+
71
+ // The note waiting for this worktree: its role's first, then its own.
72
+ function waitingNote(where, role) {
73
+ for (const file of [role ? notePath(where, role) : null, worktreeNotePath(where)]) {
74
+ if (file && fs.existsSync(file)) return file;
75
+ }
76
+ return null;
77
+ }
78
+
79
+ function writeFileAtomic(file, content) {
80
+ fs.mkdirSync(path.dirname(file), { recursive: true });
81
+ const temp = `${file}.${process.pid}.tmp`;
82
+ fs.writeFileSync(temp, content);
83
+ fs.renameSync(temp, file);
84
+ }
85
+
86
+ function isShift(record) {
87
+ return (record.refs || []).includes(REF);
88
+ }
89
+
90
+ // --- the readiness check (D4) ------------------------------------------------------
91
+
92
+ // Every process: pid, parent, elapsed time, command.
93
+ function processTable() {
94
+ const result = spawnSync("ps", ["-axo", "pid=,ppid=,pgid=,etime=,command="], { encoding: "utf8" });
95
+ const table = new Map();
96
+ for (const line of String(result.stdout || "").split("\n")) {
97
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
98
+ if (match) table.set(Number(match[1]), { pid: Number(match[1]), ppid: Number(match[2]), pgid: Number(match[3]), elapsed: match[4], command: match[5] });
99
+ }
100
+ return table;
101
+ }
102
+
103
+ // The working directory of every process: /proc where the system has it,
104
+ // lsof otherwise.
105
+ function processDirectories() {
106
+ const result = new Map();
107
+ if (fs.existsSync("/proc/self/cwd")) {
108
+ for (const entry of fs.readdirSync("/proc")) {
109
+ if (!/^\d+$/.test(entry)) continue;
110
+ try {
111
+ result.set(Number(entry), fs.readlinkSync(path.join("/proc", entry, "cwd")));
112
+ } catch {
113
+ // Gone, or not ours to read.
114
+ }
115
+ }
116
+ return result;
117
+ }
118
+ const listed = spawnSync("lsof", ["-a", "-d", "cwd", "-F", "pn"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
119
+ let pid = null;
120
+ for (const line of String(listed.stdout || "").split("\n")) {
121
+ if (line.startsWith("p")) pid = Number(line.slice(1));
122
+ else if (line.startsWith("n") && pid !== null) result.set(pid, line.slice(1));
123
+ }
124
+ return result;
125
+ }
126
+
127
+ // An interactive shell open in the worktree, such as a terminal tab, is not
128
+ // work in progress; what it runs is, and is listed by its own entry.
129
+ const IDLE_SHELL = /^-?(?:\S*\/)?(?:zsh|bash|sh|dash|fish)(?:\s+-[il]+)*\s*$/;
130
+
131
+ function liveProcesses(worktree) {
132
+ const table = processTable();
133
+ // The checking process and its ancestors are the session doing the check,
134
+ // and its process group is the command line it runs in (`… | head`).
135
+ const own = new Set();
136
+ for (let pid = process.pid; pid && !own.has(pid); pid = (table.get(pid) || {}).ppid) own.add(pid);
137
+ const group = (table.get(process.pid) || {}).pgid;
138
+ const found = [];
139
+ for (const [pid, cwd] of processDirectories()) {
140
+ if (own.has(pid) || !inside(realpath(cwd), worktree)) continue;
141
+ const row = table.get(pid);
142
+ if (!row || row.pgid === group || IDLE_SHELL.test(row.command)) continue;
143
+ found.push(row);
144
+ }
145
+ return found.sort((a, b) => a.pid - b.pid);
146
+ }
147
+
148
+ function temporaryRoots() {
149
+ return [...new Set([os.tmpdir(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"].map(realpath))];
150
+ }
151
+
152
+ function temporaryWorktrees(where) {
153
+ const listed = git(where.worktree, ["worktree", "list", "--porcelain"]);
154
+ if (!listed.ok) return [];
155
+ const trees = listed.out.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => realpath(line.slice(9)));
156
+ const main = trees[0];
157
+ const roots = temporaryRoots();
158
+ return trees.filter((tree) => tree !== main && tree !== where.worktree && roots.some((root) => inside(tree, root)));
159
+ }
160
+
161
+ function check(where, role) {
162
+ const items = [];
163
+ const notes = [];
164
+ const status = git(where.worktree, ["status", "--porcelain"]);
165
+ for (const line of status.out.split("\n").filter(Boolean)) items.push({ kind: "uncommitted", detail: line.trim() });
166
+
167
+ const remotes = git(where.worktree, ["remote"]).out.split("\n").filter(Boolean);
168
+ if (!remotes.length) {
169
+ notes.push("this repository has no remote, so unpushed commits were not checked");
170
+ } else {
171
+ const local = git(where.worktree, ["log", "--format=%h %s", "-n", "20", "HEAD", "--not", "--remotes"]);
172
+ for (const line of local.out.split("\n").filter(Boolean)) items.push({ kind: "unpushed", detail: line });
173
+ }
174
+
175
+ if (fs.existsSync(path.join(where.worktree, "keel", "guard.json"))) {
176
+ items.push({ kind: "task-in-progress", detail: "keel/guard.json: a task's write guard is still active; complete the task or clear the guard" });
177
+ }
178
+
179
+ for (const row of liveProcesses(where.worktree)) {
180
+ items.push({ kind: "process", detail: `PID ${row.pid}, running ${row.elapsed}: ${row.command}` });
181
+ }
182
+
183
+ for (const tree of temporaryWorktrees(where)) items.push({ kind: "temporary-worktree", detail: tree });
184
+
185
+ if (role) {
186
+ for (const todo of store.openTodos(where, { assignee: role })) {
187
+ if (isShift(todo)) continue;
188
+ items.push({ kind: "open-todo", detail: `${todo.id} in ${todo.group}: ${firstLine(todo.text)}` });
189
+ }
190
+ for (const record of store.unread(where, role)) {
191
+ if (isShift(record) || !store.wakes(record, role)) continue;
192
+ if (record.kind === "todo" && record.assignee === role) continue;
193
+ items.push({ kind: "unread", detail: `${record.id} in ${record.group} from ${record.from}: ${firstLine(record.text)}` });
194
+ }
195
+ } else {
196
+ notes.push("this worktree has no chat role, so its chat was not checked");
197
+ }
198
+ return { ready: items.length === 0, worktree: where.worktree, role: role || null, items, notes };
199
+ }
200
+
201
+ function firstLine(text) {
202
+ const line = String(text || "").split("\n")[0];
203
+ return line.length > 100 ? `${line.slice(0, 100)}…` : line;
204
+ }
205
+
206
+ function renderCheck(result) {
207
+ const lines = [`keel shift check: ${result.ready ? "ready" : "not ready"} (${result.worktree}${result.role ? `, role ${result.role}` : ""})`];
208
+ for (const item of result.items) lines.push(`- ${item.kind}: ${item.detail}`);
209
+ for (const note of result.notes) lines.push(`note: ${note}`);
210
+ return lines.join("\n");
211
+ }
212
+
213
+ // --- the steps ---------------------------------------------------------------------
214
+
215
+ function requireRole(where) {
216
+ return store.requireRole(where);
217
+ }
218
+
219
+ function directGroup(where, from, role) {
220
+ const group = store.directName(from, role);
221
+ if (!store.groupState(store.readLog(where, group)).exists) {
222
+ store.createGroup(where, from, group, [role], { direct: true });
223
+ }
224
+ return group;
225
+ }
226
+
227
+ function shiftRequests(where, role = null) {
228
+ const requests = [];
229
+ for (const name of store.listGroupNames(where)) {
230
+ const records = store.readLog(where, name);
231
+ const closed = new Set(records.filter((r) => r.kind === "done").map((r) => r.target));
232
+ for (const record of records) {
233
+ if (record.kind !== "todo" || !isShift(record)) continue;
234
+ if (role && record.assignee !== role) continue;
235
+ requests.push({ ...record, open: !closed.has(record.id) });
236
+ }
237
+ }
238
+ return requests.sort((a, b) => (a.id < b.id ? -1 : 1));
239
+ }
240
+
241
+ function request(where, role, text) {
242
+ const from = requireRole(where);
243
+ store.checkName(role, "Role");
244
+ if (role === from) throw new ShiftError("A shift change is requested of another role, not your own.");
245
+ const group = directGroup(where, from, role);
246
+ const body = [
247
+ `Shift change requested by ${from}. Wrap up, then hand over:`,
248
+ "1. `keel shift check` until it reports ready (or decide what may stay).",
249
+ "2. Put follow-ups where the project tracks them, and update long-lived memory you own.",
250
+ "3. `keel shift ready \"<what you were doing, next step, what you wait on, where>\"`.",
251
+ "4. Clear this session as `keel shift ready` says.",
252
+ text ? `\n${text}` : "",
253
+ ].join("\n").trim();
254
+ return store.todo(where, { group, assignee: role, text: body, refs: [REF] });
255
+ }
256
+
257
+ function readNoteText(options) {
258
+ if (options.file) return fs.readFileSync(options.file, "utf8");
259
+ if (options.text) return options.text;
260
+ if (!process.stdin.isTTY) {
261
+ try {
262
+ return fs.readFileSync(0, "utf8");
263
+ } catch {
264
+ return "";
265
+ }
266
+ }
267
+ return "";
268
+ }
269
+
270
+ function ready(where, options) {
271
+ const role = store.currentRole(where);
272
+ const result = check(where, role);
273
+ if (!result.ready && !options.forceReason) {
274
+ throw new ShiftError(`${renderCheck(result)}\nResolve these, or give --force-reason "<why they may stay>".`);
275
+ }
276
+ const text = readNoteText(options).replace(/\s+$/, "");
277
+ if (!text.trim()) throw new ShiftError("keel shift ready needs the shift note: give it as text, with --file, or on stdin.");
278
+ const stamp = store.isoLocal(new Date());
279
+ const head = [
280
+ `# Shift note: ${role || path.basename(where.worktree)}`,
281
+ "",
282
+ `Written ${stamp} in ${result.worktree}.`,
283
+ options.forceReason ? `\nLeft as is (${options.forceReason}):\n${result.items.map((item) => `- ${item.kind}: ${item.detail}`).join("\n")}` : "",
284
+ "",
285
+ ].join("\n");
286
+ const note = ownNotePath(where, role);
287
+ writeFileAtomic(note, `${head}\n${text}\n`);
288
+ // Requests are chat records; without a role there is none to close (D2).
289
+ const open = role ? shiftRequests(where, role).filter((r) => r.open) : [];
290
+ for (const todo of open) {
291
+ store.post(where, {
292
+ group: todo.group,
293
+ replyTo: todo.id,
294
+ refs: [REF],
295
+ text: `done — ${role} is ready for the shift change; the note waits for \`keel shift resume\`.${options.forceReason ? ` Left as is: ${options.forceReason}.` : ""}`,
296
+ });
297
+ }
298
+ return { role: role || null, note, closed: open.map((todo) => todo.id) };
299
+ }
300
+
301
+ function start(where, role, text) {
302
+ const from = requireRole(where);
303
+ store.checkName(role, "Role");
304
+ if (!fs.existsSync(notePath(where, role))) {
305
+ throw new ShiftError(`No shift note waits for ${role}: it has not run \`keel shift ready\`, or already resumed.`);
306
+ }
307
+ const group = directGroup(where, from, role);
308
+ const body = [
309
+ `${role}: your new shift starts now. First run \`keel context\`, then \`keel shift resume\` to read the note your previous shift left, then continue from it.`,
310
+ text ? `Next: ${text}` : "",
311
+ ].filter(Boolean).join("\n");
312
+ return store.post(where, { group, text: body, refs: [REF] });
313
+ }
314
+
315
+ function resume(where) {
316
+ const role = store.currentRole(where);
317
+ const note = waitingNote(where, role);
318
+ if (!note) return { role: role || null, note: null, text: null };
319
+ const text = fs.readFileSync(note, "utf8");
320
+ const stamp = store.isoLocal(new Date()).replace(/[:+]/g, "");
321
+ const history = path.join(shiftDir(where), "history", `${role || path.basename(note, ".md")}-${stamp}.md`);
322
+ fs.mkdirSync(path.dirname(history), { recursive: true });
323
+ fs.renameSync(note, history);
324
+ if (!role) return { role: null, note: history, text, told: null };
325
+ // The cold-start message has done its work once the note is read.
326
+ for (const record of store.unread(where, role)) {
327
+ if (isShift(record)) store.advanceCursor(where, role, record.group, record.id);
328
+ }
329
+ const latest = shiftRequests(where, role).pop();
330
+ let told = null;
331
+ if (latest && latest.from !== role) {
332
+ const group = directGroup(where, role, latest.from);
333
+ told = store.post(where, { group, text: `${role} is on shift, resumed from its shift note.`, refs: [REF] }).id;
334
+ }
335
+ return { role, note: history, text, told };
336
+ }
337
+
338
+ function status(where) {
339
+ const roles = new Map();
340
+ const entry = (role) => {
341
+ if (!roles.has(role)) roles.set(role, { role, request: null, note: null, resumed: null });
342
+ return roles.get(role);
343
+ };
344
+ for (const todo of shiftRequests(where)) {
345
+ entry(todo.assignee).request = { id: todo.id, from: todo.from, created: todo.created, open: todo.open };
346
+ }
347
+ const dir = shiftDir(where);
348
+ for (const [folder, prefix] of [[dir, ""], [path.join(dir, "worktree"), "worktree "]]) {
349
+ for (const file of safeList(folder)) {
350
+ if (!file.endsWith(".md")) continue;
351
+ const stat = fs.statSync(path.join(folder, file));
352
+ entry(`${prefix}${file.slice(0, -3)}`).note = store.isoLocal(stat.mtime);
353
+ }
354
+ }
355
+ for (const file of safeList(path.join(dir, "history"))) {
356
+ const match = file.match(/^(.+)-(\d{4}-\d{2}-\d{2}T\d+)\.md$/);
357
+ if (!match) continue;
358
+ const role = entry(match[1]);
359
+ if (!role.resumed || role.resumed < match[2]) role.resumed = match[2];
360
+ }
361
+ return [...roles.values()].sort((a, b) => (a.role < b.role ? -1 : 1));
362
+ }
363
+
364
+ function safeList(dir) {
365
+ try {
366
+ return fs.readdirSync(dir);
367
+ } catch {
368
+ return [];
369
+ }
370
+ }
371
+
372
+ function describe(row) {
373
+ if (row.note) return `${row.role}: note waiting since ${row.note}; \`keel shift start ${row.role}\` wakes it to resume`;
374
+ if (row.request && row.request.open) return `${row.role}: change requested by ${row.request.from} at ${row.request.created}; not ready yet`;
375
+ if (row.resumed) return `${row.role}: on shift, resumed ${row.resumed}`;
376
+ return `${row.role}: ready was recorded without a note`;
377
+ }
378
+
379
+ // --- the command line --------------------------------------------------------------
380
+
381
+ const CLEAR_HINT = [
382
+ "Now clear this session:",
383
+ "- Claude desktop app: call `clear_session(\"self\")` (the owner approves it), or type /clear;",
384
+ "- Claude Code CLI: /clear;",
385
+ "- Codex: start a new session in this worktree.",
386
+ "The coordinator's `keel shift start` then wakes the new shift; without chat roles, tell the new session to run `keel shift resume`.",
387
+ ].join("\n");
388
+
389
+ function runShift(argv) {
390
+ const options = { json: false, repo: process.cwd(), positionals: [], file: null, forceReason: null };
391
+ for (let index = 0; index < argv.length; index += 1) {
392
+ const arg = argv[index];
393
+ if (arg === "--json") options.json = true;
394
+ else if (arg === "--repo") options.repo = argv[++index] || "";
395
+ else if (arg === "--file") options.file = argv[++index] || "";
396
+ else if (arg === "--force-reason") options.forceReason = argv[++index] || "";
397
+ else if (arg === "--help" || arg === "-h") {
398
+ process.stdout.write(`${USAGE}\n`);
399
+ return 0;
400
+ } else options.positionals.push(arg);
401
+ }
402
+ const [action, ...rest] = options.positionals;
403
+ const out = (value, text) => process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : text}\n`);
404
+ try {
405
+ const where = store.requireLocation(options.repo);
406
+ switch (action) {
407
+ case "request": {
408
+ if (!rest[0]) throw new ShiftError("keel shift request needs the role.");
409
+ const record = request(where, rest[0], rest.slice(1).join(" "));
410
+ out({ id: record.id, group: record.group, role: rest[0] }, `Asked ${rest[0]} to change shift (${record.id} in ${record.group}).`);
411
+ return 0;
412
+ }
413
+ case "check": {
414
+ const result = check(where, store.currentRole(where));
415
+ out(result, renderCheck(result));
416
+ return result.ready ? 0 : 1;
417
+ }
418
+ case "ready": {
419
+ const result = ready(where, { ...options, text: rest.join(" ") });
420
+ const whose = result.role || "this worktree (no chat role, so no request to close)";
421
+ out({ ...result, clear: CLEAR_HINT }, `Stored the shift note for ${whose} at ${result.note}${result.closed.length ? ` and closed ${result.closed.join(", ")}` : ""}.\n${CLEAR_HINT}`);
422
+ return 0;
423
+ }
424
+ case "start": {
425
+ if (!rest[0]) throw new ShiftError("keel shift start needs the role.");
426
+ const record = start(where, rest[0], rest.slice(1).join(" "));
427
+ out({ id: record.id, group: record.group, role: rest[0] }, `Woke ${rest[0]} to start its new shift (${record.id} in ${record.group}).`);
428
+ return 0;
429
+ }
430
+ case "resume": {
431
+ const result = resume(where);
432
+ if (!result.note) {
433
+ out(result, `No shift note waits for ${result.role || "this worktree"}.`);
434
+ return 0;
435
+ }
436
+ out(result, `${result.text.replace(/\s+$/, "")}\n\n(The note moved to ${result.note}.)`);
437
+ return 0;
438
+ }
439
+ case "status": {
440
+ const rows = status(where);
441
+ out({ roles: rows }, rows.length ? rows.map(describe).join("\n") : "No shift change recorded.");
442
+ return 0;
443
+ }
444
+ default:
445
+ process.stderr.write(`${action ? `keel shift: unknown step ${action}\n` : ""}${USAGE}\n`);
446
+ return 2;
447
+ }
448
+ } catch (error) {
449
+ if (error instanceof ShiftError || error instanceof store.ChatError) {
450
+ process.stderr.write(`keel shift: ${error.message}\n`);
451
+ return 1;
452
+ }
453
+ throw error;
454
+ }
455
+ }
456
+
457
+ // The waiting note for a repository path, for `keel context` (D3); null when
458
+ // none waits or the path is not a repository.
459
+ function waitingFor(repo) {
460
+ const where = store.locate(repo);
461
+ if (!where) return null;
462
+ const note = waitingNote(where, store.currentRole(where));
463
+ if (!note) return null;
464
+ return { note, since: store.isoLocal(fs.statSync(note).mtime) };
465
+ }
466
+
467
+ module.exports = { check, runShift, waitingFor };