@christang/keel 5.182.0 → 5.184.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4316 @@
1
+ """Keel validation: shift (split from validate_plugin.py, #409)."""
2
+ from __future__ import annotations
3
+
4
+ import contextlib
5
+ import json
6
+ import gzip
7
+ import hashlib
8
+ import os
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tarfile
14
+ import tempfile
15
+ import threading
16
+ import time
17
+ import ast
18
+ import atexit
19
+ import signal
20
+ from datetime import datetime, timedelta, timezone
21
+ from concurrent.futures import ThreadPoolExecutor, as_completed
22
+ from pathlib import Path
23
+
24
+ from validation.common import (
25
+ ROOT,
26
+ chat_environment,
27
+ chat_json,
28
+ chat_log,
29
+ chat_logs_snapshot,
30
+ chat_records_with,
31
+ chat_scratch_group,
32
+ chat_session_start,
33
+ chat_wake_scratch,
34
+ chat_worktree,
35
+ host_project_name,
36
+ mailbox_common_dir,
37
+ mailbox_repository,
38
+ report,
39
+ run_keel,
40
+ run_session_start_hook,
41
+ session_start_context,
42
+ shift_scratch,
43
+ snapshot_files,
44
+ task_capsule_compact_fixture,
45
+ task_contract_fixture,
46
+ write_authorize_config,
47
+ write_text,
48
+ )
49
+ from validation import registry
50
+
51
+
52
+ def validate_two_live_sessions_on_one_role_scenario() -> int:
53
+ """Issue #369 point 4: two live sessions bound to one role are reported.
54
+
55
+ On 2026-10-18 a desktop PM session and its CLI copy both ran as `iecc-pm`
56
+ in one worktree: both posted under the one name and shared one read
57
+ cursor, and neither knew. Each session now records itself under the role;
58
+ with two live ones `keel context`, `keel chat post` and `keel chat unread`
59
+ say so, and the warning goes once one has ended.
60
+ """
61
+ label = "two-live-sessions-on-one-role:"
62
+ with tempfile.TemporaryDirectory(prefix="keel-twins-369-") as raw:
63
+ base = Path(raw)
64
+ rtl, verify, env, _ = shift_scratch(base)
65
+ write_text(verify / "openspec/specs/.keep", "")
66
+ other = subprocess.Popen(["sleep", "300"])
67
+ try:
68
+ def as_session(sid: str, pid: int) -> dict:
69
+ return {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": sid, "CLAUDE_PID": str(pid)}
70
+
71
+ def start(sid: str, pid: int) -> None:
72
+ subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=verify,
73
+ env=as_session(sid, pid), text=True, capture_output=True, check=False,
74
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": sid, "source": "startup"}))
75
+
76
+ start("sess-a", os.getpid())
77
+ alone = json.loads(run_keel(verify, "context", "--json", env=as_session("sess-a", os.getpid())).stdout)
78
+ if any("live sessions" in w for w in alone.get("warnings", [])):
79
+ report(f"{label} one session was reported as two: {alone.get('warnings')!r}")
80
+ return 1
81
+ start("sess-b", other.pid)
82
+ context = json.loads(run_keel(verify, "context", "--json", env=as_session("sess-a", os.getpid())).stdout)
83
+ warning = next((w for w in context.get("warnings", []) if "live sessions" in w), "")
84
+ for needle in ("verify", "sess-a", "sess-b", "read cursor"):
85
+ if needle not in warning:
86
+ report(f"{label} keel context's warning does not name {needle!r}: {context.get('warnings')!r}")
87
+ return 1
88
+ posted = run_keel(verify, "chat", "post", "soc", "hello", env=as_session("sess-a", os.getpid()))
89
+ if "live sessions" not in posted.stderr:
90
+ report(f"{label} keel chat post does not warn: {posted.stdout!r} {posted.stderr!r}")
91
+ return 1
92
+ read = run_keel(verify, "chat", "unread", "--json", env=as_session("sess-a", os.getpid()))
93
+ if "live sessions" not in read.stderr:
94
+ report(f"{label} keel chat unread does not warn: {read.stderr!r}")
95
+ return 1
96
+ json.loads(read.stdout)
97
+ other.kill()
98
+ other.wait()
99
+ after = json.loads(run_keel(verify, "context", "--json", env=as_session("sess-a", os.getpid())).stdout)
100
+ if any("live sessions" in w for w in after.get("warnings", [])):
101
+ report(f"{label} the warning stayed after one session ended: {after.get('warnings')!r}")
102
+ return 1
103
+ finally:
104
+ if other.poll() is None:
105
+ other.kill()
106
+ if "two-live-sessions-on-one-role" not in {name for name, _ in registry.SCENARIOS}:
107
+ report(f"{label} scenario is not registered.")
108
+ return 1
109
+ report("two-live-sessions-on-one-role scenario passed.")
110
+ return 0
111
+
112
+
113
+ def validate_patrol_rearm_scenario() -> int:
114
+ """Issue #260: the patrolling role is reminded to re-arm its schedule.
115
+
116
+ `patrol:` names the role and interval; that role's `keel context`, session
117
+ projection, and `keel shift resume` remind it; other roles and a broken
118
+ declaration are quiet. Keel schedules nothing.
119
+ """
120
+ label = "patrol-rearm:"
121
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-rearm-") as raw:
122
+ base = Path(raw)
123
+ repo = mailbox_repository(base / "repo")
124
+ write_text(repo / "openspec/specs/.keep", "")
125
+ write_authorize_config(repo, "patrol:\n role: iecc-pm\n every: 30m\n")
126
+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True, capture_output=True)
127
+ subprocess.run(["git", "commit", "-q", "-m", "patrol"], cwd=repo, check=True, capture_output=True)
128
+ pm = chat_worktree(repo, base / "pm")
129
+ rtl = chat_worktree(repo, base / "rtl")
130
+ env = chat_environment()
131
+ run_keel(pm, "chat", "role", "--set", "iecc-pm", env=env)
132
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
133
+
134
+ def look(cwd: Path) -> tuple[dict, str]:
135
+ context = json.loads(run_keel(cwd, "context", "--json", env=env).stdout)
136
+ session = run_session_start_hook(
137
+ cwd, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(cwd)},
138
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
139
+ )
140
+ return context, session_start_context(session) or ""
141
+
142
+ context, note = look(pm)
143
+ if context.get("patrol") != {"role": "iecc-pm", "every": "30m"}:
144
+ report(f"{label} the coordinator's context carries patrol {context.get('patrol')!r}.")
145
+ return 1
146
+ if "keel patrol" not in note or "30m" not in note:
147
+ report(f"{label} the coordinator's projection does not remind it: {note!r}")
148
+ return 1
149
+ ready = run_keel(pm, "shift", "ready", "next: keep patrolling", env=env)
150
+ if ready.returncode != 0:
151
+ report(f"{label} keel shift ready failed: {ready.stdout} {ready.stderr}")
152
+ return 1
153
+ resumed = run_keel(pm, "shift", "resume", env=env)
154
+ tail = resumed.stdout.strip().splitlines()[-1] if resumed.stdout.strip() else ""
155
+ if "keel patrol" not in tail or "30m" not in tail:
156
+ report(f"{label} keel shift resume does not end with the reminder: {resumed.stdout!r}")
157
+ return 1
158
+
159
+ context, note = look(rtl)
160
+ if "patrol" in context:
161
+ report(f"{label} another role carries patrol: {context.get('patrol')!r}")
162
+ return 1
163
+ if "keel patrol" in note:
164
+ report(f"{label} another role's projection reminds it: {note!r}")
165
+ return 1
166
+
167
+ write_authorize_config(pm, "patrol:\n role: iecc-pm\n every: soon\n")
168
+ broken = json.loads(run_keel(pm, "context", "--json", env=env).stdout)
169
+ if "patrol" in broken:
170
+ report(f"{label} a malformed declaration still reminds: {broken.get('patrol')!r}")
171
+ return 1
172
+ if not any("patrol" in w for w in broken.get("warnings", [])):
173
+ report(f"{label} the malformed declaration is not reported: {broken.get('warnings')!r}")
174
+ return 1
175
+ report("patrol-rearm scenario passed.")
176
+ return 0
177
+
178
+
179
+ def validate_patrol_host_task_scenario() -> int:
180
+ """Issue #295: `patrol:` names the host task; `keel patrol task` renders it.
181
+
182
+ The rendered task carries the id, a cron from `every:`, the declared model
183
+ or none, and a prompt running the change-based patrol by path; it writes
184
+ nothing. A declared host task changes the reminder.
185
+ """
186
+ label = "patrol-host-task:"
187
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-host-") as raw:
188
+ base = Path(raw)
189
+ repo = mailbox_repository(base / "repo")
190
+ write_text(repo / "openspec/specs/.keep", "")
191
+ declaration = "patrol:\n role: rtl\n every: 30m\n host_task: soc-patrol\n"
192
+ write_authorize_config(repo, declaration)
193
+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True, capture_output=True)
194
+ subprocess.run(["git", "commit", "-q", "-m", "patrol"], cwd=repo, check=True, capture_output=True)
195
+ rtl = chat_worktree(repo, base / "rtl")
196
+ env = chat_environment()
197
+
198
+ unbound = run_keel(rtl, "patrol", "task", env=env)
199
+ if unbound.returncode == 0:
200
+ report(f"{label} keel patrol task was accepted with no worktree bound to rtl.")
201
+ return 1
202
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
203
+ before = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
204
+ task = run_keel(rtl, "patrol", "task", env=env)
205
+ if task.returncode != 0:
206
+ report(f"{label} keel patrol task failed: {task.stdout} {task.stderr}")
207
+ return 1
208
+ for needle in ("soc-patrol", "*/30 * * * *", "no model is declared",
209
+ f"keel patrol --repo {rtl.resolve()} --since-last --notify"):
210
+ if needle not in task.stdout:
211
+ report(f"{label} the rendered task does not carry {needle!r}: {task.stdout!r}")
212
+ return 1
213
+ after = subprocess.run(["git", "status", "--porcelain"], cwd=rtl, capture_output=True, text=True).stdout
214
+ if before != after:
215
+ report(f"{label} keel patrol task changed the worktree: {after!r}")
216
+ return 1
217
+ write_authorize_config(rtl, declaration + " model: small-model\n")
218
+ modelled = run_keel(rtl, "patrol", "task", env=env)
219
+ if "small-model" not in modelled.stdout:
220
+ report(f"{label} the declared model is not rendered: {modelled.stdout!r}")
221
+ return 1
222
+ if "no model is declared" in modelled.stdout:
223
+ report(f"{label} a declared model is still reported as undeclared: {modelled.stdout!r}")
224
+ return 1
225
+
226
+ context = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
227
+ if (context.get("patrol") or {}).get("hostTask") != "soc-patrol":
228
+ report(f"{label} keel context carries patrol {context.get('patrol')!r}.")
229
+ return 1
230
+ session = run_session_start_hook(
231
+ rtl, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(rtl)},
232
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
233
+ )
234
+ note = session_start_context(session) or ""
235
+ if "soc-patrol" not in note or "still enabled" not in note:
236
+ report(f"{label} the session-start note does not name the host task: {note!r}")
237
+ return 1
238
+ if "re-create it with the host" in note:
239
+ report(f"{label} the note still asks to re-create a session schedule: {note!r}")
240
+ return 1
241
+
242
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 30m\n host_task: Bad_Id\n")
243
+ broken = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
244
+ if not any("host_task" in w and "Bad_Id" in w for w in broken.get("warnings", [])):
245
+ report(f"{label} a malformed host_task is not reported by name: {broken.get('warnings')!r}")
246
+ return 1
247
+ report("patrol-host-task scenario passed.")
248
+ return 0
249
+
250
+
251
+ def validate_patrol_since_last_scenario() -> int:
252
+ """Issue #295: a scheduled patrol reports only what changed, once.
253
+
254
+ `--since-last` records a baseline, then reports changed entries and exits
255
+ 2; `--notify` sends them to the coordinator as one message from
256
+ `keel-patrol`; an unchanged run is quiet. `--notify` alone is refused.
257
+ """
258
+ label = "patrol-since-last:"
259
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-since-") as raw:
260
+ base = Path(raw)
261
+ rtl, verify, env, _ = shift_scratch(base)
262
+
263
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
264
+ return run_keel(rtl, "patrol", *args, env=env)
265
+
266
+ def notices() -> list[str]:
267
+ return chat_records_with(rtl, "dm-keel-patrol--rtl", "changed")
268
+
269
+ alone = patrol("--notify")
270
+ if alone.returncode != 1:
271
+ report(f"{label} --notify without --since-last exited {alone.returncode}.")
272
+ return 1
273
+ first = patrol("--since-last", "--notify")
274
+ if first.returncode != 0:
275
+ report(f"{label} the first run exited {first.returncode}: {first.stdout!r} {first.stderr!r}")
276
+ return 1
277
+ if "baseline recorded" not in first.stdout:
278
+ report(f"{label} the first run did not record a baseline: {first.stdout!r}")
279
+ return 1
280
+ if notices():
281
+ report(f"{label} the baseline run sent a notice.")
282
+ return 1
283
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
284
+ if readied.returncode != 0:
285
+ report(f"{label} verify's ready failed: {readied.stderr}")
286
+ return 1
287
+ for args in (["commit", "-q", "--allow-empty", "-m", "landed"], ["push", "-q", "origin", "HEAD"]):
288
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
289
+ second = patrol("--since-last", "--notify")
290
+ if second.returncode != 3:
291
+ report(f"{label} the run after a change exited {second.returncode}: {second.stdout!r} {second.stderr!r}")
292
+ return 1
293
+ changed = [line for line in second.stdout.splitlines() if line.startswith("changed:")]
294
+ if not any("shift" in line and "verify" in line for line in changed):
295
+ report(f"{label} the shift status change is not reported: {second.stdout!r}")
296
+ return 1
297
+ if not any("remote" in line for line in changed):
298
+ report(f"{label} the remote tip change is not reported: {second.stdout!r}")
299
+ return 1
300
+ # Shift-status and remote changes are not risks (#307 part 3): printed, not sent.
301
+ if notices():
302
+ report(f"{label} a run with no risk sent the coordinator a notice: {notices()!r}")
303
+ return 1
304
+ third = patrol("--since-last", "--notify")
305
+ if third.returncode != 0:
306
+ report(f"{label} an unchanged run exited {third.returncode}: {third.stdout!r}")
307
+ return 1
308
+ if "changed:" in third.stdout:
309
+ report(f"{label} an unchanged run reported a change: {third.stdout!r}")
310
+ return 1
311
+ if notices():
312
+ report(f"{label} an unchanged run sent a notice.")
313
+ return 1
314
+ report("patrol-since-last scenario passed.")
315
+ return 0
316
+
317
+
318
+ def validate_patrol_exit_says_who_acts_scenario() -> int:
319
+ """Issue #350: `keel patrol` exited 2 on pure state changes too.
320
+
321
+ A coordinator's schedule wakes its model on exit 2, so a run that only
322
+ moved state or told other roles cost a model turn for nothing. Exit 2 now
323
+ means the coordinator has something to act on — a risk, or its own wait
324
+ met — and exit 3 means patrol recorded or delivered something for others.
325
+ """
326
+ label = "patrol-exit-says-who-acts:"
327
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-350-") as raw:
328
+ base = Path(raw)
329
+ rtl, verify, env, _ = shift_scratch(base)
330
+
331
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
332
+ return run_keel(rtl, "patrol", *args, env=env)
333
+
334
+ def push() -> str:
335
+ for args in (["commit", "-q", "--allow-empty", "-m", "landed"], ["push", "-q", "origin", "HEAD"]):
336
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
337
+ return subprocess.run(["git", "rev-parse", "HEAD"], cwd=rtl, text=True, capture_output=True, check=True).stdout.strip()
338
+
339
+ if patrol("--since-last", "--notify").returncode != 0:
340
+ report(f"{label} the baseline run did not exit 0.")
341
+ return 1
342
+ push()
343
+ moved = patrol("--since-last", "--notify")
344
+ if moved.returncode != 3:
345
+ report(f"{label} a run whose only news is the remote tip exited {moved.returncode}, not 3: {moved.stdout!r}")
346
+ return 1
347
+ (rtl / "stray.txt").write_text("x\n")
348
+ risky = patrol("--since-last", "--notify")
349
+ if risky.returncode != 2:
350
+ report(f"{label} a run that found a risk exited {risky.returncode}, not 2: {risky.stdout!r}")
351
+ return 1
352
+ (rtl / "stray.txt").unlink()
353
+
354
+ sha = push()
355
+ run_keel(verify, "chat", "wait", "soc", "--commit", sha, "rerun when it lands", env=env)
356
+ theirs = patrol()
357
+ if theirs.returncode != 3:
358
+ report(f"{label} a run that met another role's wait exited {theirs.returncode}, not 3: {theirs.stdout!r}")
359
+ return 1
360
+ sha = push()
361
+ run_keel(rtl, "chat", "wait", "soc", "--commit", sha, "merge the next slice", env=env)
362
+ mine = patrol()
363
+ if mine.returncode != 2:
364
+ report(f"{label} a run that met the coordinator's own wait exited {mine.returncode}, not 2: {mine.stdout!r}")
365
+ return 1
366
+ helped = run_keel(rtl, "patrol", "--help", env=env)
367
+ if "3:" not in helped.stdout:
368
+ report(f"{label} --help does not document exit 3: {helped.stdout!r}")
369
+ return 1
370
+ if "patrol-exit-says-who-acts" not in {name for name, _ in registry.SCENARIOS}:
371
+ report(f"{label} scenario is not registered.")
372
+ return 1
373
+ report("patrol-exit-says-who-acts scenario passed.")
374
+ return 0
375
+
376
+
377
+ def validate_patrol_next_scenario() -> int:
378
+ """Issue #356: a patrol recommends when to run next.
379
+
380
+ With `cadence: adaptive` the first matching rule picks the delay — risk,
381
+ quota, night, busy, idle — and each case has a failing arm: the same
382
+ fixture without its condition gives another rule. A fixed `every:` keeps
383
+ today's cadence.
384
+ """
385
+ label = "patrol-next:"
386
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-356-") as raw:
387
+ base = Path(raw)
388
+ rtl, verify, env, _ = shift_scratch(base)
389
+
390
+ def config(extra: str) -> None:
391
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 60m\n" + extra)
392
+
393
+ def patrol(*args: str) -> dict:
394
+ result = run_keel(rtl, "patrol", "--json", *args, env=env)
395
+ return json.loads(result.stdout) if result.stdout.strip().startswith("{") else {"raw": result.stdout + result.stderr}
396
+
397
+ def expect(name: str, payload: dict, rule: str, seconds: int | None) -> bool:
398
+ if payload.get("next_rule") != rule:
399
+ report(f"{label} {name}: next_rule {payload.get('next_rule')!r}, not {rule!r}: {payload!r}")
400
+ return False
401
+ if seconds is not None and payload.get("next_after_s") != seconds:
402
+ report(f"{label} {name}: next_after_s {payload.get('next_after_s')!r}, not {seconds}")
403
+ return False
404
+ return True
405
+
406
+ config("")
407
+ if not expect("fixed", patrol(), "fixed", 3600):
408
+ return 1
409
+ config(" cadence: adaptive\n")
410
+ if not expect("idle", patrol(), "idle", 3 * 3600):
411
+ return 1
412
+ subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=verify, env=env,
413
+ text=True, capture_output=True, check=False,
414
+ input=json.dumps({"cwd": str(verify), "hook_event_name": "SessionStart", "session_id": "v1", "source": "startup"}))
415
+ if not expect("busy", patrol(), "busy", 3600):
416
+ return 1
417
+ patrol("--quota", "92")
418
+ if not expect("quota", patrol("--quota", "92"), "quota", 4 * 3600):
419
+ return 1
420
+ # The risk is a clean checkout turning dirty, so the config is committed first.
421
+ subprocess.run(["git", "add", "-A"], cwd=rtl, check=True, capture_output=True)
422
+ subprocess.run(["git", "commit", "-q", "-m", "cadence"], cwd=rtl, check=True, capture_output=True)
423
+ patrol("--since-last")
424
+ (rtl / "stray.txt").write_text("x\n")
425
+ if not expect("risk", patrol("--since-last"), "risk", 30 * 60):
426
+ return 1
427
+ (rtl / "stray.txt").unlink()
428
+ patrol("--since-last")
429
+ now = datetime.now()
430
+ start = (now - timedelta(minutes=30)).strftime("%H:%M")
431
+ end_at = now + timedelta(minutes=90)
432
+ config(f" cadence: adaptive\n idle: 2h\n quiet: {start}-{end_at.strftime('%H:%M')}\n")
433
+ night = patrol()
434
+ if not expect("night", night, "night", None):
435
+ return 1
436
+ if not 80 * 60 <= night.get("next_after_s", 0) <= 91 * 60:
437
+ report(f"{label} night: next_after_s {night.get('next_after_s')} does not end at the window's end.")
438
+ return 1
439
+ config(" cadence: adaptive\n busy: 45m\n min: 50m\n")
440
+ if not expect("busy clamped to min", patrol(), "busy", 50 * 60):
441
+ return 1
442
+ text = run_keel(rtl, "patrol", env=env).stdout
443
+ if not re.search(r"^next: 50m \(busy\)$", text, re.M):
444
+ report(f"{label} the text output has no `next: 50m (busy)` line: {text!r}")
445
+ return 1
446
+ log = (mailbox_common_dir(rtl) / "keel-chat" / "patrol" / "log" / "rtl.log").read_text(encoding="utf-8").splitlines()
447
+ if not log[-1].endswith("next=50m (busy)"):
448
+ report(f"{label} the run log does not record the next run: {log[-1]!r}")
449
+ return 1
450
+ if "patrol-next" not in {name for name, _ in registry.SCENARIOS}:
451
+ report(f"{label} scenario is not registered.")
452
+ return 1
453
+ report("patrol-next scenario passed.")
454
+ return 0
455
+
456
+
457
+ def validate_launchd_stable_node_scenario() -> int:
458
+ """Issue #387: a launchd job must name a node that outlives `brew upgrade`.
459
+
460
+ `keel tick task` printed `process.execPath`, Homebrew's versioned Cellar
461
+ path, which is gone after an upgrade; launchd then fails silently every
462
+ interval. The jobs now name the `node` on PATH that is the same binary (the
463
+ symlink the package manager keeps current), leave plugin cache directories
464
+ out of PATH, and `keel --doctor` reports a job whose node no longer exists.
465
+ """
466
+ label = "launchd-stable-node:"
467
+ with tempfile.TemporaryDirectory(prefix="keel-launchd-387-") as raw:
468
+ base = Path(raw)
469
+ rtl, cx, env, _ = chat_wake_scratch(base)
470
+ real = os.path.realpath(shutil.which("node") or "node")
471
+ versioned = base / "cellar" / "node" / "9.9.9" / "bin"
472
+ versioned.mkdir(parents=True)
473
+ (versioned / "node").symlink_to(real)
474
+ stable = base / "bin"
475
+ stable.mkdir()
476
+ (stable / "node").symlink_to(versioned / "node")
477
+ cache = base / "home" / ".claude" / "plugins" / "cache" / "keel-marketplace" / "keel" / "5.149.0" / "bin"
478
+ cache.mkdir(parents=True)
479
+ path = os.pathsep.join([str(cache), str(stable), os.environ.get("PATH", "")])
480
+ env = {**env, "PATH": path}
481
+ write_text(rtl / "openspec/specs/.keep", "")
482
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 60m\n runner: tick\n")
483
+ subprocess.run(["git", "add", "-A"], cwd=rtl, check=True, capture_output=True)
484
+ subprocess.run(["git", "commit", "-q", "-m", "tick"], cwd=rtl, check=True, capture_output=True)
485
+
486
+ def keel(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
487
+ return subprocess.run([str(stable / "node"), str(ROOT / "bin" / "keel.js"), *args], cwd=cwd, env=env,
488
+ text=True, capture_output=True, check=False)
489
+
490
+ def program(plist: str) -> str:
491
+ return (re.search(r"<key>ProgramArguments</key>\s*<array>\s*<string>(.*?)</string>", plist, re.S) or [None, ""])[1]
492
+
493
+ def path_of(plist: str) -> str:
494
+ return (re.search(r"<key>PATH</key>\s*<string>(.*?)</string>", plist, re.S) or [None, ""])[1]
495
+
496
+ task = keel(rtl, "tick", "task")
497
+ if task.returncode != 0:
498
+ report(f"{label} keel tick task failed: {task.stderr!r}")
499
+ return 1
500
+ if program(task.stdout) != str(stable / "node"):
501
+ report(f"{label} the tick job names the versioned node: {program(task.stdout)!r}, not {str(stable / 'node')!r}")
502
+ return 1
503
+ if str(stable) not in path_of(task.stdout).split(os.pathsep) or "plugins/cache" in path_of(task.stdout):
504
+ report(f"{label} the tick job's PATH is not the stable directories without the plugin cache: {path_of(task.stdout)!r}")
505
+ return 1
506
+
507
+ added = keel(cx, "chat", "wake", "add")
508
+ plists = sorted((base / "agents").glob("dev.keel.chat-wake.*.plist"))
509
+ if added.returncode != 0 or len(plists) != 1:
510
+ report(f"{label} keel chat wake add wrote {len(plists)} LaunchAgents: {(added.stdout + added.stderr).strip()!r}")
511
+ return 1
512
+ waker = plists[0].read_text(encoding="utf-8")
513
+ if program(waker) != str(stable / "node"):
514
+ report(f"{label} the chat waker's LaunchAgent names the versioned node: {program(waker)!r}")
515
+ return 1
516
+ if "plugins/cache" in path_of(waker):
517
+ report(f"{label} the chat waker's LaunchAgent keeps a plugin cache directory in PATH: {path_of(waker)!r}")
518
+ return 1
519
+
520
+ gone = base / "Cellar" / "node" / "0.0.0" / "bin" / "node"
521
+ broken = base / "agents" / "dev.keel.tick.x.plist"
522
+ broken.write_text(task.stdout[task.stdout.index("<?xml"):task.stdout.index("</plist>") + 8].replace(str(stable / "node"), str(gone)), encoding="utf-8")
523
+ problem = keel(rtl, "--doctor")
524
+ line = next((l for l in problem.stdout.splitlines() if l.startswith("launchd: problem")), "")
525
+ for needle in ("dev.keel.tick.x.plist", str(gone), "keel tick task"):
526
+ if needle not in line:
527
+ report(f"{label} doctor does not name {needle!r} for a job whose node is gone: {problem.stdout!r}")
528
+ return 1
529
+ broken.write_text(broken.read_text(encoding="utf-8").replace(str(gone), str(stable / "node")), encoding="utf-8")
530
+ fine = keel(rtl, "--doctor")
531
+ if "launchd: ok" not in fine.stdout or "launchd: problem" in fine.stdout:
532
+ report(f"{label} doctor does not report ok once the node exists: {fine.stdout!r}")
533
+ return 1
534
+ if "launchd-stable-node" not in {name for name, _ in registry.SCENARIOS}:
535
+ report(f"{label} scenario is not registered.")
536
+ return 1
537
+ report("launchd-stable-node scenario passed.")
538
+ return 0
539
+
540
+
541
+ def validate_shift_slash_command_scenario() -> int:
542
+ """Issue #386: a session changes its own shift with one slash command.
543
+
544
+ `/keel:shift` is a command file in the Claude plugin that orders what a
545
+ session does: check, settle each loose end (a keep-awake the host started,
546
+ such as `caffeinate`, is not one), write the note, `ready --wake`. The
547
+ scenario finds it through the root manifest and runs its own fenced `keel
548
+ shift` lines in a clean worktree bound to a role, so a flag `keel` no
549
+ longer accepts, or a heredoc that stores nothing, fails it.
550
+ """
551
+ label = "shift-slash-command:"
552
+ manifest = json.loads((ROOT / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8"))
553
+ declared = manifest.get("commands") or []
554
+ if not declared:
555
+ report(f"{label} the root manifest declares no command")
556
+ return 1
557
+ files = [ROOT / entry for entry in declared if (ROOT / entry).name == "shift.md"]
558
+ if len(files) != 1 or not files[0].is_file():
559
+ report(f"{label} the root manifest's commands {declared!r} do not resolve to one plugins/keel/commands/shift.md")
560
+ return 1
561
+ if files[0].relative_to(ROOT).parts[:3] != ("plugins", "keel", "commands"):
562
+ report(f"{label} the command is not under plugins/keel/commands: {files[0]}")
563
+ return 1
564
+ text = files[0].read_text(encoding="utf-8")
565
+ front = re.match(r"---\n(.*?)\n---\n", text, re.S)
566
+ if not front or not re.search(r"^description: \S", front.group(1), re.M):
567
+ report(f"{label} the command has no front matter with a description.")
568
+ return 1
569
+ for needle in ("caffeinate", "--force-reason", "self-shift", "end your turn"):
570
+ if needle not in text:
571
+ report(f"{label} the command does not say {needle!r}.")
572
+ return 1
573
+ blocks = re.findall(r"```bash\n(.*?)```", text, re.S)
574
+ lines = [b for b in blocks if b.lstrip().startswith("keel shift")]
575
+ if [b.split()[2] for b in lines] != ["check", "ready"]:
576
+ report(f"{label} the command's keel shift blocks are not check, then ready: {[b.split()[:3] for b in lines]!r}")
577
+ return 1
578
+ with tempfile.TemporaryDirectory(prefix="keel-shift-386-") as raw:
579
+ base = Path(raw)
580
+ _rtl, verify, env, _ = shift_scratch(base)
581
+ shim = base / "shim"
582
+ write_text(shim / "keel", f'#!/bin/sh\nexec node "{ROOT / "bin" / "keel.js"}" "$@"\n')
583
+ (shim / "keel").chmod(0o755)
584
+ env = {**env, "PATH": f"{shim}{os.pathsep}{os.environ.get('PATH', '')}", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000"}
585
+ checked = subprocess.run(["sh", "-c", lines[0]], cwd=verify, env=env, text=True, capture_output=True, check=False)
586
+ if checked.returncode != 0:
587
+ report(f"{label} the command's check line exited {checked.returncode} in a clean worktree: {checked.stdout!r} {checked.stderr!r}")
588
+ return 1
589
+ handed = subprocess.run(["sh", "-c", lines[1]], cwd=verify, env=env, text=True, capture_output=True, check=False)
590
+ if handed.returncode != 0:
591
+ report(f"{label} the command's ready line exited {handed.returncode}: {handed.stdout!r} {handed.stderr!r}")
592
+ return 1
593
+ body = re.search(r"<<'EOF'\n(.*?)\nEOF", lines[1], re.S)
594
+ stored = mailbox_common_dir(verify) / "keel-chat" / "shift" / "verify.md"
595
+ if not body:
596
+ report(f"{label} the command's ready line carries no quoted heredoc: {lines[1]!r}")
597
+ return 1
598
+ if not stored.exists():
599
+ report(f"{label} the command's ready line stored no note at {stored}: {handed.stdout!r}")
600
+ return 1
601
+ if body.group(1).strip() not in stored.read_text(encoding="utf-8"):
602
+ report(f"{label} the stored note is not the heredoc's: {stored.read_text(encoding='utf-8')!r}")
603
+ return 1
604
+ if "wake is armed" not in handed.stdout:
605
+ report(f"{label} the command's ready line did not arm the wake: {handed.stdout!r}")
606
+ return 1
607
+ if "shift-slash-command" not in {name for name, _ in registry.SCENARIOS}:
608
+ report(f"{label} scenario is not registered.")
609
+ return 1
610
+ report("shift-slash-command scenario passed.")
611
+ return 0
612
+
613
+
614
+ def validate_tick_runs_due_patrol_scenario() -> int:
615
+ """The owner's CLI waker (2026-10-19, #356): `keel tick` runs the patrol when due.
616
+
617
+ A host scheduler (launchd) calls `keel tick` every few minutes; each call
618
+ is one model-free step. It fetches and patrols only once the last run's
619
+ recommended `next_at` has passed, records the next one, and otherwise exits
620
+ quietly. `keel tick task` prints the launchd job and creates nothing.
621
+ """
622
+ label = "tick-runs-due-patrol:"
623
+ with tempfile.TemporaryDirectory(prefix="keel-tick-") as raw:
624
+ base = Path(raw)
625
+ rtl, verify, env, _ = shift_scratch(base)
626
+ write_text(rtl / "openspec/specs/.keep", "")
627
+ write_authorize_config(rtl, "patrol:\n role: rtl\n every: 60m\n runner: tick\n cadence: adaptive\n")
628
+ subprocess.run(["git", "add", "-A"], cwd=rtl, check=True, capture_output=True)
629
+ subprocess.run(["git", "commit", "-q", "-m", "tick"], cwd=rtl, check=True, capture_output=True)
630
+ store_root = mailbox_common_dir(rtl) / "keel-chat"
631
+ log = store_root / "patrol" / "log" / "rtl.log"
632
+ state = store_root / "tick" / "state.json"
633
+
634
+ def tick(*args: str) -> subprocess.CompletedProcess[str]:
635
+ return run_keel(verify, "tick", "--repo", str(rtl), *args, env=env)
636
+
637
+ def runs() -> int:
638
+ return len(log.read_text(encoding="utf-8").splitlines()) if log.exists() else 0
639
+
640
+ first = tick()
641
+ if first.returncode != 0:
642
+ report(f"{label} the first tick exited {first.returncode}: {first.stdout!r} {first.stderr!r}")
643
+ return 1
644
+ if runs() != 1:
645
+ report(f"{label} the first tick did not run the patrol once: {runs()} log lines; {first.stdout!r}")
646
+ return 1
647
+ saved = json.loads(state.read_text(encoding="utf-8")) if state.exists() else {}
648
+ if not saved.get("patrol", {}).get("next_at"):
649
+ report(f"{label} the tick did not record the next patrol: {saved!r}")
650
+ return 1
651
+ second = tick()
652
+ if second.returncode != 0 or runs() != 1:
653
+ report(f"{label} a tick before next_at ran the patrol: {runs()} log lines; {second.stdout!r}")
654
+ return 1
655
+ if "not due" not in second.stdout:
656
+ report(f"{label} a skipped tick does not say the patrol is not due: {second.stdout!r}")
657
+ return 1
658
+ saved["patrol"]["next_at"] = "2000-01-01T00:00:00+00:00"
659
+ state.write_text(json.dumps(saved), encoding="utf-8")
660
+ tick()
661
+ if runs() != 2:
662
+ report(f"{label} a tick after next_at did not run the patrol: {runs()} log lines.")
663
+ return 1
664
+
665
+ rendered = run_keel(rtl, "tick", "task", env=env)
666
+ if rendered.returncode != 0:
667
+ report(f"{label} keel tick task failed: {rendered.stderr!r}")
668
+ return 1
669
+ for needle in ("<key>Label</key>", "<key>StartInterval</key>", "<integer>300</integer>", "<string>tick</string>",
670
+ f"<string>{os.path.realpath(rtl)}</string>", "launchctl bootstrap", "Keel creates nothing"):
671
+ if needle not in rendered.stdout:
672
+ report(f"{label} keel tick task does not carry {needle!r}: {rendered.stdout!r}")
673
+ return 1
674
+ if list((base / "home").glob("**/*.plist")) if (base / "home").exists() else []:
675
+ report(f"{label} keel tick task wrote a plist.")
676
+ return 1
677
+
678
+ context = json.loads(run_keel(rtl, "context", "--json", env=env).stdout)
679
+ if (context.get("patrol") or {}).get("runner") != "tick":
680
+ report(f"{label} the coordinator's context does not carry runner tick: {context.get('patrol')!r}")
681
+ return 1
682
+ session = run_session_start_hook(
683
+ rtl, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(rtl)},
684
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
685
+ )
686
+ reminder = session_start_context(session) or ""
687
+ if "re-create it with the host" in reminder:
688
+ report(f"{label} with runner: tick the coordinator is still told to re-create a session schedule: {reminder!r}")
689
+ return 1
690
+ if "keel tick" not in reminder:
691
+ report(f"{label} with runner: tick the projection does not name keel tick: {reminder!r}")
692
+ return 1
693
+ if "tick-runs-due-patrol" not in {name for name, _ in registry.SCENARIOS}:
694
+ report(f"{label} scenario is not registered.")
695
+ return 1
696
+ report("tick-runs-due-patrol scenario passed.")
697
+ return 0
698
+
699
+
700
+ def validate_patrol_nudge_scenario() -> int:
701
+ """Issues #307 part 1 and #313: the patrol nudges idle roles directly.
702
+
703
+ Addressed unread records nudge once per window; a closed todo nudges a
704
+ shift change at that task boundary, naming `--wake` only while another
705
+ todo is open; a self-initiated note nudges a resume; a parked note and
706
+ the patrol's own messages never do; context is no longer an input.
707
+ """
708
+ label = "patrol-nudge:"
709
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-nudge-") as raw:
710
+ base = Path(raw)
711
+ rtl, verify, env, _ = shift_scratch(base)
712
+ env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "1"}
713
+ lint = chat_worktree(rtl, base / "lint")
714
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=lint, check=True, capture_output=True)
715
+ run_keel(lint, "chat", "role", "--set", "lint", env=env)
716
+ run_keel(rtl, "chat", "group", "add", "soc", "lint", env=env)
717
+ todo_ids = []
718
+ for text in ("R009 timing fix", "R010 lint cleanup"):
719
+ made = run_keel(rtl, "chat", "todo", "soc", "--assignee", "lint", text, "--json", env=env)
720
+ todo_ids.append(json.loads(made.stdout)["id"])
721
+ run_keel(lint, "chat", "read", env=env)
722
+ run_keel(rtl, "chat", "post", "soc", "@verify please rerun R007", env=env)
723
+ time.sleep(1.2)
724
+
725
+ def nudge(*args: str) -> subprocess.CompletedProcess[str]:
726
+ return run_keel(rtl, "patrol", "--nudge", "--idle", "1s", *args, env=env)
727
+
728
+ def nudged(result: subprocess.CompletedProcess[str]) -> list[str]:
729
+ return [line for line in result.stdout.splitlines() if line.startswith("nudged ")]
730
+
731
+ def told_lint(needle: str) -> str:
732
+ return "\n".join(chat_records_with(rtl, "dm-keel-patrol--lint", needle))
733
+
734
+ seen: list[str] = []
735
+ first = nudge()
736
+ seen += nudged(first)
737
+ if "nudged verify: unread" not in nudged(first):
738
+ report(f"{label} verify was not nudged for unread: {first.stdout!r} {first.stderr!r}")
739
+ return 1
740
+ if any(line.startswith("nudged lint") for line in nudged(first)):
741
+ report(f"{label} lint was nudged before any task closed: {nudged(first)!r}")
742
+ return 1
743
+ if first.returncode != 3:
744
+ report(f"{label} a run that nudged exited {first.returncode}, not 3.")
745
+ return 1
746
+ if run_keel(verify, "chat", "notice", "--check", env=env).returncode != 0:
747
+ report(f"{label} the nudge does not wake verify.")
748
+ return 1
749
+ run_keel(lint, "chat", "done", todo_ids[0], env=env)
750
+ time.sleep(1.2)
751
+ second = nudge()
752
+ seen += nudged(second)
753
+ if nudged(second) != ["nudged lint: shift"]:
754
+ report(f"{label} closing a todo should nudge only lint's shift: {second.stdout!r} {second.stderr!r}")
755
+ return 1
756
+ if "keel shift ready --wake" not in told_lint("R009"):
757
+ report(f"{label} with a todo still open, the shift nudge does not name ready --wake: {told_lint('R009')!r}")
758
+ return 1
759
+ if "Remote Control" not in told_lint("R009"):
760
+ report(f"{label} the shift nudge does not name Remote Control.")
761
+ return 1
762
+ time.sleep(1.2)
763
+ third = nudge()
764
+ seen += nudged(third)
765
+ if nudged(third):
766
+ report(f"{label} a run with nothing new nudged: {nudged(third)!r}")
767
+ return 1
768
+ if third.returncode != 0:
769
+ report(f"{label} a run that nudged nobody exited {third.returncode}.")
770
+ return 1
771
+ run_keel(lint, "chat", "done", todo_ids[1], env=env)
772
+ time.sleep(1.2)
773
+ fourth = nudge()
774
+ seen += nudged(fourth)
775
+ if "nudged lint: shift" not in nudged(fourth):
776
+ report(f"{label} closing the last todo did not nudge lint: {fourth.stdout!r}")
777
+ return 1
778
+ last = told_lint("R010")
779
+ if "wait for the coordinator" not in last:
780
+ report(f"{label} with no todo left, the shift nudge does not say to wait for the coordinator: {last!r}")
781
+ return 1
782
+ if "--wake" in last:
783
+ report(f"{label} with no todo left, the shift nudge still names --wake: {last!r}")
784
+ return 1
785
+ armed = run_keel(lint, "shift", "ready", "--wake", "lint note", env=env)
786
+ if armed.returncode != 0:
787
+ report(f"{label} lint's ready --wake failed: {armed.stderr}")
788
+ return 1
789
+ if run_keel(verify, "shift", "ready", "--force-reason", "parked by the coordinator", "verify parked", env=env).returncode != 0:
790
+ report(f"{label} verify's ready failed.")
791
+ return 1
792
+ time.sleep(1.2)
793
+ fifth = nudge()
794
+ seen += nudged(fifth)
795
+ if "nudged lint: resume" not in nudged(fifth):
796
+ report(f"{label} lint's self-initiated note was not nudged to resume: {fifth.stdout!r}")
797
+ return 1
798
+ if "nudged verify: resume" in nudged(fifth):
799
+ report(f"{label} verify's parked note was nudged to resume.")
800
+ return 1
801
+ if "nudged lint: unread" in seen:
802
+ report(f"{label} lint was nudged over the patrol's own message.")
803
+ return 1
804
+ retired = nudge("--context", "lint=62")
805
+ if retired.returncode != 1:
806
+ report(f"{label} --context exited {retired.returncode}.")
807
+ return 1
808
+ if "retired" not in retired.stderr:
809
+ report(f"{label} the --context refusal does not say it was retired: {retired.stderr!r}")
810
+ return 1
811
+ report("patrol-nudge scenario passed.")
812
+ return 0
813
+
814
+
815
+ def validate_patrol_escalate_scenario() -> int:
816
+ """Issue #307 part 3: only risks reach the coordinator; every run is logged."""
817
+ label = "patrol-escalate:"
818
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-escalate-") as raw:
819
+ base = Path(raw)
820
+ rtl, verify, env, _ = shift_scratch(base)
821
+ env = {**env, "KEEL_PATROL_UNREAD_EVERY_MS": "1"}
822
+ runs = 0
823
+
824
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
825
+ nonlocal runs
826
+ runs += 1
827
+ return run_keel(rtl, "patrol", "--since-last", "--notify", "--idle", "1s", *args, env=env)
828
+
829
+ def sent(needle: str) -> int:
830
+ return len(chat_records_with(rtl, "dm-keel-patrol--rtl", needle))
831
+
832
+ patrol()
833
+ write_text(rtl / "dirty.txt", "left behind\n")
834
+ dirty = patrol()
835
+ if sent("uncommitted") != 1:
836
+ report(f"{label} the dirty checkout was not sent once: {dirty.stdout!r} {dirty.stderr!r}")
837
+ return 1
838
+ if not any(line.startswith("risk:") for line in dirty.stdout.splitlines()):
839
+ report(f"{label} the risk is not printed: {dirty.stdout!r}")
840
+ return 1
841
+ patrol("--disk-free-gb", "12")
842
+ if sent("free disk is 12 GB") != 1:
843
+ report(f"{label} low disk was not sent once.")
844
+ return 1
845
+ patrol("--disk-free-gb", "12")
846
+ if sent("free disk") != 1:
847
+ report(f"{label} low disk was sent again without changing.")
848
+ return 1
849
+ if sent("uncommitted") != 1:
850
+ report(f"{label} the still-dirty checkout was sent again.")
851
+ return 1
852
+ run_keel(rtl, "chat", "post", "soc", "@verify rerun R007 please", env=env)
853
+ time.sleep(1.2)
854
+ patrol("--nudge")
855
+ time.sleep(0.2)
856
+ second = patrol("--nudge")
857
+ if sent("2 nudges") != 1:
858
+ report(f"{label} two unanswered nudges were not escalated once: {second.stdout!r}")
859
+ return 1
860
+ if "verify" not in "\n".join(chat_records_with(rtl, "dm-keel-patrol--rtl", "2 nudges")):
861
+ report(f"{label} the escalation does not name verify.")
862
+ return 1
863
+ log = mailbox_common_dir(rtl) / "keel-chat" / "patrol" / "log" / "rtl.log"
864
+ lines = log.read_text(encoding="utf-8").splitlines() if log.exists() else []
865
+ if len(lines) != runs:
866
+ report(f"{label} the run log holds {len(lines)} lines for {runs} runs.")
867
+ return 1
868
+ if not all("exit=" in line and "risks=" in line for line in lines):
869
+ report(f"{label} a run log line lacks exit= or risks=: {lines!r}")
870
+ return 1
871
+ report("patrol-escalate scenario passed.")
872
+ return 0
873
+
874
+
875
+ def validate_patrol_quota_scenario() -> int:
876
+ """Issue #307 part 2: quota thresholds once per period; nudges pause near the limit."""
877
+ label = "patrol-quota:"
878
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-quota-") as raw:
879
+ base = Path(raw)
880
+ rtl, verify, env, _ = shift_scratch(base)
881
+ env = {**env, "KEEL_PATROL_UNREAD_EVERY_MS": "1"}
882
+ run_keel(rtl, "chat", "post", "soc", "@verify rerun R007 please", env=env)
883
+ time.sleep(1.2)
884
+
885
+ def patrol(quota: str) -> subprocess.CompletedProcess[str]:
886
+ return run_keel(rtl, "patrol", "--since-last", "--notify", "--nudge", "--idle", "1s", "--quota", quota, env=env)
887
+
888
+ expected = {"50": None, "91": "past 90%", "93": None, "96": "past 95%", "10": None, "92": "past 90%"}
889
+ for quota, want in expected.items():
890
+ result = patrol(quota)
891
+ lines = [line for line in result.stdout.splitlines() if line.startswith("risk: weekly quota")]
892
+ if want is None and lines:
893
+ report(f"{label} quota {quota} reported {lines!r}.")
894
+ return 1
895
+ if want is not None and len(lines) != 1:
896
+ report(f"{label} quota {quota} should report one quota line: {result.stdout!r} {result.stderr!r}")
897
+ return 1
898
+ if want is not None and want not in lines[0]:
899
+ report(f"{label} quota {quota} should report {want!r}: {lines[0]!r}")
900
+ return 1
901
+ if quota == "50" and "nudged verify: unread" not in result.stdout:
902
+ report(f"{label} verify was not nudged at 50%: {result.stdout!r}")
903
+ return 1
904
+ if quota == "91" and "nudged verify" in result.stdout:
905
+ report(f"{label} verify was nudged at 91%: {result.stdout!r}")
906
+ return 1
907
+ if quota == "91" and "nudges paused: quota at 91%" not in result.stdout:
908
+ report(f"{label} the pause is not said at 91%: {result.stdout!r}")
909
+ return 1
910
+ sent = chat_records_with(rtl, "dm-keel-patrol--rtl", "weekly quota")
911
+ if len(sent) != 3:
912
+ report(f"{label} expected three quota messages to rtl, found {len(sent)}.")
913
+ return 1
914
+ refused = run_keel(rtl, "patrol", "--quota", "120", env=env)
915
+ if refused.returncode != 1:
916
+ report(f"{label} --quota 120 exited {refused.returncode}.")
917
+ return 1
918
+ report("patrol-quota scenario passed.")
919
+ return 0
920
+
921
+
922
+ def validate_coordinator_patrol_scenario() -> int:
923
+ """Issue #260: declared waits, and a patrol that notifies once.
924
+
925
+ `keel chat wait` records what a role waits for; `keel patrol` marks a held
926
+ condition met and direct-messages the waiter, writes nothing when nothing
927
+ holds, and exits 0 (quiet), 2 (wrote), or 1 (error).
928
+ """
929
+ label = "coordinator-patrol:"
930
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-") as raw:
931
+ base = Path(raw)
932
+ rtl, verify, env = chat_scratch_group(base)
933
+ origin = base / "origin.git"
934
+ subprocess.run(["git", "init", "-q", "--bare", str(origin)], check=True, capture_output=True)
935
+ for args in (["remote", "add", "origin", str(origin)], ["push", "-q", "origin", "main"],
936
+ ["switch", "-q", "-c", "feature"], ["commit", "-q", "--allow-empty", "-m", "fix"]):
937
+ subprocess.run(["git", *args], cwd=rtl, check=True, capture_output=True)
938
+ sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=rtl, check=True, capture_output=True, text=True).stdout.strip()
939
+
940
+ def chat(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
941
+ return run_keel(cwd, "chat", *args, env=env)
942
+
943
+ def patrol(*args: str) -> subprocess.CompletedProcess[str]:
944
+ return run_keel(rtl, "patrol", *args, env=env)
945
+
946
+ waited = chat(verify, "wait", "soc", "--commit", sha, "rerun R007 when the fix lands")
947
+ if waited.returncode != 0:
948
+ report(f"{label} keel chat wait failed: {waited.stdout} {waited.stderr}")
949
+ return 1
950
+ waits = chat_json(chat(rtl, "waits", "--json")).get("waits", [])
951
+ if [(w.get("from"), w.get("condition")) for w in waits] != [("verify", f"commit {sha} on origin")]:
952
+ report(f"{label} waits lists {waits!r}.")
953
+ return 1
954
+ if chat_json(chat(rtl, "unread", "--json")).get("unread"):
955
+ report(f"{label} a wait left rtl something unread.")
956
+ return 1
957
+ for what, result in (
958
+ ("no condition", chat(verify, "wait", "soc")),
959
+ ("both conditions", chat(verify, "wait", "soc", "--commit", sha, "--issue", "42", "--closed")),
960
+ ):
961
+ if result.returncode == 0:
962
+ report(f"{label} a wait with {what} was accepted.")
963
+ return 1
964
+ if "--commit" not in result.stderr or "--issue" not in result.stderr:
965
+ report(f"{label} a wait with {what} was refused without naming both forms: {result.stderr}")
966
+ return 1
967
+
968
+ before = chat_logs_snapshot(rtl)
969
+ quiet = patrol()
970
+ if quiet.returncode != 0:
971
+ report(f"{label} patrol before the push exited {quiet.returncode}: {quiet.stdout} {quiet.stderr}")
972
+ return 1
973
+ if chat_logs_snapshot(rtl) != before:
974
+ report(f"{label} a quiet patrol wrote to the chat.")
975
+ return 1
976
+ if "verify" not in quiet.stdout:
977
+ report(f"{label} the digest does not list verify: {quiet.stdout!r}")
978
+ return 1
979
+
980
+ subprocess.run(["git", "push", "-q", "origin", "feature"], cwd=rtl, check=True, capture_output=True)
981
+ landed = patrol()
982
+ if landed.returncode != 3:
983
+ report(f"{label} patrol after the push exited {landed.returncode}, not 3: {landed.stdout} {landed.stderr}")
984
+ return 1
985
+ if chat_json(chat(rtl, "waits", "--json")).get("waits"):
986
+ report(f"{label} the met wait is still listed.")
987
+ return 1
988
+ texts = [r.get("text", "") for r in chat_json(chat(verify, "unread", "--json")).get("unread", [])]
989
+ if not any(sha[:7] in text for text in texts):
990
+ report(f"{label} verify has no unread message naming the commit: {texts!r}")
991
+ return 1
992
+ before = chat_logs_snapshot(rtl)
993
+ again = patrol()
994
+ if again.returncode != 0:
995
+ report(f"{label} a second patrol exited {again.returncode}, not 0.")
996
+ return 1
997
+ if chat_logs_snapshot(rtl) != before:
998
+ report(f"{label} a second patrol wrote again.")
999
+ return 1
1000
+
1001
+ chat(verify, "wait", "soc", "--issue", "42", "--closed")
1002
+ unchecked = patrol()
1003
+ if unchecked.returncode != 0:
1004
+ report(f"{label} patrol without --issues exited {unchecked.returncode}, not 0.")
1005
+ return 1
1006
+ if "unchecked" not in unchecked.stdout:
1007
+ report(f"{label} patrol without --issues does not report the issue wait unchecked: {unchecked.stdout!r}")
1008
+ return 1
1009
+ issues = base / "issues.json"
1010
+ issues.write_text(json.dumps([{"number": 42, "title": "clock fix", "state": "CLOSED", "labels": [], "updatedAt": "2026-10-11T00:00:00Z"}]), encoding="utf-8")
1011
+ closed = patrol("--issues", str(issues))
1012
+ if closed.returncode != 3:
1013
+ report(f"{label} patrol with issue 42 closed exited {closed.returncode}, not 3: {closed.stdout} {closed.stderr}")
1014
+ return 1
1015
+ report("coordinator-patrol scenario passed.")
1016
+ return 0
1017
+
1018
+
1019
+ def validate_patrol_issue_routing_scenario() -> int:
1020
+ """Issue #242: `issue_roles:` routes each labelled issue update once.
1021
+
1022
+ The label's role gets one direct message per `updatedAt`, deduped against
1023
+ the chat; an unreadable line is reported and routes nothing.
1024
+ """
1025
+ label = "patrol-issue-routing:"
1026
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-issues-") as raw:
1027
+ base = Path(raw)
1028
+ rtl, verify, env = chat_scratch_group(base)
1029
+ write_authorize_config(rtl, "issue_roles:\n role:verify: verify\n this line has no role\n")
1030
+ issues = base / "issues.json"
1031
+
1032
+ def patrol(updated: str) -> subprocess.CompletedProcess[str]:
1033
+ issues.write_text(json.dumps([{
1034
+ "number": 157, "title": "rerun on new commit", "state": "OPEN",
1035
+ "labels": [{"name": "role:verify"}], "updatedAt": updated,
1036
+ }]), encoding="utf-8")
1037
+ return run_keel(rtl, "patrol", "--issues", str(issues), env=env)
1038
+
1039
+ def notices() -> list:
1040
+ return [r.get("text", "") for r in chat_json(run_keel(verify, "chat", "unread", "--json", env=env)).get("unread", []) if "#157" in r.get("text", "")]
1041
+
1042
+ first = patrol("2026-10-11T01:00:00Z")
1043
+ if first.returncode != 3:
1044
+ report(f"{label} the first patrol exited {first.returncode}, not 3: {first.stdout} {first.stderr}")
1045
+ return 1
1046
+ if len(notices()) != 1:
1047
+ report(f"{label} verify has {len(notices())} notices about #157, not 1.")
1048
+ return 1
1049
+ if "this line has no role" not in first.stdout:
1050
+ report(f"{label} the unreadable issue_roles line is not reported: {first.stdout!r}")
1051
+ return 1
1052
+ before = chat_logs_snapshot(rtl)
1053
+ same = patrol("2026-10-11T01:00:00Z")
1054
+ if same.returncode != 0:
1055
+ report(f"{label} the same update exited {same.returncode}, not 0.")
1056
+ return 1
1057
+ if chat_logs_snapshot(rtl) != before:
1058
+ report(f"{label} the same update was sent again.")
1059
+ return 1
1060
+ later = patrol("2026-10-11T02:00:00Z")
1061
+ if later.returncode != 3:
1062
+ report(f"{label} a later update exited {later.returncode}, not 3.")
1063
+ return 1
1064
+ if len(notices()) != 2:
1065
+ report(f"{label} a later update left {len(notices())} notices, not 2.")
1066
+ return 1
1067
+ report("patrol-issue-routing scenario passed.")
1068
+ return 0
1069
+
1070
+
1071
+ def validate_worktree_overview_scenario() -> int:
1072
+ """Read every worktree through the CLI without fetching or changing chat."""
1073
+ label = "worktree-overview:"
1074
+ with tempfile.TemporaryDirectory(prefix="keel-worktree-overview-") as raw:
1075
+ base = Path(raw).resolve()
1076
+ repo, remote = base / "repo", base / "remote.git"
1077
+ repo.mkdir()
1078
+ env = os.environ.copy()
1079
+ env.pop("KEEL_CHAT_ROLE", None)
1080
+ env.pop("KEEL_MAIL_ROLE", None)
1081
+
1082
+ def git(*args: str, cwd: Path = repo) -> str:
1083
+ return subprocess.run(
1084
+ ["git", *args], cwd=cwd, env=env, check=True,
1085
+ capture_output=True, text=True,
1086
+ ).stdout.strip()
1087
+
1088
+ git("init", "-q", "-b", "main")
1089
+ git("config", "user.email", "test@example.invalid")
1090
+ git("config", "user.name", "Worktree test")
1091
+ (repo / "seed").write_text("base\n", encoding="utf-8")
1092
+ git("add", "seed")
1093
+ git("commit", "-qm", "base #99")
1094
+ git("init", "--bare", "-q", str(remote))
1095
+ git("remote", "add", "origin", str(remote))
1096
+ git("push", "-qu", "origin", "main")
1097
+ git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
1098
+ a, b, gone = base / "a", base / "b", base / "gone"
1099
+ git("worktree", "add", "-qb", "feature", str(a), "main")
1100
+ git("branch", "--set-upstream-to=origin/main", "feature")
1101
+ (a / "feature").write_text("feature\n", encoding="utf-8")
1102
+ git("add", "feature", cwd=a)
1103
+ git("commit", "-qm", "feature #12", "-m", "References #12 again", cwd=a)
1104
+ git("worktree", "add", "-q", "--detach", str(b), "main")
1105
+ (b / "uncommitted").write_text("dirty\n", encoding="utf-8")
1106
+ git("worktree", "add", "-q", "--detach", str(gone), "main")
1107
+ git("worktree", "lock", "--reason", "test lock", str(a))
1108
+ shutil.rmtree(gone)
1109
+ bound = run_keel(a, "chat", "role", "--set", "pm", env=env)
1110
+ if bound.returncode != 0:
1111
+ report(f"{label} could not bind pm: {bound.stderr}")
1112
+ return 1
1113
+ chat = Path(git("rev-parse", "--path-format=absolute", "--git-common-dir")) / "keel-chat"
1114
+ stamp = datetime.now(timezone.utc).isoformat()
1115
+ write_text(chat / "presence" / "pm.json", json.dumps({"state": "online", "last_active": stamp}))
1116
+
1117
+ def snapshot() -> dict[str, bytes]:
1118
+ return {str(file.relative_to(chat)): file.read_bytes()
1119
+ for file in chat.rglob("*") if file.is_file()}
1120
+
1121
+ before = snapshot()
1122
+ repository_before = {str(file.relative_to(repo)): file.read_bytes()
1123
+ for file in repo.rglob("*") if file.is_file()}
1124
+
1125
+ def overview(*args: str) -> subprocess.CompletedProcess[str]:
1126
+ # An override for the invoking session must not bind every worktree.
1127
+ return run_keel(b, "worktrees", "--repo", str(repo), *args,
1128
+ env={**env, "KEEL_CHAT_ROLE": "caller"})
1129
+
1130
+ result = overview("--json")
1131
+ if result.returncode != 0:
1132
+ report(f"{label} --json failed: {result.stderr}")
1133
+ return 1
1134
+ try:
1135
+ payload = json.loads(result.stdout)
1136
+ rows = {row["path"]: row for row in payload["worktrees"]}
1137
+ except (ValueError, KeyError, TypeError):
1138
+ report(f"{label} --json lacks worktree data: {result.stdout}")
1139
+ return 1
1140
+ if set(rows) != {str(repo), str(a), str(b), str(gone)}:
1141
+ report(f"{label} did not list every worktree: {rows}")
1142
+ return 1
1143
+ for tree, expected in (
1144
+ (a, {"branch": "feature", "ahead": 1, "behind": 0, "issues": [12],
1145
+ "role": "pm", "upstream": "origin/main", "dirty": 0,
1146
+ "locked": "test lock", "prunable": None}),
1147
+ (b, {"branch": None, "dirty": 1, "role": None, "presence": None,
1148
+ "ahead": None, "behind": None, "upstream": None, "issues": []}),
1149
+ (gone, {"missing": True}),
1150
+ ):
1151
+ for key, value in expected.items():
1152
+ if rows[str(tree)].get(key) != value:
1153
+ report(f"{label} {tree.name}'s {key} differs: {rows[str(tree)]}")
1154
+ return 1
1155
+ if rows[str(a)].get("presence") != {"state": "online", "last_active": stamp}:
1156
+ report(f"{label} a's presence differs: {rows[str(a)]}")
1157
+ return 1
1158
+ for tree in (repo, a, b):
1159
+ row = rows[str(tree)]
1160
+ if row.get("head") != git("rev-parse", "--short", "HEAD", cwd=tree):
1161
+ report(f"{label} {tree.name}'s short head differs: {row}")
1162
+ return 1
1163
+ expected_commit = {"subject": git("log", "-1", "--format=%s", cwd=tree),
1164
+ "time": git("log", "-1", "--format=%cI", cwd=tree)}
1165
+ if row.get("lastCommit") != expected_commit:
1166
+ report(f"{label} {tree.name}'s last commit differs: {row}")
1167
+ return 1
1168
+ if not rows[str(gone)].get("prunable"):
1169
+ report(f"{label} missing worktree lacks Git's prunable marker: {rows[str(gone)]}")
1170
+ return 1
1171
+ text = overview()
1172
+ if text.returncode != 0:
1173
+ report(f"{label} text output failed: {text.stderr}")
1174
+ return 1
1175
+ for needle in ("main", "as of the last fetch", str(a), str(b), str(gone), "missing"):
1176
+ if needle not in text.stdout:
1177
+ report(f"{label} text output lacks {needle!r}: {text.stdout}")
1178
+ return 1
1179
+ issues = base / "issues.json"
1180
+ updated = "2026-10-05T08:00:00Z"
1181
+ write_text(issues, json.dumps([{"number": 12, "updatedAt": updated}]))
1182
+ timed = overview("--issues", str(issues), "--json")
1183
+ if timed.returncode != 0:
1184
+ report(f"{label} passed issues file failed: {timed.stderr}")
1185
+ return 1
1186
+ timed_rows = {row["path"]: row for row in json.loads(timed.stdout)["worktrees"]}
1187
+ if timed_rows[str(a)].get("issueUpdates") != [{"number": 12, "updatedAt": updated}]:
1188
+ report(f"{label} issue 12 does not carry the passed updatedAt: {timed.stdout}")
1189
+ return 1
1190
+ timed_text = overview("--issues", str(issues))
1191
+ if updated not in timed_text.stdout:
1192
+ report(f"{label} text output lacks issue 12's passed time: {timed_text.stdout}")
1193
+ return 1
1194
+ write_text(issues, "[]")
1195
+ absent = overview("--issues", str(issues), "--json")
1196
+ if absent.returncode != 0:
1197
+ report(f"{label} empty issue array failed: {absent.stderr}")
1198
+ return 1
1199
+ absent_rows = {row["path"]: row for row in json.loads(absent.stdout)["worktrees"]}
1200
+ if absent_rows[str(a)].get("issueUpdates") != [{"number": 12, "updatedAt": None}]:
1201
+ report(f"{label} absent issue time is not null: {absent.stdout}")
1202
+ return 1
1203
+ bad = base / "bad.json"
1204
+ for content in ("not JSON", "{}", '[{"number": 12}]'):
1205
+ write_text(bad, content)
1206
+ refused = overview("--issues", str(bad))
1207
+ if refused.returncode != 1:
1208
+ report(f"{label} malformed --issues did not exit 1: {refused.returncode}")
1209
+ return 1
1210
+ if str(bad) not in refused.stderr:
1211
+ report(f"{label} malformed --issues does not name the file: {refused.stderr}")
1212
+ return 1
1213
+ if refused.stdout:
1214
+ report(f"{label} malformed --issues printed partial output: {refused.stdout}")
1215
+ return 1
1216
+ missing = base / "missing.json"
1217
+ refused = overview("--issues", str(missing))
1218
+ if refused.returncode != 1:
1219
+ report(f"{label} missing --issues did not exit 1: {refused.returncode}")
1220
+ return 1
1221
+ if str(missing) not in refused.stderr:
1222
+ report(f"{label} missing --issues does not name the file: {refused.stderr}")
1223
+ return 1
1224
+ if refused.stdout:
1225
+ report(f"{label} missing --issues printed partial output: {refused.stdout}")
1226
+ return 1
1227
+ if snapshot() != before:
1228
+ report(f"{label} the chat store's files changed")
1229
+ return 1
1230
+ repository_after = {str(file.relative_to(repo)): file.read_bytes()
1231
+ for file in repo.rglob("*") if file.is_file()}
1232
+ if repository_after != repository_before:
1233
+ report(f"{label} the repository's files changed (including Git indexes and refs)")
1234
+ return 1
1235
+ report(f"{label} scenario passed")
1236
+ return 0
1237
+
1238
+
1239
+ def validate_shift_resume_checks_commits_scenario() -> int:
1240
+ """Issue #347: a shift note's commit ids go stale before the next shift reads it.
1241
+
1242
+ `keel shift resume` lists each commit id and `<branch> @ <sha>` the note
1243
+ names, checked against the remote-tracking refs as of the last fetch:
1244
+ already in the default branch, branch moved, branch gone, or not found.
1245
+ It fetches nothing.
1246
+ """
1247
+ label = "shift-resume-checks-commits:"
1248
+ with tempfile.TemporaryDirectory(prefix="keel-shift-347-") as raw:
1249
+ base = Path(raw)
1250
+ rtl, verify, env, _ = shift_scratch(base)
1251
+
1252
+ def git(*args: str) -> str:
1253
+ return subprocess.run(["git", *args], cwd=rtl, text=True, capture_output=True, check=True).stdout.strip()
1254
+
1255
+ git("commit", "-q", "--allow-empty", "-m", "landed")
1256
+ git("push", "-q", "origin", "HEAD")
1257
+ landed = git("rev-parse", "HEAD")
1258
+ default = git("rev-parse", "--abbrev-ref", "HEAD")
1259
+ tree = git("rev-parse", "HEAD^{tree}")
1260
+ old = git("commit-tree", tree, "-p", landed, "-m", "feat one")
1261
+ git("push", "-q", "origin", f"{old}:refs/heads/feat")
1262
+ new = git("commit-tree", tree, "-p", old, "-m", "feat two")
1263
+ git("push", "-q", "origin", f"{new}:refs/heads/feat")
1264
+ note = (f"A84 {landed[:8]} is waiting to be merged. feat @ {old[:8]} waits for the push window. "
1265
+ f"gone-branch @ {landed[:8]} too. deadbee1 was the old base. Dated 20261018.")
1266
+ readied = run_keel(verify, "shift", "ready", note, env=env)
1267
+ if readied.returncode != 0:
1268
+ report(f"{label} ready failed: {readied.stderr}")
1269
+ return 1
1270
+ resumed = run_keel(verify, "shift", "resume", env=env)
1271
+ if resumed.returncode != 0:
1272
+ report(f"{label} resume failed: {resumed.stderr}")
1273
+ return 1
1274
+ lines = resumed.stdout.splitlines()
1275
+
1276
+ def line_for(token: str) -> str:
1277
+ return next((l for l in lines if l.lstrip().startswith(("- " + token, token))), "")
1278
+
1279
+ checks = (
1280
+ (landed[:8], f"already in origin/{default}"),
1281
+ (f"feat @ {old[:8]}", f"branch moved: now {new[:8]}"),
1282
+ (f"gone-branch @ {landed[:8]}", "branch gone"),
1283
+ ("deadbee1", "not found"),
1284
+ )
1285
+ for token, want in checks:
1286
+ found = line_for(token)
1287
+ if want not in found:
1288
+ report(f"{label} {token!r} is not marked {want!r}: {found!r} in {resumed.stdout!r}")
1289
+ return 1
1290
+ if line_for("20261018"):
1291
+ report(f"{label} a date was read as a commit id: {resumed.stdout!r}")
1292
+ return 1
1293
+
1294
+ # A short sha can be all digits (about 2% of them): one named after `@`,
1295
+ # or one that resolves to a commit, is still a commit id.
1296
+ digits, n = "", 0
1297
+ while not digits:
1298
+ n += 1
1299
+ candidate = git("commit-tree", tree, "-p", landed, "-m", f"digits {n}")
1300
+ if candidate[:8].isdigit():
1301
+ digits = candidate
1302
+ git("push", "-q", "origin", f"{digits}:refs/heads/digits-branch")
1303
+ run_keel(verify, "shift", "ready", f"digits-branch @ {digits[:8]} is the tip. Also see {digits[:8]}.", env=env)
1304
+ again = run_keel(verify, "shift", "resume", env=env).stdout.splitlines()
1305
+ pair = next((l for l in again if l.startswith(f"- digits-branch @ {digits[:8]}")), "")
1306
+ if "current" not in pair:
1307
+ report(f"{label} an all-digit sha after `@` is not marked current: {pair!r} in {again!r}")
1308
+ return 1
1309
+ if not any(l.startswith(f"- {digits[:8]}:") for l in again):
1310
+ report(f"{label} an all-digit sha that resolves to a commit is not listed: {again!r}")
1311
+ return 1
1312
+ if "not fetched" not in resumed.stdout:
1313
+ report(f"{label} the check does not say it did not fetch: {resumed.stdout!r}")
1314
+ return 1
1315
+ if "shift-resume-checks-commits" not in {name for name, _ in registry.SCENARIOS}:
1316
+ report(f"{label} scenario is not registered.")
1317
+ return 1
1318
+ report("shift-resume-checks-commits scenario passed.")
1319
+ return 0
1320
+
1321
+
1322
+ def validate_shift_role_elsewhere_scenario() -> int:
1323
+ """Issues #290, #291: a note filed under the role from another worktree.
1324
+
1325
+ `ready --role` files it under the role; an unbound worktree refuses to
1326
+ misfile while role requests are open; status names what works for a
1327
+ worktree note.
1328
+ """
1329
+ label = "shift-role-elsewhere:"
1330
+ with tempfile.TemporaryDirectory(prefix="keel-shift-elsewhere-") as raw:
1331
+ base = Path(raw)
1332
+ rtl, verify, env, _ = shift_scratch(base)
1333
+ loose = chat_worktree(rtl, base / "loose")
1334
+ loose2 = chat_worktree(rtl, base / "loose2")
1335
+ for tree in (loose, loose2):
1336
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
1337
+
1338
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
1339
+ return run_keel(cwd, "shift", *args, env=env)
1340
+
1341
+ shift(rtl, "request", "verify")
1342
+ common = mailbox_common_dir(rtl) / "keel-chat" / "shift"
1343
+ misfiled = shift(loose, "ready", "worked on R008 here")
1344
+ if misfiled.returncode == 0:
1345
+ report(f"{label} ready in an unbound worktree with verify's request open was accepted.")
1346
+ return 1
1347
+ if "--role verify" not in misfiled.stderr:
1348
+ report(f"{label} the refusal does not name --role verify: {misfiled.stderr}")
1349
+ return 1
1350
+ if list((common / "worktree").glob("*.md")) if (common / "worktree").exists() else []:
1351
+ report(f"{label} a refused ready still wrote a worktree note.")
1352
+ return 1
1353
+ wrong = shift(loose, "ready", "--role", "rtl", "x")
1354
+ if wrong.returncode == 0:
1355
+ report(f"{label} ready --role rtl, which has no open request, was accepted.")
1356
+ return 1
1357
+ filed = shift(loose, "ready", "--role", "verify", "worked on R008 in loose")
1358
+ if filed.returncode != 0:
1359
+ report(f"{label} ready --role verify failed: {filed.stdout} {filed.stderr}")
1360
+ return 1
1361
+ if not (common / "verify.md").exists():
1362
+ report(f"{label} ready --role verify did not file the note under verify.")
1363
+ return 1
1364
+ started = shift(rtl, "start", "verify")
1365
+ if started.returncode != 0:
1366
+ report(f"{label} keel shift start verify was refused: {started.stderr}")
1367
+ return 1
1368
+ lone = shift(loose2, "ready", "--force-reason", "the coordinator opens it", "nothing requested here")
1369
+ if lone.returncode != 0:
1370
+ report(f"{label} ready in an unbound worktree with no open request failed: {lone.stderr}")
1371
+ return 1
1372
+ status = shift(rtl, "status").stdout
1373
+ line = next((l for l in status.splitlines() if "loose2" in l), "")
1374
+ if str(loose2.resolve()) not in line or "keel shift resume" not in line:
1375
+ report(f"{label} the worktree note's status line does not name its path and keel shift resume: {line!r}")
1376
+ return 1
1377
+ if "keel shift start worktree" in status:
1378
+ report(f"{label} status still suggests keel shift start for a worktree note: {status!r}")
1379
+ return 1
1380
+ report("shift-role-elsewhere scenario passed.")
1381
+ return 0
1382
+
1383
+
1384
+ def validate_shift_self_scenario() -> int:
1385
+ """Issue #293: a role with no coordinator changes its own shift.
1386
+
1387
+ It cannot start itself, `ready` says nobody will start the new session,
1388
+ status says its own next session resumes the note, and a new session in
1389
+ an unbound worktree resumes it with `--role`.
1390
+ """
1391
+ label = "shift-self:"
1392
+ with tempfile.TemporaryDirectory(prefix="keel-shift-self-") as raw:
1393
+ base = Path(raw)
1394
+ rtl, _verify, env, _ = shift_scratch(base)
1395
+ pm = chat_worktree(rtl, base / "pm")
1396
+ other = chat_worktree(rtl, base / "other")
1397
+ for tree in (pm, other):
1398
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
1399
+ run_keel(pm, "chat", "role", "--set", "pm", env=env)
1400
+
1401
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
1402
+ return run_keel(cwd, "shift", *args, env=env)
1403
+
1404
+ readied = shift(pm, "ready", "pm note: next is R009")
1405
+ if readied.returncode != 0:
1406
+ report(f"{label} pm's ready failed: {readied.stderr}")
1407
+ return 1
1408
+ if "nobody" not in readied.stdout:
1409
+ report(f"{label} ready does not say nobody is set to start the new session: {readied.stdout!r}")
1410
+ return 1
1411
+ if "--wake" not in readied.stdout:
1412
+ report(f"{label} ready does not name --wake: {readied.stdout!r}")
1413
+ return 1
1414
+ if "The coordinator's `keel shift start` then wakes" in readied.stdout:
1415
+ report(f"{label} ready still promises a coordinator's start to a role nobody asked: {readied.stdout!r}")
1416
+ return 1
1417
+ itself = shift(pm, "start", "pm")
1418
+ if itself.returncode == 0:
1419
+ report(f"{label} keel shift start pm by pm was accepted.")
1420
+ return 1
1421
+ if "ready --wake" not in itself.stderr:
1422
+ report(f"{label} the refusal does not name ready --wake: {itself.stderr}")
1423
+ return 1
1424
+ if chat_log(rtl, "dm-pm--pm").exists():
1425
+ report(f"{label} a refused self-start still created dm-pm--pm.")
1426
+ return 1
1427
+ status = shift(rtl, "status").stdout
1428
+ line = next((l for l in status.splitlines() if l.startswith("pm:")), "")
1429
+ if "own next session" not in line:
1430
+ report(f"{label} status does not say pm's own next session resumes its note: {line!r}")
1431
+ return 1
1432
+ misbound = shift(rtl, "resume", "--role", "pm")
1433
+ if misbound.returncode == 0:
1434
+ report(f"{label} resume --role pm in rtl's worktree was accepted.")
1435
+ return 1
1436
+ resumed = shift(other, "resume", "--role", "pm")
1437
+ if resumed.returncode != 0:
1438
+ report(f"{label} resume --role pm in an unbound worktree failed: {resumed.stderr}")
1439
+ return 1
1440
+ if "next is R009" not in resumed.stdout:
1441
+ report(f"{label} resume --role pm did not print pm's note: {resumed.stdout!r}")
1442
+ return 1
1443
+ if (mailbox_common_dir(rtl) / "keel-chat" / "shift" / "pm.md").exists():
1444
+ report(f"{label} pm's note still waits after resume --role pm.")
1445
+ return 1
1446
+ report("shift-self scenario passed.")
1447
+ return 0
1448
+
1449
+
1450
+ def validate_shift_self_wake_scenario() -> int:
1451
+ """Issue #293: `ready --wake` wakes the role's next session, once.
1452
+
1453
+ A `compact` start does not trigger the waiter; a `clear` start does, and
1454
+ the role then has exactly one waking record from `keel-shift`. Without a
1455
+ chat role, `--wake` is refused.
1456
+ """
1457
+ label = "shift-self-wake:"
1458
+ protocol = (ROOT / "AGENTS.md").read_text(encoding="utf-8")
1459
+ line = next((l for l in protocol.splitlines() if l.startswith("- Keel schedules nothing")), "")
1460
+ if "keel shift ready --wake" not in line:
1461
+ report(f"{label} the protocol's scheduling line does not name the keel shift ready --wake exception: {line!r}")
1462
+ return 1
1463
+ with tempfile.TemporaryDirectory(prefix="keel-shift-wake-") as raw:
1464
+ base = Path(raw)
1465
+ rtl, verify, env, _ = shift_scratch(base)
1466
+ env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_SETTLE_MS": "500", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "20000"}
1467
+ loose = chat_worktree(rtl, base / "loose")
1468
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=loose, check=True, capture_output=True)
1469
+
1470
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
1471
+ return run_keel(cwd, "shift", *args, env=env)
1472
+
1473
+ def session_start(source: str) -> None:
1474
+ subprocess.run(
1475
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"],
1476
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
1477
+ input=json.dumps({"cwd": str(verify), "source": source, "hook_event_name": "SessionStart"}),
1478
+ )
1479
+
1480
+ def wakes() -> list[str]:
1481
+ return chat_records_with(rtl, "dm-keel-shift--verify", "keel shift resume")
1482
+
1483
+ unbound = shift(loose, "ready", "--wake", "loose note")
1484
+ if unbound.returncode == 0:
1485
+ report(f"{label} ready --wake in an unbound worktree with no --role was accepted.")
1486
+ return 1
1487
+ armed = shift(verify, "ready", "--wake", "verify note: next is R010")
1488
+ if armed.returncode != 0:
1489
+ report(f"{label} ready --wake failed: {armed.stderr}")
1490
+ return 1
1491
+ session_start("compact")
1492
+ time.sleep(1)
1493
+ if wakes():
1494
+ report(f"{label} a compact start triggered the wake.")
1495
+ return 1
1496
+ session_start("clear")
1497
+ deadline = time.time() + 5
1498
+ while time.time() < deadline and not wakes():
1499
+ time.sleep(0.1)
1500
+ found = wakes()
1501
+ if len(found) != 1:
1502
+ report(f"{label} expected exactly one wake record from keel-shift after the clear start, found {len(found)}.")
1503
+ return 1
1504
+ if "from: keel-shift" not in found[0]:
1505
+ report(f"{label} the wake record is not from keel-shift: {found[0]!r}")
1506
+ return 1
1507
+ time.sleep(0.5)
1508
+ if len(wakes()) != 1:
1509
+ report(f"{label} the waiter wrote more than one wake record.")
1510
+ return 1
1511
+ checked = run_keel(verify, "chat", "notice", "--check", env=env)
1512
+ if checked.returncode != 0:
1513
+ report(f"{label} keel chat notice --check for verify does not see the wake (exit {checked.returncode}).")
1514
+ return 1
1515
+ report("shift-self-wake scenario passed.")
1516
+ return 0
1517
+
1518
+
1519
+ def validate_role_drift_scenario() -> int:
1520
+ """Issue #301: bindings that drift from where sessions run are reported.
1521
+
1522
+ A binding to a removed worktree and a role with a waiting note and no
1523
+ session are named by `keel patrol`, `keel --doctor`, and an unbound
1524
+ session's projection; `keel chat role --prune` removes only the former.
1525
+ """
1526
+ label = "role-drift:"
1527
+ with tempfile.TemporaryDirectory(prefix="keel-role-drift-") as raw:
1528
+ base = Path(raw)
1529
+ rtl, verify, env, _ = shift_scratch(base)
1530
+ ghost = chat_worktree(rtl, base / "ghost")
1531
+ run_keel(ghost, "chat", "role", "--set", "ghost", env=env)
1532
+ subprocess.run(["git", "worktree", "remove", "--force", str(ghost)], cwd=rtl, check=True, capture_output=True)
1533
+ loose = chat_worktree(rtl, base / "loose")
1534
+ write_text(loose / "openspec/specs/.keep", "")
1535
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
1536
+ if readied.returncode != 0:
1537
+ report(f"{label} verify's ready failed: {readied.stderr}")
1538
+ return 1
1539
+
1540
+ patrolled = run_keel(rtl, "patrol", env=env)
1541
+ drift = [line for line in patrolled.stdout.splitlines() if line.startswith("drift:")]
1542
+ if not any("ghost" in line and "/ghost" in line for line in drift):
1543
+ report(f"{label} keel patrol does not report ghost's removed worktree: {patrolled.stdout!r} {patrolled.stderr!r}")
1544
+ return 1
1545
+ if not any("verify" in line and "shift note" in line for line in drift):
1546
+ report(f"{label} keel patrol does not report verify as unattended: {patrolled.stdout!r}")
1547
+ return 1
1548
+ doctor = run_keel(rtl, "--doctor", env=env).stdout
1549
+ doctor_drift = [line for line in doctor.splitlines() if line.startswith("chat roles: drift")]
1550
+ if not any("ghost" in line for line in doctor_drift):
1551
+ report(f"{label} keel --doctor does not report ghost: {doctor_drift!r}")
1552
+ return 1
1553
+ if not any("verify" in line for line in doctor_drift):
1554
+ report(f"{label} keel --doctor does not report verify: {doctor_drift!r}")
1555
+ return 1
1556
+ context = json.loads(run_keel(loose, "context", "--json", env=env).stdout)
1557
+ if "verify" not in (context.get("unattendedRoles") or []):
1558
+ report(f"{label} an unbound worktree's context does not name verify: {context.get('unattendedRoles')!r}")
1559
+ return 1
1560
+ session = run_session_start_hook(
1561
+ loose, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(loose)},
1562
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
1563
+ )
1564
+ note = session_start_context(session) or ""
1565
+ if "verify" not in note:
1566
+ report(f"{label} the unbound session's note does not name verify: {note!r}")
1567
+ return 1
1568
+ pruned = run_keel(rtl, "chat", "role", "--prune", env=env)
1569
+ if "Pruned ghost" not in pruned.stdout:
1570
+ report(f"{label} keel chat role --prune did not prune ghost: {pruned.stdout!r} {pruned.stderr!r}")
1571
+ return 1
1572
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
1573
+ if "ghost" in roles.values():
1574
+ report(f"{label} roles.json still binds ghost: {roles!r}")
1575
+ return 1
1576
+ if sorted(set(roles.values())) != ["rtl", "verify"]:
1577
+ report(f"{label} prune changed other bindings: {roles!r}")
1578
+ return 1
1579
+ again = run_keel(rtl, "chat", "role", "--prune", env=env)
1580
+ if "No binding" not in again.stdout:
1581
+ report(f"{label} a second prune did not say there was nothing to prune: {again.stdout!r}")
1582
+ return 1
1583
+ report("role-drift scenario passed.")
1584
+ return 0
1585
+
1586
+
1587
+ def validate_host_run_session_scenario() -> int:
1588
+ """Issue #300: a scheduled run started in a role's worktree is not that role.
1589
+
1590
+ Its first prompt, starting `<scheduled-task`, restores the presence its
1591
+ SessionStart replaced; its hooks then write and inject nothing, its end
1592
+ changes nothing, and it never fires `ready --wake`. An ordinary clear
1593
+ still wakes the role once, after the wake settles.
1594
+ """
1595
+ label = "host-run-session:"
1596
+ with tempfile.TemporaryDirectory(prefix="keel-host-run-") as raw:
1597
+ base = Path(raw)
1598
+ rtl, verify, env, _ = shift_scratch(base)
1599
+ env = {**env, "KEEL_SHIFT_WAKE_POLL_MS": "100", "KEEL_SHIFT_WAKE_SETTLE_MS": "1500", "KEEL_SHIFT_WAKE_TIMEOUT_MS": "30000"}
1600
+ presence = mailbox_common_dir(rtl) / "keel-chat" / "presence" / "verify.json"
1601
+
1602
+ def hook(event: str, payload: dict) -> subprocess.CompletedProcess[str]:
1603
+ return subprocess.run(
1604
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
1605
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
1606
+ input=json.dumps({"cwd": str(verify), **payload}),
1607
+ )
1608
+
1609
+ def wakes() -> list[str]:
1610
+ return chat_records_with(rtl, "dm-keel-shift--verify", "keel shift resume")
1611
+
1612
+ def current() -> str:
1613
+ return presence.read_text(encoding="utf-8") if presence.exists() else ""
1614
+
1615
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "s1"})
1616
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "hello"})
1617
+ armed = run_keel(verify, "shift", "ready", "--wake", "verify note", env=env)
1618
+ if armed.returncode != 0:
1619
+ report(f"{label} ready --wake failed: {armed.stderr}")
1620
+ return 1
1621
+ run_keel(rtl, "chat", "post", "soc", "@verify something to read", env=env)
1622
+ before = current()
1623
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "run1"})
1624
+ prompted = hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "run1",
1625
+ "prompt": '<scheduled-task name="patrol">\nrun the patrol'})
1626
+ if current() != before:
1627
+ report(f"{label} the host run's presence was not restored:\nbefore {before}\nafter {current()}")
1628
+ return 1
1629
+ if prompted.stdout.strip():
1630
+ report(f"{label} the host run's prompt hook injected output: {prompted.stdout!r}")
1631
+ return 1
1632
+ time.sleep(3)
1633
+ if wakes():
1634
+ report(f"{label} the host run's start fired the wake.")
1635
+ return 1
1636
+ hook("session-end", {"hook_event_name": "SessionEnd", "session_id": "run1"})
1637
+ if current() != before:
1638
+ report(f"{label} the host run's end changed presence:\nbefore {before}\nafter {current()}")
1639
+ return 1
1640
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "clear", "session_id": "s2"})
1641
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s2", "prompt": "carry on"})
1642
+ deadline = time.time() + 6
1643
+ while time.time() < deadline and not wakes():
1644
+ time.sleep(0.1)
1645
+ if len(wakes()) != 1:
1646
+ report(f"{label} expected one wake after the clear start, found {len(wakes())}.")
1647
+ return 1
1648
+ task_config = "patrol:\n role: verify\n every: 30m\n"
1649
+ write_text(verify / "keel" / "config.yaml", task_config)
1650
+ task = run_keel(verify, "patrol", "task", env=env)
1651
+ if "bound to no role" not in task.stdout:
1652
+ report(f"{label} keel patrol task does not say to create the task from a folder bound to no role: {task.stdout!r} {task.stderr!r}")
1653
+ return 1
1654
+ report("host-run-session scenario passed.")
1655
+ return 0
1656
+
1657
+
1658
+ def validate_shift_keeps_transcripts_scenario() -> int:
1659
+ """Issue #343: a shift's conversation outlives the host's transcript file.
1660
+
1661
+ Claude deletes transcripts after `cleanupPeriodDays` (30 by default), so
1662
+ when a role's session starts a new transcript the hook copies the ended
1663
+ one into Keel's store; `history` and `--grep` read the copy once the
1664
+ host's file is gone, and `--grep` reads a Codex rollout too.
1665
+ """
1666
+ label = "shift-keeps-transcripts:"
1667
+ with tempfile.TemporaryDirectory(prefix="keel-shift-343-") as raw:
1668
+ base = Path(raw)
1669
+ rtl, verify, env, _ = shift_scratch(base)
1670
+ store_root = mailbox_common_dir(rtl) / "keel-chat"
1671
+ kept_dir = store_root / "shift" / "transcripts" / "verify"
1672
+ transcripts = base / "transcripts"
1673
+ transcripts.mkdir()
1674
+
1675
+ def claude_transcript(name: str, said: str) -> Path:
1676
+ path = transcripts / f"{name}.jsonl"
1677
+ path.write_text("\n".join(json.dumps(record) for record in (
1678
+ {"type": "user", "timestamp": "2026-10-12T01:00:00.000Z", "message": {"role": "user", "content": "carry on"}},
1679
+ {"type": "assistant", "timestamp": "2026-10-12T01:00:05.000Z",
1680
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
1681
+ )) + "\n", encoding="utf-8")
1682
+ return path
1683
+
1684
+ def hook(transcript: Path, session: str) -> None:
1685
+ for event, name in (("session-start", "SessionStart"), ("user-prompt-submit", "UserPromptSubmit")):
1686
+ subprocess.run(
1687
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
1688
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
1689
+ input=json.dumps({"cwd": str(verify), "hook_event_name": name, "session_id": session,
1690
+ "prompt": "go", "source": "startup", "transcript_path": str(transcript)}),
1691
+ )
1692
+
1693
+ def history(*args: str) -> subprocess.CompletedProcess[str]:
1694
+ return run_keel(verify, "shift", "history", *args, env=env)
1695
+
1696
+ a = claude_transcript("a", "The arbiter retry budget is four cycles.")
1697
+ b = claude_transcript("b", "Resumed from the note.")
1698
+ hook(a, "s1")
1699
+ hook(b, "s1")
1700
+ kept_a = kept_dir / "a.jsonl.gz"
1701
+ if not kept_a.is_file():
1702
+ report(f"{label} no kept copy of transcript A under {kept_dir}: {sorted(p.name for p in kept_dir.glob('*')) if kept_dir.exists() else 'no directory'}")
1703
+ return 1
1704
+ if gzip.decompress(kept_a.read_bytes()) != a.read_bytes():
1705
+ report(f"{label} the kept copy of A is not A's bytes.")
1706
+ return 1
1707
+ if (kept_dir / "b.jsonl.gz").exists():
1708
+ report(f"{label} the current transcript B was copied while it is still being written.")
1709
+ return 1
1710
+
1711
+ a.unlink()
1712
+ listed = history("verify")
1713
+ line_a = next((l for l in listed.stdout.splitlines() if str(a) in l), "")
1714
+ if "(missing)" in line_a:
1715
+ report(f"{label} A, deleted but kept, is still listed as missing: {line_a!r}")
1716
+ return 1
1717
+ if "(kept)" not in line_a:
1718
+ report(f"{label} A, deleted but kept, is not marked (kept): {line_a!r}")
1719
+ return 1
1720
+ found = history("verify", "--grep", "retry budget")
1721
+ if found.returncode != 0:
1722
+ report(f"{label} --grep for a phrase in the kept copy of A exited {found.returncode}: {found.stdout!r} {found.stderr!r}")
1723
+ return 1
1724
+ if "retry budget" not in found.stdout:
1725
+ report(f"{label} --grep does not print the phrase from the kept copy of A: {found.stdout!r}")
1726
+ return 1
1727
+
1728
+ # A Codex rollout is searched the same way.
1729
+ c = transcripts / "rollout-c.jsonl"
1730
+ c.write_text("\n".join(json.dumps(record) for record in (
1731
+ {"timestamp": "2026-10-18T09:50:18.096Z", "type": "session_meta", "payload": {}},
1732
+ {"timestamp": "2026-10-18T09:50:21.766Z", "type": "response_item",
1733
+ "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Check the FIFO depth for the IECC lane."}]}},
1734
+ {"timestamp": "2026-10-18T09:50:23.621Z", "type": "response_item",
1735
+ "payload": {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "ok"}]}},
1736
+ )) + "\n", encoding="utf-8")
1737
+ hook(c, "s2")
1738
+ found = history("verify", "--grep", "FIFO depth")
1739
+ if found.returncode != 0:
1740
+ report(f"{label} --grep for a phrase in a Codex rollout exited {found.returncode}: {found.stdout!r} {found.stderr!r}")
1741
+ return 1
1742
+ if "FIFO depth" not in found.stdout:
1743
+ report(f"{label} --grep does not print the phrase from a Codex rollout: {found.stdout!r}")
1744
+ return 1
1745
+
1746
+ # A transcript that grew after its copy is copied again.
1747
+ with b.open("a", encoding="utf-8") as handle:
1748
+ handle.write(json.dumps({"type": "assistant", "timestamp": "2026-10-12T02:00:00.000Z",
1749
+ "message": {"role": "assistant", "content": [{"type": "text", "text": "late line"}]}}) + "\n")
1750
+ d = claude_transcript("d", "Next shift.")
1751
+ hook(d, "s3")
1752
+ kept_b = kept_dir / "b.jsonl.gz"
1753
+ if not kept_b.is_file():
1754
+ report(f"{label} B ended and has no kept copy.")
1755
+ return 1
1756
+ if gzip.decompress(kept_b.read_bytes()) != b.read_bytes():
1757
+ report(f"{label} B's kept copy does not match B after it ended.")
1758
+ return 1
1759
+ with b.open("a", encoding="utf-8") as handle:
1760
+ handle.write("{}\n")
1761
+ e = claude_transcript("e", "Another shift.")
1762
+ hook(e, "s4")
1763
+ if gzip.decompress(kept_b.read_bytes()) != b.read_bytes():
1764
+ report(f"{label} B grew after its copy and was not copied again.")
1765
+ return 1
1766
+ report("shift-keeps-transcripts scenario passed.")
1767
+ return 0
1768
+
1769
+
1770
+ def validate_shift_keeps_found_transcripts_scenario() -> int:
1771
+ """Issue #361: a transcript `history` finds but never recorded is kept too.
1772
+
1773
+ Transcripts from before segments were recorded (#304) are listed
1774
+ `(found)`; the hook copied only recorded segments, and `history` read a
1775
+ copy only through a segment record, so the oldest conversations were the
1776
+ ones left unkept.
1777
+ """
1778
+ label = "shift-keeps-found-transcripts:"
1779
+ with tempfile.TemporaryDirectory(prefix="keel-shift-361-") as raw:
1780
+ base = Path(raw)
1781
+ rtl, verify, env, _ = shift_scratch(base)
1782
+ kept_dir = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "transcripts" / "verify"
1783
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
1784
+ bound = next(path for path, role in roles.items() if role == "verify")
1785
+ project = base / "claude-config" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", bound)
1786
+ project.mkdir(parents=True)
1787
+ env = {**env, "CLAUDE_CONFIG_DIR": str(base / "claude-config")}
1788
+
1789
+ def transcript(name: str, opening: str, said: str) -> Path:
1790
+ path = project / f"{name}.jsonl"
1791
+ path.write_text("\n".join(json.dumps(record) for record in (
1792
+ {"type": "user", "timestamp": "2026-10-02T01:00:00.000Z", "cwd": bound, "message": {"role": "user", "content": opening}},
1793
+ {"type": "assistant", "timestamp": "2026-10-02T01:00:05.000Z", "cwd": bound,
1794
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
1795
+ )) + "\n", encoding="utf-8")
1796
+ return path
1797
+
1798
+ def hook(path: Path) -> None:
1799
+ for event, name in (("session-start", "SessionStart"), ("user-prompt-submit", "UserPromptSubmit")):
1800
+ subprocess.run(
1801
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
1802
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
1803
+ input=json.dumps({"cwd": str(verify), "hook_event_name": name, "session_id": "s1",
1804
+ "prompt": "go", "source": "startup", "transcript_path": str(path)}),
1805
+ )
1806
+
1807
+ old = transcript("old", "start the shift", "The ECC syndrome table was settled on day one.")
1808
+ scheduled = transcript("patrol", '<scheduled-task name="patrol">run', "patrol ran")
1809
+ listed = run_keel(verify, "shift", "history", "verify", env=env)
1810
+ if "(found)" not in next((l for l in listed.stdout.splitlines() if "old.jsonl" in l), ""):
1811
+ report(f"{label} the unrecorded transcript is not listed as found: {listed.stdout!r} {listed.stderr!r}")
1812
+ return 1
1813
+ hook(transcript("a", "carry on", "first recorded shift"))
1814
+ hook(transcript("b", "carry on", "second recorded shift"))
1815
+ kept_old = kept_dir / "old.jsonl.gz"
1816
+ if not kept_old.is_file():
1817
+ report(f"{label} a segment change left the found transcript unkept: "
1818
+ f"{sorted(p.name for p in kept_dir.glob('*')) if kept_dir.exists() else 'no directory'}")
1819
+ return 1
1820
+ if gzip.decompress(kept_old.read_bytes()) != old.read_bytes():
1821
+ report(f"{label} the found transcript's copy is not its bytes.")
1822
+ return 1
1823
+ if (kept_dir / "patrol.jsonl.gz").exists():
1824
+ report(f"{label} a scheduled run's transcript was kept as the role's conversation.")
1825
+ return 1
1826
+ if (kept_dir / "b.jsonl.gz").exists():
1827
+ report(f"{label} the current transcript was copied while it is still being written.")
1828
+ return 1
1829
+
1830
+ old.unlink()
1831
+ listed = run_keel(verify, "shift", "history", "verify", env=env)
1832
+ line = next((l for l in listed.stdout.splitlines() if "old.jsonl" in l), "")
1833
+ if "(missing)" in line:
1834
+ report(f"{label} the found transcript, deleted but kept, is listed missing: {listed.stdout!r}")
1835
+ return 1
1836
+ if "(kept)" not in line:
1837
+ report(f"{label} the found transcript, deleted but kept, is not listed (kept): {listed.stdout!r}")
1838
+ return 1
1839
+ found = run_keel(verify, "shift", "history", "verify", "--grep", "syndrome table", env=env)
1840
+ if "syndrome table" not in found.stdout:
1841
+ report(f"{label} --grep does not search the found transcript's copy: {found.stdout!r} {found.stderr!r}")
1842
+ return 1
1843
+ hook(transcript("c", "carry on", "third recorded shift"))
1844
+ listed = run_keel(verify, "shift", "history", "verify", env=env)
1845
+ if sum(1 for l in listed.stdout.splitlines() if "old.jsonl" in l) != 1:
1846
+ report(f"{label} another segment change did not leave the kept found transcript listed once: {listed.stdout!r}")
1847
+ return 1
1848
+ if "shift-keeps-found-transcripts" not in {name for name, _ in registry.SCENARIOS}:
1849
+ report(f"{label} scenario is not registered.")
1850
+ return 1
1851
+ report("shift-keeps-found-transcripts scenario passed.")
1852
+ return 0
1853
+
1854
+
1855
+ def validate_shift_history_scenario() -> int:
1856
+ """Issue #304: a cleared shift's conversation stays findable.
1857
+
1858
+ The hooks record each transcript a role's session runs in; a scheduled
1859
+ run's is undone; `keel shift history` lists and greps them; `ready` and
1860
+ the clear hint name the history and Remote Control.
1861
+ """
1862
+ label = "shift-history:"
1863
+ with tempfile.TemporaryDirectory(prefix="keel-shift-history-") as raw:
1864
+ base = Path(raw)
1865
+ rtl, verify, env, _ = shift_scratch(base)
1866
+ transcripts = base / "transcripts"
1867
+ transcripts.mkdir()
1868
+
1869
+ def transcript(name: str, said: str) -> Path:
1870
+ path = transcripts / f"{name}.jsonl"
1871
+ path.write_text("\n".join(json.dumps(record) for record in (
1872
+ {"type": "user", "timestamp": "2026-10-12T01:00:00.000Z", "message": {"role": "user", "content": "carry on with R008"}},
1873
+ {"type": "assistant", "timestamp": "2026-10-12T01:00:05.000Z",
1874
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
1875
+ )) + "\n", encoding="utf-8")
1876
+ return path
1877
+
1878
+ a = transcript("a", "The timing fix for the clock gate lands in R008 after the review.")
1879
+ b = transcript("b", "Resumed from the note.")
1880
+ c = transcript("c", "patrol run")
1881
+
1882
+ def hook(event: str, payload: dict) -> None:
1883
+ subprocess.run(
1884
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
1885
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
1886
+ input=json.dumps({"cwd": str(verify), **payload}),
1887
+ )
1888
+
1889
+ def history(*args: str) -> subprocess.CompletedProcess[str]:
1890
+ return run_keel(verify, "shift", "history", *args, env=env)
1891
+
1892
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "s1", "transcript_path": str(a)})
1893
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "go", "transcript_path": str(a)})
1894
+ readied = run_keel(verify, "shift", "ready", "verify note", env=env)
1895
+ if "keel shift history verify" not in readied.stdout:
1896
+ report(f"{label} ready does not name keel shift history verify: {readied.stdout!r} {readied.stderr!r}")
1897
+ return 1
1898
+ if "Remote Control" not in readied.stdout:
1899
+ report(f"{label} the clear hint does not name Remote Control: {readied.stdout!r}")
1900
+ return 1
1901
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "clear", "session_id": "s1", "transcript_path": str(b)})
1902
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "s1", "prompt": "resume", "transcript_path": str(b)})
1903
+ hook("session-start", {"hook_event_name": "SessionStart", "source": "startup", "session_id": "run1", "transcript_path": str(c)})
1904
+ hook("user-prompt-submit", {"hook_event_name": "UserPromptSubmit", "session_id": "run1",
1905
+ "prompt": '<scheduled-task name="patrol">run', "transcript_path": str(c)})
1906
+
1907
+ listed = history("verify")
1908
+ if listed.returncode != 0:
1909
+ report(f"{label} keel shift history failed: {listed.stderr}")
1910
+ return 1
1911
+ lines = [line for line in listed.stdout.splitlines() if ".jsonl" in line]
1912
+ if len(lines) != 2:
1913
+ report(f"{label} expected two transcript segments, got: {listed.stdout!r}")
1914
+ return 1
1915
+ if str(b) not in lines[0] or "now" not in lines[0]:
1916
+ report(f"{label} the newest segment is not B, still current: {lines[0]!r}")
1917
+ return 1
1918
+ if str(a) not in lines[1] or "now" in lines[1]:
1919
+ report(f"{label} the older segment is not A, ended: {lines[1]!r}")
1920
+ return 1
1921
+ if str(c) in listed.stdout:
1922
+ report(f"{label} the scheduled run's transcript is listed: {listed.stdout!r}")
1923
+ return 1
1924
+ found = history("verify", "--grep", "clock gate")
1925
+ if found.returncode != 0:
1926
+ report(f"{label} --grep for a phrase in A exited {found.returncode}: {found.stdout!r} {found.stderr!r}")
1927
+ return 1
1928
+ if "clock gate" not in found.stdout or str(a) not in found.stdout:
1929
+ report(f"{label} --grep does not print the phrase under A: {found.stdout!r}")
1930
+ return 1
1931
+ missing = history("verify", "--grep", "nothing like this")
1932
+ if missing.returncode != 1:
1933
+ report(f"{label} --grep for an absent phrase exited {missing.returncode}.")
1934
+ return 1
1935
+ as_json = json.loads(history("verify", "--json").stdout)
1936
+ if [seg.get("transcript") for seg in as_json.get("segments", [])] != [str(b), str(a)]:
1937
+ report(f"{label} --json segments are {as_json.get('segments')!r}.")
1938
+ return 1
1939
+
1940
+ # Earlier history, kept by Claude before Keel recorded anything (D6).
1941
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
1942
+ bound = next(path for path, role in roles.items() if role == "verify")
1943
+ project = base / "claude-config" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", bound)
1944
+ project.mkdir(parents=True)
1945
+ (project / "d.jsonl").write_text("\n".join(json.dumps(record) for record in (
1946
+ {"type": "user", "timestamp": "2026-10-04T13:19:18.000Z", "cwd": bound, "message": {"role": "user", "content": "start the shift"}},
1947
+ {"type": "assistant", "timestamp": "2026-10-04T13:27:58.000Z", "cwd": bound,
1948
+ "message": {"role": "assistant", "content": [{"type": "text", "text": "The DMC arbiter plan was agreed on the first day."}]}},
1949
+ )) + "\n", encoding="utf-8")
1950
+ (project / "e.jsonl").write_text(json.dumps(
1951
+ {"type": "user", "timestamp": "2026-10-12T11:57:15.000Z", "cwd": bound, "message": {"role": "user", "content": '<scheduled-task name="patrol">run'}}
1952
+ ) + "\n", encoding="utf-8")
1953
+ found_env = {**env, "CLAUDE_CONFIG_DIR": str(base / "claude-config")}
1954
+ earlier = run_keel(verify, "shift", "history", "verify", env=found_env)
1955
+ d_line = next((line for line in earlier.stdout.splitlines() if "d.jsonl" in line), "")
1956
+ if "(found)" not in d_line:
1957
+ report(f"{label} the earlier transcript D is not listed as found: {earlier.stdout!r} {earlier.stderr!r}")
1958
+ return 1
1959
+ if "e.jsonl" in earlier.stdout:
1960
+ report(f"{label} the scheduled run E is listed: {earlier.stdout!r}")
1961
+ return 1
1962
+ arbiter = run_keel(verify, "shift", "history", "verify", "--grep", "arbiter plan", env=found_env)
1963
+ if "arbiter plan" not in arbiter.stdout:
1964
+ report(f"{label} --grep does not search the earlier transcript D: {arbiter.stdout!r}")
1965
+ return 1
1966
+ report("shift-history scenario passed.")
1967
+ return 0
1968
+
1969
+
1970
+ def validate_shift_coordinator_last_scenario() -> int:
1971
+ """Issue #289: the coordinator starts the others before its own shift ends.
1972
+
1973
+ Its check reports a waiting, unstarted note and its ready is refused until
1974
+ it starts that role; a successor's resume lists who still waits; the
1975
+ request and ready name session state a clear destroys.
1976
+ """
1977
+ label = "shift-coordinator-last:"
1978
+ with tempfile.TemporaryDirectory(prefix="keel-shift-coordinator-") as raw:
1979
+ base = Path(raw)
1980
+ rtl, verify, env, _ = shift_scratch(base)
1981
+
1982
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
1983
+ return run_keel(cwd, "shift", *args, env=env)
1984
+
1985
+ shift(rtl, "request", "verify")
1986
+ request_text = "\n".join(chat_records_with(rtl, "dm-rtl--verify", "Shift change requested"))
1987
+ if "scheduled jobs" not in request_text:
1988
+ report(f"{label} the request does not name scheduled jobs: {request_text!r}")
1989
+ return 1
1990
+ readied = shift(verify, "ready", "verify note")
1991
+ if readied.returncode != 0:
1992
+ report(f"{label} verify's ready failed: {readied.stderr}")
1993
+ return 1
1994
+ if "scheduled jobs" not in readied.stdout:
1995
+ report(f"{label} ready's output does not name scheduled jobs: {readied.stdout!r}")
1996
+ return 1
1997
+ checked = shift(rtl, "check", "--json")
1998
+ items = json.loads(checked.stdout).get("items", [])
1999
+ if checked.returncode != 1:
2000
+ report(f"{label} rtl's check exited {checked.returncode} with verify unstarted, not 1.")
2001
+ return 1
2002
+ if not any(i.get("kind") == "unstarted" and "verify" in i.get("detail", "") for i in items):
2003
+ report(f"{label} rtl's check has no unstarted item for verify: {items!r}")
2004
+ return 1
2005
+ if shift(rtl, "ready", "rtl note").returncode == 0:
2006
+ report(f"{label} rtl's ready was accepted with verify unstarted.")
2007
+ return 1
2008
+ shift(rtl, "start", "verify")
2009
+ after = json.loads(shift(rtl, "check", "--json").stdout).get("items", [])
2010
+ if any(i.get("kind") == "unstarted" for i in after):
2011
+ report(f"{label} rtl's check still reports unstarted after start: {after!r}")
2012
+ return 1
2013
+
2014
+ shift(verify, "resume")
2015
+ shift(rtl, "request", "verify")
2016
+ shift(verify, "ready", "verify note, second round")
2017
+ forced = shift(rtl, "ready", "--force-reason", "user is away", "rtl note")
2018
+ if forced.returncode != 0:
2019
+ report(f"{label} rtl's ready --force-reason failed: {forced.stderr}")
2020
+ return 1
2021
+ resumed = shift(rtl, "resume")
2022
+ if "verify" not in resumed.stdout or "keel shift start" not in resumed.stdout:
2023
+ report(f"{label} rtl's resume does not list verify as waiting for keel shift start: {resumed.stdout!r}")
2024
+ return 1
2025
+ report("shift-coordinator-last scenario passed.")
2026
+ return 0
2027
+
2028
+
2029
+ def validate_shift_change_scenario() -> int:
2030
+ """Owner's decision of 2026-10-05: a role's session changes shift through Keel.
2031
+
2032
+ The coordinator requests it, the role's readiness check names every loose
2033
+ end, `ready` stores the shift note outside the worktree and closes the
2034
+ request, `start` wakes the cleared role only once the note waits, the
2035
+ session-start notice points to the note, and `resume` consumes it.
2036
+ """
2037
+ label = "shift-change:"
2038
+ with tempfile.TemporaryDirectory(prefix="keel-shift-") as raw:
2039
+ base = Path(raw)
2040
+ rtl, verify, env = chat_scratch_group(base)
2041
+ remote = base / "remote.git"
2042
+ subprocess.run(["git", "init", "-q", "--bare", str(remote)], check=True)
2043
+ subprocess.run(["git", "remote", "add", "origin", str(remote)], cwd=rtl, check=True)
2044
+ for tree in (rtl, verify):
2045
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
2046
+ common = mailbox_common_dir(rtl) / "keel-chat"
2047
+ signal = common / "signal" / "verify"
2048
+
2049
+ def shift(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
2050
+ return run_keel(cwd, "shift", *args, env=env)
2051
+
2052
+ def notice() -> str:
2053
+ # The SessionStart projection, which every host runs (shift-without-role D3).
2054
+ session = run_session_start_hook(
2055
+ verify, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(verify)},
2056
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"', extra_env={k: v for k, v in env.items() if k.startswith("KEEL_")},
2057
+ )
2058
+ return session_start_context(session) or ""
2059
+
2060
+ size = signal.stat().st_size if signal.exists() else 0
2061
+ requested = shift(rtl, "request", "verify")
2062
+ if requested.returncode != 0:
2063
+ report(f"{label} keel shift request failed: {requested.stderr.strip()}")
2064
+ return 1
2065
+ request = [r for r in chat_records_with(rtl, "dm-rtl--verify", "shift") if "kind: todo" in r and "keel-shift" in r]
2066
+ if not request:
2067
+ report(f"{label} no keel-shift todo reached dm-rtl--verify: {requested.stdout.strip()}")
2068
+ return 1
2069
+ if "assignee: verify" not in request[0]:
2070
+ report(f"{label} the shift request is not assigned to verify:\n{request[0]}")
2071
+ return 1
2072
+ if not signal.exists():
2073
+ report(f"{label} the request created no signal file for verify.")
2074
+ return 1
2075
+ if signal.stat().st_size <= size:
2076
+ report(f"{label} the request did not touch verify's signal file.")
2077
+ return 1
2078
+ if shift(rtl, "start", "verify").returncode == 0:
2079
+ report(f"{label} keel shift start succeeded before verify was ready.")
2080
+ return 1
2081
+
2082
+ # Every kind of loose end at once.
2083
+ write_text(verify / "scratch.txt", "uncommitted\n")
2084
+ write_text(verify / "pushed-not.txt", "x\n")
2085
+ subprocess.run(["git", "add", "pushed-not.txt"], cwd=verify, check=True)
2086
+ subprocess.run(["git", "commit", "-q", "-m", "local only"], cwd=verify, check=True)
2087
+ write_text(verify / "keel" / "guard.json", "{}\n")
2088
+ leased = run_keel(verify, "lock", "acquire", "main-checkout", "--for", "1h", "--note", "shift fixture", env=env)
2089
+ if leased.returncode != 0:
2090
+ report(f"{label} could not acquire the shift fixture lease: {leased.stderr}")
2091
+ return 1
2092
+ other_lease = run_keel(rtl, "lock", "acquire", "other-worktree", "--for", "1h", "--note", "other session", env=env)
2093
+ if other_lease.returncode != 0:
2094
+ report(f"{label} could not acquire the other worktree's lease: {other_lease.stderr}")
2095
+ return 1
2096
+ lease_file = common / "locks" / "main-checkout.json"
2097
+ lease_before = lease_file.read_bytes()
2098
+ # A Claude scratchpad of a session started in verify, and one of a
2099
+ # session started elsewhere (shift-temp-owner D1).
2100
+ scratch = Path(tempfile.gettempdir()) / f"claude-{os.getuid()}"
2101
+ slug = re.sub(r"[^A-Za-z0-9]", "-", str(verify.resolve()))
2102
+ temp_tree = scratch / slug / f"keel-test-{os.getpid()}" / "scratchpad" / "own-tmp-tree"
2103
+ other_tree = scratch / "-some-other-dir" / f"keel-test-{os.getpid()}" / "scratchpad" / "other-tmp-tree"
2104
+ for tree in (temp_tree, other_tree):
2105
+ tree.parent.mkdir(parents=True, exist_ok=True)
2106
+ subprocess.run(["git", "worktree", "add", "-q", "--detach", str(temp_tree)], cwd=verify, check=True, capture_output=True)
2107
+ run_keel(rtl, "chat", "todo", "soc", "--assignee", "verify", "Rerun the regression", env=env)
2108
+ # Its own session, as a job a session leaves behind would be: the check
2109
+ # skips its own command line's process group.
2110
+ sleeper = subprocess.Popen(["sleep", "60"], cwd=verify, start_new_session=True)
2111
+ try:
2112
+ checked = shift(verify, "check", "--json")
2113
+ if checked.returncode != 1:
2114
+ report(f"{label} keel shift check exited {checked.returncode} with loose ends present.")
2115
+ return 1
2116
+ text = checked.stdout
2117
+ lock_items = [item for item in chat_json(checked).get("items", []) if item["kind"] == "lock"]
2118
+ if len(lock_items) != 1:
2119
+ report(f"{label} expected exactly one held-worktree lock item: {text}")
2120
+ return 1
2121
+ for needle in ("main-checkout", "verify", "shift fixture", json.loads(lease_before)["expires"]):
2122
+ if needle not in lock_items[0]["detail"]:
2123
+ report(f"{label} lock item omits {needle!r}: {lock_items}")
2124
+ return 1
2125
+ if lease_file.read_bytes() != lease_before:
2126
+ report(f"{label} shift check changed the live lease")
2127
+ return 1
2128
+ for needle in ("scratch.txt", "local only", "guard.json", str(sleeper.pid), temp_tree.name, "Rerun the regression", "main-checkout"):
2129
+ if needle not in text:
2130
+ report(f"{label} keel shift check does not name {needle!r}: {text.strip()[:600]}")
2131
+ return 1
2132
+ refused = shift(verify, "ready", "next: rerun R007")
2133
+ if refused.returncode == 0:
2134
+ report(f"{label} keel shift ready succeeded with loose ends present.")
2135
+ return 1
2136
+ if "scratch.txt" not in refused.stdout + refused.stderr:
2137
+ report(f"{label} the refused ready does not name the loose ends: {refused.stderr.strip()}")
2138
+ return 1
2139
+ if (common / "shift" / "verify.md").exists():
2140
+ report(f"{label} a refused ready stored a note.")
2141
+ return 1
2142
+ finally:
2143
+ sleeper.kill()
2144
+ sleeper.wait()
2145
+
2146
+ (verify / "scratch.txt").unlink()
2147
+ (verify / "keel" / "guard.json").unlink()
2148
+ released = run_keel(verify, "lock", "release", "main-checkout", env=env)
2149
+ if released.returncode != 0:
2150
+ report(f"{label} could not release the shift fixture lease: {released.stderr}")
2151
+ return 1
2152
+ after_release = shift(verify, "check", "--json")
2153
+ if any(item["kind"] == "lock" for item in chat_json(after_release).get("items", [])):
2154
+ report(f"{label} shift check retained a lock item after release: {after_release.stdout}")
2155
+ return 1
2156
+ subprocess.run(["git", "push", "-q"], cwd=verify, check=True, capture_output=True)
2157
+ subprocess.run(["git", "worktree", "remove", "--force", str(temp_tree)], cwd=verify, check=True)
2158
+ todo_id = next(r for r in chat_records_with(rtl, "soc", "Rerun the regression"))
2159
+ open_todo = re.search(r"^id: (\S+)", todo_id, re.M).group(1)
2160
+ run_keel(verify, "chat", "done", open_todo, env=env)
2161
+ run_keel(verify, "chat", "read", env=env)
2162
+ clean = shift(verify, "check")
2163
+ if clean.returncode != 0:
2164
+ report(f"{label} keel shift check is not ready on a clean worktree: {clean.stdout.strip()} {clean.stderr.strip()}")
2165
+ return 1
2166
+ subprocess.run(["git", "worktree", "add", "-q", "--detach", str(other_tree)], cwd=verify, check=True, capture_output=True)
2167
+ try:
2168
+ foreign = shift(verify, "check")
2169
+ if foreign.returncode != 0:
2170
+ report(f"{label} another session's temporary worktree blocked the check: {foreign.stdout.strip()}")
2171
+ return 1
2172
+ if "other-tmp-tree" not in foreign.stdout:
2173
+ report(f"{label} another session's temporary worktree is not listed as a note: {foreign.stdout.strip()}")
2174
+ return 1
2175
+ finally:
2176
+ subprocess.run(["git", "worktree", "remove", "--force", str(other_tree)], cwd=verify, check=False, capture_output=True)
2177
+ shutil.rmtree(scratch / slug / f"keel-test-{os.getpid()}", ignore_errors=True)
2178
+ shutil.rmtree(scratch / "-some-other-dir" / f"keel-test-{os.getpid()}", ignore_errors=True)
2179
+
2180
+ ready = shift(verify, "ready", "next: rerun R007 on 1b64e8c")
2181
+ if ready.returncode != 0:
2182
+ report(f"{label} keel shift ready failed on a clean worktree: {ready.stderr.strip()}")
2183
+ return 1
2184
+ note = common / "shift" / "verify.md"
2185
+ if not note.exists():
2186
+ report(f"{label} no shift note was stored at {note}.")
2187
+ return 1
2188
+ if "rerun R007 on 1b64e8c" not in note.read_text(encoding="utf-8"):
2189
+ report(f"{label} the stored shift note lacks the text given to ready.")
2190
+ return 1
2191
+ for needle in ("clear_session", "/clear"):
2192
+ if needle not in ready.stdout:
2193
+ report(f"{label} keel shift ready does not say how to clear the session ({needle!r}): {ready.stdout.strip()}")
2194
+ return 1
2195
+ reply = chat_records_with(rtl, "dm-rtl--verify", "done")
2196
+ if not reply:
2197
+ report(f"{label} ready did not reply done to the request.")
2198
+ return 1
2199
+ if "kind: done" not in "".join(chat_records_with(rtl, "dm-rtl--verify", "")):
2200
+ report(f"{label} the shift request was not closed.")
2201
+ return 1
2202
+
2203
+ status = shift(rtl, "status")
2204
+ if "verify: note waiting" not in status.stdout:
2205
+ report(f"{label} keel shift status does not list verify with a waiting note: {status.stdout.strip()}")
2206
+ return 1
2207
+ if "keel shift resume" not in notice():
2208
+ report(f"{label} the session-start notice does not point to the waiting note.")
2209
+ return 1
2210
+
2211
+ size = signal.stat().st_size
2212
+ started = shift(rtl, "start", "verify", "then pick up #157")
2213
+ if started.returncode != 0:
2214
+ report(f"{label} keel shift start failed after ready: {started.stderr.strip()}")
2215
+ return 1
2216
+ if not chat_records_with(rtl, "dm-rtl--verify", "keel shift resume"):
2217
+ report(f"{label} the cold-start message does not name keel shift resume.")
2218
+ return 1
2219
+ if signal.stat().st_size <= size:
2220
+ report(f"{label} the cold-start message did not touch verify's signal file.")
2221
+ return 1
2222
+
2223
+ resumed = shift(verify, "resume")
2224
+ if resumed.returncode != 0:
2225
+ report(f"{label} keel shift resume failed: {resumed.stderr.strip()}")
2226
+ return 1
2227
+ if "rerun R007 on 1b64e8c" not in resumed.stdout:
2228
+ report(f"{label} keel shift resume did not print the note: {resumed.stdout.strip()}")
2229
+ return 1
2230
+ if note.exists():
2231
+ report(f"{label} resume left the note waiting.")
2232
+ return 1
2233
+ if not list((common / "shift" / "history").glob("verify-*.md")):
2234
+ report(f"{label} resume did not keep the note in history.")
2235
+ return 1
2236
+ if not chat_records_with(rtl, "dm-rtl--verify", "on shift"):
2237
+ report(f"{label} resume did not tell the coordinator verify is on shift.")
2238
+ return 1
2239
+ if "keel shift resume" in notice():
2240
+ report(f"{label} the notice still points to a note already resumed.")
2241
+ return 1
2242
+ again = shift(verify, "resume")
2243
+ if "no shift note" not in again.stdout.lower():
2244
+ report(f"{label} a second resume does not say no note waits: {again.stdout.strip()} {again.stderr.strip()}")
2245
+ return 1
2246
+
2247
+ for relative in ("docs/shift-change.md", "docs/shift-change.zh-CN.md"):
2248
+ if not (ROOT / relative).exists():
2249
+ report(f"{label} {relative} is missing.")
2250
+ return 1
2251
+ for readme, guide in (("README.md", "docs/shift-change.md"), ("README.zh-CN.md", "docs/shift-change.zh-CN.md")):
2252
+ if guide not in (ROOT / readme).read_text(encoding="utf-8"):
2253
+ report(f"{label} {readme} does not link {guide}.")
2254
+ return 1
2255
+ if "shift-change" not in {name for name, _ in registry.SCENARIOS}:
2256
+ report(f"{label} scenario is not registered.")
2257
+ return 1
2258
+ report("shift-change scenario passed.")
2259
+ return 0
2260
+
2261
+
2262
+ def validate_self_shift_authorization_scenario() -> int:
2263
+ """Issue #319: `self-shift` lets a desktop session take its own three steps.
2264
+
2265
+ The name is read and listed by `--doctor`, a scoped form is refused, and a
2266
+ desktop `keel shift ready --wake` says the steps are standing-authorized
2267
+ only when the repository declares it.
2268
+ """
2269
+ label = "self-shift-authorization:"
2270
+ with tempfile.TemporaryDirectory(prefix="keel-self-shift-") as raw:
2271
+ base = Path(raw)
2272
+ _rtl, verify, env, _ = shift_scratch(base)
2273
+ env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000"}
2274
+ desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319"}
2275
+ config = verify / "keel" / "config.yaml"
2276
+ reason = ("--force-reason", "the fixture config is uncommitted")
2277
+
2278
+ def declare(*entries: str) -> None:
2279
+ write_text(config, "authorize:\n" + "".join(f" - {entry}\n" for entry in entries))
2280
+
2281
+ declare("commit", "self-shift")
2282
+ doctor = run_keel(verify, "--doctor", env=env)
2283
+ if "self-shift" not in doctor.stdout or "unrecognized" in (doctor.stdout + doctor.stderr).lower():
2284
+ report(f"{label} self-shift was not read and listed as a standing authorization: {doctor.stdout.strip()} {doctor.stderr.strip()}")
2285
+ return 1
2286
+ granted = run_keel(verify, "shift", "ready", "--wake", *reason, "verify note: R015", env=desktop)
2287
+ if "Standing-authorized by `self-shift`" not in granted.stdout:
2288
+ report(f"{label} a desktop ready --wake with self-shift declared does not say the steps are standing-authorized: {granted.stdout.strip()} {granted.stderr.strip()}")
2289
+ return 1
2290
+ # Three once the Remote Control step went (#324).
2291
+ if "take these four steps now" not in granted.stdout:
2292
+ report(f"{label} a desktop ready --wake with self-shift declared does not cover four steps: {granted.stdout.strip()}")
2293
+ return 1
2294
+ run_keel(verify, "shift", "resume", env=desktop)
2295
+
2296
+ declare("commit")
2297
+ asked = run_keel(verify, "shift", "ready", "--wake", *reason, "verify note: R016", env=desktop)
2298
+ if "Standing-authorized by `self-shift`" in asked.stdout:
2299
+ report(f"{label} a desktop ready --wake without self-shift says the steps are standing-authorized: {asked.stdout.strip()}")
2300
+ return 1
2301
+ if "self-shift" not in asked.stdout:
2302
+ report(f"{label} a desktop ready --wake without self-shift does not name the declaration that would allow it: {asked.stdout.strip()}")
2303
+ return 1
2304
+ run_keel(verify, "shift", "resume", env=desktop)
2305
+
2306
+ declare("commit", "self-shift:anything")
2307
+ scoped = run_keel(verify, "--doctor", env=env)
2308
+ combined = scoped.stdout + scoped.stderr
2309
+ if "self-shift:anything" not in combined or "commit: authorized" in combined:
2310
+ report(f"{label} a scoped self-shift was not refused by name: {combined.strip()}")
2311
+ return 1
2312
+
2313
+ for relative in ("README.md", "docs/shift-change.md", "docs/shift-change.zh-CN.md"):
2314
+ if "self-shift" not in (ROOT / relative).read_text(encoding="utf-8"):
2315
+ report(f"{label} {relative} does not name self-shift.")
2316
+ return 1
2317
+ if "self-shift-authorization" not in {name for name, _ in registry.SCENARIOS}:
2318
+ report(f"{label} scenario is not registered.")
2319
+ return 1
2320
+ report("self-shift-authorization scenario passed.")
2321
+ return 0
2322
+
2323
+
2324
+ def validate_shift_restore_authorization_scenario() -> int:
2325
+ """Issue #319: `shift-restore` lets a woken desktop shift restore itself.
2326
+
2327
+ The name is read and listed by `--doctor`, a scoped form is refused, and
2328
+ a desktop `keel shift resume` says the restore is standing-authorized only
2329
+ when the repository declares it.
2330
+ """
2331
+ label = "shift-restore-authorization:"
2332
+ with tempfile.TemporaryDirectory(prefix="keel-shift-restore-") as raw:
2333
+ base = Path(raw)
2334
+ _rtl, verify, env, _ = shift_scratch(base)
2335
+ env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000"}
2336
+ desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319"}
2337
+ config = verify / "keel" / "config.yaml"
2338
+
2339
+ def declare(*entries: str) -> None:
2340
+ write_text(config, "authorize:\n" + "".join(f" - {entry}\n" for entry in entries))
2341
+
2342
+ declare("commit", "shift-restore")
2343
+ doctor = run_keel(verify, "--doctor", env=env)
2344
+ if "shift-restore" not in doctor.stdout:
2345
+ report(f"{label} keel --doctor does not list shift-restore: {doctor.stdout.strip()} {doctor.stderr.strip()}")
2346
+ return 1
2347
+ if "unrecognized" in (doctor.stdout + doctor.stderr).lower():
2348
+ report(f"{label} shift-restore was not read as a standing authorization: {doctor.stdout.strip()} {doctor.stderr.strip()}")
2349
+ return 1
2350
+ run_keel(verify, "shift", "ready", "--wake", "--force-reason", "the fixture config is uncommitted", "verify note: R013", env=desktop)
2351
+ granted = run_keel(verify, "shift", "resume", env=desktop)
2352
+ if "Standing-authorized by `shift-restore`" not in granted.stdout:
2353
+ report(f"{label} a desktop resume with shift-restore declared does not say it is standing-authorized: {granted.stdout.strip()}")
2354
+ return 1
2355
+
2356
+ declare("commit")
2357
+ run_keel(verify, "shift", "ready", "--wake", "--force-reason", "the fixture config is uncommitted", "verify note: R014", env=desktop)
2358
+ asked = run_keel(verify, "shift", "resume", env=desktop)
2359
+ if "Standing-authorized" in asked.stdout:
2360
+ report(f"{label} a desktop resume without shift-restore says the restore is standing-authorized: {asked.stdout.strip()}")
2361
+ return 1
2362
+ if "shift-restore" not in asked.stdout:
2363
+ report(f"{label} a desktop resume without shift-restore does not name the declaration that would allow it: {asked.stdout.strip()}")
2364
+ return 1
2365
+
2366
+ declare("commit", "shift-restore:anything")
2367
+ scoped = run_keel(verify, "--doctor", env=env)
2368
+ combined = scoped.stdout + scoped.stderr
2369
+ if "shift-restore:anything" not in combined or "commit: authorized" in combined:
2370
+ report(f"{label} a scoped shift-restore was not refused by name: {combined.strip()}")
2371
+ return 1
2372
+
2373
+ if "shift-restore" not in (ROOT / "README.md").read_text(encoding="utf-8"):
2374
+ report(f"{label} README.md does not document shift-restore.")
2375
+ return 1
2376
+ if "shift-restore-authorization" not in {name for name, _ in registry.SCENARIOS}:
2377
+ report(f"{label} scenario is not registered.")
2378
+ return 1
2379
+ report("shift-restore-authorization scenario passed.")
2380
+ return 0
2381
+
2382
+
2383
+ def validate_shift_await_clear_scenario() -> int:
2384
+ """`keel shift await-clear` returns once the outgoing process is gone.
2385
+
2386
+ The desktop wake starts at once and waits on it, so it can never land
2387
+ before the clear (D1, D2 of shift-desktop-wake-in-a-minute).
2388
+ """
2389
+ label = "shift-await-clear:"
2390
+ with tempfile.TemporaryDirectory(prefix="keel-shift-await-") as raw:
2391
+ base = Path(raw)
2392
+ _rtl, verify, env, _ = shift_scratch(base)
2393
+ # Reaped as soon as it exits, as the app reaps its session's process;
2394
+ # an unreaped zombie still answers kill(pid, 0).
2395
+ brief = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(1)"])
2396
+ reaper = threading.Thread(target=brief.wait)
2397
+ reaper.start()
2398
+ started = time.monotonic()
2399
+ gone = run_keel(verify, "shift", "await-clear", "--pid", str(brief.pid), "--timeout-ms", "15000", env=env)
2400
+ reaper.join()
2401
+ if gone.returncode != 0:
2402
+ report(f"{label} await-clear did not exit 0 once the process exited: {gone.returncode} {gone.stdout.strip()} {gone.stderr.strip()}")
2403
+ return 1
2404
+ if "cleared" not in gone.stdout:
2405
+ report(f"{label} await-clear did not say `cleared` once the process exited: {gone.stdout.strip()}")
2406
+ return 1
2407
+ if time.monotonic() - started > 10:
2408
+ report(f"{label} await-clear took more than 10 s to notice the process exited.")
2409
+ return 1
2410
+ live = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
2411
+ try:
2412
+ held = run_keel(verify, "shift", "await-clear", "--pid", str(live.pid), "--timeout-ms", "500", env=env)
2413
+ finally:
2414
+ live.kill()
2415
+ live.wait()
2416
+ if held.returncode != 1:
2417
+ report(f"{label} await-clear on a live process did not exit 1: {held.returncode} {held.stdout.strip()} {held.stderr.strip()}")
2418
+ return 1
2419
+ if "not cleared" not in held.stdout:
2420
+ report(f"{label} await-clear on a live process did not say `not cleared`: {held.stdout.strip()}")
2421
+ return 1
2422
+ desktop = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000", "CLAUDE_CODE_ENTRYPOINT": "claude-desktop",
2423
+ "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319", "KEEL_SHIFT_DESKTOP_PID": "4242"}
2424
+ armed = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R031", env=desktop)
2425
+ note = mailbox_common_dir(verify) / "keel-chat" / "shift" / "verify.md"
2426
+ if armed.returncode != 0:
2427
+ report(f"{label} a desktop ready --wake failed: {armed.stderr.strip()}")
2428
+ return 1
2429
+ if "Desktop process: 4242." not in note.read_text(encoding="utf-8"):
2430
+ report(f"{label} a desktop ready --wake does not record the desktop process.")
2431
+ return 1
2432
+ if "shift-await-clear" not in {name for name, _ in registry.SCENARIOS}:
2433
+ report(f"{label} scenario is not registered.")
2434
+ return 1
2435
+ report("shift-await-clear scenario passed.")
2436
+ return 0
2437
+
2438
+
2439
+ def validate_shift_start_desktop_scenario() -> int:
2440
+ """`keel shift start` names the wake step for a note written on the desktop app.
2441
+
2442
+ A desktop session with no running process sees no chat record, so the
2443
+ start record alone wakes nobody there (#320, D1 of
2444
+ shift-start-desktop-wake). Elsewhere the output is unchanged.
2445
+ """
2446
+ label = "shift-start-desktop:"
2447
+ with tempfile.TemporaryDirectory(prefix="keel-shift-start-desktop-") as raw:
2448
+ base = Path(raw)
2449
+ rtl, verify, env, _ = shift_scratch(base)
2450
+ desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-320", "KEEL_SHIFT_DESKTOP_PID": "4242"}
2451
+ ready = run_keel(verify, "shift", "ready", "verify note: next is R030", env=desktop)
2452
+ if ready.returncode != 0:
2453
+ report(f"{label} ready on the desktop app failed: {ready.stderr.strip()}")
2454
+ return 1
2455
+ started = run_keel(rtl, "shift", "start", "verify", env=env)
2456
+ if started.returncode != 0:
2457
+ report(f"{label} start failed: {started.stderr.strip()}")
2458
+ return 1
2459
+ read = run_keel(verify, "chat", "read", "dm-rtl--verify", env=env)
2460
+ if "keel shift resume" not in read.stdout:
2461
+ report(f"{label} the start record did not reach dm-rtl--verify: {read.stdout.strip()} {read.stderr.strip()}")
2462
+ return 1
2463
+ for needle in ("send_message", "get_session", "unarchive_session", "local_test-320", "keel shift resume"):
2464
+ if needle not in started.stdout:
2465
+ report(f"{label} start for a desktop note does not name {needle}: {started.stdout.strip()}")
2466
+ return 1
2467
+ if "Woke" in started.stdout:
2468
+ report(f"{label} start for a desktop note still says it woke the role: {started.stdout.strip()}")
2469
+ return 1
2470
+ run_keel(verify, "shift", "resume", env=env)
2471
+ plain = run_keel(verify, "shift", "ready", "verify note: next is R031", env=env)
2472
+ if plain.returncode != 0:
2473
+ report(f"{label} ready outside the desktop app failed: {plain.stderr.strip()}")
2474
+ return 1
2475
+ other = run_keel(rtl, "shift", "start", "verify", env=env)
2476
+ if "Woke verify" not in other.stdout or "send_message" in other.stdout:
2477
+ report(f"{label} start for a note with no desktop session changed: {other.stdout.strip()}")
2478
+ return 1
2479
+ for relative, word in (("docs/shift-change.md", "#320"), ("docs/shift-change.zh-CN.md", "#320")):
2480
+ if word not in (ROOT / relative).read_text(encoding="utf-8"):
2481
+ report(f"{label} {relative} does not mention {word}.")
2482
+ return 1
2483
+ if "shift-start-desktop" not in {name for name, _ in registry.SCENARIOS}:
2484
+ report(f"{label} scenario is not registered.")
2485
+ return 1
2486
+ report("shift-start-desktop scenario passed.")
2487
+ return 0
2488
+
2489
+
2490
+ # A claude for the hand-over's host contract (#408): `agents --json` from a rows
2491
+ # file, `stop` that drops the row's status and pid at once and ends the process
2492
+ # a second later (`late`) or never (`never`), as measured on 2.1.304 (row 0.32 s,
2493
+ # return 0.98 s, exit 3.2 s), `rm` that logs whether that process was still
2494
+ # running, and a new session for `--bg`.
2495
+ HANDOVER_CONTRACT_FAKE = """#!/usr/bin/env python3
2496
+ import json, os, subprocess, sys
2497
+ agents, calls, mode = os.environ['FAKE_AGENTS'], os.environ['FAKE_CALLS'], os.environ.get('FAKE_STOP_MODE', 'late')
2498
+ argv = sys.argv[1:]
2499
+ def running(pid):
2500
+ try:
2501
+ os.kill(pid, 0)
2502
+ except OSError:
2503
+ return False
2504
+ return True
2505
+ rows = json.loads(open(agents).read())
2506
+ record = {'argv': argv}
2507
+ if argv[:1] == ['rm']:
2508
+ gone = [row for row in rows if row['id'] == argv[1]]
2509
+ record['alive'] = bool(gone) and bool(gone[0].get('_pid')) and running(gone[0]['_pid'])
2510
+ rows = [row for row in rows if row['id'] != argv[1]]
2511
+ open(calls, 'a').write(json.dumps(record) + '\\n')
2512
+ if argv[:2] == ['agents', '--json']:
2513
+ print(json.dumps([{k: v for k, v in row.items() if not k.startswith('_')} for row in rows])); sys.exit(0)
2514
+ if argv[:1] == ['stop']:
2515
+ for row in rows:
2516
+ if row['id'] == argv[1] and 'status' in row:
2517
+ pid = row.pop('pid', None); row.pop('status', None); row['state'] = 'stopped'; row['_pid'] = pid
2518
+ if pid and mode == 'late':
2519
+ subprocess.Popen(['sh', '-c', f'sleep 1; kill {pid}'], start_new_session=True,
2520
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
2521
+ open(agents, 'w').write(json.dumps(rows)); print('stopped ' + argv[1]); sys.exit(0)
2522
+ if argv[:1] == ['--bg']:
2523
+ rows.append({'kind': 'background', 'name': 'verify', 'sessionId': 'newsess1-0000-0000-0000-000000000000', 'id': 'newsess1',
2524
+ 'status': 'busy', 'state': 'working', 'pid': os.getpid(), 'cwd': os.getcwd(), 'startedAt': 1792600000000})
2525
+ open(agents, 'w').write(json.dumps(rows)); print('backgrounded · newsess1 · verify'); sys.exit(0)
2526
+ open(agents, 'w').write(json.dumps(rows)); print('ok')
2527
+ """
2528
+
2529
+
2530
+ def detached_sleeper() -> int:
2531
+ """A process that is not this one's child, so a kill reaps it instead of leaving a zombie."""
2532
+ return int(subprocess.run(["sh", "-c", "sleep 600 >/dev/null 2>&1 & echo $!"], text=True,
2533
+ capture_output=True, check=True).stdout.strip())
2534
+
2535
+
2536
+ def validate_shift_cli_removes_after_exit_scenario() -> int:
2537
+ """Issue #408: a hand-over never removes a session whose process still runs.
2538
+
2539
+ Measured on Claude Code 2.1.304 (2026-10-21): after `claude stop` the row
2540
+ loses `status` and `pid` at 0.32 s, the command returns at 0.98 s, and the
2541
+ process exits about 3.2 s in. Since #418 the session just handed over is
2542
+ removed by default, so the removal waits for the process the note recorded.
2543
+ """
2544
+ label = "shift-cli-removes-after-exit:"
2545
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
2546
+ for mode in ("late", "never"):
2547
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408a-") as raw:
2548
+ base = Path(raw)
2549
+ rtl, verify, env, _ = shift_scratch(base)
2550
+ agents, calls, fake, config = base / "agents.json", base / "calls.jsonl", base / "fake-claude", base / "claude"
2551
+ write_text(fake, HANDOVER_CONTRACT_FAKE)
2552
+ fake.chmod(0o755)
2553
+ write_text(config / "projects" / host_project_name(verify) / f"{OLD}.jsonl",
2554
+ json.dumps({"type": "user", "message": {"role": "user", "content": "carry on"}}) + "\n")
2555
+ process = detached_sleeper()
2556
+ try:
2557
+ agents.write_text(json.dumps([{"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8],
2558
+ "status": "idle", "state": "done", "pid": process, "cwd": str(verify),
2559
+ "startedAt": 1792500000000}]))
2560
+ calls.write_text("")
2561
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config), "FAKE_AGENTS": str(agents),
2562
+ "FAKE_CALLS": str(calls), "FAKE_STOP_MODE": mode, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1",
2563
+ "KEEL_SHIFT_EXIT_WAIT_MS": "5000" if mode == "late" else "1500"}
2564
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(process)}
2565
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R030", env=cli_env)
2566
+ if readied.returncode != 0:
2567
+ report(f"{label} ready --wake failed: {readied.stderr!r}")
2568
+ return 1
2569
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
2570
+ removals = [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
2571
+ status = run_keel(rtl, "shift", "status", env=env).stdout
2572
+ if mode == "late":
2573
+ if [r["argv"][1] for r in removals] != [OLD[:8]]:
2574
+ report(f"{label} the hand-over did not remove the session just handed over once its process exited: {removals!r}")
2575
+ return 1
2576
+ if removals[0]["alive"]:
2577
+ report(f"{label} `claude rm` of the session just handed over ran while its process was still running.")
2578
+ return 1
2579
+ else:
2580
+ if removals:
2581
+ report(f"{label} a session whose process never exited was removed: {removals!r}")
2582
+ return 1
2583
+ if f"claude attach {OLD[:8]}" not in status:
2584
+ report(f"{label} shift status does not say the old session is kept for `claude attach`: {status!r}")
2585
+ return 1
2586
+ finally:
2587
+ with contextlib.suppress(OSError):
2588
+ os.kill(process, signal.SIGKILL)
2589
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
2590
+ report(f"{label} the scenario registry does not include it.")
2591
+ return 1
2592
+ report(f"{label.rstrip(':')} scenario passed.")
2593
+ return 0
2594
+
2595
+
2596
+ def validate_shift_cli_names_host_failure_scenario() -> int:
2597
+ """Issue #408: a hand-off the host cannot be asked about says why it waits."""
2598
+ label = "shift-cli-names-host-failure:"
2599
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
2600
+ for case, needle in (("missing", "claude was not found"), ("garbled", "agents --json")):
2601
+ with tempfile.TemporaryDirectory(prefix="keel-shift-408b-") as raw:
2602
+ base = Path(raw)
2603
+ rtl, verify, env, _ = shift_scratch(base)
2604
+ claude = base / "no-claude"
2605
+ if case == "garbled":
2606
+ write_text(claude, "#!/bin/sh\necho 'not a list'\n")
2607
+ claude.chmod(0o755)
2608
+ env = {**env, "KEEL_CLAUDE": str(claude), "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
2609
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
2610
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R031", env=cli_env)
2611
+ if readied.returncode != 0:
2612
+ report(f"{label} ready --wake failed ({case}): {readied.stderr!r}")
2613
+ return 1
2614
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
2615
+ status = run_keel(rtl, "shift", "status", env=env).stdout
2616
+ if "pending" not in status:
2617
+ report(f"{label} the hand-off is no longer pending ({case}): {status!r}")
2618
+ return 1
2619
+ if needle not in status:
2620
+ report(f"{label} shift status does not name why the hand-off waits ({case}, expected {needle!r}): {status!r}")
2621
+ return 1
2622
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
2623
+ report(f"{label} the scenario registry does not include it.")
2624
+ return 1
2625
+ report(f"{label.rstrip(':')} scenario passed.")
2626
+ return 0
2627
+
2628
+
2629
+ def validate_tick_retries_failed_wake_scenario() -> int:
2630
+ """Issue #408: a tick retries a failed wake a bounded number of times.
2631
+
2632
+ A tick marked the role woken whether or not the resume worked, so one
2633
+ failure was never retried; a removed session is not tried again either.
2634
+ """
2635
+ label = "tick-retries-failed-wake:"
2636
+ for case in ("failing", "removed"):
2637
+ with tempfile.TemporaryDirectory(prefix="keel-tick-408c-") as raw:
2638
+ base = Path(raw)
2639
+ rtl, verify, env, _ = shift_scratch(base)
2640
+ calls = base / "calls.jsonl"
2641
+ fake = base / "fake-claude"
2642
+ listed = "['sess-verify-1']" if case == "failing" else "['other-0000']"
2643
+ write_text(fake, "#!/usr/bin/env python3\nimport json, sys\n"
2644
+ f"open({str(calls)!r}, 'a').write(json.dumps(sys.argv[1:]) + '\\n')\n"
2645
+ "if sys.argv[1:3] == ['agents', '--json']:\n"
2646
+ f" print(json.dumps([{{'kind': 'background', 'sessionId': s, 'id': s[:8]}} for s in {listed}])); sys.exit(0)\n"
2647
+ "if sys.argv[1:2] == ['--bg']:\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n")
2648
+ fake.chmod(0o755)
2649
+ env = {**env, "KEEL_CLAUDE": str(fake)}
2650
+ dead = subprocess.Popen(["true"])
2651
+ dead.wait()
2652
+ chat_session_start(verify, env, "sess-verify-1", dead.pid)
2653
+ run_keel(rtl, "chat", "dm", "verify", "rerun R032", env=env)
2654
+ for _ in range(4):
2655
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
2656
+ made = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2657
+ resumes = [call for call in made if call[:2] == ["--bg", "--resume"]]
2658
+ lookups = [call for call in made if call[:2] == ["agents", "--json"]]
2659
+ if case == "failing" and len(resumes) != 3:
2660
+ report(f"{label} four ticks tried a failing resume {len(resumes)} times, not 3.")
2661
+ return 1
2662
+ if case == "removed" and resumes:
2663
+ report(f"{label} a removed session was resumed: {resumes!r}")
2664
+ return 1
2665
+ if case == "removed" and len(lookups) != 1:
2666
+ report(f"{label} four ticks looked up a removed session {len(lookups)} times, not once.")
2667
+ return 1
2668
+ if label.rstrip(":") not in {name for name, _ in registry.SCENARIOS}:
2669
+ report(f"{label} the scenario registry does not include it.")
2670
+ return 1
2671
+ report(f"{label.rstrip(':')} scenario passed.")
2672
+ return 0
2673
+
2674
+
2675
+ def validate_shift_cli_self_shift_scenario() -> int:
2676
+ """Issues #357 and #388 on the CLI (owner, 2026-10-19): hand over, promptly, and retire.
2677
+
2678
+ A CLI session cannot clear itself. `keel shift ready --wake` there queues
2679
+ the hand-off and leaves a waiter that, once the old session has finished,
2680
+ retires it (stop, rename by resuming it with `/rename`, stop) and starts a
2681
+ new session in the role's worktree that runs `keel shift resume`. `keel
2682
+ tick` carries out a queued hand-off too, and the two start one session. A
2683
+ session that is busy, or waiting for input (blocked on a question), is left
2684
+ alone; its job state is not read (#393). `keel shift status` shows the queue, and a
2685
+ failed start is a patrol risk.
2686
+ """
2687
+ label = "shift-cli-self-shift:"
2688
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
2689
+ with tempfile.TemporaryDirectory(prefix="keel-shift-357-") as raw:
2690
+ base = Path(raw)
2691
+ rtl, verify, env, _ = shift_scratch(base)
2692
+ calls, agents, fail, norename = base / "claude-calls.jsonl", base / "agents.json", base / "fail-start", base / "no-rename"
2693
+ stoplag = base / "stop-lag"
2694
+ fake = base / "fake-claude"
2695
+ # The fake answers with the shapes measured on Claude Code 2.1.303: a live row has `status`, `state` and `pid`; a stopped one has `state: stopped` and neither.
2696
+ # `stop` drops the row's status at once and ends its process later (#397: 0.83 s against 2.68 s measured): about a second
2697
+ # later with `stop-lag` holding `late`, never with `never`, at once otherwise. A resume while the process runs starts a copy that takes the name.
2698
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, subprocess, sys\n"
2699
+ f"agents, fail, norename, stoplag = {str(agents)!r}, {str(fail)!r}, {str(norename)!r}, {str(stoplag)!r}\n"
2700
+ f"open({str(calls)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], 'cwd': os.getcwd(), 'claude_env': sorted(k for k in os.environ if k.startswith('CLAUDE'))}}) + '\\n')\n"
2701
+ "argv = sys.argv[1:]\n"
2702
+ "def running(pid):\n"
2703
+ " try:\n os.kill(pid, 0)\n except OSError:\n return False\n return True\n"
2704
+ "rows = json.loads(open(agents).read())\n"
2705
+ "if argv[:2] == ['agents', '--json']:\n"
2706
+ " print(json.dumps([{k: v for k, v in row.items() if not k.startswith('_')} for row in rows])); sys.exit(0)\n"
2707
+ "if argv[:1] == ['stop']:\n"
2708
+ " lag = open(stoplag).read().strip() if os.path.exists(stoplag) else 'now'\n"
2709
+ " for row in rows:\n if row['id'] == argv[1] and 'status' in row:\n"
2710
+ " pid = row.pop('pid', None); row.pop('status', None); row['state'] = 'stopped'; row['_pid'] = pid\n"
2711
+ " if pid and lag == 'now':\n os.kill(pid, 15)\n"
2712
+ " elif pid and lag == 'late':\n subprocess.Popen(['sh', '-c', f'sleep 1; kill {pid}'], start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n"
2713
+ " open(agents, 'w').write(json.dumps(rows)); print('stopped ' + argv[1]); sys.exit(0)\n"
2714
+ "if argv[:2] == ['--bg', '--resume']:\n"
2715
+ " name = argv[3].split(None, 1)[1]\n"
2716
+ " live = [row for row in rows if row['sessionId'] == argv[2] and ('status' in row or (row.get('_pid') and running(row['_pid'])))]\n"
2717
+ " if live:\n"
2718
+ " copy = {k: v for k, v in live[0].items() if not k.startswith('_')}\n"
2719
+ " rows.append({**copy, 'sessionId': 'c0c0c0c0-0000-0000-0000-000000000000', 'id': 'c0c0c0c0', 'name': name, 'status': 'idle', 'state': 'working'})\n"
2720
+ " print('note: session ' + argv[2][:8] + ' is already running in the background, so this started a copy as c0c0c0c0.')\n"
2721
+ " for row in rows:\n if row['sessionId'] == argv[2] and not live and not os.path.exists(norename):\n row['name'] = name\n"
2722
+ " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · ' + ('c0c0c0c0' if live else argv[2][:8])); sys.exit(0)\n"
2723
+ "if argv[:1] == ['--bg'] and os.path.exists(fail):\n print('Workspace not trusted.', file=sys.stderr); sys.exit(1)\n"
2724
+ "if argv[:1] == ['--bg']:\n print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
2725
+ "print('stopped')\n")
2726
+ fake.chmod(0o755)
2727
+ env = {**env, "KEEL_CLAUDE": str(fake), "KEEL_SHIFT_HANDOVER_POLL_MS": "200", "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "20000"}
2728
+ # With the waiter given no time, a hand-over is the tick's alone.
2729
+ tick_only = {**env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
2730
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(os.getpid())}
2731
+ queue = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "queue"
2732
+
2733
+ children: list[int] = []
2734
+
2735
+ def end_children() -> None:
2736
+ for pid in children:
2737
+ with contextlib.suppress(OSError):
2738
+ os.kill(pid, signal.SIGTERM)
2739
+
2740
+ atexit.register(end_children)
2741
+
2742
+ def agents_row(status: str | None, state: str, name: str = "verify") -> None:
2743
+ row = {"kind": "background", "name": name, "sessionId": OLD, "id": OLD[:8], "state": state, "cwd": str(verify)}
2744
+ if status:
2745
+ # The session's process: a real one, detached so that once killed it is reaped
2746
+ # rather than left a zombie the hand-over would still see running.
2747
+ started = subprocess.run(["sh", "-c", "sleep 600 >/dev/null 2>&1 & echo $!"], capture_output=True, text=True, check=True)
2748
+ children.append(int(started.stdout.strip()))
2749
+ row["status"] = status
2750
+ row["pid"] = children[-1]
2751
+ if status == "waiting":
2752
+ row["waitingFor"] = "input needed"
2753
+ agents.write_text(json.dumps([row]))
2754
+
2755
+ def rows() -> list[dict]:
2756
+ return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []
2757
+
2758
+ def acted() -> list[list[str]]:
2759
+ return [r["argv"] for r in rows() if r["argv"][:2] != ["agents", "--json"]]
2760
+
2761
+ def starts() -> list[dict]:
2762
+ return [r for r in rows() if r["argv"][:1] == ["--bg"] and "--resume" not in r["argv"]]
2763
+
2764
+ def tick() -> subprocess.CompletedProcess[str]:
2765
+ return run_keel(verify, "tick", "--repo", str(rtl), env=tick_only)
2766
+
2767
+ def status_text() -> str:
2768
+ return run_keel(rtl, "shift", "status", env=env).stdout
2769
+
2770
+ def wait_for(condition, seconds: float = 10.0) -> bool:
2771
+ deadline = time.time() + seconds
2772
+ while time.time() < deadline:
2773
+ if condition():
2774
+ return True
2775
+ time.sleep(0.2)
2776
+ return condition()
2777
+
2778
+ agents_row("busy", "working")
2779
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R012", env=cli_env)
2780
+ if readied.returncode != 0:
2781
+ report(f"{label} ready --wake in a CLI session failed: {readied.stdout!r} {readied.stderr!r}")
2782
+ return 1
2783
+ # #418: nothing is kept by default, so the old session is removed and read through Keel's copy.
2784
+ if "keel shift history verify --show" not in readied.stdout or "--wake" in readied.stderr:
2785
+ report(f"{label} ready --wake in a CLI session does not say how the old session is read once removed: {readied.stdout!r}")
2786
+ return 1
2787
+ note = next((mailbox_common_dir(rtl) / "keel-chat" / "shift").glob("verify.md"), None)
2788
+ if not note:
2789
+ report(f"{label} ready --wake stored no note for verify.")
2790
+ return 1
2791
+ if f"CLI session: {OLD}." not in note.read_text(encoding="utf-8"):
2792
+ report(f"{label} the note does not record the CLI session.")
2793
+ return 1
2794
+
2795
+ # A busy session, and one blocked on a question (measured: status waiting, state blocked), are left alone.
2796
+ time.sleep(1.0)
2797
+ if acted():
2798
+ report(f"{label} the hand-over acted while the old session was busy: {acted()!r}")
2799
+ return 1
2800
+ if "pending" not in status_text():
2801
+ report(f"{label} shift status does not show the pending hand-off: {status_text()!r}")
2802
+ return 1
2803
+ agents_row("waiting", "blocked")
2804
+ time.sleep(1.0)
2805
+ if acted():
2806
+ report(f"{label} the hand-over cut off a session blocked on a question (status waiting): {acted()!r}")
2807
+ return 1
2808
+
2809
+ # Finished: idle, though its state still labels its last message `working` (#393, keel-maint's
2810
+ # ended turn). The waiter stops it and starts the next, named for its start, with no tick (#399).
2811
+ agents_row("idle", "working")
2812
+ if not wait_for(lambda: len(starts()) >= 1):
2813
+ report(f"{label} the waiter did not hand over without a tick: {acted()!r}")
2814
+ return 1
2815
+ order = acted()
2816
+ if any(argv[:2] == ["--bg", "--resume"] for argv in order):
2817
+ report(f"{label} the hand-over woke the old session to rename it: {order!r}")
2818
+ return 1
2819
+ if order[:1] != [["stop", OLD[:8]]] or len(order) != 2:
2820
+ report(f"{label} the old session was not retired as one stop before the new start: {order!r}")
2821
+ return 1
2822
+ named = re.compile(r"^verify · \d{2}-\d{2} \d{2}:\d{2}$")
2823
+ if order[1][:2] != ["--bg", "-n"] or not named.match(order[1][2]) or order[1][3:5] != ["--permission-mode", "auto"]:
2824
+ report(f"{label} the new session is not started as `verify · <MM-DD HH:MM>`: {order[1]!r}")
2825
+ return 1
2826
+ if "keel shift resume" not in order[1][-1] or "--resume" in order[1]:
2827
+ report(f"{label} the new session does not start fresh with a keel shift resume prompt: {order[1]!r}")
2828
+ return 1
2829
+ if os.path.realpath(starts()[0]["cwd"]) != os.path.realpath(verify):
2830
+ report(f"{label} the new session started in {starts()[0]['cwd']}, not verify's worktree.")
2831
+ return 1
2832
+ leaked = [r for r in rows() if r["claude_env"]]
2833
+ if leaked:
2834
+ report(f"{label} a claude the hand-over ran inherited the old session's {leaked[0]['claude_env']!r}.")
2835
+ return 1
2836
+ text = status_text()
2837
+ for needle in ("delivered", "newsess1", f"claude attach {OLD[:8]}", order[1][2]):
2838
+ if needle not in text:
2839
+ report(f"{label} shift status does not show {needle!r} for the delivered hand-off: {text!r}")
2840
+ return 1
2841
+ tick()
2842
+ if len(starts()) != 1 or len(acted()) != 2:
2843
+ report(f"{label} a tick after the hand-over acted again: {acted()!r}")
2844
+ return 1
2845
+
2846
+ # The tick and the waiter start one session: a fresh lock holds the tick off.
2847
+ calls.write_text("")
2848
+ agents_row("idle", "done")
2849
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R014", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
2850
+ lock = queue / "verify.lock"
2851
+ write_text(lock, "held")
2852
+ tick()
2853
+ if acted():
2854
+ report(f"{label} a tick acted while another hand-over held the lock: {acted()!r}")
2855
+ return 1
2856
+ lock.unlink()
2857
+ tick()
2858
+ if len(starts()) != 1:
2859
+ report(f"{label} the tick did not start one session once the lock was gone: {acted()!r}")
2860
+ return 1
2861
+ tick()
2862
+ if len(starts()) != 1:
2863
+ report(f"{label} a second tick started another session.")
2864
+ return 1
2865
+
2866
+ # A start that fails stays visible and is a patrol risk.
2867
+ calls.write_text("")
2868
+ agents_row("idle", "done")
2869
+ write_text(fail, "x")
2870
+ run_keel(verify, "shift", "ready", "--wake", "next: rerun R013", env={**cli_env, "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"})
2871
+ tick()
2872
+ text = status_text()
2873
+ for needle in ("failed", "Workspace not trusted"):
2874
+ if needle not in text:
2875
+ report(f"{label} a failed start does not show {needle!r}: {text!r}")
2876
+ return 1
2877
+ patrolled = run_keel(rtl, "patrol", env=env).stdout
2878
+ if not re.search(r"risk: .*verify.*hand-off", patrolled):
2879
+ report(f"{label} the patrol does not report the failed hand-off as a risk: {patrolled!r}")
2880
+ return 1
2881
+ if "shift-cli-self-shift" not in {name for name, _ in registry.SCENARIOS}:
2882
+ report(f"{label} scenario is not registered.")
2883
+ return 1
2884
+ report("shift-cli-self-shift scenario passed.")
2885
+ return 0
2886
+
2887
+
2888
+ def validate_shift_cli_keeps_old_sessions_scenario() -> int:
2889
+ """Issue #397 (owner, 2026-10-20): each CLI shift leaves a stopped session, and the list kept growing.
2890
+
2891
+ After a delivered hand-over, the newest `shift: keep_old_sessions:`
2892
+ (default 0 since #418, so the shift just handed over goes too) stopped background sessions in the role's bound worktrees stay
2893
+ listed; each older one is removed with `claude rm` once Keel's store holds
2894
+ a copy of its transcript. Only a session with a transcript, the host's or
2895
+ Keel's copy, counts (#401): one whose transcript is nowhere takes no slot and
2896
+ stays, and so do another role's sessions and the new one.
2897
+ """
2898
+ label = "shift-cli-keeps-old-sessions:"
2899
+ OLD = "5b14fbae-b6aa-40b6-a72a-b3f89d2c6eea"
2900
+ with tempfile.TemporaryDirectory(prefix="keel-shift-397-") as raw:
2901
+ base = Path(raw)
2902
+ rtl, verify, env, _ = shift_scratch(base)
2903
+ calls, agents = base / "claude-calls.jsonl", base / "agents.json"
2904
+ config_dir = base / "claude-config"
2905
+ kept_dir = mailbox_common_dir(rtl) / "keel-chat" / "shift" / "transcripts" / "verify"
2906
+ fake = base / "fake-claude"
2907
+ # Shapes measured on Claude Code 2.1.303: a live row has `status` and `pid`, a stopped one neither (#397 F3);
2908
+ # `rm` drops the row and leaves the transcript (F4). Each `rm` logs whether Keel's copy was there when it ran.
2909
+ write_text(fake, "#!/usr/bin/env python3\nimport json, os, sys\n"
2910
+ f"agents, kept = {str(agents)!r}, {str(kept_dir)!r}\n"
2911
+ "argv = sys.argv[1:]\n"
2912
+ "rows = json.loads(open(agents).read())\n"
2913
+ "record = {'argv': argv}\n"
2914
+ "if argv[:1] == ['rm']:\n"
2915
+ " gone = [row for row in rows if row['id'] == argv[1]]\n"
2916
+ " record['kept'] = bool(gone) and os.path.exists(os.path.join(kept, gone[0]['sessionId'] + '.jsonl.gz'))\n"
2917
+ " rows = [row for row in rows if row['id'] != argv[1]]\n"
2918
+ f"open({str(calls)!r}, 'a').write(json.dumps(record) + '\\n')\n"
2919
+ "if argv[:2] == ['agents', '--json']:\n print(json.dumps(rows)); sys.exit(0)\n"
2920
+ "if argv[:1] == ['stop']:\n"
2921
+ " for row in rows:\n if row['id'] == argv[1]:\n row.pop('status', None); row.pop('pid', None); row['state'] = 'stopped'\n"
2922
+ "if argv[:1] == ['--bg'] and '--resume' not in argv:\n"
2923
+ " rows.append({'kind': 'background', 'name': 'verify', 'sessionId': 'newsess1-0000-0000-0000-000000000000', 'id': 'newsess1',\n"
2924
+ " 'status': 'busy', 'state': 'working', 'pid': os.getpid(), 'cwd': os.getcwd(), 'startedAt': 1792500000000})\n"
2925
+ " open(agents, 'w').write(json.dumps(rows)); print('backgrounded · newsess1 · verify'); sys.exit(0)\n"
2926
+ "open(agents, 'w').write(json.dumps(rows)); print('ok'); sys.exit(0)\n")
2927
+ fake.chmod(0o755)
2928
+ env = {**env, "KEEL_CLAUDE": str(fake), "CLAUDE_CONFIG_DIR": str(config_dir), "KEEL_SHIFT_HANDOVER_TIMEOUT_MS": "1"}
2929
+ # The process the note records has exited by the time the hand-over removes the session,
2930
+ # as on the host; #408 makes the removal wait for it.
2931
+ exited = subprocess.Popen(["true"])
2932
+ exited.wait()
2933
+ cli_env = {**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": OLD, "CLAUDE_PID": str(exited.pid)}
2934
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
2935
+ bound = {role: path for path, role in roles.items()}
2936
+
2937
+ def transcript(cwd: str, session: str, said: str) -> None:
2938
+ project = config_dir / "projects" / re.sub(r"[^A-Za-z0-9]", "-", cwd)
2939
+ project.mkdir(parents=True, exist_ok=True)
2940
+ (project / f"{session}.jsonl").write_text("\n".join(json.dumps(record) for record in (
2941
+ {"type": "user", "timestamp": "2026-10-19T01:00:00.000Z", "cwd": cwd, "message": {"role": "user", "content": "carry on"}},
2942
+ {"type": "assistant", "timestamp": "2026-10-19T01:00:05.000Z", "cwd": cwd,
2943
+ "message": {"role": "assistant", "content": [{"type": "text", "text": said}]}},
2944
+ )) + "\n", encoding="utf-8")
2945
+
2946
+ def old_row(n: int, cwd: str, with_transcript: bool = True) -> dict:
2947
+ session = f"0{n}0{n}0{n}0{n}-0000-0000-0000-00000000000{n}"
2948
+ if with_transcript:
2949
+ transcript(cwd, session, f"old shift {n}")
2950
+ return {"kind": "background", "name": "verify", "sessionId": session, "id": session[:8], "state": "stopped",
2951
+ "cwd": cwd, "startedAt": 1792400000000 + n * 1000}
2952
+
2953
+ def setup(keep: str | None, olds: list[dict]) -> None:
2954
+ calls.write_text("")
2955
+ config = verify / "keel" / "config.yaml"
2956
+ config.parent.mkdir(parents=True, exist_ok=True)
2957
+ config.write_text(f"shift:\n keep_old_sessions: {keep}\n" if keep is not None else "", encoding="utf-8")
2958
+ subprocess.run(["git", "add", "keel/config.yaml"], cwd=verify, check=True, capture_output=True)
2959
+ subprocess.run(["git", "commit", "-q", "--allow-empty", "-m", f"keep {keep}"], cwd=verify, check=True, capture_output=True)
2960
+ subprocess.run(["git", "push", "-q", "origin", "HEAD"], cwd=verify, check=True, capture_output=True)
2961
+ transcript(bound["verify"], OLD, "the shift handing over")
2962
+ live = {"kind": "background", "name": "verify", "sessionId": OLD, "id": OLD[:8], "status": "idle", "state": "working",
2963
+ "cwd": bound["verify"], "startedAt": 1792490000000}
2964
+ agents.write_text(json.dumps([*olds, live]))
2965
+ readied = run_keel(verify, "shift", "ready", "--wake", "next: rerun R020", env=cli_env)
2966
+ if readied.returncode != 0:
2967
+ raise RuntimeError(f"ready --wake failed: {readied.stderr!r}")
2968
+ run_keel(verify, "tick", "--repo", str(rtl), env=env)
2969
+
2970
+ def removed() -> list[dict]:
2971
+ return [json.loads(line) for line in calls.read_text().splitlines() if json.loads(line)["argv"][:1] == ["rm"]]
2972
+
2973
+ # #401: a session never given a prompt has no transcript and is not a shift, so it takes no kept slot even
2974
+ # when it is newer than the others; one whose host transcript is gone but Keel holds a copy still counts.
2975
+ copy_only = old_row(1, bound["verify"], with_transcript=False)
2976
+ kept_dir.mkdir(parents=True, exist_ok=True)
2977
+ (kept_dir / f"{copy_only['sessionId']}.jsonl.gz").write_bytes(gzip.compress(b'{"type": "user"}\n'))
2978
+ olds = [copy_only, old_row(2, bound["verify"]), old_row(3, bound["verify"]), old_row(4, bound["verify"]),
2979
+ old_row(6, bound["verify"], with_transcript=False), old_row(5, bound["rtl"])]
2980
+ setup("2", olds)
2981
+ gone = removed()
2982
+ if not gone:
2983
+ report(f"{label} the hand-over removed no old session: {calls.read_text()!r}")
2984
+ return 1
2985
+ ids = sorted(r["argv"][1] for r in gone)
2986
+ if ids != ["01010101", "02020202", "03030303"]:
2987
+ report(f"{label} with keep_old_sessions 2 the removed sessions are {ids!r}, "
2988
+ "not the oldest beyond the two newest with a transcript.")
2989
+ return 1
2990
+ if not all(r["kept"] for r in gone):
2991
+ report(f"{label} a session was removed before Keel's store held its transcript: {gone!r}")
2992
+ return 1
2993
+ left = {row["id"] for row in json.loads(agents.read_text())}
2994
+ for keep_id, why in (("06060606", "the session with no transcript"), ("05050505", "rtl's session"),
2995
+ ("newsess1", "the new session"), (OLD[:8], "the shift just handed over"), ("04040404", "the second newest old session")):
2996
+ if keep_id not in left:
2997
+ report(f"{label} {why} ({keep_id}) was removed: {sorted(left)!r}")
2998
+ return 1
2999
+ text = run_keel(rtl, "shift", "status", env=env).stdout
3000
+ if "01010101" not in text or "02020202" not in text:
3001
+ report(f"{label} shift status does not name the removed sessions: {text!r}")
3002
+ return 1
3003
+
3004
+ # #418 (owner, 2026-10-21): no declaration keeps none, so the shift just handed over leaves the
3005
+ # session list too; a value that is not a whole number is named and none are kept.
3006
+ for keep in (None, "many"):
3007
+ olds = [old_row(1, bound["verify"]), old_row(2, bound["verify"]), old_row(4, bound["verify"])]
3008
+ setup(keep, olds)
3009
+ ids = sorted(r["argv"][1] for r in removed())
3010
+ if ids != sorted(["01010101", "02020202", "04040404", OLD[:8]]):
3011
+ report(f"{label} the default keeps the wrong number of old sessions (keep_old_sessions {keep!r}): removed {ids!r}")
3012
+ return 1
3013
+ if not all(r["kept"] for r in removed()):
3014
+ report(f"{label} a session was removed before Keel's store held its transcript: {removed()!r}")
3015
+ return 1
3016
+ if f"keel shift history verify --show {OLD[:8]}" not in run_keel(rtl, "shift", "status", env=env).stdout:
3017
+ report(f"{label} shift status does not say how the removed old shift is read: {run_keel(rtl, 'shift', 'status', env=env).stdout!r}")
3018
+ return 1
3019
+ if keep == "many" and "keep_old_sessions" not in run_keel(rtl, "shift", "status", env=env).stdout:
3020
+ report(f"{label} an unreadable keep_old_sessions is not named: {run_keel(rtl, 'shift', 'status', env=env).stdout!r}")
3021
+ return 1
3022
+ if "shift-cli-keeps-old-sessions" not in {name for name, _ in registry.SCENARIOS}:
3023
+ report(f"{label} scenario is not registered.")
3024
+ return 1
3025
+ report("shift-cli-keeps-old-sessions scenario passed.")
3026
+ return 0
3027
+
3028
+
3029
+ def validate_shift_history_show_scenario() -> int:
3030
+ """Issue #397 (owner, 2026-10-20): a shift no longer in `claude agents` can be read in full.
3031
+
3032
+ `keel shift history <role> --show <id>` prints the whole conversation of the
3033
+ segment whose transcript name starts with the id — prompts, replies, tool
3034
+ calls and results, in order and in full — from the host's file or, once that
3035
+ is gone, Keel's kept copy. An id that names no segment exits 1.
3036
+ """
3037
+ label = "shift-history-show:"
3038
+ with tempfile.TemporaryDirectory(prefix="keel-shift-show-") as raw:
3039
+ base = Path(raw)
3040
+ rtl, verify, env, _ = shift_scratch(base)
3041
+ roles = json.loads((mailbox_common_dir(rtl) / "keel-chat" / "roles.json").read_text(encoding="utf-8"))
3042
+ bound = next(path for path, role in roles.items() if role == "verify")
3043
+ project = base / "claude-config" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", bound)
3044
+ project.mkdir(parents=True)
3045
+ env = {**env, "CLAUDE_CONFIG_DIR": str(base / "claude-config")}
3046
+ session = "4162aee5-7549-4801-b52f-871d553bdb5a"
3047
+ long_reply = "The arbiter keeps read priority over refresh. " * 12 + "End of the long reply."
3048
+ records = (
3049
+ {"type": "user", "timestamp": "2026-10-14T15:35:29.000Z", "cwd": bound, "message": {"role": "user", "content": "rerun R012 and report"}},
3050
+ {"type": "assistant", "timestamp": "2026-10-14T15:35:40.000Z", "cwd": bound,
3051
+ "message": {"role": "assistant", "content": [{"type": "text", "text": long_reply},
3052
+ {"type": "tool_use", "id": "toolu_1", "name": "Bash", "input": {"command": "make sim R012"}}]}},
3053
+ {"type": "user", "timestamp": "2026-10-14T15:36:02.000Z", "cwd": bound,
3054
+ "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "R012 PASS 4096/4096 vectors"}]}},
3055
+ )
3056
+ old = project / f"{session}.jsonl"
3057
+ old.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8")
3058
+
3059
+ def hook(path: Path) -> None:
3060
+ for event, name in (("session-start", "SessionStart"), ("user-prompt-submit", "UserPromptSubmit")):
3061
+ subprocess.run(
3062
+ ["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", event],
3063
+ cwd=verify, env=env, text=True, capture_output=True, check=False,
3064
+ input=json.dumps({"cwd": str(verify), "hook_event_name": name, "session_id": "s1",
3065
+ "prompt": "go", "source": "startup", "transcript_path": str(path)}),
3066
+ )
3067
+
3068
+ # The next shift's segments make Keel keep the old transcript; then the host's file goes.
3069
+ for name in ("a", "b"):
3070
+ path = project / f"{name}.jsonl"
3071
+ path.write_text(json.dumps({"type": "user", "timestamp": "2026-10-15T01:00:00.000Z", "cwd": bound,
3072
+ "message": {"role": "user", "content": "carry on"}}) + "\n", encoding="utf-8")
3073
+ hook(path)
3074
+ old.unlink()
3075
+ shown = run_keel(verify, "shift", "history", "verify", "--show", session[:8], env=env)
3076
+ if shown.returncode != 0:
3077
+ report(f"{label} --show of a kept shift exited {shown.returncode}: {shown.stdout!r} {shown.stderr!r}")
3078
+ return 1
3079
+ if "rerun R012 and report" not in shown.stdout:
3080
+ report(f"{label} --show printed no conversation: {shown.stdout!r} {shown.stderr!r}")
3081
+ return 1
3082
+ if session not in shown.stdout or "2026-10-14" not in shown.stdout.splitlines()[0]:
3083
+ report(f"{label} --show's header does not name the transcript and its time span: {shown.stdout.splitlines()[:2]!r}")
3084
+ return 1
3085
+ if long_reply not in shown.stdout:
3086
+ report(f"{label} --show cut the assistant's reply short: {shown.stdout!r}")
3087
+ return 1
3088
+ order = [shown.stdout.find(text) for text in ("rerun R012 and report", long_reply, "make sim R012", "R012 PASS 4096/4096 vectors")]
3089
+ if -1 in order:
3090
+ report(f"{label} --show leaves out the prompt, reply, tool call or result: {order!r} {shown.stdout!r}")
3091
+ return 1
3092
+ if order != sorted(order):
3093
+ report(f"{label} --show does not print the prompt, reply, tool call and result in order: {order!r} {shown.stdout!r}")
3094
+ return 1
3095
+ if "Bash" not in shown.stdout:
3096
+ report(f"{label} --show does not name the tool called: {shown.stdout!r}")
3097
+ return 1
3098
+
3099
+ unknown = run_keel(verify, "shift", "history", "verify", "--show", "00000000", env=env)
3100
+ if unknown.returncode != 1:
3101
+ report(f"{label} --show of an unknown id did not exit 1: {unknown.returncode} {unknown.stdout!r} {unknown.stderr!r}")
3102
+ return 1
3103
+ if "no segment" not in (unknown.stdout + unknown.stderr).lower():
3104
+ report(f"{label} --show of an unknown id does not say no segment matches: {unknown.stdout!r} {unknown.stderr!r}")
3105
+ return 1
3106
+ if "shift-history-show" not in {name for name, _ in registry.SCENARIOS}:
3107
+ report(f"{label} scenario is not registered.")
3108
+ return 1
3109
+ report("shift-history-show scenario passed.")
3110
+ return 0
3111
+
3112
+
3113
+ def validate_shift_desktop_wake_overdue_scenario() -> int:
3114
+ """`keel shift status` flags a desktop note whose wake is overdue.
3115
+
3116
+ A wake task that never runs leaves no trace anywhere else; the waiting
3117
+ note with its recorded desktop session is the one place a coordinator or
3118
+ patrol can see it (D2 of shift-desktop-wake-confirm).
3119
+ """
3120
+ label = "shift-desktop-wake-overdue:"
3121
+ with tempfile.TemporaryDirectory(prefix="keel-shift-overdue-") as raw:
3122
+ base = Path(raw)
3123
+ _rtl, verify, env, _ = shift_scratch(base)
3124
+ env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000"}
3125
+ desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319"}
3126
+ armed = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R021", env=desktop)
3127
+ if armed.returncode != 0:
3128
+ report(f"{label} ready --wake on the desktop app failed: {armed.stderr.strip()}")
3129
+ return 1
3130
+ young = run_keel(verify, "shift", "status", env={**env, "KEEL_SHIFT_WAKE_OVERDUE_MS": "3600000"})
3131
+ if "overdue" in young.stdout:
3132
+ report(f"{label} a note written just now is already called overdue: {young.stdout.strip()}")
3133
+ return 1
3134
+ late = run_keel(verify, "shift", "status", env={**env, "KEEL_SHIFT_WAKE_OVERDUE_MS": "0"})
3135
+ for needle in ("overdue", "local_test-319", "list_task_runs", "send_message"):
3136
+ if needle not in late.stdout:
3137
+ report(f"{label} status past the overdue time does not name {needle}: {late.stdout.strip()}")
3138
+ return 1
3139
+ # Without the override the overdue time is three minutes (D4 of
3140
+ # shift-desktop-wake-in-a-minute).
3141
+ note = mailbox_common_dir(verify) / "keel-chat" / "shift" / "verify.md"
3142
+ for minutes, flagged in ((2, False), (4, True)):
3143
+ then = time.time() - minutes * 60
3144
+ os.utime(note, (then, then))
3145
+ row = run_keel(verify, "shift", "status", env=env)
3146
+ if ("overdue" in row.stdout) != flagged:
3147
+ report(f"{label} a desktop note written {minutes} minutes ago is {'not ' if flagged else ''}flagged overdue by default: {row.stdout.strip()}")
3148
+ return 1
3149
+ run_keel(verify, "shift", "resume", env=env)
3150
+ plain = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R022", env=env)
3151
+ if plain.returncode != 0:
3152
+ report(f"{label} ready --wake outside the desktop app failed: {plain.stderr.strip()}")
3153
+ return 1
3154
+ other = run_keel(verify, "shift", "status", env={**env, "KEEL_SHIFT_WAKE_OVERDUE_MS": "0"})
3155
+ if "overdue" in other.stdout:
3156
+ report(f"{label} a note with no desktop session is called overdue: {other.stdout.strip()}")
3157
+ return 1
3158
+ for relative, word in (("docs/shift-change.md", "overdue"), ("docs/shift-change.zh-CN.md", "超时")):
3159
+ if word not in (ROOT / relative).read_text(encoding="utf-8"):
3160
+ report(f"{label} {relative} does not say {word}.")
3161
+ return 1
3162
+ if "shift-desktop-wake-overdue" not in {name for name, _ in registry.SCENARIOS}:
3163
+ report(f"{label} scenario is not registered.")
3164
+ return 1
3165
+ report("shift-desktop-wake-overdue scenario passed.")
3166
+ return 0
3167
+
3168
+
3169
+ def validate_shift_desktop_wake_scenario() -> int:
3170
+ """Issue #319: on the desktop app a clear starts no session until a prompt.
3171
+
3172
+ `ready --wake` there records the session id and prints the partner recipe
3173
+ (a one-shot scheduled task that `send_message`s the session, which turns
3174
+ Remote Control back on first) instead of promising the waiter wakes it;
3175
+ `resume` there says to restore Remote Control. Elsewhere nothing changes.
3176
+ """
3177
+ label = "shift-desktop-wake:"
3178
+ with tempfile.TemporaryDirectory(prefix="keel-shift-desktop-") as raw:
3179
+ base = Path(raw)
3180
+ _rtl, verify, env, _ = shift_scratch(base)
3181
+ env = {**env, "KEEL_SHIFT_WAKE_TIMEOUT_MS": "2000"}
3182
+ # The pid is pinned so the scenario does not depend on running under a `claude` process (CI does not).
3183
+ desktop = {**env, "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "CLAUDE_CODE_HOST_SESSION_ID": "local_test-319", "KEEL_SHIFT_DESKTOP_PID": "4242"}
3184
+ note = mailbox_common_dir(verify) / "keel-chat" / "shift" / "verify.md"
3185
+
3186
+ armed = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R011", env=desktop)
3187
+ if armed.returncode != 0:
3188
+ report(f"{label} ready --wake on the desktop app failed: {armed.stderr.strip()}")
3189
+ return 1
3190
+ if "Desktop session: local_test-319" not in note.read_text(encoding="utf-8"):
3191
+ report(f"{label} the note does not record the desktop session id.")
3192
+ return 1
3193
+ # Remote Control stays on: a clear is accepted with it on, and turning it
3194
+ # off waits for a person's approval (#324 comments 6164793777, 6165454422).
3195
+ for needle in ('set_remote_control("self", false)', "cannot be cleared"):
3196
+ if needle in armed.stdout:
3197
+ report(f"{label} the desktop clear hint still says {needle}: {armed.stdout.strip()}")
3198
+ return 1
3199
+ # The task, then rename and clear at once, so the wake cannot fire
3200
+ # before the clear (#319 comments 6143435530, 6144856601).
3201
+ for needle in ("create_scheduled_task", "send_message", "local_test-319", "set_session_title",
3202
+ "mcp__ccd_session_mgmt__set_remote_control", "shift-restore"):
3203
+ if needle not in armed.stdout:
3204
+ report(f"{label} the desktop clear hint does not name {needle}: {armed.stdout.strip()}")
3205
+ return 1
3206
+ task = armed.stdout.find("create_scheduled_task")
3207
+ if not task < armed.stdout.find("set_session_title", task) < armed.stdout.find("clear_session", task):
3208
+ report(f"{label} the desktop clear hint does not order create_scheduled_task, set_session_title, clear_session: {armed.stdout.strip()}")
3209
+ return 1
3210
+ if "new address" not in armed.stdout:
3211
+ report(f"{label} the desktop clear hint does not say Remote Control reconnects under a new address: {armed.stdout.strip()}")
3212
+ return 1
3213
+ # Dismissing bound PRs did not keep the app's auto-archive off the
3214
+ # cleared session: the engine archives on every PR the session ever
3215
+ # had, and `get_status` cannot see that set (#326 comment 6163697376).
3216
+ for needle in ("unbind_pr", "get_status"):
3217
+ if needle in armed.stdout:
3218
+ report(f"{label} the desktop clear hint still names {needle}: {armed.stdout.strip()}")
3219
+ return 1
3220
+ # The wake unarchives first, then sends (#326 D2 of shift-desktop-unarchive-wake).
3221
+ for needle in ("get_session", "unarchive_session", "mcp__ccd_session_mgmt__get_session",
3222
+ "mcp__ccd_session_mgmt__unarchive_session"):
3223
+ if needle not in armed.stdout:
3224
+ report(f"{label} the desktop clear hint does not name {needle}: {armed.stdout.strip()}")
3225
+ return 1
3226
+ look = armed.stdout.find("get_session")
3227
+ if not look < armed.stdout.find("unarchive_session") < armed.stdout.find("send_message", look):
3228
+ report(f"{label} the wake does not check get_session, then unarchive_session, then send_message: {armed.stdout.strip()}")
3229
+ return 1
3230
+ # The wake starts at once and waits for the clear itself, so no minute
3231
+ # tick sits in the shift (D3 of shift-desktop-wake-in-a-minute).
3232
+ for needle in ("await-clear", "run_scheduled_task", "keel-shift-wake-verify",
3233
+ "mcp__scheduled-tasks__run_scheduled_task"):
3234
+ if needle not in armed.stdout:
3235
+ report(f"{label} the desktop clear hint does not name {needle}: {armed.stdout.strip()}")
3236
+ return 1
3237
+ for needle in ("fireAt", "three minutes"):
3238
+ if needle in armed.stdout:
3239
+ report(f"{label} the desktop clear hint still schedules the wake ({needle}): {armed.stdout.strip()}")
3240
+ return 1
3241
+ made = armed.stdout.find("create_scheduled_task")
3242
+ run = armed.stdout.find("run_scheduled_task", made + 1)
3243
+ if not made < run < armed.stdout.find("set_session_title", run) < armed.stdout.find("clear_session", run):
3244
+ report(f"{label} the desktop clear hint does not order create, run_scheduled_task, rename, clear: {armed.stdout.strip()}")
3245
+ return 1
3246
+ waits = armed.stdout.find("await-clear")
3247
+ if not waits < armed.stdout.find("get_session", waits) < armed.stdout.find("send_message", waits):
3248
+ report(f"{label} the wake does not await the clear before get_session and send_message: {armed.stdout.strip()}")
3249
+ return 1
3250
+ # The wake confirms delivery: anything but delivered or queued after the
3251
+ # archived retry is a failed wake the owner hears about (D1 of
3252
+ # shift-desktop-wake-confirm).
3253
+ for needle in ("PushNotification", "WAKE FAILED", "delivered"):
3254
+ if needle not in armed.stdout[armed.stdout.find("send_message"):]:
3255
+ report(f"{label} the desktop wake does not say {needle} after send_message: {armed.stdout.strip()}")
3256
+ return 1
3257
+ if "archived copy" in armed.stdout:
3258
+ report(f"{label} the desktop clear hint still says the rename tells an archived copy apart: {armed.stdout.strip()}")
3259
+ return 1
3260
+ if "mcp__ccd_session_mgmt__clear_session" in armed.stdout:
3261
+ report(f"{label} the desktop clear hint still blames approval of clear_session: {armed.stdout.strip()}")
3262
+ return 1
3263
+ if "The wake is armed" in armed.stdout:
3264
+ report(f"{label} the desktop clear hint still says the waiter wakes the new session: {armed.stdout.strip()}")
3265
+ return 1
3266
+ resumed = run_keel(verify, "shift", "resume", env=desktop)
3267
+ if "next is R011" not in resumed.stdout:
3268
+ report(f"{label} resume on the desktop app did not print the note: {resumed.stdout.strip()} {resumed.stderr.strip()}")
3269
+ return 1
3270
+ if "set_remote_control" not in resumed.stdout or "get_session" not in resumed.stdout:
3271
+ report(f"{label} resume on the desktop app does not say to check Remote Control and turn it back on if off: {resumed.stdout.strip()}")
3272
+ return 1
3273
+ if "set_session_title" not in resumed.stdout:
3274
+ report(f"{label} resume on the desktop app does not say to rename the session back: {resumed.stdout.strip()}")
3275
+ return 1
3276
+
3277
+ plain = run_keel(verify, "shift", "ready", "--wake", "verify note: next is R012", env=env)
3278
+ if plain.returncode != 0:
3279
+ report(f"{label} ready --wake outside the desktop app failed: {plain.stderr.strip()}")
3280
+ return 1
3281
+ if "The wake is armed" not in plain.stdout:
3282
+ report(f"{label} outside the desktop app the clear hint no longer says the wake is armed: {plain.stdout.strip()}")
3283
+ return 1
3284
+ for needle in ("send_message", "create_scheduled_task", "set_session_title", "shift-restore",
3285
+ "unbind_pr", "get_session", "unarchive_session"):
3286
+ if needle in plain.stdout:
3287
+ report(f"{label} outside the desktop app the clear hint names {needle}: {plain.stdout.strip()}")
3288
+ return 1
3289
+ if "Desktop session:" in note.read_text(encoding="utf-8"):
3290
+ report(f"{label} a note written outside the desktop app records a desktop session.")
3291
+ return 1
3292
+ again = run_keel(verify, "shift", "resume", env=env)
3293
+ if "set_remote_control" in again.stdout or "set_session_title" in again.stdout:
3294
+ report(f"{label} resume outside the desktop app names the desktop restore: {again.stdout.strip()}")
3295
+ return 1
3296
+
3297
+ for relative in ("docs/shift-change.md", "docs/shift-change.zh-CN.md"):
3298
+ text = (ROOT / relative).read_text(encoding="utf-8")
3299
+ for stale in ("unbind_pr", "cannot be cleared"):
3300
+ if stale in text:
3301
+ report(f"{label} {relative} still says {stale}.")
3302
+ return 1
3303
+ for needle in ("send_message", "set_remote_control", "set_session_title", "shift-restore",
3304
+ "get_session", "unarchive_session", "PushNotification", "WAKE FAILED",
3305
+ "await-clear", "run_scheduled_task"):
3306
+ if needle not in text:
3307
+ report(f"{label} {relative} does not name {needle} for the desktop app.")
3308
+ return 1
3309
+ if "shift-desktop-wake" not in {name for name, _ in registry.SCENARIOS}:
3310
+ report(f"{label} scenario is not registered.")
3311
+ return 1
3312
+ report("shift-desktop-wake scenario passed.")
3313
+ return 0
3314
+
3315
+
3316
+ def validate_shift_without_role_scenario() -> int:
3317
+ """Owner's remark of 2026-10-05: a shift change needs no chat role.
3318
+
3319
+ In a worktree with no `keel chat` role, `ready` keeps the note per
3320
+ worktree, `keel context` and the SessionStart projection point to it
3321
+ without changing the context's status, and `resume` consumes it.
3322
+ """
3323
+ label = "shift-without-role:"
3324
+ with tempfile.TemporaryDirectory(prefix="keel-shift-norole-") as raw:
3325
+ base = Path(raw)
3326
+ repo = mailbox_repository(base / "solo")
3327
+ env = chat_environment()
3328
+ common = mailbox_common_dir(repo) / "keel-chat"
3329
+
3330
+ def context() -> dict:
3331
+ return chat_json(run_keel(repo, "context", "--json", env=env))
3332
+
3333
+ before = context().get("status")
3334
+ # Issue #317: nothing wakes the session after a clear here, so plain
3335
+ # `ready` is refused and points to a role and --wake.
3336
+ plain = run_keel(repo, "shift", "ready", "next: rerun R007", env=env)
3337
+ if plain.returncode != 1:
3338
+ report(f"{label} plain ready in a worktree without a chat role exited {plain.returncode}, not 1: {plain.stdout.strip()}")
3339
+ return 1
3340
+ if "keel chat role --set" not in plain.stderr:
3341
+ report(f"{label} the refusal does not name `keel chat role --set`: {plain.stderr.strip()}")
3342
+ return 1
3343
+ if "--wake" not in plain.stderr:
3344
+ report(f"{label} the refusal does not name --wake: {plain.stderr.strip()}")
3345
+ return 1
3346
+ if list((common / "shift" / "worktree").glob("*.md")):
3347
+ report(f"{label} the refused ready stored a worktree note.")
3348
+ return 1
3349
+ ready = run_keel(repo, "shift", "ready", "--force-reason", "the owner opens it", "next: rerun R007", env=env)
3350
+ if ready.returncode != 0:
3351
+ report(f"{label} keel shift ready --force-reason refused in a worktree without a chat role: {ready.stderr.strip()}")
3352
+ return 1
3353
+ if "the owner opens it" not in ready.stdout:
3354
+ report(f"{label} the clear hint does not name who starts the new session: {ready.stdout.strip()}")
3355
+ return 1
3356
+ notes = list((common / "shift" / "worktree").glob("*.md"))
3357
+ if len(notes) != 1:
3358
+ report(f"{label} ready kept {len(notes)} worktree notes under keel-chat/shift/worktree/, not one.")
3359
+ return 1
3360
+ if "Started by hand: the owner opens it" not in notes[0].read_text(encoding="utf-8"):
3361
+ report(f"{label} the note does not record who starts the new session.")
3362
+ return 1
3363
+ if "Left as is" in notes[0].read_text(encoding="utf-8"):
3364
+ report(f"{label} the note lists loose ends left as is when the check found none.")
3365
+ return 1
3366
+ text = run_keel(repo, "context", env=env).stdout
3367
+ if "keel shift resume" not in text:
3368
+ report(f"{label} keel context does not point to the waiting note: {text.strip()}")
3369
+ return 1
3370
+ if context().get("status") != before:
3371
+ report(f"{label} the waiting note changed the context status from {before!r} to {context().get('status')!r}.")
3372
+ return 1
3373
+ session = run_session_start_hook(
3374
+ repo, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(repo)},
3375
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
3376
+ )
3377
+ if "keel shift resume" not in (session_start_context(session) or ""):
3378
+ report(f"{label} the SessionStart projection does not point to the waiting note.")
3379
+ return 1
3380
+ resumed = run_keel(repo, "shift", "resume", env=env)
3381
+ if "rerun R007" not in resumed.stdout:
3382
+ report(f"{label} keel shift resume did not print the note: {resumed.stdout.strip()} {resumed.stderr.strip()}")
3383
+ return 1
3384
+ if notes[0].exists():
3385
+ report(f"{label} resume left the worktree note waiting.")
3386
+ return 1
3387
+ if not list((common / "shift" / "history").glob("*.md")):
3388
+ report(f"{label} resume did not keep the note in history.")
3389
+ return 1
3390
+ if "keel shift resume" in run_keel(repo, "context", env=env).stdout:
3391
+ report(f"{label} keel context still points to a note already resumed.")
3392
+ return 1
3393
+
3394
+ # Issue #261: `--file -` is stdin, and an unreadable file is a named refusal.
3395
+ missing = base / "missing-note.md"
3396
+ refused = run_keel(repo, "shift", "ready", "--force-reason", "the owner opens it", "--file", str(missing), env=env)
3397
+ if re.search(r"^\s+at ", refused.stderr, re.M):
3398
+ report(f"{label} an unreadable --file escaped as an uncaught exception: {refused.stderr.strip()}")
3399
+ return 1
3400
+ if refused.returncode != 1:
3401
+ report(f"{label} an unreadable --file exited {refused.returncode}, not 1: {refused.stderr.strip()}")
3402
+ return 1
3403
+ if not refused.stderr.startswith("keel shift:"):
3404
+ report(f"{label} an unreadable --file was not refused as a keel shift error: {refused.stderr.strip()}")
3405
+ return 1
3406
+ if str(missing) not in refused.stderr:
3407
+ report(f"{label} the refusal of an unreadable --file does not name the path: {refused.stderr.strip()}")
3408
+ return 1
3409
+ piped = subprocess.run(
3410
+ ["node", str(ROOT / "bin" / "keel.js"), "shift", "ready", "--force-reason", "the owner opens it", "--file", "-"],
3411
+ cwd=repo, env=env, input="next: from stdin via --file -\n",
3412
+ text=True, encoding="utf-8", errors="replace", capture_output=True, check=False,
3413
+ )
3414
+ if piped.returncode != 0:
3415
+ report(f"{label} keel shift ready --file - failed: {piped.stderr.strip()}")
3416
+ return 1
3417
+ notes = list((common / "shift" / "worktree").glob("*.md"))
3418
+ if len(notes) != 1:
3419
+ report(f"{label} keel shift ready --file - kept {len(notes)} worktree notes, not one.")
3420
+ return 1
3421
+ if "from stdin via --file -" not in notes[0].read_text(encoding="utf-8"):
3422
+ report(f"{label} the note stored by keel shift ready --file - lacks the text given on stdin.")
3423
+ return 1
3424
+
3425
+ for relative, needle in (("docs/shift-change.md", "no chat role"), ("docs/shift-change.zh-CN.md", "不绑定聊天角色")):
3426
+ text = (ROOT / relative).read_text(encoding="utf-8")
3427
+ if needle not in text:
3428
+ report(f"{label} {relative} does not say a chat role is optional ({needle!r}).")
3429
+ return 1
3430
+ intro = text.split("## ", 1)[0]
3431
+ if "--wake" not in intro:
3432
+ report(f"{label} {relative} does not say an unbound self-shift needs --wake.")
3433
+ return 1
3434
+ if "--force-reason" not in intro:
3435
+ report(f"{label} {relative} does not say --force-reason files an unbound self-shift by hand.")
3436
+ return 1
3437
+ if "shift-without-role" not in {name for name, _ in registry.SCENARIOS}:
3438
+ report(f"{label} scenario is not registered.")
3439
+ return 1
3440
+ report("shift-without-role scenario passed.")
3441
+ return 0
3442
+
3443
+
3444
+ def per_worktree_change(repo: Path, name: str, *, blocked: bool = False, owner: str | None = None) -> None:
3445
+ """An actionable change; `blocked` drops its evidence-first Reason so it cannot compile."""
3446
+ tasks = task_capsule_compact_fixture()
3447
+ if blocked:
3448
+ tasks = "".join(line for line in tasks.splitlines(keepends=True) if "- Reason:" not in line)
3449
+ write_text(repo / f"openspec/changes/{name}/proposal.md", f"## Why\n\n{name}.\n\n## What Changes\n\n- {name}.\n")
3450
+ write_text(repo / f"openspec/changes/{name}/tasks.md", tasks)
3451
+ if owner:
3452
+ write_text(repo / f"openspec/changes/{name}/.openspec.yaml", f"schema: spec-driven\nkeel:\n owner: {owner}\n")
3453
+
3454
+
3455
+ def validate_context_per_worktree_scenario() -> int:
3456
+ """Issue #241: a change that belongs to another worktree is context here.
3457
+
3458
+ Ownership is the change's `owner:` role first, then committed branch
3459
+ history beyond the default branch; a change belonging elsewhere is listed
3460
+ and does not set this session's status. Explicit selection still reaches it.
3461
+ """
3462
+ label = "context-per-worktree:"
3463
+ with tempfile.TemporaryDirectory(prefix="keel-context-worktree-") as raw:
3464
+ base = Path(raw)
3465
+ main = mailbox_repository(base / "main")
3466
+ per_worktree_change(main, "broken", blocked=True)
3467
+ per_worktree_change(main, "owned", owner="verify")
3468
+ subprocess.run(["git", "add", "-A"], cwd=main, check=True, capture_output=True)
3469
+ subprocess.run(["git", "commit", "-q", "-m", "changes"], cwd=main, check=True, capture_output=True)
3470
+ rtl = chat_worktree(main, base / "rtl")
3471
+ verify = chat_worktree(main, base / "verify")
3472
+ review = chat_worktree(main, base / "review")
3473
+ env = chat_environment()
3474
+ for cwd, role in ((rtl, "rtl"), (verify, "verify"), (review, "review")):
3475
+ run_keel(cwd, "chat", "role", "--set", role, env=env)
3476
+ (rtl / "openspec/changes/broken/proposal.md").write_text("## Why\n\nbroken, edited on rtl.\n\n## What Changes\n\n- broken.\n", encoding="utf-8")
3477
+ subprocess.run(["git", "commit", "-q", "-am", "edit broken"], cwd=rtl, check=True, capture_output=True)
3478
+
3479
+ def context(cwd: Path, *args: str) -> dict:
3480
+ result = run_keel(cwd, "context", "--json", *args, env=env)
3481
+ try:
3482
+ return json.loads(result.stdout)
3483
+ except json.JSONDecodeError:
3484
+ return {"error": (result.stdout or result.stderr).strip()}
3485
+
3486
+ here = context(review)
3487
+ if here.get("status") != "idle":
3488
+ report(f"{label} review is {here.get('status')!r}, not idle: {here}")
3489
+ return 1
3490
+ elsewhere = {e.get("change"): e for e in here.get("elsewhere", [])}
3491
+ broken = elsewhere.get("broken", {})
3492
+ if broken.get("status") != "blocked":
3493
+ report(f"{label} review does not list broken as blocked: {here.get('elsewhere')!r}")
3494
+ return 1
3495
+ if broken.get("worktree") != str(rtl.resolve()):
3496
+ report(f"{label} review does not place broken in worktree rtl: {here.get('elsewhere')!r}")
3497
+ return 1
3498
+ if elsewhere.get("owned", {}).get("owner") != "verify":
3499
+ report(f"{label} review does not list owned as belonging to verify: {here.get('elsewhere')!r}")
3500
+ return 1
3501
+
3502
+ theirs = context(rtl)
3503
+ if theirs.get("status") != "blocked":
3504
+ report(f"{label} rtl is {theirs.get('status')!r}, not blocked by its own change: {theirs}")
3505
+ return 1
3506
+ if [e.get("change") for e in theirs.get("elsewhere", [])] != ["owned"]:
3507
+ report(f"{label} rtl does not list only owned as elsewhere: {theirs.get('elsewhere')!r}")
3508
+ return 1
3509
+
3510
+ owner = context(verify)
3511
+ if (owner.get("selection") or {}).get("change") != "owned":
3512
+ report(f"{label} verify does not select its owned change: {owner}")
3513
+ return 1
3514
+ if owner.get("status") != "ready":
3515
+ report(f"{label} verify's owned change is {owner.get('status')!r}, not ready: {owner}")
3516
+ return 1
3517
+
3518
+ explicit = context(review, "--change", "broken")
3519
+ if (explicit.get("selection") or {}).get("change") != "broken" and explicit.get("status") != "blocked":
3520
+ report(f"{label} explicit selection in review did not reach broken: {explicit}")
3521
+ return 1
3522
+ report("context-per-worktree scenario passed.")
3523
+ return 0
3524
+
3525
+
3526
+ def validate_session_role_identity_scenario() -> int:
3527
+ """Issue #245: the chat role is the session's identity.
3528
+
3529
+ `keel context` carries the bound role and the SessionStart projection
3530
+ names it; an unbound worktree among bound ones is reminded; a repository
3531
+ with no roles is unchanged.
3532
+ """
3533
+ label = "session-role-identity:"
3534
+ with tempfile.TemporaryDirectory(prefix="keel-role-identity-") as raw:
3535
+ base = Path(raw)
3536
+ repo = mailbox_repository(base / "repo")
3537
+ plain = mailbox_repository(base / "plain")
3538
+ # The SessionStart hook projects only where OpenSpec is present.
3539
+ for root in (repo, plain):
3540
+ write_text(root / "openspec/specs/.keep", "")
3541
+ subprocess.run(["git", "add", "-A"], cwd=root, check=True, capture_output=True)
3542
+ subprocess.run(["git", "commit", "-q", "-m", "openspec"], cwd=root, check=True, capture_output=True)
3543
+ rtl = chat_worktree(repo, base / "rtl")
3544
+ loose = chat_worktree(repo, base / "loose")
3545
+ env = chat_environment()
3546
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
3547
+
3548
+ def both(cwd: Path) -> tuple[dict, str]:
3549
+ context = json.loads(run_keel(cwd, "context", "--json", env=env).stdout)
3550
+ session = run_session_start_hook(
3551
+ cwd, {"hook_event_name": "SessionStart", "source": "startup", "cwd": str(cwd)},
3552
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
3553
+ )
3554
+ return context, session_start_context(session) or ""
3555
+
3556
+ context, note = both(rtl)
3557
+ if context.get("role") != "rtl":
3558
+ report(f"{label} rtl's context carries role {context.get('role')!r}, not 'rtl'.")
3559
+ return 1
3560
+ if "chat role: rtl" not in note:
3561
+ report(f"{label} rtl's projection does not name its role: {note!r}")
3562
+ return 1
3563
+
3564
+ context, note = both(loose)
3565
+ if context.get("role") is not None:
3566
+ report(f"{label} the unbound worktree carries role {context.get('role')!r}.")
3567
+ return 1
3568
+ if not any("keel chat role --set" in w for w in context.get("warnings", [])):
3569
+ report(f"{label} the unbound worktree is not reminded: {context.get('warnings')!r}")
3570
+ return 1
3571
+ if "keel chat role --set" not in note:
3572
+ report(f"{label} the unbound worktree's projection carries no reminder: {note!r}")
3573
+ return 1
3574
+
3575
+ context, note = both(plain)
3576
+ if "role" not in context:
3577
+ report(f"{label} a role-less repository's context has no role field: {context}")
3578
+ return 1
3579
+ if context.get("role") is not None:
3580
+ report(f"{label} a role-less repository carries role {context.get('role')!r}.")
3581
+ return 1
3582
+ if any("keel chat role --set" in w for w in context.get("warnings", [])):
3583
+ report(f"{label} a role-less repository is warned: {context.get('warnings')!r}")
3584
+ return 1
3585
+ if "chat role:" in note:
3586
+ report(f"{label} a role-less repository's projection has a role line: {note!r}")
3587
+ return 1
3588
+ report("session-role-identity scenario passed.")
3589
+ return 0
3590
+
3591
+
3592
+ def validate_idle_recent_issues_scenario() -> int:
3593
+ """Issue #278: an idle result points at the issues the branch referenced.
3594
+
3595
+ From Git alone, newest first and without repeats, in a separate field the
3596
+ session projection prints; nothing on the default branch.
3597
+ """
3598
+ label = "idle-recent-issues:"
3599
+ with tempfile.TemporaryDirectory(prefix="keel-idle-recent-") as raw:
3600
+ base = Path(raw)
3601
+ repo = mailbox_repository(base / "repo")
3602
+ write_text(repo / "openspec/specs/.keep", "")
3603
+ subprocess.run(["git", "add", "-A"], cwd=repo, check=True, capture_output=True)
3604
+ subprocess.run(["git", "commit", "-q", "-m", "openspec"], cwd=repo, check=True, capture_output=True)
3605
+ work = chat_worktree(repo, base / "work")
3606
+ for message in ("fix the lock lease (#162)", "context per worktree, #182", "follow-up for #162"):
3607
+ subprocess.run(["git", "commit", "-q", "--allow-empty", "-m", message], cwd=work, check=True, capture_output=True)
3608
+
3609
+ def look(cwd: Path) -> tuple[dict, str]:
3610
+ context = json.loads(run_keel(cwd, "context", "--json").stdout)
3611
+ session = run_session_start_hook(
3612
+ cwd, {"hook_event_name": "SessionStart", "source": "compact", "cwd": str(cwd)},
3613
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
3614
+ )
3615
+ return context, session_start_context(session) or ""
3616
+
3617
+ on_main, main_note = look(repo)
3618
+ context, note = look(work)
3619
+ if context.get("status") != "idle":
3620
+ report(f"{label} the worktree is {context.get('status')!r}, not idle.")
3621
+ return 1
3622
+ if (context.get("recent") or {}).get("issues") != [162, 182]:
3623
+ report(f"{label} recent is {context.get('recent')!r}, not issues [162, 182].")
3624
+ return 1
3625
+ if context.get("reasons") != on_main.get("reasons"):
3626
+ report(f"{label} recent issues changed the reasons: {context.get('reasons')!r}")
3627
+ return 1
3628
+ if "recently referenced: #162, #182" not in note:
3629
+ report(f"{label} the projection does not print the recent issues: {note!r}")
3630
+ return 1
3631
+ if "recent" in on_main:
3632
+ report(f"{label} the default branch carries recent: {on_main.get('recent')!r}")
3633
+ return 1
3634
+ if "recently referenced" in main_note:
3635
+ report(f"{label} the default branch's projection prints recent issues: {main_note!r}")
3636
+ return 1
3637
+ report("idle-recent-issues scenario passed.")
3638
+ return 0
3639
+
3640
+
3641
+ def validate_read_only_role_scenario() -> int:
3642
+ """Issue #246: a role listed in `read_only_roles:` infers nothing.
3643
+
3644
+ `keel context` reports one idle line naming the role, the session note
3645
+ stops asking to select an owner, a malformed entry is reported, and
3646
+ explicit selection still works.
3647
+ """
3648
+ label = "read-only-role:"
3649
+ with tempfile.TemporaryDirectory(prefix="keel-read-only-") as raw:
3650
+ repo = mailbox_repository(Path(raw) / "repo")
3651
+ per_worktree_change(repo, "first")
3652
+ per_worktree_change(repo, "second")
3653
+ write_authorize_config(repo, "read_only_roles:\n - review\n - Not A Role\n")
3654
+ env = chat_environment()
3655
+ run_keel(repo, "chat", "role", "--set", "review", env=env)
3656
+ result = run_keel(repo, "context", "--json", env=env)
3657
+ try:
3658
+ context = json.loads(result.stdout)
3659
+ except json.JSONDecodeError:
3660
+ report(f"{label} keel context printed no JSON: {result.stdout} {result.stderr}")
3661
+ return 1
3662
+ if context.get("status") != "idle":
3663
+ report(f"{label} a read-only role is {context.get('status')!r}, not idle: {context}")
3664
+ return 1
3665
+ reasons = context.get("reasons", [])
3666
+ if len(reasons) != 1:
3667
+ report(f"{label} the read-only result has {len(reasons)} reasons, not one: {reasons!r}")
3668
+ return 1
3669
+ if "review" not in reasons[0]:
3670
+ report(f"{label} the read-only reason does not name review: {reasons!r}")
3671
+ return 1
3672
+ if (context.get("readOnly") or {}).get("role") != "review":
3673
+ report(f"{label} the result carries no readOnly naming review: {context.get('readOnly')!r}")
3674
+ return 1
3675
+ if not any("Not A Role" in warning for warning in context.get("warnings", [])):
3676
+ report(f"{label} the malformed entry is not reported: {context.get('warnings')!r}")
3677
+ return 1
3678
+ session = run_session_start_hook(
3679
+ repo, {"hook_event_name": "SessionStart", "source": "compact", "cwd": str(repo)},
3680
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"',
3681
+ )
3682
+ note = session_start_context(session) or ""
3683
+ if "read-only session (role review)" not in note:
3684
+ report(f"{label} the compaction note does not name the read-only session: {note!r}")
3685
+ return 1
3686
+ if "select an owner" in note:
3687
+ report(f"{label} the compaction note still asks a read-only session to select an owner: {note!r}")
3688
+ return 1
3689
+ explicit = json.loads(run_keel(repo, "context", "--json", "--change", "first", env=env).stdout)
3690
+ if (explicit.get("selection") or {}).get("change") != "first":
3691
+ report(f"{label} explicit selection in a read-only session did not select first: {explicit}")
3692
+ return 1
3693
+ report("read-only-role scenario passed.")
3694
+ return 0
3695
+
3696
+
3697
+ def validate_stateless_continuity_scenario() -> int:
3698
+ with tempfile.TemporaryDirectory(prefix="keel-context-") as raw_tmp:
3699
+ root = Path(raw_tmp)
3700
+ repo = root / "explicit"
3701
+ repo.mkdir()
3702
+ write_text(
3703
+ repo / "openspec/changes/demo/tasks.md",
3704
+ task_contract_fixture(),
3705
+ )
3706
+
3707
+ explicit = run_keel(
3708
+ repo,
3709
+ "context",
3710
+ "--change",
3711
+ "demo",
3712
+ "--task",
3713
+ "1.1",
3714
+ "--json",
3715
+ )
3716
+ if explicit.returncode != 0:
3717
+ report("stateless-continuity scenario could not resolve an explicit task.")
3718
+ report((explicit.stderr or explicit.stdout).strip())
3719
+ return 1
3720
+ try:
3721
+ payload = json.loads(explicit.stdout)
3722
+ except json.JSONDecodeError:
3723
+ report("stateless-continuity scenario expected keel context --json output.")
3724
+ report(explicit.stdout.strip())
3725
+ return 1
3726
+ expected = {
3727
+ "schemaVersion": 1,
3728
+ "status": "ready",
3729
+ "selection": {
3730
+ "source": "explicit",
3731
+ "change": "demo",
3732
+ "task": "1.1",
3733
+ },
3734
+ }
3735
+ expected_kind = "task-start"
3736
+ if payload.get("nextAction", {}).get("kind") != expected_kind:
3737
+ report(
3738
+ "stateless-continuity scenario explicit selection reported "
3739
+ f"next action {payload.get('nextAction')!r}."
3740
+ )
3741
+ return 1
3742
+ for key, value in expected.items():
3743
+ if payload.get(key) != value:
3744
+ report(
3745
+ "stateless-continuity scenario explicit selection mismatch: "
3746
+ f"{key}={payload.get(key)!r}"
3747
+ )
3748
+ return 1
3749
+
3750
+ write_text(
3751
+ repo / "openspec/changes/other/tasks.md",
3752
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n- [ ] 1.1 Other task\n",
3753
+ )
3754
+ write_text(
3755
+ repo / "keel/HANDOFF.md",
3756
+ "---\n"
3757
+ "schema: keel-handoff/v1\n"
3758
+ "owner: openspec/changes/other/tasks.md#1.1\n"
3759
+ "action: task-start\n"
3760
+ "reason: Explicit precedence fixture\n"
3761
+ "---\n",
3762
+ )
3763
+ explicit_again = run_keel(
3764
+ repo,
3765
+ "context",
3766
+ "--change",
3767
+ "demo",
3768
+ "--task",
3769
+ "1.1",
3770
+ "--json",
3771
+ )
3772
+ explicit_again_payload = json.loads(explicit_again.stdout)
3773
+ if (
3774
+ explicit_again.returncode != 0
3775
+ or explicit_again_payload.get("selection")
3776
+ != {"source": "explicit", "change": "demo", "task": "1.1"}
3777
+ ):
3778
+ report("stateless-continuity scenario did not prioritize explicit selection.")
3779
+ report((explicit_again.stderr or explicit_again.stdout).strip())
3780
+ return 1
3781
+
3782
+ inferred_repo = root / "inferred"
3783
+ inferred_repo.mkdir()
3784
+ tasks_path = inferred_repo / "openspec/changes/only/tasks.md"
3785
+ write_text(
3786
+ tasks_path,
3787
+ task_contract_fixture() + "- [ ] 1.2 Second slice\n",
3788
+ )
3789
+ before_context = snapshot_files(inferred_repo)
3790
+ inferred = run_keel(inferred_repo, "context", "--json")
3791
+ after_context = snapshot_files(inferred_repo)
3792
+ if inferred.returncode != 0:
3793
+ report("stateless-continuity scenario could not infer a unique task.")
3794
+ report((inferred.stderr or inferred.stdout).strip())
3795
+ return 1
3796
+ inferred_payload = json.loads(inferred.stdout)
3797
+ if (
3798
+ inferred_payload.get("status") != "ready"
3799
+ or inferred_payload.get("selection")
3800
+ != {"source": "inferred", "change": "only", "task": "1.1"}
3801
+ or inferred_payload.get("nextAction", {}).get("kind") != "task-start"
3802
+ ):
3803
+ report("stateless-continuity scenario unique inference mismatch.")
3804
+ report(inferred.stdout.strip())
3805
+ return 1
3806
+ if before_context != after_context:
3807
+ report("stateless-continuity scenario persisted context state.")
3808
+ return 1
3809
+
3810
+ write_text(
3811
+ tasks_path,
3812
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
3813
+ "- [x] 1.1 First slice\n"
3814
+ "- [x] 1.2 Second slice\n",
3815
+ )
3816
+ recomputed = run_keel(inferred_repo, "context", "--json")
3817
+ recomputed_payload = json.loads(recomputed.stdout)
3818
+ if (
3819
+ recomputed.returncode != 0
3820
+ or recomputed_payload.get("status") != "ready"
3821
+ or recomputed_payload.get("selection")
3822
+ != {"source": "inferred", "change": "only", "task": None}
3823
+ or recomputed_payload.get("nextAction", {}).get("kind")
3824
+ != "change-close"
3825
+ ):
3826
+ report("stateless-continuity scenario did not recompute completed state.")
3827
+ report((recomputed.stderr or recomputed.stdout).strip())
3828
+ return 1
3829
+
3830
+ evidence_repo = root / "evidence"
3831
+ evidence_repo.mkdir()
3832
+ write_text(
3833
+ evidence_repo / "openspec/changes/evidence-ready/tasks.md",
3834
+ task_contract_fixture(evidence=("M1: passed",)).replace(
3835
+ " - Status: pending\n",
3836
+ " - Status: pass\n",
3837
+ ),
3838
+ )
3839
+ evidence_ready = run_keel(evidence_repo, "context", "--json")
3840
+ evidence_payload = json.loads(evidence_ready.stdout)
3841
+ if (
3842
+ evidence_ready.returncode != 0
3843
+ or evidence_payload.get("nextAction", {}).get("kind") != "task-complete"
3844
+ ):
3845
+ report("stateless-continuity scenario missed evidence-ready completion.")
3846
+ report((evidence_ready.stderr or evidence_ready.stdout).strip())
3847
+ return 1
3848
+
3849
+ ambiguous_repo = root / "ambiguous"
3850
+ ambiguous_repo.mkdir()
3851
+ for change in ("alpha", "beta"):
3852
+ write_text(
3853
+ ambiguous_repo / f"openspec/changes/{change}/tasks.md",
3854
+ task_contract_fixture(),
3855
+ )
3856
+ write_text(ambiguous_repo / "src/unrelated.txt", "dirty warning\n")
3857
+ git_init = subprocess.run(
3858
+ ["git", "init", "--quiet"],
3859
+ cwd=ambiguous_repo,
3860
+ capture_output=True,
3861
+ text=True,
3862
+ check=False,
3863
+ )
3864
+ if git_init.returncode != 0:
3865
+ report("stateless-continuity scenario could not initialize Git fixture.")
3866
+ return 1
3867
+ ambiguous = run_keel(ambiguous_repo, "context", "--json")
3868
+ ambiguous_payload = json.loads(ambiguous.stdout)
3869
+ if (
3870
+ ambiguous.returncode != 0
3871
+ or ambiguous_payload.get("status") != "ambiguous"
3872
+ or ambiguous_payload.get("selection") is not None
3873
+ or not any("alpha" in reason and "beta" in reason for reason in ambiguous_payload.get("reasons", []))
3874
+ or not any("src/unrelated.txt" in warning for warning in ambiguous_payload.get("warnings", []))
3875
+ ):
3876
+ report("stateless-continuity scenario guessed among multiple candidates.")
3877
+ report((ambiguous.stderr or ambiguous.stdout).strip())
3878
+ return 1
3879
+
3880
+ write_text(
3881
+ ambiguous_repo / "keel/HANDOFF.md",
3882
+ "---\n"
3883
+ "schema: keel-handoff/v1\n"
3884
+ "owner: openspec/changes/beta/tasks.md#1.1\n"
3885
+ "action: task-start\n"
3886
+ "reason: Human selected beta\n"
3887
+ "---\n",
3888
+ )
3889
+ handoff = run_keel(ambiguous_repo, "context", "--json")
3890
+ handoff_payload = json.loads(handoff.stdout)
3891
+ if (
3892
+ handoff.returncode != 0
3893
+ or handoff_payload.get("status") != "ready"
3894
+ or handoff_payload.get("selection")
3895
+ != {"source": "handoff", "change": "beta", "task": "1.1"}
3896
+ or handoff_payload.get("nextAction", {}).get("kind") != "task-start"
3897
+ ):
3898
+ report("stateless-continuity scenario did not prioritize valid HANDOFF.")
3899
+ report((handoff.stderr or handoff.stdout).strip())
3900
+ return 1
3901
+
3902
+ human = run_keel(ambiguous_repo, "context")
3903
+ for expected_text in (
3904
+ "Keel context: ready",
3905
+ "Next action: task-start",
3906
+ "Selection: beta#1.1 (handoff)",
3907
+ ):
3908
+ if human.returncode != 0 or expected_text not in human.stdout:
3909
+ report("stateless-continuity scenario human output diverged from JSON.")
3910
+ report((human.stderr or human.stdout).strip())
3911
+ return 1
3912
+
3913
+ cleared = run_keel(
3914
+ ambiguous_repo,
3915
+ "context",
3916
+ "--clear-handoff",
3917
+ "--json",
3918
+ )
3919
+ cleared_payload = json.loads(cleared.stdout)
3920
+ if (
3921
+ cleared.returncode != 0
3922
+ or (ambiguous_repo / "keel/HANDOFF.md").exists()
3923
+ or cleared_payload.get("status") != "ambiguous"
3924
+ ):
3925
+ report("stateless-continuity scenario clear did not restore inference.")
3926
+ report((cleared.stderr or cleared.stdout).strip())
3927
+ return 1
3928
+
3929
+ stale_repo = root / "stale"
3930
+ stale_repo.mkdir()
3931
+ write_text(
3932
+ stale_repo / "openspec/changes/current/tasks.md",
3933
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n- [ ] 1.1 Current task\n",
3934
+ )
3935
+ write_text(
3936
+ stale_repo / "keel/HANDOFF.md",
3937
+ "---\n"
3938
+ "schema: keel-handoff/v1\n"
3939
+ "owner: openspec/changes/missing/tasks.md#1.1\n"
3940
+ "action: task-start\n"
3941
+ "reason: Stale fixture\n"
3942
+ "---\n",
3943
+ )
3944
+ stale = run_keel(stale_repo, "context", "--json")
3945
+ stale_payload = json.loads(stale.stdout)
3946
+ if (
3947
+ stale.returncode != 0
3948
+ or stale_payload.get("status") != "blocked"
3949
+ or stale_payload.get("selection") is not None
3950
+ or not any("missing" in reason.lower() for reason in stale_payload.get("reasons", []))
3951
+ ):
3952
+ report("stateless-continuity scenario stale HANDOFF fell through.")
3953
+ report((stale.stderr or stale.stdout).strip())
3954
+ return 1
3955
+
3956
+ write_text(
3957
+ stale_repo / "openspec/changes/current/tasks.md",
3958
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n- [x] 1.1 Current task\n",
3959
+ )
3960
+ write_text(
3961
+ stale_repo / "keel/HANDOFF.md",
3962
+ "---\n"
3963
+ "schema: keel-handoff/v1\n"
3964
+ "owner: openspec/changes/current/tasks.md#1.1\n"
3965
+ "action: task-start\n"
3966
+ "reason: Completed fixture\n"
3967
+ "---\n",
3968
+ )
3969
+ completed_owner = run_keel(stale_repo, "context", "--json")
3970
+ completed_payload = json.loads(completed_owner.stdout)
3971
+ if (
3972
+ completed_owner.returncode != 0
3973
+ or completed_payload.get("status") != "blocked"
3974
+ or not any(
3975
+ "already complete" in reason
3976
+ for reason in completed_payload.get("reasons", [])
3977
+ )
3978
+ ):
3979
+ report("stateless-continuity scenario accepted completed HANDOFF owner.")
3980
+ report((completed_owner.stderr or completed_owner.stdout).strip())
3981
+ return 1
3982
+
3983
+ write_text(
3984
+ stale_repo / "openspec/changes/current/tasks.md",
3985
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n- [ ] 1.1 Current task\n",
3986
+ )
3987
+ write_text(
3988
+ stale_repo / "keel/HANDOFF.md",
3989
+ "---\n"
3990
+ "schema: keel-handoff/v1\n"
3991
+ "owner: openspec/changes/current/tasks.md#1.1\n"
3992
+ "action: task-start\n"
3993
+ "reason: Extra-field fixture\n"
3994
+ "summary: copied state is forbidden\n"
3995
+ "---\n",
3996
+ )
3997
+ extra_field = run_keel(stale_repo, "context", "--json")
3998
+ if (
3999
+ extra_field.returncode != 0
4000
+ or json.loads(extra_field.stdout).get("status") != "blocked"
4001
+ ):
4002
+ report("stateless-continuity scenario accepted non-pointer HANDOFF state.")
4003
+ report((extra_field.stderr or extra_field.stdout).strip())
4004
+ return 1
4005
+
4006
+ write_text(
4007
+ stale_repo / "keel/HANDOFF.md",
4008
+ "---\n"
4009
+ "schema: keel-handoff/v1\n"
4010
+ "owner: openspec/changes/current/tasks.md#1.1\n",
4011
+ )
4012
+ parse_failure = run_keel(stale_repo, "context", "--json")
4013
+ if (
4014
+ parse_failure.returncode == 0
4015
+ or "context input error" not in parse_failure.stderr
4016
+ ):
4017
+ report("stateless-continuity scenario did not expose HANDOFF parse failure.")
4018
+ report((parse_failure.stderr or parse_failure.stdout).strip())
4019
+ return 1
4020
+
4021
+ discuss_repo = root / "discuss"
4022
+ discuss_repo.mkdir()
4023
+ write_text(
4024
+ discuss_repo / "openspec/changes/seed/notes.md",
4025
+ "# Discussion seed\n",
4026
+ )
4027
+ discuss = run_keel(discuss_repo, "context", "--json")
4028
+ if (
4029
+ discuss.returncode != 0
4030
+ or json.loads(discuss.stdout).get("nextAction", {}).get("kind") != "discuss"
4031
+ ):
4032
+ report("stateless-continuity scenario missed discuss transition.")
4033
+ report((discuss.stderr or discuss.stdout).strip())
4034
+ return 1
4035
+
4036
+ author_repo = root / "author"
4037
+ author_repo.mkdir()
4038
+ write_text(
4039
+ author_repo / "openspec/changes/draft/proposal.md",
4040
+ "# Proposal\n",
4041
+ )
4042
+ author = run_keel(author_repo, "context", "--json")
4043
+ if (
4044
+ author.returncode != 0
4045
+ or json.loads(author.stdout).get("nextAction", {}).get("kind") != "author"
4046
+ ):
4047
+ report("stateless-continuity scenario missed author transition.")
4048
+ report((author.stderr or author.stdout).strip())
4049
+ return 1
4050
+
4051
+ idle_repo = root / "idle"
4052
+ idle_repo.mkdir()
4053
+ write_text(idle_repo / ".codex/memories/native.md", "not authority\n")
4054
+ write_text(idle_repo / ".claude/goals/native.md", "not authority\n")
4055
+ before_idle = snapshot_files(idle_repo)
4056
+ idle = run_keel(idle_repo, "context", "--json")
4057
+ after_idle = snapshot_files(idle_repo)
4058
+ idle_payload = json.loads(idle.stdout)
4059
+ if (
4060
+ idle.returncode != 0
4061
+ or idle_payload.get("status") != "idle"
4062
+ or idle_payload.get("selection") is not None
4063
+ or idle_payload.get("nextAction", {}).get("kind") != "none"
4064
+ ):
4065
+ report("stateless-continuity scenario no-work state was not idle.")
4066
+ report((idle.stderr or idle.stdout).strip())
4067
+ return 1
4068
+ if before_idle != after_idle:
4069
+ report("stateless-continuity scenario changed native runtime state.")
4070
+ return 1
4071
+
4072
+ install_repo = root / "install"
4073
+ install_repo.mkdir()
4074
+ installed = run_keel(install_repo, "--install", "--target", "codex")
4075
+ if installed.returncode != 0:
4076
+ report("stateless-continuity scenario install failed.")
4077
+ report((installed.stderr or installed.stdout).strip())
4078
+ return 1
4079
+ if (install_repo / "keel/HANDOFF.md").exists():
4080
+ report("stateless-continuity scenario new install created HANDOFF.")
4081
+ return 1
4082
+ installed_context = run_keel(install_repo, "context", "--json")
4083
+ if (
4084
+ installed_context.returncode != 0
4085
+ or json.loads(installed_context.stdout).get("status") != "idle"
4086
+ ):
4087
+ report("stateless-continuity scenario absent HANDOFF blocked inference.")
4088
+ report((installed_context.stderr or installed_context.stdout).strip())
4089
+ return 1
4090
+
4091
+ init_repo = root / "init"
4092
+ init_repo.mkdir()
4093
+ initialized = run_keel(init_repo, "--init", "--target", "opencode")
4094
+ if (
4095
+ initialized.returncode != 0
4096
+ or (init_repo / "keel/HANDOFF.md").exists()
4097
+ ):
4098
+ report("stateless-continuity scenario new init created HANDOFF.")
4099
+ report((initialized.stderr or initialized.stdout).strip())
4100
+ return 1
4101
+
4102
+ legacy_bytes = (
4103
+ "# HANDOFF\r\n\r\n"
4104
+ "active-change: preserve-me\r\n"
4105
+ "说明: 不要改写\r\n"
4106
+ ).encode("utf-8")
4107
+ legacy_path = install_repo / "keel/HANDOFF.md"
4108
+ legacy_path.parent.mkdir(parents=True, exist_ok=True)
4109
+ legacy_path.write_bytes(legacy_bytes)
4110
+ legacy_install = run_keel(install_repo, "--install", "--target", "codex")
4111
+ if (
4112
+ legacy_install.returncode != 0
4113
+ or legacy_path.read_bytes() != legacy_bytes
4114
+ or "handoff: legacy" not in legacy_install.stdout.lower()
4115
+ ):
4116
+ report("stateless-continuity scenario install did not preserve legacy HANDOFF.")
4117
+ report((legacy_install.stderr or legacy_install.stdout).strip())
4118
+ return 1
4119
+ legacy_check = run_keel(install_repo, "--check", "--target", "codex")
4120
+ if (
4121
+ legacy_check.returncode != 0
4122
+ or legacy_path.read_bytes() != legacy_bytes
4123
+ or "handoff: legacy" not in legacy_check.stdout.lower()
4124
+ or "keel context --clear-handoff" not in legacy_check.stdout
4125
+ ):
4126
+ report("stateless-continuity scenario check did not diagnose legacy HANDOFF.")
4127
+ report((legacy_check.stderr or legacy_check.stdout).strip())
4128
+ return 1
4129
+ legacy_doctor = run_keel(install_repo, "--doctor", "--target", "codex")
4130
+ if (
4131
+ legacy_doctor.returncode != 0
4132
+ or legacy_path.read_bytes() != legacy_bytes
4133
+ or "handoff: legacy" not in legacy_doctor.stdout.lower()
4134
+ ):
4135
+ report("stateless-continuity scenario doctor did not preserve legacy HANDOFF.")
4136
+ report((legacy_doctor.stderr or legacy_doctor.stdout).strip())
4137
+ return 1
4138
+ legacy_context = run_keel(install_repo, "context", "--json")
4139
+ legacy_payload = json.loads(legacy_context.stdout)
4140
+ if (
4141
+ legacy_context.returncode != 0
4142
+ or legacy_payload.get("status") != "blocked"
4143
+ or legacy_path.read_bytes() != legacy_bytes
4144
+ ):
4145
+ report("stateless-continuity scenario legacy context was not conservative.")
4146
+ report((legacy_context.stderr or legacy_context.stdout).strip())
4147
+ return 1
4148
+
4149
+ backlog_repo = root / "backlog"
4150
+ backlog_repo.mkdir()
4151
+ write_text(
4152
+ backlog_repo / "openspec/changes/executable/tasks.md",
4153
+ task_contract_fixture(),
4154
+ )
4155
+ write_text(
4156
+ backlog_repo / "openspec/changes/follow-up-backlog/tasks.md",
4157
+ "# Follow-up Backlog\n\n## Deferred Items\n\nNone.\n",
4158
+ )
4159
+ backlog_context = run_keel(backlog_repo, "context", "--json")
4160
+ backlog_payload = json.loads(backlog_context.stdout)
4161
+ if (
4162
+ backlog_context.returncode != 0
4163
+ or backlog_payload.get("status") != "ready"
4164
+ or backlog_payload.get("selection")
4165
+ != {"source": "inferred", "change": "executable", "task": "1.1"}
4166
+ or not any(
4167
+ "follow-up-backlog" in warning
4168
+ for warning in backlog_payload.get("warnings", [])
4169
+ )
4170
+ ):
4171
+ report(
4172
+ "stateless-continuity scenario let a storage-only backlog create ambiguity."
4173
+ )
4174
+ report((backlog_context.stderr or backlog_context.stdout).strip())
4175
+ return 1
4176
+
4177
+ anchor_repo = root / "anchor"
4178
+ anchor_repo.mkdir()
4179
+ anchor_tasks = task_contract_fixture()
4180
+ anchor_path = anchor_repo / "openspec/changes/demo/tasks.md"
4181
+ write_text(anchor_path, anchor_tasks)
4182
+ anchored_start = run_keel(
4183
+ anchor_repo,
4184
+ "gate",
4185
+ "task-start",
4186
+ "--change",
4187
+ "demo",
4188
+ "--task",
4189
+ "1.1",
4190
+ "--json",
4191
+ )
4192
+ anchored_payload = json.loads(anchored_start.stdout)
4193
+ anchor = (
4194
+ anchored_payload.get("contract", {})
4195
+ .get("fingerprint", {})
4196
+ .get("value", "")
4197
+ )
4198
+ if anchored_start.returncode != 0 or not re.fullmatch(r"[0-9a-f]{64}", anchor):
4199
+ report("stateless-continuity scenario could not create a task anchor.")
4200
+ report((anchored_start.stderr or anchored_start.stdout).strip())
4201
+ return 1
4202
+ anchored_tasks = anchor_tasks.replace(
4203
+ " - Evidence:\n",
4204
+ " - Evidence:\n"
4205
+ f" - Contract: keel-task-capsule/v1 sha256:{anchor}\n",
4206
+ )
4207
+ write_text(anchor_path, anchored_tasks)
4208
+ matching = run_keel(
4209
+ anchor_repo,
4210
+ "context",
4211
+ "--change",
4212
+ "demo",
4213
+ "--task",
4214
+ "1.1",
4215
+ "--json",
4216
+ )
4217
+ matching_payload = json.loads(matching.stdout)
4218
+ if (
4219
+ matching.returncode != 0
4220
+ or matching_payload.get("status") != "ready"
4221
+ or matching_payload.get("nextAction", {}).get("kind") != "task-start"
4222
+ ):
4223
+ report("stateless-continuity scenario did not resume a matching anchor.")
4224
+ report((matching.stderr or matching.stdout).strip())
4225
+ return 1
4226
+
4227
+ write_text(
4228
+ anchor_path,
4229
+ anchored_tasks.replace("src/feature.js", "src/drifted-feature.js"),
4230
+ )
4231
+ drifted_context = run_keel(
4232
+ anchor_repo,
4233
+ "context",
4234
+ "--change",
4235
+ "demo",
4236
+ "--task",
4237
+ "1.1",
4238
+ "--json",
4239
+ )
4240
+ drifted_payload = json.loads(drifted_context.stdout)
4241
+ if (
4242
+ drifted_context.returncode != 0
4243
+ or drifted_payload.get("status") != "blocked"
4244
+ or not any(
4245
+ "fingerprint" in reason.lower() or "drift" in reason.lower()
4246
+ for reason in drifted_payload.get("reasons", [])
4247
+ )
4248
+ ):
4249
+ report("stateless-continuity scenario accepted a drifted task anchor.")
4250
+ report((drifted_context.stderr or drifted_context.stdout).strip())
4251
+ return 1
4252
+
4253
+ drifted_projection = run_keel(
4254
+ anchor_repo,
4255
+ "project",
4256
+ "--target",
4257
+ "codex",
4258
+ "--event",
4259
+ "resume",
4260
+ "--change",
4261
+ "demo",
4262
+ "--task",
4263
+ "1.1",
4264
+ "--json",
4265
+ )
4266
+ drifted_projection_payload = json.loads(drifted_projection.stdout)
4267
+ if (
4268
+ drifted_projection.returncode != 0
4269
+ or drifted_projection_payload.get("status") != "blocked"
4270
+ or drifted_projection_payload.get("projection") is not None
4271
+ ):
4272
+ report("stateless-continuity scenario projected a drifted task anchor.")
4273
+ report(
4274
+ (drifted_projection.stderr or drifted_projection.stdout).strip()
4275
+ )
4276
+ return 1
4277
+
4278
+ write_text(
4279
+ anchor_repo / "keel/HANDOFF.md",
4280
+ "---\n"
4281
+ "schema: keel-handoff/v1\n"
4282
+ "owner: openspec/changes/demo/tasks.md#1.1\n"
4283
+ "action: task-start\n"
4284
+ "reason: Handoff anchor fixture\n"
4285
+ "---\n",
4286
+ )
4287
+ drifted_handoff = run_keel(anchor_repo, "context", "--json")
4288
+ drifted_handoff_payload = json.loads(drifted_handoff.stdout)
4289
+ if (
4290
+ drifted_handoff.returncode != 0
4291
+ or drifted_handoff_payload.get("status") != "blocked"
4292
+ or not any(
4293
+ "fingerprint" in reason.lower() or "drift" in reason.lower()
4294
+ for reason in drifted_handoff_payload.get("reasons", [])
4295
+ )
4296
+ ):
4297
+ report("stateless-continuity scenario let HANDOFF bypass a drifted anchor.")
4298
+ report((drifted_handoff.stderr or drifted_handoff.stdout).strip())
4299
+ return 1
4300
+
4301
+ write_text(anchor_path, anchored_tasks)
4302
+ matching_handoff = run_keel(anchor_repo, "context", "--json")
4303
+ matching_handoff_payload = json.loads(matching_handoff.stdout)
4304
+ if (
4305
+ matching_handoff.returncode != 0
4306
+ or matching_handoff_payload.get("status") != "ready"
4307
+ or matching_handoff_payload.get("selection")
4308
+ != {"source": "handoff", "change": "demo", "task": "1.1"}
4309
+ or matching_handoff_payload.get("nextAction", {}).get("kind") != "task-start"
4310
+ ):
4311
+ report("stateless-continuity scenario did not resume a matching HANDOFF anchor.")
4312
+ report((matching_handoff.stderr or matching_handoff.stdout).strip())
4313
+ return 1
4314
+
4315
+ report("stateless-continuity scenario passed.")
4316
+ return 0