@christang/keel 5.183.0 → 5.185.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,1529 @@
1
+ """Keel validation: common (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
+
25
+ ROOT = Path(__file__).resolve().parents[2]
26
+
27
+
28
+ # No scenario may reach the developer's real Claude Code or Codex: `keel
29
+ # --update` drives both through their own CLIs (#204), and a scenario that ran
30
+ # it unguarded updated the real plugins of whoever ran the suite. A scenario
31
+ # that wants a host plants a fake and names it in its own environment.
32
+ os.environ["KEEL_UPDATE_CLAUDE"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-claude")
33
+
34
+
35
+ os.environ["KEEL_UPDATE_CODEX"] = str(Path(tempfile.gettempdir()) / "keel-suite-has-no-codex")
36
+
37
+
38
+ PACKAGE_VERSION = "5.185.0"
39
+
40
+
41
+ PROTOCOL_VERSION = "5.185.0"
42
+
43
+
44
+ LEGACY_MANAGED_START = "<!-- keel:start version=2.1 -->"
45
+
46
+
47
+ OPENSPEC_SCHEMA_NAME = "keel-spec-driven"
48
+
49
+
50
+ OPENSPEC_CONFIG_PATH = Path("openspec/config.yaml")
51
+
52
+
53
+ OPENSPEC_SCHEMA_ROOT = Path("openspec/schemas") / OPENSPEC_SCHEMA_NAME
54
+
55
+
56
+ OPENSPEC_SURFACE_OVERLAY_START = (
57
+ f"<!-- keel:openspec-surface-overlay version={PROTOCOL_VERSION} -->"
58
+ )
59
+
60
+
61
+ OPENSPEC_SURFACE_OVERLAY_END = "<!-- keel:openspec-surface-overlay:end -->"
62
+
63
+
64
+ SKILL_TARGETS = {"claude", "codex", "opencode"}
65
+
66
+
67
+ HOOK_TARGETS = {"claude"}
68
+
69
+
70
+ AGENT_TARGETS: set[str] = set()
71
+
72
+
73
+ ADAPTER_TARGETS = {"claude", "codex", "opencode"}
74
+
75
+
76
+ AGENT_PROTOCOL_TARGETS = {"codex", "opencode"}
77
+
78
+
79
+ LEGACY_PROFILE_SKILLS = (
80
+ "keel-profile-web",
81
+ "keel-profile-hardware",
82
+ "keel-profile-hardware-dsl",
83
+ )
84
+
85
+
86
+ SKILL_NAME_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
87
+
88
+
89
+ PORTABLE_SKILL_FIELDS = {
90
+ "name",
91
+ "description",
92
+ "license",
93
+ "compatibility",
94
+ "metadata",
95
+ "allowed-tools",
96
+ }
97
+
98
+
99
+ MANAGED_START = f"<!-- keel:start version={PROTOCOL_VERSION} -->"
100
+
101
+
102
+ MANAGED_START_RE = re.compile(r"<!--\s*keel:start(?:\s+[^>]*)?\s*-->")
103
+
104
+
105
+ MANAGED_END = "<!-- keel:end -->"
106
+
107
+
108
+ TEMPLATE_CHECKSUM_PREFIX = "<!-- keel:content-sha256 "
109
+
110
+
111
+ TEMPLATE_CHECKSUM_SUFFIX = " -->"
112
+
113
+
114
+ # The installed bootstrap block's byte budget, asserted by `thin-native-install`
115
+ # and `delegation-resident-text`. Raised from 1024 to 1400 in 5.63.0 to carry the
116
+ # Full/Lite routing rule (#131), deliberately and in a diff.
117
+ #
118
+ # The reason has to live here, because the cap's purpose is that the budget is
119
+ # **not quietly spent later** — the adjective is the whole specification. A cap
120
+ # phrased that way is not a claim that the number is right forever; it is a claim
121
+ # that nobody moves it without a reader noticing. So a documented raise satisfies
122
+ # it and a bare larger constant does not.
123
+ #
124
+ # Why routing earned it, when delegation did not: delegation is inert until a
125
+ # project declares it, so a repository declaring nothing was already served by the
126
+ # sentence in the block. Routing is never inert — every session routes, declared
127
+ # or not — and it was the one durable rule with no gate, no command, and no
128
+ # declaration carrying it to the agent. The rejected alternative was compressing
129
+ # the existing bullets to fit under 1024, which would have gone green while paying
130
+ # for routing out of gate-discipline prose that was already earning its place.
131
+ #
132
+ # 1400 rather than a round 1536: the headroom is "current content plus one short
133
+ # clause", so the next addition has to argue for itself the way this one did.
134
+ BOOTSTRAP_BLOCK_BYTE_BUDGET = 1400
135
+
136
+
137
+ RESIDENT_BLOCKS = [
138
+ {
139
+ "name": "Bootstrap resident block",
140
+ "path": "assets/bootstrap/AGENTS.md",
141
+ "max_lines": 12,
142
+ "required": [
143
+ "Keel Bootstrap",
144
+ "keel context",
145
+ "OpenSpec artifacts and Git",
146
+ "keel gate task-start",
147
+ "task capsule",
148
+ "fingerprint",
149
+ # Prose, not a command: this sentence is the one that has actually
150
+ # been reworded under byte pressure, so it is matched as a topic —
151
+ # Touch and a `bound…` word in one statement. The other prose
152
+ # entries stay literal until one of them needs the same freedom.
153
+ re.compile(r"Touch\b[^\n]*\bbound", re.IGNORECASE),
154
+ # #414: subagents are the model's choice, treated as the main agent.
155
+ "treated as the main agent is",
156
+ "native plugin",
157
+ "keel --init",
158
+ # Routing is the one durable rule with no gate behind it, so the
159
+ # block is the only place it reaches a consuming repository (#131).
160
+ # Matched as a topic: both modes named in one statement.
161
+ re.compile(r"\bFull\b[^\n]*\bLite\b", re.IGNORECASE),
162
+ "full_mode_paths",
163
+ ],
164
+ },
165
+ ]
166
+
167
+
168
+ RESIDENT_FORBIDDEN_SNIPPETS = [
169
+ "## Goal",
170
+ "## Acceptance Criteria",
171
+ "## Files To Read Next Session",
172
+ "dry-run",
173
+ "dry run",
174
+ "for example",
175
+ ]
176
+
177
+
178
+ SKILL_DOC_REQUIREMENTS = [
179
+ {
180
+ "name": "review-checklist skill",
181
+ "path": "src/skills/keel-review-checklist/SKILL.md",
182
+ "required": [
183
+ "completion gates",
184
+ "openspec-apply-change",
185
+ "openspec-sync-specs",
186
+ "openspec-archive-change",
187
+ "## Context to read",
188
+ "keel gate task-start",
189
+ "task-complete",
190
+ "change-close",
191
+ "deterministic structure",
192
+ "## Semantic Review",
193
+ "`Acceptance check`",
194
+ "`Scope check`",
195
+ "`Findings`",
196
+ "Resolved here:",
197
+ "Durable owner:",
198
+ "Discard reason:",
199
+ "HANDOFF",
200
+ "return-to-work",
201
+ "critical expectation",
202
+ "behavior evidence",
203
+ "explicit discard reason",
204
+ "evidence details",
205
+ "## Skill change review",
206
+ "authoritative sources",
207
+ "provenance and license",
208
+ "positive and negative trigger cases",
209
+ "real-task evidence",
210
+ "portable `SKILL.md`",
211
+ "target-native discovery",
212
+ ],
213
+ },
214
+ {
215
+ "name": "handoff skill",
216
+ "path": "src/skills/keel-handoff/SKILL.md",
217
+ "required": [
218
+ "Lite mode does not create HANDOFF",
219
+ "not a durable follow-up owner",
220
+ "## Context to read",
221
+ "openspec/changes",
222
+ "discard reason",
223
+ "keel-handoff/v1",
224
+ "schema",
225
+ "owner",
226
+ "action",
227
+ "reason",
228
+ "`active-backlog`",
229
+ "`head=...`",
230
+ "expectation state",
231
+ "evidence details",
232
+ "byte-for-byte",
233
+ "keel context --clear-handoff",
234
+ "## Standalone use",
235
+ ],
236
+ },
237
+ {
238
+ # Contract anchors traceable to keel-expectation-alignment; the
239
+ # expectation-alignment-skill scenario owns the full structural and
240
+ # cross-file behavioral checks, so this entry stays anchor-level.
241
+ "name": "align-expectations skill",
242
+ "path": "src/skills/keel-align-expectations/SKILL.md",
243
+ "required": [
244
+ "quick path",
245
+ "deep path",
246
+ "one material decision at a time",
247
+ "recommended answer",
248
+ "Silence does not",
249
+ "keel/lenses/",
250
+ "Applies when",
251
+ "keel lenses add",
252
+ "no separate alignment ledger",
253
+ ],
254
+ },
255
+ {
256
+ "name": "tdd-or-test-first skill",
257
+ "path": "src/skills/keel-tdd-or-test-first/SKILL.md",
258
+ "required": [
259
+ "selected OpenSpec task",
260
+ "acceptance criteria",
261
+ "## Context to read",
262
+ "## Standalone use",
263
+ "Coupled-task preflight",
264
+ "do not infer the missing decision",
265
+ ],
266
+ },
267
+ {
268
+ "name": "debug-failure skill",
269
+ "path": "src/skills/keel-debug-failure/SKILL.md",
270
+ "required": [
271
+ "Follow-ups are limited to directly observed blockers, risks, missing scope, or escalation needs",
272
+ "Do not include roadmap suggestions, new feature suggestions, unrelated architecture critique, or opportunistic refactor suggestions",
273
+ "There is no fixed attempt count",
274
+ "## Context to read",
275
+ "## Standalone use",
276
+ "candidate completion gate",
277
+ "provisional failure",
278
+ ],
279
+ },
280
+ {
281
+ # Structure only ("Applies when" self-describing header, "Material risk
282
+ # surface", "Execution and review checks"); the expectation-alignment-skill
283
+ # scenario owns domain-keyword scoping across these three lens templates,
284
+ # so the per-domain keywords are not duplicated here.
285
+ "name": "web lens template",
286
+ "path": "assets/lenses/web.md",
287
+ "required": [
288
+ "Applies when",
289
+ "Material risk surface",
290
+ "Execution and review checks",
291
+ ],
292
+ },
293
+ {
294
+ "name": "hardware lens template",
295
+ "path": "assets/lenses/hardware.md",
296
+ "required": [
297
+ "Applies when",
298
+ "Material risk surface",
299
+ "Execution and review checks",
300
+ ],
301
+ },
302
+ {
303
+ "name": "hardware-dsl lens template",
304
+ "path": "assets/lenses/hardware-dsl.md",
305
+ "required": [
306
+ "Applies when",
307
+ "Material risk surface",
308
+ "Execution and review checks",
309
+ ],
310
+ },
311
+ ]
312
+
313
+
314
+ FORBIDDEN_SKILL_SNIPPETS = [
315
+ "Source placeholder",
316
+ "Full v2.1 protocol behavior is refined by later implementation issues",
317
+ ]
318
+
319
+
320
+ def report(message: str) -> None:
321
+ print(message)
322
+
323
+
324
+ # The runner's own source: the entry point and every module it imports (#409).
325
+ # A check that reads the runner's code reads all of it, because a check that
326
+ # read one file would go quiet about whatever moved out of it.
327
+ def validation_sources() -> list[Path]:
328
+ return [ROOT / "scripts/validate_plugin.py", *sorted((ROOT / "scripts/validation").glob("*.py"))]
329
+
330
+
331
+ def validation_source_with(marker: str) -> tuple[Path, str, int] | None:
332
+ """The source file containing `marker`, its text, and the marker's offset."""
333
+ for path in validation_sources():
334
+ text = path.read_text(encoding="utf-8")
335
+ start = text.find(marker)
336
+ if start >= 0:
337
+ return path, text, start
338
+ return None
339
+
340
+
341
+ def extract_managed_block(content: str) -> str | None:
342
+ start_match = MANAGED_START_RE.search(content)
343
+ if start_match is None:
344
+ return None
345
+ end = content.find(MANAGED_END, start_match.end())
346
+ if end == -1:
347
+ return None
348
+ return content[start_match.start() : end + len(MANAGED_END)]
349
+
350
+
351
+ def template_checksum(content: str) -> str:
352
+ return hashlib.sha256(content.encode("utf-8")).hexdigest()
353
+
354
+
355
+ def install_template_payload(content: str) -> str:
356
+ return (
357
+ content
358
+ + f"{TEMPLATE_CHECKSUM_PREFIX}{template_checksum(content)}"
359
+ + TEMPLATE_CHECKSUM_SUFFIX
360
+ + "\n"
361
+ )
362
+
363
+
364
+ def strip_template_checksum(content: str) -> tuple[str, str | None]:
365
+ lines = content.splitlines(keepends=True)
366
+ checksum: str | None = None
367
+ kept: list[str] = []
368
+ for line in lines:
369
+ stripped = line.strip()
370
+ if stripped.startswith(TEMPLATE_CHECKSUM_PREFIX) and stripped.endswith(
371
+ TEMPLATE_CHECKSUM_SUFFIX
372
+ ):
373
+ checksum = stripped[
374
+ len(TEMPLATE_CHECKSUM_PREFIX) : -len(TEMPLATE_CHECKSUM_SUFFIX)
375
+ ]
376
+ continue
377
+ kept.append(line)
378
+ return "".join(kept), checksum
379
+
380
+
381
+ def validate_resident_blocks(errors: list[str], root: Path = ROOT) -> None:
382
+ for block in RESIDENT_BLOCKS:
383
+ path = root / block["path"]
384
+ if not path.is_file():
385
+ errors.append(f"{block['name']} is missing: {block['path']}")
386
+ continue
387
+
388
+ content = path.read_text(encoding="utf-8")
389
+ managed_block = extract_managed_block(content)
390
+ if managed_block is None:
391
+ errors.append(
392
+ f"{block['name']} must contain keel managed block markers"
393
+ )
394
+ continue
395
+ if MANAGED_START not in managed_block:
396
+ errors.append(
397
+ f"{block['name']} must declare managed block version {PROTOCOL_VERSION}"
398
+ )
399
+ continue
400
+
401
+ line_count = len(managed_block.splitlines())
402
+ max_lines = int(block["max_lines"])
403
+ if line_count > max_lines:
404
+ errors.append(
405
+ f"{block['name']} has {line_count} managed-block lines; "
406
+ f"budget is {max_lines}"
407
+ )
408
+
409
+ # A required entry is one of two kinds, and they mean different things.
410
+ # A literal names a command, marker, or identifier: if the block no
411
+ # longer contains it exactly, it is telling a reader to run something
412
+ # that does not exist, so the check must fail. A pattern states a topic
413
+ # in prose: the concepts must remain, the wording may move — which it
414
+ # must be free to, because this block is under a line and byte budget
415
+ # and gets rewritten to fit.
416
+ for required in block["required"]:
417
+ if isinstance(required, str):
418
+ if required not in managed_block:
419
+ errors.append(
420
+ f"{block['name']} missing required literal: {required}"
421
+ )
422
+ elif not required.search(managed_block):
423
+ errors.append(
424
+ f"{block['name']} missing required topic: "
425
+ f"{required.pattern}"
426
+ )
427
+
428
+ lowered = managed_block.lower()
429
+ for forbidden in RESIDENT_FORBIDDEN_SNIPPETS:
430
+ if forbidden.lower() in lowered:
431
+ errors.append(
432
+ f"{block['name']} includes forbidden resident-block content: "
433
+ f"{forbidden}"
434
+ )
435
+
436
+
437
+ def validate_openspec_schema(errors: list[str]) -> None:
438
+ source_root = ROOT / "assets" / "openspec" / "schemas" / OPENSPEC_SCHEMA_NAME
439
+ required_files = [
440
+ "schema.yaml",
441
+ "templates/proposal.md",
442
+ "templates/spec.md",
443
+ "templates/design.md",
444
+ "templates/tasks.md",
445
+ ]
446
+
447
+ for relative in required_files:
448
+ if not (source_root / relative).is_file():
449
+ errors.append(
450
+ "OpenSpec source schema missing file: "
451
+ f"{source_root.relative_to(ROOT).as_posix()}/{relative}"
452
+ )
453
+
454
+ schema_path = source_root / "schema.yaml"
455
+ tasks_template_path = source_root / "templates" / "tasks.md"
456
+ if schema_path.is_file():
457
+ schema = schema_path.read_text(encoding="utf-8")
458
+ for required in (
459
+ f"name: {OPENSPEC_SCHEMA_NAME}",
460
+ "description: Keel OpenSpec workflow",
461
+ "apply:",
462
+ "openspec-apply-change",
463
+ "keel-review-checklist",
464
+ "Mode",
465
+ "Covers",
466
+ "Read",
467
+ "Touch",
468
+ "Commands",
469
+ "Acceptance",
470
+ "Coupling",
471
+ "Candidate Boundary",
472
+ "Stop Rules",
473
+ "Evidence",
474
+ "Stop if",
475
+ "Report",
476
+ "Execution recommendation",
477
+ "Autonomy boundary",
478
+ "A subagent is the model's choice and is treated as the main agent is",
479
+ "approved `tasks.md` in order",
480
+ "Modify only files listed under Touch",
481
+ "reading does not expand write authority",
482
+ "Out-of-scope Need",
483
+ "unresolved follow-ups must be owned",
484
+ "Task Authoring Gate",
485
+ "Slice Start Gate",
486
+ "source expectations",
487
+ "Rough future slices",
488
+ "new or materially expanded dedicated skill",
489
+ "authoritative sources",
490
+ "provenance and license",
491
+ "positive and negative trigger cases",
492
+ "real-task evidence",
493
+ "one of pass, passed, complete, completed, ok, or done.",
494
+ "## Expectation Coverage",
495
+ "carry a disposition",
496
+ "`Resolved here:`",
497
+ ):
498
+ if required not in schema:
499
+ errors.append(f"OpenSpec schema.yaml missing required language: {required}")
500
+
501
+ if tasks_template_path.is_file():
502
+ tasks_template = tasks_template_path.read_text(encoding="utf-8")
503
+ for required in (
504
+ "- [ ]",
505
+ "keel-task-capsule/v1",
506
+ "Covers:",
507
+ "Touch:",
508
+ "Verify:",
509
+ "Strategy:",
510
+ "M1:",
511
+ "Evidence:",
512
+ "- Contract: pending",
513
+ "Review:",
514
+ "Status: pending",
515
+ "Status: one of pass, passed, complete, completed, ok, done",
516
+ "Blocker: none",
517
+ "Mode: diagnose-only",
518
+ "Requires modifying files outside Touch.",
519
+ "## Expectation Coverage",
520
+ "Discard reason:",
521
+ ):
522
+ if required not in tasks_template:
523
+ errors.append(
524
+ f"OpenSpec tasks.md template missing required language: {required}"
525
+ )
526
+ stripped_template = re.sub(r"<!--[\s\S]*?-->", "", tasks_template)
527
+ for forbidden in (
528
+ "Owner: keel-agent",
529
+ "Mode: implementation",
530
+ "- Read:",
531
+ "- Commands:",
532
+ "- Acceptance:",
533
+ "- Execution recommendation:",
534
+ "- Rationale:",
535
+ "- Autonomy boundary:",
536
+ "- Coupling:",
537
+ "- Candidate Boundary:",
538
+ "- Stop Rules:",
539
+ "- Stop if:",
540
+ "- Report:",
541
+ ):
542
+ if forbidden in stripped_template:
543
+ errors.append(
544
+ "OpenSpec tasks.md template repeats an invariant default: "
545
+ f"{forbidden}"
546
+ )
547
+
548
+
549
+ # A source-versus-dist comparison stood here, but `dist_root` was assigned
550
+ # `source_root`, so it diffed a directory against itself and could not fail.
551
+ # The pair that really needs comparing — this packaged copy against the
552
+ # repo-local one OpenSpec resolves — is asserted by
553
+ # `invalidation-authoring-surface`.
554
+
555
+
556
+ def validate_skill_docs(errors: list[str]) -> None:
557
+ for path in sorted((ROOT / "src" / "skills").glob("*/SKILL.md")):
558
+ content = path.read_text(encoding="utf-8")
559
+ for forbidden in FORBIDDEN_SKILL_SNIPPETS:
560
+ if forbidden in content:
561
+ errors.append(
562
+ f"{path.relative_to(ROOT).as_posix()} contains placeholder language: {forbidden}"
563
+ )
564
+
565
+ for skill in SKILL_DOC_REQUIREMENTS:
566
+ path = ROOT / skill["path"]
567
+ if not path.is_file():
568
+ errors.append(f"{skill['name']} is missing: {skill['path']}")
569
+ continue
570
+
571
+ content = path.read_text(encoding="utf-8")
572
+ for required in skill["required"]:
573
+ if required not in content:
574
+ errors.append(f"{skill['name']} missing required language: {required}")
575
+
576
+
577
+ def parse_skill_frontmatter(path: Path, errors: list[str]) -> dict[str, str]:
578
+ content = path.read_text(encoding="utf-8")
579
+ lines = content.splitlines()
580
+ if not lines or lines[0] != "---":
581
+ errors.append(f"{path.as_posix()} must start with YAML frontmatter")
582
+ return {}
583
+ try:
584
+ end = lines.index("---", 1)
585
+ except ValueError:
586
+ errors.append(f"{path.as_posix()} has unterminated YAML frontmatter")
587
+ return {}
588
+
589
+ fields: dict[str, str] = {}
590
+ block_key: str | None = None
591
+ for line in lines[1:end]:
592
+ if not line:
593
+ continue
594
+ if line.startswith((" ", "\t")):
595
+ if block_key:
596
+ fields[block_key] = f"{fields[block_key]} {line.strip()}".strip()
597
+ continue
598
+ if ":" not in line:
599
+ errors.append(f"{path.as_posix()} has invalid frontmatter line: {line}")
600
+ continue
601
+ key, value = line.split(":", 1)
602
+ key = key.strip()
603
+ value = value.strip()
604
+ block_key = key if value in {"|", ">"} else None
605
+ fields[key] = "" if block_key else value.strip("'\"")
606
+ return fields
607
+
608
+
609
+ def validate_skill_portability(root: Path, errors: list[str]) -> None:
610
+ source_root = root / "src" / "skills"
611
+ plugin_root = root / "plugins" / "keel" / "skills"
612
+ if not source_root.is_dir():
613
+ errors.append("skill portability requires src/skills canonical authority")
614
+ return
615
+
616
+ source_names = {path.name for path in source_root.iterdir() if path.is_dir()}
617
+ for name in sorted(source_names):
618
+ skill_dir = source_root / name
619
+ skill_path = skill_dir / "SKILL.md"
620
+ if not skill_path.is_file():
621
+ errors.append(f"missing canonical skill: {skill_path.as_posix()}")
622
+ continue
623
+ fields = parse_skill_frontmatter(skill_path, errors)
624
+ field_name = fields.get("name", "")
625
+ description = fields.get("description", "")
626
+ if field_name != name or not SKILL_NAME_RE.fullmatch(field_name):
627
+ errors.append(
628
+ f"canonical skill name must match its portable directory: {name}"
629
+ )
630
+ if not description or len(description) > 1024:
631
+ errors.append(
632
+ f"canonical skill description must be 1-1024 characters: {name}"
633
+ )
634
+ trigger_markers = ("use when", "when ", "before ")
635
+ if not any(marker in description.lower() for marker in trigger_markers):
636
+ errors.append(
637
+ f"canonical skill description must state when it applies: {name}"
638
+ )
639
+ unknown = sorted(set(fields) - PORTABLE_SKILL_FIELDS)
640
+ if unknown:
641
+ errors.append(
642
+ f"canonical skill uses non-portable frontmatter fields: "
643
+ f"{name}: {', '.join(unknown)}"
644
+ )
645
+ content = skill_path.read_text(encoding="utf-8")
646
+ references = re.findall(
647
+ r"(?:\]\(|`)((?:references|scripts|assets)/[A-Za-z0-9_./-]+)(?:\)|`)",
648
+ content,
649
+ )
650
+ for reference in sorted(set(references)):
651
+ resource_path = (skill_path.parent / Path(reference)).resolve()
652
+ try:
653
+ resource_path.relative_to(skill_path.parent.resolve())
654
+ except ValueError:
655
+ errors.append(
656
+ f"canonical skill reference escapes its skill directory: "
657
+ f"{name}: {reference}"
658
+ )
659
+ continue
660
+ if not resource_path.is_file():
661
+ errors.append(
662
+ f"canonical skill has missing referenced resource: "
663
+ f"{name}: {reference}"
664
+ )
665
+
666
+ projection = plugin_root / name
667
+ if not projection.is_dir():
668
+ errors.append(
669
+ f"canonical skill has missing native plugin projection: {name}"
670
+ )
671
+ continue
672
+ source_files = {
673
+ path.relative_to(skill_dir).as_posix(): hashlib.sha256(
674
+ path.read_bytes()
675
+ ).hexdigest()
676
+ for path in sorted(skill_dir.rglob("*"))
677
+ if path.is_file()
678
+ }
679
+ projection_files = {
680
+ path.relative_to(projection).as_posix(): hashlib.sha256(
681
+ path.read_bytes()
682
+ ).hexdigest()
683
+ for path in sorted(projection.rglob("*"))
684
+ if path.is_file()
685
+ }
686
+ if source_files != projection_files:
687
+ errors.append(
688
+ f"native plugin skill projection differs from canonical source: "
689
+ f"{name}"
690
+ )
691
+
692
+ if plugin_root.is_dir():
693
+ for plugin_skill in sorted(
694
+ path for path in plugin_root.iterdir() if path.is_dir()
695
+ ):
696
+ if plugin_skill.name not in source_names:
697
+ errors.append(
698
+ f"native plugin skill has no canonical source: "
699
+ f"{plugin_skill.name}"
700
+ )
701
+
702
+
703
+ def write_text(path: Path, content: str) -> None:
704
+ path.parent.mkdir(parents=True, exist_ok=True)
705
+ path.write_text(content, encoding="utf-8")
706
+
707
+
708
+ def snapshot_files(root: Path) -> dict[str, str]:
709
+ snapshot: dict[str, str] = {}
710
+ for path in sorted(root.rglob("*")):
711
+ if path.is_file():
712
+ snapshot[path.relative_to(root).as_posix()] = path.read_text(encoding="utf-8")
713
+ return snapshot
714
+
715
+
716
+ def packaged_openspec_schema_install_paths(root: Path | None = None) -> list[str]:
717
+ # The root the installer itself reads (install_to_repo.openspec_schema_actions),
718
+ # which raises on the same condition. A validator that answered `[]` here left
719
+ # six install/uninstall/clear assertions iterating nothing and reporting pass.
720
+ schema_root = root if root is not None else (
721
+ ROOT / "assets" / "openspec" / "schemas" / OPENSPEC_SCHEMA_NAME
722
+ )
723
+ if not schema_root.is_dir():
724
+ raise FileNotFoundError(
725
+ f"packaged OpenSpec schema root is missing: {schema_root}"
726
+ )
727
+
728
+ return [
729
+ (OPENSPEC_SCHEMA_ROOT / path.relative_to(schema_root)).as_posix()
730
+ for path in sorted(schema_root.rglob("*"))
731
+ if path.is_file()
732
+ ]
733
+
734
+
735
+ def run_keel(
736
+ cwd: Path,
737
+ *args: str,
738
+ env: dict[str, str] | None = None,
739
+ ) -> subprocess.CompletedProcess[str]:
740
+ return subprocess.run(
741
+ ["node", str(ROOT / "bin" / "keel.js"), *args],
742
+ cwd=cwd,
743
+ env=env,
744
+ text=True,
745
+ encoding="utf-8",
746
+ errors="replace",
747
+ capture_output=True,
748
+ check=False,
749
+ )
750
+
751
+
752
+ def mailbox_repository(root: Path) -> Path:
753
+ """A committed scratch repository whose mailbox tests can add worktrees."""
754
+ root.mkdir(parents=True, exist_ok=True)
755
+ for args in (
756
+ ["init", "-q", "-b", "main"],
757
+ ["config", "user.email", "keel@example.invalid"],
758
+ ["config", "user.name", "Keel Validation"],
759
+ ["commit", "-q", "--allow-empty", "-m", "seed"],
760
+ ):
761
+ subprocess.run(["git", *args], cwd=root, check=True, capture_output=True)
762
+ return root
763
+
764
+
765
+ def mailbox_common_dir(repo: Path) -> Path:
766
+ raw = subprocess.run(
767
+ ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],
768
+ cwd=repo, check=True, capture_output=True, text=True,
769
+ ).stdout.strip()
770
+ return Path(raw)
771
+
772
+
773
+ CHAT_ROLE_VARIABLES = ("KEEL_CHAT_ROLE", "KEEL_MAIL_ROLE")
774
+
775
+
776
+ # The desktop app's session markers (#319 D5): a run inside it must not change
777
+ # what shift scenarios see.
778
+ DESKTOP_HOST_VARIABLES = ("CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_HOST_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_PID")
779
+
780
+
781
+ def chat_environment(**extra: str) -> dict[str, str]:
782
+ """The test process's environment without any inherited chat role or desktop host."""
783
+ env = {
784
+ key: value for key, value in os.environ.items()
785
+ if key not in CHAT_ROLE_VARIABLES and key not in DESKTOP_HOST_VARIABLES
786
+ }
787
+ env.update(extra)
788
+ return env
789
+
790
+
791
+ def chat_worktree(repo: Path, path: Path) -> Path:
792
+ subprocess.run(
793
+ ["git", "worktree", "add", "-q", "-b", path.name, str(path)],
794
+ cwd=repo, check=True, capture_output=True,
795
+ )
796
+ return path
797
+
798
+
799
+ def chat_log(repo: Path, group: str) -> Path:
800
+ return mailbox_common_dir(repo) / "keel-chat" / "groups" / group / "log"
801
+
802
+
803
+ def chat_json(result: subprocess.CompletedProcess[str]) -> dict:
804
+ try:
805
+ parsed = json.loads(result.stdout)
806
+ except json.JSONDecodeError:
807
+ return {}
808
+ return parsed if isinstance(parsed, dict) else {}
809
+
810
+
811
+ def chat_scratch_group(base: Path) -> tuple[Path, Path, dict[str, str]]:
812
+ """A repository with `rtl` and a `verify` worktree sharing group `soc`."""
813
+ rtl = mailbox_repository(base / "rtl")
814
+ verify = chat_worktree(rtl, base / "verify")
815
+ env = chat_environment()
816
+ for cwd, role in ((rtl, "rtl"), (verify, "verify")):
817
+ run_keel(cwd, "chat", "role", "--set", role, env=env)
818
+ run_keel(rtl, "chat", "group", "create", "soc", "--member", "verify", env=env)
819
+ return rtl, verify, env
820
+
821
+
822
+ def host_project_name(directory: Path) -> str:
823
+ """The host's project directory name for a working directory (Claude Code's sanitizing)."""
824
+ return re.sub(r"[^A-Za-z0-9]", "-", os.path.realpath(directory))
825
+
826
+
827
+ def chat_session_start(cwd: Path, env: dict, session: str, pid: int, source: str = "startup",
828
+ transcript: Path | None = None) -> subprocess.CompletedProcess:
829
+ payload = {"cwd": str(cwd), "hook_event_name": "SessionStart", "session_id": session, "source": source}
830
+ if transcript is not None:
831
+ payload["transcript_path"] = str(transcript)
832
+ return subprocess.run(["node", str(ROOT / "bin" / "keel.js"), "chat", "hook", "session-start"], cwd=cwd, text=True,
833
+ capture_output=True, check=False, input=json.dumps(payload),
834
+ env={**env, "CLAUDE_CODE_ENTRYPOINT": "cli", "CLAUDE_CODE_SESSION_ID": session, "CLAUDE_PID": str(pid)})
835
+
836
+
837
+ def chat_logs_snapshot(repo: Path) -> dict:
838
+ groups = mailbox_common_dir(repo) / "keel-chat" / "groups"
839
+ return {str(p): p.read_bytes() for p in groups.rglob("*") if p.is_file()}
840
+
841
+
842
+ def chat_records_with(repo: Path, group: str, needle: str) -> list[str]:
843
+ """Record files in `group` whose text contains `needle`."""
844
+ log = chat_log(repo, group)
845
+ if not log.is_dir():
846
+ return []
847
+ return [p.read_text(encoding="utf-8") for p in sorted(log.glob("*.md")) if needle in p.read_text(encoding="utf-8")]
848
+
849
+
850
+ def shift_scratch(base: Path) -> tuple[Path, Path, dict, Path]:
851
+ """`rtl` and `verify` worktrees pushed to a bare remote, for shift scenarios."""
852
+ rtl, verify, env = chat_scratch_group(base)
853
+ remote = base / "remote.git"
854
+ subprocess.run(["git", "init", "-q", "--bare", str(remote)], check=True, capture_output=True)
855
+ subprocess.run(["git", "remote", "add", "origin", str(remote)], cwd=rtl, check=True, capture_output=True)
856
+ for tree in (rtl, verify):
857
+ subprocess.run(["git", "push", "-q", "-u", "origin", "HEAD"], cwd=tree, check=True, capture_output=True)
858
+ return rtl, verify, env, remote
859
+
860
+
861
+ FAKE_CODEX = r"""#!/usr/bin/env node
862
+ const fs = require("fs");
863
+ let input = "";
864
+ try { input = fs.readFileSync(0, "utf8"); } catch {}
865
+ fs.appendFileSync(process.env.FAKE_CODEX_LOG, JSON.stringify({ argv: process.argv.slice(2), cwd: process.cwd(), stdin: input }) + "\n");
866
+ console.log(JSON.stringify({ type: "thread.started", thread_id: "thread-fake-1" }));
867
+ console.log(JSON.stringify({ type: "turn.completed" }));
868
+ """
869
+
870
+
871
+ def chat_wake_scratch(base: Path) -> tuple[Path, Path, dict[str, str], Path]:
872
+ """`rtl` and a `cx` worktree sharing `lab` and `other`; `cx` declares chat-reply:lab.
873
+
874
+ Returns the two worktrees, an environment whose KEEL_HOME, launchctl,
875
+ LaunchAgents directory, and Codex executable are scratch doubles, and the
876
+ file the fake Codex appends one JSON line per turn to.
877
+ """
878
+ rtl = mailbox_repository(base / "rtl")
879
+ cx = chat_worktree(rtl, base / "cx")
880
+ write_text(cx / "keel" / "config.yaml", "authorize:\n - chat-reply:lab\n")
881
+ subprocess.run(["git", "add", "keel/config.yaml"], cwd=cx, check=True, capture_output=True)
882
+ subprocess.run(["git", "commit", "-q", "-m", "chat-reply"], cwd=cx, check=True, capture_output=True)
883
+ calls = base / "codex-calls.jsonl"
884
+ codex = base / "fake-codex"
885
+ write_text(codex, FAKE_CODEX)
886
+ codex.chmod(0o755)
887
+ launchctl = base / "launchctl"
888
+ write_text(launchctl, f'#!/bin/sh\necho "$@" >> "{base / "launchctl-calls"}"\nexit 0\n')
889
+ launchctl.chmod(0o755)
890
+ env = chat_environment(
891
+ KEEL_HOME=str(base / "home"),
892
+ KEEL_CHAT_CODEX=str(codex),
893
+ FAKE_CODEX_LOG=str(calls),
894
+ KEEL_CHAT_LAUNCHCTL=str(launchctl),
895
+ KEEL_CHAT_LAUNCH_AGENTS_DIR=str(base / "agents"),
896
+ )
897
+ run_keel(rtl, "chat", "role", "--set", "rtl", env=env)
898
+ run_keel(cx, "chat", "role", "--set", "cx", env=env)
899
+ run_keel(rtl, "chat", "group", "create", "lab", "--member", "cx", env=env)
900
+ run_keel(rtl, "chat", "group", "create", "other", "--member", "cx", env=env)
901
+ return rtl, cx, env, calls
902
+
903
+
904
+ def gate_task(
905
+ *,
906
+ checked: bool,
907
+ coupling: str,
908
+ missing_field: str | None = None,
909
+ evidence: str = (
910
+ " - M1: passed\n"
911
+ " - Review:\n"
912
+ " - Status: pass\n"
913
+ " - Acceptance check: reviewed\n"
914
+ " - Scope check: reviewed\n"
915
+ " - Findings: none\n"
916
+ " - Blocker: none"
917
+ ),
918
+ ) -> str:
919
+ fields = {
920
+ "Owner": "claude",
921
+ "Mode": "implementation",
922
+ "Covers": "\n - E1: hook behavior",
923
+ "Read": "\n - openspec/changes/demo/proposal.md",
924
+ "Touch": "\n - src/example.js",
925
+ "Verification Strategy": "evidence-first",
926
+ "Verification Reason": "this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first",
927
+ "Commands": "\n - M1: npm test",
928
+ "Acceptance": "the required command succeeds",
929
+ "Execution recommendation": "Claude Code implementation note (advisory)",
930
+ "Rationale": "bounded implementation work",
931
+ "Autonomy boundary": "hard-stop",
932
+ "Coupling": coupling,
933
+ "Candidate Boundary": "one complete candidate; provisional failures are repaired before the completion gate",
934
+ "Stop Rules": "stop the current candidate at a final assertion; stop the task immediately for scope breach",
935
+ "Evidence": "\n" + evidence,
936
+ "Stop if": "scope requires files outside Touch",
937
+ "Report": "Summary and Tests Run",
938
+ }
939
+ if missing_field is not None:
940
+ del fields[missing_field]
941
+ checkbox = "x" if checked else " "
942
+ lines = [f"- [{checkbox}] 1.1 Gate fixture task"]
943
+ for name, value in fields.items():
944
+ if value.startswith("\n"):
945
+ lines.append(f" - {name}:{value}")
946
+ else:
947
+ lines.append(f" - {name}: {value}")
948
+ return "\n".join(lines) + "\n"
949
+
950
+
951
+ def write_gate_fixture(repo: Path, tasks: str, design: str = "## Context\n\nfixture\n") -> None:
952
+ change = repo / "openspec/changes/demo"
953
+ write_text(
954
+ change / "tasks.md",
955
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
956
+ "## Invalidates\n\n"
957
+ "- None.\n\n"
958
+ "## Expectation Coverage\n\n"
959
+ "- E1:\n"
960
+ " - Covered by: 1.1\n\n"
961
+ "## Tasks\n\n"
962
+ + tasks,
963
+ )
964
+ write_text(change / "proposal.md", "# Proposal\n")
965
+ write_text(change / "design.md", design)
966
+ write_text(change / "specs/demo/spec.md", "## ADDED Requirements\n")
967
+
968
+
969
+ def coupled_design_fixture() -> str:
970
+ return """## Coupled Iteration Contract
971
+
972
+ - Coupled artifacts: source and generated output.
973
+ - Invalidation triggers: source changes.
974
+ - Required regeneration: regenerate output.
975
+ - Final assertions: required checks pass.
976
+ - Conflict authority: design.md.
977
+ - Baseline policy: baseline stays fixed.
978
+ """
979
+
980
+
981
+ def task_contract_fixture(
982
+ *,
983
+ mode: str = "implementation",
984
+ touch: tuple[str, ...] = ("src/feature.js",),
985
+ commands: tuple[str, ...] = ("M1: node test.js",),
986
+ evidence: tuple[str, ...] = ("M1: pending",),
987
+ strategy: str | None = "evidence-first",
988
+ ) -> str:
989
+ touch_lines = "".join(f" - {item}\n" for item in touch)
990
+ command_lines = "".join(f" - {item}\n" for item in commands)
991
+ evidence_lines = "".join(f" - {item}\n" for item in evidence)
992
+ return (
993
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
994
+ "- [ ] 1.1 Exercise task contract\n"
995
+ " - Owner: keel-agent\n"
996
+ f" - Mode: {mode}\n"
997
+ " - Covers:\n"
998
+ " - E1: public behavior\n"
999
+ " - Read:\n"
1000
+ " - README.md\n"
1001
+ " - Touch:\n"
1002
+ f"{touch_lines}"
1003
+ + (f" - Verification Strategy: {strategy}\n" if strategy else "")
1004
+ + (f" - Verification Reason: this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first\n"
1005
+ if strategy == "evidence-first" else "")
1006
+ + " - Commands:\n"
1007
+ + f"{command_lines}"
1008
+ " - Acceptance:\n"
1009
+ " - Public behavior passes.\n"
1010
+ " - Autonomy boundary:\n"
1011
+ " - Default: hard-stop\n"
1012
+ " - Pre-authorized fallback: none\n"
1013
+ " - Coupling: none\n"
1014
+ " - Candidate Boundary:\n"
1015
+ " - Not applicable; Coupling is none.\n"
1016
+ " - Stop Rules:\n"
1017
+ " - Stop on failure.\n"
1018
+ " - Evidence:\n"
1019
+ # Emitted unconditionally rather than through `evidence`, which callers
1020
+ # override to control the M-entries. Completion requires a recorded
1021
+ # fingerprint, and `--record` rewrites this line in place, so a caller
1022
+ # that customizes its evidence must not be able to drop the anchor.
1023
+ " - Contract: pending\n"
1024
+ f"{evidence_lines}"
1025
+ " - Review:\n"
1026
+ " - Status: pending\n"
1027
+ " - Acceptance check: pending\n"
1028
+ " - Scope check: pending\n"
1029
+ " - Findings: pending\n"
1030
+ " - Blocker: none\n"
1031
+ " - Stop if:\n"
1032
+ " - Requires files outside Touch.\n"
1033
+ " - Report:\n"
1034
+ " - Summary\n"
1035
+ )
1036
+
1037
+
1038
+ def task_capsule_compact_fixture() -> str:
1039
+ return (
1040
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
1041
+ "- [ ] 1.1 Exercise task contract\n"
1042
+ " - Covers:\n"
1043
+ " - E1: Public behavior passes.\n"
1044
+ " - Read:\n"
1045
+ " - README.md\n"
1046
+ " - Touch:\n"
1047
+ " - src/feature.js\n"
1048
+ " - Verify:\n"
1049
+ " - Strategy: evidence-first\n"
1050
+ " - Reason: this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first\n"
1051
+ " - M1: node test.js\n"
1052
+ " - Autonomy boundary:\n"
1053
+ " - Default: hard-stop\n"
1054
+ " - Pre-authorized fallback: none\n"
1055
+ " - Stop Rules:\n"
1056
+ " - Stop on failure.\n"
1057
+ " - Evidence:\n"
1058
+ # Completion requires a recorded fingerprint here, so the anchor line
1059
+ # must exist for `--record` to rewrite in place. See
1060
+ # record_contract_anchor.
1061
+ " - Contract: pending\n"
1062
+ " - M1: pending\n"
1063
+ " - Stop if:\n"
1064
+ " - Requires files outside Touch.\n"
1065
+ )
1066
+
1067
+
1068
+ def tracker_owner_tasks(findings: str, closure: str) -> str:
1069
+ """One complete, checked task plus one Expectation Coverage closure line."""
1070
+ return (
1071
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
1072
+ "## Expectation Coverage\n\n"
1073
+ "- E1:\n"
1074
+ f" - {closure}\n\n"
1075
+ "## 1. Work\n\n"
1076
+ "- [x] 1.1 Complete behavior\n"
1077
+ " - Owner: keel-agent\n"
1078
+ " - Mode: implementation\n"
1079
+ " - Covers:\n"
1080
+ " - E1: public behavior\n"
1081
+ " - Read:\n"
1082
+ " - README.md\n"
1083
+ " - Touch:\n"
1084
+ " - src/feature.js\n"
1085
+ " - Verification Strategy: evidence-first\n"
1086
+ " - Verification Reason: this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first\n"
1087
+ " - Commands:\n"
1088
+ " - M1: node test.js\n"
1089
+ " - Acceptance:\n"
1090
+ " - Public behavior passes.\n"
1091
+ " - Autonomy boundary:\n"
1092
+ " - Default: hard-stop\n"
1093
+ " - Pre-authorized fallback: none\n"
1094
+ " - Coupling: none\n"
1095
+ " - Candidate Boundary:\n"
1096
+ " - One candidate.\n"
1097
+ " - Stop Rules:\n"
1098
+ " - Stop on failure.\n"
1099
+ " - Evidence:\n"
1100
+ " - Contract: pending\n"
1101
+ " - M1: passed\n"
1102
+ " - Review:\n"
1103
+ " - Status: pass\n"
1104
+ " - Acceptance check: reviewed\n"
1105
+ " - Scope check: reviewed\n"
1106
+ f" - Findings: {findings}\n"
1107
+ " - Blocker: none\n"
1108
+ " - Stop if:\n"
1109
+ " - Scope expands.\n"
1110
+ " - Report:\n"
1111
+ " - Summary\n"
1112
+ )
1113
+
1114
+
1115
+ # `@fission-ai/openspec` is this package's own declared dependency, and
1116
+ # `npm install` puts an executable at `node_modules/.bin/openspec`. npm scripts
1117
+ # see that directory on PATH; a Python subprocess started by
1118
+ # `node scripts/run_python.js` does not — so a checkout that had installed
1119
+ # everything it declares reported `validation --all failed for:
1120
+ # compact-task-authoring` while the schema it could supposedly not resolve
1121
+ # resolved perfectly (issue #105).
1122
+ #
1123
+ # The declared dependency wins over PATH. It is the version this repository is
1124
+ # tested against; a global install that happens to be on PATH is a different
1125
+ # version answering for it.
1126
+ OPENSPEC_SEARCH_ORDER = (
1127
+ "the package's own node_modules/.bin",
1128
+ "PATH",
1129
+ )
1130
+
1131
+
1132
+ @contextlib.contextmanager
1133
+ def path_without_openspec(path: str | None = None):
1134
+ """Yield `path` with every `openspec` executable on it removed, and nothing else.
1135
+
1136
+ Dropping a PATH *directory* because it holds an `openspec` also drops that
1137
+ directory's other contents. On the ordinary Homebrew plus `npm install -g`
1138
+ layout one directory holds both `openspec` and `node`, so the filter took the
1139
+ interpreter the openspec shim needs and the scenario built on it asserted that
1140
+ a shell without an interpreter fails — reported against `openspec`, which was
1141
+ installed and working (issue #137).
1142
+
1143
+ So a directory that holds the tool is replaced in place, at the same index, by
1144
+ a mirror symlinking every one of its entries except the `openspec` ones; a
1145
+ directory that does not hold it is passed through untouched. Exclusion is by
1146
+ stem, so `openspec.cmd` and its siblings cannot survive a filter whose whole
1147
+ purpose is that the name does not resolve.
1148
+
1149
+ The mirrors live for the duration of the context, so callers must hold it open
1150
+ across every child process they run against the PATH, not only across the call
1151
+ that built it.
1152
+ """
1153
+ original = os.environ.get("PATH", "") if path is None else path
1154
+ entries = [entry for entry in original.split(os.pathsep) if entry]
1155
+ with tempfile.TemporaryDirectory(prefix="keel-no-openspec-") as raw:
1156
+ mirrors = Path(raw)
1157
+ rebuilt: list[str] = []
1158
+ for index, entry in enumerate(entries):
1159
+ source = Path(entry)
1160
+ try:
1161
+ contents = sorted(source.iterdir())
1162
+ except OSError:
1163
+ # Unreadable or absent: it carried nothing resolvable either way.
1164
+ rebuilt.append(entry)
1165
+ continue
1166
+ if not any(item.stem == "openspec" for item in contents):
1167
+ rebuilt.append(entry)
1168
+ continue
1169
+ mirror = mirrors / str(index)
1170
+ try:
1171
+ mirror.mkdir()
1172
+ for item in contents:
1173
+ if item.stem == "openspec":
1174
+ continue
1175
+ (mirror / item.name).symlink_to(item)
1176
+ except OSError:
1177
+ # Windows can refuse a symlink without the privilege. Fall back to
1178
+ # dropping the directory, which is what this replaces; the caller's
1179
+ # precondition check then reports the consequence by name instead
1180
+ # of attributing it to the tool.
1181
+ continue
1182
+ rebuilt.append(str(mirror))
1183
+ yield os.pathsep.join(rebuilt)
1184
+
1185
+
1186
+ def resolve_openspec(env: dict[str, str] | None = None) -> str | None:
1187
+ local = ROOT / "node_modules" / ".bin" / "openspec"
1188
+ if local.is_file():
1189
+ return str(local)
1190
+ return shutil.which("openspec", path=(env or os.environ).get("PATH"))
1191
+
1192
+
1193
+ def run_openspec(
1194
+ cwd: Path,
1195
+ *args: str,
1196
+ env: dict[str, str] | None = None,
1197
+ ) -> subprocess.CompletedProcess[str] | None:
1198
+ executable = resolve_openspec(env)
1199
+ if executable is None:
1200
+ return None
1201
+ return subprocess.run(
1202
+ [executable, *args],
1203
+ cwd=cwd,
1204
+ env=env,
1205
+ text=True,
1206
+ encoding="utf-8",
1207
+ errors="replace",
1208
+ capture_output=True,
1209
+ check=False,
1210
+ )
1211
+
1212
+
1213
+ def legacy_v3_web_profile_text() -> str:
1214
+ return (
1215
+ "---\n"
1216
+ "name: keel-profile-web\n"
1217
+ "description: Optional Keel profile for web frontend/backend work; use during OpenSpec authoring or verification when UI, API, routing, persistence, or integration behavior may hide product assumptions.\n"
1218
+ "---\n"
1219
+ "\n"
1220
+ "# keel-profile-web\n"
1221
+ "## Purpose\n"
1222
+ "\n"
1223
+ "Use this optional domain profile to make web hidden-knowledge risk explicit before executable Keel tasks are selected. This is profile guidance only; it does not change core Keel ownership, Touch boundaries, sync/archive rules, or handoff semantics.\n"
1224
+ "\n"
1225
+ "## Risk-triggered grill\n"
1226
+ "\n"
1227
+ "Invoke `keel-grill-open-questions` during OpenSpec authoring when the change touches UI-observable behavior, public interface contracts, routing, auth/session behavior, persistence, migrations, async state, loading/error states, accessibility expectations, browser compatibility, or backend integration boundaries.\n"
1228
+ "\n"
1229
+ "Ask only questions that materially affect Acceptance, Commands, Touch, specs, design decisions, or non-goals. Stop when the task contract can be written without guessing.\n"
1230
+ "\n"
1231
+ "## Durable placement\n"
1232
+ "\n"
1233
+ "Write accepted answers into durable OpenSpec artifacts:\n"
1234
+ "\n"
1235
+ "- specs for user-visible behavior, API behavior, error handling, and scenarios.\n"
1236
+ "- design.md for framework choices, data flow, migration notes, auth/session assumptions, and trade-offs.\n"
1237
+ "- tasks.md for Acceptance, Commands, Read, Touch, Stop if, and Autonomy boundary details.\n"
1238
+ "\n"
1239
+ "Do not leave product decisions only in chat or `keel/HANDOFF.md`.\n"
1240
+ "\n"
1241
+ "## Verification prompts\n"
1242
+ "\n"
1243
+ "Prefer public interface evidence:\n"
1244
+ "\n"
1245
+ "- UI behavior through a rendered page or component workflow, not self-mocked internals.\n"
1246
+ "- API behavior through route/client contract checks, including failure paths when they affect users.\n"
1247
+ "- Data changes through migration/integration evidence when persistence semantics change.\n"
1248
+ "- Accessibility or responsive behavior checks when the task Acceptance names them.\n"
1249
+ "\n"
1250
+ "## Standalone use\n"
1251
+ "\n"
1252
+ "When used alone, report the hidden-knowledge risks found, where each accepted answer should be captured, and the public-interface evidence expected.\n"
1253
+ )
1254
+
1255
+
1256
+ PLUGIN_ROOT = Path("plugins/keel")
1257
+
1258
+
1259
+ def run_session_start_hook(
1260
+ repo: Path,
1261
+ event: dict,
1262
+ *,
1263
+ keel_cli: str | None,
1264
+ timeout_ms: int | None = None,
1265
+ panel: str | None = None,
1266
+ plugin_root: Path | None = None,
1267
+ extra_env: dict[str, str] | None = None,
1268
+ ) -> subprocess.CompletedProcess[str]:
1269
+ # The shipping plugin unless a fixture plants its own copy. A planted copy
1270
+ # is how the version the plugin reports about itself becomes something the
1271
+ # suite decides rather than something it inherits from this working tree.
1272
+ root = Path(plugin_root) if plugin_root is not None else ROOT / PLUGIN_ROOT
1273
+ env = dict(os.environ)
1274
+ # None leaves the hook to choose its own CLI, which is the only way to
1275
+ # observe that choice; every other caller pins one.
1276
+ env.pop("KEEL_CLI", None)
1277
+ if keel_cli is not None:
1278
+ env["KEEL_CLI"] = keel_cli
1279
+ env["CLAUDE_PLUGIN_ROOT"] = str(root)
1280
+ # The suite must decide the panel's state rather than inherit whatever the
1281
+ # developer running it has exported, or the default-off assertion would
1282
+ # pass or fail by accident of the shell.
1283
+ env.pop("KEEL_SESSION_PANEL", None)
1284
+ if panel is not None:
1285
+ env["KEEL_SESSION_PANEL"] = panel
1286
+ if timeout_ms is not None:
1287
+ env["KEEL_HOOK_TIMEOUT_MS"] = str(timeout_ms)
1288
+ if extra_env is not None:
1289
+ env.update(extra_env)
1290
+ return subprocess.run(
1291
+ ["node", str(root / "scripts/session-start.js")],
1292
+ cwd=repo,
1293
+ env=env,
1294
+ input=json.dumps(event),
1295
+ text=True,
1296
+ encoding="utf-8",
1297
+ errors="replace",
1298
+ capture_output=True,
1299
+ check=False,
1300
+ )
1301
+
1302
+
1303
+ def session_start_context(result: subprocess.CompletedProcess[str]) -> str | None:
1304
+ if not result.stdout.strip():
1305
+ return None
1306
+ payload = json.loads(result.stdout)
1307
+ output = payload.get("hookSpecificOutput", {})
1308
+ if output.get("hookEventName") != "SessionStart":
1309
+ raise ValueError(f"unexpected hook output shape: {result.stdout!r}")
1310
+ return output.get("additionalContext")
1311
+
1312
+
1313
+ def resident_session_start_section(path: Path) -> str | None:
1314
+ text = path.read_text(encoding="utf-8")
1315
+ match = re.search(
1316
+ r"^## Session Start$(.*?)^## ", text, re.MULTILINE | re.DOTALL
1317
+ )
1318
+ return match.group(1) if match else None
1319
+
1320
+
1321
+ # A hook stub that reports which copy ran, with what input. Used as the newer
1322
+ # install's copy of a script so the scenario can tell a hand-off from the
1323
+ # loaded script's own logic, which prints none of this.
1324
+ HANDOFF_STUB = r"""const fs = require("fs");
1325
+ const path = require("path");
1326
+ let input = "";
1327
+ try { input = fs.readFileSync(0, "utf8"); } catch {}
1328
+ const manifest = path.join(__dirname, "..", ".claude-plugin", "plugin.json");
1329
+ process.stdout.write(JSON.stringify({
1330
+ stub: JSON.parse(fs.readFileSync(manifest, "utf8")).version,
1331
+ script: path.basename(__filename),
1332
+ argv: process.argv.slice(2),
1333
+ input,
1334
+ forwarded: process.env.KEEL_HOOK_FORWARDED || null,
1335
+ root: process.env.CLAUDE_PLUGIN_ROOT || null,
1336
+ }) + "\n");
1337
+ const sleep = Number(process.env.HANDOFF_STUB_SLEEP_MS || 0);
1338
+ if (sleep) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, sleep);
1339
+ process.exit(Number(process.env.HANDOFF_STUB_STATUS || 0));
1340
+ """
1341
+
1342
+
1343
+ def plant_handoff_package(root: Path, version: str, *, stubs: tuple[str, ...] = ()) -> Path:
1344
+ """One cached Claude install: the package root with both manifests and the
1345
+ plugin's real hook scripts, of which `stubs` are replaced by HANDOFF_STUB."""
1346
+ manifest = json.dumps({"name": "keel", "version": version}, indent=2) + "\n"
1347
+ write_text(root / ".claude-plugin/plugin.json", manifest)
1348
+ write_text(root / "plugins/keel/.claude-plugin/plugin.json", manifest)
1349
+ write_text(
1350
+ root / "package.json",
1351
+ json.dumps({"name": "@christang/keel", "version": version}) + "\n",
1352
+ )
1353
+ scripts = ROOT / PLUGIN_ROOT / "scripts"
1354
+ for source in sorted(scripts.glob("*.js")):
1355
+ body = HANDOFF_STUB if source.name in stubs else source.read_text(encoding="utf-8")
1356
+ write_text(root / "plugins/keel/scripts" / source.name, body)
1357
+ return root
1358
+
1359
+
1360
+ def write_install_record(plugins_dir: Path, install_path: Path | None) -> None:
1361
+ entries = {}
1362
+ if install_path is not None:
1363
+ entries["keel@m"] = [{"scope": "user", "installPath": str(install_path), "version": "x"}]
1364
+ write_text(
1365
+ plugins_dir / "installed_plugins.json",
1366
+ json.dumps({"version": 2, "plugins": entries}) + "\n",
1367
+ )
1368
+
1369
+
1370
+ def run_hook_script(
1371
+ script: Path,
1372
+ args: list[str],
1373
+ stdin: str,
1374
+ cwd: Path,
1375
+ extra_env: dict[str, str] | None = None,
1376
+ ) -> subprocess.CompletedProcess[str]:
1377
+ env = dict(os.environ)
1378
+ for name in ("KEEL_HOOK_FORWARDED", "HANDOFF_STUB_STATUS", "HANDOFF_STUB_SLEEP_MS",
1379
+ "KEEL_HOOK_FORWARD_TIMEOUT_MS"):
1380
+ env.pop(name, None)
1381
+ env["CLAUDE_PLUGIN_ROOT"] = str(script.parents[1])
1382
+ if extra_env:
1383
+ env.update(extra_env)
1384
+ return subprocess.run(
1385
+ ["node", str(script), *args], cwd=cwd, env=env, input=stdin, text=True,
1386
+ encoding="utf-8", errors="replace", capture_output=True, check=False, timeout=60,
1387
+ )
1388
+
1389
+
1390
+ def stub_output(result: subprocess.CompletedProcess[str]) -> dict | None:
1391
+ for line in result.stdout.splitlines():
1392
+ try:
1393
+ value = json.loads(line)
1394
+ except json.JSONDecodeError:
1395
+ continue
1396
+ if isinstance(value, dict) and "stub" in value:
1397
+ return value
1398
+ return None
1399
+
1400
+
1401
+ def run_node_expression(root: Path, expression: str) -> str:
1402
+ """Evaluate a Node expression with `root` as the working directory.
1403
+
1404
+ The declaration set is read from the module that defines it rather than by
1405
+ regexing its source: a regex over the source would be a second copy of the
1406
+ same literal the check exists to remove, one level down (issue #143).
1407
+ """
1408
+ result = subprocess.run(
1409
+ ["node", "-e", expression],
1410
+ cwd=root,
1411
+ text=True,
1412
+ encoding="utf-8",
1413
+ errors="replace",
1414
+ capture_output=True,
1415
+ check=False,
1416
+ )
1417
+ return result.stdout
1418
+
1419
+
1420
+ def config_header_paragraph(config_text: str) -> str:
1421
+ """The opening paragraph that lists the declarations, whitespace-collapsed.
1422
+
1423
+ The header, not the file. Both callers used to pass the whole of
1424
+ `keel/config.yaml`, so a declaration name appearing anywhere in the body — a
1425
+ comment elsewhere that happened to use the word — satisfied "the header names
1426
+ it". `merge` did exactly that in 5.71.0, through the triage section's "never
1427
+ authorizes a merge", before the header said anything about it (#155).
1428
+ """
1429
+ lines = config_text.splitlines()
1430
+ start = next(
1431
+ (i for i, line in enumerate(lines) if "independent declarations live here" in line),
1432
+ None,
1433
+ )
1434
+ if start is None:
1435
+ return ""
1436
+ paragraph = []
1437
+ for line in lines[start:]:
1438
+ if not line.startswith("#") or line.strip() == "#":
1439
+ break
1440
+ paragraph.append(line.lstrip("#").strip())
1441
+ return re.sub(r"\s+", " ", " ".join(paragraph))
1442
+
1443
+
1444
+ def config_header_problem(names: list, config_text: str) -> str:
1445
+ """The one rule for "the header names every declaration", or "" when it does.
1446
+
1447
+ Returns the diagnostic naming the missing declaration. Deliberately reports
1448
+ no count: a count tells an author that two numbers differ, and the name tells
1449
+ them which line to write.
1450
+ """
1451
+ header = config_header_paragraph(config_text)
1452
+ if not header:
1453
+ return (
1454
+ "keel/config.yaml has no header paragraph listing its declarations "
1455
+ "(the one containing `independent declarations live here`), so "
1456
+ "nothing tells a project which keys it may write."
1457
+ )
1458
+ for name in names:
1459
+ if name not in header:
1460
+ return (
1461
+ f"keel/config.yaml's header does not name the `{name}` "
1462
+ "declaration, so a project reading it would never learn it may "
1463
+ "write one. Add it to the header's list."
1464
+ )
1465
+ return ""
1466
+
1467
+
1468
+ def write_authorize_config(repo: Path, body: str) -> None:
1469
+ (repo / "keel").mkdir(parents=True, exist_ok=True)
1470
+ (repo / "keel" / "config.yaml").write_text(body, encoding="utf-8")
1471
+
1472
+
1473
+ def guard_task_fixture(checked: bool = False) -> str:
1474
+ box = "x" if checked else " "
1475
+ return (
1476
+ "# Tasks\n\n## Invalidates\n\n- None.\n\n"
1477
+ f"- [{box}] 1.1 Exercise guarded feature\n"
1478
+ " - Covers:\n"
1479
+ " - E1: Guarded public behavior passes.\n"
1480
+ " - Touch:\n"
1481
+ " - src/feature.js\n"
1482
+ " - docs/**\n"
1483
+ " - Verify:\n"
1484
+ " - Strategy: evidence-first\n"
1485
+ " - Reason: this is a gate fixture; it exercises contract structure and has no executable behavior that can fail first\n"
1486
+ " - M1: node test.js\n"
1487
+ " - Evidence:\n"
1488
+ " - M1: pending\n"
1489
+ )
1490
+
1491
+
1492
+ # Exit code 3 means "this scenario did not run because an external runtime it
1493
+ # probes is absent". 0 is pass, 1 is fail, 2 is an unknown scenario or a usage
1494
+ # error, so conflating an unavailable runtime with either would hide both. The
1495
+ # reason is narrow on purpose: an inconvenient assertion, a hard fixture, or a
1496
+ # platform difference is a failure, never a skip.
1497
+ SKIPPED = 3
1498
+
1499
+
1500
+ def skip_scenario(label: str, reason: str) -> int:
1501
+ report(f"{label} scenario skipped: {reason}")
1502
+ return SKIPPED
1503
+
1504
+
1505
+ def run_scenario_processes(names: list, jobs: int) -> list:
1506
+ """Run each named scenario as its own --scenario subprocess in parallel.
1507
+
1508
+ Output is captured per scenario and the result list preserves the input
1509
+ order so a replay is deterministic regardless of completion timing.
1510
+ """
1511
+ # The entry point, which each scenario runs through (#409).
1512
+ script = str(ROOT / "scripts/validate_plugin.py")
1513
+
1514
+ def run_one(name: str):
1515
+ proc = subprocess.run(
1516
+ [sys.executable, script, "--scenario", name],
1517
+ capture_output=True,
1518
+ text=True,
1519
+ encoding="utf-8",
1520
+ errors="replace",
1521
+ )
1522
+ return proc.returncode, (proc.stdout or "") + (proc.stderr or "")
1523
+
1524
+ results = {}
1525
+ with ThreadPoolExecutor(max_workers=max(1, jobs)) as pool:
1526
+ futures = {pool.submit(run_one, name): name for name in names}
1527
+ for future in as_completed(futures):
1528
+ results[futures[future]] = future.result()
1529
+ return [(name, *results[name]) for name in names]