@andresmassello/uscha 1.83.0 → 1.84.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.83.0** <!-- uscha:version --> · [uscha.dev](https://uscha.dev) ·
43
+ **Kit v1.84.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`, 49 subcommands, Python stdlib) that ingests
79
+ **A measurement engine** (`qa_ledger.py`, 50 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.83.0",
3
+ "version": "1.84.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",
@@ -5786,6 +5786,225 @@ def cmd_bench(args):
5786
5786
  sys.exit(0)
5787
5787
 
5788
5788
 
5789
+ _R2_DIR = "r2"
5790
+ _R2_SIGNAL = 0.5 # intra/inter below this: inter-compiler variance is real signal
5791
+ _R2_NOISE = 1.0 # intra/inter at/above this: same-model reruns differ as much as models
5792
+
5793
+
5794
+ def _r2_class(ratio):
5795
+ if ratio is None:
5796
+ return None
5797
+ if ratio < _R2_SIGNAL:
5798
+ return "SIGNAL"
5799
+ if ratio < _R2_NOISE:
5800
+ return "NOISY"
5801
+ return "NOISE"
5802
+
5803
+
5804
+ def _r2_entry(entry_dir, name):
5805
+ """Intra-model variance for ONE bench entry (ADR-027): for each model with a run-1 (top-level
5806
+ c-<model>) AND a run-2 (r2/c-<model>), the structural distance between the two runs via the
5807
+ SAME _struct_distance the bench uses between compilers, each run's oracle pass-rate, and
5808
+ whether the two runs agree on every oracle case. Entries without r2/ report absent, never 0."""
5809
+ ir_graph, ir_errors = _load_ir_at(os.path.join(entry_dir, IR_FILE))
5810
+ try:
5811
+ with open(os.path.join(entry_dir, "oracle", "ORACLE.json"), encoding="utf-8-sig") as fh:
5812
+ cases = (json.load(fh) or {}).get("cases") or []
5813
+ except (OSError, ValueError):
5814
+ cases = []
5815
+ rec = {"archetype": name, "has_r2": False, "models": [], "intra_mean": None,
5816
+ "inter": None, "intra_over_inter": None, "class": None, "reason": None}
5817
+ r2 = os.path.join(entry_dir, _R2_DIR)
5818
+ if not os.path.isdir(r2):
5819
+ rec["reason"] = "no r2/ directory -- intra-model variance not measured"
5820
+ return rec
5821
+ rec["has_r2"] = True
5822
+ if ir_graph is None or ir_errors or not cases:
5823
+ rec["reason"] = "entry incomplete (missing/invalid IR or oracle)"
5824
+ return rec
5825
+
5826
+ def load_run(cd):
5827
+ cj = os.path.join(cd, "COMPILATION.json")
5828
+ if not os.path.isfile(cj):
5829
+ return None
5830
+ errors, _adv = _validate_compilation(cj, ir_graph)
5831
+ try:
5832
+ with open(cj, encoding="utf-8-sig") as fh:
5833
+ c = json.load(fh)
5834
+ unit = (c.get("source") or [{}])[0].get("unit")
5835
+ model = (c.get("compilation_report") or {}).get("model")
5836
+ except (OSError, ValueError, AttributeError, IndexError):
5837
+ return None
5838
+ impl = os.path.join(cd, unit.replace("/", os.sep)) if unit else None
5839
+ if not impl or not os.path.isfile(impl):
5840
+ return None
5841
+ ores = _bench_oracle_all(impl, cases)
5842
+ m = _impl_metrics(impl)
5843
+ return {"model": model, "compile_valid": not errors, "oracle": ores,
5844
+ "metrics": m if "error" not in m else None,
5845
+ "case_vector": tuple(sorted(ores.get("failing") or []))}
5846
+
5847
+ def rate(o):
5848
+ return round(o["passed"] / o["total"], 3) if o["total"] else None
5849
+
5850
+ intra = []
5851
+ run1_metrics = []
5852
+ for d in sorted(os.listdir(entry_dir)):
5853
+ if not d.startswith("c-") or not os.path.isdir(os.path.join(entry_dir, d)):
5854
+ continue
5855
+ r1 = load_run(os.path.join(entry_dir, d))
5856
+ if r1 is None:
5857
+ continue
5858
+ if r1["metrics"]:
5859
+ run1_metrics.append(r1["metrics"])
5860
+ r2run = load_run(os.path.join(r2, d))
5861
+ if r2run is None:
5862
+ rec["models"].append({"dir": d, "model": r1["model"], "r2": "absent"})
5863
+ continue
5864
+ dist = (_struct_distance(r1["metrics"], r2run["metrics"])
5865
+ if r1["metrics"] and r2run["metrics"] else None)
5866
+ stable = r1["case_vector"] == r2run["case_vector"]
5867
+ rec["models"].append({"dir": d, "model": r1["model"],
5868
+ "intra_distance": round(dist, 4) if dist is not None else None,
5869
+ "run1_passrate": rate(r1["oracle"]),
5870
+ "run2_passrate": rate(r2run["oracle"]),
5871
+ "run2_compile_valid": r2run["compile_valid"],
5872
+ "behaviour_stable": stable})
5873
+ if dist is not None:
5874
+ intra.append(dist)
5875
+ if intra:
5876
+ rec["intra_mean"] = round(sum(intra) / len(intra), 4)
5877
+ inter = []
5878
+ for i in range(len(run1_metrics)):
5879
+ for j in range(i + 1, len(run1_metrics)):
5880
+ inter.append(_struct_distance(run1_metrics[i], run1_metrics[j]))
5881
+ if inter:
5882
+ rec["inter"] = round(sum(inter) / len(inter), 4)
5883
+ if rec["intra_mean"] is not None and rec["inter"]:
5884
+ # 2 dp on purpose: the ratio moves by up to ~0.26 between interpreters (ast.walk
5885
+ # counts nodes differently on 3.8 vs 3.13 -- the 1.84.0 review measured it); more
5886
+ # decimals would print precision the measurement does not have (ADR-027).
5887
+ rec["intra_over_inter"] = round(rec["intra_mean"] / rec["inter"], 2)
5888
+ rec["class"] = _r2_class(rec["intra_over_inter"])
5889
+ elif rec["intra_mean"] is not None and rec["inter"] == 0.0:
5890
+ rec["reason"] = "inter-compiler distance is 0 (converged run-1) -- ratio undefined"
5891
+ elif rec["intra_mean"] is None:
5892
+ # r2/ exists but no model pair yielded a computable distance (unparseable source,
5893
+ # missing COMPILATION.json in every r2 model): absent, named -- never a silent None
5894
+ rec["reason"] = ("r2/ present but no model pair measurable (no parseable run-1+run-2 "
5895
+ "source for any model) -- intra-model variance not measured")
5896
+ return rec
5897
+
5898
+
5899
+ _R2_VERDICT_TEXT = {
5900
+ "SIGNAL": "Across the measured entries, same-model reruns differ far less than different "
5901
+ "models do: the inter-compiler variance the program reports is signal, not sampling "
5902
+ "noise -- for these archetypes, at n=2 per model.",
5903
+ "NOISY": "Same-model reruns differ by a sizeable fraction of the inter-compiler distance: "
5904
+ "inter-compiler variance carries information, but a delta smaller than the noise "
5905
+ "floor should not be read as an effect.",
5906
+ "NOISE": "Same-model reruns differ as much as different models do: the inter-compiler "
5907
+ "variance the program reports is dominated by sampling noise for these archetypes -- "
5908
+ "variance-based claims must be re-read.",
5909
+ "UNMEASURED": "No entry carries a second run; the noise floor is absent, not zero.",
5910
+ }
5911
+
5912
+
5913
+ def _render_r2_md(recs, agg):
5914
+ lines = ["<!-- GENERATED by qa_ledger.py bench-r2 (ADR-027) -- measured run; do not hand-edit. -->",
5915
+ "", "# DIAMOND-BENCH-R2 -- intra-model variance, the noise floor under the bench", "",
5916
+ "For every archetype with a second blind run (`r2/`) of the SAME model on the SAME "
5917
+ "canonical package: the structural distance between run 1 and run 2 (the same "
5918
+ "function the bench uses BETWEEN compilers), each run's oracle pass-rate, and "
5919
+ "whether both runs fail the same oracle cases. `intra/inter` below 0.5 reads SIGNAL "
5920
+ "(inter-compiler variance is at least twice the noise floor), 0.5-1.0 NOISY, at or "
5921
+ "above 1.0 NOISE (same-model reruns differ as much as different models). Advisory: "
5922
+ "no bench verdict changes; this qualifies every variance claim the program makes.", "",
5923
+ "| Archetype | intra (mean) | inter | intra/inter | class | per model (run1 -> run2 pass-rate, stable) |",
5924
+ "|-----------|--------------|-------|-------------|-------|--------------------------------------------|"]
5925
+ for r in recs:
5926
+ if not r["has_r2"]:
5927
+ lines.append("| %s | -- | -- | -- | (no r2) | %s |" % (r["archetype"], r["reason"] or ""))
5928
+ continue
5929
+ pm = "; ".join(("%s %s->%s %s" % (m["dir"], m.get("run1_passrate"), m.get("run2_passrate"),
5930
+ "stable" if m.get("behaviour_stable") else "DIFFERS"))
5931
+ if m.get("r2") != "absent" else ("%s (r2 absent)" % m["dir"])
5932
+ for m in r["models"])
5933
+ lines.append("| %s | %s | %s | %s | %s | %s |" % (
5934
+ r["archetype"],
5935
+ "%.4f" % r["intra_mean"] if r["intra_mean"] is not None else "--",
5936
+ "%.4f" % r["inter"] if r["inter"] is not None else "--",
5937
+ "%.2f" % r["intra_over_inter"] if r["intra_over_inter"] is not None else "--",
5938
+ r["class"] or (r["reason"] or "--"), pm))
5939
+ lines += ["", "**Aggregate:** %d entries measured -- SIGNAL %d · NOISY %d · NOISE %d · mean "
5940
+ "intra/inter %s · behaviour-stable reruns %d/%d." % (
5941
+ agg["measured"], agg["signal"], agg["noisy"], agg["noise"],
5942
+ "%.3f" % agg["mean_ratio"] if agg["mean_ratio"] is not None else "n/a",
5943
+ agg["stable"], agg["reruns"]),
5944
+ "", "## Verdict: %s" % agg["verdict"], "", _R2_VERDICT_TEXT[agg["verdict"]],
5945
+ "", "*Structural distance = mean of normalized LOC delta, AST-node delta and "
5946
+ "import-set Jaccard distance -- the one function shared by lang-compare, bench "
5947
+ "and bench-r2. n=2 per model is the minimum that yields a floor at all; it is a "
5948
+ "floor, not a distribution. The ratio is printed to 2 decimals on purpose: the "
5949
+ "AST-node count differs between Python versions (ast.walk on 3.8 vs 3.13), so a "
5950
+ "ratio can move by up to ~0.26 across interpreters without any code or model "
5951
+ "changing -- classes are stable across 3.8/3.13 on this bench, ratios are not "
5952
+ "point-precise, and an entry within ~0.25 of a threshold should be read as "
5953
+ "borderline.*", ""]
5954
+ return "\n".join(lines)
5955
+
5956
+
5957
+ def cmd_bench_r2(args):
5958
+ if not os.path.isdir(args.dir):
5959
+ print("[qa_ledger] bench-r2: no directory %s" % args.dir, file=sys.stderr)
5960
+ sys.exit(2)
5961
+ entries = sorted(d for d in os.listdir(args.dir)
5962
+ if os.path.isfile(os.path.join(args.dir, d, IR_FILE)))
5963
+ if not entries:
5964
+ print("[qa_ledger] bench-r2: no entries under %s" % args.dir, file=sys.stderr)
5965
+ sys.exit(2)
5966
+ recs = [_r2_entry(os.path.join(args.dir, e), e) for e in entries]
5967
+ measured = [r for r in recs if r["class"] is not None]
5968
+ ratios = [r["intra_over_inter"] for r in measured]
5969
+ reruns = [m for r in recs if r["has_r2"] for m in r["models"] if m.get("r2") != "absent"]
5970
+ agg = {"entries": len(recs), "with_r2": sum(1 for r in recs if r["has_r2"]),
5971
+ "measured": len(measured),
5972
+ "signal": sum(1 for r in measured if r["class"] == "SIGNAL"),
5973
+ "noisy": sum(1 for r in measured if r["class"] == "NOISY"),
5974
+ "noise": sum(1 for r in measured if r["class"] == "NOISE"),
5975
+ "mean_ratio": round(sum(ratios) / len(ratios), 3) if ratios else None,
5976
+ "reruns": len(reruns),
5977
+ "stable": sum(1 for m in reruns if m.get("behaviour_stable"))}
5978
+ if not measured:
5979
+ agg["verdict"] = "UNMEASURED"
5980
+ else:
5981
+ counts = [(agg["signal"], "SIGNAL"), (agg["noisy"], "NOISY"), (agg["noise"], "NOISE")]
5982
+ top = max(c for c, _ in counts)
5983
+ # ties resolve toward the more cautious reading (NOISE > NOISY > SIGNAL)
5984
+ agg["verdict"] = [n for c, n in reversed(counts) if c == top][0]
5985
+ md = _render_r2_md(recs, agg)
5986
+ if args.out:
5987
+ with open(args.out, "w", encoding="utf-8", newline="\n") as fh:
5988
+ fh.write(md)
5989
+ if args.json:
5990
+ print(json.dumps({"aggregate": agg, "raw": recs}, indent=2, ensure_ascii=False))
5991
+ else:
5992
+ print("BENCH-R2: %d entries, %d with r2, %d measured -- SIGNAL %d / NOISY %d / NOISE %d"
5993
+ % (agg["entries"], agg["with_r2"], agg["measured"], agg["signal"], agg["noisy"],
5994
+ agg["noise"]))
5995
+ for r in recs:
5996
+ if r["class"]:
5997
+ print(" %-17s intra %.4f inter %.4f ratio %.2f %s"
5998
+ % (r["archetype"], r["intra_mean"], r["inter"], r["intra_over_inter"],
5999
+ r["class"]))
6000
+ elif r["has_r2"]:
6001
+ print(" %-17s %s" % (r["archetype"], r["reason"]))
6002
+ print("VERDICT: %s%s" % (agg["verdict"], (" -> %s" % args.out) if args.out else ""))
6003
+ print(" (ratios are not point-precise: AST-node counts differ across Python versions; "
6004
+ "classes stable, ratios +/-0.25 -- read borderline entries as borderline)")
6005
+ sys.exit(0)
6006
+
6007
+
5789
6008
  def _bench_curable_obs(bench_dir, entry, cdir):
5790
6009
  """The curable set for one compilation: the SAME observations the M1 static extractor
5791
6010
  produces for the descriptor's static_surface, re-extracted at call time -- a verdict
@@ -5954,16 +6173,23 @@ def _lang_arm_metrics(arm_dir):
5954
6173
  dists = []
5955
6174
  for i in range(len(good)):
5956
6175
  for j in range(i + 1, len(good)):
5957
- a, b = good[i], good[j]
5958
- ia, ib = set(a["imports"]), set(b["imports"])
5959
- jac = (len(ia & ib) / len(ia | ib)) if (ia or ib) else 1.0
5960
- dloc = abs(a["loc"] - b["loc"]) / max(a["loc"], b["loc"], 1)
5961
- dast = abs(a["ast_nodes"] - b["ast_nodes"]) / max(a["ast_nodes"], b["ast_nodes"], 1)
5962
- dists.append((dloc + dast + (1.0 - jac)) / 3.0)
6176
+ dists.append(_struct_distance(good[i], good[j]))
5963
6177
  rec["variance_score"] = round(sum(dists) / len(dists), 4) if dists else None
5964
6178
  return rec, []
5965
6179
 
5966
6180
 
6181
+ def _struct_distance(a, b):
6182
+ """The ONE structural distance the program uses between two implementations -- mean of
6183
+ normalized LOC delta, AST-node delta and import-set Jaccard distance (0 = identical). Shared
6184
+ by the inter-compiler variance (lang-compare, bench) and the intra-model variance (bench-r2,
6185
+ ADR-027) so their ratio is commensurable: same function, both sides."""
6186
+ ia, ib = set(a["imports"]), set(b["imports"])
6187
+ jac = (len(ia & ib) / len(ia | ib)) if (ia or ib) else 1.0
6188
+ dloc = abs(a["loc"] - b["loc"]) / max(a["loc"], b["loc"], 1)
6189
+ dast = abs(a["ast_nodes"] - b["ast_nodes"]) / max(a["ast_nodes"], b["ast_nodes"], 1)
6190
+ return (dloc + dast + (1.0 - jac)) / 3.0
6191
+
6192
+
5967
6193
  def _oracle_hash(arm_dir):
5968
6194
  try:
5969
6195
  with open(os.path.join(arm_dir, "oracle", "ORACLE.json"), "rb") as fh:
@@ -6093,7 +6319,9 @@ def _render_lang_md(r):
6093
6319
  "arm's low variance was convergence on a shared reading (right or "
6094
6320
  "wrong): two compilers resolving the same ambiguity the same way read "
6095
6321
  "as agreement, and a rewrite that separates them raises variance "
6096
- "while moving behaviour."
6322
+ "while moving behaviour. Read any variance number here against the "
6323
+ "entry's intra-model noise floor (bench-r2, ADR-027): an inter-compiler "
6324
+ "distance below that floor is not evidence of convergence."
6097
6325
  % r.get("passrate_margin", 0.02)}[r["verdict"]],
6098
6326
  "", "*The oracle is byte-identical across both arms, so behaviour is held fixed; "
6099
6327
  "the only variable is the authoring discipline. The judgement of \"same semantic "
@@ -10246,6 +10474,17 @@ def build_parser():
10246
10474
  "(read-only), including stale verdicts whose obs no longer exists")
10247
10475
  pbc.set_defaults(func=cmd_bench_curate)
10248
10476
 
10477
+ pbr = sub.add_parser(
10478
+ "bench-r2",
10479
+ help="intra-model variance (ADR-027): for every bench entry with an r2/ second run of "
10480
+ "the same models, the run1-vs-run2 structural distance via the SAME function the "
10481
+ "bench uses between compilers, oracle stability, and a per-entry SIGNAL/NOISY/NOISE "
10482
+ "class; the noise floor under every variance claim; advisory, deterministic, no LLM")
10483
+ pbr.add_argument("--dir", required=True, help="the bench directory")
10484
+ pbr.add_argument("--out", default=None, help="write DIAMOND-BENCH-R2.md here")
10485
+ pbr.add_argument("--json", action="store_true")
10486
+ pbr.set_defaults(func=cmd_bench_r2)
10487
+
10249
10488
  plc = sub.add_parser(
10250
10489
  "lang-compare",
10251
10490
  help="controlled-language arm (ADR-019): compare a FREE-prose arm and an EARS+STE arm of "
@@ -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.83.0",
4
+ "version": "1.84.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, 49 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, 50 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.83.0",
3
+ "version": "1.84.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.83.0 <!-- uscha:version --> · **[uscha.dev](https://uscha.dev)**
3
+ **Kit version:** v1.84.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.83.0
1
+ uscha-kit 1.84.0
@@ -0,0 +1 @@
1
+ {"AC-R2-01": true, "AC-R2-02": true, "AC-R2-03": true}
@@ -5786,6 +5786,225 @@ def cmd_bench(args):
5786
5786
  sys.exit(0)
5787
5787
 
5788
5788
 
5789
+ _R2_DIR = "r2"
5790
+ _R2_SIGNAL = 0.5 # intra/inter below this: inter-compiler variance is real signal
5791
+ _R2_NOISE = 1.0 # intra/inter at/above this: same-model reruns differ as much as models
5792
+
5793
+
5794
+ def _r2_class(ratio):
5795
+ if ratio is None:
5796
+ return None
5797
+ if ratio < _R2_SIGNAL:
5798
+ return "SIGNAL"
5799
+ if ratio < _R2_NOISE:
5800
+ return "NOISY"
5801
+ return "NOISE"
5802
+
5803
+
5804
+ def _r2_entry(entry_dir, name):
5805
+ """Intra-model variance for ONE bench entry (ADR-027): for each model with a run-1 (top-level
5806
+ c-<model>) AND a run-2 (r2/c-<model>), the structural distance between the two runs via the
5807
+ SAME _struct_distance the bench uses between compilers, each run's oracle pass-rate, and
5808
+ whether the two runs agree on every oracle case. Entries without r2/ report absent, never 0."""
5809
+ ir_graph, ir_errors = _load_ir_at(os.path.join(entry_dir, IR_FILE))
5810
+ try:
5811
+ with open(os.path.join(entry_dir, "oracle", "ORACLE.json"), encoding="utf-8-sig") as fh:
5812
+ cases = (json.load(fh) or {}).get("cases") or []
5813
+ except (OSError, ValueError):
5814
+ cases = []
5815
+ rec = {"archetype": name, "has_r2": False, "models": [], "intra_mean": None,
5816
+ "inter": None, "intra_over_inter": None, "class": None, "reason": None}
5817
+ r2 = os.path.join(entry_dir, _R2_DIR)
5818
+ if not os.path.isdir(r2):
5819
+ rec["reason"] = "no r2/ directory -- intra-model variance not measured"
5820
+ return rec
5821
+ rec["has_r2"] = True
5822
+ if ir_graph is None or ir_errors or not cases:
5823
+ rec["reason"] = "entry incomplete (missing/invalid IR or oracle)"
5824
+ return rec
5825
+
5826
+ def load_run(cd):
5827
+ cj = os.path.join(cd, "COMPILATION.json")
5828
+ if not os.path.isfile(cj):
5829
+ return None
5830
+ errors, _adv = _validate_compilation(cj, ir_graph)
5831
+ try:
5832
+ with open(cj, encoding="utf-8-sig") as fh:
5833
+ c = json.load(fh)
5834
+ unit = (c.get("source") or [{}])[0].get("unit")
5835
+ model = (c.get("compilation_report") or {}).get("model")
5836
+ except (OSError, ValueError, AttributeError, IndexError):
5837
+ return None
5838
+ impl = os.path.join(cd, unit.replace("/", os.sep)) if unit else None
5839
+ if not impl or not os.path.isfile(impl):
5840
+ return None
5841
+ ores = _bench_oracle_all(impl, cases)
5842
+ m = _impl_metrics(impl)
5843
+ return {"model": model, "compile_valid": not errors, "oracle": ores,
5844
+ "metrics": m if "error" not in m else None,
5845
+ "case_vector": tuple(sorted(ores.get("failing") or []))}
5846
+
5847
+ def rate(o):
5848
+ return round(o["passed"] / o["total"], 3) if o["total"] else None
5849
+
5850
+ intra = []
5851
+ run1_metrics = []
5852
+ for d in sorted(os.listdir(entry_dir)):
5853
+ if not d.startswith("c-") or not os.path.isdir(os.path.join(entry_dir, d)):
5854
+ continue
5855
+ r1 = load_run(os.path.join(entry_dir, d))
5856
+ if r1 is None:
5857
+ continue
5858
+ if r1["metrics"]:
5859
+ run1_metrics.append(r1["metrics"])
5860
+ r2run = load_run(os.path.join(r2, d))
5861
+ if r2run is None:
5862
+ rec["models"].append({"dir": d, "model": r1["model"], "r2": "absent"})
5863
+ continue
5864
+ dist = (_struct_distance(r1["metrics"], r2run["metrics"])
5865
+ if r1["metrics"] and r2run["metrics"] else None)
5866
+ stable = r1["case_vector"] == r2run["case_vector"]
5867
+ rec["models"].append({"dir": d, "model": r1["model"],
5868
+ "intra_distance": round(dist, 4) if dist is not None else None,
5869
+ "run1_passrate": rate(r1["oracle"]),
5870
+ "run2_passrate": rate(r2run["oracle"]),
5871
+ "run2_compile_valid": r2run["compile_valid"],
5872
+ "behaviour_stable": stable})
5873
+ if dist is not None:
5874
+ intra.append(dist)
5875
+ if intra:
5876
+ rec["intra_mean"] = round(sum(intra) / len(intra), 4)
5877
+ inter = []
5878
+ for i in range(len(run1_metrics)):
5879
+ for j in range(i + 1, len(run1_metrics)):
5880
+ inter.append(_struct_distance(run1_metrics[i], run1_metrics[j]))
5881
+ if inter:
5882
+ rec["inter"] = round(sum(inter) / len(inter), 4)
5883
+ if rec["intra_mean"] is not None and rec["inter"]:
5884
+ # 2 dp on purpose: the ratio moves by up to ~0.26 between interpreters (ast.walk
5885
+ # counts nodes differently on 3.8 vs 3.13 -- the 1.84.0 review measured it); more
5886
+ # decimals would print precision the measurement does not have (ADR-027).
5887
+ rec["intra_over_inter"] = round(rec["intra_mean"] / rec["inter"], 2)
5888
+ rec["class"] = _r2_class(rec["intra_over_inter"])
5889
+ elif rec["intra_mean"] is not None and rec["inter"] == 0.0:
5890
+ rec["reason"] = "inter-compiler distance is 0 (converged run-1) -- ratio undefined"
5891
+ elif rec["intra_mean"] is None:
5892
+ # r2/ exists but no model pair yielded a computable distance (unparseable source,
5893
+ # missing COMPILATION.json in every r2 model): absent, named -- never a silent None
5894
+ rec["reason"] = ("r2/ present but no model pair measurable (no parseable run-1+run-2 "
5895
+ "source for any model) -- intra-model variance not measured")
5896
+ return rec
5897
+
5898
+
5899
+ _R2_VERDICT_TEXT = {
5900
+ "SIGNAL": "Across the measured entries, same-model reruns differ far less than different "
5901
+ "models do: the inter-compiler variance the program reports is signal, not sampling "
5902
+ "noise -- for these archetypes, at n=2 per model.",
5903
+ "NOISY": "Same-model reruns differ by a sizeable fraction of the inter-compiler distance: "
5904
+ "inter-compiler variance carries information, but a delta smaller than the noise "
5905
+ "floor should not be read as an effect.",
5906
+ "NOISE": "Same-model reruns differ as much as different models do: the inter-compiler "
5907
+ "variance the program reports is dominated by sampling noise for these archetypes -- "
5908
+ "variance-based claims must be re-read.",
5909
+ "UNMEASURED": "No entry carries a second run; the noise floor is absent, not zero.",
5910
+ }
5911
+
5912
+
5913
+ def _render_r2_md(recs, agg):
5914
+ lines = ["<!-- GENERATED by qa_ledger.py bench-r2 (ADR-027) -- measured run; do not hand-edit. -->",
5915
+ "", "# DIAMOND-BENCH-R2 -- intra-model variance, the noise floor under the bench", "",
5916
+ "For every archetype with a second blind run (`r2/`) of the SAME model on the SAME "
5917
+ "canonical package: the structural distance between run 1 and run 2 (the same "
5918
+ "function the bench uses BETWEEN compilers), each run's oracle pass-rate, and "
5919
+ "whether both runs fail the same oracle cases. `intra/inter` below 0.5 reads SIGNAL "
5920
+ "(inter-compiler variance is at least twice the noise floor), 0.5-1.0 NOISY, at or "
5921
+ "above 1.0 NOISE (same-model reruns differ as much as different models). Advisory: "
5922
+ "no bench verdict changes; this qualifies every variance claim the program makes.", "",
5923
+ "| Archetype | intra (mean) | inter | intra/inter | class | per model (run1 -> run2 pass-rate, stable) |",
5924
+ "|-----------|--------------|-------|-------------|-------|--------------------------------------------|"]
5925
+ for r in recs:
5926
+ if not r["has_r2"]:
5927
+ lines.append("| %s | -- | -- | -- | (no r2) | %s |" % (r["archetype"], r["reason"] or ""))
5928
+ continue
5929
+ pm = "; ".join(("%s %s->%s %s" % (m["dir"], m.get("run1_passrate"), m.get("run2_passrate"),
5930
+ "stable" if m.get("behaviour_stable") else "DIFFERS"))
5931
+ if m.get("r2") != "absent" else ("%s (r2 absent)" % m["dir"])
5932
+ for m in r["models"])
5933
+ lines.append("| %s | %s | %s | %s | %s | %s |" % (
5934
+ r["archetype"],
5935
+ "%.4f" % r["intra_mean"] if r["intra_mean"] is not None else "--",
5936
+ "%.4f" % r["inter"] if r["inter"] is not None else "--",
5937
+ "%.2f" % r["intra_over_inter"] if r["intra_over_inter"] is not None else "--",
5938
+ r["class"] or (r["reason"] or "--"), pm))
5939
+ lines += ["", "**Aggregate:** %d entries measured -- SIGNAL %d · NOISY %d · NOISE %d · mean "
5940
+ "intra/inter %s · behaviour-stable reruns %d/%d." % (
5941
+ agg["measured"], agg["signal"], agg["noisy"], agg["noise"],
5942
+ "%.3f" % agg["mean_ratio"] if agg["mean_ratio"] is not None else "n/a",
5943
+ agg["stable"], agg["reruns"]),
5944
+ "", "## Verdict: %s" % agg["verdict"], "", _R2_VERDICT_TEXT[agg["verdict"]],
5945
+ "", "*Structural distance = mean of normalized LOC delta, AST-node delta and "
5946
+ "import-set Jaccard distance -- the one function shared by lang-compare, bench "
5947
+ "and bench-r2. n=2 per model is the minimum that yields a floor at all; it is a "
5948
+ "floor, not a distribution. The ratio is printed to 2 decimals on purpose: the "
5949
+ "AST-node count differs between Python versions (ast.walk on 3.8 vs 3.13), so a "
5950
+ "ratio can move by up to ~0.26 across interpreters without any code or model "
5951
+ "changing -- classes are stable across 3.8/3.13 on this bench, ratios are not "
5952
+ "point-precise, and an entry within ~0.25 of a threshold should be read as "
5953
+ "borderline.*", ""]
5954
+ return "\n".join(lines)
5955
+
5956
+
5957
+ def cmd_bench_r2(args):
5958
+ if not os.path.isdir(args.dir):
5959
+ print("[qa_ledger] bench-r2: no directory %s" % args.dir, file=sys.stderr)
5960
+ sys.exit(2)
5961
+ entries = sorted(d for d in os.listdir(args.dir)
5962
+ if os.path.isfile(os.path.join(args.dir, d, IR_FILE)))
5963
+ if not entries:
5964
+ print("[qa_ledger] bench-r2: no entries under %s" % args.dir, file=sys.stderr)
5965
+ sys.exit(2)
5966
+ recs = [_r2_entry(os.path.join(args.dir, e), e) for e in entries]
5967
+ measured = [r for r in recs if r["class"] is not None]
5968
+ ratios = [r["intra_over_inter"] for r in measured]
5969
+ reruns = [m for r in recs if r["has_r2"] for m in r["models"] if m.get("r2") != "absent"]
5970
+ agg = {"entries": len(recs), "with_r2": sum(1 for r in recs if r["has_r2"]),
5971
+ "measured": len(measured),
5972
+ "signal": sum(1 for r in measured if r["class"] == "SIGNAL"),
5973
+ "noisy": sum(1 for r in measured if r["class"] == "NOISY"),
5974
+ "noise": sum(1 for r in measured if r["class"] == "NOISE"),
5975
+ "mean_ratio": round(sum(ratios) / len(ratios), 3) if ratios else None,
5976
+ "reruns": len(reruns),
5977
+ "stable": sum(1 for m in reruns if m.get("behaviour_stable"))}
5978
+ if not measured:
5979
+ agg["verdict"] = "UNMEASURED"
5980
+ else:
5981
+ counts = [(agg["signal"], "SIGNAL"), (agg["noisy"], "NOISY"), (agg["noise"], "NOISE")]
5982
+ top = max(c for c, _ in counts)
5983
+ # ties resolve toward the more cautious reading (NOISE > NOISY > SIGNAL)
5984
+ agg["verdict"] = [n for c, n in reversed(counts) if c == top][0]
5985
+ md = _render_r2_md(recs, agg)
5986
+ if args.out:
5987
+ with open(args.out, "w", encoding="utf-8", newline="\n") as fh:
5988
+ fh.write(md)
5989
+ if args.json:
5990
+ print(json.dumps({"aggregate": agg, "raw": recs}, indent=2, ensure_ascii=False))
5991
+ else:
5992
+ print("BENCH-R2: %d entries, %d with r2, %d measured -- SIGNAL %d / NOISY %d / NOISE %d"
5993
+ % (agg["entries"], agg["with_r2"], agg["measured"], agg["signal"], agg["noisy"],
5994
+ agg["noise"]))
5995
+ for r in recs:
5996
+ if r["class"]:
5997
+ print(" %-17s intra %.4f inter %.4f ratio %.2f %s"
5998
+ % (r["archetype"], r["intra_mean"], r["inter"], r["intra_over_inter"],
5999
+ r["class"]))
6000
+ elif r["has_r2"]:
6001
+ print(" %-17s %s" % (r["archetype"], r["reason"]))
6002
+ print("VERDICT: %s%s" % (agg["verdict"], (" -> %s" % args.out) if args.out else ""))
6003
+ print(" (ratios are not point-precise: AST-node counts differ across Python versions; "
6004
+ "classes stable, ratios +/-0.25 -- read borderline entries as borderline)")
6005
+ sys.exit(0)
6006
+
6007
+
5789
6008
  def _bench_curable_obs(bench_dir, entry, cdir):
5790
6009
  """The curable set for one compilation: the SAME observations the M1 static extractor
5791
6010
  produces for the descriptor's static_surface, re-extracted at call time -- a verdict
@@ -5954,16 +6173,23 @@ def _lang_arm_metrics(arm_dir):
5954
6173
  dists = []
5955
6174
  for i in range(len(good)):
5956
6175
  for j in range(i + 1, len(good)):
5957
- a, b = good[i], good[j]
5958
- ia, ib = set(a["imports"]), set(b["imports"])
5959
- jac = (len(ia & ib) / len(ia | ib)) if (ia or ib) else 1.0
5960
- dloc = abs(a["loc"] - b["loc"]) / max(a["loc"], b["loc"], 1)
5961
- dast = abs(a["ast_nodes"] - b["ast_nodes"]) / max(a["ast_nodes"], b["ast_nodes"], 1)
5962
- dists.append((dloc + dast + (1.0 - jac)) / 3.0)
6176
+ dists.append(_struct_distance(good[i], good[j]))
5963
6177
  rec["variance_score"] = round(sum(dists) / len(dists), 4) if dists else None
5964
6178
  return rec, []
5965
6179
 
5966
6180
 
6181
+ def _struct_distance(a, b):
6182
+ """The ONE structural distance the program uses between two implementations -- mean of
6183
+ normalized LOC delta, AST-node delta and import-set Jaccard distance (0 = identical). Shared
6184
+ by the inter-compiler variance (lang-compare, bench) and the intra-model variance (bench-r2,
6185
+ ADR-027) so their ratio is commensurable: same function, both sides."""
6186
+ ia, ib = set(a["imports"]), set(b["imports"])
6187
+ jac = (len(ia & ib) / len(ia | ib)) if (ia or ib) else 1.0
6188
+ dloc = abs(a["loc"] - b["loc"]) / max(a["loc"], b["loc"], 1)
6189
+ dast = abs(a["ast_nodes"] - b["ast_nodes"]) / max(a["ast_nodes"], b["ast_nodes"], 1)
6190
+ return (dloc + dast + (1.0 - jac)) / 3.0
6191
+
6192
+
5967
6193
  def _oracle_hash(arm_dir):
5968
6194
  try:
5969
6195
  with open(os.path.join(arm_dir, "oracle", "ORACLE.json"), "rb") as fh:
@@ -6093,7 +6319,9 @@ def _render_lang_md(r):
6093
6319
  "arm's low variance was convergence on a shared reading (right or "
6094
6320
  "wrong): two compilers resolving the same ambiguity the same way read "
6095
6321
  "as agreement, and a rewrite that separates them raises variance "
6096
- "while moving behaviour."
6322
+ "while moving behaviour. Read any variance number here against the "
6323
+ "entry's intra-model noise floor (bench-r2, ADR-027): an inter-compiler "
6324
+ "distance below that floor is not evidence of convergence."
6097
6325
  % r.get("passrate_margin", 0.02)}[r["verdict"]],
6098
6326
  "", "*The oracle is byte-identical across both arms, so behaviour is held fixed; "
6099
6327
  "the only variable is the authoring discipline. The judgement of \"same semantic "
@@ -10246,6 +10474,17 @@ def build_parser():
10246
10474
  "(read-only), including stale verdicts whose obs no longer exists")
10247
10475
  pbc.set_defaults(func=cmd_bench_curate)
10248
10476
 
10477
+ pbr = sub.add_parser(
10478
+ "bench-r2",
10479
+ help="intra-model variance (ADR-027): for every bench entry with an r2/ second run of "
10480
+ "the same models, the run1-vs-run2 structural distance via the SAME function the "
10481
+ "bench uses between compilers, oracle stability, and a per-entry SIGNAL/NOISY/NOISE "
10482
+ "class; the noise floor under every variance claim; advisory, deterministic, no LLM")
10483
+ pbr.add_argument("--dir", required=True, help="the bench directory")
10484
+ pbr.add_argument("--out", default=None, help="write DIAMOND-BENCH-R2.md here")
10485
+ pbr.add_argument("--json", action="store_true")
10486
+ pbr.set_defaults(func=cmd_bench_r2)
10487
+
10249
10488
  plc = sub.add_parser(
10250
10489
  "lang-compare",
10251
10490
  help="controlled-language arm (ADR-019): compare a FREE-prose arm and an EARS+STE arm of "
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.83.0",
2
+ "version": "1.84.0",
3
3
  "project": null,
4
4
  "defaults": {
5
5
  "coverage_threshold": 60,