#!/usr/bin/env python3
"""Verify the SHIFT Staff Nurse Life & Practice Hermes build kit.

This standard-library verifier checks the build kit as a supply-chain and
implementation-contract artifact. It does not claim that Hermes has built or
tested the target full-stack application.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import re
import stat
import sys
import unicodedata
import uuid
import zipfile
from copy import deepcopy
from datetime import datetime
from pathlib import Path, PurePosixPath
from typing import Any


SCRIPT = Path(__file__).resolve()
PACKAGE_NAME = "STAFF-Nurse-Life-Practice-SHIFT-Mission-Control-Hermes-Build-Kit-v1.0.0"
EXTRACTED = SCRIPT.parent.name == "tools" and (SCRIPT.parents[1] / "README-FIRST.md").is_file()
WORKSPACE = None if EXTRACTED else SCRIPT.parents[1]
DEFAULT_PACKAGE = SCRIPT.parents[1] if EXTRACTED else SCRIPT.parents[1] / "deliverables" / PACKAGE_NAME

BUILD_ID = "NAIO-SNQI-SHIFT-FUNCTIONAL-BUILD-KIT-1.0.0"
EXPECTED_MATRIX_ROWS = 216
EXPECTED_INTEGRATION_ROWS = 48
EXPECTED_TARGET_ROWS = 264
EXPECTED_CANONICAL_ROWS = 176
EXPECTED_TOTAL_EXECUTION_RECORDS = 440
EXPECTED_CONTROL_ID_DIGEST = "a8a242230200accc126b6c7a436aca94faba8a1924bd090f19a0a341226c5439"
EXPECTED_MATRIX_SEMANTIC_DIGEST = "de9739cead4d34f30ae2851e3d12e83affaabcb71051a15b03bf01c453f58b00"
EXPECTED_INTEGRATION_SEMANTIC_DIGEST = "cc18245093d9a769ae4278d720ad03bf48c867b8b10730242ed75dcedc18b6d8"
EXPECTED_CAPABILITY_CONFIG_DIGEST = "2dc89437de6a477c14668da03fde4f222d7273b4b6bdea3373cf7d0cfb1c9630"
EXPECTED_SOURCE_REGISTRY_DIGEST = "3b39d1591b41f05c36dc815b084d3b45539aa6ebed762bf81f3bca83d77ee203"
EXPECTED_MATRIX_COLUMNS = (
    "control_id",
    "screen",
    "control",
    "intended_behavior",
    "implementation_target",
    "persisted_data",
    "required_permission",
    "offline_behavior",
    "error_behavior",
    "verification_test",
    "status",
)
EXPECTED_CONTROL_LEDGER_COLUMNS = (
    "Test ID",
    "Area",
    "Priority",
    "Verification target",
    "Required evidence",
    "Result",
)
EXPECTED_INTEGRATION_LEDGER_COLUMNS = (
    "Test ID",
    "Scenario",
    "Priority",
    "Expected result",
    "Required evidence",
    "Result",
)
CRITICAL_CONTROL_PREFIXES = {
    "AGENT", "AI", "AUTH", "CTX", "EVID", "GOV", "MEM", "PWR", "QI", "REC",
}
CRITICAL_CONTROL_IDS = {"APP-004", "DIAG-008", "PKG-005", "PKG-006", "PKG-010"}
EXPECTED_EXPLICIT_CONTROLS = {
    "MISSION-011": "exact eight-stage artifact lifecycle with human-scope Approved Plan, external-only Authorized Execution and verified-reference Completed Action",
    "QI-004": "exact separately approved aggregate created outside SHIFT with steward/privacy, query/definition/version, provenance, suppression, expiry and content hash; reject row/person/event/narrative even if called deidentified",
    "GOV-001": "independent edena_tier and absolute_stop with Personal Red clean-fictional continuation only when false and Institutional Red operational blocking",
    "GOV-015": "absolute-stop no-echo, no-persistence, no-transformation and content-free human route",
    "AGENT-005": "P1/P2 exact one-run ceilings; P3 only a separately approved deterministic local personal reminder after three supervised successes with no model, institutional/QI data, connector, external destination, monitoring, staffing/surveillance input or quality decision; P4 absent",
    "CAP-002": "eligible evidence CRUD admits minimized structural process evidence only and excludes health, schedule, transport, relationship, financial, caregiving, readiness, recovery and whole-life detail from every badge record",
    "CAP-004": "exact current prerequisite chain L1 none, L2 requires L1, L3 requires L2, and L4 requires L3 plus the global orchestration capstone",
    "CAP-005": "contextual named-human review overrides criterion defaults for professional, institutional, credential, quality, employment, Yellow, Orange or otherwise consequential badge evidence",
    "ONB-006": "strict validation against distinct Staff Discover and Staff Soul adapter schemas with unknown-field, incompatible-shape and raw-answer rejection",
    "ONB-007": "field-level Mission Profile review remains non-authoritative and always requires a separate authenticated institutional runtime bind",
    "CTX-009": "server-side exact-one active workspace/role/employer-project/operational-context bind with bidirectional private-versus-institutional deployment consistency",
    "EVID-003": "exact SNLP-SRC-01..10 registry resolution with bundled path/hash verification and no invented identifier, URL, metadata, adoption or authority",
}
SHIFT_CANONICAL_SECTIONS = (
    "Installation and recovery",
    "Role, authority and active hat",
    "PHI, privacy and context isolation",
    "Clinical safety, delegation and official reporting",
    "QI governance versus research",
    "Evidence, sources, policy and truth",
    "Quality data, measurement and provenance",
    "Systems learning, equity and no surveillance",
    "Improvement method and change control",
    "Communication, teamwork and escalation",
    "Dashboard, accessibility and degraded mode",
    "Responsible AI, disclosure and automation",
    "Capacity, fatigue, recovery and whole life",
    "Learning, career, portfolio and recognition",
    "Outcomes, stewardship and honest claims",
)
EXPECTED_AGENTS = {
    "SHIFT-AGT-01": "Shift, Life & Capacity Planning Coach",
    "SHIFT-AGT-02": "General Learning & Source Verification Scout",
    "SHIFT-AGT-03": "Communication, Advocacy & Speak-Up Rehearsal Coach",
    "SHIFT-AGT-04": "Practice Boundary & Human-Escalation Questioner",
    "SHIFT-AGT-05": "Quality Opportunity & Systems-Framing Coach",
    "SHIFT-AGT-06": "Process, PDSA & Change-Readiness Planner",
    "SHIFT-AGT-07": "Aggregate Measurement, Equity & Burden Reviewer",
    "SHIFT-AGT-08": "QI, EBP, Research & Data-Authority Questioner",
    "SHIFT-AGT-09": "Learning, Career, Portfolio & Whole-Life Coach",
    "SHIFT-AGT-10": "Independent Agent Auditor & Kill Sentinel",
}
EXPECTED_EVIDENCE_TYPES = [
    "evaluated_mission",
    "reviewed_artifact",
    "source_audit",
    "correction_record",
    "minimized_process_reflection",
    "assessment_record",
    "safety_drill",
    "supervised_workflow_run",
    "accessibility_review",
    "agent_run_receipt",
    "validated_project_outcome",
]
EXPECTED_EVIDENCE_EXCLUSIONS = [
    "synthetic_or_starter_activity",
    "clicks_page_views_or_time_in_app",
    "ai_self_assessment_or_praise",
    "deleted_expired_superseded_revoked_or_conflicted_evidence",
    "unreviewed_evidence_when_review_is_required",
    "patient_event_coworker_or_identifiable_clinical_information",
    "live_care_or_clinical_decision_activity",
    "fabricated_outcome_measure_authorship_hour_credential_or_evidence",
    "restricted_employer_peer_review_incident_hr_or_secret_information",
    "private_wellbeing_relationship_financial_health_schedule_transport_caregiving_or_life_information_in_any_badge_evidence",
    "unbound_or_unauthorized_institutional_quality_activity",
    "person_level_workforce_or_quality_data",
    "external_action_or_production_automation",
]
EXPECTED_RECOMPUTE_TRIGGERS = [
    "correction",
    "deletion",
    "expiry",
    "supersession",
    "revocation",
    "criteria_version_change",
    "integrity_or_authority_conflict",
]
EXPECTED_SOURCE_RECOMMENDATIONS = {
    "SNLP-SRC-01": (
        "source/base-reference/Staff-Nurse-Life-and-Practice-Hermes-Program.md",
        "44f417b9b1d09b54fbf1629e6e3ebb82652c9dadec6941804f68e1c0c61797d5",
        ["practice", "professional_growth", "life_recovery"],
    ),
    "SNLP-SRC-02": (
        "source/base-reference/Staff-Nurse-AI-OS-Life-and-Practice-Guide.docx",
        "1f2189cee5a4b28c3baedbc9088c6d11e552b666a6781c245de7bcda69a2037a",
        ["practice", "professional_growth", "life_recovery"],
    ),
    "SNLP-SRC-03": (
        "source/shift-domain-pack/core/00-Staff-Nurse-Patient-Team-and-Quality-Trust-Shield.md",
        "055b8cd0befc691322a1de0c944c42bcc56393fbc74478721e2642528139a897",
        ["practice", "quality_improvement", "professional_growth", "life_recovery", "community_leadership"],
    ),
    "SNLP-SRC-04": (
        "source/shift-domain-pack/core/01-SHIFT-Operating-Core.md",
        "7f9870a64538119052578d4d44232fd4d06b76609fbd67fb0214bd9222f42eaa",
        ["quality_improvement", "community_leadership"],
    ),
    "SNLP-SRC-05": (
        "source/shift-domain-pack/shift/03-I-Improve-Quality-Together.md",
        "f1ef910c2e86dde1cf090967b0e5453dd9b65a80f297feadf1138ce18e4224e1",
        ["quality_improvement"],
    ),
    "SNLP-SRC-06": (
        "source/shift-domain-pack/shift/05-T-Trust-Governed-AI-and-Data.md",
        "eff8cb27a9c3835554b2e0c195e088701517e5c18de77c2f42541a44a1e0e697",
        ["quality_improvement", "practice", "community_leadership"],
    ),
    "SNLP-SRC-07": (
        "source/shift-domain-pack/shift/04-F-Flourish-in-Career-and-Life.md",
        "41587ecbdb0b5ba2d9e226fd4f2dba7b9c452248fe6f28c747d623a6a204434f",
        ["professional_growth", "life_recovery"],
    ),
    "SNLP-SRC-08": (
        "source/shift-domain-pack/shift/02-H-Humanize-Communication-and-Teamwork.md",
        "f10a4c1ee40f47e40e2377d844b7b5e83acd1294953f031f85f021c92b9689c9",
        ["practice", "professional_growth", "community_leadership"],
    ),
    "SNLP-SRC-09": (
        "source/shift-domain-pack/shift/01-S-Safeguard-Practice-and-Life.md",
        "35d54418f868dd2e2a6f98251e4e6111f5f11d48afd24de9b69f66a3887872ce",
        ["practice", "life_recovery"],
    ),
    "SNLP-SRC-10": (
        "source/shift-domain-pack/workflows/SHIFT-Launch-and-Impact-Plan.md",
        "60f52988b8ea91ee60047e08efdfa0b4f244a4c76ea809111ae72645ddab03a0",
        ["quality_improvement", "community_leadership"],
    ),
}
PROMPT_SHA = "ce884cfc6345cc93a6baec0852cf44feb44d859234ef1dc2b5ac2138df18ebe2"
BASELINE_ZIP_SHA = "69a4dd86659b41136ce9ceb2ceb52512ab567637ab0be29fdc6f6ab6573223c1"
BASE_PROGRAM_SHA = "44f417b9b1d09b54fbf1629e6e3ebb82652c9dadec6941804f68e1c0c61797d5"
BASE_GUIDE_SHA = "1f2189cee5a4b28c3baedbc9088c6d11e552b666a6781c245de7bcda69a2037a"
LEGACY_ZIP_SHA = "b3a78f0b6a86bc1bc67dcc95d087fe8c71226889ca02a285a2c4504194d8ccf5"
BASELINE_MANIFEST_SHA = "22fed55fd789c933f4e7eb50266f88f8dda47f9fba91ebbe9c2cbe4f0ab99702"
BASELINE_CHECKSUMS_SHA = "e178993d6185b126cc915f0d3026ddb3b07e7c5c7dd432aaf581152db8a5a40e"

SHIFT_TREE_HASHES = {
    "README.md": "2132749864220bcb0b6a08f6ebfb000a13b880d952a2258de55df87410cadfed",
    "core/00-Staff-Nurse-Patient-Team-and-Quality-Trust-Shield.md": "055b8cd0befc691322a1de0c944c42bcc56393fbc74478721e2642528139a897",
    "core/01-SHIFT-Operating-Core.md": "7f9870a64538119052578d4d44232fd4d06b76609fbd67fb0214bd9222f42eaa",
    "manifest.md": "e24bbab3deae67a9a8c23e17efde6d0eff5bbedc54ae1c7da51354c938bb8ca4",
    "shift/01-S-Safeguard-Practice-and-Life.md": "35d54418f868dd2e2a6f98251e4e6111f5f11d48afd24de9b69f66a3887872ce",
    "shift/02-H-Humanize-Communication-and-Teamwork.md": "f10a4c1ee40f47e40e2377d844b7b5e83acd1294953f031f85f021c92b9689c9",
    "shift/03-I-Improve-Quality-Together.md": "f1ef910c2e86dde1cf090967b0e5453dd9b65a80f297feadf1138ce18e4224e1",
    "shift/04-F-Flourish-in-Career-and-Life.md": "41587ecbdb0b5ba2d9e226fd4f2dba7b9c452248fe6f28c747d623a6a204434f",
    "shift/05-T-Trust-Governed-AI-and-Data.md": "eff8cb27a9c3835554b2e0c195e088701517e5c18de77c2f42541a44a1e0e697",
    "templates/SHIFT-Cards-and-Templates.md": "c844b3677e4b49f337ecd4a8e801d3f6eeb100748180b84122edadb8fde17a89",
    "tests/SHIFT-Acceptance-Tests.md": "44c9d15a87f36fb33a48cd504f353010ea226ca18d904bf6f4733ecf4e4b559b",
    "workflows/SHIFT-Command-Center.md": "f092436588099bbb7a8a32d26be35c3cce26c59043cbaa16d1d61c43f0e4a2bd",
    "workflows/SHIFT-Launch-and-Impact-Plan.md": "60f52988b8ea91ee60047e08efdfa0b4f244a4c76ea809111ae72645ddab03a0",
}

BASELINE_ARCHIVE = Path("source/archives/DISCOVER-Nurse-AI-OS-Mission-Control-v2.0.0.zip")
LEGACY_ARCHIVE = Path("source/archives/Staff-Nurse-and-Quality-Contributor-Complete-AI-OS-with-SHIFT-SuperPowers-Package-v1.0.zip")
PROMPT = Path("source/original-functional-build-master-prompt.md")
BASELINE = Path("source/baseline-application")
BASE_PROGRAM = Path("source/base-reference/Staff-Nurse-Life-and-Practice-Hermes-Program.md")
BASE_GUIDE = Path("source/base-reference/Staff-Nurse-AI-OS-Life-and-Practice-Guide.docx")
SHIFT_SOURCE = Path("source/shift-domain-pack")
LEGACY = Path("source/legacy-reference")

REQUIRED = (
    ".env.example",
    "README-FIRST.md",
    "GIVE-THIS-PACKAGE-TO-HERMES.md",
    "BUILD-STATUS.md",
    "INPUT-PRECEDENCE.md",
    "SOURCE-NOTES.md",
    "CHANGELOG.md",
    "LICENSE-NOTICE.md",
    "VERSION",
    "RELEASE-MANIFEST.json",
    "SHA256SUMS.txt",
    "SOURCE-INVENTORY.json",
    "implementation/STAFF-Functional-Build-Master-Prompt.md",
    "implementation/STAFF-Product-Specification.md",
    "implementation/STAFF-Architecture-and-Data-Model.md",
    "implementation/STAFF-Governance-EDENA-and-Data-Boundaries.md",
    "implementation/STAFF-Agent-Team-and-Routing.md",
    "implementation/STAFF-Personalization-Mapping-Crosswalk.md",
    "implementation/STAFF-Starter-Workspace-Crosswalk.md",
    "implementation/STAFF-Capability-and-Badge-Evidence-Model.md",
    "implementation/STAFF-Guide-Page-Content.md",
    "implementation/STAFF-Baseline-Gap-Report.md",
    "implementation/STAFF-Technical-Implementation-Guide.md",
    "implementation/STAFF-User-Installation-Guide.md",
    "implementation/STAFF-Security-and-Privacy-Checklist.md",
    "implementation/STAFF-Synthetic-Sample-Mission.md",
    "implementation/STAFF-Control-Completeness-Matrix.csv",
    "implementation/STAFF-Acceptance-and-Test-Ledger.md",
    "implementation/HERMES-FINAL-HANDOFF-REPORT-TEMPLATE.md",
    "personalization/README.md",
    "personalization/STAFF-Discover-Packet.synthetic.example.json",
    "personalization/STAFF-Soul-Profile.synthetic.example.json",
    "personalization/STAFF-Mission-Profile.synthetic.example.json",
    "personalization/input-schemas/discover-packet-input.schema.json",
    "personalization/input-schemas/soul-profile-input.schema.json",
    "schemas/STAFF-Discover-Packet.schema.json",
    "schemas/STAFF-Soul-Profile.schema.json",
    "schemas/STAFF-Mission-Profile.schema.json",
    "config/STAFF-Capability-Mastery-Criteria.v1.json",
    "config/STAFF-Source-Recommendation-Registry.v1.json",
    PROMPT.as_posix(),
    BASELINE_ARCHIVE.as_posix(),
    LEGACY_ARCHIVE.as_posix(),
    "tools/verify-build-kit.py",
    BASE_PROGRAM.as_posix(),
    BASE_GUIDE.as_posix(),
    "source/legacy-reference/Staff-Nurse-and-Quality-Contributor-Complete-AI-OS-with-SHIFT-SuperPowers-Hermes-Program.md",
    "source/legacy-reference/Staff-Nurse-and-Quality-Contributor-Complete-AI-OS-with-SHIFT-SuperPowers-Setup-Guide.md",
    "source/legacy-reference/Staff-Nurse-and-Quality-Contributor-Complete-AI-OS-with-SHIFT-SuperPowers-Setup-Guide.docx",
    *(f"source/shift-domain-pack/{path}" for path in SHIFT_TREE_HASHES),
)

PLACEHOLDERS = (
    "[PACKAGE_NAME]",
    "[SOURCE_DIRECTORY_OR_REPOSITORY]",
    "[DISCOVER_PACKET_PATH_OR_SOURCE]",
    "[SOUL_QUIZ_RESULTS_PATH_OR_SOURCE]",
    "[HERMES_PROFILE_NAME_OR_AUTO_DETECT]",
    "[USER_TYPE]",
    "[ROLE_LANES]",
    "[DOMAIN]",
    "[AGENT_LIST]",
    "[DATA_CLASSIFICATION]",
    "[DOMAIN_GUARDRAILS]",
    "[MACOS_WINDOWS_LINUX]",
    "[ZIP_INSTALLER_DESKTOP_APP_LOCAL_WEB_APP]",
)
CONTROLLED_TEXT_SUFFIXES = {".csv", ".json", ".md", ".txt", ".yaml", ".yml"}
GENERIC_PLACEHOLDER_PATTERN = re.compile(r"\[(?:TODO|TBD|PLACEHOLDER)(?:_[A-Z0-9]+)*\]|\[[A-Z][A-Z0-9_]{2,}\]")


class Checks:
    def __init__(self) -> None:
        self.passed: list[str] = []
        self.failed: list[str] = []
        self.warnings: list[str] = []

    def check(self, condition: bool, label: str, detail: Any = None) -> bool:
        if condition:
            self.passed.append(label)
            print(f"PASS  {label}")
            return True
        suffix = "" if detail in (None, "", [], {}) else f" — {detail}"
        self.failed.append(label + suffix)
        print(f"FAIL  {label}{suffix}")
        return False

    def warn(self, label: str, detail: Any = None) -> None:
        suffix = "" if detail in (None, "", [], {}) else f" — {detail}"
        self.warnings.append(label + suffix)
        print(f"WARN  {label}{suffix}")


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def normalized_digest(value: Any) -> str:
    payload = json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
    return hashlib.sha256((payload + "\n").encode("utf-8")).hexdigest()


def strict_json_loads(text: str) -> Any:
    def object_from_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
        result: dict[str, Any] = {}
        for key, value in pairs:
            if key in result:
                raise ValueError(f"duplicate JSON object key: {key!r}")
            result[key] = value
        return result

    def reject_constant(value: str) -> Any:
        raise ValueError(f"non-finite JSON number: {value}")

    return json.loads(text, object_pairs_hook=object_from_pairs, parse_constant=reject_constant)


def safe_name(name: str) -> bool:
    if not name or "\x00" in name or "\\" in name or name.startswith("/") or "//" in name:
        return False
    candidate = name[:-1] if name.endswith("/") else name
    if not candidate:
        return False
    parts = candidate.split("/")
    pure = PurePosixPath(candidate)
    return all(part not in {"", ".", ".."} and ":" not in part for part in parts) and not pure.is_absolute() and pure.parts == tuple(parts)


def files(root: Path) -> dict[str, Path]:
    if not root.is_dir():
        return {}
    return {
        path.relative_to(root).as_posix(): path
        for path in sorted(root.rglob("*"))
        if path.is_file() and not path.is_symlink()
    }


def load_json(c: Checks, path: Path, label: str) -> Any | None:
    try:
        value = strict_json_loads(path.read_text(encoding="utf-8"))
    except Exception as error:
        c.check(False, label, error)
        return None
    c.check(True, label)
    return value


def parse_checksums(path: Path) -> tuple[dict[str, str], list[str]]:
    result: dict[str, str] = {}
    errors: list[str] = []
    collisions: set[str] = set()
    for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        digest, separator, relative = line.partition("  ")
        if separator != "  " or not re.fullmatch(r"[0-9a-f]{64}", digest) or not safe_name(relative) or relative.endswith("/"):
            errors.append(f"line {number}")
            continue
        key = unicodedata.normalize("NFC", relative).casefold()
        if relative in result or key in collisions:
            errors.append(f"duplicate/collision line {number}")
            continue
        collisions.add(key)
        result[relative] = digest
    return result, errors


def markdown_table_rows(text: str) -> list[list[str]]:
    rows: list[list[str]] = []
    for line in text.splitlines():
        stripped = line.strip()
        if stripped.startswith("|") and stripped.endswith("|"):
            rows.append([cell.strip() for cell in stripped[1:-1].split("|")])
    return rows


def expected_control_priority(control_id: str) -> str:
    prefix = control_id.partition("-")[0]
    return "Critical" if prefix in CRITICAL_CONTROL_PREFIXES or control_id in CRITICAL_CONTROL_IDS else "Required"


def expected_canonical_rows() -> list[list[str]]:
    foundation_sections = (
        (range(1, 9), "Functional", 0),
        (range(9, 18), "Clinical safety and authority", 8),
        (range(18, 24), "Privacy and isolation", 17),
        (range(24, 30), "Communication and workplace safety", 23),
        (range(30, 36), "Fatigue and whole life", 29),
        (range(36, 41), "Accessibility and usability", 35),
    )
    rows = [
        [
            f"FOUNDATION-{index:03d}",
            "Foundation",
            "`Staff-Nurse-Life-and-Practice-Hermes-Program.md` → Acceptance tests → "
            f"{section} → source-order bullet {index - offset}",
            "Not Run",
        ]
        for indices, section, offset in foundation_sections
        for index in indices
    ]
    rows.extend(
        [
            f"SHIFT-{letter}{index}",
            "SHIFT overlay",
            f"`tests/SHIFT-Acceptance-Tests.md` → {section} → source ID {letter}{index}",
            "Not Run",
        ]
        for letter, section in zip("ABCDEFGHIJKLMNO", SHIFT_CANONICAL_SECTIONS)
        for index in range(1, 9)
    )
    rows.extend(
        [
            f"INTEGRATION-INT{index:02d}",
            "Complete Edition integration",
            f"`tests/SHIFT-Acceptance-Tests.md` → source ID INT{index:02d}",
            "Not Run",
        ]
        for index in range(1, 17)
    )
    return rows


def recommendation_errors(value: Any, label: str) -> list[str]:
    if not isinstance(value, dict):
        return [f"{label}: recommendation object missing"]
    errors: list[str] = []
    expected_scalars = {
        "activation_state": "recommendations_only_inactive",
        "agent_permission_state": "PERM-P0 Disabled",
        "tool_state": "disabled",
    }
    for key, expected in expected_scalars.items():
        if value.get(key) != expected:
            errors.append(f"{label}/{key}={value.get(key)!r}")
    if value.get("tool_ids") != []:
        errors.append(f"{label}/tool_ids must be empty")
    patterns = {
        "agent_ids": r"SHIFT-AGT-(?:0[1-9]|10)",
        "shift_power_ids": r"SHIFT-PWR-(?:0[1-9]|1[0-9]|20)",
        "shift_workflow_ids": r"SHIFT-WF-(?:0[1-9]|1[0-8])",
        "shift_template_ids": r"SHIFT-TPL-(?:0[1-9]|1[0-9]|2[0-5])",
        "source_recommendation_ids": r"SNLP-SRC-(?:0[1-9]|10)",
    }
    for key, pattern in patterns.items():
        items = value.get(key)
        if not isinstance(items, list):
            errors.append(f"{label}/{key} is not a list")
            continue
        if len(items) != len(set(items)):
            errors.append(f"{label}/{key} contains duplicates")
        if any(not isinstance(item, str) or re.fullmatch(pattern, item) is None for item in items):
            errors.append(f"{label}/{key} contains an invalid ID")
    capabilities = value.get("capability_ids")
    if not isinstance(capabilities, list) or len(capabilities) != len(set(capabilities)):
        errors.append(f"{label}/capability_ids is not a unique list")
    return errors


def nested_keys(value: Any) -> set[str]:
    found: set[str] = set()
    if isinstance(value, dict):
        for key, child in value.items():
            found.add(str(key))
            found.update(nested_keys(child))
    elif isinstance(value, list):
        for child in value:
            found.update(nested_keys(child))
    return found


SUPPORTED_SCHEMA_KEYWORDS = {
    "$defs", "$id", "$ref", "$schema", "additionalProperties", "allOf", "const",
    "contains", "description", "enum", "format", "if", "items", "maxContains",
    "maxItems", "maxLength", "maximum", "minContains", "minItems", "minLength",
    "minimum", "not", "oneOf", "pattern", "properties", "required", "then", "title", "type",
    "uniqueItems",
}


def schema_definition_errors(schema: Any, path: str = "$") -> list[str]:
    """Reject schema keywords outside the deliberately implemented subset."""
    if not isinstance(schema, dict):
        return [f"{path}: schema node is not an object"]
    errors = [f"{path}: unsupported keyword {key!r}" for key in schema if key not in SUPPORTED_SCHEMA_KEYWORDS]
    for container_key in ("$defs", "properties"):
        children = schema.get(container_key)
        if children is None:
            continue
        if not isinstance(children, dict):
            errors.append(f"{path}/{container_key}: must be an object")
            continue
        for name, child in children.items():
            errors.extend(schema_definition_errors(child, f"{path}/{container_key}/{name}"))
    for child_key in ("contains", "if", "items", "not", "then"):
        child = schema.get(child_key)
        if child is not None:
            errors.extend(schema_definition_errors(child, f"{path}/{child_key}"))
    for child_key in ("allOf", "oneOf"):
        children = schema.get(child_key)
        if children is None:
            continue
        if not isinstance(children, list):
            errors.append(f"{path}/{child_key}: must be an array")
            continue
        for index, child in enumerate(children):
            errors.extend(schema_definition_errors(child, f"{path}/{child_key}/{index}"))
    return errors


def json_equal(left: Any, right: Any) -> bool:
    if isinstance(left, bool) or isinstance(right, bool):
        return isinstance(left, bool) and isinstance(right, bool) and left == right
    if isinstance(left, (int, float)) and isinstance(right, (int, float)):
        return left == right
    if type(left) is not type(right):
        return False
    if isinstance(left, dict):
        return set(left) == set(right) and all(json_equal(left[key], right[key]) for key in left)
    if isinstance(left, list):
        return len(left) == len(right) and all(json_equal(a, b) for a, b in zip(left, right))
    return left == right


def json_type_matches(value: Any, expected: str) -> bool:
    return {
        "array": lambda: isinstance(value, list),
        "boolean": lambda: isinstance(value, bool),
        "integer": lambda: isinstance(value, int) and not isinstance(value, bool),
        "null": lambda: value is None,
        "number": lambda: isinstance(value, (int, float)) and not isinstance(value, bool),
        "object": lambda: isinstance(value, dict),
        "string": lambda: isinstance(value, str),
    }.get(expected, lambda: False)()


def validate_json_schema(instance: Any, schema: dict[str, Any]) -> list[str]:
    """Validate the JSON-Schema subset used by the three Staff adapter schemas."""
    root = schema

    def validate(value: Any, node: Any, path: str, ref_stack: tuple[str, ...] = ()) -> list[str]:
        if not isinstance(node, dict):
            return [f"{path}: schema node is not an object"]
        errors: list[str] = []

        reference = node.get("$ref")
        if reference is not None:
            if not isinstance(reference, str) or re.fullmatch(r"#/\$defs/[A-Za-z][A-Za-z0-9_-]*", reference) is None:
                errors.append(f"{path}: unsupported reference {reference!r}")
            elif reference in ref_stack:
                errors.append(f"{path}: cyclic reference {reference}")
            else:
                name = reference.rsplit("/", 1)[-1]
                definitions = root.get("$defs")
                target = definitions.get(name) if isinstance(definitions, dict) else None
                if not isinstance(target, dict):
                    errors.append(f"{path}: unresolved reference {reference}")
                else:
                    errors.extend(validate(value, target, path, ref_stack + (reference,)))

        expected_type = node.get("type")
        if expected_type is not None:
            expected_types = [expected_type] if isinstance(expected_type, str) else expected_type
            if not isinstance(expected_types, list) or not expected_types or any(not isinstance(item, str) for item in expected_types):
                errors.append(f"{path}: malformed type constraint")
                return errors
            if not any(json_type_matches(value, item) for item in expected_types):
                errors.append(f"{path}: expected type {'|'.join(expected_types)}, got {type(value).__name__}")
                return errors

        if "const" in node and not json_equal(value, node["const"]):
            errors.append(f"{path}: value does not equal const")
        enum = node.get("enum")
        if enum is not None:
            if not isinstance(enum, list):
                errors.append(f"{path}: malformed enum")
            elif not any(json_equal(value, candidate) for candidate in enum):
                errors.append(f"{path}: value is not in enum")

        if isinstance(value, dict):
            required = node.get("required", [])
            if not isinstance(required, list) or any(not isinstance(key, str) for key in required):
                errors.append(f"{path}: malformed required constraint")
            else:
                errors.extend(f"{path}: missing required property {key!r}" for key in required if key not in value)
            properties = node.get("properties", {})
            if not isinstance(properties, dict):
                errors.append(f"{path}: malformed properties constraint")
            else:
                for key, child in properties.items():
                    if key in value:
                        errors.extend(validate(value[key], child, f"{path}/{key}", ref_stack))
                if node.get("additionalProperties") is False:
                    errors.extend(
                        f"{path}: additional property {key!r} is forbidden"
                        for key in value if key not in properties
                    )

        if isinstance(value, list):
            if isinstance(node.get("minItems"), int) and len(value) < node["minItems"]:
                errors.append(f"{path}: fewer than minItems")
            if isinstance(node.get("maxItems"), int) and len(value) > node["maxItems"]:
                errors.append(f"{path}: more than maxItems")
            if node.get("uniqueItems") is True:
                for index, item in enumerate(value):
                    if any(json_equal(item, prior) for prior in value[:index]):
                        errors.append(f"{path}: duplicate array item at index {index}")
            item_schema = node.get("items")
            if item_schema is not None:
                for index, item in enumerate(value):
                    errors.extend(validate(item, item_schema, f"{path}/{index}", ref_stack))
            contains = node.get("contains")
            if contains is not None:
                matches = sum(not validate(item, contains, f"{path}/{index}", ref_stack) for index, item in enumerate(value))
                minimum = node.get("minContains", 1)
                maximum = node.get("maxContains")
                if not isinstance(minimum, int) or matches < minimum:
                    errors.append(f"{path}: contains matches {matches}, below minimum {minimum!r}")
                if isinstance(maximum, int) and matches > maximum:
                    errors.append(f"{path}: contains matches {matches}, above maximum {maximum}")

        if isinstance(value, str):
            if isinstance(node.get("minLength"), int) and len(value) < node["minLength"]:
                errors.append(f"{path}: shorter than minLength")
            if isinstance(node.get("maxLength"), int) and len(value) > node["maxLength"]:
                errors.append(f"{path}: longer than maxLength")
            pattern = node.get("pattern")
            if isinstance(pattern, str):
                try:
                    if re.search(pattern, value) is None:
                        errors.append(f"{path}: does not match pattern {pattern!r}")
                except re.error as error:
                    errors.append(f"{path}: invalid schema pattern {pattern!r}: {error}")
            format_name = node.get("format")
            if format_name == "uuid":
                try:
                    parsed = uuid.UUID(value)
                    valid_format = str(parsed) == value.casefold()
                except (ValueError, AttributeError):
                    valid_format = False
                if not valid_format:
                    errors.append(f"{path}: invalid UUID format")
            elif format_name == "date-time":
                try:
                    parsed_time = datetime.fromisoformat(value.replace("Z", "+00:00"))
                    valid_format = "T" in value and parsed_time.tzinfo is not None
                except ValueError:
                    valid_format = False
                if not valid_format:
                    errors.append(f"{path}: invalid date-time format")
            elif format_name is not None:
                errors.append(f"{path}: unsupported format {format_name!r}")

        if isinstance(value, (int, float)) and not isinstance(value, bool):
            if isinstance(node.get("minimum"), (int, float)) and value < node["minimum"]:
                errors.append(f"{path}: below minimum")
            if isinstance(node.get("maximum"), (int, float)) and value > node["maximum"]:
                errors.append(f"{path}: above maximum")

        one_of = node.get("oneOf")
        if isinstance(one_of, list):
            matches = sum(not validate(value, child, path, ref_stack) for child in one_of)
            if matches != 1:
                errors.append(f"{path}: oneOf matched {matches} branches")
        prohibited = node.get("not")
        if isinstance(prohibited, dict) and not validate(value, prohibited, path, ref_stack):
            errors.append(f"{path}: matched prohibited not-schema")
        all_of = node.get("allOf")
        if isinstance(all_of, list):
            for index, child in enumerate(all_of):
                errors.extend(validate(value, child, f"{path}/allOf[{index}]", ref_stack))
        condition = node.get("if")
        if isinstance(condition, dict) and not validate(value, condition, path, ref_stack):
            consequent = node.get("then")
            if isinstance(consequent, dict):
                errors.extend(validate(value, consequent, f"{path}/then", ref_stack))
        return errors

    definition_errors = schema_definition_errors(schema)
    if definition_errors:
        return definition_errors
    return validate(instance, schema, "$")


def check_controlled_placeholders(c: Checks, package: Path) -> None:
    """Scan authored build contracts while excluding immutable source evidence."""
    findings: list[str] = []
    decode_errors: list[str] = []
    for path in sorted(package.rglob("*")):
        if not path.is_file() or path.is_symlink() or path.suffix.casefold() not in CONTROLLED_TEXT_SUFFIXES:
            continue
        relative = path.relative_to(package)
        if relative.parts and relative.parts[0] == "source":
            continue
        try:
            text = path.read_text(encoding="utf-8")
        except UnicodeDecodeError as error:
            decode_errors.append(f"{relative.as_posix()}: {error}")
            continue
        hits = sorted(
            set(placeholder for placeholder in PLACEHOLDERS if placeholder in text)
            | set(GENERIC_PLACEHOLDER_PATTERN.findall(text))
        )
        if hits:
            findings.append(f"{relative.as_posix()}: {', '.join(hits)}")
    c.check(not decode_errors, "Controlled text files decode as UTF-8", decode_errors)
    c.check(not findings, "Controlled build contracts contain no unresolved placeholders", findings)


def check_package_inventory(c: Checks, package: Path) -> Any | None:
    checksum_path = package / "SHA256SUMS.txt"
    manifest_path = package / "RELEASE-MANIFEST.json"
    if not c.check(checksum_path.is_file(), "Release checksum file exists"):
        return None
    parsed, errors = parse_checksums(checksum_path)
    c.check(not errors, "Checksum syntax and paths are safe", errors)
    actual = files(package)
    expected_checksum_names = set(actual) - {"SHA256SUMS.txt"}
    c.check(set(parsed) == expected_checksum_names, "Checksum inventory is exact", {
        "missing": sorted(expected_checksum_names - set(parsed)), "extra": sorted(set(parsed) - expected_checksum_names)
    })
    mismatches = [name for name in parsed if name in actual and sha256(actual[name]) != parsed[name]]
    c.check(not mismatches, "Every package checksum matches", mismatches)

    manifest = load_json(c, manifest_path, "Release manifest parses") if c.check(manifest_path.is_file(), "Release manifest exists") else None
    if not isinstance(manifest, dict):
        return manifest
    raw = manifest.get("files_excluding_manifest_and_checksums")
    entries: dict[str, dict[str, Any]] = {}
    malformed: list[Any] = []
    if isinstance(raw, list):
        for item in raw:
            if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not safe_name(item["path"]):
                malformed.append(item)
            elif item["path"] in entries:
                malformed.append(item["path"])
            else:
                entries[item["path"]] = item
    else:
        malformed.append("missing list")
    c.check(not malformed, "Manifest file entries are well formed", malformed[:5])
    expected_manifest_names = set(actual) - {"RELEASE-MANIFEST.json", "SHA256SUMS.txt"}
    c.check(set(entries) == expected_manifest_names, "Manifest inventory is exact", {
        "missing": sorted(expected_manifest_names - set(entries)), "extra": sorted(set(entries) - expected_manifest_names)
    })
    bad = [
        name for name, item in entries.items() if name in actual and
        (item.get("sha256") != sha256(actual[name]) or item.get("bytes") != actual[name].stat().st_size)
    ]
    c.check(not bad, "Manifest hashes and byte counts match", bad)
    return manifest


def archive_files(c: Checks, path: Path, label: str) -> tuple[str | None, dict[str, bytes]]:
    try:
        with zipfile.ZipFile(path) as archive:
            infos = archive.infolist()
            names = [item.filename for item in infos]
            safe_paths = bool(names) and all(safe_name(name) for name in names)
            unique_names = len(names) == len(set(names))
            normalized = [unicodedata.normalize("NFC", name).casefold() for name in names]
            unique_normalized = len(normalized) == len(set(normalized))
            c.check(safe_paths, f"{label} paths are safe and nonempty")
            c.check(unique_names, f"{label} has no duplicate names")
            c.check(unique_normalized, f"{label} has no case/Unicode collisions")

            valid_names = [name for name in names if safe_name(name)]
            roots = {PurePosixPath(name).parts[0] for name in valid_names}
            root = next(iter(roots)) if len(roots) == 1 else None
            rooted_files = root is not None and all(
                item.is_dir() or item.filename.startswith(root + "/")
                for item in infos
            )
            c.check(root is not None, f"{label} has one root", sorted(roots))
            c.check(rooted_files, f"{label} has no file at or outside its root")

            symlinks: list[str] = []
            special: list[str] = []
            file_names: list[str] = []
            for item in infos:
                raw_mode = (item.external_attr >> 16) & 0xFFFF
                if stat.S_ISLNK(raw_mode):
                    symlinks.append(item.filename)
                if not item.is_dir():
                    file_names.append(item.filename)
                    file_type = stat.S_IFMT(raw_mode)
                    if raw_mode and file_type not in (0, stat.S_IFREG):
                        special.append(item.filename)
            prefix_conflicts = [
                name for name in file_names
                if any(other != name and other.startswith(name.rstrip("/") + "/") for other in names)
            ]
            c.check(not symlinks, f"{label} contains no symlinks", symlinks)
            c.check(not special, f"{label} contains only regular files and directories", special)
            c.check(not prefix_conflicts, f"{label} has no file/directory prefix conflicts", prefix_conflicts)
            if not (
                safe_paths and unique_names and unique_normalized and root is not None
                and rooted_files and not symlinks and not special and not prefix_conflicts
            ):
                return None, {}
            bad_crc = archive.testzip()
            c.check(bad_crc is None, f"{label} CRC passes", bad_crc)
            if bad_crc is not None:
                return None, {}
            data = {item.filename: archive.read(item) for item in infos if not item.is_dir()}
            return root, data
    except Exception as error:
        c.check(False, f"{label} opens and all members read", error)
        return None, {}


def compare_tree_archive(c: Checks, tree: Path, archive_path: Path, label: str) -> None:
    root, archived = archive_files(c, archive_path, label)
    if root is None:
        return
    stripped = {name[len(root) + 1:]: data for name, data in archived.items() if name.startswith(root + "/")}
    disk = files(tree)
    c.check(set(disk) == set(stripped), f"{label} unpacked inventory matches", {
        "missing": sorted(set(stripped) - set(disk)), "extra": sorted(set(disk) - set(stripped))
    })
    mismatches = [name for name in set(disk) & set(stripped) if disk[name].read_bytes() != stripped[name]]
    c.check(not mismatches, f"{label} unpacked bytes match", mismatches)


def check_required(c: Checks, package: Path, preassembly: bool) -> None:
    generated_or_copied = {
        "RELEASE-MANIFEST.json", "SHA256SUMS.txt", "SOURCE-INVENTORY.json",
        "implementation/STAFF-Functional-Build-Master-Prompt.md", "tools/verify-build-kit.py",
        "personalization/input-schemas/discover-packet-input.schema.json",
        "personalization/input-schemas/soul-profile-input.schema.json",
    }
    expected = [
        x for x in REQUIRED
        if not (preassembly and (x in generated_or_copied or x.startswith("source/")))
    ]
    missing = [name for name in expected if not (package / name).is_file()]
    empty = [name for name in expected if (package / name).is_file() and (package / name).stat().st_size == 0]
    c.check(not missing, "All required contracts and sources exist", missing)
    c.check(not empty, "All required contracts and sources are nonempty", empty)
    if (package / "VERSION").is_file():
        c.check((package / "VERSION").read_text(encoding="utf-8").strip() == "1.0.0", "Build-kit VERSION is 1.0.0")


def check_sources(c: Checks, package: Path, manifest: Any | None) -> None:
    prompt = package / PROMPT
    baseline_zip = package / BASELINE_ARCHIVE
    legacy_zip = package / LEGACY_ARCHIVE
    c.check(prompt.is_file() and sha256(prompt) == PROMPT_SHA, "Original functional prompt hash is exact", sha256(prompt) if prompt.is_file() else "missing")
    c.check(baseline_zip.is_file() and sha256(baseline_zip) == BASELINE_ZIP_SHA, "Baseline ZIP hash is exact", sha256(baseline_zip) if baseline_zip.is_file() else "missing")
    base_program = package / BASE_PROGRAM
    base_guide = package / BASE_GUIDE
    c.check(base_program.is_file() and sha256(base_program) == BASE_PROGRAM_SHA, "Standalone Staff Nurse foundation hash is exact", sha256(base_program) if base_program.is_file() else "missing")
    c.check(base_guide.is_file() and sha256(base_guide) == BASE_GUIDE_SHA, "Standalone Staff Nurse guide hash is exact", sha256(base_guide) if base_guide.is_file() else "missing")
    c.check(legacy_zip.is_file() and sha256(legacy_zip) == LEGACY_ZIP_SHA, "Legacy SHIFT outer ZIP hash is exact", sha256(legacy_zip) if legacy_zip.is_file() else "missing")
    if (package / BASELINE).is_dir() and baseline_zip.is_file():
        compare_tree_archive(c, package / BASELINE, baseline_zip, "Baseline source archive")
    else:
        c.check(False, "Baseline unpacked source and archive are present")
    if (package / LEGACY).is_dir() and legacy_zip.is_file():
        compare_tree_archive(c, package / LEGACY, legacy_zip, "Legacy SHIFT source archive")
    else:
        c.check(False, "Legacy SHIFT unpacked source and archive are present")
    shift = package / SHIFT_SOURCE
    observed = {name: sha256(shift / name) for name in SHIFT_TREE_HASHES if (shift / name).is_file()}
    c.check(observed == SHIFT_TREE_HASHES and set(files(shift)) == set(SHIFT_TREE_HASHES), "SHIFT source tree has exact 13 files and hashes", observed)
    tree_payload = "".join(f"{digest}  {name}\n" for name, digest in sorted(observed.items()))
    c.check(hashlib.sha256(tree_payload.encode("utf-8")).hexdigest() == "7b607658cceb23936e7a6d36dde322cbc9dba92584da3fceef108e55162b9f65", "SHIFT deterministic tree digest is exact")
    base_manifest = package / BASELINE / "RELEASE-MANIFEST.json"
    base_sums = package / BASELINE / "SHA256SUMS.txt"
    c.check(base_manifest.is_file() and sha256(base_manifest) == BASELINE_MANIFEST_SHA, "Baseline manifest hash is exact")
    c.check(base_sums.is_file() and sha256(base_sums) == BASELINE_CHECKSUMS_SHA, "Baseline checksum hash is exact")

    inventory = load_json(c, package / "SOURCE-INVENTORY.json", "Source inventory parses")
    if isinstance(inventory, dict):
        c.check(inventory.get("schema") == "NAIO-STAFF-SHIFT-BUILD-KIT-SOURCE-INVENTORY-1", "Source inventory schema is exact")
        expected_inputs = [
            {
                "id": "functional-build-master-prompt",
                "path": PROMPT.as_posix(),
                "sha256": PROMPT_SHA,
                "role": "immutable functional completeness and readiness source",
            },
            {
                "id": "mission-control-v2-baseline",
                "path": BASELINE_ARCHIVE.as_posix(),
                "sha256": BASELINE_ZIP_SHA,
                "role": "immutable working UI and state-machine baseline",
            },
            {
                "id": "staff-foundation-program",
                "path": BASE_PROGRAM.as_posix(),
                "sha256": BASE_PROGRAM_SHA,
                "role": "immutable standalone Staff Nurse Life & Practice foundation",
            },
            {
                "id": "staff-foundation-benefits-guide",
                "path": BASE_GUIDE.as_posix(),
                "sha256": BASE_GUIDE_SHA,
                "role": "immutable standalone user benefits and function guide",
            },
            {
                "id": "shift-legacy-outer-package",
                "path": LEGACY_ARCHIVE.as_posix(),
                "sha256": LEGACY_ZIP_SHA,
                "role": "immutable prior complete program/setup distribution",
            },
        ]
        c.check(inventory.get("inputs") == expected_inputs, "Source inventory input path/hash records are exact", inventory.get("inputs"))
        shift_tree = inventory.get("shift_domain_source_tree", {})
        expected_shift_files = [
            {"path": path, "sha256": digest}
            for path, digest in sorted(SHIFT_TREE_HASHES.items())
        ]
        c.check(
            isinstance(shift_tree, dict)
            and shift_tree.get("path") == SHIFT_SOURCE.as_posix()
            and shift_tree.get("original_standalone_archive_was_available") is False
            and shift_tree.get("deterministic_tree_digest") == "7b607658cceb23936e7a6d36dde322cbc9dba92584da3fceef108e55162b9f65"
            and shift_tree.get("files") == expected_shift_files,
            "Source inventory records the exact SHIFT path/hash tree and archive absence",
            shift_tree,
        )
        personal = inventory.get("personalization", {})
        c.check(isinstance(personal, dict) and all(personal.get(key) is False for key in (
            "real_discover_packet_bundled", "real_soul_quiz_result_bundled", "raw_soul_or_quiz_answers_bundled", "synthetic_examples_are_personal_facts", "synthetic_examples_are_badge_evidence"
        )), "Source inventory truthfully labels personalization")
        institutional = inventory.get("institutional_qi_workspace", {})
        c.check(isinstance(institutional, dict) and institutional == {
            "provisioned_by_this_kit": False,
            "authorized_by_this_kit": False,
            "real_quality_data_bundled": False,
        }, "Source inventory truthfully labels institutional-QI state")
        c.check(
            inventory.get("readiness") == "build instructions complete; target application and institutional-QI readiness not established",
            "Source inventory readiness is exact",
        )
    if isinstance(manifest, dict):
        sources = manifest.get("sources", {})
        c.check(sources == {
            "original_functional_build_prompt": PROMPT_SHA,
            "baseline_application_zip": BASELINE_ZIP_SHA,
            "staff_base_program": BASE_PROGRAM_SHA,
            "staff_base_guide": BASE_GUIDE_SHA,
            "shift_legacy_outer_zip": LEGACY_ZIP_SHA,
        }, "Release manifest records pinned source archives")


def check_domain(c: Checks, package: Path) -> None:
    source = package / SHIFT_SOURCE
    power_files = sorted((source / "shift").glob("*.md"))
    powers_text = "\n".join(path.read_text(encoding="utf-8") for path in power_files)
    workflow_text = (source / "workflows/SHIFT-Launch-and-Impact-Plan.md").read_text(encoding="utf-8")
    template_text = (source / "templates/SHIFT-Cards-and-Templates.md").read_text(encoding="utf-8")
    tests_text = (source / "tests/SHIFT-Acceptance-Tests.md").read_text(encoding="utf-8")
    manifest_text = (source / "manifest.md").read_text(encoding="utf-8")
    foundation_text = (package / BASE_PROGRAM).read_text(encoding="utf-8")
    powers = [int(x) for x in re.findall(r"(?m)^## Power (\d+) —", powers_text)]
    recipes = [int(x) for x in re.findall(r"(?m)^(\d+)\. \*\*[^\n]+:\*\*", workflow_text)]
    templates = [int(x) for x in re.findall(r"(?m)^## Template (\d+) —", template_text)]
    foundation_section = foundation_text.split("# 20. Acceptance tests", 1)[1].split("# 21.", 1)[0]
    foundation = re.findall(r"(?m)^- ", foundation_section)
    overlay = re.findall(r"(?m)^- \*\*[A-O](?:[1-8]):\*\*", tests_text)
    integration = re.findall(r"(?m)^- \*\*INT(?:0[1-9]|1[0-6]):\*\*", tests_text)
    c.check(powers == list(range(1, 21)), "Exactly 20 ordered canonical SHIFT powers", powers)
    c.check(len(power_files) == 5 and all("install inactive" in path.read_text(encoding="utf-8") for path in power_files) and "Optional powers: 20, all inactive" in manifest_text, "All 20 canonical powers install inactive")
    c.check(recipes == list(range(1, 19)), "Exactly 18 ordered canonical SHIFT workflows", recipes)
    c.check(templates == list(range(1, 26)), "Exactly 25 ordered canonical SHIFT templates", templates)
    c.check((len(foundation), len(overlay), len(integration)) == (40, 120, 16), "Canonical checks are exactly 40 + 120 + 16 = 176", (len(foundation), len(overlay), len(integration)))
    c.check(all(value in manifest_text for value in ("NAIO-SNQI-COMPLETE-SHIFT-1.0", "NAIO-SN-LPEF-1.0", "NAIO-SNQI-SHIFT-1.0", "snqi_shift.*")), "Canonical Staff Nurse + SHIFT identities are exact")


def check_contracts(c: Checks, package: Path, manifest: Any | None) -> None:
    check_controlled_placeholders(c, package)
    prompt = package / "implementation/STAFF-Functional-Build-Master-Prompt.md"
    if prompt.is_file():
        text = prompt.read_text(encoding="utf-8")
        c.check(not [p for p in PLACEHOLDERS if p in text], "Resolved master prompt has no unresolved placeholders")
        for needle in (
            BUILD_ID,
            "staff-nurse-life-practice-mission-control",
            "staff_nurse_life_practice",
            "/staff-nurses/dashboard",
            "snqi_shift.*",
            "NAIO-STAFF-DISCOVER-PACKET-ADAPTER-1",
            "NAIO-STAFF-SOUL-PROFILE-ADAPTER-1",
            "not_operational_build_required",
        ):
            c.check(needle in text, f"Resolved master prompt contains {needle}")

    json_errors: list[str] = []
    for path in package.rglob("*.json"):
        try:
            strict_json_loads(path.read_text(encoding="utf-8"))
        except Exception as error:
            json_errors.append(f"{path.relative_to(package)}: {error}")
    c.check(not json_errors, "Every JSON file parses", json_errors)

    agent_text = (package / "implementation/STAFF-Agent-Team-and-Routing.md").read_text(encoding="utf-8")
    registry_rows = []
    for row in markdown_table_rows(agent_text):
        if row and re.fullmatch(r"`SHIFT-AGT-(?:0[1-9]|10)`", row[0]):
            registry_rows.append(row)
    observed_agents = {
        row[0].strip("`"): row[1]
        for row in registry_rows
        if len(row) >= 5
    }
    c.check(
        len(registry_rows) == 10
        and observed_agents == EXPECTED_AGENTS
        and all(len(row) >= 5 and row[3] == "`PERM-P0 Disabled`" for row in registry_rows),
        "Agent registry has the exact ten IDs, names, and P0 installed defaults",
        observed_agents,
    )
    c.check("**Installed agent state:** `PERM-P0 Disabled`" in agent_text and "PERM-P1" in agent_text and "PERM-P2" in agent_text and "PERM-P3" in agent_text and "Not an agent/model permission" in agent_text and "PERM-P4" in agent_text and "**Absent.**" in agent_text, "Agent contract records P0 default, P1/P2 ceiling, P3 reminder-only, and absent P4")
    if prompt.is_file():
        prompt_text = prompt.read_text(encoding="utf-8")
        c.check(
            all(identifier in prompt_text and name in prompt_text for identifier, name in EXPECTED_AGENTS.items()),
            "Resolved master prompt uses the frozen agent registry",
        )
        c.check(
            "abstract, screened, non-reconstructable reflection" in prompt_text
            and "deidentified reflection" not in prompt_text
            and "a separately approved aggregate created outside SHIFT and explicitly authorized for that workspace" in prompt_text,
            "Resolved master prompt freezes non-reconstructable reflection and outside-SHIFT aggregate boundaries",
        )

    cap = load_json(c, package / "config/STAFF-Capability-Mastery-Criteria.v1.json", "Capability criteria parse")
    if isinstance(cap, dict):
        c.check(
            normalized_digest(cap) == EXPECTED_CAPABILITY_CONFIG_DIGEST,
            "Normative capability configuration matches its frozen full semantic digest",
            normalized_digest(cap),
        )
        c.check(cap.get("schema") == "NAIO-STAFF-SHIFT-CAPABILITY-MASTERY-CRITERIA-1", "Capability criteria schema ID is exact")
        c.check(cap.get("counts") == {"domains": 17, "levels": 4, "domain_criteria": 68, "capstone_criteria": 9, "total_criteria": 77}, "Capability criteria counts are 17/4/68+9=77", cap.get("counts"))
        eligibility = cap.get("eligibility")
        c.check(
            isinstance(eligibility, dict)
            and eligibility.get("allowed_evidence_types") == EXPECTED_EVIDENCE_TYPES
            and eligibility.get("excluded") == EXPECTED_EVIDENCE_EXCLUSIONS
            and eligibility.get("recompute_triggers") == EXPECTED_RECOMPUTE_TRIGGERS,
            "Capability evidence types, exclusions, and recompute triggers are exact",
            eligibility,
        )
        expected_contextual_review_policy = {
            "applies_to_all_levels": True,
            "interpretation": "The per-criterion requires_human_review Boolean is an unconditional minimum. False never means review is waived; it means apply this contextual policy.",
            "triggers": [
                "professional_or_portfolio_evidence",
                "credential_or_required_education_evidence",
                "employment_or_institutional_context",
                "quality_improvement_or_project_outcome_evidence",
                "edena_yellow_or_orange",
                "otherwise_consequential_artifact_or_claim",
            ],
            "required_result": "current_scope_matched_named_human_process_review_before_award",
            "red_rule": "edena_red_is_ineligible_until_the_separate_governance_route_permits_a_clean_eligible_artifact_and_all_required_review_is_complete",
            "cannot_be_waived_by": [
                "criterion_default_false",
                "user_preference",
                "ai_recommendation",
                "synthetic_activity",
                "prior_review_for_a_different_scope",
            ],
        }
        c.check(
            cap.get("contextual_human_review_policy") == expected_contextual_review_policy,
            "Capability model freezes the normative contextual named-human review policy",
            cap.get("contextual_human_review_policy"),
        )
        domains = cap.get("domains", [])
        valid_domains = isinstance(domains, list) and all(isinstance(domain, dict) for domain in domains)
        domain_ids = [domain.get("id") for domain in domains] if valid_domains else []
        criteria = [
            item
            for domain in domains if isinstance(domain, dict)
            for item in domain.get("criteria", []) if isinstance(item, dict)
        ]
        expected_criteria_ids = [
            f"CAP-{domain:02d}-L{level}-01"
            for domain in range(1, 18)
            for level in range(1, 5)
        ]
        criteria_ids = [item.get("id") for item in criteria]
        level_rows = cap.get("levels")
        level_ids = [item.get("id") for item in level_rows] if isinstance(level_rows, list) and all(isinstance(item, dict) for item in level_rows) else []
        capstone = cap.get("global_orchestration_capstone")
        capstone_rows = capstone.get("criteria") if isinstance(capstone, dict) else None
        capstone_ids = [item.get("id") for item in capstone_rows] if isinstance(capstone_rows, list) and all(isinstance(item, dict) for item in capstone_rows) else []
        all_criteria_ids = criteria_ids + capstone_ids
        expected_level_contract = {
            "L1": (None, 1, False, "P1", False),
            "L2": ("L1", 2, True, "P1", False),
            "L3": ("L2", 3, True, "P2", False),
            "L4": ("L3", 1, True, "P2", True),
        }
        level_prerequisites_ok = (
            isinstance(level_rows, list)
            and all(isinstance(item, dict) for item in level_rows)
            and all(
                "prerequisite_level" in item
                and item.get("prerequisite_level") == expected_level_contract[item.get("id")][0]
                for item in level_rows
                if item.get("id") in expected_level_contract
            )
            and len(level_rows) == len(expected_level_contract)
        )
        criterion_contracts_ok = all(
            item.get("required") is True
            and isinstance(item.get("description"), str)
            and bool(item["description"].strip())
            and (match := re.fullmatch(r"CAP-\d{2}-(L[1-4])-01", str(item.get("id", "")))) is not None
            and (
                item.get("prerequisite_level"),
                item.get("minimum_distinct_real_missions"),
                item.get("requires_human_review"),
                item.get("agent_permission_ceiling"),
                item.get("requires_global_orchestration_capstone"),
            ) == expected_level_contract[match.group(1)]
            and item.get("human_review_rule") == (
                "contextual_policy" if match.group(1) == "L1" else "unconditional_plus_contextual_policy"
            )
            for item in criteria
        )
        c.check(
            valid_domains
            and domain_ids == [f"CAP-{i:02d}" for i in range(1, 18)]
            and all(isinstance(domain.get("criteria"), list) and len(domain["criteria"]) == 4 for domain in domains)
            and criteria_ids == expected_criteria_ids
            and level_ids == ["L1", "L2", "L3", "L4"]
            and level_prerequisites_ok
            and capstone_ids == [f"CAPSTONE-{i:02d}" for i in range(1, 10)]
            and len(all_criteria_ids) == len(set(all_criteria_ids)) == 77,
            "Capability model recomputes to 17 domains x 4 levels plus 9 unique capstone criteria",
            {"domains": len(domain_ids), "levels": level_ids, "criteria": len(criteria_ids), "capstone": len(capstone_ids)},
        )
        c.check(criterion_contracts_ok, "Every domain criterion freezes its exact prerequisite, level evidence, and contextual-review contract")
        alignment = cap.get("shift_alignment", {})
        c.check(isinstance(alignment, dict) and alignment.get("source_defined_badge_system") is False and len(alignment.get("core_four", [])) == 4, "Capability model is truthfully build-layer and preserves Core Four")

    source_registry = load_json(
        c,
        package / "config/STAFF-Source-Recommendation-Registry.v1.json",
        "Source recommendation registry parses",
    )
    source_entries_by_id: dict[str, dict[str, Any]] = {}
    if isinstance(source_registry, dict):
        c.check(
            normalized_digest(source_registry) == EXPECTED_SOURCE_REGISTRY_DIGEST,
            "Normative source registry matches its frozen full semantic digest",
            normalized_digest(source_registry),
        )
        raw_entries = source_registry.get("entries")
        registry_entries = raw_entries if isinstance(raw_entries, list) else []
        entry_ids = [entry.get("id") for entry in registry_entries if isinstance(entry, dict)]
        expected_source_ids = list(EXPECTED_SOURCE_RECOMMENDATIONS)
        exact_entry_keys = {
            "id", "title", "path", "sha256", "source_kind", "workspace_types", "purpose",
        }
        entry_errors: list[str] = []
        for entry in registry_entries:
            if not isinstance(entry, dict):
                entry_errors.append("non-object entry")
                continue
            identifier = entry.get("id")
            expected = EXPECTED_SOURCE_RECOMMENDATIONS.get(identifier)
            if expected is None:
                entry_errors.append(f"{identifier!r}: unknown ID")
                continue
            expected_path, expected_hash, expected_workspaces = expected
            if (
                set(entry) != exact_entry_keys
                or entry.get("path") != expected_path
                or entry.get("sha256") != expected_hash
                or entry.get("workspace_types") != expected_workspaces
                or not isinstance(entry.get("title"), str)
                or not entry["title"].strip()
                or not isinstance(entry.get("source_kind"), str)
                or not entry["source_kind"].strip()
                or not isinstance(entry.get("purpose"), str)
                or not entry["purpose"].strip()
            ):
                entry_errors.append(f"{identifier}: metadata mismatch")
                continue
            source_entries_by_id[identifier] = entry
        expected_rules = {
            "exact_id_set": "SNLP-SRC-01..SNLP-SRC-10",
            "unknown_id_behavior": "reject_and_show_content_free_configuration_error",
            "hash_mismatch_behavior": "disable_recommendation_and_require_human_review",
            "missing_source_behavior": "disable_recommendation_and_preserve_no_stale_claim",
            "local_policy_precedence": True,
            "recommendation_grants_authority": False,
        }
        c.check(
            set(source_registry) == {"schema", "version", "status", "notice", "rules", "entries", "count"}
            and source_registry.get("schema") == "NAIO-STAFF-SOURCE-RECOMMENDATION-REGISTRY-1"
            and source_registry.get("version") == "1.0.0"
            and source_registry.get("status") == "normative_build_layer_contract"
            and source_registry.get("count") == 10
            and entry_ids == expected_source_ids
            and len(set(entry_ids)) == 10
            and source_registry.get("rules") == expected_rules
            and not entry_errors,
            "Source registry freezes exact schema, IDs, paths, hashes, workspace applicability, and fail-closed rules",
            entry_errors,
        )
        if manifest is not None:
            source_file_errors: list[str] = []
            for identifier, entry in source_entries_by_id.items():
                relative = entry["path"]
                source_path = package / relative
                if (
                    not safe_name(relative)
                    or not source_path.is_file()
                    or source_path.is_symlink()
                    or sha256(source_path) != entry["sha256"]
                ):
                    source_file_errors.append(identifier)
            c.check(
                not source_file_errors and len(source_entries_by_id) == 10,
                "Every source recommendation resolves to its exact regular file and pinned release hash",
                source_file_errors,
            )

    discover_schema_path = package / "schemas/STAFF-Discover-Packet.schema.json"
    soul_schema_path = package / "schemas/STAFF-Soul-Profile.schema.json"
    mission_schema_path = package / "schemas/STAFF-Mission-Profile.schema.json"
    discover_schema = load_json(c, discover_schema_path, "Staff Discover Packet schema parses")
    soul_schema = load_json(c, soul_schema_path, "Staff Soul Profile schema parses")
    schema = load_json(c, mission_schema_path, "Mission Profile schema parses")
    discover = load_json(c, package / "personalization/STAFF-Discover-Packet.synthetic.example.json", "Synthetic Discover Packet parses")
    soul = load_json(c, package / "personalization/STAFF-Soul-Profile.synthetic.example.json", "Synthetic Soul Profile parses")
    profile = load_json(c, package / "personalization/STAFF-Mission-Profile.synthetic.example.json", "Synthetic Mission Profile parses")
    copied_discover_schema = package / "personalization/input-schemas/discover-packet-input.schema.json"
    copied_soul_schema = package / "personalization/input-schemas/soul-profile-input.schema.json"
    if manifest is not None or copied_discover_schema.exists() or copied_soul_schema.exists():
        c.check(
            copied_discover_schema.is_file()
            and copied_soul_schema.is_file()
            and copied_discover_schema.read_bytes() == discover_schema_path.read_bytes()
            and copied_soul_schema.read_bytes() == soul_schema_path.read_bytes(),
            "Packaged personalization input schemas are exact copies of the Staff adapter schemas",
        )
    if isinstance(discover_schema, dict) and isinstance(discover, dict):
        errors = validate_json_schema(discover, discover_schema)
        c.check(not errors, "Synthetic Discover fixture validates against its actual Staff JSON Schema", errors[:20])
    if isinstance(soul_schema, dict) and isinstance(soul, dict):
        errors = validate_json_schema(soul, soul_schema)
        c.check(not errors, "Synthetic Soul fixture validates against its actual Staff JSON Schema", errors[:20])
    if isinstance(schema, dict) and isinstance(profile, dict):
        errors = validate_json_schema(profile, schema)
        c.check(not errors, "Synthetic Mission fixture validates against its actual Staff JSON Schema", errors[:20])

    negative_schema_probes: list[tuple[str, bool]] = []
    if isinstance(discover_schema, dict) and isinstance(discover, dict):
        probe = deepcopy(discover)
        probe["raw_answers"] = ["forbidden"]
        negative_schema_probes.append(("Discover rejects undeclared raw answers", bool(validate_json_schema(probe, discover_schema))))
        probe = deepcopy(discover)
        probe["schema"] = "WRONG-DISCOVER-SCHEMA"
        negative_schema_probes.append(("Discover rejects wrong adapter ID", bool(validate_json_schema(probe, discover_schema))))
    if isinstance(soul_schema, dict) and isinstance(soul, dict):
        probe = deepcopy(soul)
        probe["raw_answers"] = ["forbidden"]
        negative_schema_probes.append(("Soul rejects raw answers", bool(validate_json_schema(probe, soul_schema))))
        probe = deepcopy(soul)
        probe["raw_answers_present"] = True
        negative_schema_probes.append(("Soul rejects raw-answer-presence true", bool(validate_json_schema(probe, soul_schema))))
    if (
        isinstance(discover_schema, dict)
        and isinstance(soul_schema, dict)
        and isinstance(discover, dict)
        and isinstance(soul, dict)
    ):
        negative_schema_probes.append((
            "Discover schema rejects incompatible Soul shape",
            bool(validate_json_schema(soul, discover_schema)),
        ))
        negative_schema_probes.append((
            "Soul schema rejects incompatible Discover shape",
            bool(validate_json_schema(discover, soul_schema)),
        ))
    if isinstance(schema, dict) and isinstance(profile, dict):
        probe = deepcopy(profile)
        probe["institutional_runtime_bind_required"] = False
        negative_schema_probes.append(("Mission rejects disabled institutional bind", bool(validate_json_schema(probe, schema))))
        probe = deepcopy(profile)
        probe["undeclared_authority"] = True
        negative_schema_probes.append(("Mission rejects undeclared authority", bool(validate_json_schema(probe, schema))))
    c.check(
        bool(negative_schema_probes) and all(rejected for _, rejected in negative_schema_probes),
        "Staff JSON Schemas reject all deterministic negative guard probes",
        [name for name, rejected in negative_schema_probes if not rejected],
    )
    c.check(
        isinstance(discover_schema, dict)
        and discover_schema.get("$id") == "https://nurse-ai-os.local/schemas/staff-discover-packet-adapter-1.schema.json"
        and isinstance(discover_schema.get("properties"), dict)
        and discover_schema["properties"].get("schema", {}).get("const") == "NAIO-STAFF-DISCOVER-PACKET-ADAPTER-1"
        and isinstance(soul_schema, dict)
        and soul_schema.get("$id") == "https://nurse-ai-os.local/schemas/staff-soul-profile-adapter-1.schema.json"
        and isinstance(soul_schema.get("properties"), dict)
        and soul_schema["properties"].get("schema", {}).get("const") == "NAIO-STAFF-SOUL-PROFILE-ADAPTER-1",
        "Staff Discover and Soul schemas freeze their exact adapter IDs",
    )
    if isinstance(discover, dict):
        discover_assets = discover.get("asset_recommendations")
        c.check(
            discover.get("schema") == "NAIO-STAFF-DISCOVER-PACKET-ADAPTER-1"
            and discover.get("status") == "synthetic_example_unapproved"
            and discover.get("demo") is True
            and discover.get("owner_confirmed") is False
            and isinstance(discover_assets, dict)
            and discover_assets.get("activation_state") == "recommendations_only_inactive"
            and discover_assets.get("agent_permission_state") == "PERM-P0 Disabled"
            and discover_assets.get("tool_state") == "disabled"
            and discover_assets.get("tool_ids") == [],
            "Discover fixture is synthetic, unapproved, inactive, P0, and tool-free",
        )
    if isinstance(soul, dict):
        soul_ai = soul.get("derived_ai_boundaries")
        prohibited_raw_keys = {"raw_answers", "raw_quiz_answers", "raw_soul", "soul_md", "transcript", "responses"}
        c.check(
            soul.get("schema") == "NAIO-STAFF-SOUL-PROFILE-ADAPTER-1"
            and soul.get("status") == "synthetic_example_unapproved"
            and soul.get("demo") is True
            and soul.get("raw_answers_present") is False
            and not (nested_keys(soul) & prohibited_raw_keys)
            and isinstance(soul_ai, dict)
            and soul_ai.get("agent_state") == "disabled"
            and soul_ai.get("agent_permission_state") == "PERM-P0 Disabled"
            and soul_ai.get("tools") == []
            and soul_ai.get("external_actions") == "off",
            "Soul fixture is derived-only, synthetic, unapproved, P0, tool-free, and contains no raw-answer fields",
        )
    if isinstance(schema, dict) and isinstance(profile, dict):
        required = set(schema.get("required", []))
        properties = set(schema.get("properties", {}))
        c.check(required <= set(profile) <= properties, "Synthetic profile matches declared top-level property set", {"missing": sorted(required-set(profile)), "extra": sorted(set(profile)-properties)})
        schema_properties = schema.get("properties") if isinstance(schema.get("properties"), dict) else {}
        c.check(
            schema.get("$id") == "https://nurse-ai-os.local/schemas/staff-mission-profile-1.schema.json"
            and schema_properties.get("schema", {}).get("const") == "NAIO-STAFF-MISSION-PROFILE-1"
            and schema_properties.get("product_id", {}).get("const") == "staff-nurse-life-practice-mission-control"
            and schema_properties.get("lane", {}).get("const") == "staff_nurse_life_practice"
            and schema_properties.get("namespace", {}).get("const") == "snqi_shift.*"
            and schema_properties.get("canonical_route", {}).get("const") == "/staff-nurses/dashboard"
            and schema_properties.get("institutional_runtime_bind_required", {}).get("const") is True,
            "Mission Profile schema freezes the exact target identity",
        )
        authority_schema = schema_properties.get("authority_context", {})
        authority_schema_properties = (
            authority_schema.get("properties") if isinstance(authority_schema, dict) else None
        )
        deployment_values = (
            authority_schema_properties.get("deployment_context", {}).get("enum")
            if isinstance(authority_schema_properties, dict) else None
        )
        c.check(
            deployment_values == ["private_personal_mode", "institution_approved_quality_workspace"],
            "Mission Profile declares exactly the two Staff deployment contexts",
            deployment_values,
        )
        schema_definitions = schema.get("$defs") if isinstance(schema.get("$defs"), dict) else {}
        source_id_schema = schema_definitions.get("sourceRecommendationId", {})
        c.check(
            isinstance(source_id_schema, dict)
            and source_id_schema.get("enum") == list(EXPECTED_SOURCE_RECOMMENDATIONS)
            and "pattern" not in source_id_schema,
            "Mission Profile schema freezes the exact ten source-recommendation IDs as an enum",
            source_id_schema,
        )
        c.check(profile.get("schema") == "NAIO-STAFF-MISSION-PROFILE-1" and profile.get("profile_version") == "1.0-draft", "Synthetic profile contract/version is exact")
        c.check((profile.get("product_id"), profile.get("lane"), profile.get("namespace"), profile.get("canonical_route")) == (
            "staff-nurse-life-practice-mission-control", "staff_nurse_life_practice", "snqi_shift.*", "/staff-nurses/dashboard"
        ), "Synthetic profile target identity is exact")
        authority = profile.get("authority_context")
        c.check(
            profile.get("status") == "proposed"
            and profile.get("approved_at") is None
            and profile.get("demo") is True
            and profile.get("institutional_runtime_bind_required") is True
            and isinstance(authority, dict)
            and authority.get("deployment_context") == "private_personal_mode"
            and authority.get("employer_project_boundary") == "private_owner_only"
            and authority.get("qi_workspace_status") == "not_applicable"
            and authority.get("qi_or_research_determination") == "synthetic_not_applicable"
            and authority.get("human_determination_status") == "not_applicable"
            and authority.get("data_authority_status") == "not_applicable"
            and authority.get("change_authority_status") == "not_applicable"
            and authority.get("release_authority_status") == "not_applicable"
            and authority.get("runtime_workspace_bind_status") == "not_applicable"
            and authority.get("runtime_workspace_bind_ref") is None,
            "Synthetic profile is proposed, unapproved, private, and claims no institutional-QI authority",
        )
        workspaces = profile.get("role_workspaces", [])
        valid_workspaces = isinstance(workspaces, list) and all(isinstance(workspace, dict) for workspace in workspaces)
        c.check(
            valid_workspaces
            and len(workspaces) == 5
            and sum(workspace.get("relationship") == "primary" for workspace in workspaces) == 1
            and sum(workspace.get("active") is True for workspace in workspaces) == 1
            and all((workspace.get("active") is True) == (workspace.get("relationship") == "primary") for workspace in workspaces)
            and len({workspace.get("workspace_id") for workspace in workspaces}) == 5
            and {workspace.get("workspace_id") for workspace in workspaces} == {
                "staff-practice", "staff-quality-improvement", "staff-professional-growth",
                "staff-life-recovery", "staff-community-leadership",
            }
            and {workspace.get("workspace_type") for workspace in workspaces} == {"practice", "quality_improvement", "professional_growth", "life_recovery", "community_leadership"},
            "Synthetic profile has five exact protected workspaces and exactly one active Primary",
        )
        recommendation_issues = recommendation_errors(profile.get("recommended_assets"), "profile")
        for workspace in workspaces if valid_workspaces else []:
            recommendation_issues.extend(
                recommendation_errors(workspace.get("recommended_assets"), str(workspace.get("workspace_type")))
            )
        c.check(not recommendation_issues, "Top-level and workspace recommendations are inactive, P0, disabled, valid, unique, and tool-free", recommendation_issues)
        source_recommendation_issues: list[str] = []
        top_assets = profile.get("recommended_assets")
        if isinstance(top_assets, dict):
            for identifier in top_assets.get("source_recommendation_ids", []):
                if identifier not in source_entries_by_id:
                    source_recommendation_issues.append(f"profile/{identifier}: unresolved")
        for workspace in workspaces if valid_workspaces else []:
            workspace_type = workspace.get("workspace_type")
            assets = workspace.get("recommended_assets")
            if not isinstance(assets, dict):
                continue
            for identifier in assets.get("source_recommendation_ids", []):
                entry = source_entries_by_id.get(identifier)
                if entry is None:
                    source_recommendation_issues.append(f"{workspace_type}/{identifier}: unresolved")
                elif workspace_type not in entry.get("workspace_types", []):
                    source_recommendation_issues.append(f"{workspace_type}/{identifier}: inapplicable")
        c.check(
            not source_recommendation_issues,
            "Every Mission Profile source recommendation resolves and is applicable to its workspace",
            source_recommendation_issues,
        )
        represented_agents = {
            value
            for workspace in workspaces if isinstance(workspace, dict)
            for value in workspace.get("recommended_assets", {}).get("agent_ids", [])
        }
        c.check(represented_agents == set(EXPECTED_AGENTS), "Synthetic workspace recommendations represent all ten inert agents")
        aliases = set(cap.get("recommendation_aliases", {})) if isinstance(cap, dict) else set()
        all_assets = [profile.get("recommended_assets")] + [workspace.get("recommended_assets") for workspace in workspaces if isinstance(workspace, dict)]
        used_capabilities = {
            value for asset in all_assets if isinstance(asset, dict)
            for value in asset.get("capability_ids", [])
        }
        c.check(used_capabilities <= aliases, "Synthetic capability recommendations resolve to the normative criteria", sorted(used_capabilities - aliases))
        situation = profile.get("situation_context")
        active_matches = []
        if isinstance(situation, dict) and valid_workspaces:
            active_matches = [
                workspace for workspace in workspaces
                if workspace.get("active") is True
                and workspace.get("workspace_id") == situation.get("active_workspace_id")
                and workspace.get("workspace_type") == situation.get("active_workspace_type")
                and workspace.get("role_adapter") == situation.get("active_role_adapter")
                and workspace.get("operational_context") == situation.get("active_operational_context")
                and workspace.get("employer_project_boundary") == situation.get("active_employer_project_boundary")
            ]
        c.check(
            isinstance(situation, dict)
            and situation.get("one_active_context_per_mission") is True
            and len(active_matches) == 1
            and isinstance(authority, dict)
            and authority.get("active_operational_context") == situation.get("active_operational_context")
            and authority.get("role_adapter") == situation.get("active_role_adapter")
            and authority.get("employer_project_boundary") == situation.get("active_employer_project_boundary")
            and (
                authority.get("deployment_context") == "institution_approved_quality_workspace"
            ) == (
                situation.get("active_operational_context") == "institution_approved_quality"
            ),
            "Synthetic profile has one internally consistent active workspace/context and bidirectional deployment alignment",
        )

        institutional_probe = deepcopy(profile)
        institutional_probe["demo"] = False
        institutional_situation = institutional_probe.get("situation_context", {})
        institutional_authority = institutional_probe.get("authority_context", {})
        institutional_governance = institutional_probe.get("governance_preferences", {})
        institutional_workspaces = institutional_probe.get("role_workspaces", [])
        if isinstance(institutional_situation, dict):
            institutional_situation["active_workspace_id"] = "staff-quality-improvement"
            institutional_situation["active_workspace_type"] = "quality_improvement"
            institutional_situation["active_role_adapter"] = "direct_care_staff_nurse"
            institutional_situation["active_operational_context"] = "institution_approved_quality"
            institutional_situation["active_employer_project_boundary"] = "institution_verified_project_only"
        if isinstance(institutional_authority, dict):
            institutional_authority.update({
                "deployment_context": "institution_approved_quality_workspace",
                "employer_project_boundary": "institution_verified_project_only",
                "active_operational_context": "institution_approved_quality",
                "scope_status": "verified_current",
                "employer_policy_status": "verified_current",
                "qi_workspace_status": "verified_current",
                "qi_or_research_determination": "human_determined_qi",
                "human_determination_status": "verified_current",
                "data_authority_status": "verified_current",
                "change_authority_status": "verified_current",
                "release_authority_status": "verified_current",
                "runtime_workspace_bind_status": "verified_current",
                "human_determination_ref": "ext:fixture/human-determination",
                "data_authority_ref": "ext:fixture/data-authority",
                "change_authority_ref": "ext:fixture/change-authority",
                "release_authority_ref": "ext:fixture/release-authority",
                "institutional_project_boundary_ref": "ext:fixture/project-boundary",
                "runtime_workspace_bind_ref": "ext:fixture/runtime-bind",
                "verified_at": "2026-07-20T12:00:00Z",
                "expires_at": "2026-08-20T12:00:00Z",
            })
        if isinstance(institutional_governance, dict):
            institutional_governance["edition"] = "institutional_managed"
            institutional_governance["data_boundary"] = "approved_aggregate_institutional_in_separate_workspace"
        if isinstance(institutional_workspaces, list):
            for workspace in institutional_workspaces:
                if not isinstance(workspace, dict):
                    continue
                if workspace.get("workspace_type") == "quality_improvement":
                    workspace.update({
                        "active": True,
                        "relationship": "primary",
                        "operational_context": "institution_approved_quality",
                        "employer_project_boundary": "institution_verified_project_only",
                        "authorization_status": "externally_verified",
                    })
                else:
                    workspace["active"] = False
                    if workspace.get("relationship") == "primary":
                        workspace["relationship"] = "supporting"
        institutional_errors = validate_json_schema(institutional_probe, schema)
        forward_mismatch = deepcopy(profile)
        if isinstance(forward_mismatch.get("authority_context"), dict):
            forward_mismatch["authority_context"]["deployment_context"] = "institution_approved_quality_workspace"
        reverse_mismatch = deepcopy(institutional_probe)
        if isinstance(reverse_mismatch.get("authority_context"), dict):
            reverse_mismatch["authority_context"]["deployment_context"] = "private_personal_mode"
        c.check(
            not institutional_errors
            and bool(validate_json_schema(forward_mismatch, schema))
            and bool(validate_json_schema(reverse_mismatch, schema)),
            "Mission schema accepts a fully bound institutional profile and rejects both deployment/context mismatch directions",
            institutional_errors[:20],
        )
        ai = profile.get("ai_preferences")
        memory = profile.get("memory_preferences")
        boundaries = profile.get("practice_quality_boundaries")
        boundary_flags = {
            "no_phi", "no_live_care", "no_shadow_charting",
            "no_person_level_workforce_or_quality_data", "no_scope_or_competence_decisions",
            "no_official_reporting", "private_life_never_enters_institutional_workspace",
        }
        c.check(
            isinstance(ai, dict)
            and ai.get("agent_state") == "disabled"
            and ai.get("agent_permission_state") == "PERM-P0 Disabled"
            and ai.get("tool_state") == "disabled"
            and ai.get("automation_state") == "manual_preview_only"
            and ai.get("external_action_state") == "off"
            and isinstance(memory, dict)
            and memory.get("enabled") is False
            and memory.get("allowed_categories") == []
            and memory.get("default_retention_days") == 0
            and isinstance(boundaries, dict)
            and all(boundaries.get(flag) is True for flag in boundary_flags),
            "Synthetic profile freezes AI, memory, external-action, and practice/QI safety defaults",
        )
        provenance = profile.get("field_provenance")
        required_provenance = {
            "/display_name", "/mission_statement", "/core_values", "/current_priorities",
            "/strengths_and_growth", "/situation_context", "/goals", "/working_preferences",
            "/role_workspaces", "/authority_context", "/practice_quality_boundaries",
            "/ai_preferences", "/memory_preferences", "/governance_preferences",
            "/recommended_assets", "/presentation_preferences", "/accessibility_preferences",
            "/institutional_runtime_bind_required", "/uncertainties",
        }
        provenance_fields = {
            item.get("field") for item in provenance if isinstance(item, dict)
        } if isinstance(provenance, list) else set()
        c.check(
            isinstance(provenance, list)
            and all(isinstance(item, dict) and item.get("approval_status") == "proposed" and item.get("approved_at") is None for item in provenance)
            and required_provenance <= provenance_fields,
            "Synthetic profile preserves proposed, unapproved provenance for every approval group",
            sorted(required_provenance - provenance_fields),
        )

    matrix_path = package / "implementation/STAFF-Control-Completeness-Matrix.csv"
    try:
        with matrix_path.open(newline="", encoding="utf-8") as stream:
            reader = csv.DictReader(stream)
            rows = list(reader)
            matrix_columns = tuple(reader.fieldnames or ())
    except Exception as error:
        c.check(False, "Control matrix parses", error)
        rows = []
        matrix_columns = ()
    ids = [row.get("control_id", "") for row in rows]
    control_id_digest = hashlib.sha256(("\n".join(ids) + "\n").encode("utf-8")).hexdigest()
    expected_pattern = r"^[A-Z][A-Z0-9_]{1,15}-[0-9]{3}$"
    empty_matrix_cells = [
        f"row {index + 2}/{column}"
        for index, row in enumerate(rows)
        for column in EXPECTED_MATRIX_COLUMNS
        if not str(row.get(column, "")).strip()
    ]
    c.check(
        matrix_columns == EXPECTED_MATRIX_COLUMNS
        and len(rows) == EXPECTED_MATRIX_ROWS
        and len(set(ids)) == EXPECTED_MATRIX_ROWS
        and all(re.fullmatch(expected_pattern, identifier) for identifier in ids)
        and control_id_digest == EXPECTED_CONTROL_ID_DIGEST
        and not empty_matrix_cells
        and {row.get("status") for row in rows} == {"Not Run"},
        "Control matrix has the exact 11 columns, 216 unique complete controls, and Not Run defaults",
        {"columns": matrix_columns, "rows": len(rows), "id_digest": control_id_digest, "empty": empty_matrix_cells[:20]},
    )
    matrix_semantic_digest = normalized_digest([
        [row.get(column) for column in EXPECTED_MATRIX_COLUMNS]
        for row in rows
    ])
    c.check(
        matrix_semantic_digest == EXPECTED_MATRIX_SEMANTIC_DIGEST,
        "All 216 ordered matrix rows match the frozen full semantic digest",
        matrix_semantic_digest,
    )
    matrix_by_id = {row.get("control_id", ""): row for row in rows}
    explicit_mismatches: list[str] = []
    for control_id, expected_control in EXPECTED_EXPLICIT_CONTROLS.items():
        matrix = matrix_by_id.get(control_id)
        expected_test = (
            f"{expected_control}: packaged positive, negative, permission, persistence, "
            "offline, failure and boundary tests"
        )
        if matrix is None or matrix.get("control") != expected_control or matrix.get("verification_test") != expected_test:
            explicit_mismatches.append(control_id)
    c.check(
        not explicit_mismatches,
        "Matrix freezes exact artifact-lifecycle, aggregate, EDENA-tier/absolute-stop, and stopped-content controls",
        explicit_mismatches,
    )

    ledger = (package / "implementation/STAFF-Acceptance-and-Test-Ledger.md").read_text(encoding="utf-8")
    ledger_rows = markdown_table_rows(ledger)
    c.check(
        ledger_rows.count(list(EXPECTED_CONTROL_LEDGER_COLUMNS)) == 1,
        "Control-derived ledger has one exact six-column header",
    )
    c.check(
        ledger_rows.count(list(EXPECTED_INTEGRATION_LEDGER_COLUMNS)) == 1,
        "Integration ledger has one exact six-column header",
    )
    target_rows = [
        row for row in ledger_rows
        if row and (row[0].startswith("CTL-") or row[0].startswith("INT-"))
    ]
    ctl_rows = [row for row in target_rows if row[0].startswith("CTL-")]
    integration_rows = [row for row in target_rows if row[0].startswith("INT-")]
    ctl = [row[0] for row in ctl_rows]
    integration = [row[0] for row in integration_rows]
    expected_ctl = {f"CTL-{identifier}" for identifier in ids}
    semantic_mismatches: list[str] = []
    for row in ctl_rows:
        if len(row) != len(EXPECTED_CONTROL_LEDGER_COLUMNS):
            semantic_mismatches.append(f"{row[0] if row else '<empty>'}: expected six columns")
            continue
        control_id = row[0].removeprefix("CTL-")
        matrix = matrix_by_id.get(control_id)
        if matrix is None:
            semantic_mismatches.append(f"{row[0]}: no matrix row")
            continue
        expected = [
            f"CTL-{control_id}",
            matrix["screen"],
            expected_control_priority(control_id),
            matrix["verification_test"],
            f"Packaged positive/negative, scope, persistence, offline and failure evidence for {control_id}",
            "Not Run",
        ]
        if row != expected:
            semantic_mismatches.append(f"{row[0]}: {row!r} != {expected!r}")
    expected_integration = [f"INT-{index:03d}" for index in range(1, EXPECTED_INTEGRATION_ROWS + 1)]
    c.check(
        len(ctl) == len(set(ctl)) == EXPECTED_MATRIX_ROWS
        and set(ctl) == expected_ctl
        and all(row[-1] == "Not Run" for row in ctl_rows),
        "Ledger has exactly one Not Run CTL row per matrix control",
    )
    c.check(
        not semantic_mismatches,
        "Every CTL ledger row semantically equals its matrix row and frozen evidence/tier rule",
        semantic_mismatches[:20],
    )
    c.check(
        integration == expected_integration
        and all(len(row) == len(EXPECTED_INTEGRATION_LEDGER_COLUMNS) for row in integration_rows)
        and all(row[-1] == "Not Run" for row in integration_rows)
        and len(target_rows) == EXPECTED_TARGET_ROWS,
        "Ledger has exactly INT-001..INT-048 and 264 total target rows at Not Run",
        {"integration": len(integration), "target": len(target_rows)},
    )
    integration_semantic_digest = normalized_digest(integration_rows)
    c.check(
        integration_semantic_digest == EXPECTED_INTEGRATION_SEMANTIC_DIGEST,
        "All 48 ordered integration rows match the frozen full semantic digest",
        integration_semantic_digest,
    )
    canonical_rows = [
        row for row in ledger_rows
        if row and (
            row[0].startswith("FOUNDATION-")
            or row[0].startswith("SHIFT-")
            or row[0].startswith("INTEGRATION-")
        )
    ]
    canonical_ids = [row[0] for row in canonical_rows]
    exact_canonical_rows = expected_canonical_rows()
    c.check(
        canonical_rows == exact_canonical_rows
        and len(set(canonical_ids)) == EXPECTED_CANONICAL_ROWS,
        "Ledger has exact canonical IDs, suites, source pointers, and Not Run statuses",
        len(canonical_ids),
    )
    c.check(
        len(target_rows) + len(canonical_rows) == EXPECTED_TOTAL_EXECUTION_RECORDS,
        "Ledger freezes 264 target plus 176 canonical = 440 execution records",
    )

    handoff = (package / "implementation/HERMES-FINAL-HANDOFF-REPORT-TEMPLATE.md").read_text(encoding="utf-8")
    readiness = (
        "**Operational:** All acceptance criteria passed, including a genuine end-to-end streamed response through the downloaded application.",
        "**Core operational; AI setup pending:** All offline/core acceptance criteria passed, but a live configured backend was not available for the genuine-streaming acceptance test.",
        "**Not operational:** One or more core acceptance criteria failed; list each blocker.",
    )
    c.check(all(line in handoff for line in readiness), "Handoff contains the three exact readiness statements")

    boundary_text = "\n".join((package / name).read_text(encoding="utf-8") for name in (
        "README-FIRST.md", "GIVE-THIS-PACKAGE-TO-HERMES.md", "implementation/STAFF-Governance-EDENA-and-Data-Boundaries.md", "implementation/STAFF-Guide-Page-Content.md"
    )).casefold()
    needles = ["no phi", "patient", "live care", "session-only", "external actions", "pause all", "safe reset", "institution-approved", "no surveillance", "qi-versus-research", "perm-p0", "not operational"]
    c.check(all(needle in boundary_text for needle in needles), "Core patient, quality, memory, action, isolation, recovery, and readiness boundaries are documented")

    if isinstance(manifest, dict):
        build = manifest.get("build_kit", {})
        target = manifest.get("target", {})
        counts = manifest.get("counts", {})
        defaults = manifest.get("defaults", {})
        c.check(
            manifest.get("schema") == "NAIO-STAFF-SHIFT-HERMES-BUILD-KIT-1"
            and build.get("id") == BUILD_ID
            and build.get("name") == "SHIFT Staff Nurse Life & Practice Mission Control — Hermes Functional Build Kit"
            and build.get("version") == "1.0.0",
            "Manifest schema and build identity are exact",
        )
        c.check((target.get("product"), target.get("product_id"), target.get("version"), target.get("lane"), target.get("route"), target.get("namespace"), target.get("home"), target.get("readiness")) == (
            "SHIFT — Staff Nurse Life & Practice Mission Control", "staff-nurse-life-practice-mission-control", "2.0.0", "staff_nurse_life_practice", "/staff-nurses/dashboard", "snqi_shift.*", "My SHIFT Mission Control", "not_operational_build_required"
        ), "Manifest target identity and readiness are exact")
        expected_counts = {
            "role_adapters": 4, "deployment_contexts": 2, "protected_workspaces": 5,
            "core_launchers": 4, "superpowers": 20, "workflows": 18, "templates": 25,
            "agents": 10, "mastery_levels": 4, "capability_domains": 17,
            "capability_criteria_including_capstone": 77, "canonical_foundation_checks": 40,
            "canonical_overlay_checks": 120, "canonical_integration_checks": 16,
            "canonical_compatibility_checks": EXPECTED_CANONICAL_ROWS,
            "control_matrix_rows": EXPECTED_MATRIX_ROWS,
            "acceptance_ledger_explicit_target_test_rows": EXPECTED_TARGET_ROWS,
            "target_control_tests": EXPECTED_MATRIX_ROWS,
            "cross_cutting_full_stack_scenarios": EXPECTED_INTEGRATION_ROWS,
            "total_target_full_stack_tests": EXPECTED_TARGET_ROWS,
            "total_required_execution_records": EXPECTED_TOTAL_EXECUTION_RECORDS,
        }
        c.check(counts == expected_counts, "Manifest counts are exact", counts)
        expected_defaults = {
            "mode": "private_personal_synthetic_demonstration",
            "data": "public_synthetic_nurse_owned_nonsensitive_only_after_screening",
            "memory": "session_only",
            "powers": "Available Inactive",
            "workflows": "Preview Only",
            "agents": "PERM-P0 Disabled",
            "connectors_schedules_sharing_external_actions_background_agents": "Off",
            "optional_fifth_launcher": "Empty",
            "institution_approved_quality_workspace": "Unavailable until separately provisioned and bound",
        }
        c.check(defaults == expected_defaults, "Manifest records the exact safe defaults", defaults)


def check_modes(c: Checks, package: Path) -> None:
    symlinks: list[str] = []
    special: list[str] = []
    unsafe: list[str] = []
    for path in package.rglob("*"):
        relative = path.relative_to(package).as_posix()
        if path.is_symlink():
            symlinks.append(relative)
            continue
        status = path.lstat()
        mode = stat.S_IMODE(status.st_mode)
        if not (stat.S_ISDIR(status.st_mode) or stat.S_ISREG(status.st_mode)):
            special.append(relative)
            continue
        executable_contract = (
            relative == "tools/verify-build-kit.py"
            or relative.endswith(".sh")
            or relative.endswith(".command")
        )
        reasons: list[str] = []
        if mode & 0o022:
            reasons.append("group/world writable")
        if mode & 0o7000:
            reasons.append("special permission bits")
        if stat.S_ISDIR(status.st_mode) and mode & 0o500 != 0o500:
            reasons.append("owner lacks read/search")
        if stat.S_ISREG(status.st_mode):
            if not mode & 0o400:
                reasons.append("owner lacks read")
            if not executable_contract and mode & 0o111:
                reasons.append("unexpected executable bit")
        if reasons:
            unsafe.append(f"{relative}:{oct(mode)} ({', '.join(reasons)})")
    c.check(not symlinks, "Package contains no symlinks", symlinks)
    c.check(not special, "Package contains only regular files and directories", special)
    c.check(not unsafe, "Package filesystem modes are safe", unsafe[:20])


def check_outer_zip(c: Checks, package: Path, zip_path: Path) -> None:
    if not c.check(zip_path.is_file() and zip_path.stat().st_size > 0, "Final downloadable ZIP exists", zip_path):
        return
    root, archived = archive_files(c, zip_path, "Final downloadable ZIP")
    c.check(root == PACKAGE_NAME, "Final ZIP root name is exact", root)
    if root is None:
        return
    stripped = {name[len(root)+1:]: data for name, data in archived.items() if name.startswith(root + "/")}
    disk = files(package)
    c.check(set(stripped) == set(disk), "Final ZIP inventory equals release directory", {"missing": sorted(set(disk)-set(stripped)), "extra": sorted(set(stripped)-set(disk))})
    mismatch = [name for name in set(stripped) & set(disk) if stripped[name] != disk[name].read_bytes()]
    c.check(not mismatch, "Final ZIP bytes equal release directory", mismatch)
    try:
        with zipfile.ZipFile(zip_path) as archive:
            bad_modes: list[str] = []
            for info in archive.infolist():
                if info.is_dir():
                    continue
                relative = info.filename[len(root)+1:]
                mode = stat.S_IMODE((info.external_attr >> 16) & 0xFFFF)
                expected = 0o755 if relative == "tools/verify-build-kit.py" or relative.endswith(".sh") or relative.endswith(".command") else 0o644
                if mode != expected:
                    bad_modes.append(f"{relative}:{oct(mode)}")
            c.check(not bad_modes, "Final ZIP preserves normalized file modes", bad_modes[:20])
    except Exception as error:
        c.check(False, "Final ZIP mode check completes", error)


def check_release_companions(c: Checks, package: Path, zip_path: Path, required: bool) -> None:
    alias = package.parent / "STAFF-Nurse-Life-Practice-SHIFT-Mission-Control-Hermes-Build-Kit.zip"
    sidecar = package.parent / f"{PACKAGE_NAME}.zip.sha256"
    present = (alias.is_file(), sidecar.is_file())
    if not required and present == (False, False):
        c.check(True, "Release alias and checksum sidecar are intentionally unpublished at this verification stage")
        return
    c.check(all(present), "Release alias and checksum sidecar both exist", {
        "alias": present[0], "sidecar": present[1]
    })
    if not all(present) or not zip_path.is_file():
        return
    versioned_digest = sha256(zip_path)
    c.check(
        alias.stat().st_size == zip_path.stat().st_size and sha256(alias) == versioned_digest,
        "Unversioned release alias is byte-identical to the versioned ZIP",
    )
    try:
        sidecar_text = sidecar.read_text(encoding="utf-8")
    except Exception as error:
        c.check(False, "Release checksum sidecar decodes as UTF-8", error)
        return
    c.check(
        sidecar_text == f"{versioned_digest}  {zip_path.name}\n",
        "Release checksum sidecar exactly names and hashes the versioned ZIP",
        sidecar_text,
    )


def summary(c: Checks, *, preassembly: bool = False) -> int:
    print("\nValidation summary")
    print(f"PASS={len(c.passed)} FAIL={len(c.failed)} WARN={len(c.warnings)}")
    if c.failed:
        print("Failures:")
        for failure in c.failed:
            print(f"- {failure}")
        return 1
    if preassembly:
        print(
            "PRE-ASSEMBLY STRUCTURE ONLY — generated sources, release manifest, "
            "checksums, ZIP, alias, sidecar, and target runtime are not verified."
        )
    else:
        print("VERIFIED BUILD KIT — target application remains not operational until Hermes builds and executes the acceptance ledger.")
    return 0


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--package", type=Path, default=DEFAULT_PACKAGE)
    parser.add_argument("--zip", dest="zip_path", type=Path)
    parser.add_argument("--pre-assembly", action="store_true")
    parser.add_argument("--require-release-companions", action="store_true")
    args = parser.parse_args(argv)
    package = args.package.resolve()
    c = Checks()
    c.check(package.is_dir(), "Package directory exists", package)
    if not package.is_dir():
        return summary(c, preassembly=args.pre_assembly)
    if not args.pre_assembly:
        c.check(package.name == PACKAGE_NAME, "Versioned package directory name is exact", package.name)
    check_required(c, package, args.pre_assembly)
    if c.failed:
        return summary(c, preassembly=args.pre_assembly)
    if args.pre_assembly:
        check_contracts(c, package, None)
        check_modes(c, package)
        return summary(c, preassembly=True)
    manifest = check_package_inventory(c, package)
    check_sources(c, package, manifest)
    check_domain(c, package)
    check_contracts(c, package, manifest)
    check_modes(c, package)
    zip_path = args.zip_path
    if zip_path is None and WORKSPACE is not None:
        candidate = WORKSPACE / "deliverables" / f"{PACKAGE_NAME}.zip"
        zip_path = candidate if candidate.exists() else None
    if zip_path is not None:
        resolved_zip = zip_path.resolve()
        check_outer_zip(c, package, resolved_zip)
        check_release_companions(c, package, resolved_zip, args.require_release_companions)
    elif EXTRACTED:
        c.warn("Outer ZIP was not supplied; extracted directory was fully verified")
        c.check(not args.require_release_companions, "Release companions cannot be required without an outer ZIP")
    else:
        c.warn("Outer ZIP was not found; release directory was fully verified")
        c.check(not args.require_release_companions, "Release companions cannot be required without an outer ZIP")
    return summary(c)


if __name__ == "__main__":
    sys.exit(main())
