{
  "schema": "d25-msdl-live-shadow-contract-evidence/v1",
  "captured_at": "2026-09-21",
  "stage": "D25.14.1",
  "status": "shadow_contract_ready",
  "implementation": {
    "modules": ["services/msdl/control_plane.py", "services/msdl/domain_gate.py", "services/msdl/routing.py", "services/msdl/worker_pool.py", "services/msdl/asset_pipeline.py", "services/msdl/storage.py", "services/msdl/recovery.py", "services/msdl/observability.py", "services/msdl/capacity.py", "services/msdl/rollout.py", "services/msdl/live_shadow.py", "services/msdl/contracts.py", "services/msdl/url_identity.py", "services/msdl/test_scheduler.py", "services/msdl/test_domain_gate.py", "services/msdl/test_routing.py", "services/msdl/test_worker_pool.py", "services/msdl/test_asset_pipeline.py", "services/msdl/test_storage.py", "services/msdl/test_recovery.py", "services/msdl/test_observability.py", "services/msdl/test_capacity.py", "services/msdl/test_rollout.py", "services/msdl/test_live_shadow.py"],
    "package": "services/msdl",
    "database": "SQLite on an explicit local-SSD path",
    "journal_mode": "WAL",
    "synchronous": "FULL",
    "foreign_keys": true,
    "schema_version": 3,
    "single_authoritative_writer": "ControlPlane transaction methods; workers are not granted direct global-state mutation APIs",
    "live_workers_changed": false
  },
  "protocols": {
    "job": "msdl-job/1.0",
    "result": "msdl-result/1.0",
    "ack": "msdl-result-ack/1.0",
    "capability_advertisement": "worker_id + worker_version + protocols + capabilities + runtime"
  },
  "contract_invariants": [
    "JobEnvelope carries job/attempt/run/run_item context, lease_epoch, subject, execution policy and artifact requirements.",
    "ResultEnvelope reports one attempt's observations; it does not issue orchestration commands.",
    "Artifact candidates require kind, temp_location, byte_size and a 64-character SHA-256 digest.",
    "Capability negotiation requires both protocol compatibility and every required capability.",
    "Result idempotency key is attempt_id; exact replay is duplicate and conflicting replay is quarantined as protocol error.",
    "Unknown attempts and stale lease epochs cannot become authoritative results.",
    "ResultAck distinguishes transport receipt from authoritative job completion."
  ],
  "url_identity_invariants": [
    "Identity is centrally derived from normalization_version plus canonical_url; workers do not invent canonical identities.",
    "Fragments are removed from fetch identity but retained as raw observation data.",
    "Tracking parameters are removed; unknown parameters are preserved by default until site policy proves them noise.",
    "Scheme/host/default port/path/query ordering are normalized deterministically; meaningful query parameters are not silently discarded.",
    "Scope is evaluated after normalization and can reject scheme, origin, domain, path or depth independently.",
    "One (run_id, url_id) remains the unit of work; repeated discovery creates provenance observations, not duplicate identity/jobs.",
    "Normalization policy changes produce a new versioned URL identity namespace rather than rewriting old identities.",
    "Discovery registry never fetches URLs; fetch ownership remains with MSDL jobs and reusable artifacts."
  ],
  "discovery_sources_supported": ["sitemap", "html_link", "redirect", "manual_seed", "api_feed", "browser_dom"],
  "scheduler_contract": {
    "claim_model": "worker pull + atomic claim",
    "ordering": "job priority, run-item priority, created_at, job_id",
    "lease_fields": ["active_lease_epoch", "lease_owner_worker_id", "lease_issued_at", "lease_expires_at", "last_heartbeat_at", "lease_status"],
    "retry_fields": ["attempt_count", "retry_budget", "retry_reason", "backoff_policy_version", "last_error_class"],
    "fencing_tuple": ["job_id", "attempt_id", "worker_id", "lease_epoch"]
  },
  "domain_gate_contract": {
    "source_key": "One normalized domain/origin key shared by HTTP, browser and asset transports.",
    "authoritative_gap": "A successful reserve advances next_allowed_at once for the source, regardless of worker count or transport.",
    "cooldown_signals": ["403", "429", "CAPTCHA", "challenge", "rate_limited", "source_rejected"],
    "worker_local_limiter": "Optional additional protection only; it cannot replace or multiply the authoritative source gate.",
    "policy_events": "Every deny, reserve and policy signal is appended to domain_gate_events."
  },
  "routing_contract": {
    "primary": "HTTP whenever the HTTP capability is available and the global gate allows it.",
    "fallback": "Browser is allowed only after a technical HTTP failure, or when HTTP capability is unavailable.",
    "policy_boundary": "403/429/CAPTCHA/challenge are sent to Domain Gate and never trigger profile rotation.",
    "technical_failures": ["timeout", "connection_reset", "dns_error", "worker_error", "transport_error"],
    "cost_controls": "Browser cost units and maximum fallback count are explicit router policy; a denied gate is not bypassed by another transport."
  },
  "worker_pool_contract": {
    "isolation": ["process_dir", "profile_dir", "temp_dir", "output_dir", "log_dir", "cdp_port"],
    "lifecycle": ["starting", "ready", "draining", "offline"],
    "assignment_rule": "A ready profile may own at most one active job; draining profiles finish only their current job.",
    "canary": "Canary and regular slots have independent directories, ports and control metadata.",
    "runtime_boundary": "D25.08 allocates and persists boundaries but does not start processes or browsers."
  },
  "asset_pipeline_contract": {
    "classification": "Article images/media/documents are prioritized; supporting site resources are policy-filtered by default.",
    "priorities": {"article_image": 0, "article_media": 10, "article_document": 20, "supporting_image": 80, "site_script_stylesheet_font": 90},
    "dedupe": ["canonical resource URL with tracking parameters removed", "content hash after fetch"],
    "context": ["source_pages", "contexts", "classification_reason"],
    "retry": "Bounded attempts with explicit retry_wait and next_retry_at; permanent_failed after max_attempts.",
    "storage_boundary": "Pipeline records candidates/results only; byte commit and H: layout are D25.10."
  },
  "storage_commit_contract": {
    "candidate_validation": ["regular file", "byte_size", "lowercase 64-character SHA-256"],
    "atomic_write": "Copy to destination-side .part, flush/fsync, revalidate bytes, then os.replace to the final blob name.",
    "identity": "Content-addressed final name <sha256>.blob; repeat commits return deduplicated without overwrite.",
    "layout": "Archive root contains blobs/<hash-prefix>[.<shard>]/ with a configurable capacity capped at 1000 files per folder.",
    "orphan_handling": "Interrupted .part files are moved to orphans/ and preserved for D25.11 reconciliation.",
    "authority_boundary": "JSONL manifest is audit/export; control DB remains authoritative for artifact state and relations."
  },
  "recovery_resume_contract": {
    "startup_order": ["expire leases and fence stale attempts", "promote due retry_wait jobs", "quarantine storage .part files", "reconcile artifact paths and hashes", "build resumable job list"],
    "lease_recovery": "Expired leases become stale attempts and retry_wait or terminal_failed jobs through the existing retry budget.",
    "artifact_recovery": "Valid committed blobs are verified; missing committed blobs block safe resume without rewriting committed state; incomplete rows are orphaned/quarantined.",
    "resume_boundary": "Only eligible and retry_wait jobs enter the resume plan; succeeded/committed work is not downloaded again.",
    "idempotency": "Repeated startup reconciliation produces no second expiry, promotion or duplicate orphan move."
  },
  "observability_live_report_contract": {
    "schema": "msdl-live-report/v1",
    "event_fields": ["event_id", "sequence", "run_id", "event_type", "entity_type", "entity_id", "occurred_at", "payload"],
    "event_families": ["run", "page", "job", "asset", "worker", "error", "resource.sample"],
    "metrics": ["pages", "jobs", "assets", "bytes_fetched", "retries", "errors", "worker_lifecycle", "cpu_percent", "ram_mb", "eta_seconds"],
    "queue": "Bounded producer queue; filesystem/network publication is consumer work via drain/write_snapshot/flush_checkpoints.",
    "checkpoint": "A checkpoint event and JSON snapshot are produced at every checkpoint_interval completed pages; default is 100.",
    "write_safety": "Snapshots/checkpoints use destination-side temporary files, fsync and atomic os.replace."
  },
  "capacity_contract": {
    "mode": "synthetic_local_no_network",
    "matrix": [1, 2, 4, 6],
    "measurements": ["completed_pages", "duration_seconds", "throughput_pages_per_second", "gate_reservations", "gate_denials", "failed_workers"],
    "domain_gate_invariant": "All worker levels share one source timeline; every allowed reservation is separated by at least the configured gap.",
    "failure_probe": "One worker fails after a bounded number of reservations; remaining workers drain the queue without duplicate page completion.",
    "interpretation": "Compare source-saturated throughput with zero-gap local scaling; do not infer production capacity from worker count alone.",
    "production_boundary": "No live sites, browsers, TT/SM services, archive writes or production rollout are used by the harness."
  },
  "rollout_gate_contract": {
    "schema": "msdl-rollout-decision/v1",
    "mode": "side_effect_free_evaluator",
    "phases": ["shadow", "canary", "limited"],
    "quality_thresholds": {
      "html_completeness_min": 0.99,
      "article_image_completeness_min": 0.98,
      "error_rate_max": 0.02,
      "duplicate_rate_max": 0.0,
      "throughput_ratio_min": 0.75,
      "policy_signal_count_max": 0,
      "domain_gap_violations_max": 0,
      "recovery_failures_max": 0
    },
    "phase_rules": {
      "shadow": "Live evidence, observation-only and writes disabled.",
      "canary": "Exactly one worker, bounded scope, isolated archive target and explicit isolated write.",
      "limited": "Canary passed, bounded scope, rollback drill passed and explicit operator approval."
    },
    "rollback": "Freeze dispatch, drain/stop MSDL slots, leave TT.01/SM.02 and original archives unchanged, preserve control DB/evidence and resume only after review.",
    "production_boundary": "Evaluator performs no dispatcher, worker, browser, network, control DB or archive action."
  },
  "live_shadow_contract": {
    "schema": "msdl-live-shadow-acceptance/v1",
    "scope_modes": ["explicit_url_list", "path_prefix", "sitemap"],
    "max_pages": 100,
    "required_flags": ["operator_approved", "observation_only", "writes_disabled", "production_dispatch_disabled"],
    "quality_thresholds": {
      "html_completeness_min": 0.99,
      "article_image_completeness_min": 0.98,
      "error_rate_max": 0.02,
      "duplicate_rate_max": 0.0,
      "policy_signal_count_max": 0,
      "domain_gap_violations_max": 0,
      "archive_writes_max": 0,
      "production_jobs_claimed_max": 0
    },
    "production_boundary": "Readiness evaluator performs no network, browser, TT/SM, dispatcher, control DB or archive action."
  },
  "modules_verified": {
    "validator": "JobEnvelope, ResultEnvelope, ResultAck and worker capability advertisement validation",
    "negotiation": "Deterministic protocol/capability compatibility decision",
    "receiver": "In-memory prototype for accepted/duplicate/stale/unknown/conflicting result semantics"
  },
  "entities": {
    "policy_snapshots": "Immutable, versioned serialized policy attached to a run.",
    "runs": "Run lifecycle: created -> preparing -> active -> paused/draining -> completed/cancelled.",
    "url_identities": "Canonical logical URL identity independent from run, job and content hash.",
    "run_items": "Per-run scope membership and resolution state for a URL identity.",
    "jobs": "Logical work item with capability, priority, eligibility, retry budget and future lease epoch.",
    "attempts": "Append-only execution facts with worker, lease epoch and transport observations.",
    "artifacts": "Candidate/bytes_written/validated/committed lifecycle with external storage path metadata.",
    "job_artifacts": "Candidate/authoritative/diagnostic relations between logical jobs and artifacts.",
    "workers": "Capability and health registry used by the worker-pull claim prototype; live delivery remains deferred.",
    "domain_gate_state": "One current pacing/cooldown row per normalized source key in the authoritative control DB.",
    "domain_gate_events": "Append-only reserve, deny and policy-signal audit for all transports.",
    "route_decisions": "Deterministic HTTP-first/browser-fallback decisions with policy boundary and cost metadata.",
    "worker_slots": "Isolated worker lifecycle and runtime paths persisted in workers.metadata_json.",
    "asset_records": "Article-focused asset candidates/results with category, priority, source pages, context, dedupe and retry state.",
    "storage_blobs": "Validated content-addressed archive blobs plus destination-side staging and orphan quarantine.",
    "recovery_reports": "Startup reconciliation result covering leases, retry promotion, artifact integrity, orphans and resumable jobs.",
    "live_reports": "Event-driven metrics projection, bounded pending queue, recent events and 100-page checkpoint snapshots.",
    "capacity_reports": "Synthetic worker matrix and failure probe with domain-gap and throughput evidence.",
    "rollout_decisions": "Side-effect-free shadow/canary/limited decisions with thresholds, blockers, next phase and rollback plan.",
    "shadow_runs": "Bounded observation-only live-shadow plan/evidence with explicit scope, page limit and no-write boundary.",
    "events": "Append-only audit trail; normalized current-state tables remain authoritative."
  },
  "invariants_verified": [
    "Every mutating transition requires expected state_version.",
    "Invalid transitions are rejected and do not append an event.",
    "Finished attempts cannot be rewritten into another outcome.",
    "A late attempt can be recorded without regressing a succeeded job.",
    "An artifact cannot become authoritative or committed before validation.",
    "Policy, URL identity, run item and job creation are idempotent for the same immutable identity.",
    "Foreign keys and short IMMEDIATE transactions protect relational consistency.",
    "Read-only run_summary is computed from control tables, not from filenames or manifests.",
    "Every claim increments the job fencing epoch and creates one append-only attempt in the same IMMEDIATE transaction.",
    "Heartbeat is accepted only for the current job/attempt/worker/epoch tuple and cannot revive an expired lease.",
    "Expiry marks the old attempt stale and routes the job to retry_wait or terminal_failed according to retry_budget.",
    "A stale epoch cannot pass validate_fence; a later claim receives a strictly greater epoch."
    ,"One source key shares one authoritative gap across HTTP, browser and asset reservations."
    ,"403/429/CAPTCHA/challenge signals create durable policy events and shared cooldown instead of profile rotation."
    ,"A worker-local limiter is only additive and cannot multiply the source gap."
    ,"HTTP-first routing is deterministic; browser fallback is limited to technical failure or missing HTTP capability."
    ,"403/429/CAPTCHA/challenge never trigger browser/profile rotation and are recorded as policy events."
    ,"Routing cost budget and fallback count can stop an expensive browser fallback without bypassing the gate."
    ,"Every worker slot has distinct process/profile/temp/output/log directories and a unique configured CDP port."
    ,"A worker must be ready before assignment; one active job per profile is enforced and draining rejects new work."
    ,"Article images are included by default and ordered before article media/documents and supporting resources."
    ,"Supporting site resources are skipped by default and require an explicit policy override to enter the queue."
    ,"Canonical resource URL dedupe prevents duplicate fetches while preserving source pages and contexts."
    ,"A successful content hash can mark a later resource deduplicated without a second committed byte object."
    ,"Asset failures use bounded retry_wait transitions and become permanent_failed after max_attempts."
    ,"A candidate is rejected before commit when its regular-file, byte-size or SHA-256 validation fails."
    ,"Final archive publication uses destination-side fsync followed by atomic os.replace."
    ,"Repeat commits and different candidates with the same content hash resolve to one blob without overwrite."
    ,"Archive folder capacity is capped at 1000 blobs and overflow creates a hash-prefix shard."
    ,"Interrupted .part files are preserved by orphan quarantine rather than silently deleted."
    ,"Startup reconciliation fences expired attempts before constructing the resume plan."
    ,"Due retry_wait jobs are promoted atomically to eligible and are visible to worker-pull scheduling."
    ,"Committed artifact rows are never silently downgraded; missing committed bytes block safe resume for operator review."
    ,"Only eligible/retry_wait jobs are resumable; succeeded jobs are excluded from repeat download."
    ,"A second identical reconciliation run is observationally idempotent."
    ,"Live report events carry run/entity identity, monotonic sequence, timestamp and typed event family."
    ,"Metrics remain available even when the bounded pending queue evicts older events."
    ,"Every hundredth completed page creates a separate checkpoint projection without a network call."
    ,"Report snapshots and checkpoints publish atomically and leave no temporary part file after success."
    ,"Synthetic levels 1, 2, 4 and 6 complete without network or live process launch."
    ,"A shared source timeline preserves the configured domain gap at every worker level."
    ,"Source saturation and local worker scaling are measured as separate regimes."
    ,"A single synthetic worker failure is recovered by remaining workers without duplicate page completion."
    ,"Rollout evidence is evaluated without granting the evaluator authority to start, stop or mutate production services."
    ,"Shadow requires live observation-only evidence with writes disabled."
    ,"Canary requires exactly one worker, bounded scope and an isolated archive target."
    ,"Limited rollout requires a passed canary, rollback drill and explicit operator approval."
    ,"Quality, policy, domain-gap and recovery thresholds produce explicit blockers instead of automatic escalation."
    ,"Rollback preserves original services, control state and committed artifacts; resume requires operator review."
    ,"A live-shadow plan requires an explicit source key, non-empty scope and page limit between 1 and 100."
    ,"Live-shadow readiness requires observation-only mode, zero archive writes and disabled production dispatch."
    ,"Live-shadow quality ratios and policy/domain-gap signals are evaluated before any live run is considered ready."
    ,"A live-shadow evaluator returns readiness and blockers without issuing network, browser or service commands."
  ],
  "verification": {
    "command": "python -X utf8 -m unittest services.msdl.test_live_shadow services.msdl.test_rollout services.msdl.test_capacity services.msdl.test_observability services.msdl.test_recovery services.msdl.test_storage services.msdl.test_asset_pipeline services.msdl.test_worker_pool services.msdl.test_routing services.msdl.test_domain_gate services.msdl.test_scheduler services.msdl.test_url_identity services.msdl.test_contracts services.msdl.test_control_plane services.save_internet.test_core",
    "result": "PASS",
    "domain_gate_tests": 6,
    "routing_tests": 7,
    "worker_pool_tests": 8,
    "asset_pipeline_tests": 8,
    "storage_tests": 9,
    "recovery_tests": 9,
    "observability_tests": 10,
    "capacity_tests": 10,
    "rollout_tests": 10,
    "live_shadow_tests": 10,
    "scheduler_tests": 6,
    "url_identity_tests": 9,
    "contract_tests": 10,
    "control_plane_tests": 9,
    "existing_loader_tests": 10,
    "tests": 131,
    "skipped_tests": 1,
    "skip_reason": "symlink candidate check unavailable under current Windows filesystem permissions",
    "python_compile": "PASS",
    "encoding_guard": "PASS"
  },
  "deferred_to_later_stages": {
    "LIVE-SHADOW-RUN": "Run a bounded live observation-only shadow only after the operator supplies source/scope/page limit and explicit approval; no canary or production writes are implied."
  },
  "next_stage": {
    "code": "LIVE-SHADOW-RUN",
    "name": "Live Shadow Run",
    "stop_before": "Do not start a live network/browser shadow, canary, production rollout or add nine service copies until an operator supplies the exact source key, scope, page limit and explicit approval."
  }
}
