@christang/keel 5.93.0 → 5.94.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 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.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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.93.0",
3
+ "version": "5.94.0",
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.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.93.0",
5
+ "version": "5.94.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.93.0",
3
+ "version": "5.94.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.93.0",
3
+ "version": "5.94.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.93.0"
51
- PROTOCOL_VERSION = "5.93.0"
50
+ PACKAGE_VERSION = "5.94.0"
51
+ PROTOCOL_VERSION = "5.94.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
@@ -3434,9 +3434,9 @@ def slack_posts_of(slack, channel: str, record_id: str) -> list[dict]:
3434
3434
  return [m for m in slack.messages.get(channel, []) if (m.get("metadata") or {}).get("event_payload", {}).get("id") == record_id]
3435
3435
 
3436
3436
 
3437
- def role_status(cwd: Path, env: dict[str, str], role: str) -> dict:
3437
+ def bot_status(cwd: Path, env: dict[str, str], bot: str) -> dict:
3438
3438
  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), {})
3439
+ return next((entry for entry in status.get("bots") or [] if entry.get("bot") == bot), {})
3440
3440
 
3441
3441
 
3442
3442
  def validate_chat_role_apps_scenario() -> int:
@@ -3471,6 +3471,7 @@ def validate_chat_role_apps_scenario() -> int:
3471
3471
  return result.returncode == 0
3472
3472
 
3473
3473
  chat(rtl, "bridge", "add")
3474
+ chat(rtl, "bot", "add", "rtl")
3474
3475
  own_id = chat_json(chat(rtl, "post", "soc", "rtl speaks", "--json")).get("id", "")
3475
3476
  shared_id = chat_json(chat(verify, "post", "soc", "verify speaks", "--json")).get("id", "")
3476
3477
  chat(rtl, "edit", own_id, "rtl speaks (v2)")
@@ -3499,10 +3500,10 @@ def validate_chat_role_apps_scenario() -> int:
3499
3500
  if updates[0].get("_auth") != "Bearer xoxb-role-rtl":
3500
3501
  report(f"{label} the edit of rtl's record did not use the app that posted it: {updates[0].get('_auth')!r}")
3501
3502
  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}")
3503
+ if bot_status(rtl, benv, "rtl").get("roles") != ["rtl/rtl"]:
3504
+ report(f"{label} status does not list bot rtl serving rtl/rtl: {bot_status(rtl, benv, 'rtl')!r}")
3504
3505
  return 1
3505
- if role_status(rtl, benv, "verify"):
3506
+ if bot_status(rtl, benv, "verify"):
3506
3507
  report(f"{label} status lists verify, which has no token on this machine.")
3507
3508
  return 1
3508
3509
 
@@ -3517,8 +3518,8 @@ def validate_chat_role_apps_scenario() -> int:
3517
3518
  if wrong.get("username") != "rtl":
3518
3519
  report(f"{label} the fallback post is not under rtl's name: {wrong.get('username')!r}")
3519
3520
  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}")
3521
+ if bot_status(rtl, benv, "rtl").get("roles") != []:
3522
+ report(f"{label} status does not list the bot whose id no project maps as serving nothing: {bot_status(rtl, benv, 'rtl')!r}")
3522
3523
  return 1
3523
3524
 
3524
3525
  slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
@@ -3533,8 +3534,8 @@ def validate_chat_role_apps_scenario() -> int:
3533
3534
  if landed[0].get("username") != "rtl":
3534
3535
  report(f"{label} the not_in_channel fallback is not under rtl's name: {landed[0]!r}")
3535
3536
  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}")
3537
+ if "CSOC" not in (bot_status(rtl, benv, "rtl").get("invite") or []):
3538
+ report(f"{label} status does not name the channel rtl's bot must be invited to: {bot_status(rtl, benv, 'rtl')!r}")
3538
3539
  return 1
3539
3540
  slack.not_in_channel.clear()
3540
3541
 
@@ -3593,6 +3594,7 @@ def validate_chat_role_direct_scenario() -> int:
3593
3594
  slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
3594
3595
  benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
3595
3596
  run_keel(rtl, "chat", "bridge", "add", env=benv)
3597
+ run_keel(rtl, "chat", "bot", "add", "rtl", env=benv)
3596
3598
  signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "rtl"
3597
3599
 
3598
3600
  def direct(user: str, text: str, ts: str) -> dict:
@@ -3643,8 +3645,8 @@ def validate_chat_role_direct_scenario() -> int:
3643
3645
  if any(chat_records_with(rtl, group, "give me the keys") for group in ("dm-owner--rtl", "dm-rtl--ustranger", "soc")):
3644
3646
  report(f"{label} a stranger's direct message reached the store.")
3645
3647
  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}")
3648
+ if bot_status(rtl, benv, "rtl").get("direct") is not True:
3649
+ report(f"{label} status does not report rtl's direct-message connection: {bot_status(rtl, benv, 'rtl')!r}")
3648
3650
  return 1
3649
3651
  finally:
3650
3652
  stop_chat_bridge(bridge)
@@ -3672,33 +3674,120 @@ def validate_chat_role_direct_scenario() -> int:
3672
3674
  return 0
3673
3675
 
3674
3676
 
3677
+ def validate_chat_shared_bots_scenario() -> int:
3678
+ """Issue #187: one registered bot is a different role in each project.
3679
+
3680
+ A bot listed once with `keel chat bot add` serves the role each project's
3681
+ `slack.bots` maps its id to: both projects post with its token to their own
3682
+ channels, a mention of it in one project's channel reaches only that
3683
+ project's role, and a bot serving two roles opens no direct-message
3684
+ connection, because a direct message cannot say which project it is for.
3685
+ """
3686
+ label = "chat-shared-bots:"
3687
+ if chat_bridge_node_missing("chat-shared-bots"):
3688
+ return 3
3689
+ FakeSlack = fake_slack_class()
3690
+ with tempfile.TemporaryDirectory(prefix="keel-chat-shared-") as raw, FakeSlack() as slack:
3691
+ base = Path(raw)
3692
+ env = chat_environment()
3693
+ keychain = role_keychain(base, {"bot:pm": "xoxb-bot-pm", "app:pm": "xapp-bot-pm"})
3694
+ slack.identify("xoxb-bot-pm", "UBOTPM", "BBOTPM")
3695
+ benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
3696
+ repos = {}
3697
+ for name, channel in (("a", "CA"), ("b", "CB")):
3698
+ repo = mailbox_repository(base / name)
3699
+ run_keel(repo, "chat", "role", "--set", f"{name}-pm", env=env)
3700
+ run_keel(repo, "chat", "group", "create", "ops", env=env)
3701
+ chat_slack_config(repo, {"ops": channel}, bots={"UBOTPM": f"{name}-pm"})
3702
+ run_keel(repo, "chat", "bridge", "add", env=benv)
3703
+ repos[name] = repo
3704
+ added = run_keel(repos["a"], "chat", "bot", "add", "pm", env=benv)
3705
+ if added.returncode != 0:
3706
+ report(f"{label} keel chat bot add pm failed: {added.stderr.strip()}")
3707
+ return 1
3708
+ listed = run_keel(repos["a"], "chat", "bot", "list", env=benv)
3709
+ if "pm" not in listed.stdout:
3710
+ report(f"{label} keel chat bot list does not show pm: {listed.stdout.strip()} {listed.stderr.strip()}")
3711
+ return 1
3712
+ if "xoxb-bot-pm" in listed.stdout + listed.stderr:
3713
+ report(f"{label} keel chat bot list printed a token.")
3714
+ return 1
3715
+ ids = {name: chat_json(run_keel(repo, "chat", "post", "ops", f"{name} reporting", "--json", env=benv)).get("id", "") for name, repo in repos.items()}
3716
+
3717
+ bridge = start_chat_bridge(repos["a"], benv)
3718
+ try:
3719
+ if not slack.wait_for(lambda: slack.sockets_for("xapp-test-app"), 10):
3720
+ report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
3721
+ return 1
3722
+ for name, channel in (("a", "CA"), ("b", "CB")):
3723
+ if not slack.wait_for(lambda: slack_posts_of(slack, channel, ids[name])):
3724
+ report(f"{label} project {name}'s post never reached {channel}.")
3725
+ return 1
3726
+ sent = next(c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == ids[name])
3727
+ if sent.get("_auth") != "Bearer xoxb-bot-pm":
3728
+ report(f"{label} project {name}'s role did not post through the shared pm bot: {sent.get('_auth')!r}")
3729
+ return 1
3730
+ slack.push(slack_event("CA", user="UOWNER", text="<@UBOTPM> status?", ts="1800000001.000100"))
3731
+ if not slack.wait_for(lambda: chat_records_with(repos["a"], "ops", "status?")):
3732
+ report(f"{label} the owner's mention of the pm bot in CA did not reach project a.")
3733
+ return 1
3734
+ if " - a-pm" not in chat_records_with(repos["a"], "ops", "status?")[0]:
3735
+ report(f"{label} the mention in CA did not become a mention of a-pm.")
3736
+ return 1
3737
+ if chat_records_with(repos["b"], "ops", "status?"):
3738
+ report(f"{label} a mention in project a's channel reached project b.")
3739
+ return 1
3740
+ if slack.sockets_for("xapp-bot-pm"):
3741
+ report(f"{label} a bot serving two roles opened a direct-message connection.")
3742
+ return 1
3743
+ pm = bot_status(repos["a"], benv, "pm")
3744
+ if sorted(pm.get("roles") or []) != ["a/a-pm", "b/b-pm"]:
3745
+ report(f"{label} status does not list pm serving a/a-pm and b/b-pm: {pm!r}")
3746
+ return 1
3747
+ if pm.get("direct") is not False:
3748
+ report(f"{label} status does not report pm's direct messages as off: {pm!r}")
3749
+ return 1
3750
+ if "2 roles" not in str(pm.get("direct_note", "")):
3751
+ report(f"{label} status does not say why pm's direct messages are off: {pm!r}")
3752
+ return 1
3753
+ finally:
3754
+ stop_chat_bridge(bridge)
3755
+
3756
+ if "chat-shared-bots" not in {name for name, _ in SCENARIOS}:
3757
+ report(f"{label} scenario is not registered.")
3758
+ return 1
3759
+ report("chat-shared-bots scenario passed.")
3760
+ return 0
3761
+
3762
+
3675
3763
  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.
3764
+ """Issue #187: the setup guides and READMEs describe shared bots.
3677
3765
 
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.
3766
+ Both guides carry the bot section — `keel chat bot add`, the Keychain
3767
+ accounts named by bot, the `slack.bots` mapping, that one bot serves a role
3768
+ in each of several projects, and that such a bot takes no direct messages
3769
+ — and neither still ties a token to a role or equates the app limit with a
3770
+ machine count.
3682
3771
  """
3683
3772
  label = "chat-role-apps-are-documented:"
3684
3773
  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": "私聊只留在这个角色所在的电脑上",
3774
+ "docs/chat-slack-setup.md": ("serve a role in each of several projects", "takes no direct messages"),
3775
+ "docs/chat-slack-setup.zh-CN.md": ("在多个项目里各当一个角色", "不接私聊"),
3687
3776
  }
3688
- for relative, stays in guides.items():
3777
+ for relative, phrases in guides.items():
3689
3778
  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):
3779
+ for needle in ('"bots"', "keel chat bot add", "bot:<name>", "app:<name>", "chat:write.public", "im:history", *phrases):
3691
3780
  if needle not in text:
3692
3781
  report(f"{label} {relative} does not carry {needle!r}.")
3693
3782
  return 1
3694
- for stale in ("which means 10 machines", "也就是最多 10 台电脑"):
3783
+ for stale in ("bot:<role>", "which means 10 machines", "也就是最多 10 台电脑"):
3695
3784
  if stale in text:
3696
- report(f"{label} {relative} still says {stale!r}, but role apps count toward the limit too.")
3785
+ report(f"{label} {relative} still says {stale!r}.")
3697
3786
  return 1
3698
- readmes = {"README.md": "its own Slack app", "README.zh-CN.md": "自己的 Slack App"}
3787
+ readmes = {"README.md": "one bot can serve several projects", "README.zh-CN.md": "一个 bot 可以服务多个项目"}
3699
3788
  for relative, needle in readmes.items():
3700
3789
  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}.")
3790
+ report(f"{label} {relative} does not say {needle!r}.")
3702
3791
  return 1
3703
3792
  if "chat-role-apps-are-documented" not in {name for name, _ in SCENARIOS}:
3704
3793
  report(f"{label} scenario is not registered.")
@@ -36070,6 +36159,10 @@ SCENARIOS: tuple = (
36070
36159
  "chat-role-apps-are-documented",
36071
36160
  validate_chat_role_apps_are_documented_scenario,
36072
36161
  ),
36162
+ (
36163
+ "chat-shared-bots",
36164
+ validate_chat_shared_bots_scenario,
36165
+ ),
36073
36166
  (
36074
36167
  "chat-archive",
36075
36168
  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,
@@ -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 {}
@@ -736,6 +736,7 @@ function readGroups(where, role, group) {
736
736
  }
737
737
 
738
738
  module.exports = {
739
+ checkName,
739
740
  ALL,
740
741
  ChatError,
741
742
  DATA_NOTICE,