deepmodebot 0.10.0 → 0.11.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.
Files changed (75) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.omp-plugin/marketplace.json +2 -2
  4. package/README.md +15 -6
  5. package/bin/deepmodebot.mjs +104 -10
  6. package/native/dmb-gate/Cargo.toml +1 -1
  7. package/native/dmb-gate/src/agents.rs +58 -25
  8. package/native/dmb-gate/src/ci.rs +530 -14
  9. package/native/dmb-gate/src/main.rs +215 -7
  10. package/native/dmb-gate/src/reward.rs +1895 -242
  11. package/native/dmb-gate/src/sim.rs +969 -0
  12. package/native/dmb-gate/src/slop.rs +1061 -295
  13. package/package.json +1 -1
  14. package/plugins/deepmodebot/.antigravity-plugin/plugin.json +1 -1
  15. package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +1 -1
  16. package/plugins/deepmodebot/.claude-plugin/plugin.json +1 -1
  17. package/plugins/deepmodebot/.codex-plugin/plugin.json +2 -2
  18. package/plugins/deepmodebot/agents/comment-sicko.md +29 -0
  19. package/plugins/deepmodebot/agents/researcher.md +29 -0
  20. package/plugins/deepmodebot/agents/reviewer.md +29 -0
  21. package/plugins/deepmodebot/agents/scout.md +28 -0
  22. package/plugins/deepmodebot/agents/security-reviewer.md +27 -0
  23. package/plugins/deepmodebot/commands/deep.md +3 -2
  24. package/plugins/deepmodebot/commands/tournament.md +1 -1
  25. package/plugins/deepmodebot/hooks/hooks.json +12 -2
  26. package/plugins/deepmodebot/hooks.json +1 -1
  27. package/plugins/deepmodebot/scripts/antigravity-guard.mjs +740 -37
  28. package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +2 -2
  29. package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +19 -11
  30. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +51 -20
  31. package/plugins/deepmodebot/skills/deepmodebot/assets/autoroute/autoroute.py +54 -49
  32. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +4 -0
  33. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +658 -21
  34. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/holdout_guard_cases.json +272 -0
  35. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +774 -23
  36. package/plugins/deepmodebot/skills/deepmodebot/assets/f2p-gate/f2p_gate.py +547 -0
  37. package/plugins/deepmodebot/skills/deepmodebot/assets/gap-audit/gap_audit.py +5 -11
  38. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +4 -4
  39. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +53 -6
  40. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +48 -2
  41. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/local_ci.py +262 -6
  42. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/slop_gate.py +529 -122
  43. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +747 -46
  44. package/plugins/deepmodebot/skills/deepmodebot/assets/memory/project_memory.py +404 -5
  45. package/plugins/deepmodebot/skills/deepmodebot/assets/mutation/mutation_gate.py +798 -0
  46. package/plugins/deepmodebot/skills/deepmodebot/assets/reward-guard/reward_guard.py +2050 -200
  47. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule-paths.json +44 -1
  48. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule_ledger.py +278 -252
  49. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rules_watch.py +436 -0
  50. package/plugins/deepmodebot/skills/deepmodebot/assets/self-grill/self_grill.py +594 -18
  51. package/plugins/deepmodebot/skills/deepmodebot/assets/setup/project_setup.py +41 -5
  52. package/plugins/deepmodebot/skills/deepmodebot/assets/sim/sim.py +856 -0
  53. package/plugins/deepmodebot/skills/deepmodebot/assets/worker-gate/worker_gate.py +237 -0
  54. package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +3 -2
  55. package/plugins/deepmodebot/skills/deepmodebot/references/delegation.md +6 -2
  56. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +1 -1
  57. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +1 -0
  58. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +1 -1
  59. package/plugins/deepmodebot/skills/deepmodebot/references/principles/no-reward-hacking.md +6 -6
  60. package/plugins/deepmodebot/skills/deepmodebot/references/rule-approval.md +36 -16
  61. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/autoroute.md +9 -8
  62. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +1 -0
  63. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +6 -2
  64. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/mutation-testing.md +31 -9
  65. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +1 -1
  66. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +4 -4
  67. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sim.md +41 -0
  68. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +12 -0
  69. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +24 -13
  70. package/plugins/deepmodebot/skills/deepmodebot/worker.md +28 -16
  71. package/plugins/deepmodebot/agents/comment-sicko/agent.md +0 -35
  72. package/plugins/deepmodebot/agents/researcher/agent.md +0 -33
  73. package/plugins/deepmodebot/agents/reviewer/agent.md +0 -35
  74. package/plugins/deepmodebot/agents/scout/agent.md +0 -33
  75. package/plugins/deepmodebot/agents/security-reviewer/agent.md +0 -31
@@ -5,9 +5,10 @@
5
5
  python self_grill.py init --root <repo> --slug <slug> [--phase plan|checks|both] [--base <ref>] [--staged] [--force] [--refresh] [--json]
6
6
  python self_grill.py answer --dir <dir> --id <qid> --status proven|na|failed|blocked --answer <text> [--receipt <ref>] [--json]
7
7
  python self_grill.py verdict --dir <dir> [--strict] [--allow-stale] [--json]
8
- python self_grill.py bundle --root <repo> [--slug <slug>] [--claims-stdin | --claims-file <path>] [--confession <text>] [--json]
8
+ python self_grill.py bundle --root <repo> [--slug <slug>] [--role prosecutor|verifier|judge] [--mode blind|full] [--claims-stdin | --claims-file <path>] [--confession <text>] [--spec-file <path> --base <ref> [--head <ref>] [--check-cmd <cmd>]...] [--json]
9
9
  """
10
10
  import argparse
11
+ import functools
11
12
  import hashlib
12
13
  import json
13
14
  import os
@@ -16,6 +17,7 @@ import subprocess
16
17
  import sys
17
18
  import tempfile
18
19
  import time
20
+ import unicodedata
19
21
  from pathlib import Path
20
22
 
21
23
  sys.dont_write_bytecode = True
@@ -154,13 +156,17 @@ def ensure_contained(target: Path, root: Path) -> Path:
154
156
 
155
157
 
156
158
  def atomic_write_text(target: Path, content: str, root: Path) -> None:
159
+ atomic_write_bytes(target, content.encode("utf-8"), root)
160
+
161
+
162
+ def atomic_write_bytes(target: Path, content: bytes, root: Path) -> None:
157
163
  safe_target = ensure_contained(target, root)
158
164
  safe_parent = ensure_contained(safe_target.parent, root)
159
165
  safe_parent.mkdir(parents=True, exist_ok=True)
160
166
  fd, tmp_name = tempfile.mkstemp(prefix=f".{safe_target.name}.", suffix=".tmp", dir=str(safe_parent))
161
167
  tmp_path = Path(tmp_name)
162
168
  try:
163
- with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
169
+ with os.fdopen(fd, "wb") as handle:
164
170
  handle.write(content)
165
171
  handle.flush()
166
172
  os.fsync(handle.fileno())
@@ -886,11 +892,16 @@ def build_questions(
886
892
  "code-without-tests",
887
893
  )
888
894
  if test_paths:
895
+ prod_or_proof = [p for p in files if p not in test_paths and not p.lower().endswith(".md")]
896
+ comut_note = (
897
+ f" Co-mutation warning: both implementation/proof ({', '.join(prod_or_proof[:2])}) and test/eval ({', '.join(test_paths[:2])}) files changed in the same diff—prove assertions were not weakened to match broken output."
898
+ if prod_or_proof else ""
899
+ )
889
900
  add(
890
901
  "no-check-theater",
891
902
  "critical",
892
903
  "checks",
893
- "Would the new or touched tests fail if your production fix were reverted, and do they avoid mocking out the behavior under test?",
904
+ "Would the new or touched tests fail if your production fix were reverted, and do they avoid mocking out the behavior under test?" + comut_note,
894
905
  "tests-touched",
895
906
  )
896
907
  if sensitive_paths:
@@ -1003,16 +1014,19 @@ def build_questions(
1003
1014
  "no-reward-hacking",
1004
1015
  "critical",
1005
1016
  "integrity",
1006
- f"Goodhart / Anti-Reward-Hacking violation: diff triggers {len(rh_list)} reward-hack signal(s) ({locs}). Restore full thresholds/tests, replace primitive stand-ins with real upstream outputs + provenance receipts (reward_guard.py), and verify side-by-side against the reference goal.",
1017
+ f"Goodhart / Anti-Reward-Hacking violation: diff triggers {len(rh_list)} reward-hack signal(s) ({locs}). Restore strict tests/types/thresholds/snapshots, remove prod test-env or TLS/FK bypasses, run real backends/generators instead of stubs/primitives, and verify via reward_guard.py.",
1007
1018
  "reward-hacks",
1008
1019
  )
1009
- elif any(re.search(r"(?:gate|eval|bench|score|metric|validat|render|mesh|spark|fidelity)", p, re.I) for p in files):
1020
+ elif test_paths or schema_paths or any(
1021
+ re.search(r"(?:gate|eval|bench|perf|score|metric|validat|e2e|playwright|cypress|train|render|mesh|spark|fidelity)", p, re.I)
1022
+ for p in files
1023
+ ):
1010
1024
  add(
1011
1025
  "no-reward-hacking",
1012
1026
  "critical",
1013
1027
  "integrity",
1014
- "Goodhart / Anti-Reward-Hacking check: did you keep every test/reference threshold intact (zero --min-iou 0 or .skip), record upstream build provenance (job_id + SHA-256), and confirm via an independent judge that the output fulfills the real goal rather than gaming scalar metrics?",
1015
- "eval-or-pipeline-touched",
1028
+ "Goodhart / Anti-Reward-Hacking check (all domains): did you keep assertions, snapshots, coverage, typecheck/CI strictness, latency/quality bounds, and TLS/FK checks intact (zero test-env branches, E2E /api/ stubs, train-on-test leakage, or primitive stand-ins), and prove the real goal holds?",
1029
+ "verification-or-eval-touched",
1016
1030
  )
1017
1031
  add(
1018
1032
  "gaps-and-overclaims",
@@ -1391,21 +1405,578 @@ def build_prosecutor_bundle(
1391
1405
  }
1392
1406
 
1393
1407
 
1408
+ BLIND_ROLES = ("verifier", "judge")
1409
+ THINKING_WORDS = r"thinking|think|thoughts?|reasoning|scratch_?pad|reflection|chain_of_thought|cot|inner_monologue|monologue"
1410
+ THINKING_TAG_RE = re.compile(rf"<\s*(?P<close>/)?\s*(?:antml:)?(?:{THINKING_WORDS})\b(?P<attrs>[^<>]*)>")
1411
+ THINKING_FENCE_INFO_RE = re.compile(rf"\b(?:{THINKING_WORDS}|analysis|rationale)\b")
1412
+ FENCE_RE = re.compile(r"^[ \t>]*(?P<fence>`{3,}|~{3,})(?P<info>.*)$")
1413
+ HEADING_RE = re.compile(r"^[ \t>]*(?P<hashes>#{1,6})[ \t]*(?P<rest>.*)$")
1414
+ LABEL_WORDS = (
1415
+ r"(?:my\s+)?(?:reasoning|thinking|thoughts?|thought\s+process|chain[\s-]of[\s-]thought|scratch_?pad"
1416
+ r"|reflection|internal\s+monologue|self[\s-]assessment|confidence|confession)"
1417
+ )
1418
+ LABEL_HEADING_RE = re.compile(rf"^[\s*_]*{LABEL_WORDS}\b")
1419
+ LABEL_LINE_RE = re.compile(rf"^[\s>*_-]*(?:\d+[.)]\s*)?{LABEL_WORDS}\b[\s*_]*(?::[\s*_]*(?P<rest>.*))?$")
1420
+ RECEIPT_KEY_RE = re.compile(
1421
+ r"[\"']?(?:checks_ran|files_touched|contract_changes|open_risks)[\"']?\s*:"
1422
+ r"|[\"']?status[\"']?\s*[:=]\s*[\"']?(?:done|blocked|needs_contract_change)\b"
1423
+ )
1424
+ RECEIPT_WORDS_RE = re.compile(r"worker\s+receipt")
1425
+ STANDALONE_SIGNAL_RE = re.compile(r"^\W*(?:pass(?:ed)?|ok|success(?:ful)?|succeeded|done|green|all\s+green)\W*$")
1426
+ SHELL_INFO_RE = re.compile(r"^(?:bash|sh|shell|zsh|console|terminal|shell-session|powershell|pwsh|ps1|cmd|bat)\b")
1427
+ PROMPT_RE = re.compile(r"^\s*(?:\$|PS[^>\n]*>)\s+(?P<cmd>\S.*)$")
1428
+
1429
+ _SUBJECT = r"(?:tests?|test\s+suites?|suites?|checks?|specs?|builds?|lint(?:ers?|ing)?|ci|type\s*check(?:s|ing)?|assertions?|e2e)"
1430
+ _QUALIFIER = r"(?:(?:the|my|our|new|existing|relevant|local|unit|integration|all|these|those)\s+)*"
1431
+ _FILLER = r"(?:(?:are|is|were|was|have|has|had|been|now|all|still|also|both)\s+)*"
1432
+ _FIRST_PERSON_ADVERB = r"(?:\s+(?:have|also|just|already|manually|then|successfully|personally|really|carefully))*"
1433
+ PHRASE_SIGNALS: tuple[tuple[str, re.Pattern], ...] = tuple(
1434
+ (kind, re.compile(pattern))
1435
+ for kind, pattern in (
1436
+ ("pass-claim", rf"\b{_QUALIFIER}{_SUBJECT}\s+{_FILLER}(?:pass(?:es|ed|ing)?|green|succeed(?:s|ed)?|ok|okay)\b"),
1437
+ (
1438
+ "pass-claim",
1439
+ r"\b(?:everything|it|this|that)\s+(?:now\s+)?(?:passes|passed|works|worked|is\s+(?:green|passing|working|fixed|done|complete(?:d)?))\b"
1440
+ r"|\b(?:all|they|these|those)\s+(?:now\s+)?(?:pass|passes|passed|are\s+(?:green|passing|working|fixed|done))\b",
1441
+ ),
1442
+ (
1443
+ "pass-claim",
1444
+ r"\b(?:verdict|results?|status|outcome|conclusion)\s*[:=]\s*[\"'`*_ ]*(?:pass(?:ed)?|ok|success(?:ful)?|done|green|complete[d]?|fixed|good)\b",
1445
+ ),
1446
+ ("pass-claim", r"\b\d+\s+(?:tests?\s+|specs?\s+|checks?\s+|assertions?\s+)?(?:passed|passing|failed|failing)\b|\b0\s+(?:failures?|errors?|failed)\b|\bok\s*\(\d+\s+tests?\)|\bran\s+\d+\s+tests?\b"),
1447
+ (
1448
+ "pass-claim",
1449
+ r"\b(?:completed?|finished|implemented|fixed|resolved|built|verified|passed)\s+successfully\b"
1450
+ r"|\bsuccessfully\s+(?:completed?|finished|implemented|fixed|resolved|built|verified|passed|ran|run)\b"
1451
+ "|[\u2705\u2714\u2713\u2611]",
1452
+ ),
1453
+ (
1454
+ "exit-code-claim",
1455
+ r"\bexited\s+(?:with\s+)?(?:(?:code|status)\s+)?\d+\b|\bexit\s+(?:code|status)\s*(?:is|was|of|=|:)?\s*\d+\b"
1456
+ r"|(?:->|=>|\u2192|\u2014|\u2013|--|\(|:)\s*exit\s+\d+\b|\breturned\s+(?:exit\s+(?:code|status)\s+)?0\b"
1457
+ r"|\brc\s*[:=]\s*\d+\b|\bexit_code[\"']?\s*[:=]\s*\d+",
1458
+ ),
1459
+ (
1460
+ "verification-narration",
1461
+ rf"\b(?:i|we){_FIRST_PERSON_ADVERB}\s+(?:verified|validated|confirmed|tested|checked|ran|reproduced|proved|proven|ensured|inspected|exercised|smoke[- ]tested)\b"
1462
+ rf"|\b(?:i|we)(?:'ve|\s+have){_FIRST_PERSON_ADVERB}\s+(?:verified|validated|confirmed|tested|checked|run|reproduced|proved|proven|ensured|inspected|exercised)\b"
1463
+ r"|\b(?:was|were|been|is|are)\s+(?:successfully\s+)?(?:verified|validated|confirmed|tested)\b",
1464
+ ),
1465
+ (
1466
+ "confidence-claim",
1467
+ r"\bi(?:\s+am|'m)\s+(?:\w+\s+)?(?:confident|certain|sure|convinced)\b"
1468
+ r"|\b(?:confident|certain|convinced)\s+(?:that\s+)?(?:it|this|the|everything|we|all|these)\b"
1469
+ r"|\bhigh[- ]confidence\b|\bconfidence(?:\s+level)?\s*[:=]|\b\d{1,3}\s*%\s*(?:confident|sure|certain|confidence)"
1470
+ r"|\b(?:definitely|certainly|obviously|clearly)\s+(?:works|correct|fixed|done|passes|right)\b"
1471
+ r"|\b(?:no|zero)\s+(?:issues|problems|regressions|failures|bugs)\s+(?:found|remain|remaining|detected|observed)\b"
1472
+ r"|\blgtm\b|\bfully\s+(?:working|verified|tested|fixed|done|complete|green)\b"
1473
+ r"|\b(?:works|working)\s+(?:as\s+expected|correctly|perfectly|fine|properly)\b"
1474
+ r"|\ball\s+(?:acceptance\s+)?(?:criteria|requirements)\s+(?:are\s+|have\s+been\s+)?(?:met|satisfied|passing|passed|done)\b",
1475
+ ),
1476
+ )
1477
+ )
1478
+ _HOMOGLYPHS = str.maketrans(
1479
+ {
1480
+ "\u0430": "a", "\u0435": "e", "\u043e": "o", "\u0440": "p", "\u0441": "c", "\u0445": "x", "\u0443": "y",
1481
+ "\u0456": "i", "\u0455": "s", "\u0458": "j", "\u0501": "d", "\u03bf": "o", "\u03b1": "a", "\u03bd": "v",
1482
+ "\u03c1": "p", "\u2019": "'", "\u2018": "'", "\u201c": '"', "\u201d": '"',
1483
+ }
1484
+ )
1485
+ _LINE_BREAKS_RE = re.compile(r"\r\n|[\r\x0b\x0c\x85\u2028\u2029]")
1486
+
1487
+
1488
+ @functools.lru_cache(maxsize=8192)
1489
+ def _fold_char(ch: str) -> str:
1490
+ if ch in "\n\t":
1491
+ return ch
1492
+ kept = []
1493
+ for piece in unicodedata.normalize("NFKD", ch):
1494
+ if unicodedata.category(piece) in ("Mn", "Me", "Cf", "Cc", "Cs"):
1495
+ continue
1496
+ kept.append(piece.casefold().translate(_HOMOGLYPHS))
1497
+ return "".join(kept)
1498
+
1499
+
1500
+ def _fold(text: str) -> tuple[str, list[int]]:
1501
+ folded: list[str] = []
1502
+ origin: list[int] = []
1503
+ for index, ch in enumerate(text):
1504
+ piece = _fold_char(ch)
1505
+ for c in piece:
1506
+ folded.append(c)
1507
+ origin.append(index)
1508
+ return "".join(folded), origin
1509
+
1510
+
1511
+ def _collapse(text: str) -> tuple[str, list[int]]:
1512
+ folded, origin = _fold(text)
1513
+ out: list[str] = []
1514
+ positions: list[int] = []
1515
+ previous_space = False
1516
+ for index, ch in enumerate(folded):
1517
+ if ch.isspace():
1518
+ if previous_space:
1519
+ continue
1520
+ out.append(" ")
1521
+ previous_space = True
1522
+ else:
1523
+ out.append(ch)
1524
+ previous_space = False
1525
+ positions.append(origin[index])
1526
+ return "".join(out), positions
1527
+
1528
+
1529
+ def _delete_spans(text: str, origin: list[int], spans: list[tuple[int, int]]) -> str:
1530
+ cuts = sorted(
1531
+ (origin[start], len(text) if end >= len(origin) else origin[end - 1] + 1) for start, end in spans if end > start
1532
+ )
1533
+ if not cuts:
1534
+ return text
1535
+ out: list[str] = []
1536
+ cursor = 0
1537
+ for start, end in cuts:
1538
+ if start > cursor:
1539
+ out.append(text[cursor:start])
1540
+ cursor = max(cursor, end)
1541
+ out.append(text[cursor:])
1542
+ return "".join(out)
1543
+
1544
+
1545
+ def _find_fence_close(folded_lines: list[str], opener: int, fence: str) -> int:
1546
+ for index in range(opener + 1, len(folded_lines)):
1547
+ match = FENCE_RE.match(folded_lines[index])
1548
+ if match and match["fence"][0] == fence[0] and len(match["fence"]) >= len(fence) and not match["info"].strip():
1549
+ return index
1550
+ return len(folded_lines)
1551
+
1552
+
1553
+ def _drop_tagged_thinking(text: str) -> str:
1554
+ folded, origin = _fold(text)
1555
+ spans: list[tuple[int, int]] = []
1556
+ depth = 0
1557
+ start = 0
1558
+ for match in THINKING_TAG_RE.finditer(folded):
1559
+ closing = bool(match["close"])
1560
+ if not closing and match["attrs"].rstrip().endswith("/"):
1561
+ continue
1562
+ if not closing:
1563
+ if depth == 0:
1564
+ start = match.start()
1565
+ depth += 1
1566
+ elif depth > 0:
1567
+ depth -= 1
1568
+ if depth == 0:
1569
+ spans.append((start, match.end()))
1570
+ else:
1571
+ paragraph = folded.rfind("\n\n", 0, match.start())
1572
+ spans.append((paragraph + 2 if paragraph >= 0 else 0, match.end()))
1573
+ if depth > 0:
1574
+ spans.append((start, len(folded)))
1575
+ return _delete_spans(text, origin, spans)
1576
+
1577
+
1578
+ def _drop_thinking_fences(text: str) -> str:
1579
+ lines = text.split("\n")
1580
+ folded = [_fold(line)[0] for line in lines]
1581
+ keep = [True] * len(lines)
1582
+ index = 0
1583
+ while index < len(lines):
1584
+ match = FENCE_RE.match(folded[index])
1585
+ if match and THINKING_FENCE_INFO_RE.search(match["info"]):
1586
+ close = _find_fence_close(folded, index, match["fence"])
1587
+ for dropped in range(index, min(close + 1, len(lines))):
1588
+ keep[dropped] = False
1589
+ index = close + 1
1590
+ else:
1591
+ index += 1
1592
+ return "\n".join(line for line, kept in zip(lines, keep) if kept)
1593
+
1594
+
1595
+ def _match_json_object_end(text: str, start: int) -> int | None:
1596
+ depth = 0
1597
+ in_string = False
1598
+ escaped = False
1599
+ for index in range(start, len(text)):
1600
+ ch = text[index]
1601
+ if in_string:
1602
+ in_string = not (ch == '"' and not escaped)
1603
+ escaped = ch == "\\" and not escaped
1604
+ continue
1605
+ if ch == '"':
1606
+ in_string = True
1607
+ continue
1608
+ if ch == "}" and depth == 1:
1609
+ return index + 1
1610
+ depth += (ch == "{") - (ch == "}")
1611
+ return None
1612
+
1613
+
1614
+ def _enclosing_json_object(text: str, position: int) -> tuple[int, int] | None:
1615
+ window = max(0, position - 20000)
1616
+ openers = [window + m.start() for m in re.finditer(r"\{", text[window:position])][-400:]
1617
+ for opener in openers:
1618
+ end = _match_json_object_end(text, opener)
1619
+ if end is not None and end > position:
1620
+ return opener, end
1621
+ return None
1622
+
1623
+
1624
+ def _receipt_commands(object_text: str) -> list[str]:
1625
+ try:
1626
+ payload = json.loads(object_text)
1627
+ except ValueError:
1628
+ return []
1629
+ ran = payload.get("checks_ran") if isinstance(payload, dict) else None
1630
+ if not isinstance(ran, list):
1631
+ return []
1632
+ found = []
1633
+ for item in ran:
1634
+ cmd = item.get("cmd") if isinstance(item, dict) else item
1635
+ if isinstance(cmd, str):
1636
+ found.append(cmd)
1637
+ return found
1638
+
1639
+
1640
+ def _drop_receipt_objects(text: str, commands: list[str]) -> str:
1641
+ while True:
1642
+ folded, origin = _fold(text)
1643
+ match = RECEIPT_KEY_RE.search(folded)
1644
+ if not match:
1645
+ return text
1646
+ position = origin[match.start()]
1647
+ enclosing = _enclosing_json_object(text, position)
1648
+ if enclosing is None:
1649
+ line_start = text.rfind("\n", 0, position) + 1
1650
+ line_end = text.find("\n", position)
1651
+ text = text[:line_start] + (text[line_end + 1 :] if line_end >= 0 else "")
1652
+ else:
1653
+ commands.extend(_receipt_commands(text[enclosing[0] : enclosing[1]]))
1654
+ text = text[: enclosing[0]] + text[enclosing[1] :]
1655
+
1656
+
1657
+ def _section_end(folded: list[str], start: int, level: int) -> int:
1658
+ open_fence: re.Match | None = None
1659
+ for index in range(start, len(folded)):
1660
+ fence = FENCE_RE.match(folded[index])
1661
+ if open_fence is not None:
1662
+ if fence and fence["fence"][0] == open_fence["fence"][0] and len(fence["fence"]) >= len(open_fence["fence"]) and not fence["info"].strip():
1663
+ open_fence = None
1664
+ continue
1665
+ if fence:
1666
+ open_fence = fence
1667
+ continue
1668
+ heading = HEADING_RE.match(folded[index])
1669
+ if heading and len(heading["hashes"]) <= level:
1670
+ return index
1671
+ return len(folded)
1672
+
1673
+
1674
+ def _paragraph_end(folded: list[str], start: int) -> int:
1675
+ for index in range(start, len(folded)):
1676
+ if not folded[index].strip():
1677
+ return index
1678
+ return len(folded)
1679
+
1680
+
1681
+ def _drop_reasoning_sections(text: str) -> str:
1682
+ lines = text.split("\n")
1683
+ folded = [_fold(line)[0] for line in lines]
1684
+ keep = [True] * len(lines)
1685
+ index = 0
1686
+ while index < len(lines):
1687
+ heading = HEADING_RE.match(folded[index])
1688
+ label = LABEL_LINE_RE.match(folded[index])
1689
+ if heading and LABEL_HEADING_RE.match(heading["rest"]):
1690
+ end = _section_end(folded, index + 1, len(heading["hashes"]))
1691
+ elif label and (label["rest"] or "").strip(" *_"):
1692
+ end = _paragraph_end(folded, index + 1)
1693
+ elif label:
1694
+ end = _section_end(folded, index + 1, 6)
1695
+ else:
1696
+ index += 1
1697
+ continue
1698
+ for dropped in range(index, end):
1699
+ keep[dropped] = False
1700
+ index = end
1701
+ return "\n".join(line for line, kept in zip(lines, keep) if kept)
1702
+
1703
+
1704
+ def _line_has_signal(folded_line: str) -> bool:
1705
+ collapsed = " ".join(folded_line.split())
1706
+ return bool(
1707
+ RECEIPT_KEY_RE.search(collapsed)
1708
+ or RECEIPT_WORDS_RE.search(collapsed)
1709
+ or STANDALONE_SIGNAL_RE.match(collapsed)
1710
+ or any(pattern.search(collapsed) for _, pattern in PHRASE_SIGNALS)
1711
+ )
1712
+
1713
+
1714
+ def _drop_signal_lines(text: str) -> str:
1715
+ return "\n".join(line for line in text.split("\n") if not _line_has_signal(_fold(line)[0]))
1716
+
1717
+
1718
+ def _strip_pipeline(text: str) -> tuple[str, list[str]]:
1719
+ receipt_commands: list[str] = []
1720
+ stripped = _LINE_BREAKS_RE.sub("\n", text)
1721
+ stripped = _drop_tagged_thinking(stripped)
1722
+ stripped = _drop_thinking_fences(stripped)
1723
+ stripped = _drop_receipt_objects(stripped, receipt_commands)
1724
+ stripped = _drop_reasoning_sections(stripped)
1725
+ return _drop_signal_lines(stripped), receipt_commands
1726
+
1727
+
1728
+ def strip_author_signals(text: str) -> str:
1729
+ return _strip_pipeline(text)[0]
1730
+
1731
+
1732
+ def _shell_block_commands(body: list[str]) -> list[str]:
1733
+ prompted = [m["cmd"] for m in map(PROMPT_RE.match, body) if m]
1734
+ if prompted:
1735
+ return prompted
1736
+ return [line.strip() for line in body if line.strip() and not line.lstrip().startswith(("#", "//", "REM "))]
1737
+
1738
+
1739
+ def _shell_commands(stripped: str) -> list[str]:
1740
+ lines = stripped.split("\n")
1741
+ folded = [_fold(line)[0] for line in lines]
1742
+ found: list[str] = []
1743
+ index = 0
1744
+ while index < len(lines):
1745
+ fence = FENCE_RE.match(folded[index])
1746
+ if fence:
1747
+ close = _find_fence_close(folded, index, fence["fence"])
1748
+ if SHELL_INFO_RE.match(fence["info"].strip()):
1749
+ found.extend(_shell_block_commands(lines[index + 1 : close]))
1750
+ index = close + 1
1751
+ continue
1752
+ prompt = PROMPT_RE.match(lines[index])
1753
+ if prompt:
1754
+ found.append(prompt["cmd"])
1755
+ index += 1
1756
+ return found
1757
+
1758
+
1759
+ def _is_plain_command(command: str) -> bool:
1760
+ return bool(command) and all(ch == "\t" or ord(ch) >= 32 and ord(ch) != 127 for ch in command)
1761
+
1762
+
1763
+ def extract_check_commands(transcript: str) -> list[str]:
1764
+ stripped, receipt_commands = _strip_pipeline(transcript)
1765
+ seen: set[str] = set()
1766
+ commands: list[str] = []
1767
+ for raw in [*receipt_commands, *_shell_commands(stripped)]:
1768
+ command = raw.strip()
1769
+ if command in seen or not _is_plain_command(command) or _line_has_signal(_fold(command)[0]):
1770
+ continue
1771
+ seen.add(command)
1772
+ commands.append(command)
1773
+ return commands
1774
+
1775
+
1776
+ def find_leaks(text: str) -> list[dict]:
1777
+ normalized = _LINE_BREAKS_RE.sub("\n", text)
1778
+ collapsed, positions = _collapse(normalized)
1779
+ leaks: list[dict] = []
1780
+
1781
+ def add_phrase(kind: str, match: re.Match) -> None:
1782
+ line = normalized.count("\n", 0, positions[match.start()]) + 1
1783
+ excerpt = collapsed[max(0, match.start() - 12) : match.end() + 12].strip()[:100]
1784
+ leaks.append({"kind": kind, "line": line, "excerpt": excerpt})
1785
+
1786
+ for pattern in (RECEIPT_KEY_RE, RECEIPT_WORDS_RE):
1787
+ for match in pattern.finditer(collapsed):
1788
+ add_phrase("worker-receipt", match)
1789
+ for match in THINKING_TAG_RE.finditer(collapsed):
1790
+ add_phrase("reasoning-marker", match)
1791
+ for kind, pattern in PHRASE_SIGNALS:
1792
+ for match in pattern.finditer(collapsed):
1793
+ add_phrase(kind, match)
1794
+ for number, folded_line in enumerate(_fold(normalized)[0].split("\n"), 1):
1795
+ line_text = " ".join(folded_line.split())
1796
+ fence = FENCE_RE.match(folded_line)
1797
+ heading = HEADING_RE.match(folded_line)
1798
+ if (
1799
+ (fence and THINKING_FENCE_INFO_RE.search(fence["info"]))
1800
+ or LABEL_LINE_RE.match(folded_line)
1801
+ or (heading and LABEL_HEADING_RE.match(heading["rest"]))
1802
+ ):
1803
+ leaks.append({"kind": "reasoning-marker", "line": number, "excerpt": line_text[:100]})
1804
+ if STANDALONE_SIGNAL_RE.match(line_text):
1805
+ leaks.append({"kind": "pass-claim", "line": number, "excerpt": line_text[:100]})
1806
+ return leaks
1807
+
1808
+
1809
+ def assert_no_leaks(parts: dict[str, str]) -> None:
1810
+ problems: list[str] = []
1811
+ for name, text in parts.items():
1812
+ for leak in find_leaks(text):
1813
+ problems.append(f" - {name} line {leak['line']} [{leak['kind']}]: {leak['excerpt']!r}")
1814
+ if problems:
1815
+ raise SystemExit(
1816
+ "blind bundle refused: author signals leaked into the bundle (reword the spec or commands, "
1817
+ "or drop the offending input):\n" + "\n".join(problems)
1818
+ )
1819
+
1820
+
1821
+ def _sha256_hex(data: bytes) -> str:
1822
+ return hashlib.sha256(data).hexdigest()
1823
+
1824
+
1825
+ def _resolve_commit(root: Path, ref: str, label: str) -> str:
1826
+ if not ref or ref.startswith("-"):
1827
+ raise SystemExit(f"invalid {label} ref {ref!r}")
1828
+ result = _run_git(root, ["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"])
1829
+ sha = result.stdout.strip()
1830
+ if result.returncode != 0 or not sha:
1831
+ raise SystemExit(f"cannot resolve {label} ref {ref!r} to a commit")
1832
+ return sha
1833
+
1834
+
1835
+ def _git_diff_bytes(root: Path, base_sha: str, head_sha: str) -> bytes:
1836
+ env = dict(os.environ)
1837
+ env["GIT_OPTIONAL_LOCKS"] = "0"
1838
+ try:
1839
+ result = subprocess.run(
1840
+ ["git", "-c", "core.quotePath=false", "-C", str(root), "diff", "--no-color", "--no-ext-diff", "--no-textconv", base_sha, head_sha, "--"],
1841
+ capture_output=True,
1842
+ env=env,
1843
+ check=False,
1844
+ creationflags=NO_WINDOW,
1845
+ timeout=300,
1846
+ )
1847
+ except subprocess.TimeoutExpired as err:
1848
+ raise SystemExit(f"git diff {base_sha}..{head_sha} timed out after {err.timeout}s") from err
1849
+ if result.returncode != 0:
1850
+ raise SystemExit(f"git diff {base_sha}..{head_sha} failed: {result.stderr.decode('utf-8', 'replace').strip()}")
1851
+ return result.stdout
1852
+
1853
+
1854
+ def _ensure_trailing_newline(data: bytes) -> bytes:
1855
+ return data if data.endswith(b"\n") else data + b"\n"
1856
+
1857
+
1858
+ def build_blind_bundle(
1859
+ root: Path,
1860
+ spec_bytes: bytes,
1861
+ check_commands: list[str] | None = None,
1862
+ transcript: str = "",
1863
+ slug: str = "blind",
1864
+ base: str | None = None,
1865
+ head: str = "HEAD",
1866
+ ) -> dict:
1867
+ safe_root = reject_unsafe_root(root)
1868
+ if not SLUG_RE.fullmatch(slug):
1869
+ raise SystemExit(f"invalid slug {slug!r}: use lowercase kebab-case")
1870
+ if not _is_git_root_or_worktree(safe_root):
1871
+ raise SystemExit("blind bundle needs a git repository: the diff is BASE..HEAD")
1872
+ base_ref = base or _auto_merge_base(safe_root)
1873
+ if not base_ref:
1874
+ raise SystemExit("blind bundle needs --base <ref>: no merge base could be inferred")
1875
+ base_sha = _resolve_commit(safe_root, base_ref, "base")
1876
+ head_sha = _resolve_commit(safe_root, head, "head")
1877
+ diff_bytes = _git_diff_bytes(safe_root, base_sha, head_sha)
1878
+ if not diff_bytes.strip():
1879
+ raise SystemExit(f"blind bundle refused: BASE {base_sha[:12]} and HEAD {head_sha[:12]} have an empty diff")
1880
+ try:
1881
+ spec_text = spec_bytes.decode("utf-8")
1882
+ except UnicodeDecodeError as err:
1883
+ raise SystemExit(f"blind bundle refused: the spec is not valid UTF-8 ({err})") from err
1884
+ if not spec_text.strip():
1885
+ raise SystemExit("blind bundle refused: the frozen spec is empty")
1886
+
1887
+ commands: list[str] = []
1888
+ for command in [*(check_commands or []), *extract_check_commands(transcript)]:
1889
+ command = command.strip()
1890
+ if not _is_plain_command(command):
1891
+ raise SystemExit(f"blind bundle refused: command must be one printable line: {command!r}")
1892
+ if command not in commands:
1893
+ commands.append(command)
1894
+ if not commands:
1895
+ raise SystemExit("blind bundle refused: no repro/check commands; pass --check-cmd so the verifier can run them cold")
1896
+
1897
+ longest_run = max((len(run) for command in commands for run in re.findall(r"`+", command)), default=0)
1898
+ command_fence = "`" * max(3, longest_run + 1)
1899
+ spec_hash = _sha256_hex(spec_bytes)
1900
+ diff_hash = _sha256_hex(diff_bytes)
1901
+ preamble = (
1902
+ "# Blind Verification Bundle\n"
1903
+ "Input for a verifier or judge. It holds the frozen spec, the diff and the commands to run cold; no author material is included.\n"
1904
+ f"- BASE: {base_sha}\n"
1905
+ f"- HEAD: {head_sha}\n"
1906
+ f"- Spec: {len(spec_bytes)} bytes, sha256 {spec_hash}\n"
1907
+ f"- Diff: {len(diff_bytes)} bytes, sha256 {diff_hash}\n"
1908
+ "\n## Verifier protocol\n"
1909
+ "Run every command below yourself, from the repository root at HEAD, and report the exit code you observe for each. "
1910
+ "Judge the diff against the spec from your own runs only.\n"
1911
+ )
1912
+ command_block = f"\n## Commands to run cold\n{command_fence}sh\n" + "\n".join(commands) + f"\n{command_fence}\n"
1913
+ assert_no_leaks({"frame": preamble, "spec": spec_text, "commands": "\n".join(commands)})
1914
+
1915
+ bundle = b"".join(
1916
+ [
1917
+ preamble.encode("utf-8"),
1918
+ f"\n## Frozen spec\n-----BEGIN SPEC bytes={len(spec_bytes)} sha256={spec_hash}-----\n".encode("utf-8"),
1919
+ _ensure_trailing_newline(spec_bytes),
1920
+ f"-----END SPEC sha256={spec_hash}-----\n".encode("utf-8"),
1921
+ command_block.encode("utf-8"),
1922
+ f"\n## Diff BASE..HEAD\n-----BEGIN DIFF bytes={len(diff_bytes)} sha256={diff_hash}-----\n".encode("utf-8"),
1923
+ _ensure_trailing_newline(diff_bytes),
1924
+ f"-----END DIFF sha256={diff_hash}-----\n".encode("utf-8"),
1925
+ ]
1926
+ )
1927
+ _ensure_scratch_gitignore(safe_root)
1928
+ out_dir = ensure_contained(safe_root / ".scratch" / "self-grill" / slug, safe_root)
1929
+ out_dir.mkdir(parents=True, exist_ok=True)
1930
+ bundle_path = out_dir / "blind-bundle.md"
1931
+ atomic_write_bytes(bundle_path, bundle, safe_root)
1932
+ verifier_prompt = (
1933
+ f"Read ONLY `{bundle_path}` first. Run every command it lists yourself from the repository root at HEAD {head_sha[:12]}, "
1934
+ "and report your own exit code for each. Prove each spec criterion from your own runs and the diff, then try once to break it. "
1935
+ "Reply `VERDICT: DONE` or `VERDICT: NOT DONE` with the command that shows each criterion."
1936
+ )
1937
+ return {
1938
+ "mode": "blind",
1939
+ "bundle_path": str(bundle_path),
1940
+ "base": base_sha,
1941
+ "head": head_sha,
1942
+ "spec_sha256": spec_hash,
1943
+ "diff_sha256": diff_hash,
1944
+ "commands": commands,
1945
+ "verifier_prompt": verifier_prompt,
1946
+ }
1947
+
1948
+
1394
1949
  def cmd_bundle(args: argparse.Namespace) -> int:
1395
1950
  claims = sys.stdin.read() if args.claims_stdin else (Path(args.claims_file).read_text(encoding="utf-8") if args.claims_file else "")
1396
- res = build_prosecutor_bundle(
1397
- Path(args.root),
1398
- slug=args.slug,
1399
- claims_text=claims,
1400
- confession_text=args.confession or "",
1401
- base=args.base,
1402
- explicit_files=args.files,
1403
- )
1951
+ mode = args.mode or ("blind" if args.role in BLIND_ROLES else "full")
1952
+ if mode == "blind":
1953
+ if not args.spec_file:
1954
+ raise SystemExit("blind bundle needs --spec-file <frozen spec/acceptance bar>")
1955
+ if args.confession or args.files:
1956
+ raise SystemExit("blind bundle refuses --confession and --files: it holds only the spec, the BASE..HEAD diff and the commands")
1957
+ res = build_blind_bundle(
1958
+ Path(args.root),
1959
+ Path(args.spec_file).read_bytes(),
1960
+ check_commands=args.check_cmd,
1961
+ transcript=claims,
1962
+ slug=args.slug or "blind",
1963
+ base=args.base,
1964
+ head=args.head,
1965
+ )
1966
+ else:
1967
+ res = build_prosecutor_bundle(
1968
+ Path(args.root),
1969
+ slug=args.slug or "prosecutor",
1970
+ claims_text=claims,
1971
+ confession_text=args.confession or "",
1972
+ base=args.base,
1973
+ explicit_files=args.files,
1974
+ )
1404
1975
  if args.json:
1405
1976
  print(json.dumps(res, indent=2))
1406
1977
  else:
1407
1978
  print(res["bundle_path"])
1408
- print(res["prosecutor_prompt"])
1979
+ print(res.get("verifier_prompt") or res["prosecutor_prompt"])
1409
1980
  return 0
1410
1981
 
1411
1982
 
@@ -1449,11 +2020,16 @@ def build_parser() -> argparse.ArgumentParser:
1449
2020
  p_ver.add_argument("--json", action="store_true")
1450
2021
  p_ver.set_defaults(func=cmd_verdict)
1451
2022
 
1452
- p_bun = sub.add_parser("bundle", help="Pack a single-file Adaptive Hotspot Prosecutor bundle on disk.")
2023
+ p_bun = sub.add_parser("bundle", help="Pack a single-file bundle on disk: the blind verifier bundle for verifier/judge roles, the Adaptive Hotspot Prosecutor bundle otherwise.")
1453
2024
  p_bun.add_argument("--root", required=True)
1454
- p_bun.add_argument("--slug", default="prosecutor")
2025
+ p_bun.add_argument("--slug", default=None)
2026
+ p_bun.add_argument("--role", choices=("prosecutor", *BLIND_ROLES), default="prosecutor")
2027
+ p_bun.add_argument("--mode", choices=("blind", "full"), default=None)
1455
2028
  p_bun.add_argument("--base", default=None)
2029
+ p_bun.add_argument("--head", default="HEAD")
1456
2030
  p_bun.add_argument("--files", nargs="*", default=None)
2031
+ p_bun.add_argument("--spec-file", default=None)
2032
+ p_bun.add_argument("--check-cmd", action="append", default=[])
1457
2033
  p_bun.add_argument("--claims-stdin", action="store_true")
1458
2034
  p_bun.add_argument("--claims-file", default=None)
1459
2035
  p_bun.add_argument("--confession", default="")