@andresmassello/uscha 1.74.0 → 1.75.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.
package/README.md CHANGED
@@ -40,7 +40,7 @@ Requires **Python 3.8+** on the machine (the engine is Python stdlib — no pip
40
40
  runtime dependencies). The npm package is a thin router; the canonical installer is
41
41
  `uscha-kit/install-uscha.py`.
42
42
 
43
- **Kit v1.74.0** <!-- uscha:version --> · [uscha.dev](https://uscha.dev) ·
43
+ **Kit v1.75.0** <!-- uscha:version --> · [uscha.dev](https://uscha.dev) ·
44
44
  [changelog](https://github.com/andresmassello/uscha/blob/main/uscha-kit/CHANGELOG.md)
45
45
  (the per-release changelogs live in the repo, not in the npm tarball)
46
46
 
@@ -76,7 +76,7 @@ and see which file, which test, and when.
76
76
  | `/uscha-mirador` | Bird's-eye HTML dashboard: readiness, trail, acceptance, loops |
77
77
  | `/uscha-status` | One-line progress readout, in chat |
78
78
 
79
- **A measurement engine** (`qa_ledger.py`, 46 subcommands, Python stdlib) that ingests
79
+ **A measurement engine** (`qa_ledger.py`, 47 subcommands, Python stdlib) that ingests
80
80
  evidence from **11 language stacks** — maven, gradle, ant, python, node, go, rust, dotnet,
81
81
  cpp, swift, flutter — and computes a readiness score with hard caps and visible provenance.
82
82
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andresmassello/uscha",
3
- "version": "1.74.0",
3
+ "version": "1.75.0",
4
4
  "description": "Spec-driven development for LLM coding agents: 9 skills + a stdlib evidence engine. Facts block, guesses advise; the human approves.",
5
5
  "author": {
6
6
  "name": "Andres Massello",
@@ -5309,9 +5309,16 @@ _BOOTSTRAP_CASE_TIMEOUT = 15 # a compiled hook must decid
5309
5309
 
5310
5310
  def _run_oracle_case(impl_path, case):
5311
5311
  """Run ONE withheld oracle case against a compiled implementation: feed the case's stdin
5312
- (raw_stdin verbatim if present, else json.dumps(payload)) to `python <impl>`, and compare
5313
- the process exit code to `expected_exit`. Deterministic execution -- the oracle is a
5314
- `measured` fact, never an LLM judgment. Returns a per-case result dict."""
5312
+ (raw_stdin verbatim if present, else json.dumps(payload)) to `python <impl>`, and check its
5313
+ result against whichever expectations the case declares. Deterministic execution -- the
5314
+ oracle is a `measured` fact, never an LLM judgment. Returns a per-case result dict.
5315
+
5316
+ A case may assert any of: `expected_exit` (process exit code -- the M4 guard's contract),
5317
+ `expected_stdout` (the program's stdout, compared stripped -- for archetypes that COMPUTE an
5318
+ output, e.g. a parser or transformer), and `expected_json` (stdout parsed as JSON and
5319
+ compared structurally, so an output whose formatting is free but whose value is fixed is not
5320
+ penalised for whitespace or key order). The case passes iff EVERY declared expectation holds;
5321
+ a case that declares none proves nothing and fails."""
5315
5322
  if "raw_stdin" in case:
5316
5323
  stdin = case["raw_stdin"]
5317
5324
  else:
@@ -5320,14 +5327,24 @@ def _run_oracle_case(impl_path, case):
5320
5327
  r = subprocess.run([sys.executable, impl_path], input=stdin, capture_output=True,
5321
5328
  text=True, encoding="utf-8", errors="replace",
5322
5329
  timeout=_BOOTSTRAP_CASE_TIMEOUT)
5323
- got, err = r.returncode, None
5330
+ got, out, err = r.returncode, r.stdout, None
5324
5331
  except subprocess.TimeoutExpired:
5325
- got, err = None, "timeout"
5332
+ got, out, err = None, "", "timeout"
5326
5333
  except OSError as exc:
5327
- got, err = None, "could not run impl: %s" % exc
5334
+ got, out, err = None, "", "could not run impl: %s" % exc
5328
5335
  want = case.get("expected_exit")
5329
- return {"name": case.get("name"), "expected": want, "got": got,
5330
- "ok": (err is None and got == want), "error": err}
5336
+ asserted = [k for k in ("expected_exit", "expected_stdout", "expected_json") if k in case]
5337
+ ok = err is None and bool(asserted)
5338
+ if ok and "expected_exit" in case:
5339
+ ok = got == want
5340
+ if ok and "expected_stdout" in case:
5341
+ ok = (out or "").strip() == str(case["expected_stdout"]).strip()
5342
+ if ok and "expected_json" in case:
5343
+ try:
5344
+ ok = json.loads(out) == case["expected_json"]
5345
+ except (ValueError, TypeError):
5346
+ ok = False
5347
+ return {"name": case.get("name"), "expected": want, "got": got, "ok": ok, "error": err}
5331
5348
 
5332
5349
 
5333
5350
  def cmd_bootstrap_oracle(args):
@@ -5454,6 +5471,189 @@ def cmd_bootstrap_variance(args):
5454
5471
  sys.exit(0)
5455
5472
 
5456
5473
 
5474
+ # --------------------------------------------------------------------------- #
5475
+ # bench (Diamond M5: the Diamond Bench aggregates the M3/M4 primitives over a
5476
+ # set of bounded systems and emits a per-archetype verdict table. It measures
5477
+ # REGENERATION FIDELITY of canonical representations, not "which model codes
5478
+ # better" -- model identities are anonymized in the headline. Deterministic, no
5479
+ # LLM. ADR-018.)
5480
+ # --------------------------------------------------------------------------- #
5481
+ # min oracle pass-rate for a non-green compilation to still count as PARTIAL (core identity).
5482
+ _BENCH_PARTIAL_FLOOR = 0.8
5483
+
5484
+
5485
+ def _bench_oracle_all(impl_path, cases):
5486
+ results = [_run_oracle_case(impl_path, c) for c in cases]
5487
+ passed = sum(1 for r in results if r["ok"])
5488
+ return {"passed": passed, "total": len(results), "green": passed == len(results),
5489
+ "failing": [r["name"] for r in results if not r["ok"]]}
5490
+
5491
+
5492
+ def _bench_entry(entry_dir, name):
5493
+ """Run compile-validate + the withheld oracle + variance over ONE bench entry and compute
5494
+ its verdict. Reuses the M3/M4 organs unchanged; consults no model. A PASS is >=3 oracle-green
5495
+ compilations that genuinely differ; PARTIAL is core identity with the divergence isolated;
5496
+ FAIL is no green, convergence to near-identical code, or an oracle a degenerate stub can
5497
+ satisfy (non-discriminating); PENDING is an entry not yet fully compiled."""
5498
+ ir_graph, ir_errors = _load_ir_at(os.path.join(entry_dir, IR_FILE))
5499
+ try:
5500
+ with open(os.path.join(entry_dir, "oracle", "ORACLE.json"), encoding="utf-8-sig") as fh:
5501
+ cases = (json.load(fh) or {}).get("cases") or []
5502
+ except (OSError, ValueError):
5503
+ cases = []
5504
+ rec = {"archetype": name, "oracle_cases": len(cases), "compilations": [],
5505
+ "variance": None, "discrimination": None, "verdict": "PENDING", "reason": None}
5506
+ if ir_graph is None or ir_errors or not cases:
5507
+ rec["reason"] = "entry incomplete (missing/invalid IR or oracle)"
5508
+ return rec
5509
+ comp_dirs = sorted(d for d in os.listdir(entry_dir)
5510
+ if d.startswith("c-") and
5511
+ os.path.isfile(os.path.join(entry_dir, d, "COMPILATION.json")))
5512
+ for d in comp_dirs:
5513
+ cd = os.path.join(entry_dir, d)
5514
+ cj = os.path.join(cd, "COMPILATION.json")
5515
+ errors, _adv = _validate_compilation(cj, ir_graph)
5516
+ unit, model = None, None
5517
+ try:
5518
+ with open(cj, encoding="utf-8-sig") as fh:
5519
+ c = json.load(fh)
5520
+ src = c.get("source") or []
5521
+ unit = src[0].get("unit") if src else None
5522
+ model = (c.get("compilation_report") or {}).get("model")
5523
+ except (OSError, ValueError, AttributeError, IndexError):
5524
+ pass
5525
+ impl = os.path.join(cd, unit.replace("/", os.sep)) if unit else None
5526
+ ores = (_bench_oracle_all(impl, cases) if impl and os.path.isfile(impl)
5527
+ else {"passed": 0, "total": len(cases), "green": False, "failing": ["<no impl>"]})
5528
+ rec["compilations"].append({"dir": d, "model": model, "impl": impl,
5529
+ "compile_valid": not errors, "oracle": ores})
5530
+ impls = rec["compilations"]
5531
+ impl_paths = [i["impl"] for i in impls if i["impl"] and os.path.isfile(i["impl"])]
5532
+ if len(impl_paths) >= 2:
5533
+ metrics = [_impl_metrics(p) for p in impl_paths]
5534
+ shas = [m.get("sha256") for m in metrics if "error" not in m and m.get("sha256")]
5535
+ rec["variance"] = {"all_distinct": len(set(shas)) == len(shas) and len(shas) >= 2,
5536
+ "metrics": metrics}
5537
+ stub_dir = os.path.join(entry_dir, "stub")
5538
+ stub_green = False
5539
+ if os.path.isdir(stub_dir):
5540
+ stubs = sorted(f for f in os.listdir(stub_dir) if f.endswith(".py"))
5541
+ if stubs:
5542
+ sres = _bench_oracle_all(os.path.join(stub_dir, stubs[0]), cases)
5543
+ stub_green = sres["green"]
5544
+ rec["discrimination"] = {"stub_passed": sres["passed"], "total": sres["total"],
5545
+ "stub_green": stub_green}
5546
+ n = len(impls)
5547
+ if n == 0:
5548
+ rec["reason"] = "no compilations yet"
5549
+ return rec # PENDING
5550
+ all_valid = all(i["compile_valid"] for i in impls)
5551
+ greens = sum(1 for i in impls if i["oracle"]["green"])
5552
+ min_rate = min((i["oracle"]["passed"] / i["oracle"]["total"]) if i["oracle"]["total"]
5553
+ else 0.0 for i in impls)
5554
+ distinct = rec["variance"]["all_distinct"] if rec["variance"] else (n == 1)
5555
+ if stub_green:
5556
+ rec["verdict"], rec["reason"] = "FAIL", ("oracle satisfied by a degenerate stub -- not "
5557
+ "discriminating; the entry proves nothing")
5558
+ elif not all_valid:
5559
+ rec["verdict"], rec["reason"] = "FAIL", "a compilation does not validate against the pinned IR"
5560
+ elif n < 3:
5561
+ rec["verdict"], rec["reason"] = "PENDING", "fewer than 3 compilations (have %d)" % n
5562
+ elif not distinct:
5563
+ rec["verdict"], rec["reason"] = "FAIL", ("implementations converged to a byte-identical "
5564
+ "pair -- a disguised implementation")
5565
+ elif greens == n:
5566
+ rec["verdict"], rec["reason"] = "PASS", ("all %d compilations oracle-green and genuinely "
5567
+ "different -- the same system" % n)
5568
+ elif min_rate >= _BENCH_PARTIAL_FLOOR:
5569
+ rec["verdict"], rec["reason"] = "PARTIAL", ("core identity (min %.0f%% of cases); "
5570
+ "divergence isolated" % (min_rate * 100))
5571
+ else:
5572
+ rec["verdict"], rec["reason"] = "FAIL", ("a compilation below the core-identity floor "
5573
+ "(min %.0f%%)" % (min_rate * 100))
5574
+ return rec
5575
+
5576
+
5577
+ def _render_bench_md(table, anon, recs):
5578
+ lines = ["<!-- GENERATED by qa_ledger.py bench (ADR-018) -- every number is a measured run; "
5579
+ "do not hand-edit. -->", "", "# DIAMOND-BENCH", "",
5580
+ "Regeneration fidelity of canonical representations across archetypes. Each row is a "
5581
+ "bounded system compiled blind by independent models through the M3 contract and "
5582
+ "judged by a WITHHELD oracle (M4). Model identities are anonymized here; the mapping "
5583
+ "is published below.", "",
5584
+ "| Archetype | Verdict | Compilers (oracle pass / total) | Distinct | Oracle cases |",
5585
+ "|-----------|---------|--------------------------------|----------|--------------|"]
5586
+ for t in table:
5587
+ dist = "—" if t["distinct"] is None else ("yes" if t["distinct"] else "NO")
5588
+ lines.append("| %s | %s | %s | %s | %d |" % (t["archetype"], t["verdict"],
5589
+ t["compilers"], dist, t["oracle_cases"]))
5590
+ counts = {}
5591
+ for t in table:
5592
+ counts[t["verdict"]] = counts.get(t["verdict"], 0) + 1
5593
+ lines += ["", "**Coverage:** " + ", ".join("%d %s" % (v, k) for k, v in sorted(counts.items()))
5594
+ + " (of %d entries)." % len(table), "",
5595
+ "**Model map (published, not the headline):** "
5596
+ + (", ".join("%s = %s" % (a, m) for m, a in sorted(anon.items(), key=lambda x: x[1]))
5597
+ or "none yet") + ".", "",
5598
+ "## Per-entry detail", ""]
5599
+ for r in recs:
5600
+ lines.append("### %s — %s" % (r["archetype"], r["verdict"]))
5601
+ lines.append("*%s*" % (r["reason"] or ""))
5602
+ if r["compilations"]:
5603
+ for i in r["compilations"]:
5604
+ lines.append("- `%s` (%s): oracle %d/%d%s%s" % (
5605
+ i["dir"], anon.get(i["model"], i["model"] or "?"),
5606
+ i["oracle"]["passed"], i["oracle"]["total"],
5607
+ " GREEN" if i["oracle"]["green"] else "",
5608
+ "" if i["compile_valid"] else " [does not compile-validate]"))
5609
+ if r["discrimination"]:
5610
+ dsc = r["discrimination"]
5611
+ lines.append("- discrimination stub: %d/%d (%s)" % (
5612
+ dsc["stub_passed"], dsc["total"],
5613
+ "NON-DISCRIMINATING" if dsc["stub_green"] else "oracle rejects the stub"))
5614
+ lines.append("")
5615
+ return "\n".join(lines)
5616
+
5617
+
5618
+ def cmd_bench(args):
5619
+ if not os.path.isdir(args.dir):
5620
+ print("[qa_ledger] bench: no directory %s" % args.dir, file=sys.stderr)
5621
+ sys.exit(2)
5622
+ entries = sorted(d for d in os.listdir(args.dir)
5623
+ if os.path.isfile(os.path.join(args.dir, d, IR_FILE)))
5624
+ if not entries:
5625
+ print("[qa_ledger] bench: no entries under %s (an entry is a subdir with %s)"
5626
+ % (args.dir, IR_FILE), file=sys.stderr)
5627
+ sys.exit(2)
5628
+ recs = [_bench_entry(os.path.join(args.dir, e), e) for e in entries]
5629
+ models = sorted({i["model"] for r in recs for i in r["compilations"] if i.get("model")})
5630
+ anon = {m: "M%d" % (k + 1) for k, m in enumerate(models)}
5631
+ table = []
5632
+ for r in recs:
5633
+ cols = ", ".join("%s %d/%d" % (anon.get(i["model"], "?"), i["oracle"]["passed"],
5634
+ i["oracle"]["total"]) for i in r["compilations"])
5635
+ table.append({"archetype": r["archetype"], "verdict": r["verdict"],
5636
+ "compilers": cols or "(none yet)",
5637
+ "distinct": (r["variance"] or {}).get("all_distinct"),
5638
+ "oracle_cases": r["oracle_cases"], "reason": r["reason"]})
5639
+ md = _render_bench_md(table, anon, recs)
5640
+ if args.out:
5641
+ with open(args.out, "w", encoding="utf-8", newline="\n") as fh:
5642
+ fh.write(md)
5643
+ if args.json:
5644
+ print(json.dumps({"entries": len(recs), "model_map": anon, "table": table,
5645
+ "raw": recs}, indent=2, ensure_ascii=False))
5646
+ else:
5647
+ print("BENCH: %d entries" % len(recs))
5648
+ for t in table:
5649
+ dist = "" if t["distinct"] is None else (" | distinct" if t["distinct"]
5650
+ else " | CONVERGED")
5651
+ print(" %-14s %-8s | %s%s" % (t["archetype"], t["verdict"], t["compilers"], dist))
5652
+ if args.out:
5653
+ print(" -> %s" % args.out)
5654
+ sys.exit(0)
5655
+
5656
+
5457
5657
  # --------------------------------------------------------------------------- #
5458
5658
  # facts (T0 / SYSTEM-FACTS: public claims become compiled artifacts of repo
5459
5659
  # facts -- Diamond applied to Diamond. ADR-012.)
@@ -9566,6 +9766,17 @@ def build_parser():
9566
9766
  pbv.add_argument("--json", action="store_true")
9567
9767
  pbv.set_defaults(func=cmd_bootstrap_variance)
9568
9768
 
9769
+ pbn = sub.add_parser(
9770
+ "bench",
9771
+ help="the Diamond Bench (ADR-018): per-archetype verdict table over a set of bounded "
9772
+ "systems, aggregating compile-validate + bootstrap-oracle + bootstrap-variance; "
9773
+ "model identities anonymized in the headline; deterministic, no LLM")
9774
+ pbn.add_argument("--dir", required=True,
9775
+ help="the bench directory; each subdir with an IR.json is an entry")
9776
+ pbn.add_argument("--out", default=None, help="write DIAMOND-BENCH.md here")
9777
+ pbn.add_argument("--json", action="store_true")
9778
+ pbn.set_defaults(func=cmd_bench)
9779
+
9569
9780
  pcr = sub.add_parser("cleanroom",
9570
9781
  help="run a command against a CLEAN checkout of one commit in a throwaway worktree (ADR-008)")
9571
9782
  pcr.add_argument("--ledger", default="QA-LEDGER.json")
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
3
3
  "name": "uscha",
4
- "version": "1.74.0",
4
+ "version": "1.75.0",
5
5
  "displayName": "Uscha",
6
- "description": "Spec-driven development for LLM coding agents: 9 skills (discovery, adr-refine, reverse-discovery, characterize, devloop, sysdoc, rubric, mirador, status) + a stdlib measurement engine (qa_ledger.py, 46 subcommands + universal installer + npm/npx router). Facts block, guesses advise; the human approves.",
6
+ "description": "Spec-driven development for LLM coding agents: 9 skills (discovery, adr-refine, reverse-discovery, characterize, devloop, sysdoc, rubric, mirador, status) + a stdlib measurement engine (qa_ledger.py, 47 subcommands + universal installer + npm/npx router). Facts block, guesses advise; the human approves.",
7
7
  "author": {
8
8
  "name": "Andres Massello",
9
9
  "url": "https://github.com/andresmassello"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uscha",
3
- "version": "1.74.0",
3
+ "version": "1.75.0",
4
4
  "description": "Uscha spec-driven development methodology for coding agents. Includes npm/npx router.",
5
5
  "author": {
6
6
  "name": "Andres Massello",
@@ -1,6 +1,6 @@
1
1
  # uscha-kit
2
2
 
3
- **Kit version:** v1.74.0 <!-- uscha:version --> · **[uscha.dev](https://uscha.dev)**
3
+ **Kit version:** v1.75.0 <!-- uscha:version --> · **[uscha.dev](https://uscha.dev)**
4
4
 
5
5
  Spec-driven orchestrator + multi-repo QA for Claude Code, with a deterministic ledger.
6
6
  **Nine skills** (`uscha-discovery`, `uscha-adr-refine`, `uscha-devloop`, `uscha-sysdoc`, `uscha-reverse-discovery`,
package/uscha-kit/VERSION CHANGED
@@ -1 +1 @@
1
- uscha-kit 1.74.0
1
+ uscha-kit 1.75.0
@@ -0,0 +1 @@
1
+ {"AC-DB-01": true, "AC-DB-02": true, "AC-DB-03": true, "AC-DB-05": true, "AC-DB-04": true, "AC-DB-06": true}
@@ -5309,9 +5309,16 @@ _BOOTSTRAP_CASE_TIMEOUT = 15 # a compiled hook must decid
5309
5309
 
5310
5310
  def _run_oracle_case(impl_path, case):
5311
5311
  """Run ONE withheld oracle case against a compiled implementation: feed the case's stdin
5312
- (raw_stdin verbatim if present, else json.dumps(payload)) to `python <impl>`, and compare
5313
- the process exit code to `expected_exit`. Deterministic execution -- the oracle is a
5314
- `measured` fact, never an LLM judgment. Returns a per-case result dict."""
5312
+ (raw_stdin verbatim if present, else json.dumps(payload)) to `python <impl>`, and check its
5313
+ result against whichever expectations the case declares. Deterministic execution -- the
5314
+ oracle is a `measured` fact, never an LLM judgment. Returns a per-case result dict.
5315
+
5316
+ A case may assert any of: `expected_exit` (process exit code -- the M4 guard's contract),
5317
+ `expected_stdout` (the program's stdout, compared stripped -- for archetypes that COMPUTE an
5318
+ output, e.g. a parser or transformer), and `expected_json` (stdout parsed as JSON and
5319
+ compared structurally, so an output whose formatting is free but whose value is fixed is not
5320
+ penalised for whitespace or key order). The case passes iff EVERY declared expectation holds;
5321
+ a case that declares none proves nothing and fails."""
5315
5322
  if "raw_stdin" in case:
5316
5323
  stdin = case["raw_stdin"]
5317
5324
  else:
@@ -5320,14 +5327,24 @@ def _run_oracle_case(impl_path, case):
5320
5327
  r = subprocess.run([sys.executable, impl_path], input=stdin, capture_output=True,
5321
5328
  text=True, encoding="utf-8", errors="replace",
5322
5329
  timeout=_BOOTSTRAP_CASE_TIMEOUT)
5323
- got, err = r.returncode, None
5330
+ got, out, err = r.returncode, r.stdout, None
5324
5331
  except subprocess.TimeoutExpired:
5325
- got, err = None, "timeout"
5332
+ got, out, err = None, "", "timeout"
5326
5333
  except OSError as exc:
5327
- got, err = None, "could not run impl: %s" % exc
5334
+ got, out, err = None, "", "could not run impl: %s" % exc
5328
5335
  want = case.get("expected_exit")
5329
- return {"name": case.get("name"), "expected": want, "got": got,
5330
- "ok": (err is None and got == want), "error": err}
5336
+ asserted = [k for k in ("expected_exit", "expected_stdout", "expected_json") if k in case]
5337
+ ok = err is None and bool(asserted)
5338
+ if ok and "expected_exit" in case:
5339
+ ok = got == want
5340
+ if ok and "expected_stdout" in case:
5341
+ ok = (out or "").strip() == str(case["expected_stdout"]).strip()
5342
+ if ok and "expected_json" in case:
5343
+ try:
5344
+ ok = json.loads(out) == case["expected_json"]
5345
+ except (ValueError, TypeError):
5346
+ ok = False
5347
+ return {"name": case.get("name"), "expected": want, "got": got, "ok": ok, "error": err}
5331
5348
 
5332
5349
 
5333
5350
  def cmd_bootstrap_oracle(args):
@@ -5454,6 +5471,189 @@ def cmd_bootstrap_variance(args):
5454
5471
  sys.exit(0)
5455
5472
 
5456
5473
 
5474
+ # --------------------------------------------------------------------------- #
5475
+ # bench (Diamond M5: the Diamond Bench aggregates the M3/M4 primitives over a
5476
+ # set of bounded systems and emits a per-archetype verdict table. It measures
5477
+ # REGENERATION FIDELITY of canonical representations, not "which model codes
5478
+ # better" -- model identities are anonymized in the headline. Deterministic, no
5479
+ # LLM. ADR-018.)
5480
+ # --------------------------------------------------------------------------- #
5481
+ # min oracle pass-rate for a non-green compilation to still count as PARTIAL (core identity).
5482
+ _BENCH_PARTIAL_FLOOR = 0.8
5483
+
5484
+
5485
+ def _bench_oracle_all(impl_path, cases):
5486
+ results = [_run_oracle_case(impl_path, c) for c in cases]
5487
+ passed = sum(1 for r in results if r["ok"])
5488
+ return {"passed": passed, "total": len(results), "green": passed == len(results),
5489
+ "failing": [r["name"] for r in results if not r["ok"]]}
5490
+
5491
+
5492
+ def _bench_entry(entry_dir, name):
5493
+ """Run compile-validate + the withheld oracle + variance over ONE bench entry and compute
5494
+ its verdict. Reuses the M3/M4 organs unchanged; consults no model. A PASS is >=3 oracle-green
5495
+ compilations that genuinely differ; PARTIAL is core identity with the divergence isolated;
5496
+ FAIL is no green, convergence to near-identical code, or an oracle a degenerate stub can
5497
+ satisfy (non-discriminating); PENDING is an entry not yet fully compiled."""
5498
+ ir_graph, ir_errors = _load_ir_at(os.path.join(entry_dir, IR_FILE))
5499
+ try:
5500
+ with open(os.path.join(entry_dir, "oracle", "ORACLE.json"), encoding="utf-8-sig") as fh:
5501
+ cases = (json.load(fh) or {}).get("cases") or []
5502
+ except (OSError, ValueError):
5503
+ cases = []
5504
+ rec = {"archetype": name, "oracle_cases": len(cases), "compilations": [],
5505
+ "variance": None, "discrimination": None, "verdict": "PENDING", "reason": None}
5506
+ if ir_graph is None or ir_errors or not cases:
5507
+ rec["reason"] = "entry incomplete (missing/invalid IR or oracle)"
5508
+ return rec
5509
+ comp_dirs = sorted(d for d in os.listdir(entry_dir)
5510
+ if d.startswith("c-") and
5511
+ os.path.isfile(os.path.join(entry_dir, d, "COMPILATION.json")))
5512
+ for d in comp_dirs:
5513
+ cd = os.path.join(entry_dir, d)
5514
+ cj = os.path.join(cd, "COMPILATION.json")
5515
+ errors, _adv = _validate_compilation(cj, ir_graph)
5516
+ unit, model = None, None
5517
+ try:
5518
+ with open(cj, encoding="utf-8-sig") as fh:
5519
+ c = json.load(fh)
5520
+ src = c.get("source") or []
5521
+ unit = src[0].get("unit") if src else None
5522
+ model = (c.get("compilation_report") or {}).get("model")
5523
+ except (OSError, ValueError, AttributeError, IndexError):
5524
+ pass
5525
+ impl = os.path.join(cd, unit.replace("/", os.sep)) if unit else None
5526
+ ores = (_bench_oracle_all(impl, cases) if impl and os.path.isfile(impl)
5527
+ else {"passed": 0, "total": len(cases), "green": False, "failing": ["<no impl>"]})
5528
+ rec["compilations"].append({"dir": d, "model": model, "impl": impl,
5529
+ "compile_valid": not errors, "oracle": ores})
5530
+ impls = rec["compilations"]
5531
+ impl_paths = [i["impl"] for i in impls if i["impl"] and os.path.isfile(i["impl"])]
5532
+ if len(impl_paths) >= 2:
5533
+ metrics = [_impl_metrics(p) for p in impl_paths]
5534
+ shas = [m.get("sha256") for m in metrics if "error" not in m and m.get("sha256")]
5535
+ rec["variance"] = {"all_distinct": len(set(shas)) == len(shas) and len(shas) >= 2,
5536
+ "metrics": metrics}
5537
+ stub_dir = os.path.join(entry_dir, "stub")
5538
+ stub_green = False
5539
+ if os.path.isdir(stub_dir):
5540
+ stubs = sorted(f for f in os.listdir(stub_dir) if f.endswith(".py"))
5541
+ if stubs:
5542
+ sres = _bench_oracle_all(os.path.join(stub_dir, stubs[0]), cases)
5543
+ stub_green = sres["green"]
5544
+ rec["discrimination"] = {"stub_passed": sres["passed"], "total": sres["total"],
5545
+ "stub_green": stub_green}
5546
+ n = len(impls)
5547
+ if n == 0:
5548
+ rec["reason"] = "no compilations yet"
5549
+ return rec # PENDING
5550
+ all_valid = all(i["compile_valid"] for i in impls)
5551
+ greens = sum(1 for i in impls if i["oracle"]["green"])
5552
+ min_rate = min((i["oracle"]["passed"] / i["oracle"]["total"]) if i["oracle"]["total"]
5553
+ else 0.0 for i in impls)
5554
+ distinct = rec["variance"]["all_distinct"] if rec["variance"] else (n == 1)
5555
+ if stub_green:
5556
+ rec["verdict"], rec["reason"] = "FAIL", ("oracle satisfied by a degenerate stub -- not "
5557
+ "discriminating; the entry proves nothing")
5558
+ elif not all_valid:
5559
+ rec["verdict"], rec["reason"] = "FAIL", "a compilation does not validate against the pinned IR"
5560
+ elif n < 3:
5561
+ rec["verdict"], rec["reason"] = "PENDING", "fewer than 3 compilations (have %d)" % n
5562
+ elif not distinct:
5563
+ rec["verdict"], rec["reason"] = "FAIL", ("implementations converged to a byte-identical "
5564
+ "pair -- a disguised implementation")
5565
+ elif greens == n:
5566
+ rec["verdict"], rec["reason"] = "PASS", ("all %d compilations oracle-green and genuinely "
5567
+ "different -- the same system" % n)
5568
+ elif min_rate >= _BENCH_PARTIAL_FLOOR:
5569
+ rec["verdict"], rec["reason"] = "PARTIAL", ("core identity (min %.0f%% of cases); "
5570
+ "divergence isolated" % (min_rate * 100))
5571
+ else:
5572
+ rec["verdict"], rec["reason"] = "FAIL", ("a compilation below the core-identity floor "
5573
+ "(min %.0f%%)" % (min_rate * 100))
5574
+ return rec
5575
+
5576
+
5577
+ def _render_bench_md(table, anon, recs):
5578
+ lines = ["<!-- GENERATED by qa_ledger.py bench (ADR-018) -- every number is a measured run; "
5579
+ "do not hand-edit. -->", "", "# DIAMOND-BENCH", "",
5580
+ "Regeneration fidelity of canonical representations across archetypes. Each row is a "
5581
+ "bounded system compiled blind by independent models through the M3 contract and "
5582
+ "judged by a WITHHELD oracle (M4). Model identities are anonymized here; the mapping "
5583
+ "is published below.", "",
5584
+ "| Archetype | Verdict | Compilers (oracle pass / total) | Distinct | Oracle cases |",
5585
+ "|-----------|---------|--------------------------------|----------|--------------|"]
5586
+ for t in table:
5587
+ dist = "—" if t["distinct"] is None else ("yes" if t["distinct"] else "NO")
5588
+ lines.append("| %s | %s | %s | %s | %d |" % (t["archetype"], t["verdict"],
5589
+ t["compilers"], dist, t["oracle_cases"]))
5590
+ counts = {}
5591
+ for t in table:
5592
+ counts[t["verdict"]] = counts.get(t["verdict"], 0) + 1
5593
+ lines += ["", "**Coverage:** " + ", ".join("%d %s" % (v, k) for k, v in sorted(counts.items()))
5594
+ + " (of %d entries)." % len(table), "",
5595
+ "**Model map (published, not the headline):** "
5596
+ + (", ".join("%s = %s" % (a, m) for m, a in sorted(anon.items(), key=lambda x: x[1]))
5597
+ or "none yet") + ".", "",
5598
+ "## Per-entry detail", ""]
5599
+ for r in recs:
5600
+ lines.append("### %s — %s" % (r["archetype"], r["verdict"]))
5601
+ lines.append("*%s*" % (r["reason"] or ""))
5602
+ if r["compilations"]:
5603
+ for i in r["compilations"]:
5604
+ lines.append("- `%s` (%s): oracle %d/%d%s%s" % (
5605
+ i["dir"], anon.get(i["model"], i["model"] or "?"),
5606
+ i["oracle"]["passed"], i["oracle"]["total"],
5607
+ " GREEN" if i["oracle"]["green"] else "",
5608
+ "" if i["compile_valid"] else " [does not compile-validate]"))
5609
+ if r["discrimination"]:
5610
+ dsc = r["discrimination"]
5611
+ lines.append("- discrimination stub: %d/%d (%s)" % (
5612
+ dsc["stub_passed"], dsc["total"],
5613
+ "NON-DISCRIMINATING" if dsc["stub_green"] else "oracle rejects the stub"))
5614
+ lines.append("")
5615
+ return "\n".join(lines)
5616
+
5617
+
5618
+ def cmd_bench(args):
5619
+ if not os.path.isdir(args.dir):
5620
+ print("[qa_ledger] bench: no directory %s" % args.dir, file=sys.stderr)
5621
+ sys.exit(2)
5622
+ entries = sorted(d for d in os.listdir(args.dir)
5623
+ if os.path.isfile(os.path.join(args.dir, d, IR_FILE)))
5624
+ if not entries:
5625
+ print("[qa_ledger] bench: no entries under %s (an entry is a subdir with %s)"
5626
+ % (args.dir, IR_FILE), file=sys.stderr)
5627
+ sys.exit(2)
5628
+ recs = [_bench_entry(os.path.join(args.dir, e), e) for e in entries]
5629
+ models = sorted({i["model"] for r in recs for i in r["compilations"] if i.get("model")})
5630
+ anon = {m: "M%d" % (k + 1) for k, m in enumerate(models)}
5631
+ table = []
5632
+ for r in recs:
5633
+ cols = ", ".join("%s %d/%d" % (anon.get(i["model"], "?"), i["oracle"]["passed"],
5634
+ i["oracle"]["total"]) for i in r["compilations"])
5635
+ table.append({"archetype": r["archetype"], "verdict": r["verdict"],
5636
+ "compilers": cols or "(none yet)",
5637
+ "distinct": (r["variance"] or {}).get("all_distinct"),
5638
+ "oracle_cases": r["oracle_cases"], "reason": r["reason"]})
5639
+ md = _render_bench_md(table, anon, recs)
5640
+ if args.out:
5641
+ with open(args.out, "w", encoding="utf-8", newline="\n") as fh:
5642
+ fh.write(md)
5643
+ if args.json:
5644
+ print(json.dumps({"entries": len(recs), "model_map": anon, "table": table,
5645
+ "raw": recs}, indent=2, ensure_ascii=False))
5646
+ else:
5647
+ print("BENCH: %d entries" % len(recs))
5648
+ for t in table:
5649
+ dist = "" if t["distinct"] is None else (" | distinct" if t["distinct"]
5650
+ else " | CONVERGED")
5651
+ print(" %-14s %-8s | %s%s" % (t["archetype"], t["verdict"], t["compilers"], dist))
5652
+ if args.out:
5653
+ print(" -> %s" % args.out)
5654
+ sys.exit(0)
5655
+
5656
+
5457
5657
  # --------------------------------------------------------------------------- #
5458
5658
  # facts (T0 / SYSTEM-FACTS: public claims become compiled artifacts of repo
5459
5659
  # facts -- Diamond applied to Diamond. ADR-012.)
@@ -9566,6 +9766,17 @@ def build_parser():
9566
9766
  pbv.add_argument("--json", action="store_true")
9567
9767
  pbv.set_defaults(func=cmd_bootstrap_variance)
9568
9768
 
9769
+ pbn = sub.add_parser(
9770
+ "bench",
9771
+ help="the Diamond Bench (ADR-018): per-archetype verdict table over a set of bounded "
9772
+ "systems, aggregating compile-validate + bootstrap-oracle + bootstrap-variance; "
9773
+ "model identities anonymized in the headline; deterministic, no LLM")
9774
+ pbn.add_argument("--dir", required=True,
9775
+ help="the bench directory; each subdir with an IR.json is an entry")
9776
+ pbn.add_argument("--out", default=None, help="write DIAMOND-BENCH.md here")
9777
+ pbn.add_argument("--json", action="store_true")
9778
+ pbn.set_defaults(func=cmd_bench)
9779
+
9569
9780
  pcr = sub.add_parser("cleanroom",
9570
9781
  help="run a command against a CLEAN checkout of one commit in a throwaway worktree (ADR-008)")
9571
9782
  pcr.add_argument("--ledger", default="QA-LEDGER.json")
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.74.0",
2
+ "version": "1.75.0",
3
3
  "project": null,
4
4
  "defaults": {
5
5
  "coverage_threshold": 60,