draht-codex 2026.7.30 → 2026.10.4-2

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.
Files changed (110) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +81 -0
  3. package/README.md +57 -6
  4. package/agents/debugger.md +12 -1
  5. package/agents/git-committer.md +1 -0
  6. package/agents/implementer.md +11 -2
  7. package/agents/investigator.md +75 -0
  8. package/agents/reviewer.md +7 -0
  9. package/agents/speaker.md +44 -0
  10. package/agents/verifier.md +4 -3
  11. package/bin/draht-tools.cjs +472 -41
  12. package/bin/judge +613 -0
  13. package/cli.mjs +769 -46
  14. package/commands/atomic-commit.md +1 -12
  15. package/commands/create-verification-skill.md +105 -0
  16. package/commands/discuss-phase.md +3 -14
  17. package/commands/execute-phase.md +7 -14
  18. package/commands/fix.md +38 -17
  19. package/commands/grill.md +66 -0
  20. package/commands/init-project.md +5 -15
  21. package/commands/map-codebase.md +1 -13
  22. package/commands/new-project.md +5 -15
  23. package/commands/next-milestone.md +2 -13
  24. package/commands/orchestrate.md +1 -1
  25. package/commands/pause-work.md +1 -8
  26. package/commands/plan-phase.md +3 -11
  27. package/commands/progress.md +0 -8
  28. package/commands/quick.md +3 -11
  29. package/commands/resolve-conflicts.md +72 -0
  30. package/commands/resume-work.md +0 -8
  31. package/commands/review.md +6 -13
  32. package/commands/speak.md +45 -0
  33. package/commands/triage.md +161 -0
  34. package/commands/verify-work.md +6 -13
  35. package/commands/why.md +141 -0
  36. package/graph-archive.mjs +125 -0
  37. package/graph-manifest.mjs +97 -0
  38. package/hooks/hooks.json +39 -0
  39. package/package.json +5 -3
  40. package/scripts/gsd-quality-gate.cjs +3 -3
  41. package/scripts/judge-hook.cjs +42 -0
  42. package/scripts/judge-hook.py +391 -0
  43. package/scripts/judgegates.py +673 -0
  44. package/scripts/judgelib.py +382 -0
  45. package/scripts/speak.cjs +202 -0
  46. package/skills/atomic-commit/SKILL.md +1 -1
  47. package/skills/atomic-commit/command.md +62 -0
  48. package/skills/blast-radius/SKILL.md +56 -0
  49. package/skills/brainstorming/SKILL.md +11 -4
  50. package/skills/cinematic-continuation/SKILL.md +111 -0
  51. package/skills/cinematic-continuation/references/continuity-schema.md +75 -0
  52. package/skills/cinematic-continuation/references/seedance-adapter.md +44 -0
  53. package/skills/cinematic-continuation/references/style-bible.md +223 -0
  54. package/skills/cinematic-continuation/scripts/compile-continuation.mjs +173 -0
  55. package/skills/cinematic-continuation/templates/continuation-spec.json +50 -0
  56. package/skills/create-verification-skill/SKILL.md +14 -0
  57. package/skills/create-verification-skill/command.md +105 -0
  58. package/skills/debugging-workflow/SKILL.md +38 -10
  59. package/skills/discuss-phase/SKILL.md +1 -1
  60. package/skills/discuss-phase/command.md +44 -0
  61. package/skills/draht/SKILL.md +119 -0
  62. package/skills/epistemics/SKILL.md +99 -0
  63. package/skills/execute-phase/SKILL.md +1 -1
  64. package/skills/execute-phase/command.md +170 -0
  65. package/skills/explainers/SKILL.md +65 -0
  66. package/skills/fix/SKILL.md +1 -1
  67. package/skills/fix/command.md +154 -0
  68. package/skills/grill/SKILL.md +14 -0
  69. package/skills/grill/command.md +66 -0
  70. package/skills/gsd-workflow/SKILL.md +2 -0
  71. package/skills/init-project/SKILL.md +1 -1
  72. package/skills/init-project/command.md +57 -0
  73. package/skills/judge/SKILL.md +57 -0
  74. package/skills/map-codebase/SKILL.md +1 -1
  75. package/skills/map-codebase/command.md +61 -0
  76. package/skills/new-project/SKILL.md +1 -1
  77. package/skills/new-project/command.md +64 -0
  78. package/skills/next-milestone/SKILL.md +1 -1
  79. package/skills/next-milestone/command.md +42 -0
  80. package/skills/orchestrate/SKILL.md +1 -1
  81. package/skills/orchestrate/command.md +106 -0
  82. package/skills/orchestrate-loop/SKILL.md +1 -1
  83. package/skills/orchestrate-loop/command.md +100 -0
  84. package/skills/pause-work/SKILL.md +1 -1
  85. package/skills/pause-work/command.md +32 -0
  86. package/skills/plan-phase/SKILL.md +1 -1
  87. package/skills/plan-phase/command.md +140 -0
  88. package/skills/progress/SKILL.md +1 -1
  89. package/skills/progress/command.md +22 -0
  90. package/skills/quick/SKILL.md +1 -1
  91. package/skills/quick/command.md +91 -0
  92. package/skills/resolve-conflicts/SKILL.md +14 -0
  93. package/skills/resolve-conflicts/command.md +72 -0
  94. package/skills/resume-work/SKILL.md +1 -1
  95. package/skills/resume-work/command.md +27 -0
  96. package/skills/review/SKILL.md +1 -1
  97. package/skills/review/command.md +83 -0
  98. package/skills/saga-spawner/SKILL.md +131 -0
  99. package/skills/speak/SKILL.md +14 -0
  100. package/skills/speak/command.md +45 -0
  101. package/skills/tdd-workflow/SKILL.md +2 -0
  102. package/skills/triage/SKILL.md +14 -0
  103. package/skills/triage/command.md +161 -0
  104. package/skills/typescript-discipline/SKILL.md +50 -0
  105. package/skills/typescript-discipline/references/patterns.md +294 -0
  106. package/skills/unslop/SKILL.md +119 -0
  107. package/skills/verify-work/SKILL.md +1 -1
  108. package/skills/verify-work/command.md +117 -0
  109. package/skills/why/SKILL.md +14 -0
  110. package/skills/why/command.md +141 -0
@@ -0,0 +1,673 @@
1
+ """Gate judging: is the test the agent just wrote a real gate, or a rubber stamp?
2
+
3
+ The agent writing a test is the same probabilistic process the test is meant to
4
+ constrain, so a test it wrote is a claim, not evidence. This module turns that
5
+ claim into evidence wherever a machine can, and leaves exactly one question for
6
+ the human: is this the right thing to gate, and is the bar high enough.
7
+
8
+ Two stages, because the two questions can only be answered at different moments:
9
+
10
+ red — the test exists, the implementation does not. Run the test against the
11
+ code as it stands. It MUST fail, and how it fails matters: an assertion
12
+ failure is a real red, an import or compile error is a weak one (it
13
+ proves a module is missing, not that behaviour is wrong), and a pass
14
+ proves the test is not a gate at all.
15
+ green — the implementation landed and the test passes. Now mutate the source
16
+ lines the change touched and re-run: a test that survives every
17
+ mutation does not bite.
18
+
19
+ Everything here is best-effort and fail-open. A repo with no runnable test
20
+ command, no git, or a wedged suite produces a card with less evidence on it,
21
+ never a blocked session.
22
+ """
23
+
24
+ import json
25
+ import os
26
+ import re
27
+ import shutil
28
+ import subprocess
29
+ import tempfile
30
+ import time
31
+ from pathlib import Path
32
+
33
+ import judgelib as J
34
+
35
+ LEDGER = J.ROOT / "gates.jsonl"
36
+ SESSIONS = J.ROOT / "sessions"
37
+
38
+ # Defaults; overridden per repo by .planning/config.json → "gates".
39
+ DEFAULTS = {
40
+ "enabled": True,
41
+ "testCommand": None, # "{file}" is substituted; falls back to inference
42
+ "timeout": 180, # seconds per test run
43
+ "mutants": 5, # how many mutations to try at the green stage
44
+ "budget": 600, # seconds for a whole verification pass
45
+ }
46
+
47
+ # --------------------------------------------------------------------------- #
48
+ # file classification
49
+ # --------------------------------------------------------------------------- #
50
+
51
+ TEST_PATH_RE = re.compile(r"(^|/)(tests?|specs?|__tests__|testdata)(/|$)")
52
+ TEST_FILE_RE = re.compile(
53
+ r"(^|/)(test_[^/]+\.py"
54
+ r"|[^/]+_test\.(py|go|rs|ts|js|mjs|cjs)"
55
+ r"|[^/]+[._-](test|spec)\.(ts|tsx|js|jsx|mjs|cjs|py|rb|php)"
56
+ r"|[^/]+Test\.(java|kt|scala|cs)"
57
+ r"|[^/]+Tests\.(cs|swift))$"
58
+ )
59
+ CODE_SUFFIXES = {
60
+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py", ".go", ".rs", ".rb",
61
+ ".java", ".kt", ".swift", ".c", ".h", ".cc", ".cpp", ".hpp", ".cs", ".php",
62
+ ".scala", ".ex", ".exs", ".zig", ".lua",
63
+ }
64
+
65
+
66
+ def is_test_file(path):
67
+ p = str(path).replace("\\", "/")
68
+ return bool(TEST_FILE_RE.search(p) or (TEST_PATH_RE.search(p) and Path(p).suffix in CODE_SUFFIXES))
69
+
70
+
71
+ def is_code_file(path):
72
+ return Path(str(path)).suffix in CODE_SUFFIXES
73
+
74
+
75
+ def is_gateable_source(path):
76
+ """A source edit that a gate should have preceded: code, and not a test."""
77
+ return is_code_file(path) and not is_test_file(path)
78
+
79
+
80
+ # --------------------------------------------------------------------------- #
81
+ # per-session state: which tests have been written but not yet judged
82
+ # --------------------------------------------------------------------------- #
83
+
84
+ def _session_path(sid):
85
+ return SESSIONS / f"{(sid or 'unknown').replace('/', '_')}.json"
86
+
87
+
88
+ def load_session(sid):
89
+ data = J._read_json(_session_path(sid))
90
+ if not isinstance(data, dict):
91
+ data = {}
92
+ data.setdefault("pending", {}) # test path → first-seen timestamp
93
+ data.setdefault("gates", {}) # card id → {"files": [...], "stage": "red"}
94
+ return data
95
+
96
+
97
+ def save_session(sid, data):
98
+ SESSIONS.mkdir(parents=True, exist_ok=True)
99
+ J._write_json(_session_path(sid), data)
100
+
101
+
102
+ def record_test_edit(sid, path):
103
+ data = load_session(sid)
104
+ data["pending"].setdefault(os.path.realpath(str(path)), time.time())
105
+ save_session(sid, data)
106
+
107
+
108
+ def take_pending(sid):
109
+ data = load_session(sid)
110
+ files = sorted(data["pending"])
111
+ data["pending"] = {}
112
+ save_session(sid, data)
113
+ return files
114
+
115
+
116
+ def remember_gate(sid, card_id, files, stage):
117
+ data = load_session(sid)
118
+ data["gates"][card_id] = {"files": files, "stage": stage, "ts": time.time()}
119
+ save_session(sid, data)
120
+
121
+
122
+ def awaiting_green(sid):
123
+ """Gates approved at red whose mutation pass has not run yet."""
124
+ data = load_session(sid)
125
+ return {cid: g for cid, g in data["gates"].items() if g.get("stage") == "red"}
126
+
127
+
128
+ def mark_green_done(sid, card_id):
129
+ data = load_session(sid)
130
+ if card_id in data["gates"]:
131
+ data["gates"][card_id]["stage"] = "green"
132
+ save_session(sid, data)
133
+
134
+
135
+ # --------------------------------------------------------------------------- #
136
+ # repo helpers
137
+ # --------------------------------------------------------------------------- #
138
+
139
+ def _run(args, cwd=None, timeout=60, env=None):
140
+ try:
141
+ p = subprocess.run(args, cwd=cwd, timeout=timeout, capture_output=True, text=True, env=env)
142
+ return p.returncode, (p.stdout or "") + (p.stderr or "")
143
+ except subprocess.TimeoutExpired:
144
+ return 124, "timed out"
145
+ except OSError as exc:
146
+ return 127, str(exc)
147
+
148
+
149
+ def repo_root(cwd):
150
+ """The repo containing `cwd`, as a real path.
151
+
152
+ Hosts hand over a cwd that may travel through symlinks (`/var/...` for
153
+ `/private/var/...` on macOS, a symlinked home, `/tmp`), while git always
154
+ answers with the real one. Mixing the two silently produces `../../..`
155
+ paths that point outside the repo, so every path this module handles is
156
+ resolved once, here and in `rel_in_repo`.
157
+ """
158
+ code, out = _run(["git", "rev-parse", "--show-toplevel"], cwd=cwd)
159
+ if code != 0 or not out.strip():
160
+ return None
161
+ return os.path.realpath(out.strip())
162
+
163
+
164
+ def rel_in_repo(repo, path):
165
+ """`path` relative to `repo`, or None when it is not inside it."""
166
+ if not repo or not path:
167
+ return None
168
+ rel = os.path.relpath(os.path.realpath(path), os.path.realpath(repo))
169
+ if rel.startswith("..") or os.path.isabs(rel):
170
+ return None
171
+ return rel
172
+
173
+
174
+ def config(repo):
175
+ cfg = dict(DEFAULTS)
176
+ if os.environ.get("JUDGE_GATES") in ("0", "false", "off"):
177
+ cfg["enabled"] = False
178
+ if not repo:
179
+ return cfg
180
+ data = J._read_json(Path(repo) / ".planning" / "config.json") or {}
181
+ gates = data.get("gates")
182
+ if isinstance(gates, dict):
183
+ for key in DEFAULTS:
184
+ if key in gates:
185
+ cfg[key] = gates[key]
186
+ return cfg
187
+
188
+
189
+ def changed_files(repo):
190
+ code, out = _run(["git", "status", "--porcelain=1", "-z"], cwd=repo)
191
+ if code != 0:
192
+ return []
193
+ files = []
194
+ for entry in out.split("\0"):
195
+ if len(entry) > 3:
196
+ files.append(entry[3:])
197
+ return files
198
+
199
+
200
+ def changed_lines(repo, path):
201
+ """1-based line numbers added or changed in `path` versus HEAD."""
202
+ code, out = _run(["git", "diff", "-U0", "HEAD", "--", path], cwd=repo)
203
+ if code != 0:
204
+ return []
205
+ lines, current = [], 0
206
+ for line in out.split("\n"):
207
+ head = re.match(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line)
208
+ if head:
209
+ current = int(head.group(1))
210
+ continue
211
+ if line.startswith("+") and not line.startswith("+++"):
212
+ lines.append(current)
213
+ current += 1
214
+ return lines
215
+
216
+
217
+ def added_test_names(repo, paths):
218
+ """The `it(...)` / `def test_...` names this change introduces — the claims."""
219
+ names = []
220
+ patterns = [
221
+ re.compile(r"""(?:it|test|describe)\s*(?:\.\w+)?\s*\(\s*[\"'`](.+?)[\"'`]"""),
222
+ re.compile(r"""def\s+(test_[A-Za-z0-9_]+)"""),
223
+ re.compile(r"""func\s+(Test[A-Za-z0-9_]+)"""),
224
+ re.compile(r"""fn\s+(\w+)\s*\(\s*\)\s*\{?\s*(?://.*)?$"""),
225
+ ]
226
+ for path in paths:
227
+ code, out = _run(["git", "diff", "HEAD", "--", path], cwd=repo)
228
+ if code != 0 or not out.strip():
229
+ try:
230
+ out = "\n".join("+" + ln for ln in Path(repo, path).read_text().split("\n"))
231
+ except OSError:
232
+ continue
233
+ for line in out.split("\n"):
234
+ if not line.startswith("+") or line.startswith("+++"):
235
+ continue
236
+ body = line[1:]
237
+ for pattern in patterns:
238
+ found = pattern.search(body)
239
+ if found:
240
+ names.append(found.group(1).strip())
241
+ break
242
+ seen, unique = set(), []
243
+ for name in names:
244
+ if name not in seen:
245
+ seen.add(name)
246
+ unique.append(name)
247
+ return unique
248
+
249
+
250
+ def added_lines_text(repo, paths, limit=6000):
251
+ chunks = []
252
+ for path in paths:
253
+ code, out = _run(["git", "diff", "HEAD", "--", path], cwd=repo)
254
+ if code != 0 or not out.strip():
255
+ try:
256
+ out = Path(repo, path).read_text()
257
+ except OSError:
258
+ continue
259
+ chunks.append(f"── {path}\n{out}")
260
+ return "\n\n".join(chunks)[:limit]
261
+
262
+
263
+ # --------------------------------------------------------------------------- #
264
+ # static smells — cheap, no execution, work in any repo
265
+ # --------------------------------------------------------------------------- #
266
+
267
+ ASSERT_RE = re.compile(r"\b(expect|assert|assert_|should|require|assertEqual|assertThat|t\.(Error|Fatal))\b")
268
+ MOCK_ASSERT_RE = re.compile(r"(toHaveBeenCalled|toBeCalled|assert_called|assert_any_call|verify\(|\.called\b|calledWith)")
269
+ SNAPSHOT_RE = re.compile(r"toMatchSnapshot|toMatchInlineSnapshot|assert_snapshot")
270
+ SKIP_RE = re.compile(r"\b(it|test|describe)\.(skip|todo)\b|\bxit\(|\bxdescribe\(|@pytest\.mark\.skip|t\.Skip\(")
271
+ ONLY_RE = re.compile(r"\b(it|test|describe)\.only\b|\bfit\(|\bfdescribe\(")
272
+ TAUTOLOGY_RE = re.compile(r"expect\(\s*(true|1|\"\w*\")\s*\)\s*\.\s*(toBe|toEqual)\s*\(\s*\1\s*\)|assert\s+True\b|assertTrue\(True\)")
273
+ PRIVATE_RE = re.compile(r"@ts-expect-error|@ts-ignore|\[[\"']_|\._[a-zA-Z]")
274
+ EMPTY_CATCH_RE = re.compile(r"catch\s*(\([^)]*\))?\s*\{\s*\}|except[^:]*:\s*(pass|\.\.\.)\s*$")
275
+
276
+
277
+ def smells(text):
278
+ """Structural tells that a test is not the gate it looks like."""
279
+ added = [ln[1:] for ln in text.split("\n") if ln.startswith("+") and not ln.startswith("+++")]
280
+ body = "\n".join(added) if added else text
281
+ found = []
282
+
283
+ def flag(code, note):
284
+ found.append({"code": code, "note": note})
285
+
286
+ asserts = [ln for ln in body.split("\n") if ASSERT_RE.search(ln)]
287
+ if not asserts:
288
+ flag("no-assertion", "no assertion in the added test body — it can only fail by throwing")
289
+ elif all(MOCK_ASSERT_RE.search(ln) for ln in asserts):
290
+ flag("mock-only", "every assertion is about a mock being called, not about a result")
291
+ elif all(SNAPSHOT_RE.search(ln) for ln in asserts):
292
+ flag("snapshot-only", "the only assertion is a snapshot — it ratifies whatever the code does")
293
+ if TAUTOLOGY_RE.search(body):
294
+ flag("tautology", "asserts a constant against itself — passes for any implementation")
295
+ if SKIP_RE.search(body):
296
+ flag("skipped", "the test is skipped or todo — a gate that never runs")
297
+ if ONLY_RE.search(body):
298
+ flag("only", "`.only` left in — it silences every other test in the file")
299
+ if PRIVATE_RE.search(body):
300
+ flag("internals", "reaches into private internals or suppresses the type checker")
301
+ if EMPTY_CATCH_RE.search(body):
302
+ flag("swallowed", "an empty catch/except in a test hides the failure it should report")
303
+ return found
304
+
305
+
306
+ # --------------------------------------------------------------------------- #
307
+ # test command resolution
308
+ # --------------------------------------------------------------------------- #
309
+
310
+ def test_command(repo, cfg, test_file):
311
+ """Argv for running one test file, or None when nothing can be inferred."""
312
+ template = cfg.get("testCommand")
313
+ if template:
314
+ return ["sh", "-c", template.replace("{file}", test_file)]
315
+
316
+ root = Path(repo)
317
+ suffix = Path(test_file).suffix
318
+ pkg = J._read_json(root / "package.json") or {}
319
+ deps = {**(pkg.get("dependencies") or {}), **(pkg.get("devDependencies") or {})}
320
+ scripts = pkg.get("scripts") or {}
321
+
322
+ if suffix in {".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"}:
323
+ if "vitest" in deps:
324
+ return ["npx", "--no-install", "vitest", "run", test_file]
325
+ if "jest" in deps:
326
+ return ["npx", "--no-install", "jest", "--silent", test_file]
327
+ if "bun test" in str(scripts.get("test", "")) or (root / "bun.lock").exists():
328
+ return ["bun", "test", test_file]
329
+ if "node --test" in str(scripts.get("test", "")) or test_file.endswith(".test.mjs"):
330
+ return ["node", "--test", test_file]
331
+ if suffix == ".py":
332
+ if (root / "pyproject.toml").exists() or (root / "pytest.ini").exists() or "pytest" in str(scripts):
333
+ return ["python3", "-m", "pytest", "-q", test_file]
334
+ return ["python3", "-m", "unittest", test_file]
335
+ if suffix == ".go":
336
+ return ["go", "test", "./" + str(Path(test_file).parent)]
337
+ if suffix == ".rs":
338
+ return ["cargo", "test"]
339
+ return None
340
+
341
+
342
+ # --------------------------------------------------------------------------- #
343
+ # isolated replay: a throwaway worktree, never the session's own files
344
+ # --------------------------------------------------------------------------- #
345
+
346
+ DEP_DIRS = ("node_modules", ".venv", "venv", "vendor")
347
+
348
+ # A test runner already in the environment poisons the replay: a nested
349
+ # `node --test` that inherits NODE_TEST_CONTEXT reports itself to the outer
350
+ # runner and exits 0 whatever happened, which would make every mutation look
351
+ # survived and every red look green. Whatever spawned this hook — a host, a CI
352
+ # step, another test runner — the replay gets a clean slate.
353
+ POISON_ENV_PREFIXES = ("NODE_TEST", "VITEST", "JEST", "NPM_CONFIG", "npm_", "MOCHA", "TAP_", "BUN_TEST")
354
+ POISON_ENV_KEYS = ("NODE_OPTIONS", "NODE_ENV", "TEST_ENV", "FORCE_COLOR")
355
+
356
+
357
+ def clean_env():
358
+ env = {
359
+ key: value
360
+ for key, value in os.environ.items()
361
+ if key not in POISON_ENV_KEYS and not key.startswith(POISON_ENV_PREFIXES)
362
+ }
363
+ # CI keeps runners non-interactive; JUDGE_GATES stops a replayed suite from
364
+ # gating itself if the repo under test happens to be this plugin.
365
+ env.update({"CI": "1", "JUDGE_GATES": "0", "NO_COLOR": "1"})
366
+ return env
367
+
368
+
369
+ class Replay:
370
+ """A detached worktree at HEAD that the session's changes are copied into.
371
+
372
+ The point is to run the suite against states the working tree is not in —
373
+ the implementation reverted, or a mutation applied — without ever touching
374
+ the files the session is editing.
375
+ """
376
+
377
+ def __init__(self, repo, cfg):
378
+ self.repo = Path(repo)
379
+ self.cfg = cfg
380
+ self.dir = None
381
+ self.deadline = time.time() + cfg["budget"]
382
+
383
+ def __enter__(self):
384
+ self.dir = Path(tempfile.mkdtemp(prefix="judge-gate-"))
385
+ target = self.dir / "tree"
386
+ code, out = _run(["git", "worktree", "add", "--detach", str(target), "HEAD"], cwd=str(self.repo), timeout=120)
387
+ if code != 0:
388
+ shutil.rmtree(self.dir, ignore_errors=True)
389
+ self.dir = None
390
+ raise RuntimeError(f"worktree failed: {out.strip()[:200]}")
391
+ self.tree = target
392
+ self._link_deps()
393
+ return self
394
+
395
+ def __exit__(self, *_):
396
+ if self.dir:
397
+ _run(["git", "worktree", "remove", "--force", str(self.tree)], cwd=str(self.repo), timeout=120)
398
+ shutil.rmtree(self.dir, ignore_errors=True)
399
+ return False
400
+
401
+ def _link_deps(self):
402
+ """Installed dependencies are symlinked in — reinstalling is not an option."""
403
+ for name in DEP_DIRS:
404
+ for source in [self.repo / name] + list(self.repo.glob(f"*/*/{name}")) + list(self.repo.glob(f"*/{name}")):
405
+ if not source.is_dir():
406
+ continue
407
+ link = self.tree / source.relative_to(self.repo)
408
+ if link.exists() or link.is_symlink():
409
+ continue
410
+ link.parent.mkdir(parents=True, exist_ok=True)
411
+ try:
412
+ link.symlink_to(source, target_is_directory=True)
413
+ except OSError:
414
+ pass
415
+
416
+ def put_working(self, rel_paths):
417
+ """Copy the session's current version of these files into the replay."""
418
+ for rel in rel_paths:
419
+ source, dest = self.repo / rel, self.tree / rel
420
+ dest.parent.mkdir(parents=True, exist_ok=True)
421
+ if source.exists():
422
+ shutil.copy2(source, dest)
423
+ elif dest.exists():
424
+ dest.unlink()
425
+
426
+ def put_head(self, rel_paths):
427
+ """Restore these files to their committed state inside the replay."""
428
+ for rel in rel_paths:
429
+ code, _ = _run(["git", "checkout", "HEAD", "--", rel], cwd=str(self.tree))
430
+ if code != 0:
431
+ dest = self.tree / rel
432
+ if dest.exists():
433
+ dest.unlink()
434
+
435
+ def read(self, rel):
436
+ return (self.tree / rel).read_text()
437
+
438
+ def write(self, rel, text):
439
+ (self.tree / rel).write_text(text)
440
+
441
+ def run_test(self, test_file):
442
+ argv = test_command(str(self.repo), self.cfg, test_file)
443
+ if argv is None:
444
+ return None
445
+ left = max(5, min(self.cfg["timeout"], int(self.deadline - time.time())))
446
+ code, out = _run(argv, cwd=str(self.tree), timeout=left, env=clean_env())
447
+ return {"exit": code, "output": out[-4000:], "argv": argv}
448
+
449
+
450
+ # --------------------------------------------------------------------------- #
451
+ # failure classification
452
+ # --------------------------------------------------------------------------- #
453
+
454
+ IMPORT_ERROR_RE = re.compile(
455
+ r"cannot find module|module not found|modulenotfounderror|importerror|no module named"
456
+ r"|is not defined|cannot find name|has no attribute|undefined: |unresolved import"
457
+ r"|failed to resolve|collection error|error ts\d+|syntaxerror|parse error|build failed",
458
+ re.I,
459
+ )
460
+
461
+
462
+ def classify_failure(result):
463
+ """'pass' | 'assertion' | 'error' | 'timeout' | 'unrunnable' for one run."""
464
+ if result is None:
465
+ return "unrunnable"
466
+ if result["exit"] == 124:
467
+ return "timeout"
468
+ if result["exit"] == 127:
469
+ return "unrunnable"
470
+ if result["exit"] == 0:
471
+ return "pass"
472
+ return "error" if IMPORT_ERROR_RE.search(result["output"] or "") else "assertion"
473
+
474
+
475
+ # --------------------------------------------------------------------------- #
476
+ # mutation operators
477
+ # --------------------------------------------------------------------------- #
478
+
479
+ MUTATIONS = [
480
+ (re.compile(r"==="), "!=="), (re.compile(r"!=="), "==="),
481
+ (re.compile(r"(?<![=!<>])==(?!=)"), "!="), (re.compile(r"!=(?!=)"), "=="),
482
+ (re.compile(r"<=(?!=)"), "<"), (re.compile(r">=(?!=)"), ">"),
483
+ (re.compile(r"(?<![<>=])<(?![=<])"), "<="), (re.compile(r"(?<![<>=])>(?![=>])"), ">="),
484
+ (re.compile(r"&&"), "||"), (re.compile(r"\|\|"), "&&"),
485
+ (re.compile(r"\btrue\b"), "false"), (re.compile(r"\bfalse\b"), "true"),
486
+ (re.compile(r"\bTrue\b"), "False"), (re.compile(r"\bFalse\b"), "True"),
487
+ (re.compile(r"\band\b"), "or"), (re.compile(r"\bor\b"), "and"),
488
+ (re.compile(r"(?<![\w.])0(?![\w.])"), "1"), (re.compile(r"(?<![\w.])1(?![\w.])"), "2"),
489
+ (re.compile(r"\+(?![+=])"), "-"),
490
+ ]
491
+
492
+ SKIP_MUTATION_RE = re.compile(r"^\s*(//|#|/\*|\*|import\b|from\b|export\s+(type|interface)\b)")
493
+
494
+
495
+ def mutants_for(repo, path, lines, cap):
496
+ """Candidate single-token mutations on the lines this change touched."""
497
+ try:
498
+ text = Path(repo, path).read_text()
499
+ except OSError:
500
+ return []
501
+ source = text.split("\n")
502
+ out = []
503
+ for lineno in lines:
504
+ if lineno < 1 or lineno > len(source):
505
+ continue
506
+ line = source[lineno - 1]
507
+ if not line.strip() or SKIP_MUTATION_RE.match(line):
508
+ continue
509
+ for pattern, replacement in MUTATIONS:
510
+ found = pattern.search(line)
511
+ if not found:
512
+ continue
513
+ mutated = line[:found.start()] + replacement + line[found.end():]
514
+ out.append({
515
+ "file": path, "line": lineno,
516
+ "op": f"{found.group(0)} → {replacement}",
517
+ "before": line.strip()[:120], "after": mutated.strip()[:120],
518
+ })
519
+ break
520
+ # Spread the sample across distinct lines rather than clustering on one.
521
+ return out[:cap] if len(out) <= cap else [out[i] for i in range(0, len(out), max(1, len(out) // cap))][:cap]
522
+
523
+
524
+ def apply_mutant(replay, mutant):
525
+ text = replay.read(mutant["file"]).split("\n")
526
+ text[mutant["line"] - 1] = text[mutant["line"] - 1].replace(
527
+ mutant["op"].split(" → ")[0], mutant["op"].split(" → ")[1], 1
528
+ )
529
+ replay.write(mutant["file"], "\n".join(text))
530
+
531
+
532
+ # --------------------------------------------------------------------------- #
533
+ # the two verification passes
534
+ # --------------------------------------------------------------------------- #
535
+
536
+ def verify_red(repo, cfg, test_files, source_files):
537
+ """Does the new test fail against the code as it stands, and how?
538
+
539
+ Reports the mechanical fact only: `passes`, `real-red`, `weak-red`,
540
+ `timeout`, `unrunnable`. What a pass *means* depends on the moment and is
541
+ the caller's call — at the red gate, where an implementation is about to be
542
+ written, a passing test cannot constrain it and is a fake gate; at the end
543
+ of a turn with no implementation coming, a test written for behaviour that
544
+ already exists is expected to pass and only the mutation pass can score it.
545
+ """
546
+ result = {"stage": "red", "status": "done", "runs": [], "reverted": list(source_files)}
547
+ try:
548
+ with Replay(repo, cfg) as replay:
549
+ replay.put_working(test_files)
550
+ if source_files:
551
+ # A gate is judged against the implementation it precedes, so any
552
+ # source already written in this turn is reverted for the replay.
553
+ replay.put_head(source_files)
554
+ for test_file in test_files:
555
+ run = replay.run_test(test_file)
556
+ verdict = classify_failure(run)
557
+ result["runs"].append({
558
+ "file": test_file, "verdict": verdict,
559
+ "command": " ".join(run["argv"]) if run else None,
560
+ "output": (run or {}).get("output", "")[-1500:],
561
+ })
562
+ except Exception as exc:
563
+ return {"stage": "red", "status": "error", "error": str(exc)[:300], "runs": [],
564
+ "reverted": list(source_files)}
565
+
566
+ verdicts = [r["verdict"] for r in result["runs"]]
567
+ if not verdicts or all(v == "unrunnable" for v in verdicts):
568
+ result["conclusion"] = "unrunnable"
569
+ elif "pass" in verdicts:
570
+ result["conclusion"] = "passes"
571
+ elif "assertion" in verdicts:
572
+ result["conclusion"] = "real-red"
573
+ elif "timeout" in verdicts:
574
+ result["conclusion"] = "timeout"
575
+ else:
576
+ result["conclusion"] = "weak-red"
577
+ return result
578
+
579
+
580
+ def verify_green(repo, cfg, test_files, source_files):
581
+ """The test passes — now does it notice when the implementation is wrong?"""
582
+ result = {"stage": "green", "status": "done", "mutants": [], "baseline": None}
583
+ cap = int(cfg["mutants"])
584
+ try:
585
+ with Replay(repo, cfg) as replay:
586
+ replay.put_working(test_files + source_files)
587
+ baseline = replay.run_test(test_files[0])
588
+ result["baseline"] = classify_failure(baseline)
589
+ result["command"] = " ".join(baseline["argv"]) if baseline else None
590
+ if result["baseline"] != "pass":
591
+ result["note"] = "the suite does not pass in a clean replay, so mutation results would be noise"
592
+ return result
593
+
594
+ candidates = []
595
+ for path in source_files:
596
+ candidates += mutants_for(repo, path, changed_lines(repo, path), cap)
597
+ candidates = candidates[:cap]
598
+ if not candidates:
599
+ result["note"] = "no single-token mutation applies to the lines this change touched"
600
+
601
+ for mutant in candidates:
602
+ if time.time() > replay.deadline:
603
+ result["note"] = "verification budget spent — partial result"
604
+ break
605
+ apply_mutant(replay, mutant)
606
+ run = replay.run_test(test_files[0])
607
+ verdict = classify_failure(run)
608
+ mutant["result"] = verdict
609
+ # A mutant the suite cannot even load proves nothing about the test.
610
+ mutant["killed"] = verdict in ("assertion", "timeout")
611
+ mutant["invalid"] = verdict == "error"
612
+ result["mutants"].append(mutant)
613
+ replay.put_working([mutant["file"]])
614
+ except Exception as exc:
615
+ return {"stage": "green", "status": "error", "error": str(exc)[:300], "mutants": []}
616
+
617
+ scored = [m for m in result["mutants"] if not m.get("invalid")]
618
+ result["killed"] = sum(1 for m in scored if m["killed"])
619
+ result["scored"] = len(scored)
620
+ if result["baseline"] != "pass":
621
+ result["conclusion"] = "unverified"
622
+ elif not scored:
623
+ result["conclusion"] = "unverified"
624
+ elif result["killed"] == 0:
625
+ result["conclusion"] = "rubber-stamp"
626
+ elif result["killed"] < result["scored"]:
627
+ result["conclusion"] = "partial"
628
+ else:
629
+ result["conclusion"] = "bites"
630
+ return result
631
+
632
+
633
+ # --------------------------------------------------------------------------- #
634
+ # ledger — so "how good are our gates" is a trend, not a feeling
635
+ # --------------------------------------------------------------------------- #
636
+
637
+ def append_ledger(card):
638
+ meta = card.get("meta") or {}
639
+ verify = meta.get("verify") or {}
640
+ record = {
641
+ "ts": card.get("decided_at") or time.time(),
642
+ "card": card["id"],
643
+ "repo": Path(card.get("cwd") or ".").name,
644
+ "branch": meta.get("branch", ""),
645
+ "stage": meta.get("stage", ""),
646
+ "files": meta.get("files", []),
647
+ "claims": meta.get("claims", []),
648
+ "conclusion": verify.get("conclusion", ""),
649
+ "killed": verify.get("killed"),
650
+ "scored": verify.get("scored"),
651
+ "smells": [s["code"] for s in meta.get("smells", [])],
652
+ "verdict": card.get("verdict", ""),
653
+ "auto": bool(meta.get("auto")),
654
+ "comment": card.get("comment", ""),
655
+ }
656
+ J.ensure_dirs()
657
+ with LEDGER.open("a") as fh:
658
+ fh.write(json.dumps(record) + "\n")
659
+
660
+
661
+ def read_ledger(limit=None):
662
+ if not LEDGER.exists():
663
+ return []
664
+ records = []
665
+ for line in LEDGER.read_text().split("\n"):
666
+ line = line.strip()
667
+ if not line:
668
+ continue
669
+ try:
670
+ records.append(json.loads(line))
671
+ except ValueError:
672
+ continue
673
+ return records[-limit:] if limit else records