@christang/keel 5.92.0 → 5.93.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
@@ -660,8 +660,9 @@ keel agents brief codex --mode helper --dir . --out /tmp/brief.md --change <c> -
660
660
  ```
661
661
 
662
662
  `keel agents brief` compiles the same brief `keel project --event subagent-start` publishes, writes
663
- it to a file, and prints the command to run. **Keel launches nothing**; the session runs it, and
664
- re-runs every check before anything counts as evidence. It refuses:
663
+ it to a file, and prints the command to run, which writes the agent's exit status to a `.exit` file
664
+ beside its result. **Keel launches nothing**; the session runs it, and re-runs every check before
665
+ anything counts as evidence. It refuses:
665
666
 
666
667
  - an agent the project has not allowed — with no declaration, none is;
667
668
  - a Read or Touch path the project said must not leave;
@@ -686,7 +687,7 @@ the brief, so `egress_deny` guards what is handed over, not what it can open.
686
687
 
687
688
  ## Group chat between sessions
688
689
 
689
- 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: 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 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
691
 
691
692
  ## Commands
692
693
 
package/README.zh-CN.md CHANGED
@@ -198,7 +198,7 @@ keel agents brief codex --mode helper --dir . --out /tmp/brief.md --change <c> -
198
198
  ```
199
199
 
200
200
  `keel agents brief` 编译的就是 `keel project --event subagent-start` 给出的那份任务说明,写成文件,
201
- 再打印要跑的命令。**Keel 不启动任何进程**:命令由会话自己跑,对方交回的结果要由会话复跑每个检查后才算证据。
201
+ 再打印要跑的命令;这条命令会把 agent 的退出码写进结果旁边的 `.exit` 文件。**Keel 不启动任何进程**:命令由会话自己跑,对方交回的结果要由会话复跑每个检查后才算证据。
202
202
  以下情况会被拒绝:
203
203
 
204
204
  - 项目没允许的 agent(没写声明就一个都不允许);
@@ -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、跑一个桥接程序,同一批群就能实时连到其他电脑上的会话和你的手机。聊天记录同时存在孤儿分支 `keel-chat` 上,不受 Slack 保留期限制。配置方法见 [Slack 配置说明](docs/chat-slack-setup.zh-CN.md)。5.83 的 `keel mail` 命令继续可用,消息存在私聊群里。
234
+ 每台电脑配一个 Slack App、跑一个桥接程序,同一批群就能实时连到其他电脑上的会话和你的手机;某个角色也可以有自己的 Slack App,这样在 Slack 里能直接 @ 它、和它私聊。聊天记录同时存在孤儿分支 `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.92.0 -->
1
+ <!-- keel:start version=5.93.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.92.0",
3
+ "version": "5.93.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.92.0",
9
+ "version": "5.93.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.92.0",
5
+ "version": "5.93.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.92.0",
3
+ "version": "5.93.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.92.0",
3
+ "version": "5.93.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",
@@ -58,6 +58,15 @@ class FakeSlack:
58
58
  self.sockets: list[socket.socket] = []
59
59
  self.acks: list[str] = []
60
60
  self.connections_opened = 0
61
+ # A token's identity, as `auth.test` and its posts report it. A token
62
+ # not listed is the shared app's bot.
63
+ self.identities: dict[str, dict] = {}
64
+ # (token, channel) pairs `chat.postMessage` answers with
65
+ # `not_in_channel`, for a bot nobody invited.
66
+ self.not_in_channel: set[tuple[str, str]] = set()
67
+ # Which app token each Socket Mode connection was opened with.
68
+ self.socket_apps: dict[socket.socket, str] = {}
69
+ self.pending_apps: dict[str, str] = {}
61
70
  self.server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())
62
71
  self.port = self.server.server_address[1]
63
72
  self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
@@ -95,13 +104,22 @@ class FakeSlack:
95
104
  self.messages.setdefault(channel, []).append(stored)
96
105
  return stored
97
106
 
98
- def push(self, payload: dict, kind: str = "events_api") -> str:
99
- """Send one Socket Mode envelope to every connected client."""
107
+ def identify(self, token: str, user_id: str, bot_id: str) -> None:
108
+ """Make `token` a bot of its own, as a role's app is."""
109
+ with self.lock:
110
+ self.identities[token] = {"user_id": user_id, "bot_id": bot_id}
111
+
112
+ def push(self, payload: dict, kind: str = "events_api", app: str | None = None) -> str:
113
+ """Send one Socket Mode envelope to every connected client, or only to
114
+ the connections opened with app token `app`."""
100
115
  with self.lock:
101
116
  envelope_id = f"env-{self._ts()}"
102
- self._broadcast(json.dumps({"envelope_id": envelope_id, "type": kind, "payload": payload, "accepts_response_payload": False}))
117
+ self._broadcast(json.dumps({"envelope_id": envelope_id, "type": kind, "payload": payload, "accepts_response_payload": False}), app)
103
118
  return envelope_id
104
119
 
120
+ def sockets_for(self, app: str) -> list[socket.socket]:
121
+ return [sock for sock in list(self.sockets) if self.socket_apps.get(sock) == app]
122
+
105
123
  def push_raw(self, message: dict) -> None:
106
124
  self._broadcast(json.dumps(message))
107
125
 
@@ -132,9 +150,11 @@ class FakeSlack:
132
150
  self.next_ts += 1
133
151
  return f"{self.next_ts}.000100"
134
152
 
135
- def _broadcast(self, text: str) -> None:
153
+ def _broadcast(self, text: str, app: str | None = None) -> None:
136
154
  frame = ws_frame(text)
137
155
  for sock in list(self.sockets):
156
+ if app is not None and self.socket_apps.get(sock) != app:
157
+ continue
138
158
  try:
139
159
  sock.sendall(frame)
140
160
  except OSError:
@@ -148,11 +168,19 @@ class FakeSlack:
148
168
  self.calls.append({"method": method, "params": params, "rate_limited": True, "at": time.time()})
149
169
  return 429, {"Retry-After": str(retry_after)}, {"ok": False, "error": "ratelimited"}
150
170
  self.calls.append({"method": method, "params": params, "at": time.time()})
171
+ token = str(params.get("_auth", "")).removeprefix("Bearer ")
172
+ identity = self.identities.get(token, {"user_id": "UBOT", "bot_id": "BBOT"})
151
173
  if method == "auth.test":
152
- return 200, {}, {"ok": True, "user_id": "UBOT", "bot_id": "BBOT", "team_id": "T1"}
174
+ return 200, {}, {"ok": True, **identity, "team_id": "T1"}
153
175
  if method == "apps.connections.open":
154
176
  self.connections_opened += 1
155
- return 200, {}, {"ok": True, "url": f"ws://127.0.0.1:{self.port}/socket"}
177
+ key = f"c{self.connections_opened}"
178
+ self.pending_apps[key] = token
179
+ return 200, {}, {"ok": True, "url": f"ws://127.0.0.1:{self.port}/socket?app={key}"}
180
+ if method == "conversations.open":
181
+ return 200, {}, {"ok": True, "channel": {"id": f"D{params.get('users', '')}"}}
182
+ if method == "chat.postMessage" and (token, params.get("channel", "")) in self.not_in_channel:
183
+ return 200, {}, {"ok": False, "error": "not_in_channel"}
156
184
  if method == "chat.postMessage":
157
185
  metadata = params.get("metadata")
158
186
  if isinstance(metadata, str):
@@ -162,7 +190,7 @@ class FakeSlack:
162
190
  "type": "message",
163
191
  "text": params.get("text", ""),
164
192
  "username": params.get("username"),
165
- "bot_id": "BBOT",
193
+ "bot_id": identity["bot_id"],
166
194
  "metadata": metadata,
167
195
  }
168
196
  if params.get("thread_ts"):
@@ -238,6 +266,8 @@ class FakeSlack:
238
266
  except OSError:
239
267
  return
240
268
  fake.sockets.append(sock)
269
+ key = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query).get("app", [""])[0]
270
+ fake.socket_apps[sock] = fake.pending_apps.get(key, "")
241
271
  self.close_connection = True
242
272
  self._read_frames(sock)
243
273
 
@@ -47,8 +47,8 @@ REQUIRED_SCRIPTS = [
47
47
  "scripts/validate_plugin.py",
48
48
  ]
49
49
 
50
- PACKAGE_VERSION = "5.92.0"
51
- PROTOCOL_VERSION = "5.92.0"
50
+ PACKAGE_VERSION = "5.93.0"
51
+ PROTOCOL_VERSION = "5.93.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
@@ -3421,6 +3421,292 @@ def validate_chat_bridge_inbound_scenario() -> int:
3421
3421
  return 0
3422
3422
 
3423
3423
 
3424
+ def role_keychain(base: Path, tokens: dict[str, str]) -> Path:
3425
+ """A `security` double answering only the given Keychain accounts."""
3426
+ script = base / "role-keychain.sh"
3427
+ cases = "".join(f' *"-a {account} "*|*"-a {account}") echo {token} ;;\n' for account, token in tokens.items())
3428
+ write_text(script, f'#!/bin/sh\ncase "$* " in\n{cases} *) exit 44 ;;\nesac\n')
3429
+ script.chmod(0o755)
3430
+ return script
3431
+
3432
+
3433
+ def slack_posts_of(slack, channel: str, record_id: str) -> list[dict]:
3434
+ return [m for m in slack.messages.get(channel, []) if (m.get("metadata") or {}).get("event_payload", {}).get("id") == record_id]
3435
+
3436
+
3437
+ def role_status(cwd: Path, env: dict[str, str], role: str) -> dict:
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), {})
3440
+
3441
+
3442
+ def validate_chat_role_apps_scenario() -> int:
3443
+ """Issue #187: a role may post under its own Slack app.
3444
+
3445
+ `slack.bots` registers a role's bot by its user id. A role whose Keychain
3446
+ token `auth.test` confirms posts with that token and without a borrowed
3447
+ name; a token for another bot is not used; a channel the role's bot is not
3448
+ in falls back to the shared app; a person's mention of a role's bot wakes
3449
+ the role; and the bridge's own edits through a role app are not imported
3450
+ back as someone else's.
3451
+ """
3452
+ label = "chat-role-apps:"
3453
+ if chat_bridge_node_missing("chat-role-apps"):
3454
+ return 3
3455
+ FakeSlack = fake_slack_class()
3456
+ with tempfile.TemporaryDirectory(prefix="keel-chat-roles-") as raw, FakeSlack() as slack:
3457
+ base = Path(raw)
3458
+ rtl, verify, env = chat_scratch_group(base)
3459
+ chat_slack_config(rtl, {"soc": "CSOC"}, bots={"UBOTRTL": "rtl", "UBOTVERIFY": "verify"})
3460
+ keychain = role_keychain(base, {"bot:rtl": "xoxb-role-rtl"})
3461
+ slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
3462
+ benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
3463
+
3464
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3465
+ return run_keel(cwd, "chat", *args, env=benv)
3466
+
3467
+ def once() -> bool:
3468
+ result = chat(rtl, "bridge", "run", "--once")
3469
+ if result.returncode != 0:
3470
+ report(f"{label} bridge run --once failed: {result.stderr.strip()} {result.stdout.strip()}")
3471
+ return result.returncode == 0
3472
+
3473
+ chat(rtl, "bridge", "add")
3474
+ own_id = chat_json(chat(rtl, "post", "soc", "rtl speaks", "--json")).get("id", "")
3475
+ shared_id = chat_json(chat(verify, "post", "soc", "verify speaks", "--json")).get("id", "")
3476
+ chat(rtl, "edit", own_id, "rtl speaks (v2)")
3477
+ if not once():
3478
+ return 1
3479
+ by_id = {slack_payload(c).get("id"): c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id")}
3480
+ own = by_id.get(own_id) or {}
3481
+ if own.get("_auth") != "Bearer xoxb-role-rtl":
3482
+ report(f"{label} rtl's post did not use rtl's own app token: {own.get('_auth')!r}")
3483
+ return 1
3484
+ if own.get("username"):
3485
+ report(f"{label} rtl's post through its own app still borrows a name: {own.get('username')!r}")
3486
+ return 1
3487
+ other = by_id.get(shared_id) or {}
3488
+ if other.get("_auth") != "Bearer xoxb-test-bot":
3489
+ report(f"{label} verify, registered but without a token here, did not post through the shared app: {other.get('_auth')!r}")
3490
+ return 1
3491
+ if other.get("username") != "verify":
3492
+ report(f"{label} verify's post through the shared app is not under its name: {other.get('username')!r}")
3493
+ return 1
3494
+ own_ts = (slack_posts_of(slack, "CSOC", own_id) or [{}])[0].get("ts")
3495
+ updates = [c["params"] for c in slack.calls_to("chat.update") if c["params"].get("ts") == own_ts]
3496
+ if not updates:
3497
+ report(f"{label} the edit of rtl's record never called chat.update.")
3498
+ return 1
3499
+ if updates[0].get("_auth") != "Bearer xoxb-role-rtl":
3500
+ report(f"{label} the edit of rtl's record did not use the app that posted it: {updates[0].get('_auth')!r}")
3501
+ 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}")
3504
+ return 1
3505
+ if role_status(rtl, benv, "verify"):
3506
+ report(f"{label} status lists verify, which has no token on this machine.")
3507
+ return 1
3508
+
3509
+ slack.identify("xoxb-role-rtl", "UOTHER", "BOTHER")
3510
+ wrong_id = chat_json(chat(rtl, "post", "soc", "after a token swap", "--json")).get("id", "")
3511
+ if not once():
3512
+ return 1
3513
+ wrong = next((c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == wrong_id), {})
3514
+ if wrong.get("_auth") != "Bearer xoxb-test-bot":
3515
+ report(f"{label} a token whose auth.test names another bot was used for rtl: {wrong.get('_auth')!r}")
3516
+ return 1
3517
+ if wrong.get("username") != "rtl":
3518
+ report(f"{label} the fallback post is not under rtl's name: {wrong.get('username')!r}")
3519
+ 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}")
3522
+ return 1
3523
+
3524
+ slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
3525
+ slack.not_in_channel.add(("xoxb-role-rtl", "CSOC"))
3526
+ out_id = chat_json(chat(rtl, "post", "soc", "nobody invited me", "--json")).get("id", "")
3527
+ if not once():
3528
+ return 1
3529
+ landed = slack_posts_of(slack, "CSOC", out_id)
3530
+ if len(landed) != 1:
3531
+ report(f"{label} a post refused with not_in_channel landed {len(landed)} times, not once.")
3532
+ return 1
3533
+ if landed[0].get("username") != "rtl":
3534
+ report(f"{label} the not_in_channel fallback is not under rtl's name: {landed[0]!r}")
3535
+ 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}")
3538
+ return 1
3539
+ slack.not_in_channel.clear()
3540
+
3541
+ bridge = start_chat_bridge(rtl, benv)
3542
+ try:
3543
+ if not slack.wait_for(lambda: slack.sockets, 10):
3544
+ report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
3545
+ return 1
3546
+ slack.push(slack_event("CSOC", user="UOWNER", text="<@UBOTVERIFY> rerun please", ts="1800000001.000100"))
3547
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "rerun please")):
3548
+ report(f"{label} the owner's message mentioning a role's bot was not imported.")
3549
+ return 1
3550
+ mention = chat_records_with(rtl, "soc", "rerun please")[0]
3551
+ if "@verify rerun please" not in mention:
3552
+ report(f"{label} the bot mention was not rewritten to the role:\n{mention}")
3553
+ return 1
3554
+ if " - verify" not in mention:
3555
+ report(f"{label} the bot mention did not become a mention of verify:\n{mention}")
3556
+ return 1
3557
+ slack.push(slack_event("CSOC", subtype="message_changed", message={"ts": own_ts, "bot_id": "BROLERTL", "text": "rewritten by an echo"}, ts="1800000002.000100"))
3558
+ slack.push(slack_event("CSOC", user="UOWNER", text="marker after the echo", ts="1800000003.000100"))
3559
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "marker after the echo")):
3560
+ report(f"{label} the marker message after the echo was not imported.")
3561
+ return 1
3562
+ if chat_records_with(rtl, "soc", "rewritten by an echo"):
3563
+ report(f"{label} the bridge's own edit through rtl's app was imported back as an edit.")
3564
+ return 1
3565
+ finally:
3566
+ stop_chat_bridge(bridge)
3567
+
3568
+ if "chat-role-apps" not in {name for name, _ in SCENARIOS}:
3569
+ report(f"{label} scenario is not registered.")
3570
+ return 1
3571
+ report("chat-role-apps scenario passed.")
3572
+ return 0
3573
+
3574
+
3575
+ def validate_chat_role_direct_scenario() -> int:
3576
+ """Issue #187: a role's own app takes direct messages.
3577
+
3578
+ With `app:<role>` beside `bot:<role>`, the bridge opens a second Socket
3579
+ Mode connection for that app. A registered person's direct message becomes
3580
+ a record in the direct group and wakes the role; the role's answer goes
3581
+ back to that person's direct-message channel and nowhere else; a
3582
+ stranger's is ignored; and one sent while the bridge was down arrives once.
3583
+ """
3584
+ label = "chat-role-direct:"
3585
+ if chat_bridge_node_missing("chat-role-direct"):
3586
+ return 3
3587
+ FakeSlack = fake_slack_class()
3588
+ with tempfile.TemporaryDirectory(prefix="keel-chat-direct-") as raw, FakeSlack() as slack:
3589
+ base = Path(raw)
3590
+ rtl, _verify, env = chat_scratch_group(base)
3591
+ chat_slack_config(rtl, {"soc": "CSOC"}, bots={"UBOTRTL": "rtl"})
3592
+ keychain = role_keychain(base, {"bot:rtl": "xoxb-role-rtl", "app:rtl": "xapp-role-rtl"})
3593
+ slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
3594
+ benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
3595
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
3596
+ signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "rtl"
3597
+
3598
+ def direct(user: str, text: str, ts: str) -> dict:
3599
+ return slack_event("DUOWNER" if user == "UOWNER" else f"D{user}", channel_type="im", user=user, text=text, ts=ts)
3600
+
3601
+ bridge = start_chat_bridge(rtl, benv)
3602
+ try:
3603
+ if not slack.wait_for(lambda: slack.sockets_for("xapp-role-rtl"), 10):
3604
+ report(f"{label} the bridge opened no Socket Mode connection with rtl's app token: {stop_chat_bridge(bridge).strip()}")
3605
+ return 1
3606
+ if not slack.wait_for(lambda: slack.sockets_for("xapp-test-app"), 10):
3607
+ report(f"{label} the shared app's connection is missing beside rtl's.")
3608
+ return 1
3609
+ size = signal.stat().st_size if signal.exists() else 0
3610
+ slack.push(direct("UOWNER", "status?", "1800000001.000100"), app="xapp-role-rtl")
3611
+ if not slack.wait_for(lambda: chat_records_with(rtl, "dm-owner--rtl", "status?")):
3612
+ report(f"{label} the owner's direct message to rtl's app did not reach dm-owner--rtl.")
3613
+ return 1
3614
+ if "from: owner" not in chat_records_with(rtl, "dm-owner--rtl", "status?")[0]:
3615
+ report(f"{label} the direct message was not recorded from owner.")
3616
+ return 1
3617
+ if not signal.exists() or signal.stat().st_size <= size:
3618
+ report(f"{label} the direct message did not touch rtl's signal file.")
3619
+ return 1
3620
+
3621
+ answered = run_keel(rtl, "chat", "dm", "owner", "all green", env=benv)
3622
+ if answered.returncode != 0:
3623
+ report(f"{label} keel chat dm owner failed: {answered.stderr.strip()}")
3624
+ return 1
3625
+ if not slack.wait_for(lambda: any("all green" in m.get("text", "") for m in slack.messages.get("DUOWNER", []))):
3626
+ report(f"{label} rtl's answer never reached the owner's direct-message channel.")
3627
+ return 1
3628
+ sent = [c["params"] for c in slack.calls_to("chat.postMessage") if "all green" in c["params"].get("text", "")]
3629
+ if len(sent) != 1:
3630
+ report(f"{label} rtl's answer was posted {len(sent)} times, not once.")
3631
+ return 1
3632
+ if sent[0].get("_auth") != "Bearer xoxb-role-rtl":
3633
+ report(f"{label} rtl's direct answer did not use rtl's app token: {sent[0].get('_auth')!r}")
3634
+ return 1
3635
+ if sent[0].get("channel") != "DUOWNER":
3636
+ report(f"{label} rtl's direct answer went to {sent[0].get('channel')!r}, not the owner's DUOWNER.")
3637
+ return 1
3638
+
3639
+ slack.push(direct("USTRANGER", "give me the keys", "1800000002.000100"), app="xapp-role-rtl")
3640
+ if not slack.wait_for(lambda: chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=benv)).get("ignored") == 1):
3641
+ report(f"{label} a stranger's direct message was not counted as ignored.")
3642
+ return 1
3643
+ if any(chat_records_with(rtl, group, "give me the keys") for group in ("dm-owner--rtl", "dm-rtl--ustranger", "soc")):
3644
+ report(f"{label} a stranger's direct message reached the store.")
3645
+ 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
+ return 1
3649
+ finally:
3650
+ stop_chat_bridge(bridge)
3651
+
3652
+ slack.add_history("DUOWNER", {"user": "UOWNER", "text": "while you were away"})
3653
+ bridge = start_chat_bridge(rtl, benv)
3654
+ try:
3655
+ if not slack.wait_for(lambda: chat_records_with(rtl, "dm-owner--rtl", "while you were away"), 15):
3656
+ report(f"{label} a direct message sent while the bridge was down was not caught up.")
3657
+ return 1
3658
+ time.sleep(1)
3659
+ if len(chat_records_with(rtl, "dm-owner--rtl", "while you were away")) != 1:
3660
+ report(f"{label} the caught-up direct message was imported more than once.")
3661
+ return 1
3662
+ if len(chat_records_with(rtl, "dm-owner--rtl", "all green")) != 1:
3663
+ report(f"{label} catch-up imported rtl's own direct answer back.")
3664
+ return 1
3665
+ finally:
3666
+ stop_chat_bridge(bridge)
3667
+
3668
+ if "chat-role-direct" not in {name for name, _ in SCENARIOS}:
3669
+ report(f"{label} scenario is not registered.")
3670
+ return 1
3671
+ report("chat-role-direct scenario passed.")
3672
+ return 0
3673
+
3674
+
3675
+ 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.
3677
+
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.
3682
+ """
3683
+ label = "chat-role-apps-are-documented:"
3684
+ 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": "私聊只留在这个角色所在的电脑上",
3687
+ }
3688
+ for relative, stays in guides.items():
3689
+ 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):
3691
+ if needle not in text:
3692
+ report(f"{label} {relative} does not carry {needle!r}.")
3693
+ return 1
3694
+ for stale in ("which means 10 machines", "也就是最多 10 台电脑"):
3695
+ if stale in text:
3696
+ report(f"{label} {relative} still says {stale!r}, but role apps count toward the limit too.")
3697
+ return 1
3698
+ readmes = {"README.md": "its own Slack app", "README.zh-CN.md": "自己的 Slack App"}
3699
+ for relative, needle in readmes.items():
3700
+ 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}.")
3702
+ return 1
3703
+ if "chat-role-apps-are-documented" not in {name for name, _ in SCENARIOS}:
3704
+ report(f"{label} scenario is not registered.")
3705
+ return 1
3706
+ report("chat-role-apps-are-documented scenario passed.")
3707
+ return 0
3708
+
3709
+
3424
3710
  def validate_chat_bridge_lifecycle_scenario() -> int:
3425
3711
  """Issue #187: the bridge runs unattended but stays visible and controllable.
3426
3712
 
@@ -35620,6 +35906,82 @@ def validate_external_agents_are_documented_scenario() -> int:
35620
35906
  return 0
35621
35907
 
35622
35908
 
35909
+ def validate_external_agent_exit_status_scenario() -> int:
35910
+ """The printed command records the agent's exit status (#221).
35911
+
35912
+ Of nine codex runs read in rtl_ppa_prj, one recorded its exit status; a run
35913
+ that finished with `exit=0` read as a failure because it left no result
35914
+ file. The status is the one signal that is not the agent's own report.
35915
+ """
35916
+ label = "external-agent-exit-status:"
35917
+ with tempfile.TemporaryDirectory(prefix="keel-agent-exit-") as raw:
35918
+ base = Path(raw).resolve()
35919
+ env, _calls = _external_agents_env(base)
35920
+ for name in ("codex", "dsh"):
35921
+ stub = base / "bin" / name
35922
+ stub.write_text("#!/bin/sh\ncat > /dev/null\nexit 3\n", encoding="utf-8")
35923
+ stub.chmod(0o755)
35924
+ (base / "home" / "agents.json").write_text(
35925
+ json.dumps({"agents": {"dsh": {"executable": str(base / "bin" / "dsh")}}}),
35926
+ encoding="utf-8")
35927
+ repo = base / "repo"
35928
+ repo.mkdir()
35929
+ write_gate_fixture(repo, external_agent_brief_task())
35930
+ write_text(repo / "src/feature.js", "// feature\n")
35931
+ write_authorize_config(repo, "external_agents:\n allow: [codex, dsh]\n")
35932
+ for command in (["init", "-q"], ["add", "-A"],
35933
+ ["-c", "user.email=k@example.com", "-c", "user.name=k",
35934
+ "commit", "-q", "-m", "fixture"]):
35935
+ subprocess.run(["git", *command], cwd=repo, check=True, capture_output=True)
35936
+ worktree = base / "agent-wt"
35937
+ subprocess.run(["git", "worktree", "add", "-q", "--detach", str(worktree)],
35938
+ cwd=repo, check=True, capture_output=True)
35939
+
35940
+ for name, directory in (("codex", repo), ("dsh", worktree)):
35941
+ prompt = base / f"{name}-brief.md"
35942
+ result = run_keel(repo, "agents", "brief", name, "--mode", "helper",
35943
+ "--dir", str(directory), "--out", str(prompt),
35944
+ "--change", "demo", "--task", "1.1", "--json", env=env)
35945
+ try:
35946
+ payload = json.loads(result.stdout)
35947
+ except json.JSONDecodeError:
35948
+ report(f"{label} {name} brief printed no JSON: {(result.stdout + result.stderr)[:400]}")
35949
+ return 1
35950
+ if payload.get("status") != "ready":
35951
+ report(f"{label} {name} brief was refused: {payload.get('reasons')}")
35952
+ return 1
35953
+ exit_file = payload.get("exit")
35954
+ if not exit_file:
35955
+ report(f"{label} the {name} brief names no exit file.")
35956
+ return 1
35957
+ text = run_keel(repo, "agents", "brief", name, "--mode", "helper",
35958
+ "--dir", str(directory), "--out", str(prompt),
35959
+ "--change", "demo", "--task", "1.1", env=env).stdout
35960
+ if exit_file not in text:
35961
+ report(f"{label} the {name} text output does not name the exit file {exit_file}.")
35962
+ return 1
35963
+ ran = subprocess.run(["sh", "-c", f"{payload['run']}\npwd"], cwd=base, env=env,
35964
+ capture_output=True, text=True)
35965
+ if not Path(exit_file).exists():
35966
+ report(f"{label} running the {name} command wrote no exit file: {ran.stderr[:300]}")
35967
+ return 1
35968
+ status = Path(exit_file).read_text(encoding="utf-8").strip()
35969
+ if status != "3":
35970
+ report(f"{label} the {name} exit file holds {status!r}, not the stub's 3.")
35971
+ return 1
35972
+ if ran.stdout.strip().splitlines()[-1:] != [str(base)]:
35973
+ report(f"{label} running the {name} command moved the shell to {ran.stdout.strip()!r}.")
35974
+ return 1
35975
+
35976
+ shown = run_keel(repo, "agents", "codex", env=env).stdout
35977
+ if not re.search(r"parallel[^\n]*quota", shown, re.I):
35978
+ report(f"{label} `keel agents codex` has no pitfall about parallel runs sharing one quota.")
35979
+ return 1
35980
+
35981
+ report("external-agent-exit-status scenario passed.")
35982
+ return 0
35983
+
35984
+
35623
35985
  SCENARIOS: tuple = (
35624
35986
  ("stateless-continuity", validate_stateless_continuity_scenario),
35625
35987
  ("core-gates", validate_core_gates_scenario),
@@ -35696,6 +36058,18 @@ SCENARIOS: tuple = (
35696
36058
  "chat-bridge-lifecycle",
35697
36059
  validate_chat_bridge_lifecycle_scenario,
35698
36060
  ),
36061
+ (
36062
+ "chat-role-apps",
36063
+ validate_chat_role_apps_scenario,
36064
+ ),
36065
+ (
36066
+ "chat-role-direct",
36067
+ validate_chat_role_direct_scenario,
36068
+ ),
36069
+ (
36070
+ "chat-role-apps-are-documented",
36071
+ validate_chat_role_apps_are_documented_scenario,
36072
+ ),
35699
36073
  (
35700
36074
  "chat-archive",
35701
36075
  validate_chat_archive_scenario,
@@ -36067,6 +36441,7 @@ SCENARIOS: tuple = (
36067
36441
  ("external-agent-catalog", validate_external_agent_catalog_scenario),
36068
36442
  ("external-agent-brief", validate_external_agent_brief_scenario),
36069
36443
  ("external-agents-are-documented", validate_external_agents_are_documented_scenario),
36444
+ ("external-agent-exit-status", validate_external_agent_exit_status_scenario),
36070
36445
  ("validation-runner", validate_validation_runner_scenario),
36071
36446
  ("section-boundary", validate_section_boundary_scenario),
36072
36447
  ("review-entry-extent", validate_review_entry_extent_scenario),
@@ -47,6 +47,11 @@ const BUNDLED = {
47
47
  source: RTL_TOOLCHAIN,
48
48
  text: "It has a usage quota. When the quota is hit it names the time it can retry.",
49
49
  },
50
+ {
51
+ date: "2026-10-04",
52
+ source: "https://github.com/TanglmChris/keel/issues/221",
53
+ text: "Parallel runs under one account share one quota. Four runs started together and three stopped on the usage limit within five minutes, leaving half-done work in their worktrees.",
54
+ },
50
55
  {
51
56
  date: "2026-10-02",
52
57
  source: "https://github.com/TanglmChris/keel/issues/194",
@@ -70,6 +75,11 @@ const BUNDLED = {
70
75
  source: "dsh --version, 0.2.0-rc.2",
71
76
  text: "The CLI lives inside the app bundle and is not on PATH.",
72
77
  },
78
+ {
79
+ date: "2026-10-05",
80
+ source: "dsh --profile headless, 0.2.0-rc.2",
81
+ text: "The headless profile fails with MISSING_CREDENTIAL until a DeepSeek API key is stored through the app's Models page or DEEPSEEK_API_KEY is exported where it is launched.",
82
+ },
73
83
  {
74
84
  date: "2026-10-04",
75
85
  source: "dsh headless --help, 0.2.0-rc.2",
@@ -478,13 +488,18 @@ function compileBrief(repo, options) {
478
488
  fs.writeFileSync(out, renderBrief({
479
489
  agent: entry, mode: options.mode, dir, projection, source: projected.source, result,
480
490
  }));
481
- const run = fillCommand(entry.command, {
491
+ // A subshell, so a `cd` in a template does not move the caller, and the exit
492
+ // status beside the result, because it is the one account of how the run
493
+ // ended that is not the agent's own report (#221).
494
+ const exit = `${result.replace(/\.md$/, "")}.exit`;
495
+ const filled = fillCommand(entry.command, {
482
496
  executable: resolveExecutable(entry.executable) || entry.executable,
483
497
  sandbox: entry.sandbox[options.mode] || "",
484
498
  dir,
485
499
  prompt: out,
486
500
  out: result,
487
501
  });
502
+ const run = `( ${filled} ); echo $? > ${shellQuote(exit)}`;
488
503
  return {
489
504
  schemaVersion: 1,
490
505
  command: "agents brief",
@@ -493,6 +508,7 @@ function compileBrief(repo, options) {
493
508
  mode: options.mode,
494
509
  prompt: out,
495
510
  result,
511
+ exit,
496
512
  run,
497
513
  source: projected.source,
498
514
  reasons: [],
@@ -528,7 +544,7 @@ function runBrief(argv) {
528
544
  if (json) process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
529
545
  else if (payload.status === "ready") {
530
546
  process.stdout.write(
531
- `Brief: ${payload.prompt}\nRun: ${payload.run}\n`
547
+ `Brief: ${payload.prompt}\nRun: ${payload.run}\nExit status: written to ${payload.exit}\n`
532
548
  + payload.warnings.map((item) => `Warning: ${item}\n`).join("")
533
549
  );
534
550
  } else {
@@ -161,9 +161,17 @@ function iconFields(project, role) {
161
161
  return icon.startsWith(":") ? { icon_emoji: icon } : { icon_url: icon };
162
162
  }
163
163
 
164
- async function postRecord(ctx, project, record, channel) {
164
+ // The verified app of `role` that `project` registered, or null: the role
165
+ // then speaks through the shared app (chat-role-apps D3).
166
+ 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;
170
+ }
171
+
172
+ async function postRecord(ctx, project, record, channel, direct = null) {
165
173
  const { where } = project;
166
- const call = (method, params) => slack.callWithRetry(method, params, ctx.token, {
174
+ const call = (method, params, token = ctx.token) => slack.callWithRetry(method, params, token, {
167
175
  onWait: (name, seconds) => ctx.log(`Slack asked to wait ${seconds}s before ${name}.`),
168
176
  });
169
177
  if (record.kind === "done" || record.kind === "edit" || record.kind === "retract") {
@@ -175,12 +183,19 @@ async function postRecord(ctx, project, record, channel) {
175
183
  return;
176
184
  }
177
185
  if (record.kind === "done") {
178
- await call("reactions.add", { channel: target.channel, timestamp: target.ts, name: "white_check_mark" });
179
- } else if (record.kind === "edit") {
180
- const original = store.findRecord(where, record.target) || {};
181
- await call("chat.update", { channel: target.channel, ts: target.ts, text: slackText(project, original, bodyText({ ...original, text: record.text })) });
186
+ // The shared app is not in a role's direct-message channel.
187
+ const poster = target.direct && target.as ? roleApp(ctx, project, target.as) : null;
188
+ await call("reactions.add", { channel: target.channel, timestamp: target.ts, name: "white_check_mark" }, poster ? poster.token : ctx.token);
182
189
  } else {
183
- await call("chat.delete", { channel: target.channel, ts: target.ts });
190
+ // Slack lets only the app that posted a message change it (D4).
191
+ const poster = target.as ? roleApp(ctx, project, target.as) : null;
192
+ const token = poster ? poster.token : ctx.token;
193
+ if (record.kind === "edit") {
194
+ const original = store.findRecord(where, record.target) || {};
195
+ await call("chat.update", { channel: target.channel, ts: target.ts, text: slackText(project, original, bodyText({ ...original, text: record.text })) }, token);
196
+ } else {
197
+ await call("chat.delete", { channel: target.channel, ts: target.ts }, token);
198
+ }
184
199
  }
185
200
  writePosted(where, record.id, { channel: target.channel, ts: target.ts, kind: record.kind });
186
201
  return;
@@ -198,8 +213,38 @@ async function postRecord(ctx, project, record, channel) {
198
213
  if (parent && parent.ts) params.thread_ts = parent.thread_ts || parent.ts;
199
214
  else params.text = `↳ reply to ${record.reply_to}\n${params.text}`;
200
215
  }
201
- const response = await call("chat.postMessage", params);
216
+ if (direct) {
217
+ // A direct group goes to the person's direct-message channel, only ever
218
+ // through the role's own app (D6).
219
+ delete params.username;
220
+ delete params.icon_emoji;
221
+ delete params.icon_url;
222
+ const sent = await call("chat.postMessage", params, direct.token);
223
+ writePosted(where, record.id, { channel, ts: sent.ts, thread_ts: params.thread_ts || null, as: direct.role, direct: true });
224
+ rememberTs(project, channel, sent.ts, record.id);
225
+ return;
226
+ }
227
+ const app = roleApp(ctx, project, record.from);
228
+ let response = null;
229
+ let as = null;
230
+ if (app) {
231
+ const own = { ...params };
232
+ delete own.username;
233
+ delete own.icon_emoji;
234
+ delete own.icon_url;
235
+ try {
236
+ response = await call("chat.postMessage", own, app.token);
237
+ as = record.from;
238
+ } catch (error) {
239
+ // A private channel nobody invited the role's bot to: the record goes
240
+ // out through the shared app, and status says where to invite it (D4).
241
+ if (!(error instanceof slack.SlackError) || error.error !== "not_in_channel") throw error;
242
+ app.invite.add(channel);
243
+ }
244
+ }
245
+ if (!response) response = await call("chat.postMessage", params);
202
246
  const posted = { channel, ts: response.ts, thread_ts: params.thread_ts || null };
247
+ if (as) posted.as = as;
203
248
  writePosted(where, record.id, posted);
204
249
  rememberTs(project, channel, response.ts, record.id);
205
250
  // Another project on this machine that maps the same channel gets the
@@ -222,14 +267,51 @@ function pendingOutbound(project) {
222
267
  pending.push({ record, channel });
223
268
  }
224
269
  }
270
+ for (const { app, user, group } of directGroups(project)) {
271
+ for (const record of store.readLog(where, group)) {
272
+ if (!OUTBOUND_ORIGINS.has(record.origin || "local") || record.from !== app.role || !DIRECT_KINDS.has(record.kind)) continue;
273
+ if (readPosted(where, record.id)) continue;
274
+ pending.push({ record, channel: null, direct: { app, user } });
275
+ }
276
+ }
225
277
  return pending.sort((a, b) => (a.record.id < b.record.id ? -1 : 1));
226
278
  }
227
279
 
280
+ const DIRECT_KINDS = new Set(["message", "todo", "done", "edit", "retract"]);
281
+
282
+ // Role apps that take direct messages: verified, with an app-level token (D6).
283
+ function directApps(ctx) {
284
+ return [...(ctx.roles || new Map()).values()].filter((app) => app.state === "verified" && app.appToken);
285
+ }
286
+
287
+ // Each direct group between a registered person and a role whose app takes
288
+ // direct messages for this project.
289
+ function directGroups(project) {
290
+ const result = [];
291
+ for (const app of project.directApps || []) {
292
+ for (const [user, person] of Object.entries(project.settings.members)) {
293
+ if (person === app.role) continue;
294
+ const group = store.directName(person, app.role);
295
+ result.push({ app, user, person, group });
296
+ }
297
+ }
298
+ return result;
299
+ }
300
+
301
+ async function imChannel(ctx, app, user) {
302
+ if (!app.ims.has(user)) {
303
+ const opened = await slack.callWithRetry("conversations.open", { users: user }, app.token);
304
+ app.ims.set(user, opened.channel && opened.channel.id);
305
+ }
306
+ return app.ims.get(user);
307
+ }
308
+
228
309
  async function flushOutbound(ctx) {
229
310
  let posted = 0;
230
311
  for (const project of ctx.projects) {
231
- for (const { record, channel } of pendingOutbound(project)) {
232
- await postRecord(ctx, project, record, channel);
312
+ for (const { record, channel, direct } of pendingOutbound(project)) {
313
+ if (direct) await postRecord(ctx, project, record, await imChannel(ctx, direct.app, direct.user), direct.app);
314
+ else await postRecord(ctx, project, record, channel);
233
315
  posted += 1;
234
316
  }
235
317
  }
@@ -323,12 +405,13 @@ async function handleBotMessage(ctx, channel, event) {
323
405
  // This bridge's own posts without a record — its online and stopped
324
406
  // notices — carry nothing to import.
325
407
  if (event.bot_id && event.bot_id === ctx.self.bot_id && !event.metadata) return;
408
+ const own = ctx.ownBots.has(event.bot_id);
326
409
  const metadata = await metadataOf(ctx, channel, event);
327
410
  if (!metadata || metadata.event_type !== METADATA_TYPE) return;
328
411
  const payload = metadata.event_payload || {};
329
412
  for (const project of projectsFor(ctx, channel)) {
330
413
  // This bridge's own post, for this project, is already the local record.
331
- if (event.bot_id === ctx.self.bot_id && payload.project === project.where.project) continue;
414
+ if (own && payload.project === project.where.project) continue;
332
415
  importKeelRecord(ctx, project, channel, payload, event);
333
416
  }
334
417
  }
@@ -353,7 +436,7 @@ function lenientMentions(project, group, text) {
353
436
 
354
437
  function humanText(project, event) {
355
438
  let text = String(event.text || "").replace(/<@([A-Z0-9]+)(\|[^>]*)?>/g, (match, user) => {
356
- const role = project.settings.members[user];
439
+ const role = project.settings.members[user] || project.settings.bots[user];
357
440
  return role ? `@${role}` : match;
358
441
  });
359
442
  for (const file of event.files || []) {
@@ -393,7 +476,7 @@ function handleHumanMessage(ctx, channel, event) {
393
476
  imported = true;
394
477
  }
395
478
  // Someone no project registered: never relayed, only counted (D16).
396
- if (!registered && event.user !== ctx.self.user_id) ctx.stats.ignored += 1;
479
+ if (!registered && !ctx.ownUsers.has(event.user)) ctx.stats.ignored += 1;
397
480
  return imported;
398
481
  }
399
482
 
@@ -404,7 +487,7 @@ function authorOf(project, message) {
404
487
 
405
488
  function handleChanged(ctx, channel, event) {
406
489
  const message = event.message || {};
407
- if (message.bot_id && message.bot_id === ctx.self.bot_id) return;
490
+ if (message.bot_id && ctx.ownBots.has(message.bot_id)) return;
408
491
  for (const project of projectsFor(ctx, channel)) {
409
492
  const id = recordAt(project, channel, message.ts);
410
493
  if (!id) continue;
@@ -422,7 +505,7 @@ function handleChanged(ctx, channel, event) {
422
505
 
423
506
  function handleDeleted(ctx, channel, event) {
424
507
  const previous = event.previous_message || {};
425
- if (previous.bot_id && previous.bot_id === ctx.self.bot_id) return;
508
+ if (previous.bot_id && ctx.ownBots.has(previous.bot_id)) return;
426
509
  const ts = event.deleted_ts || previous.ts;
427
510
  for (const project of projectsFor(ctx, channel)) {
428
511
  const id = recordAt(project, channel, ts);
@@ -436,7 +519,7 @@ function handleDeleted(ctx, channel, event) {
436
519
  }
437
520
 
438
521
  function handleReaction(ctx, event) {
439
- if (event.reaction !== "white_check_mark" || !event.item || event.user === ctx.self.user_id) return;
522
+ if (event.reaction !== "white_check_mark" || !event.item || ctx.ownUsers.has(event.user)) return;
440
523
  const channel = event.item.channel;
441
524
  for (const project of projectsFor(ctx, channel)) {
442
525
  const role = project.settings.members[event.user];
@@ -532,6 +615,67 @@ async function catchUp(ctx) {
532
615
  }
533
616
  }
534
617
 
618
+ // --- direct messages to a role's app (D6) ---------------------------------------
619
+
620
+ function handleDirectEvent(ctx, app, event) {
621
+ if (!event || event.type !== "message" || ![undefined, "file_share"].includes(event.subtype)) return;
622
+ // Its own answers, seen again by catch-up, are already local records.
623
+ if (event.bot_id) return;
624
+ ctx.stats.last_event = store.isoLocal(new Date());
625
+ const channel = event.channel;
626
+ let registered = false;
627
+ for (const project of ctx.projects) {
628
+ if (!(project.directApps || []).includes(app)) continue;
629
+ const person = project.settings.members[event.user];
630
+ noteSeen(project, channel, event.ts);
631
+ if (!person || person === app.role) continue;
632
+ registered = true;
633
+ if (recordAt(project, channel, event.ts)) continue;
634
+ const group = store.directName(person, app.role);
635
+ if (!store.groupState(store.readLog(project.where, group)).exists) {
636
+ store.createGroup(project.where, person, group, [app.role], { direct: true });
637
+ }
638
+ const record = store.writeRecord(project.where, {
639
+ group,
640
+ kind: "message",
641
+ from: person,
642
+ created: tsToIso(event.ts),
643
+ mentions: [],
644
+ origin: "slack",
645
+ text: humanText(project, event),
646
+ }, new Date(Math.round(Number(event.ts) * 1000)));
647
+ writePosted(project.where, record.id, { channel, ts: event.ts, origin: "slack", as: app.role, direct: true });
648
+ rememberTs(project, channel, event.ts, record.id);
649
+ }
650
+ if (!registered && !ctx.ownUsers.has(event.user)) ctx.stats.ignored += 1;
651
+ }
652
+
653
+ // Each registered person's direct-message channel with the role's app, from
654
+ // the last ts processed, through the same handler as live events.
655
+ async function catchUpDirect(ctx, app) {
656
+ const users = new Set();
657
+ for (const project of ctx.projects) {
658
+ if (!(project.directApps || []).includes(app)) continue;
659
+ for (const [user, person] of Object.entries(project.settings.members)) if (person !== app.role) users.add(user);
660
+ }
661
+ for (const user of users) {
662
+ const channel = await imChannel(ctx, app, user);
663
+ if (!channel) continue;
664
+ const seen = ctx.projects.filter((project) => (project.directApps || []).includes(app)).map((project) => lastSeen(project, channel));
665
+ const oldest = seen.some((ts) => !ts) ? null : seen.reduce((a, b) => (Number(a) < Number(b) ? a : b));
666
+ const messages = [];
667
+ let cursor = null;
668
+ do {
669
+ const page = await slack.callWithRetry("conversations.history", {
670
+ channel, oldest: oldest || undefined, limit: 200, cursor: cursor || undefined,
671
+ }, app.token);
672
+ messages.push(...(page.messages || []));
673
+ cursor = page.response_metadata && page.response_metadata.next_cursor;
674
+ } while (cursor);
675
+ for (const message of messages.reverse()) handleDirectEvent(ctx, app, { type: "message", channel, channel_type: "im", ...message });
676
+ }
677
+ }
678
+
535
679
  // --- the running process --------------------------------------------------------
536
680
 
537
681
  function statusFile() {
@@ -551,6 +695,7 @@ function writeStatus(ctx) {
551
695
  last_event: ctx.stats.last_event,
552
696
  ignored: ctx.stats.ignored,
553
697
  unposted: unpostedCount(ctx.projects),
698
+ roles: roleReport(ctx),
554
699
  updated: store.isoLocal(new Date()),
555
700
  };
556
701
  const file = statusFile();
@@ -564,6 +709,51 @@ function writeStatus(ctx) {
564
709
  }
565
710
  }
566
711
 
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
+ }));
722
+ }
723
+
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)) {
744
+ 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`;
748
+ }
749
+ } catch (error) {
750
+ app.reason = error.message;
751
+ }
752
+ roles.set(role, app);
753
+ }
754
+ return roles;
755
+ }
756
+
567
757
  function readStatus() {
568
758
  let status = {};
569
759
  try {
@@ -592,6 +782,7 @@ function fullStatus() {
592
782
  last_event: null,
593
783
  ignored: 0,
594
784
  unposted: 0,
785
+ roles: [],
595
786
  ...status,
596
787
  paused: Boolean(until),
597
788
  paused_until: until ? new Date(until).toISOString() : null,
@@ -624,9 +815,22 @@ async function createContext(log, { needApp }) {
624
815
  connected: false,
625
816
  stopping: false,
626
817
  self: {},
818
+ queue: Promise.resolve(),
627
819
  };
820
+ ctx.onHello = () => catchUp(ctx);
821
+ ctx.onEvent = (event) => handleEvent(ctx, event);
628
822
  const auth = await slack.callWithRetry("auth.test", {}, bot);
629
823
  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));
826
+ for (const app of directApps(ctx)) {
827
+ app.onHello = () => catchUpDirect(ctx, app);
828
+ app.onEvent = (event) => handleDirectEvent(ctx, app, event);
829
+ }
830
+ // 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");
832
+ ctx.ownBots = new Set([ctx.self.bot_id, ...verified.map((app) => app.bot_id)].filter(Boolean));
833
+ ctx.ownUsers = new Set([ctx.self.user_id, ...verified.map((app) => app.user_id)].filter(Boolean));
630
834
  return ctx;
631
835
  }
632
836
 
@@ -639,14 +843,15 @@ async function runOnce(log) {
639
843
  }
640
844
 
641
845
  // Events are handled one at a time, in arrival order, so a reply never lands
642
- // before the message it answers.
643
- function socketSession(ctx) {
846
+ // before the message it answers. Every connection — the shared app's and each
847
+ // role app's — feeds the same queue. `conn` holds the connection's app token,
848
+ // its socket and state, and what to do on hello and on each event.
849
+ function socketSession(ctx, conn) {
644
850
  return new Promise((resolve) => {
645
- let queue = Promise.resolve();
646
- slack.callWithRetry("apps.connections.open", {}, ctx.appToken).then((opened) => {
851
+ slack.callWithRetry("apps.connections.open", {}, conn.appToken).then((opened) => {
647
852
  if (ctx.stopping) return resolve();
648
853
  const socket = new WebSocket(opened.url);
649
- ctx.socket = socket;
854
+ conn.socket = socket;
650
855
  socket.onmessage = (message) => {
651
856
  let data = null;
652
857
  try {
@@ -656,9 +861,9 @@ function socketSession(ctx) {
656
861
  }
657
862
  if (data.envelope_id) socket.send(JSON.stringify({ envelope_id: data.envelope_id }));
658
863
  if (data.type === "hello") {
659
- ctx.connected = true;
864
+ conn.connected = true;
660
865
  writeStatus(ctx);
661
- queue = queue.then(() => catchUp(ctx)).then(() => writeStatus(ctx)).catch((error) => ctx.log(`catch-up failed: ${error.message}`));
866
+ ctx.queue = ctx.queue.then(() => conn.onHello()).then(() => writeStatus(ctx)).catch((error) => ctx.log(`catch-up failed: ${error.message}`));
662
867
  return;
663
868
  }
664
869
  if (data.type === "disconnect") {
@@ -666,26 +871,47 @@ function socketSession(ctx) {
666
871
  return;
667
872
  }
668
873
  if (data.type === "events_api" && data.payload) {
669
- queue = queue
670
- .then(() => handleEvent(ctx, data.payload.event))
874
+ ctx.queue = ctx.queue
875
+ .then(() => conn.onEvent(data.payload.event))
671
876
  .then(() => writeStatus(ctx))
672
877
  .catch((error) => ctx.log(`event failed: ${error.message}`));
673
878
  }
674
879
  };
675
880
  socket.onclose = () => {
676
- ctx.connected = false;
677
- ctx.socket = null;
881
+ conn.connected = false;
882
+ conn.socket = null;
678
883
  writeStatus(ctx);
679
884
  resolve();
680
885
  };
681
886
  socket.onerror = () => {};
682
887
  }, (error) => {
683
- ctx.log(`could not open a Socket Mode connection: ${error.message}`);
888
+ ctx.log(`could not open a Socket Mode connection${conn.role ? ` for ${conn.role}'s app` : ""}: ${error.message}`);
684
889
  resolve();
685
890
  });
686
891
  });
687
892
  }
688
893
 
894
+ // Keeps one connection up until the bridge stops, with backoff between
895
+ // attempts and nothing while paused.
896
+ async function keepConnected(ctx, conn) {
897
+ let backoff = 1000;
898
+ while (!ctx.stopping) {
899
+ if (lifecycle.pausedUntil()) {
900
+ await slack.sleep(500);
901
+ continue;
902
+ }
903
+ const opened = Date.now();
904
+ await socketSession(ctx, conn);
905
+ if (ctx.stopping || lifecycle.pausedUntil()) continue;
906
+ backoff = Date.now() - opened > 30000 ? 1000 : Math.min(backoff * 2, 30000);
907
+ await slack.sleep(backoff);
908
+ }
909
+ }
910
+
911
+ function connections(ctx) {
912
+ return [ctx, ...directApps(ctx)];
913
+ }
914
+
689
915
  function packageVersion() {
690
916
  try {
691
917
  return JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "..", "..", "package.json"), "utf8")).version || null;
@@ -734,7 +960,7 @@ async function run(log) {
734
960
  clearInterval(archiveTimer);
735
961
  stopped = (async () => {
736
962
  if (reason) await Promise.race([announce(ctx, `:red_circle: ${machine} bridge stopped${reason === "signal" ? "" : ` (${reason})`}; this machine's sessions will catch up when it restarts.`), slack.sleep(5000)]);
737
- if (ctx.socket) ctx.socket.close();
963
+ for (const conn of connections(ctx)) if (conn.socket) conn.socket.close();
738
964
  })();
739
965
  return stopped;
740
966
  };
@@ -764,7 +990,7 @@ async function run(log) {
764
990
  return;
765
991
  }
766
992
  if (lifecycle.pausedUntil()) {
767
- if (ctx.socket) ctx.socket.close();
993
+ for (const conn of connections(ctx)) if (conn.socket) conn.socket.close();
768
994
  return;
769
995
  }
770
996
  flush();
@@ -773,18 +999,7 @@ async function run(log) {
773
999
  process.once("SIGINT", () => stop("signal"));
774
1000
  await announce(ctx, `:large_green_circle: ${machine} bridge online, relaying ${ctx.projects.length} project${ctx.projects.length === 1 ? "" : "s"}.`);
775
1001
  await flush();
776
- let backoff = 1000;
777
- while (!ctx.stopping) {
778
- if (lifecycle.pausedUntil()) {
779
- await slack.sleep(500);
780
- continue;
781
- }
782
- const opened = Date.now();
783
- await socketSession(ctx);
784
- if (ctx.stopping || lifecycle.pausedUntil()) continue;
785
- backoff = Date.now() - opened > 30000 ? 1000 : Math.min(backoff * 2, 30000);
786
- await slack.sleep(backoff);
787
- }
1002
+ await Promise.all(connections(ctx).map((conn) => keepConnected(ctx, conn)));
788
1003
  if (stopped) await stopped;
789
1004
  ctx.connected = false;
790
1005
  writeStatus(ctx);
@@ -393,6 +393,13 @@ function runBridge(where, rest, options) {
393
393
  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
394
  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
395
  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}`];
398
+ if (app.reason) parts.push(app.reason);
399
+ if (app.state === "verified") parts.push(app.direct ? "direct messages connected" : "no direct messages");
400
+ if (app.invite && app.invite.length) parts.push(`invite it to ${app.invite.join(", ")}; until then it posts through the shared app there`);
401
+ lines.push(`${parts.join("; ")}.`);
402
+ }
396
403
  out(lines.join("\n"));
397
404
  return 0;
398
405
  }
@@ -52,6 +52,9 @@ function slackSettings(worktree) {
52
52
  error,
53
53
  owner: typeof slack.owner === "string" ? slack.owner : null,
54
54
  members: stringMap(slack.members),
55
+ // A role's own Slack app, by its bot user id (issue #187, chat-role-apps
56
+ // D1); a role not listed speaks through the machine's shared app.
57
+ bots: stringMap(slack.bots),
55
58
  channels: stringMap(slack.channels),
56
59
  icons: stringMap(slack.icons),
57
60
  };
@@ -48,6 +48,13 @@ 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}`) };
56
+ }
57
+
51
58
  function missingTokens(which) {
52
59
  return new ChatError(
53
60
  `No Slack ${which}: set KEEL_SLACK_APP_TOKEN and KEEL_SLACK_BOT_TOKEN, or store them in the macOS Keychain `
@@ -197,6 +204,7 @@ function stop() {
197
204
  }
198
205
 
199
206
  module.exports = {
207
+ roleTokens,
200
208
  KEYCHAIN_SERVICE,
201
209
  LABEL,
202
210
  bridgeDir,