@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,1466 @@
1
+ """Keel validation: selfcheck (split from validate_plugin.py, #409)."""
2
+ from __future__ import annotations
3
+
4
+ import contextlib
5
+ import importlib
6
+ import json
7
+ import gzip
8
+ import hashlib
9
+ import os
10
+ import re
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import tarfile
15
+ import tempfile
16
+ import threading
17
+ import time
18
+ import types
19
+ import ast
20
+ import atexit
21
+ import signal
22
+ from datetime import datetime, timedelta, timezone
23
+ from concurrent.futures import ThreadPoolExecutor, as_completed
24
+ from pathlib import Path
25
+
26
+ from validation.common import (
27
+ BOOTSTRAP_BLOCK_BYTE_BUDGET,
28
+ ROOT,
29
+ report,
30
+ run_keel,
31
+ run_scenario_processes,
32
+ skip_scenario,
33
+ validate_resident_blocks,
34
+ validation_source_with,
35
+ validation_sources,
36
+ write_text,
37
+ )
38
+ from validation import registry
39
+
40
+
41
+ def _goal_tasks_file(blocks: list[str]) -> str:
42
+ return "# Tasks\n\n## Invalidates\n\n- None.\n\n" + "\n\n".join(blocks) + "\n"
43
+
44
+
45
+ def _goal_task_block(
46
+ task_id: str = "1.1",
47
+ title: str = "Deliver one bounded behavior",
48
+ checked: bool = False,
49
+ acceptance: tuple[str, ...] = ("Observable result is proven by M1.",),
50
+ strategy: str | None = "evidence-first",
51
+ filled: bool = False,
52
+ blocker: str = "none",
53
+ redgreen: bool = False,
54
+ ) -> str:
55
+ box = "x" if checked else " "
56
+ lines = [
57
+ "- [%s] %s %s" % (box, task_id, title),
58
+ " - Owner: keel-agent",
59
+ " - Mode: implementation",
60
+ " - Covers:",
61
+ " - E1: single-task goal",
62
+ " - Read:",
63
+ " - README.md",
64
+ " - Touch:",
65
+ " - src/feature.js",
66
+ ]
67
+ if strategy:
68
+ lines.append(" - Verification Strategy: %s" % strategy)
69
+ if strategy == "evidence-first":
70
+ lines.append(" - Verification Reason: this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first")
71
+ lines.append(" - Commands:")
72
+ lines.append(" - M1: node test.js")
73
+ lines.append(" - Acceptance:")
74
+ for item in acceptance:
75
+ lines.append(" - %s" % item)
76
+ lines.extend(
77
+ [
78
+ " - Autonomy boundary:",
79
+ " - Default: hard-stop",
80
+ " - Coupling: none",
81
+ " - Candidate Boundary:",
82
+ " - one candidate",
83
+ " - Stop Rules:",
84
+ " - stop on failure",
85
+ " - Evidence:",
86
+ " - Contract: pending",
87
+ ]
88
+ )
89
+ if filled:
90
+ lines.append(" - M1: node test.js passed with the expected output")
91
+ if redgreen:
92
+ lines.append(" - M1.red: the failing behavior fixture was reproduced exit 1")
93
+ lines.append(" - M1.green: the behavior fixture passed exit 0")
94
+ lines.extend(
95
+ [
96
+ " - Review:",
97
+ " - Status: pass",
98
+ " - Acceptance check: acceptance demonstrated by M1",
99
+ " - Scope check: only src/feature.js changed within Touch",
100
+ " - Findings: none",
101
+ " - Blocker: %s" % blocker,
102
+ ]
103
+ )
104
+ else:
105
+ lines.extend(
106
+ [
107
+ " - M1: pending",
108
+ " - Review:",
109
+ " - Status: pending",
110
+ " - Acceptance check: pending",
111
+ " - Scope check: pending",
112
+ " - Findings: pending",
113
+ " - Blocker: %s" % blocker,
114
+ ]
115
+ )
116
+ lines.extend(
117
+ [
118
+ " - Stop if:",
119
+ " - scope exceeds Touch",
120
+ " - Report:",
121
+ " - Summary",
122
+ ]
123
+ )
124
+ return "\n".join(lines)
125
+
126
+
127
+ def validate_runner_skip_accounting_scenario() -> int:
128
+ """Issue #10: the suite could not pass anywhere the native CLIs are absent.
129
+
130
+ Two of seventy scenarios probe native runtimes and used to `return 1` when
131
+ the CLI was missing, so no CI runner could ever go green. A skip must be
132
+ reported and counted, never conflated with a pass or a failure.
133
+ """
134
+ label = "runner-skip-accounting"
135
+ runner = str(ROOT / "scripts/validate_plugin.py")
136
+
137
+ def run_registry(results: str) -> subprocess.CompletedProcess[str]:
138
+ """Drive run_all over synthetic scenario results in a child process.
139
+
140
+ run_all dispatches each scenario as its own subprocess, which reads the
141
+ real registry from disk, so a substituted registry would be ignored.
142
+ The accounting is the behavior under test, so the process fan-out is
143
+ replaced with fixed (name, code, output) triples instead.
144
+ """
145
+ program = (
146
+ "import sys\n"
147
+ f"src = open({runner!r}, encoding='utf-8').read()\n"
148
+ "ns = {'__name__': 'v', '__file__': %r}\n" % runner
149
+ + "exec(compile(src, %r, 'exec'), ns)\n" % runner
150
+ + f"results = {results}\n"
151
+ "ns['SCENARIOS'] = tuple((n, None) for n, _, _ in results)\n"
152
+ "ns['run_baseline'] = lambda: 0\n"
153
+ "ns['run_scenario_processes'] = lambda names, jobs: results\n"
154
+ "sys.exit(ns['run_all'](2))\n"
155
+ )
156
+ return subprocess.run(
157
+ [sys.executable, "-c", program],
158
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
159
+ cwd=str(ROOT),
160
+ )
161
+
162
+ # A skipping scenario must not fail the run, must be named, and must be
163
+ # excluded from the verified count; a failing one must still fail it.
164
+ both = run_registry(
165
+ "[('fake-skip', 3, 'fake-skip scenario skipped: the frob CLI\\n'),"
166
+ " ('fake-pass', 0, 'fake-pass scenario passed.\\n')]"
167
+ )
168
+ out = (both.stdout or "") + (both.stderr or "")
169
+ if both.returncode != 0:
170
+ report(f"{label}: a skipping scenario must not fail the run.")
171
+ report(out.strip())
172
+ return 1
173
+ for needle in ("fake-skip", "skipped", "the frob CLI", "plus 1 scenario"):
174
+ if needle not in out:
175
+ report(f"{label}: the summary must report {needle!r}; got:\n{out.strip()}")
176
+ return 1
177
+ if "fake-pass" in out.split("passed:")[-1]:
178
+ report(f"{label}: a passing scenario must not be listed as skipped.")
179
+ report(out.strip())
180
+ return 1
181
+
182
+ mixed = run_registry(
183
+ "[('fake-skip', 3, 'fake-skip scenario skipped: the frob CLI\\n'),"
184
+ " ('fake-fail', 1, 'fake-fail scenario failed.\\n')]"
185
+ )
186
+ mixed_out = (mixed.stdout or "") + (mixed.stderr or "")
187
+ if mixed.returncode == 0 or "failed for: fake-fail" not in mixed_out:
188
+ report(
189
+ f"{label}: a skip beside a failure must still fail the run and name "
190
+ "the failure."
191
+ )
192
+ report(mixed_out.strip())
193
+ return 1
194
+ if "fake-skip" in mixed_out.split("failed for:")[-1]:
195
+ report(f"{label}: a skipped scenario must not be named as a failure.")
196
+ report(mixed_out.strip())
197
+ return 1
198
+
199
+ # The two real native-runtime scenarios must take the skip path, not fail,
200
+ # when their CLI cannot be resolved.
201
+ for name in ("native-plugin-marketplaces", "native-plugin-install-matrix"):
202
+ blinded = subprocess.run(
203
+ [sys.executable, runner, "--scenario", name],
204
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
205
+ cwd=str(ROOT),
206
+ env={**os.environ, "PATH": str(ROOT), "PATHEXT": ""},
207
+ )
208
+ blinded_out = (blinded.stdout or "") + (blinded.stderr or "")
209
+ if blinded.returncode != 3 or "skipped" not in blinded_out:
210
+ report(
211
+ f"{label}: {name} must exit 3 with a reported skip when its CLI "
212
+ f"cannot be resolved; got {blinded.returncode}."
213
+ )
214
+ report(blinded_out.strip())
215
+ return 1
216
+ if "codex" not in blinded_out:
217
+ report(f"{label}: {name}'s skip does not name the runtime it needed.")
218
+ report(blinded_out.strip())
219
+ return 1
220
+
221
+ if label not in {name for name, _ in registry.SCENARIOS}:
222
+ report(f"{label}: the scenario registry does not include it.")
223
+ return 1
224
+ report(f"{label} scenario passed.")
225
+ return 0
226
+
227
+
228
+ def validate_self_checks_read_every_module_scenario() -> int:
229
+ """Issue #409: a check that reads the runner's code reads every module of it.
230
+
231
+ After the split, a scan that still read `scripts/*.py` alone would pass
232
+ over every scenario that moved into `scripts/validation/` and report
233
+ nothing, which reads exactly like having nothing to report.
234
+ """
235
+ label = "self-checks-read-every-module:"
236
+ baseline = importlib.import_module("validation.baseline")
237
+ with tempfile.TemporaryDirectory(prefix="keel-409-self-checks-") as raw:
238
+ scratch = Path(raw)
239
+ write_text(scratch / "scripts/validate_plugin.py", (ROOT / "scripts/validate_plugin.py").read_text(encoding="utf-8"))
240
+ write_text(scratch / "scripts/validation/__init__.py", "")
241
+ write_text(
242
+ scratch / "scripts/validation/planted.py",
243
+ "from validation.common import ROOT, run_keel\n"
244
+ "import requests\n\n\n"
245
+ "def validate_planted_scenario() -> int:\n"
246
+ " run_keel(ROOT, \"--install\", \"--target\", \"claude\")\n"
247
+ " return 0\n",
248
+ )
249
+ saved = baseline.ROOT
250
+ baseline.ROOT = scratch
251
+ try:
252
+ path_errors: list[str] = []
253
+ baseline.validate_paths(path_errors)
254
+ import_errors: list[str] = []
255
+ baseline.validate_scripts_use_stdlib(import_errors)
256
+ finally:
257
+ baseline.ROOT = saved
258
+
259
+ planted = [e for e in path_errors if "scripts/validation/planted.py" in e]
260
+ if not any("scripts/validation/planted.py:6:" in e and "mutating Keel command" in e for e in planted):
261
+ report(f"{label} the path scan did not report the planted `run_keel(ROOT, \"--install\")` by module and line: {planted!r}")
262
+ return 1
263
+ planted = [e for e in import_errors if "scripts/validation/planted.py" in e]
264
+ if not any("requests" in e for e in planted):
265
+ report(f"{label} the standard-library check did not report the planted `import requests`: {import_errors!r}")
266
+ return 1
267
+ if any("validation" in e.split("modules:")[-1] for e in planted):
268
+ report(f"{label} the standard-library check refused the runner's own `validation` package: {planted!r}")
269
+ return 1
270
+
271
+ # The unregistered-scenario check reads modules, not one namespace.
272
+ module = types.ModuleType("validation.planted")
273
+
274
+ def validate_planted_scenario() -> int:
275
+ return 0
276
+
277
+ validate_planted_scenario.__module__ = module.__name__
278
+ module.validate_planted_scenario = validate_planted_scenario
279
+ orphans = unregistered_scenario_functions([module], registry.SCENARIOS)
280
+ if orphans != ["validation.planted.validate_planted_scenario"]:
281
+ report(f"{label} the unregistered-scenario check did not name the planted scenario: {orphans!r}")
282
+ return 1
283
+
284
+ if "self-checks-read-every-module" not in {name for name, _ in registry.SCENARIOS}:
285
+ report(f"{label} the scenario registry does not include it.")
286
+ return 1
287
+ report("self-checks-read-every-module scenario passed.")
288
+ return 0
289
+
290
+
291
+ def validate_runner_runs_one_group_scenario() -> int:
292
+ """Issue #409: one module's scenarios run alone, with the full run's accounting.
293
+
294
+ Driven like runner-skip-accounting: the entry point's source runs with a
295
+ registry of synthetic scenarios from two modules and a stubbed process
296
+ runner, so the selection, its order, and the summary are what is tested.
297
+ """
298
+ label = "runner-runs-one-group:"
299
+ runner = str(ROOT / "scripts/validate_plugin.py")
300
+
301
+ def run_group(results: str) -> subprocess.CompletedProcess[str]:
302
+ program = (
303
+ "import sys\n"
304
+ f"src = open({runner!r}, encoding='utf-8').read()\n"
305
+ "ns = {'__name__': 'v', '__file__': %r}\n" % runner
306
+ + "exec(compile(src, %r, 'exec'), ns)\n" % runner
307
+ + f"results = dict((n, (c, o)) for n, c, o in {results})\n"
308
+ "def make(name, module):\n"
309
+ " def scenario():\n"
310
+ " return 0\n"
311
+ " scenario.__module__ = module\n"
312
+ " return (name, scenario)\n"
313
+ "ns['SCENARIOS'] = (make('a-one', 'validation.alpha'), make('b-one', 'validation.beta'),\n"
314
+ " make('a-two', 'validation.alpha'), make('a-three', 'validation.alpha'))\n"
315
+ "def baseline():\n"
316
+ " raise SystemExit('the baseline ran')\n"
317
+ "ns['run_baseline'] = baseline\n"
318
+ "def processes(names, jobs):\n"
319
+ " print('handed: ' + ','.join(names))\n"
320
+ " return [(n, *results[n]) for n in names]\n"
321
+ "ns['run_scenario_processes'] = processes\n"
322
+ f"sys.argv = [{runner!r}, '--group', 'alpha', '--jobs', '2']\n"
323
+ "sys.exit(ns['main']())\n"
324
+ )
325
+ return subprocess.run(
326
+ [sys.executable, "-c", program],
327
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
328
+ cwd=str(ROOT),
329
+ )
330
+
331
+ passing = run_group(
332
+ "[('a-one', 0, 'a-one scenario passed.\\n'),"
333
+ " ('a-two', 3, 'a-two scenario skipped: the frob CLI\\n'),"
334
+ " ('a-three', 0, 'a-three scenario passed.\\n')]"
335
+ )
336
+ out = (passing.stdout or "") + (passing.stderr or "")
337
+ if "handed: a-one,a-two,a-three" not in out:
338
+ report(f"{label} --group alpha did not hand the runner exactly alpha's scenarios in registry order: {out!r}")
339
+ return 1
340
+ if "the baseline ran" in out:
341
+ report(f"{label} --group ran the baseline: {out!r}")
342
+ return 1
343
+ if passing.returncode != 0:
344
+ report(f"{label} a passing group exited {passing.returncode}: {out!r}")
345
+ return 1
346
+ if "validation --group alpha passed: 2 scenarios, 1 skipped: a-two" not in out:
347
+ report(f"{label} the group's summary does not name the group, its verified count, and its skip: {out!r}")
348
+ return 1
349
+
350
+ failing = run_group(
351
+ "[('a-one', 0, 'a-one scenario passed.\\n'),"
352
+ " ('a-two', 1, 'a-two scenario failed.\\n'),"
353
+ " ('a-three', 0, 'a-three scenario passed.\\n')]"
354
+ )
355
+ out = (failing.stdout or "") + (failing.stderr or "")
356
+ if failing.returncode != 1:
357
+ report(f"{label} a group with a failure exited {failing.returncode}, not 1: {out!r}")
358
+ return 1
359
+ if "validation --group alpha failed for: a-two" not in out:
360
+ report(f"{label} a group with a failure does not name it: {out!r}")
361
+ return 1
362
+
363
+ unknown = subprocess.run(
364
+ [sys.executable, runner, "--group", "no-such-group"],
365
+ capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=str(ROOT),
366
+ )
367
+ out = (unknown.stdout or "") + (unknown.stderr or "")
368
+ if unknown.returncode != 2:
369
+ report(f"{label} an unknown group exited {unknown.returncode}, not 2: {out!r}")
370
+ return 1
371
+ for group in ("contract", "selfcheck"):
372
+ if group not in out:
373
+ report(f"{label} an unknown group's message does not name the group {group!r}: {out!r}")
374
+ return 1
375
+
376
+ if "runner-runs-one-group" not in {name for name, _ in registry.SCENARIOS}:
377
+ report(f"{label} the scenario registry does not include it.")
378
+ return 1
379
+ report("runner-runs-one-group scenario passed.")
380
+ return 0
381
+
382
+
383
+ def validate_resident_topic_matching_scenario() -> int:
384
+ """Issue #15 item 1: required entries were named topics, matched as prose.
385
+
386
+ The bootstrap is under a line and byte budget, so its wording gets rewritten
387
+ to fit — and every rewrite of a pinned sentence failed the check that was
388
+ supposed to prove only that the topic was still covered.
389
+ """
390
+ label = "resident-topic-matching"
391
+ source = (ROOT / "assets/bootstrap/AGENTS.md").read_text(encoding="utf-8")
392
+ original = "Touch bounds product writes; the change's own dir is exempt."
393
+ if original not in source:
394
+ report(
395
+ f"{label}: the fixture's anchor sentence is not in the bootstrap; "
396
+ "update this scenario alongside the wording."
397
+ )
398
+ return 1
399
+
400
+ def errors_for(text: str) -> list[str]:
401
+ with tempfile.TemporaryDirectory(prefix="keel-resident-topic-") as raw:
402
+ root = Path(raw)
403
+ write_text(root / "assets/bootstrap/AGENTS.md", text)
404
+ found: list[str] = []
405
+ validate_resident_blocks(found, root)
406
+ return found
407
+
408
+ def touch_errors(text: str) -> list[str]:
409
+ return [item for item in errors_for(text) if "Touch" in item or "bound" in item]
410
+
411
+ baseline = errors_for(source)
412
+ if baseline:
413
+ report(f"{label}: the unmodified bootstrap must pass: {baseline}")
414
+ return 1
415
+
416
+ # A rewording that keeps both concepts in one statement must pass.
417
+ reworded = source.replace(
418
+ original, "Touch bounds product writes, not the task's own records;"
419
+ )
420
+ if touch_errors(reworded):
421
+ report(
422
+ f"{label}: a rewording that keeps the topic was rejected: "
423
+ f"{touch_errors(reworded)}"
424
+ )
425
+ return 1
426
+
427
+ # Deleting the statement must still fail.
428
+ deleted = source.replace(original, "")
429
+ if not touch_errors(deleted):
430
+ report(f"{label}: deleting the boundary statement did not fail the check.")
431
+ return 1
432
+
433
+ # Mentioning only one of the topic's words must not satisfy it.
434
+ partial = source.replace(original, "Touch the files you declared;")
435
+ if not touch_errors(partial):
436
+ report(
437
+ f"{label}: a statement mentioning only Touch, with no boundary "
438
+ "concept, satisfied the topic."
439
+ )
440
+ return 1
441
+
442
+ # A renamed command must still fail, and be reported as a literal.
443
+ renamed = source.replace("keel context", "keel status")
444
+ literal_errors = [item for item in errors_for(renamed) if "keel context" in item]
445
+ if not literal_errors:
446
+ report(f"{label}: renaming a required command did not fail the check.")
447
+ return 1
448
+ if not any("literal" in item for item in literal_errors):
449
+ report(
450
+ f"{label}: a missing command must be reported as a missing literal, "
451
+ f"distinguishably from a missing topic: {literal_errors}"
452
+ )
453
+ return 1
454
+ if any("literal" in item for item in touch_errors(deleted)):
455
+ report(
456
+ f"{label}: a missing topic must not be reported as a missing "
457
+ f"literal: {touch_errors(deleted)}"
458
+ )
459
+ return 1
460
+
461
+ if (ROOT / "assets/bootstrap/AGENTS.md").read_text(encoding="utf-8") != source:
462
+ report(f"{label}: the shipped bootstrap was left modified.")
463
+ return 1
464
+ if label not in {name for name, _ in registry.SCENARIOS}:
465
+ report(f"{label}: the scenario registry does not include it.")
466
+ return 1
467
+ report(f"{label} scenario passed.")
468
+ return 0
469
+
470
+
471
+ # The one-message-many-failures shape, counted rather than forbidden.
472
+ #
473
+ # Issue #43 records it caught by `keel-review-checklist` in three consecutive
474
+ # changes, every time in this file: `if <the run did not work> or <the output
475
+ # lacks a specific thing>:` followed by one `report(...)` describing only the
476
+ # second operand. When the first fires the sentence is false, and it sends the
477
+ # reader to a place with no problem in it.
478
+ #
479
+ # This number bounds a SHAPE. It is not a count of defects: many of the sites
480
+ # it counts carry a message that genuinely covers every operand, and deciding
481
+ # whether a particular sentence misleads needs a model, so that judgment stays
482
+ # in `keel-review-checklist`. What the number does is make a *new* one visible
483
+ # when it is written, which is earlier than a review that only runs at a
484
+ # completion gate.
485
+ #
486
+ # A pass/fail lint was the obvious form and is unshippable: the shape was
487
+ # already present at this many sites when the count was introduced, and
488
+ # rewriting them all in the file every other correctness claim rests on is a
489
+ # large blind diff. A recorded count fails when the number rises and lists what
490
+ # it measured; it also fails when the number falls without this constant being
491
+ # lowered, because a number that only checks for rises becomes false the first
492
+ # time someone fixes a site — and a false number is what this whole change is
493
+ # about. Fixing sites is expected. Lowering this constant is one line.
494
+ #
495
+ # Raised 75 -> 80 by `change-verify-deferred-evidence` (issue #95): five sites,
496
+ # each `payload.get("status") != "fail" or "<code>" not in codes(payload)`
497
+ # guarding one `report(...)`, the same already-accepted gate-result-assertion
498
+ # shape as `regression-check-tag`'s own site above. The message covers both
499
+ # operands (the gate did not fail the way the fixture requires, whichever half
500
+ # was wrong), and every site prints the full problem payload alongside it, so
501
+ # a reader is never left with only the sentence.
502
+ OR_GUARDED_ASSERTION_SITES = 74
503
+
504
+
505
+ def or_guarded_assertion_sites(source: str) -> list[int]:
506
+ """Line numbers of `if` statements where one message covers several failures.
507
+
508
+ The counted shape, stated so the next reader can restate it exactly: a body
509
+ of one or more `report(...)` calls followed by exactly one `return`, under
510
+ an `or` test with at least one membership operand (`in` / `not in`) and at
511
+ least one operand that is not.
512
+
513
+ A heuristic rule keyed on `returncode`, `is None`, `len(` and
514
+ `.get("status")` was measured first and found 68 sites against this rule's
515
+ 75; the simple one is used because a rule nobody can reproduce produces a
516
+ number nobody can check.
517
+ """
518
+
519
+ def is_report_return(body: list) -> bool:
520
+ reports = [
521
+ node for node in body
522
+ if isinstance(node, ast.Expr)
523
+ and isinstance(node.value, ast.Call)
524
+ and isinstance(node.value.func, ast.Name)
525
+ and node.value.func.id == "report"
526
+ ]
527
+ if not reports:
528
+ return False
529
+ returns = [node for node in body if isinstance(node, ast.Return)]
530
+ if len(returns) != 1:
531
+ return False
532
+ return len(body) == len(reports) + len(returns)
533
+
534
+ def is_membership(node) -> bool:
535
+ if not isinstance(node, ast.Compare):
536
+ return False
537
+ return any(isinstance(op, (ast.In, ast.NotIn)) for op in node.ops)
538
+
539
+ sites = []
540
+ for node in ast.walk(ast.parse(source)):
541
+ if not isinstance(node, ast.If):
542
+ continue
543
+ if not is_report_return(node.body):
544
+ continue
545
+ test = node.test
546
+ if not isinstance(test, ast.BoolOp):
547
+ continue
548
+ if not isinstance(test.op, ast.Or):
549
+ continue
550
+ operands = test.values
551
+ if not any(is_membership(item) for item in operands):
552
+ continue
553
+ if all(is_membership(item) for item in operands):
554
+ continue
555
+ sites.append(node.lineno)
556
+ return sorted(sites)
557
+
558
+
559
+ def assertion_site_drift(measured: list[int], recorded: int) -> str:
560
+ """Empty when the measured sites match the recorded count.
561
+
562
+ Both directions fail, and they fail differently, because they call for
563
+ opposite actions: a rise means split the assertion you just wrote, and a
564
+ fall means lower the constant.
565
+ """
566
+ if len(measured) > recorded:
567
+ return (
568
+ f"{len(measured)} assertion sites guard several distinct failures "
569
+ f"behind one message, but {recorded} are recorded. One condition "
570
+ "reporting two failures names the wrong cause whenever the other "
571
+ "one fires. Split the `if` you just added so each failure carries "
572
+ "its own message, or — if the message genuinely covers every "
573
+ "operand — raise OR_GUARDED_ASSERTION_SITES and say why. This "
574
+ "number bounds a shape and is not a count of defects. Measured at "
575
+ f"lines: {', '.join(str(line) for line in measured)}."
576
+ )
577
+ if len(measured) < recorded:
578
+ return (
579
+ f"{recorded} assertion sites are recorded but only {len(measured)} "
580
+ "are present, so the recorded number is stale. Lower "
581
+ f"OR_GUARDED_ASSERTION_SITES to {len(measured)}. The count fails in "
582
+ "this direction too because a number that only checks for rises "
583
+ "stops being true the first time a site is fixed."
584
+ )
585
+ return ""
586
+
587
+
588
+ # Synthetic sources for the counter. They are strings rather than fixtures on
589
+ # disk because the rule is about syntax, and a fixture file would itself be
590
+ # counted when the suite measures this file's siblings.
591
+ COUNTED_ASSERTION_SOURCE = '''
592
+ def probe():
593
+ if result.returncode != 0 or "Usage:" not in result.stdout:
594
+ report("no Usage: line")
595
+ return 1
596
+ return 0
597
+ '''
598
+
599
+
600
+ SPLIT_ASSERTION_SOURCE = '''
601
+ def probe():
602
+ if result.returncode != 0:
603
+ report("the command failed to run")
604
+ return 1
605
+ if "Usage:" not in result.stdout:
606
+ report("no Usage: line")
607
+ return 1
608
+ return 0
609
+ '''
610
+
611
+
612
+ ALL_MEMBERSHIP_ASSERTION_SOURCE = '''
613
+ def probe():
614
+ if "alpha" not in text or "beta" not in text:
615
+ report("the output names neither alpha nor beta")
616
+ return 1
617
+ return 0
618
+ '''
619
+
620
+
621
+ NO_REPORT_ASSERTION_SOURCE = '''
622
+ def probe():
623
+ if result.returncode != 0 or "Usage:" not in result.stdout:
624
+ cleanup()
625
+ return 1
626
+ return 0
627
+ '''
628
+
629
+
630
+ def validate_assertion_shape_count_scenario() -> int:
631
+ """Issue #43: one condition guarding two failures, caught three times.
632
+
633
+ `keel-review-checklist` catches it, but only at a completion gate and only
634
+ because a human wrote a checklist entry pointing the model at it. This
635
+ counts the shape so a new one is visible when it is written.
636
+ """
637
+ # M1 — the counter finds the shape, and stops finding it once it is split.
638
+ counted = or_guarded_assertion_sites(COUNTED_ASSERTION_SOURCE)
639
+ if counted != [3]:
640
+ report(
641
+ "assertion-shape-count: M1 the counter did not report the single "
642
+ f"counted site at line 3 of the synthetic source; got {counted}."
643
+ )
644
+ return 1
645
+ split = or_guarded_assertion_sites(SPLIT_ASSERTION_SOURCE)
646
+ if split:
647
+ report(
648
+ "assertion-shape-count: M1 splitting the assertion so each failure "
649
+ f"carries its own message must clear it; got {split}."
650
+ )
651
+ return 1
652
+
653
+ # M2 — the two shapes that are deliberately not counted.
654
+ all_membership = or_guarded_assertion_sites(ALL_MEMBERSHIP_ASSERTION_SOURCE)
655
+ if all_membership:
656
+ report(
657
+ "assertion-shape-count: M2 an `or` whose operands are all "
658
+ "membership tests is one claim about one subject and is not "
659
+ f"counted; got {all_membership}."
660
+ )
661
+ return 1
662
+ no_report = or_guarded_assertion_sites(NO_REPORT_ASSERTION_SOURCE)
663
+ if no_report:
664
+ report(
665
+ "assertion-shape-count: M2 an `if` whose body is not a report "
666
+ f"followed by a single return is not an assertion site; got "
667
+ f"{no_report}."
668
+ )
669
+ return 1
670
+
671
+ # M3 — the comparison fails in both directions, differently.
672
+ risen = assertion_site_drift([10, 20, 30], 2)
673
+ if not risen:
674
+ report(
675
+ "assertion-shape-count: M3 a measured count above the recorded one "
676
+ "produced no failure."
677
+ )
678
+ return 1
679
+ if "30" not in risen:
680
+ report(
681
+ "assertion-shape-count: M3 the rise must list the measured line "
682
+ f"numbers so the added site can be located. Got: {risen}"
683
+ )
684
+ return 1
685
+ fallen = assertion_site_drift([10], 2)
686
+ if not fallen:
687
+ report(
688
+ "assertion-shape-count: M3 a measured count below the recorded one "
689
+ "produced no failure, so the recorded number could go stale "
690
+ "silently."
691
+ )
692
+ return 1
693
+ if fallen == risen:
694
+ report(
695
+ "assertion-shape-count: M3 a rise and a fall call for opposite "
696
+ "actions and must not share a message."
697
+ )
698
+ return 1
699
+ if "stale" not in fallen:
700
+ report(
701
+ f"assertion-shape-count: M3 the fall must say the recorded number "
702
+ f"is stale and name the new one. Got: {fallen}"
703
+ )
704
+ return 1
705
+ if assertion_site_drift([10, 20], 2):
706
+ report(
707
+ "assertion-shape-count: M3 a measured count equal to the recorded "
708
+ "one must pass."
709
+ )
710
+ return 1
711
+
712
+ # M4 — the real files, and this scenario's own assertions. Every module of
713
+ # the runner is counted and each site is named as file:line (#409).
714
+ measured = []
715
+ for path in validation_sources():
716
+ relative = path.relative_to(ROOT).as_posix()
717
+ measured.extend(
718
+ f"{relative}:{line}"
719
+ for line in or_guarded_assertion_sites(path.read_text(encoding="utf-8"))
720
+ )
721
+ drift = assertion_site_drift(measured, OR_GUARDED_ASSERTION_SITES)
722
+ if drift:
723
+ report(f"assertion-shape-count: M4 {drift}")
724
+ return 1
725
+ own_path, source, own_start = validation_source_with("def validate_assertion_shape_count_scenario")
726
+ own_first_line = source[:own_start].count("\n") + 1
727
+ own_end = own_start + source[own_start:].index("\n\n\ndef ")
728
+ own_last_line = source[:own_end].count("\n") + 1
729
+ own_relative = own_path.relative_to(ROOT).as_posix()
730
+ inside = [
731
+ site for site in measured
732
+ if site.rsplit(":", 1)[0] == own_relative
733
+ and own_first_line <= int(site.rsplit(":", 1)[1]) <= own_last_line
734
+ ]
735
+ if inside:
736
+ report(
737
+ "assertion-shape-count: M4 this scenario's own assertions are of "
738
+ f"the shape it counts, at lines {inside}."
739
+ )
740
+ return 1
741
+
742
+ # M5 — the wording says what the number is.
743
+ if "bounds a shape and is not a count of defects" not in risen:
744
+ report(
745
+ "assertion-shape-count: M5 the failure must state that the count "
746
+ f"bounds a shape rather than asserting each site is wrong. Got: "
747
+ f"{risen}"
748
+ )
749
+ return 1
750
+
751
+ if "assertion-shape-count" not in {name for name, _ in registry.SCENARIOS}:
752
+ report("assertion-shape-count: the scenario registry does not include it.")
753
+ return 1
754
+ report(
755
+ f"assertion-shape-count scenario passed: {len(measured)} sites, "
756
+ "a bound on a shape and not a count of defects."
757
+ )
758
+ return 0
759
+
760
+
761
+ def unregistered_scenario_functions(modules, scenarios) -> list[str]:
762
+ """Every `validate_*_scenario` function a module defines that the registry does not list.
763
+
764
+ Read per module, since the scenarios live in several (#409); a function
765
+ another module only imports is counted where it is defined.
766
+ """
767
+ registered = {(func.__module__, func.__name__) for _, func in scenarios}
768
+ return sorted(
769
+ f"{module.__name__}.{obj_name}"
770
+ for module in modules
771
+ for obj_name, obj in vars(module).items()
772
+ if callable(obj)
773
+ and obj_name.startswith("validate_")
774
+ and obj_name.endswith("_scenario")
775
+ and getattr(obj, "__module__", None) == module.__name__
776
+ and (module.__name__, obj_name) not in registered
777
+ )
778
+
779
+
780
+ def validation_modules() -> list:
781
+ return [
782
+ importlib.import_module(f"validation.{path.stem}")
783
+ for path in validation_sources()
784
+ if path.parent.name == "validation" and path.stem != "__init__"
785
+ ]
786
+
787
+
788
+ def validate_validation_runner_scenario() -> int:
789
+ if not getattr(registry, "SCENARIOS", None):
790
+ report("validation-runner: the scenario registry is missing.")
791
+ return 1
792
+ names = [name for name, _ in registry.SCENARIOS]
793
+ if len(names) != len(set(names)):
794
+ report("validation-runner: registry names are not unique.")
795
+ return 1
796
+ orphans = unregistered_scenario_functions(validation_modules(), registry.SCENARIOS)
797
+ if orphans:
798
+ report(
799
+ "validation-runner: scenario functions missing from the registry: "
800
+ + ", ".join(orphans)
801
+ )
802
+ return 1
803
+
804
+ package = json.loads((ROOT / "package.json").read_text(encoding="utf-8"))
805
+ test_script = package.get("scripts", {}).get("test", "")
806
+ if (
807
+ "--all" not in test_script
808
+ or "--scenario" in test_script
809
+ or "&&" in test_script
810
+ ):
811
+ report(
812
+ "validation-runner: package.json test must be a single --all "
813
+ "invocation, not a per-scenario chain."
814
+ )
815
+ return 1
816
+ for name in ("README.md", "README.zh-CN.md"):
817
+ readme = (ROOT / name).read_text(encoding="utf-8")
818
+ if "--all" not in readme or "--jobs" not in readme:
819
+ report(f"validation-runner: {name} does not document the parallel runner.")
820
+ return 1
821
+
822
+ # The full gate must actually run somewhere other than one author's machine:
823
+ # a workflow drives the same single entry point on push and pull request,
824
+ # and the release workflow keeps its own tag guard rather than becoming the
825
+ # suite's only runner.
826
+ workflow_path = ROOT / ".github/workflows/test.yml"
827
+ if not workflow_path.is_file():
828
+ report(
829
+ "validation-runner: no .github/workflows/test.yml, so the full gate "
830
+ "runs only in the local pre-push hook."
831
+ )
832
+ return 1
833
+ workflow = workflow_path.read_text(encoding="utf-8")
834
+ for needle in ("npm test", "npm ci", "pull_request", "push:", "ubuntu-latest"):
835
+ if needle not in workflow:
836
+ report(
837
+ "validation-runner: the full-gate workflow does not declare "
838
+ f"{needle!r}."
839
+ )
840
+ report(workflow)
841
+ return 1
842
+ publish = (ROOT / ".github/workflows/publish.yml").read_text(encoding="utf-8")
843
+ if "does not match package.json version" not in publish:
844
+ report(
845
+ "validation-runner: the release workflow lost its tag/version guard."
846
+ )
847
+ return 1
848
+
849
+ # Behavioral: the parallel machinery preserves registry order, keeps a
850
+ # passing scenario's buffered output, and fails loudly on a bad entry.
851
+ ordered = run_scenario_processes(
852
+ ["version-alignment", "definitely-not-a-scenario"], 2
853
+ )
854
+ if [entry[0] for entry in ordered] != [
855
+ "version-alignment",
856
+ "definitely-not-a-scenario",
857
+ ]:
858
+ report("validation-runner: results are not returned in registry order.")
859
+ return 1
860
+ _, ok_code, ok_output = ordered[0]
861
+ _, bad_code, bad_output = ordered[1]
862
+ if ok_code != 0 or "version-alignment scenario passed" not in ok_output:
863
+ report("validation-runner: parallel run lost a passing scenario's output.")
864
+ return 1
865
+ if bad_code == 0 or "unknown validation scenario" not in bad_output:
866
+ report("validation-runner: an unknown scenario did not fail loudly.")
867
+ return 1
868
+
869
+ report("validation-runner scenario passed.")
870
+ return 0
871
+
872
+
873
+ # `process.exit()` discards whatever Node has not flushed, and stdout to a pipe
874
+ # is asynchronous. Whether anything is lost depends only on whether the payload
875
+ # fit the pipe buffer — so at the 64KB default nothing is ever lost, and under
876
+ # the memory pressure that shrinks buffers to a page or two, output is lost
877
+ # silently. Waiting for that condition is not a test; this scenario creates it.
878
+ def validate_output_survives_the_pipe_scenario() -> int:
879
+ label = "output-survives-the-pipe"
880
+ F_SETPIPE_SZ = 1031
881
+ try:
882
+ import fcntl
883
+ import time
884
+ except ImportError:
885
+ return skip_scenario(
886
+ label,
887
+ "fcntl is unavailable, so the pipe buffer cannot be shrunk and the "
888
+ "truncation cannot be forced rather than waited for",
889
+ )
890
+
891
+ def goal_task(acceptance_padding: int) -> str:
892
+ huge = ("Acceptance " + ("A" * acceptance_padding) + " is proven by M1.",)
893
+ return _goal_tasks_file(
894
+ [_goal_task_block(acceptance=huge, strategy="vertical-tdd")]
895
+ )
896
+
897
+ # A task-start result carries the whole compiled capsule, so a long
898
+ # Acceptance makes it larger than the shrunken pipe. (It was `keel project
899
+ # goal` until that command was removed in 5.173.0, #414.)
900
+ goal_args = (
901
+ "gate", "task-start",
902
+ "--change", "sample-change", "--task", "1.1", "--json", "--no-guard",
903
+ )
904
+
905
+ with tempfile.TemporaryDirectory(prefix="keel-pipe-") as raw:
906
+ root = Path(raw)
907
+ repo = root / "repo"
908
+ write_text(repo / "openspec/changes/sample-change/proposal.md", "# P\n")
909
+ write_text(
910
+ repo / "openspec/changes/sample-change/design.md",
911
+ "## Context\n\nfixture\n",
912
+ )
913
+ write_text(
914
+ repo / "openspec/changes/sample-change/specs/demo/spec.md",
915
+ "## ADDED Requirements\n",
916
+ )
917
+ write_text(
918
+ repo / "openspec/changes/sample-change/tasks.md", goal_task(4200)
919
+ )
920
+
921
+ # The reference length: the same invocation with nowhere to lose bytes.
922
+ redirected = run_keel(repo, *goal_args)
923
+ if redirected.returncode != 0:
924
+ report(
925
+ f"{label}: the fixture did not produce a task-start result to "
926
+ f"measure against; keel exited {redirected.returncode}."
927
+ )
928
+ report((redirected.stderr or redirected.stdout).strip()[:400])
929
+ return 1
930
+ expected = redirected.stdout.encode("utf-8")
931
+ if len(expected) <= 4096:
932
+ report(
933
+ f"{label}: the fixture projection is {len(expected)} bytes, "
934
+ "which fits the shrunken pipe, so the condition this scenario "
935
+ "exists to force would not arise."
936
+ )
937
+ return 1
938
+
939
+ read_fd, write_fd = os.pipe()
940
+ try:
941
+ fcntl.fcntl(write_fd, F_SETPIPE_SZ, 4096)
942
+ except OSError as error:
943
+ os.close(read_fd)
944
+ os.close(write_fd)
945
+ return skip_scenario(
946
+ label,
947
+ "this platform refused F_SETPIPE_SZ "
948
+ f"({error}), so the pipe buffer cannot be shrunk",
949
+ )
950
+
951
+ child = subprocess.Popen(
952
+ ["node", str(ROOT / "bin" / "keel.js"), *goal_args],
953
+ cwd=repo,
954
+ stdout=write_fd,
955
+ stderr=subprocess.DEVNULL,
956
+ )
957
+ os.close(write_fd)
958
+ # Nothing is read for a moment, so the buffer fills and the rest of the
959
+ # write is left pending. A child that discards its pending write on exit
960
+ # is finished by now, having lost everything past the buffer; a child
961
+ # that lets the event loop drain is blocked on the write and finishes
962
+ # once the loop below starts reading. Reading immediately would drain
963
+ # fast enough to let the broken form through, which is the race this
964
+ # scenario exists to remove — so the pause is the forcing condition, and
965
+ # the child is waited for after the read rather than before it.
966
+ time.sleep(1.0)
967
+ received = b""
968
+ while True:
969
+ chunk = os.read(read_fd, 65536)
970
+ if not chunk:
971
+ break
972
+ received += chunk
973
+ os.close(read_fd)
974
+ child.wait(timeout=60)
975
+
976
+ if received != expected:
977
+ report(
978
+ f"{label}: {len(received)} of {len(expected)} bytes survived a "
979
+ "4096-byte pipe. Output written for a program to read is being "
980
+ "discarded at process exit, with no error and no exit-code "
981
+ "change — the consumer receives a valid prefix of an "
982
+ "incomplete document."
983
+ )
984
+ return 1
985
+ try:
986
+ json.loads(received.decode("utf-8"))
987
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
988
+ report(f"{label}: the payload that survived does not parse: {error}.")
989
+ return 1
990
+
991
+ # D3: the one behavioral difference a reader would worry about.
992
+ ok = run_keel(repo, "--version")
993
+ if ok.returncode != 0:
994
+ report(f"{label}: a successful command returned {ok.returncode}.")
995
+ return 1
996
+ refused = run_keel(
997
+ repo, "gate", "task-start", "--change", "no-such-change", "--task", "1.1"
998
+ )
999
+ if refused.returncode != 1:
1000
+ report(
1001
+ f"{label}: a refused gate returned {refused.returncode}, not 1."
1002
+ )
1003
+ return 1
1004
+ invalid = run_keel(repo, "--not-a-flag")
1005
+ if invalid.returncode != 2:
1006
+ report(
1007
+ f"{label}: an invalid argument returned {invalid.returncode}, "
1008
+ "not 2."
1009
+ )
1010
+ return 1
1011
+
1012
+ report(f"{label} scenario passed.")
1013
+ return 0
1014
+
1015
+
1016
+ # A scenario name, as the registry spells one. Two registered names carry no
1017
+ # hyphen — `cli` and `uninstall` — so requiring one would leave exactly those
1018
+ # two unchecked, and allowing single words was measured to add no false
1019
+ # positive.
1020
+ AUTHORED_SCENARIO_NAME = re.compile(r"^[a-z0-9][a-z0-9-]*$")
1021
+
1022
+
1023
+ # The two forms a scenario reference is read in. `--scenario` is the invocation
1024
+ # itself and needs no context. The other is keyed on the *assertion* rather than
1025
+ # on the token, because kebab-case is this project's spelling for gate stages,
1026
+ # diagnostic codes, skills, capabilities, and hook events too: reading every
1027
+ # such token as a scenario name flags 22 of the 55 in the archive. Keying on
1028
+ # "stays green" flags one, and that one is a real unregistered name.
1029
+ AUTHORED_SCENARIO_FLAG = re.compile(r"--scenario\s+`?([A-Za-z0-9][\w.-]*)`?")
1030
+
1031
+
1032
+ AUTHORED_SCENARIO_STAYS_GREEN = re.compile(r"stays? green", re.IGNORECASE)
1033
+
1034
+
1035
+ AUTHORED_CHECK_LINE = re.compile(r"^-\s*M\d+\b")
1036
+
1037
+
1038
+ AUTHORED_VERIFY_BLOCK = re.compile(r"^-\s*(?:Verify|Commands):\s*$")
1039
+
1040
+
1041
+ AUTHORED_CAPSULE_BLOCK = re.compile(r"^-\s*[A-Z][A-Za-z ]*:\s*$")
1042
+
1043
+
1044
+ AUTHORED_INLINE_CODE = re.compile(r"`([^`\n]+)`")
1045
+
1046
+
1047
+ AUTHORED_SCENARIO_FORMS = (
1048
+ "A scenario reference is read in two forms: a name after `--scenario`, and "
1049
+ "a backticked lowercase token in a `Verify` M<n> check asserting that "
1050
+ "something stays green. Other backticked vocabulary in a check is not read "
1051
+ "as a scenario name."
1052
+ )
1053
+
1054
+
1055
+ def unregistered_scenario_references(
1056
+ text: str, registered: set[str]
1057
+ ) -> list[tuple[int, str, str]]:
1058
+ """Scenario names a task contract declares that the registry does not hold.
1059
+
1060
+ Returns `(line, name, form)` for each, 1-indexed, in file order. The `form`
1061
+ is which of the two recognized shapes matched, so a report can say why the
1062
+ token was read as a scenario name at all.
1063
+ """
1064
+ problems: list[tuple[int, str, str]] = []
1065
+ in_verify = False
1066
+ for line_number, line in enumerate(text.splitlines(), start=1):
1067
+ stripped = line.strip()
1068
+ # A capsule block heading ends the previous block, so `Evidence` and
1069
+ # `Stop Rules` leave the Verify block rather than extending it. Evidence
1070
+ # is written after the run, when execution has already answered the
1071
+ # question this check exists to answer earlier.
1072
+ if AUTHORED_CAPSULE_BLOCK.match(stripped):
1073
+ in_verify = bool(AUTHORED_VERIFY_BLOCK.match(stripped))
1074
+ for match in AUTHORED_SCENARIO_FLAG.finditer(line):
1075
+ name = match.group(1)
1076
+ if name not in registered:
1077
+ problems.append((line_number, name, "--scenario"))
1078
+ if not in_verify or not AUTHORED_CHECK_LINE.match(stripped):
1079
+ continue
1080
+ if not AUTHORED_SCENARIO_STAYS_GREEN.search(line):
1081
+ continue
1082
+ for token in AUTHORED_INLINE_CODE.findall(line):
1083
+ if not AUTHORED_SCENARIO_NAME.match(token):
1084
+ continue
1085
+ if token not in registered:
1086
+ problems.append((line_number, token, "stays green"))
1087
+ return problems
1088
+
1089
+
1090
+ def active_change_tasks(repo: Path) -> list[Path]:
1091
+ """Every active change's tasks.md. Archived changes are deliberately absent.
1092
+
1093
+ An archived task records what was true when it ran; a scenario renamed
1094
+ afterwards does not make that record wrong, and turning history red for it
1095
+ tells a reader nothing they can act on.
1096
+ """
1097
+ changes = repo / "openspec" / "changes"
1098
+ archive = changes / "archive"
1099
+ # The walk finds archived changes and the filter is what drops them, rather
1100
+ # than a glob depth that happens not to reach them. A depth that excludes by
1101
+ # accident passes every test aimed at the exclusion, including one aimed at
1102
+ # it on purpose.
1103
+ return sorted(
1104
+ path for path in changes.rglob("tasks.md") if archive not in path.parents
1105
+ )
1106
+
1107
+
1108
+ def validate_authored_scenario_names_scenario() -> int:
1109
+ """Issue #51: a check whose scenario name is not registered cannot run.
1110
+
1111
+ Three of the four authored contracts #51 records named something that did
1112
+ not exist, two of them scenario names, both written as an `M5 (regression)`
1113
+ check asserting that named scenarios stay green, and both found only when
1114
+ the check was executed. A fifth, unrecorded there, is
1115
+ `2026-08-01-the-name-is-not-the-thing/tasks.md:132`, which declares
1116
+ `tasks-template-validates` — a name `git log -S` finds at no commit — and
1117
+ records that check as passing.
1118
+
1119
+ The assertions live on synthetic content with a known name set, because the
1120
+ live scan reads whatever the working tree holds and is normally empty: a
1121
+ change is archived when it closes. The temp-repository half is the positive
1122
+ control for the whole path, so a run that passes because the file selection
1123
+ silently found nothing is distinguishable from one that verified something.
1124
+ """
1125
+ registered = {name for name, _ in registry.SCENARIOS}
1126
+ known = {"core-gates", "cli"}
1127
+ authored = (
1128
+ "# Tasks\n"
1129
+ "\n"
1130
+ "- [ ] 1.1 Do the thing\n"
1131
+ " - Touch:\n"
1132
+ " - src/thing.js\n"
1133
+ " - Verify:\n"
1134
+ " - Strategy: vertical-tdd\n"
1135
+ " - M1: `node scripts/run_python.js scripts/validate_plugin.py "
1136
+ "--scenario gate-diagnostics` passes\n"
1137
+ " - M2 (regression): `core-gates` and `target-surface-doctor` stay "
1138
+ "green\n"
1139
+ " - M3 (regression): `task-start`, `keel-review-checklist`, "
1140
+ "`contract-drift`, `subagent-stop`, and `keel-task-capsule` are "
1141
+ "unchanged\n"
1142
+ " - M4: `cli` and "
1143
+ "`node scripts/run_python.js scripts/validate_plugin.py "
1144
+ "--scenario core-gates` stay green\n"
1145
+ " - Evidence:\n"
1146
+ " - M2: `target-surface-doctor` stays green\n"
1147
+ )
1148
+ found = unregistered_scenario_references(authored, known)
1149
+ expected = [
1150
+ (8, "gate-diagnostics", "--scenario"),
1151
+ (9, "target-surface-doctor", "stays green"),
1152
+ ]
1153
+ if found != expected:
1154
+ report(
1155
+ "authored-scenario-names-are-registered: the recognized forms did "
1156
+ f"not report what they must. expected {expected}, found {found}."
1157
+ )
1158
+ report(AUTHORED_SCENARIO_FORMS)
1159
+ return 1
1160
+
1161
+ # Which files are read is a separate question from what is read out of
1162
+ # them, and it is the half that can silently resolve to nothing. The
1163
+ # planted reference is the positive control for the whole path: an
1164
+ # extractor that stopped reporting, or a selection that stopped finding,
1165
+ # both fail here rather than passing on an empty scan.
1166
+ with tempfile.TemporaryDirectory(prefix="keel-authored-names-") as raw:
1167
+ repo = Path(raw)
1168
+ write_text(repo / "openspec/changes/live/tasks.md", authored)
1169
+ write_text(repo / "openspec/changes/archive/old/tasks.md", authored)
1170
+ selected = active_change_tasks(repo)
1171
+ if selected != [repo / "openspec/changes/live/tasks.md"]:
1172
+ report(
1173
+ "authored-scenario-names-are-registered: the active change "
1174
+ "selection is wrong. An archived tasks.md must not be scanned "
1175
+ "and an active one must be. "
1176
+ f"selected {[str(path) for path in selected]}."
1177
+ )
1178
+ return 1
1179
+ control = [
1180
+ (path, unregistered_scenario_references(
1181
+ path.read_text(encoding="utf-8"), known
1182
+ ))
1183
+ for path in selected
1184
+ ]
1185
+ if [problems for _, problems in control] != [expected]:
1186
+ report(
1187
+ "authored-scenario-names-are-registered: a planted reference "
1188
+ "in an active change was not reported end to end, so a clean "
1189
+ "run over the real tree would prove nothing. "
1190
+ f"found {control}."
1191
+ )
1192
+ return 1
1193
+
1194
+ for path in active_change_tasks(ROOT):
1195
+ problems = unregistered_scenario_references(
1196
+ path.read_text(encoding="utf-8"), registered
1197
+ )
1198
+ if not problems:
1199
+ continue
1200
+ relative = path.relative_to(ROOT).as_posix()
1201
+ for line_number, name, form in problems:
1202
+ report(
1203
+ f"authored-scenario-names-are-registered: {relative}:"
1204
+ f"{line_number} names `{name}` after {form}, and no scenario by "
1205
+ "that name is registered, so the check that names it cannot run."
1206
+ )
1207
+ report(AUTHORED_SCENARIO_FORMS)
1208
+ return 1
1209
+
1210
+ if "authored-scenario-names-are-registered" not in {
1211
+ name for name, _ in registry.SCENARIOS
1212
+ }:
1213
+ report(
1214
+ "authored-scenario-names-are-registered: the scenario registry "
1215
+ "does not include it."
1216
+ )
1217
+ return 1
1218
+ report("authored-scenario-names-are-registered scenario passed.")
1219
+ return 0
1220
+
1221
+
1222
+ def validate_the_routing_rule_reaches_the_decision_scenario() -> int:
1223
+ """Issue #131: routing is the one durable rule with nowhere to reach the agent.
1224
+
1225
+ The block `keel --init` installs is five bullets and says nothing about Full
1226
+ or Lite; routing has no implementation at all, only four lines of prose in
1227
+ Keel's own README. So the first decision of every session is taken without
1228
+ the rule, and a project whose risk does not track diff size has no way to say
1229
+ so. The declaration is one-directional on purpose: it can raise the process
1230
+ floor and there is no key that lowers it.
1231
+ """
1232
+ label = "the-routing-rule-reaches-the-decision"
1233
+ declared = "results/experiments.jsonl"
1234
+ reason = "append-only; a one-field diff is not revertible"
1235
+
1236
+ with tempfile.TemporaryDirectory(prefix="keel-routing-") as raw:
1237
+ root = Path(raw)
1238
+
1239
+ def fixture(name: str, body: str | None) -> Path:
1240
+ repo = root / name
1241
+ repo.mkdir()
1242
+ if body is not None:
1243
+ (repo / "keel").mkdir()
1244
+ (repo / "keel" / "config.yaml").write_text(body, encoding="utf-8")
1245
+ return repo
1246
+
1247
+ def context(repo: Path) -> str:
1248
+ return run_keel(repo, "context").stdout
1249
+
1250
+ # M1 — a declared path is reported with the reason it carries, and the
1251
+ # projection is otherwise the one it would have printed anyway.
1252
+ plain = fixture("plain", "fast_check: echo plain\n")
1253
+ declaring = fixture(
1254
+ "declaring",
1255
+ f"fast_check: echo plain\nfull_mode_paths:\n - {declared}: {reason}\n",
1256
+ )
1257
+ out = context(declaring)
1258
+ if declared not in out:
1259
+ report(
1260
+ f"{label}: no routing line — a repository that declared "
1261
+ f"{declared!r} is told nothing about it at the one moment the "
1262
+ "routing decision is made."
1263
+ )
1264
+ report(out)
1265
+ return 1
1266
+ if reason not in out:
1267
+ report(
1268
+ f"{label}: the declared path is reported without its reason, so "
1269
+ "the agent learns the file is special and not what makes it so."
1270
+ )
1271
+ report(out)
1272
+ return 1
1273
+ # D5 — the fixture creates no file at that path, on purpose.
1274
+ if (declaring / declared).exists():
1275
+ report(f"{label}: the fixture created the declared path; D5 is untested.")
1276
+ return 1
1277
+ baseline = [
1278
+ line
1279
+ for line in context(plain).splitlines()
1280
+ if line.startswith(("Keel context:", "Next action:"))
1281
+ ]
1282
+ moved = [
1283
+ line
1284
+ for line in out.splitlines()
1285
+ if line.startswith(("Keel context:", "Next action:"))
1286
+ ]
1287
+ if baseline != moved:
1288
+ report(
1289
+ f"{label}: the declaration moved the projection's status or next "
1290
+ f"action; {baseline!r} became {moved!r}."
1291
+ )
1292
+ return 1
1293
+
1294
+ # M2 — an entry with no reason is not a declaration.
1295
+ bare = fixture(
1296
+ "bare", f"full_mode_paths:\n - {declared}\n"
1297
+ )
1298
+ out = context(bare)
1299
+ # Behavior before message: what D2 forbids is the entry counting as a
1300
+ # declaration, and whether it is also reported well comes after that.
1301
+ routing_lines = [
1302
+ line for line in out.splitlines() if line.startswith("Routing:")
1303
+ ]
1304
+ if any(declared in line for line in routing_lines):
1305
+ report(
1306
+ f"{label}: the reason-less entry was read as a declaration; "
1307
+ f"{routing_lines!r}"
1308
+ )
1309
+ return 1
1310
+ if "full_mode_paths" not in out or declared not in out:
1311
+ report(
1312
+ f"{label}: an entry with no reason was dropped silently; the "
1313
+ "author is left believing they declared what they typed."
1314
+ )
1315
+ report(out)
1316
+ return 1
1317
+ if "<path>: <reason>" not in out:
1318
+ report(
1319
+ f"{label}: the refusal does not name the form the entry needs."
1320
+ )
1321
+ report(out)
1322
+ return 1
1323
+
1324
+ # 1.2 — a declaration Keel cannot fully read raises the floor rather
1325
+ # than dropping it. `authorize:` and `triage:` fail closed and closed
1326
+ # means *less proceeds without a human*; for a declaration whose purpose
1327
+ # is to add process, the same principle is more Full mode, not less.
1328
+ mixed = fixture(
1329
+ "mixed",
1330
+ f"full_mode_paths:\n - {declared}: {reason}\n - src/lib.js\n",
1331
+ )
1332
+ out = context(mixed)
1333
+ routing_lines = [
1334
+ line for line in out.splitlines() if line.startswith("Routing:")
1335
+ ]
1336
+ if not any("every change" in line.lower() for line in routing_lines):
1337
+ report(
1338
+ f"{label}: routes only the entries it could read — a "
1339
+ "declaration Keel half-read was treated as the policy, so a "
1340
+ "typo silently lowers the process floor. {0!r}".format(
1341
+ routing_lines
1342
+ )
1343
+ )
1344
+ report(out)
1345
+ return 1
1346
+ if any(declared in line for line in routing_lines):
1347
+ report(
1348
+ f"{label}: the readable entry was reported as the declared set "
1349
+ "beside an unreadable one, so half a declaration acted as a "
1350
+ f"whole one; {routing_lines!r}"
1351
+ )
1352
+ return 1
1353
+ if "src/lib.js" not in out:
1354
+ report(f"{label}: the unreadable entry is not named, so the state is not attributable.")
1355
+ report(out)
1356
+ return 1
1357
+ doctor = run_keel(mixed, "--doctor").stdout
1358
+ if "full_mode_paths: failed" not in doctor or "src/lib.js" not in doctor:
1359
+ report(
1360
+ f"{label}: the doctor does not report the declaration as failed "
1361
+ "and name the entry, so it reports health the projection "
1362
+ "contradicts."
1363
+ )
1364
+ report(doctor)
1365
+ return 1
1366
+ # The conservative branch is reached by an unreadable declaration, not
1367
+ # by any declaration at all.
1368
+ if "every change" in context(declaring).lower():
1369
+ report(
1370
+ f"{label}: a readable declaration reported the "
1371
+ "everything-routes-Full state."
1372
+ )
1373
+ return 1
1374
+
1375
+ # M3 — the common case pays nothing.
1376
+ for name, body in (
1377
+ ("absent", None),
1378
+ ("blockless", "fast_check: echo blockless\n"),
1379
+ ("empty", "fast_check: echo empty\nfull_mode_paths:\n"),
1380
+ ):
1381
+ repo = fixture(name, body)
1382
+ out = context(repo)
1383
+ if "Routing:" in out or "full_mode_paths" in out:
1384
+ report(
1385
+ f"{label}: the {name} repository was told about a routing "
1386
+ "declaration it does not have."
1387
+ )
1388
+ report(out)
1389
+ return 1
1390
+
1391
+ # 1.3 — the rule itself, in the artifact `keel --init` installs. Asserted on
1392
+ # the shipped block rather than on a fixture: this is the file a consuming
1393
+ # repository receives, and its two budgets are what keep it resident.
1394
+ bootstrap_path = ROOT / "assets/bootstrap/AGENTS.md"
1395
+ bootstrap = bootstrap_path.read_text(encoding="utf-8")
1396
+ for needle, why in (
1397
+ ("Full", "the block must name the complete flow"),
1398
+ ("Lite", "the block must name the local flow"),
1399
+ ("100 lines", "the block must carry the size heuristic it is correcting"),
1400
+ ("full_mode_paths", "the block must say a project can declare exceptions"),
1401
+ ):
1402
+ if needle not in bootstrap:
1403
+ report(
1404
+ f"{label}: bootstrap states no routing rule — {why}; "
1405
+ f"{needle!r} is absent. Routing is the first decision of a "
1406
+ "session and the block a consuming repository receives is "
1407
+ "where it has to arrive."
1408
+ )
1409
+ return 1
1410
+ # Both budgets. The line one runs the check the suite enforces rather than
1411
+ # counting here; the byte one is asserted at its raised value.
1412
+ budget_errors: list[str] = []
1413
+ validate_resident_blocks(budget_errors)
1414
+ if budget_errors:
1415
+ report(f"{label}: the routing line broke the resident block line budget.")
1416
+ for error in budget_errors:
1417
+ report(f"- {error}")
1418
+ return 1
1419
+ body = bootstrap.split("<!-- keel:start", 1)[1].split("<!-- keel:end -->", 1)[0]
1420
+ block_bytes = len(("<!-- keel:start" + body + "<!-- keel:end -->").encode())
1421
+ if block_bytes >= BOOTSTRAP_BLOCK_BYTE_BUDGET:
1422
+ report(
1423
+ f"{label}: the block is {block_bytes} bytes, over its "
1424
+ f"{BOOTSTRAP_BLOCK_BYTE_BUDGET}-byte budget."
1425
+ )
1426
+ return 1
1427
+
1428
+ # The raise is only authorized because it is loud: a larger constant with no
1429
+ # argument beside it is exactly the quiet drift the cap was built to stop,
1430
+ # and it would pass every check above. So both assertions of the cap must
1431
+ # carry the reason it moved, not just the number.
1432
+ for marker in ("thin-native-install bootstrap block", "over its"):
1433
+ if validation_source_with(marker) is None:
1434
+ report(f"{label}: the byte-cap assertion {marker!r} is gone.")
1435
+ return 1
1436
+ # The rationale for a constant lives in the comment block above it, so that
1437
+ # is where it is read from — walking back over the contiguous comment lines
1438
+ # rather than guessing a window — in whichever module defines it (#409).
1439
+ defined = validation_source_with("\nBOOTSTRAP_BLOCK_BYTE_BUDGET =")
1440
+ if defined is None:
1441
+ report(f"{label}: no validation module defines BOOTSTRAP_BLOCK_BYTE_BUDGET.")
1442
+ return 1
1443
+ lines = defined[1].splitlines()
1444
+ at = next(
1445
+ i for i, line in enumerate(lines)
1446
+ if line.startswith("BOOTSTRAP_BLOCK_BYTE_BUDGET =")
1447
+ )
1448
+ top = at
1449
+ while top > 0 and lines[top - 1].startswith("#"):
1450
+ top -= 1
1451
+ rationale = "\n".join(lines[top:at + 1])
1452
+ for needle in ("routing", "not quietly"):
1453
+ if needle not in rationale:
1454
+ report(
1455
+ f"{label}: names the new cap without the reason it moved; "
1456
+ f"{needle!r} is absent from the constant's own rationale. A "
1457
+ "reader inheriting a larger number and no argument is the drift "
1458
+ "the cap exists to prevent."
1459
+ )
1460
+ return 1
1461
+
1462
+ if label not in {name for name, _ in registry.SCENARIOS}:
1463
+ report(f"{label}: the scenario registry does not include it.")
1464
+ return 1
1465
+ report(f"{label} scenario passed.")
1466
+ return 0