@christang/keel 5.227.0 → 5.229.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,1608 @@
1
+ """Scenarios for `keel sync` and the device hand-over (#526)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ import time
10
+ from pathlib import Path
11
+
12
+ from validation.common import report, run_keel, write_text
13
+
14
+
15
+ def _git_env() -> dict[str, str]:
16
+ env = os.environ.copy()
17
+ for name in ("KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE", "GIT_DIR", "GIT_WORK_TREE"):
18
+ env.pop(name, None)
19
+ return env
20
+
21
+
22
+ class _Repo:
23
+ """A repository with a bare `origin`, built for the sync scenarios."""
24
+
25
+ def __init__(self, base: Path) -> None:
26
+ self.base = base
27
+ self.repo = base / "repo"
28
+ self.remote = base / "remote.git"
29
+ self.env = _git_env()
30
+ self.repo.mkdir()
31
+ self.git("init", "-q", "-b", "main")
32
+ self.git("config", "user.email", "test@example.invalid")
33
+ self.git("config", "user.name", "Sync test")
34
+ (self.repo / "seed").write_text("base\n", encoding="utf-8")
35
+ self.git("add", "seed")
36
+ self.git("commit", "-qm", "base")
37
+ self.git("init", "--bare", "-q", "-b", "main", str(self.remote))
38
+ self.git("remote", "add", "origin", str(self.remote))
39
+ self.git("push", "-qu", "origin", "main")
40
+ self.git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
41
+
42
+ def git(self, *args: str, cwd: Path | None = None) -> str:
43
+ return subprocess.run(
44
+ ["git", *args], cwd=cwd or self.repo, env=self.env, check=True,
45
+ capture_output=True, text=True,
46
+ ).stdout.strip()
47
+
48
+ def commit(self, name: str, cwd: Path | None = None) -> str:
49
+ where = cwd or self.repo
50
+ (where / name).write_text(f"{name}\n", encoding="utf-8")
51
+ self.git("add", name, cwd=where)
52
+ self.git("commit", "-qm", f"add {name}", cwd=where)
53
+ return self.git("rev-parse", "HEAD", cwd=where)
54
+
55
+ def chat(self) -> Path:
56
+ return Path(self.git("rev-parse", "--path-format=absolute", "--git-common-dir")) / "keel-chat"
57
+
58
+ def state(self) -> dict[str, object]:
59
+ """Everything a read-only command must leave as it was."""
60
+ chat = self.chat()
61
+ return {
62
+ "refs": self.git("for-each-ref", "--format=%(refname) %(objectname)"),
63
+ "stash": self.git("stash", "list"),
64
+ "status": self.git("status", "--porcelain=v1", "--untracked-files=all"),
65
+ "chat": {str(f.relative_to(chat)): f.read_bytes() for f in chat.rglob("*") if f.is_file()}
66
+ if chat.exists() else {},
67
+ "fetch_head": (Path(self.git("rev-parse", "--path-format=absolute", "--git-common-dir")) / "FETCH_HEAD").exists(),
68
+ }
69
+
70
+
71
+ def _unknown(label: str, result: subprocess.CompletedProcess[str]) -> int:
72
+ report(f"{label} `keel sync status` is an unknown command here (exit {result.returncode}): "
73
+ f"{(result.stderr or result.stdout).strip()[:300]}")
74
+ return 1
75
+
76
+
77
+ def _populate(r: _Repo) -> dict[str, Path]:
78
+ """feat two ahead in worktree a; scratch local-only with no worktree;
79
+ worktree b clean branch with an untracked file; done merged; one stash."""
80
+ a, b = r.base / "a", r.base / "b"
81
+ r.git("worktree", "add", "-qb", "feat", str(a), "main")
82
+ r.commit("f0", cwd=a)
83
+ r.git("push", "-qu", "origin", "feat", cwd=a)
84
+ r.commit("f1", cwd=a)
85
+ r.commit("f2", cwd=a)
86
+ r.git("branch", "scratch", "main")
87
+ r.git("checkout", "-q", "scratch")
88
+ r.commit("s1")
89
+ r.git("checkout", "-q", "main")
90
+ r.git("worktree", "add", "-qb", "clean", str(b), "main")
91
+ r.git("push", "-qu", "origin", "clean", cwd=b)
92
+ (b / "untracked.txt").write_text("loose\n", encoding="utf-8")
93
+ r.git("branch", "done", "main")
94
+ r.git("checkout", "-q", "done")
95
+ r.commit("d1")
96
+ r.git("push", "-q", "origin", "done:main")
97
+ r.git("checkout", "-q", "main")
98
+ r.git("merge", "-q", "--ff-only", "origin/main")
99
+ (r.repo / "seed").write_text("stashed change\n", encoding="utf-8")
100
+ r.git("stash", "push", "-q", "-m", "keep this")
101
+ return {"a": a, "b": b}
102
+
103
+
104
+ def validate_sync_status_lists_local_only_scenario() -> int:
105
+ """#526 D2: every kind of local-only work is listed, merged work is not."""
106
+ label = "sync-status-lists-local-only:"
107
+ with tempfile.TemporaryDirectory(prefix="keel-sync-list-") as raw:
108
+ r = _Repo(Path(raw).resolve())
109
+ trees = _populate(r)
110
+ before = r.state()
111
+ result = run_keel(trees["b"], "sync", "status", "--json", env=r.env)
112
+ if result.returncode not in (0, 1) or not result.stdout.strip().startswith("{"):
113
+ return _unknown(label, result)
114
+ data = json.loads(result.stdout)
115
+ branches = {row["branch"]: row for row in data.get("branches", [])}
116
+ if set(branches) != {"feat", "scratch"}:
117
+ report(f"{label} expected local-only branches feat and scratch, got {sorted(branches)}.")
118
+ return 1
119
+ if branches["feat"].get("unpushed") != 2:
120
+ report(f"{label} feat should have 2 unpushed commits: {branches['feat']}.")
121
+ return 1
122
+ if branches["scratch"].get("remote") is not None:
123
+ report(f"{label} scratch should have no remote counterpart: {branches['scratch']}.")
124
+ return 1
125
+ worktrees = {Path(row["path"]).name: row for row in data.get("worktrees", [])}
126
+ if worktrees.get("b", {}).get("dirty") != 1:
127
+ report(f"{label} worktree b should have 1 uncommitted path: {worktrees}.")
128
+ return 1
129
+ if "a" not in worktrees:
130
+ report(f"{label} worktree a, on local-only feat, should be listed: {worktrees}.")
131
+ return 1
132
+ if "repo" in worktrees:
133
+ report(f"{label} the clean main checkout was listed as local-only.")
134
+ return 1
135
+ stash_rows = data.get("stashes", [])
136
+ if len(stash_rows) != 1:
137
+ report(f"{label} expected exactly one stash entry, got {stash_rows}.")
138
+ return 1
139
+ if "keep this" not in stash_rows[0].get("subject", ""):
140
+ report(f"{label} the stash entry does not carry its subject: {stash_rows[0]}.")
141
+ return 1
142
+ if result.returncode != 1:
143
+ report(f"{label} exit {result.returncode}, expected 1 while work is local-only.")
144
+ return 1
145
+ text = run_keel(trees["b"], "sync", "status", env=r.env)
146
+ if "as of the last fetch" not in text.stdout or "never fetched" not in text.stdout:
147
+ report(f"{label} the text output does not say counts are as of the last fetch and when: {text.stdout}")
148
+ return 1
149
+ for name in ("feat", "scratch", "untracked", "stash"):
150
+ if name not in text.stdout:
151
+ report(f"{label} the text output does not name {name}: {text.stdout}")
152
+ return 1
153
+ if "done" in [line.split()[0] for line in text.stdout.splitlines() if line.strip() and not line.startswith(" ")]:
154
+ report(f"{label} the merged branch done was listed.")
155
+ return 1
156
+ if r.state() != before:
157
+ report(f"{label} the command changed the repository, a ref, or the chat store.")
158
+ return 1
159
+ report("sync-status-lists-local-only scenario passed.")
160
+ return 0
161
+
162
+
163
+ def validate_sync_status_read_only_exit_codes_scenario() -> int:
164
+ """#526 D4: exit 0 when clean, 2 for an operational error, the same from `/`."""
165
+ label = "sync-status-read-only-exit-codes:"
166
+ with tempfile.TemporaryDirectory(prefix="keel-sync-exit-") as raw:
167
+ base = Path(raw).resolve()
168
+ r = _Repo(base)
169
+ clean = run_keel(r.repo, "sync", "status", env=r.env)
170
+ if clean.returncode != 0:
171
+ report(f"{label} a clean repository should exit 0, got {clean.returncode}: {clean.stderr.strip()}")
172
+ return 1
173
+ if "nothing is only on this machine" not in clean.stdout.lower():
174
+ report(f"{label} a clean repository should say nothing is only on this machine: {clean.stdout.strip()}")
175
+ return 1
176
+ outside = base / "outside"
177
+ outside.mkdir()
178
+ for name, args in (("outside a repository", ("--repo", str(outside))), ("an unknown argument", ("--bogus",))):
179
+ failed = run_keel(outside if args[0] == "--repo" else r.repo, "sync", "status", *args, env=r.env)
180
+ if failed.returncode != 2:
181
+ report(f"{label} {name} should exit 2, got {failed.returncode}: {failed.stderr.strip()}")
182
+ return 1
183
+ if failed.stdout.strip():
184
+ report(f"{label} {name} listed something: {failed.stdout.strip()}")
185
+ return 1
186
+ trees = _populate(r)
187
+ before = r.state()
188
+ here = run_keel(trees["a"], "sync", "status", "--json", env=r.env)
189
+ rooted = run_keel(Path("/"), "sync", "status", "--json", "--repo", str(trees["a"]), env=r.env)
190
+ for name, run in (("inside the worktree", here), ("from / with --repo", rooted)):
191
+ if run.returncode != 1:
192
+ report(f"{label} the run {name} exited {run.returncode}, expected 1: {run.stderr.strip()}")
193
+ return 1
194
+ if json.loads(here.stdout) != json.loads(rooted.stdout):
195
+ report(f"{label} a run from / with --repo differs from a run inside the worktree.")
196
+ return 1
197
+ if r.state() != before:
198
+ report(f"{label} the command changed the repository, a ref, FETCH_HEAD, or the chat store.")
199
+ return 1
200
+ report("sync-status-read-only-exit-codes scenario passed.")
201
+ return 0
202
+
203
+
204
+ def _git_wrapper(base: Path) -> tuple[dict[str, str], Path]:
205
+ """A `git` first on PATH that logs each invocation and runs the real one."""
206
+ real = shutil.which("git")
207
+ bindir, log = base / "wrapbin", base / "git.log"
208
+ bindir.mkdir()
209
+ script = bindir / "git"
210
+ script.write_text(f'#!/bin/sh\nprintf "%s\\n" "$*" >> "{log}"\nexec "{real}" "$@"\n', encoding="utf-8")
211
+ script.chmod(0o755)
212
+ env = _git_env()
213
+ env["PATH"] = f"{bindir}{os.pathsep}{env.get('PATH', '')}"
214
+ return env, log
215
+
216
+
217
+ def _logged(log: Path, word: str) -> list[str]:
218
+ if not log.exists():
219
+ return []
220
+ return [line for line in log.read_text(encoding="utf-8").splitlines() if line.split(" ", 1)[0] == word]
221
+
222
+
223
+ def _verify_rows(result: subprocess.CompletedProcess[str]) -> dict[str, dict]:
224
+ data = json.loads(result.stdout)
225
+ return {row["branch"]: row for row in data.get("verify", {}).get("branches", [])}
226
+
227
+
228
+ def validate_sync_status_verify_classifies_scenario() -> int:
229
+ """#526 D3: --verify reads the remote's real sha, once per remote."""
230
+ label = "sync-status-verify-classifies:"
231
+ with tempfile.TemporaryDirectory(prefix="keel-sync-verify-") as raw:
232
+ base = Path(raw).resolve()
233
+ r = _Repo(base)
234
+ # feat: the remote moved to a commit this clone never fetched.
235
+ r.git("checkout", "-qb", "feat")
236
+ r.commit("f1")
237
+ r.git("push", "-qu", "origin", "feat")
238
+ other = base / "other"
239
+ subprocess.run(["git", "clone", "-q", str(r.remote), str(other)], env=r.env, check=True)
240
+ for key, value in (("user.email", "o@example.invalid"), ("user.name", "Other")):
241
+ r.git("config", key, value, cwd=other)
242
+ r.git("checkout", "-q", "feat", cwd=other)
243
+ r.commit("from-other", cwd=other)
244
+ r.git("push", "-q", "origin", "feat", cwd=other)
245
+ # partial: three commits past the remote, the tracking ref advanced by hand.
246
+ r.git("checkout", "-qb", "partial", "main")
247
+ r.git("push", "-qu", "origin", "partial")
248
+ for name in ("p1", "p2", "p3"):
249
+ tip = r.commit(name)
250
+ r.git("update-ref", "refs/remotes/origin/partial", tip)
251
+ r.git("checkout", "-q", "main")
252
+ env, log = _git_wrapper(base)
253
+ offline = run_keel(r.repo, "sync", "status", "--json", env=env)
254
+ if offline.returncode not in (0, 1):
255
+ report(f"{label} plain `keel sync status` failed: {offline.stderr.strip()}")
256
+ return 1
257
+ listed = {row["branch"] for row in json.loads(offline.stdout).get("branches", [])}
258
+ if listed & {"feat", "partial"}:
259
+ report(f"{label} without --verify feat and partial should look pushed, got {sorted(listed)}.")
260
+ return 1
261
+ if _logged(log, "ls-remote"):
262
+ report(f"{label} a run without --verify ran ls-remote.")
263
+ return 1
264
+ verified = run_keel(r.repo, "sync", "status", "--verify", "--json", env=env)
265
+ if verified.returncode != 1 or not verified.stdout.strip().startswith("{"):
266
+ report(f"{label} --verify should exit 1 and report feat as unknown-to-local: exit {verified.returncode}, "
267
+ f"{(verified.stderr or verified.stdout).strip()[:300]}")
268
+ return 1
269
+ rows = _verify_rows(verified)
270
+ if rows.get("feat", {}).get("state") != "unknown-to-local":
271
+ report(f"{label} feat should be unknown-to-local, got {rows.get('feat')}.")
272
+ return 1
273
+ if rows.get("partial", {}).get("state") != "remote-behind":
274
+ report(f"{label} partial should be remote-behind, got {rows.get('partial')}.")
275
+ return 1
276
+ if rows.get("main", {}).get("state") != "same":
277
+ report(f"{label} main should be same, got {rows.get('main')}.")
278
+ return 1
279
+ calls = _logged(log, "ls-remote")
280
+ if len(calls) != 1:
281
+ report(f"{label} expected exactly one ls-remote for three branches on one remote, got {calls}.")
282
+ return 1
283
+ text = run_keel(r.repo, "sync", "status", "--verify", env=env)
284
+ if "unknown-to-local" not in text.stdout or "remote-behind" not in text.stdout:
285
+ report(f"{label} the text output does not name the states: {text.stdout}")
286
+ return 1
287
+ # A remote that is not named origin.
288
+ hub = base / "hub"
289
+ subprocess.run(["git", "clone", "-q", "-o", "hub", str(r.remote), str(hub)], env=r.env, check=True)
290
+ named = run_keel(hub, "sync", "status", "--verify", "--remote", "hub", "--json", env=r.env)
291
+ if _verify_rows(named).get("main", {}).get("state") != "same":
292
+ report(f"{label} --remote hub did not verify main: {named.stdout.strip()[:300]} {named.stderr.strip()}")
293
+ return 1
294
+ report("sync-status-verify-classifies scenario passed.")
295
+ return 0
296
+
297
+
298
+ def validate_sync_status_verify_failure_scenario() -> int:
299
+ """#526 D3: a lookup that fails is `cannot verify`, never `same`."""
300
+ label = "sync-status-verify-failure:"
301
+ with tempfile.TemporaryDirectory(prefix="keel-sync-verify-fail-") as raw:
302
+ base = Path(raw).resolve()
303
+ r = _Repo(base)
304
+ r.git("remote", "set-url", "origin", str(base / "nowhere.git"))
305
+ verified = run_keel(r.repo, "sync", "status", "--verify", "--json", env=r.env)
306
+ if verified.returncode != 1:
307
+ report(f"{label} --verify against an unreachable remote should exit 1, got {verified.returncode}: "
308
+ f"{verified.stderr.strip()}")
309
+ return 1
310
+ rows = _verify_rows(verified)
311
+ main = rows.get("main", {})
312
+ if main.get("state") != "cannot verify":
313
+ report(f"{label} main should be `cannot verify`, got {main}.")
314
+ return 1
315
+ if not main.get("error"):
316
+ report(f"{label} `cannot verify` should carry git's error, got {main}.")
317
+ return 1
318
+ if any(row.get("state") == "same" for row in rows.values()):
319
+ report(f"{label} a branch was reported same after a failed lookup: {rows}.")
320
+ return 1
321
+ offline = run_keel(r.repo, "sync", "status", env=r.env)
322
+ if offline.returncode != 0:
323
+ report(f"{label} without --verify the run should complete from local refs, got {offline.returncode}: "
324
+ f"{offline.stderr.strip()}")
325
+ return 1
326
+ report("sync-status-verify-failure scenario passed.")
327
+ return 0
328
+
329
+
330
+ def validate_sync_status_push_guidance_scenario() -> int:
331
+ """#526 D5: each fix is printed with the authorization that covers it, and run by nobody."""
332
+ label = "sync-status-push-guidance:"
333
+ with tempfile.TemporaryDirectory(prefix="keel-sync-guidance-") as raw:
334
+ base = Path(raw).resolve()
335
+ r = _Repo(base)
336
+ r.git("checkout", "-qb", "feat")
337
+ r.commit("f1")
338
+ r.git("push", "-qu", "origin", "feat")
339
+ r.commit("f2")
340
+ r.git("checkout", "-qb", "scratch", "main")
341
+ r.commit("s1")
342
+ r.git("checkout", "-q", "main")
343
+ write_text(r.repo / "keel" / "config.yaml", "authorize:\n - push:feat*\n")
344
+ r.git("add", "keel/config.yaml")
345
+ r.git("commit", "-qm", "declare push:feat*")
346
+ r.git("push", "-q", "origin", "main")
347
+ covered = run_keel(r.repo, "sync", "status", env=r.env)
348
+ lines = covered.stdout.splitlines()
349
+ feat = next((i for i, line in enumerate(lines) if line.startswith("branch feat")), None)
350
+ if feat is None:
351
+ report(f"{label} feat is not listed: {covered.stdout}")
352
+ return 1
353
+ block = "\n".join(lines[feat:feat + 3])
354
+ if "git push origin feat" not in block:
355
+ report(f"{label} feat's fix `git push origin feat` is not printed: {block}")
356
+ return 1
357
+ if "push:feat*" not in block:
358
+ report(f"{label} feat's fix does not say `push:feat*` covers it: {block}")
359
+ return 1
360
+ scratch = next((i for i, line in enumerate(lines) if line.startswith("branch scratch")), None)
361
+ block = "\n".join(lines[scratch:scratch + 3]) if scratch is not None else ""
362
+ if "git push -u origin scratch" not in block:
363
+ report(f"{label} scratch's fix `git push -u origin scratch` is not printed: {covered.stdout}")
364
+ return 1
365
+ if "push:scratch" not in block:
366
+ report(f"{label} scratch's fix does not name `push` or `push:scratch` to declare: {block}")
367
+ return 1
368
+ remote_heads = r.git("ls-remote", "--heads", str(r.remote))
369
+ if "refs/heads/scratch" in remote_heads:
370
+ report(f"{label} scratch reached the remote; the report must run nothing.")
371
+ return 1
372
+ report("sync-status-push-guidance scenario passed.")
373
+ return 0
374
+
375
+
376
+ def _declare(r: _Repo, text: str) -> None:
377
+ write_text(r.repo / "keel" / "config.yaml", text)
378
+
379
+
380
+ def _doctor_lines(r: _Repo) -> list[str]:
381
+ return run_keel(r.repo, "--doctor", env=r.env).stdout.splitlines()
382
+
383
+
384
+ def _context(r: _Repo) -> dict:
385
+ return json.loads(run_keel(r.repo, "context", "--json", env=r.env).stdout)
386
+
387
+
388
+ def validate_device_sync_authorization_name_scenario() -> int:
389
+ """#526 D10: `device-sync` is a bare authorization name; `sync` is still refused with its hint."""
390
+ label = "device-sync-authorization-name:"
391
+ with tempfile.TemporaryDirectory(prefix="keel-device-sync-") as raw:
392
+ r = _Repo(Path(raw).resolve())
393
+ _declare(r, "authorize:\n - device-sync\n")
394
+ warnings = " ".join(_context(r).get("warnings", []))
395
+ if "unrecognized" in warnings:
396
+ report(f"{label} `device-sync` was reported as unrecognized: {warnings}")
397
+ return 1
398
+ if "device-sync: authorized" not in _doctor_lines(r):
399
+ report(f"{label} keel --doctor does not list `device-sync: authorized`.")
400
+ return 1
401
+ _declare(r, "authorize:\n - sync\n")
402
+ warnings = " ".join(_context(r).get("warnings", []))
403
+ if "change-close --action" not in warnings:
404
+ report(f"{label} `sync` lost its `change-close --action` hint: {warnings}")
405
+ return 1
406
+ if "device-sync" not in warnings:
407
+ report(f"{label} the accepted names printed for `sync` do not include device-sync: {warnings}")
408
+ return 1
409
+ _declare(r, "authorize:\n - issue\n")
410
+ warnings = " ".join(_context(r).get("warnings", []))
411
+ if "issue:<owner>/<repo>" not in warnings:
412
+ report(f"{label} a bare `issue` is no longer refused with its form: {warnings}")
413
+ return 1
414
+ report("device-sync-authorization-name scenario passed.")
415
+ return 0
416
+
417
+
418
+ def validate_sync_declaration_read_scenario() -> int:
419
+ """#526 D11: `sync:` is read with `lock` and `ttl`; anything else is named and ignored."""
420
+ label = "sync-declaration-read:"
421
+ with tempfile.TemporaryDirectory(prefix="keel-sync-decl-") as raw:
422
+ r = _Repo(Path(raw).resolve())
423
+ _declare(r, "sync:\n lock: true\n ttl: 45m\n")
424
+ declared = _context(r).get("sync")
425
+ if declared != {"lock": True, "ttl": "45m", "ttlSeconds": 2700}:
426
+ report(f"{label} context's `sync` should be the lock in force with a 45-minute lease, got {declared}.")
427
+ return 1
428
+ doctor = [line for line in _doctor_lines(r) if line.startswith("sync:")]
429
+ if not doctor:
430
+ report(f"{label} keel --doctor has no `sync` line.")
431
+ return 1
432
+ for word in ("lock: true", "45m"):
433
+ if word not in doctor[0]:
434
+ report(f"{label} keel --doctor's `sync` line does not name `{word}`: {doctor[0]}")
435
+ return 1
436
+ for text, named in (("sync:\n lock: true\n ttl: soon\n", "ttl: soon"),
437
+ ("sync:\n lock: true\n ttl: 3m\n", "ttl: 3m"),
438
+ ("sync:\n lock: true\n colour: blue\n", "colour"),
439
+ ("sync:\n lock: maybe\n", "lock: maybe")):
440
+ _declare(r, text)
441
+ context = _context(r)
442
+ warnings = " ".join(context.get("warnings", []))
443
+ if named not in warnings:
444
+ report(f"{label} keel context does not name `{named}`: {warnings}")
445
+ return 1
446
+ if context.get("sync") is not None:
447
+ report(f"{label} an unreadable declaration `{named}` was still read as in force: {context.get('sync')}")
448
+ return 1
449
+ doctor = " ".join(line for line in _doctor_lines(r) if line.startswith("sync:"))
450
+ if named not in doctor:
451
+ report(f"{label} keel --doctor does not name `{named}`: {doctor}")
452
+ return 1
453
+ _declare(r, "")
454
+ if _context(r).get("sync") is not None:
455
+ report(f"{label} with no declaration context still reports a `sync` object.")
456
+ return 1
457
+ report("sync-declaration-read scenario passed.")
458
+ return 0
459
+
460
+
461
+ def _expect(label: str, what: str, result: subprocess.CompletedProcess[str], code: int,
462
+ needles: tuple[str, ...] = (), stream: str = "stderr") -> bool:
463
+ """One message per way an expected outcome can fail; True when it held."""
464
+ if result.returncode != code:
465
+ report(f"{label} {what}: expected exit {code}, got {result.returncode}: {result.stderr.strip()[:300]}")
466
+ return False
467
+ text = getattr(result, stream)
468
+ for needle in needles:
469
+ if needle not in text:
470
+ report(f"{label} {what}: the output does not name {needle!r}: {text.strip()[:300]}")
471
+ return False
472
+ return True
473
+
474
+
475
+ def _unmoved(label: str, what: str, d: "_Devices", before: str) -> bool:
476
+ if d.lock_sha() != before:
477
+ report(f"{label} {what}: the remote lock moved.")
478
+ return False
479
+ return True
480
+
481
+
482
+ # --- the branch lock (#526 D6-D10, D19, D22) ---------------------------------------------
483
+
484
+ _LOCK_CONFIG = "authorize:\n - device-sync\n - push:claude/*\nsync:\n lock: true\n ttl: 30m\n"
485
+
486
+
487
+ class _Devices:
488
+ """A bare remote and two clones, each its own device with its own chat store."""
489
+
490
+ def __init__(self, base: Path, config: str = _LOCK_CONFIG) -> None:
491
+ self.base = base
492
+ self.seed = _Repo(base)
493
+ _declare(self.seed, config)
494
+ self.seed.git("add", "keel/config.yaml")
495
+ self.seed.git("commit", "-qm", "declare the lock")
496
+ self.seed.git("push", "-q", "origin", "main")
497
+ self.seed.git("checkout", "-qb", "feat")
498
+ self.head = self.seed.commit("f1")
499
+ self.seed.git("push", "-qu", "origin", "feat")
500
+ self.remote = self.seed.remote
501
+ self.a = self.clone("a", "pm")
502
+ self.b = self.clone("b", "verify")
503
+
504
+ def clone(self, name: str, role: str) -> Path:
505
+ path = self.base / name
506
+ subprocess.run(["git", "clone", "-q", str(self.remote), str(path)], env=_git_env(), check=True,
507
+ capture_output=True)
508
+ for key, value in (("user.email", f"{name}@example.invalid"), ("user.name", name)):
509
+ self.git(path, "config", key, value)
510
+ self.git(path, "checkout", "-q", "feat")
511
+ setattr(self, f"role_{name}", role)
512
+ return path
513
+
514
+ def env(self, path: Path) -> dict[str, str]:
515
+ env = _git_env()
516
+ env["KEEL_CHAT_ROLE"] = getattr(self, f"role_{path.name}")
517
+ return env
518
+
519
+ def git(self, path: Path, *args: str) -> str:
520
+ return subprocess.run(["git", *args], cwd=path, env=_git_env(), check=True,
521
+ capture_output=True, text=True).stdout.strip()
522
+
523
+ def keel(self, path: Path, *args: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]:
524
+ return run_keel(path, *args, env=env or self.env(path))
525
+
526
+ def lock_sha(self) -> str:
527
+ out = self.git(self.base / "a", "ls-remote", str(self.remote), "refs/keel/lock/feat")
528
+ return out.split()[0] if out else ""
529
+
530
+ def lock_message(self) -> str:
531
+ sha = self.lock_sha()
532
+ return subprocess.run(["git", "--git-dir", str(self.remote), "log", "-1", "--format=%B", sha],
533
+ env=_git_env(), check=True, capture_output=True, text=True).stdout if sha else ""
534
+
535
+ def plant(self, message: str, parent: str | None = None) -> str:
536
+ """Push a lock commit as some other device would have."""
537
+ path = self.base / "a"
538
+ if parent:
539
+ self.git(path, "fetch", "-q", str(self.remote), "+refs/keel/lock/feat:refs/keel/lock/feat")
540
+ empty = self.git(path, "hash-object", "-t", "tree", "/dev/null")
541
+ args = ["commit-tree", empty, "-m", message] + (["-p", parent] if parent else [])
542
+ sha = self.git(path, *args)
543
+ self.git(path, "push", "-q", str(self.remote), f"{sha}:refs/keel/lock/feat")
544
+ return sha
545
+
546
+
547
+ def _trailer(message: str, key: str) -> str | None:
548
+ for line in message.splitlines():
549
+ if line.startswith(f"{key}: "):
550
+ return line[len(key) + 2:]
551
+ return None
552
+
553
+
554
+ def validate_branch_lock_race_scenario() -> int:
555
+ """#526 D6, D7: two devices race for a free branch; exactly one wins; the holder renews."""
556
+ label = "branch-lock-race:"
557
+ with tempfile.TemporaryDirectory(prefix="keel-branch-race-") as raw:
558
+ d = _Devices(Path(raw).resolve())
559
+ procs = [subprocess.Popen(["node", str(Path(__file__).resolve().parents[2] / "bin" / "keel.js"),
560
+ "lock", "acquire", "--branch", "feat"], cwd=path, env=d.env(path),
561
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
562
+ for path in (d.a, d.b)]
563
+ results = [(proc, *proc.communicate(timeout=120)) for proc in procs]
564
+ codes = sorted(proc.returncode for proc, _, _ in results)
565
+ if codes != [0, 1]:
566
+ report(f"{label} `keel lock acquire --branch feat` from two devices should give one 0 and one 1, got "
567
+ f"{codes}: {[(out.strip()[:200], err.strip()[:200]) for _, out, err in results]}")
568
+ return 1
569
+ winner = d.a if results[0][0].returncode == 0 else d.b
570
+ loser = d.b if winner == d.a else d.a
571
+ loser_err = results[1][2] if winner == d.a else results[0][2]
572
+ message = d.lock_message()
573
+ if _trailer(message, "keel-lock") != "held" or _trailer(message, "Seq") != "1":
574
+ report(f"{label} the remote lock should be one held commit with Seq 1: {message}")
575
+ return 1
576
+ holder = _trailer(message, "Holder") or ""
577
+ if not holder.startswith(d.env(winner)["KEEL_CHAT_ROLE"] + "@"):
578
+ report(f"{label} Holder should be the winner's role at its device, got {holder!r}.")
579
+ return 1
580
+ if "taken" not in loser_err:
581
+ report(f"{label} the loser should say the lock was taken: {loser_err.strip()}")
582
+ return 1
583
+ renew = d.keel(winner, "lock", "acquire", "--branch", "feat")
584
+ if renew.returncode != 0 or _trailer(d.lock_message(), "Seq") != "2":
585
+ report(f"{label} the holder should renew to Seq 2: exit {renew.returncode}, {renew.stderr.strip()}, "
586
+ f"{d.lock_message()}")
587
+ return 1
588
+ before = d.lock_sha()
589
+ refused = d.keel(loser, "lock", "acquire", "--branch", "feat")
590
+ if refused.returncode != 1:
591
+ report(f"{label} a second device should be refused with exit 1, got {refused.returncode}.")
592
+ return 1
593
+ for word in (holder, "expires", "head"):
594
+ if word not in refused.stderr:
595
+ report(f"{label} the refusal does not name {word!r}: {refused.stderr.strip()}")
596
+ return 1
597
+ if d.lock_sha() != before:
598
+ report(f"{label} a refused acquisition moved the remote lock.")
599
+ return 1
600
+ listed = d.keel(loser, "lock", "list", "--json")
601
+ rows = json.loads(listed.stdout).get("branchLocks", []) if listed.stdout.strip().startswith("{") else []
602
+ feat = next((row for row in rows if row.get("branch") == "feat"), None)
603
+ if not feat:
604
+ report(f"{label} `keel lock list` on the loser does not list feat's lock: {listed.stdout.strip()[:400]}")
605
+ return 1
606
+ if d.env(loser)["KEEL_CHAT_ROLE"] not in json.dumps(feat.get("waiters", [])):
607
+ report(f"{label} `keel lock list` on the loser does not list it as a waiter on feat: {feat}")
608
+ return 1
609
+ local = d.keel(winner, "lock", "acquire", "scratch-dir", "--for", "1h", "--note", "local lease")
610
+ if not _expect(label, "a local lease without --branch", local, 0, ("enforces nothing",), "stdout"):
611
+ return 1
612
+ report("branch-lock-race scenario passed.")
613
+ return 0
614
+
615
+
616
+ def validate_branch_lock_head_and_expiry_scenario() -> int:
617
+ """#526 D7, D8, D19: start where the last holder finished; take an expired lock; break only with a reason."""
618
+ label = "branch-lock-head-and-expiry:"
619
+ with tempfile.TemporaryDirectory(prefix="keel-branch-expiry-") as raw:
620
+ base = Path(raw).resolve()
621
+ d = _Devices(base)
622
+ wrap_env, log = _git_wrapper(base)
623
+ # A released lock whose head the b clone does not have yet.
624
+ d.git(d.a, "commit", "-q", "--allow-empty", "-m", "c2")
625
+ d.git(d.a, "commit", "-q", "--allow-empty", "-m", "c3")
626
+ d.git(d.a, "push", "-q", "origin", "feat")
627
+ c3 = d.git(d.a, "rev-parse", "HEAD")
628
+ released = d.plant(f"keel-lock: released\n\nHolder: pm@elsewhere-00000000\nDevice: elsewhere-00000000\n"
629
+ f"Seq: 4\nExpires: 2000-01-01T00:00:00.000Z\nHead: {c3}\n")
630
+ behind = d.keel(d.b, "lock", "acquire", "--branch", "feat", env={**wrap_env, "KEEL_CHAT_ROLE": "verify"})
631
+ if not _expect(label, "a device behind the released head", behind, 1, (c3[:8],)):
632
+ return 1
633
+ if d.lock_sha() != released:
634
+ report(f"{label} the refused acquisition moved the lock.")
635
+ return 1
636
+ d.git(d.b, "pull", "-q", "--ff-only")
637
+ caught_up = d.keel(d.b, "lock", "acquire", "--branch", "feat", env={**wrap_env, "KEEL_CHAT_ROLE": "verify"})
638
+ message = d.lock_message()
639
+ if caught_up.returncode != 0 or _trailer(message, "Seq") != "5" or _trailer(message, "keel-lock") != "held":
640
+ report(f"{label} after fast-forwarding, b should hold the lock with Seq 5: {caught_up.stderr.strip()} {message}")
641
+ return 1
642
+ # An expired holder elsewhere: taken over with a warning showing the gap.
643
+ stale = d.plant(f"keel-lock: held\n\nHolder: pm@gone-11111111\nDevice: gone-11111111\nSeq: 9\n"
644
+ f"Expires: 2000-01-01T00:00:00.000Z\nHead: {d.head}\n", parent=d.lock_sha())
645
+ took = d.keel(d.b, "lock", "acquire", "--branch", "feat", env={**wrap_env, "KEEL_CHAT_ROLE": "verify"})
646
+ message = d.lock_message()
647
+ if took.returncode != 0 or _trailer(message, "Took-over") != "pm@gone-11111111":
648
+ report(f"{label} an expired lock should be taken with Took-over: {took.stderr.strip()} {message}")
649
+ return 1
650
+ output = took.stdout + took.stderr
651
+ if d.head[:8] not in output or c3[:8] not in output:
652
+ report(f"{label} the take-over should show the last head and the remote's sha: {output.strip()}")
653
+ return 1
654
+ chat = Path(d.git(d.b, "rev-parse", "--path-format=absolute", "--git-common-dir")) / "keel-chat" / "groups"
655
+ records = "".join(f.read_text(encoding="utf-8") for f in chat.rglob("*") if f.is_file()) if chat.exists() else ""
656
+ if "feat" not in records or "pm" not in records:
657
+ report(f"{label} the previous holder's role has no chat record of the take-over.")
658
+ return 1
659
+ # A live lock held elsewhere: only --break with a reason takes it.
660
+ live = d.plant(f"keel-lock: held\n\nHolder: pm@live-22222222\nDevice: live-22222222\nSeq: 20\n"
661
+ f"Expires: 2999-01-01T00:00:00.000Z\nHead: {c3}\n", parent=d.lock_sha())
662
+ bare = d.keel(d.b, "lock", "acquire", "--branch", "feat", "--break")
663
+ if bare.returncode != 2 or d.lock_sha() != live:
664
+ report(f"{label} --break with no reason should exit 2 and move nothing, got {bare.returncode}.")
665
+ return 1
666
+ broke = d.keel(d.b, "lock", "acquire", "--branch", "feat", "--break", "A's machine is gone",
667
+ env={**wrap_env, "KEEL_CHAT_ROLE": "verify"})
668
+ message = d.lock_message()
669
+ if broke.returncode != 0 or _trailer(message, "Broke") != "pm@live-22222222 — A's machine is gone":
670
+ report(f"{label} --break with a reason should take the live lock with Broke: {broke.stderr.strip()} {message}")
671
+ return 1
672
+ parent = subprocess.run(["git", "--git-dir", str(d.remote), "rev-parse", f"{d.lock_sha()}^"],
673
+ env=_git_env(), capture_output=True, text=True).stdout.strip()
674
+ if parent != live:
675
+ report(f"{label} the break did not fast-forward the lock from the live commit.")
676
+ return 1
677
+ forced = [line for line in _logged(log, "push") if "--force" in line or " -f" in line or "+" in line.split()[-1]]
678
+ if forced:
679
+ report(f"{label} a lock push used force: {forced}")
680
+ return 1
681
+ report("branch-lock-head-and-expiry scenario passed.")
682
+ return 0
683
+
684
+
685
+ def validate_branch_lock_release_scenario() -> int:
686
+ """#526 D9: release confirms the push, messages the waiter, and refuses otherwise."""
687
+ label = "branch-lock-release:"
688
+ with tempfile.TemporaryDirectory(prefix="keel-branch-release-") as raw:
689
+ d = _Devices(Path(raw).resolve())
690
+ # Two worktrees of clone a on one chat store, as two devices, so the waiter can be messaged.
691
+ other = d.base / "a-other"
692
+ d.git(d.a, "worktree", "add", "-q", "--detach", str(other))
693
+ a_env = {**d.env(d.a), "KEEL_DEVICE": "laptop-aaaaaaaa"}
694
+ w_env = {**_git_env(), "KEEL_CHAT_ROLE": "verify", "KEEL_DEVICE": "desk-bbbbbbbb"}
695
+ held = d.keel(d.a, "lock", "acquire", "--branch", "feat", env=a_env)
696
+ if held.returncode != 0:
697
+ report(f"{label} a could not acquire feat: {held.stderr.strip()}")
698
+ return 1
699
+ d.git(other, "checkout", "-q", "--detach", "origin/feat")
700
+ waiter = run_keel(other, "lock", "acquire", "--branch", "feat", env=w_env)
701
+ if waiter.returncode != 1:
702
+ report(f"{label} the second device should be refused and wait, got {waiter.returncode}: {waiter.stderr}")
703
+ return 1
704
+ before = d.lock_sha()
705
+ d.git(d.a, "commit", "-q", "--allow-empty", "-m", "unpushed")
706
+ unpushed = d.keel(d.a, "lock", "release", "--branch", "feat", env=a_env)
707
+ what = "release over an unpushed commit"
708
+ if not _expect(label, what, unpushed, 1, ("git push origin feat",)) or not _unmoved(label, what, d, before):
709
+ return 1
710
+ d.git(d.a, "push", "-q", "origin", "feat")
711
+ (d.a / "loose.txt").write_text("x\n", encoding="utf-8")
712
+ dirty = d.keel(d.a, "lock", "release", "--branch", "feat", env=a_env)
713
+ what = "release over an untracked file"
714
+ if not _expect(label, what, dirty, 1, ("loose.txt",)) or not _unmoved(label, what, d, before):
715
+ return 1
716
+ (d.a / "loose.txt").unlink()
717
+ theirs = run_keel(other, "lock", "release", "--branch", "feat", env=w_env)
718
+ what = "releasing another device's lock"
719
+ if not _expect(label, what, theirs, 1, ("pm@laptop-aaaaaaaa",)) or not _unmoved(label, what, d, before):
720
+ return 1
721
+ done = d.keel(d.a, "lock", "release", "--branch", "feat", env=a_env)
722
+ message = d.lock_message()
723
+ tip = d.git(d.a, "rev-parse", "HEAD")
724
+ if done.returncode != 0 or _trailer(message, "keel-lock") != "released" or _trailer(message, "Head") != tip:
725
+ report(f"{label} release after the push should publish released with Head {tip[:8]}: "
726
+ f"{done.returncode} {done.stderr.strip()} {message}")
727
+ return 1
728
+ chat = Path(d.git(d.a, "rev-parse", "--path-format=absolute", "--git-common-dir")) / "keel-chat" / "groups"
729
+ records = "".join(f.read_text(encoding="utf-8") for f in chat.rglob("*") if f.is_file()) if chat.exists() else ""
730
+ if "released" not in records or "verify" not in json.dumps(sorted(str(p) for p in chat.rglob("*"))):
731
+ report(f"{label} the waiter verify has no message that feat was released.")
732
+ return 1
733
+ report("branch-lock-release scenario passed.")
734
+ return 0
735
+
736
+
737
+ def validate_branch_lock_push_authorization_scenario() -> int:
738
+ """#526 D10: lock refs only under device-sync; work branches only under push."""
739
+ label = "branch-lock-push-authorization:"
740
+ with tempfile.TemporaryDirectory(prefix="keel-branch-auth-") as raw:
741
+ base = Path(raw).resolve()
742
+ d = _Devices(base, config="authorize:\n - push:claude/*\nsync:\n lock: true\n")
743
+ for action in ("acquire", "release"):
744
+ refused = d.keel(d.a, "lock", action, "--branch", "feat")
745
+ if not _expect(label, f"`lock {action} --branch` without device-sync", refused, 3, ("device-sync",)):
746
+ return 1
747
+ if d.lock_sha():
748
+ report(f"{label} a lock ref reached the remote without device-sync.")
749
+ return 1
750
+ _declare_in(d, d.a, "authorize:\n - device-sync\n - push:claude/*\n - push-protected:release/*\nsync:\n lock: true\n")
751
+ d.git(d.a, "commit", "-q", "--allow-empty", "-m", "unpushed on feat")
752
+ remote_feat = d.git(d.a, "ls-remote", str(d.remote), "refs/heads/feat").split()[0]
753
+ renewed = d.keel(d.a, "lock", "acquire", "--branch", "feat", "--push")
754
+ if renewed.returncode != 0 or _trailer(d.lock_message(), "keel-lock") != "held":
755
+ report(f"{label} with device-sync the lock should be taken: {renewed.returncode} {renewed.stderr.strip()}")
756
+ return 1
757
+ if d.git(d.a, "ls-remote", str(d.remote), "refs/heads/feat").split()[0] != remote_feat:
758
+ report(f"{label} feat was pushed although only push:claude/* is declared.")
759
+ return 1
760
+ if "push:claude/*" not in renewed.stdout + renewed.stderr:
761
+ report(f"{label} the skipped push does not name push:claude/*: {renewed.stdout} {renewed.stderr}")
762
+ return 1
763
+ # A protected branch is skipped, a failing pre-push hook reported.
764
+ d.git(d.a, "checkout", "-qb", "release/1")
765
+ d.git(d.a, "push", "-qu", "origin", "release/1")
766
+ d.git(d.a, "commit", "-q", "--allow-empty", "-m", "protected")
767
+ protected = d.keel(d.a, "lock", "acquire", "--branch", "release/1", "--push")
768
+ if "push-protected" not in protected.stdout + protected.stderr:
769
+ report(f"{label} a push-protected branch was not reported as skipped: {protected.stdout} {protected.stderr}")
770
+ return 1
771
+ d.git(d.a, "checkout", "-qb", "claude/x")
772
+ d.git(d.a, "push", "-qu", "origin", "claude/x")
773
+ d.git(d.a, "commit", "-q", "--allow-empty", "-m", "hooked")
774
+ hook = d.a / ".git" / "hooks" / "pre-push"
775
+ hook.write_text("#!/bin/sh\necho fast_check failed >&2\nexit 1\n", encoding="utf-8")
776
+ hook.chmod(0o755)
777
+ hooked = d.keel(d.a, "lock", "acquire", "--branch", "claude/x", "--push")
778
+ if (hooked.stdout + hooked.stderr).count("fast_check failed") != 1:
779
+ report(f"{label} a failing pre-push hook should be reported once: {hooked.stdout} {hooked.stderr}")
780
+ return 1
781
+ listed = d.keel(d.a, "lock", "list")
782
+ status = d.keel(d.a, "sync", "status")
783
+ for name, out in (("keel lock list", listed.stdout), ("keel sync status", status.stdout)):
784
+ if "feat" not in out or "pm@" not in out:
785
+ report(f"{label} {name} does not show feat's lock and holder: {out}")
786
+ return 1
787
+ report("branch-lock-push-authorization scenario passed.")
788
+ return 0
789
+
790
+
791
+ def _declare_in(d: _Devices, path: Path, text: str) -> None:
792
+ write_text(path / "keel" / "config.yaml", text)
793
+ d.git(path, "add", "keel/config.yaml")
794
+ d.git(path, "commit", "-qm", "declare")
795
+ d.git(path, "push", "-q", "origin", "HEAD")
796
+
797
+
798
+ def validate_archive_carries_shift_notes_scenario() -> int:
799
+ """#526 D9: the chat archive carries hand-over notes written once under shift-notes/."""
800
+ label = "archive-carries-shift-notes:"
801
+ with tempfile.TemporaryDirectory(prefix="keel-archive-notes-") as raw:
802
+ base = Path(raw).resolve()
803
+ r = _Repo(base)
804
+ gh = base / "gh"
805
+ write_text(gh, "#!/bin/sh\necho PUBLIC\n")
806
+ gh.chmod(0o755)
807
+ env = {**r.env, "KEEL_CHAT_ROLE": "pm", "KEEL_CHAT_GH": str(gh)}
808
+ bound = run_keel(r.repo, "chat", "role", "--set", "pm", env=env)
809
+ if bound.returncode != 0:
810
+ report(f"{label} could not bind pm: {bound.stderr.strip()}")
811
+ return 1
812
+ chat = r.chat()
813
+ note = chat / "shift-notes" / "pm" / "20261116T080000Z-mac-1a2b3c4d.md"
814
+ write_text(note, "next: rerun R007 on 1b64e8c\n")
815
+ write_text(chat / "shift" / "pm.md", "the rewritten-in-place note\n")
816
+
817
+ def tree(ref: str, cwd: Path) -> list[str]:
818
+ return r.git("ls-tree", "-r", "--name-only", ref, cwd=cwd).split()
819
+
820
+ public = run_keel(r.repo, "chat", "archive", "sync", env=env)
821
+ if public.returncode != 0:
822
+ report(f"{label} archive sync failed: {public.stderr.strip()}")
823
+ return 1
824
+ files = tree("refs/heads/keel-chat", r.repo)
825
+ if "shift-notes/pm/20261116T080000Z-mac-1a2b3c4d.md" not in files:
826
+ report(f"{label} the local keel-chat commit does not carry the shift-notes file: {files}")
827
+ return 1
828
+ if any(name.startswith("shift/") for name in files):
829
+ report(f"{label} a rewritten-in-place shift/ file was archived: {files}")
830
+ return 1
831
+ if r.git("ls-remote", str(r.remote), "refs/heads/keel-chat"):
832
+ report(f"{label} a public repository with no archive_public pushed the archive.")
833
+ return 1
834
+ write_text(r.repo / "keel" / "chat.json", json.dumps({"archive": {"remote": "origin"}}) + "\n")
835
+ pushed = run_keel(r.repo, "chat", "archive", "sync", env=env)
836
+ if pushed.returncode != 0 or not r.git("ls-remote", str(r.remote), "refs/heads/keel-chat"):
837
+ report(f"{label} with archive.remote the archive should be pushed: {pushed.stdout} {pushed.stderr}")
838
+ return 1
839
+ second = base / "second"
840
+ subprocess.run(["git", "clone", "-q", str(r.remote), str(second)], env=r.env, check=True, capture_output=True)
841
+ write_text(second / "keel" / "chat.json", json.dumps({"archive": {"remote": "origin"}}) + "\n")
842
+ pulled = run_keel(second, "chat", "archive", "pull", env={**env, "KEEL_CHAT_ROLE": "verify"})
843
+ if pulled.returncode != 0:
844
+ report(f"{label} archive pull on a second clone failed: {pulled.stderr.strip()}")
845
+ return 1
846
+ copy = Path(r.git("rev-parse", "--path-format=absolute", "--git-common-dir", cwd=second)) / "keel-chat" / \
847
+ "shift-notes" / "pm" / "20261116T080000Z-mac-1a2b3c4d.md"
848
+ if not copy.exists():
849
+ report(f"{label} the second clone did not import the shift-notes file.")
850
+ return 1
851
+ if copy.read_bytes() != note.read_bytes():
852
+ report(f"{label} the imported note differs from the original.")
853
+ return 1
854
+ report("archive-carries-shift-notes scenario passed.")
855
+ return 0
856
+
857
+
858
+ # --- the gates at the sync points (#526 D12) ---------------------------------------------
859
+
860
+ def _gate_repo(base: Path, config: str) -> _Repo:
861
+ from validation.common import task_capsule_compact_fixture
862
+ r = _Repo(base)
863
+ change = r.repo / "openspec" / "changes" / "demo"
864
+ write_text(change / "tasks.md", task_capsule_compact_fixture())
865
+ write_text(change / "proposal.md", "# Proposal\n")
866
+ write_text(change / "design.md", "## Context\n\nfixture\n")
867
+ write_text(change / "specs" / "demo" / "spec.md", "## ADDED Requirements\n")
868
+ _declare(r, config)
869
+ r.git("add", "-A")
870
+ r.git("commit", "-qm", "fixture")
871
+ r.git("push", "-q", "origin", "main")
872
+ r.git("checkout", "-qb", "feat")
873
+ r.git("push", "-qu", "origin", "feat")
874
+ return r
875
+
876
+
877
+ def _gate(r: _Repo, env: dict[str, str], stage: str) -> dict:
878
+ args = ["gate", stage, "--change", "demo", "--json"]
879
+ args += ["--task", "1.1", "--no-guard"] if stage == "task-start" else ["--action", "archive"]
880
+ result = run_keel(r.repo, *args, env=env)
881
+ try:
882
+ return json.loads(result.stdout)
883
+ except json.JSONDecodeError:
884
+ return {"status": "error", "problems": [{"code": "unparsed", "message": result.stdout + result.stderr}]}
885
+
886
+
887
+ def _sync_problems(payload: dict) -> list[dict]:
888
+ return [p for p in payload.get("problems", []) if str(p.get("code", "")).startswith("sync-")]
889
+
890
+
891
+ def _has(label: str, what: str, payload: dict, code: str, *needles: str) -> bool:
892
+ found = [p for p in _sync_problems(payload) if p.get("code") == code]
893
+ if not found:
894
+ report(f"{label} {what}: expected a {code} problem, got {payload.get('status')} {_sync_problems(payload)}")
895
+ return False
896
+ for needle in needles:
897
+ if needle not in found[0].get("message", ""):
898
+ report(f"{label} {what}: the {code} problem does not name {needle!r}: {found[0].get('message')}")
899
+ return False
900
+ return True
901
+
902
+
903
+ def validate_sync_gates_lock_scenario() -> int:
904
+ """#526 D12: with the lock declared, task-start and change-close check the lock and the pushed state."""
905
+ label = "sync-gates-lock:"
906
+ with tempfile.TemporaryDirectory(prefix="keel-sync-gates-") as raw:
907
+ base = Path(raw).resolve()
908
+ r = _gate_repo(base, "authorize:\n - device-sync\nsync:\n lock: true\n")
909
+ wrap, log = _git_wrapper(base)
910
+ a = {**wrap, "KEEL_CHAT_ROLE": "pm", "KEEL_DEVICE": "dev-a"}
911
+ b = {**wrap, "KEEL_CHAT_ROLE": "verify", "KEEL_DEVICE": "dev-b"}
912
+ if not _has(label, "no lock", _gate(r, a, "task-start"), "sync-no-lock", "keel lock acquire --branch feat"):
913
+ return 1
914
+ if run_keel(r.repo, "lock", "acquire", "--branch", "feat", env=a).returncode != 0:
915
+ report(f"{label} could not acquire feat.")
916
+ return 1
917
+ lock_before = r.git("ls-remote", str(r.remote), "refs/keel/lock/feat")
918
+ log.write_text("", encoding="utf-8")
919
+ passed = _gate(r, a, "task-start")
920
+ if r.git("ls-remote", str(r.remote), "refs/keel/lock/feat") != lock_before:
921
+ report(f"{label} task-start moved the remote lock.")
922
+ return 1
923
+ if passed.get("status") != "pass":
924
+ report(f"{label} a device holding a live lock with the branch pushed should pass task-start: {passed.get('problems')}")
925
+ return 1
926
+ if len(_logged(log, "ls-remote")) != 1:
927
+ report(f"{label} task-start should make exactly one ls-remote, logged {_logged(log, 'ls-remote')}.")
928
+ return 1
929
+ if _logged(log, "push") or _logged(log, "fetch"):
930
+ report(f"{label} a gate pushed or fetched: {_logged(log, 'push') + _logged(log, 'fetch')}")
931
+ return 1
932
+ # Unpushed commit.
933
+ r.commit("u1")
934
+ if not _has(label, "an unpushed commit", _gate(r, a, "task-start"), "sync-unpushed", "git push origin feat"):
935
+ return 1
936
+ r.git("push", "-q", "origin", "feat")
937
+ # A stale tracking ref: the remote moved to a commit this clone lacks.
938
+ other = base / "other"
939
+ subprocess.run(["git", "clone", "-q", "-b", "feat", str(r.remote), str(other)], env=r.env, check=True, capture_output=True)
940
+ r.git("config", "user.email", "o@example.invalid", cwd=other)
941
+ r.git("config", "user.name", "Other", cwd=other)
942
+ r.commit("o1", cwd=other)
943
+ r.git("push", "-q", "origin", "feat", cwd=other)
944
+ head = r.git("rev-parse", "HEAD")
945
+ remote_tip = r.git("rev-parse", "HEAD", cwd=other)
946
+ if not _has(label, "a remote this clone lacks", _gate(r, a, "task-start"), "sync-remote-unknown",
947
+ "git fetch", head[:8], remote_tip[:8]):
948
+ return 1
949
+ r.git("pull", "-q", "--ff-only")
950
+ # Another device breaks the lock: the lock moved.
951
+ if run_keel(r.repo, "lock", "acquire", "--branch", "feat", "--break", "test", env=b).returncode != 0:
952
+ report(f"{label} dev-b could not break the lock.")
953
+ return 1
954
+ if not _has(label, "another device holds it", _gate(r, a, "task-start"), "sync-lock-not-held", "verify@dev-b"):
955
+ return 1
956
+ # An expired own lease.
957
+ if run_keel(r.repo, "lock", "acquire", "--branch", "feat", "--break", "back", "--for", "1s", env=a).returncode != 0:
958
+ report(f"{label} dev-a could not take the lock back.")
959
+ return 1
960
+ time.sleep(2)
961
+ if not _has(label, "an expired lease", _gate(r, a, "task-start"), "sync-lease-expired", "keel lock acquire --branch feat"):
962
+ return 1
963
+ if run_keel(r.repo, "lock", "acquire", "--branch", "feat", env=a).returncode != 0:
964
+ report(f"{label} dev-a could not renew.")
965
+ return 1
966
+ # change-close: an uncommitted path fails; clean and at the remote passes the check.
967
+ (r.repo / "loose.txt").write_text("x\n", encoding="utf-8")
968
+ if not _has(label, "change-close over an uncommitted path", _gate(r, a, "change-close"), "sync-uncommitted", "loose.txt"):
969
+ return 1
970
+ (r.repo / "loose.txt").unlink()
971
+ closing = _gate(r, a, "change-close")
972
+ if _sync_problems(closing):
973
+ report(f"{label} change-close on a clean pushed branch with the lock held should raise no sync problem: "
974
+ f"{_sync_problems(closing)}")
975
+ return 1
976
+ # task-complete reads nothing remote.
977
+ log.write_text("", encoding="utf-8")
978
+ run_keel(r.repo, "gate", "task-complete", "--change", "demo", "--task", "1.1", "--json", env=a)
979
+ if _logged(log, "ls-remote"):
980
+ report(f"{label} task-complete ran ls-remote.")
981
+ return 1
982
+ # Unreachable remote.
983
+ r.git("remote", "set-url", "origin", str(base / "nowhere.git"))
984
+ if not _has(label, "an unreachable remote", _gate(r, a, "task-start"), "sync-cannot-verify"):
985
+ return 1
986
+ if not _has(label, "an unreachable remote at close", _gate(r, a, "change-close"), "sync-cannot-verify"):
987
+ return 1
988
+ report("sync-gates-lock scenario passed.")
989
+ return 0
990
+
991
+
992
+ def validate_sync_gates_without_declaration_scenario() -> int:
993
+ """#526 D7, D11: with no `sync:` the gates neither touch the network nor change their verdict."""
994
+ label = "sync-gates-without-declaration:"
995
+ with tempfile.TemporaryDirectory(prefix="keel-sync-gates-off-") as raw:
996
+ base = Path(raw).resolve()
997
+ r = _gate_repo(base, "authorize:\n - commit\n")
998
+ r.commit("unpushed")
999
+ r.git("remote", "set-url", "origin", str(base / "nowhere.git"))
1000
+ wrap, log = _git_wrapper(base)
1001
+ started = _gate(r, wrap, "task-start")
1002
+ if started.get("status") != "pass":
1003
+ report(f"{label} task-start should pass as before: {started.get('problems')}")
1004
+ return 1
1005
+ closing = _gate(r, wrap, "change-close")
1006
+ if _sync_problems(started) or _sync_problems(closing):
1007
+ report(f"{label} a gate raised a sync problem with no declaration: {_sync_problems(started) + _sync_problems(closing)}")
1008
+ return 1
1009
+ if _logged(log, "ls-remote"):
1010
+ report(f"{label} a gate ran ls-remote with no declaration: {_logged(log, 'ls-remote')}")
1011
+ return 1
1012
+ report("sync-gates-without-declaration scenario passed.")
1013
+ return 0
1014
+
1015
+
1016
+ # --- keel context (#526 D15) ------------------------------------------------------------
1017
+
1018
+ def validate_context_warns_local_only_scenario() -> int:
1019
+ """#526 D15: one offline warning counts what is only on this machine; selection is unchanged."""
1020
+ label = "context-warns-local-only:"
1021
+ with tempfile.TemporaryDirectory(prefix="keel-context-local-") as raw:
1022
+ base = Path(raw).resolve()
1023
+ r = _gate_repo(base, "authorize:\n - commit\n")
1024
+ r.git("checkout", "-q", "main")
1025
+ clean = _context(r)
1026
+ if any("keel sync status" in w for w in clean.get("warnings", [])):
1027
+ report(f"{label} a clean repository carries a sync warning: {clean.get('warnings')}")
1028
+ return 1
1029
+ r.git("branch", "scratch", "main")
1030
+ r.git("checkout", "-q", "scratch")
1031
+ r.commit("s1")
1032
+ r.git("checkout", "-q", "main")
1033
+ (r.repo / "seed").write_text("changed\n", encoding="utf-8")
1034
+ r.git("stash", "push", "-q")
1035
+ wrap, log = _git_wrapper(base)
1036
+ found = json.loads(run_keel(r.repo, "context", "--json", env=wrap).stdout)
1037
+ warning = [w for w in found.get("warnings", []) if "keel sync status" in w]
1038
+ if len(warning) != 1:
1039
+ report(f"{label} expected one warning naming `keel sync status`, got {found.get('warnings')}")
1040
+ return 1
1041
+ for needle in ("1 local-only branch", "1 stash"):
1042
+ if needle not in warning[0]:
1043
+ report(f"{label} the warning does not count {needle!r}: {warning[0]}")
1044
+ return 1
1045
+ for key in ("status", "nextAction", "selection"):
1046
+ if found.get(key) != clean.get(key):
1047
+ report(f"{label} the warning changed {key}: {clean.get(key)} -> {found.get(key)}")
1048
+ return 1
1049
+ if _logged(log, "ls-remote") or _logged(log, "fetch"):
1050
+ report(f"{label} keel context touched the network.")
1051
+ return 1
1052
+ r.git("remote", "remove", "origin")
1053
+ none = _context(r)
1054
+ if any("keel sync status" in w for w in none.get("warnings", [])):
1055
+ report(f"{label} a repository with no remote carries a sync warning: {none.get('warnings')}")
1056
+ return 1
1057
+ report("context-warns-local-only scenario passed.")
1058
+ return 0
1059
+
1060
+
1061
+ def validate_context_lock_next_action_scenario() -> int:
1062
+ """#526 D15: under the lock, context sends the session to acquire or resume before a task."""
1063
+ from validation.common import ROOT, PLUGIN_ROOT, run_session_start_hook, session_start_context
1064
+ label = "context-lock-next-action:"
1065
+ with tempfile.TemporaryDirectory(prefix="keel-context-lock-") as raw:
1066
+ base = Path(raw).resolve()
1067
+ r = _gate_repo(base, "authorize:\n - device-sync\nsync:\n lock: true\n")
1068
+ pm_a = {**r.env, "KEEL_CHAT_ROLE": "pm", "KEEL_DEVICE": "dev-a"}
1069
+ pm_b = {**r.env, "KEEL_CHAT_ROLE": "pm", "KEEL_DEVICE": "dev-b"}
1070
+ verify_b = {**r.env, "KEEL_CHAT_ROLE": "verify", "KEEL_DEVICE": "dev-b"}
1071
+
1072
+ def ctx(env: dict[str, str]) -> dict:
1073
+ return json.loads(run_keel(r.repo, "context", "--json", env=env).stdout)
1074
+
1075
+ if run_keel(r.repo, "lock", "acquire", "--branch", "feat", env=verify_b).returncode != 0:
1076
+ report(f"{label} verify@dev-b could not acquire feat.")
1077
+ return 1
1078
+ held = ctx(pm_a)
1079
+ action = held.get("nextAction", {})
1080
+ if action.get("kind") != "lock-acquire" or action.get("command") != "keel lock acquire --branch feat":
1081
+ report(f"{label} with feat held live by another device, nextAction should be lock-acquire "
1082
+ f"`keel lock acquire --branch feat`, got {action}")
1083
+ return 1
1084
+ if "verify@dev-b" not in " ".join(held.get("reasons", [])):
1085
+ report(f"{label} the reasons do not name the holder: {held.get('reasons')}")
1086
+ return 1
1087
+ if held.get("status") != "ready":
1088
+ report(f"{label} status should stay ready, got {held.get('status')}")
1089
+ return 1
1090
+ if (held.get("selection") or {}).get("task") != "1.1":
1091
+ report(f"{label} the selection changed: {held.get('selection')}")
1092
+ return 1
1093
+ hook = run_session_start_hook(r.repo, {"hook_event_name": "SessionStart", "source": "startup"},
1094
+ keel_cli=f'node "{ROOT / "bin" / "keel.js"}"', extra_env=pm_a)
1095
+ projected = session_start_context(hook) or ""
1096
+ if "keel lock acquire --branch feat" not in projected:
1097
+ report(f"{label} the SessionStart projection does not show `keel lock acquire --branch feat`: {projected[:400]}")
1098
+ return 1
1099
+ # pm on dev-b takes it and releases it; pm on dev-a is sent to resume.
1100
+ if run_keel(r.repo, "lock", "acquire", "--branch", "feat", "--break", "test", env=pm_b).returncode != 0:
1101
+ report(f"{label} pm@dev-b could not take feat.")
1102
+ return 1
1103
+ released = run_keel(r.repo, "lock", "release", "--branch", "feat", env=pm_b)
1104
+ if released.returncode != 0:
1105
+ report(f"{label} pm@dev-b could not release feat: {released.stderr.strip()}")
1106
+ return 1
1107
+ resume = ctx(pm_a).get("nextAction", {})
1108
+ if resume.get("kind") != "shift-resume" or resume.get("command") != "keel shift resume":
1109
+ report(f"{label} a lock released by this role should send the session to `keel shift resume`, got {resume}")
1110
+ return 1
1111
+ if run_keel(r.repo, "lock", "acquire", "--branch", "feat", env=pm_a).returncode != 0:
1112
+ report(f"{label} pm@dev-a could not acquire feat.")
1113
+ return 1
1114
+ mine = ctx(pm_a).get("nextAction", {})
1115
+ if mine.get("kind") != "task-start":
1116
+ report(f"{label} with this device holding a live lock, nextAction should be task-start, got {mine}")
1117
+ return 1
1118
+ report("context-lock-next-action scenario passed.")
1119
+ return 0
1120
+
1121
+
1122
+ # --- keel shift (#526 D9, D14, D16, D17) ----------------------------------------------
1123
+
1124
+ def _shift_json(path: Path, env: dict[str, str], *args: str) -> tuple[int, dict]:
1125
+ result = run_keel(path, "shift", *args, "--json", env=env)
1126
+ try:
1127
+ return result.returncode, json.loads(result.stdout)
1128
+ except json.JSONDecodeError:
1129
+ return result.returncode, {"raw": result.stdout + result.stderr}
1130
+
1131
+
1132
+ def validate_shift_check_stash_and_notes_scenario() -> int:
1133
+ """#526 D16: a stash of this branch holds the shift; other local-only work is a note."""
1134
+ label = "shift-check-stash-and-notes:"
1135
+ with tempfile.TemporaryDirectory(prefix="keel-shift-stash-") as raw:
1136
+ base = Path(raw).resolve()
1137
+ r = _Repo(base)
1138
+ env = {**r.env, "KEEL_CHAT_ROLE": "pm", "KEEL_DEVICE": "dev-a"}
1139
+ r.git("checkout", "-qb", "feat")
1140
+ r.git("push", "-qu", "origin", "feat")
1141
+ r.git("checkout", "-qb", "other")
1142
+ (r.repo / "seed").write_text("other change\n", encoding="utf-8")
1143
+ r.git("stash", "push", "-q")
1144
+ r.git("checkout", "-q", "feat")
1145
+ # Modern Git rejects storing an ordinary commit as a stash. Generate
1146
+ # a real stash object without adding a branch-shaped reflog entry.
1147
+ (r.repo / "seed").write_text("custom stash change\n", encoding="utf-8")
1148
+ loose = r.git("stash", "create", "detached")
1149
+ r.git("checkout", "--", "seed")
1150
+ r.git("stash", "show", "--stat", loose)
1151
+ r.git("stash", "store", "-m", "custom message", loose)
1152
+ (r.repo / "seed").write_text("feat change\n", encoding="utf-8")
1153
+ r.git("stash", "push", "-q")
1154
+ r.git("branch", "scratch", "main")
1155
+ r.git("checkout", "-q", "scratch")
1156
+ r.commit("s1")
1157
+ r.git("checkout", "-q", "feat")
1158
+ code, data = _shift_json(r.repo, env, "check")
1159
+ items = data.get("items", [])
1160
+ stash_items = [i for i in items if i.get("kind") == "stash"]
1161
+ for failed, why in ((code != 1, f"the check should exit 1, got {code}"),
1162
+ (len(stash_items) != 1, f"expected exactly one stash item, got {items}"),
1163
+ (bool(stash_items) and "feat" not in stash_items[0].get("detail", ""), f"the stash item does not name feat: {stash_items}")):
1164
+ if failed:
1165
+ report(f"{label} {why}")
1166
+ return 1
1167
+ notes = " ".join(data.get("notes", []))
1168
+ for needle in ("scratch", "on other", "custom message", "keel sync status"):
1169
+ if needle not in notes:
1170
+ report(f"{label} the notes do not name {needle!r}: {data.get('notes')}")
1171
+ return 1
1172
+ ref = next((s.split(":")[0] for s in r.git("stash", "list").splitlines() if "on feat" in s), None)
1173
+ r.git("stash", "drop", "-q", ref)
1174
+ code, data = _shift_json(r.repo, env, "check")
1175
+ if code != 0:
1176
+ report(f"{label} with the feat stash dropped the check should exit 0: {data.get('items')}")
1177
+ return 1
1178
+ _declare(r, "authorize:\n - device-sync\nsync:\n lock: true\n")
1179
+ r.git("add", "keel/config.yaml")
1180
+ r.git("commit", "-qm", "lock")
1181
+ r.git("push", "-q", "origin", "feat")
1182
+ if run_keel(r.repo, "lock", "acquire", "--branch", "feat", env=env).returncode != 0:
1183
+ report(f"{label} could not acquire feat.")
1184
+ return 1
1185
+ code, data = _shift_json(r.repo, env, "check")
1186
+ if not any("keel shift ready" in n and "releases" in n for n in data.get("notes", [])):
1187
+ report(f"{label} a held lock should be a note that `keel shift ready` releases it: {data.get('notes')}")
1188
+ return 1
1189
+ report("shift-check-stash-and-notes scenario passed.")
1190
+ return 0
1191
+
1192
+
1193
+ def _archived_devices(base: Path) -> _Devices:
1194
+ d = _Devices(base, config=_LOCK_CONFIG)
1195
+ for path in (d.a, d.b):
1196
+ write_text(path / "keel" / "chat.json", json.dumps({"archive": {"remote": "origin"}}) + "\n")
1197
+ info = path / ".git" / "info" / "exclude"
1198
+ info.write_text(info.read_text(encoding="utf-8") + "keel/chat.json\n", encoding="utf-8")
1199
+ return d
1200
+
1201
+
1202
+ def _note_body(path: Path) -> str:
1203
+ return path.read_text(encoding="utf-8") if path.exists() else ""
1204
+
1205
+
1206
+ def validate_shift_ready_releases_lock_scenario() -> int:
1207
+ """#526 D9, D16: ready releases the lock with the archived note and lists what stays local."""
1208
+ label = "shift-ready-releases-lock:"
1209
+ with tempfile.TemporaryDirectory(prefix="keel-shift-ready-") as raw:
1210
+ base = Path(raw).resolve()
1211
+ d = _archived_devices(base)
1212
+ env = d.env(d.a)
1213
+ if d.keel(d.a, "lock", "acquire", "--branch", "feat").returncode != 0:
1214
+ report(f"{label} could not acquire feat.")
1215
+ return 1
1216
+ d.git(d.a, "branch", "scratch", "feat")
1217
+ d.git(d.a, "checkout", "-q", "scratch")
1218
+ d.git(d.a, "commit", "-q", "--allow-empty", "-m", "local only")
1219
+ d.git(d.a, "checkout", "-q", "feat")
1220
+ chat = Path(d.git(d.a, "rev-parse", "--path-format=absolute", "--git-common-dir")) / "keel-chat"
1221
+ # A remote that cannot be reached: ready refuses and stores nothing.
1222
+ d.git(d.a, "remote", "set-url", "origin", str(base / "nowhere.git"))
1223
+ failed = run_keel(d.a, "shift", "ready", "next: rerun R007", env=env)
1224
+ if failed.returncode != 1 or (chat / "shift" / "pm.md").exists() or (chat / "shift-notes").exists():
1225
+ report(f"{label} with the remote unreachable ready should exit 1 and store nothing: {failed.returncode} "
1226
+ f"{failed.stderr.strip()[:300]}")
1227
+ return 1
1228
+ d.git(d.a, "remote", "set-url", "origin", str(d.remote))
1229
+ done = run_keel(d.a, "shift", "ready", "next: rerun R007", env=env)
1230
+ if done.returncode != 0:
1231
+ report(f"{label} ready should succeed: {done.stderr.strip()[:400]}")
1232
+ return 1
1233
+ message = d.lock_message()
1234
+ if _trailer(message, "keel-lock") != "released":
1235
+ report(f"{label} the lock should be released: {message}")
1236
+ return 1
1237
+ head = d.git(d.a, "rev-parse", "HEAD")
1238
+ if _trailer(message, "Head") != head:
1239
+ report(f"{label} the released Head should be {head[:8]}: {message}")
1240
+ return 1
1241
+ note_path = _trailer(message, "Note") or ""
1242
+ if not note_path.startswith("shift-notes/pm/"):
1243
+ report(f"{label} Note should name a shift-notes/pm/ file: {note_path!r}")
1244
+ return 1
1245
+ if "next: rerun R007" not in _note_body(chat / note_path):
1246
+ report(f"{label} the file Note names does not hold the note: {note_path!r}")
1247
+ return 1
1248
+ archived = d.git(d.a, "ls-tree", "-r", "--name-only", "refs/heads/keel-chat").split()
1249
+ if note_path not in archived:
1250
+ report(f"{label} the archive does not carry {note_path}: {archived}")
1251
+ return 1
1252
+ stored = _note_body(chat / "shift" / "pm.md")
1253
+ if "## Not on the remote at hand-over" not in stored or "scratch" not in stored.split("## Not on the remote at hand-over")[1]:
1254
+ report(f"{label} the stored note should end with the local-only section naming scratch: {stored}")
1255
+ return 1
1256
+ with tempfile.TemporaryDirectory(prefix="keel-shift-ready-off-") as raw:
1257
+ base = Path(raw).resolve()
1258
+ r = _Repo(base)
1259
+ env = {**r.env, "KEEL_CHAT_ROLE": "pm"}
1260
+ chat = r.chat()
1261
+ plain = run_keel(r.repo, "shift", "ready", "just the text", env=env)
1262
+ body = _note_body(chat / "shift" / "pm.md")
1263
+ for failed, why in ((plain.returncode != 0, f"ready with nothing to list failed: {plain.stderr.strip()}"),
1264
+ (not body.rstrip().endswith("just the text"), f"the note should end with the text given: {body!r}"),
1265
+ ("Not on the remote" in body, f"with nothing to list the note carries a section: {body!r}")):
1266
+ if failed:
1267
+ report(f"{label} {why}")
1268
+ return 1
1269
+ run_keel(r.repo, "shift", "resume", env=env)
1270
+ r.git("branch", "scratch", "main")
1271
+ r.git("checkout", "-q", "scratch")
1272
+ r.commit("s1")
1273
+ r.git("checkout", "-q", "main")
1274
+ listed = run_keel(r.repo, "shift", "ready", "with a branch left", env=env)
1275
+ body = _note_body(chat / "shift" / "pm.md")
1276
+ for failed, why in ((listed.returncode != 0, f"ready without the declaration failed: {listed.stderr.strip()}"),
1277
+ ("## Not on the remote at hand-over" not in body, f"the section is missing: {body!r}"),
1278
+ ("scratch" not in body, f"the section does not name scratch: {body!r}")):
1279
+ if failed:
1280
+ report(f"{label} {why}")
1281
+ return 1
1282
+ if r.git("for-each-ref", "refs/keel/"):
1283
+ report(f"{label} without the declaration a lock ref was written.")
1284
+ return 1
1285
+ report("shift-ready-releases-lock scenario passed.")
1286
+ return 0
1287
+
1288
+
1289
+ def validate_shift_resume_takes_over_scenario() -> int:
1290
+ """#526 D14: resume is the takeover: switch, acquire, pull the archive, print the note."""
1291
+ label = "shift-resume-takes-over:"
1292
+ with tempfile.TemporaryDirectory(prefix="keel-shift-resume-") as raw:
1293
+ base = Path(raw).resolve()
1294
+ d = _archived_devices(base)
1295
+ a_env = d.env(d.a)
1296
+ if d.keel(d.a, "lock", "acquire", "--branch", "feat").returncode != 0:
1297
+ report(f"{label} could not acquire feat on a.")
1298
+ return 1
1299
+ d.git(d.a, "commit", "-q", "--allow-empty", "-m", "a's last commit")
1300
+ d.git(d.a, "push", "-q", "origin", "feat")
1301
+ head = d.git(d.a, "rev-parse", "HEAD")
1302
+ ready = run_keel(d.a, "shift", "ready", f"next: verify feat @ {head[:10]}", env=a_env)
1303
+ if ready.returncode != 0:
1304
+ report(f"{label} a could not hand over: {ready.stderr.strip()[:300]}")
1305
+ return 1
1306
+ d.git(d.b, "checkout", "-q", "main")
1307
+ b_env = {**_git_env(), "KEEL_CHAT_ROLE": "pm"}
1308
+ run_keel(d.b, "chat", "role", "--set", "pm", env=b_env)
1309
+ resumed = run_keel(d.b, "shift", "resume", env=b_env)
1310
+ if resumed.returncode != 0:
1311
+ report(f"{label} resume on b failed: {resumed.stderr.strip()[:400]}")
1312
+ return 1
1313
+ if d.git(d.b, "rev-parse", "--abbrev-ref", "HEAD") != "feat" or d.git(d.b, "rev-parse", "HEAD") != head:
1314
+ report(f"{label} b should be on feat at a's head {head[:8]}.")
1315
+ return 1
1316
+ holder = _trailer(d.lock_message(), "Holder") or ""
1317
+ if _trailer(d.lock_message(), "keel-lock") != "held":
1318
+ report(f"{label} the lock should be held after b's resume: {d.lock_message()}")
1319
+ return 1
1320
+ if not holder.startswith("pm@"):
1321
+ report(f"{label} the holder should be pm at b's device, got {holder!r}")
1322
+ return 1
1323
+ if f"next: verify feat @ {head[:10]}" not in resumed.stdout:
1324
+ report(f"{label} resume should print a's note: {resumed.stdout[:400]}")
1325
+ return 1
1326
+ # A third clone: a dirty worktree, then a live lock held elsewhere, are refused.
1327
+ c = d.clone("c", "pm")
1328
+ d.git(c, "checkout", "-q", "main")
1329
+ c_env = {**_git_env(), "KEEL_CHAT_ROLE": "pm"}
1330
+ run_keel(c, "chat", "role", "--set", "pm", env=c_env)
1331
+ (c / "untracked.txt").write_text("x\n", encoding="utf-8")
1332
+ dirty = run_keel(c, "shift", "resume", env=c_env)
1333
+ if not _expect(label, "resume over an untracked file", dirty, 1, ("untracked.txt",)):
1334
+ return 1
1335
+ (c / "untracked.txt").unlink()
1336
+ held = run_keel(c, "shift", "resume", env=c_env)
1337
+ if not _expect(label, "resume while b holds feat live", held, 1, (holder,)):
1338
+ return 1
1339
+ if "next: verify" in held.stdout:
1340
+ report(f"{label} a refused resume printed the note as current.")
1341
+ return 1
1342
+ report("shift-resume-takes-over scenario passed.")
1343
+ return 0
1344
+
1345
+
1346
+ def validate_handover_waits_for_lock_scenario() -> int:
1347
+ """#526 D17: a queued hand-over starts no session while another device holds the branch."""
1348
+ label = "handover-waits-for-lock:"
1349
+ with tempfile.TemporaryDirectory(prefix="keel-handover-lock-") as raw:
1350
+ base = Path(raw).resolve()
1351
+ d = _Devices(base)
1352
+ if d.keel(d.b, "lock", "acquire", "--branch", "feat").returncode != 0:
1353
+ report(f"{label} b could not acquire feat.")
1354
+ return 1
1355
+ d.git(d.a, "fetch", "-q", "origin", "+refs/keel/lock/*:refs/keel/lock/*")
1356
+ a_env = d.env(d.a)
1357
+ run_keel(d.a, "chat", "role", "--set", "pm", env=a_env)
1358
+ chat = Path(d.git(d.a, "rev-parse", "--path-format=absolute", "--git-common-dir")) / "keel-chat"
1359
+ write_text(chat / "shift" / "queue" / "pm.json", json.dumps({
1360
+ "role": "pm", "session": "11111111-2222-3333-4444-555555555555", "pid": None,
1361
+ "worktree": str(d.a), "requested_at": "2026-11-16T08:00:00+08:00", "state": "pending"}))
1362
+ calls = base / "claude.log"
1363
+ stub = base / "claude"
1364
+ stub.write_text(f'#!/bin/sh\nprintf "%s\\n" "$*" >> "{calls}"\n'
1365
+ 'case "$1" in agents) echo "[]";; esac\nexit 0\n', encoding="utf-8")
1366
+ stub.chmod(0o755)
1367
+ tick = run_keel(Path("/"), "tick", "--repo", str(d.a), env={**a_env, "KEEL_CLAUDE": str(stub)})
1368
+ started = [line for line in (calls.read_text(encoding="utf-8").splitlines() if calls.exists() else []) if "--bg" in line]
1369
+ if started:
1370
+ report(f"{label} a session was started while b holds feat: {started} {tick.stdout[-300:]}")
1371
+ return 1
1372
+ entry = json.loads((chat / "shift" / "queue" / "pm.json").read_text(encoding="utf-8"))
1373
+ holder = _trailer(d.lock_message(), "Holder") or ""
1374
+ if "feat" not in str(entry.get("waiting_on")) or holder not in str(entry.get("waiting_on")):
1375
+ report(f"{label} the entry should wait naming feat and {holder}: {entry}")
1376
+ return 1
1377
+ shown = run_keel(d.a, "shift", "status", env=a_env)
1378
+ if "feat" not in shown.stdout or holder not in shown.stdout:
1379
+ report(f"{label} `keel shift status` does not name feat and the holder: {shown.stdout[:400]}")
1380
+ return 1
1381
+ report("handover-waits-for-lock scenario passed.")
1382
+ return 0
1383
+
1384
+
1385
+ def validate_tick_renews_and_pushes_scenario() -> int:
1386
+ label = "tick-renews-and-pushes:"
1387
+ with tempfile.TemporaryDirectory(prefix="keel-tick-sync-") as raw:
1388
+ base = Path(raw)
1389
+ d = _Devices(base, _LOCK_CONFIG.replace("push:claude/*", "push"))
1390
+ env, log = _git_wrapper(base)
1391
+ env.update(KEEL_CHAT_ROLE="pm", KEEL_DEVICE="dev-a")
1392
+ d.keel(d.a, "lock", "acquire", "--branch", "feat", env=env)
1393
+ before = _trailer(d.lock_message(), "Expires")
1394
+ d.git(d.a, "commit", "--allow-empty", "-qm", "finished work")
1395
+ head = d.git(d.a, "rev-parse", "HEAD")
1396
+ log.write_text("")
1397
+ tick = run_keel(Path("/"), "tick", "--repo", str(d.a), "--json", env=env)
1398
+ message = d.lock_message()
1399
+ if tick.returncode:
1400
+ report(f"{label} tick failed: {tick.stderr}")
1401
+ return 1
1402
+ if _trailer(message, "Seq") != "2":
1403
+ report(f"{label} tick must renew once: {message}")
1404
+ return 1
1405
+ if _trailer(message, "Expires") <= before:
1406
+ report(f"{label} tick must renew from /: {tick.stdout} {tick.stderr}; lock {message}")
1407
+ return 1
1408
+ if d.git(d.a, "ls-remote", "origin", "refs/heads/feat").split()[0] != head or _trailer(message, "Head") != head:
1409
+ report(f"{label} tick must push finished work and record the remote Head: {message}")
1410
+ return 1
1411
+ pushes = _logged(log, "push")
1412
+ if any("--force" in line or not ("refs/heads/feat:refs/heads/feat" in line or ":refs/keel/lock/feat" in line) for line in pushes):
1413
+ report(f"{label} unexpected push: {pushes}")
1414
+ return 1
1415
+ other = {**env, "KEEL_DEVICE": "dev-b", "KEEL_CHAT_ROLE": "verify"}
1416
+ d.keel(d.a, "lock", "acquire", "--branch", "feat", "--break", "test takeover", env=other)
1417
+ # Restore the stale local observation so renewal must check the remote.
1418
+ old = d.git(d.a, "rev-parse", "refs/keel/lock/feat^")
1419
+ d.git(d.a, "update-ref", "refs/keel/lock/feat", old)
1420
+ held = d.lock_sha()
1421
+ first = run_keel(Path("/"), "tick", "--repo", str(d.a), env=env)
1422
+ second = run_keel(Path("/"), "tick", "--repo", str(d.a), env=env)
1423
+ if d.lock_sha() != held:
1424
+ report(f"{label} tick changed the other device lock")
1425
+ return 1
1426
+ if "dev-b" not in first.stdout:
1427
+ report(f"{label} takeover report missing: {first.stdout}")
1428
+ return 1
1429
+ if "dev-b" in second.stdout:
1430
+ report(f"{label} takeover was reported twice: {second.stdout}")
1431
+ return 1
1432
+ _declare_in(d, d.a, "sync:\n lock: true\n")
1433
+ log.write_text("")
1434
+ run_keel(Path("/"), "tick", "--repo", str(d.a), env=env)
1435
+ if _logged(log, "push") or _logged(log, "ls-remote"):
1436
+ report(f"{label} no device-sync must leave network untouched: {log.read_text()}")
1437
+ return 1
1438
+ report("tick-renews-and-pushes scenario passed.")
1439
+ return 0
1440
+
1441
+
1442
+ def validate_prompt_hook_renews_when_due_scenario() -> int:
1443
+ label = "prompt-hook-renews-when-due:"
1444
+ with tempfile.TemporaryDirectory(prefix="keel-prompt-sync-") as raw:
1445
+ base = Path(raw)
1446
+ d = _Devices(base)
1447
+ env, log = _git_wrapper(base)
1448
+ env["KEEL_DEVICE"] = "dev-a"
1449
+ d.keel(d.a, "lock", "acquire", "--branch", "feat", env=env)
1450
+ message = d.lock_message()
1451
+ # The commit trailer is the public lease clock; 15 minutes left means renewal is due.
1452
+ from datetime import datetime, timedelta, timezone
1453
+ due = (datetime.now(timezone.utc) + timedelta(minutes=15)).isoformat().replace("+00:00", "Z")
1454
+ message = message.replace(_trailer(message, "Expires"), due)
1455
+ d.plant(message, d.lock_sha())
1456
+ d.git(d.a, "fetch", "-q", "origin", "+refs/keel/lock/feat:refs/keel/lock/feat")
1457
+ before = int(_trailer(message, "Seq"))
1458
+ payload = json.dumps({"cwd": str(d.a)})
1459
+ def prompt() -> subprocess.CompletedProcess[str]:
1460
+ from validation.common import ROOT
1461
+ return subprocess.run(["node", str(ROOT / "bin/keel.js"), "chat", "hook", "user-prompt-submit"],
1462
+ input=payload, cwd="/", env=env, text=True, capture_output=True)
1463
+ first, second = prompt(), prompt()
1464
+ if first.returncode or second.returncode or int(_trailer(d.lock_message(), "Seq")) != before + 1:
1465
+ report(f"{label} two due prompts must renew only once: {first.stdout} {first.stderr} / {second.stdout} {second.stderr}")
1466
+ return 1
1467
+ message = d.lock_message().replace(_trailer(d.lock_message(), "Expires"), due)
1468
+ d.plant(message, d.lock_sha())
1469
+ d.git(d.a, "fetch", "-q", "origin", "+refs/keel/lock/feat:refs/keel/lock/feat")
1470
+ state = d.a / ".git/keel-chat/lock-renewals.json"
1471
+ state.unlink(missing_ok=True)
1472
+ d.git(d.a, "remote", "set-url", "origin", str(base / "gone"))
1473
+ failed = prompt()
1474
+ if failed.returncode or failed.stdout or failed.stderr:
1475
+ report(f"{label} unreachable remote must stay quiet and exit 0: {failed}")
1476
+ return 1
1477
+ # A foreign lock in the last fetched refs makes no network calls.
1478
+ d.git(d.a, "remote", "set-url", "origin", str(d.remote))
1479
+ message = message.replace("Device: dev-a", "Device: dev-b")
1480
+ d.plant(message, d.lock_sha())
1481
+ d.git(d.a, "fetch", "-q", "origin", "+refs/keel/lock/feat:refs/keel/lock/feat")
1482
+ log.write_text("")
1483
+ prompt()
1484
+ if _logged(log, "push") or _logged(log, "ls-remote") or _logged(log, "fetch"):
1485
+ report(f"{label} a foreign lock must not renew: {log.read_text()}")
1486
+ return 1
1487
+ report("prompt-hook-renews-when-due scenario passed.")
1488
+ return 0
1489
+
1490
+
1491
+ def validate_patrol_old_local_only_risk_scenario() -> int:
1492
+ label = "patrol-old-local-only-risk:"
1493
+ with tempfile.TemporaryDirectory(prefix="keel-patrol-sync-") as raw:
1494
+ base = Path(raw)
1495
+ r = _Repo(base)
1496
+ r.git("checkout", "-qb", "feat")
1497
+ wrap, log = _git_wrapper(base)
1498
+ wrap["KEEL_CHAT_ROLE"] = "pm"
1499
+ run_keel(r.repo, "chat", "role", "--set", "verify", env=_git_env())
1500
+ def commit_at(hours: int) -> None:
1501
+ env = {**r.env, "GIT_COMMITTER_DATE": f"{int(time.time()) - hours * 3600} +0000"}
1502
+ subprocess.run(["git", "commit", "--allow-empty", "-qm", "work"], cwd=r.repo, env=env, check=True)
1503
+ commit_at(30)
1504
+ def patrol() -> subprocess.CompletedProcess[str]:
1505
+ return run_keel(r.repo, "patrol", "--since-last", "--notify", env=wrap)
1506
+ def records(needle: str) -> list[str]:
1507
+ files = (r.chat() / "groups/dm-keel-patrol--pm/log").glob("*.md")
1508
+ return [f.read_text() for f in files if needle in f.read_text() and "kind: message" in f.read_text()]
1509
+ log.write_text("")
1510
+ runs = [patrol(), patrol(), patrol()]
1511
+ sent = records("feat")
1512
+ if len(sent) != 1:
1513
+ report(f"{label} keel-patrol must send one old feat risk, got {len(sent)}: {[x.stdout for x in runs]}")
1514
+ return 1
1515
+ if "verify" not in sent[0]:
1516
+ report(f"{label} old branch risk must name covered role verify: {sent}")
1517
+ return 1
1518
+ commit_at(0)
1519
+ patrol()
1520
+ if len(records("feat")) != 1:
1521
+ report(f"{label} growing feat must not send its risk twice")
1522
+ return 1
1523
+ r.git("checkout", "-qb", "recent", "origin/main")
1524
+ commit_at(2)
1525
+ recent = patrol()
1526
+ if "recent" in recent.stdout:
1527
+ report(f"{label} two-hour work should add no risk: {recent.stdout}")
1528
+ return 1
1529
+ r.git("checkout", "-q", "main")
1530
+ for i in range(20):
1531
+ (r.repo / f"dirty{i}").write_text("uncommitted")
1532
+ dirty = patrol()
1533
+ if "local-only" in dirty.stdout and "main" in dirty.stdout:
1534
+ report(f"{label} dirty paths alone should add no main risk: {dirty.stdout}")
1535
+ return 1
1536
+ for i in range(20):
1537
+ (r.repo / f"dirty{i}").unlink()
1538
+ (r.repo / "seed").write_text("stash this")
1539
+ env = {**r.env, "GIT_COMMITTER_DATE": f"{int(time.time()) - 3 * 86400} +0000"}
1540
+ subprocess.run(["git", "stash", "push", "-qm", "old stash"], cwd=r.repo, env=env, check=True)
1541
+ patrol(); patrol()
1542
+ if len(records("stash@{0}")) != 1:
1543
+ report(f"{label} old stash must send one standing risk: {records('stash')}")
1544
+ return 1
1545
+ if _logged(log, "fetch") or _logged(log, "ls-remote"):
1546
+ report(f"{label} patrol must use only local refs: {log.read_text()}")
1547
+ return 1
1548
+ report("patrol-old-local-only-risk scenario passed.")
1549
+ return 0
1550
+
1551
+
1552
+ def validate_doctor_reports_branch_locks_scenario() -> int:
1553
+ label = "doctor-reports-branch-locks:"
1554
+ with tempfile.TemporaryDirectory(prefix="keel-doctor-sync-") as raw:
1555
+ d = _Devices(Path(raw))
1556
+ env = {**d.env(d.a), "KEEL_DEVICE": "dev-a"}
1557
+ d.keel(d.a, "lock", "acquire", "--branch", "feat", env=env)
1558
+ doctor = d.keel(d.a, "--doctor", env=env)
1559
+ sync = "\n".join(line for line in (doctor.stdout + doctor.stderr).splitlines() if "sync" in line)
1560
+ for expected in ("lock: true", "30m", "dev-a", "feat", _trailer(d.lock_message(), "Expires"), "last renewal", "hook"):
1561
+ if expected not in sync:
1562
+ report(f"{label} sync line lacks {expected!r}: {sync}")
1563
+ return 1
1564
+ report("doctor-reports-branch-locks scenario passed.")
1565
+ return 0
1566
+
1567
+
1568
+ def validate_release_skips_nested_worktrees_scenario() -> int:
1569
+ from validation.common import ROOT
1570
+ label = "release-skips-nested-worktrees:"
1571
+ with tempfile.TemporaryDirectory(prefix="keel-release-nested-") as raw:
1572
+ fixture = Path(raw) / "candidate"
1573
+ def ignore(directory: str, names: list[str]) -> list[str]:
1574
+ excluded = {".git", "node_modules", "__pycache__"}
1575
+ if Path(directory) == ROOT / ".claude":
1576
+ excluded.add("worktrees")
1577
+ return [name for name in names if name in excluded]
1578
+ shutil.copytree(ROOT, fixture, ignore=ignore, symlinks=True)
1579
+ (fixture / "node_modules").symlink_to(ROOT / "node_modules", target_is_directory=True)
1580
+ subprocess.run(["git", "init", "-q", str(fixture)], check=True)
1581
+ nested = fixture / ".claude/worktrees/other"
1582
+ nested.mkdir(parents=True)
1583
+ subprocess.run(["git", "init", "-q", str(nested)], check=True)
1584
+ version = json.loads((fixture / "package.json").read_text())["version"]
1585
+ marker = nested / "AGENTS.md"
1586
+ marker.write_text(f"<!-- keel:start version={version} -->\nindependent checkout\n")
1587
+ old = nested / "historical.md"
1588
+ old.write_text("<!-- keel:start version=5.28.0 -->\n")
1589
+ before = {p.name: p.read_bytes() for p in (marker, old)}
1590
+ bump = subprocess.run(["node", "scripts/bump_version.js", "minor"], cwd=fixture, text=True, capture_output=True)
1591
+ if bump.returncode:
1592
+ report(f"{label} bump failed: {bump.stderr}")
1593
+ return 1
1594
+ after_version = json.loads((fixture / "package.json").read_text())["version"]
1595
+ if after_version == version:
1596
+ report(f"{label} outer version did not increment")
1597
+ return 1
1598
+ for p in (marker, old):
1599
+ if p.read_bytes() != before[p.name]:
1600
+ report(f"{label} bump modified another checkout: {p.name}")
1601
+ return 1
1602
+ baseline = subprocess.run(["node", "scripts/run_python.js", "scripts/validate_plugin.py"],
1603
+ cwd=fixture, text=True, capture_output=True)
1604
+ if baseline.returncode:
1605
+ report(f"{label} baseline must ignore another checkout's markers: {baseline.stdout} {baseline.stderr}")
1606
+ return 1
1607
+ report("release-skips-nested-worktrees scenario passed.")
1608
+ return 0