@christang/keel 5.183.0 → 5.184.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3802 @@
1
+ """Keel validation: install (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
+ BOOTSTRAP_BLOCK_BYTE_BUDGET,
26
+ LEGACY_PROFILE_SKILLS,
27
+ MANAGED_END,
28
+ OPENSPEC_CONFIG_PATH,
29
+ OPENSPEC_SCHEMA_ROOT,
30
+ OPENSPEC_SURFACE_OVERLAY_END,
31
+ OPENSPEC_SURFACE_OVERLAY_START,
32
+ PACKAGE_VERSION,
33
+ PLUGIN_ROOT,
34
+ ROOT,
35
+ extract_managed_block,
36
+ guard_task_fixture,
37
+ packaged_openspec_schema_install_paths,
38
+ path_without_openspec,
39
+ report,
40
+ run_keel,
41
+ run_openspec,
42
+ skip_scenario,
43
+ snapshot_files,
44
+ validate_openspec_schema,
45
+ validate_resident_blocks,
46
+ validate_skill_docs,
47
+ validate_skill_portability,
48
+ validation_source_with,
49
+ write_text,
50
+ )
51
+ from validation import registry
52
+
53
+
54
+ # Mirrors KEEL_PACKAGE_NAME in scripts/install_to_repo.py, one of the two
55
+ # signals is_keel_source_repo reads.
56
+ KEEL_PACKAGE_NAME = "@christang/keel"
57
+
58
+
59
+ TARGET_SKILL_ROOTS = {
60
+ "claude": Path(".claude") / "skills",
61
+ "codex": Path(".agents") / "skills",
62
+ "opencode": Path(".opencode") / "skills",
63
+ }
64
+
65
+
66
+ def has_managed_block(path: Path) -> bool:
67
+ if not path.is_file():
68
+ return False
69
+ return extract_managed_block(path.read_text(encoding="utf-8")) is not None
70
+
71
+
72
+ def run_install(repo: Path, *args: str) -> subprocess.CompletedProcess[str]:
73
+ return subprocess.run(
74
+ [
75
+ sys.executable,
76
+ str(ROOT / "scripts" / "install_to_repo.py"),
77
+ str(repo),
78
+ *args,
79
+ ],
80
+ cwd=ROOT,
81
+ text=True,
82
+ encoding="utf-8",
83
+ errors="replace",
84
+ capture_output=True,
85
+ check=False,
86
+ )
87
+
88
+
89
+ def create_skill_portability_fixture(root: Path) -> None:
90
+ write_text(
91
+ root / "src/skills/keel-example/SKILL.md",
92
+ "---\n"
93
+ "name: keel-example\n"
94
+ "description: >\n"
95
+ " Validate portable skills. Use when testing skill packaging.\n"
96
+ "---\n\n"
97
+ "# Keel Example\n",
98
+ )
99
+ source = (root / "src/skills/keel-example/SKILL.md").read_text(encoding="utf-8")
100
+ write_text(root / "plugins/keel/skills/keel-example/SKILL.md", source)
101
+
102
+
103
+ def validate_skill_portability_policy_scenario() -> int:
104
+ repository_errors: list[str] = []
105
+ validate_skill_portability(ROOT, repository_errors)
106
+ if repository_errors:
107
+ report("skill-portability-policy rejected the repository baseline:")
108
+ for error in repository_errors:
109
+ report(f"- {error}")
110
+ return 1
111
+
112
+ policy_errors: list[str] = []
113
+ validate_resident_blocks(policy_errors)
114
+ validate_openspec_schema(policy_errors)
115
+ validate_skill_docs(policy_errors)
116
+ for path in (ROOT / "AGENTS.md", ROOT / "README.md", ROOT / "README.zh-CN.md"):
117
+ content = path.read_text(encoding="utf-8")
118
+ for snippet in (
119
+ "authoritative source",
120
+ "positive and negative trigger cases"
121
+ if path.name == "AGENTS.md"
122
+ else "should-not-trigger",
123
+ "real-task evidence" if path.name == "AGENTS.md" else "real task",
124
+ "target-native",
125
+ ):
126
+ if snippet not in content:
127
+ policy_errors.append(f"{path.name} missing skill policy: {snippet}")
128
+ if policy_errors:
129
+ report("skill-portability-policy source policy validation failed:")
130
+ for error in policy_errors:
131
+ report(f"- {error}")
132
+ return 1
133
+
134
+ with tempfile.TemporaryDirectory() as temp_dir:
135
+ fixture = Path(temp_dir)
136
+ create_skill_portability_fixture(fixture)
137
+ fixture_errors: list[str] = []
138
+ validate_skill_portability(fixture, fixture_errors)
139
+ if fixture_errors:
140
+ report("skill-portability-policy rejected valid folded metadata.")
141
+ return 1
142
+
143
+ write_text(
144
+ fixture / "src/skills/keel-example/SKILL.md",
145
+ "---\n"
146
+ "name: Keel_Example\n"
147
+ "---\n\n"
148
+ "# Invalid metadata\n",
149
+ )
150
+ metadata_errors: list[str] = []
151
+ validate_skill_portability(fixture, metadata_errors)
152
+ if not any("canonical skill name" in error for error in metadata_errors):
153
+ report("skill-portability-policy accepted an invalid skill name.")
154
+ return 1
155
+ if not any("description" in error for error in metadata_errors):
156
+ report("skill-portability-policy accepted a missing description.")
157
+ return 1
158
+
159
+ create_skill_portability_fixture(fixture)
160
+ skill_path = fixture / "src/skills/keel-example/SKILL.md"
161
+ write_text(
162
+ skill_path,
163
+ skill_path.read_text(encoding="utf-8")
164
+ + "\nRead [the missing guide](references/missing.md).\n",
165
+ )
166
+ reference_errors: list[str] = []
167
+ validate_skill_portability(fixture, reference_errors)
168
+ if not any("missing referenced resource" in error for error in reference_errors):
169
+ report("skill-portability-policy accepted a broken skill reference.")
170
+ return 1
171
+
172
+ create_skill_portability_fixture(fixture)
173
+ write_text(
174
+ fixture / "plugins/keel/skills/keel-example/SKILL.md",
175
+ "# Divergent plugin projection\n",
176
+ )
177
+ projection_errors: list[str] = []
178
+ validate_skill_portability(fixture, projection_errors)
179
+ if not any(
180
+ "projection differs from canonical source" in error
181
+ for error in projection_errors
182
+ ):
183
+ report("skill-portability-policy accepted a divergent plugin projection.")
184
+ return 1
185
+
186
+ report("skill-portability-policy scenario passed.")
187
+ return 0
188
+
189
+
190
+ def posix_paths(text: str) -> str:
191
+ """Fold path separators so an assertion does not encode the host's spelling.
192
+
193
+ Keel prints these paths through the host's path joiner, so the same doctor
194
+ line reads `.claude\\commands\\opsx` on Windows and `.claude/commands/opsx`
195
+ on a POSIX runner. Assertions state the forward-slash form and normalize the
196
+ captured output, rather than branching on the platform or accepting both.
197
+ """
198
+ return (text or "").replace("\\", "/")
199
+
200
+
201
+ def validate_target_surface_scenario() -> int:
202
+ with tempfile.TemporaryDirectory(prefix="keel-surface-") as raw_tmp:
203
+ tmp = Path(raw_tmp)
204
+
205
+ claude_repo = tmp / "claude"
206
+ claude_repo.mkdir()
207
+ claude_init = run_keel(claude_repo, "--init", "--target", "claude")
208
+ if claude_init.returncode != 0:
209
+ report("target-surface scenario Claude init failed:")
210
+ report((claude_init.stderr or claude_init.stdout).strip())
211
+ return 1
212
+ claude_doctor = run_keel(claude_repo, "--doctor", "--target", "claude")
213
+ if (
214
+ claude_doctor.returncode != 0
215
+ or "Target surface:" not in claude_doctor.stdout
216
+ or "OpenSpec commands: ok" not in claude_doctor.stdout
217
+ or "skills only" not in claude_doctor.stdout
218
+ or "OpenSpec action skills: ok" not in claude_doctor.stdout
219
+ or ".claude/skills" not in posix_paths(claude_doctor.stdout)
220
+ or "bootstrap: ok" not in claude_doctor.stdout
221
+ or "CLAUDE import: ok" not in claude_doctor.stdout
222
+ or "native plugin runtime: manual" not in claude_doctor.stdout
223
+ or "Target capabilities (claude):" not in claude_doctor.stdout
224
+ or "gate.change-close: manual" not in claude_doctor.stdout
225
+ or "execution.worktree: manual" not in claude_doctor.stdout
226
+ ):
227
+ report("target-surface scenario Claude doctor did not report full surface.")
228
+ report((claude_doctor.stderr or claude_doctor.stdout).strip())
229
+ return 1
230
+
231
+ codex_repo = tmp / "codex"
232
+ codex_repo.mkdir()
233
+ codex_home = tmp / "codex-home"
234
+ env = os.environ.copy()
235
+ env["CODEX_HOME"] = str(codex_home)
236
+ codex_init = run_keel(codex_repo, "--init", "--target", "codex", env=env)
237
+ if codex_init.returncode != 0:
238
+ report("target-surface scenario Codex init failed:")
239
+ report((codex_init.stderr or codex_init.stdout).strip())
240
+ return 1
241
+ codex_doctor = run_keel(codex_repo, "--doctor", "--target", "codex", env=env)
242
+ if (
243
+ codex_doctor.returncode != 0
244
+ or "OpenSpec commands: ok" not in codex_doctor.stdout
245
+ or "OpenSpec 1.13 and later surface Codex's workflows" not in codex_doctor.stdout
246
+ or "OpenSpec action skills: ok" not in codex_doctor.stdout
247
+ or ".agents/skills" not in posix_paths(codex_doctor.stdout)
248
+ or "bootstrap: ok" not in codex_doctor.stdout
249
+ or "native plugin runtime: manual" not in codex_doctor.stdout
250
+ or "Target capabilities (codex):" not in codex_doctor.stdout
251
+ or "gate.change-close: manual" not in codex_doctor.stdout
252
+ or "execution.worktree: manual" not in codex_doctor.stdout
253
+ ):
254
+ report("target-surface scenario Codex doctor did not report full surface.")
255
+ report((codex_doctor.stderr or codex_doctor.stdout).strip())
256
+ return 1
257
+ if (codex_repo / ".claude").exists():
258
+ report("target-surface scenario Codex init created Claude-only paths.")
259
+ return 1
260
+
261
+ # OpenSpec 1.13 writes Codex's workflows as skills only (#169), so the
262
+ # surface that can go missing is a skill.
263
+ shutil.rmtree(codex_repo / ".agents/skills/openspec-propose")
264
+ codex_missing = run_keel(codex_repo, "--doctor", "--target", "codex", env=env)
265
+ if (
266
+ codex_missing.returncode != 0
267
+ or "OpenSpec action skills: missing" not in codex_missing.stdout
268
+ ):
269
+ report("target-surface scenario Codex doctor did not report a missing skill.")
270
+ report((codex_missing.stderr or codex_missing.stdout).strip())
271
+ return 1
272
+
273
+ opencode_repo = tmp / "opencode"
274
+ opencode_repo.mkdir()
275
+ opencode_init = run_keel(opencode_repo, "--init", "--target", "opencode")
276
+ if opencode_init.returncode != 0:
277
+ report("target-surface scenario OpenCode init failed:")
278
+ report((opencode_init.stderr or opencode_init.stdout).strip())
279
+ return 1
280
+ opencode_doctor = run_keel(opencode_repo, "--doctor", "--target", "opencode")
281
+ if (
282
+ opencode_doctor.returncode != 0
283
+ or "OpenSpec commands: ok" not in opencode_doctor.stdout
284
+ or "skills only" not in opencode_doctor.stdout
285
+ or "OpenSpec action skills: ok" not in opencode_doctor.stdout
286
+ or ".opencode/skills" not in posix_paths(opencode_doctor.stdout)
287
+ or "bootstrap: ok" not in opencode_doctor.stdout
288
+ or "native plugin: manual" not in opencode_doctor.stdout
289
+ or "Target capabilities (opencode):" not in opencode_doctor.stdout
290
+ or "gate.change-close: manual" not in opencode_doctor.stdout
291
+ ):
292
+ report("target-surface scenario OpenCode doctor did not report full surface.")
293
+ report((opencode_doctor.stderr or opencode_doctor.stdout).strip())
294
+ return 1
295
+ if (opencode_repo / ".claude").exists():
296
+ report("target-surface scenario OpenCode init created Claude-only paths.")
297
+ return 1
298
+
299
+ report("target-surface scenario passed.")
300
+ return 0
301
+
302
+
303
+ def validate_domain_lenses_scenario() -> int:
304
+ plugin_skills_root = ROOT / PLUGIN_ROOT / "skills"
305
+ if not (plugin_skills_root / "keel-align-expectations/SKILL.md").is_file():
306
+ report("domain-lenses scenario plugin misses the alignment skill")
307
+ return 1
308
+ lenses_root = ROOT / "assets/lenses"
309
+ for template in ("web.md", "hardware.md", "hardware-dsl.md"):
310
+ if not (lenses_root / template).is_file():
311
+ report(
312
+ "domain-lenses scenario misses the shipped lens template: "
313
+ f"{template}"
314
+ )
315
+ return 1
316
+ for legacy_skill in LEGACY_PROFILE_SKILLS:
317
+ if (plugin_skills_root / legacy_skill).exists():
318
+ report(
319
+ f"domain-lenses scenario plugin packages a legacy profile: {legacy_skill}"
320
+ )
321
+ return 1
322
+
323
+ with tempfile.TemporaryDirectory(prefix="keel-profiles-") as raw_tmp:
324
+ tmp = Path(raw_tmp)
325
+ repo = tmp / "default"
326
+ repo.mkdir()
327
+ install = run_keel(repo, "--install", "--target", "codex")
328
+ if install.returncode != 0:
329
+ report("domain-lenses scenario default install failed:")
330
+ report((install.stderr or install.stdout).strip())
331
+ return 1
332
+ if (repo / TARGET_SKILL_ROOTS["codex"]).exists():
333
+ report(
334
+ "domain-lenses scenario thin install copied Keel skill trees; "
335
+ "skills are plugin-owned in v4."
336
+ )
337
+ return 1
338
+
339
+ rejected = run_keel(repo, "--install", "--target", "codex", "--profile", "web")
340
+ rejected_text = (rejected.stderr or "") + (rejected.stdout or "")
341
+ if rejected.returncode == 0 or "keel/lenses" not in rejected_text:
342
+ report("domain-lenses scenario still accepts --profile.")
343
+ report(rejected_text.strip())
344
+ return 1
345
+
346
+ doctor = run_keel(repo, "--doctor", "--target", "codex")
347
+ doctor_text = (doctor.stderr or "") + (doctor.stdout or "")
348
+ if (
349
+ doctor.returncode != 0
350
+ or "native plugin runtime: manual" not in doctor_text
351
+ or "Keel profiles" in doctor_text
352
+ ):
353
+ report(
354
+ "domain-lenses scenario doctor still reports profile state or "
355
+ "misses the native plugin surface."
356
+ )
357
+ report(doctor_text.strip())
358
+ return 1
359
+
360
+ uninstall = run_keel(repo, "--uninstall", "--target", "codex")
361
+ agents_text = (
362
+ (repo / "AGENTS.md").read_text(encoding="utf-8")
363
+ if (repo / "AGENTS.md").exists()
364
+ else ""
365
+ )
366
+ if uninstall.returncode != 0 or "keel:start" in agents_text:
367
+ report("domain-lenses scenario uninstall left the managed bootstrap.")
368
+ report((uninstall.stderr or uninstall.stdout).strip())
369
+ return 1
370
+
371
+ report("domain-lenses scenario passed.")
372
+ return 0
373
+
374
+
375
+ def openspec_overlay_files(
376
+ repo: Path,
377
+ target: str,
378
+ codex_home: Path | None = None,
379
+ ) -> dict[str, list[Path]]:
380
+ # Keel generates skills only (#406); a command file counts only while a
381
+ # repository still holds one from an earlier `both` delivery.
382
+ def held(*paths: Path) -> list[Path]:
383
+ return [paths[0], *[p for p in paths[1:] if p.exists()]]
384
+
385
+ if target == "claude":
386
+ return {
387
+ "apply": held(
388
+ repo / ".claude/skills/openspec-apply-change/SKILL.md",
389
+ repo / ".claude/commands/opsx/apply.md",
390
+ ),
391
+ "archive": held(
392
+ repo / ".claude/skills/openspec-archive-change/SKILL.md",
393
+ repo / ".claude/commands/opsx/archive.md",
394
+ ),
395
+ }
396
+ if target == "codex":
397
+ assert codex_home is not None
398
+ # OpenSpec 1.13 and later, including the 1.14 Keel pins, write Codex's workflows as skills
399
+ # under `.agents/skills` and no command files (#169).
400
+ return {
401
+ "apply": [repo / ".agents/skills/openspec-apply-change/SKILL.md"],
402
+ "archive": [repo / ".agents/skills/openspec-archive-change/SKILL.md"],
403
+ }
404
+ return {
405
+ "apply": held(
406
+ repo / ".opencode/skills/openspec-apply-change/SKILL.md",
407
+ repo / ".opencode/commands/opsx-apply.md",
408
+ ),
409
+ "archive": held(
410
+ repo / ".opencode/skills/openspec-archive-change/SKILL.md",
411
+ repo / ".opencode/commands/opsx-archive.md",
412
+ ),
413
+ }
414
+
415
+
416
+ def strip_openspec_surface_overlay(content: str) -> str:
417
+ return re.sub(
418
+ r"<!--\s*keel:openspec-surface-overlay(?:\s+[^>]*)?\s*-->"
419
+ r".*?"
420
+ r"<!--\s*keel:openspec-surface-overlay:end\s*-->\s*",
421
+ "",
422
+ content,
423
+ flags=re.DOTALL,
424
+ )
425
+
426
+
427
+ def assert_openspec_overlay(path: Path, action: str) -> str | None:
428
+ if not path.is_file():
429
+ return f"missing overlay target: {path}"
430
+ content = path.read_text(encoding="utf-8")
431
+ if content.count(OPENSPEC_SURFACE_OVERLAY_START) != 1:
432
+ return f"{path} must contain exactly one current Keel overlay start marker"
433
+ if content.count(OPENSPEC_SURFACE_OVERLAY_END) != 1:
434
+ return f"{path} must contain exactly one Keel overlay end marker"
435
+
436
+ # Since #414 the overlay says one neutral thing about subagents and assigns
437
+ # no ownership; apply continues through an approved task list.
438
+ required = [
439
+ "Keel rules below take precedence",
440
+ "A subagent is the model's choice and is treated as the main agent is",
441
+ ]
442
+ if action == "apply":
443
+ required.extend(
444
+ [
445
+ "approved `tasks.md` in order",
446
+ "Task Authoring Gate",
447
+ "Slice Start Gate",
448
+ "source expectations",
449
+ "Rough future slices",
450
+ # A confirmation the owner already declared is routed to the
451
+ # declaration; one they did not declare is still asked for, and
452
+ # neither case touches the proof.
453
+ "standing-authorized action proceeds without",
454
+ "undeclared action still requires",
455
+ "never substitutes for a gate",
456
+ ]
457
+ )
458
+ else:
459
+ required.extend(
460
+ [
461
+ "keel gate change-close --action archive",
462
+ "keel-review-checklist",
463
+ "critical expectation",
464
+ "behavior evidence",
465
+ "durable follow-up owner",
466
+ "explicit discard reason",
467
+ "standing-authorizes `archive`",
468
+ "completion gate and follow-up ownership checks still run",
469
+ ]
470
+ )
471
+ for snippet in required:
472
+ if snippet not in content:
473
+ return f"{path} overlay missing required text: {snippet}"
474
+ return None
475
+
476
+
477
+ def assert_target_overlays(
478
+ repo: Path,
479
+ target: str,
480
+ codex_home: Path | None = None,
481
+ ) -> str | None:
482
+ for action, paths in openspec_overlay_files(repo, target, codex_home).items():
483
+ for path in paths:
484
+ error = assert_openspec_overlay(path, action)
485
+ if error:
486
+ return error
487
+ return None
488
+
489
+
490
+ OVERLAY_ACTION_SKILLS = {
491
+ "propose": "openspec-propose",
492
+ "apply": "openspec-apply-change",
493
+ "archive": "openspec-archive-change",
494
+ "sync": "openspec-sync-specs",
495
+ }
496
+
497
+
498
+ def expected_overlay_surfaces(
499
+ repo: Path,
500
+ target: str,
501
+ codex_home: Path | None = None,
502
+ ) -> list[Path]:
503
+ """Every surface `openspecOverlaySurfacesForTarget` projects the overlay onto.
504
+
505
+ Written out rather than discovered, so that a scan of the tree can be
506
+ compared against it. A scan alone answers "the files that carry the
507
+ marker", which is the same answer whether the CLI covered eight surfaces
508
+ or none — and "none of them still carry it" is exactly what a broken
509
+ surface list also reports.
510
+ """
511
+ surfaces: list[Path] = []
512
+ for action, skill in OVERLAY_ACTION_SKILLS.items():
513
+ if action == "propose" and target == "opencode":
514
+ continue
515
+ # Keel generates skills only (#406); a command file counts only while a
516
+ # repository still holds one from an earlier `both` delivery.
517
+ if target == "claude":
518
+ surfaces.append(repo / f".claude/skills/{skill}/SKILL.md")
519
+ command = repo / f".claude/commands/opsx/{action}.md"
520
+ elif target == "codex":
521
+ assert codex_home is not None
522
+ surfaces.append(repo / f".agents/skills/{skill}/SKILL.md")
523
+ command = None
524
+ else:
525
+ surfaces.append(repo / f".opencode/skills/{skill}/SKILL.md")
526
+ command = repo / f".opencode/commands/opsx-{action}.md"
527
+ if command is not None and command.exists():
528
+ surfaces.append(command)
529
+ return surfaces
530
+
531
+
532
+ def files_carrying_overlay(*roots: Path) -> set[Path]:
533
+ found: set[Path] = set()
534
+ for root in roots:
535
+ if not root.is_dir():
536
+ continue
537
+ for path in root.rglob("*.md"):
538
+ if not path.is_file():
539
+ continue
540
+ text = path.read_text(encoding="utf-8", errors="replace")
541
+ if "keel:openspec-surface-overlay" in text:
542
+ found.add(path)
543
+ return found
544
+
545
+
546
+ def validate_uninstall_removes_the_overlay_scenario() -> int:
547
+ """Uninstalling left Keel's instructions in files OpenSpec owns.
548
+
549
+ The overlay block is written into the `opsx` command surfaces and the
550
+ `openspec-*` skills, and every line of it is about Keel: the gate to run,
551
+ the checklist to run, how to invoke OpenSpec, where standing authorization
552
+ is declared. `keel --uninstall` removed the `keel:start` managed block from
553
+ AGENTS.md and CLAUDE.md and left all of that behind.
554
+
555
+ Measured 2026-08-03 at 5.22.0: Claude 8 of 8 surfaces, Codex 8 of 8 (four
556
+ of them under `CODEX_HOME/prompts/`), OpenCode 6 of 6 still carried the
557
+ marker after uninstall. Filed as
558
+ https://github.com/TanglmChris/keel/issues/50.
559
+ """
560
+ label = "uninstall-removes-the-overlay"
561
+ with tempfile.TemporaryDirectory(prefix="keel-uninstall-overlay-") as raw:
562
+ tmp = Path(raw)
563
+
564
+ for target in ("claude", "codex", "opencode"):
565
+ repo = tmp / target
566
+ repo.mkdir()
567
+ env = None
568
+ codex_home = None
569
+ roots = [repo]
570
+ if target == "codex":
571
+ codex_home = tmp / "codex-home"
572
+ env = os.environ.copy()
573
+ env["CODEX_HOME"] = str(codex_home)
574
+ roots.append(codex_home)
575
+
576
+ init = run_keel(repo, "--init", "--target", target, env=env)
577
+ if init.returncode != 0:
578
+ report(f"{label} `keel --init --target {target}` failed.")
579
+ report((init.stderr or init.stdout).strip())
580
+ return 1
581
+
582
+ # M1 positive control — the surfaces the CLI writes to are the ones
583
+ # this scenario is about to check, asserted before the act. Without
584
+ # it, a run whose surface list resolved to nothing reports the same
585
+ # clean tree as a run that removed everything.
586
+ expected = set(expected_overlay_surfaces(repo, target, codex_home))
587
+ carrying = files_carrying_overlay(*roots)
588
+ if carrying != expected:
589
+ report(
590
+ f"{label} M1 the {target} surfaces carrying the overlay "
591
+ "after init are not the ones this scenario expects, so "
592
+ "nothing after this measures removal."
593
+ )
594
+ report(f" only installed: {sorted(str(p) for p in carrying - expected)}")
595
+ report(f" only expected: {sorted(str(p) for p in expected - carrying)}")
596
+ return 1
597
+
598
+ # M2 — what the file held before Keel's block, kept so the whole
599
+ # file can be compared against it afterwards. Trailing newlines are
600
+ # normalized to one because the separator the install side inserted
601
+ # before the block goes with the block.
602
+ bodies = {}
603
+ for surface in expected:
604
+ text = surface.read_text(encoding="utf-8")
605
+ head = text[: text.index("<!-- keel:openspec-surface-overlay")]
606
+ bodies[surface] = head.rstrip("\n") + "\n"
607
+
608
+ uninstall = run_keel(repo, "--uninstall", "--target", target, env=env)
609
+ if uninstall.returncode != 0:
610
+ report(f"{label} M1 `keel --uninstall --target {target}` failed.")
611
+ report((uninstall.stderr or uninstall.stdout).strip())
612
+ return 1
613
+
614
+ # M1 — nothing Keel wrote is left in a file OpenSpec owns.
615
+ left = files_carrying_overlay(*roots)
616
+ if left:
617
+ report(
618
+ f"{label} M1 uninstalling {target} left the Keel overlay "
619
+ f"in {len(left)} of {len(expected)} surfaces, so the "
620
+ "uninstalled repository still instructs an agent to run "
621
+ "commands that were just removed."
622
+ )
623
+ for path in sorted(str(p) for p in left):
624
+ report(f" {path}")
625
+ return 1
626
+
627
+ # M4 — the run says how many surfaces it cleaned. An uninstall that
628
+ # silently does nothing and an uninstall that cleaned everything
629
+ # produce the same tree on a repository that was never installed.
630
+ if f"removed={len(expected)}" not in uninstall.stdout:
631
+ report(
632
+ f"{label} M4 uninstalling {target} did not report the "
633
+ f"{len(expected)} overlays it removed."
634
+ )
635
+ report((uninstall.stderr or uninstall.stdout).strip())
636
+ return 1
637
+
638
+ # M2 — the block, and only the block. The file is OpenSpec's, so a
639
+ # removal that took the marker and anything either side of it is a
640
+ # worse defect than the one being fixed, and "the marker is gone"
641
+ # cannot tell the two apart.
642
+ for surface, body in bodies.items():
643
+ if not surface.is_file():
644
+ report(
645
+ f"{label} M2 uninstalling {target} deleted {surface}, "
646
+ "which is OpenSpec's file. Removing Keel's block is "
647
+ "the whole obligation."
648
+ )
649
+ return 1
650
+ after = surface.read_text(encoding="utf-8")
651
+ if after != body:
652
+ report(
653
+ f"{label} M2 uninstalling {target} did not leave "
654
+ f"{surface} at the bytes that preceded the overlay."
655
+ )
656
+ report(f" expected {len(body)} bytes ending {body[-40:]!r}")
657
+ report(f" found {len(after)} bytes ending {after[-40:]!r}")
658
+ return 1
659
+
660
+ # M3 — a dry run plans the writes it would make. `--check` already had
661
+ # to learn that a Node-side step the installer's plan cannot see makes
662
+ # a dry run under-report a run that writes; the uninstall side has the
663
+ # same shape.
664
+ dry = tmp / "dry-run"
665
+ dry.mkdir()
666
+ dry_init = run_keel(dry, "--init", "--target", "claude")
667
+ if dry_init.returncode != 0:
668
+ report(f"{label} M3 dry-run fixture init failed.")
669
+ report((dry_init.stderr or dry_init.stdout).strip())
670
+ return 1
671
+ dry_expected = set(expected_overlay_surfaces(dry, "claude"))
672
+ dry_run = run_keel(dry, "--uninstall", "--target", "claude", "--dry-run")
673
+ if dry_run.returncode != 0:
674
+ report(f"{label} M3 `keel --uninstall --dry-run` failed.")
675
+ report((dry_run.stderr or dry_run.stdout).strip())
676
+ return 1
677
+ unplanned = [
678
+ str(surface)
679
+ for surface in sorted(dry_expected)
680
+ if str(surface) not in dry_run.stdout
681
+ ]
682
+ if unplanned:
683
+ report(
684
+ f"{label} M3 the dry run did not name {len(unplanned)} of "
685
+ f"{len(dry_expected)} surfaces it would clean, so the plan "
686
+ "under-reports a run that writes."
687
+ )
688
+ for surface in unplanned:
689
+ report(f" {surface}")
690
+ return 1
691
+ if files_carrying_overlay(dry) != dry_expected:
692
+ report(
693
+ f"{label} M3 the dry run removed overlays. A dry run reports "
694
+ "what it would do and writes nothing."
695
+ )
696
+ return 1
697
+
698
+ # M4 — uninstalling again, and uninstalling a repository that never
699
+ # received the overlay, both succeed. Uninstall is something a user
700
+ # reaches for when something is already wrong; failing on the second
701
+ # attempt is the worst moment to fail.
702
+ again = run_keel(tmp / "claude", "--uninstall", "--target", "claude")
703
+ if again.returncode != 0:
704
+ report(
705
+ f"{label} M4 a second uninstall failed. Uninstall is reached "
706
+ "when something is already wrong; failing on the second "
707
+ "attempt is the worst moment to fail."
708
+ )
709
+ report((again.stderr or again.stdout).strip())
710
+ return 1
711
+ if "removed=0" not in again.stdout:
712
+ report(
713
+ f"{label} M4 a second uninstall did not report that it removed "
714
+ "nothing, so a run that cleaned nothing reads like a run that "
715
+ "cleaned everything."
716
+ )
717
+ report((again.stderr or again.stdout).strip())
718
+ return 1
719
+
720
+ bare = tmp / "install-only"
721
+ bare.mkdir()
722
+ bare_install = run_keel(bare, "--install", "--target", "claude")
723
+ if bare_install.returncode != 0:
724
+ report(f"{label} M4 install-only fixture failed.")
725
+ report((bare_install.stderr or bare_install.stdout).strip())
726
+ return 1
727
+ bare_uninstall = run_keel(bare, "--uninstall", "--target", "claude")
728
+ if bare_uninstall.returncode != 0:
729
+ report(
730
+ f"{label} M4 uninstalling a repository whose OpenSpec surfaces "
731
+ "were never created failed. An absent surface is nothing to "
732
+ "remove, not an error."
733
+ )
734
+ report((bare_uninstall.stderr or bare_uninstall.stdout).strip())
735
+ return 1
736
+
737
+ if label not in {name for name, _ in registry.SCENARIOS}:
738
+ report(f"{label}: the scenario registry does not include it.")
739
+ return 1
740
+ report(f"{label} scenario passed.")
741
+ return 0
742
+
743
+
744
+ def validate_sync_surface_overlay_scenario() -> int:
745
+ """The surface that performs a gated action never named its gate.
746
+
747
+ AGENTS.md gates sync and archive identically — `keel gate change-close
748
+ --action sync|archive` plus `keel-review-checklist`. Archive's command
749
+ surface carries a Keel overlay saying so; sync's carried none, because
750
+ `OPENSPEC_OVERLAY_ACTIONS` listed only propose, apply, and archive. An
751
+ agent invoking `/opsx:sync` read generic upstream instructions and was told
752
+ nothing about the gate that decides whether the sync may complete.
753
+
754
+ Measured 2026-08-02: neither `.claude/commands/opsx/sync.md` nor
755
+ `.claude/skills/openspec-sync-specs/SKILL.md` contained `change-close`,
756
+ `keel gate`, or `keel openspec`.
757
+ """
758
+ label = "sync-surface-overlay"
759
+ marker = "keel:openspec-surface-overlay"
760
+ with tempfile.TemporaryDirectory(prefix="keel-sync-overlay-") as raw:
761
+ tmp = Path(raw)
762
+
763
+ surfaces = {
764
+ # Skills only since #406: Keel generates no `.claude/commands/opsx/`.
765
+ "claude": [
766
+ ".claude/skills/openspec-sync-specs/SKILL.md",
767
+ ],
768
+ "codex": [
769
+ ".agents/skills/openspec-sync-specs/SKILL.md",
770
+ ],
771
+ }
772
+
773
+ for target, paths in surfaces.items():
774
+ repo = tmp / target
775
+ repo.mkdir()
776
+ init = run_keel(repo, "--init", "--target", target)
777
+ if init.returncode != 0:
778
+ report(f"{label} M1 `keel --init --target {target}` failed.")
779
+ report((init.stderr or init.stdout).strip())
780
+ return 1
781
+
782
+ # M1 — the marker lands on every sync surface the target has.
783
+ for relative in paths:
784
+ surface = repo / relative
785
+ if not surface.is_file():
786
+ report(
787
+ f"{label} M1 {target} has no sync surface at "
788
+ f"{relative}, so the projection has nothing to cover."
789
+ )
790
+ return 1
791
+ text = surface.read_text(encoding="utf-8")
792
+ if marker not in text:
793
+ report(
794
+ f"{label} M1 {relative} carries no Keel overlay, so the "
795
+ "surface that performs a gated action never names its "
796
+ "gate."
797
+ )
798
+ return 1
799
+
800
+ # M2 — and it says the things that change behavior.
801
+ for needle, why in (
802
+ ("keel gate change-close --action sync", "the gate"),
803
+ ("keel-review-checklist", "the semantic review"),
804
+ ("keel openspec", "how to invoke OpenSpec off PATH"),
805
+ ("--skip-specs", "that a following archive must skip specs"),
806
+ ):
807
+ if needle not in text:
808
+ report(
809
+ f"{label} M2 the sync overlay in {relative} does "
810
+ f"not name {why} ({needle!r})."
811
+ )
812
+ return 1
813
+
814
+ # M4 — explore stays uncovered, deliberately.
815
+ explore = repo / (
816
+ ".claude/skills/openspec-explore/SKILL.md" if target == "claude"
817
+ else ".agents/skills/openspec-explore/SKILL.md"
818
+ )
819
+ if explore.is_file() and marker in explore.read_text(encoding="utf-8"):
820
+ report(
821
+ f"{label} M4 the explore surface received an overlay. It "
822
+ "reaches no gate and changes no state, so an overlay there "
823
+ "reads as governance where there is none."
824
+ )
825
+ return 1
826
+
827
+ # M3 — the doctor names sync rather than a hardcoded pair.
828
+ doctor = run_keel(repo, "--doctor", "--target", target)
829
+ overlay_lines = [
830
+ line for line in doctor.stdout.splitlines()
831
+ if "overlay" in line and line.startswith("Keel ")
832
+ ]
833
+ if not overlay_lines:
834
+ report(f"{label} M3 {target} `keel --doctor` printed no overlay line.")
835
+ report((doctor.stderr or doctor.stdout).strip())
836
+ return 1
837
+ if not any("sync" in line for line in overlay_lines):
838
+ report(
839
+ f"{label} M3 the {target} doctor overlay line does not name "
840
+ f"sync: {overlay_lines}"
841
+ )
842
+ return 1
843
+ if not any(": ok" in line for line in overlay_lines):
844
+ report(
845
+ f"{label} M3 the {target} doctor did not report the overlay "
846
+ f"healthy after a fresh install: {overlay_lines}"
847
+ )
848
+ return 1
849
+
850
+ # Uninstall is asserted by `uninstall-removes-the-overlay`, which
851
+ # covers every surface on every target rather than sync alone. It
852
+ # stripped nothing from any surface when this scenario was written;
853
+ # that was #50, and the assertion lives there because the contract
854
+ # is about all four actions, not about this one.
855
+
856
+ # M4 — covering the surface did not widen what may be standing-authorized.
857
+ config_doc = (ROOT / "keel/config.yaml").read_text(encoding="utf-8")
858
+ if re.search(r"^\s*-\s*sync\s*$", config_doc, re.MULTILINE):
859
+ report(
860
+ f"{label} M4 `sync` was added to the standing-authorization "
861
+ "vocabulary. Naming the gate that governs an action and deciding "
862
+ "whether a repository may authorize it once are separate."
863
+ )
864
+ return 1
865
+
866
+ if label not in {name for name, _ in registry.SCENARIOS}:
867
+ report(f"{label}: the scenario registry does not include it.")
868
+ return 1
869
+ report(f"{label} scenario passed.")
870
+ return 0
871
+
872
+
873
+ def overlay_action_label(text: str, pattern: str) -> str | None:
874
+ """The action list a summary line names, or None when the line is absent.
875
+
876
+ `\\S*` rather than `\\S+` on purpose: a label that derived to nothing leaves
877
+ two spaces where the actions belong, and matching it is what lets an empty
878
+ label be reported as empty instead of as a missing line.
879
+ """
880
+ match = re.search(pattern, text)
881
+ if match is None:
882
+ return None
883
+ return match.group(1)
884
+
885
+
886
+ def validate_update_restores_overlays_scenario() -> int:
887
+ label = "update-restores-overlays:"
888
+ with tempfile.TemporaryDirectory(prefix="keel-update-overlays-") as raw:
889
+ tmp = Path(raw)
890
+ repo = tmp / "mixed"
891
+ repo.mkdir()
892
+ env = os.environ.copy()
893
+ env["CODEX_HOME"] = str(tmp / "codex-home")
894
+ for target in ("claude", "codex"):
895
+ result = run_keel(repo, "--init", "--target", target, env=env)
896
+ if result.returncode:
897
+ report(f"{label} init {target} failed: {result.stderr or result.stdout}")
898
+ return 1
899
+ # Diagnose a missing foreign target before the upstream rewrite.
900
+ codex_paths = [p for paths in openspec_overlay_files(
901
+ repo, "codex", tmp / "codex-home").values() for p in paths]
902
+ for p in codex_paths:
903
+ if p.exists():
904
+ p.write_text(strip_openspec_surface_overlay(p.read_text()), encoding="utf-8")
905
+ doctor = run_keel(repo, "--doctor", "--target", "claude", env=env)
906
+ if not re.search(r"Codex.*overlay: (missing|partial)", doctor.stdout):
907
+ report(f"{label} doctor hid missing Codex overlays while selecting Claude")
908
+ return 1
909
+ for iteration in range(2):
910
+ result = run_keel(repo, "openspec", "update", env=env)
911
+ if result.returncode:
912
+ report(f"{label} update failed: {result.stderr or result.stdout}")
913
+ return 1
914
+ for target in ("claude", "codex"):
915
+ error = assert_target_overlays(repo, target, tmp / "codex-home")
916
+ if error:
917
+ report(f"{label} update {iteration}: {error}")
918
+ return 1
919
+ for action, skill in OVERLAY_ACTION_SKILLS.items():
920
+ surface = repo / (".claude/skills" if target == "claude" else ".agents/skills") / skill / "SKILL.md"
921
+ content = surface.read_text()
922
+ if content.count(OPENSPEC_SURFACE_OVERLAY_START) != 1 or content.count(OPENSPEC_SURFACE_OVERLAY_END) != 1:
923
+ report(f"{label} managed action has missing or duplicate overlays: {surface}")
924
+ return 1
925
+ if not strip_openspec_surface_overlay(content).strip():
926
+ report(f"{label} upstream body removed: {surface}")
927
+ return 1
928
+ legacy = tmp / "legacy"
929
+ legacy.mkdir()
930
+ result = run_keel(legacy, "--init", "--target", "claude", env=env)
931
+ if result.returncode:
932
+ report(f"{label} legacy fixture init failed")
933
+ return 1
934
+ for skill in OVERLAY_ACTION_SKILLS.values():
935
+ write_text(legacy / ".codex/skills" / skill / "SKILL.md", "# Legacy OpenSpec workflow\n")
936
+ doctor = run_keel(legacy, "--doctor", "--target", "claude", env=env)
937
+ if not re.search(r"Codex.*overlay: (missing|partial)", doctor.stdout):
938
+ report(f"{label} legacy Codex coverage was hidden")
939
+ return 1
940
+ # A single-target repository must stay isolated, even with global prompts.
941
+ single = tmp / "single"
942
+ single.mkdir()
943
+ result = run_keel(single, "--init", "--target", "claude", env=env)
944
+ if result.returncode:
945
+ report(f"{label} single init failed")
946
+ return 1
947
+ result = run_keel(single, "openspec", "update", env=env)
948
+ if result.returncode or (single / ".agents/skills").exists() or (single / ".codex/skills").exists():
949
+ report(f"{label} single-target update failed or created Codex surfaces")
950
+ return 1
951
+ doctor = run_keel(single, "--doctor", "--target", "claude", env=env)
952
+ if re.search(r"Codex.*overlay:", doctor.stdout):
953
+ report(f"{label} global prompts enrolled an unrelated repository")
954
+ return 1
955
+ # Invalid options fail in real upstream OpenSpec; no recovery may write.
956
+ surface = repo / ".agents/skills/openspec-apply-change/SKILL.md"
957
+ surface.write_text(strip_openspec_surface_overlay(surface.read_text()), encoding="utf-8")
958
+ files = {p: p.read_bytes() for p in repo.rglob("*.md")}
959
+ upstream = subprocess.run(
960
+ ["node", str(ROOT / "node_modules/.bin/openspec"), "update", "--keel-invalid-option"],
961
+ cwd=repo, env=env, capture_output=True, text=True, check=False)
962
+ failed = run_keel(repo, "openspec", "update", "--keel-invalid-option", env=env)
963
+ if not failed.returncode or failed.returncode != upstream.returncode or any(p.read_bytes() != b for p, b in files.items()):
964
+ report(f"{label} failed update was masked or changed surfaces")
965
+ return 1
966
+ report("update-restores-overlays scenario passed.")
967
+ return 0
968
+
969
+
970
+ def validate_openspec_skills_only_scenario() -> int:
971
+ """Issue #406: one copy of each OpenSpec workflow, whatever the global delivery.
972
+
973
+ OpenSpec reads `delivery` only from the user's global configuration, which
974
+ defaults to `both` and put every workflow on Claude twice — a skill and an
975
+ `/opsx:` command. Keel runs OpenSpec with that configuration's `delivery`
976
+ replaced by `skills`, and never writes the file itself.
977
+ """
978
+ label = "openspec-skills-only:"
979
+ with tempfile.TemporaryDirectory(prefix="keel-406-") as raw_tmp:
980
+ tmp = Path(raw_tmp)
981
+ config = tmp / "xdg/openspec/config.json"
982
+ write_text(config, json.dumps({
983
+ "featureFlags": {}, "profile": "custom", "delivery": "both",
984
+ "workflows": ["propose", "explore", "apply", "sync", "archive"],
985
+ }, indent=2) + "\n")
986
+ before = config.read_bytes()
987
+ env = dict(os.environ)
988
+ env["XDG_CONFIG_HOME"] = str(tmp / "xdg")
989
+ stray = ".claude/commands/opsx/apply.md"
990
+ upstream = "---\nname: OPSX: Apply\n---\n\nImplement tasks.\n"
991
+
992
+ def keel(repo: Path, *args: str):
993
+ result = run_keel(repo, *args, env=env)
994
+ if result.returncode != 0:
995
+ report(f"{label} `keel {' '.join(args)}` failed: {(result.stderr or result.stdout).strip()}")
996
+ return result
997
+
998
+ claude = tmp / "claude"
999
+ claude.mkdir()
1000
+ if keel(claude, "--init", "--target", "claude").returncode != 0:
1001
+ return 1
1002
+ commands = sorted(p.name for p in (claude / ".claude/commands/opsx").glob("*")) \
1003
+ if (claude / ".claude/commands/opsx").is_dir() else []
1004
+ if commands:
1005
+ report(f"{label} with a global `delivery: both`, keel --init left command files: {commands!r}")
1006
+ return 1
1007
+ skills = [claude / f".claude/skills/{skill}/SKILL.md" for skill in ("openspec-propose", "openspec-explore", "openspec-apply-change",
1008
+ "openspec-sync-specs", "openspec-archive-change")]
1009
+ absent = [str(p.relative_to(claude)) for p in skills if not p.is_file()]
1010
+ if absent:
1011
+ report(f"{label} keel --init did not generate the workflow skills: {absent!r}")
1012
+ return 1
1013
+ # OpenSpec's own text only: the Keel overlay's wording is
1014
+ # guidance-names-openspec-skills's to check.
1015
+ naming = [str(p.relative_to(claude)) for p in skills
1016
+ if "/opsx:" in strip_openspec_surface_overlay(p.read_text(encoding="utf-8"))]
1017
+ if naming:
1018
+ report(f"{label} OpenSpec's generated skill text still names `/opsx:` commands: {naming!r}")
1019
+ return 1
1020
+ unmarked = [str(p.relative_to(claude)) for p in expected_overlay_surfaces(claude, "claude")
1021
+ if OPENSPEC_SURFACE_OVERLAY_START not in p.read_text(encoding="utf-8")]
1022
+ if unmarked:
1023
+ report(f"{label} managed skills lack the Keel overlay: {unmarked!r}")
1024
+ return 1
1025
+ if config.read_bytes() != before:
1026
+ report(f"{label} keel --init rewrote the global OpenSpec configuration: {config.read_text()!r}")
1027
+ return 1
1028
+
1029
+ doctor = keel(claude, "--doctor", "--target", "claude")
1030
+ commands_line = next((l for l in doctor.stdout.splitlines() if l.startswith("OpenSpec commands:")), "")
1031
+ overlay_line = next((l for l in doctor.stdout.splitlines() if l.startswith("Keel apply/archive/sync overlay:")), "")
1032
+ if not commands_line.startswith("OpenSpec commands: ok"):
1033
+ report(f"{label} doctor does not read a skills-only repository's commands as ok: {commands_line!r}")
1034
+ return 1
1035
+ if "skills only" not in commands_line:
1036
+ report(f"{label} doctor's commands line does not say the workflows are skills only: {commands_line!r}")
1037
+ return 1
1038
+ if not overlay_line.startswith("Keel apply/archive/sync overlay: ok"):
1039
+ report(f"{label} doctor does not read the skills-only overlay as ok: {overlay_line!r}")
1040
+ return 1
1041
+ if "4/4" not in overlay_line:
1042
+ report(f"{label} doctor's overlay line does not count 4/4 surfaces: {overlay_line!r}")
1043
+ return 1
1044
+
1045
+ write_text(claude / stray, upstream)
1046
+ if keel(claude, "--install", "--target", "claude").returncode != 0:
1047
+ return 1
1048
+ if OPENSPEC_SURFACE_OVERLAY_START not in (claude / stray).read_text(encoding="utf-8"):
1049
+ report(f"{label} keel --install did not overlay a command file the repository still holds.")
1050
+ return 1
1051
+ doctor = keel(claude, "--doctor", "--target", "claude")
1052
+ commands_line = next((l for l in doctor.stdout.splitlines() if l.startswith("OpenSpec commands:")), "")
1053
+ if not commands_line.startswith("OpenSpec commands: duplicate"):
1054
+ report(f"{label} doctor does not read a leftover command file as duplicate: {commands_line!r}")
1055
+ return 1
1056
+ for needle in ("1 ", ".claude/commands/opsx", "keel --init --target claude"):
1057
+ if needle not in posix_paths(commands_line):
1058
+ report(f"{label} the duplicate line does not name {needle!r}: {commands_line!r}")
1059
+ return 1
1060
+ if keel(claude, "--init", "--target", "claude").returncode != 0:
1061
+ return 1
1062
+ if (claude / stray).exists():
1063
+ report(f"{label} keel --init did not remove a command file a `both` delivery left.")
1064
+ return 1
1065
+
1066
+ passthrough = tmp / "passthrough"
1067
+ passthrough.mkdir()
1068
+ if keel(passthrough, "--init", "--target", "claude").returncode != 0:
1069
+ return 1
1070
+ write_text(passthrough / stray, upstream)
1071
+ if keel(passthrough, "openspec", "update", "--force").returncode != 0:
1072
+ return 1
1073
+ if (passthrough / stray).exists():
1074
+ report(f"{label} keel openspec update did not remove a command file a `both` delivery left.")
1075
+ return 1
1076
+
1077
+ opencode = tmp / "opencode"
1078
+ opencode.mkdir()
1079
+ if keel(opencode, "--init", "--target", "opencode").returncode != 0:
1080
+ return 1
1081
+ left = sorted(p.name for p in (opencode / ".opencode/commands").glob("opsx-*.md")) \
1082
+ if (opencode / ".opencode/commands").is_dir() else []
1083
+ if left:
1084
+ report(f"{label} keel --init --target opencode left command files: {left!r}")
1085
+ return 1
1086
+ # Any OpenSpec command — doctor runs some — records OpenSpec's own
1087
+ # telemetry notice in the file it reads; everything else must stand.
1088
+ settled = {k: v for k, v in json.loads(config.read_text()).items() if k != "telemetry"}
1089
+ if settled != json.loads(before):
1090
+ report(f"{label} a later run changed the global OpenSpec configuration: {config.read_text()!r}")
1091
+ return 1
1092
+ # Last: OpenSpec itself may record its telemetry notice in the file it reads.
1093
+ listed = keel(passthrough, "openspec", "config", "list")
1094
+ if "delivery: both" not in listed.stdout:
1095
+ report(f"{label} keel openspec config list no longer reports the user's own delivery: {listed.stdout!r}")
1096
+ return 1
1097
+
1098
+ if "openspec-skills-only" not in {name for name, _ in registry.SCENARIOS}:
1099
+ report(f"{label} scenario is not registered.")
1100
+ return 1
1101
+ report("openspec-skills-only scenario passed.")
1102
+ return 0
1103
+
1104
+
1105
+ def validate_own_surface_is_skills_only_scenario() -> int:
1106
+ """Issue #406: this repository carries the surface Keel now generates.
1107
+
1108
+ Keel's own checkout held `.claude/commands/opsx/*` beside the skills, from
1109
+ OpenSpec 1.6 under `delivery: both`.
1110
+ """
1111
+ label = "own-surface-is-skills-only:"
1112
+ commands = ROOT / ".claude/commands/opsx"
1113
+ held = sorted(p.name for p in commands.glob("*")) if commands.is_dir() else []
1114
+ if held:
1115
+ report(f"{label} this repository still holds OpenSpec command files: {held!r}")
1116
+ return 1
1117
+ naming = [str(p.relative_to(ROOT)) for p in sorted((ROOT / ".claude/skills").glob("openspec-*/SKILL.md"))
1118
+ if "/opsx:" in p.read_text(encoding="utf-8")]
1119
+ if naming:
1120
+ report(f"{label} this repository's Claude skills still name `/opsx:` commands: {naming!r}")
1121
+ return 1
1122
+ doctor = run_keel(ROOT, "--doctor", "--target", "claude")
1123
+ lines = doctor.stdout.splitlines()
1124
+ commands_line = next((l for l in lines if l.startswith("OpenSpec commands:")), "")
1125
+ overlay_line = next((l for l in lines if l.startswith("Keel apply/archive/sync overlay:")), "")
1126
+ if not commands_line.startswith("OpenSpec commands: ok"):
1127
+ report(f"{label} doctor here does not read the commands line ok: {commands_line!r}")
1128
+ return 1
1129
+ if not overlay_line.startswith("Keel apply/archive/sync overlay: ok"):
1130
+ report(f"{label} doctor here does not read the overlay line ok: {overlay_line!r}")
1131
+ return 1
1132
+ if "own-surface-is-skills-only" not in {name for name, _ in registry.SCENARIOS}:
1133
+ report(f"{label} scenario is not registered.")
1134
+ return 1
1135
+ report("own-surface-is-skills-only scenario passed.")
1136
+ return 0
1137
+
1138
+
1139
+ def validate_openspec_surface_overlay_scenario() -> int:
1140
+ with tempfile.TemporaryDirectory(prefix="keel-overlay-") as raw_tmp:
1141
+ tmp = Path(raw_tmp)
1142
+
1143
+ claude_repo = tmp / "claude"
1144
+ claude_repo.mkdir()
1145
+ claude_init = run_keel(claude_repo, "--init", "--target", "claude")
1146
+ if claude_init.returncode != 0:
1147
+ report("openspec-surface-overlay scenario Claude init failed:")
1148
+ report((claude_init.stderr or claude_init.stdout).strip())
1149
+ return 1
1150
+ error = assert_target_overlays(claude_repo, "claude")
1151
+ if error:
1152
+ report(f"openspec-surface-overlay scenario Claude overlay failed: {error}")
1153
+ return 1
1154
+ claude_doctor = run_keel(claude_repo, "--doctor", "--target", "claude")
1155
+ if (
1156
+ claude_doctor.returncode != 0
1157
+ or "Keel apply/archive/sync overlay: ok" not in claude_doctor.stdout
1158
+ ):
1159
+ report("openspec-surface-overlay scenario Claude doctor missed overlay health.")
1160
+ report((claude_doctor.stderr or claude_doctor.stdout).strip())
1161
+ return 1
1162
+
1163
+ # Every direction that reports the overlay names the actions it covers,
1164
+ # and all of them describe one surface list. They are compared against
1165
+ # each other rather than against a literal repeated here: the doctor
1166
+ # label is already pinned above, so an action joining the managed set
1167
+ # moves all three lines together or fails on this comparison. A third
1168
+ # copy of the string is what produced the defect this guards.
1169
+ #
1170
+ # The refresh line was the copy nobody was watching. Measured 2026-08-03
1171
+ # on one repository, back to back: `--init` reported `apply/archive`
1172
+ # while `--uninstall` reported `apply/archive/sync` (issue #75).
1173
+ #
1174
+ # Absence is checked before agreement, and separately, because two
1175
+ # labels that were never found also agree.
1176
+ claude_uninstall = run_keel(claude_repo, "--uninstall", "--target", "claude")
1177
+ if claude_uninstall.returncode != 0:
1178
+ report("openspec-surface-overlay scenario Claude uninstall failed:")
1179
+ report((claude_uninstall.stderr or claude_uninstall.stdout).strip())
1180
+ return 1
1181
+ summaries = {
1182
+ "refresh": overlay_action_label(
1183
+ claude_init.stdout, r"OpenSpec (\S*) overlay refreshed="
1184
+ ),
1185
+ "doctor": overlay_action_label(
1186
+ claude_doctor.stdout, r"Keel (\S*) overlay:"
1187
+ ),
1188
+ "removal": overlay_action_label(
1189
+ claude_uninstall.stdout, r"OpenSpec (\S*) overlay removed="
1190
+ ),
1191
+ }
1192
+ for direction, printed in summaries.items():
1193
+ if printed is None:
1194
+ report(
1195
+ f"openspec-surface-overlay scenario found no {direction} "
1196
+ "overlay summary at all, so there was no label to compare "
1197
+ "rather than a label that disagreed."
1198
+ )
1199
+ return 1
1200
+ if not printed:
1201
+ report(
1202
+ f"openspec-surface-overlay scenario read an empty action "
1203
+ f"label from the {direction} summary; a label that derives "
1204
+ "to nothing reports no actions at all."
1205
+ )
1206
+ return 1
1207
+ for direction in ("refresh", "removal"):
1208
+ if summaries[direction] != summaries["doctor"]:
1209
+ report(
1210
+ "openspec-surface-overlay scenario overlay summaries "
1211
+ f"disagree: {direction} names {summaries[direction]!r} and "
1212
+ f"doctor names {summaries['doctor']!r}. They describe the "
1213
+ "same managed surface list, so one of them is written "
1214
+ "beside the action set instead of derived from it."
1215
+ )
1216
+ return 1
1217
+
1218
+ codex_repo = tmp / "codex"
1219
+ codex_repo.mkdir()
1220
+ codex_home = tmp / "codex-home"
1221
+ codex_env = os.environ.copy()
1222
+ codex_env["CODEX_HOME"] = str(codex_home)
1223
+ codex_init = run_keel(codex_repo, "--init", "--target", "codex", env=codex_env)
1224
+ if codex_init.returncode != 0:
1225
+ report("openspec-surface-overlay scenario Codex init failed:")
1226
+ report((codex_init.stderr or codex_init.stdout).strip())
1227
+ return 1
1228
+ error = assert_target_overlays(codex_repo, "codex", codex_home)
1229
+ if error:
1230
+ report(f"openspec-surface-overlay scenario Codex overlay failed: {error}")
1231
+ return 1
1232
+ codex_doctor = run_keel(codex_repo, "--doctor", "--target", "codex", env=codex_env)
1233
+ if (
1234
+ codex_doctor.returncode != 0
1235
+ or "Keel apply/archive/sync overlay: ok" not in codex_doctor.stdout
1236
+ ):
1237
+ report("openspec-surface-overlay scenario Codex doctor missed overlay health.")
1238
+ report((codex_doctor.stderr or codex_doctor.stdout).strip())
1239
+ return 1
1240
+
1241
+ codex_apply_prompt = codex_repo / ".agents/skills/openspec-apply-change/SKILL.md"
1242
+ original_prompt = codex_apply_prompt.read_text(encoding="utf-8")
1243
+ outdated_prompt = re.sub(
1244
+ r"<!--\s*keel:openspec-surface-overlay(?:\s+[^>]*)?\s*-->"
1245
+ r".*?"
1246
+ r"<!--\s*keel:openspec-surface-overlay:end\s*-->",
1247
+ "<!-- keel:openspec-surface-overlay version=0.0.0 -->\n"
1248
+ "old overlay\n"
1249
+ "<!-- keel:openspec-surface-overlay:end -->",
1250
+ original_prompt,
1251
+ flags=re.DOTALL,
1252
+ )
1253
+ write_text(codex_apply_prompt, outdated_prompt)
1254
+ codex_install = run_keel(codex_repo, "--install", "--target", "codex", env=codex_env)
1255
+ if codex_install.returncode != 0:
1256
+ report("openspec-surface-overlay scenario Codex install failed:")
1257
+ report((codex_install.stderr or codex_install.stdout).strip())
1258
+ return 1
1259
+ refreshed_prompt = codex_apply_prompt.read_text(encoding="utf-8")
1260
+ if (
1261
+ refreshed_prompt.count(OPENSPEC_SURFACE_OVERLAY_START) != 1
1262
+ or "old overlay" in refreshed_prompt
1263
+ or strip_openspec_surface_overlay(refreshed_prompt).strip() == ""
1264
+ ):
1265
+ report("openspec-surface-overlay scenario Codex install did not refresh overlay idempotently.")
1266
+ return 1
1267
+
1268
+ # M6 — a repository set up under OpenSpec 1.6 keeps its layout: skills
1269
+ # under `.codex/skills` and commands as CODEX_HOME prompts (#169).
1270
+ legacy_repo = tmp / "codex-legacy"
1271
+ legacy_home = tmp / "codex-legacy-home"
1272
+ legacy_env = os.environ.copy()
1273
+ legacy_env["CODEX_HOME"] = str(legacy_home)
1274
+ legacy_surfaces = []
1275
+ for action, skill in OVERLAY_ACTION_SKILLS.items():
1276
+ for surface in (
1277
+ legacy_repo / f".codex/skills/{skill}/SKILL.md",
1278
+ legacy_home / f"prompts/opsx-{action}.md",
1279
+ ):
1280
+ write_text(surface, f"---\nname: {skill}\n---\n\n# {action}\n")
1281
+ legacy_surfaces.append(surface)
1282
+ run_keel(legacy_repo, "--install", "--target", "codex", env=legacy_env)
1283
+ lost = [
1284
+ str(surface)
1285
+ for surface in legacy_surfaces
1286
+ if surface.read_text(encoding="utf-8").count(OPENSPEC_SURFACE_OVERLAY_START) != 1
1287
+ ]
1288
+ if lost:
1289
+ report(
1290
+ "openspec-surface-overlay scenario 1.6-layout Codex surfaces lost "
1291
+ f"their overlay: {lost!r}"
1292
+ )
1293
+ return 1
1294
+
1295
+ opencode_repo = tmp / "opencode"
1296
+ opencode_repo.mkdir()
1297
+ opencode_init = run_keel(opencode_repo, "--init", "--target", "opencode")
1298
+ if opencode_init.returncode != 0:
1299
+ report("openspec-surface-overlay scenario OpenCode init failed:")
1300
+ report((opencode_init.stderr or opencode_init.stdout).strip())
1301
+ return 1
1302
+ error = assert_target_overlays(opencode_repo, "opencode")
1303
+ if error:
1304
+ report(f"openspec-surface-overlay scenario OpenCode overlay failed: {error}")
1305
+ return 1
1306
+
1307
+ # The skill, since Keel generates no command file (#406).
1308
+ opencode_apply_skill = opencode_repo / ".opencode/skills/openspec-apply-change/SKILL.md"
1309
+ write_text(
1310
+ opencode_apply_skill,
1311
+ strip_openspec_surface_overlay(
1312
+ opencode_apply_skill.read_text(encoding="utf-8")
1313
+ ),
1314
+ )
1315
+ opencode_missing_doctor = run_keel(
1316
+ opencode_repo,
1317
+ "--doctor",
1318
+ "--target",
1319
+ "opencode",
1320
+ )
1321
+ if (
1322
+ opencode_missing_doctor.returncode != 0
1323
+ or "Keel apply/archive/sync overlay: missing" not in opencode_missing_doctor.stdout
1324
+ or "keel --install --target opencode" not in opencode_missing_doctor.stdout
1325
+ ):
1326
+ report("openspec-surface-overlay scenario doctor did not report a missing overlay marker.")
1327
+ report((opencode_missing_doctor.stderr or opencode_missing_doctor.stdout).strip())
1328
+ return 1
1329
+
1330
+ install_only_repo = tmp / "install-only"
1331
+ install_only_repo.mkdir()
1332
+ install_only = run_keel(install_only_repo, "--install", "--target", "opencode")
1333
+ if install_only.returncode != 0:
1334
+ report("openspec-surface-overlay scenario install-only target failed:")
1335
+ report((install_only.stderr or install_only.stdout).strip())
1336
+ return 1
1337
+ if (install_only_repo / ".opencode/commands/opsx-apply.md").exists():
1338
+ report("openspec-surface-overlay scenario install created placeholder OpenSpec command.")
1339
+ return 1
1340
+ install_only_doctor = run_keel(
1341
+ install_only_repo,
1342
+ "--doctor",
1343
+ "--target",
1344
+ "opencode",
1345
+ )
1346
+ if (
1347
+ install_only_doctor.returncode != 0
1348
+ or "Keel apply/archive/sync overlay: missing" not in install_only_doctor.stdout
1349
+ or "keel --init --target opencode" not in install_only_doctor.stdout
1350
+ ):
1351
+ report("openspec-surface-overlay scenario install-only doctor missed remediation.")
1352
+ report((install_only_doctor.stderr or install_only_doctor.stdout).strip())
1353
+ return 1
1354
+
1355
+ report("openspec-surface-overlay scenario passed.")
1356
+ return 0
1357
+
1358
+
1359
+ def validate_uninstall_scenario() -> int:
1360
+ with tempfile.TemporaryDirectory(prefix="keel-uninstall-") as raw_tmp:
1361
+ repo = Path(raw_tmp) / "repo"
1362
+ repo.mkdir()
1363
+
1364
+ install = run_install(repo)
1365
+ if install.returncode != 0:
1366
+ report("uninstall scenario could not install fixture repo.")
1367
+ report((install.stderr or install.stdout).strip())
1368
+ return 1
1369
+
1370
+ claude_block = extract_managed_block((repo / "CLAUDE.md").read_text(encoding="utf-8"))
1371
+ handoff_content = "# HANDOFF\nlegacy user content\n"
1372
+ if claude_block is None:
1373
+ report("uninstall scenario fixture is missing root managed blocks.")
1374
+ return 1
1375
+
1376
+ write_text(repo / "CLAUDE.md", f"claude before\n{claude_block}\nclaude after\n")
1377
+ write_text(repo / "keel/TASK.md", "active task must remain\n")
1378
+ write_text(repo / "keel/HANDOFF.md", handoff_content)
1379
+ write_text(repo / "keel/templates/TASK.lite.md", "user edited lite template\n")
1380
+ write_text(repo / "openspec/changes/real-change/proposal.md", "real change\n")
1381
+ write_text(repo / "openspec/specs/real-spec.md", "real spec\n")
1382
+ before_dry_run = snapshot_files(repo)
1383
+ dry_run = run_install(repo, "--uninstall", "--dry-run")
1384
+ after_dry_run = snapshot_files(repo)
1385
+ if dry_run.returncode != 0:
1386
+ report("uninstall scenario dry run failed:")
1387
+ report((dry_run.stderr or dry_run.stdout).strip())
1388
+ return 1
1389
+
1390
+ for expected in (
1391
+ "remove-managed CLAUDE.md",
1392
+ "remove-managed AGENTS.md",
1393
+ f"rmdir {OPENSPEC_SCHEMA_ROOT.as_posix()}",
1394
+ ):
1395
+ if expected not in dry_run.stdout:
1396
+ report(f"uninstall scenario missing dry-run action: {expected}")
1397
+ report(dry_run.stdout.strip())
1398
+ return 1
1399
+ for schema_file in packaged_openspec_schema_install_paths():
1400
+ if f"remove {schema_file}" not in dry_run.stdout:
1401
+ report(f"uninstall scenario missing schema removal: {schema_file}")
1402
+ report(dry_run.stdout.strip())
1403
+ return 1
1404
+ if "remove keel/templates/TASK.lite.md" in dry_run.stdout:
1405
+ report("uninstall scenario planned to remove a user-edited template.")
1406
+ return 1
1407
+ if "remove keel/templates/TASK.full.md" in dry_run.stdout:
1408
+ report("uninstall scenario planned to remove a legacy Full TASK template.")
1409
+ return 1
1410
+ if "remove openspec/config.yaml" in dry_run.stdout:
1411
+ report("uninstall scenario planned to remove OpenSpec config.")
1412
+ return 1
1413
+ if before_dry_run != after_dry_run:
1414
+ report("uninstall scenario dry run modified the repo.")
1415
+ return 1
1416
+
1417
+ uninstall = run_install(repo, "--uninstall")
1418
+ if uninstall.returncode != 0:
1419
+ report("uninstall scenario failed:")
1420
+ report((uninstall.stderr or uninstall.stdout).strip())
1421
+ return 1
1422
+
1423
+ if extract_managed_block((repo / "CLAUDE.md").read_text(encoding="utf-8")):
1424
+ report("uninstall scenario left CLAUDE.md managed block behind.")
1425
+ return 1
1426
+ if (repo / "CLAUDE.md").read_text(encoding="utf-8") != "claude before\n\nclaude after\n":
1427
+ report("uninstall scenario did not preserve CLAUDE.md user content.")
1428
+ return 1
1429
+ if not (repo / "keel/TASK.md").is_file():
1430
+ report("uninstall scenario deleted active TASK.md.")
1431
+ return 1
1432
+ if (repo / "keel/HANDOFF.md").read_text(encoding="utf-8") != handoff_content:
1433
+ report("uninstall scenario changed user-edited HANDOFF.md.")
1434
+ return 1
1435
+ if not (repo / "keel/templates/TASK.lite.md").is_file():
1436
+ report("uninstall scenario deleted user-edited Lite TASK template.")
1437
+ return 1
1438
+ if (repo / ".claude/skills/keel-handoff/SKILL.md").exists():
1439
+ report("uninstall scenario did not remove packaged Claude skill.")
1440
+ return 1
1441
+ if (repo / ".claude/skills/keel-review-checklist/SKILL.md").exists():
1442
+ report("uninstall scenario did not remove packaged Claude review skill.")
1443
+ return 1
1444
+ if not (repo / OPENSPEC_CONFIG_PATH).is_file():
1445
+ report("uninstall scenario deleted OpenSpec config.")
1446
+ return 1
1447
+ for schema_file in packaged_openspec_schema_install_paths():
1448
+ if (repo / schema_file).exists():
1449
+ report(f"uninstall scenario did not remove packaged OpenSpec schema: {schema_file}")
1450
+ return 1
1451
+ if (repo / OPENSPEC_SCHEMA_ROOT).exists():
1452
+ report("uninstall scenario left empty OpenSpec schema directory behind.")
1453
+ return 1
1454
+ for removed_dir in (
1455
+ ".claude",
1456
+ ):
1457
+ if (repo / removed_dir).exists():
1458
+ report(f"uninstall scenario left empty directory behind: {removed_dir}")
1459
+ return 1
1460
+ for required in (
1461
+ "openspec/changes/real-change/proposal.md",
1462
+ "openspec/specs/real-spec.md",
1463
+ ):
1464
+ if not (repo / required).is_file():
1465
+ report(f"uninstall scenario deleted real OpenSpec content: {required}")
1466
+ return 1
1467
+
1468
+ report("uninstall scenario passed.")
1469
+ return 0
1470
+
1471
+
1472
+ def validate_cli_scenario() -> int:
1473
+ help_result = run_keel(ROOT, "--help")
1474
+ if help_result.returncode != 0 or "Usage:" not in help_result.stdout:
1475
+ report("cli scenario expected keel --help to print usage.")
1476
+ report((help_result.stderr or help_result.stdout).strip())
1477
+ return 1
1478
+
1479
+ usage_block = help_result.stdout.split("Usage:", 1)[1].split("\n\n", 1)[0]
1480
+ triage_lines = [line for line in usage_block.splitlines() if "keel triage" in line]
1481
+ if not triage_lines:
1482
+ report("cli scenario expected keel --help Usage: block to list a `keel triage` line.")
1483
+ report(usage_block.strip())
1484
+ return 1
1485
+ if "--labels" not in triage_lines[0]:
1486
+ report("cli scenario expected the keel --help `keel triage` line to name --labels.")
1487
+ report(triage_lines[0].strip())
1488
+ return 1
1489
+ if "--issue" not in triage_lines[0]:
1490
+ report("cli scenario expected the keel --help `keel triage` line to name --issue.")
1491
+ report(triage_lines[0].strip())
1492
+ return 1
1493
+
1494
+ version_result = run_keel(ROOT, "--version")
1495
+ expected_version = f"keel {PACKAGE_VERSION}"
1496
+ if version_result.returncode != 0 or version_result.stdout.strip() != expected_version:
1497
+ report(f"cli scenario expected keel --version to print {expected_version}.")
1498
+ report((version_result.stderr or version_result.stdout).strip())
1499
+ return 1
1500
+
1501
+ with tempfile.TemporaryDirectory(prefix="keel-cli-") as raw_tmp:
1502
+ tmp = Path(raw_tmp)
1503
+ repo = tmp / "repo"
1504
+ repo.mkdir()
1505
+
1506
+ before_check = snapshot_files(repo)
1507
+ check_missing = run_keel(repo, "--check")
1508
+ after_check = snapshot_files(repo)
1509
+ if check_missing.returncode != 0:
1510
+ report("cli scenario keel --check failed on missing repo.")
1511
+ report((check_missing.stderr or check_missing.stdout).strip())
1512
+ return 1
1513
+ for expected in ("status: missing", "Dry-run install plan:", "create CLAUDE.md"):
1514
+ if expected not in check_missing.stdout:
1515
+ report(f"cli scenario keel --check missing output: {expected}")
1516
+ report(check_missing.stdout.strip())
1517
+ return 1
1518
+ if before_check != after_check:
1519
+ report("cli scenario keel --check modified the repo.")
1520
+ return 1
1521
+
1522
+ install = run_keel(repo, "--install")
1523
+ if install.returncode != 0:
1524
+ report("cli scenario keel --install failed.")
1525
+ report((install.stderr or install.stdout).strip())
1526
+ return 1
1527
+ for expected_file in (
1528
+ "CLAUDE.md",
1529
+ "AGENTS.md",
1530
+ OPENSPEC_CONFIG_PATH.as_posix(),
1531
+ *packaged_openspec_schema_install_paths(),
1532
+ ):
1533
+ if not (repo / expected_file).is_file():
1534
+ report(f"cli scenario keel --install missed file: {expected_file}")
1535
+ return 1
1536
+ if "@AGENTS.md" not in (repo / "CLAUDE.md").read_text(encoding="utf-8"):
1537
+ report("cli scenario keel --install missed CLAUDE.md @AGENTS.md import.")
1538
+ return 1
1539
+ if not has_managed_block(repo / "AGENTS.md"):
1540
+ report("cli scenario keel --install missed AGENTS.md bootstrap block.")
1541
+ return 1
1542
+
1543
+ check_installed = run_keel(repo, "--check")
1544
+ if check_installed.returncode != 0 or "status: installed" not in check_installed.stdout:
1545
+ report("cli scenario keel --check did not report installed.")
1546
+ report((check_installed.stderr or check_installed.stdout).strip())
1547
+ return 1
1548
+
1549
+ doctor = run_keel(repo, "--doctor")
1550
+ if (
1551
+ doctor.returncode != 0
1552
+ or "keel doctor" not in doctor.stdout
1553
+ or "openspec:" not in doctor.stdout
1554
+ ):
1555
+ report("cli scenario keel --doctor did not report environment status.")
1556
+ report((doctor.stderr or doctor.stdout).strip())
1557
+ return 1
1558
+
1559
+ write_text(
1560
+ repo / "openspec/changes/status-drift/tasks.md",
1561
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
1562
+ "## Tasks\n\n"
1563
+ "- [x] A1 implementation **未提交**\n\n"
1564
+ "## Execution Status\n\n"
1565
+ "- 合入 master(a4ca804).\n\n"
1566
+ "## Current Completion\n\n"
1567
+ "- 1 / 1.\n",
1568
+ )
1569
+ tasks_drift_check = run_keel(repo, "--check")
1570
+ if (
1571
+ tasks_drift_check.returncode == 0
1572
+ or "keel state: failed" not in tasks_drift_check.stdout
1573
+ or "Execution Status" not in tasks_drift_check.stdout
1574
+ or "Current Completion" not in tasks_drift_check.stdout
1575
+ or "commit or merge state" not in tasks_drift_check.stdout
1576
+ or "contextual commit hash" not in tasks_drift_check.stdout
1577
+ ):
1578
+ report("cli scenario keel --check did not fail on tasks.md commit-status drift.")
1579
+ report((tasks_drift_check.stderr or tasks_drift_check.stdout).strip())
1580
+ return 1
1581
+
1582
+ write_text(
1583
+ repo / "openspec/changes/status-drift/tasks.md",
1584
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
1585
+ "> Boundary: tasks.md is the source for the current change's slice checklist and logical completion only. Completion state is only `[x]` / `[ ]`; progress and the default next slice are derived from the checklist. Do not record commit hashes, branch/merge state, dirty/uncommitted state, or manually computed completion counts. Durable work state belongs in OpenSpec; HANDOFF is only an explicit pointer override.\n\n"
1586
+ "## Tasks\n\n"
1587
+ "- [x] A1 implementation\n\n"
1588
+ "## Workflow Notes\n\n"
1589
+ "- None.\n",
1590
+ )
1591
+ tasks_clean_check = run_keel(repo, "--check")
1592
+ if (
1593
+ tasks_clean_check.returncode != 0
1594
+ or "keel state: ok" not in tasks_clean_check.stdout
1595
+ ):
1596
+ report("cli scenario keel --check did not accept cleaned tasks.md.")
1597
+ report((tasks_clean_check.stderr or tasks_clean_check.stdout).strip())
1598
+ return 1
1599
+
1600
+ write_text(
1601
+ repo / "openspec/changes/archive/2026-07-09-finished/tasks.md",
1602
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
1603
+ "- [x] A1 implementation\n\n"
1604
+ "## Evidence\n\n"
1605
+ "- Scope check: pre-existing dirty paths were not attributed to this task.\n",
1606
+ )
1607
+ archived_tasks_check = run_keel(repo, "--check")
1608
+ if (
1609
+ archived_tasks_check.returncode != 0
1610
+ or "keel state: ok" not in archived_tasks_check.stdout
1611
+ ):
1612
+ report("cli scenario keel --check rejected historical evidence in archived tasks.md.")
1613
+ report((archived_tasks_check.stderr or archived_tasks_check.stdout).strip())
1614
+ return 1
1615
+
1616
+ legacy_handoff = "# HANDOFF\n\nactive-backlog: FU-25 (head=R3-A2)\n"
1617
+ write_text(
1618
+ repo / "keel/HANDOFF.md",
1619
+ legacy_handoff,
1620
+ )
1621
+ drift_check = run_keel(repo, "--check")
1622
+ if (
1623
+ drift_check.returncode != 0
1624
+ or "handoff: legacy" not in drift_check.stdout
1625
+ or (repo / "keel/HANDOFF.md").read_text(encoding="utf-8")
1626
+ != legacy_handoff
1627
+ ):
1628
+ report("cli scenario keel --check did not preserve and diagnose legacy HANDOFF.")
1629
+ report((drift_check.stderr or drift_check.stdout).strip())
1630
+ return 1
1631
+
1632
+ update = run_keel(repo, "--update", "--dry-run")
1633
+ pack_plan = (
1634
+ "would run npm pack" in update.stdout
1635
+ or "would run npm.cmd pack" in update.stdout
1636
+ )
1637
+ install_plan = (
1638
+ 'would run npm install -g "<packed-tarball>"' in update.stdout
1639
+ or 'would run npm.cmd install -g "<packed-tarball>"' in update.stdout
1640
+ )
1641
+ if (
1642
+ update.returncode != 0
1643
+ or not pack_plan
1644
+ or "@christang/keel" not in update.stdout
1645
+ or not install_plan
1646
+ ):
1647
+ report("cli scenario keel --update did not report global CLI update plan.")
1648
+ report((update.stderr or update.stdout).strip())
1649
+ return 1
1650
+
1651
+ codex_repo = tmp / "codex-repo"
1652
+ codex_repo.mkdir()
1653
+ codex_install = run_keel(codex_repo, "--install", "--target", "codex")
1654
+ if codex_install.returncode != 0:
1655
+ report("cli scenario keel --install --target codex failed.")
1656
+ report((codex_install.stderr or codex_install.stdout).strip())
1657
+ return 1
1658
+ if not (codex_repo / "AGENTS.md").is_file():
1659
+ report("cli scenario codex install missed AGENTS.md.")
1660
+ return 1
1661
+ if not has_managed_block(codex_repo / "AGENTS.md"):
1662
+ report("cli scenario codex install missed AGENTS.md bootstrap block.")
1663
+ return 1
1664
+ if (codex_repo / ".claude").exists():
1665
+ report("cli scenario codex install created Claude-only paths.")
1666
+ return 1
1667
+
1668
+ opencode_repo = tmp / "opencode-repo"
1669
+ opencode_repo.mkdir()
1670
+ opencode_install = run_keel(opencode_repo, "--install", "--target", "opencode")
1671
+ if opencode_install.returncode != 0:
1672
+ report("cli scenario keel --install --target opencode failed.")
1673
+ report((opencode_install.stderr or opencode_install.stdout).strip())
1674
+ return 1
1675
+ if not (opencode_repo / "AGENTS.md").is_file():
1676
+ report("cli scenario opencode install missed AGENTS.md.")
1677
+ return 1
1678
+ if not has_managed_block(opencode_repo / "AGENTS.md"):
1679
+ report("cli scenario opencode install missed AGENTS.md bootstrap block.")
1680
+ return 1
1681
+
1682
+ codex_init_plan = run_keel(codex_repo, "--init", "--target", "codex", "--dry-run")
1683
+ if (
1684
+ codex_init_plan.returncode != 0
1685
+ or "--tools codex" not in codex_init_plan.stdout
1686
+ ):
1687
+ report("cli scenario codex init dry-run did not plan OpenSpec codex init.")
1688
+ report((codex_init_plan.stderr or codex_init_plan.stdout).strip())
1689
+ return 1
1690
+
1691
+ before_uninstall_dry_run = snapshot_files(repo)
1692
+ uninstall_dry_run = run_keel(repo, "--uninstall", "--dry-run")
1693
+ after_uninstall_dry_run = snapshot_files(repo)
1694
+ if uninstall_dry_run.returncode != 0:
1695
+ report("cli scenario keel --uninstall --dry-run failed.")
1696
+ report((uninstall_dry_run.stderr or uninstall_dry_run.stdout).strip())
1697
+ return 1
1698
+ if "remove-managed CLAUDE.md" not in uninstall_dry_run.stdout:
1699
+ report("cli scenario uninstall dry run did not report managed removal.")
1700
+ report(uninstall_dry_run.stdout.strip())
1701
+ return 1
1702
+ if before_uninstall_dry_run != after_uninstall_dry_run:
1703
+ report("cli scenario uninstall dry run modified the repo.")
1704
+ return 1
1705
+
1706
+ uninstall = run_keel(repo, "--uninstall")
1707
+ if uninstall.returncode != 0:
1708
+ report("cli scenario keel --uninstall failed.")
1709
+ report((uninstall.stderr or uninstall.stdout).strip())
1710
+ return 1
1711
+ if extract_managed_block((repo / "CLAUDE.md").read_text(encoding="utf-8")):
1712
+ report("cli scenario uninstall left CLAUDE.md managed block behind.")
1713
+ return 1
1714
+ if (repo / "keel/HANDOFF.md").read_text(encoding="utf-8") != legacy_handoff:
1715
+ report("cli scenario uninstall changed legacy HANDOFF.md.")
1716
+ return 1
1717
+
1718
+ init = run_keel(repo, "--init")
1719
+ if init.returncode != 0:
1720
+ report("cli scenario keel --init failed.")
1721
+ report((init.stderr or init.stdout).strip())
1722
+ return 1
1723
+ if not has_managed_block(repo / "AGENTS.md"):
1724
+ report("cli scenario keel --init missed AGENTS.md bootstrap block.")
1725
+ return 1
1726
+ if "@AGENTS.md" not in (repo / "CLAUDE.md").read_text(encoding="utf-8"):
1727
+ report("cli scenario keel --init missed CLAUDE.md @AGENTS.md import.")
1728
+ return 1
1729
+
1730
+ clear = run_keel(repo, "--clear")
1731
+ if clear.returncode != 0:
1732
+ report("cli scenario keel --clear failed.")
1733
+ report((clear.stderr or clear.stdout).strip())
1734
+ return 1
1735
+ remaining_schema = [
1736
+ p
1737
+ for p in packaged_openspec_schema_install_paths()
1738
+ if (repo / p).exists()
1739
+ ]
1740
+ if remaining_schema:
1741
+ report("cli scenario keel --clear left packaged schema behind.")
1742
+ report(", ".join(remaining_schema))
1743
+ return 1
1744
+
1745
+ report("cli scenario passed.")
1746
+ return 0
1747
+
1748
+
1749
+ def validate_dry_run_overlay_accounting_scenario() -> int:
1750
+ label = "dry-run-overlay-accounting"
1751
+
1752
+ # A dry run is relied on, so it is wrong in both directions: naming a write
1753
+ # that will not happen trains the reader to ignore it, and omitting one
1754
+ # breaks the promise the dry run exists to make. `--check` used to omit the
1755
+ # overlay step entirely while `--install --dry-run` claimed every surface.
1756
+ def overlay_lines(text: str) -> list[str]:
1757
+ return [line for line in text.splitlines() if "overlay" in line]
1758
+
1759
+ def counts(text: str) -> str | None:
1760
+ found = re.search(r"refreshed=(\d+) current=(\d+) missing=(\d+)", text)
1761
+ return found.group(0) if found else None
1762
+
1763
+ with tempfile.TemporaryDirectory(prefix="keel-dry-run-overlay-") as raw_tmp:
1764
+ repo = Path(raw_tmp) / "repo"
1765
+ repo.mkdir()
1766
+ # The overlay surfaces are files OpenSpec generates; install merges into
1767
+ # them and skips the ones that are absent. Create them so this scenario
1768
+ # exercises the classification rather than the missing branch.
1769
+ for relative in (
1770
+ ".claude/skills/openspec-propose/SKILL.md",
1771
+ ".claude/skills/openspec-apply-change/SKILL.md",
1772
+ ".claude/skills/openspec-archive-change/SKILL.md",
1773
+ ".claude/commands/opsx/propose.md",
1774
+ ".claude/commands/opsx/apply.md",
1775
+ ".claude/commands/opsx/archive.md",
1776
+ ):
1777
+ write_text(repo / relative, "# OpenSpec surface\n\nGenerated body.\n")
1778
+ if run_keel(repo, "--install", "--target", "claude").returncode != 0:
1779
+ report(f"{label} could not install a fixture repository.")
1780
+ return 1
1781
+
1782
+ # Nothing stale: neither dry run may name a file.
1783
+ check = run_keel(repo, "--check", "--target", "claude")
1784
+ if any("would refresh OpenSpec" in line and ".md" in line
1785
+ for line in overlay_lines(check.stdout)):
1786
+ report(f"{label} named a surface that would not change.")
1787
+ report("\n".join(overlay_lines(check.stdout)))
1788
+ return 1
1789
+
1790
+ # Make exactly one surface stale and require both dry runs to say so.
1791
+ stale = repo / ".claude/skills/openspec-apply-change/SKILL.md"
1792
+ if not stale.is_file():
1793
+ report(f"{label} fixture has no overlay surface to make stale.")
1794
+ return 1
1795
+ original = stale.read_text(encoding="utf-8")
1796
+ stale.write_text(
1797
+ re.sub(r"(keel:openspec-surface-overlay version=)[0-9.]+", r"\g<1>0.0.1",
1798
+ original, count=1),
1799
+ encoding="utf-8",
1800
+ )
1801
+
1802
+ check = run_keel(repo, "--check", "--target", "claude")
1803
+ dry = run_keel(repo, "--install", "--dry-run", "--target", "claude")
1804
+ named = [line for line in overlay_lines(check.stdout) if ".md" in line]
1805
+ if len(named) != 1 or "openspec-apply-change" not in named[0]:
1806
+ report(f"{label} --check did not name exactly the one stale surface.")
1807
+ report("\n".join(overlay_lines(check.stdout)) or "(no overlay output)")
1808
+ return 1
1809
+ if counts(check.stdout) != counts(dry.stdout):
1810
+ report(f"{label} the two dry-run entry points disagree.")
1811
+ report(f"--check: {counts(check.stdout)} --install --dry-run: {counts(dry.stdout)}")
1812
+ return 1
1813
+ if "0.0.1" not in stale.read_text(encoding="utf-8"):
1814
+ report(f"{label} a dry run wrote to the surface it was describing.")
1815
+ return 1
1816
+
1817
+ # And the real run reports what the dry run promised.
1818
+ real = run_keel(repo, "--install", "--target", "claude")
1819
+ if counts(real.stdout) != counts(check.stdout):
1820
+ report(f"{label} the real run's counts differ from the plan's.")
1821
+ report(f"plan: {counts(check.stdout)} real: {counts(real.stdout)}")
1822
+ return 1
1823
+ if "0.0.1" in stale.read_text(encoding="utf-8"):
1824
+ report(f"{label} the real run did not refresh the stale surface.")
1825
+ return 1
1826
+
1827
+ report(f"{label} scenario passed.")
1828
+ return 0
1829
+
1830
+
1831
+ def validate_a_declared_dependency_is_resolved_scenario() -> int:
1832
+ """Issue #105: the suite looked for its own dependency only on PATH.
1833
+
1834
+ `@fission-ai/openspec` is declared in `package.json` and lands at
1835
+ `node_modules/.bin/openspec`. npm scripts see that directory; a Python
1836
+ subprocess started by `node scripts/run_python.js` does not. So on a
1837
+ checkout that had only run `npm install`, `--all` reported
1838
+ `validation --all failed for: compact-task-authoring` while the schema it
1839
+ was said to be unable to resolve resolved perfectly.
1840
+
1841
+ The second half is that scenario's own condition: an unresolvable CLI and a
1842
+ CLI that ran and refused shared one message, so the reader was sent to a
1843
+ subject with nothing wrong with it.
1844
+ """
1845
+ label = "a-declared-dependency-is-resolved"
1846
+
1847
+ # `no openspec on PATH`, and nothing else removed — by file, not by
1848
+ # directory. Removing the directory would also remove `node`, and the
1849
+ # openspec shim needs it, so the scenario would be asserting that a shell
1850
+ # without an interpreter fails (issue #137).
1851
+ with path_without_openspec() as sanitized:
1852
+ without = dict(os.environ)
1853
+ without["PATH"] = sanitized
1854
+ if shutil.which("openspec", path=without["PATH"]) is not None:
1855
+ report(
1856
+ f"{label}: could not build a PATH without openspec on it, so the "
1857
+ "reproduction cannot be set up."
1858
+ )
1859
+ return 1
1860
+ # The scenario's own precondition, asserted before the behavior. A shim
1861
+ # with no interpreter exits 127, and calling that a fact about openspec
1862
+ # sends the reader to a tool with nothing wrong with it.
1863
+ if shutil.which("node", path=without["PATH"]) is None:
1864
+ return skip_scenario(
1865
+ label,
1866
+ "node does not resolve on the PATH this scenario built, so the "
1867
+ "openspec shim it resolves would have no interpreter. That is a "
1868
+ "broken fixture, not a fact about openspec.",
1869
+ )
1870
+ resolved = run_openspec(ROOT, "--version", env=without)
1871
+ if resolved is None:
1872
+ report(
1873
+ f"{label}: with no `openspec` on PATH the runner resolved "
1874
+ "nothing, but this package declares it as a dependency and "
1875
+ "installs it at node_modules/.bin. A tool the repository ships "
1876
+ "is not a tool the host has to provide."
1877
+ )
1878
+ return 1
1879
+ if resolved.returncode != 0 or not re.search(
1880
+ r"\d+\.\d+\.\d+", resolved.stdout
1881
+ ):
1882
+ report(
1883
+ f"{label}: the resolved openspec did not report a version. "
1884
+ f"exit={resolved.returncode} out={(resolved.stdout or '').strip()!r}"
1885
+ )
1886
+ return 1
1887
+
1888
+ # And it is the declared one, not whatever a host happens to carry.
1889
+ declared = ROOT / "node_modules" / ".bin" / "openspec"
1890
+ if not declared.exists():
1891
+ report(
1892
+ f"{label}: {declared} is absent, so this scenario cannot tell a "
1893
+ "resolved dependency from a lucky PATH entry. Run `npm install`."
1894
+ )
1895
+ return 3
1896
+
1897
+ # The two failures carry their own messages. Asserted on the emitted text
1898
+ # of the scenario that had them fused, not on the source.
1899
+ marker = 'label = "compact-task-authoring"'
1900
+ found = validation_source_with(marker)
1901
+ if found is None:
1902
+ report(f"{label}: compact-task-authoring is gone, so its branch cannot be read.")
1903
+ return 1
1904
+ _, fused, start = found
1905
+ body = fused[start : start + 3000]
1906
+ for needle, why in (
1907
+ ("could not be found", "the unresolvable branch must say the tool was not found"),
1908
+ ("searched", "the unresolvable branch must name where it looked"),
1909
+ ("return 3", "an unresolvable tool reports the skip contract, not a failure"),
1910
+ ):
1911
+ if needle not in body:
1912
+ report(f"{label}: {why}; `{needle}` is absent from its branch.")
1913
+ return 1
1914
+ if re.search(r"if which is None or which\.returncode", body):
1915
+ report(
1916
+ f"{label}: compact-task-authoring still guards two distinct "
1917
+ "failures behind one condition. A tool that was never found and a "
1918
+ "tool that ran and refused are different facts, and reporting the "
1919
+ "first message when the second happened names the wrong cause."
1920
+ )
1921
+ return 1
1922
+
1923
+ if label not in {name for name, _ in registry.SCENARIOS}:
1924
+ report(f"{label}: the scenario registry does not include it.")
1925
+ return 1
1926
+ report(f"{label} scenario passed.")
1927
+ return 0
1928
+
1929
+
1930
+ def validate_packaged_schema_derivation_scenario() -> int:
1931
+ label = "packaged-schema-derivation"
1932
+
1933
+ # The helper derives the consumer-repo paths every install/uninstall/clear
1934
+ # assertion iterates. When its root stopped existing it returned an empty
1935
+ # list, so those loops compared nothing and reported success. Anchor it to
1936
+ # what the installer really writes, and make emptiness a failure here.
1937
+ try:
1938
+ packaged_openspec_schema_install_paths(ROOT / "no-such-packaged-root")
1939
+ except FileNotFoundError as error:
1940
+ if "no-such-packaged-root" not in str(error):
1941
+ report(f"{label} missing-root failure does not name the path it expected.")
1942
+ report(str(error))
1943
+ return 1
1944
+ else:
1945
+ report(
1946
+ f"{label} returned a set for a missing packaged root instead of failing; "
1947
+ "an absent root must not silently empty its callers' assertions."
1948
+ )
1949
+ return 1
1950
+
1951
+ derived = packaged_openspec_schema_install_paths()
1952
+ if not derived:
1953
+ report(
1954
+ f"{label} derived no packaged schema paths, so every assertion that "
1955
+ "iterates them verifies nothing."
1956
+ )
1957
+ return 1
1958
+
1959
+ with tempfile.TemporaryDirectory(prefix="keel-packaged-schema-") as raw_tmp:
1960
+ repo = Path(raw_tmp) / "repo"
1961
+ repo.mkdir()
1962
+ install = run_keel(repo, "--install")
1963
+ if install.returncode != 0:
1964
+ report(f"{label} keel --install failed.")
1965
+ report((install.stderr or install.stdout).strip())
1966
+ return 1
1967
+
1968
+ schema_root = repo / OPENSPEC_SCHEMA_ROOT
1969
+ installed = sorted(
1970
+ path.relative_to(repo).as_posix()
1971
+ for path in schema_root.rglob("*")
1972
+ if path.is_file()
1973
+ )
1974
+ if installed != sorted(derived):
1975
+ report(
1976
+ f"{label} derived paths do not match what keel --install wrote."
1977
+ )
1978
+ report(f"derived: {sorted(derived)}")
1979
+ report(f"installed: {installed}")
1980
+ return 1
1981
+
1982
+ report(f"{label} scenario passed.")
1983
+ return 0
1984
+
1985
+
1986
+ def validate_doctor_reads_the_diagnosed_repository_scenario() -> int:
1987
+ """Issue #57: doctor named one repository and answered about another.
1988
+
1989
+ The OpenSpec declaration was read from `PACKAGE_ROOT/package-lock.json` —
1990
+ the directory Keel is installed in — while the line above it says
1991
+ `keel doctor for <repo>`. The two coincide only when `node bin/keel.js`
1992
+ runs from Keel's own checkout, which is the one arrangement every existing
1993
+ scenario uses: `run_keel` always spawns `node <ROOT>/bin/keel.js`, so
1994
+ `PACKAGE_ROOT` is Keel's checkout no matter what `cwd` is. Driving the
1995
+ diagnosis at a repository that declares its own version is what separates
1996
+ the two roots without needing a second installation.
1997
+ """
1998
+ label = "doctor-reads-the-diagnosed-repository"
1999
+
2000
+ def openspec_line(stdout: str) -> str:
2001
+ return next(
2002
+ (line for line in stdout.splitlines() if line.startswith("openspec:")),
2003
+ "",
2004
+ )
2005
+
2006
+ # M1 first half — a repository that declares a version Keel's own tree does
2007
+ # not. The sentinel is deliberately one no published OpenSpec reports, so a
2008
+ # line carrying it cannot have come from the resolved binary either.
2009
+ declared = "0.0.1"
2010
+ with tempfile.TemporaryDirectory(prefix="keel-doctor-declares-") as raw:
2011
+ declares = Path(raw).resolve()
2012
+ write_text(
2013
+ declares / "package-lock.json",
2014
+ json.dumps(
2015
+ {
2016
+ "name": "consumer",
2017
+ "lockfileVersion": 3,
2018
+ "packages": {
2019
+ "node_modules/@fission-ai/openspec": {"version": declared}
2020
+ },
2021
+ },
2022
+ indent=2,
2023
+ )
2024
+ + "\n",
2025
+ )
2026
+ doctor = run_keel(declares, "--doctor")
2027
+ line = openspec_line(doctor.stdout or "")
2028
+ if not line:
2029
+ report(f"{label} M1 `keel --doctor` emitted no openspec line.")
2030
+ report((doctor.stdout or doctor.stderr or "").strip())
2031
+ return 1
2032
+ own_lock = json.loads((ROOT / "npm-shrinkwrap.json").read_text(encoding="utf-8"))
2033
+ own_declared = None
2034
+ for name, entry in own_lock.get("packages", {}).items():
2035
+ if name.endswith("@fission-ai/openspec"):
2036
+ own_declared = entry.get("version")
2037
+ if not own_declared:
2038
+ report(f"{label} could not read Keel's own declared OpenSpec version.")
2039
+ return 1
2040
+ # The reader sees two versions on this line: the one the resolved binary
2041
+ # reports and the one the repository declares. Assert on the declared
2042
+ # POSITION, not on bare presence — the resolved binary's version may
2043
+ # legitimately equal Keel's own declared version, and a test that reads
2044
+ # any occurrence cannot tell the two apart.
2045
+ # Two distinct failures, two conditions. A line carrying the right
2046
+ # version with no attribution and a line attributing the wrong version
2047
+ # need different fixes, and one message covering both would send half
2048
+ # its readers to a place with no problem in it.
2049
+ if "repo pins" not in line:
2050
+ report(
2051
+ f"{label} M1 the openspec line does not attribute any declared "
2052
+ "version to the repository, so a reader seeing two versions "
2053
+ "cannot tell which one is theirs."
2054
+ )
2055
+ report(f" {line}")
2056
+ return 1
2057
+ if f"repo pins {declared}" not in line:
2058
+ report(
2059
+ f"{label} M1 the openspec line attributes a declared version "
2060
+ f"to the repository, but not {declared}, which is what this "
2061
+ "repository declares. It is answering about some other "
2062
+ "repository."
2063
+ )
2064
+ report(f" {line}")
2065
+ return 1
2066
+ if own_declared != declared and f"repo pins {own_declared}" in line:
2067
+ report(
2068
+ f"{label} M1 the openspec line reports {own_declared} as the "
2069
+ "declared version. That is what is declared where Keel is "
2070
+ "installed, not where it was pointed."
2071
+ )
2072
+ report(f" {line}")
2073
+ return 1
2074
+ if not line.startswith("openspec: warning"):
2075
+ report(
2076
+ f"{label} M1 the resolved binary and the declared version "
2077
+ f"disagree ({declared} is declared and no release reports it), "
2078
+ "and the line does not state the disagreement."
2079
+ )
2080
+ report(f" {line}")
2081
+ return 1
2082
+
2083
+ # M1 second half — absence is a statement about the repository, not a read
2084
+ # failure, and not a disagreement. Most repositories do not depend on
2085
+ # OpenSpec at all, so warning here would train readers to ignore the line.
2086
+ with tempfile.TemporaryDirectory(prefix="keel-doctor-silent-") as raw:
2087
+ silent = Path(raw).resolve()
2088
+ write_text(silent / "README.md", "# consumer\n")
2089
+ doctor = run_keel(silent, "--doctor")
2090
+ line = openspec_line(doctor.stdout or "")
2091
+ if not line:
2092
+ report(f"{label} M1 `keel --doctor` emitted no openspec line.")
2093
+ report((doctor.stdout or doctor.stderr or "").strip())
2094
+ return 1
2095
+ if "declares no OpenSpec" not in line:
2096
+ report(
2097
+ f"{label} M1 a repository declaring no OpenSpec version is not "
2098
+ "reported as declaring none."
2099
+ )
2100
+ report(f" {line}")
2101
+ return 1
2102
+ if "unreadable" in line:
2103
+ report(
2104
+ f"{label} M1 the absence of a declaration is reported as a "
2105
+ "failure to read one. The two are different facts and only one "
2106
+ "of them is true here."
2107
+ )
2108
+ report(f" {line}")
2109
+ return 1
2110
+ if "answering from a different" in line:
2111
+ report(
2112
+ f"{label} M1 a repository declaring nothing is reported as "
2113
+ "disagreeing with the resolved binary. There is nothing for it "
2114
+ "to disagree with."
2115
+ )
2116
+ report(f" {line}")
2117
+ return 1
2118
+
2119
+ # M4 — two lockfiles, the precedence npm applies. A repository that
2120
+ # publishes itself carries `npm-shrinkwrap.json` (npm never publishes
2121
+ # `package-lock.json`), and where both exist npm installs from the
2122
+ # shrinkwrap, so that is the version the repository actually pins (#164).
2123
+ with tempfile.TemporaryDirectory(prefix="keel-doctor-shrinkwrap-") as raw:
2124
+ both = Path(raw).resolve()
2125
+ for name, version in (
2126
+ ("npm-shrinkwrap.json", "0.0.2"),
2127
+ ("package-lock.json", "0.0.1"),
2128
+ ):
2129
+ write_text(
2130
+ both / name,
2131
+ json.dumps(
2132
+ {
2133
+ "name": "consumer",
2134
+ "lockfileVersion": 3,
2135
+ "packages": {
2136
+ "node_modules/@fission-ai/openspec": {"version": version}
2137
+ },
2138
+ },
2139
+ indent=2,
2140
+ )
2141
+ + "\n",
2142
+ )
2143
+ doctor = run_keel(both, "--doctor")
2144
+ line = openspec_line(doctor.stdout or "")
2145
+ if "repo pins 0.0.2" not in line:
2146
+ report(
2147
+ f"{label} M4 doctor read package-lock.json over "
2148
+ "npm-shrinkwrap.json, while npm installs from the shrinkwrap "
2149
+ "when both exist."
2150
+ )
2151
+ report(f" {line}")
2152
+ return 1
2153
+
2154
+ if label not in {name for name, _ in registry.SCENARIOS}:
2155
+ report(f"{label}: the scenario registry does not include it.")
2156
+ return 1
2157
+ report(f"{label} scenario passed.")
2158
+ return 0
2159
+
2160
+
2161
+ def validate_context_names_its_keel_scenario() -> int:
2162
+ """The version comparison has to survive a runtime too old to contain it.
2163
+
2164
+ Measured 2026-08-02: installed plugin 5.7.1, CLI 5.7.0, repository protocol
2165
+ 5.14.0, and no session reported anything. The SessionStart version
2166
+ comparison shipped in 5.9.0, so the installed plugin does not carry it, and
2167
+ its silence is indistinguishable from three versions agreeing — which is
2168
+ exactly what 5.9.0 designed silence to mean.
2169
+
2170
+ That is not fixable inside the plugin: an absent mechanism cannot announce
2171
+ itself. The repository is the one participant that cannot be stale, because
2172
+ the working tree is what every runtime reads. So the version rides on
2173
+ `keel context`, which the protocol already requires, and the resident
2174
+ protocol asks for it to be reported beside the version the repository
2175
+ declares.
2176
+ """
2177
+ label = "context-names-its-keel"
2178
+ version = json.loads(
2179
+ (ROOT / "package.json").read_text(encoding="utf-8")
2180
+ )["version"]
2181
+
2182
+ with tempfile.TemporaryDirectory(prefix="keel-context-version-") as raw:
2183
+ repo = Path(raw).resolve()
2184
+
2185
+ # M1 — every status carries it. A result that omits the version cannot
2186
+ # be compared against anything, so an idle or failed answer needs it as
2187
+ # much as a selected one does.
2188
+ idle = run_keel(repo, "context")
2189
+ if version not in idle.stdout:
2190
+ report(
2191
+ f"{label} M1 an idle `keel context` does not name the Keel "
2192
+ f"that produced it: {idle.stdout.strip()!r}"
2193
+ )
2194
+ return 1
2195
+
2196
+ write_text(repo / "openspec/changes/demo/proposal.md", "# Proposal\n")
2197
+ write_text(repo / "openspec/changes/demo/tasks.md", guard_task_fixture())
2198
+ selected = run_keel(repo, "context")
2199
+ if version not in selected.stdout:
2200
+ report(
2201
+ f"{label} M1 a selected `keel context` does not name the Keel "
2202
+ f"that produced it: {selected.stdout.strip()!r}"
2203
+ )
2204
+ return 1
2205
+
2206
+ write_text(repo / "openspec/changes/broken/tasks.md", "not a task file\n")
2207
+ failing = run_keel(repo, "context")
2208
+ if version not in failing.stdout:
2209
+ report(
2210
+ f"{label} M1 an ambiguous or failing `keel context` does not "
2211
+ f"name the Keel that produced it: {failing.stdout.strip()!r}"
2212
+ )
2213
+ return 1
2214
+
2215
+ payload = run_keel(repo, "context", "--json")
2216
+ try:
2217
+ parsed = json.loads(payload.stdout)
2218
+ except json.JSONDecodeError:
2219
+ report(f"{label} M1 `keel context --json` did not emit JSON.")
2220
+ return 1
2221
+ if parsed.get("keel") != version:
2222
+ report(
2223
+ f"{label} M1 the JSON projection carries no `keel` version; got "
2224
+ f"{parsed.get('keel')!r}, expected {version!r}."
2225
+ )
2226
+ return 1
2227
+
2228
+ # M2 — the protocol asks for the comparison, and says why it does not
2229
+ # depend on the hook. Without the second half a reader who sees the
2230
+ # SessionStart line assumes it is covered.
2231
+ agents = (ROOT / "AGENTS.md").read_text(encoding="utf-8")
2232
+ for needle, why in (
2233
+ ("keel context", "the command whose output carries the version"),
2234
+ ("protocol version", "the version the repository declares"),
2235
+ ("SessionStart", "that the requirement does not depend on the hook"),
2236
+ ):
2237
+ if needle not in agents:
2238
+ report(f"{label} M2 the Session Start protocol does not name {why}.")
2239
+ return 1
2240
+ session_start = agents.split("## Full/Lite routing", 1)[0]
2241
+ if "SessionStart" not in session_start:
2242
+ report(
2243
+ f"{label} M2 the hook-independence statement is not in the Session "
2244
+ "Start section, where an agent deciding what to report reads it."
2245
+ )
2246
+ return 1
2247
+
2248
+ if label not in {name for name, _ in registry.SCENARIOS}:
2249
+ report(f"{label}: the scenario registry does not include it.")
2250
+ return 1
2251
+ report(f"{label} scenario passed.")
2252
+ return 0
2253
+
2254
+
2255
+ def validate_interpreter_surfaces_agree_scenario() -> int:
2256
+ """`keel --doctor` called an interpreter ok that the runner refuses.
2257
+
2258
+ Measured 2026-08-02: the doctor printed `python3: ok - python3` while
2259
+ `run_python.js` on the same machine printed "no Python 3.10 or newer was
2260
+ found — tried python3 (3.9.6)". Two Keel surfaces, one question, opposite
2261
+ verdicts, and the one a person runs deliberately to check their environment
2262
+ was the wrong one. The cause is two implementations: `bin/keel.js` carried
2263
+ its own `pythonCandidates` that asked only whether a command runs.
2264
+
2265
+ The same duplication hid a second defect. The candidate list held `python3`
2266
+ and `python`, so on macOS — where `python3` is the system 3.9 — the runner
2267
+ refused while `python3.11` sat on PATH, telling a reader who had already
2268
+ installed one to install one.
2269
+ """
2270
+ label = "interpreter-surfaces-agree"
2271
+ runner = ROOT / "scripts/run_python.js"
2272
+ with tempfile.TemporaryDirectory(prefix="keel-interp-agree-") as raw:
2273
+ root = Path(raw).resolve()
2274
+ script = root / "target.py"
2275
+ write_text(script, "import sys\nsys.exit(7)\n")
2276
+
2277
+ def shim(directory: Path, name: str, version: str) -> Path:
2278
+ path = directory / name
2279
+ write_text(
2280
+ path,
2281
+ "#!/bin/sh\n"
2282
+ f'if [ "$1" = "--version" ]; then echo "Python {version}"; '
2283
+ "exit 0; fi\nexit 7\n",
2284
+ )
2285
+ path.chmod(0o755)
2286
+ return path
2287
+
2288
+ # The stub directory shadows every name Keel could look for, so the
2289
+ # result does not depend on what happens to be installed on the machine
2290
+ # running the suite. Without the versioned shims, a real python3.11 on
2291
+ # PATH would satisfy the search that M1 needs to fail.
2292
+ def stub_dir(mapping: dict[str, str]) -> Path:
2293
+ directory = root / f"bin-{len(list(root.glob('bin-*')))}"
2294
+ directory.mkdir()
2295
+ for name in ("python", "python3", "python3.10", "python3.11",
2296
+ "python3.12", "python3.13"):
2297
+ shim(directory, name, mapping.get(name, "3.9.6"))
2298
+ return directory
2299
+
2300
+ def env_with(directory: Path, keel_python: str | None = None):
2301
+ env = dict(os.environ)
2302
+ env.pop("KEEL_PYTHON", None)
2303
+ env["PATH"] = str(directory) + os.pathsep + env.get("PATH", "")
2304
+ if keel_python:
2305
+ env["KEEL_PYTHON"] = keel_python
2306
+ return env
2307
+
2308
+ def run_runner(env) -> subprocess.CompletedProcess[str]:
2309
+ return subprocess.run(
2310
+ ["node", str(runner), str(script)],
2311
+ env=env, text=True, encoding="utf-8",
2312
+ errors="replace", capture_output=True, check=False,
2313
+ )
2314
+
2315
+ def doctor_python_line(env) -> str:
2316
+ result = subprocess.run(
2317
+ ["node", str(ROOT / "bin" / "keel.js"), "--doctor"],
2318
+ cwd=str(root), env=env, text=True, encoding="utf-8",
2319
+ errors="replace", capture_output=True, check=False,
2320
+ )
2321
+ for line in result.stdout.splitlines():
2322
+ if line.startswith("python3:"):
2323
+ return line
2324
+ return ""
2325
+
2326
+ # M1 — nothing on PATH reaches the minimum. Both surfaces must say so.
2327
+ old_only = stub_dir({})
2328
+ old_env = env_with(old_only)
2329
+ line = doctor_python_line(old_env)
2330
+ if not line:
2331
+ report(f"{label} M1 `keel --doctor` printed no python3 line at all.")
2332
+ return 1
2333
+ if ": ok" in line:
2334
+ report(
2335
+ f"{label} M1 the doctor called an interpreter ok that the "
2336
+ f"runner refuses. Got: {line}"
2337
+ )
2338
+ return 1
2339
+ for needle, why in (("3.9.6", "the version it found"),
2340
+ ("3.10", "the minimum required")):
2341
+ if needle not in line:
2342
+ report(f"{label} M1 the doctor line does not name {why}: {line}")
2343
+ return 1
2344
+ refused = run_runner(old_env)
2345
+ if refused.returncode == 0:
2346
+ report(
2347
+ f"{label} M1 the runner accepted an interpreter the doctor "
2348
+ "reported as a problem, so the two surfaces disagree."
2349
+ )
2350
+ return 1
2351
+
2352
+ # M2 — a usable interpreter exists only under a versioned name.
2353
+ versioned = stub_dir({"python3.11": "3.11.9"})
2354
+ versioned_env = env_with(versioned)
2355
+ used = run_runner(versioned_env)
2356
+ if used.returncode != 7:
2357
+ report(
2358
+ f"{label} M2 a usable interpreter was on PATH as python3.11 and "
2359
+ f"the runner did not use it; exited {used.returncode} rather "
2360
+ "than the script's 7."
2361
+ )
2362
+ report(f" {(used.stdout + used.stderr).strip()}")
2363
+ return 1
2364
+ versioned_line = doctor_python_line(versioned_env)
2365
+ if ": ok" not in versioned_line:
2366
+ report(
2367
+ f"{label} M2 the doctor did not report the versioned "
2368
+ f"interpreter as ok. Got: {versioned_line}"
2369
+ )
2370
+ return 1
2371
+ if "3.11.9" not in versioned_line:
2372
+ report(
2373
+ f"{label} M2 the doctor line names no version for the "
2374
+ f"interpreter it resolved. Got: {versioned_line}"
2375
+ )
2376
+ return 1
2377
+
2378
+ # M3 — the refusal names every candidate with its version, and an
2379
+ # explicit interpreter is used without a search.
2380
+ combined = f"{refused.stdout}{refused.stderr}"
2381
+ for needle in ("python3", "python3.13", "3.9.6"):
2382
+ if needle not in combined:
2383
+ report(
2384
+ f"{label} M3 the refusal does not name {needle!r} among the "
2385
+ f"candidates it tried: {combined.strip()}"
2386
+ )
2387
+ return 1
2388
+ explicit = shim(root, "explicit-python", "3.12.1")
2389
+ chosen = run_runner(env_with(old_only, str(explicit)))
2390
+ if chosen.returncode != 7:
2391
+ report(
2392
+ f"{label} M3 KEEL_PYTHON naming a usable interpreter was not "
2393
+ f"used; exited {chosen.returncode} rather than the script's 7."
2394
+ )
2395
+ return 1
2396
+
2397
+ # M4 — the versioned names are derived from the declared minimum.
2398
+ # KEEL_PYTHON is cleared because it short-circuits the search by design, so
2399
+ # a probe that inherited it would read an empty list and report the derived
2400
+ # names as missing — a true observation about the wrong question.
2401
+ probe_env = dict(os.environ)
2402
+ probe_env.pop("KEEL_PYTHON", None)
2403
+ probe = subprocess.run(
2404
+ ["node", "-e",
2405
+ "const m = require(process.argv[1]);"
2406
+ "process.stdout.write(JSON.stringify({"
2407
+ "minimum: m.MINIMUM_PYTHON,"
2408
+ "names: m.pythonCandidates().map((c) => c.command)}));",
2409
+ str(ROOT / "scripts/run_python.js")],
2410
+ env=probe_env,
2411
+ text=True, encoding="utf-8", capture_output=True, check=False,
2412
+ )
2413
+ if probe.returncode != 0:
2414
+ report(
2415
+ f"{label} M4 scripts/run_python.js does not export its minimum and "
2416
+ f"candidate list: {(probe.stdout + probe.stderr).strip()}"
2417
+ )
2418
+ return 1
2419
+ exported = json.loads(probe.stdout)
2420
+ minor = exported["minimum"][1]
2421
+ versioned_names = [
2422
+ name for name in exported["names"] if re.match(r"^python3\.\d+$", name)
2423
+ ]
2424
+ if not versioned_names:
2425
+ report(f"{label} M4 the candidate list holds no versioned names.")
2426
+ return 1
2427
+ below = [
2428
+ name for name in versioned_names
2429
+ if int(name.split(".")[1]) < minor
2430
+ ]
2431
+ if below:
2432
+ report(
2433
+ f"{label} M4 the candidate list names interpreters below the "
2434
+ f"declared minimum 3.{minor}, so the two are written separately "
2435
+ f"rather than derived: {below}"
2436
+ )
2437
+ return 1
2438
+
2439
+ if label not in {name for name, _ in registry.SCENARIOS}:
2440
+ report(f"{label}: the scenario registry does not include it.")
2441
+ return 1
2442
+ report(f"{label} scenario passed.")
2443
+ return 0
2444
+
2445
+
2446
+ def validate_dev_only_plugin_source_scoping_scenario() -> int:
2447
+ """Issue #6: plugins/keel/ exists only in Keel's own repository.
2448
+
2449
+ In a consuming project the source check is permanently `missing` and the
2450
+ next line told the author to install a plugin they had just installed.
2451
+ """
2452
+ with tempfile.TemporaryDirectory(prefix="keel-dev-only-scope-") as raw:
2453
+ consumer = Path(raw)
2454
+ init = run_keel(consumer, "--init", "--target", "claude")
2455
+ if init.returncode != 0:
2456
+ report("dev-only-plugin-source-scoping: keel --init failed.")
2457
+ report((init.stderr or init.stdout).strip())
2458
+ return 1
2459
+ doctor = run_keel(consumer, "--doctor")
2460
+ out = doctor.stdout or ""
2461
+ if "native plugin source" in out:
2462
+ report(
2463
+ "dev-only-plugin-source-scoping: a consuming project was still "
2464
+ "shown the development-only plugin source check."
2465
+ )
2466
+ report(out)
2467
+ return 1
2468
+ if "install the plugin if it is missing" in out:
2469
+ report(
2470
+ "dev-only-plugin-source-scoping: a consuming project was still "
2471
+ "told to install an already-installed plugin."
2472
+ )
2473
+ report(out)
2474
+ return 1
2475
+ if "plugin source" in out:
2476
+ report(
2477
+ "dev-only-plugin-source-scoping: the plugin source clause "
2478
+ "leaked into a consuming project's capability lines."
2479
+ )
2480
+ report(out)
2481
+ return 1
2482
+ # Keel's own repository must keep the check, which is where it means
2483
+ # something: the manifest and the CLI have to agree before release.
2484
+ own = run_keel(ROOT, "--doctor")
2485
+ if "native plugin source" not in (own.stdout or ""):
2486
+ report(
2487
+ "dev-only-plugin-source-scoping: Keel's own repository lost the "
2488
+ "plugin source check."
2489
+ )
2490
+ report((own.stdout or own.stderr).strip())
2491
+ return 1
2492
+ if "dev-only-plugin-source-scoping" not in {name for name, _ in registry.SCENARIOS}:
2493
+ report(
2494
+ "dev-only-plugin-source-scoping: the scenario registry does not "
2495
+ "include it."
2496
+ )
2497
+ return 1
2498
+ report("dev-only-plugin-source-scoping scenario passed.")
2499
+ return 0
2500
+
2501
+
2502
+ def validate_source_repo_bootstrap_skip_scenario() -> int:
2503
+ """Issue #9: `keel --install` must not overwrite Keel's own AGENTS.md.
2504
+
2505
+ Keel's repository AGENTS.md carries the full protocol that four scenarios
2506
+ assert on; the packaged asset is the shorter consumer bootstrap. Writing it
2507
+ here drops those sections and turns the repository red.
2508
+ """
2509
+ managed = re.compile(
2510
+ r"<!--\s*keel:start.*?<!--\s*keel:end\s*-->", re.DOTALL
2511
+ )
2512
+
2513
+ def block(path: Path) -> str:
2514
+ found = managed.search(path.read_text(encoding="utf-8"))
2515
+ return found.group(0) if found else ""
2516
+
2517
+ # `is_keel_source_repo` reads exactly two signals — the package name and a
2518
+ # plugins/keel directory — so a fixture carrying both exercises the same
2519
+ # branch. Running this against the real repository used to work and used to
2520
+ # rewrite the .claude/ overlay markers as a side effect, which is how the
2521
+ # marker check ended up green on that side for the wrong reason.
2522
+ if not (ROOT / "AGENTS.md").is_file() or not block(ROOT / "AGENTS.md"):
2523
+ report("source-repo-bootstrap-skip: Keel's AGENTS.md has no managed block.")
2524
+ return 1
2525
+
2526
+ with tempfile.TemporaryDirectory(prefix="keel-source-repo-") as raw:
2527
+ fixture = Path(raw) / "keel"
2528
+ write_text(fixture / "package.json", json.dumps({"name": KEEL_PACKAGE_NAME}))
2529
+ write_text(fixture / "plugins/keel/.keep", "")
2530
+ own_agents = fixture / "AGENTS.md"
2531
+ write_text(own_agents, (ROOT / "AGENTS.md").read_text(encoding="utf-8"))
2532
+ before_tree = snapshot_files(fixture)
2533
+ before = block(own_agents)
2534
+
2535
+ result = run_keel(fixture, "--install", "--target", "claude")
2536
+ if result.returncode != 0:
2537
+ report("source-repo-bootstrap-skip: keel --install failed in Keel's repo.")
2538
+ report((result.stderr or result.stdout).strip())
2539
+ return 1
2540
+ if block(own_agents) != before:
2541
+ report(
2542
+ "source-repo-bootstrap-skip: keel --install rewrote Keel's own "
2543
+ "AGENTS.md managed block."
2544
+ )
2545
+ return 1
2546
+ if "skip AGENTS.md" not in (result.stdout or ""):
2547
+ report(
2548
+ "source-repo-bootstrap-skip: the skip was silent; it must be "
2549
+ "reported explicitly."
2550
+ )
2551
+ report((result.stdout or "").strip())
2552
+ return 1
2553
+ # The original defect was the missing assertion, not only the wrong
2554
+ # repository: name what the install must not have rewritten.
2555
+ rewritten = [
2556
+ name
2557
+ for name, text in before_tree.items()
2558
+ if (fixture / name).is_file()
2559
+ and (fixture / name).read_text(encoding="utf-8") != text
2560
+ ]
2561
+ if rewritten:
2562
+ report(
2563
+ "source-repo-bootstrap-skip: keel --install rewrote files it "
2564
+ "did not announce: " + ", ".join(sorted(rewritten))
2565
+ )
2566
+ return 1
2567
+ # A consuming project must still receive the bootstrap.
2568
+ with tempfile.TemporaryDirectory(prefix="keel-bootstrap-consumer-") as raw:
2569
+ consumer = Path(raw)
2570
+ installed = run_keel(consumer, "--install", "--target", "claude")
2571
+ if installed.returncode != 0:
2572
+ report(
2573
+ "source-repo-bootstrap-skip: keel --install failed in a "
2574
+ "consuming project."
2575
+ )
2576
+ report((installed.stderr or installed.stdout).strip())
2577
+ return 1
2578
+ asset_block = block(ROOT / "assets/bootstrap/AGENTS.md")
2579
+ if block(consumer / "AGENTS.md") != asset_block:
2580
+ report(
2581
+ "source-repo-bootstrap-skip: a consuming project did not "
2582
+ "receive the packaged bootstrap block."
2583
+ )
2584
+ return 1
2585
+ if "source-repo-bootstrap-skip" not in {name for name, _ in registry.SCENARIOS}:
2586
+ report(
2587
+ "source-repo-bootstrap-skip: the scenario registry does not include it."
2588
+ )
2589
+ return 1
2590
+ report("source-repo-bootstrap-skip scenario passed.")
2591
+ return 0
2592
+
2593
+
2594
+ def validate_source_repo_cli_resolution_scenario() -> int:
2595
+ """Issue #13 item 3: a bare `keel` runs the installed package.
2596
+
2597
+ When the repository under change *is* Keel, gate commands verify the
2598
+ installed CLI rather than the working tree, and the failure mode is a
2599
+ silently stale result rather than an error. One dogfood round was lost to
2600
+ two spurious problems reported by a stale global CLI.
2601
+ """
2602
+ own = run_keel(ROOT, "--doctor")
2603
+ out = own.stdout or ""
2604
+ if "node bin/keel.js" not in out:
2605
+ report(
2606
+ "source-repo-cli-resolution: Keel's own repository is not told to "
2607
+ "run gate commands through its own entry point."
2608
+ )
2609
+ report(out)
2610
+ return 1
2611
+ # The local entry point needs an explicit repository argument; an author
2612
+ # who copies the hint without it gets an unrelated failure.
2613
+ hint = next(
2614
+ (line for line in out.splitlines() if "node bin/keel.js" in line), ""
2615
+ )
2616
+ # The line must be advisory: it describes a hazard, not a repository
2617
+ # failure, so it must never push doctor toward a non-ok verdict.
2618
+ for needle in ("gate", ".", "advisory"):
2619
+ if needle not in hint:
2620
+ report(
2621
+ "source-repo-cli-resolution: the hint does not name a usable "
2622
+ f"invocation, or is not advisory; missing {needle!r} in: {hint}"
2623
+ )
2624
+ return 1
2625
+ with tempfile.TemporaryDirectory(prefix="keel-cli-resolution-") as raw:
2626
+ consumer = Path(raw)
2627
+ init = run_keel(consumer, "--init", "--target", "claude")
2628
+ if init.returncode != 0:
2629
+ report("source-repo-cli-resolution: keel --init failed.")
2630
+ report((init.stderr or init.stdout).strip())
2631
+ return 1
2632
+ consumer_doctor = run_keel(consumer, "--doctor")
2633
+ if "node bin/keel.js" in (consumer_doctor.stdout or ""):
2634
+ report(
2635
+ "source-repo-cli-resolution: a consuming project was shown a "
2636
+ "hazard that exists only in Keel's own repository."
2637
+ )
2638
+ report(consumer_doctor.stdout or "")
2639
+ return 1
2640
+ if "source-repo-cli-resolution" not in {name for name, _ in registry.SCENARIOS}:
2641
+ report(
2642
+ "source-repo-cli-resolution: the scenario registry does not "
2643
+ "include it."
2644
+ )
2645
+ return 1
2646
+ report("source-repo-cli-resolution scenario passed.")
2647
+ return 0
2648
+
2649
+
2650
+ def validate_target_capability_adapters_scenario() -> int:
2651
+ capability_keys = (
2652
+ "continuity.start",
2653
+ "continuity.reinject",
2654
+ "gate.task-start",
2655
+ "gate.task-complete",
2656
+ "gate.change-close",
2657
+ "execution.worktree",
2658
+ )
2659
+ with tempfile.TemporaryDirectory(prefix="keel-capabilities-") as raw_tmp:
2660
+ root = Path(raw_tmp)
2661
+ for target in ("claude", "codex", "opencode"):
2662
+ repo = root / target
2663
+ repo.mkdir()
2664
+ env = dict(os.environ)
2665
+ if target == "codex":
2666
+ env["CODEX_HOME"] = str(root / "codex-home")
2667
+
2668
+ install = run_keel(
2669
+ repo,
2670
+ "--install",
2671
+ "--target",
2672
+ target,
2673
+ env=env,
2674
+ )
2675
+ if install.returncode != 0:
2676
+ report(f"target-capability-adapters {target} install failed.")
2677
+ report((install.stderr or install.stdout).strip())
2678
+ return 1
2679
+ checked = run_keel(
2680
+ repo,
2681
+ "--check",
2682
+ "--target",
2683
+ target,
2684
+ env=env,
2685
+ )
2686
+ if checked.returncode != 0 or "status: installed" not in checked.stdout:
2687
+ report(f"target-capability-adapters {target} check missed adapter.")
2688
+ report((checked.stderr or checked.stdout).strip())
2689
+ return 1
2690
+
2691
+ before_doctor = snapshot_files(repo)
2692
+ doctor = run_keel(
2693
+ repo,
2694
+ "--doctor",
2695
+ "--target",
2696
+ target,
2697
+ env=env,
2698
+ )
2699
+ after_doctor = snapshot_files(repo)
2700
+ if doctor.returncode != 0:
2701
+ report(f"target-capability-adapters {target} doctor failed.")
2702
+ report((doctor.stderr or doctor.stdout).strip())
2703
+ return 1
2704
+ if before_doctor != after_doctor:
2705
+ report(f"target-capability-adapters {target} doctor mutated config.")
2706
+ return 1
2707
+ for key in capability_keys:
2708
+ if f"{key}: manual" not in doctor.stdout:
2709
+ report(
2710
+ f"target-capability-adapters {target} did not conservatively "
2711
+ f"report {key}."
2712
+ )
2713
+ report(doctor.stdout.strip())
2714
+ return 1
2715
+ # Native target capabilities never claim enforced behavior without
2716
+ # runtime evidence.
2717
+ native_surface = doctor.stdout
2718
+ if "enforced" in native_surface:
2719
+ report(
2720
+ f"target-capability-adapters {target} invented enforced behavior."
2721
+ )
2722
+ report(doctor.stdout.strip())
2723
+ return 1
2724
+
2725
+ probe = run_keel(
2726
+ repo, "capabilities", "--target", target, "--json", env=env
2727
+ )
2728
+ if probe.returncode != 0:
2729
+ report(f"target-capability-adapters {target} capability probe failed.")
2730
+ report((probe.stderr or probe.stdout).strip())
2731
+ return 1
2732
+ probe_payload = json.loads(probe.stdout)
2733
+ if (
2734
+ probe_payload.get("schemaVersion") != 1
2735
+ or probe_payload.get("target") != target
2736
+ or set(probe_payload.get("capabilities", {})) != set(capability_keys)
2737
+ ):
2738
+ report(f"target-capability-adapters {target} probe contract mismatch.")
2739
+ report(adapter_probe.stdout.strip())
2740
+ return 1
2741
+
2742
+ write_text(
2743
+ repo / "openspec/changes/demo/tasks.md",
2744
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n- [ ] 1.1 Incomplete\n - Owner: keel-agent\n",
2745
+ )
2746
+ gate = run_keel(
2747
+ repo,
2748
+ "gate",
2749
+ "task-start",
2750
+ "--change",
2751
+ "demo",
2752
+ "--task",
2753
+ "1.1",
2754
+ "--json",
2755
+ env=env,
2756
+ )
2757
+ if (
2758
+ gate.returncode != 3
2759
+ or json.loads(gate.stdout).get("gate") != "task-start"
2760
+ or json.loads(gate.stdout).get("status") != "fail"
2761
+ ):
2762
+ report(
2763
+ f"target-capability-adapters {target} did not surface Core gate JSON."
2764
+ )
2765
+ report((gate.stderr or gate.stdout).strip())
2766
+ return 1
2767
+
2768
+ if target == "codex":
2769
+ write_text(
2770
+ Path(env["CODEX_HOME"]) / "hooks.json",
2771
+ '{"unverified": true}\n',
2772
+ )
2773
+ elif target == "opencode":
2774
+ write_text(
2775
+ repo / ".opencode/plugins/unverified.js",
2776
+ "export default {}\n",
2777
+ )
2778
+ else:
2779
+ write_text(
2780
+ repo / ".claude/trust-unverified",
2781
+ "not authoritative\n",
2782
+ )
2783
+ unverified = run_keel(
2784
+ repo,
2785
+ "capabilities",
2786
+ "--target",
2787
+ target,
2788
+ "--json",
2789
+ env=env,
2790
+ )
2791
+ if (
2792
+ unverified.returncode != 0
2793
+ or any(
2794
+ item.get("level") != "manual"
2795
+ for item in json.loads(unverified.stdout)
2796
+ .get("capabilities", {})
2797
+ .values()
2798
+ )
2799
+ ):
2800
+ report(
2801
+ f"target-capability-adapters {target} promoted unverified state."
2802
+ )
2803
+ report((unverified.stderr or unverified.stdout).strip())
2804
+ return 1
2805
+
2806
+ adapter_script = ROOT / PLUGIN_ROOT / "scripts/session-start.js"
2807
+ if not adapter_script.is_file():
2808
+ report(
2809
+ "target-capability-adapters native plugin session-start script is "
2810
+ "missing."
2811
+ )
2812
+ return 1
2813
+ adapter_content = adapter_script.read_text(encoding="utf-8")
2814
+ for forbidden in ("parseTasks", "completionProblems", "compileTaskContract"):
2815
+ if forbidden in adapter_content:
2816
+ report(
2817
+ "target-capability-adapters plugin script duplicated Core policy: "
2818
+ f"{forbidden}"
2819
+ )
2820
+ return 1
2821
+
2822
+ report("target-capability-adapters scenario passed.")
2823
+ return 0
2824
+
2825
+
2826
+ # Issue #168: 5.74.0's shrinkwrap pinned OpenSpec 1.6.0 for every install, and
2827
+ # `keel --init` ran `openspec update --force` over surfaces 1.13.2 had written,
2828
+ # deleting ~1000 lines in a consumer while doctor said `openspec: ok`.
2829
+ DOWNGRADE_LABEL = "init-never-downgrades-openspec"
2830
+
2831
+
2832
+ DOWNGRADE_SENTINEL = "keel-downgrade-sentinel: this line exists only in the planted surface"
2833
+
2834
+
2835
+ def _restamp_surfaces(repo: Path, version: str) -> Path:
2836
+ """Stamp every OpenSpec skill `generatedBy: version` and plant a sentinel."""
2837
+ skills = sorted((repo / ".claude/skills").glob("openspec-*/SKILL.md"))
2838
+ for skill in skills:
2839
+ text = skill.read_text(encoding="utf-8")
2840
+ skill.write_text(
2841
+ re.sub(r'generatedBy: "[^"]*"', f'generatedBy: "{version}"', text),
2842
+ encoding="utf-8",
2843
+ )
2844
+ target = repo / ".claude/skills/openspec-propose/SKILL.md"
2845
+ head, sep, body = target.read_text(encoding="utf-8").partition("\n---\n")
2846
+ target.write_text(head + sep + DOWNGRADE_SENTINEL + "\n" + body, encoding="utf-8")
2847
+ return target
2848
+
2849
+
2850
+ def _downgrade_m1(tmp: Path) -> str | None:
2851
+ repo = tmp / "newer"
2852
+ repo.mkdir()
2853
+ run_keel(repo, "--init", "--target", "claude")
2854
+ planted = _restamp_surfaces(repo, "99.0.0")
2855
+ again = run_keel(repo, "--init", "--target", "claude")
2856
+ output = (again.stdout or "") + (again.stderr or "")
2857
+ if DOWNGRADE_SENTINEL not in planted.read_text(encoding="utf-8"):
2858
+ return (
2859
+ "M1 keel --init rewrote OpenSpec surfaces written by a newer OpenSpec "
2860
+ "(99.0.0): the planted sentinel is gone."
2861
+ )
2862
+ if "99.0.0" not in output or "skip" not in output.lower():
2863
+ return (
2864
+ "M1 keel --init kept the surfaces but did not say it skipped the rewrite "
2865
+ f"of OpenSpec surfaces written by a newer OpenSpec: {output[-600:]!r}"
2866
+ )
2867
+ return None
2868
+
2869
+
2870
+ def _downgrade_m2(tmp: Path) -> str | None:
2871
+ repo = tmp / "doctor-newer"
2872
+ repo.mkdir()
2873
+ run_keel(repo, "--init", "--target", "claude")
2874
+ _restamp_surfaces(repo, "99.0.0")
2875
+ running = run_keel(repo, "openspec", "--version").stdout.strip()
2876
+ doctor = run_keel(repo, "--doctor").stdout or ""
2877
+ lines = [l for l in doctor.splitlines() if l.startswith("OpenSpec surfaces:")]
2878
+ if len(lines) != 1 or not lines[0].startswith("OpenSpec surfaces: warning"):
2879
+ return f"M2 doctor printed no OpenSpec surfaces warning for 99.0.0 surfaces: {lines!r}"
2880
+ for needle in ("99.0.0", running, "keel --install --target claude"):
2881
+ if needle not in lines[0]:
2882
+ return f"M2 doctor printed no OpenSpec surfaces warning carrying {needle!r}: {lines[0]!r}"
2883
+ return None
2884
+
2885
+
2886
+ def _downgrade_m3(tmp: Path) -> str | None:
2887
+ repo = tmp / "older"
2888
+ repo.mkdir()
2889
+ run_keel(repo, "--init", "--target", "claude")
2890
+ planted = _restamp_surfaces(repo, "1.0.0")
2891
+ run_keel(repo, "--init", "--target", "claude")
2892
+ if DOWNGRADE_SENTINEL in planted.read_text(encoding="utf-8"):
2893
+ return (
2894
+ "M3 keel --init skipped the OpenSpec refresh for surfaces older than "
2895
+ "the OpenSpec it runs (1.0.0); only newer surfaces are protected."
2896
+ )
2897
+ return None
2898
+
2899
+
2900
+ def _downgrade_m4(tmp: Path) -> str | None:
2901
+ repo = tmp / "git"
2902
+ repo.mkdir()
2903
+ git = ["git", "-c", "user.name=keel", "-c", "user.email=keel@example.invalid"]
2904
+ subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
2905
+ run_keel(repo, "--install", "--target", "claude")
2906
+
2907
+ def line() -> str:
2908
+ doctor = run_keel(repo, "--doctor", "--target", "claude").stdout or ""
2909
+ return next((l for l in doctor.splitlines() if l.startswith("plugin auto-update:")), "")
2910
+
2911
+ untracked = line()
2912
+ if not untracked.startswith("plugin auto-update: warning") or "git add .claude/settings.json" not in untracked:
2913
+ return f"M4 doctor did not say .claude/settings.json is untracked: {untracked!r}"
2914
+ subprocess.run([*git, "add", ".claude/settings.json"], cwd=repo, check=True)
2915
+ subprocess.run([*git, "commit", "-q", "-m", "declare"], cwd=repo, check=True)
2916
+ tracked = line()
2917
+ if not tracked.startswith("plugin auto-update: ok"):
2918
+ return f"M4 doctor did not say .claude/settings.json is untracked only while it was: {tracked!r}"
2919
+ return None
2920
+
2921
+
2922
+ def validate_init_never_downgrades_openspec_scenario() -> int:
2923
+ with tempfile.TemporaryDirectory(
2924
+ prefix="keel-downgrade-", ignore_cleanup_errors=True
2925
+ ) as raw:
2926
+ tmp = Path(raw)
2927
+ for check in (_downgrade_m1, _downgrade_m2, _downgrade_m3, _downgrade_m4):
2928
+ problem = check(tmp)
2929
+ if problem:
2930
+ report(f"{DOWNGRADE_LABEL} {problem}")
2931
+ return 1
2932
+ report(f"{DOWNGRADE_LABEL} scenario passed.")
2933
+ return 0
2934
+
2935
+
2936
+ def validate_thin_native_install_scenario() -> int:
2937
+ with tempfile.TemporaryDirectory(prefix="keel-thin-install-") as raw_tmp:
2938
+ tmp = Path(raw_tmp)
2939
+
2940
+ forbidden_copies = (
2941
+ ".claude/skills/keel-review-checklist",
2942
+ ".claude/skills/keel-align-expectations",
2943
+ ".claude/hooks/keel-gate",
2944
+ ".agents/skills/keel-review-checklist",
2945
+ "keel/adapters",
2946
+ )
2947
+
2948
+ # --- Case A: clean install delivers only the thin v4 surface ---
2949
+ repo = tmp / "clean"
2950
+ repo.mkdir()
2951
+ install = run_keel(repo, "--install")
2952
+ if install.returncode != 0:
2953
+ report("thin-native-install clean install failed.")
2954
+ report((install.stderr or install.stdout).strip())
2955
+ return 1
2956
+
2957
+ agents_path = repo / "AGENTS.md"
2958
+ if not has_managed_block(agents_path):
2959
+ report("thin-native-install missed the AGENTS.md bootstrap block.")
2960
+ return 1
2961
+ agents_text = agents_path.read_text(encoding="utf-8")
2962
+ if agents_text.count(MANAGED_END) != 1:
2963
+ report("thin-native-install wrote more than one AGENTS.md managed block.")
2964
+ return 1
2965
+ block = extract_managed_block(agents_text)
2966
+ block_bytes = len(block.encode("utf-8"))
2967
+ if block_bytes >= BOOTSTRAP_BLOCK_BYTE_BUDGET:
2968
+ report(
2969
+ "thin-native-install bootstrap block is over its "
2970
+ f"{BOOTSTRAP_BLOCK_BYTE_BUDGET}-byte budget: {block_bytes} bytes"
2971
+ )
2972
+ return 1
2973
+
2974
+ # The bootstrap is the whole resident protocol a consumer gets, and the
2975
+ # qualifier "for product files" left readers to infer what it excluded.
2976
+ # The inference actually made was that tasks.md belongs in Touch.
2977
+ if not re.search(r"Touch\b[^\n]*\bbound", block, re.IGNORECASE):
2978
+ report("thin-native-install bootstrap does not state what Touch bounds.")
2979
+ return 1
2980
+ if not re.search(r"change'?s own dir|own change dir", block, re.IGNORECASE):
2981
+ report(
2982
+ "thin-native-install bootstrap does not name the record-write "
2983
+ "exemption, so a consumer still infers that tasks.md belongs in "
2984
+ "Touch."
2985
+ )
2986
+ return 1
2987
+
2988
+ claude_text = (repo / "CLAUDE.md").read_text(encoding="utf-8")
2989
+ if claude_text.count("@AGENTS.md") != 1:
2990
+ report(
2991
+ "thin-native-install did not install exactly one Claude @AGENTS.md "
2992
+ "import."
2993
+ )
2994
+ return 1
2995
+
2996
+ for schema_file in packaged_openspec_schema_install_paths():
2997
+ if not (repo / schema_file).is_file():
2998
+ report(
2999
+ f"thin-native-install missed OpenSpec schema file: {schema_file}"
3000
+ )
3001
+ return 1
3002
+ if not (repo / OPENSPEC_CONFIG_PATH).is_file():
3003
+ report("thin-native-install missed the OpenSpec config.")
3004
+ return 1
3005
+
3006
+ leaked = [rel for rel in forbidden_copies if (repo / rel).exists()]
3007
+ if leaked:
3008
+ report(
3009
+ "thin-native-install copied Keel plugin components the CLI must "
3010
+ "leave to the native plugin."
3011
+ )
3012
+ report(", ".join(leaked))
3013
+ return 1
3014
+
3015
+ # --- Case A': re-install is idempotent, no duplicate bootstrap/import ---
3016
+ before_reinstall = agents_path.read_text(encoding="utf-8")
3017
+ reinstall = run_keel(repo, "--install")
3018
+ if reinstall.returncode != 0:
3019
+ report("thin-native-install re-install failed.")
3020
+ report((reinstall.stderr or reinstall.stdout).strip())
3021
+ return 1
3022
+ if agents_path.read_text(encoding="utf-8") != before_reinstall:
3023
+ report("thin-native-install re-install drifted the AGENTS.md bootstrap.")
3024
+ return 1
3025
+ if (repo / "CLAUDE.md").read_text(encoding="utf-8").count("@AGENTS.md") != 1:
3026
+ report("thin-native-install re-install duplicated the @AGENTS.md import.")
3027
+ return 1
3028
+
3029
+ # --- Case B: plain user content is byte-preserved and only extended ---
3030
+ user_repo = tmp / "user-content"
3031
+ user_repo.mkdir()
3032
+ user_agents = "# My Project\n\nCustom operator notes.\n"
3033
+ user_claude = "# House Guidelines\n\nReview twice.\n"
3034
+ write_text(user_repo / "AGENTS.md", user_agents)
3035
+ write_text(user_repo / "CLAUDE.md", user_claude)
3036
+ user_install = run_keel(user_repo, "--install")
3037
+ if user_install.returncode != 0:
3038
+ report("thin-native-install user-content install failed.")
3039
+ report((user_install.stderr or user_install.stdout).strip())
3040
+ return 1
3041
+ merged_agents = (user_repo / "AGENTS.md").read_text(encoding="utf-8")
3042
+ merged_claude = (user_repo / "CLAUDE.md").read_text(encoding="utf-8")
3043
+ if user_agents not in merged_agents or not has_managed_block(
3044
+ user_repo / "AGENTS.md"
3045
+ ):
3046
+ report(
3047
+ "thin-native-install did not preserve user AGENTS.md text while "
3048
+ "appending the bootstrap."
3049
+ )
3050
+ return 1
3051
+ if user_claude not in merged_claude or "@AGENTS.md" not in merged_claude:
3052
+ report(
3053
+ "thin-native-install did not preserve user CLAUDE.md text while "
3054
+ "appending the import."
3055
+ )
3056
+ return 1
3057
+
3058
+ # --- Case C: a known v3 managed block migrates idempotently ---
3059
+ legacy_repo = tmp / "legacy-block"
3060
+ legacy_repo.mkdir()
3061
+ legacy_block = (
3062
+ "# Team AGENTS\n\n"
3063
+ "<!-- keel:start version=3.0.0 -->\n"
3064
+ "## Keel Legacy Protocol\n\n"
3065
+ "- Old resident protocol body that v4 replaces.\n"
3066
+ "<!-- keel:end -->\n"
3067
+ )
3068
+ write_text(legacy_repo / "AGENTS.md", legacy_block)
3069
+ legacy_install = run_keel(legacy_repo, "--install")
3070
+ if legacy_install.returncode != 0:
3071
+ report("thin-native-install legacy-block install failed.")
3072
+ report((legacy_install.stderr or legacy_install.stdout).strip())
3073
+ return 1
3074
+ migrated = (legacy_repo / "AGENTS.md").read_text(encoding="utf-8")
3075
+ if "Old resident protocol body" in migrated:
3076
+ report("thin-native-install did not migrate the legacy v3 managed block.")
3077
+ return 1
3078
+ if "# Team AGENTS" not in migrated or migrated.count(MANAGED_END) != 1:
3079
+ report(
3080
+ "thin-native-install migration dropped user text or left multiple "
3081
+ "managed blocks."
3082
+ )
3083
+ return 1
3084
+ legacy_reinstall = run_keel(legacy_repo, "--install")
3085
+ if legacy_reinstall.returncode != 0 or (
3086
+ legacy_repo / "AGENTS.md"
3087
+ ).read_text(encoding="utf-8") != migrated:
3088
+ report("thin-native-install legacy migration is not idempotent.")
3089
+ return 1
3090
+
3091
+ # --- Case D: uncertain keel-looking content is preserved with a warning ---
3092
+ uncertain_repo = tmp / "uncertain"
3093
+ uncertain_repo.mkdir()
3094
+ uncertain_agents = (
3095
+ "# Local notes\n\n"
3096
+ "Always run keel gate task-start before implementing anything.\n"
3097
+ )
3098
+ write_text(uncertain_repo / "AGENTS.md", uncertain_agents)
3099
+ uncertain_install = run_keel(uncertain_repo, "--install")
3100
+ uncertain_text = (uncertain_install.stdout or "") + (
3101
+ uncertain_install.stderr or ""
3102
+ )
3103
+ if uncertain_install.returncode != 0:
3104
+ report("thin-native-install uncertain-content install failed.")
3105
+ report(uncertain_text.strip())
3106
+ return 1
3107
+ if (uncertain_repo / "AGENTS.md").read_text(
3108
+ encoding="utf-8"
3109
+ ) != uncertain_agents:
3110
+ report(
3111
+ "thin-native-install overwrote uncertain keel-looking AGENTS.md "
3112
+ "content instead of preserving it."
3113
+ )
3114
+ return 1
3115
+ if "preserve AGENTS.md" not in uncertain_text:
3116
+ report(
3117
+ "thin-native-install preserved uncertain content without a warning "
3118
+ "naming AGENTS.md."
3119
+ )
3120
+ report(uncertain_text.strip())
3121
+ return 1
3122
+
3123
+ # --- Case E: doctor reports the native plugin runtime with remediation ---
3124
+ # These repos consume Keel, so the runtime line and its install
3125
+ # remediation must appear, while the plugin *source* check must not:
3126
+ # plugins/keel/ exists only in Keel's own repository and `keel --init`
3127
+ # never creates it, so reporting it here is a permanent unactionable
3128
+ # `missing`. See the dev-only-plugin-source-scoping scenario.
3129
+ doctor = run_keel(repo, "--doctor")
3130
+ doctor_text = (doctor.stdout or "") + (doctor.stderr or "")
3131
+ if (
3132
+ "native plugin runtime" not in doctor_text
3133
+ or "keel@<marketplace>" not in doctor_text
3134
+ ):
3135
+ report(
3136
+ "thin-native-install doctor does not report the native plugin "
3137
+ "surface with install remediation."
3138
+ )
3139
+ report(doctor_text.strip())
3140
+ return 1
3141
+ if "native plugin source" in doctor_text:
3142
+ report(
3143
+ "thin-native-install doctor reported the development-only "
3144
+ "plugin source check in a consuming project."
3145
+ )
3146
+ report(doctor_text.strip())
3147
+ return 1
3148
+ missing_repo = tmp / "no-plugin"
3149
+ missing_repo.mkdir()
3150
+ missing_doctor = run_keel(missing_repo, "--doctor")
3151
+ missing_text = (missing_doctor.stdout or "") + (missing_doctor.stderr or "")
3152
+ if "plugin source" in missing_text:
3153
+ report(
3154
+ "thin-native-install doctor diagnosed a plugin source outside "
3155
+ "Keel's own repository."
3156
+ )
3157
+ report(missing_text.strip())
3158
+ return 1
3159
+
3160
+ report("thin-native-install scenario passed.")
3161
+ return 0
3162
+
3163
+
3164
+ def validate_domain_execution_references_scenario() -> int:
3165
+ consuming_skills = (
3166
+ "keel-tdd-or-test-first",
3167
+ "keel-debug-failure",
3168
+ "keel-review-checklist",
3169
+ )
3170
+ templates = ("web.md", "hardware.md", "hardware-dsl.md")
3171
+ roots = (ROOT / "src/skills", ROOT / PLUGIN_ROOT / "skills")
3172
+
3173
+ for root in roots:
3174
+ for skill in consuming_skills:
3175
+ text = (root / skill / "SKILL.md").read_text(encoding="utf-8")
3176
+ for needle in (
3177
+ "keel/lenses/",
3178
+ "Execution and review checks",
3179
+ "the lens whose `Applies when:` header matches",
3180
+ "no lens matches",
3181
+ ):
3182
+ if needle not in text:
3183
+ report(
3184
+ f"domain-execution-references: {root.name}/{skill} lacks "
3185
+ f"the on-demand lens consult step ({needle!r})."
3186
+ )
3187
+ return 1
3188
+
3189
+ lenses_root = ROOT / "assets/lenses"
3190
+ for template in templates:
3191
+ ref_path = lenses_root / template
3192
+ if not ref_path.is_file():
3193
+ report(f"domain-execution-references: lens template is missing: {template}")
3194
+ return 1
3195
+ text = ref_path.read_text(encoding="utf-8")
3196
+ if "## Execution and review checks" not in text:
3197
+ report(
3198
+ f"domain-execution-references: {template} lacks the "
3199
+ "execution and review section."
3200
+ )
3201
+ return 1
3202
+ if "Applies when" not in text:
3203
+ report(
3204
+ f"domain-execution-references: {template} lacks the "
3205
+ "self-describing 'Applies when' header."
3206
+ )
3207
+ return 1
3208
+ size = ref_path.stat().st_size
3209
+ if size > 3072:
3210
+ report(
3211
+ f"domain-execution-references: {template} exceeds the 3072-"
3212
+ f"byte budget ({size} bytes); move depth to dedicated skills."
3213
+ )
3214
+ return 1
3215
+
3216
+ for skill in consuming_skills:
3217
+ src_text = (roots[0] / skill / "SKILL.md").read_bytes()
3218
+ shipped_text = (roots[1] / skill / "SKILL.md").read_bytes()
3219
+ if src_text != shipped_text:
3220
+ report(
3221
+ f"domain-execution-references: shipped {skill} copy diverges "
3222
+ "from the canonical source."
3223
+ )
3224
+ return 1
3225
+
3226
+ readme = (ROOT / "README.zh-CN.md").read_text(encoding="utf-8") + (ROOT / "README.md").read_text(encoding="utf-8")
3227
+ if "Execution and review checks" not in readme:
3228
+ report(
3229
+ "domain-execution-references: README does not describe the "
3230
+ "execution/review phase coverage."
3231
+ )
3232
+ return 1
3233
+ if "domain-execution-references" not in {name for name, _ in registry.SCENARIOS}:
3234
+ report(
3235
+ "domain-execution-references: the scenario registry does not "
3236
+ "include it."
3237
+ )
3238
+ return 1
3239
+
3240
+ report("domain-execution-references scenario passed.")
3241
+ return 0
3242
+
3243
+
3244
+ def validate_domain_lens_scaffold_scenario() -> int:
3245
+ shipped = {"web", "hardware", "hardware-dsl"}
3246
+ lenses_root = ROOT / "assets/lenses"
3247
+ for name in shipped:
3248
+ if not (lenses_root / f"{name}.md").is_file():
3249
+ report(f"domain-lens-scaffold: shipped template is missing: {name}")
3250
+ return 1
3251
+
3252
+ with tempfile.TemporaryDirectory(prefix="keel-lenses-") as raw_tmp:
3253
+ repo = Path(raw_tmp) / "repo"
3254
+ repo.mkdir()
3255
+
3256
+ listing = run_keel(repo, "lenses", "list")
3257
+ if listing.returncode != 0:
3258
+ report("domain-lens-scaffold: keel lenses list failed.")
3259
+ report((listing.stderr or listing.stdout).strip())
3260
+ return 1
3261
+ for name in shipped:
3262
+ if name not in listing.stdout:
3263
+ report(
3264
+ f"domain-lens-scaffold: keel lenses list omitted the "
3265
+ f"{name} template."
3266
+ )
3267
+ report(listing.stdout.strip())
3268
+ return 1
3269
+ if "keel/lenses/" not in listing.stdout:
3270
+ report(
3271
+ "domain-lens-scaffold: keel lenses list did not name the "
3272
+ "keel/lenses/ install location."
3273
+ )
3274
+ return 1
3275
+
3276
+ add = run_keel(repo, "lenses", "add", "web")
3277
+ installed = repo / "keel/lenses/web.md"
3278
+ if add.returncode != 0 or not installed.is_file():
3279
+ report("domain-lens-scaffold: keel lenses add web did not scaffold.")
3280
+ report((add.stderr or add.stdout).strip())
3281
+ return 1
3282
+ if "Applies when:" not in installed.read_text(encoding="utf-8"):
3283
+ report(
3284
+ "domain-lens-scaffold: scaffolded lens lost its 'Applies when:' "
3285
+ "header."
3286
+ )
3287
+ return 1
3288
+
3289
+ clobber = run_keel(repo, "lenses", "add", "web")
3290
+ if clobber.returncode == 0:
3291
+ report(
3292
+ "domain-lens-scaffold: a second keel lenses add web must refuse "
3293
+ "without --force."
3294
+ )
3295
+ return 1
3296
+
3297
+ forced = run_keel(repo, "lenses", "add", "web", "--force")
3298
+ if forced.returncode != 0:
3299
+ report("domain-lens-scaffold: keel lenses add web --force failed.")
3300
+ report((forced.stderr or forced.stdout).strip())
3301
+ return 1
3302
+
3303
+ after_add = run_keel(repo, "lenses", "list")
3304
+ if "web (installed)" not in after_add.stdout:
3305
+ report(
3306
+ "domain-lens-scaffold: keel lenses list did not mark web as "
3307
+ "installed after add."
3308
+ )
3309
+ report(after_add.stdout.strip())
3310
+ return 1
3311
+
3312
+ report("domain-lens-scaffold scenario passed.")
3313
+ return 0
3314
+
3315
+
3316
+ def validate_domain_lens_doctor_scenario() -> int:
3317
+ with tempfile.TemporaryDirectory(
3318
+ prefix="keel-lens-doctor-", ignore_cleanup_errors=True
3319
+ ) as raw_tmp:
3320
+ repo = Path(raw_tmp) / "repo"
3321
+ repo.mkdir()
3322
+
3323
+ doctor = run_keel(repo, "--doctor")
3324
+ out = doctor.stdout
3325
+ if "Domain lens surface:" not in out:
3326
+ report("domain-lens-doctor: --doctor lacks the Domain lens surface section.")
3327
+ report((doctor.stderr or out).strip())
3328
+ return 1
3329
+ for name in ("web", "hardware", "hardware-dsl"):
3330
+ if name not in out:
3331
+ report(f"domain-lens-doctor: --doctor did not report the {name} template.")
3332
+ report(out.strip())
3333
+ return 1
3334
+ if "lens templates: ok" not in out:
3335
+ report("domain-lens-doctor: --doctor did not report the shipped templates as ok.")
3336
+ report(out.strip())
3337
+ return 1
3338
+
3339
+ legacy = repo / ".claude/skills/keel-profile-web/SKILL.md"
3340
+ legacy.parent.mkdir(parents=True)
3341
+ legacy.write_text("legacy profile bytes\n", encoding="utf-8")
3342
+ before = legacy.read_bytes()
3343
+
3344
+ doctor2 = run_keel(repo, "--doctor")
3345
+ out2 = doctor2.stdout
3346
+ if "legacy profiles: migrate" not in out2 or "keel-profile-web" not in out2:
3347
+ report(
3348
+ "domain-lens-doctor: --doctor did not warn about the legacy "
3349
+ "keel-profile-web skill."
3350
+ )
3351
+ report(out2.strip())
3352
+ return 1
3353
+ if "not active state" not in out2:
3354
+ report(
3355
+ "domain-lens-doctor: the legacy warning must state it is not "
3356
+ "active state."
3357
+ )
3358
+ return 1
3359
+ if legacy.read_bytes() != before:
3360
+ report("domain-lens-doctor: --doctor modified the legacy skill bytes.")
3361
+ return 1
3362
+
3363
+ report("domain-lens-doctor scenario passed.")
3364
+ return 0
3365
+
3366
+
3367
+ # The one ordered scenario registry: --scenario dispatch, the --all runner,
3368
+ # and registration assertions all read this list and nothing else.
3369
+
3370
+ # 170 scenarios and every release gate ran green while `keel openspec` did not
3371
+ # resolve on a plain `npm install` (issue #129). The cause is a layout, not a
3372
+ # behavior: npm hoists, so the OpenSpec bin lands in the consumer project's
3373
+ # `node_modules/.bin` while the lookup only searched Keel's own package root —
3374
+ # which is where it sits in a checkout of this repository, and nowhere else.
3375
+ # So the assertion has to build the other layout rather than test harder in this
3376
+ # one. Built from the package's own files instead of the registry: what is under
3377
+ # test is where a file sits, and a suite that reaches the network fails for
3378
+ # reasons that have nothing to do with this code.
3379
+ def validate_dependency_resolves_where_npm_put_it_scenario() -> int:
3380
+ label = "the-dependency-resolves-where-npm-put-it"
3381
+
3382
+ def write_openspec_stub(bin_dir: Path, version: str) -> None:
3383
+ bin_dir.mkdir(parents=True, exist_ok=True)
3384
+ if os.name == "nt":
3385
+ (bin_dir / "openspec.cmd").write_text(
3386
+ f"@echo off\necho {version}\n", encoding="utf-8"
3387
+ )
3388
+ return
3389
+ stub = bin_dir / "openspec"
3390
+ stub.write_text(f"#!/bin/sh\necho {version}\n", encoding="utf-8")
3391
+ stub.chmod(0o755)
3392
+
3393
+ def install_keel(package_root: Path) -> None:
3394
+ # The published `files` set, copied rather than packed: the tarball's
3395
+ # contents are what npm unpacks, and `npm pack` would add a network-free
3396
+ # but slow round trip through tar for no additional assertion.
3397
+ package_root.mkdir(parents=True, exist_ok=True)
3398
+ for entry in ("bin", "scripts", "src", "assets", "plugins"):
3399
+ source = ROOT / entry
3400
+ if source.exists():
3401
+ shutil.copytree(source, package_root / entry, dirs_exist_ok=True)
3402
+ shutil.copy2(ROOT / "package.json", package_root / "package.json")
3403
+
3404
+ # PATH without any openspec, so what resolves came from the layout and not
3405
+ # from the machine running the suite. Removed by file rather than by
3406
+ # directory: one directory holds `openspec` and `node` on the ordinary
3407
+ # Homebrew plus `npm install -g` layout, and the children below are run by
3408
+ # `node` (issue #137).
3409
+ def clean_env(extra_path: Path | None = None) -> dict[str, str]:
3410
+ env = dict(os.environ)
3411
+ entries = [entry for entry in sanitized_path.split(os.pathsep) if entry]
3412
+ if extra_path is not None:
3413
+ entries.insert(0, str(extra_path))
3414
+ env["PATH"] = os.pathsep.join(entries)
3415
+ return env
3416
+
3417
+ def run_installed(
3418
+ package_root: Path, cwd: Path, *args: str, env: dict[str, str] | None = None
3419
+ ) -> subprocess.CompletedProcess[str]:
3420
+ return subprocess.run(
3421
+ ["node", str(package_root / "bin" / "keel.js"), *args],
3422
+ cwd=cwd,
3423
+ env=env if env is not None else clean_env(),
3424
+ text=True,
3425
+ encoding="utf-8",
3426
+ errors="replace",
3427
+ capture_output=True,
3428
+ check=False,
3429
+ )
3430
+
3431
+ def doctor_openspec_line(result: subprocess.CompletedProcess[str]) -> str:
3432
+ return next(
3433
+ (
3434
+ line
3435
+ for line in result.stdout.splitlines()
3436
+ if line.startswith("openspec:")
3437
+ ),
3438
+ "",
3439
+ )
3440
+
3441
+ # The mirrors live for the duration of the context, so it stays open across
3442
+ # every child process below rather than only across the call that built it.
3443
+ with path_without_openspec() as sanitized_path, tempfile.TemporaryDirectory(
3444
+ prefix="keel-hoisted-"
3445
+ ) as raw:
3446
+ # The scenario's own precondition, asserted before the behavior: every
3447
+ # assertion below runs `node`, so a PATH without one is a broken fixture
3448
+ # and not a fact about where the dependency resolves.
3449
+ if shutil.which("node", path=sanitized_path) is None:
3450
+ return skip_scenario(
3451
+ label,
3452
+ "node does not resolve on the PATH this scenario built, and "
3453
+ "every assertion below runs the installed Keel through it. That "
3454
+ "is a broken fixture, not a fact about openspec.",
3455
+ )
3456
+ root = Path(raw)
3457
+
3458
+ # The layout npm actually produces: Keel unpacked under the consumer's
3459
+ # node_modules with no node_modules of its own, the dependency's bin
3460
+ # hoisted beside it.
3461
+ project = root / "project"
3462
+ package_root = project / "node_modules/@christang/keel"
3463
+ install_keel(package_root)
3464
+ write_openspec_stub(project / "node_modules/.bin", "1.12.0")
3465
+ if (package_root / "node_modules").exists():
3466
+ report(
3467
+ f"{label}: the fixture gave Keel a node_modules of its own, "
3468
+ "which is the one layout the defect does not appear in."
3469
+ )
3470
+ return 1
3471
+
3472
+ proxied = run_installed(package_root, project, "openspec", "--version")
3473
+ if proxied.returncode != 0:
3474
+ report(
3475
+ f"{label}: `keel openspec` failed against the hoisted "
3476
+ f"dependency; exit {proxied.returncode}, stderr "
3477
+ f"{proxied.stderr.strip()!r}."
3478
+ )
3479
+ return 1
3480
+ if "1.12.0" not in proxied.stdout:
3481
+ report(
3482
+ f"{label}: `keel openspec` exited 0 without running the "
3483
+ f"hoisted dependency; stdout {proxied.stdout.strip()!r}."
3484
+ )
3485
+ return 1
3486
+
3487
+ hoisted_doctor = doctor_openspec_line(
3488
+ run_installed(package_root, project, "--doctor")
3489
+ )
3490
+ if hoisted_doctor.startswith("openspec: missing"):
3491
+ report(
3492
+ f"{label}: doctor reported an installed dependency as missing; "
3493
+ f"got {hoisted_doctor!r}."
3494
+ )
3495
+ return 1
3496
+
3497
+ # Nearest wins, so a project pinning its own OpenSpec is honored over
3498
+ # one further up the tree.
3499
+ nested = root / "outer/project"
3500
+ nested_package = nested / "node_modules/@christang/keel"
3501
+ install_keel(nested_package)
3502
+ write_openspec_stub(root / "outer/node_modules/.bin", "9.9.9")
3503
+ write_openspec_stub(nested / "node_modules/.bin", "1.12.0")
3504
+ nearest = run_installed(nested_package, nested, "openspec", "--version")
3505
+ if "1.12.0" not in nearest.stdout:
3506
+ report(
3507
+ f"{label}: the farther OpenSpec won over the nearer one; got "
3508
+ f"{nearest.stdout.strip()!r}."
3509
+ )
3510
+ return 1
3511
+
3512
+ # The one case where advising a reinstall is correct.
3513
+ bare = root / "bare"
3514
+ bare_package = bare / "node_modules/@christang/keel"
3515
+ install_keel(bare_package)
3516
+ absent = doctor_openspec_line(
3517
+ run_installed(bare_package, bare, "--doctor")
3518
+ )
3519
+ if not absent.startswith("openspec: missing"):
3520
+ report(
3521
+ f"{label}: doctor did not report a genuinely absent dependency "
3522
+ f"as missing; got {absent!r}."
3523
+ )
3524
+ return 1
3525
+ if "reinstall" not in absent:
3526
+ report(
3527
+ f"{label}: doctor stopped advising a reinstall in the one case "
3528
+ f"where it is the right advice; got {absent!r}."
3529
+ )
3530
+ return 1
3531
+
3532
+ # Installed and unreachable: the package is where npm puts it, its bin
3533
+ # entry is not. Sending this reader to reinstall is what issue #129
3534
+ # measured, and it is the one action that cannot help.
3535
+ broken = root / "broken"
3536
+ broken_package = broken / "node_modules/@christang/keel"
3537
+ install_keel(broken_package)
3538
+ write_text(
3539
+ broken / "node_modules/@fission-ai/openspec/package.json",
3540
+ '{"name": "@fission-ai/openspec", "version": "1.12.0"}\n',
3541
+ )
3542
+ unreachable = doctor_openspec_line(
3543
+ run_installed(broken_package, broken, "--doctor")
3544
+ )
3545
+ if "reinstall" in unreachable and "will not change this" not in unreachable:
3546
+ report(
3547
+ f"{label}: doctor advised reinstalling for a dependency that "
3548
+ f"is already installed; got {unreachable!r}."
3549
+ )
3550
+ return 1
3551
+ if "installed" not in unreachable:
3552
+ report(
3553
+ f"{label}: doctor did not distinguish an installed but "
3554
+ f"unreachable dependency from an absent one; got "
3555
+ f"{unreachable!r}."
3556
+ )
3557
+ return 1
3558
+
3559
+ report(f"{label} scenario passed.")
3560
+ return 0
3561
+
3562
+
3563
+ def validate_doctor_openspec_honesty_scenario() -> int:
3564
+ cli = (ROOT / "bin/keel.js").read_text(encoding="utf-8")
3565
+ if "is not on PATH" not in cli:
3566
+ report(
3567
+ "doctor-openspec-honesty scenario: bin/keel.js is missing the "
3568
+ "openspec PATH-reachability warning branch."
3569
+ )
3570
+ return 1
3571
+ with tempfile.TemporaryDirectory(prefix="keel-doctor-openspec-") as raw:
3572
+ root = Path(raw)
3573
+ repo = root / "repo"
3574
+ repo.mkdir()
3575
+ stub_dir = root / "stub"
3576
+ stub_dir.mkdir()
3577
+ if os.name == "nt":
3578
+ (stub_dir / "openspec.cmd").write_text(
3579
+ "@echo off\necho 1.6.0\n", encoding="utf-8"
3580
+ )
3581
+ else:
3582
+ stub = stub_dir / "openspec"
3583
+ stub.write_text("#!/bin/sh\necho 1.6.0\n", encoding="utf-8")
3584
+ stub.chmod(0o755)
3585
+ env = dict(os.environ)
3586
+ env["PATH"] = str(stub_dir) + os.pathsep + env.get("PATH", "")
3587
+ on_path = run_keel(repo, "--doctor", env=env)
3588
+ openspec_line = next(
3589
+ (
3590
+ line
3591
+ for line in on_path.stdout.splitlines()
3592
+ if line.startswith("openspec:")
3593
+ ),
3594
+ "",
3595
+ )
3596
+ if not openspec_line.startswith("openspec: ok"):
3597
+ report(
3598
+ "doctor-openspec-honesty scenario: doctor did not report `ok` "
3599
+ "when a bare openspec is on PATH."
3600
+ )
3601
+ report(on_path.stdout.strip())
3602
+ return 1
3603
+ report("doctor-openspec-honesty scenario passed.")
3604
+ return 0
3605
+
3606
+
3607
+ # The marker's `version=` attribute is written by the installer and, before this
3608
+ # scenario, read back by nothing that runs locally: both marker parsers match
3609
+ # `keel:start(?:\s+[^>]*)?` and discard the attributes. The only reader was the
3610
+ # plugin's SessionStart hook, whose activation doctor itself reports as manual.
3611
+ def validate_marker_version_is_read_scenario() -> int:
3612
+ def doctor_protocol_line(repo: Path) -> tuple[str, int]:
3613
+ result = run_keel(repo, "--doctor")
3614
+ line = next(
3615
+ (
3616
+ entry
3617
+ for entry in result.stdout.splitlines()
3618
+ if entry.startswith("protocol:")
3619
+ ),
3620
+ "",
3621
+ )
3622
+ return line, result.returncode
3623
+
3624
+ def write_repo(root: Path, name: str, marker: str | None) -> Path:
3625
+ repo = root / name
3626
+ repo.mkdir()
3627
+ body = "# Agents\n\nSession Start.\n"
3628
+ (repo / "AGENTS.md").write_text(
3629
+ f"{marker}\n{body}" if marker is not None else body,
3630
+ encoding="utf-8",
3631
+ )
3632
+ return repo
3633
+
3634
+ with tempfile.TemporaryDirectory(prefix="keel-marker-version-") as raw:
3635
+ root = Path(raw)
3636
+
3637
+ behind = write_repo(root, "behind", "<!-- keel:start version=5.14.0 -->")
3638
+ line, behind_code = doctor_protocol_line(behind)
3639
+ if not line.startswith("protocol: warning"):
3640
+ report(
3641
+ "the-marker-version-is-read scenario: a repository declaring an "
3642
+ f"older protocol did not warn; got {line!r}."
3643
+ )
3644
+ return 1
3645
+ # #168: `keel --init` also runs OpenSpec's `--force` rewrite, which is
3646
+ # what downgraded a consumer's surfaces. The protocol refresh is install.
3647
+ if "keel --init" in line:
3648
+ report(
3649
+ "the-marker-version-is-read scenario: a repository behind its "
3650
+ f"install was told to run keel --init; got {line!r}."
3651
+ )
3652
+ return 1
3653
+ for needed in ("5.14.0", PACKAGE_VERSION, "keel --install"):
3654
+ if needed not in line:
3655
+ report(
3656
+ "the-marker-version-is-read scenario: the behind-repository "
3657
+ f"warning omits {needed!r}; got {line!r}."
3658
+ )
3659
+ return 1
3660
+ if "repository" not in line:
3661
+ report(
3662
+ "the-marker-version-is-read scenario: the warning does not name "
3663
+ f"the repository as the term that is behind; got {line!r}."
3664
+ )
3665
+ return 1
3666
+
3667
+ ahead = write_repo(root, "ahead", "<!-- keel:start version=9.99.0 -->")
3668
+ line, _ = doctor_protocol_line(ahead)
3669
+ if not line.startswith("protocol: warning"):
3670
+ report(
3671
+ "the-marker-version-is-read scenario: a repository declaring a "
3672
+ f"newer protocol did not warn; got {line!r}."
3673
+ )
3674
+ return 1
3675
+ for needed in ("9.99.0", PACKAGE_VERSION, "install"):
3676
+ if needed not in line:
3677
+ report(
3678
+ "the-marker-version-is-read scenario: the ahead-repository "
3679
+ f"warning omits {needed!r}; got {line!r}."
3680
+ )
3681
+ return 1
3682
+ if "keel --init" in line:
3683
+ report(
3684
+ "the-marker-version-is-read scenario: a repository ahead of its "
3685
+ f"install was told to re-run keel --init; got {line!r}."
3686
+ )
3687
+ return 1
3688
+
3689
+ agreed = write_repo(
3690
+ root, "agreed", f"<!-- keel:start version={PACKAGE_VERSION} -->"
3691
+ )
3692
+ line, agreed_code = doctor_protocol_line(agreed)
3693
+ if not line.startswith("protocol: ok"):
3694
+ report(
3695
+ "the-marker-version-is-read scenario: agreeing versions did not "
3696
+ f"report ok; got {line!r}."
3697
+ )
3698
+ return 1
3699
+ if line.count(PACKAGE_VERSION) < 2:
3700
+ report(
3701
+ "the-marker-version-is-read scenario: the agreeing line does not "
3702
+ f"print both versions; got {line!r}."
3703
+ )
3704
+ return 1
3705
+
3706
+ # D2: drift is a warning and nothing else. A line that could turn a
3707
+ # pipeline red on release day is a line users switch off.
3708
+ if behind_code != agreed_code:
3709
+ report(
3710
+ "the-marker-version-is-read scenario: drift changed doctor's "
3711
+ f"exit code ({behind_code} vs {agreed_code})."
3712
+ )
3713
+ return 1
3714
+
3715
+ for name, marker in (
3716
+ ("undeclared", None),
3717
+ ("attributeless", "<!-- keel:start -->"),
3718
+ ):
3719
+ repo = write_repo(root, name, marker)
3720
+ line, _ = doctor_protocol_line(repo)
3721
+ if not line.startswith("protocol: not comparable"):
3722
+ report(
3723
+ f"the-marker-version-is-read scenario: the {name} repository "
3724
+ f"did not report `not comparable`; got {line!r}."
3725
+ )
3726
+ return 1
3727
+ if "declares" not in line:
3728
+ report(
3729
+ f"the-marker-version-is-read scenario: the {name} repository "
3730
+ f"was not told which term is missing; got {line!r}."
3731
+ )
3732
+ return 1
3733
+
3734
+ report("the-marker-version-is-read scenario passed.")
3735
+ return 0
3736
+
3737
+
3738
+ # `keel --init` writes OpenSpec's command and skill surfaces, whose text says
3739
+ # `openspec new change "<name>"`. With only the Keel package installed globally
3740
+ # a bare `openspec` is not on PATH, which `keel --doctor` reports and names the
3741
+ # working invocation for. Those files belong to OpenSpec and Keel appends a
3742
+ # block rather than editing their body — so the block is where Keel says it.
3743
+ def validate_overlay_names_the_invocation_scenario() -> int:
3744
+ label = "the-overlay-names-the-invocation"
3745
+ start = "<!-- keel:openspec-surface-overlay"
3746
+ end = "<!-- keel:openspec-surface-overlay:end -->"
3747
+ with tempfile.TemporaryDirectory(prefix="keel-overlay-invocation-") as raw:
3748
+ repo = Path(raw)
3749
+ # The surfaces OpenSpec writes, as OpenSpec writes them: the overlay is
3750
+ # merged into files that already exist, and their body is the text this
3751
+ # scenario asserts Keel does not touch.
3752
+ upstream = 'Run `openspec new change "<name>"` to begin.\n'
3753
+ for action in ("propose", "apply", "sync", "archive"):
3754
+ write_text(repo / f".claude/commands/opsx/{action}.md", upstream)
3755
+ for skill in (
3756
+ "openspec-propose",
3757
+ "openspec-apply-change",
3758
+ "openspec-sync-specs",
3759
+ "openspec-archive-change",
3760
+ ):
3761
+ write_text(repo / f".claude/skills/{skill}/SKILL.md", upstream)
3762
+ installed = run_keel(repo, "--install", "--target", "claude")
3763
+ if installed.returncode != 0:
3764
+ report(
3765
+ f"{label}: the fixture install failed; "
3766
+ f"{(installed.stderr or installed.stdout).strip()[:300]}"
3767
+ )
3768
+ return 1
3769
+
3770
+ carrying = [
3771
+ path
3772
+ for path in sorted(repo.rglob("*.md"))
3773
+ if start in path.read_text(encoding="utf-8", errors="replace")
3774
+ ]
3775
+ if not carrying:
3776
+ report(f"{label}: the install wrote no file carrying an overlay.")
3777
+ return 1
3778
+ for path in carrying:
3779
+ content = path.read_text(encoding="utf-8")
3780
+ block = content[content.index(start):content.index(end) + len(end)]
3781
+ for needed in ("keel openspec", "keel --doctor"):
3782
+ if needed not in block:
3783
+ report(
3784
+ f"{label}: the overlay in {path.name} does not name "
3785
+ f"{needed!r}."
3786
+ )
3787
+ return 1
3788
+ # The boundary: everything outside the block is OpenSpec's.
3789
+ outside = (
3790
+ content[: content.index(start)]
3791
+ + content[content.index(end) + len(end):]
3792
+ )
3793
+ if start in outside or "keel openspec" in outside:
3794
+ report(
3795
+ f"{label}: {path.name} carries Keel invocation text outside "
3796
+ "the overlay block, so the OpenSpec-authored body was "
3797
+ "edited."
3798
+ )
3799
+ return 1
3800
+
3801
+ report(f"{label} scenario passed.")
3802
+ return 0