@christang/keel 5.97.0 → 5.98.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.98.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.98.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.98.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.98.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.98.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.98.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.97.0"
51
- PROTOCOL_VERSION = "5.97.0"
50
+ PACKAGE_VERSION = "5.98.0"
51
+ PROTOCOL_VERSION = "5.98.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,189 @@ 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
+ session = subprocess.run(
4485
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/mail-hook.js"), "session-start"],
4486
+ cwd=verify, env={**env, "KEEL_CLI": f'node "{ROOT / "bin" / "keel.js"}"'},
4487
+ text=True, capture_output=True, check=False,
4488
+ input=json.dumps({"hook_event_name": "SessionStart", "cwd": str(verify)}),
4489
+ )
4490
+ return chat_json(session).get("hookSpecificOutput", {}).get("additionalContext", "")
4491
+
4492
+ size = signal.stat().st_size if signal.exists() else 0
4493
+ requested = shift(rtl, "request", "verify")
4494
+ if requested.returncode != 0:
4495
+ report(f"{label} keel shift request failed: {requested.stderr.strip()}")
4496
+ return 1
4497
+ request = [r for r in chat_records_with(rtl, "dm-rtl--verify", "shift") if "kind: todo" in r and "keel-shift" in r]
4498
+ if not request:
4499
+ report(f"{label} no keel-shift todo reached dm-rtl--verify: {requested.stdout.strip()}")
4500
+ return 1
4501
+ if "assignee: verify" not in request[0]:
4502
+ report(f"{label} the shift request is not assigned to verify:\n{request[0]}")
4503
+ return 1
4504
+ if not signal.exists():
4505
+ report(f"{label} the request created no signal file for verify.")
4506
+ return 1
4507
+ if signal.stat().st_size <= size:
4508
+ report(f"{label} the request did not touch verify's signal file.")
4509
+ return 1
4510
+ if shift(rtl, "start", "verify").returncode == 0:
4511
+ report(f"{label} keel shift start succeeded before verify was ready.")
4512
+ return 1
4513
+
4514
+ # Every kind of loose end at once.
4515
+ write_text(verify / "scratch.txt", "uncommitted\n")
4516
+ write_text(verify / "pushed-not.txt", "x\n")
4517
+ subprocess.run(["git", "add", "pushed-not.txt"], cwd=verify, check=True)
4518
+ subprocess.run(["git", "commit", "-q", "-m", "local only"], cwd=verify, check=True)
4519
+ write_text(verify / "keel" / "guard.json", "{}\n")
4520
+ temp_tree = Path(tempfile.gettempdir()) / f"keel-shift-tmp-{os.getpid()}"
4521
+ subprocess.run(["git", "worktree", "add", "-q", "--detach", str(temp_tree)], cwd=verify, check=True, capture_output=True)
4522
+ run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "Rerun the regression", env=env)
4523
+ sleeper = subprocess.Popen(["sleep", "60"], cwd=verify)
4524
+ try:
4525
+ checked = shift(verify, "check", "--json")
4526
+ if checked.returncode != 1:
4527
+ report(f"{label} keel shift check exited {checked.returncode} with loose ends present.")
4528
+ return 1
4529
+ text = checked.stdout
4530
+ for needle in ("scratch.txt", "local only", "guard.json", str(sleeper.pid), temp_tree.name, "Rerun the regression"):
4531
+ if needle not in text:
4532
+ report(f"{label} keel shift check does not name {needle!r}: {text.strip()[:600]}")
4533
+ return 1
4534
+ refused = shift(verify, "ready", "next: rerun R007")
4535
+ if refused.returncode == 0:
4536
+ report(f"{label} keel shift ready succeeded with loose ends present.")
4537
+ return 1
4538
+ if "scratch.txt" not in refused.stdout + refused.stderr:
4539
+ report(f"{label} the refused ready does not name the loose ends: {refused.stderr.strip()}")
4540
+ return 1
4541
+ if (common / "shift" / "verify.md").exists():
4542
+ report(f"{label} a refused ready stored a note.")
4543
+ return 1
4544
+ finally:
4545
+ sleeper.kill()
4546
+ sleeper.wait()
4547
+
4548
+ (verify / "scratch.txt").unlink()
4549
+ (verify / "keel" / "guard.json").unlink()
4550
+ subprocess.run(["git", "push", "-q"], cwd=verify, check=True, capture_output=True)
4551
+ subprocess.run(["git", "worktree", "remove", "--force", str(temp_tree)], cwd=verify, check=True)
4552
+ todo_id = next(r for r in chat_records_with(rtl, "soc", "Rerun the regression"))
4553
+ open_todo = re.search(r"^id: (\S+)", todo_id, re.M).group(1)
4554
+ run_keel(verify, "chat", "done", open_todo, env=env)
4555
+ run_keel(verify, "chat", "read", env=env)
4556
+ clean = shift(verify, "check")
4557
+ if clean.returncode != 0:
4558
+ report(f"{label} keel shift check is not ready on a clean worktree: {clean.stdout.strip()} {clean.stderr.strip()}")
4559
+ return 1
4560
+
4561
+ ready = shift(verify, "ready", "next: rerun R007 on 1b64e8c")
4562
+ if ready.returncode != 0:
4563
+ report(f"{label} keel shift ready failed on a clean worktree: {ready.stderr.strip()}")
4564
+ return 1
4565
+ note = common / "shift" / "verify.md"
4566
+ if not note.exists():
4567
+ report(f"{label} no shift note was stored at {note}.")
4568
+ return 1
4569
+ if "rerun R007 on 1b64e8c" not in note.read_text(encoding="utf-8"):
4570
+ report(f"{label} the stored shift note lacks the text given to ready.")
4571
+ return 1
4572
+ for needle in ("clear_session", "/clear"):
4573
+ if needle not in ready.stdout:
4574
+ report(f"{label} keel shift ready does not say how to clear the session ({needle!r}): {ready.stdout.strip()}")
4575
+ return 1
4576
+ reply = chat_records_with(rtl, "dm-rtl--verify", "done")
4577
+ if not reply:
4578
+ report(f"{label} ready did not reply done to the request.")
4579
+ return 1
4580
+ if "kind: done" not in "".join(chat_records_with(rtl, "dm-rtl--verify", "")):
4581
+ report(f"{label} the shift request was not closed.")
4582
+ return 1
4583
+
4584
+ status = shift(rtl, "status")
4585
+ if "verify: note waiting" not in status.stdout:
4586
+ report(f"{label} keel shift status does not list verify with a waiting note: {status.stdout.strip()}")
4587
+ return 1
4588
+ if "keel shift resume" not in notice():
4589
+ report(f"{label} the session-start notice does not point to the waiting note.")
4590
+ return 1
4591
+
4592
+ size = signal.stat().st_size
4593
+ started = shift(rtl, "start", "verify", "then pick up #157")
4594
+ if started.returncode != 0:
4595
+ report(f"{label} keel shift start failed after ready: {started.stderr.strip()}")
4596
+ return 1
4597
+ if not chat_records_with(rtl, "dm-rtl--verify", "keel shift resume"):
4598
+ report(f"{label} the cold-start message does not name keel shift resume.")
4599
+ return 1
4600
+ if signal.stat().st_size <= size:
4601
+ report(f"{label} the cold-start message did not touch verify's signal file.")
4602
+ return 1
4603
+
4604
+ resumed = shift(verify, "resume")
4605
+ if resumed.returncode != 0:
4606
+ report(f"{label} keel shift resume failed: {resumed.stderr.strip()}")
4607
+ return 1
4608
+ if "rerun R007 on 1b64e8c" not in resumed.stdout:
4609
+ report(f"{label} keel shift resume did not print the note: {resumed.stdout.strip()}")
4610
+ return 1
4611
+ if note.exists():
4612
+ report(f"{label} resume left the note waiting.")
4613
+ return 1
4614
+ if not list((common / "shift" / "history").glob("verify-*.md")):
4615
+ report(f"{label} resume did not keep the note in history.")
4616
+ return 1
4617
+ if not chat_records_with(rtl, "dm-rtl--verify", "on shift"):
4618
+ report(f"{label} resume did not tell the coordinator verify is on shift.")
4619
+ return 1
4620
+ if "keel shift resume" in notice():
4621
+ report(f"{label} the notice still points to a note already resumed.")
4622
+ return 1
4623
+ again = shift(verify, "resume")
4624
+ if "no shift note" not in again.stdout.lower():
4625
+ report(f"{label} a second resume does not say no note waits: {again.stdout.strip()} {again.stderr.strip()}")
4626
+ return 1
4627
+
4628
+ for relative in ("docs/shift-change.md", "docs/shift-change.zh-CN.md"):
4629
+ if not (ROOT / relative).exists():
4630
+ report(f"{label} {relative} is missing.")
4631
+ return 1
4632
+ for readme, guide in (("README.md", "docs/shift-change.md"), ("README.zh-CN.md", "docs/shift-change.zh-CN.md")):
4633
+ if guide not in (ROOT / readme).read_text(encoding="utf-8"):
4634
+ report(f"{label} {readme} does not link {guide}.")
4635
+ return 1
4636
+ if "shift-change" not in {name for name, _ in SCENARIOS}:
4637
+ report(f"{label} scenario is not registered.")
4638
+ return 1
4639
+ report("shift-change scenario passed.")
4640
+ return 0
4641
+
4642
+
4460
4643
  def validate_chat_archive_scenario() -> int:
4461
4644
  """Issue #187: chat history is archived to an orphan branch, never exposed.
4462
4645
 
@@ -36923,6 +37106,7 @@ SCENARIOS: tuple = (
36923
37106
  ("init-declares-plugin-auto-update", validate_init_declares_plugin_auto_update_scenario),
36924
37107
  ("context-names-the-protocol-refresh", validate_context_names_the_protocol_refresh_scenario),
36925
37108
  ("collected-feedback-is-recorded", validate_collected_feedback_is_recorded_scenario),
37109
+ ("shift-change", validate_shift_change_scenario),
36926
37110
  ("init-never-downgrades-openspec", validate_init_never_downgrades_openspec_scenario),
36927
37111
  ("native-plugin-marketplaces", validate_native_plugin_marketplaces_scenario),
36928
37112
  ("native-plugin-install-matrix", validate_native_plugin_install_matrix_scenario),
@@ -151,6 +151,14 @@ const OWNER_RULE = "Slack notifies the owner only for messages that write `@owne
151
151
  + "needs to see or decide on, and leave it out of routine discussion. Send a risk or decision as its own message "
152
152
  + "with `@owner` rather than inside a status update.";
153
153
 
154
+ // A shift note waiting for this role (shift-change D7): the new shift reads it
155
+ // before anything else.
156
+ function shiftLine(where, role) {
157
+ const since = require("../shift").pendingNote(where, role);
158
+ if (!since) return null;
159
+ return `keel shift: your previous shift left a note (${since}); run \`keel context\`, then \`keel shift resume\`, before anything else.`;
160
+ }
161
+
154
162
  const HOST_EVENTS = {
155
163
  "session-start": "SessionStart",
156
164
  "user-prompt-submit": "UserPromptSubmit",
@@ -198,7 +206,7 @@ function hook(event, input, { mail = false } = {}) {
198
206
  const output = {
199
207
  hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [ensureSignal(where, role), ensureWorktreeSignal(where)] },
200
208
  };
201
- const context = [bridgeLine(where), text].filter(Boolean).join("\n");
209
+ const context = [bridgeLine(where), shiftLine(where, role), text].filter(Boolean).join("\n");
202
210
  if (context) output.hookSpecificOutput.additionalContext = context;
203
211
  return { code: 0, stdout: `${JSON.stringify(output)}\n` };
204
212
  }
@@ -0,0 +1,435 @@
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
+ function writeFileAtomic(file, content) {
60
+ fs.mkdirSync(path.dirname(file), { recursive: true });
61
+ const temp = `${file}.${process.pid}.tmp`;
62
+ fs.writeFileSync(temp, content);
63
+ fs.renameSync(temp, file);
64
+ }
65
+
66
+ function isShift(record) {
67
+ return (record.refs || []).includes(REF);
68
+ }
69
+
70
+ // --- the readiness check (D4) ------------------------------------------------------
71
+
72
+ // Every process: pid, parent, elapsed time, command.
73
+ function processTable() {
74
+ const result = spawnSync("ps", ["-axo", "pid=,ppid=,etime=,command="], { encoding: "utf8" });
75
+ const table = new Map();
76
+ for (const line of String(result.stdout || "").split("\n")) {
77
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
78
+ if (match) table.set(Number(match[1]), { pid: Number(match[1]), ppid: Number(match[2]), elapsed: match[3], command: match[4] });
79
+ }
80
+ return table;
81
+ }
82
+
83
+ // The working directory of every process: /proc where the system has it,
84
+ // lsof otherwise.
85
+ function processDirectories() {
86
+ const result = new Map();
87
+ if (fs.existsSync("/proc/self/cwd")) {
88
+ for (const entry of fs.readdirSync("/proc")) {
89
+ if (!/^\d+$/.test(entry)) continue;
90
+ try {
91
+ result.set(Number(entry), fs.readlinkSync(path.join("/proc", entry, "cwd")));
92
+ } catch {
93
+ // Gone, or not ours to read.
94
+ }
95
+ }
96
+ return result;
97
+ }
98
+ const listed = spawnSync("lsof", ["-a", "-d", "cwd", "-F", "pn"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
99
+ let pid = null;
100
+ for (const line of String(listed.stdout || "").split("\n")) {
101
+ if (line.startsWith("p")) pid = Number(line.slice(1));
102
+ else if (line.startsWith("n") && pid !== null) result.set(pid, line.slice(1));
103
+ }
104
+ return result;
105
+ }
106
+
107
+ // An interactive shell open in the worktree, such as a terminal tab, is not
108
+ // work in progress; what it runs is, and is listed by its own entry.
109
+ const IDLE_SHELL = /^-?(?:\S*\/)?(?:zsh|bash|sh|dash|fish)(?:\s+-[il]+)*\s*$/;
110
+
111
+ function liveProcesses(worktree) {
112
+ const table = processTable();
113
+ // The checking process and its ancestors are the session doing the check.
114
+ const own = new Set();
115
+ for (let pid = process.pid; pid && !own.has(pid); pid = (table.get(pid) || {}).ppid) own.add(pid);
116
+ const found = [];
117
+ for (const [pid, cwd] of processDirectories()) {
118
+ if (own.has(pid) || !inside(realpath(cwd), worktree)) continue;
119
+ const row = table.get(pid);
120
+ if (!row || IDLE_SHELL.test(row.command)) continue;
121
+ found.push(row);
122
+ }
123
+ return found.sort((a, b) => a.pid - b.pid);
124
+ }
125
+
126
+ function temporaryRoots() {
127
+ return [...new Set([os.tmpdir(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"].map(realpath))];
128
+ }
129
+
130
+ function temporaryWorktrees(where) {
131
+ const listed = git(where.worktree, ["worktree", "list", "--porcelain"]);
132
+ if (!listed.ok) return [];
133
+ const trees = listed.out.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => realpath(line.slice(9)));
134
+ const main = trees[0];
135
+ const roots = temporaryRoots();
136
+ return trees.filter((tree) => tree !== main && tree !== where.worktree && roots.some((root) => inside(tree, root)));
137
+ }
138
+
139
+ function check(where, role) {
140
+ const items = [];
141
+ const notes = [];
142
+ const status = git(where.worktree, ["status", "--porcelain"]);
143
+ for (const line of status.out.split("\n").filter(Boolean)) items.push({ kind: "uncommitted", detail: line.trim() });
144
+
145
+ const remotes = git(where.worktree, ["remote"]).out.split("\n").filter(Boolean);
146
+ if (!remotes.length) {
147
+ notes.push("this repository has no remote, so unpushed commits were not checked");
148
+ } else {
149
+ const local = git(where.worktree, ["log", "--format=%h %s", "-n", "20", "HEAD", "--not", "--remotes"]);
150
+ for (const line of local.out.split("\n").filter(Boolean)) items.push({ kind: "unpushed", detail: line });
151
+ }
152
+
153
+ if (fs.existsSync(path.join(where.worktree, "keel", "guard.json"))) {
154
+ 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" });
155
+ }
156
+
157
+ for (const row of liveProcesses(where.worktree)) {
158
+ items.push({ kind: "process", detail: `PID ${row.pid}, running ${row.elapsed}: ${row.command}` });
159
+ }
160
+
161
+ for (const tree of temporaryWorktrees(where)) items.push({ kind: "temporary-worktree", detail: tree });
162
+
163
+ if (role) {
164
+ for (const todo of store.openTodos(where, { assignee: role })) {
165
+ if (isShift(todo)) continue;
166
+ items.push({ kind: "open-todo", detail: `${todo.id} in ${todo.group}: ${firstLine(todo.text)}` });
167
+ }
168
+ for (const record of store.unread(where, role)) {
169
+ if (isShift(record) || !store.wakes(record, role)) continue;
170
+ if (record.kind === "todo" && record.assignee === role) continue;
171
+ items.push({ kind: "unread", detail: `${record.id} in ${record.group} from ${record.from}: ${firstLine(record.text)}` });
172
+ }
173
+ } else {
174
+ notes.push("this worktree has no chat role, so its chat was not checked");
175
+ }
176
+ return { ready: items.length === 0, worktree: where.worktree, role: role || null, items, notes };
177
+ }
178
+
179
+ function firstLine(text) {
180
+ const line = String(text || "").split("\n")[0];
181
+ return line.length > 100 ? `${line.slice(0, 100)}…` : line;
182
+ }
183
+
184
+ function renderCheck(result) {
185
+ const lines = [`keel shift check: ${result.ready ? "ready" : "not ready"} (${result.worktree}${result.role ? `, role ${result.role}` : ""})`];
186
+ for (const item of result.items) lines.push(`- ${item.kind}: ${item.detail}`);
187
+ for (const note of result.notes) lines.push(`note: ${note}`);
188
+ return lines.join("\n");
189
+ }
190
+
191
+ // --- the steps ---------------------------------------------------------------------
192
+
193
+ function requireRole(where) {
194
+ return store.requireRole(where);
195
+ }
196
+
197
+ function directGroup(where, from, role) {
198
+ const group = store.directName(from, role);
199
+ if (!store.groupState(store.readLog(where, group)).exists) {
200
+ store.createGroup(where, from, group, [role], { direct: true });
201
+ }
202
+ return group;
203
+ }
204
+
205
+ function shiftRequests(where, role = null) {
206
+ const requests = [];
207
+ for (const name of store.listGroupNames(where)) {
208
+ const records = store.readLog(where, name);
209
+ const closed = new Set(records.filter((r) => r.kind === "done").map((r) => r.target));
210
+ for (const record of records) {
211
+ if (record.kind !== "todo" || !isShift(record)) continue;
212
+ if (role && record.assignee !== role) continue;
213
+ requests.push({ ...record, open: !closed.has(record.id) });
214
+ }
215
+ }
216
+ return requests.sort((a, b) => (a.id < b.id ? -1 : 1));
217
+ }
218
+
219
+ function request(where, role, text) {
220
+ const from = requireRole(where);
221
+ store.checkName(role, "Role");
222
+ if (role === from) throw new ShiftError("A shift change is requested of another role, not your own.");
223
+ const group = directGroup(where, from, role);
224
+ const body = [
225
+ `Shift change requested by ${from}. Wrap up, then hand over:`,
226
+ "1. `keel shift check` until it reports ready (or decide what may stay).",
227
+ "2. Put follow-ups where the project tracks them, and update long-lived memory you own.",
228
+ "3. `keel shift ready \"<what you were doing, next step, what you wait on, where>\"`.",
229
+ "4. Clear this session as `keel shift ready` says.",
230
+ text ? `\n${text}` : "",
231
+ ].join("\n").trim();
232
+ return store.todo(where, { group, assignee: role, text: body, refs: [REF] });
233
+ }
234
+
235
+ function readNoteText(options) {
236
+ if (options.file) return fs.readFileSync(options.file, "utf8");
237
+ if (options.text) return options.text;
238
+ if (!process.stdin.isTTY) {
239
+ try {
240
+ return fs.readFileSync(0, "utf8");
241
+ } catch {
242
+ return "";
243
+ }
244
+ }
245
+ return "";
246
+ }
247
+
248
+ function ready(where, options) {
249
+ const role = requireRole(where);
250
+ const result = check(where, role);
251
+ if (!result.ready && !options.forceReason) {
252
+ throw new ShiftError(`${renderCheck(result)}\nResolve these, or give --force-reason "<why they may stay>".`);
253
+ }
254
+ const text = readNoteText(options).replace(/\s+$/, "");
255
+ if (!text.trim()) throw new ShiftError("keel shift ready needs the shift note: give it as text, with --file, or on stdin.");
256
+ const stamp = store.isoLocal(new Date());
257
+ const head = [
258
+ `# Shift note: ${role}`,
259
+ "",
260
+ `Written ${stamp} in ${result.worktree}.`,
261
+ options.forceReason ? `\nLeft as is (${options.forceReason}):\n${result.items.map((item) => `- ${item.kind}: ${item.detail}`).join("\n")}` : "",
262
+ "",
263
+ ].join("\n");
264
+ writeFileAtomic(notePath(where, role), `${head}\n${text}\n`);
265
+ const open = shiftRequests(where, role).filter((r) => r.open);
266
+ for (const todo of open) {
267
+ store.post(where, {
268
+ group: todo.group,
269
+ replyTo: todo.id,
270
+ refs: [REF],
271
+ text: `done — ${role} is ready for the shift change; the note waits for \`keel shift resume\`.${options.forceReason ? ` Left as is: ${options.forceReason}.` : ""}`,
272
+ });
273
+ }
274
+ return { role, note: notePath(where, role), closed: open.map((todo) => todo.id) };
275
+ }
276
+
277
+ function start(where, role, text) {
278
+ const from = requireRole(where);
279
+ store.checkName(role, "Role");
280
+ if (!fs.existsSync(notePath(where, role))) {
281
+ throw new ShiftError(`No shift note waits for ${role}: it has not run \`keel shift ready\`, or already resumed.`);
282
+ }
283
+ const group = directGroup(where, from, role);
284
+ const body = [
285
+ `${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.`,
286
+ text ? `Next: ${text}` : "",
287
+ ].filter(Boolean).join("\n");
288
+ return store.post(where, { group, text: body, refs: [REF] });
289
+ }
290
+
291
+ function resume(where) {
292
+ const role = requireRole(where);
293
+ const note = notePath(where, role);
294
+ if (!fs.existsSync(note)) return { role, note: null, text: null };
295
+ const text = fs.readFileSync(note, "utf8");
296
+ const stamp = store.isoLocal(new Date()).replace(/[:+]/g, "");
297
+ const history = path.join(shiftDir(where), "history", `${role}-${stamp}.md`);
298
+ fs.mkdirSync(path.dirname(history), { recursive: true });
299
+ fs.renameSync(note, history);
300
+ // The cold-start message has done its work once the note is read.
301
+ for (const record of store.unread(where, role)) {
302
+ if (isShift(record)) store.advanceCursor(where, role, record.group, record.id);
303
+ }
304
+ const latest = shiftRequests(where, role).pop();
305
+ let told = null;
306
+ if (latest && latest.from !== role) {
307
+ const group = directGroup(where, role, latest.from);
308
+ told = store.post(where, { group, text: `${role} is on shift, resumed from its shift note.`, refs: [REF] }).id;
309
+ }
310
+ return { role, note: history, text, told };
311
+ }
312
+
313
+ function status(where) {
314
+ const roles = new Map();
315
+ const entry = (role) => {
316
+ if (!roles.has(role)) roles.set(role, { role, request: null, note: null, resumed: null });
317
+ return roles.get(role);
318
+ };
319
+ for (const todo of shiftRequests(where)) {
320
+ entry(todo.assignee).request = { id: todo.id, from: todo.from, created: todo.created, open: todo.open };
321
+ }
322
+ const dir = shiftDir(where);
323
+ for (const file of safeList(dir)) {
324
+ if (!file.endsWith(".md")) continue;
325
+ const stat = fs.statSync(path.join(dir, file));
326
+ entry(file.slice(0, -3)).note = store.isoLocal(stat.mtime);
327
+ }
328
+ for (const file of safeList(path.join(dir, "history"))) {
329
+ const match = file.match(/^(.+)-(\d{4}-\d{2}-\d{2}T\d+)\.md$/);
330
+ if (!match) continue;
331
+ const role = entry(match[1]);
332
+ if (!role.resumed || role.resumed < match[2]) role.resumed = match[2];
333
+ }
334
+ return [...roles.values()].sort((a, b) => (a.role < b.role ? -1 : 1));
335
+ }
336
+
337
+ function safeList(dir) {
338
+ try {
339
+ return fs.readdirSync(dir);
340
+ } catch {
341
+ return [];
342
+ }
343
+ }
344
+
345
+ function describe(row) {
346
+ if (row.note) return `${row.role}: note waiting since ${row.note}; \`keel shift start ${row.role}\` wakes it to resume`;
347
+ if (row.request && row.request.open) return `${row.role}: change requested by ${row.request.from} at ${row.request.created}; not ready yet`;
348
+ if (row.resumed) return `${row.role}: on shift, resumed ${row.resumed}`;
349
+ return `${row.role}: ready was recorded without a note`;
350
+ }
351
+
352
+ // --- the command line --------------------------------------------------------------
353
+
354
+ const CLEAR_HINT = [
355
+ "Now clear this session:",
356
+ "- Claude desktop app: call `clear_session(\"self\")` (the owner approves it), or type /clear;",
357
+ "- Claude Code CLI: /clear;",
358
+ "- Codex: start a new session in this worktree.",
359
+ "The coordinator's `keel shift start` then wakes the new shift.",
360
+ ].join("\n");
361
+
362
+ function runShift(argv) {
363
+ const options = { json: false, repo: process.cwd(), positionals: [], file: null, forceReason: null };
364
+ for (let index = 0; index < argv.length; index += 1) {
365
+ const arg = argv[index];
366
+ if (arg === "--json") options.json = true;
367
+ else if (arg === "--repo") options.repo = argv[++index] || "";
368
+ else if (arg === "--file") options.file = argv[++index] || "";
369
+ else if (arg === "--force-reason") options.forceReason = argv[++index] || "";
370
+ else if (arg === "--help" || arg === "-h") {
371
+ process.stdout.write(`${USAGE}\n`);
372
+ return 0;
373
+ } else options.positionals.push(arg);
374
+ }
375
+ const [action, ...rest] = options.positionals;
376
+ const out = (value, text) => process.stdout.write(`${options.json ? JSON.stringify(value, null, 2) : text}\n`);
377
+ try {
378
+ const where = store.requireLocation(options.repo);
379
+ switch (action) {
380
+ case "request": {
381
+ if (!rest[0]) throw new ShiftError("keel shift request needs the role.");
382
+ const record = request(where, rest[0], rest.slice(1).join(" "));
383
+ out({ id: record.id, group: record.group, role: rest[0] }, `Asked ${rest[0]} to change shift (${record.id} in ${record.group}).`);
384
+ return 0;
385
+ }
386
+ case "check": {
387
+ const result = check(where, store.currentRole(where));
388
+ out(result, renderCheck(result));
389
+ return result.ready ? 0 : 1;
390
+ }
391
+ case "ready": {
392
+ const result = ready(where, { ...options, text: rest.join(" ") });
393
+ out({ ...result, clear: CLEAR_HINT }, `Stored the shift note for ${result.role} at ${result.note}${result.closed.length ? ` and closed ${result.closed.join(", ")}` : ""}.\n${CLEAR_HINT}`);
394
+ return 0;
395
+ }
396
+ case "start": {
397
+ if (!rest[0]) throw new ShiftError("keel shift start needs the role.");
398
+ const record = start(where, rest[0], rest.slice(1).join(" "));
399
+ out({ id: record.id, group: record.group, role: rest[0] }, `Woke ${rest[0]} to start its new shift (${record.id} in ${record.group}).`);
400
+ return 0;
401
+ }
402
+ case "resume": {
403
+ const result = resume(where);
404
+ if (!result.note) {
405
+ out(result, `No shift note waits for ${result.role}.`);
406
+ return 0;
407
+ }
408
+ out(result, `${result.text.replace(/\s+$/, "")}\n\n(The note moved to ${result.note}.)`);
409
+ return 0;
410
+ }
411
+ case "status": {
412
+ const rows = status(where);
413
+ out({ roles: rows }, rows.length ? rows.map(describe).join("\n") : "No shift change recorded.");
414
+ return 0;
415
+ }
416
+ default:
417
+ process.stderr.write(`${action ? `keel shift: unknown step ${action}\n` : ""}${USAGE}\n`);
418
+ return 2;
419
+ }
420
+ } catch (error) {
421
+ if (error instanceof ShiftError || error instanceof store.ChatError) {
422
+ process.stderr.write(`keel shift: ${error.message}\n`);
423
+ return 1;
424
+ }
425
+ throw error;
426
+ }
427
+ }
428
+
429
+ function pendingNote(where, role) {
430
+ const note = notePath(where, role);
431
+ if (!fs.existsSync(note)) return null;
432
+ return store.isoLocal(fs.statSync(note).mtime);
433
+ }
434
+
435
+ module.exports = { check, pendingNote, runShift };