@christang/keel 5.83.0 → 5.85.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.
@@ -12,7 +12,10 @@ import shutil
12
12
  import subprocess
13
13
  import sys
14
14
  import tempfile
15
+ import threading
16
+ import time
15
17
  import ast
18
+ from datetime import datetime, timedelta, timezone
16
19
  from concurrent.futures import ThreadPoolExecutor, as_completed
17
20
  from pathlib import Path
18
21
 
@@ -38,8 +41,8 @@ REQUIRED_SCRIPTS = [
38
41
  "scripts/validate_plugin.py",
39
42
  ]
40
43
 
41
- PACKAGE_VERSION = "5.83.0"
42
- PROTOCOL_VERSION = "5.83.0"
44
+ PACKAGE_VERSION = "5.85.0"
45
+ PROTOCOL_VERSION = "5.85.0"
43
46
  LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
44
47
  OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
45
48
  # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
@@ -2191,170 +2194,455 @@ def mailbox_common_dir(repo: Path) -> Path:
2191
2194
  return Path(raw)
2192
2195
 
2193
2196
 
2194
- def validate_mailbox_cli_scenario() -> int:
2195
- """Issue #180: worktrees of one repository exchange Markdown mail by role.
2197
+ CHAT_ROLE_VARIABLES = ("KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE")
2196
2198
 
2197
- Everything goes through public `keel mail`: binding roles, sending from
2198
- one worktree, listing and reading in another, isolation from a second
2199
- repository, the reply link, and that unread mail changes no context.
2199
+
2200
+ def chat_environment(**extra: str) -> dict[str, str]:
2201
+ """The test process's environment without any inherited chat role."""
2202
+ env = {key: value for key, value in os.environ.items() if key not in CHAT_ROLE_VARIABLES}
2203
+ env.update(extra)
2204
+ return env
2205
+
2206
+
2207
+ def chat_worktree(repo: Path, path: Path) -> Path:
2208
+ subprocess.run(
2209
+ ["git", "worktree", "add", "-q", "-b", path.name, str(path)],
2210
+ cwd=repo, check=True, capture_output=True,
2211
+ )
2212
+ return path
2213
+
2214
+
2215
+ def chat_log(repo: Path, group: str) -> Path:
2216
+ return mailbox_common_dir(repo) / "keel-chat" / "groups" / group / "log"
2217
+
2218
+
2219
+ def chat_json(result: subprocess.CompletedProcess[str]) -> dict:
2220
+ try:
2221
+ parsed = json.loads(result.stdout)
2222
+ except json.JSONDecodeError:
2223
+ return {}
2224
+ return parsed if isinstance(parsed, dict) else {}
2225
+
2226
+
2227
+ def validate_chat_core_scenario() -> int:
2228
+ """Issue #187: roles share groups through an append-only store.
2229
+
2230
+ Everything goes through public `keel chat` across four worktrees of one
2231
+ repository and a separate repository: role and alias binding and their
2232
+ refusals, group membership and its refusals, immutable record files,
2233
+ mention resolution through an alias, per-member cursors and receipts, a
2234
+ direct group, archive, isolation, and that unread chat changes no context.
2200
2235
  """
2201
- label = "mailbox-cli: keel mail"
2202
- with tempfile.TemporaryDirectory(prefix="keel-mailbox-") as raw:
2236
+ label = "chat-core: keel chat"
2237
+ with tempfile.TemporaryDirectory(prefix="keel-chat-core-") as raw:
2203
2238
  base = Path(raw)
2204
2239
  rtl = mailbox_repository(base / "rtl")
2205
- verify = base / "verify"
2206
- subprocess.run(
2207
- ["git", "worktree", "add", "-q", "-b", "verify", str(verify)],
2208
- cwd=rtl, check=True, capture_output=True,
2209
- )
2240
+ verify = chat_worktree(rtl, base / "verify")
2241
+ lint = chat_worktree(rtl, base / "lint")
2242
+ maint = chat_worktree(rtl, base / "maint")
2210
2243
  other = mailbox_repository(base / "other")
2211
- env = {key: value for key, value in os.environ.items() if key != "KEEL_MAIL_ROLE"}
2244
+ env = chat_environment()
2212
2245
 
2213
- def mail(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
2214
- return run_keel(cwd, "mail", *args, env=env)
2246
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
2247
+ return run_keel(cwd, "chat", *args, env=env)
2215
2248
 
2216
- unbound = mail(rtl, "send", "--to", "verify", "--subject", "s", "--body", "b")
2249
+ unbound = chat(rtl, "post", "soc", "hello")
2217
2250
  if unbound.returncode == 0:
2218
- report(f"{label} send from an unbound worktree succeeded.")
2251
+ report(f"{label} a post from an unbound worktree succeeded.")
2219
2252
  return 1
2220
- if "keel mail role --set" not in unbound.stderr:
2221
- report(f"{label} the unbound-sender refusal does not name `keel mail role --set`.")
2222
- report((unbound.stderr or unbound.stdout).strip())
2253
+ if "keel chat role --set" not in unbound.stderr:
2254
+ report(f"{label} the unbound-poster refusal does not name `keel chat role --set`: {(unbound.stderr or unbound.stdout).strip()}")
2223
2255
  return 1
2224
- bad = mail(rtl, "role", "--set", "Bad Name")
2256
+ bad = chat(rtl, "role", "--set", "Bad Name")
2225
2257
  if bad.returncode == 0:
2226
2258
  report(f"{label} role --set accepted the invalid name 'Bad Name'.")
2227
2259
  return 1
2228
2260
  if "[a-z0-9]" not in bad.stderr:
2229
2261
  report(f"{label} the invalid-role refusal does not name the pattern: {bad.stderr.strip()}")
2230
2262
  return 1
2231
- if (mailbox_common_dir(rtl) / "keel-mailbox").exists():
2232
- report(f"{label} a refused role wrote to the mailbox.")
2263
+ if (mailbox_common_dir(rtl) / "keel-chat").exists():
2264
+ report(f"{label} a refused role wrote to the chat store.")
2233
2265
  return 1
2234
2266
 
2235
- for cwd, role in ((rtl, "rtl"), (verify, "verify"), (other, "verify")):
2236
- bound = mail(cwd, "role", "--set", role)
2267
+ for cwd, role in ((rtl, "rtl"), (verify, "verify"), (lint, "lint"), (maint, "claude-maint"), (other, "verify")):
2268
+ bound = chat(cwd, "role", "--set", role)
2237
2269
  if bound.returncode != 0:
2238
2270
  report(f"{label} role --set {role} failed: {bound.stderr.strip()}")
2239
2271
  return 1
2240
- shown = mail(verify, "role", "--json")
2241
- if shown.returncode != 0:
2242
- report(f"{label} role --json failed: {shown.stderr.strip()}")
2272
+ shown = chat(verify, "role", "--json")
2273
+ if chat_json(shown).get("role") != "verify":
2274
+ report(f"{label} role --json did not report the bound role: {shown.stdout.strip()} {shown.stderr.strip()}")
2275
+ return 1
2276
+ aliased = chat(maint, "role", "--alias", "cm")
2277
+ if aliased.returncode != 0:
2278
+ report(f"{label} role --alias cm failed: {aliased.stderr.strip()}")
2279
+ return 1
2280
+ taken = chat(lint, "role", "--alias", "CM")
2281
+ if taken.returncode == 0:
2282
+ report(f"{label} a second role took the alias 'cm'.")
2243
2283
  return 1
2244
- if json.loads(shown.stdout).get("role") != "verify":
2245
- report(f"{label} role did not report the bound role: {shown.stdout.strip()}")
2284
+ if "claude-maint" not in taken.stderr:
2285
+ report(f"{label} the taken-alias refusal does not name its holder: {taken.stderr.strip()}")
2246
2286
  return 1
2247
2287
 
2248
2288
  context_before = run_keel(verify, "context", "--json", env=env)
2249
2289
 
2250
- sent = mail(
2251
- rtl, "send", "--to", "verify", "--subject", "Stimulus misreads spec",
2252
- "--body", "Fix the testcase and rerun.", "--ref", "abc1234", "--json",
2253
- )
2254
- if sent.returncode != 0:
2255
- report(f"{label} send failed: {sent.stderr.strip()}")
2290
+ created = chat(rtl, "group", "create", "soc", "--member", "verify", "--member", "lint", "--member", "claude-maint")
2291
+ if created.returncode != 0:
2292
+ report(f"{label} group create failed: {created.stderr.strip()}")
2293
+ return 1
2294
+ first = chat(rtl, "post", "soc", "Stimulus misreads the spec.", "--json")
2295
+ first_id = chat_json(first).get("id", "")
2296
+ if not first_id:
2297
+ report(f"{label} post did not report an id: {first.stdout.strip()} {first.stderr.strip()}")
2298
+ return 1
2299
+ peek = chat(verify, "soc", "--peek", "--json")
2300
+ texts = [(r.get("from"), r.get("text")) for r in chat_json(peek).get("records", [])]
2301
+ if ("rtl", "Stimulus misreads the spec.") not in texts:
2302
+ report(f"{label} the verify worktree did not see rtl's message: {peek.stdout.strip()} {peek.stderr.strip()}")
2303
+ return 1
2304
+ record_file = chat_log(rtl, "soc") / f"{first_id}.md"
2305
+ if not record_file.is_file():
2306
+ report(f"{label} no record file {record_file} for the posted message.")
2307
+ return 1
2308
+ original = record_file.read_bytes()
2309
+ 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):
2310
+ report(f"{label} the record's created stamp carries no UTC offset:\n{original.decode()}")
2311
+ return 1
2312
+ if not original.startswith(b"---\n"):
2313
+ report(f"{label} the record file has no frontmatter.")
2256
2314
  return 1
2257
- message_id = json.loads(sent.stdout).get("id", "")
2258
2315
 
2259
- listed = mail(verify, "list", "--json")
2260
- unread = json.loads(listed.stdout).get("unread", []) if listed.returncode == 0 else []
2261
- if [(m.get("from"), m.get("subject")) for m in unread] != [("rtl", "Stimulus misreads spec")]:
2262
- report(f"{label} list in the verify worktree did not show the message: {listed.stdout.strip()}")
2316
+ mention = chat(verify, "post", "soc", "@CM please check the waveform", "--json")
2317
+ mention_id = chat_json(mention).get("id", "")
2318
+ if not mention_id:
2319
+ report(f"{label} the aliased mention was not posted: {mention.stderr.strip()}")
2263
2320
  return 1
2264
- box = mailbox_common_dir(rtl) / "keel-mailbox" / "verify"
2265
- files = list((box / "new").glob("*.md"))
2266
- if len(files) != 1:
2267
- report(f"{label} expected one message file under {box / 'new'}, found {len(files)}.")
2321
+ mentions = chat_json(chat(rtl, "show", mention_id, "--json")).get("record", {}).get("mentions")
2322
+ if mentions != ["claude-maint"]:
2323
+ report(f"{label} @CM did not resolve to claude-maint: {mentions!r}")
2268
2324
  return 1
2269
- if not (box / ".signal").is_file():
2270
- report(f"{label} the signal file {box / '.signal'} is missing.")
2325
+ if record_file.read_bytes() != original:
2326
+ report(f"{label} a later post changed an earlier record file.")
2271
2327
  return 1
2272
- text = files[0].read_text(encoding="utf-8")
2273
- for needle in (
2274
- f"id: {message_id}", "from: rtl", "to: verify", "created: ",
2275
- "subject: Stimulus misreads spec", "refs:", "abc1234",
2276
- "Fix the testcase and rerun.",
2277
- ):
2278
- if needle not in text:
2279
- report(f"{label} message file lacks {needle!r}:\n{text}")
2280
- return 1
2281
- if not text.startswith("---\n"):
2282
- report(f"{label} message file has no frontmatter.")
2328
+
2329
+ count = len(list(chat_log(rtl, "soc").glob("*.md")))
2330
+ stranger = chat(rtl, "post", "soc", "@stranger hi")
2331
+ if stranger.returncode == 0:
2332
+ report(f"{label} a mention of a non-member was posted.")
2333
+ return 1
2334
+ if "stranger" not in stranger.stderr:
2335
+ report(f"{label} the non-member refusal does not name 'stranger': {stranger.stderr.strip()}")
2336
+ return 1
2337
+ if len(list(chat_log(rtl, "soc").glob("*.md"))) != count:
2338
+ report(f"{label} the refused mention wrote a record.")
2283
2339
  return 1
2284
2340
 
2285
- elsewhere = mail(other, "list", "--json")
2286
- if elsewhere.returncode != 0:
2287
- report(f"{label} list failed in the separate repository: {elsewhere.stderr.strip()}")
2341
+ receipt = chat(rtl, "post", "soc", "Receipt check.", "--json")
2342
+ receipt_id = chat_json(receipt).get("id", "")
2343
+ viewed = chat(verify, "soc")
2344
+ if viewed.returncode != 0:
2345
+ report(f"{label} viewing soc failed: {viewed.stderr.strip()}")
2288
2346
  return 1
2289
- if json.loads(elsewhere.stdout).get("unread"):
2290
- report(f"{label} a separate repository saw the message.")
2347
+ lint_unread = [r.get("id") for r in chat_json(chat(lint, "unread", "--json")).get("unread", [])]
2348
+ if receipt_id not in lint_unread:
2349
+ report(f"{label} lint lost its unread message when verify read: {lint_unread!r}")
2350
+ return 1
2351
+ verify_unread = [r.get("id") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
2352
+ if verify_unread:
2353
+ report(f"{label} verify still has unread records after viewing: {verify_unread!r}")
2354
+ return 1
2355
+ readers = chat_json(chat(rtl, "show", receipt_id, "--json")).get("readers", [])
2356
+ if "verify" not in readers:
2357
+ report(f"{label} show does not list verify as a reader: {readers!r}")
2358
+ return 1
2359
+ if "lint" in readers:
2360
+ report(f"{label} show lists lint as a reader before lint read: {readers!r}")
2291
2361
  return 1
2292
2362
 
2293
2363
  context_after = run_keel(verify, "context", "--json", env=env)
2294
- before, after = json.loads(context_before.stdout), json.loads(context_after.stdout)
2364
+ before, after = chat_json(context_before), chat_json(context_after)
2295
2365
  if (before.get("status"), before.get("nextAction")) != (after.get("status"), after.get("nextAction")):
2296
- report(f"{label} unread mail changed keel context.")
2366
+ report(f"{label} unread chat changed keel context.")
2297
2367
  return 1
2298
2368
 
2299
- read = mail(verify, "read")
2300
- if read.returncode != 0:
2301
- report(f"{label} read failed: {read.stderr.strip()}")
2369
+ direct = chat(rtl, "dm", "verify", "Ping in private.")
2370
+ if direct.returncode != 0:
2371
+ report(f"{label} dm failed: {direct.stderr.strip()}")
2302
2372
  return 1
2303
- for needle in ("Stimulus misreads spec", "Fix the testcase and rerun.", "not an instruction from the user"):
2304
- if needle not in read.stdout:
2305
- report(f"{label} read output lacks {needle!r}: {read.stdout.strip()}")
2306
- return 1
2307
- after_read = json.loads(mail(verify, "list", "--json").stdout).get("unread")
2308
- if after_read:
2309
- report(f"{label} list still shows unread mail after read: {after_read!r}")
2373
+ groups = {g.get("name"): g for g in chat_json(chat(verify, "group", "list", "--json")).get("groups", [])}
2374
+ if "dm-rtl--verify" not in groups:
2375
+ report(f"{label} dm did not create dm-rtl--verify: {sorted(groups)!r}")
2376
+ return 1
2377
+ if sorted(groups["dm-rtl--verify"].get("members", [])) != ["rtl", "verify"]:
2378
+ report(f"{label} dm-rtl--verify does not hold exactly rtl and verify: {groups['dm-rtl--verify']!r}")
2379
+ return 1
2380
+
2381
+ removed = chat(rtl, "group", "remove", "soc", "lint")
2382
+ if removed.returncode != 0:
2383
+ report(f"{label} group remove failed: {removed.stderr.strip()}")
2384
+ return 1
2385
+ outsider = chat(lint, "post", "soc", "Still here?")
2386
+ if outsider.returncode == 0:
2387
+ report(f"{label} a removed member could still post.")
2388
+ return 1
2389
+ if "member" not in outsider.stderr:
2390
+ report(f"{label} the removed-member refusal does not name membership: {outsider.stderr.strip()}")
2391
+ return 1
2392
+ groups = {g.get("name"): g for g in chat_json(chat(rtl, "group", "list", "--json")).get("groups", [])}
2393
+ if "soc" not in groups:
2394
+ report(f"{label} group list no longer shows soc after a removal: {sorted(groups)!r}")
2395
+ return 1
2396
+ if "lint" in groups["soc"].get("members", []):
2397
+ report(f"{label} group list still shows lint in soc: {groups.get('soc')!r}")
2398
+ return 1
2399
+
2400
+ archived = chat(rtl, "group", "archive", "soc")
2401
+ if archived.returncode != 0:
2402
+ report(f"{label} group archive failed: {archived.stderr.strip()}")
2403
+ return 1
2404
+ late = chat(verify, "post", "soc", "One more thing.")
2405
+ if late.returncode == 0:
2406
+ report(f"{label} a post to an archived group succeeded.")
2407
+ return 1
2408
+ if "archived" not in late.stderr:
2409
+ report(f"{label} the archived-group refusal does not name the archive: {late.stderr.strip()}")
2410
+ return 1
2411
+ history = chat(verify, "soc", "--peek")
2412
+ if "Stimulus misreads the spec." not in history.stdout:
2413
+ report(f"{label} an archived group's history is not readable: {history.stdout.strip()} {history.stderr.strip()}")
2414
+ return 1
2415
+
2416
+ elsewhere = chat_json(chat(other, "group", "list", "--json", "--all")).get("groups", [])
2417
+ if any(g.get("name") == "soc" for g in elsewhere):
2418
+ report(f"{label} a separate repository lists soc.")
2419
+ return 1
2420
+
2421
+ if "chat-core" not in {name for name, _ in SCENARIOS}:
2422
+ report(f"{label} scenario is not registered.")
2423
+ return 1
2424
+ report("chat-core scenario passed.")
2425
+ return 0
2426
+
2427
+
2428
+ def chat_scratch_group(base: Path) -> tuple[Path, Path, dict[str, str]]:
2429
+ """A repository with `rtl` and a `verify` worktree sharing group `soc`."""
2430
+ rtl = mailbox_repository(base / "rtl")
2431
+ verify = chat_worktree(rtl, base / "verify")
2432
+ env = chat_environment()
2433
+ for cwd, role in ((rtl, "rtl"), (verify, "verify")):
2434
+ run_keel(cwd, "chat", "role", "--set", role, env=env)
2435
+ run_keel(rtl, "chat", "group", "create", "soc", "--member", "verify", env=env)
2436
+ return rtl, verify, env
2437
+
2438
+
2439
+ def validate_chat_records_scenario() -> int:
2440
+ """Issue #187: todos, edits, retractions, search, and local-time display.
2441
+
2442
+ A todo links an issue and closes by `done` or a ✅ reply; an edit keeps
2443
+ the original file; search reaches archived groups; and a stored offset is
2444
+ shown in the viewer's local time, never as the raw stamp.
2445
+ """
2446
+ label = "chat-records:"
2447
+ with tempfile.TemporaryDirectory(prefix="keel-chat-records-") as raw:
2448
+ base = Path(raw)
2449
+ rtl, verify, env = chat_scratch_group(base)
2450
+
2451
+ def chat(cwd: Path, *args: str, extra: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]:
2452
+ return run_keel(cwd, "chat", *args, env={**env, **(extra or {})})
2453
+
2454
+ todo = chat(rtl, "todo", "soc", "--assignee", "verify", "--issue", "42", "Rerun the regression", "--json")
2455
+ todo_id = chat_json(todo).get("id", "")
2456
+ if not todo_id:
2457
+ report(f"{label} keel chat todo did not report an id: {todo.stdout.strip()} {todo.stderr.strip()}")
2458
+ return 1
2459
+ mine = chat_json(chat(verify, "todos", "--mine", "--json")).get("todos", [])
2460
+ listed = [t for t in mine if t.get("id") == todo_id]
2461
+ if not listed:
2462
+ report(f"{label} todos --mine for verify does not list the todo: {mine!r}")
2463
+ return 1
2464
+ if listed[0].get("issue") != "#42":
2465
+ report(f"{label} the todo does not carry issue #42: {listed[0]!r}")
2466
+ return 1
2467
+ closed = chat(verify, "post", "soc", "✅ merged", "--reply-to", todo_id)
2468
+ if closed.returncode != 0:
2469
+ report(f"{label} the ✅ reply failed: {closed.stderr.strip()}")
2470
+ return 1
2471
+ open_ids = [t.get("id") for t in chat_json(chat(rtl, "todos", "--json")).get("todos", [])]
2472
+ if todo_id in open_ids:
2473
+ report(f"{label} a todo answered with ✅ is still listed: {open_ids!r}")
2474
+ return 1
2475
+ second_id = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "Update the spec", "--json")).get("id", "")
2476
+ done = chat(verify, "done", second_id)
2477
+ if done.returncode != 0:
2478
+ report(f"{label} keel chat done failed: {done.stderr.strip()}")
2479
+ return 1
2480
+ open_ids = [t.get("id") for t in chat_json(chat(rtl, "todos", "--json")).get("todos", [])]
2481
+ if second_id in open_ids:
2482
+ report(f"{label} a todo closed with keel chat done is still listed: {open_ids!r}")
2310
2483
  return 1
2311
- if list((box / "new").glob("*.md")):
2312
- report(f"{label} read left the message in new/.")
2484
+
2485
+ message_id = chat_json(chat(rtl, "post", "soc", "Clock is 100MHz", "--json")).get("id", "")
2486
+ message_file = chat_log(rtl, "soc") / f"{message_id}.md"
2487
+ original = message_file.read_bytes()
2488
+ foreign = chat(verify, "edit", message_id, "Clock is 50MHz")
2489
+ if foreign.returncode == 0:
2490
+ report(f"{label} a role edited another role's message.")
2491
+ return 1
2492
+ edited = chat(rtl, "edit", message_id, "Clock is 200MHz")
2493
+ if edited.returncode != 0:
2494
+ report(f"{label} keel chat edit failed: {edited.stderr.strip()}")
2495
+ return 1
2496
+ shown = {r.get("id"): r for r in chat_json(chat(verify, "soc", "--peek", "--json")).get("records", [])}
2497
+ if shown.get(message_id, {}).get("text") != "Clock is 200MHz":
2498
+ report(f"{label} the view does not show the edited text: {shown.get(message_id)!r}")
2499
+ return 1
2500
+ if not shown[message_id].get("edited"):
2501
+ report(f"{label} the view does not mark the edited message: {shown[message_id]!r}")
2313
2502
  return 1
2314
- if len(list((box / "done").glob("*.md"))) != 1:
2315
- report(f"{label} read did not put the message in done/.")
2503
+ if message_file.read_bytes() != original:
2504
+ report(f"{label} the edit changed the original record file.")
2505
+ return 1
2506
+ retract_id = chat_json(chat(rtl, "post", "soc", "Wrong channel", "--json")).get("id", "")
2507
+ retracted = chat(rtl, "retract", retract_id)
2508
+ if retracted.returncode != 0:
2509
+ report(f"{label} keel chat retract failed: {retracted.stderr.strip()}")
2510
+ return 1
2511
+ shown = {r.get("id"): r for r in chat_json(chat(verify, "soc", "--peek", "--json")).get("records", [])}
2512
+ if not shown.get(retract_id, {}).get("retracted"):
2513
+ report(f"{label} the view does not mark the retracted message: {shown.get(retract_id)!r}")
2316
2514
  return 1
2317
2515
 
2318
- reply = mail(verify, "send", "--to", "rtl", "--subject", "Re: stimulus", "--reply-to", message_id, "--body", "Done.")
2319
- replies = list((mailbox_common_dir(rtl) / "keel-mailbox" / "rtl" / "new").glob("*.md"))
2320
- if reply.returncode != 0:
2321
- report(f"{label} the reply failed: {reply.stderr.strip()}")
2516
+ chat(rtl, "group", "create", "old", "--member", "verify")
2517
+ chat(rtl, "post", "old", "Legacy PLL notes live here")
2518
+ chat(rtl, "group", "archive", "old")
2519
+ found = chat_json(chat(verify, "search", "PLL", "--json")).get("results", [])
2520
+ if [r.get("group") for r in found] != ["old"]:
2521
+ report(f"{label} search did not find the record in the archived group: {found!r}")
2322
2522
  return 1
2323
- if len(replies) != 1:
2324
- report(f"{label} expected one reply in rtl/new, found {len(replies)}.")
2523
+
2524
+ stamp_id = "20261001T060000000Z-rtl-0a0b0c"
2525
+ write_text(
2526
+ chat_log(rtl, "soc") / f"{stamp_id}.md",
2527
+ f"---\nid: {stamp_id}\ngroup: soc\nkind: message\nfrom: rtl\n"
2528
+ "created: 2026-10-01T06:00:00+00:00\n---\n\nMorning sync\n",
2529
+ )
2530
+ local = chat(verify, "soc", "--peek", extra={"TZ": "Asia/Shanghai"})
2531
+ if "2026-10-01 14:00" not in local.stdout:
2532
+ 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()}")
2325
2533
  return 1
2326
- if f"reply_to: {message_id}" not in replies[0].read_text(encoding="utf-8"):
2327
- report(f"{label} the reply did not carry reply_to {message_id}.")
2534
+ if "06:00:00+00:00" in local.stdout:
2535
+ report(f"{label} the view prints the raw stored stamp.")
2328
2536
  return 1
2329
2537
 
2330
- if "mailbox-cli" not in {name for name, _ in SCENARIOS}:
2331
- report("mailbox-cli: scenario is not registered.")
2538
+ if "chat-records" not in {name for name, _ in SCENARIOS}:
2539
+ report(f"{label} scenario is not registered.")
2332
2540
  return 1
2333
- report("mailbox-cli scenario passed.")
2541
+ report("chat-records scenario passed.")
2334
2542
  return 0
2335
2543
 
2336
2544
 
2337
- def validate_mailbox_claude_hooks_scenario() -> int:
2338
- """Issue #180: Claude Code learns of mail at start, per prompt, and idle.
2545
+ def validate_chat_mail_migration_scenario() -> int:
2546
+ """Issue #187: 5.83 mail migrates into direct groups; `keel mail` still works.
2547
+
2548
+ A scratch repository is seeded with the 5.83 mailbox layout by hand, as an
2549
+ upgraded repository would hold it. The first `keel mail` command migrates
2550
+ it — unread stays unread, read stays read, the binding carries over, and
2551
+ the old directory is renamed rather than deleted — and the 5.83 commands
2552
+ then work on the direct groups.
2553
+ """
2554
+ label = "chat-mail-migration:"
2555
+ with tempfile.TemporaryDirectory(prefix="keel-chat-migration-") as raw:
2556
+ base = Path(raw)
2557
+ rtl = mailbox_repository(base / "rtl")
2558
+ verify = chat_worktree(rtl, base / "verify")
2559
+ env = chat_environment()
2560
+ common = mailbox_common_dir(rtl)
2561
+ box = common / "keel-mailbox"
2562
+ old_unread = "20261001T010000Z-rtl-aaaaaa"
2563
+ old_read = "20261001T000000Z-rtl-bbbbbb"
2564
+ write_text(
2565
+ box / "verify" / "new" / f"{old_unread}.md",
2566
+ f"---\nid: {old_unread}\nfrom: rtl\nto: verify\ncreated: 2026-10-01T01:00:00.000Z\n"
2567
+ "subject: Rerun the suite\n---\n\nThe clock fix landed.\n",
2568
+ )
2569
+ write_text(
2570
+ box / "verify" / "done" / f"{old_read}.md",
2571
+ f"---\nid: {old_read}\nfrom: rtl\nto: verify\ncreated: 2026-10-01T00:00:00.000Z\n"
2572
+ "subject: Hello\n---\n\nAlready read.\n",
2573
+ )
2574
+ write_text(box / "roles.json", json.dumps({str(rtl.resolve()): "rtl", str(verify.resolve()): "verify"}) + "\n")
2575
+
2576
+ def mail(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
2577
+ return run_keel(cwd, "mail", *args, env=env)
2578
+
2579
+ listed = mail(verify, "list", "--json")
2580
+ unread = chat_json(listed).get("unread", [])
2581
+ if [(m.get("from"), m.get("subject")) for m in unread] != [("rtl", "Rerun the suite")]:
2582
+ report(f"{label} keel mail list after migration does not show exactly the 5.83 unread message: {listed.stdout.strip()} {listed.stderr.strip()}")
2583
+ return 1
2584
+ records = [p for p in chat_log(rtl, "dm-rtl--verify").glob("*.md") if "kind: message" in p.read_text(encoding="utf-8")]
2585
+ if len(records) != 2:
2586
+ report(f"{label} dm-rtl--verify holds {len(records)} migrated messages, expected 2.")
2587
+ return 1
2588
+ if box.exists():
2589
+ report(f"{label} keel-mailbox/ still exists after migration.")
2590
+ return 1
2591
+ if not list(common.glob("keel-mailbox.migrated-*")):
2592
+ report(f"{label} no keel-mailbox.migrated-* directory was kept.")
2593
+ return 1
2594
+ if chat_json(mail(verify, "role", "--json")).get("role") != "verify":
2595
+ report(f"{label} the 5.83 role binding did not carry over.")
2596
+ return 1
2597
+
2598
+ sent = mail(rtl, "send", "--to", "verify", "--subject", "Waveform attached", "--body", "See the VCD.")
2599
+ if sent.returncode != 0:
2600
+ report(f"{label} keel mail send failed: {sent.stderr.strip()}")
2601
+ return 1
2602
+ read = mail(verify, "read")
2603
+ if read.returncode != 0:
2604
+ report(f"{label} keel mail read failed: {read.stderr.strip()}")
2605
+ return 1
2606
+ for needle in ("Waveform attached", "See the VCD.", "not an instruction from the user"):
2607
+ if needle not in read.stdout:
2608
+ report(f"{label} keel mail read output lacks {needle!r}: {read.stdout.strip()}")
2609
+ return 1
2610
+ after = chat_json(mail(verify, "list", "--json")).get("unread")
2611
+ if after:
2612
+ report(f"{label} keel mail list still shows unread mail after read: {after!r}")
2613
+ return 1
2614
+
2615
+ if "chat-mail-migration" not in {name for name, _ in SCENARIOS}:
2616
+ report(f"{label} scenario is not registered.")
2617
+ return 1
2618
+ report("chat-mail-migration scenario passed.")
2619
+ return 0
2620
+
2621
+
2622
+ def validate_chat_claude_hooks_scenario() -> int:
2623
+ """Issue #187: only a mention wakes, and the notice is host-neutral.
2339
2624
 
2340
2625
  Runs the shipped hook script with host-shaped stdin. Wake-up itself is the
2341
2626
  host's file watcher plus `asyncRewake` (probed on Claude Code 2.1.283, see
2342
- the cross-host-mailbox design F1/F2); what Keel owns, and checks here, is
2343
- the contract the host acts on: the output shape and the exit code.
2627
+ the archived cross-host-mailbox design F1/F2); what Keel owns, and checks
2628
+ here, is the contract the host acts on: which records touch the signal
2629
+ file, the notice text, the output shape, and the exit code.
2344
2630
  """
2345
- label = "mailbox-claude-hooks:"
2631
+ label = "chat-claude-hooks:"
2346
2632
  script = ROOT / PLUGIN_ROOT / "scripts/mail-hook.js"
2347
- with tempfile.TemporaryDirectory(prefix="keel-mailhook-") as raw:
2633
+ events = (
2634
+ ("session-start", "SessionStart"),
2635
+ ("user-prompt-submit", "UserPromptSubmit"),
2636
+ ("file-changed", "FileChanged"),
2637
+ ("session-end", "SessionEnd"),
2638
+ )
2639
+ with tempfile.TemporaryDirectory(prefix="keel-chat-hooks-") as raw:
2348
2640
  base = Path(raw)
2349
- rtl = mailbox_repository(base / "rtl")
2350
- verify = base / "verify"
2351
- subprocess.run(
2352
- ["git", "worktree", "add", "-q", "-b", "verify", str(verify)],
2353
- cwd=rtl, check=True, capture_output=True,
2354
- )
2355
- unbound = mailbox_repository(base / "unbound")
2356
- env = {key: value for key, value in os.environ.items() if key != "KEEL_MAIL_ROLE"}
2641
+ rtl, verify, env = chat_scratch_group(base)
2357
2642
  env["KEEL_CLI"] = f'node "{ROOT / "bin" / "keel.js"}"'
2643
+ unbound = mailbox_repository(base / "unbound")
2644
+ plain = base / "plain"
2645
+ plain.mkdir()
2358
2646
 
2359
2647
  def hook(cwd: Path, event: str, host_event: str) -> subprocess.CompletedProcess[str]:
2360
2648
  return subprocess.run(
@@ -2363,100 +2651,1232 @@ def validate_mailbox_claude_hooks_scenario() -> int:
2363
2651
  input=json.dumps({"hook_event_name": host_event, "cwd": str(cwd)}),
2364
2652
  )
2365
2653
 
2366
- events = (
2367
- ("session-start", "SessionStart"),
2368
- ("user-prompt-submit", "UserPromptSubmit"),
2369
- ("file-changed", "FileChanged"),
2370
- )
2654
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
2655
+ return run_keel(cwd, "chat", *args, env=env)
2656
+
2371
2657
  if not script.is_file():
2372
2658
  report(f"{label} {script.relative_to(ROOT)} does not exist.")
2373
2659
  return 1
2374
- for event, host_event in events:
2375
- quiet = hook(unbound, event, host_event)
2376
- if quiet.returncode != 0:
2377
- report(f"{label} {event} exited {quiet.returncode} in an unbound worktree.")
2378
- return 1
2379
- if quiet.stdout.strip() or quiet.stderr.strip():
2380
- report(f"{label} {event} wrote output in an unbound worktree: {(quiet.stdout + quiet.stderr).strip()!r}")
2381
- return 1
2660
+ for cwd in (unbound, plain):
2661
+ for event, host_event in events:
2662
+ quiet = hook(cwd, event, host_event)
2663
+ if quiet.returncode != 0:
2664
+ report(f"{label} {event} exited {quiet.returncode} in {cwd.name}, which has no role.")
2665
+ return 1
2666
+ if quiet.stdout.strip() or quiet.stderr.strip():
2667
+ report(f"{label} {event} wrote output in {cwd.name}, which has no role: {(quiet.stdout + quiet.stderr).strip()!r}")
2668
+ return 1
2382
2669
 
2383
- for cwd, role in ((rtl, "rtl"), (verify, "verify")):
2384
- run_keel(cwd, "mail", "role", "--set", role, env=env)
2385
- sent = run_keel(
2386
- rtl, "mail", "send", "--to", "verify", "--subject", "Rerun the regression",
2387
- "--body", "Spec section 4 was misread.", "--json", env=env,
2388
- )
2389
- if sent.returncode != 0:
2390
- report(f"{label} could not send the fixture message: {sent.stderr.strip()}")
2391
- return 1
2392
- message_id = json.loads(sent.stdout)["id"]
2393
- signal = mailbox_common_dir(rtl) / "keel-mailbox" / "verify" / ".signal"
2394
- inbox = mailbox_common_dir(rtl) / "keel-mailbox" / "verify" / "new"
2670
+ signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "verify"
2395
2671
 
2396
- def names_the_message(text: str) -> str | None:
2397
- for needle in (message_id, "`rtl`", "Rerun the regression", "keel mail read", "not an instruction from the user"):
2398
- if needle not in text:
2399
- return needle
2400
- return None
2672
+ def signal_size() -> int:
2673
+ return signal.stat().st_size if signal.exists() else 0
2401
2674
 
2402
- start = hook(verify, "session-start", "SessionStart")
2403
- if start.returncode != 0:
2404
- report(f"{label} session-start exited {start.returncode}: {start.stderr.strip()}")
2405
- return 1
2406
- output = json.loads(start.stdout).get("hookSpecificOutput", {})
2407
- if output.get("hookEventName") != "SessionStart":
2408
- report(f"{label} session-start output names event {output.get('hookEventName')!r}.")
2675
+ chat(rtl, "post", "soc", "@all standup in five")
2676
+ if signal_size():
2677
+ report(f"{label} an @all post touched verify's signal file.")
2409
2678
  return 1
2410
- missing = names_the_message(output.get("additionalContext", ""))
2411
- if missing:
2412
- report(f"{label} session-start additionalContext lacks {missing!r}.")
2413
- return 1
2414
- if output.get("watchPaths") != [str(signal)]:
2415
- report(f"{label} session-start watchPaths is {output.get('watchPaths')!r}, not [{str(signal)!r}].")
2679
+ broadcast = hook(verify, "file-changed", "FileChanged")
2680
+ if broadcast.returncode != 0:
2681
+ report(f"{label} file-changed exited {broadcast.returncode} after an @all post; only a mention wakes.")
2416
2682
  return 1
2417
-
2418
2683
  prompt = hook(verify, "user-prompt-submit", "UserPromptSubmit")
2419
- if prompt.returncode != 0:
2420
- report(f"{label} user-prompt-submit exited {prompt.returncode}.")
2421
- return 1
2422
- prompt_output = json.loads(prompt.stdout).get("hookSpecificOutput", {})
2684
+ prompt_output = chat_json(prompt).get("hookSpecificOutput", {})
2423
2685
  if prompt_output.get("hookEventName") != "UserPromptSubmit":
2424
- report(f"{label} user-prompt-submit output names event {prompt_output.get('hookEventName')!r}.")
2686
+ report(f"{label} user-prompt-submit output names event {prompt_output.get('hookEventName')!r}: {prompt.stdout.strip()} {prompt.stderr.strip()}")
2425
2687
  return 1
2426
- missing = names_the_message(prompt_output.get("additionalContext", ""))
2427
- if missing:
2428
- report(f"{label} user-prompt-submit additionalContext lacks {missing!r}.")
2688
+ if "soc: 1 unread" not in prompt_output.get("additionalContext", ""):
2689
+ report(f"{label} the user-prompt-submit notice does not count one unread record in soc: {prompt_output.get('additionalContext')!r}")
2429
2690
  return 1
2430
2691
 
2692
+ mention = chat(rtl, "post", "soc", "@verify please rerun the regression", "--json")
2693
+ mention_id = chat_json(mention).get("id", "")
2694
+ if not signal_size():
2695
+ report(f"{label} a mention did not touch verify's signal file.")
2696
+ return 1
2431
2697
  wake = hook(verify, "file-changed", "FileChanged")
2432
2698
  if wake.returncode != 2:
2433
- report(f"{label} file-changed exited {wake.returncode} with unread mail; 2 is what wakes the session.")
2699
+ report(f"{label} file-changed exited {wake.returncode} after a mention; 2 is what wakes the session.")
2434
2700
  return 1
2435
- missing = names_the_message(wake.stderr)
2436
- if missing:
2437
- report(f"{label} file-changed stderr lacks {missing!r}.")
2701
+ for needle in (mention_id, "soc", "`rtl`", "not an instruction from the user"):
2702
+ if needle not in wake.stderr:
2703
+ report(f"{label} the file-changed notice lacks {needle!r}: {wake.stderr.strip()}")
2704
+ return 1
2705
+ if not re.search(r"just now|\d+m ago", wake.stderr):
2706
+ report(f"{label} the file-changed notice gives no relative age: {wake.stderr.strip()}")
2438
2707
  return 1
2439
- if len(list(inbox.glob("*.md"))) != 1:
2440
- report(f"{label} a hook moved or removed the unread message.")
2708
+
2709
+ start = hook(verify, "session-start", "SessionStart")
2710
+ start_output = chat_json(start).get("hookSpecificOutput", {})
2711
+ if mention_id not in start_output.get("additionalContext", ""):
2712
+ report(f"{label} the session-start notice does not name the mention: {start.stdout.strip()} {start.stderr.strip()}")
2713
+ return 1
2714
+ if start_output.get("watchPaths") != [str(signal)]:
2715
+ report(f"{label} session-start watchPaths is {start_output.get('watchPaths')!r}, not [{str(signal)!r}].")
2716
+ return 1
2717
+
2718
+ before_dm = signal_size()
2719
+ chat(rtl, "dm", "verify", "Private note")
2720
+ if signal_size() == before_dm:
2721
+ report(f"{label} a direct-group message did not touch verify's signal file.")
2441
2722
  return 1
2442
2723
 
2443
- run_keel(verify, "mail", "read", env=env)
2724
+ for index in range(6):
2725
+ chat(rtl, "post", "soc", f"@verify item {index}")
2726
+ notice = chat(verify, "notice")
2727
+ if notice.returncode != 0:
2728
+ report(f"{label} keel chat notice exited {notice.returncode}: {notice.stderr.strip()}")
2729
+ return 1
2730
+ listed = len(re.findall(r"^- \S+ in ", notice.stdout, re.M))
2731
+ if listed != 5:
2732
+ report(f"{label} keel chat notice lists {listed} records, not five:\n{notice.stdout}")
2733
+ return 1
2734
+ if "3 more" not in notice.stdout:
2735
+ report(f"{label} keel chat notice does not state the three it left out:\n{notice.stdout}")
2736
+ return 1
2737
+ unread = chat_json(chat(verify, "unread", "--json")).get("unread", [])
2738
+ if len(unread) != 9:
2739
+ report(f"{label} a hook or notice advanced verify's cursor: {len(unread)} unread, expected 9.")
2740
+ return 1
2741
+
2742
+ ended = hook(verify, "session-end", "SessionEnd")
2743
+ if ended.returncode != 0:
2744
+ report(f"{label} session-end exited {ended.returncode}: {ended.stderr.strip()}")
2745
+ return 1
2746
+ queued = chat(rtl, "post", "soc", "@verify ping")
2747
+ if "verify" not in queued.stdout or "offline" not in queued.stdout:
2748
+ report(f"{label} a mention of an offline member does not report it offline: {queued.stdout.strip()} {queued.stderr.strip()}")
2749
+ return 1
2750
+
2751
+ chat(verify, "read")
2444
2752
  after = hook(verify, "file-changed", "FileChanged")
2445
2753
  if after.returncode != 0:
2446
- report(f"{label} file-changed exited {after.returncode} after the mail was read.")
2754
+ report(f"{label} file-changed exited {after.returncode} with nothing unread.")
2447
2755
  return 1
2448
2756
  if after.stderr.strip():
2449
- report(f"{label} file-changed wrote {after.stderr.strip()!r} with no unread mail.")
2757
+ report(f"{label} file-changed wrote {after.stderr.strip()!r} with nothing unread.")
2450
2758
  return 1
2451
2759
  quiet_prompt = hook(verify, "user-prompt-submit", "UserPromptSubmit")
2452
2760
  if quiet_prompt.stdout.strip():
2453
- report(f"{label} user-prompt-submit still announced mail after it was read.")
2761
+ report(f"{label} user-prompt-submit still announced records after they were read.")
2454
2762
  return 1
2455
2763
 
2456
- if "mailbox-claude-hooks" not in {name for name, _ in SCENARIOS}:
2764
+ if "chat-claude-hooks" not in {name for name, _ in SCENARIOS}:
2457
2765
  report(f"{label} scenario is not registered.")
2458
2766
  return 1
2459
- report("mailbox-claude-hooks scenario passed.")
2767
+ report("chat-claude-hooks scenario passed.")
2768
+ return 0
2769
+
2770
+
2771
+ def validate_chat_loop_guards_scenario() -> int:
2772
+ """Issue #187: a rate limit and a ping-pong breaker stop runaway agents.
2773
+
2774
+ Two agents answering each other eight times in a row are stopped, the
2775
+ owner is called with one system record, and the owner's post clears the
2776
+ block. A role over its configured post rate is refused by name; the owner
2777
+ never is.
2778
+ """
2779
+ label = "chat-loop-guards:"
2780
+ with tempfile.TemporaryDirectory(prefix="keel-chat-guards-") as raw:
2781
+ base = Path(raw)
2782
+ rtl, verify, env = chat_scratch_group(base)
2783
+ lint = chat_worktree(rtl, base / "lint")
2784
+ run_keel(lint, "chat", "role", "--set", "lint", env=env)
2785
+ run_keel(rtl, "chat", "group", "add", "soc", "lint", env=env)
2786
+
2787
+ def chat(cwd: Path, *args: str, role: str | None = None) -> subprocess.CompletedProcess[str]:
2788
+ extra = {"KEEL_CHAT_ROLE": role} if role else {}
2789
+ return run_keel(cwd, "chat", *args, env={**env, **extra})
2790
+
2791
+ for index in range(8):
2792
+ cwd = rtl if index % 2 == 0 else verify
2793
+ turn = chat(cwd, "post", "soc", f"round {index}")
2794
+ if turn.returncode != 0:
2795
+ report(f"{label} alternating post {index} was refused before the threshold: {turn.stderr.strip()}")
2796
+ return 1
2797
+ ninth = chat(rtl, "post", "soc", "round 8")
2798
+ if ninth.returncode == 0:
2799
+ report(f"{label} a ninth alternating post was accepted.")
2800
+ return 1
2801
+ if "loop guard" not in ninth.stderr:
2802
+ report(f"{label} the ping-pong refusal does not name the loop guard: {ninth.stderr.strip()}")
2803
+ return 1
2804
+ chat(verify, "post", "soc", "round 8 again")
2805
+ records = [p.read_text(encoding="utf-8") for p in chat_log(rtl, "soc").glob("*.md")]
2806
+ system = [r for r in records if "kind: system" in r]
2807
+ if len(system) != 1:
2808
+ report(f"{label} expected one system record after two refused posts, found {len(system)}.")
2809
+ return 1
2810
+ if " - owner" not in system[0]:
2811
+ report(f"{label} the system record does not mention owner:\n{system[0]}")
2812
+ return 1
2813
+ owner = chat(rtl, "post", "soc", "Stop and summarize, please.", role="owner")
2814
+ if owner.returncode != 0:
2815
+ report(f"{label} the owner's post was refused: {owner.stderr.strip()}")
2816
+ return 1
2817
+ resumed = chat(rtl, "post", "soc", "Summary: the clock fix is in.")
2818
+ if resumed.returncode != 0:
2819
+ report(f"{label} rtl could not post after the owner did: {resumed.stderr.strip()}")
2820
+ return 1
2821
+
2822
+ write_text(lint / "keel" / "chat.json", json.dumps({"limits": {"rate": 3, "window_minutes": 10}}) + "\n")
2823
+ for index in range(3):
2824
+ within = chat(lint, "post", "soc", f"lint note {index}")
2825
+ if within.returncode != 0:
2826
+ report(f"{label} lint post {index} was refused within the limit: {within.stderr.strip()}")
2827
+ return 1
2828
+ over = chat(lint, "post", "soc", "lint note 3")
2829
+ if over.returncode == 0:
2830
+ report(f"{label} a fourth post within ten minutes was accepted with limits.rate 3.")
2831
+ return 1
2832
+ if "limits.rate" not in over.stderr:
2833
+ report(f"{label} the rate refusal does not name limits.rate: {over.stderr.strip()}")
2834
+ return 1
2835
+ for index in range(4):
2836
+ boss = chat(lint, "post", "soc", f"owner note {index}", role="owner")
2837
+ if boss.returncode != 0:
2838
+ report(f"{label} the owner was rate-limited: {boss.stderr.strip()}")
2839
+ return 1
2840
+
2841
+ if "chat-loop-guards" not in {name for name, _ in SCENARIOS}:
2842
+ report(f"{label} scenario is not registered.")
2843
+ return 1
2844
+ report("chat-loop-guards scenario passed.")
2845
+ return 0
2846
+
2847
+
2848
+ def validate_chat_human_view_scenario() -> int:
2849
+ """Issue #187: a person reads and posts from the terminal and a transcript.
2850
+
2851
+ The owner posts by role; the group view shows local times, mention, reply,
2852
+ and todo markers, and each member's presence; `--since` limits the window;
2853
+ `--follow` prints a message posted from another worktree while it runs;
2854
+ and the per-group Markdown transcript is regenerated after each write.
2855
+ """
2856
+ label = "chat-human-view:"
2857
+ with tempfile.TemporaryDirectory(prefix="keel-chat-view-") as raw:
2858
+ base = Path(raw)
2859
+ rtl, verify, env = chat_scratch_group(base)
2860
+
2861
+ def chat(cwd: Path, *args: str, role: str | None = None) -> subprocess.CompletedProcess[str]:
2862
+ extra = {"KEEL_CHAT_ROLE": role} if role else {}
2863
+ return run_keel(cwd, "chat", *args, env={**env, **extra})
2864
+
2865
+ hello = chat(rtl, "soc", "hello from the phone", role="owner")
2866
+ if hello.returncode != 0:
2867
+ report(f"{label} the owner could not post with keel chat soc <text>: {hello.stderr.strip()}")
2868
+ return 1
2869
+ root_id = chat_json(chat(rtl, "post", "soc", "@verify check the clock", "--json")).get("id", "")
2870
+ chat(verify, "post", "soc", "on it", "--reply-to", root_id)
2871
+ chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun the suite")
2872
+ old_id = "20200101T000000000Z-rtl-0c0c0c"
2873
+ old_created = (datetime.now(timezone.utc) - timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
2874
+ write_text(
2875
+ chat_log(rtl, "soc") / f"{old_id}.md",
2876
+ f"---\nid: {old_id}\ngroup: soc\nkind: message\nfrom: rtl\ncreated: {old_created}\n---\n\nback-dated note\n",
2877
+ )
2878
+
2879
+ view = chat(rtl, "soc", "--peek")
2880
+ text = view.stdout
2881
+ for needle, what in (
2882
+ ("owner: hello from the phone", "the owner's message"),
2883
+ ("@verify", "the mention marker"),
2884
+ (f"↳ {root_id}", "the reply marker"),
2885
+ ("[todo → verify", "the todo marker"),
2886
+ ):
2887
+ if needle not in text:
2888
+ report(f"{label} the view lacks {what} ({needle!r}):\n{text}{view.stderr}")
2889
+ return 1
2890
+ if not re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d rtl", text, re.M):
2891
+ report(f"{label} the view shows no local date and HH:MM before a sender:\n{text}")
2892
+ return 1
2893
+ presence = re.search(r"^Members: (.*)$", text, re.M)
2894
+ if not presence:
2895
+ report(f"{label} the view has no Members presence line:\n{text}")
2896
+ return 1
2897
+ for role in ("rtl", "verify"):
2898
+ if not re.search(rf"{role} \((online|idle|offline)", presence.group(1)):
2899
+ report(f"{label} the presence line gives no state for {role}: {presence.group(1)}")
2900
+ return 1
2901
+
2902
+ recent = chat(rtl, "soc", "--peek", "--since", "1m")
2903
+ if "back-dated note" in recent.stdout:
2904
+ report(f"{label} --since 1m still shows a record from two hours ago.")
2905
+ return 1
2906
+ if "on it" not in recent.stdout:
2907
+ report(f"{label} --since 1m dropped a record from just now:\n{recent.stdout}{recent.stderr}")
2908
+ return 1
2909
+
2910
+ follower = subprocess.Popen(
2911
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "soc", "--follow", "--peek"],
2912
+ cwd=verify, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
2913
+ )
2914
+ lines_seen: list[str] = []
2915
+ reader = threading.Thread(
2916
+ target=lambda: lines_seen.extend(iter(follower.stdout.readline, "")), daemon=True,
2917
+ )
2918
+ reader.start()
2919
+ try:
2920
+ time.sleep(1.5)
2921
+ chat(rtl, "post", "soc", "followed message")
2922
+ deadline = time.time() + 5
2923
+ while time.time() < deadline and not any("followed message" in line for line in lines_seen):
2924
+ time.sleep(0.2)
2925
+ finally:
2926
+ follower.terminate()
2927
+ follower.wait(timeout=5)
2928
+ seen = "".join(lines_seen)
2929
+ if "followed message" not in seen:
2930
+ report(f"{label} --follow did not print a message posted from another worktree within five seconds: {seen!r}")
2931
+ return 1
2932
+
2933
+ transcript = mailbox_common_dir(rtl) / "keel-chat" / "transcripts" / "soc.md"
2934
+ if not transcript.is_file():
2935
+ report(f"{label} no transcript at {transcript}.")
2936
+ return 1
2937
+ lines = transcript.read_text(encoding="utf-8").splitlines()
2938
+ headings = [line for line in lines if re.match(r"^## \d{4}-\d\d-\d\d$", line)]
2939
+ if not headings or len(headings) != len(set(headings)):
2940
+ report(f"{label} the transcript's day headings are missing or repeated: {headings!r}")
2941
+ return 1
2942
+ for message in ("hello from the phone", "followed message", "on it"):
2943
+ if not any(re.match(rf"^\d\d:\d\d \S+: .*{re.escape(message)}", line) for line in lines):
2944
+ report(f"{label} the transcript has no `HH:MM sender: text` line for {message!r}.")
2945
+ return 1
2946
+
2947
+ if "chat-human-view" not in {name for name, _ in SCENARIOS}:
2948
+ report(f"{label} scenario is not registered.")
2949
+ return 1
2950
+ report("chat-human-view scenario passed.")
2951
+ return 0
2952
+
2953
+
2954
+ def chat_bridge_node_missing(label: str) -> bool:
2955
+ """Whether this Node lacks the WebSocket the bridge needs (Node 22+).
2956
+
2957
+ On the Node 20 floor the bridge scenarios report themselves skipped; the
2958
+ full-gate workflow runs them again on Node 22 in the same job.
2959
+ """
2960
+ probe = subprocess.run(
2961
+ ["node", "-p", "typeof globalThis.WebSocket"], capture_output=True, text=True,
2962
+ )
2963
+ if probe.stdout.strip() == "function":
2964
+ return False
2965
+ report(f"{label} skipped: keel chat bridge needs Node 22 or newer for its built-in WebSocket; this Node has none.")
2966
+ return True
2967
+
2968
+
2969
+ def fake_slack_class():
2970
+ """The local Slack stand-in, loaded by path from beside this script.
2971
+
2972
+ `scripts/fake_slack.py` uses the standard library only; it is loaded from
2973
+ its file rather than imported by name, so this validator keeps importing
2974
+ nothing but the standard library.
2975
+ """
2976
+ import importlib.util # noqa: PLC0415 - only the Slack scenarios need it
2977
+
2978
+ spec = importlib.util.spec_from_file_location("keel_fake_slack", ROOT / "scripts" / "fake_slack.py")
2979
+ module = importlib.util.module_from_spec(spec)
2980
+ spec.loader.exec_module(module)
2981
+ return module.FakeSlack
2982
+
2983
+
2984
+ def chat_slack_config(repo: Path, channels: dict[str, str], *, enabled: bool = True, **extra: object) -> None:
2985
+ config = {
2986
+ "slack": {
2987
+ "enabled": enabled,
2988
+ "owner": "UOWNER",
2989
+ "members": {"UOWNER": "owner"},
2990
+ "channels": channels,
2991
+ **extra,
2992
+ }
2993
+ }
2994
+ write_text(repo / "keel" / "chat.json", json.dumps(config, indent=2) + "\n")
2995
+
2996
+
2997
+ def chat_bridge_environment(env: dict[str, str], home: Path, slack) -> dict[str, str]:
2998
+ return {
2999
+ **env,
3000
+ "KEEL_HOME": str(home),
3001
+ "KEEL_SLACK_API_BASE": slack.api_base,
3002
+ "KEEL_SLACK_BOT_TOKEN": "xoxb-test-bot",
3003
+ "KEEL_SLACK_APP_TOKEN": "xapp-test-app",
3004
+ "KEEL_CHAT_MACHINE": "mac-test",
3005
+ }
3006
+
3007
+
3008
+ def slack_payload(call: dict) -> dict:
3009
+ metadata = call["params"].get("metadata") or {}
3010
+ if isinstance(metadata, str):
3011
+ metadata = json.loads(metadata)
3012
+ return (metadata or {}).get("event_payload") or {}
3013
+
3014
+
3015
+ def validate_chat_bridge_outbound_scenario() -> int:
3016
+ """Issue #187: the bridge posts an opted-in project's records to Slack.
3017
+
3018
+ Runs `keel chat bridge run --once` against a local fake Slack. Each record
3019
+ is posted once, under its role's name, with the exact record in message
3020
+ metadata; replies thread; a mention of the owner becomes a Slack mention;
3021
+ secrets are redacted on the way out and kept locally; long text is cut
3022
+ with a pointer; a 429 is waited out; done, edit, and retract follow their
3023
+ message; a project that did not opt in sends nothing; and a Node without
3024
+ WebSocket is told it needs Node 22.
3025
+ """
3026
+ label = "chat-bridge-outbound:"
3027
+ if chat_bridge_node_missing("chat-bridge-outbound"):
3028
+ return 3
3029
+ FakeSlack = fake_slack_class()
3030
+ with tempfile.TemporaryDirectory(prefix="keel-chat-out-") as raw, FakeSlack() as slack:
3031
+ base = Path(raw)
3032
+ rtl, verify, env = chat_scratch_group(base)
3033
+ quiet = mailbox_repository(base / "quiet")
3034
+ run_keel(quiet, "chat", "role", "--set", "rtl", env=env)
3035
+ run_keel(quiet, "chat", "group", "create", "ops", env=env)
3036
+ chat_slack_config(rtl, {"soc": "CSOC"})
3037
+ chat_slack_config(quiet, {"ops": "COPS"}, enabled=False)
3038
+ benv = chat_bridge_environment(env, base / "home", slack)
3039
+
3040
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3041
+ return run_keel(cwd, "chat", *args, env=benv)
3042
+
3043
+ for project in (rtl, quiet):
3044
+ added = chat(project, "bridge", "add")
3045
+ if added.returncode != 0:
3046
+ report(f"{label} bridge add failed in {project.name}: {added.stderr.strip()}")
3047
+ return 1
3048
+ chat(quiet, "post", "ops", "not for slack")
3049
+ root_id = chat_json(chat(rtl, "post", "soc", "Clock fix is in", "--json")).get("id", "")
3050
+ reply_id = chat_json(chat(verify, "post", "soc", "@owner done?", "--reply-to", root_id, "--json")).get("id", "")
3051
+ long_id = chat_json(chat(rtl, "post", "soc", "x" * 5000, "--json")).get("id", "")
3052
+ secret_id = chat_json(chat(rtl, "post", "soc", "token is xoxb-123-456-abcdef ok", "--json")).get("id", "")
3053
+ todo_id = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun", "--json")).get("id", "")
3054
+ chat(verify, "done", todo_id)
3055
+ chat(rtl, "edit", root_id, "Clock fix is in (v2)")
3056
+ gone_id = chat_json(chat(rtl, "post", "soc", "wrong group", "--json")).get("id", "")
3057
+ chat(rtl, "retract", gone_id)
3058
+ slack.rate_limit("chat.postMessage", 1)
3059
+
3060
+ started = time.time()
3061
+ run = chat(rtl, "bridge", "run", "--once")
3062
+ elapsed = time.time() - started
3063
+ if run.returncode != 0:
3064
+ report(f"{label} bridge run --once failed: {run.stderr.strip()} {run.stdout.strip()}")
3065
+ return 1
3066
+
3067
+ posts = slack.calls_to("chat.postMessage")
3068
+ by_id: dict[str, list[dict]] = {}
3069
+ for call in posts:
3070
+ by_id.setdefault(slack_payload(call).get("id", ""), []).append(call)
3071
+ for record_id in (root_id, reply_id, long_id, secret_id, todo_id, gone_id):
3072
+ if len(by_id.get(record_id, [])) != 1:
3073
+ report(f"{label} record {record_id} was posted {len(by_id.get(record_id, []))} times, not once.")
3074
+ return 1
3075
+ root = by_id[root_id][0]
3076
+ if root["params"].get("username") != "rtl":
3077
+ report(f"{label} the post is not under the role's name: username {root['params'].get('username')!r}.")
3078
+ return 1
3079
+ if root["params"].get("channel") != "CSOC":
3080
+ report(f"{label} the post went to {root['params'].get('channel')!r}, not the mapped CSOC.")
3081
+ return 1
3082
+ metadata = root["params"].get("metadata")
3083
+ metadata = json.loads(metadata) if isinstance(metadata, str) else metadata
3084
+ if (metadata or {}).get("event_type") != "keel_chat_record":
3085
+ report(f"{label} the post's metadata is not a keel_chat_record: {metadata!r}")
3086
+ return 1
3087
+ payload = slack_payload(root)
3088
+ if payload.get("from") != "rtl":
3089
+ report(f"{label} the metadata payload does not carry the record's sender: {payload!r}")
3090
+ return 1
3091
+ if payload.get("kind") != "message":
3092
+ report(f"{label} the metadata payload does not carry the record's kind: {payload!r}")
3093
+ return 1
3094
+ root_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == root_id)
3095
+ reply = by_id[reply_id][0]["params"]
3096
+ if reply.get("thread_ts") != root_ts:
3097
+ report(f"{label} the reply's thread_ts is {reply.get('thread_ts')!r}, not the root's {root_ts!r}.")
3098
+ return 1
3099
+ if "<@UOWNER>" not in reply.get("text", ""):
3100
+ report(f"{label} a mention of owner did not become a Slack mention: {reply.get('text')!r}")
3101
+ return 1
3102
+ long_text = by_id[long_id][0]["params"].get("text", "")
3103
+ if len(long_text) > 3200:
3104
+ report(f"{label} a 5,000-character body was sent at {len(long_text)} characters, not cut.")
3105
+ return 1
3106
+ if "keel chat show" not in long_text:
3107
+ report(f"{label} the cut body carries no keel chat show pointer.")
3108
+ return 1
3109
+ secret_text = by_id[secret_id][0]["params"].get("text", "")
3110
+ if "xoxb-123" in secret_text:
3111
+ report(f"{label} a token was sent to Slack: {secret_text!r}")
3112
+ return 1
3113
+ if "[redacted]" not in secret_text:
3114
+ report(f"{label} the redacted text carries no [redacted] marker: {secret_text!r}")
3115
+ return 1
3116
+ if "xoxb-123-456-abcdef" not in (chat_log(rtl, "soc") / f"{secret_id}.md").read_text(encoding="utf-8"):
3117
+ report(f"{label} redaction changed the local record.")
3118
+ return 1
3119
+ if not any(call.get("rate_limited") for call in slack.calls if call["method"] == "chat.postMessage"):
3120
+ report(f"{label} the fake server never answered 429, so the retry was not exercised.")
3121
+ return 1
3122
+ if elapsed < 1.0:
3123
+ report(f"{label} the run finished in {elapsed:.2f}s, before the 1s Retry-After passed.")
3124
+ return 1
3125
+ if any(call["params"].get("channel") == "COPS" for call in slack.calls):
3126
+ report(f"{label} a project without slack.enabled was posted to Slack.")
3127
+ return 1
3128
+ todo_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == todo_id)
3129
+ reactions = slack.calls_to("reactions.add")
3130
+ if not any(c["params"].get("timestamp") == todo_ts and c["params"].get("name") == "white_check_mark" for c in reactions):
3131
+ report(f"{label} the done todo did not get a ✅ reaction: {reactions!r}")
3132
+ return 1
3133
+ updates = slack.calls_to("chat.update")
3134
+ if not any(c["params"].get("ts") == root_ts and "v2" in c["params"].get("text", "") for c in updates):
3135
+ report(f"{label} the edit did not call chat.update on the root: {updates!r}")
3136
+ return 1
3137
+ gone_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == gone_id)
3138
+ if not any(c["params"].get("ts") == gone_ts for c in slack.calls_to("chat.delete")):
3139
+ report(f"{label} the retraction did not call chat.delete.")
3140
+ return 1
3141
+
3142
+ before = len(slack.calls_to("chat.postMessage"))
3143
+ again = chat(rtl, "bridge", "run", "--once")
3144
+ if again.returncode != 0:
3145
+ report(f"{label} a second bridge run failed: {again.stderr.strip()}")
3146
+ return 1
3147
+ if len(slack.calls_to("chat.postMessage")) != before:
3148
+ report(f"{label} a second run posted records again.")
3149
+ return 1
3150
+
3151
+ no_ws = base / "no-websocket.js"
3152
+ write_text(no_ws, "delete globalThis.WebSocket;\n")
3153
+ old_node = run_keel(rtl, "chat", "bridge", "run", "--once", env={**benv, "NODE_OPTIONS": f"--require {no_ws}"})
3154
+ if old_node.returncode == 0:
3155
+ report(f"{label} bridge run started without a WebSocket implementation.")
3156
+ return 1
3157
+ if "Node 22" not in old_node.stderr:
3158
+ report(f"{label} the missing-WebSocket refusal does not name Node 22: {old_node.stderr.strip()}")
3159
+ return 1
3160
+
3161
+ if "chat-bridge-outbound" not in {name for name, _ in SCENARIOS}:
3162
+ report(f"{label} scenario is not registered.")
3163
+ return 1
3164
+ report("chat-bridge-outbound scenario passed.")
3165
+ return 0
3166
+
3167
+
3168
+ def chat_records_with(repo: Path, group: str, needle: str) -> list[str]:
3169
+ """Record files in `group` whose text contains `needle`."""
3170
+ log = chat_log(repo, group)
3171
+ if not log.is_dir():
3172
+ return []
3173
+ return [p.read_text(encoding="utf-8") for p in sorted(log.glob("*.md")) if needle in p.read_text(encoding="utf-8")]
3174
+
3175
+
3176
+ def start_chat_bridge(cwd: Path, env: dict[str, str]) -> subprocess.Popen:
3177
+ return subprocess.Popen(
3178
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "bridge", "run"],
3179
+ cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
3180
+ )
3181
+
3182
+
3183
+ def stop_chat_bridge(process: subprocess.Popen) -> str:
3184
+ process.terminate()
3185
+ try:
3186
+ _, stderr = process.communicate(timeout=10)
3187
+ except subprocess.TimeoutExpired:
3188
+ process.kill()
3189
+ _, stderr = process.communicate()
3190
+ return stderr or ""
3191
+
3192
+
3193
+ def slack_event(channel: str, **fields: object) -> dict:
3194
+ return {"type": "event_callback", "event": {"type": "message", "channel": channel, **fields}}
3195
+
3196
+
3197
+ def validate_chat_bridge_inbound_scenario() -> int:
3198
+ """Issue #187: what arrives from Slack, and only that, reaches the store.
3199
+
3200
+ A running `keel chat bridge run` against the fake server: a registered
3201
+ person's message is imported and wakes the session it mentions; a
3202
+ stranger's is ignored and counted; another machine's post is rebuilt from
3203
+ its metadata exactly once, fetching metadata the event lacked; this
3204
+ bridge's own post is not re-imported; threads, edits, deletions, ✅, and
3205
+ files map onto records; two projects sharing a channel both get a post;
3206
+ and what was missed while stopped is caught up once.
3207
+ """
3208
+ label = "chat-bridge-inbound:"
3209
+ if chat_bridge_node_missing("chat-bridge-inbound"):
3210
+ return 3
3211
+ FakeSlack = fake_slack_class()
3212
+ with tempfile.TemporaryDirectory(prefix="keel-chat-in-") as raw, FakeSlack() as slack:
3213
+ base = Path(raw)
3214
+ rtl, verify, env = chat_scratch_group(base)
3215
+ chat_slack_config(rtl, {"soc": "CSOC"})
3216
+ shared = []
3217
+ for name in ("a", "b"):
3218
+ repo = mailbox_repository(base / name)
3219
+ run_keel(repo, "chat", "role", "--set", "rtl", env=env)
3220
+ run_keel(repo, "chat", "group", "create", "ops", env=env)
3221
+ chat_slack_config(repo, {"ops": "COPS"})
3222
+ shared.append(repo)
3223
+ benv = chat_bridge_environment(env, base / "home", slack)
3224
+
3225
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3226
+ return run_keel(cwd, "chat", *args, env=benv)
3227
+
3228
+ for project in (rtl, *shared):
3229
+ chat(project, "bridge", "add")
3230
+ signal = mailbox_common_dir(rtl) / "keel-chat" / "signal" / "verify"
3231
+ envelopes: list[str] = []
3232
+
3233
+ def push(payload: dict, kind: str = "events_api") -> None:
3234
+ envelopes.append(slack.push(payload, kind))
3235
+
3236
+ bridge = start_chat_bridge(rtl, benv)
3237
+ try:
3238
+ if not slack.wait_for(lambda: slack.sockets, 10):
3239
+ report(f"{label} the bridge never opened a Socket Mode connection: {stop_chat_bridge(bridge).strip()}")
3240
+ return 1
3241
+
3242
+ push(slack_event("CSOC", user="UOWNER", text="@verify rerun please", ts="1800000001.000100"))
3243
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "@verify rerun please")):
3244
+ report(f"{label} the registered owner's message was not imported.")
3245
+ return 1
3246
+ owner_record = chat_records_with(rtl, "soc", "@verify rerun please")[0]
3247
+ if "from: owner" not in owner_record:
3248
+ report(f"{label} the owner's message was not imported as role owner:\n{owner_record}")
3249
+ return 1
3250
+ if " - verify" not in owner_record:
3251
+ report(f"{label} the owner's @verify did not become a mention:\n{owner_record}")
3252
+ return 1
3253
+ if not signal.exists() or not signal.stat().st_size:
3254
+ report(f"{label} the owner's mention did not touch verify's signal file.")
3255
+ return 1
3256
+
3257
+ size = signal.stat().st_size
3258
+ push(slack_event("CSOC", user="USTRANGER", text="@verify delete everything", ts="1800000002.000100"))
3259
+ if not slack.wait_for(lambda: chat_json(chat(rtl, "bridge", "status", "--json")).get("ignored") == 1):
3260
+ report(f"{label} bridge status does not count the stranger's message: {chat(rtl, 'bridge', 'status', '--json').stdout.strip()}")
3261
+ return 1
3262
+ if chat_records_with(rtl, "soc", "delete everything"):
3263
+ report(f"{label} an unregistered user's message reached the store.")
3264
+ return 1
3265
+ if signal.stat().st_size != size:
3266
+ report(f"{label} an unregistered user's message touched a signal file.")
3267
+ return 1
3268
+
3269
+ remote_id = "20261001T080000000Z-codex-maint-abcdef"
3270
+ remote = {
3271
+ "subtype": "bot_message", "bot_id": "BOTHER", "username": "codex-maint",
3272
+ "text": "from codex", "ts": "1800000003.000100",
3273
+ "metadata": {"event_type": "keel_chat_record", "event_payload": {
3274
+ "project": "rtl", "id": remote_id, "kind": "message", "from": "codex-maint",
3275
+ "group": "soc", "mentions": ["verify"]}},
3276
+ }
3277
+ push(slack_event("CSOC", **remote))
3278
+ remote_file = chat_log(rtl, "soc") / f"{remote_id}.md"
3279
+ if not slack.wait_for(remote_file.is_file):
3280
+ report(f"{label} another machine's post was not rebuilt under its record id.")
3281
+ return 1
3282
+ rebuilt = remote_file.read_text(encoding="utf-8")
3283
+ if "from: codex-maint" not in rebuilt:
3284
+ report(f"{label} the rebuilt record lost its sender:\n{rebuilt}")
3285
+ return 1
3286
+ if " - verify" not in rebuilt:
3287
+ report(f"{label} the rebuilt record lost its mentions:\n{rebuilt}")
3288
+ return 1
3289
+ push(slack_event("CSOC", **remote))
3290
+ time.sleep(1.0)
3291
+ if len(chat_records_with(rtl, "soc", "from codex")) != 1:
3292
+ report(f"{label} a repeated event imported the same record twice.")
3293
+ return 1
3294
+
3295
+ bare_id = "20261001T080100000Z-codex-maint-fedcba"
3296
+ stored = slack.add_history("CSOC", {
3297
+ "subtype": "bot_message", "bot_id": "BOTHER", "username": "codex-maint", "text": "metadata later",
3298
+ "metadata": {"event_type": "keel_chat_record", "event_payload": {
3299
+ "project": "rtl", "id": bare_id, "kind": "message", "from": "codex-maint", "group": "soc"}},
3300
+ })
3301
+ push(slack_event("CSOC", subtype="bot_message", bot_id="BOTHER", username="codex-maint", text="metadata later", ts=stored["ts"]))
3302
+ if not slack.wait_for((chat_log(rtl, "soc") / f"{bare_id}.md").is_file):
3303
+ report(f"{label} a bot message without metadata in its event was not resolved through history.")
3304
+ return 1
3305
+ if not any(str(c["params"].get("include_all_metadata")).lower() in ("1", "true") for c in slack.calls_to("conversations.history")):
3306
+ report(f"{label} metadata was not fetched with include_all_metadata.")
3307
+ return 1
3308
+
3309
+ echo_id = chat_json(chat(rtl, "post", "soc", "local echo", "--json")).get("id", "")
3310
+ if not slack.wait_for(lambda: any(slack_payload(c).get("id") == echo_id for c in slack.calls_to("chat.postMessage"))):
3311
+ report(f"{label} the running bridge did not post a new local record.")
3312
+ return 1
3313
+ echo = next(m for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == echo_id)
3314
+ push(slack_event("CSOC", subtype="bot_message", bot_id="BBOT", username="rtl", text="local echo", ts=echo["ts"], metadata=echo["metadata"]))
3315
+ time.sleep(1.0)
3316
+ if len(chat_records_with(rtl, "soc", "local echo")) != 1:
3317
+ report(f"{label} this bridge's own post was imported back into its project.")
3318
+ return 1
3319
+
3320
+ push(slack_event("CSOC", user="UOWNER", text="noted", ts="1800000010.000100", thread_ts=echo["ts"]))
3321
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "noted")):
3322
+ report(f"{label} the owner's thread reply was not imported.")
3323
+ return 1
3324
+ if f"reply_to: {echo_id}" not in chat_records_with(rtl, "soc", "noted")[0]:
3325
+ report(f"{label} the thread reply does not point at its root {echo_id}.")
3326
+ return 1
3327
+
3328
+ push(slack_event("CSOC", subtype="message_changed", message={"user": "UOWNER", "text": "@verify rerun now", "ts": "1800000001.000100"}, previous_message={"user": "UOWNER", "ts": "1800000001.000100"}))
3329
+ if not slack.wait_for(lambda: any("kind: edit" in r for r in chat_records_with(rtl, "soc", "rerun now"))):
3330
+ report(f"{label} a Slack edit did not become an edit record.")
3331
+ return 1
3332
+ push(slack_event("CSOC", subtype="message_deleted", deleted_ts="1800000010.000100", previous_message={"user": "UOWNER", "ts": "1800000010.000100"}))
3333
+ 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"))):
3334
+ report(f"{label} a Slack deletion did not become a retract record.")
3335
+ return 1
3336
+
3337
+ todo_id = chat_json(chat(rtl, "todo", "soc", "--assignee", "verify", "Rerun", "--json")).get("id", "")
3338
+ if not slack.wait_for(lambda: any(slack_payload(c).get("id") == todo_id for c in slack.calls_to("chat.postMessage"))):
3339
+ report(f"{label} the todo was not posted.")
3340
+ return 1
3341
+ todo_ts = next(m["ts"] for m in slack.messages["CSOC"] if (m.get("metadata") or {}).get("event_payload", {}).get("id") == todo_id)
3342
+ push({"type": "event_callback", "event": {"type": "reaction_added", "user": "UOWNER", "reaction": "white_check_mark", "item": {"type": "message", "channel": "CSOC", "ts": todo_ts}}})
3343
+ if not slack.wait_for(lambda: todo_id not in [t.get("id") for t in chat_json(chat(rtl, "todos", "--json")).get("todos", [])]):
3344
+ report(f"{label} a ✅ from a registered user did not close the todo.")
3345
+ return 1
3346
+
3347
+ push(slack_event("CSOC", user="UOWNER", text="waveform", ts="1800000020.000100", files=[{"name": "wave.vcd", "permalink": "https://files.example/wave.vcd"}]))
3348
+ if not slack.wait_for(lambda: chat_records_with(rtl, "soc", "https://files.example/wave.vcd")):
3349
+ report(f"{label} a shared file did not become a link line.")
3350
+ return 1
3351
+
3352
+ a, b = shared
3353
+ ops_id = chat_json(chat(a, "post", "ops", "shared hello", "--json")).get("id", "")
3354
+ if not slack.wait_for(lambda: chat_records_with(b, "ops", "shared hello")):
3355
+ report(f"{label} project b did not receive project a's post in the shared channel.")
3356
+ return 1
3357
+ ops_posts = [c for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == ops_id]
3358
+ if len(ops_posts) != 1:
3359
+ report(f"{label} the shared-channel post was sent {len(ops_posts)} times, not once.")
3360
+ return 1
3361
+ if ops_posts[0]["params"].get("username") != "a/rtl":
3362
+ report(f"{label} the shared-channel post is not under a/rtl: {ops_posts[0]['params'].get('username')!r}")
3363
+ return 1
3364
+ if "from: a/rtl" not in chat_records_with(b, "ops", "shared hello")[0]:
3365
+ report(f"{label} project b's copy is not from a/rtl.")
3366
+ return 1
3367
+
3368
+ missing = [e for e in envelopes if e not in slack.acks]
3369
+ if missing:
3370
+ report(f"{label} envelopes were not acknowledged: {missing!r}")
3371
+ return 1
3372
+ finally:
3373
+ log = stop_chat_bridge(bridge)
3374
+
3375
+ slack.add_history("CSOC", {"user": "UOWNER", "text": "while you were away"})
3376
+ for _ in range(2):
3377
+ bridge = start_chat_bridge(rtl, benv)
3378
+ try:
3379
+ slack.wait_for(lambda: chat_records_with(rtl, "soc", "while you were away"), 10)
3380
+ time.sleep(1.0)
3381
+ finally:
3382
+ log = stop_chat_bridge(bridge)
3383
+ caught = chat_records_with(rtl, "soc", "while you were away")
3384
+ if len(caught) != 1:
3385
+ report(f"{label} a message sent while the bridge was down was imported {len(caught)} times, not once: {log.strip()}")
3386
+ return 1
3387
+
3388
+ if "chat-bridge-inbound" not in {name for name, _ in SCENARIOS}:
3389
+ report(f"{label} scenario is not registered.")
3390
+ return 1
3391
+ report("chat-bridge-inbound scenario passed.")
3392
+ return 0
3393
+
3394
+
3395
+ def validate_chat_bridge_lifecycle_scenario() -> int:
3396
+ """Issue #187: the bridge runs unattended but stays visible and controllable.
3397
+
3398
+ Tokens come from the environment or the Keychain and land in no file;
3399
+ `install` and `uninstall` drive launchctl for a user LaunchAgent; `pause`
3400
+ queues and then delivers; the bridge reconnects after a refresh request
3401
+ or a dropped socket, announces itself online and stopped, exits for a
3402
+ restart when Keel's version changes, reports its state through `status`,
3403
+ and a session in a Slack-enabled project is told when it is not running.
3404
+ The system boundary — `launchctl`, `security`, and the LaunchAgents
3405
+ directory — is replaced by test doubles; nothing touches the real ones.
3406
+ """
3407
+ import plistlib # noqa: PLC0415 - only this scenario reads a plist
3408
+
3409
+ label = "chat-bridge-lifecycle:"
3410
+ if chat_bridge_node_missing("chat-bridge-lifecycle"):
3411
+ return 3
3412
+ FakeSlack = fake_slack_class()
3413
+ with tempfile.TemporaryDirectory(prefix="keel-chat-life-") as raw, FakeSlack() as slack:
3414
+ base = Path(raw)
3415
+ rtl, verify, env = chat_scratch_group(base)
3416
+ chat_slack_config(rtl, {"soc": "CSOC"})
3417
+ home = base / "home"
3418
+ benv = chat_bridge_environment(env, home, slack)
3419
+ run_keel(rtl, "chat", "bridge", "add", env=benv)
3420
+
3421
+ empty_security = base / "security-empty"
3422
+ write_text(empty_security, "#!/bin/sh\nexit 44\n")
3423
+ empty_security.chmod(0o755)
3424
+ keychain = base / "security-keychain"
3425
+ write_text(
3426
+ keychain,
3427
+ "#!/bin/sh\n"
3428
+ 'case "$*" in\n'
3429
+ ' *"-a app"*) echo xapp-from-keychain-0000 ;;\n'
3430
+ ' *"-a bot"*) echo xoxb-from-keychain-0000 ;;\n'
3431
+ " *) exit 44 ;;\n"
3432
+ "esac\n",
3433
+ )
3434
+ keychain.chmod(0o755)
3435
+ no_tokens = {k: v for k, v in benv.items() if k not in ("KEEL_SLACK_BOT_TOKEN", "KEEL_SLACK_APP_TOKEN")}
3436
+
3437
+ missing = run_keel(rtl, "chat", "bridge", "run", env={**no_tokens, "KEEL_CHAT_SECURITY": str(empty_security)})
3438
+ if missing.returncode == 0:
3439
+ report(f"{label} bridge run started with no token anywhere.")
3440
+ return 1
3441
+ for needle in ("KEEL_SLACK_APP_TOKEN", "keel-chat-slack"):
3442
+ if needle not in missing.stderr:
3443
+ report(f"{label} the missing-token refusal does not name {needle}: {missing.stderr.strip()}")
3444
+ return 1
3445
+
3446
+ session = subprocess.run(
3447
+ ["node", str(ROOT / PLUGIN_ROOT / "scripts/mail-hook.js"), "session-start"],
3448
+ cwd=rtl, env={**benv, "KEEL_CLI": f'node "{ROOT / "bin" / "keel.js"}"'},
3449
+ text=True, capture_output=True, check=False,
3450
+ input=json.dumps({"hook_event_name": "SessionStart", "cwd": str(rtl)}),
3451
+ )
3452
+ context = chat_json(session).get("hookSpecificOutput", {}).get("additionalContext", "")
3453
+ if "bridge" not in context or "not running" not in context:
3454
+ report(f"{label} a session in a Slack-enabled project is not told the bridge is not running: {session.stdout.strip()} {session.stderr.strip()}")
3455
+ return 1
3456
+
3457
+ keyed_env = {**no_tokens, "KEEL_CHAT_SECURITY": str(keychain)}
3458
+ bridge = start_chat_bridge(rtl, keyed_env)
3459
+ try:
3460
+ if not slack.wait_for(lambda: slack.sockets, 10):
3461
+ report(f"{label} the bridge did not connect with Keychain tokens: {stop_chat_bridge(bridge).strip()}")
3462
+ return 1
3463
+ if not any("Bearer xapp-from-keychain-0000" == c["params"].get("_auth") for c in slack.calls_to("apps.connections.open")):
3464
+ report(f"{label} the Socket Mode connection did not use the Keychain app token.")
3465
+ return 1
3466
+ if not slack.wait_for(lambda: any("bridge online" in c["params"].get("text", "") for c in slack.calls_to("chat.postMessage"))):
3467
+ report(f"{label} the bridge did not announce itself online.")
3468
+ return 1
3469
+
3470
+ status = chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=keyed_env))
3471
+ for key in ("connected", "projects", "last_event", "ignored", "unposted", "installed", "paused"):
3472
+ if key not in status:
3473
+ report(f"{label} bridge status --json lacks {key!r}: {status!r}")
3474
+ return 1
3475
+ if status.get("connected") is not True:
3476
+ report(f"{label} bridge status does not report the connection: {status!r}")
3477
+ return 1
3478
+
3479
+ opened = slack.connections_opened
3480
+ slack.push_raw({"type": "disconnect", "reason": "refresh_requested"})
3481
+ if not slack.wait_for(lambda: slack.connections_opened > opened and slack.sockets, 10):
3482
+ report(f"{label} the bridge did not reconnect after refresh_requested.")
3483
+ return 1
3484
+ opened = slack.connections_opened
3485
+ slack.drop_connections()
3486
+ if not slack.wait_for(lambda: slack.connections_opened > opened and slack.sockets, 15):
3487
+ report(f"{label} the bridge did not reconnect after the socket dropped.")
3488
+ return 1
3489
+
3490
+ paused = run_keel(rtl, "chat", "bridge", "pause", "3s", env=keyed_env)
3491
+ if paused.returncode != 0:
3492
+ report(f"{label} bridge pause failed: {paused.stderr.strip()}")
3493
+ return 1
3494
+ time.sleep(1.5)
3495
+ held_id = chat_json(run_keel(rtl, "chat", "post", "soc", "held during pause", "--json", env=keyed_env)).get("id", "")
3496
+ time.sleep(1.0)
3497
+ if any(slack_payload(c).get("id") == held_id for c in slack.calls_to("chat.postMessage")):
3498
+ report(f"{label} a record was sent while the bridge was paused.")
3499
+ return 1
3500
+ if not slack.wait_for(lambda: any(slack_payload(c).get("id") == held_id for c in slack.calls_to("chat.postMessage")), 10):
3501
+ report(f"{label} the record held during the pause was not sent after it.")
3502
+ return 1
3503
+ if len([c for c in slack.calls_to("chat.postMessage") if slack_payload(c).get("id") == held_id]) != 1:
3504
+ report(f"{label} the held record was sent more than once.")
3505
+ return 1
3506
+ finally:
3507
+ log = stop_chat_bridge(bridge)
3508
+ if not any("bridge stopped" in c["params"].get("text", "") for c in slack.calls_to("chat.postMessage")):
3509
+ report(f"{label} the bridge did not announce a clean stop: {log.strip()}")
3510
+ return 1
3511
+ tokens = ("xoxb-from-keychain-0000", "xapp-from-keychain-0000")
3512
+ for root in (home, mailbox_common_dir(rtl) / "keel-chat"):
3513
+ for path in root.rglob("*"):
3514
+ if path.is_file() and any(token in path.read_text(encoding="utf-8", errors="replace") for token in tokens):
3515
+ report(f"{label} a Slack token was written to {path}.")
3516
+ return 1
3517
+
3518
+ tree = base / "keel-copy"
3519
+ for part in ("bin", "src", "scripts"):
3520
+ shutil.copytree(ROOT / part, tree / part)
3521
+ shutil.copy(ROOT / "package.json", tree / "package.json")
3522
+ copied = subprocess.Popen(
3523
+ ["node", str(tree / "bin" / "keel.js"), "chat", "bridge", "run"],
3524
+ cwd=rtl, env=benv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
3525
+ )
3526
+ try:
3527
+ slack.wait_for(lambda: slack.sockets, 10)
3528
+ manifest = json.loads((tree / "package.json").read_text(encoding="utf-8"))
3529
+ manifest["version"] = "99.0.0"
3530
+ write_text(tree / "package.json", json.dumps(manifest, indent=2) + "\n")
3531
+ copied.wait(timeout=15)
3532
+ except subprocess.TimeoutExpired:
3533
+ copied.kill()
3534
+ report(f"{label} the bridge kept running after Keel's version changed.")
3535
+ return 1
3536
+ restart_log = copied.stderr.read() if copied.stderr else ""
3537
+ if "99.0.0" not in restart_log:
3538
+ report(f"{label} the version-change exit does not name the new version: {restart_log.strip()}")
3539
+ return 1
3540
+
3541
+ agents = base / "LaunchAgents"
3542
+ calls = base / "launchctl.log"
3543
+ launchctl = base / "launchctl"
3544
+ write_text(launchctl, f'#!/bin/sh\necho "$@" >> "{calls}"\nexit 0\n')
3545
+ launchctl.chmod(0o755)
3546
+ lenv = {**benv, "KEEL_CHAT_LAUNCHCTL": str(launchctl), "KEEL_CHAT_LAUNCH_AGENTS_DIR": str(agents)}
3547
+ installed = run_keel(rtl, "chat", "bridge", "install", env=lenv)
3548
+ if installed.returncode != 0:
3549
+ report(f"{label} bridge install failed: {installed.stderr.strip()}")
3550
+ return 1
3551
+ plists = list(agents.glob("*.plist"))
3552
+ if len(plists) != 1:
3553
+ report(f"{label} install wrote {len(plists)} plists, not one.")
3554
+ return 1
3555
+ plist = plistlib.loads(plists[0].read_bytes())
3556
+ if plist.get("RunAtLoad") is not True:
3557
+ report(f"{label} the LaunchAgent does not start at login: {plist!r}")
3558
+ return 1
3559
+ if plist.get("KeepAlive") is not True:
3560
+ report(f"{label} the LaunchAgent is not kept alive: {plist!r}")
3561
+ return 1
3562
+ if " ".join(plist.get("ProgramArguments", [])[-3:]) != "chat bridge run":
3563
+ report(f"{label} the LaunchAgent does not run `chat bridge run`: {plist.get('ProgramArguments')!r}")
3564
+ return 1
3565
+ if any(token in plists[0].read_text(encoding="utf-8") for token in ("xoxb-", "xapp-")):
3566
+ report(f"{label} the LaunchAgent carries a Slack token.")
3567
+ return 1
3568
+ if "bootstrap" not in calls.read_text(encoding="utf-8"):
3569
+ report(f"{label} install did not ask launchctl to bootstrap the agent: {calls.read_text(encoding='utf-8')!r}")
3570
+ return 1
3571
+ if chat_json(run_keel(rtl, "chat", "bridge", "status", "--json", env=lenv)).get("installed") is not True:
3572
+ report(f"{label} bridge status does not report the installed agent.")
3573
+ return 1
3574
+ removed = run_keel(rtl, "chat", "bridge", "uninstall", env=lenv)
3575
+ if removed.returncode != 0:
3576
+ report(f"{label} bridge uninstall failed: {removed.stderr.strip()}")
3577
+ return 1
3578
+ if "bootout" not in calls.read_text(encoding="utf-8"):
3579
+ report(f"{label} uninstall did not ask launchctl to boot the agent out.")
3580
+ return 1
3581
+ if list(agents.glob("*.plist")):
3582
+ report(f"{label} uninstall left the plist behind.")
3583
+ return 1
3584
+
3585
+ if "chat-bridge-lifecycle" not in {name for name, _ in SCENARIOS}:
3586
+ report(f"{label} scenario is not registered.")
3587
+ return 1
3588
+ report("chat-bridge-lifecycle scenario passed.")
3589
+ return 0
3590
+
3591
+
3592
+ def validate_chat_archive_scenario() -> int:
3593
+ """Issue #187: chat history is archived to an orphan branch, never exposed.
3594
+
3595
+ `keel chat archive sync` commits the shared layer of the store to
3596
+ `refs/heads/keel-chat` with plumbing, leaving the worktree and index as
3597
+ they were; refuses to push a repository reported public unless the
3598
+ project declared a remote or accepted publication; merges another clone's
3599
+ records by union; and `archive pull` restores history in a fresh clone.
3600
+ """
3601
+ label = "chat-archive:"
3602
+ with tempfile.TemporaryDirectory(prefix="keel-chat-archive-") as raw:
3603
+ base = Path(raw)
3604
+ remote = base / "remote.git"
3605
+ subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(remote)], check=True, capture_output=True)
3606
+ rtl, verify, env = chat_scratch_group(base)
3607
+ subprocess.run(["git", "remote", "add", "origin", str(remote)], cwd=rtl, check=True, capture_output=True)
3608
+ subprocess.run(["git", "push", "-q", "origin", "main"], cwd=rtl, check=True, capture_output=True)
3609
+ gh = base / "gh"
3610
+ write_text(gh, "#!/bin/sh\necho PUBLIC\n")
3611
+ gh.chmod(0o755)
3612
+ aenv = {**env, "KEEL_CHAT_GH": str(gh)}
3613
+
3614
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
3615
+ return run_keel(cwd, "chat", *args, env=aenv)
3616
+
3617
+ def remote_has_branch() -> bool:
3618
+ listed = subprocess.run(["git", "ls-remote", str(remote), "refs/heads/keel-chat"], capture_output=True, text=True)
3619
+ return bool(listed.stdout.strip())
3620
+
3621
+ def branch_files(repo: Path) -> list[str]:
3622
+ listed = subprocess.run(["git", "ls-tree", "-r", "--name-only", "refs/heads/keel-chat"], cwd=repo, capture_output=True, text=True)
3623
+ return listed.stdout.split()
3624
+
3625
+ chat(rtl, "post", "soc", "first archived message")
3626
+ chat(verify, "post", "soc", "second archived message")
3627
+ write_text(rtl / "scratch.txt", "untracked work in progress\n")
3628
+ write_text(rtl / "keel" / "chat.json", json.dumps({"slack": {"enabled": True, "channels": {}}}) + "\n")
3629
+ before = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
3630
+ index_before = (mailbox_common_dir(rtl) / "index").read_bytes()
3631
+
3632
+ refused = chat(rtl, "archive", "sync")
3633
+ if refused.returncode != 0:
3634
+ report(f"{label} archive sync failed: {refused.stderr.strip()}")
3635
+ return 1
3636
+ files = branch_files(rtl)
3637
+ logs = [f for f in files if f.startswith("groups/soc/log/") and f.endswith(".md")]
3638
+ if len(logs) < 2:
3639
+ report(f"{label} refs/heads/keel-chat does not hold the group's records: {files!r}")
3640
+ return 1
3641
+ local_only = [f for f in files if f == "roles.json" or f.split("/")[0] in ("signal", "bridge", "transcripts", ".tmp")]
3642
+ if local_only:
3643
+ report(f"{label} the archive carries local-only files: {local_only!r}")
3644
+ return 1
3645
+ after = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
3646
+ if after != before:
3647
+ report(f"{label} archive sync changed the worktree status:\nbefore {before!r}\nafter {after!r}")
3648
+ return 1
3649
+ if (mailbox_common_dir(rtl) / "index").read_bytes() != index_before:
3650
+ report(f"{label} archive sync changed the index.")
3651
+ return 1
3652
+ if remote_has_branch():
3653
+ report(f"{label} a repository reported public was pushed with no declaration.")
3654
+ return 1
3655
+ for needle in ("archive_public", "archive.remote"):
3656
+ if needle not in refused.stdout + refused.stderr:
3657
+ report(f"{label} the refused push does not name {needle}: {(refused.stdout + refused.stderr).strip()}")
3658
+ return 1
3659
+
3660
+ write_text(rtl / "keel" / "chat.json", json.dumps({"slack": {"enabled": True, "channels": {}}, "archive": {"remote": "origin"}}) + "\n")
3661
+ pushed = chat(rtl, "archive", "sync")
3662
+ if pushed.returncode != 0:
3663
+ report(f"{label} archive sync with archive.remote failed: {pushed.stderr.strip()}")
3664
+ return 1
3665
+ if not remote_has_branch():
3666
+ report(f"{label} archive.remote was declared and nothing was pushed: {(pushed.stdout + pushed.stderr).strip()}")
3667
+ return 1
3668
+
3669
+ clone = base / "clone"
3670
+ subprocess.run(["git", "clone", "-q", str(remote), str(clone)], check=True, capture_output=True)
3671
+ run_keel(clone, "chat", "role", "--set", "verify", env=aenv)
3672
+ pulled = chat(clone, "archive", "pull")
3673
+ if pulled.returncode != 0:
3674
+ report(f"{label} archive pull failed in a fresh clone: {pulled.stderr.strip()}")
3675
+ return 1
3676
+ restored = chat(clone, "soc", "--peek")
3677
+ if "first archived message" not in restored.stdout:
3678
+ report(f"{label} a fresh clone does not show the archived history after pull: {restored.stdout.strip()} {restored.stderr.strip()}")
3679
+ return 1
3680
+
3681
+ write_text(clone / "keel" / "chat.json", json.dumps({"archive": {"remote": "origin"}}) + "\n")
3682
+ clone_id = chat_json(chat(clone, "post", "soc", "from the second machine", "--json")).get("id", "")
3683
+ if chat(clone, "archive", "sync").returncode != 0:
3684
+ report(f"{label} archive sync failed in the second clone.")
3685
+ return 1
3686
+ third = chat_json(chat(rtl, "post", "soc", "third from the first machine", "--json")).get("id", "")
3687
+ merged = chat(rtl, "archive", "sync")
3688
+ if merged.returncode != 0:
3689
+ report(f"{label} archive sync failed when merging the second clone's history: {merged.stderr.strip()}")
3690
+ return 1
3691
+ files = branch_files(rtl)
3692
+ for record_id, where in ((clone_id, "the second clone"), (third, "the first clone")):
3693
+ if f"groups/soc/log/{record_id}.md" not in files:
3694
+ report(f"{label} the merged archive lacks the record from {where}.")
3695
+ return 1
3696
+ if "from the second machine" not in chat(rtl, "soc", "--peek").stdout:
3697
+ report(f"{label} the first clone's store did not gain the second clone's record on sync.")
3698
+ return 1
3699
+
3700
+ if "chat-archive" not in {name for name, _ in SCENARIOS}:
3701
+ report(f"{label} scenario is not registered.")
3702
+ return 1
3703
+ report("chat-archive scenario passed.")
3704
+ return 0
3705
+
3706
+
3707
+ def validate_record_derives_skeleton_scenario() -> int:
3708
+ """Issue #179: `--record` writes the record slots a capsule implies.
3709
+
3710
+ Every slot it writes is a placeholder the gates still refuse as unfilled,
3711
+ so this changes who types the bookkeeping and not what completion needs.
3712
+ """
3713
+ label = "record-derives-skeleton:"
3714
+ fixture = task_capsule_compact_fixture()
3715
+ no_evidence = fixture.replace(
3716
+ " - Evidence:\n - Contract: pending\n - M1: pending\n", ""
3717
+ )
3718
+ red_green = no_evidence.replace(
3719
+ " - Strategy: evidence-first\n"
3720
+ " - Reason: this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first\n"
3721
+ " - M1: node test.js\n",
3722
+ " - Strategy: vertical-tdd\n"
3723
+ " - M1: node test.js asserts the feature. Fails with: `boom`\n"
3724
+ " - M2 (regression): node old.js stays green\n"
3725
+ " - M3: node edge.js asserts the edge. Fails with: `edge` Detects: `drop the guard` -> `edge`\n",
3726
+ )
3727
+ if red_green == no_evidence:
3728
+ report(f"{label} the fixture's Verify block moved; update this scenario.")
3729
+ return 1
3730
+ expected_slots = [
3731
+ " - M1: pending",
3732
+ " - M1.red: pending",
3733
+ " - M1.green: pending",
3734
+ " - M2: pending",
3735
+ " - M3: pending",
3736
+ " - M3.red: pending",
3737
+ " - M3.green: pending",
3738
+ " - M3.detects: pending",
3739
+ " - Review:",
3740
+ " - Status: pending",
3741
+ " - Acceptance check: pending",
3742
+ " - Scope check: pending",
3743
+ " - Findings: pending",
3744
+ " - Blocker: none",
3745
+ " - Reauthorizations: none",
3746
+ ]
3747
+ with tempfile.TemporaryDirectory(prefix="keel-skeleton-") as raw:
3748
+ repo = Path(raw)
3749
+ tasks = repo / "openspec/changes/demo/tasks.md"
3750
+
3751
+ def record(*extra: str) -> tuple[int, dict]:
3752
+ result = run_keel(
3753
+ repo, "gate", "task-start", "--change", "demo", "--task", "1.1",
3754
+ *extra, "--json",
3755
+ )
3756
+ return result.returncode, json.loads(result.stdout)
3757
+
3758
+ write_text(tasks, red_green)
3759
+ code, payload = record("--record", "--no-guard")
3760
+ if code != 0:
3761
+ report(f"{label} --record refused a valid task with no Evidence: {payload.get('problems')!r}")
3762
+ return 1
3763
+ if payload.get("record", {}).get("status") != "recorded":
3764
+ report(f"{label} the outcome was {payload.get('record')!r}, not recorded.")
3765
+ return 1
3766
+ fingerprint = payload["contract"]["fingerprint"]["value"]
3767
+ after = tasks.read_text(encoding="utf-8")
3768
+ before_lines, after_lines = red_green.splitlines(), after.splitlines()
3769
+ added = [line for line in after_lines if line not in before_lines]
3770
+ want = [" - Evidence:", f" - Contract: keel-task-capsule/v1 sha256:{fingerprint}", *expected_slots]
3771
+ if added != want:
3772
+ report(f"{label} --record added {added!r}, expected {want!r}.")
3773
+ return 1
3774
+ if [line for line in before_lines if line not in after_lines]:
3775
+ report(f"{label} --record removed or rewrote a line outside the Evidence it added.")
3776
+ return 1
3777
+ code, again = record("--record", "--no-guard")
3778
+ if code != 0 or tasks.read_text(encoding="utf-8") != after:
3779
+ report(f"{label} a second --record was not byte-identical.")
3780
+ return 1
3781
+ if again.get("record", {}).get("status") != "unchanged":
3782
+ report(f"{label} a second --record reported {again.get('record')!r}, not unchanged.")
3783
+ return 1
3784
+ completion = run_keel(repo, "gate", "task-complete", "--change", "demo", "--task", "1.1", "--json")
3785
+ if completion.returncode == 0:
3786
+ report(f"{label} task-complete accepted a task whose slots were only filled with pending.")
3787
+ return 1
3788
+
3789
+ kept = red_green.replace(
3790
+ " - Stop if:\n",
3791
+ " - Evidence:\n - M1: pass. node test.js printed ok.\n - Stop if:\n",
3792
+ )
3793
+ write_text(tasks, kept)
3794
+ code, payload = record("--record", "--no-guard")
3795
+ text = tasks.read_text(encoding="utf-8")
3796
+ if code != 0:
3797
+ report(f"{label} --record refused a task with a partial Evidence block: {payload.get('problems')!r}")
3798
+ return 1
3799
+ if " - M1: pass. node test.js printed ok." not in text:
3800
+ report(f"{label} --record rewrote an existing concrete M1 line.")
3801
+ return 1
3802
+ if " - M1: pending" in text:
3803
+ report(f"{label} --record added a second M1 slot beside the kept one.")
3804
+ return 1
3805
+ if " - M1.red: pending" not in text:
3806
+ report(f"{label} --record did not add the missing M1.red slot beside the kept M1.")
3807
+ return 1
3808
+
3809
+ write_text(tasks, no_evidence)
3810
+ code, payload = record("--record", "--no-guard")
3811
+ text = tasks.read_text(encoding="utf-8")
3812
+ if code != 0:
3813
+ report(f"{label} --record refused a valid evidence-first task: {payload.get('problems')!r}")
3814
+ return 1
3815
+ if ".red:" in text or ".green:" in text:
3816
+ report(f"{label} an evidence-first task was given .red/.green slots.")
3817
+ return 1
3818
+
3819
+ broken = red_green.replace(" - Strategy: vertical-tdd\n", "")
3820
+ write_text(tasks, broken)
3821
+ code, payload = record("--record")
3822
+ if code == 0:
3823
+ report(f"{label} --record filled slots around a task with no Strategy.")
3824
+ return 1
3825
+ if tasks.read_text(encoding="utf-8") != broken:
3826
+ report(f"{label} a refused --record wrote to tasks.md.")
3827
+ return 1
3828
+ if (repo / "keel/guard.json").exists():
3829
+ report(f"{label} a refused --record wrote the guard manifest.")
3830
+ return 1
3831
+
3832
+ write_text(tasks, fixture.replace(" - M1: pending\n", ""))
3833
+ code, payload = record()
3834
+ messages = [item.get("message", "") for item in payload.get("problems", [])]
3835
+ if code == 0:
3836
+ report(f"{label} task-start without --record accepted a missing M1 slot.")
3837
+ return 1
3838
+ if not any("--record" in message for message in messages):
3839
+ report(f"{label} the evidence-label-mismatch refusal does not name --record: {messages!r}")
3840
+ return 1
3841
+
3842
+ if "record-derives-skeleton" not in {name for name, _ in SCENARIOS}:
3843
+ report(f"{label} scenario is not registered.")
3844
+ return 1
3845
+ report("record-derives-skeleton scenario passed.")
3846
+ return 0
3847
+
3848
+
3849
+ def validate_review_checklist_defers_to_gate_scenario() -> int:
3850
+ """Issue #179: Review guidance keeps what no gate can judge, and only that.
3851
+
3852
+ `task-complete` refuses a missing or drifted Contract anchor and missing
3853
+ `.red`/`.green` Evidence on its own, so asking the agent to confirm them
3854
+ again is reading cost without a criterion. What stays is the judgment.
3855
+ """
3856
+ label = "review-checklist-defers-to-gate:"
3857
+ for root in ("src/skills", f"{PLUGIN_ROOT}/skills"):
3858
+ text = (ROOT / root / "keel-review-checklist" / "SKILL.md").read_text(encoding="utf-8")
3859
+ flat = " ".join(text.split())
3860
+ for restated in (
3861
+ "Evidence `Contract` line records the task-start capsule fingerprint",
3862
+ "confirm concrete per-label `.red` and `.green` Evidence exists",
3863
+ ):
3864
+ if restated in flat:
3865
+ report(f"{label} {root} keel-review-checklist still restates a gate refusal: {restated!r}")
3866
+ return 1
3867
+ for kept in (
3868
+ "evidence-first tasks",
3869
+ "observable proof",
3870
+ "through the public interface",
3871
+ "not build-only or shape-only",
3872
+ ):
3873
+ if kept not in flat:
3874
+ report(f"{label} {root} keel-review-checklist lost the judgment {kept!r}.")
3875
+ return 1
3876
+ if "review-checklist-defers-to-gate" not in {name for name, _ in SCENARIOS}:
3877
+ report(f"{label} scenario is not registered.")
3878
+ return 1
3879
+ report("review-checklist-defers-to-gate scenario passed.")
2460
3880
  return 0
2461
3881
 
2462
3882
 
@@ -14380,6 +15800,13 @@ def validate_core_gates_scenario() -> int:
14380
15800
  " - Evidence:\n"
14381
15801
  f" - Contract: {anchor}\n"
14382
15802
  " - M1: pending\n"
15803
+ " - Review:\n"
15804
+ " - Status: pending\n"
15805
+ " - Acceptance check: pending\n"
15806
+ " - Scope check: pending\n"
15807
+ " - Findings: pending\n"
15808
+ " - Blocker: none\n"
15809
+ " - Reauthorizations: none\n"
14383
15810
  " - Report:\n"
14384
15811
  " - Summary\n"
14385
15812
  )
@@ -14527,24 +15954,23 @@ def validate_core_gates_scenario() -> int:
14527
15954
  write_text(record_tasks, record_task("pending").replace(
14528
15955
  " - Contract: pending\n", ""
14529
15956
  ))
15957
+ # Issue #179: a missing anchor is a missing record slot, which
15958
+ # `--record` now derives instead of refusing; refusal is kept for an
15959
+ # authoring error (see `record-derives-skeleton`).
14530
15960
  missing_anchor = run_keel(
14531
15961
  record_repo, "gate", "task-start",
14532
- "--change", "demo", "--task", "1.1", "--record", "--json",
15962
+ "--change", "demo", "--task", "1.1", "--record", "--no-guard", "--json",
14533
15963
  )
14534
- if (
14535
- missing_anchor.returncode != 3
14536
- or not any(
14537
- problem.get("code") == "record-refused"
14538
- for problem in json.loads(missing_anchor.stdout).get("problems", [])
14539
- )
14540
- or (record_repo / "keel/guard.json").exists()
14541
- ):
15964
+ if missing_anchor.returncode != 0:
14542
15965
  report(
14543
- "core-gates scenario --record with a missing anchor must "
14544
- "refuse and write nothing, not even the guard manifest."
15966
+ "core-gates scenario --record with a missing anchor must add "
15967
+ "the anchor and pass."
14545
15968
  )
14546
15969
  report((missing_anchor.stderr or missing_anchor.stdout).strip())
14547
15970
  return 1
15971
+ if " - Contract: keel-task-capsule/v1 sha256:" not in record_tasks.read_text(encoding="utf-8"):
15972
+ report("core-gates scenario --record did not write the missing Contract anchor.")
15973
+ return 1
14548
15974
 
14549
15975
  invalid_base = run_keel(
14550
15976
  completion_repo,
@@ -15337,10 +16763,10 @@ def validate_native_plugin_manifests_scenario() -> int:
15337
16763
  report(f"native-plugin-manifests {label} lacks description/author.name.")
15338
16764
  return 1
15339
16765
 
15340
- if "hooks" in codex_manifest:
16766
+ if codex_manifest.get("hooks") != "./hooks/codex.json":
15341
16767
  report(
15342
- "native-plugin-manifests codex manifest declares an unsupported hooks "
15343
- "field; default discovery must load hooks/hooks.json."
16768
+ "native-plugin-manifests codex manifest must select its host-compatible "
16769
+ "hooks/codex.json configuration."
15344
16770
  )
15345
16771
  return 1
15346
16772
  interface = codex_manifest.get("interface", {})
@@ -15497,8 +16923,9 @@ def validate_native_plugin_manifests_scenario() -> int:
15497
16923
  "${CLAUDE_PLUGIN_ROOT}/plugins/keel/scripts/",
15498
16924
  )
15499
16925
  )
15500
- # Plus the Claude-only mailbox hooks (#180). They stay out of hooks.json,
15501
- # which Codex loads too: FileChanged and `asyncRewake` are Claude Code's.
16926
+ # Plus the Claude-only chat hooks (#180, #187). They stay out of
16927
+ # hooks.json, which Codex loads too: FileChanged, `asyncRewake`, and the
16928
+ # SessionEnd presence hook are Claude Code's.
15502
16929
  def mail_hook(event: str, **extra: object) -> dict:
15503
16930
  return {
15504
16931
  "type": "command",
@@ -15519,11 +16946,12 @@ def validate_native_plugin_manifests_scenario() -> int:
15519
16946
  expected_hooks["FileChanged"] = [
15520
16947
  {"hooks": [mail_hook("file-changed", asyncRewake=True)]}
15521
16948
  ]
16949
+ expected_hooks["SessionEnd"] = [{"hooks": [mail_hook("session-end")]}]
15522
16950
  if root_manifest.get("hooks") != expected_hooks:
15523
16951
  report(
15524
16952
  "native-plugin-manifests root plugin manifest hooks diverge "
15525
16953
  f"from {PLUGIN_ROOT}/hooks/hooks.json after resolving script paths "
15526
- "from the repository root, plus the Claude-only mailbox hooks: "
16954
+ "from the repository root, plus the Claude-only chat hooks: "
15527
16955
  f"{root_manifest.get('hooks')!r}"
15528
16956
  )
15529
16957
  return 1
@@ -32200,6 +33628,15 @@ def validate_the_repository_lands_what_passed_scenario() -> int:
32200
33628
  return 0
32201
33629
 
32202
33630
 
33631
+ def validate_codex_receiving_scenario() -> int:
33632
+ result = subprocess.run(
33633
+ [sys.executable, str(ROOT / "scripts/validate_codex_receiving.py")],
33634
+ capture_output=True, text=True,
33635
+ )
33636
+ report((result.stdout + result.stderr).strip())
33637
+ return result.returncode
33638
+
33639
+
32203
33640
  SCENARIOS: tuple = (
32204
33641
  ("stateless-continuity", validate_stateless_continuity_scenario),
32205
33642
  ("core-gates", validate_core_gates_scenario),
@@ -32229,13 +33666,64 @@ SCENARIOS: tuple = (
32229
33666
  "decisions-are-selectable",
32230
33667
  validate_decisions_are_selectable_scenario,
32231
33668
  ),
33669
+ (
33670
+ "chat-core",
33671
+ validate_chat_core_scenario,
33672
+ ),
33673
+ ("codex-receiving", validate_codex_receiving_scenario),
33674
+ (
33675
+ "chat-records",
33676
+ validate_chat_records_scenario,
33677
+ ),
33678
+ # The 5.83 names (#180), kept as aliases of the scenarios that replaced
33679
+ # them (#187), because open changes still name them in their checks.
32232
33680
  (
32233
33681
  "mailbox-cli",
32234
- validate_mailbox_cli_scenario,
33682
+ validate_chat_mail_migration_scenario,
32235
33683
  ),
32236
33684
  (
32237
33685
  "mailbox-claude-hooks",
32238
- validate_mailbox_claude_hooks_scenario,
33686
+ validate_chat_claude_hooks_scenario,
33687
+ ),
33688
+ (
33689
+ "chat-mail-migration",
33690
+ validate_chat_mail_migration_scenario,
33691
+ ),
33692
+ (
33693
+ "chat-claude-hooks",
33694
+ validate_chat_claude_hooks_scenario,
33695
+ ),
33696
+ (
33697
+ "chat-loop-guards",
33698
+ validate_chat_loop_guards_scenario,
33699
+ ),
33700
+ (
33701
+ "chat-human-view",
33702
+ validate_chat_human_view_scenario,
33703
+ ),
33704
+ (
33705
+ "chat-bridge-outbound",
33706
+ validate_chat_bridge_outbound_scenario,
33707
+ ),
33708
+ (
33709
+ "chat-bridge-inbound",
33710
+ validate_chat_bridge_inbound_scenario,
33711
+ ),
33712
+ (
33713
+ "chat-bridge-lifecycle",
33714
+ validate_chat_bridge_lifecycle_scenario,
33715
+ ),
33716
+ (
33717
+ "chat-archive",
33718
+ validate_chat_archive_scenario,
33719
+ ),
33720
+ (
33721
+ "record-derives-skeleton",
33722
+ validate_record_derives_skeleton_scenario,
33723
+ ),
33724
+ (
33725
+ "review-checklist-defers-to-gate",
33726
+ validate_review_checklist_defers_to_gate_scenario,
32239
33727
  ),
32240
33728
  (
32241
33729
  "covers-annotation-entry",