@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 @@
1
+ """Keel validation modules (#409)."""
@@ -0,0 +1,509 @@
1
+ """Keel validation: baseline (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
+ LEGACY_PROFILE_SKILLS,
26
+ PACKAGE_VERSION,
27
+ ROOT,
28
+ )
29
+
30
+
31
+ REQUIRED_DIRECTORIES = [
32
+ "bin",
33
+ "src",
34
+ "src/core",
35
+ "src/skills",
36
+ "scripts",
37
+ "plugins/keel",
38
+ "plugins/keel/skills",
39
+ "assets/bootstrap",
40
+ "assets/openspec",
41
+ ]
42
+
43
+
44
+ REQUIRED_SCRIPTS = [
45
+ "bin/keel.js",
46
+ "scripts/install_to_repo.py",
47
+ "scripts/run_python.js",
48
+ "scripts/validate_plugin.py",
49
+ ]
50
+
51
+
52
+ CORE_KEEL_SKILLS = {
53
+ "keel-align-expectations",
54
+ "keel-debug-failure",
55
+ "keel-handoff",
56
+ "keel-review-checklist",
57
+ "keel-tdd-or-test-first",
58
+ }
59
+
60
+
61
+ TEMPLATE_REQUIREMENTS: list[dict] = []
62
+
63
+
64
+ def validate_manifest(errors: list[str]) -> None:
65
+ package_path = ROOT / "package.json"
66
+ try:
67
+ package_version = json.loads(
68
+ package_path.read_text(encoding="utf-8")
69
+ ).get("version")
70
+ except (FileNotFoundError, json.JSONDecodeError):
71
+ package_version = None
72
+
73
+ if (ROOT / "plugin.json").exists():
74
+ errors.append(
75
+ "legacy custom plugin.json must be retired in the Keel 4.0.0 native "
76
+ "plugin release"
77
+ )
78
+
79
+ for runtime in (".codex-plugin", ".claude-plugin"):
80
+ manifest_path = ROOT / "plugins" / "keel" / runtime / "plugin.json"
81
+ if not manifest_path.is_file():
82
+ errors.append(
83
+ f"missing native plugin manifest: plugins/keel/{runtime}/plugin.json"
84
+ )
85
+ continue
86
+ try:
87
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
88
+ except json.JSONDecodeError as exc:
89
+ errors.append(
90
+ f"native plugin manifest is not valid JSON: {runtime}: {exc}"
91
+ )
92
+ continue
93
+ if manifest.get("name") != "keel":
94
+ errors.append(
95
+ f"native plugin manifest {runtime} must declare name keel"
96
+ )
97
+ version = manifest.get("version")
98
+ if package_version is not None and version != package_version:
99
+ errors.append(
100
+ f"native plugin manifest {runtime} version {version!r} must equal "
101
+ f"package version {package_version!r}"
102
+ )
103
+
104
+ skills_root = ROOT / "plugins" / "keel" / "skills"
105
+ if not skills_root.is_dir():
106
+ errors.append("plugins/keel/skills must hold the canonical skill set")
107
+ return
108
+ packaged = {path.name for path in skills_root.iterdir() if path.is_dir()}
109
+ missing = sorted(set(CORE_KEEL_SKILLS) - packaged)
110
+ if missing:
111
+ errors.append(
112
+ "plugins/keel/skills missing canonical skills: " + ", ".join(missing)
113
+ )
114
+ for legacy_skill in LEGACY_PROFILE_SKILLS:
115
+ if legacy_skill in packaged:
116
+ errors.append(
117
+ f"plugins/keel/skills must not package legacy profile skill "
118
+ f"{legacy_skill!r}"
119
+ )
120
+
121
+
122
+ def validate_npm_package(errors: list[str]) -> None:
123
+ package_path = ROOT / "package.json"
124
+ if not package_path.is_file():
125
+ errors.append("missing package.json")
126
+ return
127
+
128
+ try:
129
+ package = json.loads(package_path.read_text(encoding="utf-8"))
130
+ except json.JSONDecodeError as exc:
131
+ errors.append(f"package.json is not valid JSON: {exc}")
132
+ return
133
+
134
+ if package.get("name") != "@christang/keel":
135
+ errors.append("package.json must declare npm package name @christang/keel")
136
+ if package.get("version") != PACKAGE_VERSION:
137
+ errors.append(f"package.json must declare version {PACKAGE_VERSION}")
138
+
139
+ bin_map = package.get("bin")
140
+ if not isinstance(bin_map, dict) or bin_map.get("keel") != "bin/keel.js":
141
+ errors.append("package.json must expose bin keel -> bin/keel.js")
142
+
143
+ scripts = package.get("scripts")
144
+ if not isinstance(scripts, dict):
145
+ errors.append("package.json must declare npm scripts")
146
+ else:
147
+ for script_name in ("validate", "test"):
148
+ script_value = scripts.get(script_name)
149
+ if not isinstance(script_value, str):
150
+ errors.append(f"package.json missing npm script: {script_name}")
151
+ continue
152
+ if "scripts/run_python.js" not in script_value:
153
+ errors.append(
154
+ f"package.json script {script_name!r} must use scripts/run_python.js"
155
+ )
156
+ if "python scripts/" in script_value:
157
+ errors.append(
158
+ f"package.json script {script_name!r} must not depend on bare python"
159
+ )
160
+
161
+ dependencies = package.get("dependencies")
162
+ if (
163
+ not isinstance(dependencies, dict)
164
+ or dependencies.get("@fission-ai/openspec") != "^1.4.1"
165
+ ):
166
+ errors.append("package.json must depend on @fission-ai/openspec ^1.4.1")
167
+
168
+ files = package.get("files")
169
+ if not isinstance(files, list):
170
+ errors.append("package.json must declare files for npm packaging")
171
+ else:
172
+ for required in ("bin/", "scripts/", "assets/", "README.md", "plugins/"):
173
+ if required not in files:
174
+ errors.append(f"package.json files missing packaged path: {required}")
175
+ for forbidden in ("dist/", "plugin.json"):
176
+ if forbidden in files:
177
+ errors.append(
178
+ "package.json files must not ship retired custom distribution: "
179
+ f"{forbidden}"
180
+ )
181
+
182
+ cli_path = ROOT / "bin" / "keel.js"
183
+ if not cli_path.is_file():
184
+ errors.append("missing npm CLI entrypoint: bin/keel.js")
185
+ return
186
+
187
+ cli = cli_path.read_text(encoding="utf-8")
188
+ for required in (
189
+ "#!/usr/bin/env node",
190
+ "--init",
191
+ "--install",
192
+ "--clear",
193
+ "--uninstall",
194
+ "--update",
195
+ "--check",
196
+ "--doctor",
197
+ "capabilities",
198
+ "gate",
199
+ "lenses",
200
+ "--profile",
201
+ "--version",
202
+ "--help",
203
+ "--source",
204
+ "global keel CLI",
205
+ "DEFAULT_UPDATE_SOURCE",
206
+ "KEEL_PYTHON",
207
+ "findOpenSpecCommand",
208
+ ):
209
+ if required not in cli:
210
+ errors.append(f"bin/keel.js missing required CLI support: {required}")
211
+
212
+
213
+ # Path expressions rooted at a tree the retirement check above requires to be
214
+ # absent. `src/core` and `src/skills` are live, so only the retired `src`
215
+ # children are listed.
216
+ # Keel subcommands that write. A scenario may point read-only ones at the
217
+ # repository root; these need a fixture.
218
+ MUTATING_KEEL_COMMANDS = (
219
+ "--install",
220
+ "--init",
221
+ "--uninstall",
222
+ "--clear",
223
+ "--update",
224
+ "--with-git-hooks",
225
+ )
226
+
227
+
228
+ RETIRED_PATH_EXPRESSIONS = (
229
+ r'ROOT\s*/\s*"dist"',
230
+ r'ROOT\s*/\s*"src"\s*/\s*"assets"',
231
+ r'ROOT\s*/\s*"src"\s*/\s*"hooks"',
232
+ r'ROOT\s*/\s*"src"\s*/\s*"adapters"',
233
+ )
234
+
235
+
236
+ def runner_sources() -> list[Path]:
237
+ """The runner's files under this module's ROOT: the entry point and every module (#409)."""
238
+ return [ROOT / "scripts/validate_plugin.py", *sorted((ROOT / "scripts/validation").glob("*.py"))]
239
+
240
+
241
+ def validate_paths(errors: list[str]) -> None:
242
+ for directory in REQUIRED_DIRECTORIES:
243
+ if not (ROOT / directory).is_dir():
244
+ errors.append(f"missing directory: {directory}")
245
+
246
+ for script in REQUIRED_SCRIPTS:
247
+ if not (ROOT / script).is_file():
248
+ errors.append(f"missing script entrypoint: {script}")
249
+
250
+ for root_label, skills_root in (
251
+ ("source", ROOT / "src" / "skills"),
252
+ ("plugin", ROOT / "plugins" / "keel" / "skills"),
253
+ ):
254
+ if not skills_root.is_dir():
255
+ continue
256
+ for skill_doc in sorted(skills_root.glob("*/SKILL.md")):
257
+ name = skill_doc.parent.name
258
+ content = skill_doc.read_text(encoding="utf-8")
259
+ if not re.search(
260
+ rf"^name:\s*{re.escape(name)}\s*$", content, re.MULTILINE
261
+ ):
262
+ errors.append(
263
+ "skill frontmatter name must match folder key "
264
+ f"{name!r} ({root_label}): "
265
+ f"{skill_doc.relative_to(ROOT).as_posix()}"
266
+ )
267
+
268
+ for retired in ("dist", "plugin.json", "src/adapters", "src/hooks"):
269
+ if (ROOT / retired).exists():
270
+ errors.append(
271
+ f"retired custom distribution path must be removed: {retired}"
272
+ )
273
+
274
+ # Every file of the runner — the entry point and each module under
275
+ # scripts/validation/ — since a scan of one file would pass over whatever
276
+ # moved out of it (#409).
277
+ validator_sources = [
278
+ (path.relative_to(ROOT).as_posix(), path.read_text(encoding="utf-8"))
279
+ for path in runner_sources()
280
+ ]
281
+
282
+ # A scenario that writes to the repository it validates can satisfy the very
283
+ # condition another check asserts, and a check whose input its own run
284
+ # produces cannot fail. Reads against ROOT are fine and common; writes are
285
+ # not. Keyed on the mutating subcommand rather than on ROOT itself, so
286
+ # `--version`, `--doctor`, and the gates stay legal.
287
+ for relative, validator_source in validator_sources:
288
+ for line_number, line in enumerate(validator_source.splitlines(), start=1):
289
+ invocation = re.search(r"run_(?:keel|install)\(\s*ROOT\s*,([^)]*)", line)
290
+ if not invocation:
291
+ continue
292
+ if any(
293
+ re.search(rf'"{command}"', invocation.group(1))
294
+ for command in MUTATING_KEEL_COMMANDS
295
+ ):
296
+ errors.append(
297
+ "a scenario must not run a mutating Keel command against the "
298
+ "repository it validates; build a fixture instead: "
299
+ f"{relative}:{line_number}: {line.strip()}"
300
+ )
301
+
302
+ # Every Keel marker that carries a version is a shipped claim about which
303
+ # version this is. Derive the set from the markers that exist rather than a
304
+ # fixed list, because a fixed list is the next thing to fall behind — which
305
+ # is exactly how the `.codex/` overlays sat four versions back unnoticed.
306
+ for marker_file in sorted(ROOT.rglob("*")):
307
+ if not marker_file.is_file() or not marker_file.suffix in (".md", ".json"):
308
+ continue
309
+ relative = marker_file.relative_to(ROOT).as_posix()
310
+ if relative.startswith(("node_modules/", "openspec/changes/archive/", "keel/archive/")):
311
+ continue
312
+ try:
313
+ text = marker_file.read_text(encoding="utf-8")
314
+ except (UnicodeDecodeError, OSError):
315
+ continue
316
+ for found in re.findall(r"keel:[a-z-]+(?::end)?\s+version=([0-9][^\s>]*)", text):
317
+ if found != PACKAGE_VERSION:
318
+ errors.append(
319
+ "shipped version marker disagrees with the package version "
320
+ f"{PACKAGE_VERSION}: {relative} says {found}"
321
+ )
322
+
323
+ # Asserting the trees are gone is not enough: a check that still resolves a
324
+ # path into one of them can only ever find nothing, and rglob over a missing
325
+ # directory yields no error, so the check reports success forever. Naming a
326
+ # retired tree in a string literal is fine — that is how the checks above
327
+ # state what must not exist; building a Path into one is not.
328
+ for relative, validator_source in validator_sources:
329
+ for line_number, line in enumerate(validator_source.splitlines(), start=1):
330
+ if any(re.search(pattern, line) for pattern in RETIRED_PATH_EXPRESSIONS):
331
+ errors.append(
332
+ "validator resolves a path under a retired distribution tree, "
333
+ "so the check it feeds can only iterate nothing: "
334
+ f"{relative}:{line_number}: {line.strip()}"
335
+ )
336
+
337
+
338
+ def validate_templates(errors: list[str]) -> None:
339
+ for template in TEMPLATE_REQUIREMENTS:
340
+ path = ROOT / template["path"]
341
+ if not path.is_file():
342
+ errors.append(f"{template['name']} is missing: {template['path']}")
343
+ continue
344
+
345
+ content = path.read_text(encoding="utf-8")
346
+ marker = template.get("marker")
347
+ if marker is not None and marker not in content:
348
+ errors.append(f"{template['name']} missing marker: {marker}")
349
+ for required in template["required"]:
350
+ if required not in content:
351
+ errors.append(f"{template['name']} missing required section: {required}")
352
+ for forbidden in template.get("forbidden", []):
353
+ if forbidden in content:
354
+ errors.append(
355
+ f"{template['name']} includes forbidden content: {forbidden}"
356
+ )
357
+
358
+ # What actually ships is whatever package.json declares, so derive the roots
359
+ # from there rather than naming a tree that can retire out from under the
360
+ # check the way `src/assets` and `dist` did.
361
+ packaged_roots = [
362
+ ROOT / entry
363
+ for entry in json.loads(
364
+ (ROOT / "package.json").read_text(encoding="utf-8")
365
+ ).get("files", [])
366
+ if (ROOT / entry).is_dir()
367
+ ]
368
+
369
+ active_task_placeholders = [
370
+ path.relative_to(ROOT).as_posix()
371
+ for base in packaged_roots
372
+ for path in base.rglob("keel/TASK.md")
373
+ ]
374
+ if active_task_placeholders:
375
+ errors.append(
376
+ "package must not include an active keel/TASK.md placeholder: "
377
+ + ", ".join(active_task_placeholders)
378
+ )
379
+
380
+ backlog_assets = [
381
+ path.relative_to(ROOT).as_posix()
382
+ for base in packaged_roots
383
+ for path in base.rglob("keel/backlog/*")
384
+ ]
385
+ if backlog_assets:
386
+ errors.append(
387
+ "package must not include keel backlog assets: "
388
+ + ", ".join(sorted(backlog_assets))
389
+ )
390
+
391
+
392
+ def validate_scripts_use_stdlib(errors: list[str]) -> None:
393
+ stdlib_modules = set(
394
+ getattr(
395
+ sys,
396
+ "stdlib_module_names",
397
+ {
398
+ "argparse",
399
+ "ast",
400
+ "dataclasses",
401
+ "hashlib",
402
+ "json",
403
+ "os",
404
+ "pathlib",
405
+ "re",
406
+ "shutil",
407
+ "subprocess",
408
+ "sys",
409
+ "tempfile",
410
+ },
411
+ )
412
+ )
413
+ # `validation` is the runner's own package under scripts/ (#409).
414
+ allowed = stdlib_modules | {"__future__", "validation"}
415
+
416
+ # The runner's modules under scripts/validation/ are scripts too (#409).
417
+ for script in sorted({*(ROOT / "scripts").glob("*.py"), *runner_sources()}):
418
+ tree = ast.parse(script.read_text(encoding="utf-8"), filename=str(script))
419
+ imports: set[str] = set()
420
+ for node in ast.walk(tree):
421
+ if isinstance(node, ast.Import):
422
+ imports.update(alias.name.split(".")[0] for alias in node.names)
423
+ elif isinstance(node, ast.ImportFrom) and node.module:
424
+ imports.add(node.module.split(".")[0])
425
+
426
+ external = sorted(import_name for import_name in imports if import_name not in allowed)
427
+ if external:
428
+ errors.append(
429
+ f"{script.relative_to(ROOT).as_posix()} imports non-stdlib modules: "
430
+ + ", ".join(external)
431
+ )
432
+
433
+
434
+ def validate_review_status_single_source(errors: list[str]) -> None:
435
+ contract = (ROOT / "src/core/task-contract.js").read_text(encoding="utf-8")
436
+ if "ACCEPTED_REVIEW_STATUSES" not in contract:
437
+ errors.append(
438
+ "src/core/task-contract.js must define the shared "
439
+ "ACCEPTED_REVIEW_STATUSES constant."
440
+ )
441
+ if '"done"' not in contract:
442
+ errors.append(
443
+ "ACCEPTED_REVIEW_STATUSES must include the `done` Review Status."
444
+ )
445
+ literal = "pass|passed|complete|completed|ok"
446
+ for relative in ("src/core/gates.js", "src/core/context.js"):
447
+ content = (ROOT / relative).read_text(encoding="utf-8")
448
+ if "ACCEPTED_REVIEW_STATUSES" not in content:
449
+ errors.append(
450
+ f"{relative} must consume the shared ACCEPTED_REVIEW_STATUSES "
451
+ "constant rather than an inline Review Status vocabulary."
452
+ )
453
+ if literal in content:
454
+ errors.append(
455
+ f"{relative} still hard-codes the Review Status vocabulary "
456
+ f"`{literal}`; consume the shared constant instead."
457
+ )
458
+
459
+
460
+ def validate_install_honesty(errors: list[str]) -> None:
461
+ installer = (ROOT / "scripts/install_to_repo.py").read_text(encoding="utf-8")
462
+ if "def skill_actions" in installer or "dist_asset(target_name, \"skills\")" in installer:
463
+ errors.append(
464
+ "install_to_repo.py must not carry the dead keel-* skill_actions "
465
+ "path; keel-* skills are plugin-delivered."
466
+ )
467
+ cli = (ROOT / "bin/keel.js").read_text(encoding="utf-8")
468
+ if "delivered by the installed Keel plugin" not in cli:
469
+ errors.append(
470
+ "keel --help/--doctor must state that keel-* skills are delivered "
471
+ "by the installed Keel plugin, not installed by the CLI."
472
+ )
473
+ if ".claude/skills/keel-*." in cli:
474
+ errors.append(
475
+ "keel --help must not claim the CLI installs skills under "
476
+ ".claude/skills/keel-*."
477
+ )
478
+
479
+
480
+ def validate_openspec_invocable(errors: list[str]) -> None:
481
+ cli = (ROOT / "bin/keel.js").read_text(encoding="utf-8")
482
+ if 'options.action === "openspec"' not in cli:
483
+ errors.append("bin/keel.js must implement the `keel openspec` passthrough.")
484
+ # Once per overlay, in the header every action shares (#413).
485
+ if cli.count("Invoke the OpenSpec CLI as `keel openspec") < 2:
486
+ errors.append(
487
+ "the apply, archive, and sync overlays must direct agents to `keel openspec` "
488
+ "in place of a bare openspec command."
489
+ )
490
+
491
+
492
+ def validate_archive_overlay_hygiene(errors: list[str]) -> None:
493
+ cli = (ROOT / "bin/keel.js").read_text(encoding="utf-8")
494
+ if "--skip-specs" not in cli:
495
+ errors.append(
496
+ "the archive overlay must direct archive to pass --skip-specs "
497
+ "after the openspec-sync-specs skill has promoted the delta."
498
+ )
499
+ if "drop the change's guard manifest" not in cli:
500
+ errors.append(
501
+ "the archive overlay must remind the agent to run keel guard clear "
502
+ "after archiving."
503
+ )
504
+ gates = (ROOT / "src/core/gates.js").read_text(encoding="utf-8")
505
+ if "clearGuard" in gates:
506
+ errors.append(
507
+ "gates must stay read-only: gate code must not clear the guard "
508
+ "manifest (guard clear is explicit via keel guard clear)."
509
+ )