Add P0 infrastructure for the Volve-DIA benchmark
Set up the data, parsing and quality-control layer for a public benchmark on the Volve daily drilling reports (DDR) and WITSML real-time data. - Data manifest with SHA-256 hashes of the three Volve subtrees in use. - DDR XML parser into DuckDB (1,759 reports, 26 wellbores, 23,447 activities, 17 tables) with locked expected counts. - Render QC of the publisher HTML against the XML (272,544 items). - OCR client for the shared chandra vLLM service, with a page cache keyed on model, prompt hash, dpi, max_tokens and temperature, and OCR QC against the HTML on a 26-report pilot. - Run logging (scripts/runlog.sh, logs/index.csv), the P0 runner and 40 tests. - Research plan, technical overview and progress page (in Vietnamese). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
251
.agents/skills/scientific-writing/scripts/_common.py
Normal file
251
.agents/skills/scientific-writing/scripts/_common.py
Normal file
@@ -0,0 +1,251 @@
|
||||
"""Shared, dependency-free safety helpers for scientific-writing CLIs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
MAX_FILE_BYTES = 5_000_000
|
||||
MAX_RECORDS = 10_000
|
||||
MAX_JSON_NODES = 100_000
|
||||
MAX_JSON_DEPTH = 50
|
||||
MAX_CSV_FIELD_BYTES = 100_000
|
||||
|
||||
|
||||
class InputError(ValueError):
|
||||
"""Raised when a local input fails a bounded safety check."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Issue:
|
||||
severity: str
|
||||
code: str
|
||||
location: str | None = None
|
||||
item_id: str | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, str]:
|
||||
return {key: value for key, value in asdict(self).items() if value is not None}
|
||||
|
||||
|
||||
def _checked_file(path_value: str | Path, suffixes: Iterable[str]) -> Path:
|
||||
path = Path(path_value)
|
||||
allowed = {suffix.lower() for suffix in suffixes}
|
||||
if path.is_symlink():
|
||||
raise InputError("symbolic-link inputs are not accepted")
|
||||
if not path.is_file():
|
||||
raise InputError("input must be an existing regular file")
|
||||
if path.suffix.lower() not in allowed:
|
||||
raise InputError(
|
||||
f"input extension must be one of: {', '.join(sorted(allowed))}"
|
||||
)
|
||||
if path.stat().st_size > MAX_FILE_BYTES:
|
||||
raise InputError(f"input exceeds {MAX_FILE_BYTES} bytes")
|
||||
return path
|
||||
|
||||
|
||||
def read_text(path_value: str | Path, suffixes: Iterable[str]) -> str:
|
||||
path = _checked_file(path_value, suffixes)
|
||||
try:
|
||||
return path.read_text(encoding="utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise InputError("input must be UTF-8 text") from exc
|
||||
|
||||
|
||||
def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
result: dict[str, Any] = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise InputError("JSON contains a duplicate object key")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _reject_nonfinite_json(_value: str) -> None:
|
||||
raise InputError("JSON non-finite numbers are not accepted")
|
||||
|
||||
|
||||
def _check_json_bounds(value: Any, depth: int = 0) -> int:
|
||||
if depth > MAX_JSON_DEPTH:
|
||||
raise InputError(f"JSON nesting exceeds {MAX_JSON_DEPTH} levels")
|
||||
count = 1
|
||||
if isinstance(value, dict):
|
||||
for child in value.values():
|
||||
count += _check_json_bounds(child, depth + 1)
|
||||
elif isinstance(value, list):
|
||||
if len(value) > MAX_RECORDS:
|
||||
raise InputError(f"JSON array exceeds {MAX_RECORDS} records")
|
||||
for child in value:
|
||||
count += _check_json_bounds(child, depth + 1)
|
||||
if count > MAX_JSON_NODES:
|
||||
raise InputError(f"JSON exceeds {MAX_JSON_NODES} nodes")
|
||||
return count
|
||||
|
||||
|
||||
def read_json(path_value: str | Path) -> Any:
|
||||
text = read_text(path_value, {".json"})
|
||||
try:
|
||||
value = json.loads(
|
||||
text,
|
||||
object_pairs_hook=_reject_duplicate_keys,
|
||||
parse_constant=_reject_nonfinite_json,
|
||||
)
|
||||
except (json.JSONDecodeError, RecursionError) as exc:
|
||||
raise InputError("input is not valid bounded JSON") from exc
|
||||
_check_json_bounds(value)
|
||||
return value
|
||||
|
||||
|
||||
def read_csv(path_value: str | Path) -> tuple[list[str], list[dict[str, str]]]:
|
||||
text = read_text(path_value, {".csv"})
|
||||
csv.field_size_limit(MAX_CSV_FIELD_BYTES)
|
||||
try:
|
||||
reader = csv.DictReader(io.StringIO(text, newline=""))
|
||||
fields = list(reader.fieldnames or [])
|
||||
if not fields or any(not field for field in fields):
|
||||
raise InputError("CSV requires a non-empty header row")
|
||||
if len(set(fields)) != len(fields):
|
||||
raise InputError("CSV contains duplicate header names")
|
||||
rows: list[dict[str, str]] = []
|
||||
for index, row in enumerate(reader, start=1):
|
||||
if index > MAX_RECORDS:
|
||||
raise InputError(f"CSV exceeds {MAX_RECORDS} data rows")
|
||||
if None in row:
|
||||
raise InputError("CSV row has more fields than the header")
|
||||
rows.append({key: value or "" for key, value in row.items()})
|
||||
except csv.Error as exc:
|
||||
raise InputError("input is not valid bounded CSV") from exc
|
||||
return fields, rows
|
||||
|
||||
|
||||
def issue(
|
||||
severity: str,
|
||||
code: str,
|
||||
*,
|
||||
location: str | None = None,
|
||||
item_id: str | None = None,
|
||||
) -> Issue:
|
||||
if severity not in {"error", "warning", "info"}:
|
||||
raise ValueError("unsupported issue severity")
|
||||
return Issue(severity=severity, code=code, location=location, item_id=item_id)
|
||||
|
||||
|
||||
def emit_report(
|
||||
tool: str,
|
||||
issues: Iterable[Issue],
|
||||
*,
|
||||
summary: dict[str, Any] | None = None,
|
||||
) -> int:
|
||||
ordered = sorted(
|
||||
issues,
|
||||
key=lambda item: (
|
||||
{"error": 0, "warning": 1, "info": 2}[item.severity],
|
||||
item.code,
|
||||
item.location or "",
|
||||
item.item_id or "",
|
||||
),
|
||||
)
|
||||
error_count = sum(item.severity == "error" for item in ordered)
|
||||
warning_count = sum(item.severity == "warning" for item in ordered)
|
||||
payload = {
|
||||
"tool": tool,
|
||||
"status": "fail" if error_count else "pass",
|
||||
"summary": {
|
||||
"errors": error_count,
|
||||
"warnings": warning_count,
|
||||
**(summary or {}),
|
||||
},
|
||||
"issues": [item.to_dict() for item in ordered],
|
||||
}
|
||||
print(json.dumps(payload, indent=2, sort_keys=True))
|
||||
return 1 if error_count else 0
|
||||
|
||||
|
||||
def emit_input_error(tool: str, exc: Exception) -> int:
|
||||
return emit_report(
|
||||
tool,
|
||||
[issue("error", "INVALID_INPUT", location=type(exc).__name__)],
|
||||
)
|
||||
|
||||
|
||||
def require_object(value: Any, label: str = "root") -> dict[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
raise InputError(f"{label} must be a JSON object")
|
||||
return value
|
||||
|
||||
|
||||
def require_list(value: Any, label: str) -> list[Any]:
|
||||
if not isinstance(value, list):
|
||||
raise InputError(f"{label} must be a JSON array")
|
||||
if len(value) > MAX_RECORDS:
|
||||
raise InputError(f"{label} exceeds {MAX_RECORDS} records")
|
||||
return value
|
||||
|
||||
|
||||
def is_nonempty_string(value: Any) -> bool:
|
||||
return isinstance(value, str) and bool(value.strip())
|
||||
|
||||
|
||||
def is_iso_date(value: Any) -> bool:
|
||||
"""Accept an actual calendar date in the exact YYYY-MM-DD form."""
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
try:
|
||||
return date.fromisoformat(value).isoformat() == value
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def is_placeholder(value: Any) -> bool:
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
lowered = value.strip().lower()
|
||||
return (
|
||||
not lowered
|
||||
or "[[todo" in lowered
|
||||
or lowered in {"todo", "tbd", "tk", "replace_me", "unknown"}
|
||||
)
|
||||
|
||||
|
||||
def write_new_text(
|
||||
path_value: str | Path, content: str, suffixes: Iterable[str]
|
||||
) -> Path:
|
||||
path = Path(path_value)
|
||||
allowed = {suffix.lower() for suffix in suffixes}
|
||||
if path.suffix.lower() not in allowed:
|
||||
raise InputError(
|
||||
f"output extension must be one of: {', '.join(sorted(allowed))}"
|
||||
)
|
||||
if path.exists() or path.is_symlink():
|
||||
raise InputError("output already exists; refusing to overwrite")
|
||||
parent = path.parent
|
||||
if not parent.is_dir() or parent.is_symlink():
|
||||
raise InputError("output parent must be an existing regular directory")
|
||||
encoded = content.encode("utf-8")
|
||||
if len(encoded) > MAX_FILE_BYTES:
|
||||
raise InputError(f"output exceeds {MAX_FILE_BYTES} bytes")
|
||||
with path.open("x", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(content)
|
||||
return path
|
||||
|
||||
|
||||
def main_guard(tool: str, callback: Any) -> int:
|
||||
try:
|
||||
return int(callback())
|
||||
except (InputError, OSError, ValueError) as exc:
|
||||
return emit_input_error(tool, exc)
|
||||
|
||||
|
||||
def run(tool: str, callback: Any) -> None:
|
||||
raise SystemExit(main_guard(tool, callback))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("This module is imported by the scientific-writing command-line tools.")
|
||||
sys.exit(0)
|
||||
272
.agents/skills/scientific-writing/scripts/audit_claims.py
Normal file
272
.agents/skills/scientific-writing/scripts/audit_claims.py
Normal file
@@ -0,0 +1,272 @@
|
||||
"""Audit claim-to-evidence mappings and local citation markers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from _common import (
|
||||
InputError,
|
||||
Issue,
|
||||
emit_report,
|
||||
is_nonempty_string,
|
||||
issue,
|
||||
read_csv,
|
||||
read_json,
|
||||
read_text,
|
||||
require_list,
|
||||
require_object,
|
||||
run,
|
||||
)
|
||||
from validate_manifest import validate_source_manifest
|
||||
|
||||
TOOL = "audit_claims"
|
||||
REQUIRED_FIELDS = {
|
||||
"claim_id",
|
||||
"section",
|
||||
"claim_kind",
|
||||
"claim_text_sha256",
|
||||
"evidence_ids",
|
||||
"verification_status",
|
||||
"uncertainty",
|
||||
"analysis_intent",
|
||||
}
|
||||
CLAIM_ID_RE = re.compile(r"^C[0-9]{3,8}$")
|
||||
EVIDENCE_ID_RE = re.compile(r"^E[0-9]{3,8}$")
|
||||
SHA256_RE = re.compile(r"^[a-f0-9]{64}$")
|
||||
CLAIM_MARKER_RE = re.compile(r"\[claim:(C[0-9]{3,8})\]")
|
||||
EVIDENCE_MARKER_RE = re.compile(
|
||||
r"\[evidence:((?:E[0-9]{3,8})(?:\s*,\s*E[0-9]{3,8})*)\]"
|
||||
)
|
||||
CITATION_MARKER_RE = re.compile(r"\[@(E[0-9]{3,8})\]")
|
||||
NUMERIC_RE = re.compile(r"(?<![A-Za-z])(?:[<>]=?\s*)?[0-9]+(?:\.[0-9]+)?%?")
|
||||
CLAIM_KINDS = {"factual", "numeric", "method", "result", "interpretive", "declaration"}
|
||||
UNCERTAINTY = {"not_applicable", "not_estimated", "low", "moderate", "high"}
|
||||
ANALYSIS_INTENT = {"confirmatory", "exploratory", "descriptive", "not_applicable"}
|
||||
|
||||
|
||||
def _split_evidence_ids(value: str) -> list[str]:
|
||||
return [part.strip() for part in value.split(";") if part.strip()]
|
||||
|
||||
|
||||
def load_sources(path: str) -> dict[str, bool]:
|
||||
data = require_object(read_json(path), "source_manifest")
|
||||
if any(
|
||||
item.severity == "error"
|
||||
for item in validate_source_manifest(data, require_verified=False)
|
||||
):
|
||||
raise InputError("source manifest failed validation")
|
||||
sources: dict[str, bool] = {}
|
||||
for index, raw_source in enumerate(require_list(data.get("sources"), "sources")):
|
||||
source = require_object(raw_source, f"sources[{index}]")
|
||||
evidence_id = source.get("evidence_id")
|
||||
if not isinstance(evidence_id, str) or not EVIDENCE_ID_RE.fullmatch(
|
||||
evidence_id
|
||||
):
|
||||
raise InputError("source manifest contains an invalid evidence_id")
|
||||
if evidence_id in sources:
|
||||
raise InputError("source manifest contains duplicate evidence_id values")
|
||||
verification = require_object(source.get("verification"), "verification")
|
||||
sources[evidence_id] = (
|
||||
verification.get("status") == "verified"
|
||||
and verification.get("source_opened") is True
|
||||
)
|
||||
return sources
|
||||
|
||||
|
||||
def claim_text_hash(line: str) -> str:
|
||||
"""Hash one physical claim line, excluding markers and normalizing whitespace."""
|
||||
text = CLAIM_MARKER_RE.sub("", line)
|
||||
text = EVIDENCE_MARKER_RE.sub("", text)
|
||||
text = CITATION_MARKER_RE.sub("", text)
|
||||
normalized = " ".join(text.split())
|
||||
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def load_claims(
|
||||
path: str,
|
||||
sources: dict[str, bool],
|
||||
) -> tuple[dict[str, dict[str, Any]], list[Issue]]:
|
||||
fields, rows = read_csv(path)
|
||||
if set(fields) != REQUIRED_FIELDS:
|
||||
missing = ",".join(sorted(REQUIRED_FIELDS - set(fields)))
|
||||
extra = ",".join(sorted(set(fields) - REQUIRED_FIELDS))
|
||||
raise InputError(
|
||||
f"claim registry headers must match the schema; missing={missing}; extra={extra}"
|
||||
)
|
||||
issues: list[Issue] = []
|
||||
claims: dict[str, dict[str, Any]] = {}
|
||||
for row_number, row in enumerate(rows, start=2):
|
||||
location = f"row:{row_number}"
|
||||
claim_id = row["claim_id"].strip()
|
||||
if not CLAIM_ID_RE.fullmatch(claim_id):
|
||||
issues.append(issue("error", "INVALID_CLAIM_ID", location=location))
|
||||
continue
|
||||
if claim_id in claims:
|
||||
issues.append(issue("error", "DUPLICATE_CLAIM_ID", item_id=claim_id))
|
||||
continue
|
||||
claims[claim_id] = row
|
||||
if row["claim_kind"] not in CLAIM_KINDS:
|
||||
issues.append(issue("error", "INVALID_CLAIM_KIND", item_id=claim_id))
|
||||
if not is_nonempty_string(row["section"]):
|
||||
issues.append(issue("error", "MISSING_CLAIM_SECTION", item_id=claim_id))
|
||||
if not SHA256_RE.fullmatch(row["claim_text_sha256"]):
|
||||
issues.append(issue("error", "INVALID_CLAIM_TEXT_HASH", item_id=claim_id))
|
||||
if row["verification_status"] != "verified":
|
||||
issues.append(issue("error", "CLAIM_NOT_VERIFIED", item_id=claim_id))
|
||||
if row["uncertainty"] not in UNCERTAINTY:
|
||||
issues.append(
|
||||
issue("error", "INVALID_UNCERTAINTY_STATUS", item_id=claim_id)
|
||||
)
|
||||
if row["analysis_intent"] not in ANALYSIS_INTENT:
|
||||
issues.append(issue("error", "INVALID_ANALYSIS_INTENT", item_id=claim_id))
|
||||
|
||||
evidence_ids = _split_evidence_ids(row["evidence_ids"])
|
||||
row["_evidence_ids"] = evidence_ids
|
||||
if not evidence_ids:
|
||||
issues.append(issue("error", "CLAIM_WITHOUT_EVIDENCE", item_id=claim_id))
|
||||
for evidence_id in evidence_ids:
|
||||
if not EVIDENCE_ID_RE.fullmatch(evidence_id):
|
||||
issues.append(
|
||||
issue("error", "INVALID_CLAIM_EVIDENCE_ID", item_id=claim_id)
|
||||
)
|
||||
elif evidence_id not in sources:
|
||||
issues.append(
|
||||
issue("error", "UNKNOWN_CLAIM_EVIDENCE", item_id=claim_id)
|
||||
)
|
||||
elif not sources[evidence_id]:
|
||||
issues.append(
|
||||
issue("error", "UNVERIFIED_CLAIM_EVIDENCE", item_id=claim_id)
|
||||
)
|
||||
return claims, issues
|
||||
|
||||
|
||||
def audit_markdown(
|
||||
text: str,
|
||||
claims: dict[str, dict[str, Any]],
|
||||
sources: dict[str, bool],
|
||||
) -> tuple[list[Issue], set[str]]:
|
||||
issues: list[Issue] = []
|
||||
used_claims: set[str] = set()
|
||||
in_fence = False
|
||||
for line_number, line in enumerate(text.splitlines(), start=1):
|
||||
stripped = line.strip()
|
||||
if stripped.startswith(("```", "~~~")):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence or not stripped or stripped.startswith(("#", "<!--")):
|
||||
continue
|
||||
|
||||
line_claims = CLAIM_MARKER_RE.findall(line)
|
||||
if len(line_claims) > 1:
|
||||
issues.append(
|
||||
issue("error", "MULTIPLE_CLAIMS_ON_LINE", location=f"line:{line_number}")
|
||||
)
|
||||
line_evidence: set[str] = set(CITATION_MARKER_RE.findall(line))
|
||||
for group in EVIDENCE_MARKER_RE.findall(line):
|
||||
line_evidence.update(part.strip() for part in group.split(","))
|
||||
|
||||
for evidence_id in sorted(line_evidence):
|
||||
if evidence_id not in sources:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"UNKNOWN_CITATION_MARKER",
|
||||
location=f"line:{line_number}",
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
elif not sources[evidence_id]:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"UNVERIFIED_CITATION_MARKER",
|
||||
location=f"line:{line_number}",
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
|
||||
for claim_id in line_claims:
|
||||
used_claims.add(claim_id)
|
||||
if claim_id not in claims:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"UNKNOWN_CLAIM_MARKER",
|
||||
location=f"line:{line_number}",
|
||||
item_id=claim_id,
|
||||
)
|
||||
)
|
||||
continue
|
||||
expected = set(claims[claim_id].get("_evidence_ids", []))
|
||||
if len(line_claims) == 1 and claim_text_hash(line) != claims[claim_id].get(
|
||||
"claim_text_sha256"
|
||||
):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"CLAIM_TEXT_HASH_MISMATCH",
|
||||
location=f"line:{line_number}",
|
||||
item_id=claim_id,
|
||||
)
|
||||
)
|
||||
if not expected.issubset(line_evidence):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"CLAIM_MARKER_MISSING_EVIDENCE_MARKER",
|
||||
location=f"line:{line_number}",
|
||||
item_id=claim_id,
|
||||
)
|
||||
)
|
||||
|
||||
if NUMERIC_RE.search(line) and not line_claims:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"UNTAGGED_NUMERIC_CONTENT",
|
||||
location=f"line:{line_number}",
|
||||
)
|
||||
)
|
||||
return issues, used_claims
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Audit local Markdown claim markers against a CSV claim registry and "
|
||||
"verified JSON source manifest. Output never includes manuscript text."
|
||||
)
|
||||
)
|
||||
parser.add_argument("manuscript", help="UTF-8 Markdown manuscript")
|
||||
parser.add_argument("claims", help="UTF-8 CSV claim-evidence registry")
|
||||
parser.add_argument("sources", help="UTF-8 JSON source manifest")
|
||||
return parser
|
||||
|
||||
|
||||
def cli() -> int:
|
||||
args = build_parser().parse_args()
|
||||
sources = load_sources(args.sources)
|
||||
claims, issues = load_claims(args.claims, sources)
|
||||
text = read_text(args.manuscript, {".md", ".markdown"})
|
||||
markdown_issues, used_claims = audit_markdown(text, claims, sources)
|
||||
issues.extend(markdown_issues)
|
||||
for claim_id in sorted(set(claims) - used_claims):
|
||||
issues.append(
|
||||
issue("warning", "CLAIM_NOT_USED_IN_MANUSCRIPT", item_id=claim_id)
|
||||
)
|
||||
return emit_report(
|
||||
TOOL,
|
||||
issues,
|
||||
summary={
|
||||
"claims_registered": len(claims),
|
||||
"claims_used": len(used_claims),
|
||||
"sources_registered": len(sources),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TOOL, cli)
|
||||
408
.agents/skills/scientific-writing/scripts/check_consistency.py
Normal file
408
.agents/skills/scientific-writing/scripts/check_consistency.py
Normal file
@@ -0,0 +1,408 @@
|
||||
"""Check numeric and methods-results consistency in a bounded JSON registry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from _common import (
|
||||
InputError,
|
||||
Issue,
|
||||
emit_report,
|
||||
is_nonempty_string,
|
||||
is_placeholder,
|
||||
issue,
|
||||
read_json,
|
||||
require_list,
|
||||
require_object,
|
||||
run,
|
||||
)
|
||||
|
||||
TOOL = "check_consistency"
|
||||
FACT_ID_RE = re.compile(r"^N[0-9]{3,8}$")
|
||||
METHOD_ID_RE = re.compile(r"^M[0-9]{3,8}$")
|
||||
RESULT_ID_RE = re.compile(r"^R[0-9]{3,8}$")
|
||||
OUTCOME_ID_RE = re.compile(r"^O[0-9]{3,8}$")
|
||||
EVIDENCE_ID_RE = re.compile(r"^E[0-9]{3,8}$")
|
||||
ANALYSIS_INTENT = {"confirmatory", "exploratory", "descriptive"}
|
||||
PROTOCOL_STATUS = {
|
||||
"prespecified",
|
||||
"amended_before_analysis",
|
||||
"post_hoc",
|
||||
"not_applicable",
|
||||
}
|
||||
ROOT_FIELDS = {"schema_version", "numeric_facts", "methods", "results"}
|
||||
FACT_FIELDS = {
|
||||
"fact_id",
|
||||
"concept",
|
||||
"section",
|
||||
"value",
|
||||
"unit",
|
||||
"numerator",
|
||||
"denominator",
|
||||
"sample_size",
|
||||
"analysis_set",
|
||||
"evidence_ids",
|
||||
}
|
||||
METHOD_FIELDS = {
|
||||
"method_id",
|
||||
"name",
|
||||
"analysis_intent",
|
||||
"protocol_status",
|
||||
"outcome_ids",
|
||||
}
|
||||
RESULT_FIELDS = {
|
||||
"result_id",
|
||||
"method_id",
|
||||
"outcome_id",
|
||||
"analysis_intent",
|
||||
"sample_size",
|
||||
"evidence_ids",
|
||||
"reported_sections",
|
||||
}
|
||||
|
||||
|
||||
def _is_number(value: Any) -> bool:
|
||||
return (
|
||||
isinstance(value, (int, float))
|
||||
and not isinstance(value, bool)
|
||||
and math.isfinite(value)
|
||||
)
|
||||
|
||||
|
||||
def _check_fields(
|
||||
value: dict[str, Any],
|
||||
expected: set[str],
|
||||
*,
|
||||
location: str,
|
||||
issues: list[Issue],
|
||||
) -> None:
|
||||
for key in sorted(set(value) - expected):
|
||||
issues.append(
|
||||
issue("error", "UNKNOWN_SCHEMA_FIELD", location=location, item_id=key)
|
||||
)
|
||||
for key in sorted(expected - set(value)):
|
||||
issues.append(
|
||||
issue("error", "MISSING_SCHEMA_FIELD", location=location, item_id=key)
|
||||
)
|
||||
|
||||
|
||||
def _validate_ids(
|
||||
values: Any,
|
||||
*,
|
||||
pattern: re.Pattern[str],
|
||||
location: str,
|
||||
code: str,
|
||||
issues: list[Issue],
|
||||
) -> list[str]:
|
||||
ids = require_list(values, location)
|
||||
valid: list[str] = []
|
||||
for raw_value in ids:
|
||||
if not isinstance(raw_value, str) or not pattern.fullmatch(raw_value):
|
||||
issues.append(issue("error", code, location=location))
|
||||
else:
|
||||
valid.append(raw_value)
|
||||
return valid
|
||||
|
||||
|
||||
def validate_numeric_facts(data: dict[str, Any]) -> tuple[list[Issue], int]:
|
||||
issues: list[Issue] = []
|
||||
facts = require_list(data.get("numeric_facts"), "numeric_facts")
|
||||
seen_ids: set[str] = set()
|
||||
by_concept: dict[
|
||||
tuple[str, str],
|
||||
tuple[float, str, str, int | None, float | None, float | None],
|
||||
] = {}
|
||||
for index, raw_fact in enumerate(facts):
|
||||
fact = require_object(raw_fact, f"numeric_facts[{index}]")
|
||||
location = f"numeric_facts[{index}]"
|
||||
_check_fields(fact, FACT_FIELDS, location=location, issues=issues)
|
||||
fact_id = fact.get("fact_id")
|
||||
if not isinstance(fact_id, str) or not FACT_ID_RE.fullmatch(fact_id):
|
||||
issues.append(issue("error", "INVALID_FACT_ID", location=location))
|
||||
fact_id = None
|
||||
elif fact_id in seen_ids:
|
||||
issues.append(issue("error", "DUPLICATE_FACT_ID", item_id=fact_id))
|
||||
else:
|
||||
seen_ids.add(fact_id)
|
||||
|
||||
concept = fact.get("concept")
|
||||
section = fact.get("section")
|
||||
unit = fact.get("unit")
|
||||
analysis_set = fact.get("analysis_set")
|
||||
for key, value in {
|
||||
"concept": concept,
|
||||
"section": section,
|
||||
"unit": unit,
|
||||
"analysis_set": analysis_set,
|
||||
}.items():
|
||||
if not is_nonempty_string(value) or is_placeholder(value):
|
||||
issues.append(
|
||||
issue("error", "MISSING_FACT_FIELD", location=key, item_id=fact_id)
|
||||
)
|
||||
|
||||
value = fact.get("value")
|
||||
if not _is_number(value):
|
||||
issues.append(issue("error", "INVALID_FACT_VALUE", item_id=fact_id))
|
||||
sample_size = fact.get("sample_size")
|
||||
if sample_size is not None and (
|
||||
not isinstance(sample_size, int)
|
||||
or isinstance(sample_size, bool)
|
||||
or sample_size <= 0
|
||||
):
|
||||
issues.append(issue("error", "INVALID_FACT_SAMPLE_SIZE", item_id=fact_id))
|
||||
|
||||
numerator = fact.get("numerator")
|
||||
denominator = fact.get("denominator")
|
||||
if numerator is not None or denominator is not None:
|
||||
if (
|
||||
not _is_number(numerator)
|
||||
or not _is_number(denominator)
|
||||
or denominator <= 0
|
||||
):
|
||||
issues.append(
|
||||
issue("error", "INVALID_NUMERATOR_DENOMINATOR", item_id=fact_id)
|
||||
)
|
||||
elif numerator > denominator:
|
||||
issues.append(
|
||||
issue("error", "NUMERATOR_EXCEEDS_DENOMINATOR", item_id=fact_id)
|
||||
)
|
||||
elif unit == "percent" and _is_number(value):
|
||||
expected = 100.0 * float(numerator) / float(denominator)
|
||||
if not math.isclose(float(value), expected, rel_tol=0.0, abs_tol=0.05):
|
||||
issues.append(
|
||||
issue("error", "PERCENT_DENOMINATOR_MISMATCH", item_id=fact_id)
|
||||
)
|
||||
|
||||
evidence_ids = _validate_ids(
|
||||
fact.get("evidence_ids"),
|
||||
pattern=EVIDENCE_ID_RE,
|
||||
location=f"{location}.evidence_ids",
|
||||
code="INVALID_FACT_EVIDENCE_ID",
|
||||
issues=issues,
|
||||
)
|
||||
if not evidence_ids:
|
||||
issues.append(issue("error", "FACT_WITHOUT_EVIDENCE", item_id=fact_id))
|
||||
|
||||
if (
|
||||
is_nonempty_string(concept)
|
||||
and is_nonempty_string(analysis_set)
|
||||
and is_nonempty_string(unit)
|
||||
and _is_number(value)
|
||||
and is_nonempty_string(section)
|
||||
):
|
||||
key = (str(concept), str(analysis_set))
|
||||
prior = by_concept.get(key)
|
||||
current = (
|
||||
float(value),
|
||||
str(unit),
|
||||
str(section),
|
||||
(
|
||||
sample_size
|
||||
if isinstance(sample_size, int)
|
||||
and not isinstance(sample_size, bool)
|
||||
and sample_size > 0
|
||||
else None
|
||||
),
|
||||
float(numerator) if _is_number(numerator) else None,
|
||||
float(denominator) if _is_number(denominator) else None,
|
||||
)
|
||||
if prior is not None:
|
||||
if prior[1] != current[1]:
|
||||
issues.append(issue("error", "UNIT_MISMATCH", item_id=fact_id))
|
||||
elif not math.isclose(prior[0], current[0], rel_tol=0.0, abs_tol=1e-12):
|
||||
issues.append(
|
||||
issue("error", "CROSS_SECTION_VALUE_MISMATCH", item_id=fact_id)
|
||||
)
|
||||
if prior[3] != current[3]:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"CROSS_SECTION_SAMPLE_SIZE_MISMATCH",
|
||||
item_id=fact_id,
|
||||
)
|
||||
)
|
||||
if prior[4:] != current[4:]:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"CROSS_SECTION_DENOMINATOR_MISMATCH",
|
||||
item_id=fact_id,
|
||||
)
|
||||
)
|
||||
else:
|
||||
by_concept[key] = current
|
||||
return issues, len(facts)
|
||||
|
||||
|
||||
def validate_methods_results(data: dict[str, Any]) -> tuple[list[Issue], int, int]:
|
||||
issues: list[Issue] = []
|
||||
methods: dict[str, dict[str, Any]] = {}
|
||||
expected_outcomes: dict[str, set[str]] = {}
|
||||
for index, raw_method in enumerate(require_list(data.get("methods"), "methods")):
|
||||
method = require_object(raw_method, f"methods[{index}]")
|
||||
_check_fields(
|
||||
method,
|
||||
METHOD_FIELDS,
|
||||
location=f"methods[{index}]",
|
||||
issues=issues,
|
||||
)
|
||||
method_id = method.get("method_id")
|
||||
if not isinstance(method_id, str) or not METHOD_ID_RE.fullmatch(method_id):
|
||||
issues.append(
|
||||
issue("error", "INVALID_METHOD_ID", location=f"methods[{index}]")
|
||||
)
|
||||
continue
|
||||
if method_id in methods:
|
||||
issues.append(issue("error", "DUPLICATE_METHOD_ID", item_id=method_id))
|
||||
continue
|
||||
methods[method_id] = method
|
||||
if not is_nonempty_string(method.get("name")) or is_placeholder(
|
||||
method.get("name")
|
||||
):
|
||||
issues.append(issue("error", "MISSING_METHOD_NAME", item_id=method_id))
|
||||
if method.get("analysis_intent") not in ANALYSIS_INTENT:
|
||||
issues.append(
|
||||
issue("error", "INVALID_METHOD_ANALYSIS_INTENT", item_id=method_id)
|
||||
)
|
||||
if method.get("protocol_status") not in PROTOCOL_STATUS:
|
||||
issues.append(issue("error", "INVALID_PROTOCOL_STATUS", item_id=method_id))
|
||||
outcomes = set(
|
||||
_validate_ids(
|
||||
method.get("outcome_ids"),
|
||||
pattern=OUTCOME_ID_RE,
|
||||
location=f"methods[{index}].outcome_ids",
|
||||
code="INVALID_METHOD_OUTCOME_ID",
|
||||
issues=issues,
|
||||
)
|
||||
)
|
||||
if not outcomes:
|
||||
issues.append(issue("error", "METHOD_WITHOUT_OUTCOME", item_id=method_id))
|
||||
expected_outcomes[method_id] = outcomes
|
||||
|
||||
results = require_list(data.get("results"), "results")
|
||||
seen_result_ids: set[str] = set()
|
||||
observed_outcomes: dict[str, set[str]] = {method_id: set() for method_id in methods}
|
||||
for index, raw_result in enumerate(results):
|
||||
result = require_object(raw_result, f"results[{index}]")
|
||||
_check_fields(
|
||||
result,
|
||||
RESULT_FIELDS,
|
||||
location=f"results[{index}]",
|
||||
issues=issues,
|
||||
)
|
||||
result_id = result.get("result_id")
|
||||
if not isinstance(result_id, str) or not RESULT_ID_RE.fullmatch(result_id):
|
||||
issues.append(
|
||||
issue("error", "INVALID_RESULT_ID", location=f"results[{index}]")
|
||||
)
|
||||
result_id = None
|
||||
elif result_id in seen_result_ids:
|
||||
issues.append(issue("error", "DUPLICATE_RESULT_ID", item_id=result_id))
|
||||
else:
|
||||
seen_result_ids.add(result_id)
|
||||
|
||||
method_id = result.get("method_id")
|
||||
outcome_id = result.get("outcome_id")
|
||||
if method_id not in methods:
|
||||
issues.append(
|
||||
issue("error", "RESULT_WITHOUT_DECLARED_METHOD", item_id=result_id)
|
||||
)
|
||||
else:
|
||||
if not isinstance(outcome_id, str) or not OUTCOME_ID_RE.fullmatch(
|
||||
outcome_id
|
||||
):
|
||||
issues.append(
|
||||
issue("error", "INVALID_RESULT_OUTCOME_ID", item_id=result_id)
|
||||
)
|
||||
else:
|
||||
observed_outcomes[method_id].add(outcome_id)
|
||||
if outcome_id not in expected_outcomes[method_id]:
|
||||
issues.append(
|
||||
issue("error", "UNDECLARED_RESULT_OUTCOME", item_id=result_id)
|
||||
)
|
||||
if result.get("analysis_intent") != methods[method_id].get(
|
||||
"analysis_intent"
|
||||
):
|
||||
issues.append(
|
||||
issue("error", "ANALYSIS_INTENT_MISMATCH", item_id=result_id)
|
||||
)
|
||||
|
||||
sample_size = result.get("sample_size")
|
||||
if (
|
||||
not isinstance(sample_size, int)
|
||||
or isinstance(sample_size, bool)
|
||||
or sample_size <= 0
|
||||
):
|
||||
issues.append(
|
||||
issue("error", "INVALID_RESULT_SAMPLE_SIZE", item_id=result_id)
|
||||
)
|
||||
evidence_ids = _validate_ids(
|
||||
result.get("evidence_ids"),
|
||||
pattern=EVIDENCE_ID_RE,
|
||||
location=f"results[{index}].evidence_ids",
|
||||
code="INVALID_RESULT_EVIDENCE_ID",
|
||||
issues=issues,
|
||||
)
|
||||
if not evidence_ids:
|
||||
issues.append(issue("error", "RESULT_WITHOUT_EVIDENCE", item_id=result_id))
|
||||
sections = result.get("reported_sections")
|
||||
if (
|
||||
not isinstance(sections, list)
|
||||
or not sections
|
||||
or not all(is_nonempty_string(value) for value in sections)
|
||||
):
|
||||
issues.append(
|
||||
issue("error", "RESULT_WITHOUT_REPORTED_SECTION", item_id=result_id)
|
||||
)
|
||||
|
||||
for method_id, outcomes in expected_outcomes.items():
|
||||
for outcome_id in sorted(outcomes - observed_outcomes.get(method_id, set())):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"METHOD_OUTCOME_WITHOUT_RESULT",
|
||||
location=method_id,
|
||||
item_id=outcome_id,
|
||||
)
|
||||
)
|
||||
return issues, len(methods), len(results)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Check a local JSON registry for repeated numeric values, units, "
|
||||
"denominators, sample sizes, and declared methods-results mappings."
|
||||
)
|
||||
)
|
||||
parser.add_argument("registry", help="UTF-8 JSON consistency registry")
|
||||
return parser
|
||||
|
||||
|
||||
def cli() -> int:
|
||||
args = build_parser().parse_args()
|
||||
data = require_object(read_json(args.registry), "consistency_registry")
|
||||
root_issues: list[Issue] = []
|
||||
_check_fields(data, ROOT_FIELDS, location="root", issues=root_issues)
|
||||
if data.get("schema_version") != "1.0":
|
||||
raise InputError("unsupported consistency registry version")
|
||||
issues, fact_count = validate_numeric_facts(data)
|
||||
issues.extend(root_issues)
|
||||
method_issues, method_count, result_count = validate_methods_results(data)
|
||||
issues.extend(method_issues)
|
||||
return emit_report(
|
||||
TOOL,
|
||||
issues,
|
||||
summary={
|
||||
"numeric_facts": fact_count,
|
||||
"methods": method_count,
|
||||
"results": result_count,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TOOL, cli)
|
||||
219
.agents/skills/scientific-writing/scripts/check_references.py
Normal file
219
.agents/skills/scientific-writing/scripts/check_references.py
Normal file
@@ -0,0 +1,219 @@
|
||||
"""Check local reference identifiers and duplicates without resolving them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any
|
||||
|
||||
from _common import (
|
||||
InputError,
|
||||
Issue,
|
||||
emit_report,
|
||||
is_nonempty_string,
|
||||
issue,
|
||||
read_json,
|
||||
require_list,
|
||||
require_object,
|
||||
run,
|
||||
)
|
||||
from validate_manifest import validate_source_manifest
|
||||
|
||||
TOOL = "check_references"
|
||||
EVIDENCE_ID_RE = re.compile(r"^E[0-9]{3,8}$")
|
||||
DOI_RE = re.compile(r"^10\.[0-9]{4,9}/\S+$", re.IGNORECASE)
|
||||
PMID_RE = re.compile(r"^[1-9][0-9]{0,8}$")
|
||||
PMCID_RE = re.compile(r"^PMC[1-9][0-9]{0,8}$", re.IGNORECASE)
|
||||
URL_RE = re.compile(r"^https?://[^\s]+$", re.IGNORECASE)
|
||||
|
||||
|
||||
def normalize_doi(value: str) -> str:
|
||||
normalized = value.strip().lower()
|
||||
for prefix in ("https://doi.org/", "http://doi.org/", "doi:"):
|
||||
if normalized.startswith(prefix):
|
||||
normalized = normalized[len(prefix) :]
|
||||
break
|
||||
return normalized.rstrip(".,;")
|
||||
|
||||
|
||||
def normalize_title(value: str) -> str:
|
||||
decomposed = unicodedata.normalize("NFKD", value).casefold()
|
||||
return " ".join(re.findall(r"[a-z0-9]+", decomposed))
|
||||
|
||||
|
||||
def normalize_isbn(value: str) -> str:
|
||||
return re.sub(r"[^0-9Xx]", "", value)
|
||||
|
||||
|
||||
def valid_isbn(value: str) -> bool:
|
||||
normalized = normalize_isbn(value)
|
||||
if len(normalized) == 10:
|
||||
if not re.fullmatch(r"[0-9]{9}[0-9Xx]", normalized):
|
||||
return False
|
||||
total = sum(
|
||||
(10 - index) * (10 if char.lower() == "x" else int(char))
|
||||
for index, char in enumerate(normalized)
|
||||
)
|
||||
return total % 11 == 0
|
||||
if len(normalized) == 13 and normalized.isdigit():
|
||||
total = sum(
|
||||
int(char) * (1 if index % 2 == 0 else 3)
|
||||
for index, char in enumerate(normalized)
|
||||
)
|
||||
return total % 10 == 0
|
||||
return False
|
||||
|
||||
|
||||
def _record_duplicate(
|
||||
seen: dict[str, str],
|
||||
normalized: str,
|
||||
evidence_id: str,
|
||||
code: str,
|
||||
issues: list[Issue],
|
||||
) -> None:
|
||||
if not normalized:
|
||||
return
|
||||
prior = seen.get(normalized)
|
||||
if prior is not None and prior != evidence_id:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
code,
|
||||
location=prior,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
else:
|
||||
seen[normalized] = evidence_id
|
||||
|
||||
|
||||
def check_sources(data: dict[str, Any]) -> tuple[list[Issue], int]:
|
||||
issues = validate_source_manifest(data, require_verified=False)
|
||||
sources = require_list(data.get("sources"), "sources")
|
||||
evidence_ids: set[str] = set()
|
||||
seen_dois: dict[str, str] = {}
|
||||
seen_pmids: dict[str, str] = {}
|
||||
seen_pmcids: dict[str, str] = {}
|
||||
seen_isbns: dict[str, str] = {}
|
||||
seen_titles: dict[str, str] = {}
|
||||
|
||||
for index, raw_source in enumerate(sources):
|
||||
source = require_object(raw_source, f"sources[{index}]")
|
||||
evidence_id = source.get("evidence_id")
|
||||
if not isinstance(evidence_id, str) or not EVIDENCE_ID_RE.fullmatch(
|
||||
evidence_id
|
||||
):
|
||||
issues.append(
|
||||
issue("error", "INVALID_EVIDENCE_ID", location=f"sources[{index}]")
|
||||
)
|
||||
continue
|
||||
if evidence_id in evidence_ids:
|
||||
issues.append(issue("error", "DUPLICATE_EVIDENCE_ID", item_id=evidence_id))
|
||||
continue
|
||||
evidence_ids.add(evidence_id)
|
||||
|
||||
title = source.get("title")
|
||||
if is_nonempty_string(title):
|
||||
_record_duplicate(
|
||||
seen_titles,
|
||||
normalize_title(str(title)),
|
||||
evidence_id,
|
||||
"POSSIBLE_DUPLICATE_TITLE",
|
||||
issues,
|
||||
)
|
||||
|
||||
identifiers = require_object(
|
||||
source.get("identifiers"), f"sources[{index}].identifiers"
|
||||
)
|
||||
doi = identifiers.get("doi")
|
||||
if is_nonempty_string(doi):
|
||||
normalized_doi = normalize_doi(str(doi))
|
||||
if not DOI_RE.fullmatch(normalized_doi):
|
||||
issues.append(issue("error", "MALFORMED_DOI", item_id=evidence_id))
|
||||
else:
|
||||
_record_duplicate(
|
||||
seen_dois,
|
||||
normalized_doi,
|
||||
evidence_id,
|
||||
"DUPLICATE_DOI",
|
||||
issues,
|
||||
)
|
||||
|
||||
pmid = identifiers.get("pmid")
|
||||
if is_nonempty_string(pmid):
|
||||
normalized_pmid = str(pmid).strip()
|
||||
if not PMID_RE.fullmatch(normalized_pmid):
|
||||
issues.append(issue("error", "MALFORMED_PMID", item_id=evidence_id))
|
||||
else:
|
||||
_record_duplicate(
|
||||
seen_pmids,
|
||||
normalized_pmid,
|
||||
evidence_id,
|
||||
"DUPLICATE_PMID",
|
||||
issues,
|
||||
)
|
||||
|
||||
pmcid = identifiers.get("pmcid")
|
||||
if is_nonempty_string(pmcid):
|
||||
normalized_pmcid = str(pmcid).strip().upper()
|
||||
if not PMCID_RE.fullmatch(normalized_pmcid):
|
||||
issues.append(issue("error", "MALFORMED_PMCID", item_id=evidence_id))
|
||||
else:
|
||||
_record_duplicate(
|
||||
seen_pmcids,
|
||||
normalized_pmcid,
|
||||
evidence_id,
|
||||
"DUPLICATE_PMCID",
|
||||
issues,
|
||||
)
|
||||
|
||||
isbn = identifiers.get("isbn")
|
||||
if is_nonempty_string(isbn):
|
||||
normalized_isbn = normalize_isbn(str(isbn))
|
||||
if not valid_isbn(normalized_isbn):
|
||||
issues.append(issue("error", "MALFORMED_ISBN", item_id=evidence_id))
|
||||
else:
|
||||
_record_duplicate(
|
||||
seen_isbns,
|
||||
normalized_isbn.upper(),
|
||||
evidence_id,
|
||||
"DUPLICATE_ISBN",
|
||||
issues,
|
||||
)
|
||||
|
||||
url = identifiers.get("url")
|
||||
if is_nonempty_string(url) and not URL_RE.fullmatch(str(url).strip()):
|
||||
issues.append(issue("error", "MALFORMED_URL", item_id=evidence_id))
|
||||
|
||||
if not any(is_nonempty_string(value) for value in identifiers.values()):
|
||||
issues.append(
|
||||
issue("warning", "NO_IDENTIFIER_TO_CHECK", item_id=evidence_id)
|
||||
)
|
||||
return issues, len(sources)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Validate DOI, PMID, PMCID, ISBN, and URL syntax and flag duplicates "
|
||||
"in a local source manifest. No identifier is resolved over a network."
|
||||
)
|
||||
)
|
||||
parser.add_argument("sources", help="UTF-8 JSON source manifest")
|
||||
return parser
|
||||
|
||||
|
||||
def cli() -> int:
|
||||
args = build_parser().parse_args()
|
||||
data = require_object(read_json(args.sources), "source_manifest")
|
||||
if data.get("schema_version") != "1.0":
|
||||
raise InputError("unsupported source-manifest version")
|
||||
issues, count = check_sources(data)
|
||||
return emit_report(
|
||||
TOOL, issues, summary={"sources_checked": count, "network_used": False}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TOOL, cli)
|
||||
171
.agents/skills/scientific-writing/scripts/lint_manuscript.py
Normal file
171
.agents/skills/scientific-writing/scripts/lint_manuscript.py
Normal file
@@ -0,0 +1,171 @@
|
||||
"""Lint manuscript Markdown for placeholders, language risks, and sensitive content."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from _common import (
|
||||
Issue,
|
||||
emit_report,
|
||||
issue,
|
||||
read_json,
|
||||
read_text,
|
||||
require_object,
|
||||
run,
|
||||
)
|
||||
|
||||
TOOL = "lint_manuscript"
|
||||
PLACEHOLDER_PATTERNS = (
|
||||
re.compile(r"\[\[\s*TODO\b", re.IGNORECASE),
|
||||
re.compile(r"\b(?:TODO|TBD|TK)\b", re.IGNORECASE),
|
||||
re.compile(r"\[\s*(?:insert|add|describe|replace)[^\]]*\]", re.IGNORECASE),
|
||||
re.compile(r"\blorem ipsum\b", re.IGNORECASE),
|
||||
re.compile(r"\bX{4,}\b"),
|
||||
)
|
||||
SENSITIVE_PATTERNS = (
|
||||
re.compile(r"\b(?:MRN|medical record number)\s*[:#]", re.IGNORECASE),
|
||||
re.compile(r"\b(?:SSN|social security number)\s*[:#]", re.IGNORECASE),
|
||||
re.compile(r"\b(?:DOB|date of birth)\s*[:#]", re.IGNORECASE),
|
||||
re.compile(r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", re.IGNORECASE),
|
||||
re.compile(
|
||||
r"\b(?:PHI|protected health information|patient name|participant name)\b",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
re.compile(r"\b(?:confidential|proprietary|trade secret)\b", re.IGNORECASE),
|
||||
re.compile(
|
||||
r"\b(?:peer[- ]review material|unpublished manuscript)\b", re.IGNORECASE
|
||||
),
|
||||
)
|
||||
DECLARATION_RE = re.compile(
|
||||
r"\b(?:ethics (?:approval|committee)|IRB|informed consent|funded by|"
|
||||
r"conflict[s]? of interest|data (?:are|is) available|code (?:is|are) available)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
OVERSTATEMENT_RE = re.compile(
|
||||
r"\b(?:proves?|definitively|guarantees?|no limitations|universally|"
|
||||
r"highly significant|no effect)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
CAUSAL_RE = re.compile(
|
||||
r"\b(?:causes?|caused|proves?|demonstrates? that)\b", re.IGNORECASE
|
||||
)
|
||||
CLAIM_MARKER_RE = re.compile(r"\[claim:C[0-9]{3,8}\]")
|
||||
EVIDENCE_MARKER_RE = re.compile(r"(?:\[evidence:E[0-9]|\[@E[0-9])")
|
||||
OBSERVATIONAL_DESIGNS = {
|
||||
"observational",
|
||||
"cohort",
|
||||
"case_control",
|
||||
"cross_sectional",
|
||||
"routinely_collected_health_data",
|
||||
}
|
||||
|
||||
|
||||
def load_manifest(path: str | None) -> tuple[dict[str, Any] | None, list[Issue]]:
|
||||
if path is None:
|
||||
return None, [
|
||||
issue(
|
||||
"warning",
|
||||
"CONFIDENTIALITY_GATE_NOT_CHECKED",
|
||||
location="manifest",
|
||||
)
|
||||
]
|
||||
data = require_object(read_json(path), "manuscript_manifest")
|
||||
issues: list[Issue] = []
|
||||
review = require_object(
|
||||
data.get("confidentiality_review"), "confidentiality_review"
|
||||
)
|
||||
if review.get("completed") is not True:
|
||||
issues.append(
|
||||
issue("error", "CONFIDENTIALITY_REVIEW_INCOMPLETE", location="manifest")
|
||||
)
|
||||
if review.get("policy_checked") is not True:
|
||||
issues.append(issue("error", "POLICY_REVIEW_INCOMPLETE", location="manifest"))
|
||||
return data, issues
|
||||
|
||||
|
||||
def lint_text(text: str, manifest: dict[str, Any] | None) -> list[Issue]:
|
||||
issues: list[Issue] = []
|
||||
study_design = str((manifest or {}).get("study_design", "")).casefold()
|
||||
submission_ready = (manifest or {}).get("submission_ready") is True
|
||||
in_fence = False
|
||||
for line_number, line in enumerate(text.splitlines(), start=1):
|
||||
stripped = line.strip()
|
||||
if stripped.startswith(("```", "~~~")):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
location = f"line:{line_number}"
|
||||
for pattern in PLACEHOLDER_PATTERNS:
|
||||
if pattern.search(line):
|
||||
issues.append(
|
||||
issue("error", "UNRESOLVED_PLACEHOLDER", location=location)
|
||||
)
|
||||
break
|
||||
for pattern in SENSITIVE_PATTERNS:
|
||||
if pattern.search(line):
|
||||
issues.append(
|
||||
issue("warning", "POTENTIAL_RESTRICTED_CONTENT", location=location)
|
||||
)
|
||||
break
|
||||
if DECLARATION_RE.search(line) and not (
|
||||
CLAIM_MARKER_RE.search(line) and EVIDENCE_MARKER_RE.search(line)
|
||||
):
|
||||
issues.append(
|
||||
issue(
|
||||
"error", "DECLARATION_WITHOUT_EVIDENCE_MARKERS", location=location
|
||||
)
|
||||
)
|
||||
if OVERSTATEMENT_RE.search(line):
|
||||
issues.append(
|
||||
issue("warning", "POTENTIAL_OVERSTATEMENT", location=location)
|
||||
)
|
||||
if study_design in OBSERVATIONAL_DESIGNS and CAUSAL_RE.search(line):
|
||||
issues.append(
|
||||
issue(
|
||||
"warning",
|
||||
"CAUSAL_LANGUAGE_FOR_OBSERVATIONAL_DESIGN",
|
||||
location=location,
|
||||
)
|
||||
)
|
||||
if submission_ready and "NOT FOR SUBMISSION" in line.upper():
|
||||
issues.append(
|
||||
issue("error", "DRAFT_BANNER_ON_READY_MANUSCRIPT", location=location)
|
||||
)
|
||||
if not text.strip():
|
||||
issues.append(issue("error", "EMPTY_MANUSCRIPT", location="document"))
|
||||
return issues
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Lint local Markdown without echoing source text. Flags unresolved "
|
||||
"placeholders, risky declarations, possible sensitive content, and "
|
||||
"language that needs human review."
|
||||
)
|
||||
)
|
||||
parser.add_argument("manuscript", help="UTF-8 Markdown manuscript")
|
||||
parser.add_argument(
|
||||
"--manifest",
|
||||
help="optional UTF-8 JSON manuscript manifest with confidentiality gates",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def cli() -> int:
|
||||
args = build_parser().parse_args()
|
||||
manifest, issues = load_manifest(args.manifest)
|
||||
text = read_text(args.manuscript, {".md", ".markdown"})
|
||||
issues.extend(lint_text(text, manifest))
|
||||
return emit_report(
|
||||
TOOL,
|
||||
issues,
|
||||
summary={"lines_checked": len(text.splitlines()), "raw_text_echoed": False},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TOOL, cli)
|
||||
143
.agents/skills/scientific-writing/scripts/scaffold_manuscript.py
Normal file
143
.agents/skills/scientific-writing/scripts/scaffold_manuscript.py
Normal file
@@ -0,0 +1,143 @@
|
||||
"""Generate a local, explicitly incomplete manuscript workspace."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from _common import (
|
||||
InputError,
|
||||
emit_report,
|
||||
read_json,
|
||||
read_text,
|
||||
require_object,
|
||||
run,
|
||||
write_new_text,
|
||||
)
|
||||
|
||||
TOOL = "scaffold_manuscript"
|
||||
ASSET_DIR = Path(__file__).resolve().parents[1] / "assets"
|
||||
DOCUMENT_ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9._-]{1,63}$")
|
||||
GUIDELINE_ID_RE = re.compile(r"^[a-z][a-z0-9.-]{1,63}$")
|
||||
TEMPLATE_FILES = {
|
||||
"manuscript.md": "manuscript_scaffold.md",
|
||||
"claims.csv": "claim_evidence_template.csv",
|
||||
"source_manifest.json": "source_manifest_template.json",
|
||||
"consistency_manifest.json": "consistency_manifest_template.json",
|
||||
"authorship.json": "authorship_template.json",
|
||||
}
|
||||
|
||||
|
||||
def _json_text(value: Any) -> str:
|
||||
return json.dumps(value, indent=2, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
def _prepare_manifest(
|
||||
*,
|
||||
document_id: str,
|
||||
study_design: str,
|
||||
guidelines: list[str],
|
||||
) -> str:
|
||||
data = require_object(
|
||||
read_json(ASSET_DIR / "manuscript_manifest_template.json"),
|
||||
"manuscript_manifest_template",
|
||||
)
|
||||
data["document_id"] = document_id
|
||||
data["study_design"] = study_design
|
||||
data["reporting_guidelines"] = guidelines
|
||||
return _json_text(data)
|
||||
|
||||
|
||||
def _prepare_coverage(guidelines: list[str]) -> str:
|
||||
data = require_object(
|
||||
read_json(ASSET_DIR / "reporting_coverage_template.json"),
|
||||
"reporting_coverage_template",
|
||||
)
|
||||
data["guideline_id"] = guidelines[0] if guidelines else "[[TODO:guideline-id]]"
|
||||
return _json_text(data)
|
||||
|
||||
|
||||
def generate(
|
||||
output_dir: Path,
|
||||
*,
|
||||
document_id: str,
|
||||
study_design: str,
|
||||
guidelines: list[str],
|
||||
) -> list[str]:
|
||||
if output_dir.exists() or output_dir.is_symlink():
|
||||
raise InputError("output directory already exists; refusing to overwrite")
|
||||
parent = output_dir.parent
|
||||
if not parent.is_dir() or parent.is_symlink():
|
||||
raise InputError("output parent must be an existing regular directory")
|
||||
|
||||
prepared: dict[str, str] = {
|
||||
destination: read_text(ASSET_DIR / source, {Path(source).suffix})
|
||||
for destination, source in TEMPLATE_FILES.items()
|
||||
}
|
||||
prepared["manuscript_manifest.json"] = _prepare_manifest(
|
||||
document_id=document_id,
|
||||
study_design=study_design,
|
||||
guidelines=guidelines,
|
||||
)
|
||||
prepared["reporting_coverage.json"] = _prepare_coverage(guidelines)
|
||||
|
||||
output_dir.mkdir(mode=0o700)
|
||||
for filename in sorted(prepared):
|
||||
write_new_text(
|
||||
output_dir / filename,
|
||||
prepared[filename],
|
||||
{Path(filename).suffix},
|
||||
)
|
||||
return sorted(prepared)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Create a deterministic local manuscript workspace. Generated files "
|
||||
"are marked incomplete and must pass all validators before submission."
|
||||
)
|
||||
)
|
||||
parser.add_argument("--output-dir", required=True, help="new directory to create")
|
||||
parser.add_argument("--document-id", required=True)
|
||||
parser.add_argument("--study-design", required=True)
|
||||
parser.add_argument(
|
||||
"--guideline",
|
||||
action="append",
|
||||
default=[],
|
||||
help="candidate reporting-guideline ID; repeat as needed",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def cli() -> int:
|
||||
args = build_parser().parse_args()
|
||||
if not DOCUMENT_ID_RE.fullmatch(args.document_id):
|
||||
raise InputError("document-id must be 2-64 safe identifier characters")
|
||||
if not DOCUMENT_ID_RE.fullmatch(args.study_design):
|
||||
raise InputError("study-design must be a safe identifier")
|
||||
guidelines = sorted(set(args.guideline))
|
||||
if any(not GUIDELINE_ID_RE.fullmatch(value) for value in guidelines):
|
||||
raise InputError("guideline IDs must be safe lowercase identifiers")
|
||||
files = generate(
|
||||
Path(args.output_dir),
|
||||
document_id=args.document_id,
|
||||
study_design=args.study_design,
|
||||
guidelines=guidelines,
|
||||
)
|
||||
return emit_report(
|
||||
TOOL,
|
||||
[],
|
||||
summary={
|
||||
"files_created": files,
|
||||
"submission_ready": False,
|
||||
"overwrites": False,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TOOL, cli)
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Select reporting guidance and check non-scoring coverage metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from _common import (
|
||||
InputError,
|
||||
Issue,
|
||||
emit_report,
|
||||
is_nonempty_string,
|
||||
issue,
|
||||
read_json,
|
||||
require_list,
|
||||
require_object,
|
||||
run,
|
||||
)
|
||||
|
||||
TOOL = "select_reporting_guidelines"
|
||||
REGISTRY_PATH = (
|
||||
Path(__file__).resolve().parents[1] / "assets" / "reporting_guidelines.json"
|
||||
)
|
||||
DISCLAIMER = (
|
||||
"Selection and coverage are non-scoring aids. They do not reproduce an official "
|
||||
"checklist, appraise study quality, certify compliance, or replace the current "
|
||||
"guideline and target-journal instructions."
|
||||
)
|
||||
|
||||
|
||||
def load_registry() -> dict[str, dict[str, Any]]:
|
||||
root = require_object(read_json(REGISTRY_PATH), "registry")
|
||||
if root.get("schema_version") != "1.0":
|
||||
raise InputError("unsupported reporting-guideline registry version")
|
||||
raw_items = require_list(root.get("guidelines"), "guidelines")
|
||||
registry: dict[str, dict[str, Any]] = {}
|
||||
for raw_item in raw_items:
|
||||
item = require_object(raw_item, "guideline")
|
||||
guideline_id = item.get("id")
|
||||
if not is_nonempty_string(guideline_id) or guideline_id in registry:
|
||||
raise InputError("registry guideline IDs must be non-empty and unique")
|
||||
registry[guideline_id] = item
|
||||
return registry
|
||||
|
||||
|
||||
def _condition_matches(item: dict[str, Any], args: argparse.Namespace) -> bool:
|
||||
conditions = require_object(item.get("conditions", {}), "conditions")
|
||||
for flag in ("ai", "llm", "routinely_collected", "qualitative_component"):
|
||||
required = conditions.get(flag)
|
||||
if required is True and not getattr(args, flag):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def select_guidelines(
|
||||
registry: dict[str, dict[str, Any]],
|
||||
args: argparse.Namespace,
|
||||
) -> tuple[list[str], list[str], list[Issue]]:
|
||||
primary: list[str] = []
|
||||
extensions: list[str] = []
|
||||
issues: list[Issue] = []
|
||||
for guideline_id, item in registry.items():
|
||||
designs = require_list(
|
||||
item.get("study_designs"), f"{guideline_id}.study_designs"
|
||||
)
|
||||
if args.study_design not in designs:
|
||||
continue
|
||||
if bool(item.get("protocol")) != bool(args.protocol):
|
||||
continue
|
||||
if not _condition_matches(item, args):
|
||||
continue
|
||||
if item.get("role") == "primary":
|
||||
primary.append(guideline_id)
|
||||
elif item.get("role") == "extension":
|
||||
extensions.append(guideline_id)
|
||||
|
||||
if not primary:
|
||||
issues.append(
|
||||
issue("warning", "NO_PRIMARY_LOCAL_MATCH", item_id=args.study_design)
|
||||
)
|
||||
if args.llm and not args.ai:
|
||||
issues.append(issue("error", "LLM_REQUIRES_AI_FLAG", location="arguments"))
|
||||
return sorted(primary), sorted(extensions), issues
|
||||
|
||||
|
||||
def check_coverage(
|
||||
registry: dict[str, dict[str, Any]],
|
||||
coverage_path: str,
|
||||
) -> tuple[list[Issue], dict[str, Any]]:
|
||||
data = require_object(read_json(coverage_path), "coverage")
|
||||
if data.get("schema_version") != "1.0":
|
||||
raise InputError("unsupported reporting-coverage schema version")
|
||||
guideline_id = data.get("guideline_id")
|
||||
if guideline_id not in registry:
|
||||
raise InputError("coverage guideline_id is not in the bundled registry")
|
||||
guideline = registry[guideline_id]
|
||||
expected = {
|
||||
item["id"]: item
|
||||
for item in (
|
||||
require_object(raw, "coverage_topic")
|
||||
for raw in require_list(guideline.get("coverage_topics"), "coverage_topics")
|
||||
)
|
||||
}
|
||||
|
||||
issues: list[Issue] = []
|
||||
observed: dict[str, dict[str, Any]] = {}
|
||||
for index, raw_item in enumerate(require_list(data.get("items"), "items")):
|
||||
item = require_object(raw_item, f"items[{index}]")
|
||||
topic_id = item.get("topic_id")
|
||||
if topic_id not in expected:
|
||||
issues.append(
|
||||
issue("error", "UNKNOWN_COVERAGE_TOPIC", location=f"items[{index}]")
|
||||
)
|
||||
continue
|
||||
if topic_id in observed:
|
||||
issues.append(
|
||||
issue("error", "DUPLICATE_COVERAGE_TOPIC", item_id=str(topic_id))
|
||||
)
|
||||
continue
|
||||
observed[str(topic_id)] = item
|
||||
status = item.get("status")
|
||||
if status not in {"addressed", "not_applicable", "missing"}:
|
||||
issues.append(
|
||||
issue("error", "INVALID_COVERAGE_STATUS", item_id=str(topic_id))
|
||||
)
|
||||
if status == "addressed":
|
||||
locations = item.get("locations")
|
||||
if (
|
||||
not isinstance(locations, list)
|
||||
or not locations
|
||||
or not all(is_nonempty_string(value) for value in locations)
|
||||
):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"ADDRESSED_TOPIC_WITHOUT_LOCATION",
|
||||
item_id=str(topic_id),
|
||||
)
|
||||
)
|
||||
if status == "not_applicable" and not is_nonempty_string(item.get("rationale")):
|
||||
issues.append(
|
||||
issue(
|
||||
"error", "NOT_APPLICABLE_WITHOUT_RATIONALE", item_id=str(topic_id)
|
||||
)
|
||||
)
|
||||
if status == "missing":
|
||||
issues.append(
|
||||
issue("error", "COVERAGE_TOPIC_MISSING", item_id=str(topic_id))
|
||||
)
|
||||
|
||||
for topic_id in sorted(set(expected) - set(observed)):
|
||||
issues.append(issue("error", "COVERAGE_TOPIC_NOT_RECORDED", item_id=topic_id))
|
||||
|
||||
summary = {
|
||||
"guideline_id": guideline_id,
|
||||
"topics_expected": len(expected),
|
||||
"topics_recorded": len(observed),
|
||||
"coverage_status": (
|
||||
"incomplete"
|
||||
if any(item.severity == "error" for item in issues)
|
||||
else "all_bundled_topics_addressed"
|
||||
),
|
||||
"disclaimer": DISCLAIMER,
|
||||
}
|
||||
return issues, summary
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Use the bundled offline registry to select candidate reporting guidance "
|
||||
"or validate a non-scoring coverage record."
|
||||
)
|
||||
)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
select_parser = subparsers.add_parser(
|
||||
"select",
|
||||
help="select candidate guidelines from study metadata",
|
||||
)
|
||||
select_parser.add_argument("--study-design", required=True)
|
||||
select_parser.add_argument("--protocol", action="store_true")
|
||||
select_parser.add_argument("--ai", action="store_true")
|
||||
select_parser.add_argument("--llm", action="store_true")
|
||||
select_parser.add_argument("--routinely-collected", action="store_true")
|
||||
select_parser.add_argument("--qualitative-component", action="store_true")
|
||||
|
||||
check_parser = subparsers.add_parser(
|
||||
"check",
|
||||
help="validate high-level coverage metadata",
|
||||
)
|
||||
check_parser.add_argument("coverage", help="UTF-8 JSON coverage record")
|
||||
return parser
|
||||
|
||||
|
||||
def cli() -> int:
|
||||
args = build_parser().parse_args()
|
||||
registry = load_registry()
|
||||
if args.command == "select":
|
||||
primary, extensions, issues = select_guidelines(registry, args)
|
||||
summary = {
|
||||
"study_design": args.study_design,
|
||||
"primary": primary,
|
||||
"extensions": extensions,
|
||||
"disclaimer": DISCLAIMER,
|
||||
}
|
||||
else:
|
||||
issues, summary = check_coverage(registry, args.coverage)
|
||||
return emit_report(TOOL, issues, summary=summary)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TOOL, cli)
|
||||
324
.agents/skills/scientific-writing/scripts/validate_authorship.py
Normal file
324
.agents/skills/scientific-writing/scripts/validate_authorship.py
Normal file
@@ -0,0 +1,324 @@
|
||||
"""Validate human authorship, CRediT roles, accountability, and AI disclosure."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from _common import (
|
||||
InputError,
|
||||
Issue,
|
||||
emit_report,
|
||||
is_nonempty_string,
|
||||
is_iso_date,
|
||||
is_placeholder,
|
||||
issue,
|
||||
read_json,
|
||||
require_list,
|
||||
require_object,
|
||||
run,
|
||||
)
|
||||
|
||||
TOOL = "validate_authorship"
|
||||
AUTHOR_ID_RE = re.compile(r"^A[0-9]{3,8}$")
|
||||
CONTRIBUTOR_ID_RE = re.compile(r"^K[0-9]{3,8}$")
|
||||
SHA256_RE = re.compile(r"^[a-f0-9]{64}$")
|
||||
CREDIT_ROLES = {
|
||||
"conceptualization",
|
||||
"data curation",
|
||||
"formal analysis",
|
||||
"funding acquisition",
|
||||
"investigation",
|
||||
"methodology",
|
||||
"project administration",
|
||||
"resources",
|
||||
"software",
|
||||
"supervision",
|
||||
"validation",
|
||||
"visualization",
|
||||
"writing – original draft",
|
||||
"writing – review & editing",
|
||||
}
|
||||
AUTHORSHIP_CRITERIA = {
|
||||
"substantial_contribution",
|
||||
"drafted_or_critically_revised",
|
||||
"final_approval",
|
||||
"accountable_for_work",
|
||||
}
|
||||
DISCLOSURE_LOCATIONS = {"cover_letter", "acknowledgments", "methods", "other"}
|
||||
MATERIAL_CLASSES = {
|
||||
"none",
|
||||
"public_text",
|
||||
"unpublished_manuscript",
|
||||
"peer_review_material",
|
||||
"source_documents",
|
||||
"sensitive_data",
|
||||
"phi",
|
||||
"proprietary_content",
|
||||
}
|
||||
RESTRICTED_MATERIAL_CLASSES = MATERIAL_CLASSES - {"none", "public_text"}
|
||||
|
||||
|
||||
def _validate_roles(
|
||||
roles_value: Any,
|
||||
*,
|
||||
item_id: str,
|
||||
issues: list[Issue],
|
||||
) -> None:
|
||||
roles = require_list(roles_value, f"{item_id}.credit_roles")
|
||||
if not roles:
|
||||
issues.append(issue("error", "NO_CREDIT_ROLE", item_id=item_id))
|
||||
normalized: set[str] = set()
|
||||
for role in roles:
|
||||
if not isinstance(role, str) or role.casefold() not in CREDIT_ROLES:
|
||||
issues.append(issue("error", "INVALID_CREDIT_ROLE", item_id=item_id))
|
||||
elif role.casefold() in normalized:
|
||||
issues.append(issue("error", "DUPLICATE_CREDIT_ROLE", item_id=item_id))
|
||||
else:
|
||||
normalized.add(role.casefold())
|
||||
|
||||
|
||||
def validate_people(data: dict[str, Any]) -> tuple[list[Issue], set[str]]:
|
||||
issues: list[Issue] = []
|
||||
author_ids: set[str] = set()
|
||||
for index, raw_author in enumerate(require_list(data.get("authors"), "authors")):
|
||||
author = require_object(raw_author, f"authors[{index}]")
|
||||
author_id = author.get("author_id")
|
||||
if not isinstance(author_id, str) or not AUTHOR_ID_RE.fullmatch(author_id):
|
||||
issues.append(
|
||||
issue("error", "INVALID_AUTHOR_ID", location=f"authors[{index}]")
|
||||
)
|
||||
continue
|
||||
if author_id in author_ids:
|
||||
issues.append(issue("error", "DUPLICATE_AUTHOR_ID", item_id=author_id))
|
||||
continue
|
||||
author_ids.add(author_id)
|
||||
if author.get("is_human") is not True:
|
||||
issues.append(
|
||||
issue("error", "NONHUMAN_AUTHOR_PROHIBITED", item_id=author_id)
|
||||
)
|
||||
if not is_nonempty_string(author.get("name")) or is_placeholder(
|
||||
author.get("name")
|
||||
):
|
||||
issues.append(issue("error", "MISSING_AUTHOR_NAME", item_id=author_id))
|
||||
criteria = require_object(
|
||||
author.get("authorship_criteria"),
|
||||
f"{author_id}.authorship_criteria",
|
||||
)
|
||||
for criterion in AUTHORSHIP_CRITERIA:
|
||||
if criteria.get(criterion) is not True:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"AUTHORSHIP_CRITERION_NOT_MET",
|
||||
location=criterion,
|
||||
item_id=author_id,
|
||||
)
|
||||
)
|
||||
_validate_roles(author.get("credit_roles"), item_id=author_id, issues=issues)
|
||||
|
||||
if not author_ids:
|
||||
issues.append(issue("error", "NO_HUMAN_AUTHORS", location="authors"))
|
||||
|
||||
contributor_ids: set[str] = set()
|
||||
for index, raw_contributor in enumerate(
|
||||
require_list(data.get("contributors", []), "contributors")
|
||||
):
|
||||
contributor = require_object(raw_contributor, f"contributors[{index}]")
|
||||
contributor_id = contributor.get("contributor_id")
|
||||
if (
|
||||
not isinstance(contributor_id, str)
|
||||
or not CONTRIBUTOR_ID_RE.fullmatch(contributor_id)
|
||||
or contributor_id in contributor_ids
|
||||
):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INVALID_OR_DUPLICATE_CONTRIBUTOR_ID",
|
||||
location=f"contributors[{index}]",
|
||||
)
|
||||
)
|
||||
continue
|
||||
contributor_ids.add(contributor_id)
|
||||
if contributor.get("is_human") is not True:
|
||||
issues.append(
|
||||
issue("error", "NONHUMAN_CONTRIBUTOR_RECORD", item_id=contributor_id)
|
||||
)
|
||||
_validate_roles(
|
||||
contributor.get("credit_roles"),
|
||||
item_id=contributor_id,
|
||||
issues=issues,
|
||||
)
|
||||
return issues, author_ids
|
||||
|
||||
|
||||
def validate_accountability(
|
||||
data: dict[str, Any],
|
||||
author_ids: set[str],
|
||||
) -> list[Issue]:
|
||||
issues: list[Issue] = []
|
||||
corresponding = data.get("corresponding_author_id")
|
||||
if corresponding not in author_ids:
|
||||
issues.append(issue("error", "INVALID_CORRESPONDING_AUTHOR"))
|
||||
accountability = require_object(data.get("accountability"), "accountability")
|
||||
if accountability.get("all_authors_approved") is not True:
|
||||
issues.append(
|
||||
issue("error", "FINAL_APPROVAL_INCOMPLETE", location="accountability")
|
||||
)
|
||||
guarantors = require_list(
|
||||
accountability.get("guarantor_author_ids"), "guarantor_author_ids"
|
||||
)
|
||||
if not guarantors:
|
||||
issues.append(
|
||||
issue("error", "NO_ACCOUNTABILITY_GUARANTOR", location="accountability")
|
||||
)
|
||||
for guarantor in guarantors:
|
||||
if guarantor not in author_ids:
|
||||
issues.append(
|
||||
issue("error", "INVALID_GUARANTOR_AUTHOR", item_id=str(guarantor))
|
||||
)
|
||||
return issues
|
||||
|
||||
|
||||
def validate_ai_disclosure(data: dict[str, Any]) -> tuple[list[Issue], int]:
|
||||
issues: list[Issue] = []
|
||||
ai_use = require_object(data.get("ai_use"), "ai_use")
|
||||
used = ai_use.get("used")
|
||||
if not isinstance(used, bool):
|
||||
issues.append(issue("error", "AI_USED_NOT_BOOLEAN", location="ai_use"))
|
||||
used = False
|
||||
tools = require_list(ai_use.get("tools"), "ai_use.tools")
|
||||
if used and not tools:
|
||||
issues.append(issue("error", "AI_USE_WITHOUT_TOOL_RECORD", location="ai_use"))
|
||||
if not used and tools:
|
||||
issues.append(issue("error", "AI_TOOL_RECORDED_WHEN_UNUSED", location="ai_use"))
|
||||
|
||||
if ai_use.get("human_verification_complete") is not True:
|
||||
issues.append(issue("error", "AI_OUTPUT_NOT_HUMAN_VERIFIED", location="ai_use"))
|
||||
if ai_use.get("journal_policy_checked") is not True:
|
||||
issues.append(
|
||||
issue("error", "JOURNAL_AI_POLICY_NOT_CHECKED", location="ai_use")
|
||||
)
|
||||
locations = require_list(ai_use.get("disclosed_in"), "ai_use.disclosed_in")
|
||||
if used and not locations:
|
||||
issues.append(issue("error", "AI_USE_NOT_DISCLOSED", location="ai_use"))
|
||||
for location in locations:
|
||||
if location not in DISCLOSURE_LOCATIONS:
|
||||
issues.append(
|
||||
issue("error", "INVALID_AI_DISCLOSURE_LOCATION", location="ai_use")
|
||||
)
|
||||
|
||||
for index, raw_tool in enumerate(tools):
|
||||
tool = require_object(raw_tool, f"ai_use.tools[{index}]")
|
||||
tool_id = f"tool:{index + 1}"
|
||||
for key in ("name", "version", "provider", "purpose"):
|
||||
if not is_nonempty_string(tool.get(key)) or is_placeholder(tool.get(key)):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INCOMPLETE_AI_TOOL_RECORD",
|
||||
location=key,
|
||||
item_id=tool_id,
|
||||
)
|
||||
)
|
||||
material_class = tool.get("materials_sent")
|
||||
if material_class not in MATERIAL_CLASSES:
|
||||
issues.append(issue("error", "INVALID_AI_MATERIAL_CLASS", item_id=tool_id))
|
||||
if not isinstance(tool.get("external_service"), bool):
|
||||
issues.append(
|
||||
issue("error", "EXTERNAL_SERVICE_NOT_BOOLEAN", item_id=tool_id)
|
||||
)
|
||||
if (
|
||||
tool.get("external_service") is True
|
||||
and material_class in RESTRICTED_MATERIAL_CLASSES
|
||||
):
|
||||
if tool.get("explicit_authorization") is not True:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"RESTRICTED_EXTERNAL_TRANSFER_UNAUTHORIZED",
|
||||
item_id=tool_id,
|
||||
)
|
||||
)
|
||||
if tool.get("policy_reviewed") is not True:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"RESTRICTED_EXTERNAL_TRANSFER_POLICY_UNREVIEWED",
|
||||
item_id=tool_id,
|
||||
)
|
||||
)
|
||||
return issues, len(tools)
|
||||
|
||||
|
||||
def validate_declarations(data: dict[str, Any]) -> list[Issue]:
|
||||
issues: list[Issue] = []
|
||||
declarations = require_object(data.get("declarations"), "declarations")
|
||||
for declaration_id in (
|
||||
"ai_use",
|
||||
"author_contributions",
|
||||
"conflicts",
|
||||
"funding",
|
||||
):
|
||||
declaration = require_object(
|
||||
declarations.get(declaration_id),
|
||||
f"declarations.{declaration_id}",
|
||||
)
|
||||
if declaration.get("status") not in {"verified", "not_applicable"}:
|
||||
issues.append(
|
||||
issue("error", "DECLARATION_NOT_VERIFIED", item_id=declaration_id)
|
||||
)
|
||||
if not SHA256_RE.fullmatch(str(declaration.get("content_sha256", ""))):
|
||||
issues.append(
|
||||
issue("error", "INVALID_DECLARATION_HASH", item_id=declaration_id)
|
||||
)
|
||||
if not is_nonempty_string(declaration.get("verified_by")) or is_placeholder(
|
||||
declaration.get("verified_by")
|
||||
):
|
||||
issues.append(
|
||||
issue("error", "DECLARATION_VERIFIER_MISSING", item_id=declaration_id)
|
||||
)
|
||||
if not is_iso_date(declaration.get("verified_on")):
|
||||
issues.append(
|
||||
issue("error", "INVALID_DECLARATION_DATE", item_id=declaration_id)
|
||||
)
|
||||
return issues
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Validate a local authorship JSON record against human accountability, "
|
||||
"CRediT role names, AI disclosure, and restricted-material transfer gates."
|
||||
)
|
||||
)
|
||||
parser.add_argument(
|
||||
"authorship", help="UTF-8 JSON authorship and disclosure record"
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def cli() -> int:
|
||||
args = build_parser().parse_args()
|
||||
data = require_object(read_json(args.authorship), "authorship")
|
||||
if data.get("schema_version") != "1.0":
|
||||
raise InputError("unsupported authorship schema version")
|
||||
issues, author_ids = validate_people(data)
|
||||
issues.extend(validate_accountability(data, author_ids))
|
||||
ai_issues, tool_count = validate_ai_disclosure(data)
|
||||
issues.extend(ai_issues)
|
||||
issues.extend(validate_declarations(data))
|
||||
return emit_report(
|
||||
TOOL,
|
||||
issues,
|
||||
summary={
|
||||
"authors": len(author_ids),
|
||||
"ai_tools": tool_count,
|
||||
"credit_taxonomy": "ANSI/NISO Z39.104-2022",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TOOL, cli)
|
||||
460
.agents/skills/scientific-writing/scripts/validate_manifest.py
Normal file
460
.agents/skills/scientific-writing/scripts/validate_manifest.py
Normal file
@@ -0,0 +1,460 @@
|
||||
"""Validate bounded manuscript and source manifests without network access."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from _common import (
|
||||
InputError,
|
||||
Issue,
|
||||
emit_report,
|
||||
is_nonempty_string,
|
||||
is_iso_date,
|
||||
is_placeholder,
|
||||
issue,
|
||||
read_json,
|
||||
require_list,
|
||||
require_object,
|
||||
run,
|
||||
)
|
||||
|
||||
TOOL = "validate_manifest"
|
||||
ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9._-]{1,63}$")
|
||||
EVIDENCE_ID_RE = re.compile(r"^E[0-9]{3,8}$")
|
||||
SOURCE_TYPES = {
|
||||
"journal_article",
|
||||
"book",
|
||||
"chapter",
|
||||
"conference_paper",
|
||||
"dataset",
|
||||
"software",
|
||||
"preprint",
|
||||
"report",
|
||||
"policy",
|
||||
"guideline",
|
||||
"registry",
|
||||
"webpage",
|
||||
"other",
|
||||
}
|
||||
CONFIDENTIALITY = {"public", "restricted", "sensitive", "proprietary"}
|
||||
DRAFT_STATUSES = {"draft", "internal_review", "submission_candidate", "submitted"}
|
||||
STATEMENT_STATUSES = {"not_applicable", "missing", "draft", "verified"}
|
||||
MANUSCRIPT_FIELDS = {
|
||||
"schema_version",
|
||||
"document_id",
|
||||
"study_design",
|
||||
"draft_status",
|
||||
"submission_ready",
|
||||
"registries",
|
||||
"reporting_guidelines",
|
||||
"human_verification",
|
||||
"confidentiality_review",
|
||||
"required_statements",
|
||||
}
|
||||
SOURCE_FIELDS = {
|
||||
"evidence_id",
|
||||
"source_type",
|
||||
"title",
|
||||
"authors",
|
||||
"year",
|
||||
"identifiers",
|
||||
"locator",
|
||||
"confidentiality",
|
||||
"verification",
|
||||
}
|
||||
IDENTIFIER_FIELDS = {"doi", "pmid", "pmcid", "isbn", "url"}
|
||||
VERIFICATION_FIELDS = {"status", "source_opened", "verified_by", "verified_on"}
|
||||
|
||||
|
||||
def _check_unknown_fields(
|
||||
obj: dict[str, Any],
|
||||
allowed: set[str],
|
||||
*,
|
||||
location: str,
|
||||
issues: list[Issue],
|
||||
) -> None:
|
||||
for key in sorted(set(obj) - allowed):
|
||||
issues.append(
|
||||
issue("error", "UNKNOWN_SCHEMA_FIELD", location=location, item_id=key)
|
||||
)
|
||||
|
||||
|
||||
def _missing_or_placeholder(
|
||||
obj: dict[str, Any],
|
||||
key: str,
|
||||
*,
|
||||
location: str,
|
||||
issues: list[Issue],
|
||||
) -> None:
|
||||
value = obj.get(key)
|
||||
if not is_nonempty_string(value) or is_placeholder(value):
|
||||
issues.append(
|
||||
issue("error", "MISSING_VERIFIED_VALUE", location=location, item_id=key)
|
||||
)
|
||||
|
||||
|
||||
def _validate_human_gate(
|
||||
value: Any,
|
||||
*,
|
||||
location: str,
|
||||
submission_ready: bool,
|
||||
issues: list[Issue],
|
||||
) -> None:
|
||||
gate = require_object(value, location)
|
||||
completed = gate.get("completed")
|
||||
if not isinstance(completed, bool):
|
||||
issues.append(issue("error", "GATE_COMPLETED_NOT_BOOLEAN", location=location))
|
||||
return
|
||||
if completed:
|
||||
_missing_or_placeholder(gate, "verified_by", location=location, issues=issues)
|
||||
verified_on = gate.get("verified_on")
|
||||
if not is_iso_date(verified_on):
|
||||
issues.append(
|
||||
issue("error", "INVALID_VERIFICATION_DATE", location=location)
|
||||
)
|
||||
elif submission_ready:
|
||||
issues.append(issue("error", "SUBMISSION_GATE_INCOMPLETE", location=location))
|
||||
|
||||
|
||||
def validate_manuscript_manifest(data: dict[str, Any]) -> list[Issue]:
|
||||
issues: list[Issue] = []
|
||||
_check_unknown_fields(
|
||||
data,
|
||||
MANUSCRIPT_FIELDS,
|
||||
location="root",
|
||||
issues=issues,
|
||||
)
|
||||
if data.get("schema_version") != "1.0":
|
||||
issues.append(
|
||||
issue("error", "UNSUPPORTED_SCHEMA_VERSION", location="schema_version")
|
||||
)
|
||||
|
||||
document_id = data.get("document_id")
|
||||
if not isinstance(document_id, str) or not ID_RE.fullmatch(document_id):
|
||||
issues.append(issue("error", "INVALID_DOCUMENT_ID", location="document_id"))
|
||||
_missing_or_placeholder(data, "study_design", location="root", issues=issues)
|
||||
|
||||
draft_status = data.get("draft_status")
|
||||
if draft_status not in DRAFT_STATUSES:
|
||||
issues.append(issue("error", "INVALID_DRAFT_STATUS", location="draft_status"))
|
||||
submission_ready = data.get("submission_ready")
|
||||
if not isinstance(submission_ready, bool):
|
||||
issues.append(
|
||||
issue("error", "SUBMISSION_READY_NOT_BOOLEAN", location="submission_ready")
|
||||
)
|
||||
submission_ready = False
|
||||
|
||||
paths = require_object(data.get("registries"), "registries")
|
||||
for key in (
|
||||
"source_manifest",
|
||||
"claim_evidence",
|
||||
"consistency_manifest",
|
||||
"authorship_manifest",
|
||||
"reporting_coverage",
|
||||
):
|
||||
_missing_or_placeholder(paths, key, location="registries", issues=issues)
|
||||
|
||||
guidelines = require_list(data.get("reporting_guidelines"), "reporting_guidelines")
|
||||
if submission_ready and not guidelines:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"NO_REPORTING_GUIDELINE_RECORDED",
|
||||
location="reporting_guidelines",
|
||||
)
|
||||
)
|
||||
for index, guideline_id in enumerate(guidelines):
|
||||
if not isinstance(guideline_id, str) or not ID_RE.fullmatch(guideline_id):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INVALID_GUIDELINE_ID",
|
||||
location=f"reporting_guidelines[{index}]",
|
||||
)
|
||||
)
|
||||
|
||||
_validate_human_gate(
|
||||
data.get("human_verification"),
|
||||
location="human_verification",
|
||||
submission_ready=bool(submission_ready),
|
||||
issues=issues,
|
||||
)
|
||||
confidentiality = require_object(
|
||||
data.get("confidentiality_review"), "confidentiality_review"
|
||||
)
|
||||
_validate_human_gate(
|
||||
confidentiality,
|
||||
location="confidentiality_review",
|
||||
submission_ready=bool(submission_ready),
|
||||
issues=issues,
|
||||
)
|
||||
if not isinstance(confidentiality.get("policy_checked"), bool):
|
||||
issues.append(
|
||||
issue(
|
||||
"error", "POLICY_CHECKED_NOT_BOOLEAN", location="confidentiality_review"
|
||||
)
|
||||
)
|
||||
elif submission_ready and not confidentiality["policy_checked"]:
|
||||
issues.append(
|
||||
issue(
|
||||
"error", "POLICY_REVIEW_INCOMPLETE", location="confidentiality_review"
|
||||
)
|
||||
)
|
||||
if not isinstance(confidentiality.get("external_services_authorized"), bool):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"EXTERNAL_AUTHORIZATION_NOT_BOOLEAN",
|
||||
location="confidentiality_review",
|
||||
)
|
||||
)
|
||||
|
||||
statements = require_object(data.get("required_statements"), "required_statements")
|
||||
for key in (
|
||||
"ethics",
|
||||
"consent",
|
||||
"funding",
|
||||
"conflicts",
|
||||
"data_availability",
|
||||
"code_availability",
|
||||
"author_contributions",
|
||||
"ai_disclosure",
|
||||
):
|
||||
status = statements.get(key)
|
||||
if status not in STATEMENT_STATUSES:
|
||||
issues.append(issue("error", "INVALID_STATEMENT_STATUS", location=key))
|
||||
elif submission_ready and status in {"missing", "draft"}:
|
||||
issues.append(issue("error", "UNVERIFIED_REQUIRED_STATEMENT", location=key))
|
||||
|
||||
if submission_ready and draft_status not in {"submission_candidate", "submitted"}:
|
||||
issues.append(issue("error", "READY_STATUS_MISMATCH", location="draft_status"))
|
||||
return issues
|
||||
|
||||
|
||||
def validate_source_manifest(
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
require_verified: bool,
|
||||
) -> list[Issue]:
|
||||
issues: list[Issue] = []
|
||||
_check_unknown_fields(
|
||||
data,
|
||||
{"schema_version", "sources"},
|
||||
location="root",
|
||||
issues=issues,
|
||||
)
|
||||
if data.get("schema_version") != "1.0":
|
||||
issues.append(
|
||||
issue("error", "UNSUPPORTED_SCHEMA_VERSION", location="schema_version")
|
||||
)
|
||||
sources = require_list(data.get("sources"), "sources")
|
||||
seen_ids: set[str] = set()
|
||||
for index, raw_source in enumerate(sources):
|
||||
location = f"sources[{index}]"
|
||||
source = require_object(raw_source, location)
|
||||
_check_unknown_fields(
|
||||
source,
|
||||
SOURCE_FIELDS,
|
||||
location=location,
|
||||
issues=issues,
|
||||
)
|
||||
evidence_id = source.get("evidence_id")
|
||||
if not isinstance(evidence_id, str) or not EVIDENCE_ID_RE.fullmatch(
|
||||
evidence_id
|
||||
):
|
||||
issues.append(issue("error", "INVALID_EVIDENCE_ID", location=location))
|
||||
evidence_id = None
|
||||
elif evidence_id in seen_ids:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"DUPLICATE_EVIDENCE_ID",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
else:
|
||||
seen_ids.add(evidence_id)
|
||||
|
||||
if source.get("source_type") not in SOURCE_TYPES:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INVALID_SOURCE_TYPE",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
_missing_or_placeholder(source, "title", location=location, issues=issues)
|
||||
authors = require_list(source.get("authors"), f"{location}.authors")
|
||||
for author in authors:
|
||||
if not is_nonempty_string(author) or is_placeholder(author):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INVALID_SOURCE_AUTHOR",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
|
||||
year = source.get("year")
|
||||
if year is not None and (
|
||||
not isinstance(year, int)
|
||||
or isinstance(year, bool)
|
||||
or not 1000 <= year <= 2100
|
||||
):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INVALID_SOURCE_YEAR",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
|
||||
identifiers = require_object(
|
||||
source.get("identifiers"), f"{location}.identifiers"
|
||||
)
|
||||
_check_unknown_fields(
|
||||
identifiers,
|
||||
IDENTIFIER_FIELDS,
|
||||
location=f"{location}.identifiers",
|
||||
issues=issues,
|
||||
)
|
||||
if not any(is_nonempty_string(value) for value in identifiers.values()):
|
||||
issues.append(
|
||||
issue(
|
||||
"warning",
|
||||
"NO_SOURCE_IDENTIFIER",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
if not is_nonempty_string(source.get("locator")) or is_placeholder(
|
||||
source.get("locator")
|
||||
):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"MISSING_SOURCE_LOCATOR",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
|
||||
confidentiality = source.get("confidentiality")
|
||||
if confidentiality not in CONFIDENTIALITY:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INVALID_CONFIDENTIALITY_CLASS",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
|
||||
verification = require_object(
|
||||
source.get("verification"), f"{location}.verification"
|
||||
)
|
||||
_check_unknown_fields(
|
||||
verification,
|
||||
VERIFICATION_FIELDS,
|
||||
location=f"{location}.verification",
|
||||
issues=issues,
|
||||
)
|
||||
status = verification.get("status")
|
||||
if status not in {"unverified", "verified", "rejected"}:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INVALID_VERIFICATION_STATUS",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
if status == "verified":
|
||||
_missing_or_placeholder(
|
||||
verification,
|
||||
"verified_by",
|
||||
location=location,
|
||||
issues=issues,
|
||||
)
|
||||
verified_on = verification.get("verified_on")
|
||||
if not is_iso_date(verified_on):
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"INVALID_VERIFICATION_DATE",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
if verification.get("source_opened") is not True:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"SOURCE_NOT_OPENED_FOR_VERIFICATION",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
elif require_verified:
|
||||
issues.append(
|
||||
issue(
|
||||
"error",
|
||||
"SOURCE_NOT_VERIFIED",
|
||||
location=location,
|
||||
item_id=evidence_id,
|
||||
)
|
||||
)
|
||||
return issues
|
||||
|
||||
|
||||
def detect_kind(data: dict[str, Any]) -> str:
|
||||
if "sources" in data:
|
||||
return "source"
|
||||
if "document_id" in data:
|
||||
return "manuscript"
|
||||
raise InputError("unable to infer manifest kind")
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Validate a local JSON manuscript or source manifest. "
|
||||
"No network calls or identifier resolution are performed."
|
||||
)
|
||||
)
|
||||
parser.add_argument("manifest", help="UTF-8 JSON manifest (maximum 5 MB)")
|
||||
parser.add_argument(
|
||||
"--kind",
|
||||
choices=("auto", "manuscript", "source"),
|
||||
default="auto",
|
||||
help="manifest schema to validate (default: infer from keys)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--require-verified",
|
||||
action="store_true",
|
||||
help="for source manifests, fail if any source is not verified",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def cli() -> int:
|
||||
args = build_parser().parse_args()
|
||||
data = require_object(read_json(args.manifest))
|
||||
kind = detect_kind(data) if args.kind == "auto" else args.kind
|
||||
if kind == "manuscript":
|
||||
issues = validate_manuscript_manifest(data)
|
||||
records = 1
|
||||
else:
|
||||
issues = validate_source_manifest(data, require_verified=args.require_verified)
|
||||
records = len(require_list(data.get("sources"), "sources"))
|
||||
return emit_report(TOOL, issues, summary={"kind": kind, "records": records})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(TOOL, cli)
|
||||
Reference in New Issue
Block a user