@christang/keel 5.183.0 → 5.184.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.
@@ -0,0 +1,4441 @@
1
+ """Keel validation: chat (split from validate_plugin.py, #409)."""
2
+ from __future__ import annotations
3
+
4
+ import contextlib
5
+ import json
6
+ import gzip
7
+ import hashlib
8
+ import os
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tarfile
14
+ import tempfile
15
+ import threading
16
+ import time
17
+ import ast
18
+ import atexit
19
+ import signal
20
+ from datetime import datetime, timedelta, timezone
21
+ from concurrent.futures import ThreadPoolExecutor, as_completed
22
+ from pathlib import Path
23
+
24
+ from validation.common import (
25
+ PLUGIN_ROOT,
26
+ ROOT,
27
+ chat_environment,
28
+ chat_json,
29
+ chat_log,
30
+ chat_records_with,
31
+ chat_scratch_group,
32
+ chat_session_start,
33
+ chat_wake_scratch,
34
+ chat_worktree,
35
+ host_project_name,
36
+ mailbox_common_dir,
37
+ mailbox_repository,
38
+ report,
39
+ run_keel,
40
+ run_session_start_hook,
41
+ session_start_context,
42
+ shift_scratch,
43
+ write_authorize_config,
44
+ write_text,
45
+ )
46
+ from validation import registry
47
+
48
+
49
+ def validate_chat_core_scenario() -> int:
50
+ """Issue #187: roles share groups through an append-only store.
51
+
52
+ Everything goes through public `keel chat` across four worktrees of one
53
+ repository and a separate repository: role and alias binding and their
54
+ refusals, group membership and its refusals, immutable record files,
55
+ mention resolution through an alias, per-member cursors and receipts, a
56
+ direct group, archive, isolation, and that unread chat changes no context.
57
+ """
58
+ label = "chat-core: keel chat"
59
+ with tempfile.TemporaryDirectory(prefix="keel-chat-core-") as raw:
60
+ base = Path(raw)
61
+ rtl = mailbox_repository(base / "rtl")
62
+ verify = chat_worktree(rtl, base / "verify")
63
+ lint = chat_worktree(rtl, base / "lint")
64
+ maint = chat_worktree(rtl, base / "maint")
65
+ other = mailbox_repository(base / "other")
66
+ env = chat_environment()
67
+
68
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
69
+ return run_keel(cwd, "chat", *args, env=env)
70
+
71
+ unbound = chat(rtl, "post", "soc", "hello")
72
+ if unbound.returncode == 0:
73
+ report(f"{label} a post from an unbound worktree succeeded.")
74
+ return 1
75
+ if "keel chat role --set" not in unbound.stderr:
76
+ report(f"{label} the unbound-poster refusal does not name `keel chat role --set`: {(unbound.stderr or unbound.stdout).strip()}")
77
+ return 1
78
+ bad = chat(rtl, "role", "--set", "Bad Name")
79
+ if bad.returncode == 0:
80
+ report(f"{label} role --set accepted the invalid name 'Bad Name'.")
81
+ return 1
82
+ if "[a-z0-9]" not in bad.stderr:
83
+ report(f"{label} the invalid-role refusal does not name the pattern: {bad.stderr.strip()}")
84
+ return 1
85
+ if (mailbox_common_dir(rtl) / "keel-chat").exists():
86
+ report(f"{label} a refused role wrote to the chat store.")
87
+ return 1
88
+
89
+ for cwd, role in ((rtl, "rtl"), (verify, "verify"), (lint, "lint"), (maint, "claude-maint"), (other, "verify")):
90
+ bound = chat(cwd, "role", "--set", role)
91
+ if bound.returncode != 0:
92
+ report(f"{label} role --set {role} failed: {bound.stderr.strip()}")
93
+ return 1
94
+ shown = chat(verify, "role", "--json")
95
+ if chat_json(shown).get("role") != "verify":
96
+ report(f"{label} role --json did not report the bound role: {shown.stdout.strip()} {shown.stderr.strip()}")
97
+ return 1
98
+ aliased = chat(maint, "role", "--alias", "cm")
99
+ if aliased.returncode != 0:
100
+ report(f"{label} role --alias cm failed: {aliased.stderr.strip()}")
101
+ return 1
102
+ taken = chat(lint, "role", "--alias", "CM")
103
+ if taken.returncode == 0:
104
+ report(f"{label} a second role took the alias 'cm'.")
105
+ return 1
106
+ if "claude-maint" not in taken.stderr:
107
+ report(f"{label} the taken-alias refusal does not name its holder: {taken.stderr.strip()}")
108
+ return 1
109
+
110
+ context_before = run_keel(verify, "context", "--json", env=env)
111
+
112
+ created = chat(rtl, "group", "create", "soc", "--member", "verify", "--member", "lint", "--member", "claude-maint")
113
+ if created.returncode != 0:
114
+ report(f"{label} group create failed: {created.stderr.strip()}")
115
+ return 1
116
+ first = chat(rtl, "post", "soc", "Stimulus misreads the spec.", "--json")
117
+ first_id = chat_json(first).get("id", "")
118
+ if not first_id:
119
+ report(f"{label} post did not report an id: {first.stdout.strip()} {first.stderr.strip()}")
120
+ return 1
121
+ peek = chat(verify, "soc", "--peek", "--json")
122
+ # Keel stamps the time by default (#349); the stamp is not the author's text.
123
+ texts = [(r.get("from"), re.sub(r"^\[\d{2}-\d{2} \d{2}:\d{2}\] ", "", r.get("text") or "")) for r in chat_json(peek).get("records", [])]
124
+ if ("rtl", "Stimulus misreads the spec.") not in texts:
125
+ report(f"{label} the verify worktree did not see rtl's message: {peek.stdout.strip()} {peek.stderr.strip()}")
126
+ return 1
127
+ record_file = chat_log(rtl, "soc") / f"{first_id}.md"
128
+ if not record_file.is_file():
129
+ report(f"{label} no record file {record_file} for the posted message.")
130
+ return 1
131
+ original = record_file.read_bytes()
132
+ if not re.search(rb"^created: \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d[+-]\d\d:\d\d$", original, re.M):
133
+ report(f"{label} the record's created stamp carries no UTC offset:\n{original.decode()}")
134
+ return 1
135
+ if not original.startswith(b"---\n"):
136
+ report(f"{label} the record file has no frontmatter.")
137
+ return 1
138
+
139
+ mention = chat(verify, "post", "soc", "@CM please check the waveform", "--json")
140
+ mention_id = chat_json(mention).get("id", "")
141
+ if not mention_id:
142
+ report(f"{label} the aliased mention was not posted: {mention.stderr.strip()}")
143
+ return 1
144
+ mentions = chat_json(chat(rtl, "show", mention_id, "--json")).get("record", {}).get("mentions")
145
+ if mentions != ["claude-maint"]:
146
+ report(f"{label} @CM did not resolve to claude-maint: {mentions!r}")
147
+ return 1
148
+ if record_file.read_bytes() != original:
149
+ report(f"{label} a later post changed an earlier record file.")
150
+ return 1
151
+
152
+ count = len(list(chat_log(rtl, "soc").glob("*.md")))
153
+ stranger = chat(rtl, "post", "soc", "@stranger hi")
154
+ if stranger.returncode == 0:
155
+ report(f"{label} a mention of a non-member was posted.")
156
+ return 1
157
+ if "stranger" not in stranger.stderr:
158
+ report(f"{label} the non-member refusal does not name 'stranger': {stranger.stderr.strip()}")
159
+ return 1
160
+ if len(list(chat_log(rtl, "soc").glob("*.md"))) != count:
161
+ report(f"{label} the refused mention wrote a record.")
162
+ return 1
163
+
164
+ receipt = chat(rtl, "post", "soc", "Receipt check.", "--json")
165
+ receipt_id = chat_json(receipt).get("id", "")
166
+ viewed = chat(verify, "soc")
167
+ if viewed.returncode != 0:
168
+ report(f"{label} viewing soc failed: {viewed.stderr.strip()}")
169
+ return 1
170
+ lint_unread = [r.get("id") for r in chat_json(chat(lint, "unread", "--json")).get("unread", [])]
171
+ if receipt_id not in lint_unread:
172
+ report(f"{label} lint lost its unread message when verify read: {lint_unread!r}")
173
+ return 1
174
+ verify_unread = [r.get("id") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
175
+ if verify_unread:
176
+ report(f"{label} verify still has unread records after viewing: {verify_unread!r}")
177
+ return 1
178
+ readers = chat_json(chat(rtl, "show", receipt_id, "--json")).get("readers", [])
179
+ if "verify" not in readers:
180
+ report(f"{label} show does not list verify as a reader: {readers!r}")
181
+ return 1
182
+ if "lint" in readers:
183
+ report(f"{label} show lists lint as a reader before lint read: {readers!r}")
184
+ return 1
185
+
186
+ context_after = run_keel(verify, "context", "--json", env=env)
187
+ before, after = chat_json(context_before), chat_json(context_after)
188
+ if (before.get("status"), before.get("nextAction")) != (after.get("status"), after.get("nextAction")):
189
+ report(f"{label} unread chat changed keel context.")
190
+ return 1
191
+
192
+ direct = chat(rtl, "dm", "verify", "Ping in private.")
193
+ if direct.returncode != 0:
194
+ report(f"{label} dm failed: {direct.stderr.strip()}")
195
+ return 1
196
+ groups = {g.get("name"): g for g in chat_json(chat(verify, "group", "list", "--json")).get("groups", [])}
197
+ if "dm-rtl--verify" not in groups:
198
+ report(f"{label} dm did not create dm-rtl--verify: {sorted(groups)!r}")
199
+ return 1
200
+ if sorted(groups["dm-rtl--verify"].get("members", [])) != ["rtl", "verify"]:
201
+ report(f"{label} dm-rtl--verify does not hold exactly rtl and verify: {groups['dm-rtl--verify']!r}")
202
+ return 1
203
+
204
+ removed = chat(rtl, "group", "remove", "soc", "lint")
205
+ if removed.returncode != 0:
206
+ report(f"{label} group remove failed: {removed.stderr.strip()}")
207
+ return 1
208
+ outsider = chat(lint, "post", "soc", "Still here?")
209
+ if outsider.returncode == 0:
210
+ report(f"{label} a removed member could still post.")
211
+ return 1
212
+ if "member" not in outsider.stderr:
213
+ report(f"{label} the removed-member refusal does not name membership: {outsider.stderr.strip()}")
214
+ return 1
215
+ groups = {g.get("name"): g for g in chat_json(chat(rtl, "group", "list", "--json")).get("groups", [])}
216
+ if "soc" not in groups:
217
+ report(f"{label} group list no longer shows soc after a removal: {sorted(groups)!r}")
218
+ return 1
219
+ if "lint" in groups["soc"].get("members", []):
220
+ report(f"{label} group list still shows lint in soc: {groups.get('soc')!r}")
221
+ return 1
222
+
223
+ archived = chat(rtl, "group", "archive", "soc")
224
+ if archived.returncode != 0:
225
+ report(f"{label} group archive failed: {archived.stderr.strip()}")
226
+ return 1
227
+ late = chat(verify, "post", "soc", "One more thing.")
228
+ if late.returncode == 0:
229
+ report(f"{label} a post to an archived group succeeded.")
230
+ return 1
231
+ if "archived" not in late.stderr:
232
+ report(f"{label} the archived-group refusal does not name the archive: {late.stderr.strip()}")
233
+ return 1
234
+ history = chat(verify, "soc", "--peek")
235
+ if "Stimulus misreads the spec." not in history.stdout:
236
+ report(f"{label} an archived group's history is not readable: {history.stdout.strip()} {history.stderr.strip()}")
237
+ return 1
238
+
239
+ elsewhere = chat_json(chat(other, "group", "list", "--json", "--all")).get("groups", [])
240
+ if any(g.get("name") == "soc" for g in elsewhere):
241
+ report(f"{label} a separate repository lists soc.")
242
+ return 1
243
+
244
+ if "chat-core" not in {name for name, _ in registry.SCENARIOS}:
245
+ report(f"{label} scenario is not registered.")
246
+ return 1
247
+ report("chat-core scenario passed.")
248
+ return 0
249
+
250
+
251
+ def validate_chat_mention_skips_code_scenario() -> int:
252
+ """Issue #345: `keel chat post` refused a whole message over `@<commit-id>`
253
+ or an `@word` inside backticks.
254
+
255
+ The refusal exists so a typo cannot post a message that reaches nobody;
256
+ a commit id (`branch @ 638059e4`) and quoted text are not mentions.
257
+ """
258
+ label = "chat-mention-skips-code:"
259
+ with tempfile.TemporaryDirectory(prefix="keel-chat-345-") as raw:
260
+ base = Path(raw)
261
+ rtl, _verify, env = chat_scratch_group(base)
262
+
263
+ def post(text: str) -> subprocess.CompletedProcess[str]:
264
+ return run_keel(rtl, "chat", "post", "soc", text, "--json", env=env)
265
+
266
+ for name, text in (
267
+ ("commit-id", "main moved: claude/x @638059e4 waiting for the push window"),
268
+ ("long-commit-id", "landed @638059e4c0ffee1234567890abcdef12345678"),
269
+ ("inline-code", "write it as `@verifyy` in the note"),
270
+ ("fenced", "example:\n```\nkeel chat post soc @nobody hi\n```\nthat is all"),
271
+ ):
272
+ result = post(text)
273
+ if result.returncode != 0:
274
+ report(f"{label} a post with {name} was refused: {result.stdout!r} {result.stderr!r}")
275
+ return 1
276
+ mentions = chat_json(result).get("mentions", [])
277
+ if mentions:
278
+ report(f"{label} a post with {name} recorded mentions {mentions!r}.")
279
+ return 1
280
+
281
+ typo = post("@verifyy please check")
282
+ if typo.returncode == 0:
283
+ report(f"{label} a bare typo is no longer refused: {typo.stdout!r}")
284
+ return 1
285
+ if "@verifyy is not a member" not in typo.stderr:
286
+ report(f"{label} a bare typo's refusal does not name it: {typo.stderr!r}")
287
+ return 1
288
+ real = post("`@nobody` is quoted, @verify is asked")
289
+ if real.returncode != 0:
290
+ report(f"{label} a real mention beside quoted text was refused: {real.stderr!r}")
291
+ return 1
292
+ if chat_json(real).get("mentions") != ["verify"]:
293
+ report(f"{label} a real mention beside quoted text was not recorded alone: {real.stdout!r}")
294
+ return 1
295
+ if "chat-mention-skips-code" not in {name for name, _ in registry.SCENARIOS}:
296
+ report(f"{label} scenario is not registered.")
297
+ return 1
298
+ report("chat-mention-skips-code scenario passed.")
299
+ return 0
300
+
301
+
302
+ def chat_presence(rtl: Path, role: str) -> dict:
303
+ path = mailbox_common_dir(rtl) / "keel-chat" / "presence" / f"{role}.json"
304
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
305
+
306
+
307
+ def chat_session_list(rtl: Path, role: str) -> dict:
308
+ path = mailbox_common_dir(rtl) / "keel-chat" / "presence" / f"{role}.sessions.json"
309
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
310
+
311
+
312
+ def chat_session_record(rtl: Path, session: str) -> dict:
313
+ path = mailbox_common_dir(rtl) / "keel-chat" / "sessions" / f"{session}.json"
314
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
315
+
316
+
317
+ def validate_chat_hook_follows_session_worktree_scenario() -> int:
318
+ """Issue #415 (measured 2026-10-21): a resumed `claude --bg -w` session's
319
+ SessionStart reports the directory it was launched from as `cwd`.
320
+
321
+ keel-maint-2, launched from the main checkout, was recorded as the main
322
+ checkout's role (codex-issues) and watched its signal, so a message to
323
+ keel-maint-2 did not wake it. The transcript stays in the host project
324
+ directory of the worktree the session really runs in; the hook follows it.
325
+ """
326
+ label = "chat-hook-follows-session-worktree:"
327
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415a-") as raw:
328
+ base = Path(raw)
329
+ rtl, verify, env = chat_scratch_group(base)
330
+ chat_session_start(rtl, env, "sess-r", os.getpid())
331
+ transcript = base / "claude" / "projects" / host_project_name(verify) / "sess-v.jsonl"
332
+ started = chat_session_start(rtl, env, "sess-v", os.getpid(), source="resume", transcript=transcript)
333
+ try:
334
+ watched = json.loads(started.stdout)["hookSpecificOutput"]["watchPaths"]
335
+ except (ValueError, KeyError, TypeError):
336
+ report(f"{label} the resumed session's SessionStart printed no watch paths: {started.stdout!r} {started.stderr!r}")
337
+ return 1
338
+ if not any(path.endswith("/signal/verify") for path in watched) or any(path.endswith("/signal/rtl") for path in watched):
339
+ report(f"{label} a session whose transcript is verify's watches {watched!r}, not verify's signal alone.")
340
+ return 1
341
+ verify_presence = chat_presence(rtl, "verify")
342
+ if verify_presence.get("cli_session") != "sess-v" or os.path.realpath(verify_presence.get("cli_worktree") or "") != os.path.realpath(verify):
343
+ report(f"{label} verify's presence does not record the resumed session in verify's worktree: {verify_presence!r}")
344
+ return 1
345
+ if chat_session_record(rtl, "sess-v").get("role") != "verify":
346
+ report(f"{label} the resumed session's record names {chat_session_record(rtl, 'sess-v').get('role')!r}, not verify.")
347
+ return 1
348
+ if chat_presence(rtl, "rtl").get("cli_session") != "sess-r":
349
+ report(f"{label} rtl's presence took the resumed session: {chat_presence(rtl, 'rtl')!r}")
350
+ return 1
351
+ if "sess-v" in chat_session_list(rtl, "rtl"):
352
+ report(f"{label} rtl's session list took the resumed session: {chat_session_list(rtl, 'rtl')!r}")
353
+ return 1
354
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
355
+ report(f"{label} the scenario registry does not include it.")
356
+ return 1
357
+ report(f"{label.rstrip(':')} scenario passed.")
358
+ return 0
359
+
360
+
361
+ def validate_chat_visitor_not_recorded_scenario() -> int:
362
+ """Issue #415: a session that runs a keel command in another role's worktree
363
+ is not that role's session, and a caller with no Claude session clears nothing."""
364
+ label = "chat-visitor-not-recorded:"
365
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415b-") as raw:
366
+ base = Path(raw)
367
+ rtl, verify, env = chat_scratch_group(base)
368
+ chat_session_start(rtl, env, "sess-r", os.getpid())
369
+ chat_session_start(verify, env, "sess-v", os.getpid())
370
+ visitor = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-r", "CLAUDE_PID": str(os.getpid())}
371
+ run_keel(verify, "chat", "unread", env=visitor)
372
+ bare = {key: value for key, value in env.items() if not key.startswith("CLAUDE")}
373
+ run_keel(verify, "chat", "unread", env=bare)
374
+ # A session binding verify's worktree from elsewhere, on someone's behalf: its
375
+ # transcript lies under rtl's project directory, so it is not recorded.
376
+ config = base / "claude"
377
+ write_text(config / "projects" / host_project_name(rtl) / "sess-r.jsonl", "{}\n")
378
+ run_keel(verify, "chat", "role", "--set", "verify", env={**visitor, "CLAUDE_CONFIG_DIR": str(config)})
379
+ presence = chat_presence(rtl, "verify")
380
+ if presence.get("cli_session") != "sess-v" or os.path.realpath(presence.get("cli_worktree") or "") != os.path.realpath(verify):
381
+ report(f"{label} a visiting or session-less keel command replaced verify's recorded session: {presence!r}")
382
+ return 1
383
+ if set(chat_session_list(rtl, "verify")) != {"sess-v"}:
384
+ report(f"{label} verify's session list is {sorted(chat_session_list(rtl, 'verify'))!r}, not its own session alone.")
385
+ return 1
386
+ own = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-v", "CLAUDE_PID": str(os.getpid())}
387
+ before = chat_presence(rtl, "verify").get("last_active")
388
+ time.sleep(1.1)
389
+ run_keel(verify, "chat", "unread", env=own)
390
+ if chat_presence(rtl, "verify").get("last_active") == before:
391
+ report(f"{label} verify's own session running a keel command no longer marks it active.")
392
+ return 1
393
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
394
+ report(f"{label} the scenario registry does not include it.")
395
+ return 1
396
+ report(f"{label.rstrip(':')} scenario passed.")
397
+ return 0
398
+
399
+
400
+ def validate_chat_role_set_records_session_scenario() -> int:
401
+ """Issue #415: `keel chat role --set` in the live session makes it the role's session.
402
+
403
+ keel-maint-2 bound its role after starting, and `keel chat wake now
404
+ keel-maint-2` then found no session to resume.
405
+ """
406
+ label = "chat-role-set-records-session:"
407
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415c-") as raw:
408
+ base = Path(raw)
409
+ rtl, _verify, env = chat_scratch_group(base)
410
+ lane = chat_worktree(rtl, base / "lane")
411
+ config = base / "claude"
412
+ transcript = config / "projects" / host_project_name(lane) / "sess-3.jsonl"
413
+ write_text(transcript, json.dumps({"type": "user", "message": {"role": "user", "content": "hi"}}) + "\n")
414
+ env = {**env, "CLAUDE_CONFIG_DIR": str(config)}
415
+ chat_session_start(lane, env, "sess-3", os.getpid(), transcript=transcript)
416
+ bound = run_keel(lane, "chat", "role", "--set", "verify2",
417
+ env={**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-3", "CLAUDE_PID": str(os.getpid())})
418
+ if bound.returncode != 0:
419
+ report(f"{label} role --set failed: {bound.stdout!r} {bound.stderr!r}")
420
+ return 1
421
+ presence = chat_presence(rtl, "verify2")
422
+ if presence.get("cli_session") != "sess-3" or os.path.realpath(presence.get("cli_worktree") or "") != os.path.realpath(lane):
423
+ report(f"{label} binding a role did not record the session that bound it: {presence!r}")
424
+ return 1
425
+ if chat_session_record(rtl, "sess-3").get("role") != "verify2":
426
+ report(f"{label} the binding session's record names {chat_session_record(rtl, 'sess-3').get('role')!r}, not verify2.")
427
+ return 1
428
+ segments_file = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "segments" / "verify2.json"
429
+ segments = json.loads(segments_file.read_text(encoding="utf-8")).get("segments", []) if segments_file.exists() else []
430
+ if not segments or os.path.realpath(segments[-1].get("transcript", "")) != os.path.realpath(transcript):
431
+ report(f"{label} verify2's current segment is not the binding session's transcript: {segments!r}")
432
+ return 1
433
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
434
+ report(f"{label} the scenario registry does not include it.")
435
+ return 1
436
+ report(f"{label.rstrip(':')} scenario passed.")
437
+ return 0
438
+
439
+
440
+ def validate_chat_wake_skips_removed_session_scenario() -> int:
441
+ """Issue #415: a role's recorded session that `claude rm` removed is not resumed."""
442
+ label = "chat-wake-skips-removed-session:"
443
+ with tempfile.TemporaryDirectory(prefix="keel-chat-415d-") as raw:
444
+ base = Path(raw)
445
+ rtl, verify, env, _ = shift_scratch(base)
446
+ calls = base / "claude-calls.jsonl"
447
+ fake = base / "fake-claude"
448
+ write_text(fake, "#!/usr/bin/env python3\nimport json, sys\n"
449
+ f"open({str(calls)!r}, 'a').write(json.dumps(sys.argv[1:]) + '\\n')\n"
450
+ "if sys.argv[1:3] == ['agents', '--json']:\n"
451
+ " print(json.dumps([{'kind': 'background', 'sessionId': 'other-0000', 'id': 'other-00', 'cwd': '/tmp'}]))\n"
452
+ "else:\n print('backgrounded · fake')\n")
453
+ fake.chmod(0o755)
454
+ env = {**env, "KEEL_CLAUDE": str(fake)}
455
+ dead = subprocess.Popen(["true"])
456
+ dead.wait()
457
+ chat_session_start(verify, env, "sess-verify-1", dead.pid)
458
+ woke = run_keel(rtl, "chat", "wake", "now", "verify", env=env)
459
+ made = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
460
+ if any(call[:1] == ["--bg"] for call in made):
461
+ report(f"{label} wake now resumed a session claude agents no longer lists: {made!r}")
462
+ return 1
463
+ if woke.returncode == 0:
464
+ report(f"{label} wake now exits 0 for a session it could not resume: {woke.stdout!r}")
465
+ return 1
466
+ if "removed" not in (woke.stdout + woke.stderr):
467
+ report(f"{label} wake now does not say the recorded session was removed: {woke.stdout!r} {woke.stderr!r}")
468
+ return 1
469
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
470
+ report(f"{label} the scenario registry does not include it.")
471
+ return 1
472
+ report(f"{label.rstrip(':')} scenario passed.")
473
+ return 0
474
+
475
+
476
+ def validate_chat_wake_now_cli_scenario() -> int:
477
+ """Issue #348 on the CLI (owner's CLI waker, 2026-10-19): one step wakes a role.
478
+
479
+ A background CLI session's hooks record its session id and process. When
480
+ that process has exited, `keel chat wake now <role>` resumes it with
481
+ `claude --bg --resume <id> "<pointer>"` in its worktree — no other flag, so
482
+ the id is kept — and `keel tick` does the same once per new addressed
483
+ record. A running session is left to the record itself, which wakes it.
484
+ """
485
+ label = "chat-wake-now-cli:"
486
+ with tempfile.TemporaryDirectory(prefix="keel-wake-348-") as raw:
487
+ base = Path(raw)
488
+ rtl, verify, env, _ = shift_scratch(base)
489
+ calls = base / "claude-calls.jsonl"
490
+ fake = base / "fake-claude"
491
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
492
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd()}}) + '\\n')\n"
493
+ "print('backgrounded · fake')\n")
494
+ fake.chmod(0o755)
495
+ env = {**env, "KEEL_CLAUDE": str(fake)}
496
+ dead = subprocess.Popen(["true"])
497
+ dead.wait()
498
+
499
+ def start(pid: int) -> None:
500
+ subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=verify, text=True,
501
+ capture_output=True, check=False,
502
+ env={**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": "sess-verify-1", "CLAUDE_PID": str(pid)},
503
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": "sess-verify-1", "source": "startup"}))
504
+
505
+ def made() -> list[dict]:
506
+ # The resumes only: since #415 a wake first reads `claude agents --json --all`.
507
+ calls_made = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
508
+ return [call for call in calls_made if call["argv"][:1] == ["--bg"]]
509
+
510
+ start(dead.pid)
511
+ posted = run_keel(rtl, "chat", "dm", "verify", "rerun R009", env=env)
512
+ if "keel chat wake now verify" not in posted.stdout:
513
+ report(f"{label} a dm to a role whose CLI process exited does not name `keel chat wake now verify`: {posted.stdout!r}")
514
+ return 1
515
+ if "get_session" in posted.stdout:
516
+ report(f"{label} a CLI role is given the desktop wake step: {posted.stdout!r}")
517
+ return 1
518
+ woke = run_keel(rtl, "chat", "wake", "now", "verify", env=env)
519
+ if woke.returncode != 0:
520
+ report(f"{label} keel chat wake now failed: {woke.stdout!r} {woke.stderr!r}")
521
+ return 1
522
+ if len(made()) != 1:
523
+ report(f"{label} wake now did not run claude once: {made()!r}")
524
+ return 1
525
+ call = made()[0]
526
+ if call["argv"][:3] != ["--bg", "--resume", "sess-verify-1"] or len(call["argv"]) != 4:
527
+ report(f"{label} wake now ran claude with {call['argv']!r}, not --bg --resume <id> <prompt> and nothing else.")
528
+ return 1
529
+ if "keel chat unread" not in call["argv"][3]:
530
+ report(f"{label} the resume prompt does not point at keel chat unread: {call['argv'][3]!r}")
531
+ return 1
532
+ if os.path.realpath(call["cwd"]) != os.path.realpath(verify):
533
+ report(f"{label} claude was resumed in {call['cwd']}, not verify's worktree.")
534
+ return 1
535
+
536
+ start(os.getpid())
537
+ alive = run_keel(rtl, "chat", "wake", "now", "verify", env=env)
538
+ if len(made()) != 1:
539
+ report(f"{label} wake now resumed a role whose process is running: {made()!r}")
540
+ return 1
541
+ if "running" not in alive.stdout:
542
+ report(f"{label} wake now does not say the session is running: {alive.stdout!r}")
543
+ return 1
544
+
545
+ start(dead.pid)
546
+ run_keel(rtl, "chat", "dm", "verify", "rerun R010", env=env)
547
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
548
+ if len(made()) != 2:
549
+ report(f"{label} keel tick did not wake the exited role for its new record: {made()!r}")
550
+ return 1
551
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
552
+ if len(made()) != 2:
553
+ report(f"{label} a second tick woke the role again for the same record: {made()!r}")
554
+ return 1
555
+ time.sleep(2)
556
+ nudged = run_keel(rtl, "patrol", "--nudge", "--idle", "1s", env=env).stdout
557
+ escalation = next((l for l in nudged.splitlines() if "verify" in l and "wakes nothing" in l), "")
558
+ if "keel chat wake now verify" not in escalation or "get_session" in escalation:
559
+ report(f"{label} the patrol's nudge escalation for an ended CLI session is not `keel chat wake now verify`: {nudged!r}")
560
+ return 1
561
+ run_keel(rtl, "chat", "role", "--park", "verify", "--reason", "held for review", env=env)
562
+ run_keel(rtl, "chat", "dm", "verify", "rerun R011", env=env)
563
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
564
+ if len(made()) != 2:
565
+ report(f"{label} keel tick woke a parked role: {made()!r}")
566
+ return 1
567
+ if "chat-wake-now-cli" not in {name for name, _ in registry.SCENARIOS}:
568
+ report(f"{label} scenario is not registered.")
569
+ return 1
570
+ report("chat-wake-now-cli scenario passed.")
571
+ return 0
572
+
573
+
574
+ def validate_chat_role_rename_scenario() -> int:
575
+ """Issue #376: a renamed role kept nothing but its worktree binding.
576
+
577
+ kaiwu-ip renamed nine roles on 2026-10-19 with `role --set <new>`; the old
578
+ name stayed a member of every direct group, kept the cursors, the shift
579
+ note and the patrol state, and could not become an alias. `keel chat role
580
+ --rename <old> <new>` reads the log through the rename and moves the state.
581
+ """
582
+ label = "chat-role-rename:"
583
+ with tempfile.TemporaryDirectory(prefix="keel-rename-376-") as raw:
584
+ base = Path(raw)
585
+ rtl, verify, env, _ = shift_scratch(base / "one")
586
+ run_keel(rtl, "chat", "dm", "verify", "hello there", env=env)
587
+ run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "fix the lint", env=env)
588
+ run_keel(verify, "chat", "read", env=env)
589
+ readied = run_keel(verify, "shift", "ready", "--force-reason", "test", "half way through the lint", env=env)
590
+ if readied.returncode != 0:
591
+ report(f"{label} shift ready failed: {readied.stdout!r} {readied.stderr!r}")
592
+ return 1
593
+ write_text(verify / "keel/config.yaml", "patrol:\n role: verify\n every: 30m\n")
594
+ for args, why, needle in ((("nobody", "check"), "an unknown role", "no role nobody"),
595
+ (("verify", "verify"), "a rename onto itself", "itself"),
596
+ (("verify", "rtl"), "a rename onto a role bound elsewhere", "both bound")):
597
+ refused = run_keel(verify, "chat", "role", "--rename", *args, env=env)
598
+ if refused.returncode == 0:
599
+ report(f"{label} {why} was accepted: {refused.stdout!r}")
600
+ return 1
601
+ if needle not in refused.stderr:
602
+ report(f"{label} {why} was not refused for that reason: {refused.stderr!r}")
603
+ return 1
604
+ renamed = run_keel(verify, "chat", "role", "--rename", "verify", "check", env=env)
605
+ if renamed.returncode != 0:
606
+ report(f"{label} keel chat role --rename was refused: {renamed.stdout!r} {renamed.stderr!r}")
607
+ return 1
608
+ if "role: verify" not in renamed.stdout:
609
+ report(f"{label} the rename does not list keel/config.yaml's patrol line: {renamed.stdout!r}")
610
+ return 1
611
+ groups = json.loads(run_keel(verify, "chat", "group", "list", "--json", env=env).stdout)["groups"]
612
+ for name in ("soc", "dm-rtl--verify"):
613
+ members = next((g["members"] for g in groups if g["name"] == name), [])
614
+ if "check" not in members:
615
+ report(f"{label} check is not a member of {name}: {groups!r}")
616
+ return 1
617
+ todos = json.loads(run_keel(verify, "chat", "todos", "--mine", "--json", env=env).stdout)["todos"]
618
+ if not any("fix the lint" in t.get("text", "") for t in todos):
619
+ report(f"{label} check does not hold verify's todo: {todos!r}")
620
+ return 1
621
+ unread = json.loads(run_keel(verify, "chat", "unread", "--json", env=env).stdout)
622
+ if "hello there" in json.dumps(unread):
623
+ report(f"{label} a record verify had read is unread again: {unread!r}")
624
+ return 1
625
+ status = json.loads(run_keel(verify, "shift", "status", "--json", env=env).stdout)
626
+ if not any(r.get("role") == "check" and r.get("note") for r in status.get("roles", [])):
627
+ report(f"{label} shift status shows no note under check: {status!r}")
628
+ return 1
629
+ posted = run_keel(rtl, "chat", "post", "soc", "@verify please look", "--json", env=env)
630
+ if posted.returncode != 0:
631
+ report(f"{label} @verify was refused: {posted.stderr!r}")
632
+ return 1
633
+ if "check" not in json.loads(posted.stdout).get("mentions", []):
634
+ report(f"{label} @verify does not mention check: {posted.stdout!r}")
635
+ return 1
636
+ if run_keel(verify, "chat", "notice", "--check", env=env).returncode != 0:
637
+ report(f"{label} @verify does not wake check")
638
+ return 1
639
+ rebound = run_keel(rtl, "chat", "role", "--set", "verify", env=env)
640
+ if rebound.returncode == 0:
641
+ report(f"{label} binding the old name was accepted: {rebound.stdout!r}")
642
+ return 1
643
+ if "check" not in rebound.stderr:
644
+ report(f"{label} binding the old name was refused without naming check: {rebound.stderr!r}")
645
+ return 1
646
+
647
+ rtl2, verify2, env2, _ = shift_scratch(base / "two")
648
+ run_keel(rtl2, "chat", "post", "soc", "first", env=env2)
649
+ run_keel(verify2, "chat", "read", env=env2)
650
+ run_keel(rtl2, "chat", "group", "add", "soc", "check", env=env2)
651
+ # kaiwu-ip's order: the new name joined, then the old one was removed.
652
+ run_keel(rtl2, "chat", "group", "remove", "soc", "verify", env=env2)
653
+ run_keel(rtl2, "chat", "post", "soc", "second", env=env2)
654
+ run_keel(verify2, "chat", "role", "--set", "check", env=env2)
655
+ run_keel(verify2, "chat", "read", env=env2)
656
+ merged = run_keel(verify2, "chat", "role", "--rename", "verify", "check", env=env2)
657
+ if merged.returncode != 0:
658
+ report(f"{label} keel chat role --rename was refused onto an existing role: {merged.stdout!r} {merged.stderr!r}")
659
+ return 1
660
+ groups2 = json.loads(run_keel(verify2, "chat", "group", "list", "--json", env=env2).stdout)["groups"]
661
+ if "check" not in next((g["members"] for g in groups2 if g["name"] == "soc"), []):
662
+ report(f"{label} the old name's leave after the new one joined removed check from soc: {groups2!r}")
663
+ return 1
664
+ left = json.loads(run_keel(verify2, "chat", "unread", "--json", env=env2).stdout)
665
+ if "second" in json.dumps(left):
666
+ report(f"{label} check's later cursor was not kept: {left!r}")
667
+ return 1
668
+ alias = run_keel(rtl2, "chat", "role", "--alias", "verify", env=env2)
669
+ if alias.returncode == 0:
670
+ report(f"{label} --alias verify was accepted: {alias.stdout!r}")
671
+ return 1
672
+ if "check" not in alias.stderr:
673
+ report(f"{label} --alias verify was refused without naming check: {alias.stderr!r}")
674
+ return 1
675
+ if "chat-role-rename" not in {name for name, _ in registry.SCENARIOS}:
676
+ report(f"{label} scenario is not registered.")
677
+ return 1
678
+ report("chat-role-rename scenario passed.")
679
+ return 0
680
+
681
+
682
+ def validate_chat_supersedes_scenario() -> int:
683
+ """Issue #252: a record supersedes its author's earlier one.
684
+
685
+ A superseded record leaves unread, so it neither wakes nor is listed; a
686
+ group view marks both records; and unread and the notice list newest first.
687
+ """
688
+ label = "chat-supersedes:"
689
+ with tempfile.TemporaryDirectory(prefix="keel-chat-supersedes-") as raw:
690
+ base = Path(raw)
691
+ rtl, verify, env = chat_scratch_group(base)
692
+
693
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
694
+ return run_keel(cwd, "chat", *args, env=env)
695
+
696
+ def posted_id(result: subprocess.CompletedProcess[str]) -> str:
697
+ return chat_json(result).get("id", "")
698
+
699
+ first = posted_id(chat(rtl, "post", "soc", "@verify verify owns integration", "--json"))
700
+ second_run = chat(rtl, "post", "soc", "@verify design owns integration", "--supersedes", first, "--json")
701
+ second = posted_id(second_run)
702
+ if not first or not second:
703
+ report(f"{label} the posts did not return ids: {second_run.stdout} {second_run.stderr}")
704
+ return 1
705
+ unread = [r.get("id") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
706
+ if unread != [second]:
707
+ report(f"{label} verify's unread is {unread!r}, not only the superseding record {second}.")
708
+ return 1
709
+ notice = chat_json(chat(verify, "notice", "--json")).get("notice", "")
710
+ if first in notice:
711
+ report(f"{label} the wake notice still lists the superseded record {first}: {notice!r}")
712
+ return 1
713
+ if second not in notice:
714
+ report(f"{label} the wake notice does not list the superseding record {second}: {notice!r}")
715
+ return 1
716
+ view = chat(rtl, "soc", "--peek").stdout
717
+ if f"(superseded by {second})" not in view:
718
+ report(f"{label} the group view does not mark {first} superseded by {second}: {view!r}")
719
+ return 1
720
+ if f"(supersedes {first})" not in view:
721
+ report(f"{label} the group view does not mark {second} as superseding {first}: {view!r}")
722
+ return 1
723
+
724
+ refusals = []
725
+ other = posted_id(chat(verify, "post", "soc", "verify's own note", "--json"))
726
+ refusals.append(("another author's record", chat(rtl, "post", "soc", "x", "--supersedes", other), "verify"))
727
+ refusals.append(("an already superseded record", chat(rtl, "post", "soc", "x", "--supersedes", first), second))
728
+ gone = posted_id(chat(rtl, "post", "soc", "to retract", "--json"))
729
+ chat(rtl, "retract", gone)
730
+ refusals.append(("a retracted record", chat(rtl, "post", "soc", "x", "--supersedes", gone), "retracted"))
731
+ chat(rtl, "group", "create", "ops", "--member", "verify")
732
+ elsewhere = posted_id(chat(rtl, "post", "ops", "ops note", "--json"))
733
+ refusals.append(("a record in another group", chat(rtl, "post", "soc", "x", "--supersedes", elsewhere), "ops"))
734
+ for what, result, needle in refusals:
735
+ if result.returncode == 0:
736
+ report(f"{label} superseding {what} was accepted: {result.stdout}")
737
+ return 1
738
+ if needle not in result.stderr:
739
+ report(f"{label} superseding {what} was refused without naming {needle!r}: {result.stderr}")
740
+ return 1
741
+
742
+ chat(verify, "read")
743
+ ordered = [posted_id(chat(rtl, "post", "soc", f"@verify step {n}", "--json")) for n in (1, 2, 3)]
744
+ listed = [r.get("id") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
745
+ if listed != list(reversed(ordered)):
746
+ report(f"{label} unread is not newest first: {listed!r}, posted {ordered!r}.")
747
+ return 1
748
+ notice = chat_json(chat(verify, "notice", "--json")).get("notice", "")
749
+ positions = [notice.find(i) for i in reversed(ordered)]
750
+ if -1 in positions:
751
+ report(f"{label} the wake notice does not list all three posts: {notice!r}")
752
+ return 1
753
+ if positions != sorted(positions):
754
+ report(f"{label} the wake notice is not newest first: {notice!r}")
755
+ return 1
756
+
757
+ report("chat-supersedes scenario passed.")
758
+ return 0
759
+
760
+
761
+ def validate_chat_listen_only_scenario() -> int:
762
+ """Issue #248: a listen-only member hears a group but does not post in it.
763
+
764
+ It has records unread and is woken like any member, may acknowledge and
765
+ close its assigned todos, and is refused posting, opening a todo, and
766
+ changing the group.
767
+ """
768
+ label = "chat-listen-only:"
769
+ with tempfile.TemporaryDirectory(prefix="keel-chat-listen-") as raw:
770
+ base = Path(raw)
771
+ rtl, verify, env = chat_scratch_group(base)
772
+ review = chat_worktree(rtl, base / "review")
773
+
774
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
775
+ return run_keel(cwd, "chat", *args, env=env)
776
+
777
+ chat(review, "role", "--set", "review")
778
+ added = chat(rtl, "group", "add", "soc", "review", "--listen")
779
+ if added.returncode != 0:
780
+ report(f"{label} group add --listen failed: {added.stderr}")
781
+ return 1
782
+ asked = chat_json(chat(rtl, "post", "soc", "@review is clause 4 waived?", "--ack", "--json")).get("id", "")
783
+ unread = [r.get("id") for r in chat_json(chat(review, "unread", "--json")).get("unread", [])]
784
+ if asked not in unread:
785
+ report(f"{label} the listen-only member does not have the mention unread: {unread!r}")
786
+ return 1
787
+ if chat(review, "notice", "--check").returncode != 0:
788
+ report(f"{label} the listen-only member is not woken by a mention.")
789
+ return 1
790
+ todo = chat_json(chat(rtl, "todo", "soc", "--assignee", "review", "check clause 4", "--json")).get("id", "")
791
+ for what, result in (
792
+ ("ack", chat(review, "ack", asked)),
793
+ ("done", chat(review, "done", todo)),
794
+ ):
795
+ if result.returncode != 0:
796
+ report(f"{label} the listen-only member could not {what}: {result.stderr}")
797
+ return 1
798
+ for what, result in (
799
+ ("post", chat(review, "post", "soc", "waived")),
800
+ ("todo", chat(review, "todo", "soc", "--assignee", "rtl", "waive it")),
801
+ ("group add", chat(review, "group", "add", "soc", "spec")),
802
+ ("group archive", chat(review, "group", "archive", "soc")),
803
+ ):
804
+ if result.returncode == 0:
805
+ report(f"{label} the listen-only member's {what} was accepted.")
806
+ return 1
807
+ if "listen-only" not in result.stderr:
808
+ report(f"{label} the listen-only member's {what} was refused without naming listen-only: {result.stderr}")
809
+ return 1
810
+ listed = chat(rtl, "group", "list").stdout
811
+ if "review (listen)" not in listed:
812
+ report(f"{label} group list does not mark the listen-only member: {listed!r}")
813
+ return 1
814
+ report("chat-listen-only scenario passed.")
815
+ return 0
816
+
817
+
818
+ def validate_chat_stamp_help_scenario() -> int:
819
+ """Issue #298: `--stamp` writes Keel's time; `keel chat --help` is not an error."""
820
+ label = "chat-stamp-help:"
821
+ with tempfile.TemporaryDirectory(prefix="keel-chat-stamp-") as raw:
822
+ base = Path(raw)
823
+ rtl, _verify, env = chat_scratch_group(base)
824
+
825
+ def stamped(group: str, *args: str) -> str | None:
826
+ posted = run_keel(rtl, "chat", *args, env=env)
827
+ if posted.returncode != 0:
828
+ return f"{' '.join(args)} failed: {posted.stderr.strip()}"
829
+ record = sorted(chat_log(rtl, group).glob("*.md"))[-1].read_text(encoding="utf-8")
830
+ created = re.search(r"^created: \d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2})", record, re.M)
831
+ if not created:
832
+ return f"the record has no created time:\n{record}"
833
+ month, day, hour, minute = created.groups()
834
+ want = f"[{month}-{day} {hour}:{minute}] "
835
+ body = record.split("\n---\n", 1)[1].strip()
836
+ if not body.startswith(want):
837
+ return f"{' '.join(args)} stored {body!r}, not text starting with {want!r}"
838
+ return None
839
+
840
+ for group, args in (("soc", ("post", "soc", "--stamp", "R008 done")), ("dm-rtl--verify", ("dm", "verify", "--stamp", "x"))):
841
+ problem = stamped(group, *args)
842
+ if problem:
843
+ report(f"{label} {problem}")
844
+ return 1
845
+ for flag in ("--help", "-h"):
846
+ helped = run_keel(rtl, "chat", flag, env=env)
847
+ if helped.returncode != 0:
848
+ report(f"{label} keel chat {flag} exited {helped.returncode}: {helped.stderr.strip()}")
849
+ return 1
850
+ if "Usage:" not in helped.stdout:
851
+ report(f"{label} keel chat {flag} printed no usage: {helped.stdout!r}")
852
+ return 1
853
+ report("chat-stamp-help scenario passed.")
854
+ return 0
855
+
856
+
857
+ def validate_chat_stamp_default_scenario() -> int:
858
+ """Issue #349: `post` and `dm` stamp Keel's time by default.
859
+
860
+ `--stamp` was opt-in, so replies written without it carried hand-typed
861
+ times — one said "12:0x" at 12:50. The stamp is now the default, `--no-stamp`
862
+ opts out, and a text that already opens with a stamp is not stamped twice.
863
+ """
864
+ label = "chat-stamp-default:"
865
+ with tempfile.TemporaryDirectory(prefix="keel-chat-349-") as raw:
866
+ base = Path(raw)
867
+ rtl, _verify, env = chat_scratch_group(base)
868
+
869
+ def last(group: str) -> tuple[str, str]:
870
+ record = sorted(chat_log(rtl, group).glob("*.md"))[-1].read_text(encoding="utf-8")
871
+ created = re.search(r"^created: \d{4}-(\d{2})-(\d{2})T(\d{2}):(\d{2})", record, re.M)
872
+ month, day, hour, minute = created.groups()
873
+ return f"[{month}-{day} {hour}:{minute}] ", record.split("\n---\n", 1)[1].strip()
874
+
875
+ def chat(*args: str) -> subprocess.CompletedProcess[str]:
876
+ return run_keel(rtl, "chat", *args, env=env)
877
+
878
+ first = chat_json(chat("post", "soc", "R009 done", "--json"))
879
+ for group, args, text in (
880
+ ("soc", ("post", "soc", "plain post"), "plain post"),
881
+ ("soc", ("post", "soc", "--reply-to", first.get("id", ""), "a reply"), "a reply"),
882
+ ("dm-rtl--verify", ("dm", "verify", "a direct message"), "a direct message"),
883
+ ):
884
+ done = chat(*args)
885
+ if done.returncode != 0:
886
+ report(f"{label} {' '.join(args)} failed: {done.stderr.strip()}")
887
+ return 1
888
+ want, body = last(group)
889
+ if body != want + text:
890
+ report(f"{label} {' '.join(args)} without --stamp stored {body!r}, not {want + text!r}")
891
+ return 1
892
+ chat("post", "soc", "--no-stamp", "no stamp here")
893
+ _, body = last("soc")
894
+ if body != "no stamp here":
895
+ report(f"{label} --no-stamp stored {body!r}")
896
+ return 1
897
+ chat("post", "soc", "[10-19 11:00] already stamped")
898
+ _, body = last("soc")
899
+ if body != "[10-19 11:00] already stamped":
900
+ report(f"{label} a text that opens with a stamp was stamped again: {body!r}")
901
+ return 1
902
+ both = chat("post", "soc", "--stamp", "--no-stamp", "x")
903
+ if both.returncode == 0:
904
+ report(f"{label} --stamp with --no-stamp was accepted.")
905
+ return 1
906
+ # A stamp must not change what the text means (D3).
907
+ todo = chat_json(chat("todo", "soc", "--assignee", "verify", "rerun R009", "--json")).get("id", "")
908
+ if not todo:
909
+ report(f"{label} the todo was not created.")
910
+ return 1
911
+ if not any(t.get("id") == todo for t in chat_json(chat("todos", "soc", "--json")).get("todos", [])):
912
+ report(f"{label} the new todo is not listed open.")
913
+ return 1
914
+ chat("post", "soc", "--reply-to", todo, "✅ rerun clean")
915
+ listed = chat_json(chat("todos", "soc", "--json"))
916
+ if any(t.get("id") == todo for t in listed.get("todos", [])):
917
+ report(f"{label} a stamped ✅ reply did not close its todo: {listed!r}")
918
+ return 1
919
+ chat("post", "soc", "# Plan\n- one\n- two")
920
+ want, body = last("soc")
921
+ if body != want.rstrip() + "\n# Plan\n- one\n- two":
922
+ report(f"{label} a post opening with a heading was not stamped on its own line: {body!r}")
923
+ return 1
924
+ if "chat-stamp-default" not in {name for name, _ in registry.SCENARIOS}:
925
+ report(f"{label} scenario is not registered.")
926
+ return 1
927
+ report("chat-stamp-default scenario passed.")
928
+ return 0
929
+
930
+
931
+ def validate_chat_ack_scenario() -> int:
932
+ """Issue #253: a record asks for an acknowledgement and the sender sees who gave it.
933
+
934
+ An acknowledgement is `keel chat ack <id>` or a reply from an addressed
935
+ role; it marks the record read, wakes nobody, and is refused where it means
936
+ nothing; `show` and `acks` split the addressed roles three ways.
937
+ """
938
+ label = "chat-ack:"
939
+ with tempfile.TemporaryDirectory(prefix="keel-chat-ack-") as raw:
940
+ base = Path(raw)
941
+ rtl, verify, env = chat_scratch_group(base)
942
+ spec = chat_worktree(rtl, base / "spec")
943
+ run_keel(spec, "chat", "role", "--set", "spec", env=env)
944
+ run_keel(rtl, "chat", "group", "add", "soc", "spec", env=env)
945
+
946
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
947
+ return run_keel(cwd, "chat", *args, env=env)
948
+
949
+ asked = chat_json(chat(rtl, "post", "soc", "@verify @spec rerun R007 on 1b64e8c", "--ack", "--json")).get("id", "")
950
+ if not asked:
951
+ report(f"{label} a post with --ack returned no id.")
952
+ return 1
953
+ acked = chat(verify, "ack", asked)
954
+ if acked.returncode != 0:
955
+ report(f"{label} verify could not acknowledge: {acked.stderr}")
956
+ return 1
957
+ view = chat(spec, "soc").stdout
958
+ if "(ack requested)" not in view:
959
+ report(f"{label} spec's group view does not mark the record (ack requested): {view!r}")
960
+ return 1
961
+ acks = chat_json(chat(rtl, "show", asked, "--json")).get("acks", {})
962
+ if acks.get("acknowledged") != ["verify"]:
963
+ report(f"{label} show lists acknowledged {acks.get('acknowledged')!r}, not ['verify'].")
964
+ return 1
965
+ if acks.get("readNotAcknowledged") != ["spec"]:
966
+ report(f"{label} show lists read-not-acknowledged {acks.get('readNotAcknowledged')!r}, not ['spec'].")
967
+ return 1
968
+ if acks.get("unread") != []:
969
+ report(f"{label} show lists unread {acks.get('unread')!r}, not [].")
970
+ return 1
971
+ waiting = chat_json(chat(rtl, "acks", "--mine", "--json")).get("records", [])
972
+ if [r.get("id") for r in waiting] != [asked]:
973
+ report(f"{label} acks --mine lists {[r.get('id') for r in waiting]!r}, not [{asked}].")
974
+ return 1
975
+ rtl_unread = chat_json(chat(rtl, "unread", "--json")).get("unread", [])
976
+ if rtl_unread:
977
+ report(f"{label} the acknowledgement left rtl something unread: {rtl_unread!r}")
978
+ return 1
979
+
980
+ chat(spec, "post", "soc", "on it", "--reply-to", asked)
981
+ acks = chat_json(chat(rtl, "show", asked, "--json")).get("acks", {})
982
+ if acks.get("acknowledged") != ["spec", "verify"]:
983
+ report(f"{label} a reply did not acknowledge: acknowledged {acks.get('acknowledged')!r}.")
984
+ return 1
985
+ if chat_json(chat(rtl, "acks", "--json")).get("records", []):
986
+ report(f"{label} a fully acknowledged record is still listed by acks.")
987
+ return 1
988
+
989
+ later = chat_json(chat(rtl, "post", "soc", "@spec check the clock", "--ack", "--json")).get("id", "")
990
+ notice = chat_json(chat(spec, "notice", "--json")).get("notice", "")
991
+ if "(ack requested)" not in notice:
992
+ report(f"{label} spec's wake notice does not mark {later} (ack requested): {notice!r}")
993
+ return 1
994
+ plain = chat_json(chat(rtl, "post", "soc", "@spec fyi", "--json")).get("id", "")
995
+ refusals = [
996
+ ("a record that does not ask", chat(spec, "ack", plain), "does not ask"),
997
+ ("a record that does not address the role", chat(verify, "ack", later), "does not address"),
998
+ ("a record already acknowledged", chat(verify, "ack", asked), "already acknowledged"),
999
+ ("--ack on a record addressing nobody", chat(rtl, "post", "soc", "note to self", "--ack"), "addresses no one"),
1000
+ ]
1001
+ for what, result, needle in refusals:
1002
+ if result.returncode == 0:
1003
+ report(f"{label} {what} was accepted: {result.stdout}")
1004
+ return 1
1005
+ if needle not in result.stderr:
1006
+ report(f"{label} {what} was refused without saying {needle!r}: {result.stderr}")
1007
+ return 1
1008
+
1009
+ report("chat-ack scenario passed.")
1010
+ return 0
1011
+
1012
+
1013
+ def validate_chat_summary_scenario() -> int:
1014
+ """Issue #255: `keel chat summary --since` digests what changed, per group and sender.
1015
+
1016
+ Built from the records alone: a superseded record folds into its
1017
+ successor, todos carry open or done, waiting acknowledgements name who
1018
+ has not given one, and no read cursor moves.
1019
+ """
1020
+ label = "chat-summary:"
1021
+ with tempfile.TemporaryDirectory(prefix="keel-chat-summary-") as raw:
1022
+ base = Path(raw)
1023
+ rtl, verify, env = chat_scratch_group(base)
1024
+ loose = chat_worktree(rtl, base / "loose")
1025
+
1026
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
1027
+ return run_keel(cwd, "chat", *args, env=env)
1028
+
1029
+ # A record's `created` is stamped to the second, so the time is too.
1030
+ before = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
1031
+ rule = chat_json(chat(rtl, "post", "soc", "rule: rerun on every merge", "--json")).get("id", "")
1032
+ newer = chat_json(chat(rtl, "post", "soc", "rule: rerun nightly", "--supersedes", rule, "--json")).get("id", "")
1033
+ asked = chat_json(chat(rtl, "post", "soc", "@verify confirm R007", "--ack", "--json")).get("id", "")
1034
+ closed = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "rerun R007", "--json")).get("id", "")
1035
+ chat(verify, "done", closed)
1036
+ chat(verify, "post", "soc", "R007 is green")
1037
+ still = chat_json(chat(verify, "todo", "soc", "--assignee", "rtl", "review the clock fix", "--json")).get("id", "")
1038
+ if not all((rule, newer, asked, closed, still)):
1039
+ report(f"{label} the fixture could not post every record: {[rule, newer, asked, closed, still]!r}")
1040
+ return 1
1041
+
1042
+ store = Path(chat_json(chat(rtl, "role", "--json")).get("store", ""))
1043
+ cursors = {path: path.read_bytes() for path in (store / "cursors").rglob("*") if path.is_file()}
1044
+ result = chat(rtl, "summary", "--since", before, "--json")
1045
+ if result.returncode != 0:
1046
+ report(f"{label} keel chat summary failed: {result.stdout} {result.stderr}")
1047
+ return 1
1048
+ payload = chat_json(result)
1049
+ after = {path: path.read_bytes() for path in (store / "cursors").rglob("*") if path.is_file()}
1050
+ if after != cursors:
1051
+ report(f"{label} the summary moved a read cursor.")
1052
+ return 1
1053
+ groups = {group.get("group"): group for group in payload.get("groups", [])}
1054
+ if list(groups) != ["soc"]:
1055
+ report(f"{label} the summary lists groups {list(groups)!r}, not ['soc'].")
1056
+ return 1
1057
+ senders = {sender.get("role"): sender for sender in groups["soc"].get("senders", [])}
1058
+ if list(senders) != ["rtl", "verify"]:
1059
+ report(f"{label} the senders are {list(senders)!r}, not ['rtl', 'verify'] in role order.")
1060
+ return 1
1061
+ r, v = senders["rtl"], senders["verify"]
1062
+ expected = [
1063
+ ("rtl's message count, the superseded rule folded", r.get("messages"), 2),
1064
+ ("rtl's todo, closed", [(t.get("id"), t.get("assignee"), t.get("state")) for t in r.get("todosOpened", [])], [(closed, "verify", "done")]),
1065
+ ("rtl's superseding record", [(x.get("id"), x.get("supersedes")) for x in r.get("supersedes", [])], [(newer, rule)]),
1066
+ ("verify's message count", v.get("messages"), 1),
1067
+ ("verify's todo, open", [(t.get("id"), t.get("assignee"), t.get("state")) for t in v.get("todosOpened", [])], [(still, "rtl", "open")]),
1068
+ ("verify's closed todo", [t.get("id") for t in v.get("todosClosed", [])], [closed]),
1069
+ ("the waiting acknowledgement", [(a.get("id"), a.get("waiting")) for a in payload.get("waitingAcks", [])], [(asked, ["verify"])]),
1070
+ ]
1071
+ for what, got, want in expected:
1072
+ if got != want:
1073
+ report(f"{label} {what} is {got!r}, not {want!r}.")
1074
+ return 1
1075
+ if rule in json.dumps(payload).replace(f'"supersedes": "{rule}"', ""):
1076
+ report(f"{label} the superseded rule {rule} is listed on its own.")
1077
+ return 1
1078
+ text = chat(rtl, "summary", "--since", before)
1079
+ if text.returncode != 0:
1080
+ report(f"{label} the text summary failed: {text.stderr!r}")
1081
+ return 1
1082
+ if f"{newer} superseded {rule}" not in text.stdout:
1083
+ report(f"{label} the text summary does not name the superseding record: {text.stdout!r}")
1084
+ return 1
1085
+
1086
+ quiet = chat(rtl, "summary", "--since", "2999-01-01")
1087
+ if quiet.returncode != 0:
1088
+ report(f"{label} a time after the last record exited {quiet.returncode}: {quiet.stderr!r}")
1089
+ return 1
1090
+ if "nothing changed" not in quiet.stdout:
1091
+ report(f"{label} a time after the last record did not say nothing changed: {quiet.stdout!r}")
1092
+ return 1
1093
+ refusals = [
1094
+ ("a summary without --since", chat(rtl, "summary"), "--since"),
1095
+ ("an unreadable --since", chat(rtl, "summary", "--since", "yesterdayish"), "--since"),
1096
+ ("a worktree with no role", chat(loose, "summary", "--since", "1d"), "keel chat role --set"),
1097
+ ]
1098
+ for what, refused, needle in refusals:
1099
+ if refused.returncode == 0:
1100
+ report(f"{label} {what} was accepted: {refused.stdout}")
1101
+ return 1
1102
+ if needle not in refused.stderr:
1103
+ report(f"{label} {what} was refused without naming {needle!r}: {refused.stderr}")
1104
+ return 1
1105
+
1106
+ report("chat-summary scenario passed.")
1107
+ return 0
1108
+
1109
+
1110
+ def validate_chat_records_scenario() -> int:
1111
+ """Issue #187: todos, edits, retractions, search, and local-time display.
1112
+
1113
+ A todo links an issue and closes by `done` or a ✅ reply; an edit keeps
1114
+ the original file; search reaches archived groups; and a stored offset is
1115
+ shown in the viewer's local time, never as the raw stamp.
1116
+ """
1117
+ label = "chat-records:"
1118
+ with tempfile.TemporaryDirectory(prefix="keel-chat-records-") as raw:
1119
+ base = Path(raw)
1120
+ rtl, verify, env = chat_scratch_group(base)
1121
+
1122
+ def chat(cwd: Path, *args: str, extra: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]:
1123
+ return run_keel(cwd, "chat", *args, env={**env, **(extra or {})})
1124
+
1125
+ todo = chat(rtl, "todo", "soc", "--assignee", "verify", "--issue", "42", "Rerun the regression", "--json")
1126
+ todo_id = chat_json(todo).get("id", "")
1127
+ if not todo_id:
1128
+ report(f"{label} keel chat todo did not report an id: {todo.stdout.strip()} {todo.stderr.strip()}")
1129
+ return 1
1130
+ mine = chat_json(chat(verify, "todos", "--mine", "--json")).get("todos", [])
1131
+ listed = [t for t in mine if t.get("id") == todo_id]
1132
+ if not listed:
1133
+ report(f"{label} todos --mine for verify does not list the todo: {mine!r}")
1134
+ return 1
1135
+ if listed[0].get("issue") != "#42":
1136
+ report(f"{label} the todo does not carry issue #42: {listed[0]!r}")
1137
+ return 1
1138
+ closed = chat(verify, "post", "soc", "✅ merged", "--reply-to", todo_id)
1139
+ if closed.returncode != 0:
1140
+ report(f"{label} the ✅ reply failed: {closed.stderr.strip()}")
1141
+ return 1
1142
+ open_ids = [t.get("id") for t in chat_json(chat(rtl, "todos", "--json")).get("todos", [])]
1143
+ if todo_id in open_ids:
1144
+ report(f"{label} a todo answered with ✅ is still listed: {open_ids!r}")
1145
+ return 1
1146
+ second_id = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "Update the spec", "--json")).get("id", "")
1147
+ done = chat(verify, "done", second_id)
1148
+ if done.returncode != 0:
1149
+ report(f"{label} keel chat done failed: {done.stderr.strip()}")
1150
+ return 1
1151
+ open_ids = [t.get("id") for t in chat_json(chat(rtl, "todos", "--json")).get("todos", [])]
1152
+ if second_id in open_ids:
1153
+ report(f"{label} a todo closed with keel chat done is still listed: {open_ids!r}")
1154
+ return 1
1155
+
1156
+ message_id = chat_json(chat(rtl, "post", "soc", "Clock is 100MHz", "--json")).get("id", "")
1157
+ message_file = chat_log(rtl, "soc") / f"{message_id}.md"
1158
+ original = message_file.read_bytes()
1159
+ foreign = chat(verify, "edit", message_id, "Clock is 50MHz")
1160
+ if foreign.returncode == 0:
1161
+ report(f"{label} a role edited another role's message.")
1162
+ return 1
1163
+ edited = chat(rtl, "edit", message_id, "Clock is 200MHz")
1164
+ if edited.returncode != 0:
1165
+ report(f"{label} keel chat edit failed: {edited.stderr.strip()}")
1166
+ return 1
1167
+ shown = {r.get("id"): r for r in chat_json(chat(verify, "soc", "--peek", "--json")).get("records", [])}
1168
+ if shown.get(message_id, {}).get("text") != "Clock is 200MHz":
1169
+ report(f"{label} the view does not show the edited text: {shown.get(message_id)!r}")
1170
+ return 1
1171
+ if not shown[message_id].get("edited"):
1172
+ report(f"{label} the view does not mark the edited message: {shown[message_id]!r}")
1173
+ return 1
1174
+ if message_file.read_bytes() != original:
1175
+ report(f"{label} the edit changed the original record file.")
1176
+ return 1
1177
+ retract_id = chat_json(chat(rtl, "post", "soc", "Wrong channel", "--json")).get("id", "")
1178
+ retracted = chat(rtl, "retract", retract_id)
1179
+ if retracted.returncode != 0:
1180
+ report(f"{label} keel chat retract failed: {retracted.stderr.strip()}")
1181
+ return 1
1182
+ shown = {r.get("id"): r for r in chat_json(chat(verify, "soc", "--peek", "--json")).get("records", [])}
1183
+ if not shown.get(retract_id, {}).get("retracted"):
1184
+ report(f"{label} the view does not mark the retracted message: {shown.get(retract_id)!r}")
1185
+ return 1
1186
+
1187
+ chat(rtl, "group", "create", "old", "--member", "verify")
1188
+ chat(rtl, "post", "old", "Legacy PLL notes live here")
1189
+ chat(rtl, "group", "archive", "old")
1190
+ found = chat_json(chat(verify, "search", "PLL", "--json")).get("results", [])
1191
+ if [r.get("group") for r in found] != ["old"]:
1192
+ report(f"{label} search did not find the record in the archived group: {found!r}")
1193
+ return 1
1194
+
1195
+ stamp_id = "20261001T060000000Z-rtl-0a0b0c"
1196
+ write_text(
1197
+ chat_log(rtl, "soc") / f"{stamp_id}.md",
1198
+ f"---\nid: {stamp_id}\ngroup: soc\nkind: message\nfrom: rtl\n"
1199
+ "created: 2026-10-01T06:00:00+00:00\n---\n\nMorning sync\n",
1200
+ )
1201
+ local = chat(verify, "soc", "--peek", extra={"TZ": "Asia/Shanghai"})
1202
+ if "2026-10-01 14:00" not in local.stdout:
1203
+ report(f"{label} a 06:00 UTC record is not shown as 2026-10-01 14:00 in Asia/Shanghai: {local.stdout.strip()} {local.stderr.strip()}")
1204
+ return 1
1205
+ if "06:00:00+00:00" in local.stdout:
1206
+ report(f"{label} the view prints the raw stored stamp.")
1207
+ return 1
1208
+
1209
+ if "chat-records" not in {name for name, _ in registry.SCENARIOS}:
1210
+ report(f"{label} scenario is not registered.")
1211
+ return 1
1212
+ report("chat-records scenario passed.")
1213
+ return 0
1214
+
1215
+
1216
+ def validate_chat_mail_migration_scenario() -> int:
1217
+ """Issue #187: 5.83 mail migrates into direct groups; `keel mail` still works.
1218
+
1219
+ A scratch repository is seeded with the 5.83 mailbox layout by hand, as an
1220
+ upgraded repository would hold it. The first `keel mail` command migrates
1221
+ it — unread stays unread, read stays read, the binding carries over, and
1222
+ the old directory is renamed rather than deleted — and the 5.83 commands
1223
+ then work on the direct groups.
1224
+ """
1225
+ label = "chat-mail-migration:"
1226
+ with tempfile.TemporaryDirectory(prefix="keel-chat-migration-") as raw:
1227
+ base = Path(raw)
1228
+ rtl = mailbox_repository(base / "rtl")
1229
+ verify = chat_worktree(rtl, base / "verify")
1230
+ env = chat_environment()
1231
+ common = mailbox_common_dir(rtl)
1232
+ box = common / "keel-mailbox"
1233
+ old_unread = "20261001T010000Z-rtl-aaaaaa"
1234
+ old_read = "20261001T000000Z-rtl-bbbbbb"
1235
+ write_text(
1236
+ box / "verify" / "new" / f"{old_unread}.md",
1237
+ f"---\nid: {old_unread}\nfrom: rtl\nto: verify\ncreated: 2026-10-01T01:00:00.000Z\n"
1238
+ "subject: Rerun the suite\n---\n\nThe clock fix landed.\n",
1239
+ )
1240
+ write_text(
1241
+ box / "verify" / "done" / f"{old_read}.md",
1242
+ f"---\nid: {old_read}\nfrom: rtl\nto: verify\ncreated: 2026-10-01T00:00:00.000Z\n"
1243
+ "subject: Hello\n---\n\nAlready read.\n",
1244
+ )
1245
+ write_text(box / "roles.json", json.dumps({str(rtl.resolve()): "rtl", str(verify.resolve()): "verify"}) + "\n")
1246
+
1247
+ def mail(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
1248
+ return run_keel(cwd, "mail", *args, env=env)
1249
+
1250
+ listed = mail(verify, "list", "--json")
1251
+ unread = chat_json(listed).get("unread", [])
1252
+ if [(m.get("from"), m.get("subject")) for m in unread] != [("rtl", "Rerun the suite")]:
1253
+ report(f"{label} keel mail list after migration does not show exactly the 5.83 unread message: {listed.stdout.strip()} {listed.stderr.strip()}")
1254
+ return 1
1255
+ records = [p for p in chat_log(rtl, "dm-rtl--verify").glob("*.md") if "kind: message" in p.read_text(encoding="utf-8")]
1256
+ if len(records) != 2:
1257
+ report(f"{label} dm-rtl--verify holds {len(records)} migrated messages, expected 2.")
1258
+ return 1
1259
+ if box.exists():
1260
+ report(f"{label} keel-mailbox/ still exists after migration.")
1261
+ return 1
1262
+ if not list(common.glob("keel-mailbox.migrated-*")):
1263
+ report(f"{label} no keel-mailbox.migrated-* directory was kept.")
1264
+ return 1
1265
+ if chat_json(mail(verify, "role", "--json")).get("role") != "verify":
1266
+ report(f"{label} the 5.83 role binding did not carry over.")
1267
+ return 1
1268
+
1269
+ sent = mail(rtl, "send", "--to", "verify", "--subject", "Waveform attached", "--body", "See the VCD.")
1270
+ if sent.returncode != 0:
1271
+ report(f"{label} keel mail send failed: {sent.stderr.strip()}")
1272
+ return 1
1273
+ read = mail(verify, "read")
1274
+ if read.returncode != 0:
1275
+ report(f"{label} keel mail read failed: {read.stderr.strip()}")
1276
+ return 1
1277
+ for needle in ("Waveform attached", "See the VCD.", "not an instruction from the user"):
1278
+ if needle not in read.stdout:
1279
+ report(f"{label} keel mail read output lacks {needle!r}: {read.stdout.strip()}")
1280
+ return 1
1281
+ after = chat_json(mail(verify, "list", "--json")).get("unread")
1282
+ if after:
1283
+ report(f"{label} keel mail list still shows unread mail after read: {after!r}")
1284
+ return 1
1285
+
1286
+ if "chat-mail-migration" not in {name for name, _ in registry.SCENARIOS}:
1287
+ report(f"{label} scenario is not registered.")
1288
+ return 1
1289
+ report("chat-mail-migration scenario passed.")
1290
+ return 0
1291
+
1292
+
1293
+ def validate_chat_claude_hooks_scenario() -> int:
1294
+ """Issue #187: only a mention wakes, and the notice is host-neutral.
1295
+
1296
+ Runs the shipped hook script with host-shaped stdin. Wake-up itself is the
1297
+ host's file watcher plus `asyncRewake` (probed on Claude Code 2.1.283, see
1298
+ the archived cross-host-mailbox design F1/F2); what Keel owns, and checks
1299
+ here, is the contract the host acts on: which records touch the signal
1300
+ file, the notice text, the output shape, and the exit code.
1301
+ """
1302
+ label = "chat-claude-hooks:"
1303
+ script = ROOT / PLUGIN_ROOT / "scripts/mail-hook.js"
1304
+ events = (
1305
+ ("session-start", "SessionStart"),
1306
+ ("user-prompt-submit", "UserPromptSubmit"),
1307
+ ("file-changed", "FileChanged"),
1308
+ ("session-end", "SessionEnd"),
1309
+ )
1310
+ with tempfile.TemporaryDirectory(prefix="keel-chat-hooks-") as raw:
1311
+ base = Path(raw)
1312
+ rtl, verify, env = chat_scratch_group(base)
1313
+ env["KEEL_CLI"] = f'node "{ROOT / "bin" / "keel.js"}"'
1314
+ unbound = mailbox_repository(base / "unbound")
1315
+ plain = base / "plain"
1316
+ plain.mkdir()
1317
+
1318
+ def hook(cwd: Path, event: str, host_event: str) -> subprocess.CompletedProcess[str]:
1319
+ return subprocess.run(
1320
+ ["node", str(script), event],
1321
+ cwd=cwd, env=env, text=True, capture_output=True, check=False,
1322
+ input=json.dumps({"hook_event_name": host_event, "cwd": str(cwd)}),
1323
+ )
1324
+
1325
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
1326
+ return run_keel(cwd, "chat", *args, env=env)
1327
+
1328
+ if not script.is_file():
1329
+ report(f"{label} {script.relative_to(ROOT)} does not exist.")
1330
+ return 1
1331
+ late_watch: list[str] = []
1332
+ for cwd in (unbound, plain):
1333
+ for event, host_event in events:
1334
+ quiet = hook(cwd, event, host_event)
1335
+ if quiet.returncode != 0:
1336
+ report(f"{label} {event} exited {quiet.returncode} in {cwd.name}, which has no role.")
1337
+ return 1
1338
+ if cwd == unbound and event == "session-start":
1339
+ # A session may start before its worktree's role is bound;
1340
+ # it still watches the worktree's signal, and nothing else.
1341
+ output = chat_json(quiet).get("hookSpecificOutput", {})
1342
+ watched = output.get("watchPaths") or []
1343
+ if len(watched) != 1:
1344
+ report(f"{label} session-start in a worktree with no role does not watch exactly one path: {quiet.stdout.strip()!r}")
1345
+ return 1
1346
+ if "/signal/worktree/" not in watched[0]:
1347
+ report(f"{label} session-start in a worktree with no role watches something other than the worktree signal: {watched!r}")
1348
+ return 1
1349
+ if output.get("additionalContext"):
1350
+ report(f"{label} session-start in a worktree with no role printed notice text: {quiet.stdout.strip()!r}")
1351
+ return 1
1352
+ late_watch = watched
1353
+ continue
1354
+ if quiet.stdout.strip() or quiet.stderr.strip():
1355
+ report(f"{label} {event} wrote output in {cwd.name}, which has no role: {(quiet.stdout + quiet.stderr).strip()!r}")
1356
+ return 1
1357
+ chat(unbound, "role", "--set", "late")
1358
+ chat(unbound, "group", "create", "side", "--member", "poster")
1359
+ run_keel(unbound, "chat", "post", "side", "@late please look", env={**env, "KEEL_CHAT_ROLE": "poster"})
1360
+ late_signal = Path(late_watch[0])
1361
+ if not late_signal.exists() or not late_signal.stat().st_size:
1362
+ report(f"{label} a mention of a role bound after session start did not touch the worktree signal that session watches.")
1363
+ return 1
1364
+ late_wake = hook(unbound, "file-changed", "FileChanged")
1365
+ if late_wake.returncode != 2:
1366
+ report(f"{label} file-changed exited {late_wake.returncode} for a role bound after session start, not 2.")
1367
+ return 1
1368
+
1369
+ signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "verify"
1370
+
1371
+ def signal_size() -> int:
1372
+ return signal.stat().st_size if signal.exists() else 0
1373
+
1374
+ chat(rtl, "post", "soc", "@all standup in five")
1375
+ if signal_size():
1376
+ report(f"{label} an @all post touched verify's signal file.")
1377
+ return 1
1378
+ broadcast = hook(verify, "file-changed", "FileChanged")
1379
+ if broadcast.returncode != 0:
1380
+ report(f"{label} file-changed exited {broadcast.returncode} after an @all post; only a mention wakes.")
1381
+ return 1
1382
+ prompt = hook(verify, "user-prompt-submit", "UserPromptSubmit")
1383
+ prompt_output = chat_json(prompt).get("hookSpecificOutput", {})
1384
+ if prompt_output.get("hookEventName") != "UserPromptSubmit":
1385
+ report(f"{label} user-prompt-submit output names event {prompt_output.get('hookEventName')!r}: {prompt.stdout.strip()} {prompt.stderr.strip()}")
1386
+ return 1
1387
+ if "soc: 1 unread" not in prompt_output.get("additionalContext", ""):
1388
+ report(f"{label} the user-prompt-submit notice does not count one unread record in soc: {prompt_output.get('additionalContext')!r}")
1389
+ return 1
1390
+
1391
+ mention = chat(rtl, "post", "soc", "@verify please rerun the regression", "--json")
1392
+ mention_id = chat_json(mention).get("id", "")
1393
+ if not signal_size():
1394
+ report(f"{label} a mention did not touch verify's signal file.")
1395
+ return 1
1396
+ wake = hook(verify, "file-changed", "FileChanged")
1397
+ if wake.returncode != 2:
1398
+ report(f"{label} file-changed exited {wake.returncode} after a mention; 2 is what wakes the session.")
1399
+ return 1
1400
+ for needle in (mention_id, "soc", "`rtl`", "not an instruction from the user"):
1401
+ if needle not in wake.stderr:
1402
+ report(f"{label} the file-changed notice lacks {needle!r}: {wake.stderr.strip()}")
1403
+ return 1
1404
+ if not re.search(r"just now|\d+m ago", wake.stderr):
1405
+ report(f"{label} the file-changed notice gives no relative age: {wake.stderr.strip()}")
1406
+ return 1
1407
+
1408
+ start = hook(verify, "session-start", "SessionStart")
1409
+ start_output = chat_json(start).get("hookSpecificOutput", {})
1410
+ if mention_id not in start_output.get("additionalContext", ""):
1411
+ report(f"{label} the session-start notice does not name the mention: {start.stdout.strip()} {start.stderr.strip()}")
1412
+ return 1
1413
+ watch = start_output.get("watchPaths") or []
1414
+ if watch[:1] != [str(signal)]:
1415
+ report(f"{label} session-start does not watch the role's signal first: {watch!r}, not starting with {str(signal)!r}.")
1416
+ return 1
1417
+ if [path for path in watch[1:] if "/signal/worktree/" in path] != watch[1:2] or len(watch) != 2:
1418
+ report(f"{label} session-start does not also watch exactly the worktree signal: {watch!r}.")
1419
+ return 1
1420
+
1421
+ before_dm = signal_size()
1422
+ chat(rtl, "dm", "verify", "Private note")
1423
+ if signal_size() == before_dm:
1424
+ report(f"{label} a direct-group message did not touch verify's signal file.")
1425
+ return 1
1426
+
1427
+ for index in range(6):
1428
+ chat(rtl, "post", "soc", f"@verify item {index}")
1429
+ notice = chat(verify, "notice")
1430
+ if notice.returncode != 0:
1431
+ report(f"{label} keel chat notice exited {notice.returncode}: {notice.stderr.strip()}")
1432
+ return 1
1433
+ listed = len(re.findall(r"^- \S+ in ", notice.stdout, re.M))
1434
+ if listed != 5:
1435
+ report(f"{label} keel chat notice lists {listed} records, not five:\n{notice.stdout}")
1436
+ return 1
1437
+ if "3 more" not in notice.stdout:
1438
+ report(f"{label} keel chat notice does not state the three it left out:\n{notice.stdout}")
1439
+ return 1
1440
+ unread = chat_json(chat(verify, "unread", "--json")).get("unread", [])
1441
+ if len(unread) != 9:
1442
+ report(f"{label} a hook or notice advanced verify's cursor: {len(unread)} unread, expected 9.")
1443
+ return 1
1444
+
1445
+ ended = hook(verify, "session-end", "SessionEnd")
1446
+ if ended.returncode != 0:
1447
+ report(f"{label} session-end exited {ended.returncode}: {ended.stderr.strip()}")
1448
+ return 1
1449
+ queued = chat(rtl, "post", "soc", "@verify ping")
1450
+ if "verify" not in queued.stdout or "offline" not in queued.stdout:
1451
+ report(f"{label} a mention of an offline member does not report it offline: {queued.stdout.strip()} {queued.stderr.strip()}")
1452
+ return 1
1453
+
1454
+ chat(verify, "read")
1455
+ after = hook(verify, "file-changed", "FileChanged")
1456
+ if after.returncode != 0:
1457
+ report(f"{label} file-changed exited {after.returncode} with nothing unread.")
1458
+ return 1
1459
+ if after.stderr.strip():
1460
+ report(f"{label} file-changed wrote {after.stderr.strip()!r} with nothing unread.")
1461
+ return 1
1462
+ quiet_prompt = hook(verify, "user-prompt-submit", "UserPromptSubmit")
1463
+ if quiet_prompt.stdout.strip():
1464
+ report(f"{label} user-prompt-submit still announced records after they were read.")
1465
+ return 1
1466
+
1467
+ if "chat-claude-hooks" not in {name for name, _ in registry.SCENARIOS}:
1468
+ report(f"{label} scenario is not registered.")
1469
+ return 1
1470
+ report("chat-claude-hooks scenario passed.")
1471
+ return 0
1472
+
1473
+
1474
+ def validate_chat_loop_guards_scenario() -> int:
1475
+ """Issue #187: a rate limit and a ping-pong breaker stop runaway agents.
1476
+
1477
+ Two agents answering each other eight times in a row are stopped, the
1478
+ owner is called with one system record, and the owner's post clears the
1479
+ block. A role over its configured post rate is refused by name; the owner
1480
+ never is.
1481
+ """
1482
+ label = "chat-loop-guards:"
1483
+ with tempfile.TemporaryDirectory(prefix="keel-chat-guards-") as raw:
1484
+ base = Path(raw)
1485
+ rtl, verify, env = chat_scratch_group(base)
1486
+ lint = chat_worktree(rtl, base / "lint")
1487
+ run_keel(lint, "chat", "role", "--set", "lint", env=env)
1488
+ run_keel(rtl, "chat", "group", "add", "soc", "lint", env=env)
1489
+
1490
+ def chat(cwd: Path, *args: str, role: str | None = None) -> subprocess.CompletedProcess[str]:
1491
+ extra = {"KEEL_CHAT_ROLE": role} if role else {}
1492
+ return run_keel(cwd, "chat", *args, env={**env, **extra})
1493
+
1494
+ # Enough rate for the ping-pong rounds below; the rate limit is checked with lint.
1495
+ for tree in (rtl, verify):
1496
+ write_text(tree / "keel" / "chat.json", json.dumps({"limits": {"rate": 100}}) + "\n")
1497
+
1498
+ def alternate(group: str, start: int, poster=None) -> str | None:
1499
+ post = poster or (lambda cwd, text: chat(cwd, "post", group, text))
1500
+ for index in range(start, start + 8):
1501
+ cwd = rtl if index % 2 == 0 else verify
1502
+ turn = post(cwd, f"round {index}")
1503
+ if turn.returncode != 0:
1504
+ return f"alternating post {index} in {group} was refused before the threshold: {turn.stderr.strip()}"
1505
+ return None
1506
+
1507
+ def systems(group: str) -> list[str]:
1508
+ return [p.read_text(encoding="utf-8") for p in chat_log(rtl, group).glob("*.md") if "kind: system" in p.read_text(encoding="utf-8")]
1509
+
1510
+ problem = alternate("soc", 0)
1511
+ if problem:
1512
+ report(f"{label} {problem}")
1513
+ return 1
1514
+ ninth = chat(rtl, "post", "soc", "round 8")
1515
+ if ninth.returncode == 0:
1516
+ report(f"{label} a ninth quick alternating post was accepted.")
1517
+ return 1
1518
+ if "loop guard" not in ninth.stderr:
1519
+ report(f"{label} the ping-pong refusal does not name the loop guard: {ninth.stderr.strip()}")
1520
+ return 1
1521
+ if "--not-a-loop" not in ninth.stderr:
1522
+ report(f"{label} the first refusal does not name --not-a-loop: {ninth.stderr.strip()}")
1523
+ return 1
1524
+ if systems("soc"):
1525
+ report(f"{label} the first trip already called the owner.")
1526
+ return 1
1527
+ overridden = chat(rtl, "post", "soc", "--not-a-loop", "new assignment", "R009 next")
1528
+ if overridden.returncode != 0:
1529
+ report(f"{label} a --not-a-loop post was refused: {overridden.stderr.strip()}")
1530
+ return 1
1531
+ if not chat_records_with(rtl, "soc", "not_a_loop: new assignment"):
1532
+ report(f"{label} the override's reason is not recorded on the post.")
1533
+ return 1
1534
+ problem = alternate("soc", 9)
1535
+ if problem:
1536
+ report(f"{label} after the override, {problem}")
1537
+ return 1
1538
+ again = chat(rtl, "post", "soc", "round 17")
1539
+ if again.returncode == 0:
1540
+ report(f"{label} a quick alternating post after the override run was accepted.")
1541
+ return 1
1542
+ chat(verify, "post", "soc", "round 17 again")
1543
+ if len(systems("soc")) != 1:
1544
+ report(f"{label} expected one system record after the repeat trip, found {len(systems('soc'))}.")
1545
+ return 1
1546
+ if " - owner" not in systems("soc")[0]:
1547
+ report(f"{label} the system record does not mention owner:\n{systems('soc')[0]}")
1548
+ return 1
1549
+ refused_override = chat(rtl, "post", "soc", "--not-a-loop", "really", "x")
1550
+ if refused_override.returncode == 0:
1551
+ report(f"{label} an override was accepted after the owner was called.")
1552
+ return 1
1553
+ owner = chat(rtl, "post", "soc", "Stop and summarize, please.", role="owner")
1554
+ if owner.returncode != 0:
1555
+ report(f"{label} the owner's post was refused: {owner.stderr.strip()}")
1556
+ return 1
1557
+ resumed = chat(rtl, "post", "soc", "Summary: the clock fix is in.")
1558
+ if resumed.returncode != 0:
1559
+ report(f"{label} rtl could not post after the owner did: {resumed.stderr.strip()}")
1560
+ return 1
1561
+
1562
+ direct = lambda cwd, text: chat(cwd, "dm", "verify" if cwd == rtl else "rtl", text)
1563
+ for step in (lambda: alternate("dm-rtl--verify", 0, direct),
1564
+ lambda: None if chat(rtl, "dm", "verify", "--not-a-loop", "work", "x").returncode == 0 else "the direct override was refused",
1565
+ lambda: alternate("dm-rtl--verify", 1, direct)):
1566
+ problem = step()
1567
+ if problem:
1568
+ report(f"{label} in the direct group, {problem}")
1569
+ return 1
1570
+ escalated = chat(verify, "dm", "rtl", "one more")
1571
+ if escalated.returncode == 0:
1572
+ report(f"{label} the repeat trip in the direct group was accepted.")
1573
+ return 1
1574
+ if "another member" in escalated.stderr:
1575
+ report(f"{label} the direct group's refusal names another member: {escalated.stderr.strip()}")
1576
+ return 1
1577
+
1578
+ run_keel(rtl, "chat", "group", "create", "slow", "--member", "verify", env=env)
1579
+ problem = alternate("slow", 0)
1580
+ if problem:
1581
+ report(f"{label} {problem}")
1582
+ return 1
1583
+ hours_ago = (datetime.now().astimezone() - timedelta(hours=3)).isoformat(timespec="seconds")
1584
+ for record in chat_log(rtl, "slow").glob("*.md"):
1585
+ text = record.read_text(encoding="utf-8")
1586
+ record.write_text(re.sub(r"^created: .*$", f"created: {hours_ago}", text, count=1, flags=re.M), encoding="utf-8")
1587
+ slow = chat(rtl, "post", "slow", "a new piece of work, hours later")
1588
+ if slow.returncode != 0:
1589
+ report(f"{label} a post after a slow exchange was refused: {slow.stderr.strip()}")
1590
+ return 1
1591
+
1592
+ write_text(lint / "keel" / "chat.json", json.dumps({"limits": {"rate": 3, "window_minutes": 10}}) + "\n")
1593
+ for index in range(3):
1594
+ within = chat(lint, "post", "soc", f"lint note {index}")
1595
+ if within.returncode != 0:
1596
+ report(f"{label} lint post {index} was refused within the limit: {within.stderr.strip()}")
1597
+ return 1
1598
+ over = chat(lint, "post", "soc", "lint note 3")
1599
+ if over.returncode == 0:
1600
+ report(f"{label} a fourth post within ten minutes was accepted with limits.rate 3.")
1601
+ return 1
1602
+ if "limits.rate" not in over.stderr:
1603
+ report(f"{label} the rate refusal does not name limits.rate: {over.stderr.strip()}")
1604
+ return 1
1605
+ for index in range(4):
1606
+ boss = chat(lint, "post", "soc", f"owner note {index}", role="owner")
1607
+ if boss.returncode != 0:
1608
+ report(f"{label} the owner was rate-limited: {boss.stderr.strip()}")
1609
+ return 1
1610
+
1611
+ if "chat-loop-guards" not in {name for name, _ in registry.SCENARIOS}:
1612
+ report(f"{label} scenario is not registered.")
1613
+ return 1
1614
+ report("chat-loop-guards scenario passed.")
1615
+ return 0
1616
+
1617
+
1618
+ def validate_chat_human_view_scenario() -> int:
1619
+ """Issue #187: a person reads and posts from the terminal and a transcript.
1620
+
1621
+ The owner posts by role; the group view shows local times, mention, reply,
1622
+ and todo markers, and each member's presence; `--since` limits the window;
1623
+ `--follow` prints a message posted from another worktree while it runs;
1624
+ and the per-group Markdown transcript is regenerated after each write.
1625
+ """
1626
+ label = "chat-human-view:"
1627
+ with tempfile.TemporaryDirectory(prefix="keel-chat-view-") as raw:
1628
+ base = Path(raw)
1629
+ rtl, verify, env = chat_scratch_group(base)
1630
+
1631
+ def chat(cwd: Path, *args: str, role: str | None = None) -> subprocess.CompletedProcess[str]:
1632
+ extra = {"KEEL_CHAT_ROLE": role} if role else {}
1633
+ return run_keel(cwd, "chat", *args, env={**env, **extra})
1634
+
1635
+ hello = chat(rtl, "soc", "hello from the phone", role="owner")
1636
+ if hello.returncode != 0:
1637
+ report(f"{label} the owner could not post with keel chat soc <text>: {hello.stderr.strip()}")
1638
+ return 1
1639
+ root_id = chat_json(chat(rtl, "post", "soc", "@verify check the clock", "--json")).get("id", "")
1640
+ chat(verify, "post", "soc", "on it", "--reply-to", root_id)
1641
+ chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun the suite")
1642
+ old_id = "20200101T000000000Z-rtl-0c0c0c"
1643
+ old_created = (datetime.now(timezone.utc) - timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
1644
+ write_text(
1645
+ chat_log(rtl, "soc") / f"{old_id}.md",
1646
+ f"---\nid: {old_id}\ngroup: soc\nkind: message\nfrom: rtl\ncreated: {old_created}\n---\n\nback-dated note\n",
1647
+ )
1648
+
1649
+ view = chat(rtl, "soc", "--peek")
1650
+ text = view.stdout
1651
+ for needle, what in (
1652
+ ("owner: hello from the phone", "the owner's message"),
1653
+ ("@verify", "the mention marker"),
1654
+ (f"↳ {root_id}", "the reply marker"),
1655
+ ("[todo → verify", "the todo marker"),
1656
+ ):
1657
+ if needle not in text:
1658
+ report(f"{label} the view lacks {what} ({needle!r}):\n{text}{view.stderr}")
1659
+ return 1
1660
+ if not re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d rtl", text, re.M):
1661
+ report(f"{label} the view shows no local date and HH:MM before a sender:\n{text}")
1662
+ return 1
1663
+ presence = re.search(r"^Members: (.*)$", text, re.M)
1664
+ if not presence:
1665
+ report(f"{label} the view has no Members presence line:\n{text}")
1666
+ return 1
1667
+ for role in ("rtl", "verify"):
1668
+ if not re.search(rf"{role} \((online|idle|offline)", presence.group(1)):
1669
+ report(f"{label} the presence line gives no state for {role}: {presence.group(1)}")
1670
+ return 1
1671
+
1672
+ chat(rtl, "post", "soc", "@all standup in five")
1673
+ everyone = chat(rtl, "soc", "--peek").stdout
1674
+ if "@all @all" in everyone:
1675
+ report(f"{label} the view repeats a mention its text already shows: {everyone}")
1676
+ return 1
1677
+ recent = chat(rtl, "soc", "--peek", "--since", "1m")
1678
+ if "back-dated note" in recent.stdout:
1679
+ report(f"{label} --since 1m still shows a record from two hours ago.")
1680
+ return 1
1681
+ if "on it" not in recent.stdout:
1682
+ report(f"{label} --since 1m dropped a record from just now:\n{recent.stdout}{recent.stderr}")
1683
+ return 1
1684
+
1685
+ follower = subprocess.Popen(
1686
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "soc", "--follow", "--peek"],
1687
+ cwd=verify, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
1688
+ )
1689
+ lines_seen: list[str] = []
1690
+ reader = threading.Thread(
1691
+ target=lambda: lines_seen.extend(iter(follower.stdout.readline, "")), daemon=True,
1692
+ )
1693
+ reader.start()
1694
+ try:
1695
+ time.sleep(1.5)
1696
+ chat(rtl, "post", "soc", "followed message")
1697
+ deadline = time.time() + 5
1698
+ while time.time() < deadline and not any("followed message" in line for line in lines_seen):
1699
+ time.sleep(0.2)
1700
+ # A record whose id sorts before ones already shown — written by a
1701
+ # machine whose clock runs behind — must still be printed (#196).
1702
+ late_id = "20200101T000001000Z-verify-1a7e1a"
1703
+ write_text(
1704
+ chat_log(rtl, "soc") / f"{late_id}.md",
1705
+ f"---\nid: {late_id}\ngroup: soc\nkind: message\nfrom: verify\n"
1706
+ "created: 2020-01-01T00:00:01+00:00\n---\n\nlate arrival\n",
1707
+ )
1708
+ deadline = time.time() + 5
1709
+ while time.time() < deadline and not any("late arrival" in line for line in lines_seen):
1710
+ time.sleep(0.2)
1711
+ finally:
1712
+ follower.terminate()
1713
+ follower.wait(timeout=5)
1714
+ seen = "".join(lines_seen)
1715
+ if "followed message" not in seen:
1716
+ report(f"{label} --follow did not print a message posted from another worktree within five seconds: {seen!r}")
1717
+ return 1
1718
+ if "late arrival" not in seen:
1719
+ report(f"{label} --follow did not print a record whose id sorts before the ones already shown: {seen!r}")
1720
+ return 1
1721
+
1722
+ transcript = mailbox_common_dir(rtl) / "keel-chat" / "transcripts" / "soc.md"
1723
+ if not transcript.is_file():
1724
+ report(f"{label} no transcript at {transcript}.")
1725
+ return 1
1726
+ lines = transcript.read_text(encoding="utf-8").splitlines()
1727
+ headings = [line for line in lines if re.match(r"^## \d{4}-\d\d-\d\d$", line)]
1728
+ if not headings or len(headings) != len(set(headings)):
1729
+ report(f"{label} the transcript's day headings are missing or repeated: {headings!r}")
1730
+ return 1
1731
+ for message in ("hello from the phone", "followed message", "on it"):
1732
+ if not any(re.match(rf"^\d\d:\d\d \S+: .*{re.escape(message)}", line) for line in lines):
1733
+ report(f"{label} the transcript has no `HH:MM sender: text` line for {message!r}.")
1734
+ return 1
1735
+
1736
+ if "chat-human-view" not in {name for name, _ in registry.SCENARIOS}:
1737
+ report(f"{label} scenario is not registered.")
1738
+ return 1
1739
+ report("chat-human-view scenario passed.")
1740
+ return 0
1741
+
1742
+
1743
+ def chat_bridge_node_missing(label: str) -> bool:
1744
+ """Whether this Node lacks the WebSocket the bridge needs (Node 22+).
1745
+
1746
+ On the Node 20 floor the bridge scenarios report themselves skipped; the
1747
+ full-gate workflow runs them again on Node 22 in the same job.
1748
+ """
1749
+ probe = subprocess.run(
1750
+ ["node", "-p", "typeof globalThis.WebSocket"], capture_output=True, text=True,
1751
+ )
1752
+ if probe.stdout.strip() == "function":
1753
+ return False
1754
+ report(f"{label} skipped: keel chat bridge needs Node 22 or newer for its built-in WebSocket; this Node has none.")
1755
+ return True
1756
+
1757
+
1758
+ def fake_slack_class():
1759
+ """The local Slack stand-in, loaded by path from beside this script.
1760
+
1761
+ `scripts/fake_slack.py` uses the standard library only; it is loaded from
1762
+ its file rather than imported by name, so this validator keeps importing
1763
+ nothing but the standard library.
1764
+ """
1765
+ import importlib.util # noqa: PLC0415 - only the Slack scenarios need it
1766
+
1767
+ spec = importlib.util.spec_from_file_location("keel_fake_slack", ROOT / "scripts" / "fake_slack.py")
1768
+ module = importlib.util.module_from_spec(spec)
1769
+ spec.loader.exec_module(module)
1770
+ return module.FakeSlack
1771
+
1772
+
1773
+ def chat_slack_config(repo: Path, channels: dict[str, str], *, enabled: bool = True, **extra: object) -> None:
1774
+ config = {
1775
+ "slack": {
1776
+ "enabled": enabled,
1777
+ "owner": "UOWNER",
1778
+ "members": {"UOWNER": "owner"},
1779
+ "channels": channels,
1780
+ **extra,
1781
+ }
1782
+ }
1783
+ write_text(repo / "keel" / "chat.json", json.dumps(config, indent=2) + "\n")
1784
+
1785
+
1786
+ def chat_bridge_environment(env: dict[str, str], home: Path, slack) -> dict[str, str]:
1787
+ return {
1788
+ **env,
1789
+ "KEEL_HOME": str(home),
1790
+ "KEEL_SLACK_API_BASE": slack.api_base,
1791
+ "KEEL_SLACK_BOT_TOKEN": "xoxb-test-bot",
1792
+ "KEEL_SLACK_APP_TOKEN": "xapp-test-app",
1793
+ "KEEL_CHAT_MACHINE": "mac-test",
1794
+ }
1795
+
1796
+
1797
+ def slack_payload(call: dict) -> dict:
1798
+ metadata = call["params"].get("metadata") or {}
1799
+ if isinstance(metadata, str):
1800
+ metadata = json.loads(metadata)
1801
+ return (metadata or {}).get("event_payload") or {}
1802
+
1803
+
1804
+ def validate_chat_bridge_outbound_scenario() -> int:
1805
+ """Issue #187: the bridge posts an opted-in project's records to Slack.
1806
+
1807
+ Runs `keel chat bridge run --once` against a local fake Slack. Each record
1808
+ is posted once, under its role's name, with the exact record in message
1809
+ metadata; replies thread; a mention of the owner becomes a Slack mention;
1810
+ secrets are redacted on the way out and kept locally; long text is cut
1811
+ with a pointer; a 429 is waited out; done, edit, and retract follow their
1812
+ message; a project that did not opt in sends nothing; and a Node without
1813
+ WebSocket is told it needs Node 22.
1814
+ """
1815
+ label = "chat-bridge-outbound:"
1816
+ if chat_bridge_node_missing("chat-bridge-outbound"):
1817
+ return 3
1818
+ FakeSlack = fake_slack_class()
1819
+ with tempfile.TemporaryDirectory(prefix="keel-chat-out-") as raw, FakeSlack() as slack:
1820
+ base = Path(raw)
1821
+ rtl, verify, env = chat_scratch_group(base)
1822
+ quiet = mailbox_repository(base / "quiet")
1823
+ run_keel(quiet, "chat", "role", "--set", "rtl", env=env)
1824
+ run_keel(quiet, "chat", "group", "create", "ops", env=env)
1825
+ chat_slack_config(rtl, {"soc": "CSOC"})
1826
+ chat_slack_config(quiet, {"ops": "COPS"}, enabled=False)
1827
+ benv = chat_bridge_environment(env, base / "home", slack)
1828
+
1829
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
1830
+ return run_keel(cwd, "chat", *args, env=benv)
1831
+
1832
+ for project in (rtl, quiet):
1833
+ added = chat(project, "bridge", "add")
1834
+ if added.returncode != 0:
1835
+ report(f"{label} bridge add failed in {project.name}: {added.stderr.strip()}")
1836
+ return 1
1837
+ chat(quiet, "post", "ops", "not for slack")
1838
+ root_id = chat_json(chat(rtl, "post", "soc", "Clock fix is in", "--json")).get("id", "")
1839
+ reply_id = chat_json(chat(verify, "post", "soc", "@owner done?", "--reply-to", root_id, "--json")).get("id", "")
1840
+ long_id = chat_json(chat(rtl, "post", "soc", "x" * 5000, "--json")).get("id", "")
1841
+ secret_id = chat_json(chat(rtl, "post", "soc", "token is xoxb-123-456-abcdef ok", "--json")).get("id", "")
1842
+ todo_id = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun", "--json")).get("id", "")
1843
+ chat(verify, "done", todo_id)
1844
+ chat(rtl, "edit", root_id, "Clock fix is in (v2)")
1845
+ gone_id = chat_json(chat(rtl, "post", "soc", "wrong group", "--json")).get("id", "")
1846
+ chat(rtl, "retract", gone_id)
1847
+ asked_id = chat_json(chat(rtl, "post", "soc", "@verify confirm the clock", "--ack", "--json")).get("id", "")
1848
+ ack_id = chat_json(chat(verify, "ack", asked_id, "--json")).get("id", "")
1849
+ old_rule_id = chat_json(chat(rtl, "post", "soc", "verify owns integration", "--json")).get("id", "")
1850
+ new_rule_id = chat_json(chat(rtl, "post", "soc", "design owns integration", "--supersedes", old_rule_id, "--json")).get("id", "")
1851
+ slack.rate_limit("chat.postMessage", 1)
1852
+
1853
+ started = time.time()
1854
+ run = chat(rtl, "bridge", "run", "--once")
1855
+ elapsed = time.time() - started
1856
+ if run.returncode != 0:
1857
+ report(f"{label} bridge run --once failed: {run.stderr.strip()} {run.stdout.strip()}")
1858
+ return 1
1859
+
1860
+ posts = slack.calls_to("chat.postMessage")
1861
+ by_id: dict[str, list[dict]] = {}
1862
+ for call in posts:
1863
+ by_id.setdefault(slack_payload(call).get("id", ""), []).append(call)
1864
+ for record_id in (root_id, reply_id, long_id, secret_id, todo_id, gone_id):
1865
+ if len(by_id.get(record_id, [])) != 1:
1866
+ report(f"{label} record {record_id} was posted {len(by_id.get(record_id, []))} times, not once.")
1867
+ return 1
1868
+ root = by_id[root_id][0]
1869
+ if root["params"].get("username") != "rtl":
1870
+ report(f"{label} the post is not under the role's name: username {root['params'].get('username')!r}.")
1871
+ return 1
1872
+ if root["params"].get("channel") != "CSOC":
1873
+ report(f"{label} the post went to {root['params'].get('channel')!r}, not the mapped CSOC.")
1874
+ return 1
1875
+ metadata = root["params"].get("metadata")
1876
+ metadata = json.loads(metadata) if isinstance(metadata, str) else metadata
1877
+ if (metadata or {}).get("event_type") != "keel_chat_record":
1878
+ report(f"{label} the post's metadata is not a keel_chat_record: {metadata!r}")
1879
+ return 1
1880
+ payload = slack_payload(root)
1881
+ if payload.get("from") != "rtl":
1882
+ report(f"{label} the metadata payload does not carry the record's sender: {payload!r}")
1883
+ return 1
1884
+ if payload.get("kind") != "message":
1885
+ report(f"{label} the metadata payload does not carry the record's kind: {payload!r}")
1886
+ return 1
1887
+ root_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == root_id)
1888
+ reply = by_id[reply_id][0]["params"]
1889
+ if reply.get("thread_ts") != root_ts:
1890
+ report(f"{label} the reply's thread_ts is {reply.get('thread_ts')!r}, not the root's {root_ts!r}.")
1891
+ return 1
1892
+ if "<@UOWNER>" not in reply.get("text", ""):
1893
+ report(f"{label} a mention of owner did not become a Slack mention: {reply.get('text')!r}")
1894
+ return 1
1895
+ long_text = by_id[long_id][0]["params"].get("text", "")
1896
+ if len(long_text) > 3200:
1897
+ report(f"{label} a 5,000-character body was sent at {len(long_text)} characters, not cut.")
1898
+ return 1
1899
+ if "keel chat show" not in long_text:
1900
+ report(f"{label} the cut body carries no keel chat show pointer.")
1901
+ return 1
1902
+ secret_text = by_id[secret_id][0]["params"].get("text", "")
1903
+ if "xoxb-123" in secret_text:
1904
+ report(f"{label} a token was sent to Slack: {secret_text!r}")
1905
+ return 1
1906
+ if "[redacted]" not in secret_text:
1907
+ report(f"{label} the redacted text carries no [redacted] marker: {secret_text!r}")
1908
+ return 1
1909
+ if "xoxb-123-456-abcdef" not in (chat_log(rtl, "soc") / f"{secret_id}.md").read_text(encoding="utf-8"):
1910
+ report(f"{label} redaction changed the local record.")
1911
+ return 1
1912
+ if not any(call.get("rate_limited") for call in slack.calls if call["method"] == "chat.postMessage"):
1913
+ report(f"{label} the fake server never answered 429, so the retry was not exercised.")
1914
+ return 1
1915
+ if elapsed < 1.0:
1916
+ report(f"{label} the run finished in {elapsed:.2f}s, before the 1s Retry-After passed.")
1917
+ return 1
1918
+ if any(call["params"].get("channel") == "COPS" for call in slack.calls):
1919
+ report(f"{label} a project without slack.enabled was posted to Slack.")
1920
+ return 1
1921
+ todo_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == todo_id)
1922
+ reactions = slack.calls_to("reactions.add")
1923
+ if not any(c["params"].get("timestamp") == todo_ts and c["params"].get("name") == "white_check_mark" for c in reactions):
1924
+ report(f"{label} the done todo did not get a ✅ reaction: {reactions!r}")
1925
+ return 1
1926
+ updates = slack.calls_to("chat.update")
1927
+ if not any(c["params"].get("ts") == root_ts and "v2" in c["params"].get("text", "") for c in updates):
1928
+ report(f"{label} the edit did not call chat.update on the root: {updates!r}")
1929
+ return 1
1930
+ gone_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == gone_id)
1931
+ if not any(c["params"].get("ts") == gone_ts for c in slack.calls_to("chat.delete")):
1932
+ report(f"{label} the retraction did not call chat.delete.")
1933
+ return 1
1934
+ # Issue #253: an acknowledgement stays local.
1935
+ if not ack_id:
1936
+ report(f"{label} the acknowledgement returned no id.")
1937
+ return 1
1938
+ carried = [c for c in slack.calls if ack_id in json.dumps(c.get("params", {}))]
1939
+ if carried:
1940
+ report(f"{label} the acknowledgement {ack_id} reached Slack: {carried!r}")
1941
+ return 1
1942
+ # Issue #252: a superseded record's Slack copy says so.
1943
+ if not new_rule_id:
1944
+ report(f"{label} the superseding post returned no id.")
1945
+ return 1
1946
+ old_rule_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == old_rule_id)
1947
+ marked = [c for c in slack.calls_to("chat.update") if c["params"].get("ts") == old_rule_ts]
1948
+ if not marked:
1949
+ report(f"{label} the superseded record's Slack message was never updated.")
1950
+ return 1
1951
+ if not marked[-1]["params"].get("text", "").startswith(f"(superseded by {new_rule_id})"):
1952
+ report(f"{label} the superseded Slack message does not open with its successor: {marked[-1]['params'].get('text')!r}")
1953
+ return 1
1954
+
1955
+ before = len(slack.calls_to("chat.postMessage"))
1956
+ # launchd starts the bridge in `/`, outside every repository, so the
1957
+ # second run starts outside one too.
1958
+ elsewhere = base / "elsewhere"
1959
+ elsewhere.mkdir()
1960
+ again = chat(elsewhere, "bridge", "run", "--once")
1961
+ if again.returncode != 0:
1962
+ report(f"{label} a bridge run started outside any repository failed: {again.stderr.strip()}")
1963
+ return 1
1964
+ if len(slack.calls_to("chat.postMessage")) != before:
1965
+ report(f"{label} a second run posted records again.")
1966
+ return 1
1967
+
1968
+ no_ws = base / "no-websocket.js"
1969
+ write_text(no_ws, "delete globalThis.WebSocket;\n")
1970
+ old_node = run_keel(rtl, "chat", "bridge", "run", "--once", env={**benv, "NODE_OPTIONS": f"--require {no_ws}"})
1971
+ if old_node.returncode == 0:
1972
+ report(f"{label} bridge run started without a WebSocket implementation.")
1973
+ return 1
1974
+ if "Node 22" not in old_node.stderr:
1975
+ report(f"{label} the missing-WebSocket refusal does not name Node 22: {old_node.stderr.strip()}")
1976
+ return 1
1977
+
1978
+ if "chat-bridge-outbound" not in {name for name, _ in registry.SCENARIOS}:
1979
+ report(f"{label} scenario is not registered.")
1980
+ return 1
1981
+ report("chat-bridge-outbound scenario passed.")
1982
+ return 0
1983
+
1984
+
1985
+ def start_chat_bridge(cwd: Path, env: dict[str, str]) -> subprocess.Popen:
1986
+ return subprocess.Popen(
1987
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "bridge", "run"],
1988
+ cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
1989
+ )
1990
+
1991
+
1992
+ def stop_chat_bridge(process: subprocess.Popen) -> str:
1993
+ process.terminate()
1994
+ try:
1995
+ _, stderr = process.communicate(timeout=10)
1996
+ except subprocess.TimeoutExpired:
1997
+ process.kill()
1998
+ _, stderr = process.communicate()
1999
+ return stderr or ""
2000
+
2001
+
2002
+ def slack_event(channel: str, **fields: object) -> dict:
2003
+ return {"type": "event_callback", "event": {"type": "message", "channel": channel, **fields}}
2004
+
2005
+
2006
+ def validate_chat_bridge_inbound_scenario() -> int:
2007
+ """Issue #187: what arrives from Slack, and only that, reaches the store.
2008
+
2009
+ A running `keel chat bridge run` against the fake server: a registered
2010
+ person's message is imported and wakes the session it mentions; a
2011
+ stranger's is ignored and counted; another machine's post is rebuilt from
2012
+ its metadata exactly once, fetching metadata the event lacked; this
2013
+ bridge's own post is not re-imported; threads, edits, deletions, ✅, and
2014
+ files map onto records; two projects sharing a channel both get a post;
2015
+ and what was missed while stopped is caught up once.
2016
+ """
2017
+ label = "chat-bridge-inbound:"
2018
+ if chat_bridge_node_missing("chat-bridge-inbound"):
2019
+ return 3
2020
+ FakeSlack = fake_slack_class()
2021
+ with tempfile.TemporaryDirectory(prefix="keel-chat-in-") as raw, FakeSlack() as slack:
2022
+ base = Path(raw)
2023
+ rtl, verify, env = chat_scratch_group(base)
2024
+ chat_slack_config(rtl, {"soc": "CSOC"})
2025
+ shared = []
2026
+ for name in ("a", "b"):
2027
+ repo = mailbox_repository(base / name)
2028
+ run_keel(repo, "chat", "role", "--set", "rtl", env=env)
2029
+ run_keel(repo, "chat", "group", "create", "ops", env=env)
2030
+ chat_slack_config(repo, {"ops": "COPS"})
2031
+ shared.append(repo)
2032
+ benv = chat_bridge_environment(env, base / "home", slack)
2033
+
2034
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
2035
+ return run_keel(cwd, "chat", *args, env=benv)
2036
+
2037
+ for project in (rtl, *shared):
2038
+ chat(project, "bridge", "add")
2039
+ signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "verify"
2040
+ envelopes: list[str] = []
2041
+
2042
+ def push(payload: dict, kind: str = "events_api") -> None:
2043
+ envelopes.append(slack.push(payload, kind))
2044
+
2045
+ bridge = start_chat_bridge(rtl, benv)
2046
+ try:
2047
+ if not slack.wait_for(lambda: slack.sockets, 10):
2048
+ report(f"{label} the bridge never opened a Socket Mode connection: {stop_chat_bridge(bridge).strip()}")
2049
+ return 1
2050
+
2051
+ push(slack_event("CSOC", user="UOWNER", text="@verify rerun please", ts="1800000001.000100"))
2052
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "@verify rerun please")):
2053
+ report(f"{label} the registered owner's message was not imported.")
2054
+ return 1
2055
+ owner_record = chat_records_with(rtl, "soc", "@verify rerun please")[0]
2056
+ if "from: owner" not in owner_record:
2057
+ report(f"{label} the owner's message was not imported as role owner:\n{owner_record}")
2058
+ return 1
2059
+ if " - verify" not in owner_record:
2060
+ report(f"{label} the owner's @verify did not become a mention:\n{owner_record}")
2061
+ return 1
2062
+ # The record is written before the signal is appended (#231), so
2063
+ # wait for the signal rather than reading it once.
2064
+ if not slack.wait_for(lambda: signal.exists() and signal.stat().st_size, 5):
2065
+ report(f"{label} the owner's mention did not touch verify's signal file.")
2066
+ return 1
2067
+
2068
+ size = signal.stat().st_size
2069
+ push(slack_event("CSOC", user="USTRANGER", text="@verify delete everything", ts="1800000002.000100"))
2070
+ if not slack.wait_for(lambda: chat_json(chat(rtl, "bridge", "status", "--json")).get("ignored") == 1):
2071
+ report(f"{label} bridge status does not count the stranger's message: {chat(rtl, 'bridge', 'status', '--json').stdout.strip()}")
2072
+ return 1
2073
+ if chat_records_with(rtl, "soc", "delete everything"):
2074
+ report(f"{label} an unregistered user's message reached the store.")
2075
+ return 1
2076
+ if signal.stat().st_size != size:
2077
+ report(f"{label} an unregistered user's message touched a signal file.")
2078
+ return 1
2079
+
2080
+ remote_id = "20261001T080000000Z-codex-maint-abcdef"
2081
+ remote = {
2082
+ "subtype": "bot_message", "bot_id": "BOTHER", "username": "codex-maint",
2083
+ "text": "from codex", "ts": "1800000003.000100",
2084
+ "metadata": {"event_type": "keel_chat_record", "event_payload": {
2085
+ "project": "rtl", "id": remote_id, "kind": "message", "from": "codex-maint",
2086
+ "group": "soc", "mentions": ["verify"]}},
2087
+ }
2088
+ push(slack_event("CSOC", **remote))
2089
+ remote_file = chat_log(rtl, "soc") / f"{remote_id}.md"
2090
+ if not slack.wait_for(remote_file.is_file):
2091
+ report(f"{label} another machine's post was not rebuilt under its record id.")
2092
+ return 1
2093
+ rebuilt = remote_file.read_text(encoding="utf-8")
2094
+ if "from: codex-maint" not in rebuilt:
2095
+ report(f"{label} the rebuilt record lost its sender:\n{rebuilt}")
2096
+ return 1
2097
+ if " - verify" not in rebuilt:
2098
+ report(f"{label} the rebuilt record lost its mentions:\n{rebuilt}")
2099
+ return 1
2100
+ push(slack_event("CSOC", **remote))
2101
+ time.sleep(1.0)
2102
+ if len(chat_records_with(rtl, "soc", "from codex")) != 1:
2103
+ report(f"{label} a repeated event imported the same record twice.")
2104
+ return 1
2105
+
2106
+ bare_id = "20261001T080100000Z-codex-maint-fedcba"
2107
+ stored = slack.add_history("CSOC", {
2108
+ "subtype": "bot_message", "bot_id": "BOTHER", "username": "codex-maint", "text": "metadata later",
2109
+ "metadata": {"event_type": "keel_chat_record", "event_payload": {
2110
+ "project": "rtl", "id": bare_id, "kind": "message", "from": "codex-maint", "group": "soc"}},
2111
+ })
2112
+ push(slack_event("CSOC", subtype="bot_message", bot_id="BOTHER", username="codex-maint", text="metadata later", ts=stored["ts"]))
2113
+ if not slack.wait_for((chat_log(rtl, "soc") / f"{bare_id}.md").is_file):
2114
+ report(f"{label} a bot message without metadata in its event was not resolved through history.")
2115
+ return 1
2116
+ if not any(str(c["params"].get("include_all_metadata")).lower() in ("1", "true") for c in slack.calls_to("conversations.history")):
2117
+ report(f"{label} metadata was not fetched with include_all_metadata.")
2118
+ return 1
2119
+
2120
+ echo_id = chat_json(chat(rtl, "post", "soc", "local echo", "--json")).get("id", "")
2121
+ if not slack.wait_for(lambda: any(slack_payload(c).get("id") == echo_id for c in slack.calls_to("chat.postMessage"))):
2122
+ report(f"{label} the running bridge did not post a new local record.")
2123
+ return 1
2124
+ echo = next(m for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == echo_id)
2125
+ push(slack_event("CSOC", subtype="bot_message", bot_id="BBOT", username="rtl", text="local echo", ts=echo["ts"], metadata=echo["metadata"]))
2126
+ time.sleep(1.0)
2127
+ if len(chat_records_with(rtl, "soc", "local echo")) != 1:
2128
+ report(f"{label} this bridge's own post was imported back into its project.")
2129
+ return 1
2130
+
2131
+ push(slack_event("CSOC", user="UOWNER", text="noted", ts="1800000010.000100", thread_ts=echo["ts"]))
2132
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "noted")):
2133
+ report(f"{label} the owner's thread reply was not imported.")
2134
+ return 1
2135
+ if f"reply_to: {echo_id}" not in chat_records_with(rtl, "soc", "noted")[0]:
2136
+ report(f"{label} the thread reply does not point at its root {echo_id}.")
2137
+ return 1
2138
+
2139
+ push(slack_event("CSOC", subtype="message_changed", message={"user": "UOWNER", "text": "@verify rerun now", "ts": "1800000001.000100"}, previous_message={"user": "UOWNER", "ts": "1800000001.000100"}))
2140
+ if not slack.wait_for(lambda: any("kind: edit" in r for r in chat_records_with(rtl, "soc", "rerun now"))):
2141
+ report(f"{label} a Slack edit did not become an edit record.")
2142
+ return 1
2143
+ push(slack_event("CSOC", subtype="message_deleted", deleted_ts="1800000010.000100", previous_message={"user": "UOWNER", "ts": "1800000010.000100"}))
2144
+ if not slack.wait_for(lambda: any("kind: retract" in p.read_text(encoding="utf-8") for p in chat_log(rtl, "soc").glob("*.md"))):
2145
+ report(f"{label} a Slack deletion did not become a retract record.")
2146
+ return 1
2147
+
2148
+ todo_id = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun", "--json")).get("id", "")
2149
+ if not slack.wait_for(lambda: any(slack_payload(c).get("id") == todo_id for c in slack.calls_to("chat.postMessage"))):
2150
+ report(f"{label} the todo was not posted.")
2151
+ return 1
2152
+ todo_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == todo_id)
2153
+ push({"type": "event_callback", "event": {"type": "reaction_added", "user": "UOWNER", "reaction": "white_check_mark", "item": {"type": "message", "channel": "CSOC", "ts": todo_ts}}})
2154
+ if not slack.wait_for(lambda: todo_id not in [t.get("id") for t in chat_json(chat(rtl, "todos", "--json")).get("todos", [])]):
2155
+ report(f"{label} a ✅ from a registered user did not close the todo.")
2156
+ return 1
2157
+
2158
+ push(slack_event("CSOC", user="UOWNER", text="waveform", ts="1800000020.000100", files=[{"name": "wave.vcd", "permalink": "https://files.example/wave.vcd"}]))
2159
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "https://files.example/wave.vcd")):
2160
+ report(f"{label} a shared file did not become a link line.")
2161
+ return 1
2162
+
2163
+ a, b = shared
2164
+ ops_id = chat_json(chat(a, "post", "ops", "shared hello", "--json")).get("id", "")
2165
+ if not slack.wait_for(lambda: chat_records_with(b, "ops", "shared hello")):
2166
+ report(f"{label} project b did not receive project a's post in the shared channel.")
2167
+ return 1
2168
+ ops_posts = [c for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == ops_id]
2169
+ if len(ops_posts) != 1:
2170
+ report(f"{label} the shared-channel post was sent {len(ops_posts)} times, not once.")
2171
+ return 1
2172
+ if ops_posts[0]["params"].get("username") != "a/rtl":
2173
+ report(f"{label} the shared-channel post is not under a/rtl: {ops_posts[0]['params'].get('username')!r}")
2174
+ return 1
2175
+ if "from: a/rtl" not in chat_records_with(b, "ops", "shared hello")[0]:
2176
+ report(f"{label} project b's copy is not from a/rtl.")
2177
+ return 1
2178
+
2179
+ missing = [e for e in envelopes if e not in slack.acks]
2180
+ if missing:
2181
+ report(f"{label} envelopes were not acknowledged: {missing!r}")
2182
+ return 1
2183
+ finally:
2184
+ log = stop_chat_bridge(bridge)
2185
+
2186
+ slack.add_history("CSOC", {"user": "UOWNER", "text": "while you were away"})
2187
+ for _ in range(2):
2188
+ bridge = start_chat_bridge(rtl, benv)
2189
+ try:
2190
+ slack.wait_for(lambda: chat_records_with(rtl, "soc", "while you were away"), 10)
2191
+ time.sleep(1.0)
2192
+ finally:
2193
+ log = stop_chat_bridge(bridge)
2194
+ caught = chat_records_with(rtl, "soc", "while you were away")
2195
+ if len(caught) != 1:
2196
+ report(f"{label} a message sent while the bridge was down was imported {len(caught)} times, not once: {log.strip()}")
2197
+ return 1
2198
+
2199
+ if "chat-bridge-inbound" not in {name for name, _ in registry.SCENARIOS}:
2200
+ report(f"{label} scenario is not registered.")
2201
+ return 1
2202
+ report("chat-bridge-inbound scenario passed.")
2203
+ return 0
2204
+
2205
+
2206
+ def role_keychain(base: Path, tokens: dict[str, str]) -> Path:
2207
+ """A `security` double answering only the given Keychain accounts."""
2208
+ script = base / "role-keychain.sh"
2209
+ cases = "".join(f' *"-a {account} "*|*"-a {account}") echo {token} ;;\n' for account, token in tokens.items())
2210
+ write_text(script, f'#!/bin/sh\ncase "$* " in\n{cases} *) exit 44 ;;\nesac\n')
2211
+ script.chmod(0o755)
2212
+ return script
2213
+
2214
+
2215
+ def slack_posts_of(slack, channel: str, record_id: str) -> list[dict]:
2216
+ return [m for m in slack.messages.get(channel, []) if (m.get("metadata") or {}).get("event_payload", {}).get("id") == record_id]
2217
+
2218
+
2219
+ def bot_status(cwd: Path, env: dict[str, str], bot: str) -> dict:
2220
+ status = chat_json(run_keel(cwd, "chat", "bridge", "status", "--json", env=env))
2221
+ return next((entry for entry in status.get("bots") or [] if entry.get("bot") == bot), {})
2222
+
2223
+
2224
+ def validate_chat_role_apps_scenario() -> int:
2225
+ """Issue #187: a role may post under its own Slack app.
2226
+
2227
+ `slack.bots` registers a role's bot by its user id. A role whose Keychain
2228
+ token `auth.test` confirms posts with that token and without a borrowed
2229
+ name; a token for another bot is not used; a channel the role's bot is not
2230
+ in falls back to the shared app; a person's mention of a role's bot wakes
2231
+ the role; and the bridge's own edits through a role app are not imported
2232
+ back as someone else's.
2233
+ """
2234
+ label = "chat-role-apps:"
2235
+ if chat_bridge_node_missing("chat-role-apps"):
2236
+ return 3
2237
+ FakeSlack = fake_slack_class()
2238
+ with tempfile.TemporaryDirectory(prefix="keel-chat-roles-") as raw, FakeSlack() as slack:
2239
+ base = Path(raw)
2240
+ rtl, verify, env = chat_scratch_group(base)
2241
+ chat_slack_config(rtl, {"soc": "CSOC"}, bots={"UBOTRTL": "rtl", "UBOTVERIFY": "verify"})
2242
+ keychain = role_keychain(base, {"bot:rtl": "xoxb-role-rtl"})
2243
+ slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
2244
+ benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
2245
+
2246
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
2247
+ return run_keel(cwd, "chat", *args, env=benv)
2248
+
2249
+ def once() -> bool:
2250
+ result = chat(rtl, "bridge", "run", "--once")
2251
+ if result.returncode != 0:
2252
+ report(f"{label} bridge run --once failed: {result.stderr.strip()} {result.stdout.strip()}")
2253
+ return result.returncode == 0
2254
+
2255
+ chat(rtl, "bridge", "add")
2256
+ chat(rtl, "bot", "add", "rtl")
2257
+ own_id = chat_json(chat(rtl, "post", "soc", "rtl speaks", "--json")).get("id", "")
2258
+ shared_id = chat_json(chat(verify, "post", "soc", "verify speaks", "--json")).get("id", "")
2259
+ chat(rtl, "edit", own_id, "rtl speaks (v2)")
2260
+ if not once():
2261
+ return 1
2262
+ by_id = {slack_payload(c).get("id"): c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id")}
2263
+ own = by_id.get(own_id) or {}
2264
+ if own.get("_auth") != "Bearer xoxb-role-rtl":
2265
+ report(f"{label} rtl's post did not use rtl's own app token: {own.get('_auth')!r}")
2266
+ return 1
2267
+ if own.get("username"):
2268
+ report(f"{label} rtl's post through its own app still borrows a name: {own.get('username')!r}")
2269
+ return 1
2270
+ other = by_id.get(shared_id) or {}
2271
+ if other.get("_auth") != "Bearer xoxb-test-bot":
2272
+ report(f"{label} verify, registered but without a token here, did not post through the shared app: {other.get('_auth')!r}")
2273
+ return 1
2274
+ if other.get("username") != "verify":
2275
+ report(f"{label} verify's post through the shared app is not under its name: {other.get('username')!r}")
2276
+ return 1
2277
+ own_ts = (slack_posts_of(slack, "CSOC", own_id) or [{}])[0].get("ts")
2278
+ updates = [c["params"] for c in slack.calls_to("chat.update") if c["params"].get("ts") == own_ts]
2279
+ if not updates:
2280
+ report(f"{label} the edit of rtl's record never called chat.update.")
2281
+ return 1
2282
+ if updates[0].get("_auth") != "Bearer xoxb-role-rtl":
2283
+ report(f"{label} the edit of rtl's record did not use the app that posted it: {updates[0].get('_auth')!r}")
2284
+ return 1
2285
+ if bot_status(rtl, benv, "rtl").get("roles") != ["rtl/rtl"]:
2286
+ report(f"{label} status does not list bot rtl serving rtl/rtl: {bot_status(rtl, benv, 'rtl')!r}")
2287
+ return 1
2288
+ if bot_status(rtl, benv, "verify"):
2289
+ report(f"{label} status lists verify, which has no token on this machine.")
2290
+ return 1
2291
+
2292
+ slack.identify("xoxb-role-rtl", "UOTHER", "BOTHER")
2293
+ wrong_id = chat_json(chat(rtl, "post", "soc", "after a token swap", "--json")).get("id", "")
2294
+ if not once():
2295
+ return 1
2296
+ wrong = next((c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == wrong_id), {})
2297
+ if wrong.get("_auth") != "Bearer xoxb-test-bot":
2298
+ report(f"{label} a token whose auth.test names another bot was used for rtl: {wrong.get('_auth')!r}")
2299
+ return 1
2300
+ if wrong.get("username") != "rtl":
2301
+ report(f"{label} the fallback post is not under rtl's name: {wrong.get('username')!r}")
2302
+ return 1
2303
+ if bot_status(rtl, benv, "rtl").get("roles") != []:
2304
+ report(f"{label} status does not list the bot whose id no project maps as serving nothing: {bot_status(rtl, benv, 'rtl')!r}")
2305
+ return 1
2306
+
2307
+ slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
2308
+ slack.not_in_channel.add(("xoxb-role-rtl", "CSOC"))
2309
+ out_id = chat_json(chat(rtl, "post", "soc", "nobody invited me", "--json")).get("id", "")
2310
+ if not once():
2311
+ return 1
2312
+ landed = slack_posts_of(slack, "CSOC", out_id)
2313
+ if len(landed) != 1:
2314
+ report(f"{label} a post refused with not_in_channel landed {len(landed)} times, not once.")
2315
+ return 1
2316
+ if landed[0].get("username") != "rtl":
2317
+ report(f"{label} the not_in_channel fallback is not under rtl's name: {landed[0]!r}")
2318
+ return 1
2319
+ if "CSOC" not in (bot_status(rtl, benv, "rtl").get("invite") or []):
2320
+ report(f"{label} status does not name the channel rtl's bot must be invited to: {bot_status(rtl, benv, 'rtl')!r}")
2321
+ return 1
2322
+ slack.not_in_channel.clear()
2323
+
2324
+ bridge = start_chat_bridge(rtl, benv)
2325
+ try:
2326
+ if not slack.wait_for(lambda: slack.sockets, 10):
2327
+ report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
2328
+ return 1
2329
+ slack.push(slack_event("CSOC", user="UOWNER", text="<@UBOTVERIFY> rerun please", ts="1800000001.000100"))
2330
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "rerun please")):
2331
+ report(f"{label} the owner's message mentioning a role's bot was not imported.")
2332
+ return 1
2333
+ mention = chat_records_with(rtl, "soc", "rerun please")[0]
2334
+ if "@verify rerun please" not in mention:
2335
+ report(f"{label} the bot mention was not rewritten to the role:\n{mention}")
2336
+ return 1
2337
+ if " - verify" not in mention:
2338
+ report(f"{label} the bot mention did not become a mention of verify:\n{mention}")
2339
+ return 1
2340
+ slack.push(slack_event("CSOC", subtype="message_changed", message={"ts": own_ts, "bot_id": "BROLERTL", "text": "rewritten by an echo"}, ts="1800000002.000100"))
2341
+ slack.push(slack_event("CSOC", user="UOWNER", text="marker after the echo", ts="1800000003.000100"))
2342
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "marker after the echo")):
2343
+ report(f"{label} the marker message after the echo was not imported.")
2344
+ return 1
2345
+ if chat_records_with(rtl, "soc", "rewritten by an echo"):
2346
+ report(f"{label} the bridge's own edit through rtl's app was imported back as an edit.")
2347
+ return 1
2348
+ finally:
2349
+ stop_chat_bridge(bridge)
2350
+
2351
+ if "chat-role-apps" not in {name for name, _ in registry.SCENARIOS}:
2352
+ report(f"{label} scenario is not registered.")
2353
+ return 1
2354
+ report("chat-role-apps scenario passed.")
2355
+ return 0
2356
+
2357
+
2358
+ def validate_chat_role_direct_scenario() -> int:
2359
+ """Issue #187: a role's own app takes direct messages.
2360
+
2361
+ With `app:<role>` beside `bot:<role>`, the bridge opens a second Socket
2362
+ Mode connection for that app. A registered person's direct message becomes
2363
+ a record in the direct group and wakes the role; the role's answer goes
2364
+ back to that person's direct-message channel and nowhere else; a
2365
+ stranger's is ignored; and one sent while the bridge was down arrives once.
2366
+ """
2367
+ label = "chat-role-direct:"
2368
+ if chat_bridge_node_missing("chat-role-direct"):
2369
+ return 3
2370
+ FakeSlack = fake_slack_class()
2371
+ with tempfile.TemporaryDirectory(prefix="keel-chat-direct-") as raw, FakeSlack() as slack:
2372
+ base = Path(raw)
2373
+ rtl, _verify, env = chat_scratch_group(base)
2374
+ chat_slack_config(rtl, {"soc": "CSOC"}, bots={"UBOTRTL": "rtl"})
2375
+ keychain = role_keychain(base, {"bot:rtl": "xoxb-role-rtl", "app:rtl": "xapp-role-rtl"})
2376
+ slack.identify("xoxb-role-rtl", "UBOTRTL", "BROLERTL")
2377
+ benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
2378
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
2379
+ run_keel(rtl, "chat", "bot", "add", "rtl", env=benv)
2380
+ signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "rtl"
2381
+
2382
+ def direct(user: str, text: str, ts: str) -> dict:
2383
+ return slack_event("DUOWNER" if user == "UOWNER" else f"D{user}", channel_type="im", user=user, text=text, ts=ts)
2384
+
2385
+ bridge = start_chat_bridge(rtl, benv)
2386
+ try:
2387
+ if not slack.wait_for(lambda: slack.sockets_for("xapp-role-rtl"), 10):
2388
+ report(f"{label} the bridge opened no Socket Mode connection with rtl's app token: {stop_chat_bridge(bridge).strip()}")
2389
+ return 1
2390
+ if not slack.wait_for(lambda: slack.sockets_for("xapp-test-app"), 10):
2391
+ report(f"{label} the shared app's connection is missing beside rtl's.")
2392
+ return 1
2393
+ size = signal.stat().st_size if signal.exists() else 0
2394
+ slack.push(direct("UOWNER", "status?", "1800000001.000100"), app="xapp-role-rtl")
2395
+ if not slack.wait_for(lambda: chat_records_with(rtl, "dm-owner--rtl", "status?")):
2396
+ report(f"{label} the owner's direct message to rtl's app did not reach dm-owner--rtl.")
2397
+ return 1
2398
+ if "from: owner" not in chat_records_with(rtl, "dm-owner--rtl", "status?")[0]:
2399
+ report(f"{label} the direct message was not recorded from owner.")
2400
+ return 1
2401
+ if not signal.exists() or signal.stat().st_size <= size:
2402
+ report(f"{label} the direct message did not touch rtl's signal file.")
2403
+ return 1
2404
+
2405
+ answered = run_keel(rtl, "chat", "dm", "owner", "all green", env=benv)
2406
+ if answered.returncode != 0:
2407
+ report(f"{label} keel chat dm owner failed: {answered.stderr.strip()}")
2408
+ return 1
2409
+ if not slack.wait_for(lambda: any("all green" in m.get("text", "") for m in slack.messages.get("DUOWNER", []))):
2410
+ report(f"{label} rtl's answer never reached the owner's direct-message channel.")
2411
+ return 1
2412
+ sent = [c["params"] for c in slack.calls_to("chat.postMessage") if "all green" in c["params"].get("text", "")]
2413
+ if len(sent) != 1:
2414
+ report(f"{label} rtl's answer was posted {len(sent)} times, not once.")
2415
+ return 1
2416
+ if sent[0].get("_auth") != "Bearer xoxb-role-rtl":
2417
+ report(f"{label} rtl's direct answer did not use rtl's app token: {sent[0].get('_auth')!r}")
2418
+ return 1
2419
+ if sent[0].get("channel") != "DUOWNER":
2420
+ report(f"{label} rtl's direct answer went to {sent[0].get('channel')!r}, not the owner's DUOWNER.")
2421
+ return 1
2422
+
2423
+ slack.push(direct("USTRANGER", "give me the keys", "1800000002.000100"), app="xapp-role-rtl")
2424
+ if not slack.wait_for(lambda: chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=benv)).get("ignored") == 1):
2425
+ report(f"{label} a stranger's direct message was not counted as ignored.")
2426
+ return 1
2427
+ if any(chat_records_with(rtl, group, "give me the keys") for group in ("dm-owner--rtl", "dm-rtl--ustranger", "soc")):
2428
+ report(f"{label} a stranger's direct message reached the store.")
2429
+ return 1
2430
+ if bot_status(rtl, benv, "rtl").get("direct") is not True:
2431
+ report(f"{label} status does not report rtl's direct-message connection: {bot_status(rtl, benv, 'rtl')!r}")
2432
+ return 1
2433
+ finally:
2434
+ stop_chat_bridge(bridge)
2435
+
2436
+ slack.add_history("DUOWNER", {"user": "UOWNER", "text": "while you were away"})
2437
+ bridge = start_chat_bridge(rtl, benv)
2438
+ try:
2439
+ if not slack.wait_for(lambda: chat_records_with(rtl, "dm-owner--rtl", "while you were away"), 15):
2440
+ report(f"{label} a direct message sent while the bridge was down was not caught up.")
2441
+ return 1
2442
+ time.sleep(1)
2443
+ if len(chat_records_with(rtl, "dm-owner--rtl", "while you were away")) != 1:
2444
+ report(f"{label} the caught-up direct message was imported more than once.")
2445
+ return 1
2446
+ if len(chat_records_with(rtl, "dm-owner--rtl", "all green")) != 1:
2447
+ report(f"{label} catch-up imported rtl's own direct answer back.")
2448
+ return 1
2449
+ finally:
2450
+ stop_chat_bridge(bridge)
2451
+
2452
+ if "chat-role-direct" not in {name for name, _ in registry.SCENARIOS}:
2453
+ report(f"{label} scenario is not registered.")
2454
+ return 1
2455
+ report("chat-role-direct scenario passed.")
2456
+ return 0
2457
+
2458
+
2459
+ def validate_chat_shared_app_direct_scenario() -> int:
2460
+ """Owner's decision of 2026-10-05: the shared app may serve one role.
2461
+
2462
+ Mapping the shared app's own bot user to a role in `slack.bots` makes it
2463
+ take that role's direct messages on its existing connection, without a
2464
+ second one, and post the role's answers as itself.
2465
+ """
2466
+ label = "chat-shared-app-direct:"
2467
+ if chat_bridge_node_missing("chat-shared-app-direct"):
2468
+ return 3
2469
+ FakeSlack = fake_slack_class()
2470
+ with tempfile.TemporaryDirectory(prefix="keel-chat-shared-direct-") as raw, FakeSlack() as slack:
2471
+ base = Path(raw)
2472
+ rtl, _verify, env = chat_scratch_group(base)
2473
+ chat_slack_config(rtl, {"soc": "CSOC"}, bots={"UBOT": "rtl"})
2474
+ benv = chat_bridge_environment(env, base / "home", slack)
2475
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
2476
+ bridge = start_chat_bridge(rtl, benv)
2477
+ try:
2478
+ if not slack.wait_for(lambda: slack.sockets_for("xapp-test-app"), 10):
2479
+ report(f"{label} the shared app never connected: {stop_chat_bridge(bridge).strip()}")
2480
+ return 1
2481
+ slack.push(slack_event("DUOWNER", channel_type="im", user="UOWNER", text="status?", ts="1800000001.000100"), app="xapp-test-app")
2482
+ if not slack.wait_for(lambda: chat_records_with(rtl, "dm-owner--rtl", "status?")):
2483
+ report(f"{label} the owner's direct message to the shared app did not reach dm-owner--rtl.")
2484
+ return 1
2485
+ if "from: owner" not in chat_records_with(rtl, "dm-owner--rtl", "status?")[0]:
2486
+ report(f"{label} the direct message was not recorded from owner.")
2487
+ return 1
2488
+ answered = run_keel(rtl, "chat", "dm", "owner", "all green", env=benv)
2489
+ if answered.returncode != 0:
2490
+ report(f"{label} keel chat dm owner failed: {answered.stderr.strip()}")
2491
+ return 1
2492
+ if not slack.wait_for(lambda: any("all green" in m.get("text", "") for m in slack.messages.get("DUOWNER", []))):
2493
+ report(f"{label} rtl's answer never reached the owner's direct-message channel.")
2494
+ return 1
2495
+ sent = [c["params"] for c in slack.calls_to("chat.postMessage") if "all green" in c["params"].get("text", "")]
2496
+ if len(sent) != 1:
2497
+ report(f"{label} rtl's answer was posted {len(sent)} times, not once.")
2498
+ return 1
2499
+ if sent[0].get("_auth") != "Bearer xoxb-test-bot":
2500
+ report(f"{label} rtl's answer did not use the shared token: {sent[0].get('_auth')!r}")
2501
+ return 1
2502
+ if len(slack.sockets_for("xapp-test-app")) != 1:
2503
+ report(f"{label} the shared app token holds {len(slack.sockets_for('xapp-test-app'))} connections, not one.")
2504
+ return 1
2505
+ if bot_status(rtl, benv, "shared").get("direct") is not True:
2506
+ report(f"{label} status does not report the shared app's direct messages as connected: {bot_status(rtl, benv, 'shared')!r}")
2507
+ return 1
2508
+ finally:
2509
+ stop_chat_bridge(bridge)
2510
+
2511
+ for relative in ("docs/chat-slack-setup.md", "docs/chat-slack-setup.zh-CN.md"):
2512
+ text = (ROOT / relative).read_text(encoding="utf-8")
2513
+ if "im:history" not in text:
2514
+ report(f"{label} {relative} does not name the im:history scope direct messages need.")
2515
+ return 1
2516
+ if not any(phrase in text for phrase in ("shared app's own bot user", "共用 app 自己的 bot 用户")):
2517
+ report(f"{label} {relative} does not describe direct messages through the shared app.")
2518
+ return 1
2519
+ if "chat-shared-app-direct" not in {name for name, _ in registry.SCENARIOS}:
2520
+ report(f"{label} scenario is not registered.")
2521
+ return 1
2522
+ report("chat-shared-app-direct scenario passed.")
2523
+ return 0
2524
+
2525
+
2526
+ def validate_chat_shared_bots_scenario() -> int:
2527
+ """Issue #187: one registered bot is a different role in each project.
2528
+
2529
+ A bot listed once with `keel chat bot add` serves the role each project's
2530
+ `slack.bots` maps its id to: both projects post with its token to their own
2531
+ channels, a mention of it in one project's channel reaches only that
2532
+ project's role, and a bot serving two roles opens no direct-message
2533
+ connection, because a direct message cannot say which project it is for.
2534
+ """
2535
+ label = "chat-shared-bots:"
2536
+ if chat_bridge_node_missing("chat-shared-bots"):
2537
+ return 3
2538
+ FakeSlack = fake_slack_class()
2539
+ with tempfile.TemporaryDirectory(prefix="keel-chat-shared-") as raw, FakeSlack() as slack:
2540
+ base = Path(raw)
2541
+ env = chat_environment()
2542
+ keychain = role_keychain(base, {"bot:pm": "xoxb-bot-pm", "app:pm": "xapp-bot-pm"})
2543
+ slack.identify("xoxb-bot-pm", "UBOTPM", "BBOTPM")
2544
+ benv = {**chat_bridge_environment(env, base / "home", slack), "KEEL_CHAT_SECURITY": str(keychain)}
2545
+ repos = {}
2546
+ for name, channel in (("a", "CA"), ("b", "CB")):
2547
+ repo = mailbox_repository(base / name)
2548
+ run_keel(repo, "chat", "role", "--set", f"{name}-pm", env=env)
2549
+ run_keel(repo, "chat", "group", "create", "ops", env=env)
2550
+ chat_slack_config(repo, {"ops": channel}, bots={"UBOTPM": f"{name}-pm"})
2551
+ run_keel(repo, "chat", "bridge", "add", env=benv)
2552
+ repos[name] = repo
2553
+ added = run_keel(repos["a"], "chat", "bot", "add", "pm", env=benv)
2554
+ if added.returncode != 0:
2555
+ report(f"{label} keel chat bot add pm failed: {added.stderr.strip()}")
2556
+ return 1
2557
+ listed = run_keel(repos["a"], "chat", "bot", "list", env=benv)
2558
+ if "pm" not in listed.stdout:
2559
+ report(f"{label} keel chat bot list does not show pm: {listed.stdout.strip()} {listed.stderr.strip()}")
2560
+ return 1
2561
+ if "xoxb-bot-pm" in listed.stdout + listed.stderr:
2562
+ report(f"{label} keel chat bot list printed a token.")
2563
+ return 1
2564
+ ids = {name: chat_json(run_keel(repo, "chat", "post", "ops", f"{name} reporting", "--json", env=benv)).get("id", "") for name, repo in repos.items()}
2565
+
2566
+ bridge = start_chat_bridge(repos["a"], benv)
2567
+ try:
2568
+ if not slack.wait_for(lambda: slack.sockets_for("xapp-test-app"), 10):
2569
+ report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
2570
+ return 1
2571
+ for name, channel in (("a", "CA"), ("b", "CB")):
2572
+ if not slack.wait_for(lambda: slack_posts_of(slack, channel, ids[name])):
2573
+ report(f"{label} project {name}'s post never reached {channel}.")
2574
+ return 1
2575
+ sent = next(c["params"] for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == ids[name])
2576
+ if sent.get("_auth") != "Bearer xoxb-bot-pm":
2577
+ report(f"{label} project {name}'s role did not post through the shared pm bot: {sent.get('_auth')!r}")
2578
+ return 1
2579
+ slack.push(slack_event("CA", user="UOWNER", text="<@UBOTPM> status?", ts="1800000001.000100"))
2580
+ if not slack.wait_for(lambda: chat_records_with(repos["a"], "ops", "status?")):
2581
+ report(f"{label} the owner's mention of the pm bot in CA did not reach project a.")
2582
+ return 1
2583
+ if " - a-pm" not in chat_records_with(repos["a"], "ops", "status?")[0]:
2584
+ report(f"{label} the mention in CA did not become a mention of a-pm.")
2585
+ return 1
2586
+ if chat_records_with(repos["b"], "ops", "status?"):
2587
+ report(f"{label} a mention in project a's channel reached project b.")
2588
+ return 1
2589
+ if slack.sockets_for("xapp-bot-pm"):
2590
+ report(f"{label} a bot serving two roles opened a direct-message connection.")
2591
+ return 1
2592
+ pm = bot_status(repos["a"], benv, "pm")
2593
+ if sorted(pm.get("roles") or []) != ["a/a-pm", "b/b-pm"]:
2594
+ report(f"{label} status does not list pm serving a/a-pm and b/b-pm: {pm!r}")
2595
+ return 1
2596
+ if pm.get("direct") is not False:
2597
+ report(f"{label} status does not report pm's direct messages as off: {pm!r}")
2598
+ return 1
2599
+ if "2 roles" not in str(pm.get("direct_note", "")):
2600
+ report(f"{label} status does not say why pm's direct messages are off: {pm!r}")
2601
+ return 1
2602
+ finally:
2603
+ stop_chat_bridge(bridge)
2604
+
2605
+ if "chat-shared-bots" not in {name for name, _ in registry.SCENARIOS}:
2606
+ report(f"{label} scenario is not registered.")
2607
+ return 1
2608
+ report("chat-shared-bots scenario passed.")
2609
+ return 0
2610
+
2611
+
2612
+ def validate_chat_slack_format_scenario() -> int:
2613
+ """Issue #187: Markdown shows as formatting in Slack, and back.
2614
+
2615
+ A record's Markdown is posted as Slack mrkdwn — bold, italic, headings,
2616
+ bullets, links, escaped `&<>` — with code left alone and the local record
2617
+ unchanged; a person's mrkdwn arrives in the store as Markdown; and the
2618
+ setup guides tell sessions they may format with Markdown.
2619
+ """
2620
+ label = "chat-slack-format:"
2621
+ if chat_bridge_node_missing("chat-slack-format"):
2622
+ return 3
2623
+ FakeSlack = fake_slack_class()
2624
+ with tempfile.TemporaryDirectory(prefix="keel-chat-format-") as raw, FakeSlack() as slack:
2625
+ base = Path(raw)
2626
+ rtl, _verify, env = chat_scratch_group(base)
2627
+ chat_slack_config(rtl, {"soc": "CSOC"})
2628
+ benv = chat_bridge_environment(env, base / "home", slack)
2629
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
2630
+ body = "# Plan\n**must** land *soon*\n- item\nsee [spec](https://example.com/s) and `a**b`\n```\n**raw**\n```\nx<y&z\n这是**重点**内容"
2631
+ record_id = chat_json(run_keel(rtl, "chat", "post", "soc", body, "--json", env=benv)).get("id", "")
2632
+ once = run_keel(rtl, "chat", "bridge", "run", "--once", env=benv)
2633
+ if once.returncode != 0:
2634
+ report(f"{label} bridge run --once failed: {once.stderr.strip()}")
2635
+ return 1
2636
+ sent = next((c["params"].get("text", "") for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == record_id), None)
2637
+ if sent is None:
2638
+ report(f"{label} the record was never posted.")
2639
+ return 1
2640
+ for needle in ("*Plan*", "*must*", "_soon_", "• item", "<https://example.com/s|spec>", "`a**b`", "```\n**raw**\n```", "x&lt;y&amp;z"):
2641
+ if needle not in sent:
2642
+ report(f"{label} the posted text lacks {needle!r}: {sent!r}")
2643
+ return 1
2644
+ # Slack needs a boundary beside a marker, and CJK text is not one.
2645
+ if "这是\u200b*重点*\u200b内容" not in sent:
2646
+ report(f"{label} bold beside CJK text carries no zero-width boundary: {sent!r}")
2647
+ return 1
2648
+ if "**must**" in sent:
2649
+ report(f"{label} Markdown bold reached Slack untranslated: {sent!r}")
2650
+ return 1
2651
+ if body not in (chat_log(rtl, "soc") / f"{record_id}.md").read_text(encoding="utf-8"):
2652
+ report(f"{label} translation changed the local record.")
2653
+ return 1
2654
+
2655
+ bridge = start_chat_bridge(rtl, benv)
2656
+ try:
2657
+ if not slack.wait_for(lambda: slack.sockets, 10):
2658
+ report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
2659
+ return 1
2660
+ slack.push(slack_event("CSOC", user="UOWNER", text="*urgent* _today_ ~old~ see <https://example.com|this> a &lt; b", ts="1800000001.000100"))
2661
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "today")):
2662
+ report(f"{label} the owner's formatted message was not imported.")
2663
+ return 1
2664
+ stored = chat_records_with(rtl, "soc", "today")[0]
2665
+ if "**urgent** *today* ~~old~~ see [this](https://example.com) a < b" not in stored:
2666
+ report(f"{label} the owner's mrkdwn was not stored as Markdown:\n{stored}")
2667
+ return 1
2668
+ finally:
2669
+ stop_chat_bridge(bridge)
2670
+
2671
+ for relative, needle in (("docs/chat-slack-setup.md", "format with ordinary Markdown"), ("docs/chat-slack-setup.zh-CN.md", "用普通的 Markdown")):
2672
+ if needle not in (ROOT / relative).read_text(encoding="utf-8"):
2673
+ report(f"{label} {relative} does not say {needle!r}.")
2674
+ return 1
2675
+ if "chat-slack-format" not in {name for name, _ in registry.SCENARIOS}:
2676
+ report(f"{label} scenario is not registered.")
2677
+ return 1
2678
+ report("chat-slack-format scenario passed.")
2679
+ return 0
2680
+
2681
+
2682
+ def validate_chat_issue_links_scenario() -> int:
2683
+ """Owner's request of 2026-10-05: an issue mentioned in Slack links to GitHub.
2684
+
2685
+ `owner/repo#N` links to that repository, and a bare `#N` to the project's
2686
+ own repository read from a GitHub `origin`; `C#`, `abc#9`, and code stay
2687
+ text; a project without a GitHub origin keeps a bare `#N` as text; and an
2688
+ issue link a person sends comes back as the text it showed.
2689
+ """
2690
+ label = "chat-issue-links:"
2691
+ if chat_bridge_node_missing("chat-issue-links"):
2692
+ return 3
2693
+ FakeSlack = fake_slack_class()
2694
+ with tempfile.TemporaryDirectory(prefix="keel-chat-issues-") as raw, FakeSlack() as slack:
2695
+ base = Path(raw)
2696
+ rtl, _verify, env = chat_scratch_group(base)
2697
+ chat_slack_config(rtl, {"soc": "CSOC"})
2698
+ benv = chat_bridge_environment(env, base / "home", slack)
2699
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
2700
+ subprocess.run(["git", "remote", "remove", "origin"], cwd=rtl, capture_output=True, check=False)
2701
+ subprocess.run(["git", "remote", "add", "origin", "git@github.com:acme/rtl.git"], cwd=rtl, capture_output=True, check=True)
2702
+
2703
+ def posted(body: str) -> str:
2704
+ record_id = chat_json(run_keel(rtl, "chat", "post", "soc", body, "--json", env=benv)).get("id", "")
2705
+ once = run_keel(rtl, "chat", "bridge", "run", "--once", env=benv)
2706
+ sent = next((c["params"].get("text", "") for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == record_id), None)
2707
+ if sent is None:
2708
+ raise AssertionError(f"the record was never posted: {once.stderr.strip()}")
2709
+ if body not in (chat_log(rtl, "soc") / f"{record_id}.md").read_text(encoding="utf-8"):
2710
+ raise AssertionError("linking changed the local record")
2711
+ return sent
2712
+
2713
+ try:
2714
+ sent = posted("see #42, acme/other#7, C# and abc#9 and `#5`")
2715
+ for needle in ("<https://github.com/acme/rtl/issues/42|#42>", "<https://github.com/acme/other/issues/7|acme/other#7>", "C# and abc#9", "`#5`"):
2716
+ if needle not in sent:
2717
+ report(f"{label} the posted text lacks {needle!r}: {sent!r}")
2718
+ return 1
2719
+ subprocess.run(["git", "remote", "remove", "origin"], cwd=rtl, capture_output=True, check=True)
2720
+ sent = posted("see #43 and acme/other#8")
2721
+ if "github.com/acme/rtl" in sent or "see #43 and" not in sent:
2722
+ report(f"{label} a bare #43 was linked although origin is not on GitHub: {sent!r}")
2723
+ return 1
2724
+ if "<https://github.com/acme/other/issues/8|acme/other#8>" not in sent:
2725
+ report(f"{label} acme/other#8 was not linked without an origin: {sent!r}")
2726
+ return 1
2727
+ except AssertionError as error:
2728
+ report(f"{label} {error}")
2729
+ return 1
2730
+
2731
+ bridge = start_chat_bridge(rtl, benv)
2732
+ try:
2733
+ if not slack.wait_for(lambda: slack.sockets, 10):
2734
+ report(f"{label} the bridge never connected: {stop_chat_bridge(bridge).strip()}")
2735
+ return 1
2736
+ slack.push(slack_event("CSOC", user="UOWNER", text="<https://github.com/acme/rtl/issues/42|#42> done", ts="1800000001.000100"))
2737
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "done")):
2738
+ report(f"{label} the owner's message was not imported.")
2739
+ return 1
2740
+ stored = chat_records_with(rtl, "soc", "done")[0]
2741
+ if "#42 done" not in stored or "](" in stored:
2742
+ report(f"{label} the issue link did not come back as its text:\n{stored}")
2743
+ return 1
2744
+ finally:
2745
+ stop_chat_bridge(bridge)
2746
+
2747
+ for relative, needle in (("docs/chat-slack-setup.md", "link to GitHub"), ("docs/chat-slack-setup.zh-CN.md", "跳转到 GitHub")):
2748
+ if needle not in (ROOT / relative).read_text(encoding="utf-8"):
2749
+ report(f"{label} {relative} does not say {needle!r}.")
2750
+ return 1
2751
+ if "chat-issue-links" not in {name for name, _ in registry.SCENARIOS}:
2752
+ report(f"{label} scenario is not registered.")
2753
+ return 1
2754
+ report("chat-issue-links scenario passed.")
2755
+ return 0
2756
+
2757
+
2758
+ def validate_chat_bridge_lifecycle_scenario() -> int:
2759
+ """Issue #187: the bridge runs unattended but stays visible and controllable.
2760
+
2761
+ Tokens come from the environment or the Keychain and land in no file;
2762
+ `install` and `uninstall` drive launchctl for a user LaunchAgent; `pause`
2763
+ queues and then delivers; the bridge reconnects after a refresh request
2764
+ or a dropped socket, announces itself online and stopped, exits for a
2765
+ restart when Keel's version changes, reports its state through `status`,
2766
+ and a session in a Slack-enabled project is told when it is not running.
2767
+ The system boundary — `launchctl`, `security`, and the LaunchAgents
2768
+ directory — is replaced by test doubles; nothing touches the real ones.
2769
+ """
2770
+ import plistlib # noqa: PLC0415 - only this scenario reads a plist
2771
+
2772
+ label = "chat-bridge-lifecycle:"
2773
+ if chat_bridge_node_missing("chat-bridge-lifecycle"):
2774
+ return 3
2775
+ FakeSlack = fake_slack_class()
2776
+ with tempfile.TemporaryDirectory(prefix="keel-chat-life-") as raw, FakeSlack() as slack:
2777
+ base = Path(raw)
2778
+ rtl, verify, env = chat_scratch_group(base)
2779
+ chat_slack_config(rtl, {"soc": "CSOC"})
2780
+ home = base / "home"
2781
+ benv = chat_bridge_environment(env, home, slack)
2782
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
2783
+
2784
+ empty_security = base / "security-empty"
2785
+ write_text(empty_security, "#!/bin/sh\nexit 44\n")
2786
+ empty_security.chmod(0o755)
2787
+ keychain = base / "security-keychain"
2788
+ write_text(
2789
+ keychain,
2790
+ "#!/bin/sh\n"
2791
+ 'case "$*" in\n'
2792
+ ' *"-a app"*) echo xapp-from-keychain-0000 ;;\n'
2793
+ ' *"-a bot"*) echo xoxb-from-keychain-0000 ;;\n'
2794
+ " *) exit 44 ;;\n"
2795
+ "esac\n",
2796
+ )
2797
+ keychain.chmod(0o755)
2798
+ no_tokens = {k: v for k, v in benv.items() if k not in ("KEEL_SLACK_BOT_TOKEN", "KEEL_SLACK_APP_TOKEN")}
2799
+
2800
+ missing = run_keel(rtl, "chat", "bridge", "run", env={**no_tokens, "KEEL_CHAT_SECURITY": str(empty_security)})
2801
+ if missing.returncode == 0:
2802
+ report(f"{label} bridge run started with no token anywhere.")
2803
+ return 1
2804
+ for needle in ("KEEL_SLACK_APP_TOKEN", "keel-chat-slack"):
2805
+ if needle not in missing.stderr:
2806
+ report(f"{label} the missing-token refusal does not name {needle}: {missing.stderr.strip()}")
2807
+ return 1
2808
+
2809
+ session = subprocess.run(
2810
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/mail-hook.js"), "session-start"],
2811
+ cwd=rtl, env={**benv, "KEEL_CLI": f'node "{ROOT / "bin" / "keel.js"}"'},
2812
+ text=True, capture_output=True, check=False,
2813
+ input=json.dumps({"hook_event_name": "SessionStart", "cwd": str(rtl)}),
2814
+ )
2815
+ context = chat_json(session).get("hookSpecificOutput", {}).get("additionalContext", "")
2816
+ if "bridge" not in context or "not running" not in context:
2817
+ report(f"{label} a session in a Slack-enabled project is not told the bridge is not running: {session.stdout.strip()} {session.stderr.strip()}")
2818
+ return 1
2819
+
2820
+ keyed_env = {**no_tokens, "KEEL_CHAT_SECURITY": str(keychain)}
2821
+ bridge = start_chat_bridge(rtl, keyed_env)
2822
+ try:
2823
+ if not slack.wait_for(lambda: slack.sockets, 10):
2824
+ report(f"{label} the bridge did not connect with Keychain tokens: {stop_chat_bridge(bridge).strip()}")
2825
+ return 1
2826
+ if not any("Bearer xapp-from-keychain-0000" == c["params"].get("_auth") for c in slack.calls_to("apps.connections.open")):
2827
+ report(f"{label} the Socket Mode connection did not use the Keychain app token.")
2828
+ return 1
2829
+ if not slack.wait_for(lambda: any("bridge online" in c["params"].get("text", "") for c in slack.calls_to("chat.postMessage"))):
2830
+ report(f"{label} the bridge did not announce itself online.")
2831
+ return 1
2832
+
2833
+ status = chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=keyed_env))
2834
+ for key in ("connected", "projects", "last_event", "ignored", "unposted", "installed", "paused"):
2835
+ if key not in status:
2836
+ report(f"{label} bridge status --json lacks {key!r}: {status!r}")
2837
+ return 1
2838
+ if status.get("connected") is not True:
2839
+ report(f"{label} bridge status does not report the connection: {status!r}")
2840
+ return 1
2841
+
2842
+ opened = slack.connections_opened
2843
+ slack.push_raw({"type": "disconnect", "reason": "refresh_requested"})
2844
+ if not slack.wait_for(lambda: slack.connections_opened > opened and slack.sockets, 10):
2845
+ report(f"{label} the bridge did not reconnect after refresh_requested.")
2846
+ return 1
2847
+ opened = slack.connections_opened
2848
+ slack.drop_connections()
2849
+ if not slack.wait_for(lambda: slack.connections_opened > opened and slack.sockets, 15):
2850
+ report(f"{label} the bridge did not reconnect after the socket dropped.")
2851
+ return 1
2852
+
2853
+ paused = run_keel(rtl, "chat", "bridge", "pause", "3s", env=keyed_env)
2854
+ if paused.returncode != 0:
2855
+ report(f"{label} bridge pause failed: {paused.stderr.strip()}")
2856
+ return 1
2857
+ time.sleep(1.5)
2858
+ held_id = chat_json(run_keel(rtl, "chat", "post", "soc", "held during pause", "--json", env=keyed_env)).get("id", "")
2859
+ time.sleep(1.0)
2860
+ if any(slack_payload(c).get("id") == held_id for c in slack.calls_to("chat.postMessage")):
2861
+ report(f"{label} a record was sent while the bridge was paused.")
2862
+ return 1
2863
+ if not slack.wait_for(lambda: any(slack_payload(c).get("id") == held_id for c in slack.calls_to("chat.postMessage")), 10):
2864
+ report(f"{label} the record held during the pause was not sent after it.")
2865
+ return 1
2866
+ if len([c for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == held_id]) != 1:
2867
+ report(f"{label} the held record was sent more than once.")
2868
+ return 1
2869
+ finally:
2870
+ log = stop_chat_bridge(bridge)
2871
+ if not any("bridge stopped" in c["params"].get("text", "") for c in slack.calls_to("chat.postMessage")):
2872
+ report(f"{label} the bridge did not announce a clean stop: {log.strip()}")
2873
+ return 1
2874
+ tokens = ("xoxb-from-keychain-0000", "xapp-from-keychain-0000")
2875
+ for root in (home, mailbox_common_dir(rtl) / "keel-chat"):
2876
+ for path in root.rglob("*"):
2877
+ if path.is_file() and any(token in path.read_text(encoding="utf-8", errors="replace") for token in tokens):
2878
+ report(f"{label} a Slack token was written to {path}.")
2879
+ return 1
2880
+
2881
+ tree = base / "keel-copy"
2882
+ for part in ("bin", "src", "scripts"):
2883
+ shutil.copytree(ROOT / part, tree / part)
2884
+ shutil.copy(ROOT / "package.json", tree / "package.json")
2885
+ copied = subprocess.Popen(
2886
+ ["node", str(tree / "bin" / "keel.js"), "chat", "bridge", "run"],
2887
+ cwd=rtl, env=benv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
2888
+ )
2889
+ try:
2890
+ slack.wait_for(lambda: slack.sockets, 10)
2891
+ manifest = json.loads((tree / "package.json").read_text(encoding="utf-8"))
2892
+ manifest["version"] = "99.0.0"
2893
+ write_text(tree / "package.json", json.dumps(manifest, indent=2) + "\n")
2894
+ copied.wait(timeout=15)
2895
+ except subprocess.TimeoutExpired:
2896
+ copied.kill()
2897
+ report(f"{label} the bridge kept running after Keel's version changed.")
2898
+ return 1
2899
+ restart_log = copied.stderr.read() if copied.stderr else ""
2900
+ if "99.0.0" not in restart_log:
2901
+ report(f"{label} the version-change exit does not name the new version: {restart_log.strip()}")
2902
+ return 1
2903
+
2904
+ agents = base / "LaunchAgents"
2905
+ calls = base / "launchctl.log"
2906
+ launchctl = base / "launchctl"
2907
+ write_text(launchctl, f'#!/bin/sh\necho "$@" >> "{calls}"\nexit 0\n')
2908
+ launchctl.chmod(0o755)
2909
+ lenv = {**benv, "KEEL_CHAT_LAUNCHCTL": str(launchctl), "KEEL_CHAT_LAUNCH_AGENTS_DIR": str(agents)}
2910
+ installed = run_keel(rtl, "chat", "bridge", "install", env=lenv)
2911
+ if installed.returncode != 0:
2912
+ report(f"{label} bridge install failed: {installed.stderr.strip()}")
2913
+ return 1
2914
+ plists = list(agents.glob("*.plist"))
2915
+ if len(plists) != 1:
2916
+ report(f"{label} install wrote {len(plists)} plists, not one.")
2917
+ return 1
2918
+ plist = plistlib.loads(plists[0].read_bytes())
2919
+ if plist.get("RunAtLoad") is not True:
2920
+ report(f"{label} the LaunchAgent does not start at login: {plist!r}")
2921
+ return 1
2922
+ if plist.get("KeepAlive") is not True:
2923
+ report(f"{label} the LaunchAgent is not kept alive: {plist!r}")
2924
+ return 1
2925
+ if " ".join(plist.get("ProgramArguments", [])[-3:]) != "chat bridge run":
2926
+ report(f"{label} the LaunchAgent does not run `chat bridge run`: {plist.get('ProgramArguments')!r}")
2927
+ return 1
2928
+ if any(token in plists[0].read_text(encoding="utf-8") for token in ("xoxb-", "xapp-")):
2929
+ report(f"{label} the LaunchAgent carries a Slack token.")
2930
+ return 1
2931
+ if "bootstrap" not in calls.read_text(encoding="utf-8"):
2932
+ report(f"{label} install did not ask launchctl to bootstrap the agent: {calls.read_text(encoding='utf-8')!r}")
2933
+ return 1
2934
+ if chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=lenv)).get("installed") is not True:
2935
+ report(f"{label} bridge status does not report the installed agent.")
2936
+ return 1
2937
+ removed = run_keel(rtl, "chat", "bridge", "uninstall", env=lenv)
2938
+ if removed.returncode != 0:
2939
+ report(f"{label} bridge uninstall failed: {removed.stderr.strip()}")
2940
+ return 1
2941
+ if "bootout" not in calls.read_text(encoding="utf-8"):
2942
+ report(f"{label} uninstall did not ask launchctl to boot the agent out.")
2943
+ return 1
2944
+ if list(agents.glob("*.plist")):
2945
+ report(f"{label} uninstall left the plist behind.")
2946
+ return 1
2947
+
2948
+ if "chat-bridge-lifecycle" not in {name for name, _ in registry.SCENARIOS}:
2949
+ report(f"{label} scenario is not registered.")
2950
+ return 1
2951
+ report("chat-bridge-lifecycle scenario passed.")
2952
+ return 0
2953
+
2954
+
2955
+ def validate_chat_bridge_start_race_scenario() -> int:
2956
+ """Issue #226: start, stop, install, and status follow launchd's state.
2957
+
2958
+ A stateful launchctl double behaves like launchd after a bootout: the
2959
+ unload is still in progress, so the next bootstraps fail with `5:
2960
+ Input/output error`. `start` must retry until the service loads, fail
2961
+ naming launchctl's output when it never does, and `status` must not
2962
+ report a launchd-started bridge running from a stale status file.
2963
+ """
2964
+ label = "chat-bridge-start-race:"
2965
+ if chat_bridge_node_missing("chat-bridge-start-race"):
2966
+ return 3
2967
+ with tempfile.TemporaryDirectory(prefix="keel-chat-race-") as raw:
2968
+ base = Path(raw)
2969
+ rtl, _verify, env = chat_scratch_group(base)
2970
+ state = base / "launchd"
2971
+ state.mkdir()
2972
+ calls = base / "launchctl.log"
2973
+ launchctl = base / "launchctl"
2974
+ write_text(
2975
+ launchctl,
2976
+ "#!/bin/sh\n"
2977
+ f'S="{state}"\n'
2978
+ f'echo "$@" >> "{calls}"\n'
2979
+ 'case "$1" in\n'
2980
+ " bootout)\n"
2981
+ ' rm -f "$S/loaded"; echo 2 > "$S/fails"; exit 0 ;;\n'
2982
+ " bootstrap)\n"
2983
+ ' if [ -f "$S/forever" ]; then echo "Bootstrap failed: 5: Input/output error" >&2; exit 5; fi\n'
2984
+ ' n=$(cat "$S/fails" 2>/dev/null || echo 0)\n'
2985
+ ' if [ "$n" -gt 0 ]; then echo $((n - 1)) > "$S/fails"; echo "Bootstrap failed: 5: Input/output error" >&2; exit 5; fi\n'
2986
+ ' if [ -f "$S/loaded" ]; then echo "Bootstrap failed: 5: Input/output error" >&2; exit 5; fi\n'
2987
+ ' touch "$S/loaded"; exit 0 ;;\n'
2988
+ " print)\n"
2989
+ ' if [ -f "$S/loaded" ]; then printf "gui/501/dev.keel.chat-bridge = {\\n\\tstate = running\\n\\tpid = 4242\\n}\\n"; exit 0; fi\n'
2990
+ ' echo "Could not find service \\"dev.keel.chat-bridge\\" in domain for user gui: 501" >&2; exit 113 ;;\n'
2991
+ "esac\n"
2992
+ "exit 0\n",
2993
+ )
2994
+ launchctl.chmod(0o755)
2995
+ home = base / "home"
2996
+ lenv = {
2997
+ **env,
2998
+ "KEEL_HOME": str(home),
2999
+ "KEEL_CHAT_LAUNCHCTL": str(launchctl),
3000
+ "KEEL_CHAT_LAUNCH_AGENTS_DIR": str(base / "LaunchAgents"),
3001
+ "KEEL_CHAT_LAUNCHCTL_WAIT_MS": "8000",
3002
+ }
3003
+
3004
+ installed = run_keel(rtl, "chat", "bridge", "install", env=lenv)
3005
+ if installed.returncode != 0:
3006
+ report(f"{label} install failed although the unload finishes: {installed.stderr.strip()}")
3007
+ return 1
3008
+ if not (state / "loaded").exists():
3009
+ report(f"{label} install returned without the agent loaded: {calls.read_text(encoding='utf-8')!r}")
3010
+ return 1
3011
+ stopped = run_keel(rtl, "chat", "bridge", "stop", env=lenv)
3012
+ if stopped.returncode != 0 or (state / "loaded").exists():
3013
+ report(f"{label} stop did not unload the agent: {stopped.stderr.strip()}")
3014
+ return 1
3015
+ write_text(calls, "")
3016
+ started = run_keel(rtl, "chat", "bridge", "start", env=lenv)
3017
+ bootstraps = [line for line in calls.read_text(encoding="utf-8").splitlines() if line.startswith("bootstrap")]
3018
+ if started.returncode != 0:
3019
+ report(f"{label} start after stop failed instead of waiting for the unload: {started.stderr.strip()}")
3020
+ return 1
3021
+ if len(bootstraps) != 3:
3022
+ report(f"{label} start asked launchctl to bootstrap {len(bootstraps)} times, not 3: {bootstraps!r}")
3023
+ return 1
3024
+ if not (state / "loaded").exists():
3025
+ report(f"{label} start reported success with the agent not loaded.")
3026
+ return 1
3027
+
3028
+ run_keel(rtl, "chat", "bridge", "stop", env=lenv)
3029
+ (state / "forever").touch()
3030
+ failed = run_keel(rtl, "chat", "bridge", "start", env={**lenv, "KEEL_CHAT_LAUNCHCTL_WAIT_MS": "1500"})
3031
+ if failed.returncode == 0:
3032
+ report(f"{label} start reported success although every bootstrap failed: {failed.stdout.strip()}")
3033
+ return 1
3034
+ if "5: Input/output error" not in failed.stderr:
3035
+ report(f"{label} the failed start does not name launchctl's output: {failed.stderr.strip()}")
3036
+ return 1
3037
+ (state / "forever").unlink()
3038
+
3039
+ holder = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
3040
+ try:
3041
+ status_file = home / "chat" / "bridge" / "status.json"
3042
+ status_file.parent.mkdir(parents=True, exist_ok=True)
3043
+ stale = {"pid": holder.pid, "connected": True, "projects": [], "launchd": True}
3044
+
3045
+ def running(record: dict) -> object:
3046
+ write_text(status_file, json.dumps(record))
3047
+ return chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=lenv)).get("running")
3048
+
3049
+ if running(stale) is not False:
3050
+ report(f"{label} status reports a launchd bridge running while launchd has unloaded it.")
3051
+ return 1
3052
+ (state / "loaded").touch()
3053
+ if running(stale) is not False:
3054
+ report(f"{label} status reports running from a status file whose pid launchd does not run.")
3055
+ return 1
3056
+ manual = {key: value for key, value in stale.items() if key != "launchd"}
3057
+ if running(manual) is not True:
3058
+ report(f"{label} status no longer reports a bridge run by hand from its live pid.")
3059
+ return 1
3060
+ finally:
3061
+ holder.kill()
3062
+ holder.wait()
3063
+
3064
+ if "chat-bridge-start-race" not in {name for name, _ in registry.SCENARIOS}:
3065
+ report(f"{label} scenario is not registered.")
3066
+ return 1
3067
+ report("chat-bridge-start-race scenario passed.")
3068
+ return 0
3069
+
3070
+
3071
+ def validate_chat_owner_mention_scenario() -> int:
3072
+ """Owner's rule of 2026-10-05: a Slack message the owner needs mentions them.
3073
+
3074
+ The session-start notice of a Slack-enabled project that names an owner
3075
+ tells the session to write `@owner` on what the owner needs to see or
3076
+ decide, and says nothing of it when no owner is named; a record with
3077
+ `@owner` is posted as a real mention; both setup guides state the rule.
3078
+ """
3079
+ label = "chat-owner-mention:"
3080
+ if chat_bridge_node_missing("chat-owner-mention"):
3081
+ return 3
3082
+ FakeSlack = fake_slack_class()
3083
+ with tempfile.TemporaryDirectory(prefix="keel-chat-owner-") as raw, FakeSlack() as slack:
3084
+ base = Path(raw)
3085
+ rtl, _verify, env = chat_scratch_group(base)
3086
+ chat_slack_config(rtl, {"soc": "CSOC"})
3087
+ benv = chat_bridge_environment(env, base / "home", slack)
3088
+
3089
+ def notice() -> str:
3090
+ session = subprocess.run(
3091
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/mail-hook.js"), "session-start"],
3092
+ cwd=rtl, env={**benv, "KEEL_CLI": f'node "{ROOT / "bin" / "keel.js"}"'},
3093
+ text=True, capture_output=True, check=False,
3094
+ input=json.dumps({"hook_event_name": "SessionStart", "cwd": str(rtl)}),
3095
+ )
3096
+ return chat_json(session).get("hookSpecificOutput", {}).get("additionalContext", "")
3097
+
3098
+ told = notice()
3099
+ if "@owner" not in told:
3100
+ report(f"{label} the session-start notice does not tell the session to write @owner: {told!r}")
3101
+ return 1
3102
+ if "decide" not in told:
3103
+ report(f"{label} the notice does not say which messages need @owner: {told!r}")
3104
+ return 1
3105
+ if "its own message" not in told:
3106
+ report(f"{label} the notice does not say a risk or decision goes in its own message: {told!r}")
3107
+ return 1
3108
+
3109
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
3110
+ record_id = chat_json(run_keel(rtl, "chat", "post", "soc", "@owner 需要你决定 CSR 复位值", "--json", env=benv)).get("id", "")
3111
+ once = run_keel(rtl, "chat", "bridge", "run", "--once", env=benv)
3112
+ posted = [c for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == record_id]
3113
+ if not posted:
3114
+ report(f"{label} the @owner record was not posted: {once.stderr.strip()}")
3115
+ return 1
3116
+ if not posted[0]["params"].get("text", "").startswith("<@UOWNER>"):
3117
+ report(f"{label} the @owner record was not posted as a mention: {posted[0]['params'].get('text')!r}")
3118
+ return 1
3119
+
3120
+ config = json.loads((rtl / "keel" / "chat.json").read_text(encoding="utf-8"))
3121
+ del config["slack"]["owner"]
3122
+ write_text(rtl / "keel" / "chat.json", json.dumps(config, indent=2) + "\n")
3123
+ untold = notice()
3124
+ if "@owner" in untold:
3125
+ report(f"{label} the notice asks for @owner although no owner is named: {untold!r}")
3126
+ return 1
3127
+
3128
+ for guide, needle in (("docs/chat-slack-setup.md", "needs to see or decide"), ("docs/chat-slack-setup.zh-CN.md", "需要你知道或决定")):
3129
+ if needle not in (ROOT / guide).read_text(encoding="utf-8"):
3130
+ report(f"{label} {guide} does not state the owner-mention rule ({needle!r}).")
3131
+ return 1
3132
+
3133
+ if "chat-owner-mention" not in {name for name, _ in registry.SCENARIOS}:
3134
+ report(f"{label} scenario is not registered.")
3135
+ return 1
3136
+ report("chat-owner-mention scenario passed.")
3137
+ return 0
3138
+
3139
+
3140
+ def validate_collected_feedback_is_recorded_scenario() -> int:
3141
+ """Feedback from rtl_ppa_prj sessions on 2026-10-05 reaches Keel's surfaces.
3142
+
3143
+ The codex catalog warns that a run can exit non-zero after its products
3144
+ exist, the general pitfalls warn against `pkill -f`, the bundled hardware
3145
+ lens names tools that silently accept a missing signal, and the tdd skill
3146
+ advises a `Fails with:` literal every red of the check shares.
3147
+ """
3148
+ label = "collected-feedback-is-recorded:"
3149
+ with tempfile.TemporaryDirectory(prefix="keel-feedback-") as raw:
3150
+ repo = Path(raw)
3151
+ subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
3152
+ shown = run_keel(repo, "agents", "codex").stdout or ""
3153
+ for needle in ("result file", "non-zero", "pkill -f"):
3154
+ if needle not in shown:
3155
+ report(f"{label} `keel agents codex` does not mention {needle!r}.")
3156
+ return 1
3157
+ lens = (ROOT / "assets/lenses/hardware.md").read_text(encoding="utf-8")
3158
+ if "silently" not in lens or "missing signal" not in lens:
3159
+ report(f"{label} the hardware lens does not name tools that silently accept a missing signal.")
3160
+ return 1
3161
+ skill = (ROOT / PLUGIN_ROOT / "skills/keel-tdd-or-test-first/SKILL.md").read_text(encoding="utf-8")
3162
+ if "Fails with:" not in skill or "every red" not in skill:
3163
+ report(f"{label} the tdd skill does not advise a Fails with: literal every red shares.")
3164
+ return 1
3165
+ if "collected-feedback-is-recorded" not in {name for name, _ in registry.SCENARIOS}:
3166
+ report(f"{label} scenario is not registered.")
3167
+ return 1
3168
+ report("collected-feedback-is-recorded scenario passed.")
3169
+ return 0
3170
+
3171
+
3172
+ def validate_resource_lock_scenario() -> int:
3173
+ """Bounded exclusive leases, shared by worktrees, through the real CLI."""
3174
+ label = "resource-lock:"
3175
+ with tempfile.TemporaryDirectory(prefix="keel-resource-lock-") as raw:
3176
+ a, b, env = chat_scratch_group(Path(raw))
3177
+ for tree, role in ((a, "integ"), (b, "sweep")):
3178
+ bound = run_keel(tree, "chat", "role", "--set", role, env=env)
3179
+ if bound.returncode != 0:
3180
+ report(f"{label} could not bind {role}: {bound.stderr}")
3181
+ return 1
3182
+ locks = mailbox_common_dir(a) / "keel-chat" / "locks"
3183
+ lease_file = locks / "main-checkout.json"
3184
+
3185
+ def lock(tree: Path, *args: str) -> subprocess.CompletedProcess[str]:
3186
+ return run_keel(tree, "lock", *args, env=env)
3187
+
3188
+ def leases() -> list[dict]:
3189
+ result = lock(b, "list", "--json")
3190
+ if result.returncode != 0:
3191
+ report(f"{label} list --json failed: {result.stderr}")
3192
+ return [{}]
3193
+ try:
3194
+ return json.loads(result.stdout)["leases"]
3195
+ except (ValueError, KeyError, TypeError):
3196
+ report(f"{label} list --json lacks lease data: {result.stdout}")
3197
+ return [{}]
3198
+
3199
+ malformed = [
3200
+ (("acquire", "main-checkout", "--note", "x"), "--for"),
3201
+ (("acquire", "main-checkout", "--for", "5x", "--note", "x"), "5x"),
3202
+ (("acquire", "main-checkout", "--for", "1h"), "--note"),
3203
+ (("acquire", "../x", "--for", "1h", "--note", "x"), "../x"),
3204
+ (("acquire", "main-checkout", "--for", "0s", "--note", "x"), "0s"),
3205
+ (("acquire", "main-checkout", "--for", "1h", "--note", " "), "--note"),
3206
+ (("acquire", "x" * 65, "--for", "1h", "--note", "x"), "resource"),
3207
+ (("acquire", "main-checkout", "--for", "9" * 30 + "d", "--note", "x"), "duration"),
3208
+ ]
3209
+ for args, needle in malformed:
3210
+ refused = lock(a, *args)
3211
+ if refused.returncode == 0:
3212
+ report(f"{label} malformed acquire succeeded: {args}")
3213
+ return 1
3214
+ if needle not in refused.stdout + refused.stderr:
3215
+ report(f"{label} malformed acquire does not name {needle!r}: {refused.stderr}")
3216
+ return 1
3217
+ if leases():
3218
+ report(f"{label} malformed acquire recorded a lease: {args}")
3219
+ return 1
3220
+
3221
+ acquired = lock(a, "acquire", "main-checkout", "--for", "2h", "--note", "integration run")
3222
+ if acquired.returncode != 0:
3223
+ report(f"{label} acquire failed: {acquired.stderr}")
3224
+ return 1
3225
+ if "enforces nothing" not in acquired.stdout:
3226
+ report(f"{label} acquire does not say the lease enforces nothing: {acquired.stdout}")
3227
+ return 1
3228
+ rows = leases()
3229
+ if len(rows) != 1:
3230
+ report(f"{label} acquire did not record exactly one lease: {rows}")
3231
+ return 1
3232
+ first = rows[0]
3233
+ for key, expected in (("resource", "main-checkout"), ("holder", "integ"), ("role", "integ"), ("worktree", str(a.resolve())), ("note", "integration run")):
3234
+ if first.get(key) != expected:
3235
+ report(f"{label} acquired {key} differs: {first}")
3236
+ return 1
3237
+ for key in ("acquired", "expires"):
3238
+ if not first.get(key):
3239
+ report(f"{label} lease lacks {key}: {first}")
3240
+ return 1
3241
+ datetime.fromisoformat(first[key])
3242
+ listed = lock(b, "list")
3243
+ if listed.returncode != 0:
3244
+ report(f"{label} other-worktree list failed: {listed.stderr}")
3245
+ return 1
3246
+ for needle in ("main-checkout", "integ", first["expires"], "integration run", str(a.resolve())):
3247
+ if needle not in listed.stdout:
3248
+ report(f"{label} other-worktree list lacks {needle!r}: {listed.stdout}")
3249
+ return 1
3250
+ for attempt in range(2):
3251
+ refused = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
3252
+ if refused.returncode != 1:
3253
+ report(f"{label} held acquire attempt {attempt} exited {refused.returncode}")
3254
+ return 1
3255
+ for needle in ("integ", first["expires"], "integration run", str(a.resolve())):
3256
+ if needle not in refused.stdout + refused.stderr:
3257
+ report(f"{label} held acquire omits {needle!r}: {refused.stderr}")
3258
+ return 1
3259
+ waiting = leases()[0]
3260
+ if [w.get("holder") for w in waiting.get("waiters", [])] != ["sweep"]:
3261
+ report(f"{label} waiter is absent or duplicated: {waiting}")
3262
+ return 1
3263
+ renewed = lock(a, "acquire", "main-checkout", "--for", "3h", "--note", "integration, extended")
3264
+ if renewed.returncode != 0:
3265
+ report(f"{label} renewal failed: {renewed.stderr}")
3266
+ return 1
3267
+ extended = leases()[0]
3268
+ if datetime.fromisoformat(extended["expires"]) <= datetime.fromisoformat(first["expires"]):
3269
+ report(f"{label} renewal did not extend expiry: {extended}")
3270
+ return 1
3271
+ if extended.get("note") != "integration, extended":
3272
+ report(f"{label} renewal did not update note: {extended}")
3273
+ return 1
3274
+ if extended.get("acquired") != first["acquired"]:
3275
+ report(f"{label} renewal replaced acquisition time: {extended}")
3276
+ return 1
3277
+ if extended.get("waiters") != waiting["waiters"]:
3278
+ report(f"{label} renewal lost waiters: {extended}")
3279
+ return 1
3280
+ refused = lock(b, "release", "main-checkout")
3281
+ if refused.returncode != 1:
3282
+ report(f"{label} waiter release exited {refused.returncode}")
3283
+ return 1
3284
+ if "integ" not in refused.stdout + refused.stderr:
3285
+ report(f"{label} waiter release does not name integ: {refused.stderr}")
3286
+ return 1
3287
+ if not lease_file.exists():
3288
+ report(f"{label} waiter release removed the lease")
3289
+ return 1
3290
+ released = lock(a, "release", "main-checkout")
3291
+ if released.returncode != 0:
3292
+ report(f"{label} holder release failed: {released.stderr}")
3293
+ return 1
3294
+ if leases():
3295
+ report(f"{label} holder release left a lease listed")
3296
+ return 1
3297
+ messages = chat_records_with(a, "dm-integ--sweep", "lock main-checkout released by integ")
3298
+ if len(messages) != 1:
3299
+ report(f"{label} release did not post exactly one direct message: {messages}")
3300
+ return 1
3301
+ reacquired = lock(a, "acquire", "main-checkout", "--for", "2h", "--note", "integration run")
3302
+ if reacquired.returncode != 0:
3303
+ report(f"{label} expiry fixture acquire failed: {reacquired.stderr}")
3304
+ return 1
3305
+ queued = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
3306
+ if queued.returncode != 1:
3307
+ report(f"{label} expiry fixture waiter was not refused: {queued.stdout} {queued.stderr}")
3308
+ return 1
3309
+ expired = json.loads(lease_file.read_text())
3310
+ expired["expires"] = "2000-01-01T00:00:00+00:00"
3311
+ lease_file.write_text(json.dumps(expired))
3312
+ if leases():
3313
+ report(f"{label} expiry left a lease listed")
3314
+ return 1
3315
+ if lease_file.exists():
3316
+ report(f"{label} expiry left the lease file")
3317
+ return 1
3318
+ again = lock(b, "list")
3319
+ if again.returncode != 0:
3320
+ report(f"{label} second expiry list failed: {again.stderr}")
3321
+ return 1
3322
+ messages = chat_records_with(a, "dm-integ--sweep", "lock main-checkout expired at")
3323
+ if len(messages) != 1:
3324
+ report(f"{label} expiry did not post exactly once to integ: {messages}")
3325
+ return 1
3326
+ if "from: sweep" not in messages[0]:
3327
+ report(f"{label} expiry message is not from sweep: {messages[0]}")
3328
+ return 1
3329
+ if chat_records_with(b, "dm-sweep--sweep", "lock main-checkout expired at"):
3330
+ report(f"{label} expiry posted a direct message from sweep to itself")
3331
+ return 1
3332
+ reclaimed = lock(b, "acquire", "main-checkout", "--for", "1h", "--note", "formal sweep")
3333
+ if reclaimed.returncode != 0:
3334
+ report(f"{label} sweep could not acquire after expiry: {reclaimed.stderr}")
3335
+ return 1
3336
+ released = lock(b, "release", "main-checkout")
3337
+ if released.returncode != 0:
3338
+ report(f"{label} sweep release after expiry failed: {released.stderr}")
3339
+ return 1
3340
+
3341
+ # Simultaneous public commands: a lease must have exactly one winner.
3342
+ command = ["node", str(ROOT / "bin" / "keel.js"), "lock", "acquire", "race", "--for", "1h", "--note", "race"]
3343
+ racers = [subprocess.Popen(command, cwd=tree, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for tree in (a, b)]
3344
+ outputs = [p.communicate(timeout=30) for p in racers]
3345
+ if sorted(p.returncode for p in racers) != [0, 1]:
3346
+ report(f"{label} racing acquires lack exactly one winner: {outputs}")
3347
+ return 1
3348
+ rows = leases()
3349
+ if len(rows) != 1:
3350
+ report(f"{label} race recorded other than one lease: {rows}")
3351
+ return 1
3352
+ winner = a if racers[0].returncode == 0 else b
3353
+ if rows[0].get("worktree") != str(winner.resolve()):
3354
+ report(f"{label} race lease does not belong to the winner: {rows}")
3355
+ return 1
3356
+ if len(rows[0].get("waiters", [])) != 1:
3357
+ report(f"{label} racing loser was not recorded as a waiter: {rows}")
3358
+ return 1
3359
+ released = lock(winner, "release", "race")
3360
+ if released.returncode != 0:
3361
+ report(f"{label} race winner could not release: {released.stderr}")
3362
+ return 1
3363
+
3364
+ # A mutex left by a crashed command is stale after 30 seconds.
3365
+ mutex = locks / ".mutation"
3366
+ mutex.mkdir(parents=True, exist_ok=True)
3367
+ os.utime(mutex, (time.time() - 120, time.time() - 120))
3368
+ unstuck = lock(a, "list")
3369
+ if unstuck.returncode != 0:
3370
+ report(f"{label} a stale mutex blocked keel lock list: {unstuck.stderr}")
3371
+ return 1
3372
+ if mutex.exists():
3373
+ report(f"{label} a stale mutex was left in place after keel lock list.")
3374
+ return 1
3375
+
3376
+ # No role: worktree identity, --repo, read-only shift and printed expiry.
3377
+ c = chat_worktree(a, Path(raw) / "unbound")
3378
+ acquired = lock(a, "acquire", "cpu-1", "--for", "1h", "--note", "slot", "--repo", str(c))
3379
+ if acquired.returncode != 0:
3380
+ report(f"{label} unbound --repo acquire failed: {acquired.stderr}")
3381
+ return 1
3382
+ row = leases()[0]
3383
+ if not row.get("holder", "").startswith("worktree:unbound-"):
3384
+ report(f"{label} unbound lease lacks worktree identity: {row}")
3385
+ return 1
3386
+ if row.get("role") is not None:
3387
+ report(f"{label} unbound lease has a chat role: {row}")
3388
+ return 1
3389
+ file = locks / "cpu-1.json"
3390
+ row["expires"] = "2000-01-01T00:00:00+00:00"
3391
+ file.write_text(json.dumps(row))
3392
+ before = file.read_bytes()
3393
+ checked = run_keel(c, "shift", "check", "--json", env=env)
3394
+ if any(item["kind"] == "lock" for item in chat_json(checked).get("items", [])):
3395
+ report(f"{label} shift check reports an expired lease")
3396
+ return 1
3397
+ if file.read_bytes() != before:
3398
+ report(f"{label} shift check mutated the expired lease")
3399
+ return 1
3400
+ freed = lock(c, "list", "--json")
3401
+ if freed.returncode != 0:
3402
+ report(f"{label} unbound expiry command failed: {freed.stderr}")
3403
+ return 1
3404
+ if "cpu-1" not in freed.stderr:
3405
+ report(f"{label} unbound expiry was not printed beside JSON: {freed.stderr}")
3406
+ return 1
3407
+ if chat_json(freed).get("leases") != []:
3408
+ report(f"{label} unbound expiry list is not empty JSON: {freed.stdout}")
3409
+ return 1
3410
+ guide = ROOT / "docs" / "resource-lock.md"
3411
+ if not guide.exists():
3412
+ report(f"{label} docs/resource-lock.md is missing")
3413
+ return 1
3414
+ if "enforces nothing" not in guide.read_text():
3415
+ report(f"{label} guide does not say the lease enforces nothing")
3416
+ return 1
3417
+ if "docs/resource-lock.md" not in (ROOT / "README.md").read_text():
3418
+ report(f"{label} README does not link the guide")
3419
+ return 1
3420
+ if "resource-lock" not in {name for name, _ in registry.SCENARIOS}:
3421
+ report(f"{label} scenario is not registered")
3422
+ return 1
3423
+ report("resource-lock scenario passed.")
3424
+ return 0
3425
+
3426
+
3427
+ def validate_owner_language_scenario() -> int:
3428
+ """Issue #305: a declared owner language is restated where replies are written."""
3429
+ label = "owner-language:"
3430
+ protocol = (ROOT / "AGENTS.md").read_text(encoding="utf-8")
3431
+ if "declares `owner_language:`" not in protocol:
3432
+ report(f"{label} AGENTS.md does not make a declared owner_language binding.")
3433
+ return 1
3434
+ with tempfile.TemporaryDirectory(prefix="keel-owner-language-") as raw:
3435
+ base = Path(raw)
3436
+ rtl, verify, env = chat_scratch_group(base)
3437
+ loose = chat_worktree(rtl, base / "loose")
3438
+ for tree in (rtl, loose):
3439
+ write_text(tree / "openspec/specs/.keep", "")
3440
+ write_authorize_config(tree, "owner_language: zh\n")
3441
+
3442
+ def prompt(cwd: Path) -> str:
3443
+ result = subprocess.run(
3444
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "user-prompt-submit"],
3445
+ cwd=cwd, env=env, text=True, capture_output=True, check=False,
3446
+ input=json.dumps({"cwd": str(cwd), "hook_event_name": "UserPromptSubmit", "session_id": "p1", "prompt": "go on"}),
3447
+ )
3448
+ if not result.stdout.strip():
3449
+ return ""
3450
+ return json.loads(result.stdout).get("hookSpecificOutput", {}).get("additionalContext", "")
3451
+
3452
+ unbound = prompt(loose)
3453
+ if "中文" not in unbound:
3454
+ report(f"{label} the prompt hook in an unbound worktree does not restate the language: {unbound!r}")
3455
+ return 1
3456
+ if "structured-choice" not in unbound:
3457
+ report(f"{label} the restated rule does not cover structured-choice options: {unbound!r}")
3458
+ return 1
3459
+ context = json.loads(run_keel(loose, "context", "--json", env=env).stdout)
3460
+ if context.get("ownerLanguage") != "zh":
3461
+ report(f"{label} keel context carries ownerLanguage {context.get('ownerLanguage')!r}.")
3462
+ return 1
3463
+ session = run_session_start_hook(
3464
+ loose, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(loose)},
3465
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
3466
+ )
3467
+ if "中文" not in (session_start_context(session) or ""):
3468
+ report(f"{label} the session-start note does not state the language: {session_start_context(session)!r}")
3469
+ return 1
3470
+ run_keel(verify, "chat", "post", "soc", "@rtl please look", env=env)
3471
+ bound = prompt(rtl)
3472
+ if "中文" not in bound:
3473
+ report(f"{label} a bound role's prompt hook lost the language line: {bound!r}")
3474
+ return 1
3475
+ if "please look" not in bound:
3476
+ report(f"{label} a bound role's prompt hook lost the chat notice: {bound!r}")
3477
+ return 1
3478
+ write_authorize_config(loose, "owner_language: Chinese!\n")
3479
+ broken = json.loads(run_keel(loose, "context", "--json", env=env).stdout)
3480
+ if not any("owner_language" in w for w in broken.get("warnings", [])):
3481
+ report(f"{label} a malformed owner_language is not reported: {broken.get('warnings')!r}")
3482
+ return 1
3483
+ if "ownerLanguage" in broken:
3484
+ report(f"{label} a malformed owner_language is still carried: {broken.get('ownerLanguage')!r}")
3485
+ return 1
3486
+ if "Owner language" in prompt(loose):
3487
+ report(f"{label} a malformed owner_language still adds a language line.")
3488
+ return 1
3489
+ report("owner-language scenario passed.")
3490
+ return 0
3491
+
3492
+
3493
+ def validate_owner_language_after_tools_scenario() -> int:
3494
+ """Issue #311: the owner's language is restated after runs of tool calls."""
3495
+ label = "owner-language-after-tools:"
3496
+ manifest = json.loads((ROOT / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8"))
3497
+ post = json.dumps(manifest.get("hooks", {}).get("PostToolUse", []))
3498
+ if "mail-hook.js" not in post or "post-tool-use" not in post:
3499
+ report(f"{label} .claude-plugin/plugin.json does not register PostToolUse on mail-hook.js post-tool-use: {post}")
3500
+ return 1
3501
+ with tempfile.TemporaryDirectory(prefix="keel-language-tools-") as raw:
3502
+ base = Path(raw)
3503
+ rtl, _verify, env = chat_scratch_group(base)
3504
+ env = {**env, "KEEL_CLI": f'node "{ROOT / "bin" / "keel.js"}"'}
3505
+ write_authorize_config(rtl, "owner_language: zh\n")
3506
+
3507
+ def hook(event: str, payload: dict) -> str:
3508
+ result = subprocess.run(
3509
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/mail-hook.js"), event],
3510
+ cwd=rtl, env=env, text=True, capture_output=True, check=False,
3511
+ input=json.dumps({"cwd": str(rtl), **payload}),
3512
+ )
3513
+ if not result.stdout.strip():
3514
+ return ""
3515
+ return json.loads(result.stdout).get("hookSpecificOutput", {}).get("additionalContext", "")
3516
+
3517
+ def tool(session: str) -> str:
3518
+ return hook("post-tool-use", {"hook_event_name": "PostToolUse", "session_id": session, "tool_name": "Bash"})
3519
+
3520
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "t1", "prompt": "go on"})
3521
+ outputs = [tool("t1") for _ in range(16)]
3522
+ early = [n + 1 for n, text in enumerate(outputs[:14]) if text]
3523
+ if early:
3524
+ report(f"{label} PostToolUse calls {early} restated the rule before the 15th.")
3525
+ return 1
3526
+ if "中文" not in outputs[14]:
3527
+ report(f"{label} the 15th PostToolUse did not restate the rule: {outputs[14]!r}")
3528
+ return 1
3529
+ if outputs[15]:
3530
+ report(f"{label} the 16th PostToolUse restated the rule again: {outputs[15]!r}")
3531
+ return 1
3532
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "t1", "prompt": "next"})
3533
+ if tool("t1"):
3534
+ report(f"{label} the first tool call after a prompt restated the rule.")
3535
+ return 1
3536
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "run1"})
3537
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "run1", "prompt": '<scheduled-task name="patrol">run'})
3538
+ if any(tool("run1") for _ in range(16)):
3539
+ report(f"{label} a host-run session was reminded.")
3540
+ return 1
3541
+ write_authorize_config(rtl, "")
3542
+ if any(tool("t2") for _ in range(16)):
3543
+ report(f"{label} a repository without owner_language was reminded.")
3544
+ return 1
3545
+ report("owner-language-after-tools scenario passed.")
3546
+ return 0
3547
+
3548
+
3549
+ def validate_chat_park_role_scenario() -> int:
3550
+ """A role parked on purpose is left alone, and posters are told (#316).
3551
+
3552
+ `keel chat role --park` records the park; posts naming the role say it is
3553
+ parked; the patrol neither nudges it nor reports it; `--unpark` summarizes
3554
+ what waited; a session running as the role ends the park (chat-park-role
3555
+ D1-D5).
3556
+ """
3557
+ label = "chat-park-role:"
3558
+ with tempfile.TemporaryDirectory(prefix="keel-chat-park-role-") as raw:
3559
+ base = Path(raw)
3560
+ rtl, verify, env, _ = shift_scratch(base)
3561
+ run_keel(rtl, "chat", "group", "create", "soc", "verify", env=env)
3562
+ ghost = run_keel(rtl, "chat", "role", "--park", "ghost", env=env)
3563
+ if ghost.returncode == 0:
3564
+ report(f"{label} parking an unbound role was accepted: {ghost.stdout.strip()}")
3565
+ return 1
3566
+ run_keel(rtl, "chat", "post", "soc", "@verify please rerun R007", env=env)
3567
+ time.sleep(1.2)
3568
+ parked = run_keel(rtl, "chat", "role", "--park", "verify", "--reason", "until R040", env=env)
3569
+ made = run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "R041 rerun", env=env)
3570
+ if made.returncode != 0:
3571
+ report(f"{label} a todo for a parked role failed: {made.stderr.strip()}")
3572
+ return 1
3573
+ if "verify is parked" not in made.stdout:
3574
+ report(f"{label} a todo for a parked role does not say verify is parked: {made.stdout.strip()} (--park: {parked.stderr.strip() or parked.stdout.strip()})")
3575
+ return 1
3576
+ if "until R040" not in made.stdout:
3577
+ report(f"{label} a todo for a parked role does not give the reason: {made.stdout.strip()}")
3578
+ return 1
3579
+ as_json = run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "R042 rerun", "--json", env=env)
3580
+ entries = json.loads(as_json.stdout).get("parked") if as_json.returncode == 0 else None
3581
+ if not entries or entries[0].get("role") != "verify" or entries[0].get("reason") != "until R040":
3582
+ report(f"{label} --json does not carry parked: {as_json.stdout.strip()}")
3583
+ return 1
3584
+
3585
+ def patrol() -> subprocess.CompletedProcess[str]:
3586
+ return run_keel(rtl, "patrol", "--nudge", "--idle", "1s", env=env)
3587
+
3588
+ for attempt in (1, 2):
3589
+ time.sleep(1.2)
3590
+ run = patrol()
3591
+ lines = run.stdout.splitlines()
3592
+ if any(line.startswith("nudged verify") for line in lines):
3593
+ report(f"{label} patrol run {attempt} nudged the parked role: {run.stdout.strip()}")
3594
+ return 1
3595
+ if any(line.startswith(("risk:", "drift:")) and "verify" in line for line in lines):
3596
+ report(f"{label} patrol run {attempt} reported the parked role: {run.stdout.strip()}")
3597
+ return 1
3598
+ if not any(line.startswith("role verify:") and "parked" in line for line in lines):
3599
+ report(f"{label} patrol run {attempt} does not show verify as parked: {run.stdout.strip()}")
3600
+ return 1
3601
+ unparked = run_keel(rtl, "chat", "role", "--unpark", "verify", env=env)
3602
+ if unparked.returncode != 0:
3603
+ report(f"{label} --unpark failed: {unparked.stderr.strip()}")
3604
+ return 1
3605
+ if "waited" not in unparked.stdout:
3606
+ report(f"{label} --unpark does not report what waited: {unparked.stdout.strip()}")
3607
+ return 1
3608
+ time.sleep(1.2)
3609
+ after = patrol()
3610
+ if "nudged verify: unread" not in after.stdout:
3611
+ report(f"{label} after --unpark the patrol did not nudge verify: {after.stdout.strip()}")
3612
+ return 1
3613
+ plain = run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "R043 rerun", env=env)
3614
+ if "parked" in plain.stdout:
3615
+ report(f"{label} a todo after --unpark still says parked: {plain.stdout.strip()}")
3616
+ return 1
3617
+ run_keel(rtl, "chat", "role", "--park", "verify", env=env)
3618
+ time.sleep(1.2)
3619
+ subprocess.run(
3620
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"],
3621
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
3622
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "source": "startup"}),
3623
+ )
3624
+ resumed = run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "R044 rerun", env=env)
3625
+ if "parked" in resumed.stdout:
3626
+ report(f"{label} a session running as verify did not end the park: {resumed.stdout.strip()}")
3627
+ return 1
3628
+ for relative in ("docs/chat-slack-setup.md", "docs/chat-slack-setup.zh-CN.md"):
3629
+ if "--park" not in (ROOT / relative).read_text(encoding="utf-8"):
3630
+ report(f"{label} {relative} does not mention --park.")
3631
+ return 1
3632
+ if "chat-park-role" not in {name for name, _ in registry.SCENARIOS}:
3633
+ report(f"{label} scenario is not registered.")
3634
+ return 1
3635
+ report("chat-park-role scenario passed.")
3636
+ return 0
3637
+
3638
+
3639
+ def validate_chat_wake_idle_desktop_scenario() -> int:
3640
+ """A record for an idle desktop session names the step that wakes it (#331).
3641
+
3642
+ On the Claude desktop app a session with no running Claude process reads
3643
+ no chat record, so a todo or a patrol nudge alone wakes nothing there
3644
+ (chat-wake-idle-desktop D1-D4). Outside the desktop app nothing changes.
3645
+ """
3646
+ label = "chat-wake-idle-desktop:"
3647
+ with tempfile.TemporaryDirectory(prefix="keel-chat-wake-idle-desktop-") as raw:
3648
+ base = Path(raw)
3649
+ rtl, verify, env, _ = shift_scratch(base)
3650
+ gone = subprocess.Popen(["node", "-e", ""])
3651
+ gone.wait()
3652
+ desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-331", "KEEL_SHIFT_DESKTOP_PID": str(gone.pid)}
3653
+
3654
+ def hook(environment: dict) -> subprocess.CompletedProcess[str]:
3655
+ return subprocess.run(
3656
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"],
3657
+ cwd=verify, env=environment, text=True, capture_output=True, check=False,
3658
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "source": "startup"}),
3659
+ )
3660
+
3661
+ steps = ("send_message", "get_session", "unarchive_session", "local_test-331")
3662
+ started = hook(desktop)
3663
+ if started.returncode != 0:
3664
+ report(f"{label} the desktop session-start hook failed: {started.stderr.strip()}")
3665
+ return 1
3666
+ run_keel(rtl, "chat", "group", "create", "soc", "verify", env=env)
3667
+ made = run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "R031 rerun", env=env)
3668
+ if made.returncode != 0:
3669
+ report(f"{label} todo failed: {made.stderr.strip()}")
3670
+ return 1
3671
+ for needle in steps:
3672
+ if needle not in made.stdout:
3673
+ report(f"{label} a todo for an idle desktop session does not name {needle}: {made.stdout.strip()}")
3674
+ return 1
3675
+ as_json = run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "R032 rerun", "--json", env=env)
3676
+ asleep = json.loads(as_json.stdout).get("asleep") if as_json.returncode == 0 else None
3677
+ if asleep != [{"role": "verify", "session": "local_test-331"}]:
3678
+ report(f"{label} --json does not carry asleep: {as_json.stdout.strip()} {as_json.stderr.strip()}")
3679
+ return 1
3680
+ stored = run_keel(verify, "chat", "todos", "--mine", env=desktop)
3681
+ if "R031 rerun" not in stored.stdout:
3682
+ report(f"{label} the todo was not stored: {stored.stdout.strip()}")
3683
+ return 1
3684
+ time.sleep(1.2)
3685
+ patrol = run_keel(rtl, "patrol", "--nudge", "--idle", "1s", env=env)
3686
+ if "nudged verify" not in patrol.stdout:
3687
+ report(f"{label} the patrol did not nudge verify: {patrol.stdout.strip()} {patrol.stderr.strip()}")
3688
+ return 1
3689
+ risks = [line for line in patrol.stdout.splitlines() if line.startswith("risk:")]
3690
+ if not any("local_test-331" in line and "send_message" in line for line in risks):
3691
+ report(f"{label} the first nudge to an idle desktop session reports no risk naming its wake step: {patrol.stdout.strip()}")
3692
+ return 1
3693
+ if hook(env).returncode != 0:
3694
+ report(f"{label} the plain session-start hook failed.")
3695
+ return 1
3696
+ plain = run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "R033 rerun", env=env)
3697
+ if any(needle in plain.stdout for needle in steps):
3698
+ report(f"{label} a todo for a session outside the desktop app still names a wake step: {plain.stdout.strip()}")
3699
+ return 1
3700
+ for relative in ("docs/chat-slack-setup.md", "docs/chat-slack-setup.zh-CN.md"):
3701
+ if "#331" not in (ROOT / relative).read_text(encoding="utf-8"):
3702
+ report(f"{label} {relative} does not mention #331.")
3703
+ return 1
3704
+ if "chat-wake-idle-desktop" not in {name for name, _ in registry.SCENARIOS}:
3705
+ report(f"{label} scenario is not registered.")
3706
+ return 1
3707
+ report("chat-wake-idle-desktop scenario passed.")
3708
+ return 0
3709
+
3710
+
3711
+ def validate_chat_archive_scenario() -> int:
3712
+ """Issue #187: chat history is archived to an orphan branch, never exposed.
3713
+
3714
+ `keel chat archive sync` commits the shared layer of the store to
3715
+ `refs/heads/keel-chat` with plumbing, leaving the worktree and index as
3716
+ they were; refuses to push a repository reported public unless the
3717
+ project declared a remote or accepted publication; merges another clone's
3718
+ records by union; and `archive pull` restores history in a fresh clone.
3719
+ """
3720
+ label = "chat-archive:"
3721
+ with tempfile.TemporaryDirectory(prefix="keel-chat-archive-") as raw:
3722
+ base = Path(raw)
3723
+ remote = base / "remote.git"
3724
+ subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(remote)], check=True, capture_output=True)
3725
+ rtl, verify, env = chat_scratch_group(base)
3726
+ subprocess.run(["git", "remote", "add", "origin", str(remote)], cwd=rtl, check=True, capture_output=True)
3727
+ subprocess.run(["git", "push", "-q", "origin", "main"], cwd=rtl, check=True, capture_output=True)
3728
+ gh = base / "gh"
3729
+ write_text(gh, "#!/bin/sh\necho PUBLIC\n")
3730
+ gh.chmod(0o755)
3731
+ aenv = {**env, "KEEL_CHAT_GH": str(gh)}
3732
+
3733
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3734
+ return run_keel(cwd, "chat", *args, env=aenv)
3735
+
3736
+ def remote_has_branch() -> bool:
3737
+ listed = subprocess.run(["git", "ls-remote", str(remote), "refs/heads/keel-chat"], capture_output=True, text=True)
3738
+ return bool(listed.stdout.strip())
3739
+
3740
+ def branch_files(repo: Path) -> list[str]:
3741
+ listed = subprocess.run(["git", "ls-tree", "-r", "--name-only", "refs/heads/keel-chat"], cwd=repo, capture_output=True, text=True)
3742
+ return listed.stdout.split()
3743
+
3744
+ chat(rtl, "post", "soc", "first archived message")
3745
+ chat(verify, "post", "soc", "second archived message")
3746
+ write_text(rtl / "scratch.txt", "untracked work in progress\n")
3747
+ write_text(rtl / "keel" / "chat.json", json.dumps({"slack": {"enabled": True, "channels": {}}}) + "\n")
3748
+ before = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
3749
+ index_before = (mailbox_common_dir(rtl) / "index").read_bytes()
3750
+
3751
+ refused = chat(rtl, "archive", "sync")
3752
+ if refused.returncode != 0:
3753
+ report(f"{label} archive sync failed: {refused.stderr.strip()}")
3754
+ return 1
3755
+ files = branch_files(rtl)
3756
+ logs = [f for f in files if f.startswith("groups/soc/log/") and f.endswith(".md")]
3757
+ if len(logs) < 2:
3758
+ report(f"{label} refs/heads/keel-chat does not hold the group's records: {files!r}")
3759
+ return 1
3760
+ local_only = [f for f in files if f == "roles.json" or f.split("/")[0] in ("signal", "bridge", "transcripts", ".tmp")]
3761
+ if local_only:
3762
+ report(f"{label} the archive carries local-only files: {local_only!r}")
3763
+ return 1
3764
+ after = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
3765
+ if after != before:
3766
+ report(f"{label} archive sync changed the worktree status:\nbefore {before!r}\nafter {after!r}")
3767
+ return 1
3768
+ if (mailbox_common_dir(rtl) / "index").read_bytes() != index_before:
3769
+ report(f"{label} archive sync changed the index.")
3770
+ return 1
3771
+ if remote_has_branch():
3772
+ report(f"{label} a repository reported public was pushed with no declaration.")
3773
+ return 1
3774
+ for needle in ("archive_public", "archive.remote"):
3775
+ if needle not in refused.stdout + refused.stderr:
3776
+ report(f"{label} the refused push does not name {needle}: {(refused.stdout + refused.stderr).strip()}")
3777
+ return 1
3778
+
3779
+ write_text(rtl / "keel" / "chat.json", json.dumps({"slack": {"enabled": True, "channels": {}}, "archive": {"remote": "origin"}}) + "\n")
3780
+ pushed = chat(rtl, "archive", "sync")
3781
+ if pushed.returncode != 0:
3782
+ report(f"{label} archive sync with archive.remote failed: {pushed.stderr.strip()}")
3783
+ return 1
3784
+ if not remote_has_branch():
3785
+ report(f"{label} archive.remote was declared and nothing was pushed: {(pushed.stdout + pushed.stderr).strip()}")
3786
+ return 1
3787
+
3788
+ clone = base / "clone"
3789
+ subprocess.run(["git", "clone", "-q", str(remote), str(clone)], check=True, capture_output=True)
3790
+ run_keel(clone, "chat", "role", "--set", "verify", env=aenv)
3791
+ pulled = chat(clone, "archive", "pull")
3792
+ if pulled.returncode != 0:
3793
+ report(f"{label} archive pull failed in a fresh clone: {pulled.stderr.strip()}")
3794
+ return 1
3795
+ restored = chat(clone, "soc", "--peek")
3796
+ if "first archived message" not in restored.stdout:
3797
+ report(f"{label} a fresh clone does not show the archived history after pull: {restored.stdout.strip()} {restored.stderr.strip()}")
3798
+ return 1
3799
+
3800
+ write_text(clone / "keel" / "chat.json", json.dumps({"archive": {"remote": "origin"}}) + "\n")
3801
+ clone_id = chat_json(chat(clone, "post", "soc", "from the second machine", "--json")).get("id", "")
3802
+ if chat(clone, "archive", "sync").returncode != 0:
3803
+ report(f"{label} archive sync failed in the second clone.")
3804
+ return 1
3805
+ third = chat_json(chat(rtl, "post", "soc", "third from the first machine", "--json")).get("id", "")
3806
+ merged = chat(rtl, "archive", "sync")
3807
+ if merged.returncode != 0:
3808
+ report(f"{label} archive sync failed when merging the second clone's history: {merged.stderr.strip()}")
3809
+ return 1
3810
+ files = branch_files(rtl)
3811
+ for record_id, where in ((clone_id, "the second clone"), (third, "the first clone")):
3812
+ if f"groups/soc/log/{record_id}.md" not in files:
3813
+ report(f"{label} the merged archive lacks the record from {where}.")
3814
+ return 1
3815
+ if "from the second machine" not in chat(rtl, "soc", "--peek").stdout:
3816
+ report(f"{label} the first clone's store did not gain the second clone's record on sync.")
3817
+ return 1
3818
+
3819
+ if "chat-archive" not in {name for name, _ in registry.SCENARIOS}:
3820
+ report(f"{label} scenario is not registered.")
3821
+ return 1
3822
+ report("chat-archive scenario passed.")
3823
+ return 0
3824
+
3825
+
3826
+ def validate_chat_reply_marks_read_scenario() -> int:
3827
+ """Issue #201: answering a record marks it read for the one who answered.
3828
+
3829
+ A reply moves the poster's cursor to the replied-to record and `done`
3830
+ moves the closer's cursor to the todo, never backwards, so records after
3831
+ the answered one stay unread.
3832
+ """
3833
+ label = "chat-reply-marks-read:"
3834
+ with tempfile.TemporaryDirectory(prefix="keel-chat-reply-read-") as raw:
3835
+ base = Path(raw)
3836
+ rtl, verify, env = chat_scratch_group(base)
3837
+
3838
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3839
+ return run_keel(cwd, "chat", *args, env=env)
3840
+
3841
+ def unread_ids() -> list[str]:
3842
+ return [r.get("id") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
3843
+
3844
+ first = chat_json(chat(rtl, "post", "soc", "@verify first", "--json")).get("id", "")
3845
+ second = chat_json(chat(rtl, "post", "soc", "@verify second", "--json")).get("id", "")
3846
+ if not first or not second:
3847
+ report(f"{label} the two posts did not report ids.")
3848
+ return 1
3849
+ replied = chat(verify, "post", "soc", "on it", "--reply-to", first)
3850
+ if replied.returncode != 0:
3851
+ report(f"{label} the reply failed: {replied.stderr.strip()}")
3852
+ return 1
3853
+ after_reply = unread_ids()
3854
+ if first in after_reply:
3855
+ report(f"{label} the replied-to record is still unread for verify: {after_reply!r}")
3856
+ return 1
3857
+ if second not in after_reply:
3858
+ report(f"{label} the record after the replied-to one is no longer unread: {after_reply!r}")
3859
+ return 1
3860
+ readers = chat_json(chat(rtl, "show", first, "--json")).get("readers", [])
3861
+ if "verify" not in readers:
3862
+ report(f"{label} show does not list verify as a reader after its reply: {readers!r}")
3863
+ return 1
3864
+
3865
+ task = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun", "--json")).get("id", "")
3866
+ closed = chat(verify, "done", task)
3867
+ if closed.returncode != 0:
3868
+ report(f"{label} done failed: {closed.stderr.strip()}")
3869
+ return 1
3870
+ after_done = unread_ids()
3871
+ if task in after_done:
3872
+ report(f"{label} the closed todo is still unread for verify: {after_done!r}")
3873
+ return 1
3874
+
3875
+ third = chat_json(chat(rtl, "post", "soc", "@verify third", "--json")).get("id", "")
3876
+ chat(verify, "post", "soc", "late answer", "--reply-to", first)
3877
+ if third not in unread_ids():
3878
+ report(f"{label} a reply to a record behind the cursor moved it past a later unread record.")
3879
+ return 1
3880
+
3881
+ if "chat-reply-marks-read" not in {name for name, _ in registry.SCENARIOS}:
3882
+ report(f"{label} scenario is not registered.")
3883
+ return 1
3884
+ report("chat-reply-marks-read scenario passed.")
3885
+ return 0
3886
+
3887
+
3888
+ def codex_calls(calls: Path) -> list[dict]:
3889
+ if not calls.exists():
3890
+ return []
3891
+ return [json.loads(line) for line in calls.read_text().splitlines() if line.strip()]
3892
+
3893
+
3894
+ def validate_chat_wake_run_scenario() -> int:
3895
+ """Issue #203: an addressed record starts one Codex turn, and nothing else does.
3896
+
3897
+ A registered waker starts a turn only for unread records that wake the
3898
+ role, in a group declaring chat-reply, newer than what an earlier turn
3899
+ was given; the first turn creates the thread and later ones resume it,
3900
+ with compaction and the git common directory as a writable root, under a
3901
+ per-hour limit and a per-role lock, and nothing lands in the worktree.
3902
+ """
3903
+ label = "chat-wake-run:"
3904
+ with tempfile.TemporaryDirectory(prefix="keel-chat-wake-run-") as raw:
3905
+ base = Path(raw)
3906
+ rtl, cx, env, calls = chat_wake_scratch(base)
3907
+
3908
+ def keel(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3909
+ return run_keel(cwd, "chat", *args, env=env)
3910
+
3911
+ def run_once() -> subprocess.CompletedProcess[str]:
3912
+ return keel(base, "wake", "run", "--once", "--worktree", str(cx))
3913
+
3914
+ added = keel(cx, "wake", "add")
3915
+ if added.returncode != 0:
3916
+ report(f"{label} keel chat wake add failed: {(added.stdout + added.stderr).strip()}")
3917
+ return 1
3918
+ before = subprocess.run(["git", "status", "--porcelain"], cwd=cx, capture_output=True, text=True).stdout
3919
+
3920
+ def expect_turns(count: int, why: str) -> bool:
3921
+ result = run_once()
3922
+ if result.returncode != 0:
3923
+ report(f"{label} wake run --once failed {why}: {(result.stdout + result.stderr).strip()}")
3924
+ return False
3925
+ turns = codex_calls(calls)
3926
+ if len(turns) != count:
3927
+ report(f"{label} {len(turns)} Codex turns {why}, not {count}.")
3928
+ return False
3929
+ return True
3930
+
3931
+ if not expect_turns(0, "with nothing unread"):
3932
+ return 1
3933
+ keel(rtl, "post", "lab", "@all standup")
3934
+ if not expect_turns(0, "when the only unread record is @all"):
3935
+ return 1
3936
+ keel(rtl, "post", "other", "@cx ping-in-other")
3937
+ if not expect_turns(0, "for a mention in a group without chat-reply"):
3938
+ return 1
3939
+ keel(rtl, "post", "lab", "@cx ping-secret-123")
3940
+ if not expect_turns(1, "for one @cx record in lab"):
3941
+ return 1
3942
+ first = codex_calls(calls)[0]
3943
+ argv = first["argv"]
3944
+ common = str(mailbox_common_dir(rtl))
3945
+ if argv[:2] != ["exec", "--json"]:
3946
+ report(f"{label} the first turn is not a new `exec --json` turn: {argv!r}")
3947
+ return 1
3948
+ if "resume" in argv:
3949
+ report(f"{label} the first turn resumes a thread although none exists: {argv!r}")
3950
+ return 1
3951
+ joined = " ".join(argv)
3952
+ for needle in ("model_auto_compact_token_limit=100000", 'sandbox_mode="workspace-write"', "sandbox_workspace_write.writable_roots=", common):
3953
+ if needle not in joined:
3954
+ report(f"{label} the turn's arguments lack {needle!r}: {argv!r}")
3955
+ return 1
3956
+ if Path(first["cwd"]).resolve() != cx.resolve():
3957
+ report(f"{label} the turn ran in {first['cwd']}, not the worktree.")
3958
+ return 1
3959
+ if "ping-secret-123" in joined:
3960
+ report(f"{label} the record text reached the turn's arguments.")
3961
+ return 1
3962
+ if "ping-secret-123" in first["stdin"]:
3963
+ report(f"{label} the record text reached the turn's standard input.")
3964
+ return 1
3965
+ registrations = chat_json(keel(cx, "wake", "status", "--json")).get("registrations", [])
3966
+ if len(registrations) != 1:
3967
+ report(f"{label} status lists {len(registrations)} registrations, not one: {registrations!r}")
3968
+ return 1
3969
+ if registrations[0].get("thread") != "thread-fake-1":
3970
+ report(f"{label} status does not report the turn's thread: {registrations!r}")
3971
+ return 1
3972
+ if not expect_turns(1, "on a second run with no new record"):
3973
+ return 1
3974
+ keel(rtl, "post", "lab", "@cx second")
3975
+ if not expect_turns(2, "for a second @cx record"):
3976
+ return 1
3977
+ second = codex_calls(calls)[1]["argv"]
3978
+ if second[:3] != ["exec", "resume", "thread-fake-1"]:
3979
+ report(f"{label} the second turn does not resume the thread: {second!r}")
3980
+ return 1
3981
+
3982
+ limited = keel(cx, "wake", "add", "--max-per-hour", "2")
3983
+ if limited.returncode != 0:
3984
+ report(f"{label} wake add --max-per-hour failed: {(limited.stdout + limited.stderr).strip()}")
3985
+ return 1
3986
+ keel(rtl, "post", "lab", "@cx third")
3987
+ if not expect_turns(2, "past the hourly limit of 2"):
3988
+ return 1
3989
+ held = chat_json(keel(cx, "wake", "status", "--json")).get("registrations", [{}])[0]
3990
+ if held.get("held") is not True:
3991
+ report(f"{label} status does not report the registration held: {held!r}")
3992
+ return 1
3993
+
3994
+ keel(cx, "wake", "add", "--max-per-hour", "10")
3995
+ lock = base / "home" / "chat" / "wake" / f"{held.get('label')}.lock"
3996
+ write_text(lock, f"{os.getpid()}\n")
3997
+ if not expect_turns(2, "while another run holds the role's lock"):
3998
+ return 1
3999
+ lock.unlink()
4000
+ if not expect_turns(3, "after the lock is released"):
4001
+ return 1
4002
+
4003
+ after = subprocess.run(["git", "status", "--porcelain"], cwd=cx, capture_output=True, text=True).stdout
4004
+ if after.strip():
4005
+ report(f"{label} the waker left files in the worktree: {after!r} (before: {before!r})")
4006
+ return 1
4007
+ if not (base / "home" / "chat" / "wake.json").exists():
4008
+ report(f"{label} the registration is not under KEEL_HOME.")
4009
+ return 1
4010
+
4011
+ if "chat-wake-run" not in {name for name, _ in registry.SCENARIOS}:
4012
+ report(f"{label} scenario is not registered.")
4013
+ return 1
4014
+ report("chat-wake-run scenario passed.")
4015
+ return 0
4016
+
4017
+
4018
+ def validate_chat_wake_lifecycle_scenario() -> int:
4019
+ """Issue #203: the owner installs and removes a waker, and it watches the signal file.
4020
+
4021
+ `wake add` writes a LaunchAgent that watches the role's signal file and
4022
+ runs `wake run --once --worktree <path>` at load and on each change; it is
4023
+ refused without a role or for a host other than Codex, and warns when no
4024
+ chat-reply is declared; `wake remove` unloads and deletes it and keeps
4025
+ the log.
4026
+ """
4027
+ import plistlib # noqa: PLC0415 - only the lifecycle scenarios read a plist
4028
+
4029
+ label = "chat-wake-lifecycle:"
4030
+ with tempfile.TemporaryDirectory(prefix="keel-chat-wake-life-") as raw:
4031
+ base = Path(raw)
4032
+ rtl, cx, env, calls = chat_wake_scratch(base)
4033
+ norole = chat_worktree(rtl, base / "norole")
4034
+ agents = base / "agents"
4035
+ launchctl_calls = base / "launchctl-calls"
4036
+
4037
+ def keel(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
4038
+ return run_keel(cwd, "chat", *args, env=env)
4039
+
4040
+ added = keel(cx, "wake", "add")
4041
+ if added.returncode != 0:
4042
+ report(f"{label} wake add failed: {(added.stdout + added.stderr).strip()}")
4043
+ return 1
4044
+ plists = list(agents.glob("*.plist"))
4045
+ if len(plists) != 1:
4046
+ report(f"{label} wake add wrote {len(plists)} plists, not one.")
4047
+ return 1
4048
+ plist = plistlib.loads(plists[0].read_bytes())
4049
+ if not str(plist.get("Label", "")).startswith("dev.keel.chat-wake.cx-"):
4050
+ report(f"{label} the LaunchAgent label does not name the role: {plist.get('Label')!r}")
4051
+ return 1
4052
+ signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "cx"
4053
+ if [Path(p).resolve() for p in plist.get("WatchPaths", [])] != [signal.resolve()]:
4054
+ report(f"{label} the LaunchAgent does not watch the role's signal file: {plist.get('WatchPaths')!r}")
4055
+ return 1
4056
+ if not signal.exists():
4057
+ report(f"{label} wake add did not create the signal file it watches.")
4058
+ return 1
4059
+ program = plist.get("ProgramArguments", [])
4060
+ if program[-6:-1] != ["chat", "wake", "run", "--once", "--worktree"]:
4061
+ report(f"{label} the LaunchAgent does not run `chat wake run --once --worktree`: {program!r}")
4062
+ return 1
4063
+ if Path(program[-1]).resolve() != cx.resolve():
4064
+ report(f"{label} the LaunchAgent names {program[-1]}, not the worktree.")
4065
+ return 1
4066
+ if plist.get("RunAtLoad") is not True:
4067
+ report(f"{label} the LaunchAgent does not run at load: {plist!r}")
4068
+ return 1
4069
+ if "bootstrap" not in launchctl_calls.read_text():
4070
+ report(f"{label} wake add did not load the LaunchAgent.")
4071
+ return 1
4072
+
4073
+ unbound = keel(norole, "wake", "add")
4074
+ if unbound.returncode == 0:
4075
+ report(f"{label} wake add succeeded in a worktree with no role.")
4076
+ return 1
4077
+ if "role" not in unbound.stderr:
4078
+ report(f"{label} the no-role refusal does not say a role is needed: {unbound.stderr.strip()}")
4079
+ return 1
4080
+ other_host = keel(cx, "wake", "add", "--host", "claude")
4081
+ if other_host.returncode == 0:
4082
+ report(f"{label} wake add accepted --host claude.")
4083
+ return 1
4084
+ if "--host" not in other_host.stderr:
4085
+ report(f"{label} the host refusal does not name --host: {other_host.stderr.strip()}")
4086
+ return 1
4087
+
4088
+ listed = chat_json(keel(cx, "wake", "status", "--json")).get("registrations", [])
4089
+ mine = [entry for entry in listed if entry.get("role") == "cx"]
4090
+ if len(mine) != 1:
4091
+ report(f"{label} status does not list the cx registration once: {listed!r}")
4092
+ return 1
4093
+ if mine[0].get("installed") is not True:
4094
+ report(f"{label} status does not report the waker installed: {mine[0]!r}")
4095
+ return 1
4096
+
4097
+ undeclared = keel(rtl, "wake", "add")
4098
+ if undeclared.returncode != 0:
4099
+ report(f"{label} wake add without chat-reply failed: {(undeclared.stdout + undeclared.stderr).strip()}")
4100
+ return 1
4101
+ if "declares no chat-reply" not in undeclared.stdout:
4102
+ report(f"{label} wake add without chat-reply does not say nothing will wake: {undeclared.stdout.strip()}")
4103
+ return 1
4104
+
4105
+ keel(rtl, "post", "lab", "@cx ping")
4106
+ keel(base, "wake", "run", "--once", "--worktree", str(cx))
4107
+ log = Path(mine[0].get("log", ""))
4108
+ if not log.exists():
4109
+ report(f"{label} a turn wrote no wake log at {log}.")
4110
+ return 1
4111
+ removed = keel(cx, "wake", "remove")
4112
+ if removed.returncode != 0:
4113
+ report(f"{label} wake remove failed: {(removed.stdout + removed.stderr).strip()}")
4114
+ return 1
4115
+ if "bootout" not in launchctl_calls.read_text():
4116
+ report(f"{label} wake remove did not unload the LaunchAgent.")
4117
+ return 1
4118
+ if plists[0].exists():
4119
+ report(f"{label} wake remove left the plist.")
4120
+ return 1
4121
+ remaining = chat_json(keel(cx, "wake", "status", "--json")).get("registrations", [])
4122
+ if any(entry.get("role") == "cx" for entry in remaining):
4123
+ report(f"{label} wake remove left the registration: {remaining!r}")
4124
+ return 1
4125
+ if not log.exists():
4126
+ report(f"{label} wake remove deleted the log.")
4127
+ return 1
4128
+
4129
+ if "chat-wake-lifecycle" not in {name for name, _ in registry.SCENARIOS}:
4130
+ report(f"{label} scenario is not registered.")
4131
+ return 1
4132
+ report("chat-wake-lifecycle scenario passed.")
4133
+ return 0
4134
+
4135
+
4136
+ def validate_chat_notice_check_scenario() -> int:
4137
+ """Issue #194: a scheduler asks, without a model turn, whether to start one.
4138
+
4139
+ `keel chat notice --check` prints nothing and moves no cursor. It exits
4140
+ 0 exactly when something that would wake the role is unread — a mention,
4141
+ an assigned todo, a direct message — and 1 otherwise, including for a
4142
+ broadcast alone, outside a repository, and with no role bound.
4143
+ """
4144
+ label = "chat-notice-check:"
4145
+ with tempfile.TemporaryDirectory(prefix="keel-chat-check-") as raw:
4146
+ base = Path(raw)
4147
+ rtl, verify, env = chat_scratch_group(base)
4148
+ unbound = mailbox_repository(base / "unbound")
4149
+ plain = base / "plain"
4150
+ plain.mkdir()
4151
+
4152
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
4153
+ return run_keel(cwd, "chat", *args, env=env)
4154
+
4155
+ def check(cwd: Path, expected: int, why: str) -> bool:
4156
+ result = chat(cwd, "notice", "--check")
4157
+ if result.stdout or result.stderr:
4158
+ report(f"{label} --check wrote output {why}: {(result.stdout + result.stderr).strip()!r}")
4159
+ return False
4160
+ if result.returncode != expected:
4161
+ report(f"{label} --check exited {result.returncode} {why}, not {expected}.")
4162
+ return False
4163
+ return True
4164
+
4165
+ if not check(verify, 1, "with nothing unread"):
4166
+ return 1
4167
+ chat(rtl, "post", "soc", "@all standup in five")
4168
+ if not check(verify, 1, "when the only unread record is @all"):
4169
+ return 1
4170
+ chat(rtl, "post", "soc", "@verify please rerun")
4171
+ if not check(verify, 0, "with an unread @verify"):
4172
+ return 1
4173
+ before = chat_json(chat(verify, "unread", "--json")).get("unread", [])
4174
+ store = mailbox_common_dir(rtl) / "keel-chat"
4175
+
4176
+ def snapshot() -> dict[str, bytes]:
4177
+ return {str(p.relative_to(store)): p.read_bytes() for p in store.rglob("*") if p.is_file()}
4178
+
4179
+ files_before = snapshot()
4180
+ if not check(verify, 0, "a second time"):
4181
+ return 1
4182
+ if snapshot() != files_before:
4183
+ report(f"{label} --check wrote to the chat store.")
4184
+ return 1
4185
+ after = chat_json(chat(verify, "unread", "--json")).get("unread", [])
4186
+ if [r.get("id") for r in after] != [r.get("id") for r in before]:
4187
+ report(f"{label} --check changed what verify has unread.")
4188
+ return 1
4189
+ chat(verify, "read")
4190
+ if not check(verify, 1, "after verify read everything"):
4191
+ return 1
4192
+ chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun")
4193
+ if not check(verify, 0, "with an assigned todo unread"):
4194
+ return 1
4195
+ chat(verify, "read")
4196
+ chat(rtl, "dm", "verify", "Private note")
4197
+ if not check(verify, 0, "with a direct message unread"):
4198
+ return 1
4199
+ if not check(plain, 1, "outside any repository"):
4200
+ return 1
4201
+ if not check(unbound, 1, "in a worktree with no role"):
4202
+ return 1
4203
+
4204
+ if "chat-notice-check" not in {name for name, _ in registry.SCENARIOS}:
4205
+ report(f"{label} scenario is not registered.")
4206
+ return 1
4207
+ report("chat-notice-check scenario passed.")
4208
+ return 0
4209
+
4210
+
4211
+ def validate_chat_dm_long_role_names_scenario() -> int:
4212
+ """Issue #403 (kaiwu-ip, 2026-10-20): two long role names could not share a direct group.
4213
+
4214
+ `dm-<a>--<b>` of two 32-character-at-most role names can be up to 69
4215
+ characters, and the group-name check stopped at 32, so `keel chat dm`
4216
+ between `kaiwu-design-iecc` and `kaiwu-pm-iecc` failed. A direct group's
4217
+ name is valid when it is two different valid role names in sorted order,
4218
+ wherever a group is named, listed or authorized; any other name still
4219
+ follows the role-name pattern.
4220
+ """
4221
+ label = "chat-dm-long-role-names:"
4222
+ group = "dm-kaiwu-design-iecc--kaiwu-pm-iecc"
4223
+ with tempfile.TemporaryDirectory(prefix="keel-chat-403-") as raw:
4224
+ base = Path(raw)
4225
+ design = mailbox_repository(base / "design")
4226
+ pm = chat_worktree(design, base / "pm")
4227
+ env = chat_environment()
4228
+ for cwd, role in ((design, "kaiwu-design-iecc"), (pm, "kaiwu-pm-iecc")):
4229
+ bound = run_keel(cwd, "chat", "role", "--set", role, env=env)
4230
+ if bound.returncode != 0:
4231
+ report(f"{label} could not bind {role}: {bound.stderr!r}")
4232
+ return 1
4233
+
4234
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
4235
+ return run_keel(cwd, "chat", *args, env=env)
4236
+
4237
+ sent = chat(design, "dm", "kaiwu-pm-iecc", "lease freed")
4238
+ if sent.returncode != 0:
4239
+ report(f"{label} a direct message between long role names failed: {sent.stderr.strip()!r}")
4240
+ return 1
4241
+ unread = chat(pm, "unread").stdout
4242
+ if "lease freed" not in unread:
4243
+ report(f"{label} kaiwu-pm-iecc does not have the message unread: {unread!r}")
4244
+ return 1
4245
+ peeked = chat(pm, group, "--peek")
4246
+ if peeked.returncode != 0:
4247
+ report(f"{label} `keel chat {group} --peek` failed: {peeked.stderr!r}")
4248
+ return 1
4249
+ if "lease freed" not in peeked.stdout:
4250
+ report(f"{label} `keel chat {group} --peek` does not print the message: {peeked.stdout!r}")
4251
+ return 1
4252
+ listed = chat(pm, "group", "list", "--json")
4253
+ groups = {row["name"]: row for row in json.loads(listed.stdout or "{}").get("groups", [])} if listed.returncode == 0 else {}
4254
+ if not groups.get(group, {}).get("direct"):
4255
+ report(f"{label} group list does not list {group} as direct: {listed.stdout!r} {listed.stderr!r}")
4256
+ return 1
4257
+ for cwd in (design, pm):
4258
+ write_text(cwd / "keel" / "config.yaml", f"authorize:\n - chat-reply:{group}\n")
4259
+ doctor = run_keel(design, "--doctor", env=env).stdout or ""
4260
+ if not re.search(r"chat-reply: authorized.*" + re.escape(group), doctor):
4261
+ report(f"{label} doctor does not read chat-reply:{group}: {[l for l in doctor.splitlines() if 'chat-reply' in l or 'authoriz' in l]!r}")
4262
+ return 1
4263
+ for bad in ("dm-kaiwu-pm-iecc--kaiwu-design-iecc", "Not_A_Group", "x" * 33):
4264
+ refused = chat(design, bad, "--peek")
4265
+ if refused.returncode == 0:
4266
+ report(f"{label} the group name {bad!r} was accepted: {refused.stdout!r}")
4267
+ return 1
4268
+ if "is not a valid name" not in refused.stderr:
4269
+ report(f"{label} the group name {bad!r} was refused, but not as an invalid name: {refused.stderr!r}")
4270
+ return 1
4271
+ if "chat-dm-long-role-names" not in {name for name, _ in registry.SCENARIOS}:
4272
+ report(f"{label} scenario is not registered.")
4273
+ return 1
4274
+ report("chat-dm-long-role-names scenario passed.")
4275
+ return 0
4276
+
4277
+
4278
+ def validate_lock_notice_best_effort_scenario() -> int:
4279
+ """Issue #403 (kaiwu-ip, 2026-10-20): a lease could not be freed while its notice failed.
4280
+
4281
+ Release and the expiry sweep posted to the waiters before removing the
4282
+ lease, so a notice that could not be posted failed the command and kept
4283
+ the lease until a different role's command freed it. A lease is freed
4284
+ first; a notice that cannot be posted is a warning naming the role.
4285
+ """
4286
+ label = "lock-notice-best-effort:"
4287
+ with tempfile.TemporaryDirectory(prefix="keel-lock-403-") as raw:
4288
+ base = Path(raw)
4289
+ a, b, env = chat_scratch_group(base)
4290
+ c = chat_worktree(a, base / "design")
4291
+ d = chat_worktree(a, base / "pm")
4292
+ for tree, role in ((a, "integ"), (b, "sweep"), (c, "kaiwu-design-iecc"), (d, "kaiwu-pm-iecc")):
4293
+ bound = run_keel(tree, "chat", "role", "--set", role, env=env)
4294
+ if bound.returncode != 0:
4295
+ report(f"{label} could not bind {role}: {bound.stderr!r}")
4296
+ return 1
4297
+ lease_file = mailbox_common_dir(a) / "keel-chat" / "locks" / "main-checkout.json"
4298
+
4299
+ def lock(tree: Path, *args: str) -> subprocess.CompletedProcess[str]:
4300
+ return run_keel(tree, "lock", *args, env=env)
4301
+
4302
+ def hold_with_waiter() -> None:
4303
+ for tree, note in ((a, "integration run"), (b, "formal sweep")):
4304
+ lock(tree, "acquire", "main-checkout", "--for", "2h", "--note", note)
4305
+ if "sweep" not in lease_file.read_text():
4306
+ raise RuntimeError(f"sweep was not recorded as a waiter: {lease_file.read_text()!r}")
4307
+
4308
+ # The holder–waiter direct group is archived, so no message can be posted to it.
4309
+ run_keel(a, "chat", "dm", "sweep", "before the archive", env=env)
4310
+ archived = run_keel(a, "chat", "group", "archive", "dm-integ--sweep", env=env)
4311
+ if archived.returncode != 0:
4312
+ report(f"{label} could not archive dm-integ--sweep: {archived.stderr!r}")
4313
+ return 1
4314
+ hold_with_waiter()
4315
+ released = lock(a, "release", "main-checkout")
4316
+ if released.returncode != 0 or lease_file.exists():
4317
+ report(f"{label} a notice that could not be posted kept the lease: exit {released.returncode}, {released.stderr.strip()!r}")
4318
+ return 1
4319
+ if "warning" not in released.stderr or "sweep" not in released.stderr:
4320
+ report(f"{label} release did not warn naming sweep: {released.stderr!r}")
4321
+ return 1
4322
+ listed = lock(b, "list")
4323
+ if listed.returncode != 0:
4324
+ report(f"{label} keel lock list after the release failed: {listed.stderr!r}")
4325
+ return 1
4326
+ if "main-checkout" in listed.stdout:
4327
+ report(f"{label} keel lock list still shows the released lease: {listed.stdout!r}")
4328
+ return 1
4329
+
4330
+ hold_with_waiter()
4331
+ expired = json.loads(lease_file.read_text())
4332
+ expired["expires"] = "2000-01-01T00:00:00+00:00"
4333
+ lease_file.write_text(json.dumps(expired))
4334
+ swept = lock(a, "list")
4335
+ if swept.returncode != 0 or lease_file.exists():
4336
+ report(f"{label} an expired lease whose notice could not be posted was kept: exit {swept.returncode}, {swept.stderr.strip()!r}")
4337
+ return 1
4338
+ if "warning" not in swept.stderr or "sweep" not in swept.stderr:
4339
+ report(f"{label} the expiry sweep did not warn naming sweep: {swept.stderr!r}")
4340
+ return 1
4341
+
4342
+ lock(c, "acquire", "cpu-heavy", "--for", "10m", "--note", "heavy run")
4343
+ lock(d, "acquire", "cpu-heavy", "--for", "10m", "--note", "queued")
4344
+ released = lock(c, "release", "cpu-heavy")
4345
+ if released.returncode != 0:
4346
+ report(f"{label} release between long role names failed: {released.stderr.strip()!r}")
4347
+ return 1
4348
+ if "warning" in released.stderr:
4349
+ report(f"{label} release between long role names warned: {released.stderr.strip()!r}")
4350
+ return 1
4351
+ listed = lock(d, "list")
4352
+ if listed.returncode != 0:
4353
+ report(f"{label} keel lock list after the long-name release failed: {listed.stderr!r}")
4354
+ return 1
4355
+ if "cpu-heavy" in listed.stdout:
4356
+ report(f"{label} keel lock list still shows cpu-heavy after its release: {listed.stdout!r}")
4357
+ return 1
4358
+ if len(chat_records_with(a, "dm-kaiwu-design-iecc--kaiwu-pm-iecc", "lock cpu-heavy released by kaiwu-design-iecc")) != 1:
4359
+ report(f"{label} the waiter kaiwu-pm-iecc was not told of the release.")
4360
+ return 1
4361
+ if "lock-notice-best-effort" not in {name for name, _ in registry.SCENARIOS}:
4362
+ report(f"{label} scenario is not registered.")
4363
+ return 1
4364
+ report("lock-notice-best-effort scenario passed.")
4365
+ return 0
4366
+
4367
+
4368
+ def validate_chat_reply_authorization_scenario() -> int:
4369
+ """Issue #195: answering in a declared group needs no per-session grant.
4370
+
4371
+ `chat-reply:<group>` is a scoped standing authorization: doctor reports it,
4372
+ a bare `chat-reply` is refused with its form and voids the declaration,
4373
+ and the notice gains one sentence naming the group — beside, never in
4374
+ place of, the data-not-instruction sentence. Without a declaration the
4375
+ notice is unchanged.
4376
+ """
4377
+ label = "chat-reply-authorization:"
4378
+ with tempfile.TemporaryDirectory(prefix="keel-chat-reply-") as raw:
4379
+ base = Path(raw)
4380
+ rtl, verify, env = chat_scratch_group(base)
4381
+
4382
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
4383
+ return run_keel(cwd, "chat", *args, env=env)
4384
+
4385
+ chat(rtl, "post", "soc", "@verify please rerun")
4386
+ plain = chat(verify, "notice").stdout
4387
+ if "not an instruction from the user" not in plain:
4388
+ report(f"{label} the undeclared notice lost the data-not-instruction sentence: {plain!r}")
4389
+ return 1
4390
+ if "chat-reply" in plain:
4391
+ report(f"{label} the notice mentions chat-reply with nothing declared: {plain!r}")
4392
+ return 1
4393
+
4394
+ for cwd in (rtl, verify):
4395
+ write_text(cwd / "keel" / "config.yaml", "authorize:\n - chat-reply\n")
4396
+ bare = run_keel(rtl, "--doctor", env=env).stdout or ""
4397
+ if "chat-reply:<group>" not in bare:
4398
+ report(f"{label} doctor does not name the chat-reply:<group> form for a bare entry: {[l for l in bare.splitlines() if 'authoriz' in l or 'chat-reply' in l]!r}")
4399
+ return 1
4400
+ if "authorize: failed" not in bare or "authorizes nothing" not in bare:
4401
+ report(f"{label} a bare chat-reply did not void the declaration.")
4402
+ return 1
4403
+
4404
+ for cwd in (rtl, verify):
4405
+ write_text(cwd / "keel" / "config.yaml", "authorize:\n - chat-reply:soc\n")
4406
+ doctor = run_keel(rtl, "--doctor", env=env).stdout or ""
4407
+ if not re.search(r"chat-reply: authorized.*soc", doctor):
4408
+ report(f"{label} doctor does not report chat-reply:soc as authorized: {[l for l in doctor.splitlines() if 'chat-reply' in l]!r}")
4409
+ return 1
4410
+ if "commit: not authorized" not in doctor:
4411
+ report(f"{label} declaring chat-reply:soc authorized something else.")
4412
+ return 1
4413
+ declared = chat(verify, "notice").stdout
4414
+ if "not an instruction from the user" not in declared:
4415
+ report(f"{label} declaring chat-reply removed the data-not-instruction sentence: {declared!r}")
4416
+ return 1
4417
+ sentence = [line for line in declared.splitlines() if "chat-reply:soc" in line]
4418
+ if len(sentence) != 1:
4419
+ report(f"{label} the notice does not carry exactly one chat-reply sentence naming soc: {declared!r}")
4420
+ return 1
4421
+ if "user" not in sentence[0] or "anything else" not in sentence[0].lower():
4422
+ report(f"{label} the chat-reply sentence does not say that anything else needs the user: {sentence[0]!r}")
4423
+ return 1
4424
+ if declared.replace(sentence[0] + "\n", "") != plain:
4425
+ report(f"{label} declaring chat-reply changed the notice beyond the one sentence.")
4426
+ return 1
4427
+
4428
+ if "chat-reply-authorization" not in {name for name, _ in registry.SCENARIOS}:
4429
+ report(f"{label} scenario is not registered.")
4430
+ return 1
4431
+ report("chat-reply-authorization scenario passed.")
4432
+ return 0
4433
+
4434
+
4435
+ def validate_codex_receiving_scenario() -> int:
4436
+ result = subprocess.run(
4437
+ [sys.executable, str(ROOT / "scripts/validate_codex_receiving.py")],
4438
+ capture_output=True, text=True,
4439
+ )
4440
+ report((result.stdout + result.stderr).strip())
4441
+ return result.returncode