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/_skill_lint.py

View on GitHub
"""Shared helpers for SKILL.md frontmatter linting + cross-lint H2-section
literal checks.

Frontmatter helpers (check_data_access_level.py, check_task_type.py)
validate that every top-level SKILL.md declares a required metadata field
drawn from a closed vocabulary.

`h2_section_body` / `check_section_literals` are the H2 line-walk variant
shared by the block-scoped string-check lints (check_394, check_390): the
"named H2 must exist and carry every load-bearing literal" pattern. This is
ONE of several section extractors in scripts/ — the heading-level / regex /
fence-aware variants (check_392, check_216, check_firm_rules_sync) are
deliberately not interchangeable with this plain line-walk and are not
consolidated here.

`norm_ws` / `read_or_exit2` are the verbatim-witness-lint pair
(check_reviewer_data_fences, check_reviewer_finding_contract): whitespace
folding is load-bearing for "verbatim match modulo wrapping" pins, so it must
be single-sourced rather than re-implemented per lint. (Older lints with
private `_norm` copies — check_instruction_data_boundary,
check_firm_rules_sync — predate this helper; migrating them is a follow-up.)

`extract_marker_block` / `first_difference` / `check_marker_copies` are the
marker-block sync trio (check_routing_core_sync, check_method_weaknesses_sync,
check_review_form_note_sync, #923): one canonical block between an HTML
comment marker pair, copied byte for byte into each surface.
"""
from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path

import yaml

# One row of the `.claude/CLAUDE.md` § "Skills Overview" table. The first cell is
# the backticked skill directory name followed by its `vX.Y.Z` token. Two forms
# are shared so the lints agree on what a row is:
#   PREFIX — name only. check_skill_inventory_parity.py uses it to find every
#            row that names a skill, so a row can never hide from the parity
#            check by omitting its version.
#   FULL   — name + version. check_version_consistency.py parses versions with
#            it; the parity lint reports any PREFIX row that is not also a FULL
#            row, closing the gap where a version-less row is invisible to the
#            version lint (it only iterates FULL matches).
SKILLS_TABLE_ROW_PREFIX = r"^\|\s*`([a-z0-9-]+)`"
SKILLS_TABLE_ROW_FULL = SKILLS_TABLE_ROW_PREFIX + r"\s+v([A-Za-z0-9.\-_+]+)\s*\|"

SKIP_DIRS = frozenset(
    {"shared", "scripts", "docs", ".git", ".github", "examples", ".local-plans", ".claude"}
)


class FrontmatterError(Exception):
    """Raised when SKILL.md frontmatter cannot be parsed.

    Distinct from a missing fence (returns None) and an empty fence
    (returns {}). Callers should catch this and surface the path +
    parser detail on stdout, not stderr — CI logs commonly capture
    only stdout.
    """


def iter_skill_files(root: Path) -> list[Path]:
    """Top-level SKILL.md files only. Skips SKIP_DIRS."""
    results: list[Path] = []
    for child in sorted(root.iterdir()):
        if not child.is_dir() or child.name in SKIP_DIRS:
            continue
        skill_md = child / "SKILL.md"
        if skill_md.is_file():
            results.append(skill_md)
    return results


def parse_frontmatter(path: Path) -> dict | None:
    """Parse the YAML frontmatter of a SKILL.md.

    Three outcomes:
      - dict (possibly empty) — fence present and parseable
      - None                  — no opening '---' fence
      - raises FrontmatterError — fence present but YAML invalid
    """
    text = path.read_text(encoding="utf-8")
    if not text.startswith("---"):
        return None
    match = re.match(r"\A---\r?\n(?P<fm>.*?)(?:\r?\n)---(?:\r?\n|$)", text, re.DOTALL)
    if not match:
        raise FrontmatterError(f"{path}: missing closing YAML frontmatter fence")
    fm = match.group("fm")
    try:
        data = yaml.safe_load(fm) or {}
    except yaml.YAMLError as exc:
        raise FrontmatterError(f"{path}: malformed YAML frontmatter: {exc}") from exc
    if not isinstance(data, dict):
        raise FrontmatterError(
            f"{path}: YAML frontmatter must be a mapping/object, got {type(data).__name__}"
        )
    return data


def split_frontmatter(text: str) -> tuple[dict | None, str]:
    """Split YAML frontmatter from body. Lenient variant of parse_frontmatter.

    Unlike parse_frontmatter, callers here need access to the body and
    prefer "no frontmatter" to an exception when YAML is malformed (the
    caller's surrounding check will surface the structural error). Both
    invalid-fence and invalid-YAML return (None, text) rather than raising.
    """
    if not text.startswith("---"):
        return None, text
    match = re.match(r"\A---\r?\n(?P<fm>.*?)(?:\r?\n)---(?:\r?\n|$)", text, re.DOTALL)
    if not match:
        return None, text
    try:
        data = yaml.safe_load(match.group("fm")) or {}
    except yaml.YAMLError:
        return None, text
    if not isinstance(data, dict):
        return None, text
    return data, text[match.end():]


def check_metadata_field(
    root: Path,
    field: str,
    legal_values: set[str] | frozenset[str],
) -> list[str]:
    """Return a list of human-readable violation messages, empty if all pass."""
    violations: list[str] = []
    skills = iter_skill_files(root)
    if not skills:
        violations.append(f"no SKILL.md files found under {root}")
        return violations
    for path in skills:
        try:
            fm = parse_frontmatter(path)
        except FrontmatterError as exc:
            violations.append(str(exc))
            continue
        if fm is None:
            violations.append(f"{path}: missing YAML frontmatter")
            continue
        metadata = fm.get("metadata") or {}
        if field not in metadata:
            violations.append(f"{path}: metadata.{field} is missing")
            continue
        value = metadata[field]
        if value not in legal_values:
            violations.append(
                f"{path}: metadata.{field} = {value!r}, "
                f"must be one of {sorted(legal_values)}"
            )
    return violations


def h2_section_body(text: str, heading: str) -> str | None:
    """Return the BODY of the H2 starting with `heading` (heading line
    excluded) up to the next H2, or None when the heading is absent. The
    section boundary is explicit: a line is a boundary iff it starts a new
    H2 (`## `); internal H3s and code fences are part of the body."""
    body: list[str] = []
    in_section = False
    for line in text.splitlines():
        if line.startswith(heading):
            in_section = True
            continue
        if in_section and line.startswith("## "):
            break
        if in_section:
            body.append(line)
    return "\n".join(body) if in_section else None


def check_section_literals(invariant: int, text: str, heading: str,
                           label: str,
                           literals: dict[str, str]) -> list[str]:
    """The named H2 section must exist and carry every load-bearing literal.
    Shared by the block-scoped string-check lints (check_394, check_390)."""
    section = h2_section_body(text, heading)
    if section is None:
        return [f"invariant {invariant}: {label} section '{heading}' missing"]
    return [
        f"invariant {invariant}: {label} section lost the "
        f"{name} literal ({literal!r})"
        for name, literal in literals.items()
        if literal not in section
    ]


def heading_section(text: str, heading: str) -> str | None:
    """Return the body of the section opened by the exact heading line
    (column 0, outside ``` fences), up to the next heading of the SAME or
    HIGHER level outside fences — deeper child headings stay inside the body.
    None if absent. Nestable: pass a parent section's body back in to bind a
    child heading to that parent (delivery-block scoping — a heading matched
    anywhere in the file is NOT the delivered block)."""
    open_level = len(heading) - len(heading.lstrip("#"))
    stop = re.compile(rf"#{{1,{open_level}}} ")
    # Both Markdown fence forms count — a heading "hidden" in a ~~~ block must
    # not read as a real section boundary (CommonMark close: same fence char,
    # run length >= the opening run, at most 3 spaces of indentation).
    fence_re = re.compile(r"[ ]{0,3}(`{3,}|~{3,})")
    # A CLOSING fence is the run alone on its line (CommonMark: no info string
    # on a closer — "~~~not-a-close" does NOT close a ~~~ block — and a
    # 4-space-indented run is content, not a closer).
    fence_close_re = re.compile(r"[ ]{0,3}(`{3,}|~{3,})\s*$")
    fence: str | None = None  # the opening fence run while inside a fenced block
    started = False
    body: list[str] = []
    for line in text.splitlines(keepends=True):
        m = fence_re.match(line)
        if fence is not None:
            mc = fence_close_re.match(line)
            if mc and mc.group(1)[0] == fence[0] and len(mc.group(1)) >= len(fence):
                fence = None
            if started:
                body.append(line)
            continue
        if m:
            fence = m.group(1)
            if started:
                body.append(line)
            continue
        if not started:
            if line.rstrip("\n") == heading:
                started = True
            continue
        if stop.match(line):
            break
        body.append(line)
    return "".join(body) if started else None


def norm_ws(text: str) -> str:
    """Collapse all whitespace runs so line-wrapping does not defeat a
    verbatim-witness compare. Load-bearing for the fence/finding-contract
    pins — hardening added here reaches every importing lint at once."""
    return re.sub(r"\s+", " ", text).strip()


def read_or_exit2(root: Path, rel: str, *, exact: bool = False) -> str:
    """Read a required lint surface; a missing file is an invocation error
    (exit 2), never a lint failure (exit 1). With `exact`, line endings stay
    as stored instead of being translated to LF."""
    p = root / rel
    if not p.is_file():
        print(f"ERROR: required file missing: {rel}", file=sys.stderr)
        raise SystemExit(2)
    return p.read_bytes().decode("utf-8") if exact else p.read_text(encoding="utf-8")


def extract_marker_block(text: str, label: str, begin: str, end: str,
                         name: str) -> tuple[str | None, list[str]]:
    """Return the text between the one `begin`/`end` marker pair, or None with
    the errors. A marker line may end in CR; the block keeps its CRs for the
    comparison. `name` names the block in the empty-block error."""
    lines = text.split("\n")
    begins = [i for i, line in enumerate(lines) if line.rstrip("\r") == begin]
    ends = [i for i, line in enumerate(lines) if line.rstrip("\r") == end]
    errors: list[str] = []
    for marker, whole in ((begin, begins), (end, ends)):
        total = text.count(marker)
        if total != 1 or len(whole) != 1:
            errors.append(f"{label}: expected one {marker} alone on its line, "
                          f"found {total} occurrence(s), {len(whole)} on their own line")
    if errors:
        return None, errors
    if begins[0] > ends[0]:
        return None, [f"{label}: {end} comes before {begin}"]
    block = "\n".join(lines[begins[0] + 1:ends[0]])
    if not block.strip():
        return None, [f"{label}: the {name} block is empty"]
    return block, []


def first_difference(copy: str, canonical: str) -> str:
    """Say where a copied block first departs from the canonical block."""
    copy_lines, canon_lines = copy.split("\n"), canonical.split("\n")
    for number, (got, want) in enumerate(zip(copy_lines, canon_lines), start=1):
        if got != want:
            if got.rstrip("\r") == want.rstrip("\r"):
                return f"block line {number} differs only in its line ending"
            return f"block line {number} differs"
    return (f"block has {len(copy_lines)} lines, canonical has {len(canon_lines)}")


def check_marker_copies(root: Path, canonical: Path, copies: list[Path] | tuple[Path, ...],
                        begin: str, end: str, name: str, canonical_id: str,
                        copy_id: str) -> tuple[str | None, list[str]]:
    """Extract the canonical block, then check that every copy holds one marker
    pair around a byte-identical block. Returns the canonical block (None when
    it is malformed) and the errors; a missing file exits 2."""
    block, errors = extract_marker_block(read_or_exit2(root, str(canonical), exact=True),
                                         f"{canonical_id} {canonical}", begin, end, name)
    for rel in copies:
        copy, copy_errors = extract_marker_block(read_or_exit2(root, str(rel), exact=True),
                                                 f"{copy_id} {rel}", begin, end, name)
        errors += copy_errors
        if copy is not None and block is not None and copy != block:
            errors.append(f"{copy_id} {rel}: {name} block differs from {canonical} "
                          f"({first_difference(copy, block)})")
    return block, errors


def run_lint(field: str, legal_values: set[str] | frozenset[str], ok_message: str) -> int:
    """argparse + check + print + exit-code wrapper (check_task_type.py;
    check_data_access_level.py grew its own #756 pin-layer main and no
    longer uses this)."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--path",
        type=Path,
        default=Path(__file__).resolve().parent.parent,
    )
    args = parser.parse_args()

    violations = check_metadata_field(args.path, field, legal_values)
    if violations:
        for v in violations:
            print(f"ERROR: {v}")
        print(f"\n{len(violations)} violation(s) found.", file=sys.stderr)
        return 1
    print(ok_message)
    return 0
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