@christang/keel 5.93.0 → 5.94.1

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 have its own Slack app, so you can mention it and message it privately in Slack. 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). 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 App,这样在 Slack 里能直接 @ 它、和它私聊。聊天记录同时存在孤儿分支 `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)。5.83 的 `keel mail` 命令继续可用,消息存在私聊群里。
235
235
 
236
236
  ## 命令参考
237
237
 
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.93.0 -->
1
+ <!-- keel:start version=5.94.1 -->
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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.93.0",
3
+ "version": "5.94.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.93.0",
9
+ "version": "5.94.1",
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.93.0",
5
+ "version": "5.94.1",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.93.0",
3
+ "version": "5.94.1",
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.93.0",
3
+ "version": "5.94.1",
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.93.0"
51
- PROTOCOL_VERSION = "5.93.0"
50
+ PACKAGE_VERSION = "5.94.1"
51
+ PROTOCOL_VERSION = "5.94.1"
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
@@ -2663,15 +2663,43 @@ def validate_chat_claude_hooks_scenario() -> int:
2663
2663
  if not script.is_file():
2664
2664
  report(f"{label} {script.relative_to(ROOT)} does not exist.")
2665
2665
  return 1
2666
+ late_watch: list[str] = []
2666
2667
  for cwd in (unbound, plain):
2667
2668
  for event, host_event in events:
2668
2669
  quiet = hook(cwd, event, host_event)
2669
2670
  if quiet.returncode != 0:
2670
2671
  report(f"{label} {event} exited {quiet.returncode} in {cwd.name}, which has no role.")
2671
2672
  return 1
2673
+ if cwd == unbound and event == "session-start":
2674
+ # A session may start before its worktree's role is bound;
2675
+ # it still watches the worktree's signal, and nothing else.
2676
+ output = chat_json(quiet).get("hookSpecificOutput", {})
2677
+ watched = output.get("watchPaths") or []
2678
+ if len(watched) != 1:
2679
+ report(f"{label} session-start in a worktree with no role does not watch exactly one path: {quiet.stdout.strip()!r}")
2680
+ return 1
2681
+ if "/signal/worktree/" not in watched[0]:
2682
+ report(f"{label} session-start in a worktree with no role watches something other than the worktree signal: {watched!r}")
2683
+ return 1
2684
+ if output.get("additionalContext"):
2685
+ report(f"{label} session-start in a worktree with no role printed notice text: {quiet.stdout.strip()!r}")
2686
+ return 1
2687
+ late_watch = watched
2688
+ continue
2672
2689
  if quiet.stdout.strip() or quiet.stderr.strip():
2673
2690
  report(f"{label} {event} wrote output in {cwd.name}, which has no role: {(quiet.stdout + quiet.stderr).strip()!r}")
2674
2691
  return 1
2692
+ chat(unbound, "role", "--set", "late")
2693
+ chat(unbound, "group", "create", "side", "--member", "poster")
2694
+ run_keel(unbound, "chat", "post", "side", "@late please look", env={**env, "KEEL_CHAT_ROLE": "poster"})
2695
+ late_signal = Path(late_watch[0])
2696
+ if not late_signal.exists() or not late_signal.stat().st_size:
2697
+ report(f"{label} a mention of a role bound after session start did not touch the worktree signal that session watches.")
2698
+ return 1
2699
+ late_wake = hook(unbound, "file-changed", "FileChanged")
2700
+ if late_wake.returncode != 2:
2701
+ report(f"{label} file-changed exited {late_wake.returncode} for a role bound after session start, not 2.")
2702
+ return 1
2675
2703
 
2676
2704
  signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "verify"
2677
2705
 
@@ -2717,8 +2745,12 @@ def validate_chat_claude_hooks_scenario() -> int:
2717
2745
  if mention_id not in start_output.get("additionalContext", ""):
2718
2746
  report(f"{label} the session-start notice does not name the mention: {start.stdout.strip()} {start.stderr.strip()}")
2719
2747
  return 1
2720
- if start_output.get("watchPaths") != [str(signal)]:
2721
- report(f"{label} session-start watchPaths is {start_output.get('watchPaths')!r}, not [{str(signal)!r}].")
2748
+ watch = start_output.get("watchPaths") or []
2749
+ if watch[:1] != [str(signal)]:
2750
+ report(f"{label} session-start does not watch the role's signal first: {watch!r}, not starting with {str(signal)!r}.")
2751
+ return 1
2752
+ if [path for path in watch[1:] if "/signal/worktree/" in path] != watch[1:2] or len(watch) != 2:
2753
+ report(f"{label} session-start does not also watch exactly the worktree signal: {watch!r}.")
2722
2754
  return 1
2723
2755
 
2724
2756
  before_dm = signal_size()
@@ -3434,9 +3466,9 @@ def slack_posts_of(slack, channel: str, record_id: str) -> list[dict]:
3434
3466
  return [m for m in slack.messages.get(channel, []) if (m.get("metadata") or {}).get("event_payload", {}).get("id") == record_id]
3435
3467
 
3436
3468
 
3437
- def role_status(cwd: Path, env: dict[str, str], role: str) -> dict:
3469
+ def bot_status(cwd: Path, env: dict[str, str], bot: str) -> dict:
3438
3470
  status = chat_json(run_keel(cwd, "chat", "bridge", "status", "--json", env=env))
3439
- return next((entry for entry in status.get("roles") or [] if entry.get("role") == role), {})
3471
+ return next((entry for entry in status.get("bots") or [] if entry.get("bot") == bot), {})
3440
3472
 
3441
3473
 
3442
3474
  def validate_chat_role_apps_scenario() -> int:
@@ -3471,6 +3503,7 @@ def validate_chat_role_apps_scenario() -> int:
3471
3503
  return result.returncode == 0
3472
3504
 
3473
3505
  chat(rtl, "bridge", "add")
3506
+ chat(rtl, "bot", "add", "rtl")
3474
3507
  own_id = chat_json(chat(rtl, "post", "soc", "rtl speaks", "--json")).get("id", "")
3475
3508
  shared_id = chat_json(chat(verify, "post", "soc", "verify speaks", "--json")).get("id", "")
3476
3509
  chat(rtl, "edit", own_id, "rtl speaks (v2)")
@@ -3499,10 +3532,10 @@ def validate_chat_role_apps_scenario() -> int:
3499
3532
  if updates[0].get("_auth") != "Bearer xoxb-role-rtl":
3500
3533
  report(f"{label} the edit of rtl's record did not use the app that posted it: {updates[0].get('_auth')!r}")
3501
3534
  return 1
3502
- if role_status(rtl, benv, "rtl").get("state") != "verified":
3503
- report(f"{label} status does not report rtl's app as verified: {role_status(rtl, benv, 'rtl')!r}")
3535
+ if bot_status(rtl, benv, "rtl").get("roles") != ["rtl/rtl"]:
3536
+ report(f"{label} status does not list bot rtl serving rtl/rtl: {bot_status(rtl, benv, 'rtl')!r}")
3504
3537
  return 1
3505
- if role_status(rtl, benv, "verify"):
3538
+ if bot_status(rtl, benv, "verify"):
3506
3539
  report(f"{label} status lists verify, which has no token on this machine.")
3507
3540
  return 1
3508
3541
 
@@ -3517,8 +3550,8 @@ def validate_chat_role_apps_scenario() -> int:
3517
3550
  if wrong.get("username") != "rtl":
3518
3551
  report(f"{label} the fallback post is not under rtl's name: {wrong.get('username')!r}")
3519
3552
  return 1
3520
- if role_status(rtl, benv, "rtl").get("state") != "mismatch":
3521
- report(f"{label} status does not report the swapped token as a mismatch: {role_status(rtl, benv, 'rtl')!r}")
3553
+ if bot_status(rtl, benv, "rtl").get("roles") != []:
3554
+ report(f"{label} status does not list the bot whose id no project maps as serving nothing: {bot_status(rtl, benv, 'rtl')!r}")
3522
3555
  return 1
3523
3556
 
3524
3557
  slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
@@ -3533,8 +3566,8 @@ def validate_chat_role_apps_scenario() -> int:
3533
3566
  if landed[0].get("username") != "rtl":
3534
3567
  report(f"{label} the not_in_channel fallback is not under rtl's name: {landed[0]!r}")
3535
3568
  return 1
3536
- if "CSOC" not in (role_status(rtl, benv, "rtl").get("invite") or []):
3537
- report(f"{label} status does not name the channel rtl's bot must be invited to: {role_status(rtl, benv, 'rtl')!r}")
3569
+ if "CSOC" not in (bot_status(rtl, benv, "rtl").get("invite") or []):
3570
+ report(f"{label} status does not name the channel rtl's bot must be invited to: {bot_status(rtl, benv, 'rtl')!r}")
3538
3571
  return 1
3539
3572
  slack.not_in_channel.clear()
3540
3573
 
@@ -3593,6 +3626,7 @@ def validate_chat_role_direct_scenario() -> int:
3593
3626
  slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
3594
3627
  benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
3595
3628
  run_keel(rtl, "chat", "bridge", "add", env=benv)
3629
+ run_keel(rtl, "chat", "bot", "add", "rtl", env=benv)
3596
3630
  signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "rtl"
3597
3631
 
3598
3632
  def direct(user: str, text: str, ts: str) -> dict:
@@ -3643,8 +3677,8 @@ def validate_chat_role_direct_scenario() -> int:
3643
3677
  if any(chat_records_with(rtl, group, "give me the keys") for group in ("dm-owner--rtl", "dm-rtl--ustranger", "soc")):
3644
3678
  report(f"{label} a stranger's direct message reached the store.")
3645
3679
  return 1
3646
- if not role_status(rtl, benv, "rtl").get("direct"):
3647
- report(f"{label} status does not report rtl's direct-message connection: {role_status(rtl, benv, 'rtl')!r}")
3680
+ if bot_status(rtl, benv, "rtl").get("direct") is not True:
3681
+ report(f"{label} status does not report rtl's direct-message connection: {bot_status(rtl, benv, 'rtl')!r}")
3648
3682
  return 1
3649
3683
  finally:
3650
3684
  stop_chat_bridge(bridge)
@@ -3672,33 +3706,120 @@ def validate_chat_role_direct_scenario() -> int:
3672
3706
  return 0
3673
3707
 
3674
3708
 
3709
+ def validate_chat_shared_bots_scenario() -> int:
3710
+ """Issue #187: one registered bot is a different role in each project.
3711
+
3712
+ A bot listed once with `keel chat bot add` serves the role each project's
3713
+ `slack.bots` maps its id to: both projects post with its token to their own
3714
+ channels, a mention of it in one project's channel reaches only that
3715
+ project's role, and a bot serving two roles opens no direct-message
3716
+ connection, because a direct message cannot say which project it is for.
3717
+ """
3718
+ label = "chat-shared-bots:"
3719
+ if chat_bridge_node_missing("chat-shared-bots"):
3720
+ return 3
3721
+ FakeSlack = fake_slack_class()
3722
+ with tempfile.TemporaryDirectory(prefix="keel-chat-shared-") as raw, FakeSlack() as slack:
3723
+ base = Path(raw)
3724
+ env = chat_environment()
3725
+ keychain = role_keychain(base, {"bot:pm": "xoxb-bot-pm", "app:pm": "xapp-bot-pm"})
3726
+ slack.identify("xoxb-bot-pm", "UBOTPM", "BBOTPM")
3727
+ benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
3728
+ repos = {}
3729
+ for name, channel in (("a", "CA"), ("b", "CB")):
3730
+ repo = mailbox_repository(base / name)
3731
+ run_keel(repo, "chat", "role", "--set", f"{name}-pm", env=env)
3732
+ run_keel(repo, "chat", "group", "create", "ops", env=env)
3733
+ chat_slack_config(repo, {"ops": channel}, bots={"UBOTPM": f"{name}-pm"})
3734
+ run_keel(repo, "chat", "bridge", "add", env=benv)
3735
+ repos[name] = repo
3736
+ added = run_keel(repos["a"], "chat", "bot", "add", "pm", env=benv)
3737
+ if added.returncode != 0:
3738
+ report(f"{label} keel chat bot add pm failed: {added.stderr.strip()}")
3739
+ return 1
3740
+ listed = run_keel(repos["a"], "chat", "bot", "list", env=benv)
3741
+ if "pm" not in listed.stdout:
3742
+ report(f"{label} keel chat bot list does not show pm: {listed.stdout.strip()} {listed.stderr.strip()}")
3743
+ return 1
3744
+ if "xoxb-bot-pm" in listed.stdout + listed.stderr:
3745
+ report(f"{label} keel chat bot list printed a token.")
3746
+ return 1
3747
+ ids = {name: chat_json(run_keel(repo, "chat", "post", "ops", f"{name} reporting", "--json", env=benv)).get("id", "") for name, repo in repos.items()}
3748
+
3749
+ bridge = start_chat_bridge(repos["a"], benv)
3750
+ try:
3751
+ if not slack.wait_for(lambda: slack.sockets_for("xapp-test-app"), 10):
3752
+ report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
3753
+ return 1
3754
+ for name, channel in (("a", "CA"), ("b", "CB")):
3755
+ if not slack.wait_for(lambda: slack_posts_of(slack, channel, ids[name])):
3756
+ report(f"{label} project {name}'s post never reached {channel}.")
3757
+ return 1
3758
+ sent = next(c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == ids[name])
3759
+ if sent.get("_auth") != "Bearer xoxb-bot-pm":
3760
+ report(f"{label} project {name}'s role did not post through the shared pm bot: {sent.get('_auth')!r}")
3761
+ return 1
3762
+ slack.push(slack_event("CA", user="UOWNER", text="<@UBOTPM> status?", ts="1800000001.000100"))
3763
+ if not slack.wait_for(lambda: chat_records_with(repos["a"], "ops", "status?")):
3764
+ report(f"{label} the owner's mention of the pm bot in CA did not reach project a.")
3765
+ return 1
3766
+ if " - a-pm" not in chat_records_with(repos["a"], "ops", "status?")[0]:
3767
+ report(f"{label} the mention in CA did not become a mention of a-pm.")
3768
+ return 1
3769
+ if chat_records_with(repos["b"], "ops", "status?"):
3770
+ report(f"{label} a mention in project a's channel reached project b.")
3771
+ return 1
3772
+ if slack.sockets_for("xapp-bot-pm"):
3773
+ report(f"{label} a bot serving two roles opened a direct-message connection.")
3774
+ return 1
3775
+ pm = bot_status(repos["a"], benv, "pm")
3776
+ if sorted(pm.get("roles") or []) != ["a/a-pm", "b/b-pm"]:
3777
+ report(f"{label} status does not list pm serving a/a-pm and b/b-pm: {pm!r}")
3778
+ return 1
3779
+ if pm.get("direct") is not False:
3780
+ report(f"{label} status does not report pm's direct messages as off: {pm!r}")
3781
+ return 1
3782
+ if "2 roles" not in str(pm.get("direct_note", "")):
3783
+ report(f"{label} status does not say why pm's direct messages are off: {pm!r}")
3784
+ return 1
3785
+ finally:
3786
+ stop_chat_bridge(bridge)
3787
+
3788
+ if "chat-shared-bots" not in {name for name, _ in SCENARIOS}:
3789
+ report(f"{label} scenario is not registered.")
3790
+ return 1
3791
+ report("chat-shared-bots scenario passed.")
3792
+ return 0
3793
+
3794
+
3675
3795
  def validate_chat_role_apps_are_documented_scenario() -> int:
3676
- """Issue #187: the setup guides and READMEs say a role may have its own app.
3796
+ """Issue #187: the setup guides and READMEs describe shared bots.
3677
3797
 
3678
- Both guides carry the role-app section — the `slack.bots` registration,
3679
- the two Keychain accounts, the manifest's direct-message scopes, and that
3680
- direct messages stay on the role's machine — and neither still equates the
3681
- free plan's app limit with a machine count.
3798
+ Both guides carry the bot section — `keel chat bot add`, the Keychain
3799
+ accounts named by bot, the `slack.bots` mapping, that one bot serves a role
3800
+ in each of several projects, and that such a bot takes no direct messages
3801
+ — and neither still ties a token to a role or equates the app limit with a
3802
+ machine count.
3682
3803
  """
3683
3804
  label = "chat-role-apps-are-documented:"
3684
3805
  guides = {
3685
- "docs/chat-slack-setup.md": "Direct messages stay on the machine where the role runs",
3686
- "docs/chat-slack-setup.zh-CN.md": "私聊只留在这个角色所在的电脑上",
3806
+ "docs/chat-slack-setup.md": ("serve a role in each of several projects", "takes no direct messages"),
3807
+ "docs/chat-slack-setup.zh-CN.md": ("在多个项目里各当一个角色", "不接私聊"),
3687
3808
  }
3688
- for relative, stays in guides.items():
3809
+ for relative, phrases in guides.items():
3689
3810
  text = (ROOT / relative).read_text(encoding="utf-8")
3690
- for needle in ('"bots"', "bot:<role>", "app:<role>", "chat:write.public", "im:history", "im:write", stays):
3811
+ for needle in ('"bots"', "keel chat bot add", "bot:<name>", "app:<name>", "chat:write.public", "im:history", *phrases):
3691
3812
  if needle not in text:
3692
3813
  report(f"{label} {relative} does not carry {needle!r}.")
3693
3814
  return 1
3694
- for stale in ("which means 10 machines", "也就是最多 10 台电脑"):
3815
+ for stale in ("bot:<role>", "which means 10 machines", "也就是最多 10 台电脑"):
3695
3816
  if stale in text:
3696
- report(f"{label} {relative} still says {stale!r}, but role apps count toward the limit too.")
3817
+ report(f"{label} {relative} still says {stale!r}.")
3697
3818
  return 1
3698
- readmes = {"README.md": "its own Slack app", "README.zh-CN.md": "自己的 Slack App"}
3819
+ readmes = {"README.md": "one bot can serve several projects", "README.zh-CN.md": "一个 bot 可以服务多个项目"}
3699
3820
  for relative, needle in readmes.items():
3700
3821
  if needle not in (ROOT / relative).read_text(encoding="utf-8"):
3701
- report(f"{label} {relative} does not say a role may have {needle!r}.")
3822
+ report(f"{label} {relative} does not say {needle!r}.")
3702
3823
  return 1
3703
3824
  if "chat-role-apps-are-documented" not in {name for name, _ in SCENARIOS}:
3704
3825
  report(f"{label} scenario is not registered.")
@@ -36070,6 +36191,10 @@ SCENARIOS: tuple = (
36070
36191
  "chat-role-apps-are-documented",
36071
36192
  validate_chat_role_apps_are_documented_scenario,
36072
36193
  ),
36194
+ (
36195
+ "chat-shared-bots",
36196
+ validate_chat_shared_bots_scenario,
36197
+ ),
36073
36198
  (
36074
36199
  "chat-archive",
36075
36200
  validate_chat_archive_scenario,
@@ -45,6 +45,40 @@ function readRegistry() {
45
45
  }
46
46
  }
47
47
 
48
+ // The bots this machine holds tokens for, by name (chat-shared-bots D1). Names
49
+ // only: the tokens stay in the Keychain.
50
+ function botsFile() {
51
+ return path.join(keelHome(), "chat", "bots.json");
52
+ }
53
+
54
+ function readBots() {
55
+ try {
56
+ const parsed = JSON.parse(fs.readFileSync(botsFile(), "utf8"));
57
+ return Array.isArray(parsed.bots) ? parsed.bots.filter((entry) => typeof entry === "string") : [];
58
+ } catch {
59
+ return [];
60
+ }
61
+ }
62
+
63
+ function writeBots(bots) {
64
+ const file = botsFile();
65
+ fs.mkdirSync(path.dirname(file), { recursive: true });
66
+ const temp = `${file}.${process.pid}.tmp`;
67
+ fs.writeFileSync(temp, `${JSON.stringify({ bots: [...new Set(bots)].sort() }, null, 2)}\n`);
68
+ fs.renameSync(temp, file);
69
+ }
70
+
71
+ function addBot(name) {
72
+ store.checkName(name, "Bot");
73
+ writeBots([...readBots(), name]);
74
+ return name;
75
+ }
76
+
77
+ function removeBot(name) {
78
+ writeBots(readBots().filter((entry) => entry !== name));
79
+ return name;
80
+ }
81
+
48
82
  function writeRegistry(projects) {
49
83
  const file = registryFile();
50
84
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -161,12 +195,10 @@ function iconFields(project, role) {
161
195
  return icon.startsWith(":") ? { icon_emoji: icon } : { icon_url: icon };
162
196
  }
163
197
 
164
- // The verified app of `role` that `project` registered, or null: the role
165
- // then speaks through the shared app (chat-role-apps D3).
198
+ // The verified bot that `project` maps to `role`, or null: the role then
199
+ // speaks through the shared app (chat-shared-bots D2).
166
200
  function roleApp(ctx, project, role) {
167
- const app = ctx.roles.get(role);
168
- if (!app || app.state !== "verified") return null;
169
- return project.settings.bots[app.user_id] === role ? app : null;
201
+ return (project.roleBots && project.roleBots.get(role)) || null;
170
202
  }
171
203
 
172
204
  async function postRecord(ctx, project, record, channel, direct = null) {
@@ -279,9 +311,11 @@ function pendingOutbound(project) {
279
311
 
280
312
  const DIRECT_KINDS = new Set(["message", "todo", "done", "edit", "retract"]);
281
313
 
282
- // Role apps that take direct messages: verified, with an app-level token (D6).
314
+ // Bots that take direct messages: verified, with an app-level token, and
315
+ // serving exactly one role, since a direct message cannot say which project it
316
+ // is for (chat-shared-bots D4).
283
317
  function directApps(ctx) {
284
- return [...(ctx.roles || new Map()).values()].filter((app) => app.state === "verified" && app.appToken);
318
+ return [...(ctx.bots || new Map()).values()].filter((app) => app.state === "verified" && app.appToken && app.serves.length === 1);
285
319
  }
286
320
 
287
321
  // Each direct group between a registered person and a role whose app takes
@@ -695,7 +729,7 @@ function writeStatus(ctx) {
695
729
  last_event: ctx.stats.last_event,
696
730
  ignored: ctx.stats.ignored,
697
731
  unposted: unpostedCount(ctx.projects),
698
- roles: roleReport(ctx),
732
+ bots: botReport(ctx),
699
733
  updated: store.isoLocal(new Date()),
700
734
  };
701
735
  const file = statusFile();
@@ -709,49 +743,57 @@ function writeStatus(ctx) {
709
743
  }
710
744
  }
711
745
 
712
- // Each role app this machine holds a token for (D8). A role registered with
713
- // no token here lives on another machine and is not listed.
714
- function roleReport(ctx) {
715
- return [...(ctx.roles || new Map()).values()].map((app) => ({
716
- role: app.role,
717
- state: app.state,
718
- ...(app.reason ? { reason: app.reason } : {}),
719
- direct: Boolean(app.connected),
720
- invite: [...app.invite].sort(),
721
- }));
746
+ // Each bot this machine lists, with the roles it serves (chat-shared-bots D5).
747
+ function botReport(ctx) {
748
+ return [...(ctx.bots || new Map()).values()].map((app) => {
749
+ let directNote = null;
750
+ if (app.state === "verified" && app.appToken && app.serves.length > 1) directNote = `off: serves ${app.serves.length} roles, and a direct message cannot say which project it is for`;
751
+ else if (app.state === "verified" && !app.appToken) directNote = `off: no app:${app.name} token`;
752
+ return {
753
+ bot: app.name,
754
+ state: app.state,
755
+ ...(app.reason ? { reason: app.reason } : {}),
756
+ roles: app.serves.map((entry) => entry.label),
757
+ direct: Boolean(app.connected),
758
+ ...(directNote ? { direct_note: directNote } : {}),
759
+ invite: [...app.invite].sort(),
760
+ };
761
+ });
722
762
  }
723
763
 
724
- // Checks every registered role's Keychain token with auth.test and keeps it
725
- // only for the bot user the registration names (D3).
726
- async function verifyRoles(ctx) {
727
- const declared = new Map();
728
- for (const project of ctx.projects) {
729
- for (const [user, role] of Object.entries(project.settings.bots)) {
730
- if (!declared.has(role)) declared.set(role, new Set());
731
- declared.get(role).add(user);
732
- }
733
- }
734
- const roles = new Map();
735
- for (const [role, users] of declared) {
736
- const tokens = lifecycle.roleTokens(role);
737
- if (!tokens.bot) continue;
738
- const app = { role, token: tokens.bot, appToken: tokens.app, state: "failed", reason: null, user_id: null, bot_id: null, invite: new Set(), connected: false, socket: null, ims: new Map() };
739
- try {
740
- const auth = await slack.callWithRetry("auth.test", {}, tokens.bot, { attempts: 2 });
741
- app.user_id = auth.user_id || null;
742
- app.bot_id = auth.bot_id || null;
743
- if (users.has(app.user_id)) {
764
+ // Checks each listed bot's Keychain token with auth.test, then gives each
765
+ // project's role the bot its `slack.bots` maps to it (D2).
766
+ async function verifyBots(ctx) {
767
+ const bots = new Map();
768
+ for (const name of readBots()) {
769
+ const tokens = lifecycle.botTokens(name);
770
+ const app = { name, role: null, token: tokens.bot, appToken: tokens.app, state: "failed", reason: null, user_id: null, bot_id: null, serves: [], invite: new Set(), connected: false, socket: null, ims: new Map() };
771
+ if (!tokens.bot) {
772
+ app.reason = `no bot:${name} token in the Keychain`;
773
+ } else {
774
+ try {
775
+ const auth = await slack.callWithRetry("auth.test", {}, tokens.bot, { attempts: 2 });
776
+ app.user_id = auth.user_id || null;
777
+ app.bot_id = auth.bot_id || null;
744
778
  app.state = "verified";
745
- } else {
746
- app.state = "mismatch";
747
- app.reason = `bot:${role} belongs to ${app.user_id}, not the ${[...users].join(" or ")} keel/chat.json registers`;
779
+ } catch (error) {
780
+ app.reason = error.message;
748
781
  }
749
- } catch (error) {
750
- app.reason = error.message;
751
782
  }
752
- roles.set(role, app);
783
+ bots.set(name, app);
784
+ }
785
+ for (const project of ctx.projects) {
786
+ project.roleBots = new Map();
787
+ for (const app of bots.values()) {
788
+ if (app.state !== "verified") continue;
789
+ const role = project.settings.bots[app.user_id];
790
+ if (!role) continue;
791
+ project.roleBots.set(role, app);
792
+ app.serves.push({ project, role, label: `${project.where.project}/${role}` });
793
+ }
753
794
  }
754
- return roles;
795
+ for (const app of bots.values()) if (app.serves.length === 1) app.role = app.serves[0].role;
796
+ return bots;
755
797
  }
756
798
 
757
799
  function readStatus() {
@@ -782,7 +824,7 @@ function fullStatus() {
782
824
  last_event: null,
783
825
  ignored: 0,
784
826
  unposted: 0,
785
- roles: [],
827
+ bots: [],
786
828
  ...status,
787
829
  paused: Boolean(until),
788
830
  paused_until: until ? new Date(until).toISOString() : null,
@@ -821,14 +863,14 @@ async function createContext(log, { needApp }) {
821
863
  ctx.onEvent = (event) => handleEvent(ctx, event);
822
864
  const auth = await slack.callWithRetry("auth.test", {}, bot);
823
865
  ctx.self = { bot_id: auth.bot_id || null, user_id: auth.user_id || null };
824
- ctx.roles = await verifyRoles(ctx);
825
- for (const project of ctx.projects) project.directApps = directApps(ctx).filter((app) => roleApp(ctx, project, app.role));
866
+ ctx.bots = await verifyBots(ctx);
867
+ for (const project of ctx.projects) project.directApps = directApps(ctx).filter((app) => app.serves[0].project === project);
826
868
  for (const app of directApps(ctx)) {
827
869
  app.onHello = () => catchUpDirect(ctx, app);
828
870
  app.onEvent = (event) => handleDirectEvent(ctx, app, event);
829
871
  }
830
872
  // Posts and actions through a verified role app are this bridge's own (D5).
831
- const verified = [...ctx.roles.values()].filter((app) => app.state === "verified");
873
+ const verified = [...ctx.bots.values()].filter((app) => app.state === "verified");
832
874
  ctx.ownBots = new Set([ctx.self.bot_id, ...verified.map((app) => app.bot_id)].filter(Boolean));
833
875
  ctx.ownUsers = new Set([ctx.self.user_id, ...verified.map((app) => app.user_id)].filter(Boolean));
834
876
  return ctx;
@@ -1008,6 +1050,9 @@ async function run(log) {
1008
1050
 
1009
1051
  module.exports = {
1010
1052
  METADATA_TYPE,
1053
+ addBot,
1054
+ readBots,
1055
+ removeBot,
1011
1056
  addProject,
1012
1057
  keelHome,
1013
1058
  readPosted,
@@ -38,6 +38,7 @@ const USAGE = [
38
38
  "keel chat bridge install|uninstall|start|stop (the macOS login item that keeps the bridge running)",
39
39
  "keel chat bridge pause <30m|2h|1d> | resume",
40
40
  "keel chat bridge status [--json]",
41
+ "keel chat bot add|remove <name> | list (the Slack bots this machine holds Keychain tokens for, as bot:<name> and app:<name>)",
41
42
  "keel chat notice (what is unread and addressed to you, for any host; always exits 0)",
42
43
  "keel chat notice --check (for schedulers: no output; exit 0 only when something addressed to you is unread, else 1)",
43
44
  "keel chat hook session-start|user-prompt-submit|file-changed|session-end (Claude Code hook; JSON on stdin)",
@@ -370,6 +371,38 @@ function dispatch(where, options) {
370
371
  }
371
372
  }
372
373
 
374
+ // The machine's bot list (chat-shared-bots D1). It needs no repository and
375
+ // shows only whether each Keychain entry exists, never its value.
376
+ function runBot(rest) {
377
+ const bridge = require("./bridge");
378
+ const lifecycle = require("./lifecycle");
379
+ const [action, name] = rest;
380
+ switch (action) {
381
+ case "add":
382
+ if (!name) throw new ChatError("keel chat bot add needs a bot name.");
383
+ out(`Listed bot ${bridge.addBot(name)}. Store its tokens as Keychain accounts bot:${name} and app:${name} of service keel-chat-slack, map its Slack user id to a role in each project's keel/chat.json slack.bots, and restart the bridge.`);
384
+ return 0;
385
+ case "remove":
386
+ if (!name) throw new ChatError("keel chat bot remove needs a bot name.");
387
+ out(`Unlisted bot ${bridge.removeBot(name)}; its Keychain entries are untouched. Restart the bridge to stop using it.`);
388
+ return 0;
389
+ case "list": {
390
+ const bots = bridge.readBots();
391
+ if (!bots.length) {
392
+ out("No bots listed on this machine. Add one with `keel chat bot add <name>`.");
393
+ return 0;
394
+ }
395
+ for (const bot of bots) {
396
+ const tokens = lifecycle.botTokens(bot);
397
+ out(`${bot}: bot token ${tokens.bot ? "stored" : "missing"}, app token ${tokens.app ? "stored" : "missing"}`);
398
+ }
399
+ return 0;
400
+ }
401
+ default:
402
+ throw new ChatError(`Unknown keel chat bot action ${JSON.stringify(action)}: use add, remove, or list.`);
403
+ }
404
+ }
405
+
373
406
  function runBridge(where, rest, options) {
374
407
  const bridge = require("./bridge");
375
408
  const lifecycle = require("./lifecycle");
@@ -393,10 +426,11 @@ function runBridge(where, rest, options) {
393
426
  const lines = [`keel chat bridge: ${status.installed ? "installed as a login item" : "not installed"}; ${status.running ? `running (pid ${status.pid}), ${status.connected ? "connected" : "not connected"}` : "not running"}${status.paused ? `, paused until ${status.paused_until}` : ""}.`];
394
427
  if (status.running) lines.push(`Serving ${status.projects.length} project${status.projects.length === 1 ? "" : "s"}; last event ${status.last_event || "none yet"}; ${status.unposted} waiting to send; ${status.ignored} ignored from unregistered senders.`);
395
428
  else lines.push("Slack messages are not reaching this machine's sessions; local chat still works and nothing is lost.");
396
- for (const app of status.roles || []) {
397
- const parts = [`Role app ${app.role}: ${app.state}`];
429
+ for (const app of status.bots || []) {
430
+ const parts = [`Bot ${app.bot}: ${app.state}`];
398
431
  if (app.reason) parts.push(app.reason);
399
- if (app.state === "verified") parts.push(app.direct ? "direct messages connected" : "no direct messages");
432
+ if (app.state === "verified") parts.push(app.roles.length ? `serves ${app.roles.join(", ")}` : "serves no role: no project's slack.bots maps its id");
433
+ if (app.state === "verified") parts.push(app.direct ? "direct messages connected" : `direct messages ${app.direct_note || "not connected"}`);
400
434
  if (app.invite && app.invite.length) parts.push(`invite it to ${app.invite.join(", ")}; until then it posts through the shared app there`);
401
435
  lines.push(`${parts.join("; ")}.`);
402
436
  }
@@ -509,6 +543,8 @@ function runChat(argv) {
509
543
  if (options.positionals[0] === "bridge" && !["add", "remove"].includes(options.positionals[1])) {
510
544
  return runBridge(null, options.positionals.slice(1), options);
511
545
  }
546
+ // The bot list belongs to the machine, like the bridge.
547
+ if (options.positionals[0] === "bot") return runBot(options.positionals.slice(1));
512
548
  // A notice is read by hosts on every prompt: outside a repository it says
513
549
  // nothing and still exits 0.
514
550
  if (options.positionals[0] === "notice" && !store.locate(cwd)) return 0;
@@ -48,11 +48,11 @@ function tokens() {
48
48
  return { app: app || null, bot: bot || null };
49
49
  }
50
50
 
51
- // A role's own app (chat-role-apps D2): Keychain only, on the machine where
52
- // the role runs, because an environment variable would have to encode a role
53
- // name in its own name.
54
- function roleTokens(role) {
55
- return { bot: keychainToken(`bot:${role}`), app: keychainToken(`app:${role}`) };
51
+ // A registered bot's tokens (chat-shared-bots D1): Keychain only, by the
52
+ // bot's name, because an environment variable would have to encode that name
53
+ // in its own.
54
+ function botTokens(name) {
55
+ return { bot: keychainToken(`bot:${name}`), app: keychainToken(`app:${name}`) };
56
56
  }
57
57
 
58
58
  function missingTokens(which) {
@@ -204,7 +204,7 @@ function stop() {
204
204
  }
205
205
 
206
206
  module.exports = {
207
- roleTokens,
207
+ botTokens,
208
208
  KEYCHAIN_SERVICE,
209
209
  LABEL,
210
210
  bridgeDir,
@@ -114,6 +114,13 @@ function ensureSignal(where, role) {
114
114
  return signal;
115
115
  }
116
116
 
117
+ function ensureWorktreeSignal(where) {
118
+ const signal = store.worktreeSignalPath(where.root, where.worktree);
119
+ fs.mkdirSync(path.dirname(signal), { recursive: true });
120
+ if (!fs.existsSync(signal)) fs.writeFileSync(signal, "");
121
+ return signal;
122
+ }
123
+
117
124
  // For a Slack-enabled project, whether this machine's bridge is carrying the
118
125
  // chat, so a session does not assume the owner's phone can reach it (D18).
119
126
  function bridgeLine(where) {
@@ -161,6 +168,13 @@ function hook(event, input, { mail = false } = {}) {
161
168
  } catch {
162
169
  role = null;
163
170
  }
171
+ // A session's watch list is fixed at SessionStart, so a worktree with no role
172
+ // yet still watches its own signal, which a role bound later will touch
173
+ // (chat-wake-late-binding D1). Nothing else is said until there is a role.
174
+ if (where && !role && event === "session-start") {
175
+ const watched = ensureWorktreeSignal(where);
176
+ return { code: 0, stdout: `${JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [watched] } })}\n` };
177
+ }
164
178
  if (!where || !role) return { code: 0 };
165
179
  if (event === "session-end") {
166
180
  touchPresence(where, role, "offline");
@@ -171,7 +185,7 @@ function hook(event, input, { mail = false } = {}) {
171
185
  const text = chatText && mail ? `${chatText}\n${MAIL_POINTER}` : chatText;
172
186
  if (event === "session-start") {
173
187
  const output = {
174
- hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [ensureSignal(where, role)] },
188
+ hookSpecificOutput: { hookEventName: "SessionStart", watchPaths: [ensureSignal(where, role), ensureWorktreeSignal(where)] },
175
189
  };
176
190
  const context = [bridgeLine(where), text].filter(Boolean).join("\n");
177
191
  if (context) output.hookSpecificOutput.additionalContext = context;
@@ -48,7 +48,7 @@ const FIELD_ORDER = [
48
48
  const RESERVED_GROUPS = new Set([
49
49
  "role", "group", "post", "dm", "unread", "read", "show", "list", "help",
50
50
  "hook", "notice", "todo", "todos", "done", "edit", "retract", "search",
51
- "bridge", "archive", "transcript",
51
+ "bridge", "archive", "transcript", "bot",
52
52
  ]);
53
53
 
54
54
  class ChatError extends Error {}
@@ -345,14 +345,31 @@ function writeRecord(where, fields, date = new Date()) {
345
345
  writeAtomic(where.root, target, renderRecord(record));
346
346
  refreshTranscript(where, record.group);
347
347
  // After the rename, so a host woken by the signal always finds the record.
348
- for (const role of signalTargets(record)) {
349
- const signal = path.join(where.root, "signal", role);
350
- fs.mkdirSync(path.dirname(signal), { recursive: true });
351
- fs.appendFileSync(signal, `${record.id}\n`);
348
+ // Each worktree bound to a woken role gets its own signal too, which a
349
+ // session watches from its start whether or not a role was bound yet
350
+ // (chat-wake-late-binding D2).
351
+ const targets = signalTargets(record);
352
+ const bound = targets.length ? readRoles(where.root) : {};
353
+ for (const role of targets) {
354
+ const signals = [path.join(where.root, "signal", role)];
355
+ for (const [worktree, name] of Object.entries(bound)) {
356
+ if (name === role) signals.push(worktreeSignalPath(where.root, worktree));
357
+ }
358
+ for (const signal of signals) {
359
+ fs.mkdirSync(path.dirname(signal), { recursive: true });
360
+ fs.appendFileSync(signal, `${record.id}\n`);
361
+ }
352
362
  }
353
363
  return record;
354
364
  }
355
365
 
366
+ // A worktree's own signal file: the first 16 hex digits of the SHA-256 of its
367
+ // path, so it names the worktree whatever role it later binds.
368
+ function worktreeSignalPath(root, worktree) {
369
+ const id = require("crypto").createHash("sha256").update(worktree).digest("hex").slice(0, 16);
370
+ return path.join(root, "signal", "worktree", id);
371
+ }
372
+
356
373
  // The transcript is derived and local (D1): regenerated whole after each
357
374
  // write, and never a source of anything. A failure to write it fails nothing.
358
375
  function refreshTranscript(where, group) {
@@ -736,6 +753,8 @@ function readGroups(where, role, group) {
736
753
  }
737
754
 
738
755
  module.exports = {
756
+ checkName,
757
+ worktreeSignalPath,
739
758
  ALL,
740
759
  ChatError,
741
760
  DATA_NOTICE,