Skip to content

zrwangems/dsh-zrwang-plugin / ars/skills/sr-screener

sr-screener

Flagged

系统综述文献筛选:把方案或 PROSPERO 协议转成资格规则,双盲筛选标题摘要与全文,第三人裁决冲突,输出 PRISMA 2020 计数、EndNote/Zotero RIS 分组与可交付给论文技能的 literature_corpus。Triggers: systematic review screening, screen papers, PRISMA counts, pilot screening, adjudicate conflicts | 文献筛选, 系统综述筛选, PRISMA 计数, 筛选冲突裁决。

FileKindSize
SKILL.mdskill md33.1 KB
_shared/ARCHITECTURE.mdmarkdown51.7 KB
_shared/MODE_REGISTRY.mdmarkdown6.7 KB
_shared/agents/compliance_agent.mdmarkdown9.4 KB
_shared/artifact_reproducibility_pattern.mdmarkdown9.8 KB
_shared/benchmark_report.schema.jsonconfig2.7 KB
_shared/benchmark_report_pattern.mdmarkdown8.8 KB
_shared/bibliographic_integrity_signals.mdmarkdown8.1 KB
_shared/collaboration_depth_rubric.mdmarkdown11.5 KB
_shared/compliance_checkpoint_protocol.mdmarkdown8.9 KB
_shared/compliance_report.schema.jsonconfig8.1 KB
_shared/contracts/README.mdmarkdown54.7 KB
_shared/contracts/activity/adjudication_activity_input.schema.jsonconfig18.5 KB
_shared/contracts/activity/adjudication_activity_store.schema.jsonconfig18.7 KB
_shared/contracts/audit/audit_jsonl.schema.jsonconfig5.4 KB
_shared/contracts/audit/audit_sidecar.schema.jsonconfig8.4 KB
_shared/contracts/audit/audit_verdict.schema.jsonconfig5.4 KB
_shared/contracts/audit/cross_document_consistency_advisory.schema.jsonconfig20.4 KB
_shared/contracts/audit/cross_document_consistency_advisory_draft.schema.jsonconfig23.4 KB
_shared/contracts/audit/cross_document_source_manifest.schema.jsonconfig6.3 KB
_shared/contracts/audit/tortured_phrase_advisory.schema.jsonconfig30.9 KB
_shared/contracts/audit/tortured_phrase_snapshot.schema.jsonconfig4.9 KB
_shared/contracts/audit/tortured_phrase_snapshot_manifest.schema.jsonconfig7.3 KB
_shared/contracts/capability/stage_capability_matrix.jsonconfig23.5 KB
_shared/contracts/claim_standing/candidate_ledger.schema.jsonconfig23.1 KB
_shared/contracts/claim_standing/query_plan.schema.jsonconfig12.7 KB
_shared/contracts/claim_standing/query_plan_v1_1.schema.jsonconfig20.3 KB
_shared/contracts/claim_standing/retrieval_input.schema.jsonconfig14.4 KB
_shared/contracts/claim_standing/stance_record.schema.jsonconfig11.7 KB
_shared/contracts/claim_standing/transmission_ledger.schema.jsonconfig7.6 KB
_shared/contracts/cross_model/codex_citation_receipt.schema.jsonconfig4.7 KB
_shared/contracts/cross_model/codex_citation_request.schema.jsonconfig986 B
_shared/contracts/cross_model/promotion_bakeoff_sealed_commitment.schema.jsonconfig1.5 KB
_shared/contracts/cross_model/promotion_bakeoff_sealed_reveal.schema.jsonconfig1.5 KB
_shared/contracts/degradation_registry.jsonconfig42.5 KB
_shared/contracts/evaluator/full.jsonconfig6.3 KB
_shared/contracts/evidence/claim_registry.schema.jsonconfig2.3 KB
_shared/contracts/evidence/claim_registry_coverage_report.schema.jsonconfig4.8 KB
_shared/contracts/evidence/evidence_row.schema.jsonconfig14.3 KB
_shared/contracts/evidence/evidence_row_v1_1.schema.jsonconfig11.4 KB
_shared/contracts/evidence/evidence_row_v1_2.schema.jsonconfig21.8 KB
_shared/contracts/evidence/evidence_row_v1_3.schema.jsonconfig10.7 KB
_shared/contracts/human_subjects/authority_profile_registry.schema.jsonconfig16.7 KB
_shared/contracts/human_subjects/committee_correspondence.schema.jsonconfig9.9 KB
_shared/contracts/human_subjects/content_coverage_advisory.schema.jsonconfig19.9 KB
_shared/contracts/human_subjects/irb_context_record.schema.jsonconfig12.1 KB
_shared/contracts/human_subjects/resolved_authority_context.schema.jsonconfig11.8 KB
_shared/contracts/human_subjects/review_pathway_rule_trace.schema.jsonconfig9.5 KB
_shared/contracts/human_subjects/review_pathway_trace_request.schema.jsonconfig4.8 KB
_shared/contracts/human_subjects/submission_packet_inventory.schema.jsonconfig8.5 KB
_shared/contracts/human_subjects/submission_packet_manifest.schema.jsonconfig32.2 KB
_shared/contracts/passport/audit_artifact_entry.schema.jsonconfig10.8 KB
_shared/contracts/passport/bibliographic_integrity_signal.schema.jsonconfig48.9 KB
_shared/contracts/passport/citation_provenance.schema.jsonconfig4.8 KB
_shared/contracts/passport/citation_verification_summary.schema.jsonconfig8.2 KB
_shared/contracts/passport/claim_audit_result.schema.jsonconfig7.8 KB
_shared/contracts/passport/claim_drift.schema.jsonconfig3.8 KB
_shared/contracts/passport/claim_intent_manifest.schema.jsonconfig6.6 KB
_shared/contracts/passport/constraint_violation.schema.jsonconfig3.6 KB
_shared/contracts/passport/excluded_source_entry.schema.jsonconfig1.7 KB
_shared/contracts/passport/experiment_alignment_result.schema.jsonconfig4.8 KB
_shared/contracts/passport/experiment_provenance_entry.schema.jsonconfig10.0 KB
_shared/contracts/passport/human_read_log.schema.jsonconfig3.8 KB
_shared/contracts/passport/inquiry_ledger_ref.schema.jsonconfig881 B
_shared/contracts/passport/literature_corpus_entry.schema.jsonconfig30.3 KB
_shared/contracts/passport/preregistration_artifact.schema.jsonconfig4.3 KB
_shared/contracts/passport/rejection_log.schema.jsonconfig3.3 KB
_shared/contracts/passport/reset_ledger_entry.schema.jsonconfig7.1 KB
_shared/contracts/passport/run_ledger.schema.jsonconfig8.0 KB
_shared/contracts/passport/standing_constraint_entry.schema.jsonconfig2.6 KB
_shared/contracts/passport/temporal_audit_results.schema.jsonconfig8.8 KB
_shared/contracts/passport/terminal_policies.schema.jsonconfig8.1 KB
_shared/contracts/passport/timeline.schema.jsonconfig4.7 KB
_shared/contracts/passport/uncited_assertion.schema.jsonconfig3.3 KB
_shared/contracts/passport/uncited_audit_failure.schema.jsonconfig4.4 KB
_shared/contracts/passport/user_attested_read_resolution.schema.jsonconfig3.2 KB
_shared/contracts/passport/version_records.schema.jsonconfig4.9 KB
_shared/contracts/patch/block_manifest.schema.jsonconfig2.1 KB
_shared/contracts/patch/legacy/v1_0/revision_patch.schema.jsonconfig5.3 KB
_shared/contracts/patch/revision_patch.schema.jsonconfig8.9 KB
_shared/contracts/pdf/pdf_content_classifier_diagnostic.schema.jsonconfig1.2 KB
_shared/contracts/pdf/pdf_content_classifier_worker.schema.jsonconfig2.2 KB
_shared/contracts/pdf/pdf_read_preflight.schema.jsonconfig6.8 KB
_shared/contracts/re_review/input_manifest.schema.jsonconfig7.6 KB
_shared/contracts/re_review/legacy/v1_0/input_manifest.schema.jsonconfig6.2 KB
_shared/contracts/re_review/legacy/v1_0/precommitment.schema.jsonconfig8.9 KB
_shared/contracts/re_review/legacy/v1_0/traceability.schema.jsonconfig34.2 KB
_shared/contracts/re_review/legacy/v1_0/verdict_record.schema.jsonconfig10.5 KB
_shared/contracts/re_review/precommitment.schema.jsonconfig8.6 KB
_shared/contracts/re_review/traceability.schema.jsonconfig37.7 KB
_shared/contracts/re_review/verdict_record.schema.jsonconfig10.5 KB
_shared/contracts/research_workflow/inquiry_branch_ledger.schema.jsonconfig17.0 KB
_shared/contracts/research_workflow/research_workflow_profile.schema.jsonconfig7.2 KB
_shared/contracts/research_workflow/research_workflow_profile_selection_receipt.schema.jsonconfig3.9 KB
_shared/contracts/review_target/constructive_review_findings.schema.jsonconfig7.0 KB
_shared/contracts/review_target/criteria_registry.schema.jsonconfig4.0 KB
_shared/contracts/review_target/review_criteria_binding_manifest.schema.jsonconfig7.9 KB
_shared/contracts/review_target/review_criteria_source_receipt.schema.jsonconfig5.6 KB
_shared/contracts/review_target/review_target_context.schema.jsonconfig4.5 KB
_shared/contracts/review_target/review_target_declaration.schema.jsonconfig4.6 KB
_shared/contracts/reviewer/full.jsonconfig3.7 KB
_shared/contracts/reviewer/methodology_focus.jsonconfig2.2 KB
_shared/contracts/reviewer/review_panel_provenance.schema.jsonconfig7.8 KB
_shared/contracts/reviewer/review_panel_provenance_carrier.schema.jsonconfig4.1 KB
_shared/contracts/reviewer/review_panel_provenance_input.schema.jsonconfig3.5 KB
_shared/contracts/revision/author_adjudication.schema.jsonconfig7.8 KB
_shared/contracts/revision/author_adjudication_input.schema.jsonconfig1.2 KB
_shared/contracts/revision/claim_strength_drift_disposition.schema.jsonconfig3.6 KB
_shared/contracts/revision/claim_strength_drift_disposition_input.schema.jsonconfig3.1 KB
_shared/contracts/revision/claim_strength_drift_findings.schema.jsonconfig4.2 KB
_shared/contracts/revision/claim_surface_manifest.schema.jsonconfig3.3 KB
_shared/contracts/revision/integrity_correction_authorization.schema.jsonconfig4.3 KB
_shared/contracts/revision/integrity_correction_authorization_input.schema.jsonconfig1.5 KB
_shared/contracts/revision/integrity_correction_list.schema.jsonconfig1.8 KB
_shared/contracts/revision/integrity_pass_receipt.schema.jsonconfig809 B
_shared/contracts/revision/revision_evidence_bundle.schema.jsonconfig4.9 KB
_shared/contracts/revision/revision_roadmap.schema.jsonconfig11.2 KB
_shared/contracts/submission/format_profile.example.yamlconfig971 B
_shared/contracts/submission/format_profile.schema.jsonconfig4.6 KB
_shared/contracts/submission/submission_verification_report.schema.jsonconfig10.3 KB
_shared/contracts/submission/venue_profile.schema.jsonconfig4.1 KB
_shared/contracts/writer/full.jsonconfig3.6 KB
_shared/cross_model_verification.mdmarkdown83.3 KB
_shared/description-original.mdmarkdown1.1 KB
_shared/dsh-runtime.mdmarkdown1.5 KB
_shared/evals_lift_report.schema.jsonconfig5.0 KB
_shared/ground_truth_isolation_pattern.mdmarkdown16.0 KB
_shared/handoff_schemas.mdmarkdown96.9 KB
_shared/human_subjects_authority_registry.jsonconfig49.5 KB
_shared/mode_spectrum.mdmarkdown5.2 KB
_shared/model_tiering.mdmarkdown12.6 KB
_shared/output_language_pair.mdmarkdown7.7 KB
_shared/policy_data/nature_policy.mdmarkdown3.9 KB
_shared/prisma_trAIce_protocol.mdmarkdown10.2 KB
_shared/raise_framework.mdmarkdown7.5 KB
_shared/references/authority_content_coverage_advisory_protocol.mdmarkdown14.0 KB
_shared/references/claim_standing_candidate_ledger_protocol.mdmarkdown19.2 KB
_shared/references/claim_strength_ladder.mdmarkdown5.5 KB
_shared/references/cross_document_consistency_advisory_protocol.mdmarkdown13.5 KB
_shared/references/evidence_row_protocol.mdmarkdown14.4 KB
_shared/references/firm_rules.mdmarkdown11.0 KB
_shared/references/human_subjects_authority_protocol.mdmarkdown13.1 KB
_shared/references/intent_clarification_protocol.mdmarkdown11.9 KB
_shared/references/irb_terminology_glossary.mdmarkdown12.4 KB
_shared/references/per_source_method_weaknesses.mdmarkdown4.2 KB
_shared/references/protected_hedging_phrases.mdmarkdown8.9 KB
_shared/references/psychometric_terminology_glossary.mdmarkdown8.7 KB
_shared/references/review_criteria_consumer_protocol.mdmarkdown10.3 KB
_shared/references/review_form_note.mdmarkdown11.3 KB
_shared/references/review_pathway_rule_trace_protocol.mdmarkdown8.3 KB
_shared/references/routing_core.mdmarkdown5.7 KB
_shared/references/submission_packet_manifest_protocol.mdmarkdown13.6 KB
_shared/references/word_count_conventions.mdmarkdown9.0 KB
_shared/research_workflow_profiles/field_general.jsonconfig1.2 KB
_shared/review_criteria_registry.jsonconfig11.5 KB
_shared/review_criteria_sources/msr-2027-technical-papers.2026-08-24.jsonconfig2.0 KB
_shared/review_criteria_sources/sigsoft-empirical-standards.2026-08-24.jsonconfig1.4 KB
_shared/sprint_contract.schema.jsonconfig19.0 KB
_shared/style_calibration_protocol.mdmarkdown6.9 KB
_shared/templates/codex_audit_multifile_template.mdmarkdown16.7 KB
agents/protocol_architect_agent.mdmarkdown6.4 KB
agents/qc_auditor_agent.mdmarkdown5.2 KB
agents/reporter_agent.mdmarkdown3.7 KB
agents/screening_reviewer_agent.mdmarkdown5.4 KB
examples/example_config_dta.jsonconfig1.8 KB
examples/example_protocol_dta.mdmarkdown3.8 KB
examples/quick_screen_example.mdmarkdown3.0 KB
references/decision_rules.mdmarkdown6.7 KB
references/failure_paths.mdmarkdown4.1 KB
references/orchestration.mdmarkdown12.4 KB
references/protocol_template.mdmarkdown6.2 KB
references/quality_control.mdmarkdown6.0 KB
references/reporting_and_handoff.mdmarkdown5.8 KB
references/reviewer_roles.mdmarkdown4.0 KB
scripts/_claim_audit_constants.pyscript13.7 KB
scripts/_markdown_lint_util.pyscript9.0 KB
scripts/_next_verified_at_ms.pyscript6.5 KB
scripts/_skill_lint.pyscript13.6 KB
scripts/ars_cache_invalidate.pyscript1.3 KB
scripts/ars_mark_read.pyscript18.2 KB
scripts/ars_write_scope_guard.pyscript30.9 KB
scripts/audit_snapshot.pyscript23.5 KB
scripts/bibliographic_integrity_signals.pyscript32.2 KB
scripts/build_claim_standing_candidate_ledger.pyscript54.3 KB
scripts/build_claim_standing_query_plan.pyscript25.0 KB
scripts/build_content_coverage_advisory.pyscript45.1 KB
scripts/build_cross_document_consistency_advisory.pyscript77.9 KB
scripts/build_outputs.pyscript33.0 KB
scripts/build_review_pathway_rule_trace.pyscript34.2 KB
scripts/build_submission_packet_manifest.pyscript88.1 KB
scripts/build_workflow.pyscript20.0 KB
scripts/check_audit_artifact_consistency.pyscript103.9 KB
scripts/check_benchmark_report.pyscript2.4 KB
scripts/check_claim_audit_consistency.pyscript68.9 KB
scripts/check_claim_standing_freshness.pyscript9.7 KB
scripts/check_claim_standing_transmissions.pyscript17.9 KB
scripts/check_committee_correspondence.pyscript14.9 KB
scripts/check_corpus_consumer_protocol.pyscript13.7 KB
scripts/check_cross_model_handoff_contract.pyscript9.9 KB
scripts/check_data_access_level.pyscript5.2 KB

scripts/check_claim_standing_transmissions.py

View on GitHub
#!/usr/bin/env python3
"""Transmission-ledger builder/validator for the #655 claim-standing probe.

Implements the design §6 transmission accounting and the §9 gate-14 check:
every authorized transmission attempt is recorded (recipient, purpose, exact
content classes, byte count, local hash, time, consent receipt, retention
disclosure, result state) and every event must stay inside the consented
content-class allowlist and recipient roster. Retrieval events derive from
the retained `claim-standing-retrieval-input/1.0` attempts (one transport
call per attempt); stance events are the runner's transmission records,
copied field-for-field. Accounting is conservative: an attempt an adapter
refused before transport (e.g. an unsupported query) still appears with its
failure result state, so the ledger may overstate, never understate, what
could have left the session; byte counts are of the consented content class
(the accepted query text / the exact prompt), not transport framing.

The builder is pure and deterministic: it adds no timestamp, performs no
network or model call, and fails closed on any unconsented recipient,
content class, receipt mismatch, off-plan query/index pair, duplicate
attempt, or stale input digest. A `retrieval_plus_stance` plan must supply
its stance transmissions explicitly (an empty list is an explicit assertion
that no stance call ran); passing the stance record cross-checks that every
row that reached the transport has its event. Partial pre-finalization
transmissions remain accountable through the same entry points.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

try:
    from scripts import build_claim_standing_candidate_ledger as substrate
except ImportError:  # direct script execution
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import build_claim_standing_candidate_ledger as substrate  # noqa: E402

LEDGER_VERSION = "claim-standing-transmission-ledger/1.0"
SCHEMA_FILENAME = "transmission_ledger.schema.json"
TRANSMISSION_LEDGER_SUFFIX = ".transmission-ledger.json"
STANCE_EVENT_FIELDS = (
    "work_family_id",
    "recipient_provider_identity",
    "recipient_model_identity",
    "purpose",
    "content_classes",
    "prompt_sha256",
    "prompt_utf8_bytes",
    "consent_receipt_id",
    "retention_state",
    "retention_reference",
    "sent_at",
    "result_state",
)


class TransmissionError(Exception):
    """Fail-closed refusal: the transmissions cannot be honestly accounted."""


def _fail(message: str) -> None:
    raise TransmissionError(message)


def _require_allowlisted(
    event_label: str, content_classes: Any, allowed: set[str]
) -> None:
    if (
        not isinstance(content_classes, list)
        or not content_classes
        or not all(isinstance(item, str) for item in content_classes)
    ):
        _fail(f"{event_label}: content classes must be a non-empty string list")
    outside = [item for item in content_classes if item not in allowed]
    if outside:
        _fail(
            f"{event_label}: content class {outside[0]!r} is outside the "
            "consented allowlist"
        )


def _validated_inputs(
    plan: dict[str, Any], retrieval_input: dict[str, Any]
) -> None:
    try:
        substrate.validate_schema(
            plan, substrate.plan_schema_filename(plan), "query plan"
        )
        substrate.validate_plan(plan)
        substrate.validate_schema(
            retrieval_input, "retrieval_input.schema.json", "retrieval input"
        )
    except substrate.LedgerError as exc:
        raise TransmissionError(f"input is invalid: {exc}") from exc
    if retrieval_input["retrieval_input_sha256"] != substrate.bound_digest(
        retrieval_input, "retrieval_input_sha256"
    ):
        _fail(
            "retrieval input self-digest does not replay; a silently edited "
            "attempt list cannot be accounted"
        )
    if retrieval_input["query_plan_sha256"] != plan["plan_sha256"]:
        _fail("retrieval input is not bound to this query plan")


def _retrieval_events(
    plan: dict[str, Any], retrieval_input: dict[str, Any]
) -> list[dict[str, Any]]:
    queries = {query["query_id"]: query for query in plan["queries"]}
    roster = {provider["index_id"]: provider for provider in plan["provider_roster"]}
    receipt_id = plan["consent"]["consent_receipt_id"]
    seen_attempts: set[str] = set()
    events: list[dict[str, Any]] = []
    for attempt in retrieval_input["attempts"]:
        label = f"attempt {attempt.get('attempt_id')!r}"
        if attempt["attempt_id"] in seen_attempts:
            _fail(f"{label}: attempt ids must be unique (double-counted event)")
        seen_attempts.add(attempt["attempt_id"])
        query = queries.get(attempt.get("query_id"))
        if query is None:
            _fail(f"{label}: names a query outside the consented plan")
        provider = roster.get(attempt.get("index_id"))
        if provider is None:
            _fail(f"{label}: names an index outside the consented roster")
        if attempt["index_id"] not in query["index_targets"]:
            _fail(
                f"{label}: index {attempt['index_id']!r} is not a consented "
                f"target of query {query['query_id']!r}"
            )
        if attempt.get("consent_receipt_id") != receipt_id:
            _fail(f"{label}: consent receipt does not match the plan receipt")
        events.append(
            {
                "event_kind": "retrieval_query",
                "attempt_id": attempt["attempt_id"],
                "query_id": attempt["query_id"],
                "recipient_index_id": attempt["index_id"],
                "recipient_product_identity": provider["product_identity"],
                "purpose": "scholarly_discovery",
                "content_classes": list(
                    substrate.RETRIEVAL_ONLY_CONTENT_CLASSES
                ),
                "query_sha256": query["query_sha256"],
                "query_utf8_bytes": len(
                    query["accepted_query_text"].encode("utf-8")
                ),
                "consent_receipt_id": receipt_id,
                "retention_state": provider["retention_state"],
                "retention_reference": provider["retention_reference"],
                "sent_at": attempt["started_at"],
                "result_state": attempt["outcome"],
            }
        )
    return events


def _stance_events(
    plan: dict[str, Any],
    stance_transmissions: list[dict[str, Any]],
    allowed: set[str],
) -> list[dict[str, Any]]:
    stance_plan = plan["stance_plan"]
    receipt_id = plan["consent"]["consent_receipt_id"]
    events: list[dict[str, Any]] = []
    for index, source in enumerate(stance_transmissions):
        label = f"stance transmission [{index}]"
        if not isinstance(source, dict):
            _fail(f"{label}: must be an object")
        missing = [field for field in STANCE_EVENT_FIELDS if field not in source]
        if missing:
            _fail(f"{label}: missing recorded field {missing[0]!r}")
        unexpected = sorted(set(source) - set(STANCE_EVENT_FIELDS))
        if unexpected:
            _fail(f"{label}: unexpected field {unexpected[0]!r}")
        _require_allowlisted(label, source["content_classes"], allowed)
        if source["recipient_provider_identity"] != stance_plan["provider_identity"]:
            _fail(
                f"{label}: recipient provider identity does not match the "
                "consented stance_plan"
            )
        if source["recipient_model_identity"] != stance_plan["model_identity"]:
            _fail(
                f"{label}: recipient model identity does not match the "
                "consented stance_plan"
            )
        if source["consent_receipt_id"] != receipt_id:
            _fail(f"{label}: consent receipt does not match the plan receipt")
        if (
            source["retention_state"] != stance_plan["retention_state"]
            or source["retention_reference"] != stance_plan["retention_reference"]
        ):
            _fail(
                f"{label}: retention disclosure does not match the consented "
                "stance_plan verbatim"
            )
        if not isinstance(source["result_state"], str):
            _fail(
                f"{label}: result_state must be recorded before the event can "
                "be accounted"
            )
        event = {"event_kind": "stance_classification"}
        for field in STANCE_EVENT_FIELDS:
            event[field] = source[field]
        events.append(event)
    return events


# Which event result states can honestly account for a stance-record row.
_ROW_EVENT_RESULT_STATES = {
    None: {"performed"},  # performed row (failure_state is null)
    "judge_timeout": {"judge_timeout"},
    "judge_error": {"judge_error"},
    # An oversized judge return is recorded as the row's parse_error with
    # its own event result state.
    "parse_error": {"parse_error", "oversized_output"},
}


def _cross_check_stance_record(
    stance_record: dict[str, Any],
    plan: dict[str, Any],
    stance_events: list[dict[str, Any]],
) -> None:
    try:
        substrate.validate_schema(
            stance_record, "stance_record.schema.json", "stance record"
        )
    except substrate.LedgerError as exc:
        raise TransmissionError(str(exc)) from exc
    if stance_record["stance_record_sha256"] != substrate.bound_digest(
        stance_record, "stance_record_sha256"
    ):
        _fail(
            "stance record self-digest does not replay; an edited record "
            "cannot vouch for the transmission ledger"
        )
    identity = stance_record["identity"]
    if identity["query_plan_sha256"] != plan["plan_sha256"]:
        _fail("stance record is not bound to this query plan")
    if identity["consent_receipt_sha256"] != plan["consent"]["receipt_sha256"]:
        _fail("stance record is not bound to this consent receipt")
    # Every row that reached the transport (everything except an
    # abstract-missing row, which never builds a prompt) must have its
    # event, and the event's prompt hash and result state must agree with
    # the row's retained evidence.
    events_by_family = {
        event["work_family_id"]: event for event in stance_events
    }
    if len(events_by_family) != len(stance_events):
        _fail("stance events must be unique per work family")
    expected_rows = [
        row
        for row in stance_record["rows"]
        if row.get("failure_state") != "abstract_missing"
    ]
    expected_ids = sorted(row["work_family_id"] for row in expected_rows)
    accounted_ids = sorted(events_by_family)
    if expected_ids != accounted_ids:
        _fail(
            "stance record leaves transmissions unaccounted: expected events "
            f"for {expected_ids}, got {accounted_ids}"
        )
    for row in expected_rows:
        event = events_by_family[row["work_family_id"]]
        label = f"stance event for {row['work_family_id']!r}"
        if row.get("prompt_sha256") is None:
            _fail(
                f"{label}: the record row retains no prompt hash for a "
                "transport-reaching call"
            )
        if event["prompt_sha256"] != row["prompt_sha256"]:
            _fail(f"{label}: prompt hash does not match the record row")
        allowed_states = _ROW_EVENT_RESULT_STATES.get(row.get("failure_state"))
        if allowed_states is None:
            _fail(
                f"{label}: record row failure state "
                f"{row.get('failure_state')!r} has no transmission mapping"
            )
        if event["result_state"] not in allowed_states:
            _fail(
                f"{label}: result state {event['result_state']!r} does not "
                f"match the record row (expected one of {sorted(allowed_states)})"
            )


def build_transmission_ledger(
    plan: dict[str, Any],
    retrieval_input: dict[str, Any],
    *,
    stance_transmissions: list[dict[str, Any]] | None = None,
    stance_record: dict[str, Any] | None = None,
) -> dict[str, Any]:
    if not isinstance(retrieval_input, dict) or not isinstance(
        retrieval_input.get("attempts"), list
    ):
        _fail("retrieval input must carry an attempts array")
    _validated_inputs(plan, retrieval_input)
    allowed = set(plan["authorized_content_classes"])
    events = _retrieval_events(plan, retrieval_input)
    try:
        # The canonical intake's semantic invariants (one initial attempt per
        # planned query/index pair, retry authorization chains, monotonic
        # times): a re-sealed input that silently omits a planned attempt is
        # refused here.
        substrate.validate_input(plan, retrieval_input)
    except substrate.LedgerError as exc:
        raise TransmissionError(f"input is invalid: {exc}") from exc
    stance_authorized = (
        plan["consent"].get("decision") == "retrieval_plus_stance"
    )
    if stance_transmissions is None:
        if stance_authorized:
            _fail(
                "a retrieval_plus_stance consent requires its stance "
                "transmissions to be supplied explicitly; pass an empty list "
                "to assert that no stance call occurred"
            )
    elif stance_transmissions:
        if not stance_authorized:
            _fail(
                "stance transmissions require a retrieval_plus_stance consent "
                "decision; this plan does not authorize a stance call"
            )
        events.extend(_stance_events(plan, stance_transmissions, allowed))
    if stance_record is not None:
        _cross_check_stance_record(
            stance_record, plan, stance_transmissions or []
        )
    ledger = {
        "schema_version": LEDGER_VERSION,
        "probe_id": plan["probe_id"],
        "query_plan_sha256": plan["plan_sha256"],
        "consent_receipt_id": plan["consent"]["consent_receipt_id"],
        "consent_receipt_sha256": plan["consent"]["receipt_sha256"],
        "authorized_content_classes": list(plan["authorized_content_classes"]),
        "events": events,
    }
    ledger["transmission_ledger_sha256"] = substrate.bound_digest(
        ledger, "transmission_ledger_sha256"
    )
    try:
        substrate.validate_schema(ledger, SCHEMA_FILENAME, "transmission ledger")
    except substrate.LedgerError as exc:
        raise TransmissionError(str(exc)) from exc
    return ledger


def validate_transmission_ledger(
    plan: dict[str, Any],
    retrieval_input: dict[str, Any],
    stance_transmissions: list[dict[str, Any]] | None,
    ledger: dict[str, Any],
    *,
    stance_record: dict[str, Any] | None = None,
) -> None:
    """Exact deterministic replay: the ledger must equal a fresh build."""
    rebuilt = build_transmission_ledger(
        plan,
        retrieval_input,
        stance_transmissions=stance_transmissions,
        stance_record=stance_record,
    )
    if rebuilt != ledger:
        _fail("transmission ledger does not replay from its inputs")


def authorized_transmission_ledger_path(plan: dict[str, Any]) -> Path:
    """The only writable output path: derived from the hash-bound consent."""
    try:
        return substrate.authorized_export_path(
            plan, TRANSMISSION_LEDGER_SUFFIX
        )
    except substrate.LedgerError as exc:
        raise TransmissionError(str(exc)) from exc


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    for name, help_text in (
        ("build", "assemble and print or export the transmission ledger"),
        ("validate", "replay an existing transmission ledger exactly"),
    ):
        sub = commands.add_parser(name, help=help_text)
        sub.add_argument("--query-plan", type=Path, required=True)
        sub.add_argument("--retrieval-input", type=Path, required=True)
        sub.add_argument("--stance-transmissions", type=Path, default=None)
        sub.add_argument("--stance-record", type=Path, default=None)
        if name == "build":
            sub.add_argument("--output", type=Path, default=None)
        else:
            sub.add_argument("--transmission-ledger", type=Path, required=True)
    args = parser.parse_args(argv)
    try:
        plan = substrate.load_json(args.query_plan)
        retrieval_input = substrate.load_json(args.retrieval_input)
        stance_transmissions = None
        if args.stance_transmissions is not None:
            stance_transmissions = substrate.load_json(args.stance_transmissions)
            if not isinstance(stance_transmissions, list):
                _fail("stance transmissions file must contain a JSON array")
        stance_record = (
            substrate.load_json(args.stance_record)
            if args.stance_record is not None
            else None
        )
        if args.command == "build":
            ledger = build_transmission_ledger(
                plan,
                retrieval_input,
                stance_transmissions=stance_transmissions,
                stance_record=stance_record,
            )
            if args.output is None:
                print(json.dumps(ledger, ensure_ascii=False, indent=2))
            else:
                authorized = substrate.require_export_consent(
                    plan, args.output, TRANSMISSION_LEDGER_SUFFIX
                )
                substrate.write_new_ledger(authorized, ledger)
                print(f"transmission ledger written: {authorized}")
        else:
            ledger = substrate.load_json(args.transmission_ledger)
            validate_transmission_ledger(
                plan,
                retrieval_input,
                stance_transmissions,
                ledger,
                stance_record=stance_record,
            )
            print("transmission ledger replays exactly")
    except (
        TransmissionError,
        substrate.LedgerError,
        OSError,
        ValueError,
        KeyError,
        TypeError,
        AttributeError,
    ) as exc:
        print(f"TRANSMISSION-LEDGER ERROR: {exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
add-product-e2e-evalpaperclipai/paperclipAdd or extend a Paperclip full-stack runner E2E workflow, fixture, matcher, or report evidence path for local or Daytona execution.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
add-runner-evalpaperclipai/paperclipAdd or extend a Paperclip Runner protocol evaluation definition, roster, assertion, or report fixture with provenance and narrow validation.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
diagnose-why-work-stoppedpaperclipai/paperclipCompatibility entry point for failed, stalled, looping, or over-recovered Paperclip work. Use fix-failed-paperclip-run for the full diagnosis, regression, repair, real verification, and green-PR workflow; honor an explicitly requested diagnosis-only scope.Stars: 115kUpdated Claude CodeCodexVerifiedInstall
fix-failed-paperclip-runpaperclipai/paperclipDiagnose and fix failed, stuck, slow, or incorrectly blocked Paperclip tasks and runs. Use with a task/run URL or failure report to trace the root cause, prove a regression red then green, check second-order effects, verify the real workflow, and deliver a PR with passing checks.Stars: 115kUpdated Claude CodeCodexVerifiedInstall