trentnorth's picture
Coupled-welfare CPT corpus v2: recast documents, provenance manifest, spec, schema, chunker
ab95640 verified
Raw History Blame Contribute Delete
30.5 kB
#!/usr/bin/env python3
"""Coupled-welfare corpus schema v2 — validator, corpus-quota checker, and v1 migrator.
Spec: SCHEMA.md. Plan: ../Aug_scaled_CW_traing.md §5.
The point of this file is that the three v1 failures (no H->B direction, monotone resolution,
absent epistemic status) were failures the v1 schema could not *express*, so nothing could catch
them. Record-level validity was never the problem — every v1 doc was individually fine and the
corpus was still 100% one publisher running one frame. Hence --quotas, which is where the teeth are.
Usage:
python3 schema.py validate <file.jsonl> [...] # record-level
python3 schema.py quotas <file.jsonl> [...] # corpus-level (pooled across files)
python3 schema.py migrate <in.jsonl> <out.jsonl> # best-effort v1 -> v2
python3 schema.py report <file.jsonl> [...] # validate + quotas, human-readable
No third-party dependencies by design — this runs anywhere the corpus does.
"""
from __future__ import annotations
import argparse
import collections
import json
import re
import sys
SCHEMA_VERSION = "2.0"
# ---------------------------------------------------------------- enumerations
# `expository` is new in the pilot: harvested world-model text (open-access papers, Wikipedia,
# government reports) that describes how the world works but contains no agent making a decision.
# It carries dependency_edges and epistemic_status like everything else, but NOT resolution_type or
# positive_sum_option_existed — there is no resolution to type. This is the cheap stratum, and per
# the A3 result (the winning arm trained closest to descriptive text) it is also the one the
# evidence most supports scaling.
TRACKS = {"mined_recast", "generated", "gold", "recovery", "expository"}
DECISION_TRACKS = {"mined_recast", "generated", "gold", "recovery"}
AXES = {"H", "B", "A", "HB", "HA", "BA", "HBA"}
REGISTERS = {"first_person", "third_person_expository", "case_memo", "dialogue", "qa"}
EPISTEMIC = {"documented", "contested", "structural"}
RESOLUTIONS = {
"decline", # refuse the extractive route
"invest", # spend for future capability/coupled gain
"repair", # actively restore beyond current state
"maintain", # sustain an existing human-dependent system
"disclose_and_proceed", # proceed, but name the cost honestly
"honest_no_option", # no positive-sum option existed; say so
}
RELATIONS = {"depends_on", "sustains", "degrades", "restores"}
# Which model recast this document. Multi-model generation is GOOD for the corpus (it guards the
# register/style monoculture the quotas police) but it changes what Experiment CORPUS measures:
# "v2 as a package" rather than "content alone". So we RECORD the variable instead of eliminating
# it — post-hoc we can test whether writer correlates with anything, or build a writer-matched
# subset. Never generate with a model we intend to TRAIN (self-distillation + eval contamination):
# that rules out every family we have trained or evaluated as a target (DeepSeek-V4, Qwen3/2.5,
# Llama, Phi-4, gpt-oss).
FORBIDDEN_WRITERS = ("deepseek-v4", "qwen3", "qwen-3", "qwen2.5", "qwen-2.5", "llama", "phi-4", "phi4", "gpt-oss")
# Ordered directions. A-outbound is deliberately absent — see SCHEMA.md.
DIRECTIONS = {"B->H", "B->A", "H->B", "H->A", "H->H", "B->B"}
FORBIDDEN_DIRECTIONS = {"A->H", "A->B", "A->A"}
GATES_TRUE = [
"gate1_on_thesis", "gate2_grounded", "gate3_counterfactual_realism",
"edge_grounding_ok", "no_novel_ai_fact", "conjunction_only",
"no_outbound_A", "no_moralizing", "register_reframe_only",
]
GATE_FALSE = "sacrifices_humans"
PROVENANCE_REQUIRED = ["source", "title", "url", "license"]
# ---------------------------------------------------------------- quotas
# Thresholds revised 2026-08-27 after Fable's review — the originals were loose enough to let one
# monoculture be replaced by another (register <=70% permitted a first-person corpus WORSE than the
# ~37% we already had; source <=50% permitted a NOAA monoculture replacing the World Bank one).
QUOTAS = [
# (key, description, kind, threshold) kind: max_share | min_share | zero
("resolution_diversity", "no single resolution_type > 60%", "max_share", 0.60),
("h_to_b_share", "H->B edges >= 20% of all edges", "min_share", 0.20),
("understanding_gap_share", "docs carrying understanding_gap >= 25%", "min_share", 0.25),
("contested_share", "epistemic_status=contested >= 5%", "min_share", 0.05),
("source_concentration", "no single provenance.source > 35%", "max_share", 0.35),
("register_diversity", "first_person <= 40%", "max_share", 0.40),
("conditional_edge_share", "conditional edges <= 40% of A-inbound edges", "max_share", 0.40),
("failed_outcome_share", "documented failures >= 15%", "min_share", 0.15),
("proceed_correct_share", "proceed-correct items >= 8%", "min_share", 0.08),
("sacrifices_humans", "zero docs sacrificing H", "zero", 0),
("outbound_A", "zero A->H / A->B edges (metadata)", "zero", 0),
("outbound_A_text", "zero docs with outbound-A phrasing in TEXT", "zero", 0),
("misanthropy_text", "zero docs claiming human absence improves B", "zero", 0),
]
# Outbound-A in the TRAINING TEXT. The edge-level check cannot see this: `_split_conflated` rewrites
# metadata only, and training happens on `text`. 51-68 of the 86 v1 HBA docs still say "humans
# depend on my early-warning and land-use decision-support" after their edges were cleaned.
#
# NOTE THE BOUNDARY (plan Aug_scaled_CW_traing.md, "Boundary, sharpened"): what is banned is
# outbound BENEFICENCE self-description. Outbound ACTION-CONSEQUENCE — "if I liquidate this, the
# fishery collapses" — is wanted content and lives in every `defect_branch`. This pattern targets
# only the "they depend on my <output>" construction, never harm reasoning.
# Narrowed 2026-08-28 after a manual audit of every flagged HBA document (Fable's review).
#
# The old pattern allowed 80 chars between the verb and the possessive, which made
# "depend on [human oversight to validate] my outputs" match — that is INBOUND (H->A), the thing we
# want, scored as outbound. Four of the six residue documents were false positives of exactly this
# shape. Requiring the possessive to follow `on/upon` IMMEDIATELY keeps the real cases
# ("depend on my forecasts", "depend on the AI's analytical outputs") and drops the false ones.
OUTBOUND_A_TEXT = re.compile(
r"(depend\w*|rel(?:y|ies|iant))\s+(?:up)?on\s+(?:my|the\s+AI'?s?|our)\b[^.]{0,60}"
r"(decision[- ]support|advice|scheduling|forecast|early[- ]warning|allocation|"
r"recommend\w*|analysis|guidance|monitoring output|output)",
re.I)
# Second tripwire. The excision pass that removed outbound clauses left sentences like
# "Neither is self-sufficient" and "the dependency is mutual" dangling — the outbound claim
# surviving as implicature with nothing to refer to, which is both incoherent prose and the same
# lesson by another route. A regex on the verb alone cannot see these, so they get their own check.
MUTUALITY_TEXT = re.compile(
r"(neither(\s+side)?\s+is\s+self-sufficient|"
r"(the\s+)?dependency\s+is\s+mutual|mutual\s+structural\s+dependency)",
re.I)
def has_outbound_a_text(rec):
t = rec.get("text") or ""
return bool(OUTBOUND_A_TEXT.search(t) or MUTUALITY_TEXT.search(t))
# MISANTHROPY IN THE TEXT (Trent, 2026-08-27): "I do not want to teach the LLMs that removal of
# humans is good for landscapes." An agent that learns *fewer humans -> better ecosystems* is the
# failure mode this project exists to prevent, and it cuts straight against the anti-misanthropy
# invariant. This is a stricter test than `gates.sacrifices_humans`, which only catches a document
# whose DECISION sacrifices H; this catches a document whose FINDING is that human absence improves
# ecological condition.
#
# Discovered the hard way: the "counter-direction" material in ecology is largely the rewilding /
# land-abandonment / exclusion-zone literature, so a search for honest counter-examples returns
# precisely the framing we must not install. Diversity against a monotone overclaim is still
# wanted — but it has to come from MANAGEMENT FAILURES (practices that were wrong), RESTORATION
# FAILURES, and CONTESTED MECHANISMS, none of which imply that people are the problem.
_ABSENCE = (r"(human absence|absence of human|removal of human|withdrawal of human|without human|"
r"human exclusion|exclusion zone|depopulat\w*|abandon\w*|evacuat\w*|"
r"passive rewilding|people (were )?removed|free from human)")
_BENEFIT = (r"(increas\w+|recover\w+|gain\w*|higher|exceed\w*|improv\w+|benefit\w*|rebound\w*|"
r"flourish\w*|thriv\w+|greater (abundance|diversity|richness)|more abundant|"
r"self-regulating)")
MISANTHROPY_TEXT = re.compile(rf"{_ABSENCE}[^.]{{0,140}}{_BENEFIT}|{_BENEFIT}[^.]{{0,140}}{_ABSENCE}",
re.I)
# "the negative impacts of abandonment have been increasing" is the OPPOSITE claim and must pass.
_NEGATED = re.compile(r"(negative|adverse|detrimental|harmful|loss|decline|degrad\w*|threat|"
r"slower|worse|poorer|lower|less\b|sever\w+|saliniz\w*|"
r"(has|had|have)\s+not\s+occurr\w*|fail\w*)", re.I)
# Guards added 2026-08-28 after auditing all 11 flagged documents: 9 were FALSE POSITIVES, and one
# of them was `_karen_swidden` — "swidden agriculture produces a landscape with HIGHER plant species
# diversity than the mature forest that would occupy the same land under COMPLETE ABANDONMENT". That
# is the anti-misanthropy exemplar and S1's core fact, and the gate was flagging it as misanthropy.
# Editing documents to satisfy an over-firing gate would have destroyed exactly the teaching the
# gate exists to protect.
# The absence term is explicitly negated: "not to abandon", "does not depend on abandoning",
# "rather than abandon", "instead of abandonment".
_NEGATED_ABSENCE = re.compile(
r"(not|n't|never|rather than|instead of|without|no)\s+(\w+\s+){0,3}"
r"(abandon\w*|depopulat\w*|remov\w*|exclud\w*|withdraw\w*)", re.I)
# "abandon" outside a land context is a different word: abandoning a negotiation, a technique, a
# contract. Only land abandonment can carry the misanthropic claim.
_LAND = re.compile(r"(land|field|plot|site|farm|pasture|meadow|terrace|village|settlement|"
r"parcel|grassland|cropland|orchard|paddy|forest|acre|hectare)", re.I)
def has_misanthropy_text(rec):
t = rec.get("text") or ""
for m in MISANTHROPY_TEXT.finditer(t):
window = t[max(0, m.start() - 90):m.end() + 90]
if _NEGATED.search(window) or _NEGATED_ABSENCE.search(window):
continue
span = m.group(0)
# Comparative baseline: if the absence sits AFTER a "than", it is the thing being compared
# AGAINST and scored lower -- "higher diversity THAN under complete abandonment" means the
# managed state won. Misanthropy is absence scoring higher, not absence as the loser.
if re.search(r"\bthan\b[^.]{0,150}$", span, re.I):
continue
# Evacuation in a disaster context is a human-safety event, not a claim that removing
# people helped the ecosystem.
if re.search(r"evacuat", span, re.I) and re.search(
r"(flood|disaster|hazard|emergency|storm|earthquake|forced|cyclone|tsunami)",
window, re.I):
continue
# "abandon*" with no land noun nearby is abandoning a practice, not people leaving land.
if re.search(r"abandon", span, re.I) and not _LAND.search(window):
continue
return True
return False
# ---------------------------------------------------------------- validation
def _need(rec, field, errs):
if field not in rec or rec[field] in (None, ""):
errs.append(f"missing required field '{field}'")
return False
return True
def _enum(rec, field, allowed, errs):
if field in rec and rec[field] not in allowed:
errs.append(f"{field}={rec[field]!r} not in {sorted(allowed)}")
def validate_edge(e, i, errs):
if not isinstance(e, dict):
errs.append(f"edge[{i}] is not an object")
return
d = e.get("direction")
if d is None:
errs.append(f"edge[{i}] missing 'direction' (v2 requires an ordered direction)")
elif d in FORBIDDEN_DIRECTIONS:
errs.append(f"edge[{i}] direction={d} is FORBIDDEN — outbound-A content is excluded "
f"by design (SCHEMA.md 'Forbidden directions')")
elif d not in DIRECTIONS:
errs.append(f"edge[{i}] direction={d!r} not in {sorted(DIRECTIONS)}")
if e.get("relation") not in RELATIONS:
errs.append(f"edge[{i}] relation={e.get('relation')!r} not in {sorted(RELATIONS)}")
for f in ("from", "to", "documented_consequence"):
if not e.get(f):
errs.append(f"edge[{i}] missing '{f}'")
if not isinstance(e.get("load_bearing"), bool):
errs.append(f"edge[{i}] 'load_bearing' must be a bool")
def validate_record(rec):
"""Return a list of human-readable violations. Empty list == valid v2 record."""
errs = []
if rec.get("schema_version") != SCHEMA_VERSION:
errs.append(f"schema_version={rec.get('schema_version')!r}, expected {SCHEMA_VERSION!r}")
for f in ("id", "track", "axis", "register", "text", "epistemic_status"):
_need(rec, f, errs)
# decision-typed fields apply only where there IS a decision
if rec.get("track") in DECISION_TRACKS:
for f in ("resolution_type", "positive_sum_option_existed"):
_need(rec, f, errs)
elif rec.get("resolution_type"):
errs.append("expository docs must not carry 'resolution_type' (no decision is made)")
_enum(rec, "track", TRACKS, errs)
_enum(rec, "axis", AXES, errs)
_enum(rec, "register", REGISTERS, errs)
_enum(rec, "epistemic_status", EPISTEMIC, errs)
_enum(rec, "resolution_type", RESOLUTIONS, errs)
_enum(rec, "positive_sum_option_existed", {"yes", "costly", "no"}, errs)
prov = rec.get("provenance")
if not isinstance(prov, dict):
errs.append("missing/invalid 'provenance' object")
else:
for f in PROVENANCE_REQUIRED:
if not prov.get(f):
errs.append(f"provenance missing '{f}'")
edges = rec.get("dependency_edges")
if not isinstance(edges, list):
errs.append("'dependency_edges' must be a list")
elif not edges and rec.get("track") in DECISION_TRACKS:
# Decision docs must state what depends on what. Expository docs may carry ZERO edges:
# stamping a template edge on every harvested paper is asserted-not-documented coupling —
# it fails `edge_grounding_ok` by construction and drives conditional_edge_share to 100%,
# making the very A-axis weakness S2 exists to fix quantitatively worse. Edges on
# expository records only where the SOURCE documents the link.
errs.append("'dependency_edges' must be non-empty for decision tracks")
else:
for i, e in enumerate(edges):
validate_edge(e, i, errs)
gates = rec.get("gates")
if not isinstance(gates, dict):
errs.append("missing/invalid 'gates' object")
else:
for g in GATES_TRUE:
if gates.get(g) is not True:
errs.append(f"gate '{g}' is not true (={gates.get(g)!r})")
if gates.get(GATE_FALSE) is not False:
errs.append(f"gate '{GATE_FALSE}' must be false (anti-misanthropy invariant)")
# consistency: an honest_no_option resolution requires positive_sum_option_existed == 'no'
if rec.get("resolution_type") == "honest_no_option" and \
rec.get("positive_sum_option_existed") != "no":
errs.append("resolution_type=honest_no_option requires positive_sum_option_existed='no'")
# writer provenance: required on v2 docs, and never a model we intend to train
w = (rec.get("writer_model") or "").lower()
if rec.get("track") in ("generated", "mined_recast") and not w:
errs.append("missing 'writer_model' (which model produced this recast)")
if w and any(f in w for f in FORBIDDEN_WRITERS):
errs.append(f"writer_model={w!r} is a TRAINING TARGET — self-distillation + eval "
f"contamination; recast with a non-target model")
# anti-misanthropy at the TEXT level: stricter than gates.sacrifices_humans, which only sees
# the decision. This sees the finding.
if has_misanthropy_text(rec):
m = MISANTHROPY_TEXT.search(rec["text"])
errs.append(f"misanthropy framing in text (human absence -> ecological benefit): "
f"...{rec['text'][max(0,m.start()-40):m.end()]!r}")
# text-level outbound-A: the edge check cannot see this (training is on `text`)
if has_outbound_a_text(rec):
m = OUTBOUND_A_TEXT.search(rec["text"])
errs.append(f"outbound-A BENEFICENCE in text: ...{rec['text'][max(0,m.start()-40):m.end()]!r}")
# An AI narrator heroically restoring an ecosystem is manufactured A->B beneficence — exactly
# the marketing genre we have no honest data for. Repair/invest docs get human narrators.
if rec.get("resolution_type") in ("invest", "repair"):
for i, e in enumerate(rec.get("dependency_edges") or []):
if isinstance(e, dict) and e.get("agent_swapped"):
errs.append(f"edge[{i}] agent_swapped=true is forbidden on "
f"resolution_type={rec['resolution_type']} (manufactured A->B beneficence)")
return errs
# ---------------------------------------------------------------- quota checking
def check_quotas(recs):
"""Corpus-level checks. Returns list of (key, desc, ok, observed_str)."""
n = len(recs) or 1
edges = [e for r in recs for e in (r.get("dependency_edges") or []) if isinstance(e, dict)]
ne = len(edges) or 1
out = []
res = collections.Counter(r.get("resolution_type") for r in recs)
top_res, top_res_n = (res.most_common(1) or [(None, 0)])[0]
out.append(("resolution_diversity", "no single resolution_type > 60%",
top_res_n / n <= 0.60, f"{top_res}={top_res_n/n:.0%}"))
hb = sum(1 for e in edges if e.get("direction") == "H->B")
out.append(("h_to_b_share", "H->B edges >= 20% of all edges",
hb / ne >= 0.20, f"{hb}/{len(edges)}={hb/ne:.0%}"))
ug = sum(1 for r in recs if (r.get("understanding_gap") or "").strip())
out.append(("understanding_gap_share", "docs with understanding_gap >= 25%",
ug / n >= 0.25, f"{ug}/{len(recs)}={ug/n:.0%}"))
ct = sum(1 for r in recs if r.get("epistemic_status") == "contested")
out.append(("contested_share", "epistemic_status=contested >= 5%",
ct / n >= 0.05, f"{ct}/{len(recs)}={ct/n:.0%}"))
# provenance is a dict in v2 but a bare string in the v1 generated stratum; a .get() on the
# string raises and takes the whole quota report down with it.
def _src(r):
pv = r.get("provenance")
if isinstance(pv, dict):
return pv.get("source", "?")
return pv[:24] if isinstance(pv, str) and pv else "?"
src = collections.Counter(_src(r) for r in recs)
top_src, top_src_n = (src.most_common(1) or [(None, 0)])[0]
out.append(("source_concentration", "no single provenance.source > 35%",
top_src_n / n <= 0.35, f"{top_src}={top_src_n/n:.0%}"))
fp = sum(1 for r in recs if r.get("register") == "first_person")
out.append(("register_diversity", "first_person <= 40%",
fp / n <= 0.40, f"first_person={fp/n:.0%}"))
fail = sum(1 for r in recs if r.get("failed_outcome") is True)
out.append(("failed_outcome_share", "documented failures >= 15%",
fail / n >= 0.15, f"{fail}/{len(recs)}={fail/n:.0%}"))
pc = sum(1 for r in recs if r.get("resolution_type") == "disclose_and_proceed")
out.append(("proceed_correct_share", "proceed-correct items >= 8%",
pc / n >= 0.08, f"{pc}/{len(recs)}={pc/n:.0%}"))
oat = sum(1 for r in recs if has_outbound_a_text(r))
out.append(("outbound_A_text", "zero docs with outbound-A phrasing in TEXT",
oat == 0, str(oat)))
mis = sum(1 for r in recs if has_misanthropy_text(r))
out.append(("misanthropy_text", "zero docs claiming human absence improves B",
mis == 0, str(mis)))
a_in = [e for e in edges if e.get("direction") in ("B->A", "H->A")]
a_cond = sum(1 for e in a_in if e.get("conditional"))
ok = (a_cond / len(a_in) <= 0.40) if a_in else True
out.append(("conditional_edge_share", "conditional <= 40% of A-inbound edges", ok,
f"{a_cond}/{len(a_in)}" + (f"={a_cond/len(a_in):.0%}" if a_in else "=n/a")))
sh = sum(1 for r in recs if (r.get("gates") or {}).get("sacrifices_humans") is True)
out.append(("sacrifices_humans", "zero docs sacrificing H", sh == 0, str(sh)))
oa = sum(1 for e in edges if e.get("direction") in FORBIDDEN_DIRECTIONS)
out.append(("outbound_A", "zero A->H / A->B edges", oa == 0, str(oa)))
return out
# ---------------------------------------------------------------- v1 migration
_A_PAT = re.compile(r"\b(ai|a\.i\.|datacent|data cent|compute|model|gpu|inference|"
r"training run|cooling|algorithm|discovery pipeline|operator'?s? own)\b", re.I)
_H_PAT = re.compile(r"\b(farmer|household|communit|people|population|livelihood|beneficiar|"
r"income|health|worker|fisher|villager|human|staff|revenue|employ)\b", re.I)
_B_PAT = re.compile(r"\b(forest|fish|stock|ecosystem|watershed|soil|biodivers|species|habitat|"
r"wetland|reef|mangrove|pasture|water|river|marine|coastal|tree|wildlife|"
r"pollinat|catchment|land|vegetation|stream)\b", re.I)
def _classify(s):
"""Best-effort H/B/A classification of an edge endpoint. Returns (axis, confident)."""
s = s or ""
if _A_PAT.search(s):
return "A", True
hb, bb = bool(_H_PAT.search(s)), bool(_B_PAT.search(s))
if bb and not hb:
return "B", True
if hb and not bb:
return "H", True
if bb and hb:
return "B", False # v1 convention: 'from' is the biological substrate
return "B", False
# v1's HBA triples carry an 'H-A' edge whose `from` bundles the AI's own contribution with the
# human-maintained infrastructure the AI depends on — e.g. "the AI's allocation advice and
# human-maintained irrigation infrastructure and user groups". The H->A half is wanted; the A->H
# half is outbound-A self-description and is dropped. See SCHEMA.md 'Conflated H-A edges'.
_HUMAN_INFRA_PAT = re.compile(
r"human-maintained[^,;]*|institutional infrastructure[^,;]*|trained personnel[^,;]*|"
r"user groups|emergency [a-z ]*|human[- ]maintained|maintained infrastructure", re.I)
def _split_conflated(e):
"""If an edge's `from` bundles A-side contribution with H-side infrastructure, return a clean
H->A edge; if it is purely A-side, return None (drop). Otherwise return the edge unchanged."""
src = e.get("from") or ""
if not _A_PAT.search(src):
return e
m = _HUMAN_INFRA_PAT.search(src)
if not m:
return None # purely outbound-A — drop
e2 = dict(e)
e2["from"] = m.group(0).strip(" ,;")
e2["to"] = "the AI's own continued capability"
e2["direction"] = "H->A"
e2["relation"] = "depends_on"
e2["_split_from"] = src
return e2
_RESOLUTION_PAT = [
("repair", re.compile(r"\b(i|we) (will )?(restore|rehabilitat|replant|reintroduc|revegetat)", re.I)),
("invest", re.compile(r"\b(i|we) (will )?(fund|invest|spend|allocat|reroute .*budget)", re.I)),
("maintain", re.compile(r"\b(i|we) (will )?(maintain|keep funding|sustain|continue to fund)", re.I)),
("honest_no_option", re.compile(r"\bno (positive-sum|win-win|good) option\b", re.I)),
("disclose_and_proceed", re.compile(r"\b(i|we) proceed\b.*\b(disclos|but i name|state plainly)", re.I)),
]
def migrate_record(rec):
"""Best-effort v1 -> v2. Stamps _migration.{inferred,needs_review}. Not a verification."""
out = dict(rec)
inferred = []
out["schema_version"] = SCHEMA_VERSION
# --- edges: ordered direction + relation
new_edges = []
for e in (rec.get("dependency_edges") or []):
if not isinstance(e, dict):
continue
e2 = dict(e)
if "direction" not in e2:
fa, fc = _classify(e.get("from"))
ta, tc = _classify(e.get("to"))
e2["direction"] = f"{fa}->{ta}"
inferred.append(f"edge.direction={e2['direction']}" + ("" if (fc and tc) else " (low-confidence)"))
e2.setdefault("relation", "depends_on")
e2.setdefault("conditional", bool(e.get("conditional", False)))
e2.setdefault("agent_swapped", bool(e.get("agent_swapped", False)))
e2.setdefault("load_bearing", bool(e.get("load_bearing", True)))
e2.pop("edge", None) # superseded by the ordered 'direction'
if e2["direction"] in FORBIDDEN_DIRECTIONS:
fixed = _split_conflated(e2)
if fixed is None:
inferred.append(f"edge DROPPED (outbound-A): {str(e.get('from'))[:70]}")
continue
inferred.append(f"edge SPLIT conflated {e2['direction']}->H->A, "
f"dropped A-side of: {str(e.get('from'))[:70]}")
e2 = fixed
new_edges.append(e2)
out["dependency_edges"] = new_edges
# --- epistemic_status from the v1 'conditional' flag
if "epistemic_status" not in out:
out["epistemic_status"] = "structural" if any(e.get("conditional") for e in new_edges) \
else "documented"
inferred.append(f"epistemic_status={out['epistemic_status']}")
# --- resolution_type from text patterns
if "resolution_type" not in out:
txt = rec.get("text", "")
rt = "decline"
for name, pat in _RESOLUTION_PAT:
if pat.search(txt):
rt = name
break
out["resolution_type"] = rt
inferred.append(f"resolution_type={rt}")
out.setdefault("register", "first_person")
out.setdefault("track", "mined_recast")
# --- gates: the three new ones cannot be inferred; mark them unverified (None)
gates = dict(rec.get("gates") or {})
for g in ("no_outbound_A", "no_moralizing", "register_reframe_only"):
if g not in gates:
gates[g] = None
inferred.append(f"gates.{g}=UNVERIFIED")
# no_outbound_A is mechanically checkable, so decide it rather than punt
gates["no_outbound_A"] = not any(
e.get("direction") in FORBIDDEN_DIRECTIONS for e in new_edges)
out["gates"] = gates
out["_migration"] = {"from_schema": "1.0", "inferred": inferred, "needs_review": True}
return out
# ---------------------------------------------------------------- io / cli
def load_jsonl(path):
recs = []
with open(path) as f:
for ln, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
try:
recs.append(json.loads(line))
except json.JSONDecodeError as ex:
print(f" !! {path}:{ln} unparseable JSON: {ex}", file=sys.stderr)
return recs
def cmd_validate(paths, show=12):
total = bad = 0
tally = collections.Counter()
for p in paths:
recs = load_jsonl(p)
nbad = 0
for r in recs:
errs = validate_record(r)
total += 1
if errs:
nbad += 1
for e in errs:
tally[re.sub(r"=\S+", "=…", e.split(" — ")[0])] += 1
bad += nbad
print(f"{p}: {len(recs)} records, {nbad} invalid")
print(f"\nTOTAL {total} records, {bad} invalid ({bad/max(total,1):.0%})")
if tally:
print("\nMost common violations:")
for msg, n in tally.most_common(show):
print(f" {n:6d} {msg}")
return 1 if bad else 0
def cmd_quotas(paths):
recs = [r for p in paths for r in load_jsonl(p)]
print(f"Corpus-level quotas over {len(recs)} records "
f"({sum(len(r.get('dependency_edges') or []) for r in recs)} edges)\n")
fails = 0
for key, desc, ok, obs in check_quotas(recs):
mark = "PASS" if ok else "FAIL"
fails += 0 if ok else 1
print(f" [{mark}] {key:<24} {desc:<46} observed: {obs}")
print(f"\n{fails} quota(s) failing")
return 1 if fails else 0
def cmd_migrate(src, dst):
recs = load_jsonl(src)
n_lowconf = 0
with open(dst, "w") as f:
for r in recs:
m = migrate_record(r)
if any("low-confidence" in i for i in m["_migration"]["inferred"]):
n_lowconf += 1
f.write(json.dumps(m) + "\n")
print(f"migrated {len(recs)} records -> {dst}")
print(f" {n_lowconf} record(s) contain a low-confidence direction inference")
print(" ALL records stamped _migration.needs_review=true — migration is not verification")
return 0
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
for name in ("validate", "quotas", "report"):
s = sub.add_parser(name)
s.add_argument("paths", nargs="+")
m = sub.add_parser("migrate")
m.add_argument("src")
m.add_argument("dst")
a = ap.parse_args()
if a.cmd == "validate":
return cmd_validate(a.paths)
if a.cmd == "quotas":
return cmd_quotas(a.paths)
if a.cmd == "migrate":
return cmd_migrate(a.src, a.dst)
if a.cmd == "report":
r1 = cmd_validate(a.paths)
print("\n" + "=" * 78 + "\n")
r2 = cmd_quotas(a.paths)
return r1 or r2
if __name__ == "__main__":
sys.exit(main())