From 362daa90d142d9e87215dd199d93735bec896f05 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Sun, 26 Jul 2026 22:20:52 -0500 Subject: [PATCH 001/124] MCP Integration: Create PRD --- .archflow/tasks/mcp-integration/prd.md | 257 +++++++++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 .archflow/tasks/mcp-integration/prd.md diff --git a/.archflow/tasks/mcp-integration/prd.md b/.archflow/tasks/mcp-integration/prd.md new file mode 100644 index 00000000..d2615825 --- /dev/null +++ b/.archflow/tasks/mcp-integration/prd.md @@ -0,0 +1,257 @@ +# PRD: MCP Integration + +> Revise ArchFlow from a set of prompt-heavy, manually handed-off skills into a durable terminal workflow: thin phase skills execute a published workflow graph through a bundled local MCP server, persist every consequential step and decision, obtain genuinely fresh cross-family review, and recover safely from interruptions without ever inventing human approval. ArchFlow remains fully usable with only a coding agent and a terminal; Archforge may drive the same contracts later but is never required. + +## Problem Statement + +ArchFlow's current six skills carry most workflow control in prompts and conversation. They infer progress from the presence and contents of Markdown artifacts, rely on the active agent session to remember intermediate decisions, and ask the user to copy a prompt into the other client at every counter-review gate. This keeps the implementation lightweight, but makes retries, interrupted sessions, concurrent hosts, and independent review difficult to reason about. The workflow can appear resumable while lacking a single durable account of what artifact was reviewed, which decision applies to it, or whether a partial step may safely be repeated. + +The current process also spends human attention uniformly: every document and implementation phase stops for review even when no policy, drift, or quality trigger warrants it. At the same time, the manual cross-client handoff can be skipped or accidentally replaced by a same-family review that looks independent but is not. + +This revision moves control that requires durable state or host capabilities into explicit contracts: + +- a machine-readable phase graph says what runs next; +- a repository constitution supplies stable, auditable constraints; +- phase skills marshal one shared production/review/adjudication/gate pipeline; +- a local MCP server persists truthful state, dispatches fresh cross-family reviewers, and waits on explicit human decisions; and +- every review, approval, waiver, and drift verdict is bound to the exact artifact and declared inputs it evaluated. + +The goal is not a general workflow engine. It is a focused revision of ArchFlow's existing PRD-to-implementation process that automates safe mechanics while preserving human authority at every trust boundary. + +## Target Users + +### Primary users + +- **Developers using Claude Code or Codex in a terminal.** They need one consistent ArchFlow process across both hosts, reliable status after a session ends, fewer manual review handoffs, and clear recovery instructions when automation is unavailable. +- **Developers working manually without Archforge.** They must be able to initialize a repository, inspect the workflow and constitution, resolve gates or waivers through local files, and resume every phase without a UI or hosted control plane. + +### Future consumers + +- **Archforge-driven users.** Archforge may inspect the published graph, write task configuration and explicit decision artifacts, and drive the same MCP tools. It receives no privileged workflow path and cannot become a dependency for terminal use. + +## Core Value Proposition + +ArchFlow must make a terminal-driven agent workflow recoverable and independently reviewed while keeping advancement, waiver, and commit authority explicitly human. + +## Product Definitions + +| Term | Meaning in this product | +|------|-------------------------| +| Declared inputs | The versioned workflow/configuration, pinned constitution, artifact and upstream versions, rubric, phase instance, and other explicitly permitted material used by a step. | +| Artifact binding | A review, adjudication, triage, gate, waiver, or approval identifies the exact subject and inputs by path/identity and digest; a mutable filename alone is insufficient. | +| Fresh counter-review | A new, non-resumed process/session with no producer conversation, triage, prior findings, discovered repo/global instructions, or repository access. It receives only an inspectable, hashed envelope containing the artifact, rubric, fixed output contract, and minimal phase/identity metadata. Upstream documents and constitution content are reserved for adjudication. | +| Deterministic rerun | Given the same declared inputs, a rerun selects the same canonical targets, restores/reuses the exact previously validated authoritative phase outputs rather than generating or merging from partial prose, and leaves unrelated dirty changes untouched. Operational attempt metadata may change; authoritative result bytes do not. A changed input fingerprint creates a new generation and authoritative result. | +| Explicit decision | A schema-valid human or Archforge-authored decision tied to the exact pending gate and subject digest. Conversation, timeout, cancellation, file absence, and agent inference are not decisions. Manual files provide traceability, not cryptographic proof of approver identity. | +| Degraded evidence | A documented fallback result with lower assurance than the normal pipeline. It is labeled as degraded and can never silently manufacture a pass or approval. | + +## Functional Requirements + +### Must Have (v1) + +#### Published workflow and repository contracts + +| ID | Requirement | Description | +|----|-------------|-------------| +| REQ-01 | Repository initialization | A new `archflow-init` skill scaffolds the repository-owned workflow, constitution templates, shared globals, and host registration needed for terminal operation, including `.mcp.json` for Claude Code and `~/.codex/config.toml` for Codex. Initialization is idempotent, preserves unrelated Claude/Codex configuration, and reports unsupported or untrusted host configuration rather than claiming success. | +| REQ-02 | Repository layout | Initialization establishes `.archflow/workflow.yaml`, `.archflow/constitution/{README.md,00-process.md,10-architecture.md,20-data.md,30-product.md}`, existing global documents, and per-task `config.yaml`, `state.json`, active `gate.json`/`gate.decision`, canonical PRD/design/phase artifacts, implementation notes, and review/decision evidence. Canonical v1 paths include `design.md`, `phases//design.md`, `phases//impl-notes.md`, `reviews/.{self,counter,triage,adjudication}.md`, optional `reviews/.gate-counter..md`, and retained `decisions//{request,decision}.json`. `` is reversibly encoded as `prd`, `design`, `phase-design-`, or `phase-impl-`, so iterated phases never overwrite one another's evidence. | +| REQ-03 | Published phase graph | `.archflow/workflow.yaml` is the source of truth for the shipped ArchFlow phase ordering, dependencies, per-phase pipelines, optionality, iteration, and gate policy. A human or Archforge can determine the next legal action from the graph and task state without hardcoding that graph outside ArchFlow. In v1 the published file is an inspectable contract over a fixed phase/step vocabulary, not a user extension API. | +| REQ-04 | Versioned and pinned execution inputs | Every machine-readable workflow/configuration/state/gate/decision/review format is versioned and strictly validated. At task start, the task records stable task/repository identity, an immutable base commit, and workflow, constitution, and configuration versions or digests. In-flight behavior cannot silently change when repository files change. V1 keeps those inputs pinned for the task; adopting changed workflow or policy requires a new task unless the future REQ-50 migration flow is implemented. | +| REQ-05 | Workflow validation | Before agent work begins, the shipped ArchFlow graph, recognized phase/step vocabulary, and task configuration are validated. Malformed schemas, altered/unknown structure, duplicate IDs, invalid dependencies or iteration, unsatisfied prerequisites, and unknown models/families fail closed with an actionable error. Supporting arbitrary phases, steps, or plugins is not required. | +| REQ-06 | Fixed v1 graph | The shipped workflow exposes the phase behavior below. `on_trigger` review/advancement gates open when a constitution trigger fires, drift is material, adjudication fails or is uncertain, attempts are exhausted, or a task-branch constitution edit is present. This policy does not replace the separate mandatory human authorization before any commit. | + +| Phase | Skill | Requires | Pipeline | Gate | +|-------|-------|----------|----------|------| +| Explore | `archflow-explore` | — | produce | never; optional | +| PRD | `archflow-prd` | — | produce → self-review → counter-review → triage → adjudicate | always | +| Design | `archflow-design` | PRD | produce → self-review → counter-review → triage → adjudicate | always | +| Phase design | `archflow-phase-design` | design | same shared pipeline, iterated per phase | on trigger | +| Phase implementation | `archflow-phase-impl` | phase design | same shared pipeline, iterated per phase | on trigger | + +#### Thin skill behavior and shared pipeline + +| ID | Requirement | Description | +|----|-------------|-------------| +| REQ-07 | Skills as phase marshallers | Phase skills express phase-specific artifact production and rubrics but delegate durable state, model routing, counter-review dispatch, adjudication, and blocking gates to the MCP contracts. No skill branches on Claude Code versus Codex or asks a model to self-identify its host. | +| REQ-08 | Persisted step boundaries | In normal MCP operation, each pipeline step calls `archflow_state` to record a validated `running`/entry state before work and a validated outcome on exit. Every step writes its declared artifact or decision record; information required to resume, review, or advance is never held only in conversation. When the state tool/server is unavailable, REQ-38–REQ-40 define the complete artifact-based manual contract. | +| REQ-09 | Phase-specific production | Explore produces disposable context without review or gate. PRD and design run the complete pipeline and always require explicit human approval. Phase design checks drift against the approved `design.md` and becomes workflow-approved/`DESIGNED` only after the current-digest pipeline succeeds with no trigger gate, or after every opened gate is explicitly resolved. Code cannot begin from an incomplete, failed, or pending-gate phase design. Phase implementation checks drift against both the approved phase design and task design, preserves the `no document → DESIGNED → IN PROGRESS → COMPLETE` lifecycle, updates parent PRD/design when implementation changes reality, writes durable implementation notes/logs, and proposes task-independent conventions outside `.archflow/`. Regardless of `on_trigger` review-gate outcome, the skill stops before commit and obtains a distinct explicit human commit authorization bound to the final implementation diff and current artifact digests; phase completion/commit cannot precede that decision. | +| REQ-10 | Phase-specific rubrics | PRD, design, and phase-design rubrics evaluate completeness, consistency, assumptions, requirement testability, and fitness to the brief. Implementation rubrics evaluate simplicity, duplication, design conformance, dead code, error handling, and whether abstractions are justified. Counter-review uses the declared rubric adversarially; it does not optimize for raw finding count. | +| REQ-11 | Structured review artifacts | Self-review, counter-review, triage, and adjudication outputs conform to versioned schemas, canonical Markdown rendering, and the non-colliding `` paths in REQ-02. Headers identify at least the task/phase instance, step, subject/input digests, verdict, blocking count, trigger/rule IDs, assurance source, model/effort when known, and execution identity. Server-dispatched counter-review/adjudication provenance is server-attested. In-session self-review model/effort metadata is agent-declared or `unknown`, never presented as server-attested; `archflow_state` still binds its input/result digests. Findings have stable IDs, severity, evidence, and suggested resolution; triage dispositions each applicable finding exactly once. | +| REQ-12 | Review verdict semantics | A raw review `fail` contains one or more blocking findings and permits the required transition into triage, but it cannot authorize advancement. `pass` contains no blocking findings. `advisory` carries only non-blocking findings. Contradictory counts/verdicts, malformed output, and unsupported fields fail closed and cannot replace a prior valid artifact. Triage either rejects a finding with evidence or accepts it and sends the artifact back to production for revision. | +| REQ-13 | Review fixed point and evidence freshness | Required reviews, triage, adjudication, and gate/approval evidence bind to the exact artifact and declared-input digests. If triage accepts any finding, the producer rewrites the artifact; that new digest invalidates the old self-review, counter-review, triage, and adjudication for advancement and reruns self-review → counter-review → triage. The loop closes only when the current digest has current self/counter evidence, every finding is dispositioned, and no blocker remains; adjudication then evaluates that same digest. Attempts are bounded by configuration, and exhaustion opens a human gate. Changing an approved upstream invalidates affected downstream evidence. Stale evidence may be retained for diagnosis but never authorizes advancement. | +| REQ-14 | Status from durable truth | In normal MCP operation, `archflow-status` reads validated `state.json` and reports the exact task, phase instance, step, attempt/status, blocking reason, and one safe next action. In manual degraded operation it reconstructs only milestones proven by the canonical artifact/decision contract in REQ-38–REQ-40, labels the result degraded, and never infers an approval or waiver from absence, conversation, or ambiguous artifacts. Missing/corrupt inputs remain unknown with repair guidance. | + +#### Constitution, waivers, and drift + +| ID | Requirement | Description | +|----|-------------|-------------| +| REQ-15 | Repository constitution | One version-controlled constitution applies to every task in a repository. Rules have stable unique IDs, status, human-readable text, and optional `review_trigger`/`enforced_by` declarations. IDs are appended or deprecated, never renumbered or reused. Adjudication evaluates each trigger against the declared current artifact/diff/evidence and returns matched and uncertain rule IDs with evidence; either outcome opens an `on_trigger` gate. Mechanically enforced rules remain in the constitution, and their evidence must bind to the current subject digest; missing, stale, unknown, or failed evidence is not compliance. | +| REQ-16 | Tasks consume policy | Tasks may cite, comply with, fail, or request a scoped waiver against a rule; they cannot amend the governing constitution. Amendments use normal base-branch code review. Any task-branch diff touching `.archflow/constitution/` opens an unconditional human gate and does not alter pinned adjudication rules. That gate cannot approve or waive the task-local amendment: advancement requires removing/reverting the edit, or completing normal base-branch amendment review and then starting a new task (or using future REQ-50 migration). | +| REQ-17 | Immutable policy basis | The governing constitution is resolved from the task's immutable starting commit, not a moving branch name or mutable worktree file. Its digest/version is pinned in task state. Applicable rules are supplied to production as constraints, while adjudication checks the complete pinned policy basis as a backstop. Missing/unresolvable policy or current `enforced_by` evidence cannot be treated as compliance. | +| REQ-18 | Scoped waivers | `archflow_waiver` creates a durable, explicit human decision request tied to the exact rule version, task, narrow scope, rationale, subject/evidence digests, and gate identity. Grant or denial is explicit; a grant records provenance and expires at the stated task boundary. A waiver never amends policy or applies to another rule, task, or changed subject implicitly. | +| REQ-19 | Independent adjudication results | Adjudication emits separate constitution-compliance and upstream-drift results plus matched/uncertain trigger IDs and supporting evidence. Drift is `aligned`, `incidental`, or `material`: incidental clarifications are recorded and may proceed; material changes that would surprise a reader of the approved document open a gate and normally require amendment/reapproval of the affected upstream artifact. Approved upstream versions remain identifiable even when canonical parent documents are later updated to reflect reality. | +| REQ-20 | Triggered human authority | Constitution review triggers or uncertainty, material drift, failed/uncertain adjudication, exhausted attempts, waivers, and task-branch constitution edits require explicit human decisions. PRD and design approvals always require a human, and commit authorization follows REQ-09. No agent, model result, timeout, or fallback may invent approval or waive a gate. A constitution-edit gate can request revert/abort or direct normal base-branch amendment work; an approval-shaped decision cannot authorize the task-local edit. | + +#### Durable task state, reruns, and isolation + +| ID | Requirement | Description | +|----|-------------|-------------| +| REQ-21 | Truthful state machine | In normal MCP operation, `state.json` is the validated source of truth for phase instance, step, status, attempts, declared-input fingerprint, current authoritative artifacts, approvals, open gates, and waivers. A step cannot be succeeded unless its required artifact exists, validates, and matches the recorded digest. Terminal task states and waiver expiration are explicit. When the server is unavailable, the canonical artifact/decision contract in REQ-38–REQ-40 is the conservative manual authority instead of a fabricated `state.json` update. | +| REQ-22 | Crash-safe recovery | State, gate, decision, and server-authored review writes are replacement-based and crash-safe from a reader's perspective. Killing a host/server before, during, or after dispatch/write leaves either the prior or next complete valid revision. On restart the workflow can resume, reconcile, safely retry, or provide a precise repair action; it never skips validation or converts interruption into approval. | +| REQ-23 | Idempotent transition intent | Every mutating tool call carries a stable `intent_id`, caller-observed `expected_revision`, and `input_fingerprint`. Repeating the same intent with the same inputs is safe and does not duplicate authoritative artifacts, reviews, gates, or waivers. Reusing an identity with different inputs is rejected as `INTENT_MISMATCH`; a stale expected revision is `STATE_CONFLICT`. Retries are bounded, classified, and never silently change model family, model, policy, or inputs. | +| REQ-24 | Conflict-aware concurrent sessions | Multiple Claude/Codex/Archforge sessions cannot silently overwrite one task's state. State carries a monotonic revision; exactly one competing transition wins and stale writers receive `STATE_CONFLICT`. Independent tasks may proceed concurrently. Architecture may choose locking, compare-and-swap, or an equivalent cross-process mechanism. | +| REQ-25 | Deterministic overwrite contract | Rerunning a phase with an unchanged input fingerprint restores/reuses the exact previously validated authoritative output bytes and canonical targets; it never re-generates from or appends/merges partial worktree prose. A changed input fingerprint creates a new authoritative result. Result reuse changes only the phase's declared outputs and never resets, cleans, or stashes the worktree, consumes another task's state, or modifies unrelated tracked/untracked changes. The architecture may choose cache/snapshot storage, but v1 must retain enough validated result data to satisfy this contract in normal and manual modes. | +| REQ-26 | Repository and task isolation | Every tool resolves a canonical Git repository/worktree root and limits reads/writes to the active task and declared artifact classes. Constitution and approved upstream artifacts are narrow declared exceptions. Traversal, absolute/symlink escape, cross-task access, and mismatched repository identity are rejected before any read or child dispatch; supported worktrees and paths with spaces/Unicode work correctly. | + +#### Bundled local MCP server + +| ID | Requirement | Description | +|----|-------------|-------------| +| REQ-27 | Exactly five workflow tools | The bundled server exposes the five logical tools in the source design: `archflow_state`, `archflow_counter_review`, `archflow_adjudicate`, `archflow_gate`, and `archflow_waiver`. Git and ordinary file operations that a skill can perform do not become additional MCP tools. | +| REQ-28 | Local stdio service | The server is implemented in Node/TypeScript, spawned locally by the host, and communicates only over MCP stdio; it opens no network listener. Stdout contains only valid MCP protocol traffic. Installation leaves a version-pinned, offline-runnable server command rather than fetching an unpinned package at host startup. | +| REQ-29 | Host detection | After MCP initialization, the server uses the connection's immutable `clientInfo`/protocol metadata and supported real-host fixtures to identify Claude Code or Codex. Unknown, missing, ambiguous, or unsupported identities produce an actionable `UNSUPPORTED_HOST` result and launch no model process. Skills contain no host-specific routing logic. | +| REQ-30 | Configuration-driven routing | Server defaults bind Claude producers to Codex-family counter-review/adjudication and Codex producers to Claude-family counter-review/adjudication; self-review remains an in-session same-host subagent. Counter-review and adjudication default to higher reasoning effort than production because they are short, high-consequence calls. Versioned per-task `config.yaml`, written by a human or Archforge, may override models/effort by role and phase. Model names are configuration, not skill/server constants, and are validated before dispatch. | +| REQ-31 | Cross-family counter-review | Producer and counter-reviewer families are derived from trusted runtime/configuration metadata. Same-family counter-review is a hard `FAMILY_MISMATCH`, including degraded mode. Rate-limit or availability failure is distinguishable, leaves the step pending/failed, and never launches the producer family as a substitute. | +| REQ-32 | Inspectable fresh context | Counter-review and adjudication use short-lived, non-resumed CLI processes with no inherited producer session, prior findings/triage, repo/global agent instructions, or repository access. Counter-review receives exactly the artifact, rubric, fixed output contract, and minimal phase/identity metadata—no upstream document, constitution, repository, or other file content. Adjudication separately receives its artifact, fixed contract, pinned constitution, and declared approved upstream inputs. Both envelopes are versioned, size-bounded, inspectable, and hashed. | +| REQ-33 | Validated model results | CLI adapters request versioned structured output, validate it in the server, and only then render canonical review/adjudication files. The server records actual adapter, CLI version, canonical model/family, configured effort, input digest, and derived verdict/count; model-authored prose cannot forge trusted provenance or advancement fields. | +| REQ-34 | Subscription-authenticated dispatch | Counter-review/adjudication dispatch uses the user's existing first-party Claude/Codex subscription-authenticated CLI sessions and never requires or falls back to API keys, metered API billing, gateways, or cloud-provider routes. Authentication is preflighted; ambiguous, logged-out, API-key, or unsupported-provider states fail before invocation. Child environments exclude provider keys/routing variables and unrelated secrets while preserving only what is required for the supported CLI login. | +| REQ-35 | Child-process lifecycle | Child CLIs are launched without a shell and have explicit working directory, input/output bounds, timeout/cancellation handling, and stable failure classes for missing CLI, auth, unsupported model, rate limit, timeout, cancellation, malformed output, output overflow, nonzero exit, and I/O failure. Cancellation/timeout/server shutdown terminates descendants, leaves workflow evidence truthful, and never becomes a successful review or approval. | + +The v1 MCP surface is normative. Every request/result uses a versioned schema and the active repository/task identity established by validated session or request metadata. Every mutating request also carries `intent_id`, `expected_revision`, and `input_fingerprint`; a success result reports the resulting revision. Failures expose a stable code, retryability, and safe diagnostic without producing the success side effect. An idempotent replay returns the recorded result, reuse with changed inputs returns `INTENT_MISMATCH`, and a stale revision returns `STATE_CONFLICT`. + +| Tool | Required request shape | Required success result | Required effect | +|------|------------------------|-------------------------|-----------------| +| `archflow_state` | `(phase_instance, step, status, artifact?)` plus common mutation fields | `{path, revision, status}` | Validate the transition and atomically replace the active task's `state.json`; an idempotent replay returns the same authoritative revision. | +| `archflow_counter_review` | `(artifact_path, rubric)` plus common mutation fields | `{path, verdict, blocking_count, revision}` | Dispatch a fresh opposite-family reviewer and write the current phase-instance counter-review artifact only after structured-result validation. | +| `archflow_adjudicate` | `(artifact_path, upstream_paths[])` plus common mutation fields | `{path, constitution, drift, triggers[], revision}` | Dispatch the configured adjudicator against the pinned constitution/declared upstreams and write the phase-instance adjudication artifact. | +| `archflow_gate` | `(phase_instance, summary, context)` plus common mutation fields | `{decision, notes, revision}` | Publish/resume the digest-bound gate, block as required by REQ-37, validate its decision, and return it exactly once. | +| `archflow_waiver` | `(rule_id, rationale, scope)` plus common mutation fields | `{granted, notes, revision}` | Use the same durable blocking decision mechanism and, on grant, record the exact scoped waiver in task state/manual evidence. | + +#### Durable gates and degraded terminal operation + +| ID | Requirement | Description | +|----|-------------|-------------| +| REQ-36 | Durable gate lifecycle | `archflow_gate`/`archflow_waiver` durably publish active `gate.json` and an awaiting-human state before blocking. A gate has a unique ID, task/phase/kind, subject/context digests, allowed decisions, and creation metadata. Only a valid atomic `gate.decision` for that exact ID/subject resolves it; stale, partial, malformed, duplicated, or mismatched decisions cannot advance. Each opened/resolved request and decision is retained at `decisions//{request,decision}.json`; the singular gate files are active-gate interfaces, not the historical record. Supported-host installation documents/configures a human-decision tool-timeout window, but the server has no internal approval timeout. | +| REQ-37 | Genuinely blocking and resumable | While connected, a gate/waiver call remains pending until a valid decision or an explicit external cancellation/failure; it never poll-and-returns a pending value as success. Host timeout, MCP cancellation, client/server exit, or session death leaves the gate pending and resumable. A later invocation observes the same gate and valid decision rather than creating a duplicate. Approval/grant advances once; revise/reject/deny/cancel remain explicit non-advancing outcomes. | +| REQ-38 | Complete documented fallback per tool | Every skill documents one exact file/prompt fallback and resume path for each unavailable tool. If state is unavailable, the write is skipped and status uses only canonical artifacts. Counter-review emits a self-contained other-client prompt and stops until a schema-valid cross-family artifact exists. Adjudication may run as explicitly lower-assurance same-family review against pinned inputs; failure or uncertainty opens a manual human gate. Gate/waiver fallbacks publish the pending request and stop; after the user gives an explicit decision, the skill records the schema-valid decision file before advancing. No fallback outcome exists only in conversation. | +| REQ-39 | Complete manual source of truth | With the entire MCP server unavailable, declared production/review/triage/adjudication artifacts plus the full retained `decisions//` chain form the conservative manual milestone record; active `gate.json`/`gate.decision` represent only the currently pending interaction. A skill advances only when files required for the milestone validate and all required explicit decisions exist; absence or ambiguity remains non-advancing. This mode retains the validated authoritative result needed by REQ-25 and can reach task completion even if MCP never recovers. If it does recover, the server reconciles/imports the same evidence without discarding it, repeating a resolved decision, or inferring missing state. | +| REQ-40 | Terminal-only completion | A developer can initialize, configure, inspect, run, gate, waive, interrupt, resume, and complete the full workflow using only a supported terminal, Git worktree, Claude Code or Codex, and local files—including documented manual operation when the MCP server remains unavailable. Archforge is not installed or required for any v1 acceptance path. | +| REQ-41 | Counter-review prompt at every human gate | Every human review/approval gate presents a self-contained ready-to-run prompt for the other client as an optional additional counter-review, even when the automated counter-review already ran. The user alone decides whether to run it. If run, its digest-bound supplemental result is written to `reviews/.gate-counter..md`, triaged before the gate resolves, and any accepted change re-enters the REQ-13 fixed-point loop. Declining the optional check does not fabricate a review and does not prevent an otherwise valid explicit gate decision. | + +### Should Have (v1+) + +| ID | Requirement | Description | +|----|-------------|-------------| +| REQ-50 | Explicit task migration | Provide a guided, human-approved re-pin/migration flow for tasks that intentionally adopt a newer workflow or constitution, with dependency-aware invalidation of prior evidence. V1 may instead keep tasks pinned and require a new task/run. | +| REQ-52 | Durable audit export | If post-PR audit retention becomes a product need, export a compact approval/waiver/evidence summary to a deliberately retained location before `.archflow/` is removed. This is separate from v1 development-lifecycle traceability. | + +### Out of Scope + +| Feature | Reason | +|---------|--------| +| Archforge implementation or dependency | This task publishes contracts Archforge can consume; it does not build the driver or require it for terminal use. | +| General-purpose workflow/plugin engine or custom graph vocabulary | The repository copy of the shipped v1 graph is inspectable and driveable, but arbitrary user-defined phases, steps, skills, or plugins are not supported. Unsupported structural edits fail clearly. | +| Web UI, hosted service, callback server, or network MCP transport | V1 is a local terminal product over stdio. Model CLIs may use their normal provider network path. | +| Additional MCP tools | The five-tool boundary is deliberate; Git and file reads remain in skills/server internals where applicable. | +| API-key or custom-provider dispatch | The target contract is first-party subscription-authenticated CLI dispatch with no metered API-key fallback. | +| Cross-platform/native Windows expansion | V1 supports environments already supported by ArchFlow's Bash installer unless architecture explicitly validates an expansion. Robust paths and worktrees within those environments are in scope. | +| Cryptographic approver identity or malicious-local-user protection | Manual decision files provide local traceability, not strong identity, signatures, or protection from an attacker who controls the filesystem. Tampering that affects workflow evidence must still be detected and fail closed where specified. | +| Seeded deterministic LLM generation | Supported CLIs do not promise seeded deterministic text. V1 satisfies identical reruns by retaining and reusing the previously validated authoritative output for an unchanged input fingerprint. | +| Per-task constitution amendments | Tasks consume the pinned repository constitution and may request narrow waivers; amendments happen on the base branch through normal review. | +| Permanent external audit storage | `.archflow/` remains development-lifecycle state for v1. Retention before PR is an explicit architecture/product documentation decision, not an implied permanent guarantee. | + +## Non-Functional Requirements + +| Category | Requirement | +|----------|-------------| +| Human authority | There are zero advancement, commit, approval, gate, or waiver outcomes inferred from agent prose, model verdict alone, timeout, cancellation, missing files, or fallback. Every required human action—including clean-path commit authorization—is explicit and artifact-bound. | +| Durability | At every state/artifact/gate write boundary, interruption leaves a valid authoritative normal-mode state, a valid manual-mode milestone record, or a precise non-advancing recovery condition. No open gate becomes approved and no completed evidence is silently lost. | +| Concurrency | Cross-process concurrent transitions on one task serialize or return `STATE_CONFLICT`; no waiver, gate, approval, or step update is lost. | +| Integrity | Machine-readable inputs and outputs are schema-versioned and validated on read. Stale/mismatched digests, invalid transitions, contradictory verdicts, and partially written files fail closed. Server-attested and agent-declared provenance are distinguishable. | +| Review independence | Counter-review is always a fresh opposite-family process with an observable artifact-and-rubric-only content envelope. An unavailable opposite family is visible failure, never a same-family substitution. | +| Security and privacy | The server is local stdio-only, tool paths are task-scoped, reviewer children cannot write the repo, shell interpolation is not used, and provider credentials/routing variables or unrelated developer secrets are not forwarded or logged. | +| Protocol correctness | Initialization precedes tool calls, unsupported hosts fail without dispatch, stdout remains valid MCP traffic, and minimum supported MCP/Node/CLI/host versions are documented and contract-tested. Dependencies and protocol/SDK versions are pinned. Gate calls remain genuinely blocking under the documented supported-host timeout configuration and degrade durably on external cancellation. | +| Distribution | After installation, the supported Node/CLI environment can start the bundled server without downloading an unpinned runtime package. Init/registration is repeatable and preserves unrelated settings. | +| Error quality | Host, configuration, authentication, rate limit, child lifecycle, schema, state conflict, path, and gate errors remain distinguishable and offer a safe next action. Unknown failures are never classified as pass or approval. | +| Review quality | Release evaluation uses a curated corpus with seeded requirement defects, policy violations, drift cases, and clean controls. It measures expected blocker detection, false blockers, triage completeness, and defects found after pass; it does not reward the number of findings. Thresholds are set from the corpus before release rather than invented in this PRD. | +| Supported-environment portability | Repository relocation, linked worktrees, and paths with spaces/Unicode behave correctly in the Bash-installer environments claimed by the release. Machine-specific executable paths are not written into portable task state. | + +## Research Summary + +### Domain Context + +Research focused on durable workflow execution and human oversight; competitive research was intentionally skipped because this is an internal workflow revision with an authoritative design, not a market-positioning exercise. + +The main conclusion is that ArchFlow is becoming a small durable workflow coordinator, even though its work products remain files and agent sessions. Durable execution guidance supports explicit idempotency identities, persisted intent/results, and rejection of retries whose parameters changed. Provenance practice supports binding evidence to exact outputs and declared inputs rather than mutable paths. Human-oversight guidance supports explicit gates, exception/waiver records, adjudication, and go/no-go outcomes rather than conversational approval. + +Those conclusions produced three requirements beyond the happy-path design: immutable task inputs, digest-bound evidence with stale-evidence invalidation, and durable gates that survive the request/session that opened them. They also expose the current pre-PR deletion of `.archflow/` as a conscious retention boundary: v1 can promise lifecycle traceability, but not permanent audit history unless an export is later added. + +### Technology Landscape + +The MCP design is feasible as a local Node/TypeScript stdio server, but correctness depends on the host and child-process boundaries. Current MCP lifecycle metadata provides `clientInfo`, but host names are vendor-defined, so supported Claude Code/Codex handshake fixtures and fail-closed handling are required. Stdio requires protocol-only stdout. Blocking calls are cancellable and host tool timeouts differ, so the gate must be durable independently of a live request. + +Both Claude and Codex CLIs can run short-lived non-interactive model processes with explicit model/effort and structured output, but their exact flags and authentication behavior are version-sensitive. CLI adapters therefore need minimum-version contract tests, environment isolation, structured-output validation, and stable failure classification. Neither CLI promises seeded deterministic text, so v1 must retain/reuse the previously validated result when an unchanged input fingerprint requires an identical rerun. + +### Primary Research Sources + +- [MCP lifecycle and `clientInfo`](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle), [stdio transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports), and [cancellation](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation) +- [Claude Code CLI/programmatic operation](https://code.claude.com/docs/en/headless) and [credential-use terms](https://code.claude.com/docs/en/legal-and-compliance) +- [Codex non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode) and [MCP timeout configuration](https://learn.chatgpt.com/docs/extend/mcp) +- [AWS guidance on safe, idempotent retries](https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/) + +### Key Risks + +| Risk | Product response | +|------|------------------| +| Anthropic credential-use terms may prohibit a third-party tool from routing Free/Pro/Max subscription credentials through `claude -p`. | Release remains blocked absent written Anthropic clarification or a qualified legal determination that the local integration is permitted. An internal risk acceptance does not itself establish permission; allowing that disposition requires an explicit owner change to this release criterion. API-key/custom-provider fallback is not an implicit resolution. | +| Review or approval refers to a path whose contents later changed. | Every evidence item binds to subject/input digests; mutation invalidates stale dependent evidence. | +| A long human gate outlives MCP/host timeout or cancellation. | Gate state and decision are durable; disconnection leaves it pending and a later call resumes it. | +| Two hosts or Archforge race on one task. | One revision wins; stale writers receive a conflict and cannot overwrite the winner. | +| A fresh process still inherits producer instructions, repository access, or the wrong family. | The input envelope is explicit/hashed, repo/global instruction discovery is disabled, repository writes are disabled, and family is validated from trusted routing metadata. | +| Trigger rules are too broad or too narrow. | Use a drift/policy fixture corpus and review false gates/misses before reducing mandatory human gates; adjudication uncertainty opens a gate. | +| Same-family fallback creates review theater. | Counter-review never falls back to same-family. Same-family adjudication is labeled degraded, and failure/uncertainty gates. | +| State appears durable but crashes between output/state writes create ambiguity. | Artifact-state digest agreement, complete revisions, crash testing, and explicit reconcile/retry outcomes are release criteria. | +| `.archflow/` deletion removes the only record of decisions and waivers. | Architecture must explicitly document which evidence is intentionally ephemeral and whether a pre-PR summary/export is needed; v1 does not promise permanent audit storage. | +| Subscription/auth changes or CLI releases break dispatch silently. | Authentication and version preflights fail before model invocation; adapters are covered by supported-version fixtures. | + +## Constraints + +| Constraint | Details | +|------------|---------| +| Terminal-first | Full functionality must require only a supported terminal, Git repository/worktree, coding agent, and local files. Archforge is an optimization only. | +| Fixed server boundary | V1 uses a bundled Node/TypeScript MCP server over local stdio and exposes exactly five workflow tools. | +| Host scope | Claude Code and Codex are the producer hosts and review families in scope. Skills remain host-neutral; routing stays in the server/adapters. | +| Authentication | Target dispatch uses existing first-party subscription-authenticated CLIs, never API keys or metered fallback. Written Anthropic clarification or a qualified legal determination for the local Claude dispatch model is a release blocker unless the owner explicitly revises this PRD. | +| Human trust boundaries | Never commit or pass a required review gate without explicit approval; never implement before approved phase design; tasks stay isolated; parent documents stay current; completed phases keep implementation notes and propose durable conventions outside `.archflow/`. | +| Policy scope | One constitution applies repository-wide and is pinned per task from an immutable commit. Task branches cannot redefine their governing policy. | +| Platform scope | V1 support follows the current Bash installer unless architecture proves and documents a wider matrix. Native Windows expansion is not assumed. | +| Audit lifecycle | `.archflow/` is tracked during development and currently removed before PR. The architecture must decide/document retention or export semantics without claiming tamper-proof or permanent audit storage. | +| Model nondeterminism | New generations for changed inputs may vary. Unchanged-input reruns do not rely on model determinism; they restore/reuse the exact previously validated authoritative output. | +| Timeline | No delivery date is assumed by this PRD. Archforge work must not begin until the terminal validation criteria pass. | + +## Success Metrics and Release Validation + +The first six scenarios preserve the authoritative design's terminal definition of done. The additional guardrails make those scenarios credible under failures and concurrent use. + +| ID | Success condition | +|----|-------------------| +| VAL-01 | Using only a terminal, a representative feature goes from PRD through every design/implementation phase to merged implementation in both producer directions. Every required approval and implementation note is present, and a clean no-trigger implementation demonstrably refuses to commit until a human authorizes the exact final diff/artifact digests. | +| VAL-02 | On a curated artifact corpus, opposite-family counter-review catches seeded substantive defects that require producer action while clean controls expose false blockers; results demonstrate useful independent review rather than restatements/nitpicks. A fixture with accepted findings and two artifact rewrites proves that each new digest reruns self/counter review, all current findings are triaged, only the final digest is adjudicated, and exhaustion gates. Release thresholds are explicitly approved from observed benchmark data. | +| VAL-03 | A constitution violation is detected against the pinned constitution, blocks advancement, and a correctly scoped explicit waiver grant resumes the task; stale, mismatched, denied, or malformed waiver decisions do not. | +| VAL-04 | A material implementation drift from approved phase/task design is detected and escalated; aligned/incidental fixtures behave as specified, and accepted material drift reopens the affected upstream approval/evidence chain. | +| VAL-05 | After a clean run records a validated authoritative result, rerunning the phase from the same declared-input fingerprint on a dirty worktree restores byte-identical authoritative phase outputs at the same canonical paths without consuming partial prose. Unrelated tracked/untracked files remain byte-for-byte unchanged, operational attempt metadata is distinguishable from the result, and no duplicate authoritative result remains. | +| VAL-06 | `state.json` truthfully reflects every phase/step boundary. Killing a producer or server before/during/after state/artifact writes and child dispatch yields valid state that resumes, safely retries, or stops with precise repair guidance; no approval or required review is skipped. | +| VAL-07 | Claude-producer→Codex-reviewer and Codex-producer→Claude-reviewer tests prove a fresh PID/session and opposite family. The counter child receives only artifact, rubric, fixed result contract, and minimal identity metadata—no upstream/constitution/repository content, producer/triage/previous-review context, repo/global instructions, child persistence, or repository access. | +| VAL-08 | MCP `tools/list` exposes exactly the five names and versioned schemas in the normative table, including common intent/revision/fingerprint fields, and valid/invalid calls exhibit those effects without a sixth workflow tool. Idempotent replay returns the recorded result; changed-input reuse returns `INTENT_MISMATCH`; stale revision returns `STATE_CONFLICT`. Missing/ambiguous host identity, API-key or unsupported auth, rate exhaustion, missing CLI, bad model, timeout, cancellation, output overflow, invalid structured output, and nonzero child exit remain distinguishable; none writes a pass artifact, advances state, or launches same-family fallback. | +| VAL-09 | Under documented Claude/Codex timeout configuration, a connected gate call stays pending until a valid decision or explicit external cancellation/failure—it never returns a pending result as success. Killing/restarting or cancelling leaves one durable pending gate. Partial, malformed, wrong-task, wrong-digest, wrong-ID, stale, and replayed decisions cannot resolve it; one valid explicit decision resolves it exactly once after resume and remains in its gate-ID archive. Every human gate also presents the optional REQ-41 prompt; a produced supplemental review is triaged, while an explicit decline does not fabricate one. | +| VAL-10 | Two server processes racing from the same `expected_revision` on one task produce one winner plus `STATE_CONFLICT`, with no lost gate/waiver/update; an exact same-intent replay returns its recorded result. Different tasks proceed independently and never read each other's artifacts. | +| VAL-11 | Path tests reject traversal, absolute/symlink escape, and cross-task access before read/spawn while supported linked worktrees, relocation, and space/Unicode paths succeed. Init is idempotent, preserves unrelated host config, and reports unsupported runtime/CLI or untrusted Codex project config. | +| VAL-12 | With each MCP capability unavailable in turn—and with the entire server never returning—a terminal-only run uses canonical manual artifacts, retained authoritative results, and multiple non-colliding gate-ID decision records to pause, advance, resume, and reach completion without manufacturing pass/approval/completion. The scenario includes PRD/design approval, at least two phase decisions, one waiver, and commit authorization. A separate recovery run imports/reconciles the complete chain without repeating resolved decisions. | +| VAL-13 | Provider key/routing sentinels placed in the parent environment are absent from reviewer children and persisted diagnostics. The server opens no listener and emits only MCP protocol traffic on stdout. | +| VAL-14 | Before release, written Anthropic clarification or a qualified legal determination establishes that the local subscription-authenticated Claude dispatch is permitted. An internal risk acceptance alone does not satisfy this condition; accepting unresolved terms risk requires explicit owner authorization to revise the criterion. API-key/custom-provider fallback requires an explicit PRD scope change. | +| VAL-15 | Constitution fixtures cover positive, negative, and uncertain `review_trigger` evaluation plus current, missing, stale, and failed `enforced_by` evidence. Matched/uncertain triggers gate; missing/stale/failed evidence never passes. A task-branch constitution edit cannot advance on an approval-shaped decision and must be reverted/removed or handled through base-branch amendment plus a new/migrated task. | +| VAL-16 | A task with at least two implementation phases proves that `phase-design-` and `phase-impl-` review, supplemental gate-counter, retained decision, rerun, and status evidence use reversible non-colliding paths and that later phases never overwrite earlier evidence. It also proves code cannot start until phase design is workflow-approved as defined in REQ-09. | + +Archforge implementation must not begin until VAL-01 through VAL-06 pass in a terminal. VAL-02 is the decisive product validation: if independent review does not reliably improve substantive quality, the architecture's central automation premise must be revisited rather than hidden by more mechanics. + +--- +*Created: 2026-07-26* From 5120c73e4940fbaf6750126fd00efb0573c04ecb Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Sun, 26 Jul 2026 22:21:16 -0500 Subject: [PATCH 002/124] Reference design --- docs/mcp-integration-design.md | 279 +++++++++++++++++++++++++++++++++ 1 file changed, 279 insertions(+) create mode 100644 docs/mcp-integration-design.md diff --git a/docs/mcp-integration-design.md b/docs/mcp-integration-design.md new file mode 100644 index 00000000..60ff8539 --- /dev/null +++ b/docs/mcp-integration-design.md @@ -0,0 +1,279 @@ +# Archflow — Detailed Design + +**Scope:** what changes in the skills, what the constitution looks like, and what the bundled MCP server does. +**Constraint:** Archflow must be fully usable with nothing but a terminal and a coding agent. Archforge is an optimization, never a dependency. + +--- + +## 1. Repo layout + +The Archflow folder is scaffolded into every repo it operates on. The skills themselves install to the agent's skills directory (`~/.claude/skills/`, `~/.agents/skills/`) and are not part of the repo. + +``` +/ + .archflow/ + workflow.yaml # phase graph — the machine-readable workflow definition + constitution/ + README.md + 00-process.md + 10-architecture.md + 20-data.md + 30-product.md + # conventions, stack, glossary + tasks/ + / + config.yaml # model routing; written by human or Archforge + state.json # current phase/step/status + gate.json # present only while a gate is open + gate.decision # written by human or Archforge to resolve a gate + prd.md + design.md + phases//design.md + phases//impl-notes.md + reviews/ + .self.md + .counter.md + .triage.md + .adjudication.md +``` + +### 1.1 `workflow.yaml` + +Archflow owns the phase graph and publishes it so that anything driving the workflow — a human reading it, or Archforge — knows what comes next without hardcoding. + +```yaml +phases: + - id: explore + skill: archflow-explore + pipeline: [produce] + gate: never + optional: true + - id: prd + skill: archflow-prd + pipeline: [produce, self_review, counter_review, triage, adjudicate] + gate: always + - id: design + skill: archflow-design + requires: [prd] + pipeline: [produce, self_review, counter_review, triage, adjudicate] + gate: always + - id: phase-design + skill: archflow-phase-design + requires: [design] + iterates: per_phase + pipeline: [produce, self_review, counter_review, triage, adjudicate] + gate: on_trigger + - id: phase-impl + skill: archflow-phase-impl + requires: [phase-design] + iterates: per_phase + pipeline: [produce, self_review, counter_review, triage, adjudicate] + gate: on_trigger +``` + +`gate: on_trigger` means a human is involved only if a constitution `review_trigger` fires, drift is material, adjudication fails, or attempts are exhausted. + +--- + +## 2. Skills become marshallers + +### 2.1 The pipeline + +Every phase skill runs the same sequence. What varies is the rubric and the artifact. + +``` +1. PRODUCE author the artifact, with constitution injected as constraints +2. SELF REVIEW in-session subagent, craft rubric +3. COUNTER MCP dispatch to the other model family, fresh context +4. TRIAGE reconcile findings; accept or reject each with a reason +5. ADJUDICATE constitution compliance + drift against approved upstream docs +6. GATE raise if required by workflow.yaml or by a trigger; otherwise advance +``` + +Each step calls `archflow_state` on entry and exit. Each step writes a file. Nothing is passed only in conversation. + +### 2.2 What changes in each existing skill + +| Skill | Change | +|---|---| +| `archflow-explore` | Produce only. No review pipeline, no gate. Output is disposable. | +| `archflow-prd` | Add pipeline steps 2–6. Gate always. | +| `archflow-design` | Add pipeline steps 2–6. Gate always. | +| `archflow-phase-design` | Add pipeline steps 2–6. Gate on trigger. Drift measured against `design.md`. | +| `archflow-phase-impl` | Add pipeline steps 2–6. Gate on trigger. Drift measured against `phases//design.md` and `design.md`. | +| `archflow-status` | Read `state.json` instead of inferring from artifacts. | +| *(new)* `archflow-init` | Scaffold `.archflow/` into a repo: workflow.yaml, constitution templates, globals. | + +### 2.3 Rubrics + +Step 2's rubric is bound per phase: + +- **Artifact phases (prd, design, phase-design)** — completeness, internal consistency, unstated assumptions, testability of requirements, does this answer the brief. +- **Implementation phases (phase-impl)** — DRY, simplicity, matches the phase design, dead code, error handling, does each abstraction earn its keep. + +Step 3 uses the same rubric but with an adversarial framing and fresh context: *find what's wrong with this*, not *polish this*. + +### 2.4 Hard requirements on skill behavior + +1. **Deterministic overwrite.** Re-running a phase on a dirty worktree produces the same result as running it clean. No appending, no "I see a partial PRD exists." This is what makes retries safe. +2. **Structured verdict headers.** Every review artifact opens with frontmatter that can be parsed without reading prose: + ```yaml + --- + phase: prd + step: counter_review + verdict: pass | fail | advisory + blocking_count: 2 + review_triggers: [DATA-3] + model: + --- + ``` +3. **No host branching.** Skills contain zero logic keyed on whether they're running in Claude Code or Codex. If a skill needs to know, the decision is in the wrong layer. +4. **Degrade cleanly.** If the MCP server is unreachable, each tool has a documented fallback (§4.4). The skill still completes; it just asks more of the human. + +--- + +## 3. The constitution + +### 3.1 Placement and scope + +One constitution per repo, at the top level of `.archflow/`, applying to every task in that repo. Different repos legitimately differ. There is no per-task or per-branch scope. + +**Invariants:** + +1. **Tasks consume, never author.** A task cites, fails, or requests a waiver against a rule. It cannot add or edit one. +2. **A waiver is not an amendment.** Waivers are per-task, recorded in `state.json`, and expire with the task. +3. **Stable rule IDs.** `DATA-3`, not "the migration one." Append and deprecate; never renumber or reuse. +4. **Versioned with the repo.** Amendments go through normal code review on the base branch. + +### 3.2 The worktree hazard + +The constitution is a file in a repo the agent can write to. A producer can edit the rule blocking it — this is a realistic agent shortcut, not a paranoid edge case. Two required mitigations: + +1. **Adjudication reads the constitution from the base ref.** `git show :.archflow/constitution/...`, never `cat`. A task is judged against the rules that existed when it started. The skill does this directly; no MCP tool needed. +2. **Any diff touching `.archflow/constitution/` in a task branch is an unconditional gate**, regardless of phase or verdict. + +### 3.3 Rule format + +```markdown +## DATA-3 — Schema changes require human review +Any change that adds, alters, or drops a table, column, index, or constraint +must be reviewed by a human before the phase advances. + +review_trigger: artifact adds or modifies a migration +rationale: schema changes are expensive to reverse and easy to get subtly wrong +``` + +```markdown +## STACK-2 — No new runtime dependencies without approval +enforced_by: lint rule `no-unapproved-deps` +review_trigger: dependency manifest modified +``` + +`review_trigger` is what makes a phase stop even when it passes. `enforced_by` tells the adjudicator a rule is checked mechanically so it doesn't spend attention re-deriving it. + +### 3.4 Constitution as input, not just check + +Applicable rules are injected into the producer's context at step 1. The adjudicator is a **backstop confirming compliance**, not a discovery mechanism. If adjudication routinely finds violations, the injection is broken — fix the input, not the check. + +Rules mechanically enforced still belong in the constitution. The constitution is the single source of truth for what's mandatory; the linter is an implementation detail of how some rules get checked. A rule that lives only in lint config becomes tribal knowledge. + +### 3.5 Drift + +Adjudication returns two independent verdicts. The second asks: **does this still live inside the PRD and architecture that were approved?** + +- `aligned` — proceed. +- `incidental` — small clarifications that don't change intent. Recorded, no stop. +- `material` — contradicts, expands, or invalidates something approved. Gate. Resolution is usually to amend the upstream document and re-gate it, not to bend the phase back into shape. + +Keep `material` narrow or the automation goal dies. Guidance: material means *a reader of the approved document would be surprised* — a new external dependency, a changed contract, a dropped requirement, a different data model. Adding a helper is not material. Silently choosing a different library than the architecture named is. + +--- + +## 4. The MCP server + +Bundled with Archflow. Runs locally, spawned by the host over stdio. Its job is to give the agent workflow capabilities that a prompt cannot provide: spawning another model, persisting structured state, and blocking on a human. + +### 4.1 Tools + +| Tool | Signature (shape) | Effect | +|---|---|---| +| `archflow_state` | `(phase, step, status, artifact?)` | Write `state.json`. Cheap, called at every step boundary. | +| `archflow_counter_review` | `(artifact_path, rubric)` → `{path, verdict, blocking_count}` | Spawn the other model family with fresh context; write `reviews/.counter.md`; return the parsed verdict. | +| `archflow_adjudicate` | `(artifact_path, upstream_paths[])` → `{constitution, drift, triggers[]}` | Spawn adjudicator with the base-ref constitution and approved upstream docs; write `reviews/.adjudication.md`. | +| `archflow_gate` | `(phase, summary, context)` → `{decision, notes}` | Write `gate.json`, block until `gate.decision` appears, return it. | +| `archflow_waiver` | `(rule_id, rationale)` → `{granted, notes}` | Same blocking mechanism as gate; records to `state.json` on grant. | + +Five tools. Resist adding more — anything the skill can do with `git` or file reads should not be a tool. + +### 4.2 Host detection + +The MCP `initialize` handshake carries `clientInfo: {name, version}`. The server reads it and knows definitively which host it's serving. Skills never ask, and never rely on a model's self-report of its own identity — models misidentify their versions routinely, and host context in system prompts drifts between releases. + +### 4.3 Model routing + +Defaults ship with the server, keyed on `clientInfo`: + +| Host | producer | self-review | counter-review | adjudicator | +|---|---|---|---|---| +| Claude Code | host model | host model, in-session subagent | Codex family | Codex family | +| Codex | host model | host model, in-session subagent | Claude family | Claude family | + +**One rule, two bindings.** The author writes; a subagent on the same model does the cheap craft pass; the other family provides the adversarial pass. Self-review stays in-session deliberately — its value is being cheap and context-local, and dispatching a separate process for it spends counter-review budget on the least discriminating pass in the pipeline. + +`tasks//config.yaml` overrides the defaults. Written by hand in manual mode, by Archforge in driven mode: + +```yaml +roles: + counter-reviewer: { model: , reasoning: high } + adjudicator: { model: , reasoning: high } +overrides: + design: + counter-reviewer: { model: , reasoning: high } +``` + +Model strings are configuration, never hardcoded in skills or server source. + +**Dispatch flags.** For Codex the server uses `-m ` plus `-c model_reasoning_effort=""`, or a named `--profile`. For Claude, `--model` plus thinking budget. Counter-review and adjudication run at higher reasoning effort than authoring — they're short, single-artifact calls where depth is cheap and being wrong is expensive. + +*Constraint:* a resumed Codex session inherits the original model and reasoning effort; they cannot be overridden on resume. Any "retry with more effort" path must be a clean re-dispatch. + +### 4.4 Invariants + +1. **Counter-reviewer family ≠ producer family.** Validated at dispatch. Same-family is a hard error, not a warning — it looks like coverage and isn't. +2. **Counter-review context is fresh.** No producer session history, no triage output, no earlier findings. Artifact and rubric only. +3. **Rate-limit exhaustion fails loud.** If the counter-review family is unavailable, the step fails with a distinguishable error. It never silently falls back to same-family. +4. **Blocking tools are genuinely blocking.** `archflow_gate` waits on a file, with a long timeout. It does not poll-and-return, and it does not invent an approval. + +### 4.5 Degraded operation + +The server is bundled with Archflow, so its absence should be rare — but the skills document a fallback for each tool so the workflow survives a broken install: + +| Tool | Fallback | +|---|---| +| `archflow_state` | Skip. Status is reconstructable from artifacts on disk. | +| `archflow_counter_review` | Emit a ready-to-paste cross-client prompt (current ArchflowV2 behavior) and stop. | +| `archflow_adjudicate` | Run as an in-session subagent against the base-ref constitution. Weaker (same model) but functional. | +| `archflow_gate` | Print the decision summary and stop. | +| `archflow_waiver` | Print the request and stop. | + +### 4.6 Implementation notes + +- **Language:** Node/TypeScript for distribution ease (`npx`, no runtime install for most developers). Rust is defensible if you later want Archforge to embed the server in-process, but separate processes keep the standalone story simple and the coupling honest. +- **Transport:** stdio. Local only. No network listener. +- **Registration:** `archflow-init` writes the server into `.mcp.json` (Claude Code) and `~/.codex/config.toml` (Codex). +- **Sub-dispatch:** counter-review and adjudication spawn short-lived non-interactive CLI processes (`claude -p`, `codex exec`) under the user's existing subscription auth. Never require API keys. Never export `ANTHROPIC_API_KEY`/`OPENAI_API_KEY` into the child environment — they shadow subscription auth and silently switch to metered billing. + +--- + +## 5. Validation criteria before starting Archforge + +Archflow is done when, using only a terminal: + +1. A feature goes from PRD to merged implementation through every phase. +2. Counter-reviews produce findings the producer actually had to act on — if they come back with restatements and nitpicks, the premise of the whole design is wrong and Archforge shouldn't be built on it. +3. A constitution violation is caught, and the waiver path works. +4. A material drift is caught at phase-impl and correctly escalates. +5. Re-running a phase on a dirty worktree produces a clean, identical result. +6. `state.json` accurately reflects position at every point, verified by killing a session mid-phase and reading the file. + +Item 2 is the one that matters. The rest is mechanics. \ No newline at end of file From cfc3ecadaeb4e0b5e17f434565b7e6d9c9fa30b8 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Sun, 26 Jul 2026 23:46:42 -0500 Subject: [PATCH 003/124] MCP Integration: Design Architecture --- .../tasks/mcp-integration/architecture.md | 700 ++++++++++++++++++ .archflow/tasks/mcp-integration/prd.md | 12 +- .../reviews/architecture-counter-review.md | 238 ++++++ .../reviews/review-findings.md | 49 ++ 4 files changed, 996 insertions(+), 3 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/architecture.md create mode 100644 .archflow/tasks/mcp-integration/reviews/architecture-counter-review.md create mode 100644 .archflow/tasks/mcp-integration/reviews/review-findings.md diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md new file mode 100644 index 00000000..de610bb7 --- /dev/null +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -0,0 +1,700 @@ +# Architecture: MCP Integration + +> Technical design for MCP Integration based on [prd.md](./prd.md), originating from the repository's [detailed design](../../../docs/mcp-integration-design.md) + +`docs/mcp-integration-design.md` is preserved as the originating design lineage. The approved PRD and this architecture are normative wherever they differ; the source design receives a visible lineage/supersession banner and remains linked through later documentation updates rather than being treated as unrelated obsolete material. + +## Technology Stack + +| Layer | Choice | Rationale | +|-------|--------|-----------| +| Runtime and language | Node.js `24.15.0` functional minimum; TypeScript `7.0.2`; `@types/node` `24.13.3`; ECMAScript modules | `write-file-atomic` 8 sets the functional Node floor. Release and CI use the current Node 24 LTS security patch (`24.18.0` at design time), while `@types/node` `24.13.3` is the current compatible Node-24 major typing line pinned independently; runtime and typings patch numbers need not match. | +| MCP | Protocol `2025-11-25`; `@modelcontextprotocol/server@2.0.0-beta.5` | The user accepted the current v2 beta. The SDK is isolated behind an adapter and protected by protocol fixtures and a controlled upgrade procedure. There is no `@modelcontextprotocol/node` dependency and SDK v1 is not a runtime fallback. | +| Tool schemas | Zod `4.4.3` | MCP-facing schemas are derived or wrapped from the normative durable contracts wherever shapes overlap, with only transport-specific wrappers defined locally. | +| Durable schemas | JSON Schema 2020-12 with Ajv `8.20.0` in strict mode | The versioned durable JSON Schema is normative for every persisted shape and every overlapping MCP/persisted shape; files remain independently readable and fail closed on unknown or contradictory data. | +| YAML contracts | `yaml` `2.9.0` | Parses workflow/config files with actionable source locations. | +| Persistence | Repository files, core SHA-256, `write-file-atomic` `8.0.0`, `proper-lockfile` `4.1.2` behind an internal adapter | Keeps authority inspectable and branch-shareable. The lock package's maintenance risk is contained behind replaceable interfaces and crash/race fixtures. | +| Child processes | `execa` `10.0.0` with `shell: false`, `killDescendants: true`, `cancelSignal`, timeout, `maxBuffer`, and forced-termination escalation inside provider-owned OS containment | Execa supplies process control, but each provider must also use a PID namespace/cgroup, Windows job object, or proven equivalent that terminates descendants even after they create new process groups or sessions. | +| Packaging | esbuild `0.28.1`, exact npm lockfile, single host-neutral server/local-helper bundle | `install.sh` installs both `archflow-mcp` and `archflow-local` without an unpinned startup download. | +| Verification | Vitest `4.1.10`, fixture CLIs, fault injection, protocol fixtures, and black-box host/sandbox suites | Critical persistence, host, process, protocol, and manual-mode behavior is exercised at its real boundaries. | + +All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. The listed direct libraries are permissively licensed. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 6 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. + +## System Architecture + +The MCP server is a local, stdio-only durable workflow coordinator. Skills remain the host-neutral source of phase-specific production instructions and rubrics. The server owns only capabilities prompts cannot safely supply: validated transitions, immutable retained results, cross-family process dispatch, policy/drift adjudication, and durable human decisions. + +```text +Claude Code or Codex + | + | thin host-neutral skill + exactly five MCP tools + v +MCP v2 stdio boundary + | + +--> request validation / immutable connection identity + +--> repository + task path guard + +--> workflow/state transition service + +--> file store: lock, CAS, snapshots, projections, reconcile + +--> gate/waiver service <---- explicit local decision files + | + +--> dispatch coordinator + | + +--> versioned, hashed, size-bounded envelope + +--> capability-proven OS sandbox + +--> fresh Claude CLI or Codex CLI process + +--> structured JSON validation + +--> canonical Markdown renderer + +archflow-local (same installed bundle, no MCP transport) + +--> validate / hash / canonical render + +--> snapshot / collision-safe restore + +--> atomic decision creation / degraded status + +--> reconcile/import / legacy upgrade staging + +Git task branch + records workflow state, evidence, decisions, and authoritative snapshots + for the development lifecycle; .archflow/ is deliberately removed before PR +``` + +### Request and Mutation Flow + +The server establishes the repository identity, supported host identity, protocol version, and configuration policy during MCP initialization. A tool call cannot override connection host identity. Every mutating request then follows this order: + +1. Canonicalize the Git worktree and task identity, resolve every declared path, and reject traversal, absolute paths, symlink escapes, cross-task paths, or repository-identity mismatch before any artifact read or child launch. +2. Reconcile the bounded current working set against validated state, then acquire the task-specific same-filesystem process lock. Tasks have independent locks. +3. Reread and strictly validate `state.json` and every referenced machine-readable input; never rely on an earlier in-memory copy. If state is absent, reject every operation except a direct normal/legacy initialization artifact or a `manual-checkpoint-import` whose checkpoint 1 contains one of those valid initialization manifests. +4. Compare `expected_revision` independently on every invocation, including retries and replay attempts; a mismatch returns `STATE_CONFLICT` before intent handling. +5. Check `intent_id` against the canonical request digest. A replay succeeds only when current validated state references the committed intent, result, and resulting revision. A matching but merely prepared receipt is not success; changed reuse returns `INTENT_MISMATCH`. +6. Verify the entire versioned `config.yaml` against the digest pinned at task initialization, returning non-advancing `PINNED_CONFIG_MISMATCH` before dispatch or transition on any byte change; then recompute the declared-input fingerprint from canonical bytes and pinned inputs. The caller's `input_fingerprint` is an assertion, never authority. +7. Perform the bounded operation. Model calls execute from a non-repository temporary directory through the proven sandbox provider. Model JSON must validate before it can become evidence. +8. Materialize the complete immutable result and manifest under its content address, then atomically replace only the declared canonical projections and a `prepared` intent receipt. All pre-state artifacts remain explicitly non-authoritative. +9. Atomically replace `state.json` last with the next monotonic revision and references to the prepared intent/result, thereby committing them. A later maintenance pass may mark the receipt committed, but state is the authority. + +A crash before step 9 never implies success. Ordinary pre-request reconciliation is bounded to the projections referenced by current state, the active or prepared intent relevant to the request, and the active gate or manual-checkpoint head; it does not scan retained result, intent, decision, or checkpoint history. A full-chain/history audit is reserved for explicit repair, import, or audit operations. Reconciliation restores the current projections when collision-safe, otherwise stops for the applicable gate or exact repair; it never promotes a prepared/orphan result or model output by inference. Long-lived gates are the exception to holding a lock continuously: gate creation is committed under the sequence above, the lock is released while the request blocks on a decision file, and resolution reacquires the lock and applies a new CAS transition against the same gate ID. + +The canonical request digest has one closed field list: contract/schema version, logical tool name, canonical repository identity, canonical task identity, operation tag, that operation's request-specific semantic fields from the five-tool table and closed artifact union, and the recomputed declared-input fingerprint. No other field participates. In particular, `intent_id` identifies the receipt but is not self-hashed, while `expected_revision`, connection/transport identifiers, timestamps, attempt counters, timeout/cancellation state, and retry metadata are excluded. CAS remains independent: a retry after `SUPPLEMENTAL_REVIEW_REQUIRED` reuses the same intent and digest with the newly observed `expected_revision`; if triage changes or supersedes the subject, the caller creates a fresh `intent_id`, fingerprint, and request digest. + +Locking and revision CAS coordinate only processes sharing the same filesystem. Git is transport and history, not a distributed lock. Cross-clone concurrent mutation is unsupported and locally undetectable before histories diverge, so one-writer handoff is an operational precondition rather than a server-enforced exclusion. One active writer/worktree owns a task branch; handoff requires an explicit human-approved checkpoint commit and push, a clean pull by the next writer, and identity/revision/conflict checks before mutation. Startup and pull/handoff checks detect divergent task-branch history or Git conflicts; `.archflow/**` uses `merge=binary` (or an equivalent non-text merge policy), and any conflict/divergence state is non-authoritative and blocks mutation. Repair guidance preserves both heads, names the last common authoritative checkpoint, requires the human to choose/replay one successor chain, and records a fresh clean handoff before the next writer resumes. Neither the server nor helper auto-merges, commits, pushes, or claims it can reject an independent clone before divergence. + +Repository initialization and task initialization are distinct. `archflow-init` scaffolds repository assets and host registration only. Before a task can start, the workflow and constitution assets must exist in an immutable human-approved commit; ArchFlow never creates that commit automatically. Fresh task creation through its skill and `archflow-local` stages a `task-initialization` manifest, and `archflow_state` adopts it directly or through a closed manual checkpoint import whose first checkpoint contains that manifest. Both routes begin at no-state/revision-sentinel-0 and establish initialized/revision-1 authority before adopting any later checkpoint. Missing, uncommitted, mismatched, or task-locally modified policy bases fail closed. + +### Directory Structure + +```text +package.json +package-lock.json +tsconfig.json +vitest.config.ts +src/ + main.ts # stdio entry; protocol-only stdout + mcp/ + server.ts # MCP v2 lifecycle and connection context + tools.ts # exactly five registrations + sdk-adapter.ts # beta SDK isolation seam + local/ + cli.ts # archflow-local command surface + operations.ts # shared validation/reconcile/manual operations + contracts/ + mcp.ts # Zod request/result/error contracts + schemas/ # versioned JSON Schemas for durable files + workflow.ts # fixed graph/vocabulary validation + renderers.ts # structured JSON -> canonical Markdown + repository/ + identity.ts # Git/worktree discovery and immutable identity + paths.ts # task-scoped allowlist and symlink defense + state/ + store.ts # transition orchestration and reconciliation + transitions.ts # legal state machine + snapshots.ts # content-addressed result materialization/restore + atomic.ts # atomic replacement abstraction + lock.ts # wrapped per-task lock implementation + implementation-manifest.ts # source-tree/diff snapshot contract + legacy-import-manifest.ts # no-state initialization contract + decisions/ + gates.ts # one-active-gate lifecycle + waivers.ts # rule-scoped grants/denials + review/ + envelopes.ts # bounded, hashed child inputs + counter-review.ts + adjudication.ts + render.ts + dispatch/ + coordinator.ts + errors.ts # stable failure taxonomy + environment.ts # allowlisted child environment + process-tree.ts + sandbox/ + provider.ts # capability/proof interface + probe.ts # black-box repo-read/write isolation checks + hosts/ + claude.ts + codex.ts + identity.ts + init/ + assets.ts + registration.ts # preserving JSON/TOML/settings edits + diagnostics.ts +assets/ + workflow.yaml + constitution/ + README.md + 00-process.md + 10-architecture.md + 20-data.md + 30-product.md +skills/ # one host-neutral source, copied to both clients + archflow-init/SKILL.md + archflow-upgrade/SKILL.md + archflow-explore/SKILL.md + archflow-prd/SKILL.md + archflow-design/SKILL.md + archflow-phase-design/SKILL.md + archflow-phase-impl/SKILL.md + archflow-status/SKILL.md +test/ + unit/ + contracts/ + fixtures/ + mcp/ + claude-cli/ + codex-cli/ + repositories/ + corpus/ + integration/ + isolation/ + crash/ + e2e/ +dist/ # generated offline server/helper bundle, release artifact +install.sh +.github/workflows/ci.yml +``` + +Initialization creates the canonical repository-owned layout below. This layout supersedes the old `architecture.md`, flat phase documents, and ad hoc review names for new tasks; a canonical task has only one authority. + +```text +.archflow/ + workflow.yaml + constitution/ + README.md + 00-process.md + 10-architecture.md + 20-data.md + 30-product.md + + tasks// + config.yaml # versioned whole-file digest pinned at task initialization + state.json + gate.json # only while one gate is active + gate.decision # active-gate decision interface + prd.md + design.md + phases// + design.md + impl-notes.md + reviews/ + .self.md + .counter.md + .triage.md + .adjudication.md + .gate-counter..md + decisions// + request.json + decision.json + results/sha256// + manifest.json + payload/ + intents/.json + attempts//.json + manual/checkpoints/-.json + maintenance/.json + imports// + manifest.json + payload/ +``` + +`results/`, `intents/`, `attempts/`, `manual/checkpoints/`, reviews, decisions, and state are ordinary files checked into Git with the task on its shared branch. Snapshot/checkpoint manifests and manual checkpoints are immutable after creation. `attempts/` is diagnostic and cannot authorize advancement. Every currently authoritative generation and all decision, review, and manual-checkpoint evidence remain retained for the task lifetime. `.archflow/` provides development-lifecycle traceability only and is removed before PR; v1 deliberately does not add or promise a permanent audit export. + +### Data Model and Invariants + +| Entity | Durable identity and content | Authority/invariant | +|--------|------------------------------|---------------------| +| Repository | Canonical worktree root, Git common identity, immutable starting commit | Relocation and linked worktrees are supported; the identity must still match the active task. | +| Task | Canonical task ID, repository identity, import/code baseline, approved policy-base commit, pinned constitution/workflow digests, and whole-file `config.yaml` digest | The approved policy base is explicit and separate from imported or current code. The entire versioned config is immutable for the task; normal execution never reads another task. | +| Task initialization manifest | Versioned normal task ID/repository identity, normal code baseline, explicitly approved policy-base commit and constitution digest, pinned workflow digest, exact whole-file `config.yaml` digest, and canonical paths | Required first authority for a normal task, supplied directly or as checkpoint 1 of a closed manual import. Its policy assets must resolve from an immutable human-approved commit; ArchFlow does not commit them. | +| State revision | Schema version, monotonic revision, phase instance, step/status/attempt, authoritative result refs, approvals, open gate, waivers | `state.json` is normal-mode authority and is written last. A successful step references validating artifacts with matching digests. | +| Declared-input fingerprint | Hash of versioned workflow, the immutable whole-config digest, pinned constitution, canonical artifact/upstream Git identities, rubric, phase instance, and explicitly declared inputs | Recomputed by the server from the canonical identities below. Whole-config binding is deliberate: because config cannot change within a task, it never causes partial in-task invalidation. | +| Result snapshot | Content-addressed manifest, canonical Git identities for tracked outputs, and bounded copied payloads only where required | Immutable and task-local. Canonical Markdown/files are replaceable projections of a referenced snapshot; copied payload accounting enforces the limits below. | +| Intent receipt | Intent ID, canonical request digest, prior/result revision, result/error reference, `prepared`/`committed` marker | Prepared receipts are never replay success. Only current state can commit/reference an intent/result/revision; changed reuse is `INTENT_MISMATCH`. | +| Implementation-output manifest | Versioned tagged artifact binding declared source/task paths and add/modify/delete/rename operations; file type, tree mode, and canonical Git blob identities; before/after digests; base/index/worktree identity; parent-document outputs; exact canonical diff digest; snapshot/restore targets; bounded raw payload bytes where required; and undeclared-change scan | It is the complete phase-implementation and commit-authorization subject. Tracked outputs reuse Git objects rather than copied payloads; restore is collision-safe in normal and manual mode. | +| Legacy-import initialization manifest | Versioned tagged artifact containing selected legacy source identity, immutable import digest, destination identity, code/import baselines, approved policy-base commit/constitution, exact destination `config.yaml` digest, canonical mapping, and staged payload refs | Authorizes only the no-state → initialized transition for a distinct destination and pins that destination's whole config. Imported prose/history remains unapproved/historical. | +| Manual milestone checkpoint | Immutable schema-versioned task/phase/step/status, declared-input fingerprint, authoritative result/snapshot and projection digests, current evidence chain, decisions/gates/waivers, predecessor checkpoint digest/revision, and degraded assurance | In manual mode, only snapshots reachable from the latest valid predecessor-linked checkpoint are authoritative. Prepared/uncheckpointed files are not. Normal and legacy initialization each begin with a checkpoint. | +| Review evidence | Structured source JSON represented by canonical Markdown with subject/input digests, stable findings, verdict/counts, assurance and execution metadata | JSON validates before Markdown rendering. Server-attested, agent-declared, and degraded provenance are distinct and cannot be upgraded by prose. | +| Gate | Unique ID, task/phase/kind, subject/context digests, allowed decisions, active status | At most one active gate per task. Timeout, cancellation, disconnect, or missing decision leaves it pending. | +| Decision | Gate ID, exact subject/context digests, allowed explicit outcome, notes/provenance | Resolves once and is retained under `decisions//`; singular gate files are interfaces, not history. | +| Waiver | Pinned rule version, narrow scope, task/subject/evidence digests, explicit grant/denial and expiry | Never amends policy, crosses tasks, or silently follows a changed subject. | +| Phase instance | `prd`, `design`, `phase-design-`, or `phase-impl-` | Encoding is reversible; phases and supplemental gate reviews never overwrite one another. | + +Canonical Git identity is part of the contract, not an ambient checkout accident. Pinned committed inputs bind the exact Git blob bytes and tree modes from the pinned tree. Repository attributes mark `.archflow/** -text merge=binary`, so its tracked authority bytes neither pass through end-of-line conversion nor receive text merges. For tracked implementation outputs, the manifest binds and reuses the canonical Git blob OID produced after the path's Git attributes/clean conversion plus the tree mode (`100644`, `100755`, `120000`, or deletion); their payload bytes are not duplicated in result storage. Raw payload bytes are copied only when collision-safe restoration needs bytes not available from the bound Git object or an output is untracked/generated and therefore has no canonical blob yet. This contract is invariant across `core.autocrlf`, working-tree line endings, `core.fileMode`, executable-bit support, and symlink checkout capability; unsupported materialization fails with guidance instead of changing the identity. + +Copied untracked/generated/restore payload is capped at 25 MiB per result and 250 MiB per task, counted from validated stored bytes before projection. Exceeding either limit returns stable non-advancing `SNAPSHOT_LIMIT` with the exact offending paths, current/cap byte counts, and safe guidance to reduce or track the declared output; payload is never truncated and never moves to external hidden authority. Before any snapshot or manual checkpoint is projected into Git-tracked `.archflow/`, ArchFlow scans the complete candidate projection for secrets and fails closed with path-safe remediation. Guidance explicitly warns that later deletion of `.archflow/` does not erase secrets from branch history. + +Retention preserves every currently authoritative generation and the complete decision/review/manual-checkpoint chain through task lifetime. An explicit human-approved maintenance operation may prune only unreferenced diagnostic attempts and superseded non-authoritative payloads after reachability validation proves deterministic rerun and every checkpoint chain remain intact. It writes an immutable maintenance record containing every deleted digest, byte count, and human reason before deletion; it cannot prune manifests, current generations, authoritative evidence, or any payload still needed for replay/restore. + +The entire versioned `config.yaml` is pinned byte-for-byte by its initialization digest. Every status/readiness check and mutating invocation verifies it before dispatch or state transition; any difference returns `PINNED_CONFIG_MISMATCH`, identifies the expected and observed digests without echoing config content, and gives one safe next action. There is no in-task amendment or re-pin. An intentional routing, model, or effort change requires a distinct new task or the explicit upgrade flow, so whole-config fingerprint binding never triggers partial in-task evidence invalidation. + +If restoring a declared path would overwrite divergent worktree bytes, reconciliation opens the sole active `restore-collision` gate. Its exact decisions are: `discard-and-restore`, which discards only the declared-path worktree bytes and restores the recorded generation; `adopt-as-new-generation`, which is valid only after the caller changes the declared inputs/fingerprint and supplies a rationale, then creates a new generation from those bytes; or `abort`, which leaves both worktree and state non-advancing. No default, timeout, retry, manual fallback, or repair path silently overwrites the collision. + +Further invariants: + +- The shipped workflow has a fixed phase/step vocabulary. The repository copy is inspectable and driveable, not a plugin engine; structural edits fail validation. +- Normal task state cannot appear from directory presence. Only a validating `task-initialization` transition creates revision 1; legacy initialization uses its separate tag. Both pin an approved immutable policy basis. +- The phase lifecycle remains no document → `DESIGNED` → `IN PROGRESS` → `COMPLETE`. Phase implementation cannot start until the current phase design is workflow-approved. +- An artifact rewrite invalidates all dependent current-digest evidence. Accepted review findings rerun self-review, counter-review, and triage; only the final digest is adjudicated. Exhaustion opens a gate. +- PRD and design always gate. Trigger/uncertainty, material drift, failed adjudication, attempts exhaustion, waivers, and task-branch constitution edits gate. Every implementation also requires a separate digest-bound commit authorization. +- The pinned constitution is read from the immutable base commit. Missing/stale `enforced_by` evidence does not pass. A task-branch constitution-edit gate may request revert/abort or base-branch amendment work, but cannot approve the edit. +- Approved upstream snapshots remain addressable after canonical parent documents are updated. Accepted material drift reopens the affected upstream evidence and approval chain. +- Normal evidence is server-attested only where the server observed the adapter, CLI, family, model, effort, input, and result. In-session self-review is agent-declared or unknown. Manual fallback is explicitly degraded. +- Pure manual authority is the greatest valid immutable checkpoint chain, never loose files or a fabricated `state.json`. Each checkpoint commits exact snapshots, projections, evidence, and decisions through its predecessor digest. +- One active gate is preserved through waiver sequencing. A current review/approval gate may resolve explicitly as non-advancing `waiver-requested`, then closes and archives before `archflow_waiver` opens the sole waiver gate for the recorded rule and scope. A grant resumes the phase against exactly that record; denial remains non-advancing. Gates are never nested. + +### Five-Tool MCP API Boundary + +The MCP server registers exactly these five logical workflow tools. All requests and results are versioned. Repository/task identity comes from validated connection/request context. Every mutation includes `intent_id`, `expected_revision`, and caller-asserted `input_fingerprint`; every success reports the resulting revision. Every error has a stable code, retryability, and safe diagnostic and performs no success side effect. + +| Tool | Request-specific fields | Success result | Architectural effect | +|------|-------------------------|----------------|----------------------| +| `archflow_state` | `phase_instance`, `step`, `status`, optional versioned `artifact` tagged union | `path`, `revision`, `status` | Validates a workflow transition and atomically projects the next `state.json`; same-intent replay returns a result only when current state commits it. | +| `archflow_counter_review` | task-relative `artifact_path`, structured `rubric` | `path`, `verdict`, `blocking_count`, `revision` | Dispatches a fresh opposite-family process with only the counter envelope, validates JSON, stores a result snapshot, and projects the phase-instance counter-review Markdown. | +| `archflow_adjudicate` | task-relative `artifact_path`, declared `upstream_paths` | `path`, separate `constitution` and `drift`, `triggers`, `revision` | Dispatches the configured adjudicator against the pinned constitution and approved upstream snapshots, then records canonical evidence. | +| `archflow_gate` | `phase_instance`, `summary`, structured `context` | explicit `decision`, `notes`, `revision` | Creates or resumes one digest-bound gate and remains pending until a valid decision or explicit cancellation/failure. It never returns “pending” as success. | +| `archflow_waiver` | `rule_id`, `rationale`, narrow `scope` | explicit `granted`, `notes`, `revision` | Uses the same durable gate mechanism and records a grant only for the pinned rule/task/subject/scope. | + +Init, upgrade, status reconstruction, Git inspection, ordinary file reads, artifact production, and manual fallback remain skill or server-internal mechanics. They do not add a sixth tool. + +`archflow_state.artifact` is a closed, versioned tagged union: + +- `task-initialization` binds a fresh task ID/repository identity, normal code baseline, explicitly approved policy-base commit and constitution, pinned workflow digest, exact whole-file `config.yaml` digest, and canonical paths. It is the required first normal authority and may be adopted directly or only as checkpoint 1 of a validating `manual-checkpoint-import`. +- `document` binds a canonical task-relative document path, bytes/digest, declared inputs, snapshot, and projection target. +- `implementation-output` carries the complete implementation-output manifest: declared repository/task-relative source paths; add/modify/delete/rename operations; regular/symlink file type and tree mode; canonical post-attributes Git blob OIDs reused for tracked outputs; capped raw payload bytes only for collision-safe restore or untracked/generated outputs; before/after identities; immutable base commit plus index/worktree identity; parent PRD/design/implementation-note outputs; the exact canonical diff digest used for review and commit authorization; snapshot and restore targets; byte-accounting/secret-scan results; and undeclared-change detection results. Restore validates current collisions and before-images before changing only declared targets; ambiguity opens `restore-collision` and is non-advancing in both normal and manual modes. +- `legacy-import-initialization` carries the immutable staged-import manifest required as the first authority for a legacy destination, including the destination's exact whole-file `config.yaml` digest. It may be adopted directly or as checkpoint 1 of a closed manual import. It uses existing `phase_instance: prd`, leaves the imported PRD draft pending its normal pipeline, creates no migration phase, separates policy from code/import baselines, and rejects unresolved task-local constitution edits. +- `manual-checkpoint-import` carries the greatest fully validated predecessor-linked manual checkpoint chain for adoption/reconciliation into server state. When state is absent, checkpoint 1 must contain a valid `task-initialization` or `legacy-import-initialization`; the server establishes revision 1 from it, then adopts the remaining closed chain without replaying decisions. A single state-last commit references the validated chain and final adopted revision, so interruption cannot expose partial authority. When state exists, the predecessor must match it exactly. No route imports a gap, loose prepared file, or unreferenced decision. + +The union makes document, code-output, and migration state representable without adding a tool or inventing a migration phase instance. + +Gate IDs are deterministic and caller-known from canonical task identity, `intent_id`, and request digest. A skill can therefore present the REQ-41 prompt with the exact gate ID before invoking the blocking call. `archflow_gate` publishes and commits the request before it waits. The other client emits versioned structured JSON, not an authoritative Markdown file. From a second terminal, the human runs `archflow-local` in normal or manual mode; it validates the JSON, binds the exact task/gate/subject/input digests, canonically renders it, and atomically renames the complete projection to `reviews/.gate-counter..md`. The blocking server observes only complete atomic projections, using a filesystem notification plus bounded polling fallback so missed/coalesced notifications do not strand a gate. + +While a gate is pending, its closed legal transition set is supplemental-review ingestion, triage of that review, an explicit decline or gate decision, explicit cancellation, or supersession after an accepted change/changed subject. If an untriaged supplemental review arrives, the wait ends with retryable non-success `SUPPLEMENTAL_REVIEW_REQUIRED` while the gate remains pending. The resumed orchestrator rejects current-digest findings and retries the same intent with refreshed CAS, or accepts a change, closes the gate as non-advancing `superseded`, re-enters the fixed-point pipeline, and later creates a fresh intent and deterministic gate for the new subject. Explicit decline fabricates no review and allows the otherwise-valid decision path. + +### Review Dispatch and Trust Boundaries + +The producer host is derived only from immutable MCP `clientInfo` and supported real-host handshake fixtures. Unknown or ambiguous hosts return `UNSUPPORTED_HOST` before dispatch. Per-task routing can select model and effort, but trusted adapter metadata defines family; counter-review refuses same-family routing with `FAMILY_MISMATCH`. Adjudication may use the opposite family normally; an unavoidable same-family manual adjudication is labeled degraded and failure/uncertainty gates. + +Each dispatch creates a fresh, non-resumed child in a temporary directory outside the repository. Counter-review receives only the artifact bytes, adversarial rubric, fixed result schema, and minimal phase/execution identity. Adjudication receives only its artifact, fixed schema, pinned constitution, and declared approved upstream bytes. Envelopes are canonical, size-bounded, hashed, and retained as declared input evidence. A measured host-specific read set contains the selected first-party CLI's executables, libraries, CA material, and narrowly required own subscription-authentication paths plus envelope/temp paths. ArchFlow trusts that supported CLI and its descendants to use that CLI's own credential store; shared access within the selected CLI process tree is not a release blocker. ArchFlow itself never reads, copies, injects, prompts for, persists, or logs credential values. Generated empty config/home paths are used where compatible. Producer history, triage, prior findings, repository/global agent instructions/config, the other model family's credential store, unrelated secrets/files, and child persistence remain denied. + +`--sandbox read-only` and a temporary current directory are defense-in-depth, not the repository-read boundary. A `SandboxProvider` must: + +- declare its OS/runtime/license identity; +- prepare an auditable allowlist containing the envelope, temp/output paths, and only the measured runtime plus selected CLI's narrowly required own authentication paths; +- prevent reads and writes to the repository and sibling tasks by absolute path, traversal, symlink, inherited descriptor, or child process; +- deny global agent instructions/config, the other model family's credential store, and unrelated secrets; scrub API keys and provider-routing variables; and prove unrelated-secret canaries cannot be read or emitted without treating the selected CLI process tree's use of its own subscription store as a failure; +- allow only the provider-network behavior needed by the first-party CLI; +- use an OS containment primitive capable of terminating every descendant on abort, timeout, server shutdown, or output overflow even if a descendant creates a new process group/session—PID namespace/cgroup, Windows job object, or a proven equivalent, not Execa best effort alone; and +- return a capability proof tied to the OS, provider, CLI/runtime versions, exact allowed-read manifest, and randomized denied canaries. + +At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 6 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. + +The Claude adapter uses fresh `--safe-mode`, `--tools ""`, a strict empty MCP config, disabled slash commands, no persistence, and schema-constrained output. It preflights subscription authentication and managed hooks/policy. Host setup configures and validates the Claude server entry's persistent per-server `timeout` when supported; otherwise a newly started host must inherit `MCP_TOOL_TIMEOUT` as described below. Cancellation or host timeout always leaves a durable resumable gate; timeout-then-resume is supported normal behavior. The Codex adapter uses exact fixture-proven ephemeral, ignore-user-config, `--ignore-rules`, read-only, and output-schema behavior while preserving first-party auth; `--ignore-rules` is inherited-context isolation only, never security confinement. It configures/tests `project_doc_max_bytes=0` or a proven equivalent and rejects managed instruction injection. An ArchFlow deny-all Codex execpolicy remains an early feasibility candidate, and the design does not claim it works. Both adapters still require OS sandbox proof, are version-gated from real fixtures, and spawn with `shell: false`, scrubbed environment, no provider keys/routing or unrelated secrets, `killDescendants`, cancellation, timeout/output bounds, forced escalation, and provider-owned descendant containment. Stable failures cover missing CLI, auth, unsupported host/model, family mismatch, rate limit, timeout, cancellation, overflow, invalid output, nonzero exit, and I/O failure. + +### Initialization, Manual Operation, and Upgrade + +`install.sh` installs one offline host-neutral bundle with stable PATH-resolved `archflow-mcp` and `archflow-local` launchers, then copies the same `skills/` source to both clients. Claude registration must run `claude mcp add --scope project archflow -- archflow-mcp`; the official command creates/updates the PRD-required project `.mcp.json`, which is shared and committed with the repository. It registers the stable command name, never an absolute home/install path. Codex likewise uses its official project registration command. Init preserves all unrelated server entries and settings and narrowly patches only persistent fields the official commands cannot express—such as a supported per-server timeout or required Codex fields—with parse-before/after and byte-preservation fixtures; it never replaces whole JSON/TOML files or claims a generic rewriter. + +Init cannot set an environment variable inherited by the already-running host. If Claude has no persistent per-server timeout, init emits this exact shell-profile line and restart instruction: `export MCP_TOOL_TIMEOUT=3600000` followed by “add this line to the shell profile that launches Claude Code, start a new terminal, then restart Claude Code.” It launches/verifies a newly started host and fails closed until the `archflow-mcp` child inherits the parsed value `3600000`. It detects registration collisions, invalid/untrusted configuration, unsupported runtime/CLI versions, managed-instruction hazards, and missing launcher/sandbox capability. Machine-specific executable locations stay only in installation/PATH resolution and never enter `.mcp.json` or portable task state. + +`archflow-local` exposes local operations for validate, hash, canonical render, snapshot/restore, human-approved maintenance, atomic decision creation, degraded status, reconcile/import, upgrade staging, and `checkpoint`. These are CLI/library functions from the same installed bundle, not MCP tools. “Server unavailable” means this helper remains available. If both server and helper are unavailable, skills fail non-advancing with installation/repair instructions rather than improvising file formats. + +Manual mode never fabricates `state.json`. `archflow-local checkpoint` first reconciles and validates, then atomically writes the next immutable `manual/checkpoints/-.json` bound to its predecessor. Only snapshots and projections referenced by the greatest valid chain checkpoint are authoritative; prepared files not checkpointed remain non-authoritative. Initial normal and legacy checkpoints commit the corresponding task-initialization or legacy-import manifest and approved policy basis. Counter-review emits a self-contained opposite-client prompt and stops. Same-family adjudication is degraded and gates uncertainty. Status is labeled degraded; collision, chain gap, or ambiguity stops. When the server returns, it adopts only the greatest valid chain through `manual-checkpoint-import`, without replaying decisions or inferring missing revisions. + +`archflow-upgrade` invokes an offline local upgrade orchestrator. The user supplies one legacy source and a distinct unused destination; the orchestrator alone receives narrow permission to read that source, stages a hashed immutable import below the destination, and never edits the source. It resolves an explicitly approved policy-base commit/constitution and destination whole-config digest separately from the import/code baseline and rejects unresolved task-local constitution edits. After staging is complete, it calls `archflow_state` with a `legacy-import-initialization` artifact for the destination's no-state → initialized transition. A prepared import or interrupted call is not authoritative; exact replay succeeds only after destination state commits its intent/result/revision, while changed replay or collisions stop. + +Imported PRD, design, and phase documents map to the existing `prd`, `design`, `phase-design-`, and `phase-impl-` instances and rerun their current pipelines—there is no migration phase instance. Legacy completed code is audited through each `phase-impl-` implementation-output manifest and an explicit migration gate kind before it can be represented as validated. Normal/manual paths share staged manifests and conservative milestones. Normal task tools retain the cross-task prohibition; only the offline pre-initialization orchestrator may read the explicitly selected legacy source. + +## Key Decisions + +| Decision | Options Considered | Choice | Rationale | +|----------|--------------------|--------|-----------| +| MCP generation | SDK v1; v2 beta; direct protocol implementation | Exact-pinned MCP v2 beta behind an adapter | The user accepted beta churn for the current API. Contract fixtures and a controlled upgrade procedure contain that risk better than designing against the superseded surface. | +| Workflow authority | Conversation/artifact inference; SQLite; repository files | Strict, file-native state and evidence tracked on the task branch | Human and agents can inspect/share it with Git; there is no hidden database authority. | +| Task creation | Directory presence; init-created state; manifest adoption | Separate normal/legacy initialization tags adopted by `archflow_state` | Both pin a human-approved immutable policy base; repository init never silently creates task authority or commits. | +| Deterministic rerun | Seed model calls; regenerate/merge; retain exact results | Immutable content-addressed snapshots and canonical projections | Supported CLIs do not promise seeded output. Exact bytes are reusable without touching unrelated dirty files. | +| Concurrency | Best-effort; distributed Git lock; local task lock plus CAS | Lock/CAS on one filesystem; one active writer/worktree per task branch with clean checkpoint handoff | Git cannot coordinate live writers. Explicit commit/push/pull handoff prevents false distributed-safety claims and is never automated. | +| State commit order | State before artifact; implicit replay from receipt; prepared result then state commit | Snapshots/projections/receipt are prepared; `state.json` alone commits them; reconcile before every interpretation | A crash cannot turn a prepared receipt into replay success or promote an orphan. | +| Review representation | Model-authored Markdown; raw JSON only; validated JSON plus canonical Markdown | Validate structured JSON, retain it in snapshots, render deterministic Markdown | Separates machine authority from readable evidence and prevents prose from forging verdict/provenance fields. | +| Review isolation | Fresh prompt only; temp cwd/read-only flag; OS-enforced capability-tested sandbox | Sandbox-provider boundary with black-box repository-read/write proof | Fresh process identity is insufficient if the reviewer can discover repository context by absolute path. Unsupported environments fail closed. | +| Sandbox dependency | Roll OS-specific isolation; immediately adopt a tool; evaluate a provider | Prefer `@anthropic-ai/sandbox-runtime` behind the boundary, but adopt only after proof and explicit component-license approval | The package is Apache-2.0, while Linux bubblewrap/socat introduce LGPL/GPL. Unsupported is safer than silent adoption. | +| Reviewer fallback | Same-family substitute; skip; visible pending failure | No same-family counter-review fallback | Substitution would create the appearance of independence. Manual cross-client handoff remains available. | +| Host routing | Skill branches/self-report; environment variable; MCP identity plus adapter fixtures | Immutable connection identity and validated per-task config | Keeps skills host-neutral and fails safely as host/version behavior changes. | +| Task configuration | Mutable per-step routing; partial invalidation; immutable whole config | Pin the complete versioned `config.yaml` at initialization | Routing/model/effort changes create a new task or explicit upgrade; a changed config can never reinterpret evidence inside the current task. | +| Human gates | Conversation approval; short polling; durable blocking gate | One active digest-bound gate with archived decisions and external cancellation semantics | Approval survives sessions and cannot be inferred from timeout, absence, or model prose. | +| Legacy tasks | Auto-promote; mutate in place; abandon; migrate to a new canonical task | Explicit `archflow-upgrade` import followed by current evidence and approvals | Preserves history without representing legacy prose or conversation as modern evidence. | +| Manual mechanics | Skills hand-author formats; extra MCP tools; offline local helper | Bundled host-neutral `archflow-local` CLI/library sharing server contracts | Manual validation and recovery remain deterministic without expanding the five-tool MCP surface. | +| Manual authority | Loose evidence files; fabricated state; immutable checkpoint chain | Greatest valid predecessor-linked manual checkpoint | Prepared files and gaps cannot become authority; server recovery imports the closed chain once without replaying decisions. | +| Policy during upgrade | Derive from imported/code baseline; current worktree; explicit approved policy base | Separate approved policy-base commit/constitution from import/code baseline | Legacy code cannot select or silently modify the policy used to validate it. | +| Distribution | `npx` at startup; dev checkout; offline server/helper bundle | One pinned installed bundle with MCP and local launchers | Host startup and degraded operation are offline/reproducible while skills keep one source. | +| Snapshot bounds and retention | Unbounded payload copies; hidden external store; Git-object reuse plus bounded payloads | Reuse tracked Git objects, cap copied payloads, retain authority/evidence, and allow recorded pruning of unreachable non-authority only | Bounds growth without truncation, hidden authority, broken reruns, or broken checkpoint chains. | +| Audit lifetime | Permanent external archive; delete without explanation; lifecycle Git evidence | Track all evidence on the branch and remove `.archflow/` before PR | Matches current product scope. Durable external export remains REQ-52, not an implied v1 promise. | + +## Testing and Release Strategy + +Testing follows the trust boundaries rather than module percentages: + +- Unit tests cover schema rejection, fixed graph validation, transition tables, canonical hashing/rendering, path allowlists, routing, error classification, and gate/waiver decision validation. A shared valid/invalid corpus proves Ajv and Zod agree for every overlapping durable/MCP shape. +- Contract tests pin MCP initialization and `tools/list` to protocol `2025-11-25`, exactly five v2 tools, schemas, cancellation, and protocol-only stdout. Recorded real Claude Code and Codex handshakes protect host detection from vendor naming drift. +- State integration tests cover normal/legacy no-state initialization, immutable whole-config pinning and `PINNED_CONFIG_MISMATCH`, uncommitted/mismatched policy bases, two same-filesystem processes, exact replay/mismatch/conflict races, prepared-receipt crashes, implementation manifests, independent tasks, projection restore and `restore-collision`, manual checkpoint-chain import, and fault injection. Separate-clone tests acknowledge that pre-divergence concurrency is locally undetectable, then exercise divergent-history/conflict detection, non-authoritative blocking, repair/replay, and clean Git handoff. +- Path tests use traversal, absolute paths, symlink escapes, sibling tasks, linked worktrees, relocation, and paths with spaces/Unicode before reads or dispatch. +- Adapter fixtures use fake CLIs for every stable failure class and version behavior. Real supported-version smoke fixtures verify first-party auth detection, model/family identity, flags, fresh PID/session, structured output, cancellation, and process-tree death without persisting secrets. +- Sandbox black-box tests use randomized repository/instruction, other-family-auth, and unrelated-secret canaries plus output/diagnostic scans to prove the selected first-party CLI can use its own subscription authentication while ArchFlow never handles credential values, API keys/provider routing are scrubbed, model input remains envelope-only, writes remain temp-only, and repository/sibling/global discovery fails. Shared own-auth access inside the selected CLI process tree is not a failure. Tests also spawn descendants that create new process groups/sessions and prove the provider containment primitive terminates them on every stop path. A provider/OS/CLI combination is unsupported until this passes under its release artifact. +- Review/adjudication corpus tests seed substantive defects, clean controls, trigger uncertainty, `enforced_by` evidence states, aligned/incidental/material drift, repeated rewrites, and exhaustion. Release thresholds are chosen and explicitly approved from observed results; finding count is not the metric. +- Manual-mode tests remove each tool and then the server while retaining `archflow-local`, drive normal and legacy initialization plus two phases through immutable checkpoint chains, gates, waiver, supplemental review/decline, commit authorization, and greatest-valid-chain recovery/import. Prepared/unlinked files remain non-authoritative; removing server and helper fails for repair. +- End-to-end tests run both producer directions entirely from a terminal and verify branch-tracked artifacts, explicit checkpoint handoff, no auto-commit, no premature implementation/commit, parent updates, non-colliding evidence, immutable config mismatch status, representative snapshot growth/caps/retention/maintenance records/secret rejection, deterministic dirty-worktree restore/collision decisions, Git normalization across line-ending and mode/symlink checkout configurations, interruption/resume, and cleanup guidance. +- Repository-consistency tests compare `CLAUDE.md`, tracked/project `AGENTS.md` policy where in scope, `README.md`, `docs/archflow-process.md`, the preserved lineage/supersession banner and links in `docs/mcp-integration-design.md`, `install.sh` output, and every installed skill listing against the canonical workflow/tool/layout contracts. + +Release is blocked unless all applicable tests pass and the supported matrix is documented. In addition: + +1. A sandbox provider/OS combination has current black-box proof and an explicitly acceptable license. Unsupported environments fail closed rather than receiving reduced isolation. +2. Real minimum supported Claude/Codex host and CLI versions have fixtures; initialization validates the persistent per-server timeout or inherited `MCP_TOOL_TIMEOUT`, Claude safe-mode/tool/MCP/slash-command/persistence constraints, Codex config/rules/project-document suppression, and official registration behavior. +3. Written Anthropic clarification or a qualified legal determination establishes that third-party local subscription-authenticated Claude dispatch is permitted (`VAL-14`). Internal risk acceptance alone does not satisfy this gate. Until then, the integration may be implemented and tested with fixtures, but no release may advertise or enable that Claude dispatch path. +4. The exact dependency lock, licenses/notices, MCP beta migration notes, and offline bundle are reproducible. Any selected sandbox license is surfaced explicitly. +5. `VAL-01` through `VAL-06` pass in terminal runs before Archforge implementation begins. If `VAL-02` does not demonstrate useful independent review, the automation premise is revisited rather than compensated for with more mechanics. + +## Requirement and Validation Coverage + +| Coverage area | Requirements | Validation | Primary phases | Proof boundary | +|---------------|--------------|------------|----------------|----------------| +| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 9, 10, 15 | Strict assets/schemas, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | +| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 8, 10, 14, 15 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | +| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 1, 2, 3, 4, 7, 10, 11, 13, 14 | Structured JSON/projections, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | +| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 7, 12, 13, 14 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | +| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 5, 7, 12, 14 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | +| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 2, 3, 4, 5, 11, 13, 14 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | +| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 2, 3, 4, 5, 11, 12, 13 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | +| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 2, 3, 4, 6, 12, 13, 14 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | +| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 1, 8, 9, 13, 14 | v2 fixtures expose five stdio tools; the separate offline helper is not an MCP tool. | +| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 6, 8, 13, 14 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | +| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 6, 7, 8, 13, 14 | Hashed envelopes, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | +| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 6, 9, 13, 14, 15 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | +| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 5, 8, 11, 13, 14 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | +| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 8, 9, 11, 12, 14 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | +| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 5, 10, 11, 14 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | +| Legacy migration | REQ-50 | VAL-17 | 2, 3, 4, 5, 12, 13, 14 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | + +All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release validations `VAL-01` through `VAL-17`, appear above. `REQ-52` remains explicitly outside the v1 architecture. + +## Phases + +### Phase 1: Contracts, Assets, and Package Scaffold + +**Goal**: Establish a buildable server package and the versioned contracts all later phases share. + +**Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-11, REQ-12, REQ-15, REQ-17, REQ-27, REQ-28, REQ-33 + +**Scope**: As the first Phase 1 action before server implementation, add a visible lineage/supersession banner to `docs/mcp-integration-design.md` identifying it as the originating detailed design and the approved PRD/architecture as normative where they differ; Phase 15 later updates the surrounding documentation while preserving that history. Then add Node/TypeScript/MCP v2 beta package scaffolding and exact lockfile; isolate the beta SDK adapter; define the fixed workflow vocabulary, shipped workflow and constitution assets, normative strict durable JSON Schemas, derived/wrapped Zod MCP contracts, a shared validator-agreement corpus, canonical phase-instance encoding, canonical Markdown renderers, error envelope, license notices, build, lint/typecheck, and protocol/contract fixture harness. This phase does not implement persistent transitions or dispatch. + +**Success Criteria**: + +- [ ] The project installs from the exact lockfile, typechecks, tests, and builds at the functional Node floor `24.15.0`; CI/release also passes on the current Node 24 LTS security patch (`24.18.0` at design time), independently of the Node-24 typings patch. +- [ ] MCP initialization and `tools/list` fixtures expose protocol `2025-11-25`, exactly the five named tools, and versioned schemas; stdout contains no non-protocol output. +- [ ] Valid workflow/review/state samples round-trip through strict schemas and canonical rendering, while unknown graph vocabulary, invalid verdict/count combinations, and non-reversible phase IDs fail with stable errors. For every overlapping persisted/MCP shape, the same valid/invalid corpus proves Ajv and Zod accept and reject identically. +- [ ] The dependency-upgrade procedure demonstrates that changing the MCP beta pin requires fixture, lockfile, and license review. +- [ ] Phase 1's first change adds the source design's visible lineage/supersession banner, links the approved PRD/architecture, preserves its originating-design status, and precedes all server implementation. + +### Phase 2: Repository Identity, Paths, Schemas, and Canonical Digests + +**Goal**: Establish the repository/task identity, path safety, durable schemas, immutable task configuration, and byte-stable digest contracts used by every mutation. + +**Depends on**: Phase 1 + +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-13, REQ-14, REQ-21, REQ-26, REQ-33, REQ-39, REQ-50 + +**Scope**: Implement Git/worktree and task identity; `.archflow/** -text merge=binary`; path allowlists; task-initialization, document, implementation-output, legacy-import, manual-checkpoint, checkpoint-import, maintenance-record, and snapshot-accounting schemas; exact whole-file `config.yaml` pinning; canonical Git blob/tree-mode and request/input digests; divergence/conflict detection; and secret-scan result contracts. This phase does not implement state mutation or payload restore. + +**Success Criteria**: + +- [ ] Task initialization schemas bind the exact whole-file config digest. Any byte change is detected as `PINNED_CONFIG_MISMATCH` with expected/observed digests and no config content; no re-pin/amendment schema exists. +- [ ] Traversal, absolute paths, symlink escape, cross-task access, and identity mismatch fail before reads, while linked worktrees, relocation, spaces, and Unicode pass. +- [ ] Committed inputs and tracked outputs have identical canonical Git blob/tree identities across LF/CRLF worktrees, `core.autocrlf`, `core.fileMode`, executable-bit support, and symlink-capable/incapable checkouts; unsupported materialization fails closed. +- [ ] Valid initialization/document/implementation/import/checkpoint/maintenance samples round-trip through normative schemas; predecessor gaps, unknown fields, digest mismatches, invalid phase IDs, and contradictory accounting fail with stable errors. +- [ ] Startup and pull/handoff detection identifies divergent histories and `.archflow/**` conflicts as non-authoritative without claiming it can detect independent-clone concurrency before divergence. + +### Phase 3: Transaction Kernel, Intent/CAS, and Crash Recovery + +**Goal**: Commit one task's transitions exactly once under races, crashes, retries, config drift, and bounded reconciliation. + +**Depends on**: Phase 2 + +**Requirements**: REQ-04, REQ-08, REQ-13, REQ-14, REQ-21, REQ-22, REQ-23, REQ-24, REQ-26, REQ-39, REQ-50 + +**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 4. + +**Success Criteria**: + +- [ ] Exact replay returns the recorded revision/result only when current state commits it; prepared receipts do not. The request digest excludes revision/retry transport data, CAS is checked on every invocation, changed reuse returns `INTENT_MISMATCH`, stale writers return `STATE_CONFLICT`, and two same-filesystem processes yield one winner. +- [ ] Fault injection before/during/after every receipt/projection/state write leaves prior/next valid state or precise non-advancing repair; reconciliation never promotes an orphan as success. +- [ ] A normal task reaches revision 1 only from a valid `task-initialization` supplied directly or as checkpoint 1 of a closed manual import; legacy initialization follows its tagged equivalent and missing/mismatched policy fails. +- [ ] Any config byte change returns `PINNED_CONFIG_MISMATCH` before dispatch/state transition; status reports the mismatch and directs intentional routing/model/effort changes to a distinct task or explicit upgrade. +- [ ] Mature-task step boundaries and status reconcile only current state projections, the relevant active/prepared intent, and active gate/checkpoint head; only explicit repair/import/audit walks history. +- [ ] Divergent/conflicted clones remain non-authoritative until preserve-both-heads repair selects/replays one successor chain and records a clean one-writer handoff. + +### Phase 4: Snapshots, Implementation Manifests, and Restore + +**Goal**: Retain and restore deterministic declared outputs within explicit storage, retention, collision, and secret-safety bounds. + +**Depends on**: Phase 3 + +**Requirements**: REQ-08, REQ-11, REQ-13, REQ-21, REQ-22, REQ-23, REQ-25, REQ-26, REQ-33, REQ-39, REQ-50 + +**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 5 connects collision decisions to the gate service. + +**Success Criteria**: + +- [ ] An unchanged fingerprint restores byte-identical declared outputs while unrelated tracked/untracked bytes remain untouched; a changed fingerprint creates one new retained generation, and a collision changes nothing before an explicit decision. +- [ ] Implementation manifests round-trip add/modify/delete/rename, binary content, tree modes, canonical post-attributes Git blob OIDs, retained restore/untracked payloads, before/after identities, parent outputs, and exact diff digest; tracked outputs reuse Git objects rather than copied payloads. +- [ ] Representative payload growth reaches but never exceeds 25 MiB per result or 250 MiB per task; either excess returns non-advancing `SNAPSHOT_LIMIT` with counts/guidance, writes no partial/truncated payload, and creates no hidden authority. +- [ ] Every current authoritative generation and all decision/review/checkpoint evidence remain reachable. Human-approved maintenance prunes only unreferenced diagnostic attempts or superseded non-authoritative payloads, writes an immutable deleted-digest/bytes/reason record, and cannot break rerun, restore, or checkpoint chains. +- [ ] Secret fixtures in any candidate Git-tracked snapshot/checkpoint projection fail before projection with safe remediation warning that later `.archflow/` deletion cannot erase branch history; clean binary/text fixtures pass without logging secret values. +- [ ] Snapshot/projection/restore fault injection preserves prior/next authority or exact repair, and the three `restore-collision` outcomes are representable without silent overwrite. + +### Phase 5: Durable Gates, Waivers, and Manual Decisions + +**Goal**: Persist every human authority boundary independently of a live MCP request. + +**Depends on**: Phase 4 + +**Requirements**: REQ-09, REQ-13, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 + +**Scope**: Implement the one-active-gate lifecycle, retained gate-ID request/decision archives, blocking/cancellation/resume semantics, `waiver-requested` close/archive sequencing, scoped waivers and expiry, digest-bound commit authorization, `restore-collision`, supplemental gate-counter evidence paths, exact manual request/decision templates, and conservative evidence reconciliation. + +**Success Criteria**: + +- [ ] A connected call blocks until a schema-valid exact decision or explicit cancellation/failure; restart/cancellation leaves one resumable pending gate and never returns pending as success. +- [ ] Partial, malformed, stale, wrong-task, wrong-ID, wrong-digest, duplicated, and approval-shaped constitution-edit decisions cannot resolve or advance a gate; one valid decision resolves exactly once. +- [ ] Two processes cannot create or resolve conflicting gates/waivers; separate tasks can wait independently. +- [ ] Manual files can record multiple non-colliding gates, one waiver, supplemental review/decline, and commit authorization, and recovery imports only complete decisions without repetition. +- [ ] A `SUPPLEMENTAL_REVIEW_REQUIRED` retry after an intervening transition reuses the same intent/request digest with refreshed `expected_revision`; accepted-change or other subject supersession closes the old gate and requires a fresh intent/generation. +- [ ] `waiver-requested` is non-advancing and archives the current gate before the sole waiver gate opens; grant resumes only the recorded rule/scope, denial remains non-advancing, and no nested gate exists. `restore-collision` exposes only discard-and-restore, adopt-as-new-generation with changed inputs/fingerprint and rationale, or abort. +- [ ] A real Claude host timeout leaves one pending gate, and a later invocation resumes and resolves that gate exactly once; timeout-then-resume is normal supported behavior. + +### Phase 6: Host Identity, Sandbox, and CLI Dispatch + +**Goal**: Prove fresh opposite-family reviewer processes receive only declared envelopes and are safe to dispatch on every claimed environment. + +**Depends on**: Phases 1–5 + +**Requirements**: REQ-26, REQ-29, REQ-30, REQ-31, REQ-32, REQ-34, REQ-35 + +**Scope**: Implement immutable host identity, routing/family validation, exact adapters, auth/version/managed-policy preflights, selected-CLI runtime/own-auth allowlists, generated empty config/home, repository/global/other-family/unrelated-secret isolation, environment scrubbing, canary/output scans, bounded envelopes, process lifecycle/failures, provider probes, and candidate/license evaluation without automatic adoption. + +**Success Criteria**: + +- [ ] Real handshake fixtures identify supported Claude Code/Codex versions; missing/ambiguous/unsupported identity and same-family routing launch no child. +- [ ] Both producer directions prove a fresh PID/session and expected family. Provider-key/routing sentinels and unrelated secrets are absent from child input and persisted diagnostics. +- [ ] Both supported first-party CLIs use their own subscription authentication without ArchFlow reading, copying, injecting, prompting for, persisting, or logging credential values. Shared own-auth access in the selected CLI process tree is permitted; API-key/provider-routing variables remain scrubbed. +- [ ] A randomized black-box child can read its envelope/temp, measured runtime, and selected CLI's narrowly required own-auth paths, but cannot read/write the repository, sibling tasks, global agent instructions/config, the other family's credential store, or unrelated-secret canaries. Output/diagnostics emit no unrelated-secret canary. No environment is supported without this proof in both producer directions. +- [ ] Missing CLI, bad/unsupported auth or model, rate limit, timeout, cancellation, output overflow, invalid JSON, nonzero exit, and I/O failure remain distinguishable; descendants die and none produces pass evidence. +- [ ] For every supported SandboxProvider, descendants that create new process groups/sessions are terminated by the provider's PID namespace/cgroup/job object or proven equivalent on cancellation, timeout, shutdown, and overflow; Execa best effort alone cannot satisfy the proof. +- [ ] Any external sandbox dependency and license is presented for explicit acceptance before adoption; copyleft is never silently bundled. +- [ ] The Anthropic subscription-authenticated dispatch path remains release-disabled until written clarification or a qualified legal determination satisfies `VAL-14`; implementation or fixture success is not legal approval. + +### Phase 7: Constitution Adjudication, Drift, and Review Fixed Point + +**Goal**: Turn validated reviewer output and pinned policy/upstream inputs into current-digest advancement evidence. + +**Depends on**: Phases 1–6 + +**Requirements**: REQ-10, REQ-11, REQ-12, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-32, REQ-33 + +**Scope**: Implement counter-review/adjudication orchestration, structured result validation, server-attested canonical rendering, stable findings and exact triage, accepted-finding reruns, attempt bounds, explicit approved-policy-base constitution resolution, `review_trigger` and current `enforced_by` evaluation, separate compliance/drift verdicts, unresolved task-local constitution-edit rejection, and upstream evidence invalidation/reopening. + +**Success Criteria**: + +- [ ] Accepted findings across two rewrites invalidate stale evidence, rerun self/counter/triage, and adjudicate only the final digest; blockers never authorize advancement and exhaustion gates. +- [ ] The curated corpus distinguishes seeded substantive defects from clean controls and records approved release thresholds based on quality rather than finding count. +- [ ] Positive, negative, and uncertain triggers plus current/missing/stale/failed mechanical evidence behave fail-closed against the approved policy-base constitution. +- [ ] Aligned and incidental drift are recorded correctly; material drift gates and an accepted change reopens the affected upstream approval/evidence chain. + +### Phase 8: Five-Tool MCP Assembly and Offline Local CLI + +**Goal**: Assemble persistence, dispatch, adjudication, and decisions behind the complete and only MCP workflow surface. + +**Depends on**: Phases 1–7 + +**Requirements**: REQ-07, REQ-08, REQ-11, REQ-13, REQ-21, REQ-23, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40 + +**Scope**: Wire exactly five handlers through the v2 adapter and implement `archflow-local` for validate, hash, render, snapshot/restore, human-approved maintenance with immutable records, atomic decisions, degraded status, reconcile/import, upgrade staging, and immutable checkpoint creation/chain validation. Connect mutation/replay, dispatch, evidence, supplemental interruption, cancellation, protocol-only stdout, and public errors. Init and upgrade remain outside the tool list. + +**Success Criteria**: + +- [ ] Live `tools/list` returns exactly `archflow_state`, `archflow_counter_review`, `archflow_adjudicate`, `archflow_gate`, and `archflow_waiver`, with the normative schemas and no sixth workflow tool. +- [ ] Valid and invalid calls exhibit replay, mismatch, conflict, family, host, path, child, and blocking semantics without partial success side effects. +- [ ] MCP cancellation leaves durable truth and kills active descendants; reconnect/resume observes existing state/gate rather than duplicating work. +- [ ] The bundled server emits only MCP traffic on stdout and opens no network listener. +- [ ] The offline helper performs its named local operations without MCP, shares schemas/renderers with the server, and is absent from `tools/list`. +- [ ] `archflow-local checkpoint` atomically extends only a valid reconciled chain, and server adoption imports only its greatest valid checkpoint via the closed union tag. + +### Phase 9: Installer, Initialization, and Host Registration + +**Goal**: Install the offline bundle and initialize supported repositories repeatedly without damaging host or project configuration. + +**Depends on**: Phases 1, 6, and 8 + +**Requirements**: REQ-01, REQ-02, REQ-28, REQ-29, REQ-34, REQ-37, REQ-40 + +**Scope**: Extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. + +**Success Criteria**: + +- [ ] Installation from a clean checkout starts the exact pinned bundle offline on every claimed Node/host environment. +- [ ] Init reruns byte-stably, preserves unrelated JSON/TOML/settings, and reports collisions, malformed/untrusted config, unsupported runtime/CLI/auth, or missing sandbox proof without claiming success. +- [ ] Claude registration uses `claude mcp add --scope project archflow -- archflow-mcp`, produces the PRD-required shared/committed `.mcp.json`, contains no absolute home/install path, and preserves unrelated project registration/config bytes. Codex registration likewise uses its stable PATH launcher and preserves unrelated config. +- [ ] When Claude lacks a persistent per-server timeout, init explains that it cannot alter the current host's inherited environment, emits exactly `export MCP_TOOL_TIMEOUT=3600000` plus profile/new-terminal/restart guidance, and fails closed until a newly started host proves `archflow-mcp` inherited `3600000`. +- [ ] The owned install manifest upgrades/removes only ArchFlow-owned obsolete files; unrelated Claude/Codex skills and host files remain byte-identical. +- [ ] Initialized state is Git-trackable/shareable, contains no machine-specific executable path in portable task state, and works after repository relocation and in linked/space/Unicode worktrees. +- [ ] `archflow-init` creates no task state and no commit. Fresh task creation refuses to start until workflow/constitution assets resolve from an explicitly approved immutable commit and then stages the normal initialization manifest. + +### Phase 10: Normal-Mode Thin Phase Skills and Truthful Status + +**Goal**: Drive the normal MCP workflow from host-neutral phase skills and report only reconciled durable truth. + +**Depends on**: Phases 1–9 + +**Requirements**: REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-13, REQ-14, REQ-20, REQ-41 + +**Scope**: Rewrite the five phase skills and status as normal-mode marshallers over the fixed pipeline; preserve one source for both clients; use implementation manifests; enforce workflow approval and exact-diff commit authorization; update canonical parents/notes; offer deterministic gate-ID supplemental prompts; direct the second-terminal human to ingest the other client's structured JSON through `archflow-local`; and reconcile before truthful status. Manual fallbacks and upgrade are later phases. + +**Success Criteria**: + +- [ ] No skill branches on host identity or adds workflow tools; the same source installs and drives both producer directions. +- [ ] Phase design cannot become `DESIGNED` or permit code while evidence/gates are incomplete, and phase implementation cannot commit/complete before explicit final-digest authorization. +- [ ] Every human gate offers the optional other-client prompt; the other client emits structured JSON and, from a second terminal, the human runs `archflow-local` in normal/manual mode to validate, bind, canonically render, and atomically rename it to the gate-counter path. Decline records no fabricated review. +- [ ] The server sees only complete supplemental projections through filesystem notification plus bounded polling fallback. The gate-pending transition table admits only supplemental ingestion, triage, explicit decline/decision, cancellation, or supersession; `SUPPLEMENTAL_REVIEW_REQUIRED` rejection resumes the gate and accepted change supersedes it and re-enters the fixed point. +- [ ] Status verifies the immutable whole-config digest before recommending work; `PINNED_CONFIG_MISMATCH` reports no config content and recommends only a distinct new task or explicit upgrade for intentional routing/model/effort changes. + +### Phase 11: Manual and Degraded Recovery Workflow + +**Goal**: Complete and recover the workflow conservatively when individual MCP tools or the server are unavailable. + +**Depends on**: Phases 1–10 + +**Requirements**: REQ-08, REQ-09, REQ-11, REQ-12, REQ-13, REQ-14, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41 + +**Scope**: Add exact per-tool fallback templates and skill flows using `archflow-local` for reconciliation, validation/hashing/rendering, snapshots/restores, atomic decisions, immutable manual milestone checkpoints, degraded status, and greatest-valid-chain import. Define initial normal/legacy checkpoints, one-writer handoff, and both-server-and-helper repair behavior. + +**Success Criteria**: + +- [ ] Removing each MCP capability and then the whole server still yields validating non-colliding artifacts, explicit decisions, retained exact results, and degraded truthful status through a multi-phase task. +- [ ] Prepared receipts/results never become manual success; collision, ambiguity, or absent helper stops non-advancing with exact repair instructions. +- [ ] Only snapshots/evidence/decisions reachable from the latest valid checkpoint are manual authority; server recovery adopts the greatest closed chain without replay or inferred gaps. +- [ ] Supplemental-review arrival, rejection/resume, accepted-change supersession, explicit decline, cancellation, and restart behave identically to normal-mode milestones. +- [ ] Manual operation never auto-commits/pushes and documents clean human-approved checkpoint handoff between writers. + +### Phase 12: Legacy Upgrade Workflow + +**Goal**: Migrate selected legacy material into a distinct canonical task without changing or implicitly approving the source. + +**Depends on**: Phases 2–5, 7, 8, 10, and 11 + +**Requirements**: REQ-02, REQ-04, REQ-09, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 + +**Scope**: Add `archflow-upgrade` and its offline orchestrator: narrow selected-source read, immutable destination staging, explicit policy-base selection, no-state initialization manifest transition, mapping into existing phase instances, current-pipeline reruns, phase implementation-output audits, migration gate kind, and normal/manual interruption/replay. Use this repository's current legacy `.archflow/tasks/...` layout as an upgrade fixture and document release handling for users whose legacy tasks are in flight. + +**Success Criteria**: + +- [ ] Source bytes remain identical; destination staging is content-addressed and an interrupted/prepared import never initializes state. +- [ ] Exact replay returns the committed initialized destination, while changed source/destination/policy/config inputs or collisions stop without overwrite; the destination's whole config is pinned by its initialization manifest. +- [ ] Imported PRD/design/phases are unapproved/historical until existing current-digest pipelines approve them; no migration phase instance exists. +- [ ] Completed code is validated only by `phase-impl-` implementation manifests and an explicit migration gate, with separate approved policy and import/code baselines. +- [ ] Pure manual upgrade begins with a validating legacy-initialization checkpoint and later server recovery adopts its chain without changing the source or replaying decisions. +- [ ] The repository's current legacy task layout upgrades through the same fixture path, and release guidance tells users with in-flight tasks how to finish in legacy tooling or checkpoint/handoff into a distinct upgraded task without silent in-place conversion. + +### Phase 13: Reliability and Security Matrices + +**Goal**: Prove persistence, race, path, process, and isolation invariants under adversarial failures. + +**Depends on**: Phases 1–12 + +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-50 + +**Scope**: Expand the owning-phase proofs across fault/configuration matrices: task/manual initialization and checkpoint chains; immutable-config mutations; local races and clone-divergence repair; Git text/mode/symlink normalization; snapshot growth/caps/retention/maintenance/secret scanning; implementation-manifest operations; path portability; gate attacks; selected-CLI own-auth trust with repository/global/other-family/unrelated-secret isolation; managed context injection; descendant escape; cancellation; and migration. + +**Success Criteria**: + +- [ ] Every crash point leaves committed prior/next state or precise non-advancing repair, with prepared material never inferred as success. +- [ ] Same-filesystem races yield one winner plus `STATE_CONFLICT`; independent-clone concurrency is documented as unsupported and locally undetectable before divergence, while divergent histories/conflicts are detected, remain non-authoritative, and pass preserve-both-heads repair plus clean one-writer handoff tests. +- [ ] Path, sandbox, managed-context, secret, descendant, and malformed-decision attacks read/write no undeclared repository data and create no pass/approval. +- [ ] Every config-byte mutation, including routing/model/effort and semantically equivalent rewrites, returns `PINNED_CONFIG_MISMATCH` before dispatch/transition and status gives the new-task/upgrade guidance. +- [ ] The selected CLI may use its own subscription store, but ArchFlow never handles credential values; repository/global/other-family/unrelated-secret canaries remain unreadable/unemitted, and API-key/provider-routing sentinels are absent. Lack of this proof marks the matrix entry unsupported. +- [ ] Binary/mode/rename/delete restore, manual recovery, and legacy staging remain collision-safe under fault injection; tracked canonical blob/tree identities remain stable across attributes, LF/CRLF and `core.autocrlf`, `core.fileMode`, executable-bit, and symlink checkout cases. +- [ ] Boundary and over-limit payload matrices prove 25 MiB/result and 250 MiB/task enforcement, no truncation/hidden authority, authoritative/evidence retention, maintenance reachability records, and pre-projection secret rejection under crashes and retries. + +### Phase 14: Real-Host E2E and Review-Quality Validation + +**Goal**: Validate useful independent review and complete normal, manual, and migration journeys in both producer directions. + +**Depends on**: Phases 1–13 + +**Requirements**: REQ-01, REQ-02, REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 + +**Scope**: Run real supported Claude→Codex and Codex→Claude journeys, clean normal initialization plus policy/config mismatch cases, server-absent checkpoint journeys, upgrade journeys, multi-phase non-collision, representative snapshot growth/caps/retention/maintenance/secret rejection, dirty restore and `restore-collision` decisions, interruption/resume, optional gate review, selected-CLI own-auth plus prohibited-access canaries/output scans, and the review/policy/drift corpus. Set thresholds from results. + +**Success Criteria**: + +- [ ] `VAL-01` through `VAL-13` and `VAL-15` through `VAL-17` have reproducible evidence; `VAL-01` through `VAL-06` pass before any Archforge work begins. +- [ ] Both producer directions prove fresh opposite-family review, exact approvals/commit subjects, non-colliding phase evidence, parent updates, and no premature implementation or commit. +- [ ] Normal, manual, and migration journeys reach equivalent conservative milestones through interruption without fabricated evidence. +- [ ] Normal and manual journeys prove no restore collision overwrites silently: discard-and-restore touches only declared paths, adopt requires changed declared inputs/fingerprint plus rationale and creates a new generation, and abort leaves state/worktree non-advancing. +- [ ] Clean normal initialization reaches revision 1 only from the committed approved policy base; missing/uncommitted/mismatched bases fail. Manual initialization/checkpoints and greatest-chain recovery produce equivalent conservative authority. +- [ ] Every supported real host/provider proves the selected first-party CLI's own subscription authentication works in both producer directions while ArchFlow handles no credential values, API-key/provider routing is scrubbed, and repository/global/other-family/unrelated-secret canaries remain inaccessible/unemitted; shared selected-CLI own-auth access alone does not fail the run. +- [ ] A real task reaches the snapshot boundaries, receives `SNAPSHOT_LIMIT` above either cap without partial authority, retains all current/evidence chains, records a safe maintenance prune, and rejects a secret-bearing checkpoint before Git projection. +- [ ] The approved corpus thresholds demonstrate substantive defect detection and acceptable false blockers; failure of `VAL-02` reopens the automation premise. + +### Phase 15: Release Packaging, Support Matrix, and Documentation Consistency + +**Goal**: Produce a coherent beta release candidate and an explicit report of any remaining external release blockers. + +**Depends on**: Phases 1–14 + +**Requirements**: REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 + +**Scope**: Reproduce the exact server/helper bundle and dependency notices; publish the supported Node/host/CLI/OS/sandbox/auth matrix and operations guidance; update `CLAUDE.md`, tracked/project `AGENTS.md` policy where in scope, `README.md`, process documentation, and the originating `docs/mcp-integration-design.md` while preserving its visible lineage/supersession banner and links to the normative PRD/architecture; update `install.sh` output and every installed skill listing; add agreement tests; and report the external Anthropic legal gate. + +**Success Criteria**: + +- [ ] The Node `24.15.0` functional floor, current Node 24 LTS security patch used by release/CI (`24.18.0` at design time), independently pinned Node-24 typings line, exact dependency/CLI/host pins, bundle hashes, licenses, and approved sandbox components are documented and reproducible offline. +- [ ] Repository-facing docs, installer output, assets, schemas, workflow, five-tool list, two launchers, canonical paths, and all installed skill listings pass consistency tests. +- [ ] Documentation preserves `docs/mcp-integration-design.md` as originating design lineage, retains its supersession banner, and identifies the approved PRD/architecture as normative where they differ. +- [ ] Supported environments have current real fixtures and sandbox proofs; all others fail closed with actionable guidance. +- [ ] Phase implementation/documentation may complete without the `VAL-14` determination, but release remains explicitly blocked until written Anthropic clarification or qualified legal determination exists. +- [ ] Cleanup guidance states `.archflow/` is branch-tracked development-lifecycle evidence removed before PR and v1 has no permanent audit export. + +## Progress + +| Phase | Name | Status | +|-------|------|--------| +| 1 | Contracts, Assets, and Package Scaffold | Not Started | +| 2 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | +| 3 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | +| 4 | Snapshots, Implementation Manifests, and Restore | Not Started | +| 5 | Durable Gates, Waivers, and Manual Decisions | Not Started | +| 6 | Host Identity, Sandbox, and CLI Dispatch | Not Started | +| 7 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | +| 8 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | +| 9 | Installer, Initialization, and Host Registration | Not Started | +| 10 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | +| 11 | Manual and Degraded Recovery Workflow | Not Started | +| 12 | Legacy Upgrade Workflow | Not Started | +| 13 | Reliability and Security Matrices | Not Started | +| 14 | Real-Host E2E and Review-Quality Validation | Not Started | +| 15 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | + +--- +*Created: 2026-07-26* diff --git a/.archflow/tasks/mcp-integration/prd.md b/.archflow/tasks/mcp-integration/prd.md index d2615825..065f3852 100644 --- a/.archflow/tasks/mcp-integration/prd.md +++ b/.archflow/tasks/mcp-integration/prd.md @@ -55,7 +55,7 @@ ArchFlow must make a terminal-driven agent workflow recoverable and independentl | REQ-01 | Repository initialization | A new `archflow-init` skill scaffolds the repository-owned workflow, constitution templates, shared globals, and host registration needed for terminal operation, including `.mcp.json` for Claude Code and `~/.codex/config.toml` for Codex. Initialization is idempotent, preserves unrelated Claude/Codex configuration, and reports unsupported or untrusted host configuration rather than claiming success. | | REQ-02 | Repository layout | Initialization establishes `.archflow/workflow.yaml`, `.archflow/constitution/{README.md,00-process.md,10-architecture.md,20-data.md,30-product.md}`, existing global documents, and per-task `config.yaml`, `state.json`, active `gate.json`/`gate.decision`, canonical PRD/design/phase artifacts, implementation notes, and review/decision evidence. Canonical v1 paths include `design.md`, `phases//design.md`, `phases//impl-notes.md`, `reviews/.{self,counter,triage,adjudication}.md`, optional `reviews/.gate-counter..md`, and retained `decisions//{request,decision}.json`. `` is reversibly encoded as `prd`, `design`, `phase-design-`, or `phase-impl-`, so iterated phases never overwrite one another's evidence. | | REQ-03 | Published phase graph | `.archflow/workflow.yaml` is the source of truth for the shipped ArchFlow phase ordering, dependencies, per-phase pipelines, optionality, iteration, and gate policy. A human or Archforge can determine the next legal action from the graph and task state without hardcoding that graph outside ArchFlow. In v1 the published file is an inspectable contract over a fixed phase/step vocabulary, not a user extension API. | -| REQ-04 | Versioned and pinned execution inputs | Every machine-readable workflow/configuration/state/gate/decision/review format is versioned and strictly validated. At task start, the task records stable task/repository identity, an immutable base commit, and workflow, constitution, and configuration versions or digests. In-flight behavior cannot silently change when repository files change. V1 keeps those inputs pinned for the task; adopting changed workflow or policy requires a new task unless the future REQ-50 migration flow is implemented. | +| REQ-04 | Versioned and pinned execution inputs | Every machine-readable workflow/configuration/state/gate/decision/review format is versioned and strictly validated. At task start, the task records stable task/repository identity, an immutable base commit, and workflow, constitution, and configuration versions or digests. In-flight behavior cannot silently change when repository files change. V1 keeps those inputs pinned for the task; adopting changed workflow or policy requires a new task or the explicit REQ-50 upgrade flow. | | REQ-05 | Workflow validation | Before agent work begins, the shipped ArchFlow graph, recognized phase/step vocabulary, and task configuration are validated. Malformed schemas, altered/unknown structure, duplicate IDs, invalid dependencies or iteration, unsatisfied prerequisites, and unknown models/families fail closed with an actionable error. Supporting arbitrary phases, steps, or plugins is not required. | | REQ-06 | Fixed v1 graph | The shipped workflow exposes the phase behavior below. `on_trigger` review/advancement gates open when a constitution trigger fires, drift is material, adjudication fails or is uncertain, attempts are exhausted, or a task-branch constitution edit is present. This policy does not replace the separate mandatory human authorization before any commit. | @@ -85,7 +85,7 @@ ArchFlow must make a terminal-driven agent workflow recoverable and independentl | ID | Requirement | Description | |----|-------------|-------------| | REQ-15 | Repository constitution | One version-controlled constitution applies to every task in a repository. Rules have stable unique IDs, status, human-readable text, and optional `review_trigger`/`enforced_by` declarations. IDs are appended or deprecated, never renumbered or reused. Adjudication evaluates each trigger against the declared current artifact/diff/evidence and returns matched and uncertain rule IDs with evidence; either outcome opens an `on_trigger` gate. Mechanically enforced rules remain in the constitution, and their evidence must bind to the current subject digest; missing, stale, unknown, or failed evidence is not compliance. | -| REQ-16 | Tasks consume policy | Tasks may cite, comply with, fail, or request a scoped waiver against a rule; they cannot amend the governing constitution. Amendments use normal base-branch code review. Any task-branch diff touching `.archflow/constitution/` opens an unconditional human gate and does not alter pinned adjudication rules. That gate cannot approve or waive the task-local amendment: advancement requires removing/reverting the edit, or completing normal base-branch amendment review and then starting a new task (or using future REQ-50 migration). | +| REQ-16 | Tasks consume policy | Tasks may cite, comply with, fail, or request a scoped waiver against a rule; they cannot amend the governing constitution. Amendments use normal base-branch code review. Any task-branch diff touching `.archflow/constitution/` opens an unconditional human gate and does not alter pinned adjudication rules. That gate cannot approve or waive the task-local amendment: advancement requires removing/reverting the edit, or completing normal base-branch amendment review and then starting a new task (or using the explicit REQ-50 upgrade flow). | | REQ-17 | Immutable policy basis | The governing constitution is resolved from the task's immutable starting commit, not a moving branch name or mutable worktree file. Its digest/version is pinned in task state. Applicable rules are supplied to production as constraints, while adjudication checks the complete pinned policy basis as a backstop. Missing/unresolvable policy or current `enforced_by` evidence cannot be treated as compliance. | | REQ-18 | Scoped waivers | `archflow_waiver` creates a durable, explicit human decision request tied to the exact rule version, task, narrow scope, rationale, subject/evidence digests, and gate identity. Grant or denial is explicit; a grant records provenance and expires at the stated task boundary. A waiver never amends policy or applies to another rule, task, or changed subject implicitly. | | REQ-19 | Independent adjudication results | Adjudication emits separate constitution-compliance and upstream-drift results plus matched/uncertain trigger IDs and supporting evidence. Drift is `aligned`, `incidental`, or `material`: incidental clarifications are recorded and may proceed; material changes that would surprise a reader of the approved document open a gate and normally require amendment/reapproval of the affected upstream artifact. Approved upstream versions remain identifiable even when canonical parent documents are later updated to reflect reality. | @@ -137,11 +137,16 @@ The v1 MCP surface is normative. Every request/result uses a versioned schema an | REQ-40 | Terminal-only completion | A developer can initialize, configure, inspect, run, gate, waive, interrupt, resume, and complete the full workflow using only a supported terminal, Git worktree, Claude Code or Codex, and local files—including documented manual operation when the MCP server remains unavailable. Archforge is not installed or required for any v1 acceptance path. | | REQ-41 | Counter-review prompt at every human gate | Every human review/approval gate presents a self-contained ready-to-run prompt for the other client as an optional additional counter-review, even when the automated counter-review already ran. The user alone decides whether to run it. If run, its digest-bound supplemental result is written to `reviews/.gate-counter..md`, triaged before the gate resolves, and any accepted change re-enters the REQ-13 fixed-point loop. Declining the optional check does not fabricate a review and does not prevent an otherwise valid explicit gate decision. | +#### Legacy task upgrade + +| ID | Requirement | Description | +|----|-------------|-------------| +| REQ-50 | Explicit legacy task upgrade | A new `archflow-upgrade` skill provides a guided migration from a legacy task layout into a new canonical task identity without modifying the legacy task. It imports legacy PRD, architecture, phase designs, and implementation history only as unapproved draft or historical inputs; creates current versioned configuration/state pinned to the current workflow, repository identity, an explicit approved policy-base commit and constitution, and a separately bound import/code baseline; and reruns every review, adjudication, and explicit human approval required for current evidence. Upgrade rejects unresolved task-local constitution edits. Legacy prose, conversational approvals, commits, or artifact presence never become current approval evidence implicitly. Completed legacy implementation may be represented as validated only after an explicit migration audit binds the current code/artifacts and human decision. Migration uses the existing five MCP tools and has a complete manual fallback; it is not a sixth workflow tool. | + ### Should Have (v1+) | ID | Requirement | Description | |----|-------------|-------------| -| REQ-50 | Explicit task migration | Provide a guided, human-approved re-pin/migration flow for tasks that intentionally adopt a newer workflow or constitution, with dependency-aware invalidation of prior evidence. V1 may instead keep tasks pinned and require a new task/run. | | REQ-52 | Durable audit export | If post-PR audit retention becomes a product need, export a compact approval/waiver/evidence summary to a deliberately retained location before `.archflow/` is removed. This is separate from v1 development-lifecycle traceability. | ### Out of Scope @@ -250,6 +255,7 @@ The first six scenarios preserve the authoritative design's terminal definition | VAL-14 | Before release, written Anthropic clarification or a qualified legal determination establishes that the local subscription-authenticated Claude dispatch is permitted. An internal risk acceptance alone does not satisfy this condition; accepting unresolved terms risk requires explicit owner authorization to revise the criterion. API-key/custom-provider fallback requires an explicit PRD scope change. | | VAL-15 | Constitution fixtures cover positive, negative, and uncertain `review_trigger` evaluation plus current, missing, stale, and failed `enforced_by` evidence. Matched/uncertain triggers gate; missing/stale/failed evidence never passes. A task-branch constitution edit cannot advance on an approval-shaped decision and must be reverted/removed or handled through base-branch amendment plus a new/migrated task. | | VAL-16 | A task with at least two implementation phases proves that `phase-design-` and `phase-impl-` review, supplemental gate-counter, retained decision, rerun, and status evidence use reversible non-colliding paths and that later phases never overwrite earlier evidence. It also proves code cannot start until phase design is workflow-approved as defined in REQ-09. | +| VAL-17 | `archflow-upgrade` imports a representative legacy task into a distinct canonical task without changing the source task, labels imported documents/history as unapproved, and refuses to claim any current approval or completed phase until the required current-digest pipeline and explicit migration decisions succeed. Normal and manual upgrade paths produce equivalent conservative milestones, and interruption or rerun never duplicates decisions or overwrites either task. | Archforge implementation must not begin until VAL-01 through VAL-06 pass in a terminal. VAL-02 is the decisive product validation: if independent review does not reliably improve substantive quality, the architecture's central automation premise must be revisited rather than hidden by more mechanics. diff --git a/.archflow/tasks/mcp-integration/reviews/architecture-counter-review.md b/.archflow/tasks/mcp-integration/reviews/architecture-counter-review.md new file mode 100644 index 00000000..41bd9e6e --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/architecture-counter-review.md @@ -0,0 +1,238 @@ +# Counter-Review: MCP Integration Architecture + +> Adversarial review of [architecture.md](../architecture.md) against [prd.md](../prd.md), the current repository, and the installed Claude Code / Codex CLIs. +> +> Reviewer context: fresh read; no access to the drafting conversation or the two prior review rounds. + +## Method and evidence base + +Claims were checked against live artifacts rather than recollection: + +- Every pinned dependency was resolved against the npm registry (`npm view version`). +- `claude --help` / `claude mcp add --help` on **Claude Code 2.1.220**. +- `codex --help` / `codex exec --help` / `codex sandbox --help` / `codex mcp add --help` on **codex-cli 0.145.0**. +- `execa@10.0.0` was unpacked and its option typings read directly. +- Codex's own `read-only` sandbox was exercised against real credential and repository paths (results in Blocker 2). +- Requirement-to-phase coverage was recomputed by hand from the 13 phase requirement lists. + +**Version pins are accurate and should not be re-litigated.** `@modelcontextprotocol/server@2.0.0-beta.5`, `typescript@7.0.2`, `zod@4.4.3`, `ajv@8.20.0`, `yaml@2.9.0`, `execa@10.0.0`, `write-file-atomic@8.0.0`, `proper-lockfile@4.1.2`, `esbuild@0.28.1`, `vitest@4.1.10` all exist and are current latest. Node `24.18.0` is a real release and is the current v24 head. The CLI flags the adapters depend on all exist: Claude `--safe-mode`, `--tools`, `--strict-mcp-config`, `--disable-slash-commands`, `--no-session-persistence`, `--json-schema`; Codex `--ephemeral`, `--ignore-user-config`, `--ignore-rules`, `--sandbox read-only`, `--output-schema`, `--json`, `-C/--cd`. Requirement coverage is genuinely complete: **all of REQ-01–41 and REQ-50 appear in at least one phase's requirement list**, and VAL-01–17 all appear in the coverage table. The prior rounds did that work well. + +What follows is what survived. + +--- + +## Blockers + +### B-1 — The two premises that can invalidate the whole design are proven last + +**Evidence.** The PRD is explicit: "VAL-02 is the decisive product validation: if independent review does not reliably improve substantive quality, the architecture's central automation premise must be revisited rather than hidden by more mechanics" (prd.md, after the VAL table). The architecture agrees — Testing and Release Strategy item 5: "If `VAL-02` does not demonstrate useful independent review, the automation premise is revisited rather than compensated for with more mechanics." + +It then schedules that test in **Phase 12 of 13**, after content-addressed storage, checkpoint chains, gate/waiver lifecycles, the sandbox provider, the five-tool assembly, the installer, eight rewritten skills, the manual-mode workflow, and the legacy upgrade pipeline are all built. The second existential item — provable launcher-versus-model credential confinement (Phase 4) — is likewise gated behind Phases 1–3, and its failure mode is "the environment is unsupported," i.e. the product does not ship there. + +The architecture therefore maximizes sunk cost before its own go/no-go. Every phase dependency is a straight chain (`Depends on: Phases 1–N`), so there is no path where the premise test lands earlier by accident. + +**Why this is a blocker and not a preference.** The PRD's response to VAL-02 failure is "revisit the architecture," not "adjust a threshold." An architecture whose stated failure mode requires discarding twelve phases of work has mis-ordered its risk. + +**Suggested resolution.** Insert a Phase 0 feasibility spike, explicitly throwaway, with no durable-state machinery: hand-driven `claude -p` and `codex exec` calls in both directions over a small seeded-defect corpus, plus the credential-confinement probe from B-2. Gate Phases 1–13 on it. Its success criteria are VAL-02's substance and B-2's proof; its artifacts are a report and a decision, not code. If the spike fails, the loss is days rather than the whole plan. + +### B-2 — Codex cannot be made credential-safe with the mechanisms the architecture names, and there is no contingency + +**Evidence.** The architecture requires the sandbox provider to "prove that model-controlled descendants/tools cannot read or emit subscription tokens, auth files, credential file descriptors, keychain neighbors, or unrelated credentials," and offers three escape hatches: "a proven no-tool invocation or a narrowly scoped credential broker/parent-versus-descendant confinement." + +For the Claude reviewer, a no-tool invocation exists and is named: `--tools ""` ("Use `\"\"` to disable all tools" — `claude --help`, verified on 2.1.220). For the Codex reviewer, **none of the three exists**: + +1. *No-tool invocation.* `codex exec --help` (0.145.0) exposes no flag that disables the shell/exec tool. The architecture's Codex flag list (`--ephemeral`, `--ignore-user-config`, `--ignore-rules`, `--sandbox read-only`, `--output-schema`) contains no such control, and none was found in `codex --help`, `codex exec --help`, `codex features`, or `codex debug`. +2. *Credential broker.* Codex subscription auth is a file (`$CODEX_HOME/auth.json`, present here at 4167 bytes, mode `-rw-------`). There is no documented interface to inject it out-of-band; the only non-file path is `OPENAI_API_KEY`, which REQ-34 forbids. +3. *Parent-versus-descendant confinement.* The named preferred provider (`@anthropic-ai/sandbox-runtime`) uses bubblewrap on Linux. The launcher must be able to read `auth.json` to authenticate, so it must be bind-mounted into the namespace — and the model's shell tool is a descendant **inside that same mount namespace**. A bind-mount sandbox cannot grant a path to a process and deny it to that process's own children. + +Measured directly, from a temp cwd outside the repository, under Codex's own `read-only` sandbox: + +``` +$ codex sandbox -c sandbox_mode='"read-only"' -- sh -c 'wc -c < "$HOME/.codex/auth.json"' +4167 # own subscription credentials: READABLE +$ codex sandbox -c sandbox_mode='"read-only"' -- sh -c 'wc -c < "$HOME/.claude/.credentials.json"' +509 # the OTHER client's credentials: READABLE +$ codex sandbox -c sandbox_mode='"read-only"' -- sh -c 'wc -c < .../mcp-server/CLAUDE.md' +4531 # arbitrary repository file by absolute path: READABLE +$ codex sandbox -c sandbox_mode='"read-only"' -- sh -c 'echo x > .../mcp-server/CANARY.txt' +sh: 1: cannot create ...: Read-only file system # writes: BLOCKED +``` + +This confirms the architecture's own caution that `--sandbox read-only` "is defense-in-depth, not the repository-read boundary" — but it also shows the exposure includes the *other family's* credentials, and that read-only blocks only writes. + +**Consequence.** Under the architecture's fail-closed rule ("If a Codex/host/provider combination cannot prove launcher-versus-model credential separation, it is unsupported"), the Claude-producer → Codex-reviewer direction is likely unsupported on every OS. Same-family fallback is a hard `FAMILY_MISMATCH` by design. So one of the two directions required by REQ-31, VAL-07, and Phase 12's success criteria has no delivery path, and the architecture defines no contingency — Phase 4 simply marks a matrix entry unsupported and Phase 12 still asserts "Both producer directions prove...". + +**Suggested resolution.** Three concrete moves, in order: + +1. **Reconsider `--ignore-rules`.** It is listed among Codex isolation flags, but its documented effect is "Do not load user or project execpolicy `.rules` files" — it *removes* the only user-configurable command-restriction layer. A purpose-built ArchFlow execpolicy that denies every command, supplied via a generated `CODEX_HOME`, is the closest thing to a `--tools ""` equivalent Codex offers. Isolating from the user's rules and shipping ArchFlow's own deny-all rules are different goals; the current flag list achieves the first at the cost of the second. +2. Move this probe into Phase 0 (B-1) so the answer is known before Phases 1–3 are built. +3. Decide and document the contingency now: if Codex-as-reviewer cannot be confined, does v1 ship Codex-producer → Claude-reviewer only (and how do REQ-31/VAL-07/Phase 12 change), or does the release block? Today the architecture's answer is an unstated "unsupported," which silently deletes half the product. + +### B-3 — The `intent_id` / `expected_revision` / request-digest contract is self-contradictory on the paths the design relies on most + +**Evidence.** The mutation sequence fixes three rules: step 4, "A replay succeeds only when current validated state references the committed intent, result, and resulting revision... changed reuse returns `INTENT_MISMATCH`"; step 5, "Compare `expected_revision`; a mismatch returns `STATE_CONFLICT`"; and the Intent receipt row, "Intent ID, canonical request digest, prior/result revision...". The set of fields inside the "canonical request digest" is never defined. + +That omission breaks two flows the architecture explicitly requires: + +*Supplemental-review retry.* `SUPPLEMENTAL_REVIEW_REQUIRED` is described as "retryable non-success" while "the gate remains pending," and "The resumed orchestrator triages it." Triage is a state transition, so it advances the revision. The retried `archflow_gate` call must therefore carry a **new** `expected_revision`. If `expected_revision` is inside the canonical request digest, that retry is "changed reuse" → `INTENT_MISMATCH`, and the pending gate can never be resumed. If it is outside, then step 5's CAS behavior on a replayed intent is undefined — a replay would be validated against a revision the receipt does not bind. + +*Gate supersession.* On an accepted supplemental finding the gate closes as `superseded`, the artifact is rewritten, and the design "creates a new digest/new deterministic gate." Gate IDs derive from "canonical task identity, `intent_id`, and request digest," so a new gate ID follows from either a new digest or a new intent. But if the skill reuses the intent (the natural reading of "the same logical operation"), the changed subject digest makes it `INTENT_MISMATCH`. The architecture never says a fresh `intent_id` is required here. + +The same ambiguity applies to every mutating call that is legitimately retried after an intervening transition — which, given that reconciliation runs "before every request," is the common case, not the edge case. + +**Suggested resolution.** In the Five-Tool MCP API Boundary section, define the canonical request digest as an explicit closed field list; exclude `expected_revision` from it and state that CAS is evaluated independently of intent identity; and state the intent lifecycle rule directly — a retry after `SUPPLEMENTAL_REVIEW_REQUIRED` reuses the intent with a refreshed `expected_revision`, while a superseded gate requires a fresh `intent_id`. Add a Phase 3 success criterion covering retry-after-intervening-transition, since no current criterion exercises it. + +--- + +## Majors + +### M-1 — Declared-input fingerprint scope invalidates unrelated approved work, and pinned config has no amendment path + +**Evidence.** The fingerprint is defined as a "Hash of versioned workflow/config, pinned constitution, artifact/upstream bytes, rubric, phase instance, and explicitly declared inputs." REQ-25 and the architecture agree that "a changed fingerprint creates a new retained result." REQ-30 permits a human or Archforge to write per-task `config.yaml` to "override models/effort by role and phase." + +So editing the adjudicator's effort level changes `config.yaml`, which changes the fingerprint of every step in the task — including the already-approved PRD and design — forcing new authoritative results for documents whose content and inputs did not change. Meanwhile REQ-04 pins the config digest at task start and the architecture makes mismatched policy bases "fail closed," so there is also no legal way to make that edit: the task either rejects it or invalidates itself. + +**Suggested resolution.** Narrow the fingerprint to the inputs a step actually consumes — for a dispatch step, the resolved routing entry for that role/phase rather than the whole file; for a document step, no routing input at all. Separately, define an explicit config-amendment transition (a gate kind) that re-pins the digest and states precisely which retained results it invalidates. + +### M-2 — REQ-01's `.mcp.json` is not delivered by the registration approach, and the alternative leaks a machine path into the user's repository + +**Evidence.** REQ-01 states initialization scaffolds "host registration needed for terminal operation, **including `.mcp.json` for Claude Code** and `~/.codex/config.toml` for Codex." The architecture instead says "Registration prefers official `claude mcp add` and `codex mcp add` commands" and never names a scope. + +Verified: `claude mcp add --help` shows `-s, --scope Configuration scope (local, user, or project) (default: "local")`. The default writes to the user-level store, **not** `.mcp.json`; only `--scope project` produces `.mcp.json`. As written, REQ-01's Claude half is unmet. + +Choosing `--scope project` creates the opposite problem. `.mcp.json` is a tracked repository file that outlives the pre-PR deletion of `.archflow/`, and it must contain the absolute path to the installed `archflow-mcp` launcher — which directly contradicts the architecture's own rule that "Machine-specific executable locations stay in host registration, never portable task state," and would ship one developer's `$HOME` path to everyone who clones the repo. + +**Suggested resolution.** Decide and state the scope. If project scope is required by REQ-01, resolve the path problem explicitly (a launcher on `PATH`, or a documented `${ARCHFLOW_MCP}` indirection) and say whether `.mcp.json` is committed or gitignored. Add a Phase 7 success criterion naming `.mcp.json` — the current criteria say only "Official Claude and Codex registrations use the stable launcher." + +### M-3 — Content digests are defined without reference to Git's text normalization + +**Evidence.** This repository already ships `.gitattributes` containing `* text=auto`. The architecture's entire evidence model rests on digests of file bytes — "artifact/upstream bytes," "before/after digests," "exact canonical diff digest," "byte-identical declared outputs" — and its handoff model is explicitly commit → push → clean pull into a different worktree or clone: "handoff requires an explicit human-approved checkpoint commit and push, a clean pull by the next writer, and identity/revision/conflict checks before mutation." + +The document never states whether a digest is taken over Git **blob** bytes or over **worktree** bytes, and never mentions `text=auto`, `core.autocrlf`, `core.fileMode`, or symlink checkout behavior. Under `text=auto`, worktree bytes and blob bytes differ whenever normalization applies, and differ *between clones* depending on the puller's config. The implementation-output manifest specifically binds "regular/symlink file type, executable mode, and binary-safe bytes" — all three are things Git checkout can legitimately change across machines. The consequence is a handoff that fails digest validation, or worse, a byte-identical "restore" that writes the wrong line endings. + +**Suggested resolution.** State the rule: committed policy inputs (constitution, workflow) digest over Git blob bytes read from the pinned commit; task artifacts and implementation outputs digest over raw worktree bytes with normalization disabled for `.archflow/` (ship `.archflow/** -text` in `.gitattributes`, and treat snapshot payloads as binary). Add checkout-normalization and `core.fileMode` cases to the Phase 2 path/manifest criteria and the Phase 11 matrix — neither currently mentions Git normalization at all. + +### M-4 — REQ-41's supplemental review has no defined producer while the orchestrator is blocked + +**Evidence.** `archflow_gate` "publishes and commits the request before it waits," and the wait ends with `SUPPLEMENTAL_REVIEW_REQUIRED` "If an untriaged supplemental review arrives." But a blocking MCP tool call occupies the orchestrator's turn — the agent that would write `reviews/.gate-counter..md` is precisely the agent that is blocked. The architecture never names who creates that file. + +The gap is not merely bookkeeping. REQ-11 requires structured JSON that "validates before Markdown rendering," and the architecture repeats that "Model JSON must validate before it can become evidence." A human pasting the other client's output into a file does not produce validating JSON, and the architecture never states that `archflow-local validate/render` is the normal-mode path for this (its description of `archflow-local` is framed as the server-unavailable helper). Three further mechanics are undefined: whether `archflow_state` transitions are legal while a gate is pending (triage requires it); how the blocked server *detects* the file's arrival (poll interval? watch? at what cost given "reconciliation runs before every request"); and what happens if the file appears mid-write. + +**Suggested resolution.** Name the actor and the path explicitly — most plausibly: the gate prompt instructs the other client to emit JSON to stdout, the human saves it, and `archflow-local` validates/renders/binds it in normal mode too. State that gate-pending state transitions are legal and enumerate which ones. Define the detection mechanism and its atomicity requirement. Add this end-to-end path to Phase 8's criteria, which currently assert the return code without saying how the file got there. + +### M-5 — The one-writer invariant has no enforcement mechanism, but Phase 11 claims a test for it + +**Evidence.** The architecture is candid that "Locking and revision CAS coordinate only processes sharing the same filesystem. Git is transport and history, not a distributed lock," and then asserts "One active writer/worktree owns a task branch." Phase 11's success criteria promise "independent clones are rejected until a clean checkpoint handoff," and Phase 2's promise "Separate-clone tests reject concurrent mutation." + +No mechanism is described that could reject them. Two clones each hold `state.json` at revision *N*; each takes its own local lock, passes its own CAS against its own copy, and writes revision *N+1* with different content. Nothing in the described design detects the other. REQ-24 — a Must Have — says "Multiple Claude/Codex/Archforge sessions cannot silently overwrite one task's state"; a second clone can, and the divergence surfaces only as a Git merge conflict later. + +Relatedly, the architecture never addresses what a merge conflict in `.archflow/` means. `state.json`, checkpoint files, and intent receipts are content that must not be textually merged, and there is no `merge=` strategy, conflict-detection rule, or repair procedure anywhere in the document. + +**Suggested resolution.** Either (a) add a real mechanism — a writer lease committed into `state.json` (writer identity + acquisition revision) plus a handoff transition that is the only way to change it, with mutation refused when the lease names another writer; or (b) drop the claim, state plainly that cross-clone concurrency is undetectable by design, and replace the two test criteria with Git-merge-conflict *detection and repair* criteria. Either way, specify `.archflow/** merge=binary` (or equivalent) and a documented conflict repair path. + +### M-6 — Manual mode's independence is asserted rather than established, and it roughly doubles the build + +**Evidence.** The architecture states: "'Server unavailable' means this helper remains available." But `archflow-local` is, by the same paragraph, "CLI/library functions from the **same installed bundle**" — same Node runtime, same esbuild output, same schemas, same code. The failure classes where the server is unavailable *and* the helper is not are narrow: broken host MCP registration, a host that disables the server, an MCP transport/protocol fault, or an exhausted tool timeout. Every failure that kills the bundle, the launcher, or Node kills both, which the architecture concedes in the next sentence ("If both server and helper are unavailable, skills fail non-advancing"). + +Against that narrow class, the design commits to: immutable checkpoint chains with predecessor digests, greatest-valid-chain semantics, `manual-checkpoint-import` as a first-class union member with checkpoint-1 initialization constraints, degraded status reconstruction, exact per-tool fallback templates, a manual legacy-upgrade path, and manual matrices in Phases 3, 9, 10, 11, and 12. Phase 9 in effect reimplements the entire workflow a second time as skill instructions. This is the single largest cost item in the architecture and it is justified by an unexamined assumption about independent failure. + +The PRD does require it (REQ-38–REQ-40), so the architecture cannot unilaterally drop it — but it can and should surface the cost and the narrowness so the owner can decide. + +**Suggested resolution.** Add an explicit paragraph enumerating the failure classes manual mode covers and the (larger) set it does not, so "complete manual fallback" is not over-claimed. Then put the trade to the user as a scope question: is full manual *completion* (REQ-39, reaching task completion with the server never recovering) worth roughly a doubling of surface area versus manual *pause-and-repair*? That is an owner decision, not an architectural one, but it should be made before Phase 3 rather than discovered in Phase 9. + +### M-7 — A restore collision is an unresolvable deadlock with no human escape hatch + +**Evidence.** REQ-25 requires that an unchanged fingerprint "restores/reuses the exact previously validated authoritative output bytes"; the architecture makes restore "collision-safe, refuses undeclared changes" and states "ambiguity is non-advancing in both normal and manual modes." + +Take the ordinary case: a developer edits a source file that a completed phase declared as an output, then reruns the phase. The fingerprint is unchanged, so regeneration is forbidden. Restore detects a before-image mismatch, so restore is refused. The task cannot advance and cannot retreat. The gate trigger list — "Trigger/uncertainty, material drift, failed adjudication, attempts exhaustion, waivers, and task-branch constitution edits gate" — does not include restore collision, so the design's own escape valve is unavailable. + +**Suggested resolution.** Add a `restore-collision` gate kind with explicit, enumerated human decisions (accept worktree bytes as a new generation with a recorded rationale; discard worktree bytes and restore; abort). Add it to the gate kinds in Phase 3 and to the dirty-worktree criteria in Phases 2 and 12, which currently test only the clean-restore path. + +### M-8 — Phase 2 is the system, not a phase; Phases 11–12 duplicate proof obligations already owned earlier + +**Evidence.** Phase 2's scope is a single sentence containing: Git/worktree and task identity, path allowlists, six schemas, revision-0→1 adoption, fingerprints, lock/CAS, prepared receipts, immutable snapshots, atomic projections, state-last commitment, implementation bindings, collision-safe restore, and reconciliation — behind seven checkboxes. That is the durable core of the entire product in one phase, and the ArchFlow phase model (`DESIGNED → IN PROGRESS → COMPLETE` with a single design gate and a single commit authorization) has no way to review it incrementally. + +Symmetrically, Phases 11 and 12 restate obligations already claimed as success criteria elsewhere. Phase 2 asserts "Fault injection **before/during/after every** snapshot/projection/state write"; Phase 11 then asserts "Complete fault injection at every durable boundary." Phase 4 asserts a randomized black-box sandbox proof; Phase 11 asserts credential canaries again. When two phases claim the same proof, either can be marked COMPLETE while deferring the hard half to the other — which is exactly the failure the state machine exists to prevent. + +Finally, every phase depends on all its predecessors and nothing produces an end-to-end usable increment until Phase 8 of 13. For a tool the team dogfoods, that is a long time with no feedback. + +**Suggested resolution.** Split Phase 2 along its natural seam (identity + paths + schemas; then lock/CAS + prepared/commit + reconciliation; then snapshots + implementation manifests + restore). Re-frame Phases 11–12 as *matrix expansion* over criteria owned by earlier phases, with each restated criterion naming its owning phase, so the boundary is "Phase 4 proved one configuration; Phase 11 proves the matrix." Consider a thin vertical slice — one document phase, produce → counter-review → gate → approve, no manual mode, no upgrade — landing before Phase 5. + +### M-9 — The snapshot store has no size bound, retention policy, or exclusion rule + +**Evidence.** `results/sha256//payload/` retains "exact output bytes" for every result, snapshots are "immutable after creation," and all of it is "ordinary files checked into Git with the task on its shared branch." The implementation-output manifest binds "binary bytes" of declared source paths with before/after images. + +So for every implementation phase, the task branch gains a second full copy of the changed source files — inside the repository that already stores them, in Git, in a directory whose only cleanup is wholesale deletion before PR. Every rewrite in the fixed-point loop ("Accepted findings across two rewrites") adds another retained generation. Add `attempts/`, `intents/`, `manual/checkpoints/`, and `imports//payload/`, and the growth is unbounded and unmeasured — no size cap, no GC, no exclusion for large or binary files, and no performance criterion anywhere in the document. + +There is a second-order concern: a secret accidentally committed once now exists in at least two Git-tracked locations, and the deletion story ("`.archflow/` is removed before PR") removes it from the tree but not from branch history. + +**Suggested resolution.** Bound it explicitly: for outputs that are already tracked Git content, store the blob OID and digest rather than a byte copy, and reserve payload copies for untracked or generated artifacts; cap payload size with a stated failure mode; define retention for `attempts/` and superseded results. Add a criterion measuring `.archflow/` growth across a representative multi-phase task. + +### M-10 — Two schema systems describe the same shapes with no stated source of truth + +**Evidence.** The stack table assigns Zod 4 to "MCP request/result schemas" and JSON Schema 2020-12 + Ajv strict to "durable schemas," and the directory layout mirrors that split (`contracts/mcp.ts` vs `contracts/schemas/`). But the shapes overlap: `archflow_state.artifact` is simultaneously an MCP request field (Zod, published in `tools/list`) and a durable manifest (`implementation-manifest.ts`, `legacy-import-manifest.ts`, JSON Schema). Review results, checkpoints, and decisions are likewise both wire payloads and files. + +No generation direction is specified and no conformance test is required. The divergence failure is fail-*open*: the server advertises and accepts a request the Zod schema permits, then fails to persist it because the Ajv schema rejects it — after the caller has been told the shape is valid. Phase 1's criteria cover round-tripping and rejection within each system, never agreement between them. + +**Suggested resolution.** Pick one source of truth — Zod as authoring surface, JSON Schema generated from it (`z.toJSONSchema`) for durable files and for the published tool schemas — or keep both and add a Phase 1 success criterion that proves, for every shared type, that the two schemas accept and reject identical corpora. + +### M-11 — `archflow-init` cannot set the timeout it is required to configure + +**Evidence.** REQ-36 says "Supported-host installation documents/configures a human-decision tool-timeout window." The architecture's mechanism is "the Claude server entry's persistent per-server `timeout` when supported; otherwise it requires and validates an inherited `MCP_TOOL_TIMEOUT` environment variable." + +Verified: `claude mcp add --help` on 2.1.220 exposes no timeout option at all (`--callback-port`, `--client-id`, `--client-secret`, `-e/--env`, `-H/--header`, `-s/--scope`, `-t/--transport`). Claude Code's tool timeout is an environment variable of the **host** process. `archflow-init` runs as a child; it can validate that the variable is present but cannot durably set it — the "otherwise" branch therefore reduces to "fail initialization unless the user has already exported it in their shell profile," which the architecture never says. + +The consequence path is also undescribed: if the variable is absent or short, a gate call hits the host tool timeout, the gate stays pending (correct), the agent receives an error, and must re-call — a retry loop that is the *designed* behavior but appears nowhere as such, and is not exercised by any success criterion. + +**Suggested resolution.** State the shell-profile guidance init emits, state that init fails closed when the variable is absent, and describe timeout-then-resume as supported normal-mode behavior. Add a Phase 3 or Phase 6 criterion that a gate survives a real host tool timeout and resumes on the next call at the *default* timeout, since that is what most users will run with. (I did not verify whether a `timeout` key is honored inside a Claude MCP server entry — the "when supported" hedge is prudent, but the fallback branch needs the detail above regardless.) + +--- + +## Minors + +### m-1 — Coverage table and phase requirement lists disagree + +The coverage table lists Phase 11 under "Host identity and routing (REQ-29, REQ-30, REQ-31)" and Phase 6 under "Degraded/manual terminal completion (REQ-38, REQ-39, REQ-40)," but Phase 11's requirement list omits REQ-30 and Phase 6's omits REQ-38/39/40. The table is presented as the audit artifact ("All v1 requirements... appear above"), so the two directions should be reconciled or the table generated from the phase lists. + +### m-2 — The Node `24.18.0` floor has no stated cause + +`24.18.0` is real and is the current v24 head — i.e. the floor is "whatever was newest at drafting time." It excludes 24.11–24.17 users for no documented reason and will be stale before release. A minimum should cite the feature or security fix that requires it, or be expressed as a policy ("current v24 LTS at release, minimum X because Y"). + +### m-3 — `@types/node` is pinned older than the runtime floor + +`@types/node@24.13.3` against a Node `24.18.0` runtime (latest published is `26.1.1`). Harmless, but the pairing rule should be stated so a future upgrade does not read it as an error. + +### m-4 — `killDescendants` is documented as best-effort, and no phase requires a kill-group primitive + +From `execa@10.0.0`'s own typings: "When the subprocess is terminated by Execa, also terminate all of its descendant processes... **This is best-effort: descendant processes that create their own process group or session are not terminated.**" The stack table presents it as the mechanism and defers the residue to "sandbox/cgroup/job-object tests." But the `SandboxProvider` contract requires only that it "terminate the process tree on abort, timeout, server shutdown, or output overflow" — it does not require a primitive that can actually guarantee that (PID namespace, cgroup, or job object). Move the requirement into the provider contract rather than the test list. + +### m-5 — `--ignore-rules` is listed as isolation but reduces hardening + +Its documented effect is "Do not load user or project execpolicy `.rules` files." That is context isolation, not confinement — it removes the only user-configurable command-restriction layer for a process that (per B-2) retains a shell. Label it accordingly, and see B-2 for the inverted use. + +### m-6 — The cited source design still contradicts this architecture + +`docs/mcp-integration-design.md` is named by REQ-27 as "the source design" and still shows the superseded contract: `archflow_state (phase, step, status, artifact?)`, `reviews/.counter.md`, `archflow_waiver (rule_id, rationale)` without scope, and a degraded table that directly contradicts the new manual model — "`archflow_state`: Skip. Status is reconstructable from artifacts on disk" and "`archflow_adjudicate`: Run as an in-session subagent." Phase 13 defers reconciliation to the last phase, leaving two live and contradictory design documents for the whole build. Mark it superseded in Phase 1 instead. + +### m-7 — Waiver sequencing under the one-active-gate rule is unstated + +"At most one active gate per task," and `archflow_waiver` "Uses the same durable gate mechanism." The natural flow — an adjudication gate opens, and the human's answer is "request a waiver" — cannot proceed without first resolving or cancelling the open gate. Define the ordering, or state that a waiver may nest. + +### m-8 — Reconciliation cost is unbounded and unmeasured + +"Reconciliation runs before every request, replay, status report, or manual interpretation and compares state references, projection digests, prepared receipts, and snapshot manifests." For a mature task with many phases and retained results (see M-9), that is O(all evidence) on every call, including cheap `archflow_state` step boundaries which the source design describes as "Cheap, called at every step boundary." No performance criterion exists anywhere in the document. + +### m-9 — ArchFlow's own tasks and installer are not in the migration plan + +This repository's in-flight tasks — including this one — use the layout the new canonical layout supersedes (`architecture.md`, `reviews/-counter-review.md`, flat `phases/phase-N-*.md`). `archflow-upgrade` arrives in Phase 10 and Phase 13 updates the docs, but nothing states whether ArchFlow dogfoods its own upgrade path on itself, or how existing users' in-flight tasks are handled at release. Separately, `install.sh`'s `STALE_SKILLS` mechanism is the only place skill removal is handled and Phase 7 does not mention it, though two skills are being added and six rewritten. + +--- + +## Summary + +The requirement coverage, version pins, CLI flag knowledge, and failure-semantics discipline in this document are unusually good, and the prior rounds clearly closed the easy gaps. What remains is concentrated in three places: **risk ordering** (B-1 — the premises that can kill the design are tested last), **one verified infeasibility** (B-2 — Codex reviewer credential confinement, with no contingency for losing half the product), and **an under-specified core protocol** (B-3 — intent/revision/digest composition, which is cheap to fix now and expensive after Phase 2). The majors are mostly places where a strong invariant is asserted without a mechanism (M-5), a scope without a bound (M-1, M-9), or a requirement without a delivery path (M-2, M-4, M-11). + +Nothing here suggests the design is wrong in its fundamentals. B-1 and B-2 together do suggest the *plan* should not proceed to Phase 1 in its current order. + +--- +*Counter-review: 2026-07-26 · Reviewer: Claude Opus 5 (independent read) · Subject: architecture.md as of this commit* diff --git a/.archflow/tasks/mcp-integration/reviews/review-findings.md b/.archflow/tasks/mcp-integration/reviews/review-findings.md new file mode 100644 index 00000000..290d285b --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/review-findings.md @@ -0,0 +1,49 @@ +# Architecture Counter-Review Adjudication + +> Subject: [architecture.md](../architecture.md) +> Source review: [architecture-counter-review.md](./architecture-counter-review.md) +> Adjudicated: 2026-07-26 + +Dispositions were verified against the current PRD and architecture, repository configuration and legacy documentation, `claude` 2.1.220 help, and `codex-cli` 0.145.0 help. `FIX` means the finding is valid and has a decision-free correction. `REJECT` means the stated defect is disproved by an existing requirement or contract. `ASK` means the concern is valid but resolving it changes product behavior, scope, or phase strategy. + +The `File:line` column preserves locations in the adjudicated pre-remediation revision so each row remains traceable to the source review; accepted changes moved some corresponding text in the current architecture. + +| ID | File:line | Claim | Disposition | One-line reason | Phase 2 outcome | +|----|-----------|-------|-------------|-----------------|-----------------| +| B-1 | `prd.md:259`; `architecture.md:425,570-587` | The decisive review-quality premise and reviewer-isolation feasibility are proven after most implementation work. | ASK | The ordering is exactly as claimed, but adding a throwaway Phase 0 and renumbering dependencies is a phase-strategy decision for the owner. | Integrated: no Phase 0 was added; review-quality validation and sandbox proof remain in their planned implementation phases. | +| B-2 | `architecture.md:274-288,425-443,582-586` | Codex has no demonstrated way to keep subscription credentials from its model-controlled shell, so one required producer direction may be infeasible. | ASK | Local `codex exec --help` confirms no no-tools flag, and the architecture has no product contingency if confinement proof fails; narrowing directionality or blocking release changes approved scope. | Integrated: the supported first-party CLI may use its own subscription authentication; ArchFlow still isolates repository/global context, other-family credentials, and unrelated secrets and never handles credential values. | +| B-3 | `architecture.md:61-68,250-268` | Canonical request-digest fields and intent lifecycle are undefined for supplemental-review retry and gate supersession. | FIX | The request digest omits a closed field definition, so refreshed CAS revisions and new-subject intents can currently be classified inconsistently. | Completed: closed digest fields, independent CAS, same-intent retry, and fresh-intent supersession are defined and tested. | +| M-1 | `architecture.md:66,220-221,316`; `prd.md:58,112` | Hashing all pinned `config.yaml` makes unrelated routing changes invalidate all evidence, while no legal config-amendment path exists. | ASK | The architecture binds the whole config rather than each step's resolved entry, but allowing in-task re-pinning and choosing invalidation scope is a behavior/policy decision. | Integrated: `config.yaml` is immutable and pinned for the task; any edit returns `PINNED_CONFIG_MISMATCH` and requires a new task or explicit upgrade rather than in-task re-pinning. | +| M-2 | `prd.md:55`; `architecture.md:292,481-497` | The registration plan does not guarantee the required project `.mcp.json`, and default Claude scope is local. | FIX | `claude mcp add --help` confirms local is the default; project scope plus a PATH-resolved `archflow-mcp` command can meet REQ-01 without embedding a home-directory path. | Completed: project scope, shared `.mcp.json`, PATH launcher, and preservation criteria are explicit. | +| M-3 | `.gitattributes:2`; `architecture.md:66,73,223,262` | Digest and restore semantics ignore Git text normalization, modes, and cross-clone checkout behavior. | FIX | The repository uses `* text=auto`, while the design never distinguishes Git blob identity from raw worktree bytes. | Completed: blob/tree-mode authority, `.archflow/** -text merge=binary`, and checkout-normalization matrices are defined. | +| M-4 | `architecture.md:268,294-296,507-514`; `prd.md:138` | The supplemental gate-review producer, atomic ingestion path, legal pending-gate transitions, and detection mechanism are undefined. | FIX | Deterministic gate IDs solve naming, but the document does not say how a second terminal validates/publishes evidence or how the blocked call observes it safely. | Completed: second-terminal JSON ingestion, atomic projection, observation, and pending-gate transitions are specified. | +| M-5 | `architecture.md:73,310,331,358,560-566` | Independent-clone rejection is claimed although local locks/CAS cannot observe another clone, and merge-conflict semantics are absent. | FIX | The architecture itself limits coordination to one filesystem; cross-clone mutation must be an unsupported operational precondition with divergence detection/repair, not a tested rejection guarantee. | Completed: unsupported pre-divergence concurrency, binary merge policy, divergence detection, blocking, and repair replace the false rejection claim. | +| M-6 | `architecture.md:294-296,319-320`; `prd.md:135-137` | Manual mode is not an independent fallback and its surface may not justify its cost. | REJECT | The architecture explicitly scopes fallback to MCP/tool/server failure while the same bundle remains available and fails for repair if both paths are gone; full server-absent completion is mandated by REQ-38–REQ-40. | No change. | +| M-7 | `architecture.md:238,262,309,357`; `prd.md:102` | A changed phase-owned file can cause an unchanged-input restore collision with no human escape path. | FIX | Collision is currently only non-advancing and no gate kind permits an explicit restore, adopt-as-new-input, or abort decision. | Completed: `restore-collision` offers discard-and-restore, changed-input new generation, or abort, with no silent overwrite. | +| M-8 | `architecture.md:388-406,552-587` | Phase 2 is oversized, later matrix phases duplicate earlier proof ownership, and usable vertical feedback arrives too late. | ASK | Phase 2 contains several independently testable storage kernels and the proof boundaries overlap, but splitting/reordering the approved phase plan is an owner-level planning tradeoff. | Integrated: the former Phase 2 is now three independently testable phases; later matrix phases expand rather than defer each implementing phase's proof. | +| M-9 | `architecture.md:199-211,223,309`; `prd.md:102` | Git-tracked immutable snapshots have no size bound, retention rule, deduplication policy, or secret-amplification control. | ASK | The unbounded duplicate-byte design is real, but payload caps, Git-blob reuse, and retention/GC behavior materially trade determinism, repository size, and recoverability. | Integrated: tracked output reuses Git object identity; copied payloads are capped at 25 MiB/result and 250 MiB/task, with secret scanning, authoritative retention, and explicit recorded pruning. | +| M-10 | `architecture.md:11-12,94-95,379-386` | Zod and JSON Schema/Ajv describe overlapping wire/durable types without a declared source of truth or conformance proof. | FIX | Shared shapes can diverge even though each schema validates independently; Phase 1 needs an explicit authority/generation rule or equivalent-corpus test. | Completed: durable JSON Schema is normative and a shared corpus proves Ajv/Zod agreement for overlapping shapes. | +| M-11 | `architecture.md:288,292,343,489-495`; `prd.md:133-134` | Init cannot itself persist the Claude host environment timeout and timeout-then-resume is undocumented and untested. | FIX | Claude's installed `mcp add` has no timeout option; the design must emit shell-profile guidance, fail closed when required configuration is absent, and test durable resume after a real host timeout. | Completed: exact profile/restart guidance, inheritance verification, fail-closed behavior, and timeout-resume testing are specified. | +| m-1 | `architecture.md:361,365,468,558` | Coverage-table phase references disagree with the corresponding phase requirement lists. | FIX | Phase 11 omits REQ-30 and Phase 6 omits REQ-38–REQ-40 despite the coverage table assigning them there. | Completed: Phase 6 includes REQ-38–REQ-40 and Phase 11 includes REQ-30. | +| m-2 | `architecture.md:8` | Node 24.18.0 is presented as a fixed floor without stating the functional/security policy behind it. | FIX | The floor should distinguish the dependency-driven minimum from the policy of testing the current Node 24 LTS security patch at release. | Completed: 24.15.0 is the functional floor and release/CI use the current Node 24 LTS security patch. | +| m-3 | `architecture.md:8` | `@types/node` 24.13.3 appears older than the Node 24.18.0 runtime without an explained pairing rule. | FIX | Node type patch versions do not track runtime patch versions; the document should say it pins the current compatible Node-24 typings independently. | Completed: the Node-24 typings line is explicitly independent of runtime patch numbering. | +| m-4 | `architecture.md:15,276-284,425-443` | Execa descendant termination is best-effort, while the sandbox provider lacks an explicit containment primitive requirement. | FIX | Tests alone do not guarantee daemon/session escape termination; the provider contract must require an OS containment primitive and prove it. | Completed: provider-owned PID namespace/cgroup/job-object-equivalent containment and escape tests are required. | +| m-5 | `architecture.md:288,425-443` | Codex `--ignore-rules` is described among isolation controls although it removes execpolicy rather than confining commands. | FIX | Installed help confirms the flag exists, but it is context isolation, not a security boundary; any ArchFlow deny-all policy remains a feasibility-spike candidate. | Completed: the flag is labeled context isolation only and deny-all execpolicy remains unproven. | +| m-6 | `docs/mcp-integration-design.md:198-257`; `architecture.md:338,589-605` | The old source design contradicts the new contract until the final documentation phase. | FIX | The referenced document still specifies old tool/fallback behavior, so Phase 1 must mark it superseded before implementation relies on the new architecture. | Completed: marking the source design superseded is Phase 1's first required change and criterion. | +| m-7 | `architecture.md:226-228,238,253-254,317` | Waiver sequencing is undefined when the same task already has its one active gate. | FIX | A sequential transition from the current gate into a waiver request is needed; nesting would violate the one-active-gate invariant. | Completed: `waiver-requested` closes/archives before the sole waiver gate opens; nested gates are forbidden. | +| m-8 | `architecture.md:71,329-336` | Full reconciliation before every call is unbounded as retained history grows. | FIX | Normal requests should validate only current state references and the active/prepared intent, reserving full-history scans for explicit audit/repair with performance criteria. | Completed: ordinary reconciliation is head-bounded; full history is limited to explicit audit/repair/import with performance criteria. | +| m-9 | `architecture.md:298-300,489-497,534-550`; `install.sh:29-56` | The release plan does not explicitly migrate ArchFlow's own legacy tasks or replace the installer's hard-coded stale-skill cleanup. | FIX | The current repository is itself a legacy-layout fixture, and `STALE_SKILLS` cannot safely manage future owned-file additions/removals without an ownership manifest. | Completed: Phase 7 adds an owned install manifest and Phase 10 dogfoods the repository's legacy layout with in-flight-user guidance. | + +## Resolved owner decisions + +The five `ASK` findings were resolved by the owner and integrated into the architecture: + +1. **B-1:** no Phase 0; keep premise validation in the implementation plan. +2. **B-2:** trust the supported first-party CLI's own subscription-auth access; ArchFlow still denies repository/global context and unrelated secrets and never forwards or logs credentials. +3. **M-1:** pin all routing configuration immutably per task; edits fail closed and require a new/upgraded task. +4. **M-8:** split the current persistence phase into three independently testable phases and keep proof ownership in the implementing phase. +5. **M-9:** reuse tracked Git blobs; apply 25 MiB/result and 250 MiB/task copied-payload caps with explicit failure and recorded pruning rules. + +## Design lineage follow-up + +The owner confirmed that [docs/mcp-integration-design.md](../../../../docs/mcp-integration-design.md) is the originating design. The architecture now cites it explicitly as design lineage while stating that the approved PRD and architecture are normative where the documents differ; the source design remains preserved rather than treated as unrelated obsolete material. From 67dea85ac2a759a45f36ec743d6acede4a5d868c Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 01:19:10 -0500 Subject: [PATCH 004/124] MCP Integration: Design Phase 1 --- .../tasks/mcp-integration/architecture.md | 171 ++++++++++-------- ...1-contracts-assets-and-package-scaffold.md | 102 +++++++++++ .archflow/tasks/mcp-integration/prd.md | 2 +- .../reviews/phase-1-design-counter-review.md | 108 +++++++++++ 4 files changed, 308 insertions(+), 75 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-1-design-counter-review.md diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index de610bb7..bea54d75 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -16,9 +16,9 @@ | Persistence | Repository files, core SHA-256, `write-file-atomic` `8.0.0`, `proper-lockfile` `4.1.2` behind an internal adapter | Keeps authority inspectable and branch-shareable. The lock package's maintenance risk is contained behind replaceable interfaces and crash/race fixtures. | | Child processes | `execa` `10.0.0` with `shell: false`, `killDescendants: true`, `cancelSignal`, timeout, `maxBuffer`, and forced-termination escalation inside provider-owned OS containment | Execa supplies process control, but each provider must also use a PID namespace/cgroup, Windows job object, or proven equivalent that terminates descendants even after they create new process groups or sessions. | | Packaging | esbuild `0.28.1`, exact npm lockfile, single host-neutral server/local-helper bundle | `install.sh` installs both `archflow-mcp` and `archflow-local` without an unpinned startup download. | -| Verification | Vitest `4.1.10`, fixture CLIs, fault injection, protocol fixtures, and black-box host/sandbox suites | Critical persistence, host, process, protocol, and manual-mode behavior is exercised at its real boundaries. | +| Verification | Vitest `4.1.10` with direct dev pin Vite `7.3.6`, fixture CLIs, fault injection, protocol fixtures, and black-box host/sandbox suites | The exact Vite 7 pin constrains Vitest to its supported permissive line; the lock must prove no `lightningcss` or other copyleft dependency before acceptance. Critical persistence, host, process, protocol, and manual-mode behavior is exercised at its real boundaries. | -All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. The listed direct libraries are permissively licensed. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 6 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. +All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. Direct pins are permissively licensed, and the complete lock must independently prove a permissive-only graph. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 7 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. ## System Architecture @@ -301,7 +301,7 @@ Each dispatch creates a fresh, non-resumed child in a temporary directory outsid - use an OS containment primitive capable of terminating every descendant on abort, timeout, server shutdown, or output overflow even if a descendant creates a new process group/session—PID namespace/cgroup, Windows job object, or a proven equivalent, not Execa best effort alone; and - return a capability proof tied to the OS, provider, CLI/runtime versions, exact allowed-read manifest, and randomized denied canaries. -At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 6 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. +At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 7 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. The Claude adapter uses fresh `--safe-mode`, `--tools ""`, a strict empty MCP config, disabled slash commands, no persistence, and schema-constrained output. It preflights subscription authentication and managed hooks/policy. Host setup configures and validates the Claude server entry's persistent per-server `timeout` when supported; otherwise a newly started host must inherit `MCP_TOOL_TIMEOUT` as described below. Cancellation or host timeout always leaves a durable resumable gate; timeout-then-resume is supported normal behavior. The Codex adapter uses exact fixture-proven ephemeral, ignore-user-config, `--ignore-rules`, read-only, and output-schema behavior while preserving first-party auth; `--ignore-rules` is inherited-context isolation only, never security confinement. It configures/tests `project_doc_max_bytes=0` or a proven equivalent and rejects managed instruction injection. An ArchFlow deny-all Codex execpolicy remains an early feasibility candidate, and the design does not claim it works. Both adapters still require OS sandbox proof, are version-gated from real fixtures, and spawn with `shell: false`, scrubbed environment, no provider keys/routing or unrelated secrets, `killDescendants`, cancellation, timeout/output bounds, forced escalation, and provider-owned descendant containment. Stable failures cover missing CLI, auth, unsupported host/model, family mismatch, rate limit, timeout, cancellation, overflow, invalid output, nonzero exit, and I/O failure. @@ -371,22 +371,22 @@ Release is blocked unless all applicable tests pass and the supported matrix is | Coverage area | Requirements | Validation | Primary phases | Proof boundary | |---------------|--------------|------------|----------------|----------------| -| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 9, 10, 15 | Strict assets/schemas, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | -| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 8, 10, 14, 15 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | -| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 1, 2, 3, 4, 7, 10, 11, 13, 14 | Structured JSON/projections, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | -| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 7, 12, 13, 14 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | -| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 5, 7, 12, 14 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | -| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 2, 3, 4, 5, 11, 13, 14 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | -| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 2, 3, 4, 5, 11, 12, 13 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | -| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 2, 3, 4, 6, 12, 13, 14 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | -| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 1, 8, 9, 13, 14 | v2 fixtures expose five stdio tools; the separate offline helper is not an MCP tool. | -| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 6, 8, 13, 14 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | -| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 6, 7, 8, 13, 14 | Hashed envelopes, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | -| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 6, 9, 13, 14, 15 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | -| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 5, 8, 11, 13, 14 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | -| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 8, 9, 11, 12, 14 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | -| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 5, 10, 11, 14 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | -| Legacy migration | REQ-50 | VAL-17 | 2, 3, 4, 5, 12, 13, 14 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | +| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 10, 11, 16 | Strict assets/schemas, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | +| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 9, 11, 15, 16 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | +| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 2, 3, 4, 5, 8, 11, 12, 14, 15 | Structured JSON/projections, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | +| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 2, 8, 13, 14, 15 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | +| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 2, 6, 8, 13, 15 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | +| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 3, 4, 5, 6, 12, 14, 15 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | +| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 3, 4, 5, 6, 12, 13, 14 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | +| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 3, 4, 5, 7, 13, 14, 15 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | +| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 2, 9, 10, 14, 15 | v2 fixtures expose five stdio tools; the separate offline helper is not an MCP tool. | +| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 7, 9, 14, 15 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | +| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 2, 7, 8, 9, 14, 15 | Hashed envelopes, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | +| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 7, 10, 14, 15, 16 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | +| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 2, 6, 9, 12, 14, 15 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | +| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 9, 10, 12, 13, 15 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | +| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 2, 6, 11, 12, 15 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | +| Legacy migration | REQ-50 | VAL-17 | 3, 4, 5, 6, 13, 14, 15 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release validations `VAL-01` through `VAL-17`, appear above. `REQ-52` remains explicitly outside the v1 architecture. @@ -394,47 +394,68 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali ### Phase 1: Contracts, Assets, and Package Scaffold -**Goal**: Establish a buildable server package and the versioned contracts all later phases share. +**Goal**: Establish the buildable package foundation and foundational repository contracts. -**Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-11, REQ-12, REQ-15, REQ-17, REQ-27, REQ-28, REQ-33 +**Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-15, REQ-17 -**Scope**: As the first Phase 1 action before server implementation, add a visible lineage/supersession banner to `docs/mcp-integration-design.md` identifying it as the originating detailed design and the approved PRD/architecture as normative where they differ; Phase 15 later updates the surrounding documentation while preserving that history. Then add Node/TypeScript/MCP v2 beta package scaffolding and exact lockfile; isolate the beta SDK adapter; define the fixed workflow vocabulary, shipped workflow and constitution assets, normative strict durable JSON Schemas, derived/wrapped Zod MCP contracts, a shared validator-agreement corpus, canonical phase-instance encoding, canonical Markdown renderers, error envelope, license notices, build, lint/typecheck, and protocol/contract fixture harness. This phase does not implement persistent transitions or dispatch. +**Scope**: First add the visible lineage/supersession banner to `docs/mcp-integration-design.md`, preserving it as originating design and linking the normative PRD/architecture; Phase 16 later updates surrounding documentation. Establish a private ESM package, exact lockfile, scripts, Node matrix CI, dependency notices/policy, and only Phase-1 direct dependencies: Zod, Ajv, `ajv-formats`, YAML, TypeScript, Node typings, esbuild, Vitest, and direct Vite `7.3.6`. Implement recursive plain-JSON preflight, strict non-mutating Ajv2020, explicit Zod agreement infrastructure, branded canonical phase-instance codec, safe YAML parsing, fixed workflow/config/rubric/constitution rule contracts, shipped workflow/constitution assets, and append-only constitution evolution fixtures. This phase has no review/triage/adjudication contracts or renderers, error registry, tool schemas, MCP SDK/server, or tracked offline bundle. **Success Criteria**: -- [ ] The project installs from the exact lockfile, typechecks, tests, and builds at the functional Node floor `24.15.0`; CI/release also passes on the current Node 24 LTS security patch (`24.18.0` at design time), independently of the Node-24 typings patch. -- [ ] MCP initialization and `tools/list` fixtures expose protocol `2025-11-25`, exactly the five named tools, and versioned schemas; stdout contains no non-protocol output. -- [ ] Valid workflow/review/state samples round-trip through strict schemas and canonical rendering, while unknown graph vocabulary, invalid verdict/count combinations, and non-reversible phase IDs fail with stable errors. For every overlapping persisted/MCP shape, the same valid/invalid corpus proves Ajv and Zod accept and reject identically. -- [ ] The dependency-upgrade procedure demonstrates that changing the MCP beta pin requires fixture, lockfile, and license review. +- [ ] Clean exact-lock install, strict typecheck, foundational tests, and temporary esbuild output pass on Node `24.15.0` and `24.18.0`; TypeScript is CLI-only with explicit `rootDir` and Node types. +- [ ] The exact lock includes direct `vite@7.3.6`, excludes `lightningcss`, and passes complete permissive-only license/NOTICE proof; copyleft, unreviewed licenses, ranged direct pins, and later-phase dependencies fail policy. +- [ ] Recursive plain-JSON/Ajv/Zod agreement fixtures reject mutation, non-plain prototypes, dangerous keys, unknown structure, bad formats, and YAML ambiguity with stable located validation results. +- [ ] Exact workflow/config/rubric/constitution assets and schemas round-trip; graph mutations, authoritative family config, invalid rubric modes, duplicate/invalid rules, and illegal append/deprecate/version evolution fail. +- [ ] Branded positive-safe phase numbers and phase-instance IDs are minted only by codecs/validators; compile-time assertions and runtime aliases reject non-canonical values, while Explore remains disposable pre-task vocabulary rather than a phase instance. - [ ] Phase 1's first change adds the source design's visible lineage/supersession banner, links the approved PRD/architecture, preserves its originating-design status, and precedes all server implementation. -### Phase 2: Repository Identity, Paths, Schemas, and Canonical Digests +### Phase 2: Review Evidence and Inert MCP Boundary -**Goal**: Establish the repository/task identity, path safety, durable schemas, immutable task configuration, and byte-stable digest contracts used by every mutation. +**Goal**: Freeze trust-bearing review, gate, error, and tool interfaces and prove the inert stdio MCP boundary. **Depends on**: Phase 1 +**Requirements**: REQ-04, REQ-05, REQ-10, REQ-11, REQ-12, REQ-15, REQ-17, REQ-27, REQ-28, REQ-33 + +**Scope**: Define complete raw/derived/agent-declared/server-attested/degraded review evidence, composite finding references and triage, digest-bound adjudication and canonical renderers, the full v1 error registry, discriminated gate contexts and the exhaustive decision map, and exactly five versioned request/result schemas with `archflow_state.artifact` disabled. Pin required request `task_id` and immutable connection repository-candidate context. Add the exact MCP SDK pin and currency fixtures; isolate beta.5's low-level `Server` advanced seam with owned `tools/list`/`tools/call` validation and `projectCallToolResult`. Track `dist/archflow-mcp.js` and `dist/manifest.json` and prove clean-checkout offline startup. This phase implements no persistence, dispatch, durable gate lifecycle, or durable state/artifact schema. + +**Success Criteria**: + +- [ ] Closed schemas/interfaces enumerate every field and trust source for raw finding/review, derived review, `AgentDeclaredReview`, `ServerAttestedReview`, `DegradedReview`, `ReviewEvidence`, `FindingRef`, `TriageDisposition`, `ValidatedTriage`, `AdapterObservation`, and `AuthorityLink`; verdict/count/binding fields are recomputed, untrusted, or internally minted as specified. +- [ ] Server attestation carries adapter/CLI/family/model/effort plus invocation/result/input/output linkage, is minted only behind an opaque internal capability, and persisted acceptance verifies matching receipt/state/result references; forged, schema-shaped, wrong-invocation, and wrong-digest provenance fails. +- [ ] Composite `(review_evidence_digest, finding_id)` identity dispositions cover every applicable finding exactly once, and digest-bound `ValidatedAdjudication` retains per-rule compliance findings, all `enforced_by` states, separate drift, triggers, and canonical byte-stable rendering. +- [ ] One exhaustive gate-kind decision authority drives JSON Schema/Zod/runtime contracts. `validateProjectResult(definition, parsedInput, result)` correlates every `GateSuccess.decision` with the parsed gate kind, maps illegal or corrupt results to validated `INTERNAL_ERROR`, and negative result fixtures cover every kind; waiver and supplemental choices remain separate. +- [ ] Real protocol `2025-11-25` fixtures expose exactly `archflow_state`, `archflow_counter_review`, `archflow_adjudicate`, `archflow_gate`, and `archflow_waiver`, with closed request/result schemas and no sixth tool. Known-tool parse failures return stable `CONTRACT_*` results with zero business calls; unknown/disabled names use the protocol error path; stdout is protocol-only and no listener opens. +- [ ] The complete v1 error registry fixes owner/retryability/safe diagnostics. Every project result is validated against its definition and parsed request before `CallToolResult` mapping; corrupt errors/successes and cross-tool result substitution become `INTERNAL_ERROR`. +- [ ] Exact SDK currency/upgrade fixtures couple pin, lock, low-level adapter, wire schemas, bundle, and license evidence. Tracked `dist/manifest.json` binds bundle SHA-256, Node target, package/lock, source entry, and schema/assets digests; a clean checkout starts the bundle without `node_modules`, npm, cache, network, or startup build. + +### Phase 3: Repository Identity, Paths, Schemas, and Canonical Digests + +**Goal**: Establish the repository/task identity, path safety, durable schemas, immutable task configuration, and byte-stable digest contracts used by every mutation. + +**Depends on**: Phases 1 and 2 + **Requirements**: REQ-04, REQ-05, REQ-11, REQ-13, REQ-14, REQ-21, REQ-26, REQ-33, REQ-39, REQ-50 -**Scope**: Implement Git/worktree and task identity; `.archflow/** -text merge=binary`; path allowlists; task-initialization, document, implementation-output, legacy-import, manual-checkpoint, checkpoint-import, maintenance-record, and snapshot-accounting schemas; exact whole-file `config.yaml` pinning; canonical Git blob/tree-mode and request/input digests; divergence/conflict detection; and secret-scan result contracts. This phase does not implement state mutation or payload restore. +**Scope**: Implement Git/worktree and task identity; `.archflow/** -text merge=binary`; path allowlists; the durable `state.json` schema and task-initialization, document, implementation-output, legacy-import, manual-checkpoint, checkpoint-import, maintenance-record, and snapshot-accounting schemas; exact whole-file `config.yaml` pinning; canonical Git blob/tree-mode and request/input digests; divergence/conflict detection; and secret-scan result contracts. This phase does not implement state mutation or payload restore. **Success Criteria**: - [ ] Task initialization schemas bind the exact whole-file config digest. Any byte change is detected as `PINNED_CONFIG_MISMATCH` with expected/observed digests and no config content; no re-pin/amendment schema exists. - [ ] Traversal, absolute paths, symlink escape, cross-task access, and identity mismatch fail before reads, while linked worktrees, relocation, spaces, and Unicode pass. - [ ] Committed inputs and tracked outputs have identical canonical Git blob/tree identities across LF/CRLF worktrees, `core.autocrlf`, `core.fileMode`, executable-bit support, and symlink-capable/incapable checkouts; unsupported materialization fails closed. -- [ ] Valid initialization/document/implementation/import/checkpoint/maintenance samples round-trip through normative schemas; predecessor gaps, unknown fields, digest mismatches, invalid phase IDs, and contradictory accounting fail with stable errors. +- [ ] Valid state/initialization/document/implementation/import/checkpoint/maintenance samples round-trip through normative schemas; predecessor gaps, unknown fields, digest mismatches, invalid phase IDs, and contradictory accounting fail with stable errors. - [ ] Startup and pull/handoff detection identifies divergent histories and `.archflow/**` conflicts as non-authoritative without claiming it can detect independent-clone concurrency before divergence. -### Phase 3: Transaction Kernel, Intent/CAS, and Crash Recovery +### Phase 4: Transaction Kernel, Intent/CAS, and Crash Recovery **Goal**: Commit one task's transitions exactly once under races, crashes, retries, config drift, and bounded reconciliation. -**Depends on**: Phase 2 +**Depends on**: Phase 3 **Requirements**: REQ-04, REQ-08, REQ-13, REQ-14, REQ-21, REQ-22, REQ-23, REQ-24, REQ-26, REQ-39, REQ-50 -**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 4. +**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 5. **Success Criteria**: @@ -445,15 +466,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Mature-task step boundaries and status reconcile only current state projections, the relevant active/prepared intent, and active gate/checkpoint head; only explicit repair/import/audit walks history. - [ ] Divergent/conflicted clones remain non-authoritative until preserve-both-heads repair selects/replays one successor chain and records a clean one-writer handoff. -### Phase 4: Snapshots, Implementation Manifests, and Restore +### Phase 5: Snapshots, Implementation Manifests, and Restore **Goal**: Retain and restore deterministic declared outputs within explicit storage, retention, collision, and secret-safety bounds. -**Depends on**: Phase 3 +**Depends on**: Phase 4 **Requirements**: REQ-08, REQ-11, REQ-13, REQ-21, REQ-22, REQ-23, REQ-25, REQ-26, REQ-33, REQ-39, REQ-50 -**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 5 connects collision decisions to the gate service. +**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 6 connects collision decisions to the gate service. **Success Criteria**: @@ -464,11 +485,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Secret fixtures in any candidate Git-tracked snapshot/checkpoint projection fail before projection with safe remediation warning that later `.archflow/` deletion cannot erase branch history; clean binary/text fixtures pass without logging secret values. - [ ] Snapshot/projection/restore fault injection preserves prior/next authority or exact repair, and the three `restore-collision` outcomes are representable without silent overwrite. -### Phase 5: Durable Gates, Waivers, and Manual Decisions +### Phase 6: Durable Gates, Waivers, and Manual Decisions **Goal**: Persist every human authority boundary independently of a live MCP request. -**Depends on**: Phase 4 +**Depends on**: Phase 5 **Requirements**: REQ-09, REQ-13, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -484,11 +505,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] `waiver-requested` is non-advancing and archives the current gate before the sole waiver gate opens; grant resumes only the recorded rule/scope, denial remains non-advancing, and no nested gate exists. `restore-collision` exposes only discard-and-restore, adopt-as-new-generation with changed inputs/fingerprint and rationale, or abort. - [ ] A real Claude host timeout leaves one pending gate, and a later invocation resumes and resolves that gate exactly once; timeout-then-resume is normal supported behavior. -### Phase 6: Host Identity, Sandbox, and CLI Dispatch +### Phase 7: Host Identity, Sandbox, and CLI Dispatch **Goal**: Prove fresh opposite-family reviewer processes receive only declared envelopes and are safe to dispatch on every claimed environment. -**Depends on**: Phases 1–5 +**Depends on**: Phases 1–6 **Requirements**: REQ-26, REQ-29, REQ-30, REQ-31, REQ-32, REQ-34, REQ-35 @@ -505,11 +526,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Any external sandbox dependency and license is presented for explicit acceptance before adoption; copyleft is never silently bundled. - [ ] The Anthropic subscription-authenticated dispatch path remains release-disabled until written clarification or a qualified legal determination satisfies `VAL-14`; implementation or fixture success is not legal approval. -### Phase 7: Constitution Adjudication, Drift, and Review Fixed Point +### Phase 8: Constitution Adjudication, Drift, and Review Fixed Point **Goal**: Turn validated reviewer output and pinned policy/upstream inputs into current-digest advancement evidence. -**Depends on**: Phases 1–6 +**Depends on**: Phases 1–7 **Requirements**: REQ-10, REQ-11, REQ-12, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-32, REQ-33 @@ -522,15 +543,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Positive, negative, and uncertain triggers plus current/missing/stale/failed mechanical evidence behave fail-closed against the approved policy-base constitution. - [ ] Aligned and incidental drift are recorded correctly; material drift gates and an accepted change reopens the affected upstream approval/evidence chain. -### Phase 8: Five-Tool MCP Assembly and Offline Local CLI +### Phase 9: Five-Tool MCP Assembly and Offline Local CLI **Goal**: Assemble persistence, dispatch, adjudication, and decisions behind the complete and only MCP workflow surface. -**Depends on**: Phases 1–7 +**Depends on**: Phases 1–8 **Requirements**: REQ-07, REQ-08, REQ-11, REQ-13, REQ-21, REQ-23, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40 -**Scope**: Wire exactly five handlers through the v2 adapter and implement `archflow-local` for validate, hash, render, snapshot/restore, human-approved maintenance with immutable records, atomic decisions, degraded status, reconcile/import, upgrade staging, and immutable checkpoint creation/chain validation. Connect mutation/replay, dispatch, evidence, supplemental interruption, cancellation, protocol-only stdout, and public errors. Init and upgrade remain outside the tool list. +**Scope**: Wire exactly five handlers through the v2 adapter and implement `archflow-local` for validate, hash, render, snapshot/restore, human-approved maintenance with immutable records, atomic decisions, degraded status, reconcile/import, upgrade staging, and immutable checkpoint creation/chain validation. Connect mutation/replay, dispatch, evidence, supplemental interruption, cancellation, protocol-only stdout, and public errors. Rebuild the Phase 2 tracked bundle and `dist/manifest.json` for the full server/helper assembly. Init and upgrade remain outside the tool list. **Success Criteria**: @@ -540,16 +561,17 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] The bundled server emits only MCP traffic on stdout and opens no network listener. - [ ] The offline helper performs its named local operations without MCP, shares schemas/renderers with the server, and is absent from `tools/list`. - [ ] `archflow-local checkpoint` atomically extends only a valid reconciled chain, and server adoption imports only its greatest valid checkpoint via the closed union tag. +- [ ] The updated tracked manifest binds the complete server/helper bundle to current package/lock/source/schema/assets digests and passes clean-checkout offline startup before installer work. -### Phase 9: Installer, Initialization, and Host Registration +### Phase 10: Installer, Initialization, and Host Registration **Goal**: Install the offline bundle and initialize supported repositories repeatedly without damaging host or project configuration. -**Depends on**: Phases 1, 6, and 8 +**Depends on**: Phases 1, 7, and 9 **Requirements**: REQ-01, REQ-02, REQ-28, REQ-29, REQ-34, REQ-37, REQ-40 -**Scope**: Extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. +**Scope**: Verify the Phase 9 tracked bundle/manifest, then extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. **Success Criteria**: @@ -561,11 +583,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Initialized state is Git-trackable/shareable, contains no machine-specific executable path in portable task state, and works after repository relocation and in linked/space/Unicode worktrees. - [ ] `archflow-init` creates no task state and no commit. Fresh task creation refuses to start until workflow/constitution assets resolve from an explicitly approved immutable commit and then stages the normal initialization manifest. -### Phase 10: Normal-Mode Thin Phase Skills and Truthful Status +### Phase 11: Normal-Mode Thin Phase Skills and Truthful Status **Goal**: Drive the normal MCP workflow from host-neutral phase skills and report only reconciled durable truth. -**Depends on**: Phases 1–9 +**Depends on**: Phases 1–10 **Requirements**: REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-13, REQ-14, REQ-20, REQ-41 @@ -579,11 +601,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] The server sees only complete supplemental projections through filesystem notification plus bounded polling fallback. The gate-pending transition table admits only supplemental ingestion, triage, explicit decline/decision, cancellation, or supersession; `SUPPLEMENTAL_REVIEW_REQUIRED` rejection resumes the gate and accepted change supersedes it and re-enters the fixed point. - [ ] Status verifies the immutable whole-config digest before recommending work; `PINNED_CONFIG_MISMATCH` reports no config content and recommends only a distinct new task or explicit upgrade for intentional routing/model/effort changes. -### Phase 11: Manual and Degraded Recovery Workflow +### Phase 12: Manual and Degraded Recovery Workflow **Goal**: Complete and recover the workflow conservatively when individual MCP tools or the server are unavailable. -**Depends on**: Phases 1–10 +**Depends on**: Phases 1–11 **Requirements**: REQ-08, REQ-09, REQ-11, REQ-12, REQ-13, REQ-14, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41 @@ -597,11 +619,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Supplemental-review arrival, rejection/resume, accepted-change supersession, explicit decline, cancellation, and restart behave identically to normal-mode milestones. - [ ] Manual operation never auto-commits/pushes and documents clean human-approved checkpoint handoff between writers. -### Phase 12: Legacy Upgrade Workflow +### Phase 13: Legacy Upgrade Workflow **Goal**: Migrate selected legacy material into a distinct canonical task without changing or implicitly approving the source. -**Depends on**: Phases 2–5, 7, 8, 10, and 11 +**Depends on**: Phases 3–6, 8, 9, 11, and 12 **Requirements**: REQ-02, REQ-04, REQ-09, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -616,11 +638,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Pure manual upgrade begins with a validating legacy-initialization checkpoint and later server recovery adopts its chain without changing the source or replaying decisions. - [ ] The repository's current legacy task layout upgrades through the same fixture path, and release guidance tells users with in-flight tasks how to finish in legacy tooling or checkpoint/handoff into a distinct upgraded task without silent in-place conversion. -### Phase 13: Reliability and Security Matrices +### Phase 14: Reliability and Security Matrices **Goal**: Prove persistence, race, path, process, and isolation invariants under adversarial failures. -**Depends on**: Phases 1–12 +**Depends on**: Phases 1–13 **Requirements**: REQ-04, REQ-05, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-50 @@ -636,11 +658,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Binary/mode/rename/delete restore, manual recovery, and legacy staging remain collision-safe under fault injection; tracked canonical blob/tree identities remain stable across attributes, LF/CRLF and `core.autocrlf`, `core.fileMode`, executable-bit, and symlink checkout cases. - [ ] Boundary and over-limit payload matrices prove 25 MiB/result and 250 MiB/task enforcement, no truncation/hidden authority, authoritative/evidence retention, maintenance reachability records, and pre-projection secret rejection under crashes and retries. -### Phase 14: Real-Host E2E and Review-Quality Validation +### Phase 15: Real-Host E2E and Review-Quality Validation **Goal**: Validate useful independent review and complete normal, manual, and migration journeys in both producer directions. -**Depends on**: Phases 1–13 +**Depends on**: Phases 1–14 **Requirements**: REQ-01, REQ-02, REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -657,11 +679,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] A real task reaches the snapshot boundaries, receives `SNAPSHOT_LIMIT` above either cap without partial authority, retains all current/evidence chains, records a safe maintenance prune, and rejects a secret-bearing checkpoint before Git projection. - [ ] The approved corpus thresholds demonstrate substantive defect detection and acceptable false blockers; failure of `VAL-02` reopens the automation premise. -### Phase 15: Release Packaging, Support Matrix, and Documentation Consistency +### Phase 16: Release Packaging, Support Matrix, and Documentation Consistency **Goal**: Produce a coherent beta release candidate and an explicit report of any remaining external release blockers. -**Depends on**: Phases 1–14 +**Depends on**: Phases 1–15 **Requirements**: REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -681,20 +703,21 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali | Phase | Name | Status | |-------|------|--------| | 1 | Contracts, Assets, and Package Scaffold | Not Started | -| 2 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | -| 3 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | -| 4 | Snapshots, Implementation Manifests, and Restore | Not Started | -| 5 | Durable Gates, Waivers, and Manual Decisions | Not Started | -| 6 | Host Identity, Sandbox, and CLI Dispatch | Not Started | -| 7 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | -| 8 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | -| 9 | Installer, Initialization, and Host Registration | Not Started | -| 10 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | -| 11 | Manual and Degraded Recovery Workflow | Not Started | -| 12 | Legacy Upgrade Workflow | Not Started | -| 13 | Reliability and Security Matrices | Not Started | -| 14 | Real-Host E2E and Review-Quality Validation | Not Started | -| 15 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | +| 2 | Review Evidence and Inert MCP Boundary | Not Started | +| 3 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | +| 4 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | +| 5 | Snapshots, Implementation Manifests, and Restore | Not Started | +| 6 | Durable Gates, Waivers, and Manual Decisions | Not Started | +| 7 | Host Identity, Sandbox, and CLI Dispatch | Not Started | +| 8 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | +| 9 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | +| 10 | Installer, Initialization, and Host Registration | Not Started | +| 11 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | +| 12 | Manual and Degraded Recovery Workflow | Not Started | +| 13 | Legacy Upgrade Workflow | Not Started | +| 14 | Reliability and Security Matrices | Not Started | +| 15 | Real-Host E2E and Review-Quality Validation | Not Started | +| 16 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | --- *Created: 2026-07-26* diff --git a/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold.md b/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold.md new file mode 100644 index 00000000..1e9ad305 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold.md @@ -0,0 +1,102 @@ +# Phase 1: Contracts, Assets, and Package Scaffold + +**Status**: DESIGNED +**Task**: mcp-integration +**Goal**: Establish the buildable package foundation and foundational repository contracts. +**Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-15, REQ-17 + +## Context + +This repository currently contains portable skills rather than a Node package. The first implementation edit adds a visible lineage/supersession banner to `docs/mcp-integration-design.md`: its originating heading/body remain intact, and resolving links identify the approved PRD and architecture as normative where they differ. The implementation log records that ordering; Phase 16 later updates surrounding release documentation. + +The owner-approved architecture split keeps Phase 1 to package and foundational repository contracts. Review/triage/adjudication evidence, canonical review renderers, the error registry, gate/tool schemas, MCP SDK/server, and tracked offline bundle move to Phase 2. Durable `state.json`, detailed artifact/import/checkpoint/maintenance/snapshot schemas, and repository/Git/path/digest semantics belong to Phase 3. Explore remains fixed workflow vocabulary but is disposable pre-task work: it has no durable phase instance, review evidence, or state record. + +## What We're Building + +We will create a private ESM package with an exact npm lockfile, CLI-only TypeScript 7 checks, temporary esbuild verification output, Vitest/Vite tests, dependency notices/policy, and CI on exact Node `24.15.0` and `24.18.0`. Phase 1's only direct pins are `zod@4.4.3`, `ajv@8.20.0`, `ajv-formats@3.0.1`, `yaml@2.9.0`, `typescript@7.0.2`, `@types/node@24.13.3`, `esbuild@0.28.1`, `vitest@4.1.10`, and direct dev pin `vite@7.3.6`. The Vite pin constrains Vitest to its supported Vite 7 line; acceptance requires lock-wide proof that `lightningcss` and every copyleft or unreviewed dependency are absent. A live implementation-time currency review rechecks every pin and license before package work. + +Foundational validation uses normative JSON Schema 2020-12, strict non-mutating Ajv2020 with `ajv-formats`, and explicit Zod mirrors only where useful to later boundaries. A recursive plain-JSON preflight rejects non-JSON values, cycles, non-plain prototypes, and dangerous own keys before Ajv. One safe YAML 1.2 parser feeds the exact fixed workflow, model/effort-only task config, structured artifact/implementation rubrics, and deterministic constitution frontmatter. Constitution evolution compares the prior pinned rule registry to the candidate and keeps IDs append-only with positive per-rule versions. + +## Files + +| Action | File | Purpose | +|--------|------|---------| +| Modify first | `docs/mcp-integration-design.md` | Add the lineage/supersession banner while preserving the originating body. | +| Create | `package.json`, `package-lock.json`, `.gitignore` | Define the private exact-pinned package and ignore only temporary build/test output, never future tracked `dist/`. | +| Create | `tsconfig.json`, `vitest.config.ts`, `.github/workflows/ci.yml` | Pin CLI-only TypeScript settings, Vitest/Vite configuration, and both exact Node versions. | +| Create | `THIRD_PARTY_NOTICES.md`, `docs/dependency-upgrades.md`, `scripts/check-{dependency-policy,notices}.mjs` | Enforce the direct allowlist, currency/upgrade review, lock-wide permissive licenses, and complete notices. | +| Create | `src/contracts/{index,versions,plain-json,validators,phase-instance,vocabulary,yaml,workflow,config,rubric,constitution}.ts` | Export validation infrastructure, branded codecs, fixed vocabulary, YAML parsing, and foundational repository contracts. | +| Create | `src/contracts/schemas/v1/{primitives,phase-instance,workflow,config,rubric,constitution-rule}.schema.json` | Provide independently inspectable foundational JSON Schema 2020-12 contracts. | +| Create | `assets/workflow.yaml`, `assets/constitution/{README,00-process,10-architecture,20-data,30-product}.md` | Publish the exact v1 graph and versioned frontmatter-plus-prose policy templates. | +| Create | `test/unit/{plain-json,phase-instance,yaml,workflow-config,rubric,constitution}.test.ts`, `test/contracts/foundational-schema-agreement.test.ts`, `test/fixtures/foundation/**` | Verify foundational schemas, assets, evolution, codecs, parser safety, and agreement. | +| Generate and ignore | temporary build/coverage output | Prove the contract barrel bundles under Node 24 without creating a tracked release artifact or startup command. | + +Phase 1 creates no `src/main.ts`, `src/mcp/`, review/evidence schemas, renderers, error/gate/tool contracts, MCP fixtures, or `dist/`. It does not modify `install.sh`, `skills/`, `README.md`, `CLAUDE.md`, `docs/archflow-process.md`, `.gitattributes`, or the user-owned `AGENTS.md`. + +## Contract Interfaces + +```ts +export const SCHEMA_IDS = { + primitives: "urn:archflow:schema:v1:primitives", + phaseInstance: "urn:archflow:schema:v1:phase-instance", + workflow: "urn:archflow:schema:v1:workflow", + config: "urn:archflow:schema:v1:config", + rubric: "urn:archflow:schema:v1:rubric", + constitutionRule: "urn:archflow:schema:v1:constitution-rule" +} as const; + +declare const positiveSafePhaseBrand: unique symbol; +declare const phaseInstanceIdBrand: unique symbol; +export type PositiveSafePhaseNumber = number & { readonly [positiveSafePhaseBrand]: true }; +export type PhaseInstanceId = string & { readonly [phaseInstanceIdBrand]: true }; +export type PhaseInstance = + | { readonly kind: "prd" } + | { readonly kind: "design" } + | { readonly kind: "phase-design"; readonly phase: PositiveSafePhaseNumber } + | { readonly kind: "phase-impl"; readonly phase: PositiveSafePhaseNumber }; +export function parsePositiveSafePhaseNumber(value: unknown): PositiveSafePhaseNumber; +export function encodePhaseInstance(value: PhaseInstance): PhaseInstanceId; +export function decodePhaseInstance(value: unknown): PhaseInstance; + +export const PHASE_IDS = ["explore", "prd", "design", "phase-design", "phase-impl"] as const; +export const PIPELINE_STEPS = ["produce", "self_review", "counter_review", "triage", "adjudicate"] as const; +export const GATE_POLICIES = ["never", "always", "on_trigger"] as const; +export const ITERATION_POLICIES = ["per_phase"] as const; + +export interface RubricV1 { readonly schema_version: "1"; readonly kind: "artifact" | "implementation"; readonly mode: "self_review" | "adversarial"; readonly criteria: readonly { readonly id: string; readonly text: string; readonly blocking: boolean }[] } +export interface ConstitutionRuleV1 { readonly id: string; readonly version: number; readonly status: "active" | "deprecated"; readonly text: string; readonly review_trigger?: string; readonly enforced_by?: readonly string[] } +export type ConstitutionRegistry = ReadonlyMap; +export function parseSingleYamlDocument(source: string, label: string): unknown; +export function validateConstitutionEvolution(previous: ConstitutionRegistry, candidate: readonly ConstitutionRuleV1[]): ConstitutionRegistry; +``` + +Boundary parsers accept `unknown`; only validated codecs mint phase brands. A phase number is a positive safe canonical base-10 integer without signs, leading zeros, decimals, exponents, separators, path syntax, percent escapes, or Unicode digit aliases. Explore is validated in the graph but cannot enter `PhaseInstance`. Config may select role/phase/model/effort only; canonical model family is later derived from trusted adapter metadata. Constitution candidates retain every prior ID, cannot reactivate deprecated rules, and require a version increase for any permitted content/status change. + +## Work Breakdown + +1. **Record design lineage**: Add and verify the banner before package files, preserve all source-design body bytes below it, resolve both normative links, and record the sequence in the implementation log. +2. **Establish package, license, and CI policy**: Recheck pin currency/licenses, create the private exact package/lock and TypeScript/esbuild/Vitest/Vite configuration, enforce the nine-package direct allowlist and complete permissive-only lock notices, and run exact Node floor/current-patch CI. +3. **Build validation and canonical syntax foundations**: Implement recursive plain-JSON validation, strict non-mutating Ajv2020 plus formats, explicit Zod agreement helpers, safe single-document YAML parsing, schema IDs, fixed vocabulary, and the opaque phase codec with compile-time/runtime proofs. +4. **Publish foundational repository contracts and assets**: Author and validate the exact workflow, model/effort config, artifact/implementation rubric, constitution frontmatter/templates, cross-file uniqueness, and append-only versioned constitution evolution against the prior pinned snapshot. +5. **Close foundational verification**: Run clean install, typecheck, temporary bundle, Node matrix, schema/agreement/mutation corpora, YAML/location cases, phase aliases, asset goldens, dependency allowlist, and full lock license/NOTICE checks; confirm all Phase-2/3 surfaces remain absent. + +## Success Criteria + +- [ ] The source design receives only a resolving lineage/supersession banner above an otherwise byte-preserved originating body, and the implementation log records that it was first. +- [ ] Clean exact-lock install, `tsc --noEmit`, foundational tests, and temporary Node-24 ESM bundle pass on exact Node `24.15.0` and `24.18.0`; the current Node `24.11.1` shell is not acceptance evidence. +- [ ] All nine direct pins are exact and current at implementation time. Direct `vite@7.3.6` constrains Vitest's graph; the lock excludes `lightningcss`, copyleft, missing/unreviewed licenses, later-phase dependencies, and stale notices. +- [ ] Plain-JSON preflight and strict non-mutating Ajv/Zod agreement reject non-plain/inherited objects, cycles/non-JSON values, dangerous keys, unknown properties, invalid formats, and contradictory validator acceptance. +- [ ] Workflow/config share the safe one-document YAML path. Exact graph topology, role/phase/model/effort config, rubric kind/mode, constitution frontmatter, cross-file rule uniqueness, and append-only rule evolution pass; malformed/unknown/duplicate/reused/reactivated/unversioned cases fail with located diagnostics. +- [ ] Only codecs/validators mint positive-safe phase numbers and canonical phase IDs; compile-time assertions and runtime aliases reject invalid forms, and Explore remains graph-only pre-task vocabulary. +- [ ] No review/triage/adjudication schema or renderer, error/gate/tool contract, MCP dependency/server/fixture, tracked bundle, durable state/artifact schema, persistence, dispatch, or installer work enters Phase 1. + +## Verification Steps + +1. Compare the source-design body below its banner byte-for-byte with the prior version and resolve the PRD/architecture links. +2. Record live official currency/license evidence for all nine direct pins. From the exact lock, assert direct `vite@7.3.6`, no `lightningcss`, no copyleft, complete license/NOTICE files, no ranges, and no unapproved dependency. +3. On exact Node `v24.15.0` and `v24.18.0`, independently run `npm ci`, `npm run typecheck`, `npm test`, `npm run test:contracts`, `npm run check:dependencies`, `npm run check:notices`, and the temporary build; ensure temporary output is ignored and no `dist/` artifact is created. +4. Run plain-JSON/Ajv/Zod/YAML corpora for prototypes, inherited values, dangerous keys, cycles, non-finite/unsupported values, formats, unknown keys, duplicate/multiple YAML documents, aliases/tags, and Unicode source locations. +5. Run graph/config/rubric/constitution fixtures and old-to-new constitution evolution cases for append, versioned edit/deprecate, deletion, renumber/reuse, reactivation, and missing/non-incremented versions. Run compile-time brand assertions and runtime phase aliases, then use scoped status/diff checks to prove every Phase-2/3 and excluded surface remains untouched. + +--- +*Designed: 2026-07-26* diff --git a/.archflow/tasks/mcp-integration/prd.md b/.archflow/tasks/mcp-integration/prd.md index 065f3852..b11729a5 100644 --- a/.archflow/tasks/mcp-integration/prd.md +++ b/.archflow/tasks/mcp-integration/prd.md @@ -72,7 +72,7 @@ ArchFlow must make a terminal-driven agent workflow recoverable and independentl | ID | Requirement | Description | |----|-------------|-------------| | REQ-07 | Skills as phase marshallers | Phase skills express phase-specific artifact production and rubrics but delegate durable state, model routing, counter-review dispatch, adjudication, and blocking gates to the MCP contracts. No skill branches on Claude Code versus Codex or asks a model to self-identify its host. | -| REQ-08 | Persisted step boundaries | In normal MCP operation, each pipeline step calls `archflow_state` to record a validated `running`/entry state before work and a validated outcome on exit. Every step writes its declared artifact or decision record; information required to resume, review, or advance is never held only in conversation. When the state tool/server is unavailable, REQ-38–REQ-40 define the complete artifact-based manual contract. | +| REQ-08 | Persisted step boundaries | In normal MCP operation, each task pipeline step calls `archflow_state` to record a validated `running`/entry state before work and a validated outcome on exit. Optional Explore is disposable pre-task work that documents architecture context, so it is exempt from durable workflow state and produces no task phase instance or review/state evidence. Every durable task step writes its declared artifact or decision record; information required to resume, review, or advance is never held only in conversation. When the state tool/server is unavailable, REQ-38–REQ-40 define the complete artifact-based manual contract. | | REQ-09 | Phase-specific production | Explore produces disposable context without review or gate. PRD and design run the complete pipeline and always require explicit human approval. Phase design checks drift against the approved `design.md` and becomes workflow-approved/`DESIGNED` only after the current-digest pipeline succeeds with no trigger gate, or after every opened gate is explicitly resolved. Code cannot begin from an incomplete, failed, or pending-gate phase design. Phase implementation checks drift against both the approved phase design and task design, preserves the `no document → DESIGNED → IN PROGRESS → COMPLETE` lifecycle, updates parent PRD/design when implementation changes reality, writes durable implementation notes/logs, and proposes task-independent conventions outside `.archflow/`. Regardless of `on_trigger` review-gate outcome, the skill stops before commit and obtains a distinct explicit human commit authorization bound to the final implementation diff and current artifact digests; phase completion/commit cannot precede that decision. | | REQ-10 | Phase-specific rubrics | PRD, design, and phase-design rubrics evaluate completeness, consistency, assumptions, requirement testability, and fitness to the brief. Implementation rubrics evaluate simplicity, duplication, design conformance, dead code, error handling, and whether abstractions are justified. Counter-review uses the declared rubric adversarially; it does not optimize for raw finding count. | | REQ-11 | Structured review artifacts | Self-review, counter-review, triage, and adjudication outputs conform to versioned schemas, canonical Markdown rendering, and the non-colliding `` paths in REQ-02. Headers identify at least the task/phase instance, step, subject/input digests, verdict, blocking count, trigger/rule IDs, assurance source, model/effort when known, and execution identity. Server-dispatched counter-review/adjudication provenance is server-attested. In-session self-review model/effort metadata is agent-declared or `unknown`, never presented as server-attested; `archflow_state` still binds its input/result digests. Findings have stable IDs, severity, evidence, and suggested resolution; triage dispositions each applicable finding exactly once. | diff --git a/.archflow/tasks/mcp-integration/reviews/phase-1-design-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-1-design-counter-review.md new file mode 100644 index 00000000..ead56bf2 --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-1-design-counter-review.md @@ -0,0 +1,108 @@ +# Phase 1 Design Counter-Review + +> Subject: `phases/phase-1-contracts-assets-and-package-scaffold.md` +> Reviewed against: `architecture.md`, `prd.md`, the current repository at `cfc3ecadaeb4e0b5e17f434565b7e6d9c9fa30b8`, and live official dependency/API sources on 2026-07-27. `.archflow/context/` is absent. + +## Findings + +### 1. Major — The exact Vitest graph introduces a copyleft dependency without the required human decision + +The design says all direct and transitive licenses are acceptable and makes `vitest@4.1.10` part of the exact Phase 1 graph. A clean resolution currently produces `vitest@4.1.10 -> vite@8.1.5 -> lightningcss@1.33.0` (plus its platform binding), and Lightning CSS is MPL-2.0. The architecture's dependency-review policy says copyleft of any strength must be flagged for the user to decide, never silently adopted. This is therefore not an implementation-time notices detail: the phase design currently presupposes an approval that has not occurred. + +Official evidence: [Vitest 4.1.10 manifest](https://github.com/vitest-dev/vitest/blob/v4.1.10/packages/vitest/package.json), [Vite 8.1.5 manifest](https://github.com/vitejs/vite/blob/v8.1.5/packages/vite/package.json), and [Lightning CSS 1.33.0 license](https://github.com/parcel-bundler/lightningcss/blob/v1.33.0/LICENSE). + +**Suggested resolution:** Before approving Phase 1, either obtain and record explicit human acceptance of MPL-2.0 and pin the required notice/source-compliance checks, or choose an exact test dependency graph that remains within the already accepted permissive-license policy. Remove the unconditional claim that all transitive licenses are acceptable until that decision is made. + +### 2. Major — Triage identity can collapse unrelated findings from different reviews + +`deriveTriage(reviews, dispositions)` is specified to cover every “distinct finding ID” across a set of review evidence. Finding IDs are model-authored and only promised to be stable; two independent reviews can both emit a local ID such as `F-1` for different defects. Treating the bare ID as the key either collapses two applicable findings into one disposition or makes valid evidence ambiguous, contrary to REQ-11's requirement to disposition each applicable finding exactly once. + +**Suggested resolution:** Freeze a composite finding identity such as `(review evidence digest, finding_id)`, deterministically namespace IDs at evidence ingestion, or explicitly reject cross-review collisions. Pin the choice in `TriageDisposition`/`ValidatedTriage` and add a corpus case with two evidence items that use the same local ID for different findings. + +### 3. Major — `GateContextV1` admits decision sets forbidden by the PRD and architecture + +The proposed contract makes `kind: GateKind` and `allowed_decisions: GateDecision[]` independent. A schema-valid `constitution-edit` context can therefore advertise `approve`, although REQ-16/REQ-20 explicitly forbid an approval-shaped resolution, and a `restore-collision` context can advertise generic decisions instead of the architecture's exact three choices. Phase 5 cannot safely repair this after Phase 1 freezes and advertises the foundational contract. + +**Suggested resolution:** Replace the independent fields with a discriminated union or a single centralized exhaustive kind-to-legal-decisions map used by both JSON Schema and Zod. Enforce non-empty, duplicate-free, exact decision sets and add positive/negative fixtures for every gate kind. + +### 4. Major — The adjudication contract omits constitution-compliance evidence required by REQ-15 and REQ-19 + +`ConstitutionResult` contains only a verdict plus matched and uncertain rule-ID arrays. `DriftResult` and `Trigger` carry evidence, but a constitution failure—especially missing, stale, unknown, or failed `enforced_by` evidence—need not correspond to a trigger and has nowhere to retain its supporting evidence. The PRD requires separate constitution/drift results with supporting evidence, and later canonical rendering cannot reconstruct evidence that the frozen result type discarded. + +**Suggested resolution:** Add digest-bound per-rule compliance evidence/findings to `ConstitutionResult` (or a clearly linked adjudication evidence collection), including the state of `enforced_by` evidence. Define the currently omitted `ValidatedAdjudication` interface and add fail/uncertain/missing/stale mechanical-evidence fixtures. + +### 5. Major — Known-tool validation failures contradict the parent stable-error contract + +The phase deliberately maps bad versions, unknown fields, disabled `artifact`, and malformed nested inputs to an SDK-generated `isError: true` result with no `structuredContent`. However, the PRD's normative MCP boundary and the architecture say failures expose a stable code, retryability, and safe diagnostic, while `tools/list` advertises a closed `ProjectResult` result schema. The SDK behavior is real and current, but this phase design is silently creating an exception to the parent contract rather than reconciling it. + +**Suggested resolution:** Either amend the PRD/architecture explicitly so pre-handler known-tool argument failures are protocol/SDK errors outside the project envelope, including the observable stable contract clients may rely on, or add an adapter boundary that maps those failures into the declared `CONTRACT_*` project envelope without invoking business handlers. Keep unknown tool names on the separate JSON-RPC path and fixture-test the chosen distinction. + +### 6. Major — Explore is in the fixed workflow but cannot be represented at the state boundary + +The design includes `explore` in `PHASE_IDS` and the published graph, while `PhaseInstance`, `PhaseInstanceId`, and therefore `StateInput` omit it. REQ-06 defines Explore's `produce` pipeline and REQ-08 says every pipeline step records entry and exit through `archflow_state`; REQ-02, conversely, lists only PRD/design/iterated design and implementation evidence identities. The current contract cannot satisfy both readings. + +**Suggested resolution:** Obtain an explicit parent-contract decision: either add a canonical `explore` phase instance and define its disposable state/evidence semantics, or amend REQ-08/workflow wording to exempt Explore from durable state while retaining its graph entry. Then make the vocabulary, codec, workflow validator, state schema, and fixtures agree. + +### 7. Major — Request-sourced repository/task identity has no defined transport seam + +`IdentityCapture` allows `source: "request"` and carries raw repository/task strings, and the adapter chunk is expected to capture and test that source. None of the five tool inputs carries identity, and the design does not name an MCP `_meta` field, initialization binding, or other request-context location from which it comes. Phase 2 is assigned identity validation, but it cannot validate or bind a transport field that Phase 1 never defines; different chunks can invent incompatible sources. + +**Suggested resolution:** Define the exact MCP connection/request metadata location, versioned shape, precedence, absence/duplication rules, and trust status now, with wire fixtures. If no request identity channel is intended, remove the request variant from the Phase 1 contract and introduce it only when its owning phase defines the transport. + +### 8. Major — Server-attested provenance is exposed as a forgeable public constructor seam + +The design exports `attestServerReview(review, binding)` but does not define `ServerBinding`, its required observed fields, who is allowed to construct it, or how persisted acceptance verifies its linkage to server state/receipts. A schema-valid caller-created binding could therefore manufacture `server-attested` evidence, contrary to REQ-11 and REQ-33. The other omitted types (`AgentBinding`, `DegradedBinding`, `ReviewEvidence`, and their assurance-specific fields) also leave the most important cross-chunk trust boundary unpinned. + +**Suggested resolution:** Specify every binding/evidence type and invariant in the phase contract. Keep server attestation behind an internal/opaque adapter capability rather than a generally callable constructor, and require persisted acceptance to verify the attestation against the observed invocation/result identity—not merely the schema-shaped provenance fields. Add forged-binding and wrong-invocation fixtures. + +### 9. Major — The phase design changes the parent Phase 1 state-schema acceptance criterion without approval + +The architecture's Phase 1 scope calls for normative strict durable schemas and its success criteria explicitly require valid workflow/review/**state** samples to round-trip. The phase design reinterprets “state samples” as inert `archflow_state` request samples, disables `artifact`, and defers durable `state.json` entirely. Phase 2 does own the detailed state/artifact schema family, so the documents are genuinely inconsistent; the lower-level phase design cannot resolve that inconsistency merely by calling its interpretation a clarification. + +**Suggested resolution:** Reconcile the architecture with explicit user approval before implementation: either amend the Phase 1 scope/criterion to say “inert state-tool request samples” and name Phase 2 as the first owner of durable state schemas, or add the minimum durable state contract and samples required by the current Phase 1 wording. Do not let implementation choose between two normative acceptance boundaries. + +### 10. Major — The offline bundle handoff to Phase 9 is not pinned + +Phase 1 creates `.gitignore`, generates `dist/archflow-mcp.js`, and verifies cached `npm ci --offline`, but never states whether the bundle is tracked, packaged as a retained release artifact, or ignored. REQ-28 ultimately requires an installed, version-pinned command that starts offline, and Phase 9 assumes an offline bundle exists from a clean checkout. A cache-warmed install test does not define how that payload reaches a clean installer checkout. + +**Suggested resolution:** Specify the cross-phase artifact contract now: whether `dist` is committed, attached as a hash-verified release/tarball asset, or reproducibly built before packaging from a separately provisioned dependency cache. Align `.gitignore`, package scripts, Phase 9 inputs, and the clean-checkout test with that choice; distinguish “offline startup” from “offline dependency installation.” + +### 11. Minor — The exported phase types statically admit encodings the runtime contract forbids + +`PhaseInstance.phase` is an unconstrained `number` and `PhaseInstanceId` uses `` `${number}` ``, which admits zero, negative, decimal, exponent, `NaN`, and unsafe-number forms at TypeScript call sites even though the prose requires a positive safe canonical integer and byte-for-byte round-trip. Runtime validation can reject them, but the advertised cross-chunk types do not encode the invariant. + +**Suggested resolution:** Use an opaque validated positive-safe phase-number type and a branded canonical `PhaseInstanceId` constructed only by the codec, while keeping boundary parsers on plain `string`/`unknown`. Add compile-time assertions alongside the runtime alias corpus. + +## Overall assessment + +No dependency version is stale as of 2026-07-27, and the MCP beta.5 assumptions about Standard Schema inputs, pre-handler argument rejection, skipped SDK output validation for `isError`, separate unknown-tool JSON-RPC errors, protocol `2025-11-25`, and direct 2025-era stdio remain current. The remaining defects are concentrated in trust-bearing contract seams and one unresolved license decision. No blocker requires abandoning the phase, but the major findings should be resolved before design approval because Phase 1 is intended to freeze the interfaces every later phase consumes. + +## Triage + +Triaged against the approved PRD/architecture, the revised phase design, live npm manifests and official dependency/API documentation on 2026-07-27. The owner approved both parent-contract corrections on 2026-07-27; the PRD and architecture now record them. + +| Finding | Disposition | Resolution | +|---------|-------------|------------| +| 1. Vitest graph introduces MPL-2.0 | **Accepted** | Added exact direct dev pin `vite@7.3.6`, which Vitest 4.1.10 supports and which prevents current resolution to Vite 8/Lightning CSS. The design now requires lock-wide proof of no `lightningcss`, no copyleft package, and complete license/NOTICE evidence; it no longer presupposes transitive acceptability. MPL is not adopted. | +| 2. Triage identity collisions | **Accepted** | Architecture Phase 2 owns composite `FindingRef { review_evidence_digest, finding_id }`; every disposition keys that pair, and fixtures cover two reviews that both use local ID `F-1`. | +| 3. Illegal gate-decision combinations | **Accepted in part** | Architecture Phase 2 freezes discriminated gate contexts and one exhaustive `GATE_DECISIONS_BY_KIND` authority shared by JSON Schema, Zod, result correlation, and fixtures. Parent-fixed constitution-edit, restore-collision, commit-authorization, waiver, and supplemental outcomes are separated and exact. New Phase 6 still derives and compares the authoritative set before publishing/resolving a durable gate. | +| 4. Missing constitution-compliance evidence | **Accepted** | Architecture Phase 2 owns digest-bound per-rule compliance findings, rule version/outcome, all `enforced_by` states, separate drift/triggers, `ValidatedAdjudication`, renderers, and missing/stale/unknown/failed/digest-mismatch fixtures. | +| 5. Known-tool failures violate stable-error contract | **Accepted** | Architecture Phase 2 owns beta.5's low-level `Server` seam, safe parsing of known calls into stable `CONTRACT_*` results, exact tool/error schemas, and `projectCallToolResult`; only unknown/disabled names remain protocol errors. Its SDK currency check must prove an equivalent seam if the deprecated-but-supported API changes. | +| 6. Explore cannot be represented at state boundary | **Accepted** | The owner approved treating Explore as disposable pre-task work present only in workflow vocabulary, with no phase/review/state evidence. PRD REQ-08 now explicitly exempts Explore from durable state recording. | +| 7. Undefined request identity transport | **Accepted** | Architecture Phase 2 defines immutable startup/initialize repository/host candidates and required request `task_id`; new Phase 3 validates/canonicalizes them before reads. No request may override repository or host identity or use hidden metadata. | +| 8. Forgeable server-attested provenance | **Accepted in part** | Architecture Phase 2 defines all binding/evidence types, internal opaque observation/attestation minting, receipt/state/result linkage verification, and forged/wrong-invocation fixtures. Schema-shaped provenance alone cannot upgrade assurance. | +| 9. Phase design reinterprets parent state criterion | **Accepted** | The owner approved the architecture split: Phase 2 owns inert `archflow_state` request/tool schemas, while new Phase 3 owns durable `state.json` and detailed artifact schemas. Narrowed Phase 1 contains neither surface. | +| 10. Offline bundle handoff unspecified | **Accepted** | Architecture Phase 2 tracks `dist/archflow-mcp.js` and `dist/manifest.json` with bundle/source/schema/assets/package/lock identities and clean-checkout offline proof. New Phase 9 updates the same artifact for full assembly; new Phase 10 verifies it before installation. | +| 11. Phase types over-admit invalid encodings | **Accepted** | Added opaque `PositiveSafePhaseNumber` and canonical `PhaseInstanceId` brands minted only by validators/codecs, with boundary parsers accepting `unknown` and both compile-time and runtime invalid-alias fixtures. | + +The revisions are substantial, so the fully reconciled design requires another fresh-context review before it is presented for approval. + +## Post-triage sizing review + +A fresh-context review found the reconciled Phase 1 still oversized because package/assets/validator foundations and trust-bearing review/MCP/bundle contracts competed for one implementation session. The user approved a split and full downstream renumbering on 2026-07-27: + +- Phase 1 now ends at the buildable package, validation infrastructure, branded codec, and workflow/config/rubric/constitution contracts/assets. +- New architecture Phase 2 owns review/triage/adjudication, gate/error/tool interfaces, inert MCP protocol proof, provenance linkage, and tracked offline bundle. +- New Phase 3 owns durable state and detailed artifact/repository schemas; old Phases 2–15 become new Phases 3–16. + +This sizing decision supersedes the final sentence above: the narrowed Phase 1 is now sized to five implementation chunks, while the trust-bearing work receives its own phase and review gate. From 9ddc26369de17329a4e0524b0ae8d558c47770b0 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 10:52:08 -0500 Subject: [PATCH 005/124] MCP Integration Phase 1: Contracts, Assets, and Package Scaffold Establish the exact-pinned Node package, foundational JSON Schema/Zod/YAML contracts, workflow and constitution assets, and canonical phase codecs. Add runnable bundle, dependency/license/notice verification, exact Node CI, and triaged counter-review fixes without entering later-phase MCP or persistence scope. --- .../tasks/mcp-integration/architecture.md | 14 +- ...ntracts-assets-and-package-scaffold-log.md | 40 + ...1-contracts-assets-and-package-scaffold.md | 17 +- .../reviews/phase-1-impl-counter-review.md | 52 + .github/workflows/ci.yml | 33 + .gitignore | 5 + THIRD_PARTY_NOTICES.md | 160 ++ assets/constitution/00-process.md | 7 + assets/constitution/10-architecture.md | 7 + assets/constitution/20-data.md | 10 + assets/constitution/30-product.md | 7 + assets/constitution/README.md | 5 + assets/workflow.yaml | 27 + docs/dependency-upgrades.md | 29 + docs/mcp-integration-design.md | 2 + notices/typescript-7.0.2-NOTICE.txt | 436 ++++ package-lock.json | 2024 +++++++++++++++++ package.json | 30 + scripts/build-temp.mjs | 14 + scripts/check-dependency-policy.mjs | 102 + scripts/check-notices.mjs | 156 ++ scripts/smoke-temp-bundle.mjs | 27 + scripts/test-notices-policy.mjs | 56 + src/contracts/config.ts | 45 + src/contracts/constitution.ts | 75 + src/contracts/index.ts | 10 + src/contracts/phase-instance.ts | 42 + src/contracts/plain-json.ts | 115 + src/contracts/rubric.ts | 40 + src/contracts/schemas/v1/config.schema.json | 11 + .../schemas/v1/constitution-rule.schema.json | 9 + .../schemas/v1/phase-instance.schema.json | 36 + .../schemas/v1/primitives.schema.json | 11 + src/contracts/schemas/v1/rubric.schema.json | 10 + src/contracts/schemas/v1/workflow.schema.json | 19 + src/contracts/validators.ts | 114 + src/contracts/versions.ts | 10 + src/contracts/vocabulary.ts | 9 + src/contracts/workflow.ts | 47 + src/contracts/yaml.ts | 43 + .../foundational-schema-agreement.test.ts | 77 + .../foundation/config/invalid-authority.yaml | 4 + test/fixtures/foundation/config/valid.yaml | 7 + .../constitution/invalid-frontmatter.md | 7 + .../fixtures/foundation/constitution/valid.md | 8 + .../foundation/rubric/invalid-mode.json | 1 + test/fixtures/foundation/rubric/valid.json | 1 + .../workflow/invalid-mutated-gate.yaml | 6 + test/fixtures/foundation/workflow/valid.yaml | 6 + test/unit/constitution.test.ts | 71 + test/unit/phase-instance.test.ts | 88 + test/unit/plain-json.test.ts | 91 + test/unit/rubric.test.ts | 42 + test/unit/workflow-config.test.ts | 76 + test/unit/yaml.test.ts | 40 + tsconfig.json | 18 + vitest.config.ts | 11 + 57 files changed, 4446 insertions(+), 14 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold-log.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-1-impl-counter-review.md create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 THIRD_PARTY_NOTICES.md create mode 100644 assets/constitution/00-process.md create mode 100644 assets/constitution/10-architecture.md create mode 100644 assets/constitution/20-data.md create mode 100644 assets/constitution/30-product.md create mode 100644 assets/constitution/README.md create mode 100644 assets/workflow.yaml create mode 100644 docs/dependency-upgrades.md create mode 100644 notices/typescript-7.0.2-NOTICE.txt create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 scripts/build-temp.mjs create mode 100644 scripts/check-dependency-policy.mjs create mode 100644 scripts/check-notices.mjs create mode 100644 scripts/smoke-temp-bundle.mjs create mode 100644 scripts/test-notices-policy.mjs create mode 100644 src/contracts/config.ts create mode 100644 src/contracts/constitution.ts create mode 100644 src/contracts/index.ts create mode 100644 src/contracts/phase-instance.ts create mode 100644 src/contracts/plain-json.ts create mode 100644 src/contracts/rubric.ts create mode 100644 src/contracts/schemas/v1/config.schema.json create mode 100644 src/contracts/schemas/v1/constitution-rule.schema.json create mode 100644 src/contracts/schemas/v1/phase-instance.schema.json create mode 100644 src/contracts/schemas/v1/primitives.schema.json create mode 100644 src/contracts/schemas/v1/rubric.schema.json create mode 100644 src/contracts/schemas/v1/workflow.schema.json create mode 100644 src/contracts/validators.ts create mode 100644 src/contracts/versions.ts create mode 100644 src/contracts/vocabulary.ts create mode 100644 src/contracts/workflow.ts create mode 100644 src/contracts/yaml.ts create mode 100644 test/contracts/foundational-schema-agreement.test.ts create mode 100644 test/fixtures/foundation/config/invalid-authority.yaml create mode 100644 test/fixtures/foundation/config/valid.yaml create mode 100644 test/fixtures/foundation/constitution/invalid-frontmatter.md create mode 100644 test/fixtures/foundation/constitution/valid.md create mode 100644 test/fixtures/foundation/rubric/invalid-mode.json create mode 100644 test/fixtures/foundation/rubric/valid.json create mode 100644 test/fixtures/foundation/workflow/invalid-mutated-gate.yaml create mode 100644 test/fixtures/foundation/workflow/valid.yaml create mode 100644 test/unit/constitution.test.ts create mode 100644 test/unit/phase-instance.test.ts create mode 100644 test/unit/plain-json.test.ts create mode 100644 test/unit/rubric.test.ts create mode 100644 test/unit/workflow-config.test.ts create mode 100644 test/unit/yaml.test.ts create mode 100644 tsconfig.json create mode 100644 vitest.config.ts diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index bea54d75..d986b7c5 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -394,6 +394,8 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali ### Phase 1: Contracts, Assets, and Package Scaffold +**Status**: COMPLETE (2026-07-27) + **Goal**: Establish the buildable package foundation and foundational repository contracts. **Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-15, REQ-17 @@ -402,12 +404,12 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali **Success Criteria**: -- [ ] Clean exact-lock install, strict typecheck, foundational tests, and temporary esbuild output pass on Node `24.15.0` and `24.18.0`; TypeScript is CLI-only with explicit `rootDir` and Node types. -- [ ] The exact lock includes direct `vite@7.3.6`, excludes `lightningcss`, and passes complete permissive-only license/NOTICE proof; copyleft, unreviewed licenses, ranged direct pins, and later-phase dependencies fail policy. -- [ ] Recursive plain-JSON/Ajv/Zod agreement fixtures reject mutation, non-plain prototypes, dangerous keys, unknown structure, bad formats, and YAML ambiguity with stable located validation results. -- [ ] Exact workflow/config/rubric/constitution assets and schemas round-trip; graph mutations, authoritative family config, invalid rubric modes, duplicate/invalid rules, and illegal append/deprecate/version evolution fail. -- [ ] Branded positive-safe phase numbers and phase-instance IDs are minted only by codecs/validators; compile-time assertions and runtime aliases reject non-canonical values, while Explore remains disposable pre-task vocabulary rather than a phase instance. -- [ ] Phase 1's first change adds the source design's visible lineage/supersession banner, links the approved PRD/architecture, preserves its originating-design status, and precedes all server implementation. +- [x] Clean exact-lock install, strict typecheck, foundational tests, and temporary esbuild output pass on Node `24.15.0` and `24.18.0`; TypeScript is CLI-only with explicit `rootDir` and Node types. +- [x] The exact lock includes direct `vite@7.3.6`, excludes `lightningcss`, and passes complete permissive-only license/NOTICE proof; copyleft, unreviewed licenses, ranged direct pins, and later-phase dependencies fail policy. +- [x] Recursive plain-JSON/Ajv/Zod agreement fixtures reject mutation, non-plain prototypes, dangerous keys, unknown structure, bad formats, and YAML ambiguity with stable located validation results. +- [x] Exact workflow/config/rubric/constitution assets and schemas round-trip; graph mutations, authoritative family config, invalid rubric modes, duplicate/invalid rules, and illegal append/deprecate/version evolution fail. +- [x] Branded positive-safe phase numbers and phase-instance IDs are minted only by codecs/validators; compile-time assertions and runtime aliases reject non-canonical values, while Explore remains disposable pre-task vocabulary rather than a phase instance. +- [x] Phase 1's first change adds the source design's visible lineage/supersession banner, links the approved PRD/architecture, preserves its originating-design status, and precedes all server implementation. ### Phase 2: Review Evidence and Inert MCP Boundary diff --git a/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold-log.md b/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold-log.md new file mode 100644 index 00000000..ee799a83 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold-log.md @@ -0,0 +1,40 @@ +## Implementation Log: Phase 1 - Contracts, Assets, and Package Scaffold + +### Decisions Made + +- Added the design-lineage banner to `docs/mcp-integration-design.md` before creating implementation files. The complete originating body below the banner remains byte-identical to its pre-implementation version. +- Kept JSON Schema 2020-12 normative and used strict, non-mutating Ajv2020 with `ajv-formats`; exported Zod boundary parsers all run the recursive plain-JSON preflight first. +- Kept the approved array-shaped rubric contract and represented its semantic criterion-ID uniqueness rule with the namespaced `x-archflow-unique-by` keyword, registered centrally by `createJsonSchemaValidator` and agreement-tested against Zod. +- Pinned the exact nine direct packages and retained Vite `7.3.6` to keep the Vitest graph on the reviewed permissive-only Vite 7 line. +- Retained the identical TypeScript 7.0.2 standalone notice once at `notices/typescript-7.0.2-NOTICE.txt`, with source and retained digests mapped to all 21 locked TypeScript packages. + +### Deviations from Plan + +- Added `scripts/build-temp.mjs` and `scripts/smoke-temp-bundle.mjs` instead of relying on an esbuild-only package command. The behavioral smoke is necessary to prove the temporary ESM bundle loads and exercises YAML, Ajv/formats, rejection, and phase-codec behavior under each exact Node version. +- Added `scripts/test-notices-policy.mjs` and the tracked `notices/` asset after implementation counter-review found that an SPDX table alone did not retain mandatory standalone notice content. Mutation cases now reject changed, missing, and newly unmapped notice files. +- Added the `x-archflow-unique-by` semantic schema keyword after counter-review exposed that standard `uniqueItems` compares whole criterion objects rather than criterion IDs. +- No PRD requirement changed, and no Phase 2 or Phase 3 implementation surface entered Phase 1. + +### Patterns Established + +- Every public parser accepting `unknown` performs `assertPlainJson` before schema parsing so prototypes, accessors, dangerous keys, cycles, and non-JSON values fail before validator inspection. +- JSON Schema/Zod overlap is tested with positive, negative, disagreement, and non-mutation cases; schema-specific semantic constraints are explicitly namespaced and registered in the central Ajv factory. +- Dependency updates regenerate the exact lock deliberately, rerun lock-wide license policy, update retained notices and digests, and execute notice mutation tests. +- Generated verification bundles live only below ignored `.tmp/`; the release `dist/` path remains absent and unignored for Phase 2's tracked artifact. + +### Gotchas + +- Esbuild can emit an ESM file that still contains CommonJS dynamic-require paths. The temporary bundle injects `createRequire` compatibility and must be behaviorally exercised, not merely produced. +- npm lock metadata is enough for the SPDX inventory but not for package-distributed standalone notices. Those require retained content, exact package mappings, and source/retained digest verification. +- Canonical iterated identities use `phase-design-` and `phase-impl-`; colon forms and all non-canonical numeric aliases are invalid. +- TypeScript's project includes `src`, `test`, and root configuration, so the explicit CLI-only `rootDir` is `.`. + +### Key Interfaces + +- `src/contracts/versions.ts`: `SCHEMA_IDS` and `SCHEMA_VERSION` define the six foundational v1 schema identities. +- `src/contracts/plain-json.ts`: `assertPlainJson(value: unknown, label?: string): asserts value is PlainJsonValue` is the required first boundary check. +- `src/contracts/validators.ts`: `createJsonSchemaValidator(schema, referencedSchemas?)`, `assertValidJsonSchema(validator, value, label?)`, and `assertZodAgreement(value, jsonValidator, zodSchema, label?)` own strict Ajv and overlap validation. +- `src/contracts/phase-instance.ts`: `parsePositiveSafePhaseNumber(value)`, `encodePhaseInstance(value)`, and `decodePhaseInstance(value)` mint and parse only `prd`, `design`, `phase-design-`, and `phase-impl-` identities. +- `src/contracts/yaml.ts`: `parseSingleYamlDocument(source: string, label: string): unknown` is the sole safe YAML 1.2 entry point. +- `src/contracts/workflow.ts`, `config.ts`, `rubric.ts`, and `constitution.ts` expose the foundational repository parsers; `validateConstitutionEvolution(previous, candidate)` enforces append-only stable rule IDs and positive versions. +- `scripts/check-dependency-policy.mjs`, `check-notices.mjs`, and `test-notices-policy.mjs` enforce the exact dependency/license/notice contract used by CI. diff --git a/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold.md b/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold.md index 1e9ad305..cecc457b 100644 --- a/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold.md +++ b/.archflow/tasks/mcp-integration/phases/phase-1-contracts-assets-and-package-scaffold.md @@ -1,6 +1,7 @@ # Phase 1: Contracts, Assets, and Package Scaffold -**Status**: DESIGNED +**Status**: COMPLETE +**Implemented**: 2026-07-27 **Task**: mcp-integration **Goal**: Establish the buildable package foundation and foundational repository contracts. **Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-15, REQ-17 @@ -82,13 +83,13 @@ Boundary parsers accept `unknown`; only validated codecs mint phase brands. A ph ## Success Criteria -- [ ] The source design receives only a resolving lineage/supersession banner above an otherwise byte-preserved originating body, and the implementation log records that it was first. -- [ ] Clean exact-lock install, `tsc --noEmit`, foundational tests, and temporary Node-24 ESM bundle pass on exact Node `24.15.0` and `24.18.0`; the current Node `24.11.1` shell is not acceptance evidence. -- [ ] All nine direct pins are exact and current at implementation time. Direct `vite@7.3.6` constrains Vitest's graph; the lock excludes `lightningcss`, copyleft, missing/unreviewed licenses, later-phase dependencies, and stale notices. -- [ ] Plain-JSON preflight and strict non-mutating Ajv/Zod agreement reject non-plain/inherited objects, cycles/non-JSON values, dangerous keys, unknown properties, invalid formats, and contradictory validator acceptance. -- [ ] Workflow/config share the safe one-document YAML path. Exact graph topology, role/phase/model/effort config, rubric kind/mode, constitution frontmatter, cross-file rule uniqueness, and append-only rule evolution pass; malformed/unknown/duplicate/reused/reactivated/unversioned cases fail with located diagnostics. -- [ ] Only codecs/validators mint positive-safe phase numbers and canonical phase IDs; compile-time assertions and runtime aliases reject invalid forms, and Explore remains graph-only pre-task vocabulary. -- [ ] No review/triage/adjudication schema or renderer, error/gate/tool contract, MCP dependency/server/fixture, tracked bundle, durable state/artifact schema, persistence, dispatch, or installer work enters Phase 1. +- [x] The source design receives only a resolving lineage/supersession banner above an otherwise byte-preserved originating body, and the implementation log records that it was first. +- [x] Clean exact-lock install, `tsc --noEmit`, foundational tests, and temporary Node-24 ESM bundle pass on exact Node `24.15.0` and `24.18.0`; the current Node `24.11.1` shell is not acceptance evidence. +- [x] All nine direct pins are exact and current at implementation time. Direct `vite@7.3.6` constrains Vitest's graph; the lock excludes `lightningcss`, copyleft, missing/unreviewed licenses, later-phase dependencies, and stale notices. +- [x] Plain-JSON preflight and strict non-mutating Ajv/Zod agreement reject non-plain/inherited objects, cycles/non-JSON values, dangerous keys, unknown properties, invalid formats, and contradictory validator acceptance. +- [x] Workflow/config share the safe one-document YAML path. Exact graph topology, role/phase/model/effort config, rubric kind/mode, constitution frontmatter, cross-file rule uniqueness, and append-only rule evolution pass; malformed/unknown/duplicate/reused/reactivated/unversioned cases fail with located diagnostics. +- [x] Only codecs/validators mint positive-safe phase numbers and canonical phase IDs; compile-time assertions and runtime aliases reject invalid forms, and Explore remains graph-only pre-task vocabulary. +- [x] No review/triage/adjudication schema or renderer, error/gate/tool contract, MCP dependency/server/fixture, tracked bundle, durable state/artifact schema, persistence, dispatch, or installer work enters Phase 1. ## Verification Steps diff --git a/.archflow/tasks/mcp-integration/reviews/phase-1-impl-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-1-impl-counter-review.md new file mode 100644 index 00000000..adc5d1ca --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-1-impl-counter-review.md @@ -0,0 +1,52 @@ +# Phase 1 Implementation Counter-Review + +## Findings + +1. **Major — The phase-instance codec uses a non-normative `:` encoding.** + + `src/contracts/phase-instance.ts` encodes and accepts `phase-design:42` and `phase-impl:42`, and the unit tests freeze those forms. The approved PRD (`REQ-02`, `VAL-16`) and architecture's Phase Instance contract require `phase-design-` and `phase-impl-`. If this ships, later review, decision, migration, and status paths built from the codec will not match the canonical repository layout. + + **Suggested resolution:** Change the codec and its alias corpus to emit and accept only `phase-design-` / `phase-impl-`, retaining the existing positive-safe canonical integer checks. Add direct tests against the parent-contract examples so the delimiter cannot drift again. + +2. **Major — The advertised temporary ESM bundle is not runnable.** + + `npm run build:temp` exits successfully, but importing `.tmp/archflow-contracts.mjs` under Node 24 fails immediately with `Error: Dynamic require of "process" is not supported`, originating in the bundled `yaml` CommonJS code. CI only checks that esbuild produced a file, so it reports success without driving the artifact. This does not prove a working Node-24 ESM bundle as required by the phase verification boundary. + + **Suggested resolution:** Adjust the esbuild configuration so the generated ESM artifact can load its bundled dependencies correctly, then add a Node import/smoke invocation of the generated file to `build:temp` or CI. Keep the output temporary and continue asserting that no `dist/` artifact is produced. + +3. **Major — Public Zod boundary parsers bypass the plain-JSON preflight.** + + `parseConfigV1`, `parseRubricV1`, and `parseConstitutionRuleV1` accept `unknown` but call Zod directly. Objects whose required values exist only on a custom prototype are accepted and normalized into apparently valid own-property objects; accessor getters are also executed during parsing. This violates the phase contract that boundary validation reject inherited/non-plain values and dangerous inspection behavior. The tests prove preflight only through `JsonSchemaValidator.assert`/`assertZodAgreement`, leaving the exported direct parsers unprotected. + + **Suggested resolution:** Run `assertPlainJson` before every exported `unknown` boundary parser (or expose one shared preflighted parsing seam and keep raw schemas internal). Add inherited-object, accessor, dangerous-key, and non-JSON cases to each exported parser's tests, not only to the generic validator tests. + +4. **Major — The normative rubric JSON Schema and its Zod mirror disagree on duplicate criterion IDs.** + + `rubricV1Schema` rejects two criteria with the same `id` even when their other fields differ, but `rubric.schema.json` uses only `uniqueItems: true`, which rejects duplicate whole objects rather than duplicate IDs. The normative JSON Schema therefore accepts a rubric the Zod mirror rejects, contrary to the required agreement and fail-closed duplicate handling. The contract corpus tests only one-criterion rubrics and miss this contradiction. + + **Suggested resolution:** Represent or validate criterion identity in a way the normative contract can enforce consistently (for example, change the durable shape to an ID-keyed object, or add a clearly defined semantic validation layer used by both paths). Add the existing differing-body duplicate-ID case to the Ajv/Zod agreement corpus and require both validators to reject it for the same contract reason. + +5. **Major — The notices check does not prove complete required notices.** + + `scripts/check-notices.mjs` only compares package/version/license table rows with lockfile metadata. It never inspects or retains required notice files or license text. The installed graph already contains `typescript/NOTICE.txt` and `@typescript/typescript-linux-x64/NOTICE.txt`, but their required contents are absent from `THIRD_PARTY_NOTICES.md`; the checker still reports completeness. This falls short of the design's complete license/NOTICE proof and could let future mandatory attribution text disappear silently. + + **Suggested resolution:** Define the retained notice/license artifact policy now, include the applicable notice contents (or tracked verbatim files) for packages that ship them, and make the checker inventory and verify those files/content in addition to SPDX lock metadata. Add a mutation test that removes or changes a required notice and proves the check fails. + +6. **Minor — `tsconfig.json` omits the architecture's explicit `rootDir`.** + + The Phase 1 architecture success criteria require CLI-only TypeScript with an explicit `rootDir` and Node types. Node types are configured, but `rootDir` is absent, so TypeScript infers it from the mixed `src`, `test`, and config inputs. + + **Suggested resolution:** Add the intended explicit `rootDir` consistent with the chosen source/test layout, or revise the architecture criterion through the normal approval path if a single root is intentionally inappropriate. + +## Triage + +Triaged against the approved PRD, architecture, and Phase 1 design on 2026-07-27. All six findings identify valid contract or verification gaps. + +| Finding | Disposition | Resolution | +|---------|-------------|------------| +| 1. Non-normative phase-instance delimiter | **Accepted and fixed** | The codec now emits and accepts only `phase-design-` and `phase-impl-`. Parent-contract examples, positive-safe bounds, legacy colon forms, aliases, path syntax, percent escapes, and Unicode digits are covered directly. | +| 2. Temporary ESM bundle is not proven runnable | **Accepted and fixed** | A plain import succeeded in the triage environment, but the bundle still contained a latent CommonJS dynamic-require path and the build did not drive exported behavior. The esbuild API build now supplies Node ESM `createRequire` compatibility, and `build:temp` imports the bundle and exercises YAML parsing, Ajv/formats validation, rejection behavior, and the phase API under the active Node version. CI runs this smoke in both exact Node jobs. | +| 3. Public Zod parsers bypass plain-JSON preflight | **Accepted and fixed** | Every exported foundational `unknown` parser now invokes `assertPlainJson` before Zod. Parser-specific tests prove inherited objects, accessors without getter execution, dangerous keys, and non-JSON values fail at the boundary. | +| 4. Duplicate rubric IDs differ between JSON Schema and Zod | **Accepted and fixed** | The normative rubric schema declares the namespaced `x-archflow-unique-by: id` semantic constraint, and strict Ajv registers the non-mutating keyword used to enforce it. The agreement corpus now proves differing-body duplicate IDs are rejected by both Ajv and Zod without mutation. | +| 5. Notices check proves only SPDX rows | **Accepted and fixed** | The complete TypeScript 7.0.2 standalone notice is retained once with exact source/retained digests and mapped to all 21 locked TypeScript packages, including optional platforms. The checker verifies lock-wide SPDX rows, retained content, installed source notices, and rejects any installed unmapped standalone notice; mutation tests prove changed, missing, and unexpected notice content fails. | +| 6. Missing explicit TypeScript `rootDir` | **Accepted and fixed** | `rootDir` is explicitly `.` so the CLI-only no-emit project consistently covers source, tests, and root configuration while retaining strict Node typings. | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..455f7c5c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + verify: + name: Node ${{ matrix.node-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: ["24.15.0", "24.18.0"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: npm + - run: npm ci + - run: npm run typecheck + - run: npm test + - run: npm run test:contracts + - run: npm run build:temp + - run: npm run check:dependencies + - run: npm run check:notices + - run: npm run test:notices-policy + - name: Assert no tracked-release bundle was produced + run: test ! -e dist diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..6b8c473a --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +.tmp/ +coverage/ +.vitest/ +*.tsbuildinfo diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..714ed438 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,160 @@ +# Third-party notices + +This private development package currently has no project license. Its locked third-party dependency graph is listed below for license review and reproducibility. Package license declarations are retained in the SPDX inventory; standalone attribution notices are retained and content-addressed in this repository as described below. + +This inventory is generated from and checked against `package-lock.json`. Optional platform packages are included even when they are not installed on the current host. + +| Locked package | SPDX license | +| --- | --- | +| `@esbuild/aix-ppc64@0.28.1` | `MIT` | +| `@esbuild/android-arm64@0.28.1` | `MIT` | +| `@esbuild/android-arm@0.28.1` | `MIT` | +| `@esbuild/android-x64@0.28.1` | `MIT` | +| `@esbuild/darwin-arm64@0.28.1` | `MIT` | +| `@esbuild/darwin-x64@0.28.1` | `MIT` | +| `@esbuild/freebsd-arm64@0.28.1` | `MIT` | +| `@esbuild/freebsd-x64@0.28.1` | `MIT` | +| `@esbuild/linux-arm64@0.28.1` | `MIT` | +| `@esbuild/linux-arm@0.28.1` | `MIT` | +| `@esbuild/linux-ia32@0.28.1` | `MIT` | +| `@esbuild/linux-loong64@0.28.1` | `MIT` | +| `@esbuild/linux-mips64el@0.28.1` | `MIT` | +| `@esbuild/linux-ppc64@0.28.1` | `MIT` | +| `@esbuild/linux-riscv64@0.28.1` | `MIT` | +| `@esbuild/linux-s390x@0.28.1` | `MIT` | +| `@esbuild/linux-x64@0.28.1` | `MIT` | +| `@esbuild/netbsd-arm64@0.28.1` | `MIT` | +| `@esbuild/netbsd-x64@0.28.1` | `MIT` | +| `@esbuild/openbsd-arm64@0.28.1` | `MIT` | +| `@esbuild/openbsd-x64@0.28.1` | `MIT` | +| `@esbuild/openharmony-arm64@0.28.1` | `MIT` | +| `@esbuild/sunos-x64@0.28.1` | `MIT` | +| `@esbuild/win32-arm64@0.28.1` | `MIT` | +| `@esbuild/win32-ia32@0.28.1` | `MIT` | +| `@esbuild/win32-x64@0.28.1` | `MIT` | +| `@jridgewell/sourcemap-codec@1.5.5` | `MIT` | +| `@rollup/rollup-android-arm-eabi@4.62.3` | `MIT` | +| `@rollup/rollup-android-arm64@4.62.3` | `MIT` | +| `@rollup/rollup-darwin-arm64@4.62.3` | `MIT` | +| `@rollup/rollup-darwin-x64@4.62.3` | `MIT` | +| `@rollup/rollup-freebsd-arm64@4.62.3` | `MIT` | +| `@rollup/rollup-freebsd-x64@4.62.3` | `MIT` | +| `@rollup/rollup-linux-arm-gnueabihf@4.62.3` | `MIT` | +| `@rollup/rollup-linux-arm-musleabihf@4.62.3` | `MIT` | +| `@rollup/rollup-linux-arm64-gnu@4.62.3` | `MIT` | +| `@rollup/rollup-linux-arm64-musl@4.62.3` | `MIT` | +| `@rollup/rollup-linux-loong64-gnu@4.62.3` | `MIT` | +| `@rollup/rollup-linux-loong64-musl@4.62.3` | `MIT` | +| `@rollup/rollup-linux-ppc64-gnu@4.62.3` | `MIT` | +| `@rollup/rollup-linux-ppc64-musl@4.62.3` | `MIT` | +| `@rollup/rollup-linux-riscv64-gnu@4.62.3` | `MIT` | +| `@rollup/rollup-linux-riscv64-musl@4.62.3` | `MIT` | +| `@rollup/rollup-linux-s390x-gnu@4.62.3` | `MIT` | +| `@rollup/rollup-linux-x64-gnu@4.62.3` | `MIT` | +| `@rollup/rollup-linux-x64-musl@4.62.3` | `MIT` | +| `@rollup/rollup-openbsd-x64@4.62.3` | `MIT` | +| `@rollup/rollup-openharmony-arm64@4.62.3` | `MIT` | +| `@rollup/rollup-win32-arm64-msvc@4.62.3` | `MIT` | +| `@rollup/rollup-win32-ia32-msvc@4.62.3` | `MIT` | +| `@rollup/rollup-win32-x64-gnu@4.62.3` | `MIT` | +| `@rollup/rollup-win32-x64-msvc@4.62.3` | `MIT` | +| `@standard-schema/spec@1.1.0` | `MIT` | +| `@types/chai@5.2.3` | `MIT` | +| `@types/deep-eql@4.0.2` | `MIT` | +| `@types/estree@1.0.9` | `MIT` | +| `@types/node@24.13.3` | `MIT` | +| `@typescript/typescript-aix-ppc64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-darwin-arm64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-darwin-x64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-freebsd-arm64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-freebsd-x64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-linux-arm64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-linux-arm@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-linux-loong64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-linux-mips64el@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-linux-ppc64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-linux-riscv64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-linux-s390x@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-linux-x64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-netbsd-arm64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-netbsd-x64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-openbsd-arm64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-openbsd-x64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-sunos-x64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-win32-arm64@7.0.2` | `Apache-2.0` | +| `@typescript/typescript-win32-x64@7.0.2` | `Apache-2.0` | +| `@vitest/expect@4.1.10` | `MIT` | +| `@vitest/mocker@4.1.10` | `MIT` | +| `@vitest/pretty-format@4.1.10` | `MIT` | +| `@vitest/runner@4.1.10` | `MIT` | +| `@vitest/snapshot@4.1.10` | `MIT` | +| `@vitest/spy@4.1.10` | `MIT` | +| `@vitest/utils@4.1.10` | `MIT` | +| `ajv-formats@3.0.1` | `MIT` | +| `ajv@8.20.0` | `MIT` | +| `assertion-error@2.0.1` | `MIT` | +| `chai@6.2.2` | `MIT` | +| `convert-source-map@2.0.0` | `MIT` | +| `es-module-lexer@2.3.1` | `MIT` | +| `esbuild@0.28.1` | `MIT` | +| `estree-walker@3.0.3` | `MIT` | +| `expect-type@1.4.0` | `Apache-2.0` | +| `fast-deep-equal@3.1.3` | `MIT` | +| `fast-uri@3.1.4` | `BSD-3-Clause` | +| `fdir@6.5.0` | `MIT` | +| `fsevents@2.3.3` | `MIT` | +| `json-schema-traverse@1.0.0` | `MIT` | +| `magic-string@0.30.21` | `MIT` | +| `nanoid@3.3.16` | `MIT` | +| `obug@2.1.4` | `MIT` | +| `pathe@2.0.3` | `MIT` | +| `picocolors@1.1.1` | `ISC` | +| `picomatch@4.0.5` | `MIT` | +| `postcss@8.5.23` | `MIT` | +| `require-from-string@2.0.2` | `MIT` | +| `rollup@4.62.3` | `MIT` | +| `siginfo@2.0.0` | `ISC` | +| `source-map-js@1.2.1` | `BSD-3-Clause` | +| `stackback@0.0.2` | `MIT` | +| `std-env@4.2.0` | `MIT` | +| `tinybench@2.9.0` | `MIT` | +| `tinyexec@1.2.4` | `MIT` | +| `tinyglobby@0.2.17` | `MIT` | +| `tinyrainbow@3.1.0` | `MIT` | +| `typescript@7.0.2` | `Apache-2.0` | +| `undici-types@7.18.2` | `MIT` | +| `vite@7.3.6` | `MIT` | +| `vitest@4.1.10` | `MIT` | +| `why-is-node-running@2.3.0` | `MIT` | +| `yaml@2.9.0` | `ISC` | +| `zod@4.4.3` | `MIT` | + +## Retained standalone notices + +The SPDX table is the exact-lock license inventory. In addition, any package-distributed standalone `NOTICE` or `THIRD_PARTY` file is a required retained artifact. Phase 1 reviewed every exact TypeScript 7.0.2 registry tarball in the lock, including optional platform packages not installed on this host. All 21 tarballs contain the same raw `NOTICE.txt` digest shown below, so one repository-normalized copy is retained and every exact package is mapped to it. The source and retained SHA-256 digests deliberately differ because the tracked copy uses repository-normalized text formatting. + +The notices checker inventories installed package notice files, verifies their source digest when present, requires the explicit mapping for all reviewed optional packages, and verifies the retained file content. A lock/version change invalidates these mappings and requires a fresh tarball review. + +| Locked package | Source NOTICE SHA-256 | Retained path | Retained SHA-256 | +| --- | --- | --- | --- | +| `@typescript/typescript-aix-ppc64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-darwin-arm64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-darwin-x64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-freebsd-arm64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-freebsd-x64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-linux-arm64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-linux-arm@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-linux-loong64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-linux-mips64el@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-linux-ppc64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-linux-riscv64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-linux-s390x@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-linux-x64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-netbsd-arm64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-netbsd-x64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-openbsd-arm64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-openbsd-x64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-sunos-x64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-win32-arm64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `@typescript/typescript-win32-x64@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | +| `typescript@7.0.2` | `f5c708b59114507b8b27b48181b6883d106bbca0c1634bbee45b5e344237b66b` | `notices/typescript-7.0.2-NOTICE.txt` | `f457d58282f3bcf3422ac3190a35e06fba0413624b255c2f33f18f0158226bd8` | diff --git a/assets/constitution/00-process.md b/assets/constitution/00-process.md new file mode 100644 index 00000000..82671351 --- /dev/null +++ b/assets/constitution/00-process.md @@ -0,0 +1,7 @@ +--- +id: explicit-human-authority +version: 1 +status: active +review_trigger: Advancement, approval, review-gate, waiver, or commit authority is inferred rather than explicitly recorded by a human for the exact subject. +--- +Required human decisions are explicit and bound to the exact artifact or code subject under review. Silence, elapsed time, agent prose, or a model verdict never supplies approval, waives a gate, authorizes a commit, or advances the workflow. diff --git a/assets/constitution/10-architecture.md b/assets/constitution/10-architecture.md new file mode 100644 index 00000000..f495c32a --- /dev/null +++ b/assets/constitution/10-architecture.md @@ -0,0 +1,7 @@ +--- +id: approved-design-before-code +version: 1 +status: active +review_trigger: Implementation begins before the applicable phase design is approved, or implementation materially departs from approved architecture without updating and re-reviewing its governing plan. +--- +Implementation starts only from an approved phase design. The PRD, architecture, and phase design remain truthful as work proceeds; material deviations update the governing documents and re-enter the applicable review boundary before dependent work advances. diff --git a/assets/constitution/20-data.md b/assets/constitution/20-data.md new file mode 100644 index 00000000..914cc8a4 --- /dev/null +++ b/assets/constitution/20-data.md @@ -0,0 +1,10 @@ +--- +id: task-and-evidence-isolation +version: 1 +status: active +review_trigger: A task reads or mutates another task's files, or an approval, waiver, review, or result is used for bytes other than the subject it identifies. +enforced_by: + - task-path-boundary-tests + - subject-digest-validation +--- +Tasks are isolated from one another. Durable decisions and evidence identify the exact task and subject bytes they govern; stale, mismatched, cross-task, malformed, or partial evidence fails closed and cannot authorize advancement. diff --git a/assets/constitution/30-product.md b/assets/constitution/30-product.md new file mode 100644 index 00000000..94f365c0 --- /dev/null +++ b/assets/constitution/30-product.md @@ -0,0 +1,7 @@ +--- +id: honest-human-centered-outcomes +version: 1 +status: active +review_trigger: A failure, cancellation, unavailable reviewer, uncertain policy result, or missing evidence is represented as success or silently bypassed. +--- +ArchFlow reports uncertainty and failure honestly and preserves human control. Automation performs the labor it can, but unavailable capabilities, inconclusive adjudication, missing evidence, and exhausted attempts remain visible non-success states with a safe next action. diff --git a/assets/constitution/README.md b/assets/constitution/README.md new file mode 100644 index 00000000..6815b047 --- /dev/null +++ b/assets/constitution/README.md @@ -0,0 +1,5 @@ +# ArchFlow constitution + +Each numbered Markdown file is one repository-wide policy rule. YAML frontmatter carries its stable identity and positive version; the prose body is the normative rule text. Rule IDs are append-only across approved revisions: change content or status only with a higher version, deprecate instead of deleting, and never reactivate a deprecated ID. + +Tasks pin these files from an immutable, human-approved policy-base commit. A task branch cannot amend its own governing constitution. diff --git a/assets/workflow.yaml b/assets/workflow.yaml new file mode 100644 index 00000000..b9456311 --- /dev/null +++ b/assets/workflow.yaml @@ -0,0 +1,27 @@ +phases: + - id: explore + skill: archflow-explore + pipeline: [produce] + gate: never + optional: true + - id: prd + skill: archflow-prd + pipeline: [produce, self_review, counter_review, triage, adjudicate] + gate: always + - id: design + skill: archflow-design + requires: [prd] + pipeline: [produce, self_review, counter_review, triage, adjudicate] + gate: always + - id: phase-design + skill: archflow-phase-design + requires: [design] + iterates: per_phase + pipeline: [produce, self_review, counter_review, triage, adjudicate] + gate: on_trigger + - id: phase-impl + skill: archflow-phase-impl + requires: [phase-design] + iterates: per_phase + pipeline: [produce, self_review, counter_review, triage, adjudicate] + gate: on_trigger diff --git a/docs/dependency-upgrades.md b/docs/dependency-upgrades.md new file mode 100644 index 00000000..acd51512 --- /dev/null +++ b/docs/dependency-upgrades.md @@ -0,0 +1,29 @@ +# Dependency upgrades + +ArchFlow uses exact direct versions and an exact npm lockfile. Dependency changes are deliberate review events, not routine range resolution. + +## Currency review — 2026-07-27 + +Registry metadata was reviewed for every Phase 1 direct pin. The selected versions are current on the review date, with two intentional line choices: + +| Package | Pin | Review result | +| --- | --- | --- | +| `zod` | `4.4.3` | Current; MIT | +| `ajv` | `8.20.0` | Current; MIT | +| `ajv-formats` | `3.0.1` | Current; MIT | +| `yaml` | `2.9.0` | Current; ISC | +| `typescript` | `7.0.2` | Current; Apache-2.0 | +| `@types/node` | `24.13.3` | Current compatible Node 24 typing line; MIT. Runtime and typing patch versions are intentionally independent. | +| `esbuild` | `0.28.1` | Current; MIT | +| `vitest` | `4.1.10` | Current; MIT | +| `vite` | `7.3.6` | Current supported Vite 7 line; MIT. Vite 8 is intentionally excluded because its current graph introduces MPL-2.0 Lightning CSS. | + +## Upgrade procedure + +1. Review official registry/repository release and license metadata for each proposed direct update and its resolved graph. +2. Edit only exact versions in `package.json`, then deliberately regenerate `package-lock.json` with the intended npm version. +3. Update `THIRD_PARTY_NOTICES.md` from the resolved lock inventory. +4. Run `npm ci`, `npm run typecheck`, `npm test`, `npm run test:contracts`, `npm run build:temp`, `npm run check:dependencies`, `npm run check:notices`, and `npm run test:notices-policy` on both supported exact Node versions. +5. Review schema, serialized-format, CLI, and protocol migrations before accepting the regenerated lock. + +The dependency policy rejects direct ranges, packages outside the phase allowlist, missing/unreviewed licenses, copyleft licenses, Lightning CSS, and dependencies reserved for later phases. Any policy expansion requires explicit review rather than weakening the checker as part of an unrelated update. diff --git a/docs/mcp-integration-design.md b/docs/mcp-integration-design.md index 60ff8539..d3591274 100644 --- a/docs/mcp-integration-design.md +++ b/docs/mcp-integration-design.md @@ -1,3 +1,5 @@ +> **Design lineage:** This is the preserved originating design for the MCP integration. The approved [product requirements](../.archflow/tasks/mcp-integration/prd.md) and [architecture](../.archflow/tasks/mcp-integration/architecture.md) are normative wherever they differ from this document. + # Archflow — Detailed Design **Scope:** what changes in the skills, what the constitution looks like, and what the bundled MCP server does. diff --git a/notices/typescript-7.0.2-NOTICE.txt b/notices/typescript-7.0.2-NOTICE.txt new file mode 100644 index 00000000..27cd2800 --- /dev/null +++ b/notices/typescript-7.0.2-NOTICE.txt @@ -0,0 +1,436 @@ +NOTICES AND INFORMATION +Do Not Translate or Localize + +This software incorporates material from third parties. +Microsoft makes certain open source code available at https://3rdpartysource.microsoft.com, +or you may send a check or money order for US $5.00, including the product name, +the open source component name, platform, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the extent +required to debug changes to any libraries licensed under the GNU Lesser General Public License. + + +------------------- DefinitelyTyped -------------------- +This file is based on or incorporates material from the projects listed below (collectively "Third Party Code"). Microsoft is not the original author of the Third Party Code. The original copyright notice and the license, under which Microsoft received such Third Party Code, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft, not the third party, licenses the Third Party Code to you under the terms set forth in the EULA for the Microsoft Product. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise. +DefinitelyTyped +This project is licensed under the MIT license. Copyrights are respective of each contributor listed at the beginning of each definition file. Provided for Informational Purposes Only + +MIT License +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-------------------------------------------------------------------------------------- + +------------------- Unicode -------------------- +UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE + +Unicode Data Files include all data files under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and +http://www.unicode.org/utility/trac/browser/. + +Unicode Data Files do not include PDF online code charts under the +directory http://www.unicode.org/Public/. + +Software includes any source code published in the Unicode Standard +or under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +http://www.unicode.org/cldr/data/, http://source.icu-project.org/repos/icu/, and +http://www.unicode.org/utility/trac/browser/. + +NOTICE TO USER: Carefully read the following legal agreement. +BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S +DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), +YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. +IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE +THE DATA FILES OR SOFTWARE. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1991-2017 Unicode, Inc. All rights reserved. +Distributed under the Terms of Use in http://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation +(the "Data Files") or Unicode software and any associated documentation +(the "Software") to deal in the Data Files or Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of +the Data Files or Software, and to permit persons to whom the Data Files +or Software are furnished to do so, provided that either +(a) this copyright and permission notice appear with all copies +of the Data Files or Software, or +(b) this copyright and permission notice appear in associated +Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT OF THIRD PARTY RIGHTS. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS +NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL +DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, +DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, +use or other dealings in these Data Files or Software without prior +written authorization of the copyright holder. +------------------------------------------------------------------------------------- + +-------------------Document Object Model----------------------------- +DOM + +W3C License +This work is being provided by the copyright holders under the following license. +By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. +Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following +on ALL copies of the work or portions thereof, including modifications: +* The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. +* Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included. +* Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived +from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." +Disclaimers +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR +FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. +The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. +Title to copyright in this work will at all times remain with copyright holders. + +--------- + +DOM +Copyright © 2018 WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License: Attribution 4.0 International +======================================================================= +Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: + +wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= +Creative Commons Attribution 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. + +-------------------------------------------------------------------------------- + +----------------------Web Background Synchronization------------------------------ + +Web Background Synchronization Specification +Portions of spec © by W3C + +W3C Community Final Specification Agreement +To secure commitments from participants for the full text of a Community or Business Group Report, the group may call for voluntary commitments to the following terms; a "summary" is +available. See also the related "W3C Community Contributor License Agreement". +1. The Purpose of this Agreement. +This Agreement sets forth the terms under which I make certain copyright and patent rights available to you for your implementation of the Specification. +Any other capitalized terms not specifically defined herein have the same meaning as those terms have in the "W3C Patent Policy", and if not defined there, in the "W3C Process Document". +2. Copyrights. +2.1. Copyright Grant. I grant to you a perpetual (for the duration of the applicable copyright), worldwide, non-exclusive, no-charge, royalty-free, copyright license, without any obligation for accounting to me, to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, distribute, and implement the Specification to the full extent of my copyright interest in the Specification. +2.2. Attribution. As a condition of the copyright grant, you must include an attribution to the Specification in any derivative work you make based on the Specification. That attribution must include, at minimum, the Specification name and version number. +3. Patents. +3.1. Patent Licensing Commitment. I agree to license my Essential Claims under the W3C Community RF Licensing Requirements. This requirement includes Essential Claims that I own and any that I have the right to license without obligation of payment or other consideration to an unrelated third party. W3C Community RF Licensing Requirements obligations made concerning the Specification and described in this policy are binding on me for the life of the patents in question and encumber the patents containing Essential Claims, regardless of changes in participation status or W3C Membership. I also agree to license my Essential Claims under the W3C Community RF Licensing Requirements in derivative works of the Specification so long as all normative portions of the Specification are maintained and that this licensing commitment does not extend to any portion of the derivative work that was not included in the Specification. +3.2. Optional, Additional Patent Grant. In addition to the provisions of Section 3.1, I may also, at my option, make certain intellectual property rights infringed by implementations of the Specification, including Essential Claims, available by providing those terms via the W3C Web site. +4. No Other Rights. Except as specifically set forth in this Agreement, no other express or implied patent, trademark, copyright, or other property rights are granted under this Agreement, including by implication, waiver, or estoppel. +5. Antitrust Compliance. I acknowledge that I may compete with other participants, that I am under no obligation to implement the Specification, that each participant is free to develop competing technologies and standards, and that each party is free to license its patent rights to third parties, including for the purpose of enabling competing technologies and standards. +6. Non-Circumvention. I agree that I will not intentionally take or willfully assist any third party to take any action for the purpose of circumventing my obligations under this Agreement. +7. Transition to W3C Recommendation Track. The Specification developed by the Project may transition to the W3C Recommendation Track. The W3C Team is responsible for notifying me that a Corresponding Working Group has been chartered. I have no obligation to join the Corresponding Working Group. If the Specification developed by the Project transitions to the W3C Recommendation Track, the following terms apply: +7.1. If I join the Corresponding Working Group. If I join the Corresponding Working Group, I will be subject to all W3C rules, obligations, licensing commitments, and policies that govern that Corresponding Working Group. +7.2. If I Do Not Join the Corresponding Working Group. +7.2.1. Licensing Obligations to Resulting Specification. If I do not join the Corresponding Working Group, I agree to offer patent licenses according to the W3C Royalty-Free licensing requirements described in Section 5 of the W3C Patent Policy for the portions of the Specification included in the resulting Recommendation. This licensing commitment does not extend to any portion of an implementation of the Recommendation that was not included in the Specification. This licensing commitment may not be revoked but may be modified through the exclusion process defined in Section 4 of the W3C Patent Policy. I am not required to join the Corresponding Working Group to exclude patents from the W3C Royalty-Free licensing commitment, but must otherwise follow the normal exclusion procedures defined by the W3C Patent Policy. The W3C Team will notify me of any Call for Exclusion in the Corresponding Working Group as set forth in Section 4.5 of the W3C Patent Policy. +7.2.2. No Disclosure Obligation. If I do not join the Corresponding Working Group, I have no patent disclosure obligations outside of those set forth in Section 6 of the W3C Patent Policy. +8. Conflict of Interest. I will disclose significant relationships when those relationships might reasonably be perceived as creating a conflict of interest with my role. I will notify W3C of any change in my affiliation using W3C-provided mechanisms. +9. Representations, Warranties and Disclaimers. I represent and warrant that I am legally entitled to grant the rights and promises set forth in this Agreement. IN ALL OTHER RESPECTS THE SPECIFICATION IS PROVIDED “AS IS.” The entire risk as to implementing or otherwise using the Specification is assumed by the implementer and user. Except as stated herein, I expressly disclaim any warranties (express, implied, or otherwise), including implied warranties of merchantability, non-infringement, fitness for a particular purpose, or title, related to the Specification. IN NO EVENT WILL ANY PARTY BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS OR ANY FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO THIS AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. All of my obligations under Section 3 regarding the transfer, successors in interest, or assignment of Granted Claims will be satisfied if I notify the transferee or assignee of any patent that I know contains Granted Claims of the obligations under Section 3. Nothing in this Agreement requires me to undertake a patent search. +10. Definitions. +10.1. Agreement. “Agreement” means this W3C Community Final Specification Agreement. +10.2. Corresponding Working Group. “Corresponding Working Group” is a W3C Working Group that is chartered to develop a Recommendation, as defined in the W3C Process Document, that takes the Specification as an input. +10.3. Essential Claims. “Essential Claims” shall mean all claims in any patent or patent application in any jurisdiction in the world that would necessarily be infringed by implementation of the Specification. A claim is necessarily infringed hereunder only when it is not possible to avoid infringing it because there is no non-infringing alternative for implementing the normative portions of the Specification. Existence of a non-infringing alternative shall be judged based on the state of the art at the time of the publication of the Specification. The following are expressly excluded from and shall not be deemed to constitute Essential Claims: +10.3.1. any claims other than as set forth above even if contained in the same patent as Essential Claims; and +10.3.2. claims which would be infringed only by: +portions of an implementation that are not specified in the normative portions of the Specification, or +enabling technologies that may be necessary to make or use any product or portion thereof that complies with the Specification and are not themselves expressly set forth in the Specification (e.g., semiconductor manufacturing technology, compiler technology, object-oriented technology, basic operating system technology, and the like); or +the implementation of technology developed elsewhere and merely incorporated by reference in the body of the Specification. +10.3.3. design patents and design registrations. +For purposes of this definition, the normative portions of the Specification shall be deemed to include only architectural and interoperability requirements. Optional features in the RFC 2119 sense are considered normative unless they are specifically identified as informative. Implementation examples or any other material that merely illustrate the requirements of the Specification are informative, rather than normative. +10.4. I, Me, or My. “I,” “me,” or “my” refers to the signatory. +10.5 Project. “Project” means the W3C Community Group or Business Group for which I executed this Agreement. +10.6. Specification. “Specification” means the Specification identified by the Project as the target of this agreement in a call for Final Specification Commitments. W3C shall provide the authoritative mechanisms for the identification of this Specification. +10.7. W3C Community RF Licensing Requirements. “W3C Community RF Licensing Requirements” license shall mean a non-assignable, non-sublicensable license to make, have made, use, sell, have sold, offer to sell, import, and distribute and dispose of implementations of the Specification that: +10.7.1. shall be available to all, worldwide, whether or not they are W3C Members; +10.7.2. shall extend to all Essential Claims owned or controlled by me; +10.7.3. may be limited to implementations of the Specification, and to what is required by the Specification; +10.7.4. may be conditioned on a grant of a reciprocal RF license (as defined in this policy) to all Essential Claims owned or controlled by the licensee. A reciprocal license may be required to be available to all, and a reciprocal license may itself be conditioned on a further reciprocal license from all. +10.7.5. may not be conditioned on payment of royalties, fees or other consideration; +10.7.6. may be suspended with respect to any licensee when licensor issued by licensee for infringement of claims essential to implement the Specification or any W3C Recommendation; +10.7.7. may not impose any further conditions or restrictions on the use of any technology, intellectual property rights, or other restrictions on behavior of the licensee, but may include reasonable, customary terms relating to operation or maintenance of the license relationship such as the following: choice of law and dispute resolution; +10.7.8. shall not be considered accepted by an implementer who manifests an intent not to accept the terms of the W3C Community RF Licensing Requirements license as offered by the licensor. +10.7.9. The RF license conforming to the requirements in this policy shall be made available by the licensor as long as the Specification is in effect. The term of such license shall be for the life of the patents in question. +I am encouraged to provide a contact from which licensing information can be obtained and other relevant licensing information. Any such information will be made publicly available. +10.8. You or Your. “You,” “you,” or “your” means any person or entity who exercises copyright or patent rights granted under this Agreement, and any person that person or entity controls. + +------------------------------------------------------------------------------------- + +------------------- WebGL ----------------------------- +Copyright (c) 2018 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +------------------------------------------------------ + +--------------------------------------------------------- + + +github.com/zeebo/xxh3 v1.1.0 - BSD-2-Clause + + +Copyright (c) 2019, Jeff Wendling +Copyright (c) 2012-2014, Yann Collet + +Copyright (c) . All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 - BSD-3-Clause + + +Copyright 2010 The Go Authors +Copyright 2011 The Go Authors +Copyright 2016 The Go Authors +Copyright 2018 The Go Authors +Copyright 2020 The Go Authors +Copyright 2021 The Go Authors +Copyright 2022 The Go Authors +Copyright 2023 The Go Authors +Copyright 2024 The Go Authors +Copyright (c) 2020 The Go Authors + +Copyright (c) . All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +golang.org/x/sync v0.21.0 - BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang + + +Copyright 2009 The Go Authors +Copyright 2013 The Go Authors +Copyright 2016 The Go Authors +Copyright 2017 The Go Authors +Copyright 2019 The Go Authors + +BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang + +--------------------------------------------------------- + +--------------------------------------------------------- + +golang.org/x/sys v0.46.0 - BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang + + +Copyright 2009 The Go Authors +Copyright 2010 The Go Authors +Copyright 2011 The Go Authors +Copyright 2012 The Go Authors +Copyright 2013 The Go Authors +Copyright 2014 The Go Authors +Copyright 2015 The Go Authors +Copyright 2016 The Go Authors +Copyright 2017 The Go Authors +Copyright 2018 The Go Authors +Copyright 2019 The Go Authors +Copyright 2020 The Go Authors +Copyright 2021 The Go Authors +Copyright 2022 The Go Authors +Copyright 2023 The Go Authors +Copyright 2024 The Go Authors +Copyright 2025 The Go Authors +Copyright 2009,2010 The Go Authors + +BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang + +--------------------------------------------------------- + +--------------------------------------------------------- + +golang.org/x/term v0.44.0 - BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang + + +Copyright 2009 The Go Authors +Copyright 2011 The Go Authors +Copyright 2013 The Go Authors +Copyright 2019 The Go Authors +Copyright 2021 The Go Authors + +BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang + +--------------------------------------------------------- + +--------------------------------------------------------- + +golang.org/x/text v0.38.0 - BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang + + +(c) AeHa (c) +(c) EeAoq (c) +(c) EAiE (c) A +(c) lEEe (c) AE +(c) (c) AAEE (c) +(c) oav!A (c) AY +(c) aA"AE (c) 1AE (c) +Copyright 2009 The Go Authors +Copyright 2011 The Go Authors +Copyright 2012 The Go Authors +Copyright 2013 The Go Authors +Copyright 2014 The Go Authors +Copyright 2015 The Go Authors +Copyright 2016 The Go Authors +Copyright 2017 The Go Authors +Copyright 2018 The Go Authors +Copyright 2019 The Go Authors +Copyright 2021 The Go Authors +Copyright 2025 The Go Authors + +BSD-3-Clause AND LicenseRef-scancode-google-patent-license-golang + +--------------------------------------------------------- + +--------------------------------------------------------- + +github.com/klauspost/cpuid/v2 v2.2.10 - MIT + + +Copyright (c) 2015 Klaus Post +Copyright (c) 2020 Klaus Post +Copyright (c) 2021 Klaus Post +Copyright 2018 The Go Authors +Copyright (c) 2015- Klaus Post & Contributors + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +github.com/Microsoft/go-winio v0.6.2 - MIT + + +Copyright (c) 2015 Microsoft +Copyright 2013 The Go Authors + +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------------------------- + +--------------------------------------------------------- + +github.com/mackerelio/go-osstat v0.2.7 - Apache-2.0 + + +Copyright 2017-2019 Hatena Co., Ltd. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +--------------------------------------------------------- + +--------------------------------------------------------- + +parcel-bundler/watcher 8926bb8b281733bbfcaf69bb4e62ab7a1431c42a - MIT + + +Copyright Node.js contributors +Copyright 2012-2020 Facebook, Inc. +Copyright (c) 2017-present Devon Govett + +MIT License + +Copyright (c) 2017-present Devon Govett + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +--------------------------------------------------------- diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..1609372a --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2024 @@ +{ + "name": "archflow-mcp-server", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "archflow-mcp-server", + "version": "0.0.0", + "dependencies": { + "ajv": "8.20.0", + "ajv-formats": "3.0.1", + "yaml": "2.9.0", + "zod": "4.4.3" + }, + "devDependencies": { + "@types/node": "24.13.3", + "esbuild": "0.28.1", + "typescript": "7.0.2", + "vite": "7.3.6", + "vitest": "4.1.10" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.3.tgz", + "integrity": "sha512-c0wdcekXtQvvn5Tsrk/+op/gUArrbWaFduBnTLP2l1cKLSQs4diMWjJw3m6A0DdzT8dAAX95KpkJ3qynCePbmw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.3.tgz", + "integrity": "sha512-3YjElDdWN+qXAFbJ/CzPV+0wspLqh54k/I6GfdYtEJRqg7buSgc1yPM3B+93j1M4neobtkATHZTmxK2AMVGfnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.3.tgz", + "integrity": "sha512-Pch2pFNOxxz1hTjypIdPyRTR6riiwRl84+VcN9djS680fw+Co1nAJINrdpqp7KV0NvyuU8ilZXZCjd7ykJl1GQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.3.tgz", + "integrity": "sha512-LEuncFUHFiF8t4yZVZvvZA1wk0pjAscRnsrn1EfTEmN4HXotBi2YtcnLRyaK6UbuczW7xZS5ES+81Rdz8Z0T6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.3.tgz", + "integrity": "sha512-zvBUvsQUpOWALdDsk6qbS8bXf2VxmPisuudNDrY7x0p0jBdsoZl8HsHczIOgkQiZldmcacMKtBzpoGVNeIe2bQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.3.tgz", + "integrity": "sha512-C2KmNrcSem/AMg984H/dev+si0lieQGdXdR/lYGJnuumXnFb9Y7QdiI62obFdLlxRYLBv4P0eUVIDbD4c1vVvw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.3.tgz", + "integrity": "sha512-ggXnsTAEzNQx74XpunRsiZ9aBZDsI7XIa0hm2nzR9f4WzH5/f/d73ZSDaC5ejJ8YLY4NW+V3wr0tjOaeCq8hqA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.3.tgz", + "integrity": "sha512-2vng+FlzNUhKZxtej3IUqJgbZoQk2M/dwQM20+ULV0R/E/8tr9/P6uEf2iiGIk4HL0zMKh5Jry7mUHdUOvyGgA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.3.tgz", + "integrity": "sha512-LLLFZKt4/Nraf9rxDkhiU8QVgLF4WmCkfr0L4fj0fPfIZFBib0DeiFk1hhaYKd03LFAFJcxHslhDFlNJLylf5Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.3.tgz", + "integrity": "sha512-WJkdQCvS9sWNOUBJZfQRKpZGFBztRzcowI+nndmflKgU4XY+3a420FgTOSKTsVqJbnzSxeT4vaJalpOaPo2YCQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.3.tgz", + "integrity": "sha512-PwHXCCS2n64/1Ot6rP1YEYA02MGYBcQlr8CSZZyrUG2O7NH6NklYmvr9v3Jy+5e/eDeNchc/ukmKJi9LuflMIQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.3.tgz", + "integrity": "sha512-vUjxINQu3RC8NZS3ykk1gN65gIz8pAopOq2HXuZhiIxHdx7TFvDG+jgrdSgInu1Eza4/Rfi2VzZgyIgEH4WOaw==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.3.tgz", + "integrity": "sha512-wzko4aJ13+0G3kGnviCg5gnXFKd40izKsrf2uOw12US4XqprkDrmwOpeW14aSNa37V8bfPcz5Fkob6LZ3BAPmA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.3.tgz", + "integrity": "sha512-8120ue0JUMSwy11stlwnfdX3pPd+WZYGCDBwEHWtIHi6pOpZmsEF5QKB7a/UN+XFdqvobxz98kv8RTqikyCEBw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.3.tgz", + "integrity": "sha512-XLFHnR3tXMjbOCh2vtVJHmxt+995uJsTERQyseFDRA0xxMxyTZPLa3OIUlyFaO4mF/Lu0FjmWHCuPXJT1n/IOg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.3.tgz", + "integrity": "sha512-se6yXvNGMIl0f+RQzyh7XAmia8/9kplQx424wnG2w0C1oi6XgO6Y8otKhdXFHbHs88Ihavzmvh1NWjuovE76BQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.3.tgz", + "integrity": "sha512-gNoxRefktVIiGflpONuxWWXZAzIQG++z9qHO3xKwk4WdDMuQja3JHGfE1u0i3PfPDyvhypdk+WrgIJqLhGG7sg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.3.tgz", + "integrity": "sha512-V4KtWtQfAFMU7+9/A/VDps/VI8CHd3cYz0L8sgJzz8qK7eY7wI4ruFD82UYIYvW9Z4DtlTfhQcsl4XyPHW5uSg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.3.tgz", + "integrity": "sha512-LBx9LYXvj2CBkMkjLdNAWLwH0MLMin7do2VcVo9kVPibGLkY0BQQut2fv7NVqkXqZ/CrAu9LqDHVV1xHCMpCPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.3.tgz", + "integrity": "sha512-ABVf3Q0RCu7NcyCCOZQI0pJ3GuSdfSl8EXcy88QtdceIMIoCUdfhsJChZ64L9zVM2aJHjde1Bhn5uqSRcX9ySA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.3.tgz", + "integrity": "sha512-+2Cy/ldweGBLlPIKsQLF8U5N44a0KDdbrk1rAjHOM9M2K+kGdIVjHLmmrZIcx+9Ny3ke/1JomCsDI1ocb11+sg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.3.tgz", + "integrity": "sha512-dtZvzc8BedpSaFNy75x6uiWwAGTH+aZHDtdrqP6qk+WcLJrfti6sGje1ZJ9UxyzDLF23d/mV+PaMwuC0hL7UVA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.3.tgz", + "integrity": "sha512-Rj8Ra4noo+aYy7sKBggCx0407mws34kAb1ySyWuq5DAtFBQdkSwnsjCgPrhPe9cvgBKZIukpE+CVHvORCS93kQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.3.tgz", + "integrity": "sha512-vp7N084ew/odXn2gi/mzm9mUkQu9l6AiN6dt4IeUM2Uvm9o+cVmP+YkqbMOteLbiGgqBBlJZjIMYVCfOOIVbVQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.3.tgz", + "integrity": "sha512-MOG/3gTOn4Fwf574RVOaY61I5o6P90legkFADiTyn1hyjNydT+cerU2rLUwPdZkKKyJ+iT+K9p7WXK4LM1Ka6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.13.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz", + "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitest/expect": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz", + "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.10", + "@vitest/utils": "4.1.10", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz", + "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.10", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz", + "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz", + "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.10", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz", + "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.10", + "@vitest/utils": "4.1.10", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz", + "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz", + "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.10", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-module-lexer": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.1.tgz", + "integrity": "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz", + "integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/nanoid": { + "version": "3.3.16", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz", + "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", + "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.23", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz", + "integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.16", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.62.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.3.tgz", + "integrity": "sha512-Gu0c0iH9FzgX1L1t7ByIbbS3Vmdz+6KHm/EsqmmC71gUQ82yvZRkTK6XzrFObSka91WUVdynqp6nsfilzr5k6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.62.3", + "@rollup/rollup-android-arm64": "4.62.3", + "@rollup/rollup-darwin-arm64": "4.62.3", + "@rollup/rollup-darwin-x64": "4.62.3", + "@rollup/rollup-freebsd-arm64": "4.62.3", + "@rollup/rollup-freebsd-x64": "4.62.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.62.3", + "@rollup/rollup-linux-arm-musleabihf": "4.62.3", + "@rollup/rollup-linux-arm64-gnu": "4.62.3", + "@rollup/rollup-linux-arm64-musl": "4.62.3", + "@rollup/rollup-linux-loong64-gnu": "4.62.3", + "@rollup/rollup-linux-loong64-musl": "4.62.3", + "@rollup/rollup-linux-ppc64-gnu": "4.62.3", + "@rollup/rollup-linux-ppc64-musl": "4.62.3", + "@rollup/rollup-linux-riscv64-gnu": "4.62.3", + "@rollup/rollup-linux-riscv64-musl": "4.62.3", + "@rollup/rollup-linux-s390x-gnu": "4.62.3", + "@rollup/rollup-linux-x64-gnu": "4.62.3", + "@rollup/rollup-linux-x64-musl": "4.62.3", + "@rollup/rollup-openbsd-x64": "4.62.3", + "@rollup/rollup-openharmony-arm64": "4.62.3", + "@rollup/rollup-win32-arm64-msvc": "4.62.3", + "@rollup/rollup-win32-ia32-msvc": "4.62.3", + "@rollup/rollup-win32-x64-gnu": "4.62.3", + "@rollup/rollup-win32-x64-msvc": "4.62.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", + "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz", + "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "7.3.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", + "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0 || ^0.28.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz", + "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.10", + "@vitest/mocker": "4.1.10", + "@vitest/pretty-format": "4.1.10", + "@vitest/runner": "4.1.10", + "@vitest/snapshot": "4.1.10", + "@vitest/spy": "4.1.10", + "@vitest/utils": "4.1.10", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.10", + "@vitest/browser-preview": "4.1.10", + "@vitest/browser-webdriverio": "4.1.10", + "@vitest/coverage-istanbul": "4.1.10", + "@vitest/coverage-v8": "4.1.10", + "@vitest/ui": "4.1.10", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..1e028b05 --- /dev/null +++ b/package.json @@ -0,0 +1,30 @@ +{ + "name": "archflow-mcp-server", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vitest run", + "test:unit": "vitest run test/unit", + "test:contracts": "vitest run test/contracts", + "build:temp": "node scripts/build-temp.mjs && node scripts/smoke-temp-bundle.mjs", + "check:dependencies": "node scripts/check-dependency-policy.mjs", + "check:notices": "node scripts/check-notices.mjs", + "test:notices-policy": "node scripts/test-notices-policy.mjs", + "check": "npm run typecheck && npm test && npm run test:contracts && npm run build:temp && npm run check:dependencies && npm run check:notices && npm run test:notices-policy" + }, + "dependencies": { + "ajv": "8.20.0", + "ajv-formats": "3.0.1", + "yaml": "2.9.0", + "zod": "4.4.3" + }, + "devDependencies": { + "@types/node": "24.13.3", + "esbuild": "0.28.1", + "typescript": "7.0.2", + "vite": "7.3.6", + "vitest": "4.1.10" + } +} diff --git a/scripts/build-temp.mjs b/scripts/build-temp.mjs new file mode 100644 index 00000000..47dc8356 --- /dev/null +++ b/scripts/build-temp.mjs @@ -0,0 +1,14 @@ +import { build } from "esbuild"; + +await build({ + entryPoints: ["src/contracts/index.ts"], + outfile: ".tmp/archflow-contracts.mjs", + bundle: true, + platform: "node", + format: "esm", + target: "node24", + sourcemap: true, + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' + } +}); diff --git a/scripts/check-dependency-policy.mjs b/scripts/check-dependency-policy.mjs new file mode 100644 index 00000000..0d764587 --- /dev/null +++ b/scripts/check-dependency-policy.mjs @@ -0,0 +1,102 @@ +import { readFile } from "node:fs/promises"; + +const expectedRuntime = Object.freeze({ + ajv: "8.20.0", + "ajv-formats": "3.0.1", + yaml: "2.9.0", + zod: "4.4.3" +}); +const expectedDevelopment = Object.freeze({ + "@types/node": "24.13.3", + esbuild: "0.28.1", + typescript: "7.0.2", + vite: "7.3.6", + vitest: "4.1.10" +}); +const approvedLicenses = new Set([ + "0BSD", + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "ISC", + "MIT" +]); +const prohibitedLaterPhasePackages = new Set([ + "@anthropic-ai/sandbox-runtime", + "@modelcontextprotocol/server", + "execa", + "proper-lockfile", + "write-file-atomic" +]); + +const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")); +const lock = JSON.parse(await readFile(new URL("../package-lock.json", import.meta.url), "utf8")); +const failures = []; + +function compareDirect(actual, expected, label) { + const actualEntries = Object.entries(actual ?? {}).sort(([a], [b]) => a.localeCompare(b)); + const expectedEntries = Object.entries(expected).sort(([a], [b]) => a.localeCompare(b)); + if (JSON.stringify(actualEntries) !== JSON.stringify(expectedEntries)) { + failures.push(`${label} must contain exactly ${JSON.stringify(expected)}`); + } + for (const [name, version] of actualEntries) { + if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(String(version))) { + failures.push(`${label} dependency ${name} is not an exact version: ${version}`); + } + } +} + +if (packageJson.private !== true || packageJson.type !== "module") { + failures.push("package.json must describe a private ESM package"); +} +compareDirect(packageJson.dependencies, expectedRuntime, "runtime"); +compareDirect(packageJson.devDependencies, expectedDevelopment, "development"); +for (const field of ["optionalDependencies", "peerDependencies", "bundledDependencies", "bundleDependencies"]) { + if (packageJson[field] !== undefined) { + failures.push(`package.json must not declare direct packages through ${field}`); + } +} + +if (lock.lockfileVersion !== 3 || lock.requires !== true) { + failures.push("package-lock.json must be an npm lockfileVersion 3 exact lock"); +} +const root = lock.packages?.[""]; +compareDirect(root?.dependencies, expectedRuntime, "lockfile root runtime"); +compareDirect(root?.devDependencies, expectedDevelopment, "lockfile root development"); +for (const field of ["optionalDependencies", "peerDependencies", "bundledDependencies", "bundleDependencies"]) { + if (root?.[field] !== undefined) { + failures.push(`lockfile root must not declare direct packages through ${field}`); + } +} + +function packageNameFromPath(path, metadata) { + if (metadata.name) return metadata.name; + const marker = "node_modules/"; + const index = path.lastIndexOf(marker); + return index === -1 ? "" : path.slice(index + marker.length); +} + +for (const [path, metadata] of Object.entries(lock.packages ?? {})) { + if (path === "") continue; + const name = packageNameFromPath(path, metadata); + if (!name || !metadata.version || !metadata.integrity || !metadata.resolved) { + failures.push(`incomplete exact-lock metadata at ${path}`); + continue; + } + if (name === "lightningcss" || name.startsWith("lightningcss-")) { + failures.push(`prohibited Lightning CSS package resolved: ${name}@${metadata.version}`); + } + if (prohibitedLaterPhasePackages.has(name)) { + failures.push(`later-phase package resolved early: ${name}@${metadata.version}`); + } + if (!approvedLicenses.has(metadata.license)) { + failures.push(`unreviewed or non-permissive license ${String(metadata.license)} at ${name}@${metadata.version}`); + } +} + +if (failures.length > 0) { + console.error(failures.map((failure) => `- ${failure}`).join("\n")); + process.exitCode = 1; +} else { + console.log(`Dependency policy passed for ${Object.keys(lock.packages).length - 1} locked package entries.`); +} diff --git a/scripts/check-notices.mjs b/scripts/check-notices.mjs new file mode 100644 index 00000000..96015508 --- /dev/null +++ b/scripts/check-notices.mjs @@ -0,0 +1,156 @@ +import { createHash } from "node:crypto"; +import { access, readFile, readdir } from "node:fs/promises"; +import { constants } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const options = parseOptions(process.argv.slice(2)); +const lockPath = resolve(options.lock ?? `${repositoryRoot}/package-lock.json`); +const inventoryPath = resolve(options.inventory ?? `${repositoryRoot}/THIRD_PARTY_NOTICES.md`); +const noticeRoot = resolve(options.noticeRoot ?? repositoryRoot); +const installedRoot = resolve(options.installedRoot ?? `${repositoryRoot}/node_modules`); + +const lock = JSON.parse(await readFile(lockPath, "utf8")); +const inventory = await readFile(inventoryPath, "utf8"); +const failures = []; + +function parseOptions(args) { + const parsed = {}; + for (let index = 0; index < args.length; index += 2) { + const flag = args[index]; + const value = args[index + 1]; + if (value === undefined) throw new Error(`missing value for ${flag}`); + if (flag === "--lock") parsed.lock = value; + else if (flag === "--inventory") parsed.inventory = value; + else if (flag === "--notice-root") parsed.noticeRoot = value; + else if (flag === "--installed-root") parsed.installedRoot = value; + else throw new Error(`unknown option ${flag}`); + } + return parsed; +} + +function packageNameFromPath(path, metadata) { + if (metadata.name) return metadata.name; + const marker = "node_modules/"; + const index = path.lastIndexOf(marker); + return index === -1 ? "" : path.slice(index + marker.length); +} + +function digest(content) { + return createHash("sha256").update(content).digest("hex"); +} + +function isNoticeFilename(filename) { + return /^(?:notice|third[-_ ]?party)(?:\.|$)/iu.test(filename); +} + +const lockedPackages = new Map(); +const expectedSpdx = new Set(); +for (const [path, metadata] of Object.entries(lock.packages ?? {})) { + if (path === "") continue; + const name = packageNameFromPath(path, metadata); + const identity = `${name}@${metadata.version}`; + lockedPackages.set(identity, { path, name, metadata }); + expectedSpdx.add(`${identity} | ${metadata.license}`); +} + +const recordedSpdx = new Set( + [...inventory.matchAll(/^\| `([^`]+)` \| `([^`]+)` \|$/gm)].map((match) => `${match[1]} | ${match[2]}`) +); +for (const entry of [...expectedSpdx].filter((value) => !recordedSpdx.has(value)).sort()) { + failures.push(`missing SPDX inventory entry: ${entry}`); +} +for (const entry of [...recordedSpdx].filter((value) => !expectedSpdx.has(value)).sort()) { + failures.push(`stale SPDX inventory entry: ${entry}`); +} + +const retainedMappings = new Map(); +for (const match of inventory.matchAll( + /^\| `([^`]+)` \| `([a-f0-9]{64})` \| `([^`]+)` \| `([a-f0-9]{64})` \|$/gm +)) { + retainedMappings.set(match[1], { + sourceDigest: match[2], + retainedPath: match[3], + retainedDigest: match[4] + }); +} + +const reviewedTypeScriptPackages = new Set( + [...lockedPackages.keys()].filter( + (identity) => identity === "typescript@7.0.2" || /^@typescript\/typescript-[^@]+@7\.0\.2$/u.test(identity) + ) +); +for (const identity of reviewedTypeScriptPackages) { + if (!retainedMappings.has(identity)) failures.push(`missing retained NOTICE mapping: ${identity}`); +} +for (const identity of retainedMappings.keys()) { + if (!lockedPackages.has(identity)) failures.push(`retained NOTICE mapping is not in the lock: ${identity}`); +} + +const verifiedAssets = new Set(); +for (const [identity, mapping] of retainedMappings) { + const assetKey = `${mapping.retainedPath}|${mapping.retainedDigest}`; + if (!verifiedAssets.has(assetKey)) { + let content; + try { + content = await readFile(resolve(noticeRoot, mapping.retainedPath)); + } catch { + failures.push(`missing retained NOTICE asset: ${mapping.retainedPath}`); + continue; + } + const actualDigest = digest(content); + if (actualDigest !== mapping.retainedDigest) { + failures.push(`retained NOTICE digest mismatch for ${mapping.retainedPath}: ${actualDigest}`); + } + verifiedAssets.add(assetKey); + } + + const locked = lockedPackages.get(identity); + if (locked === undefined) continue; + const packageDirectory = resolve(installedRoot, locked.path.replace(/^node_modules\//u, "")); + try { + await access(packageDirectory, constants.R_OK); + } catch { + continue; + } + const noticeFiles = (await readdir(packageDirectory)).filter(isNoticeFilename); + if (noticeFiles.length === 0) { + failures.push(`installed package is missing its reviewed NOTICE: ${identity}`); + continue; + } + for (const filename of noticeFiles) { + const installedDigest = digest(await readFile(resolve(packageDirectory, filename))); + if (installedDigest !== mapping.sourceDigest) { + failures.push(`installed NOTICE digest mismatch for ${identity}/${filename}: ${installedDigest}`); + } + } +} + +try { + await access(installedRoot, constants.R_OK); + for (const [identity, locked] of lockedPackages) { + const packageDirectory = resolve(installedRoot, locked.path.replace(/^node_modules\//u, "")); + let entries; + try { + entries = await readdir(packageDirectory); + } catch { + continue; + } + const noticeFiles = entries.filter(isNoticeFilename); + if (noticeFiles.length > 0 && !retainedMappings.has(identity)) { + failures.push(`installed package has an unreviewed standalone notice: ${identity} (${noticeFiles.join(", ")})`); + } + } +} catch { + failures.push(`cannot inventory installed dependencies at ${installedRoot}; run npm ci first`); +} + +if (failures.length > 0) { + console.error(failures.map((failure) => `- ${failure}`).join("\n")); + process.exitCode = 1; +} else { + console.log( + `Notices passed for ${expectedSpdx.size} locked SPDX entries and ${retainedMappings.size} reviewed package NOTICE mappings.` + ); +} diff --git a/scripts/smoke-temp-bundle.mjs b/scripts/smoke-temp-bundle.mjs new file mode 100644 index 00000000..ca9375e3 --- /dev/null +++ b/scripts/smoke-temp-bundle.mjs @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; + +const contracts = await import(new URL("../.tmp/archflow-contracts.mjs", import.meta.url)); + +assert.deepEqual( + contracts.parseSingleYamlDocument("name: archflow\nenabled: true\n", "bundle-smoke.yaml"), + { name: "archflow", enabled: true } +); + +const validator = contracts.createJsonSchemaValidator({ + $schema: "https://json-schema.org/draft/2020-12/schema", + type: "object", + additionalProperties: false, + required: ["id", "uri"], + properties: { + id: { type: "integer", minimum: 1 }, + uri: { type: "string", format: "uri" } + } +}); +assert.deepEqual(validator.assert({ id: 1, uri: "https://example.test/contract" }, "bundle-smoke"), { + id: 1, + uri: "https://example.test/contract" +}); +assert.throws(() => validator.assert({ id: 0, uri: "not a URI" }, "bundle-smoke")); +assert.equal(contracts.parsePositiveSafePhaseNumber(1), 1); + +console.log(`Temporary contract bundle loaded and exercised under ${process.version}.`); diff --git a/scripts/test-notices-policy.mjs b/scripts/test-notices-policy.mjs new file mode 100644 index 00000000..08ce400e --- /dev/null +++ b/scripts/test-notices-policy.mjs @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import { cp, mkdir, mkdtemp, rm, unlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); +const temporaryRoot = await mkdtemp(resolve(tmpdir(), "archflow-notices-policy-")); +const retainedPath = "notices/typescript-7.0.2-NOTICE.txt"; + +function runCheck(installedRoot = `${repositoryRoot}/node_modules`) { + return spawnSync( + process.execPath, + [ + `${repositoryRoot}/scripts/check-notices.mjs`, + "--lock", + `${repositoryRoot}/package-lock.json`, + "--inventory", + `${repositoryRoot}/THIRD_PARTY_NOTICES.md`, + "--notice-root", + temporaryRoot, + "--installed-root", + installedRoot + ], + { encoding: "utf8" } + ); +} + +try { + await cp(`${repositoryRoot}/notices`, `${temporaryRoot}/notices`, { recursive: true }); + assert.equal(runCheck().status, 0, "copied retained notices should pass policy"); + + await writeFile(`${temporaryRoot}/${retainedPath}`, "changed notice\n"); + const changed = runCheck(); + assert.notEqual(changed.status, 0, "changed retained notice must fail policy"); + assert.match(changed.stderr, /retained NOTICE digest mismatch/u); + + await cp(`${repositoryRoot}/${retainedPath}`, `${temporaryRoot}/${retainedPath}`); + await unlink(`${temporaryRoot}/${retainedPath}`); + const missing = runCheck(); + assert.notEqual(missing.status, 0, "missing retained notice must fail policy"); + assert.match(missing.stderr, /missing retained NOTICE asset/u); + + await cp(`${repositoryRoot}/${retainedPath}`, `${temporaryRoot}/${retainedPath}`); + const syntheticInstalledRoot = `${temporaryRoot}/installed`; + await mkdir(`${syntheticInstalledRoot}/ajv`, { recursive: true }); + await writeFile(`${syntheticInstalledRoot}/ajv/NOTICE.txt`, "unexpected unmapped notice\n"); + const unmapped = runCheck(syntheticInstalledRoot); + assert.notEqual(unmapped.status, 0, "unexpected package notice must fail policy"); + assert.match(unmapped.stderr, /unreviewed standalone notice/u); + + console.log("Notice policy mutation checks rejected changed, missing, and unmapped notice content."); +} finally { + await rm(temporaryRoot, { recursive: true, force: true }); +} diff --git a/src/contracts/config.ts b/src/contracts/config.ts new file mode 100644 index 00000000..1290ab49 --- /dev/null +++ b/src/contracts/config.ts @@ -0,0 +1,45 @@ +import { z } from "zod"; + +import { assertPlainJson } from "./plain-json.js"; +import { parseSingleYamlDocument } from "./yaml.js"; + +export const ROUTING_ROLES = ["producer", "self-reviewer", "counter-reviewer", "adjudicator"] as const; +export const REASONING_EFFORTS = ["low", "medium", "high", "xhigh", "max", "ultra"] as const; + +const routeSchema = z.object({ + model: z.string().min(1).refine((value) => value.trim().length > 0, "model must contain a non-whitespace character"), + effort: z.enum(REASONING_EFFORTS), +}).strict(); + +const rolesSchema = z.object({ + producer: routeSchema.optional(), + "self-reviewer": routeSchema.optional(), + "counter-reviewer": routeSchema.optional(), + adjudicator: routeSchema.optional(), +}).strict(); + +const overridesSchema = z.object({ + explore: rolesSchema.optional(), + prd: rolesSchema.optional(), + design: rolesSchema.optional(), + "phase-design": rolesSchema.optional(), + "phase-impl": rolesSchema.optional(), +}).strict(); + +export const configV1Schema = z.object({ + schema_version: z.literal("1"), + roles: rolesSchema, + overrides: overridesSchema.optional(), +}).strict(); + +export type ModelRouteV1 = z.infer; +export type ConfigV1 = z.infer; + +export function parseConfigV1(value: unknown): ConfigV1 { + assertPlainJson(value, "config"); + return configV1Schema.parse(value); +} + +export function parseConfigYaml(source: string, label = "config.yaml"): ConfigV1 { + return parseConfigV1(parseSingleYamlDocument(source, label)); +} diff --git a/src/contracts/constitution.ts b/src/contracts/constitution.ts new file mode 100644 index 00000000..e08467e8 --- /dev/null +++ b/src/contracts/constitution.ts @@ -0,0 +1,75 @@ +import { z } from "zod"; + +import { assertPlainJson } from "./plain-json.js"; +import { parseSingleYamlDocument } from "./yaml.js"; + +export interface ConstitutionRuleV1 { + readonly id: string; + readonly version: number; + readonly status: "active" | "deprecated"; + readonly text: string; + readonly review_trigger?: string; + readonly enforced_by?: readonly string[]; +} + +export type ConstitutionRegistry = ReadonlyMap; + +const frontmatterSchema = z.object({ + id: z.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/), + version: z.number().int().positive().safe(), + status: z.enum(["active", "deprecated"]), + review_trigger: z.string().min(1).refine((value) => value.trim().length > 0, "review_trigger must contain a non-whitespace character").optional(), + enforced_by: z.array(z.string().min(1).refine((value) => value.trim().length > 0, "enforced_by entries must contain a non-whitespace character")).min(1).optional(), +}).strict(); + +export const constitutionRuleV1Schema = frontmatterSchema.extend({ text: z.string().min(1).refine((value) => value.trim().length > 0, "text must contain a non-whitespace character") }).strict(); + +export function parseConstitutionRuleV1(value: unknown): ConstitutionRuleV1 { + assertPlainJson(value, "constitution rule"); + const parsed = constitutionRuleV1Schema.parse(value); + return { + id: parsed.id, + version: parsed.version, + status: parsed.status, + text: parsed.text, + ...(parsed.review_trigger === undefined ? {} : { review_trigger: parsed.review_trigger }), + ...(parsed.enforced_by === undefined ? {} : { enforced_by: parsed.enforced_by }), + }; +} + +export function parseConstitutionRuleMarkdown(source: string, label: string): ConstitutionRuleV1 { + const normalized = source.replaceAll("\r\n", "\n"); + if (!normalized.startsWith("---\n")) throw new Error(`${label}: expected opening YAML frontmatter delimiter`); + const close = normalized.indexOf("\n---\n", 4); + if (close < 0) throw new Error(`${label}: expected closing YAML frontmatter delimiter`); + const frontmatter = parseSingleYamlDocument(normalized.slice(4, close), `${label} frontmatter`); + const text = normalized.slice(close + 5).trim(); + return parseConstitutionRuleV1({ ...frontmatter as object, text }); +} + +function registryFromRules(rules: readonly ConstitutionRuleV1[]): Map { + const registry = new Map(); + for (const candidate of rules) { + const rule = parseConstitutionRuleV1(candidate); + if (registry.has(rule.id)) throw new Error(`Duplicate constitution rule id: ${rule.id}`); + registry.set(rule.id, Object.freeze(rule)); + } + return registry; +} + +export function parseConstitutionRuleFiles(files: Readonly>): ConstitutionRegistry { + return registryFromRules(Object.keys(files).sort().map((path) => parseConstitutionRuleMarkdown(files[path]!, path))); +} + +export function validateConstitutionEvolution(previous: ConstitutionRegistry, candidate: readonly ConstitutionRuleV1[]): ConstitutionRegistry { + const next = registryFromRules(candidate); + for (const [id, prior] of previous) { + const current = next.get(id); + if (!current) throw new Error(`Constitution rule ${id} cannot be deleted or reused`); + if (prior.status === "deprecated" && current.status === "active") throw new Error(`Deprecated constitution rule ${id} cannot be reactivated`); + const contentChanged = prior.status !== current.status || prior.text !== current.text || prior.review_trigger !== current.review_trigger || JSON.stringify(prior.enforced_by) !== JSON.stringify(current.enforced_by); + if (contentChanged && current.version <= prior.version) throw new Error(`Changed constitution rule ${id} must increment its version`); + if (!contentChanged && current.version !== prior.version) throw new Error(`Unchanged constitution rule ${id} must retain its version`); + } + return next; +} diff --git a/src/contracts/index.ts b/src/contracts/index.ts new file mode 100644 index 00000000..fdd218a9 --- /dev/null +++ b/src/contracts/index.ts @@ -0,0 +1,10 @@ +export * from "./versions.js"; +export * from "./plain-json.js"; +export * from "./validators.js"; +export * from "./phase-instance.js"; +export * from "./yaml.js"; +export * from "./workflow.js"; +export type { IterationPolicy } from "./vocabulary.js"; +export * from "./config.js"; +export * from "./rubric.js"; +export * from "./constitution.js"; diff --git a/src/contracts/phase-instance.ts b/src/contracts/phase-instance.ts new file mode 100644 index 00000000..3a8fbc25 --- /dev/null +++ b/src/contracts/phase-instance.ts @@ -0,0 +1,42 @@ +declare const positiveSafePhaseBrand: unique symbol; +declare const phaseInstanceIdBrand: unique symbol; + +export type PositiveSafePhaseNumber = number & { readonly [positiveSafePhaseBrand]: true }; +export type PhaseInstanceId = string & { readonly [phaseInstanceIdBrand]: true }; + +export type PhaseInstance = + | { readonly kind: "prd" } + | { readonly kind: "design" } + | { readonly kind: "phase-design"; readonly phase: PositiveSafePhaseNumber } + | { readonly kind: "phase-impl"; readonly phase: PositiveSafePhaseNumber }; + +export function parsePositiveSafePhaseNumber(value: unknown): PositiveSafePhaseNumber { + if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) { + throw new TypeError("phase number must be a positive safe integer"); + } + return value as PositiveSafePhaseNumber; +} + +export function encodePhaseInstance(value: PhaseInstance): PhaseInstanceId { + switch (value.kind) { + case "prd": + case "design": + return value.kind as PhaseInstanceId; + case "phase-design": + case "phase-impl": { + const phase = parsePositiveSafePhaseNumber(value.phase); + return `${value.kind}-${phase}` as PhaseInstanceId; + } + } +} + +const ITERATED_PHASE = /^(phase-design|phase-impl)-([1-9][0-9]*)$/u; + +export function decodePhaseInstance(value: unknown): PhaseInstance { + if (value === "prd" || value === "design") return { kind: value }; + if (typeof value !== "string") throw new TypeError("phase instance must be a canonical string"); + const match = ITERATED_PHASE.exec(value); + if (match === null) throw new TypeError("phase instance must use a canonical phase encoding"); + const phase = parsePositiveSafePhaseNumber(Number(match[2])); + return match[1] === "phase-design" ? { kind: "phase-design", phase } : { kind: "phase-impl", phase }; +} diff --git a/src/contracts/plain-json.ts b/src/contracts/plain-json.ts new file mode 100644 index 00000000..663ab281 --- /dev/null +++ b/src/contracts/plain-json.ts @@ -0,0 +1,115 @@ +export type PlainJsonPrimitive = string | number | boolean | null; +export type PlainJsonValue = PlainJsonPrimitive | readonly PlainJsonValue[] | PlainJsonObject; +export interface PlainJsonObject { + readonly [key: string]: PlainJsonValue; +} + +const DANGEROUS_KEYS = new Set(["__proto__", "prototype", "constructor"]); + +export class PlainJsonError extends TypeError { + public constructor(message: string, public readonly path: string) { + super(`${message} at ${path}`); + this.name = "PlainJsonError"; + } +} + +function childPath(path: string, key: string): string { + return /^[A-Za-z_$][\w$]*$/u.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`; +} + +function fail(message: string, path: string): never { + throw new PlainJsonError(message, path); +} + +function assertDescriptorStable( + object: object, + key: PropertyKey, + before: PropertyDescriptor, + path: string +): void { + const after = Object.getOwnPropertyDescriptor(object, key); + if ( + after === undefined || + after.configurable !== before.configurable || + after.enumerable !== before.enumerable || + after.writable !== before.writable || + after.value !== before.value || + after.get !== before.get || + after.set !== before.set + ) { + fail("value mutated while it was being inspected", path); + } +} + +function inspect(value: unknown, path: string, ancestors: WeakSet): void { + if (value === null || typeof value === "string" || typeof value === "boolean") return; + if (typeof value === "number") { + if (!Number.isFinite(value)) fail("non-finite numbers are not JSON values", path); + return; + } + if (typeof value !== "object") fail(`unsupported ${typeof value} value`, path); + + const object = value as object; + if (ancestors.has(object)) fail("cyclic references are not JSON values", path); + + const isArray = Array.isArray(object); + const prototype = Object.getPrototypeOf(object); + if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) { + fail("objects must have a plain prototype", path); + } + + const keys = Reflect.ownKeys(object); + if (keys.some((key) => typeof key === "symbol")) fail("symbol keys are not JSON object keys", path); + + ancestors.add(object); + try { + if (isArray) { + const array = object as unknown[]; + const expectedKeys = new Set(["length", ...Array.from({ length: array.length }, (_, index) => String(index))]); + for (const key of keys) { + if (typeof key !== "string" || !expectedKeys.has(key)) fail("arrays may only contain indexed elements", path); + } + for (let index = 0; index < array.length; index += 1) { + if (!Object.prototype.hasOwnProperty.call(array, index)) fail("sparse array holes are not JSON values", `${path}[${index}]`); + const descriptor = Object.getOwnPropertyDescriptor(array, String(index)); + if (descriptor === undefined || !("value" in descriptor)) fail("accessor properties are not JSON values", `${path}[${index}]`); + inspect(descriptor.value, `${path}[${index}]`, ancestors); + assertDescriptorStable(array, String(index), descriptor, `${path}[${index}]`); + } + } else { + for (const key of keys as string[]) { + const propertyPath = childPath(path, key); + if (DANGEROUS_KEYS.has(key)) fail(`dangerous own key ${JSON.stringify(key)} is forbidden`, propertyPath); + const descriptor = Object.getOwnPropertyDescriptor(object, key); + if (descriptor === undefined || !("value" in descriptor)) fail("accessor properties are not JSON values", propertyPath); + if (!descriptor.enumerable) fail("non-enumerable properties are not JSON values", propertyPath); + inspect(descriptor.value, propertyPath, ancestors); + assertDescriptorStable(object, key, descriptor, propertyPath); + } + } + const afterKeys = Reflect.ownKeys(object); + if (keys.length !== afterKeys.length || keys.some((key, index) => key !== afterKeys[index])) { + fail("value mutated while it was being inspected", path); + } + } finally { + ancestors.delete(object); + } +} + +export function assertPlainJson(value: unknown, label = "value"): asserts value is PlainJsonValue { + inspect(value, label, new WeakSet()); +} + +export function isPlainJsonValue(value: unknown): value is PlainJsonValue { + try { + assertPlainJson(value); + return true; + } catch { + return false; + } +} + +export function parsePlainJson(value: unknown, label = "value"): PlainJsonValue { + assertPlainJson(value, label); + return value; +} diff --git a/src/contracts/rubric.ts b/src/contracts/rubric.ts new file mode 100644 index 00000000..4f6fc009 --- /dev/null +++ b/src/contracts/rubric.ts @@ -0,0 +1,40 @@ +import { z } from "zod"; + +import { assertPlainJson } from "./plain-json.js"; + +export interface RubricCriterionV1 { + readonly id: string; + readonly text: string; + readonly blocking: boolean; +} + +export interface RubricV1 { + readonly schema_version: "1"; + readonly kind: "artifact" | "implementation"; + readonly mode: "self_review" | "adversarial"; + readonly criteria: readonly RubricCriterionV1[]; +} + +export const rubricV1Schema = z.object({ + schema_version: z.literal("1"), + kind: z.enum(["artifact", "implementation"]), + mode: z.enum(["self_review", "adversarial"]), + criteria: z.array(z.object({ + id: z.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/), + text: z.string().min(1).refine((value) => value.trim().length > 0, "criterion text must contain a non-whitespace character"), + blocking: z.boolean(), + }).strict()).min(1), +}).strict().superRefine((rubric, context) => { + const seen = new Set(); + rubric.criteria.forEach((criterion, index) => { + if (seen.has(criterion.id)) { + context.addIssue({ code: "custom", path: ["criteria", index, "id"], message: `Duplicate criterion id: ${criterion.id}` }); + } + seen.add(criterion.id); + }); +}); + +export function parseRubricV1(value: unknown): RubricV1 { + assertPlainJson(value, "rubric"); + return rubricV1Schema.parse(value); +} diff --git a/src/contracts/schemas/v1/config.schema.json b/src/contracts/schemas/v1/config.schema.json new file mode 100644 index 00000000..8d7a1f21 --- /dev/null +++ b/src/contracts/schemas/v1/config.schema.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:config", + "$defs": { + "route": { "type": "object", "additionalProperties": false, "required": ["model", "effort"], "properties": { "model": { "type": "string", "minLength": 1, "pattern": "\\S" }, "effort": { "enum": ["low", "medium", "high", "xhigh", "max", "ultra"] } } }, + "roles": { "type": "object", "additionalProperties": false, "properties": { "producer": { "$ref": "#/$defs/route" }, "self-reviewer": { "$ref": "#/$defs/route" }, "counter-reviewer": { "$ref": "#/$defs/route" }, "adjudicator": { "$ref": "#/$defs/route" } } }, + "overrides": { "type": "object", "additionalProperties": false, "properties": { "explore": { "$ref": "#/$defs/roles" }, "prd": { "$ref": "#/$defs/roles" }, "design": { "$ref": "#/$defs/roles" }, "phase-design": { "$ref": "#/$defs/roles" }, "phase-impl": { "$ref": "#/$defs/roles" } } } + }, + "type": "object", "additionalProperties": false, "required": ["schema_version", "roles"], + "properties": { "schema_version": { "const": "1" }, "roles": { "$ref": "#/$defs/roles" }, "overrides": { "$ref": "#/$defs/overrides" } } +} diff --git a/src/contracts/schemas/v1/constitution-rule.schema.json b/src/contracts/schemas/v1/constitution-rule.schema.json new file mode 100644 index 00000000..ef6f3f3e --- /dev/null +++ b/src/contracts/schemas/v1/constitution-rule.schema.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:constitution-rule", + "type": "object", "additionalProperties": false, + "required": ["id", "version", "status", "text"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }, "version": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, "status": { "enum": ["active", "deprecated"] }, "text": { "type": "string", "minLength": 1, "pattern": "\\S" }, "review_trigger": { "type": "string", "minLength": 1, "pattern": "\\S" }, "enforced_by": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 1, "pattern": "\\S" } } + } +} diff --git a/src/contracts/schemas/v1/phase-instance.schema.json b/src/contracts/schemas/v1/phase-instance.schema.json new file mode 100644 index 00000000..d230cd69 --- /dev/null +++ b/src/contracts/schemas/v1/phase-instance.schema.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:phase-instance", + "oneOf": [ + { + "type": "object", + "properties": { "kind": { "const": "prd" } }, + "required": ["kind"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { "kind": { "const": "design" } }, + "required": ["kind"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { "const": "phase-design" }, + "phase": { "$ref": "urn:archflow:schema:v1:primitives#/$defs/positiveSafePhaseNumber" } + }, + "required": ["kind", "phase"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { "const": "phase-impl" }, + "phase": { "$ref": "urn:archflow:schema:v1:primitives#/$defs/positiveSafePhaseNumber" } + }, + "required": ["kind", "phase"], + "additionalProperties": false + } + ] +} diff --git a/src/contracts/schemas/v1/primitives.schema.json b/src/contracts/schemas/v1/primitives.schema.json new file mode 100644 index 00000000..e730bde0 --- /dev/null +++ b/src/contracts/schemas/v1/primitives.schema.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:primitives", + "$defs": { + "positiveSafePhaseNumber": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + } +} diff --git a/src/contracts/schemas/v1/rubric.schema.json b/src/contracts/schemas/v1/rubric.schema.json new file mode 100644 index 00000000..747ed248 --- /dev/null +++ b/src/contracts/schemas/v1/rubric.schema.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:rubric", + "type": "object", "additionalProperties": false, + "required": ["schema_version", "kind", "mode", "criteria"], + "properties": { + "schema_version": { "const": "1" }, "kind": { "enum": ["artifact", "implementation"] }, "mode": { "enum": ["self_review", "adversarial"] }, + "criteria": { "type": "array", "minItems": 1, "uniqueItems": true, "x-archflow-unique-by": "id", "items": { "type": "object", "additionalProperties": false, "required": ["id", "text", "blocking"], "properties": { "id": { "type": "string", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }, "text": { "type": "string", "minLength": 1, "pattern": "\\S" }, "blocking": { "type": "boolean" } } } } + } +} diff --git a/src/contracts/schemas/v1/workflow.schema.json b/src/contracts/schemas/v1/workflow.schema.json new file mode 100644 index 00000000..b0bcd579 --- /dev/null +++ b/src/contracts/schemas/v1/workflow.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:workflow", + "type": "object", + "additionalProperties": false, + "required": ["phases"], + "properties": { + "phases": { + "type": "array", "minItems": 5, "maxItems": 5, + "prefixItems": [ + { "const": { "id": "explore", "skill": "archflow-explore", "pipeline": ["produce"], "gate": "never", "optional": true } }, + { "const": { "id": "prd", "skill": "archflow-prd", "pipeline": ["produce", "self_review", "counter_review", "triage", "adjudicate"], "gate": "always" } }, + { "const": { "id": "design", "skill": "archflow-design", "requires": ["prd"], "pipeline": ["produce", "self_review", "counter_review", "triage", "adjudicate"], "gate": "always" } }, + { "const": { "id": "phase-design", "skill": "archflow-phase-design", "requires": ["design"], "iterates": "per_phase", "pipeline": ["produce", "self_review", "counter_review", "triage", "adjudicate"], "gate": "on_trigger" } }, + { "const": { "id": "phase-impl", "skill": "archflow-phase-impl", "requires": ["phase-design"], "iterates": "per_phase", "pipeline": ["produce", "self_review", "counter_review", "triage", "adjudicate"], "gate": "on_trigger" } } + ] + } + } +} diff --git a/src/contracts/validators.ts b/src/contracts/validators.ts new file mode 100644 index 00000000..19121cba --- /dev/null +++ b/src/contracts/validators.ts @@ -0,0 +1,114 @@ +import { isDeepStrictEqual } from "node:util"; +import { Ajv2020, type AnySchema, type ErrorObject, type ValidateFunction } from "ajv/dist/2020.js"; +import * as formatsModule from "ajv-formats"; +import type { FormatsPlugin } from "ajv-formats"; +import { assertPlainJson, type PlainJsonValue } from "./plain-json.js"; + +export interface JsonSchemaValidator { + readonly validate: ValidateFunction; + readonly assert: (value: unknown, label?: string) => T; +} + +export interface ZodLikeSchema { + safeParse(value: unknown): { success: true; data: T } | { success: false; error: unknown }; +} + +export class ContractValidationError extends TypeError { + public constructor(message: string, public readonly details?: unknown) { + super(message); + this.name = "ContractValidationError"; + } +} + +function formatAjvErrors(errors: ErrorObject[] | null | undefined): string { + if (errors === undefined || errors === null || errors.length === 0) return "schema validation failed"; + return errors.map((error) => `${error.instancePath || "/"} ${error.message ?? error.keyword}`).join("; "); +} + +function hasUniqueObjectPropertyValues(property: string, data: unknown[]): boolean { + const seen = new Set(); + for (const item of data) { + if (typeof item !== "object" || item === null) continue; + const descriptor = Object.getOwnPropertyDescriptor(item, property); + const value = descriptor !== undefined && "value" in descriptor ? descriptor.value : undefined; + if (seen.has(value)) return false; + seen.add(value); + } + return true; +} + +export function createJsonSchemaValidator( + schema: AnySchema, + referencedSchemas: readonly AnySchema[] = [] +): JsonSchemaValidator { + const ajv = new Ajv2020({ + strict: true, + allErrors: true, + allowUnionTypes: false, + coerceTypes: false, + removeAdditional: false, + useDefaults: false, + validateFormats: true + }); + const addFormats = formatsModule.default as unknown as FormatsPlugin; + addFormats(ajv); + ajv.addKeyword({ + keyword: "x-archflow-unique-by", + schemaType: "string", + metaSchema: { type: "string", minLength: 1 }, + type: "array", + errors: false, + validate: hasUniqueObjectPropertyValues + }); + for (const referencedSchema of referencedSchemas) ajv.addSchema(referencedSchema); + const validate = ajv.compile(schema); + const assert = (value: unknown, label = "value"): T => { + assertPlainJson(value, label); + if (!validate(value)) throw new ContractValidationError(`${label}: ${formatAjvErrors(validate.errors)}`, validate.errors); + return value as unknown as T; + }; + return { validate, assert }; +} + +export function assertValidJsonSchema( + validator: JsonSchemaValidator | ValidateFunction, + value: unknown, + label = "value" +): asserts value is T { + assertPlainJson(value, label); + if ("assert" in validator) { + validator.assert(value, label); + return; + } + if (!validator(value)) throw new ContractValidationError(`${label}: ${formatAjvErrors(validator.errors)}`, validator.errors); +} + +export function assertZodAgreement( + value: unknown, + jsonValidator: JsonSchemaValidator | ValidateFunction, + zodSchema: ZodLikeSchema, + label = "value" +): T { + assertPlainJson(value, label); + const before = structuredClone(value as PlainJsonValue); + const ajvValidate = "validate" in jsonValidator ? jsonValidator.validate : jsonValidator; + const jsonAccepted = ajvValidate(value); + const zodResult = zodSchema.safeParse(value); + if (!isDeepStrictEqual(value, before)) throw new ContractValidationError(`${label}: a validator mutated its input`); + if (jsonAccepted !== zodResult.success) { + throw new ContractValidationError(`${label}: JSON Schema and Zod validators disagree`, { + jsonSchemaErrors: ajvValidate.errors, + zodError: zodResult.success ? undefined : zodResult.error + }); + } + if (!jsonAccepted || !zodResult.success) { + throw new ContractValidationError(`${label}: schema validation failed: ${formatAjvErrors(ajvValidate.errors)}`, { + jsonSchemaErrors: ajvValidate.errors, + zodError: zodResult.success ? undefined : zodResult.error + }); + } + if (!isDeepStrictEqual(zodResult.data, value)) { + throw new ContractValidationError(`${label}: Zod mirrors must not transform validated values`); + } + return value as T; +} diff --git a/src/contracts/versions.ts b/src/contracts/versions.ts new file mode 100644 index 00000000..2bb5e2bf --- /dev/null +++ b/src/contracts/versions.ts @@ -0,0 +1,10 @@ +export const SCHEMA_VERSION = "1" as const; + +export const SCHEMA_IDS = { + primitives: "urn:archflow:schema:v1:primitives", + phaseInstance: "urn:archflow:schema:v1:phase-instance", + workflow: "urn:archflow:schema:v1:workflow", + config: "urn:archflow:schema:v1:config", + rubric: "urn:archflow:schema:v1:rubric", + constitutionRule: "urn:archflow:schema:v1:constitution-rule" +} as const; diff --git a/src/contracts/vocabulary.ts b/src/contracts/vocabulary.ts new file mode 100644 index 00000000..396a31fd --- /dev/null +++ b/src/contracts/vocabulary.ts @@ -0,0 +1,9 @@ +export const PHASE_IDS = ["explore", "prd", "design", "phase-design", "phase-impl"] as const; +export const PIPELINE_STEPS = ["produce", "self_review", "counter_review", "triage", "adjudicate"] as const; +export const GATE_POLICIES = ["never", "always", "on_trigger"] as const; +export const ITERATION_POLICIES = ["per_phase"] as const; + +export type PhaseId = (typeof PHASE_IDS)[number]; +export type PipelineStep = (typeof PIPELINE_STEPS)[number]; +export type GatePolicy = (typeof GATE_POLICIES)[number]; +export type IterationPolicy = (typeof ITERATION_POLICIES)[number]; diff --git a/src/contracts/workflow.ts b/src/contracts/workflow.ts new file mode 100644 index 00000000..685bc722 --- /dev/null +++ b/src/contracts/workflow.ts @@ -0,0 +1,47 @@ +import { z } from "zod"; + +import { assertPlainJson } from "./plain-json.js"; +import { parseSingleYamlDocument } from "./yaml.js"; +import { GATE_POLICIES, ITERATION_POLICIES, PHASE_IDS, PIPELINE_STEPS } from "./vocabulary.js"; + +export { GATE_POLICIES, ITERATION_POLICIES, PHASE_IDS, PIPELINE_STEPS } from "./vocabulary.js"; +export type { GatePolicy, IterationPolicy, PhaseId, PipelineStep } from "./vocabulary.js"; + +const phaseSchema = z.object({ + id: z.enum(PHASE_IDS), + skill: z.string().min(1), + requires: z.array(z.enum(PHASE_IDS)).min(1).optional(), + iterates: z.enum(ITERATION_POLICIES).optional(), + pipeline: z.array(z.enum(PIPELINE_STEPS)).min(1), + gate: z.enum(GATE_POLICIES), + optional: z.boolean().optional(), +}).strict(); + +export const workflowV1Schema = z.object({ phases: z.array(phaseSchema) }).strict().superRefine((workflow, context) => { + if (!sameJson(workflow, WORKFLOW_V1)) context.addIssue({ code: "custom", message: "Workflow must match the fixed ArchFlow v1 graph exactly" }); +}); + +export type WorkflowV1 = z.infer; + +export const WORKFLOW_V1: WorkflowV1 = { + phases: [ + { id: "explore", skill: "archflow-explore", pipeline: ["produce"], gate: "never", optional: true }, + { id: "prd", skill: "archflow-prd", pipeline: ["produce", "self_review", "counter_review", "triage", "adjudicate"], gate: "always" }, + { id: "design", skill: "archflow-design", requires: ["prd"], pipeline: ["produce", "self_review", "counter_review", "triage", "adjudicate"], gate: "always" }, + { id: "phase-design", skill: "archflow-phase-design", requires: ["design"], iterates: "per_phase", pipeline: ["produce", "self_review", "counter_review", "triage", "adjudicate"], gate: "on_trigger" }, + { id: "phase-impl", skill: "archflow-phase-impl", requires: ["phase-design"], iterates: "per_phase", pipeline: ["produce", "self_review", "counter_review", "triage", "adjudicate"], gate: "on_trigger" }, + ], +}; + +function sameJson(left: unknown, right: unknown): boolean { + return JSON.stringify(left) === JSON.stringify(right); +} + +export function parseWorkflowV1(value: unknown): WorkflowV1 { + assertPlainJson(value, "workflow"); + return workflowV1Schema.parse(value); +} + +export function parseWorkflowYaml(source: string, label = "workflow.yaml"): WorkflowV1 { + return parseWorkflowV1(parseSingleYamlDocument(source, label)); +} diff --git a/src/contracts/yaml.ts b/src/contracts/yaml.ts new file mode 100644 index 00000000..0214d9bf --- /dev/null +++ b/src/contracts/yaml.ts @@ -0,0 +1,43 @@ +import { LineCounter, isAlias, parseAllDocuments, visit } from "yaml"; +import { assertPlainJson } from "./plain-json.js"; + +function locatedMessage(label: string, error: { message: string; linePos?: readonly { line: number; col: number }[] }): string { + const position = error.linePos?.[0]; + return position === undefined ? `${label}: ${error.message}` : `${label}:${position.line}:${position.col}: ${error.message}`; +} + +export function parseSingleYamlDocument(source: string, label: string): unknown { + if (typeof source !== "string") throw new TypeError(`${label}: YAML source must be a string`); + const lineCounter = new LineCounter(); + const documents = parseAllDocuments(source, { + version: "1.2", + schema: "core", + strict: true, + uniqueKeys: true, + merge: false, + customTags: [], + lineCounter, + prettyErrors: true + }); + if (documents.length !== 1) throw new SyntaxError(`${label}: expected exactly one YAML document, found ${documents.length}`); + const document = documents[0]!; + if (document.errors.length > 0) throw new SyntaxError(locatedMessage(label, document.errors[0]!)); + if (document.warnings.length > 0) throw new SyntaxError(locatedMessage(label, document.warnings[0]!)); + + let aliasOffset: number | undefined; + visit(document, (_key, node) => { + if (isAlias(node)) { + aliasOffset = node.range?.[0]; + return visit.BREAK; + } + return undefined; + }); + if (aliasOffset !== undefined) { + const position = lineCounter.linePos(aliasOffset); + throw new SyntaxError(`${label}:${position.line}:${position.col}: YAML aliases are not allowed`); + } + + const value = document.toJS({ maxAliasCount: 0 }); + assertPlainJson(value, label); + return value; +} diff --git a/test/contracts/foundational-schema-agreement.test.ts b/test/contracts/foundational-schema-agreement.test.ts new file mode 100644 index 00000000..88148be5 --- /dev/null +++ b/test/contracts/foundational-schema-agreement.test.ts @@ -0,0 +1,77 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +import { configV1Schema } from "../../src/contracts/config.js"; +import { constitutionRuleV1Schema } from "../../src/contracts/constitution.js"; +import { rubricV1Schema } from "../../src/contracts/rubric.js"; +import { assertZodAgreement, createJsonSchemaValidator } from "../../src/contracts/validators.js"; +import { workflowV1Schema } from "../../src/contracts/workflow.js"; + +const schema = async (name: string) => JSON.parse(await readFile(new URL(`../../src/contracts/schemas/v1/${name}.schema.json`, import.meta.url), "utf8")) as object; + +describe("normative foundational JSON Schemas agree with Zod mirrors", () => { + it("compiles phase-instance references and enforces the canonical object contract", async () => { + const validator = createJsonSchemaValidator( + await schema("phase-instance"), + [await schema("primitives")] + ); + const valid = [ + { kind: "prd" }, + { kind: "design" }, + { kind: "phase-design", phase: 1 }, + { kind: "phase-impl", phase: Number.MAX_SAFE_INTEGER }, + ]; + for (const value of valid) expect(validator.assert(value)).toBe(value); + for (const invalid of [ + { kind: "explore" }, + { kind: "phase-design", phase: 0 }, + { kind: "phase-impl", phase: Number.MAX_SAFE_INTEGER + 1 }, + { kind: "phase-impl", phase: 1, extra: true }, + ]) expect(() => validator.assert(invalid)).toThrow(); + }); + + it("agrees for workflow valid and mutated cases", async () => { + const validator = createJsonSchemaValidator(await schema("workflow")); + const valid = JSON.parse(JSON.stringify((await import("../../src/contracts/workflow.js")).WORKFLOW_V1)) as unknown; + expect(assertZodAgreement(valid, validator, workflowV1Schema)).toEqual(valid); + const invalid = structuredClone(valid) as { phases: Array<{ gate: string }> }; + invalid.phases[1]!.gate = "on_trigger"; + expect(() => assertZodAgreement(invalid, validator, workflowV1Schema)).toThrow(/schema validation failed|must be equal/); + }); + + it("agrees for routing boundaries", async () => { + const validator = createJsonSchemaValidator(await schema("config")); + const valid = { schema_version: "1", roles: { "counter-reviewer": { model: "example", effort: "high" } }, overrides: { design: { adjudicator: { model: "other", effort: "xhigh" } } } }; + expect(assertZodAgreement(valid, validator, configV1Schema)).toEqual(valid); + for (const invalid of [ + { ...valid, repository: "/tmp/repo" }, + { ...valid, roles: { producer: { model: "x", effort: "high", family: "codex" } } }, + { ...valid, roles: { producer: { model: " ", effort: "high" } } }, + { ...valid, overrides: { unknown: {} } }, + ]) expect(() => assertZodAgreement(invalid, validator, configV1Schema)).toThrow(/schema validation failed|additional properties/); + }); + + it("agrees for rubric and constitution rule shapes", async () => { + const rubricValidator = createJsonSchemaValidator(await schema("rubric")); + const rubric = { schema_version: "1", kind: "implementation", mode: "adversarial", criteria: [{ id: "correctness", text: "Behavior matches the approved design.", blocking: true }] }; + expect(assertZodAgreement(rubric, rubricValidator, rubricV1Schema)).toEqual(rubric); + expect(() => assertZodAgreement({ ...rubric, mode: "friendly" }, rubricValidator, rubricV1Schema)).toThrow(); + expect(() => assertZodAgreement({ ...rubric, criteria: [{ id: "correctness", text: " ", blocking: true }] }, rubricValidator, rubricV1Schema)).toThrow(); + const duplicateIdWithDifferentBodies = { + ...rubric, + criteria: [ + { id: "correctness", text: "First formulation.", blocking: true }, + { id: "correctness", text: "Different formulation.", blocking: false } + ] + }; + const duplicateBefore = structuredClone(duplicateIdWithDifferentBodies); + expect(() => rubricValidator.assert(duplicateIdWithDifferentBodies)).toThrow(/x-archflow-unique-by/iu); + expect(() => assertZodAgreement(duplicateIdWithDifferentBodies, rubricValidator, rubricV1Schema)).toThrow(/schema validation failed/iu); + expect(duplicateIdWithDifferentBodies).toEqual(duplicateBefore); + + const constitutionValidator = createJsonSchemaValidator(await schema("constitution-rule")); + const rule = { id: "stable-rule", version: 1, status: "active", text: "Preserve this invariant." }; + expect(assertZodAgreement(rule, constitutionValidator, constitutionRuleV1Schema)).toEqual(rule); + expect(() => assertZodAgreement({ ...rule, version: 0 }, constitutionValidator, constitutionRuleV1Schema)).toThrow(); + }); +}); diff --git a/test/fixtures/foundation/config/invalid-authority.yaml b/test/fixtures/foundation/config/invalid-authority.yaml new file mode 100644 index 00000000..b504bfe9 --- /dev/null +++ b/test/fixtures/foundation/config/invalid-authority.yaml @@ -0,0 +1,4 @@ +schema_version: "1" +repository: /tmp/not-authority +roles: + counter-reviewer: {model: gpt-example, effort: high, family: codex} diff --git a/test/fixtures/foundation/config/valid.yaml b/test/fixtures/foundation/config/valid.yaml new file mode 100644 index 00000000..d18a037b --- /dev/null +++ b/test/fixtures/foundation/config/valid.yaml @@ -0,0 +1,7 @@ +schema_version: "1" +roles: + counter-reviewer: {model: gpt-example, effort: high} + adjudicator: {model: claude-example, effort: high} +overrides: + design: + counter-reviewer: {model: gpt-design-example, effort: xhigh} diff --git a/test/fixtures/foundation/constitution/invalid-frontmatter.md b/test/fixtures/foundation/constitution/invalid-frontmatter.md new file mode 100644 index 00000000..803da194 --- /dev/null +++ b/test/fixtures/foundation/constitution/invalid-frontmatter.md @@ -0,0 +1,7 @@ +--- +id: Bad Rule +version: 0 +status: pending +unknown: true +--- +This must fail. diff --git a/test/fixtures/foundation/constitution/valid.md b/test/fixtures/foundation/constitution/valid.md new file mode 100644 index 00000000..4461b49c --- /dev/null +++ b/test/fixtures/foundation/constitution/valid.md @@ -0,0 +1,8 @@ +--- +id: stable-rule +version: 1 +status: active +review_trigger: The invariant may be violated. +enforced_by: [invariant-test] +--- +Preserve the invariant at every boundary. diff --git a/test/fixtures/foundation/rubric/invalid-mode.json b/test/fixtures/foundation/rubric/invalid-mode.json new file mode 100644 index 00000000..c856020f --- /dev/null +++ b/test/fixtures/foundation/rubric/invalid-mode.json @@ -0,0 +1 @@ +{"schema_version":"1","kind":"artifact","mode":"friendly","criteria":[{"id":"coverage","text":"Check coverage.","blocking":true}]} diff --git a/test/fixtures/foundation/rubric/valid.json b/test/fixtures/foundation/rubric/valid.json new file mode 100644 index 00000000..146d2359 --- /dev/null +++ b/test/fixtures/foundation/rubric/valid.json @@ -0,0 +1 @@ +{"schema_version":"1","kind":"artifact","mode":"adversarial","criteria":[{"id":"requirement-coverage","text":"Every approved requirement is addressed or explicitly out of scope.","blocking":true},{"id":"clear-language","text":"The artifact is understandable to its intended reader.","blocking":false}]} diff --git a/test/fixtures/foundation/workflow/invalid-mutated-gate.yaml b/test/fixtures/foundation/workflow/invalid-mutated-gate.yaml new file mode 100644 index 00000000..f4202fff --- /dev/null +++ b/test/fixtures/foundation/workflow/invalid-mutated-gate.yaml @@ -0,0 +1,6 @@ +phases: + - {id: explore, skill: archflow-explore, pipeline: [produce], gate: never, optional: true} + - {id: prd, skill: archflow-prd, pipeline: [produce, self_review, counter_review, triage, adjudicate], gate: on_trigger} + - {id: design, skill: archflow-design, requires: [prd], pipeline: [produce, self_review, counter_review, triage, adjudicate], gate: always} + - {id: phase-design, skill: archflow-phase-design, requires: [design], iterates: per_phase, pipeline: [produce, self_review, counter_review, triage, adjudicate], gate: on_trigger} + - {id: phase-impl, skill: archflow-phase-impl, requires: [phase-design], iterates: per_phase, pipeline: [produce, self_review, counter_review, triage, adjudicate], gate: on_trigger} diff --git a/test/fixtures/foundation/workflow/valid.yaml b/test/fixtures/foundation/workflow/valid.yaml new file mode 100644 index 00000000..0388e794 --- /dev/null +++ b/test/fixtures/foundation/workflow/valid.yaml @@ -0,0 +1,6 @@ +phases: + - {id: explore, skill: archflow-explore, pipeline: [produce], gate: never, optional: true} + - {id: prd, skill: archflow-prd, pipeline: [produce, self_review, counter_review, triage, adjudicate], gate: always} + - {id: design, skill: archflow-design, requires: [prd], pipeline: [produce, self_review, counter_review, triage, adjudicate], gate: always} + - {id: phase-design, skill: archflow-phase-design, requires: [design], iterates: per_phase, pipeline: [produce, self_review, counter_review, triage, adjudicate], gate: on_trigger} + - {id: phase-impl, skill: archflow-phase-impl, requires: [phase-design], iterates: per_phase, pipeline: [produce, self_review, counter_review, triage, adjudicate], gate: on_trigger} diff --git a/test/unit/constitution.test.ts b/test/unit/constitution.test.ts new file mode 100644 index 00000000..a733fc7b --- /dev/null +++ b/test/unit/constitution.test.ts @@ -0,0 +1,71 @@ +import { readFile, readdir } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +import { parseConstitutionRuleFiles, parseConstitutionRuleMarkdown, validateConstitutionEvolution, type ConstitutionRuleV1 } from "../../src/contracts/constitution.js"; +import { parseConstitutionRuleV1 } from "../../src/contracts/constitution.js"; +import { PlainJsonError } from "../../src/contracts/plain-json.js"; + +const rule = (overrides: Partial = {}): ConstitutionRuleV1 => ({ id: "stable-rule", version: 1, status: "active", text: "Preserve the invariant.", ...overrides }); + +describe("constitution Markdown", () => { + it("loads every shipped numbered policy with unique IDs", async () => { + const directory = new URL("../../assets/constitution/", import.meta.url); + const paths = (await readdir(directory)).filter((path) => /^\d\d-.*\.md$/u.test(path)); + const files = Object.fromEntries(await Promise.all(paths.map(async (path) => [path, await readFile(new URL(path, directory), "utf8")] as const))); + const registry = parseConstitutionRuleFiles(files); + expect([...registry.keys()]).toEqual(["explicit-human-authority", "approved-design-before-code", "task-and-evidence-isolation", "honest-human-centered-outcomes"]); + }); + + it("parses deterministic frontmatter and prose", async () => { + const source = await readFile(new URL("../fixtures/foundation/constitution/valid.md", import.meta.url), "utf8"); + expect(parseConstitutionRuleMarkdown(source, "valid.md")).toMatchObject({ id: "stable-rule", version: 1, text: "Preserve the invariant at every boundary." }); + }); + + it("rejects invalid metadata and duplicate IDs across files", async () => { + const invalid = await readFile(new URL("../fixtures/foundation/constitution/invalid-frontmatter.md", import.meta.url), "utf8"); + expect(() => parseConstitutionRuleMarkdown(invalid, "invalid.md")).toThrow(); + const valid = await readFile(new URL("../fixtures/foundation/constitution/valid.md", import.meta.url), "utf8"); + expect(() => parseConstitutionRuleFiles({ "a.md": valid, "b.md": valid })).toThrow(/Duplicate constitution rule id/); + }); + + it("plain-JSON preflights the direct unknown boundary without invoking getters", () => { + const valid = rule() as unknown as Record; + expect(() => parseConstitutionRuleV1(Object.create(valid))).toThrow(PlainJsonError); + + let getterCalls = 0; + const accessor = { ...valid }; + Object.defineProperty(accessor, "id", { + enumerable: true, + get: () => { + getterCalls += 1; + return valid.id; + } + }); + expect(() => parseConstitutionRuleV1(accessor)).toThrow(PlainJsonError); + expect(getterCalls).toBe(0); + + const dangerous = structuredClone(valid); + Object.defineProperty(dangerous, "prototype", { enumerable: true, value: "forbidden" }); + expect(() => parseConstitutionRuleV1(dangerous)).toThrow(PlainJsonError); + expect(() => parseConstitutionRuleV1({ ...structuredClone(valid), unsupported: undefined })).toThrow(PlainJsonError); + }); +}); + +describe("constitution evolution", () => { + const prior = new Map([["stable-rule", rule()]]); + + it("permits append, versioned edit, and versioned deprecation", () => { + expect(validateConstitutionEvolution(prior, [rule(), rule({ id: "new-rule", text: "New invariant." })]).size).toBe(2); + expect(validateConstitutionEvolution(prior, [rule({ version: 2, text: "Clarified invariant." })]).get("stable-rule")?.version).toBe(2); + expect(validateConstitutionEvolution(prior, [rule({ version: 2, status: "deprecated" })]).get("stable-rule")?.status).toBe("deprecated"); + }); + + it("rejects deletion, ID reuse, reactivation, and version errors", () => { + expect(() => validateConstitutionEvolution(prior, [])).toThrow(/cannot be deleted/); + expect(() => validateConstitutionEvolution(prior, [rule({ id: "replacement" })])).toThrow(/cannot be deleted/); + expect(() => validateConstitutionEvolution(prior, [rule({ text: "Changed." })])).toThrow(/increment/); + expect(() => validateConstitutionEvolution(prior, [rule({ version: 2 })])).toThrow(/retain/); + const deprecated = new Map([["stable-rule", rule({ version: 2, status: "deprecated" })]]); + expect(() => validateConstitutionEvolution(deprecated, [rule({ version: 3, status: "active" })])).toThrow(/reactivated/); + }); +}); diff --git a/test/unit/phase-instance.test.ts b/test/unit/phase-instance.test.ts new file mode 100644 index 00000000..95a2e832 --- /dev/null +++ b/test/unit/phase-instance.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; +import { + decodePhaseInstance, + encodePhaseInstance, + parsePositiveSafePhaseNumber, + type PhaseInstance, + type PhaseInstanceId, + type PositiveSafePhaseNumber +} from "../../src/contracts/index.js"; + +describe("phase instance codec", () => { + it("round-trips every canonical shape", () => { + const phase = parsePositiveSafePhaseNumber(42); + const values: readonly PhaseInstance[] = [ + { kind: "prd" }, + { kind: "design" }, + { kind: "phase-design", phase }, + { kind: "phase-impl", phase } + ]; + expect(values.map(encodePhaseInstance)).toEqual(["prd", "design", "phase-design-42", "phase-impl-42"]); + for (const value of values) expect(decodePhaseInstance(encodePhaseInstance(value))).toEqual(value); + }); + + it.each([1, 2, Number.MAX_SAFE_INTEGER])("accepts positive safe phase number %s", (value) => { + expect(parsePositiveSafePhaseNumber(value)).toBe(value); + }); + + it("decodes the parent contract's canonical hyphenated examples directly", () => { + expect(decodePhaseInstance("phase-design-1")).toEqual({ + kind: "phase-design", + phase: parsePositiveSafePhaseNumber(1) + }); + expect(decodePhaseInstance(`phase-impl-${Number.MAX_SAFE_INTEGER}`)).toEqual({ + kind: "phase-impl", + phase: parsePositiveSafePhaseNumber(Number.MAX_SAFE_INTEGER) + }); + }); + + it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1, "1", null])( + "rejects invalid phase number %s", + (value) => expect(() => parsePositiveSafePhaseNumber(value)).toThrow(/positive safe integer/iu) + ); + + it.each([ + "explore", + "phase-design", + "phase-impl", + "phase-design:1", + "phase-impl:1", + "phase-design_1", + "phase-design:0", + "phase-design:01", + "phase-design:+1", + "phase-design:-1", + "phase-design:1.0", + "phase-design:1e0", + "phase-design:1_0", + "phase-design:9007199254740992", + "phase-design:%31", + "phase-design:١", + " phase-design:1", + "phase-design-0", + "phase-design-01", + "phase-design-+1", + "phase-design--1", + "phase-design-1.0", + "phase-design-1e0", + "phase-design-1_0", + "phase-design-9007199254740992", + "phase-design-%31", + "phase-design-١", + " phase-design-1", + "phase-impl-1/../../x" + ])("rejects non-canonical alias %s", (value) => { + expect(() => decodePhaseInstance(value)).toThrow(); + }); + + it("keeps brands opaque at compile time", () => { + expectTypeOf().toMatchTypeOf(); + expectTypeOf().toMatchTypeOf(); + // @ts-expect-error plain numbers cannot mint the phase-number brand + const invalidPhase: PositiveSafePhaseNumber = 1; + // @ts-expect-error plain strings cannot mint the phase-instance ID brand + const invalidId: PhaseInstanceId = "prd"; + expect(invalidPhase).toBe(1); + expect(invalidId).toBe("prd"); + }); +}); diff --git a/test/unit/plain-json.test.ts b/test/unit/plain-json.test.ts new file mode 100644 index 00000000..b2f76261 --- /dev/null +++ b/test/unit/plain-json.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from "vitest"; +import { z } from "zod"; +import { + ContractValidationError, + PlainJsonError, + assertPlainJson, + assertZodAgreement, + createJsonSchemaValidator, + isPlainJsonValue +} from "../../src/contracts/index.js"; + +describe("plain JSON preflight", () => { + it("accepts JSON trees and does not mutate them", () => { + const shared = { ok: true }; + const value = { text: "héllo", count: 1, nil: null, list: [shared, shared] }; + const before = structuredClone(value); + assertPlainJson(value, "fixture"); + expect(value).toEqual(before); + expect(isPlainJsonValue(value)).toBe(true); + }); + + it.each([ + ["undefined", { value: undefined }], + ["function", { value: () => undefined }], + ["bigint", { value: 1n }], + ["symbol", { value: Symbol("no") }], + ["NaN", { value: Number.NaN }], + ["infinity", { value: Number.POSITIVE_INFINITY }], + ["date", new Date(0)], + ["map", new Map()], + ["sparse array", Array(2)] + ])("rejects %s values", (_name, value) => { + expect(() => assertPlainJson(value)).toThrow(PlainJsonError); + }); + + it("rejects cycles while allowing repeated non-cyclic references", () => { + const cyclic: { self?: unknown } = {}; + cyclic.self = cyclic; + expect(() => assertPlainJson(cyclic)).toThrow(/cyclic/iu); + const leaf = { value: 1 }; + expect(() => assertPlainJson([leaf, leaf])).not.toThrow(); + }); + + it("rejects inherited, accessor, symbol, and dangerous own properties", () => { + expect(() => assertPlainJson(Object.create({ inherited: true }))).toThrow(/plain prototype/iu); + + const accessor = {}; + Object.defineProperty(accessor, "value", { enumerable: true, get: () => 1 }); + expect(() => assertPlainJson(accessor)).toThrow(/accessor/iu); + + const symbolKey = { [Symbol("hidden")]: true }; + expect(() => assertPlainJson(symbolKey)).toThrow(/symbol/iu); + + for (const key of ["__proto__", "prototype", "constructor"]) { + const dangerous = {}; + Object.defineProperty(dangerous, key, { value: true, enumerable: true }); + expect(() => assertPlainJson(dangerous), key).toThrow(/dangerous own key/iu); + } + }); +}); + +describe("strict validator infrastructure", () => { + const jsonSchema = { + type: "object", + properties: { email: { type: "string", format: "email" } }, + required: ["email"], + additionalProperties: false + } as const; + const validator = createJsonSchemaValidator<{ readonly email: string }>(jsonSchema); + const zodSchema = z.strictObject({ email: z.email() }); + + it("enforces formats and closed objects without changing the input", () => { + const value = { email: "person@example.com" }; + const before = structuredClone(value); + validator.assert(value); + expect(assertZodAgreement(value, validator, zodSchema)).toBe(value); + expect(value).toEqual(before); + expect(() => validator.assert({ email: "not-an-email" })).toThrow(ContractValidationError); + expect(() => validator.assert({ email: "person@example.com", extra: true })).toThrow(ContractValidationError); + }); + + it("reports contradictory Zod and JSON Schema acceptance", () => { + const disagreeing = z.strictObject({ email: z.literal("different@example.com") }); + expect(() => assertZodAgreement({ email: "person@example.com" }, validator, disagreeing)).toThrow(/disagree/iu); + }); + + it("runs plain-JSON preflight before schema validation", () => { + const inherited = Object.create({ email: "person@example.com" }) as unknown; + expect(() => validator.assert(inherited)).toThrow(PlainJsonError); + }); +}); diff --git a/test/unit/rubric.test.ts b/test/unit/rubric.test.ts new file mode 100644 index 00000000..bfd6c897 --- /dev/null +++ b/test/unit/rubric.test.ts @@ -0,0 +1,42 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +import { PlainJsonError } from "../../src/contracts/plain-json.js"; +import { parseRubricV1 } from "../../src/contracts/rubric.js"; + +const fixture = async (name: string) => JSON.parse(await readFile(new URL(`../fixtures/foundation/rubric/${name}`, import.meta.url), "utf8")) as unknown; + +describe("RubricV1", () => { + it("accepts stable structured criteria", async () => { + expect(parseRubricV1(await fixture("valid.json")).criteria).toHaveLength(2); + }); + + it("rejects invalid modes, unknown fields, and duplicate IDs", async () => { + const invalidMode = await fixture("invalid-mode.json"); + expect(() => parseRubricV1(invalidMode)).toThrow(); + expect(() => parseRubricV1({ schema_version: "1", kind: "artifact", mode: "self_review", criteria: [{ id: "a", text: "A", blocking: true }], verdict: "pass" })).toThrow(); + expect(() => parseRubricV1({ schema_version: "1", kind: "implementation", mode: "adversarial", criteria: [{ id: "same", text: "A", blocking: true }, { id: "same", text: "B", blocking: false }] })).toThrow(/Duplicate criterion id/); + }); + + it("plain-JSON preflights the direct unknown boundary without invoking getters", async () => { + const valid = await fixture("valid.json") as Record; + expect(() => parseRubricV1(Object.create(valid))).toThrow(PlainJsonError); + + let getterCalls = 0; + const accessor = { ...valid }; + Object.defineProperty(accessor, "criteria", { + enumerable: true, + get: () => { + getterCalls += 1; + return valid.criteria; + } + }); + expect(() => parseRubricV1(accessor)).toThrow(PlainJsonError); + expect(getterCalls).toBe(0); + + const dangerous = structuredClone(valid); + Object.defineProperty(dangerous, "__proto__", { enumerable: true, value: "forbidden" }); + expect(() => parseRubricV1(dangerous)).toThrow(PlainJsonError); + expect(() => parseRubricV1({ ...structuredClone(valid), unsupported: Number.NaN })).toThrow(PlainJsonError); + }); +}); diff --git a/test/unit/workflow-config.test.ts b/test/unit/workflow-config.test.ts new file mode 100644 index 00000000..f773c93d --- /dev/null +++ b/test/unit/workflow-config.test.ts @@ -0,0 +1,76 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +import { parseConfigV1, parseConfigYaml } from "../../src/contracts/config.js"; +import { PlainJsonError } from "../../src/contracts/plain-json.js"; +import { parseWorkflowV1, parseWorkflowYaml, WORKFLOW_V1 } from "../../src/contracts/workflow.js"; + +const fixture = (path: string) => readFile(new URL(`../fixtures/foundation/${path}`, import.meta.url), "utf8"); + +function expectPreflightedBoundary( + parser: (value: unknown) => unknown, + valid: Record, + accessorKey: string +): void { + expect(() => parser(Object.create(valid))).toThrow(PlainJsonError); + + let getterCalls = 0; + const accessor = { ...valid }; + Object.defineProperty(accessor, accessorKey, { + enumerable: true, + get: () => { + getterCalls += 1; + return valid[accessorKey]; + } + }); + expect(() => parser(accessor)).toThrow(PlainJsonError); + expect(getterCalls).toBe(0); + + const dangerous = structuredClone(valid); + Object.defineProperty(dangerous, "constructor", { enumerable: true, value: "forbidden" }); + expect(() => parser(dangerous)).toThrow(PlainJsonError); + expect(() => parser({ ...structuredClone(valid), unsupported: 1n })).toThrow(PlainJsonError); +} + +describe("fixed workflow", () => { + it("accepts the shipped graph and keeps Explore graph-only", async () => { + const workflow = parseWorkflowYaml(await readFile(new URL("../../assets/workflow.yaml", import.meta.url), "utf8")); + expect(workflow.phases.map(({ id }) => id)).toEqual(["explore", "prd", "design", "phase-design", "phase-impl"]); + expect(workflow.phases[0]).toMatchObject({ pipeline: ["produce"], gate: "never", optional: true }); + }); + + it("rejects graph mutations", async () => { + const source = await fixture("workflow/invalid-mutated-gate.yaml"); + expect(() => parseWorkflowYaml(source)).toThrow(/fixed ArchFlow v1 graph/); + }); + + it("plain-JSON preflights the direct unknown boundary without invoking getters", () => { + expectPreflightedBoundary(parseWorkflowV1, structuredClone(WORKFLOW_V1) as unknown as Record, "phases"); + }); +}); + +describe("model routing configuration", () => { + it("accepts only role and phase model/effort selection", async () => { + const config = parseConfigYaml(await fixture("config/valid.yaml")); + expect(config.overrides?.design?.["counter-reviewer"]?.effort).toBe("xhigh"); + }); + + it("rejects repository and model-family authority", async () => { + const source = await fixture("config/invalid-authority.yaml"); + expect(() => parseConfigYaml(source)).toThrow(); + }); + + it("rejects task, host, unknown role, and unknown phase keys", () => { + const route = { model: "example", effort: "high" }; + for (const invalid of [ + { schema_version: "1", task: "other", roles: {} }, + { schema_version: "1", host: "codex", roles: {} }, + { schema_version: "1", roles: { reviewer: route } }, + { schema_version: "1", roles: {}, overrides: { release: { producer: route } } }, + ]) expect(() => parseConfigYaml(JSON.stringify(invalid))).toThrow(); + }); + + it("plain-JSON preflights the direct unknown boundary without invoking getters", () => { + expectPreflightedBoundary(parseConfigV1, { schema_version: "1", roles: {} }, "schema_version"); + }); +}); diff --git a/test/unit/yaml.test.ts b/test/unit/yaml.test.ts new file mode 100644 index 00000000..f472385c --- /dev/null +++ b/test/unit/yaml.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { parseSingleYamlDocument } from "../../src/contracts/index.js"; + +describe("safe YAML parsing", () => { + it("parses one YAML 1.2 document into a plain JSON value", () => { + const result = parseSingleYamlDocument("enabled: true\nlegacy_word: yes\nitems:\n - 1\n - null\n", "config.yaml"); + expect(result).toEqual({ enabled: true, legacy_word: "yes", items: [1, null] }); + }); + + it("rejects duplicate keys with label and location", () => { + expect(() => parseSingleYamlDocument("name: first\nname: second\n", "workflow.yaml")).toThrow( + /workflow\.yaml:\d+:\d+.*unique|workflow\.yaml:\d+:\d+.*map key/iu + ); + }); + + it("reports useful Unicode-aware line and column diagnostics", () => { + try { + parseSingleYamlDocument("title: café ☕\nitems: [one, two\n", "unicode.yaml"); + throw new Error("expected malformed YAML to fail"); + } catch (error) { + expect(error).toBeInstanceOf(SyntaxError); + expect(String(error)).toMatch(/unicode\.yaml:\d+:\d+/u); + } + }); + + it.each([ + ["multiple documents", "one: 1\n---\ntwo: 2\n", /exactly one/iu], + ["aliases", "base: &base\n ok: true\ncopy: *base\n", /alias/iu], + ["custom tags", "value: !custom hello\n", /tag/iu] + ])("rejects %s", (_name, source, message) => { + expect(() => parseSingleYamlDocument(source, "unsafe.yaml")).toThrow(message); + }); + + it("does not mutate or reuse parser state across calls", () => { + const source = "nested:\n value: 1\n"; + const first = parseSingleYamlDocument(source, "first.yaml") as { nested: { value: number } }; + first.nested.value = 2; + expect(parseSingleYamlDocument(source, "second.yaml")).toEqual({ nested: { value: 1 } }); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..abab6100 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2024", + "lib": ["ES2024"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": ".", + "strict": true, + "noEmit": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "verbatimModuleSyntax": true, + "resolveJsonModule": true, + "types": ["node"], + "skipLibCheck": false + }, + "include": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts"] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 00000000..b521c0d9 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + environment: "node", + include: ["test/**/*.test.ts"], + coverage: { + reportsDirectory: "coverage" + } + } +}); From 4e343efcb5d27b12019ee45718f2b97a75ef2df8 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 12:28:13 -0500 Subject: [PATCH 006/124] MCP Integration: Design Phase 2 --- .../tasks/mcp-integration/architecture.md | 178 ++-- ...-review-evidence-and-contract-authority.md | 935 ++++++++++++++++++ .../reviews/phase-2-design-counter-review.md | 132 +++ 3 files changed, 1167 insertions(+), 78 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-2-design-counter-review.md diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index d986b7c5..4f47ee73 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -18,7 +18,7 @@ | Packaging | esbuild `0.28.1`, exact npm lockfile, single host-neutral server/local-helper bundle | `install.sh` installs both `archflow-mcp` and `archflow-local` without an unpinned startup download. | | Verification | Vitest `4.1.10` with direct dev pin Vite `7.3.6`, fixture CLIs, fault injection, protocol fixtures, and black-box host/sandbox suites | The exact Vite 7 pin constrains Vitest to its supported permissive line; the lock must prove no `lightningcss` or other copyleft dependency before acceptance. Critical persistence, host, process, protocol, and manual-mode behavior is exercised at its real boundaries. | -All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. Direct pins are permissively licensed, and the complete lock must independently prove a permissive-only graph. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 7 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. +All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. Direct pins are permissively licensed, and the complete lock must independently prove a permissive-only graph. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 8 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. ## System Architecture @@ -301,7 +301,7 @@ Each dispatch creates a fresh, non-resumed child in a temporary directory outsid - use an OS containment primitive capable of terminating every descendant on abort, timeout, server shutdown, or output overflow even if a descendant creates a new process group/session—PID namespace/cgroup, Windows job object, or a proven equivalent, not Execa best effort alone; and - return a capability proof tied to the OS, provider, CLI/runtime versions, exact allowed-read manifest, and randomized denied canaries. -At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 7 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. +At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 8 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. The Claude adapter uses fresh `--safe-mode`, `--tools ""`, a strict empty MCP config, disabled slash commands, no persistence, and schema-constrained output. It preflights subscription authentication and managed hooks/policy. Host setup configures and validates the Claude server entry's persistent per-server `timeout` when supported; otherwise a newly started host must inherit `MCP_TOOL_TIMEOUT` as described below. Cancellation or host timeout always leaves a durable resumable gate; timeout-then-resume is supported normal behavior. The Codex adapter uses exact fixture-proven ephemeral, ignore-user-config, `--ignore-rules`, read-only, and output-schema behavior while preserving first-party auth; `--ignore-rules` is inherited-context isolation only, never security confinement. It configures/tests `project_doc_max_bytes=0` or a proven equivalent and rejects managed instruction injection. An ArchFlow deny-all Codex execpolicy remains an early feasibility candidate, and the design does not claim it works. Both adapters still require OS sandbox proof, are version-gated from real fixtures, and spawn with `shell: false`, scrubbed environment, no provider keys/routing or unrelated secrets, `killDescendants`, cancellation, timeout/output bounds, forced escalation, and provider-owned descendant containment. Stable failures cover missing CLI, auth, unsupported host/model, family mismatch, rate limit, timeout, cancellation, overflow, invalid output, nonzero exit, and I/O failure. @@ -371,22 +371,22 @@ Release is blocked unless all applicable tests pass and the supported matrix is | Coverage area | Requirements | Validation | Primary phases | Proof boundary | |---------------|--------------|------------|----------------|----------------| -| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 10, 11, 16 | Strict assets/schemas, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | -| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 9, 11, 15, 16 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | -| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 2, 3, 4, 5, 8, 11, 12, 14, 15 | Structured JSON/projections, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | -| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 2, 8, 13, 14, 15 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | -| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 2, 6, 8, 13, 15 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | -| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 3, 4, 5, 6, 12, 14, 15 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | -| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 3, 4, 5, 6, 12, 13, 14 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | -| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 3, 4, 5, 7, 13, 14, 15 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | -| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 2, 9, 10, 14, 15 | v2 fixtures expose five stdio tools; the separate offline helper is not an MCP tool. | -| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 7, 9, 14, 15 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | -| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 2, 7, 8, 9, 14, 15 | Hashed envelopes, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | -| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 7, 10, 14, 15, 16 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | -| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 2, 6, 9, 12, 14, 15 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | -| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 9, 10, 12, 13, 15 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | -| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 2, 6, 11, 12, 15 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | -| Legacy migration | REQ-50 | VAL-17 | 3, 4, 5, 6, 13, 14, 15 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | +| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 11, 12, 17 | Strict assets/schemas, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | +| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 10, 12, 16, 17 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | +| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 2, 4, 5, 6, 9, 12, 13, 15, 16 | Structured JSON/projections, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | +| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 2, 9, 14, 15, 16 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | +| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 2, 7, 9, 14, 16 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | +| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 4, 5, 6, 7, 13, 15, 16 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | +| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 4, 5, 6, 7, 13, 14, 15 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | +| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 4, 5, 6, 8, 14, 15, 16 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | +| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 2, 3, 10, 11, 15, 16 | Correlated five-tool contracts and v2 fixtures expose only the stdio boundary; the separate offline helper is not an MCP tool. | +| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 8, 10, 15, 16 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | +| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 2, 3, 8, 9, 10, 15, 16 | Hashed envelopes, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | +| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 8, 11, 15, 16, 17 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | +| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 2, 7, 10, 13, 15, 16 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | +| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 10, 11, 13, 14, 16 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | +| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 2, 7, 12, 13, 16 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | +| Legacy migration | REQ-50 | VAL-17 | 4, 5, 6, 7, 14, 15, 16 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release validations `VAL-01` through `VAL-17`, appear above. `REQ-52` remains explicitly outside the v1 architecture. @@ -400,7 +400,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali **Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-15, REQ-17 -**Scope**: First add the visible lineage/supersession banner to `docs/mcp-integration-design.md`, preserving it as originating design and linking the normative PRD/architecture; Phase 16 later updates surrounding documentation. Establish a private ESM package, exact lockfile, scripts, Node matrix CI, dependency notices/policy, and only Phase-1 direct dependencies: Zod, Ajv, `ajv-formats`, YAML, TypeScript, Node typings, esbuild, Vitest, and direct Vite `7.3.6`. Implement recursive plain-JSON preflight, strict non-mutating Ajv2020, explicit Zod agreement infrastructure, branded canonical phase-instance codec, safe YAML parsing, fixed workflow/config/rubric/constitution rule contracts, shipped workflow/constitution assets, and append-only constitution evolution fixtures. This phase has no review/triage/adjudication contracts or renderers, error registry, tool schemas, MCP SDK/server, or tracked offline bundle. +**Scope**: First add the visible lineage/supersession banner to `docs/mcp-integration-design.md`, preserving it as originating design and linking the normative PRD/architecture; Phase 17 later updates surrounding documentation. Establish a private ESM package, exact lockfile, scripts, Node matrix CI, dependency notices/policy, and only Phase-1 direct dependencies: Zod, Ajv, `ajv-formats`, YAML, TypeScript, Node typings, esbuild, Vitest, and direct Vite `7.3.6`. Implement recursive plain-JSON preflight, strict non-mutating Ajv2020, explicit Zod agreement infrastructure, branded canonical phase-instance codec, safe YAML parsing, fixed workflow/config/rubric/constitution rule contracts, shipped workflow/constitution assets, and append-only constitution evolution fixtures. This phase has no review/triage/adjudication contracts or renderers, error registry, tool schemas, MCP SDK/server, or tracked offline bundle. **Success Criteria**: @@ -411,31 +411,52 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [x] Branded positive-safe phase numbers and phase-instance IDs are minted only by codecs/validators; compile-time assertions and runtime aliases reject non-canonical values, while Explore remains disposable pre-task vocabulary rather than a phase instance. - [x] Phase 1's first change adds the source design's visible lineage/supersession banner, links the approved PRD/architecture, preserves its originating-design status, and precedes all server implementation. -### Phase 2: Review Evidence and Inert MCP Boundary +### Phase 2: Review Evidence and Contract Authority -**Goal**: Freeze trust-bearing review, gate, error, and tool interfaces and prove the inert stdio MCP boundary. +**Goal**: Freeze the trust-bearing semantic, provenance, gate, error, tool, connection, and invocation contracts before any MCP transport or durable workflow implementation adopts them. **Depends on**: Phase 1 -**Requirements**: REQ-04, REQ-05, REQ-10, REQ-11, REQ-12, REQ-15, REQ-17, REQ-27, REQ-28, REQ-33 +**Requirements**: REQ-04, REQ-05, REQ-10, REQ-11, REQ-12, REQ-13, REQ-15, REQ-17, REQ-18, REQ-19, REQ-20, REQ-23, REQ-27, REQ-33, REQ-36, REQ-37, REQ-41, REQ-50 -**Scope**: Define complete raw/derived/agent-declared/server-attested/degraded review evidence, composite finding references and triage, digest-bound adjudication and canonical renderers, the full v1 error registry, discriminated gate contexts and the exhaustive decision map, and exactly five versioned request/result schemas with `archflow_state.artifact` disabled. Pin required request `task_id` and immutable connection repository-candidate context. Add the exact MCP SDK pin and currency fixtures; isolate beta.5's low-level `Server` advanced seam with owned `tools/list`/`tools/call` validation and `projectCallToolResult`. Track `dist/archflow-mcp.js` and `dist/manifest.json` and prove clean-checkout offline startup. This phase implements no persistence, dispatch, durable gate lifecycle, or durable state/artifact schema. +**Scope**: Define complete raw/derived/agent-declared/server-attested/degraded review evidence, composite finding references, exact current-slot triage, digest-bound adjudication, supplemental evidence/choices, and canonical anti-spoofing renderers. Establish scope-bound observation/result/authority expectations; one exact gate catalogue with waiver, restore, migration, human-decision, and commit subjects; separate exhaustive project-result and ArchFlow protocol-error registries plus explicit SDK-standard-error ownership; and exactly five versioned request/result contract pairs, with `archflow_state.artifact` temporarily disabled. Pin required request `task_id`, lexical path claims, and branded immutable connection/invocation contexts without adopting transport types. This phase adds no MCP SDK dependency, server, protocol fixtures, bundle, persistence, dispatch, durable gate lifecycle, or durable state/artifact schema. **Success Criteria**: -- [ ] Closed schemas/interfaces enumerate every field and trust source for raw finding/review, derived review, `AgentDeclaredReview`, `ServerAttestedReview`, `DegradedReview`, `ReviewEvidence`, `FindingRef`, `TriageDisposition`, `ValidatedTriage`, `AdapterObservation`, and `AuthorityLink`; verdict/count/binding fields are recomputed, untrusted, or internally minted as specified. -- [ ] Server attestation carries adapter/CLI/family/model/effort plus invocation/result/input/output linkage, is minted only behind an opaque internal capability, and persisted acceptance verifies matching receipt/state/result references; forged, schema-shaped, wrong-invocation, and wrong-digest provenance fails. -- [ ] Composite `(review_evidence_digest, finding_id)` identity dispositions cover every applicable finding exactly once, and digest-bound `ValidatedAdjudication` retains per-rule compliance findings, all `enforced_by` states, separate drift, triggers, and canonical byte-stable rendering. -- [ ] One exhaustive gate-kind decision authority drives JSON Schema/Zod/runtime contracts. `validateProjectResult(definition, parsedInput, result)` correlates every `GateSuccess.decision` with the parsed gate kind, maps illegal or corrupt results to validated `INTERNAL_ERROR`, and negative result fixtures cover every kind; waiver and supplemental choices remain separate. -- [ ] Real protocol `2025-11-25` fixtures expose exactly `archflow_state`, `archflow_counter_review`, `archflow_adjudicate`, `archflow_gate`, and `archflow_waiver`, with closed request/result schemas and no sixth tool. Known-tool parse failures return stable `CONTRACT_*` results with zero business calls; unknown/disabled names use the protocol error path; stdout is protocol-only and no listener opens. -- [ ] The complete v1 error registry fixes owner/retryability/safe diagnostics. Every project result is validated against its definition and parsed request before `CallToolResult` mapping; corrupt errors/successes and cross-tool result substitution become `INTERNAL_ERROR`. -- [ ] Exact SDK currency/upgrade fixtures couple pin, lock, low-level adapter, wire schemas, bundle, and license evidence. Tracked `dist/manifest.json` binds bundle SHA-256, Node target, package/lock, source entry, and schema/assets digests; a clean checkout starts the bundle without `node_modules`, npm, cache, network, or startup build. +- [ ] Closed schemas/interfaces enumerate every field and trust source for raw finding/review, derived review, `AgentDeclaredReview`, `ServerAttestedReview`, `DegradedReview`, `ReviewEvidence`, `FindingRef`, `TriageDisposition`, `ValidatedTriage`, `AdapterObservation`, and scope-bound `AuthorityLink`; verdict/count/binding fields are recomputed, untrusted, or internally minted as specified. +- [ ] Server attestation is minted only from an invocation-scoped observation capability containing immutable expected envelope bindings and observer-owned output bytes. Phase 2 freezes scope-bound receipt/state/result/checkpoint authority-link contracts and proves the capability seams with internal fixtures; Phase 4 and later owners verify live links/currentness. Forged, schema-shaped, wrong-policy, wrong-scope, wrong-invocation, and wrong-digest provenance cannot qualify. +- [ ] Composite `(review_evidence_digest, finding_id)` dispositions cover the exact applicable current finding set once and only once, reject stale/foreign/duplicate/missing findings, and digest-bound `ValidatedAdjudication` retains per-rule compliance findings, all `enforced_by` states, separate drift, triggers, and canonical byte-stable rendering. +- [ ] One normative gate contract catalogue defines all nine exact contexts, decision payloads, effect classes, decision envelopes, waiver origin/binding, supplemental actions, restore/migration subjects, and commit authorization over the implementation result/diff/current artifacts; cross-kind or cross-gate substitution fails. +- [ ] Exactly five correlated request/result definitions exist for `archflow_state`, `archflow_counter_review`, `archflow_adjudicate`, `archflow_gate`, and `archflow_waiver`, with no sixth tool and `archflow_state.artifact` rejected until its durable union exists. Structural result validation is distinct from expectation-based authoritative correlation; wrong invocation/gate/revision/path/semantic results fail when a later owner supplies the scoped expectation. +- [ ] Separate exhaustive project and ArchFlow protocol error registries fix per-code ownership, retryability, safe parameters, one next action, and projection eligibility; standard SDK/MCP/JSON-RPC errors have an explicit mapping boundary rather than being misrepresented as project errors. +- [ ] Internal constructors validate, copy, and freeze initialization-established connection data and per-invocation metadata exactly once while preserving `AbortSignal` as the sole live capability; repeated initialization and request identity overrides fail. No SDK or transport-owned type leaks into these interfaces. +- [ ] No MCP SDK package, MCP server, protocol fixture, tracked bundle, persistence implementation, dispatch implementation, durable gate lifecycle, or durable state/artifact schema is introduced in this phase. -### Phase 3: Repository Identity, Paths, Schemas, and Canonical Digests +### Phase 3: Inert MCP Boundary and Offline Bundle + +**Goal**: Adopt the exact MCP dependency and prove a low-level, isolated, stdio-only transport and offline release bundle over injected inert handlers. + +**Depends on**: Phase 2 + +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28, REQ-33 + +**Scope**: Recheck and adopt the exact MCP SDK and protocol pins, update dependency/license evidence, and isolate the low-level adapter behind the Phase 2 contracts. Implement singleton protocol `2025-11-25` negotiation, owned stdio lifecycle, `tools/list` and `tools/call` validation over inert injected handlers, definition-bound structural project-result projection, and cancellation without business-state side effects. Exercise the expectation consumer with internal fixtures, but leave production expectation minting to the later repository/transaction owners. Add real protocol fixtures and track `dist/archflow-mcp.js` plus `dist/manifest.json` for copy-only clean-checkout offline startup under a Node-core network/listener guard. This phase implements no persistence, dispatch, durable gate lifecycle, durable state schema, or durable artifact schema. + +**Success Criteria**: + +- [ ] Live protocol `2025-11-25` fixtures negotiate exactly once and expose exactly the five Phase 2 tools with their closed schemas; unsupported or repeated negotiation, unknown tools, and disabled operations use the protocol error path without invoking a project handler. +- [ ] The low-level adapter owns stdio startup/shutdown and protocol-only stdout, accepts only immutable connection/invocation contexts and injected inert handlers, and keeps SDK types confined to the adapter seam. +- [ ] Known-tool parse failures return stable projected `CONTRACT_*` project results with zero handler calls; every handler result is definition-correlated and structurally revalidated before projection, while malformed or cross-tool results project a safe validated `INTERNAL_ERROR`. Internal fixtures prove expectation-based authoritative rejection without claiming that the inert production boundary can mint repository paths, revisions, gate IDs, or result identities. +- [ ] Protocol cancellation reaches the injected invocation signal, returns no fabricated success, and leaves no listener, background transport, or durable side effect after shutdown. +- [ ] Live protocol fixtures cover initialization, `tools/list`, every request/result and protocol-error path, result projection, cancellation, stderr diagnostics, and stdout purity without requiring persistence or dispatch. +- [ ] Exact SDK/protocol currency evidence records the checked version, release/source, lockfile identity, adapter fixture expectations, and permissive license result; pin/lock/fixture drift fails verification. +- [ ] Tracked `dist/manifest.json` binds bundle SHA-256, Node target, package/lock, source entry, and schema/assets digests. A clean checkout copy starts the bundle without `node_modules`, npm, cache, network, or startup build, while a Node-core guard proves no network or listener API is opened. + +### Phase 4: Repository Identity, Paths, Schemas, and Canonical Digests **Goal**: Establish the repository/task identity, path safety, durable schemas, immutable task configuration, and byte-stable digest contracts used by every mutation. -**Depends on**: Phases 1 and 2 +**Depends on**: Phases 1–3 **Requirements**: REQ-04, REQ-05, REQ-11, REQ-13, REQ-14, REQ-21, REQ-26, REQ-33, REQ-39, REQ-50 @@ -449,15 +470,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Valid state/initialization/document/implementation/import/checkpoint/maintenance samples round-trip through normative schemas; predecessor gaps, unknown fields, digest mismatches, invalid phase IDs, and contradictory accounting fail with stable errors. - [ ] Startup and pull/handoff detection identifies divergent histories and `.archflow/**` conflicts as non-authoritative without claiming it can detect independent-clone concurrency before divergence. -### Phase 4: Transaction Kernel, Intent/CAS, and Crash Recovery +### Phase 5: Transaction Kernel, Intent/CAS, and Crash Recovery **Goal**: Commit one task's transitions exactly once under races, crashes, retries, config drift, and bounded reconciliation. -**Depends on**: Phase 3 +**Depends on**: Phase 4 **Requirements**: REQ-04, REQ-08, REQ-13, REQ-14, REQ-21, REQ-22, REQ-23, REQ-24, REQ-26, REQ-39, REQ-50 -**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 5. +**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 6. **Success Criteria**: @@ -468,15 +489,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Mature-task step boundaries and status reconcile only current state projections, the relevant active/prepared intent, and active gate/checkpoint head; only explicit repair/import/audit walks history. - [ ] Divergent/conflicted clones remain non-authoritative until preserve-both-heads repair selects/replays one successor chain and records a clean one-writer handoff. -### Phase 5: Snapshots, Implementation Manifests, and Restore +### Phase 6: Snapshots, Implementation Manifests, and Restore **Goal**: Retain and restore deterministic declared outputs within explicit storage, retention, collision, and secret-safety bounds. -**Depends on**: Phase 4 +**Depends on**: Phase 5 **Requirements**: REQ-08, REQ-11, REQ-13, REQ-21, REQ-22, REQ-23, REQ-25, REQ-26, REQ-33, REQ-39, REQ-50 -**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 6 connects collision decisions to the gate service. +**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 7 connects collision decisions to the gate service. **Success Criteria**: @@ -487,11 +508,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Secret fixtures in any candidate Git-tracked snapshot/checkpoint projection fail before projection with safe remediation warning that later `.archflow/` deletion cannot erase branch history; clean binary/text fixtures pass without logging secret values. - [ ] Snapshot/projection/restore fault injection preserves prior/next authority or exact repair, and the three `restore-collision` outcomes are representable without silent overwrite. -### Phase 6: Durable Gates, Waivers, and Manual Decisions +### Phase 7: Durable Gates, Waivers, and Manual Decisions **Goal**: Persist every human authority boundary independently of a live MCP request. -**Depends on**: Phase 5 +**Depends on**: Phase 6 **Requirements**: REQ-09, REQ-13, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -507,11 +528,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] `waiver-requested` is non-advancing and archives the current gate before the sole waiver gate opens; grant resumes only the recorded rule/scope, denial remains non-advancing, and no nested gate exists. `restore-collision` exposes only discard-and-restore, adopt-as-new-generation with changed inputs/fingerprint and rationale, or abort. - [ ] A real Claude host timeout leaves one pending gate, and a later invocation resumes and resolves that gate exactly once; timeout-then-resume is normal supported behavior. -### Phase 7: Host Identity, Sandbox, and CLI Dispatch +### Phase 8: Host Identity, Sandbox, and CLI Dispatch **Goal**: Prove fresh opposite-family reviewer processes receive only declared envelopes and are safe to dispatch on every claimed environment. -**Depends on**: Phases 1–6 +**Depends on**: Phases 1–7 **Requirements**: REQ-26, REQ-29, REQ-30, REQ-31, REQ-32, REQ-34, REQ-35 @@ -528,11 +549,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Any external sandbox dependency and license is presented for explicit acceptance before adoption; copyleft is never silently bundled. - [ ] The Anthropic subscription-authenticated dispatch path remains release-disabled until written clarification or a qualified legal determination satisfies `VAL-14`; implementation or fixture success is not legal approval. -### Phase 8: Constitution Adjudication, Drift, and Review Fixed Point +### Phase 9: Constitution Adjudication, Drift, and Review Fixed Point **Goal**: Turn validated reviewer output and pinned policy/upstream inputs into current-digest advancement evidence. -**Depends on**: Phases 1–7 +**Depends on**: Phases 1–8 **Requirements**: REQ-10, REQ-11, REQ-12, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-32, REQ-33 @@ -545,15 +566,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Positive, negative, and uncertain triggers plus current/missing/stale/failed mechanical evidence behave fail-closed against the approved policy-base constitution. - [ ] Aligned and incidental drift are recorded correctly; material drift gates and an accepted change reopens the affected upstream approval/evidence chain. -### Phase 9: Five-Tool MCP Assembly and Offline Local CLI +### Phase 10: Five-Tool MCP Assembly and Offline Local CLI **Goal**: Assemble persistence, dispatch, adjudication, and decisions behind the complete and only MCP workflow surface. -**Depends on**: Phases 1–8 +**Depends on**: Phases 1–9 **Requirements**: REQ-07, REQ-08, REQ-11, REQ-13, REQ-21, REQ-23, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40 -**Scope**: Wire exactly five handlers through the v2 adapter and implement `archflow-local` for validate, hash, render, snapshot/restore, human-approved maintenance with immutable records, atomic decisions, degraded status, reconcile/import, upgrade staging, and immutable checkpoint creation/chain validation. Connect mutation/replay, dispatch, evidence, supplemental interruption, cancellation, protocol-only stdout, and public errors. Rebuild the Phase 2 tracked bundle and `dist/manifest.json` for the full server/helper assembly. Init and upgrade remain outside the tool list. +**Scope**: Wire exactly five handlers through the v2 adapter and implement `archflow-local` for validate, hash, render, snapshot/restore, human-approved maintenance with immutable records, atomic decisions, degraded status, reconcile/import, upgrade staging, and immutable checkpoint creation/chain validation. Connect mutation/replay, dispatch, evidence, supplemental interruption, cancellation, protocol-only stdout, and public errors. Rebuild the Phase 3 tracked bundle and `dist/manifest.json` for the full server/helper assembly. Init and upgrade remain outside the tool list. **Success Criteria**: @@ -565,15 +586,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] `archflow-local checkpoint` atomically extends only a valid reconciled chain, and server adoption imports only its greatest valid checkpoint via the closed union tag. - [ ] The updated tracked manifest binds the complete server/helper bundle to current package/lock/source/schema/assets digests and passes clean-checkout offline startup before installer work. -### Phase 10: Installer, Initialization, and Host Registration +### Phase 11: Installer, Initialization, and Host Registration **Goal**: Install the offline bundle and initialize supported repositories repeatedly without damaging host or project configuration. -**Depends on**: Phases 1, 7, and 9 +**Depends on**: Phases 1, 8, and 10 **Requirements**: REQ-01, REQ-02, REQ-28, REQ-29, REQ-34, REQ-37, REQ-40 -**Scope**: Verify the Phase 9 tracked bundle/manifest, then extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. +**Scope**: Verify the Phase 10 tracked bundle/manifest, then extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. **Success Criteria**: @@ -585,11 +606,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Initialized state is Git-trackable/shareable, contains no machine-specific executable path in portable task state, and works after repository relocation and in linked/space/Unicode worktrees. - [ ] `archflow-init` creates no task state and no commit. Fresh task creation refuses to start until workflow/constitution assets resolve from an explicitly approved immutable commit and then stages the normal initialization manifest. -### Phase 11: Normal-Mode Thin Phase Skills and Truthful Status +### Phase 12: Normal-Mode Thin Phase Skills and Truthful Status **Goal**: Drive the normal MCP workflow from host-neutral phase skills and report only reconciled durable truth. -**Depends on**: Phases 1–10 +**Depends on**: Phases 1–11 **Requirements**: REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-13, REQ-14, REQ-20, REQ-41 @@ -603,11 +624,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] The server sees only complete supplemental projections through filesystem notification plus bounded polling fallback. The gate-pending transition table admits only supplemental ingestion, triage, explicit decline/decision, cancellation, or supersession; `SUPPLEMENTAL_REVIEW_REQUIRED` rejection resumes the gate and accepted change supersedes it and re-enters the fixed point. - [ ] Status verifies the immutable whole-config digest before recommending work; `PINNED_CONFIG_MISMATCH` reports no config content and recommends only a distinct new task or explicit upgrade for intentional routing/model/effort changes. -### Phase 12: Manual and Degraded Recovery Workflow +### Phase 13: Manual and Degraded Recovery Workflow **Goal**: Complete and recover the workflow conservatively when individual MCP tools or the server are unavailable. -**Depends on**: Phases 1–11 +**Depends on**: Phases 1–12 **Requirements**: REQ-08, REQ-09, REQ-11, REQ-12, REQ-13, REQ-14, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41 @@ -621,11 +642,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Supplemental-review arrival, rejection/resume, accepted-change supersession, explicit decline, cancellation, and restart behave identically to normal-mode milestones. - [ ] Manual operation never auto-commits/pushes and documents clean human-approved checkpoint handoff between writers. -### Phase 13: Legacy Upgrade Workflow +### Phase 14: Legacy Upgrade Workflow **Goal**: Migrate selected legacy material into a distinct canonical task without changing or implicitly approving the source. -**Depends on**: Phases 3–6, 8, 9, 11, and 12 +**Depends on**: Phases 4–7, 9, 10, 12, and 13 **Requirements**: REQ-02, REQ-04, REQ-09, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -640,11 +661,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Pure manual upgrade begins with a validating legacy-initialization checkpoint and later server recovery adopts its chain without changing the source or replaying decisions. - [ ] The repository's current legacy task layout upgrades through the same fixture path, and release guidance tells users with in-flight tasks how to finish in legacy tooling or checkpoint/handoff into a distinct upgraded task without silent in-place conversion. -### Phase 14: Reliability and Security Matrices +### Phase 15: Reliability and Security Matrices **Goal**: Prove persistence, race, path, process, and isolation invariants under adversarial failures. -**Depends on**: Phases 1–13 +**Depends on**: Phases 1–14 **Requirements**: REQ-04, REQ-05, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-50 @@ -660,11 +681,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Binary/mode/rename/delete restore, manual recovery, and legacy staging remain collision-safe under fault injection; tracked canonical blob/tree identities remain stable across attributes, LF/CRLF and `core.autocrlf`, `core.fileMode`, executable-bit, and symlink checkout cases. - [ ] Boundary and over-limit payload matrices prove 25 MiB/result and 250 MiB/task enforcement, no truncation/hidden authority, authoritative/evidence retention, maintenance reachability records, and pre-projection secret rejection under crashes and retries. -### Phase 15: Real-Host E2E and Review-Quality Validation +### Phase 16: Real-Host E2E and Review-Quality Validation **Goal**: Validate useful independent review and complete normal, manual, and migration journeys in both producer directions. -**Depends on**: Phases 1–14 +**Depends on**: Phases 1–15 **Requirements**: REQ-01, REQ-02, REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -681,11 +702,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] A real task reaches the snapshot boundaries, receives `SNAPSHOT_LIMIT` above either cap without partial authority, retains all current/evidence chains, records a safe maintenance prune, and rejects a secret-bearing checkpoint before Git projection. - [ ] The approved corpus thresholds demonstrate substantive defect detection and acceptable false blockers; failure of `VAL-02` reopens the automation premise. -### Phase 16: Release Packaging, Support Matrix, and Documentation Consistency +### Phase 17: Release Packaging, Support Matrix, and Documentation Consistency **Goal**: Produce a coherent beta release candidate and an explicit report of any remaining external release blockers. -**Depends on**: Phases 1–15 +**Depends on**: Phases 1–16 **Requirements**: REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -704,22 +725,23 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali | Phase | Name | Status | |-------|------|--------| -| 1 | Contracts, Assets, and Package Scaffold | Not Started | -| 2 | Review Evidence and Inert MCP Boundary | Not Started | -| 3 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | -| 4 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | -| 5 | Snapshots, Implementation Manifests, and Restore | Not Started | -| 6 | Durable Gates, Waivers, and Manual Decisions | Not Started | -| 7 | Host Identity, Sandbox, and CLI Dispatch | Not Started | -| 8 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | -| 9 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | -| 10 | Installer, Initialization, and Host Registration | Not Started | -| 11 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | -| 12 | Manual and Degraded Recovery Workflow | Not Started | -| 13 | Legacy Upgrade Workflow | Not Started | -| 14 | Reliability and Security Matrices | Not Started | -| 15 | Real-Host E2E and Review-Quality Validation | Not Started | -| 16 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | +| 1 | Contracts, Assets, and Package Scaffold | COMPLETE (2026-07-27) | +| 2 | Review Evidence and Contract Authority | Not Started | +| 3 | Inert MCP Boundary and Offline Bundle | Not Started | +| 4 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | +| 5 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | +| 6 | Snapshots, Implementation Manifests, and Restore | Not Started | +| 7 | Durable Gates, Waivers, and Manual Decisions | Not Started | +| 8 | Host Identity, Sandbox, and CLI Dispatch | Not Started | +| 9 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | +| 10 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | +| 11 | Installer, Initialization, and Host Registration | Not Started | +| 12 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | +| 13 | Manual and Degraded Recovery Workflow | Not Started | +| 14 | Legacy Upgrade Workflow | Not Started | +| 15 | Reliability and Security Matrices | Not Started | +| 16 | Real-Host E2E and Review-Quality Validation | Not Started | +| 17 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | --- *Created: 2026-07-26* diff --git a/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority.md b/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority.md new file mode 100644 index 00000000..5e0a26d2 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority.md @@ -0,0 +1,935 @@ +# Phase 2: Review Evidence and Contract Authority + +**Status**: DESIGNED +**Task**: mcp-integration +**Goal**: Freeze the trust-bearing semantic, provenance, gate, error, tool, connection, and invocation contracts before any MCP transport or durable workflow implementation adopts them. +**Requirements**: REQ-04, REQ-05, REQ-10, REQ-11, REQ-12, REQ-13, REQ-15, REQ-17, REQ-18, REQ-19, REQ-20, REQ-23, REQ-27, REQ-33, REQ-36, REQ-37, REQ-41, REQ-50 + +## Context + +Phase 1 established the private ESM package, recursive plain-JSON preflight, strict non-mutating Ajv 2020 validation, strict Zod mirrors, canonical phase-instance codecs, and the first six normative v1 schemas. Phase 2 extends those patterns: JSON Schema remains normative, every parser accepting `unknown` performs the plain-JSON preflight, Zod mirrors reject unknown fields without transforming input, and agreement/non-mutation tests protect every overlapping representation. `SCHEMA_IDS` and the public contracts barrel remain the discovery points. + +The approved architecture split keeps this phase transport-neutral. It freezes evidence, capability, gate, error, five-tool, and invocation seams that later implementations must adopt, but it does not install or use an MCP SDK, start a server, negotiate a protocol, create protocol fixtures, produce `dist/`, or change package, lock, CI, dependency, or release surfaces. Phase 4 computes canonical repository digests and decides currentness; this phase validates SHA-256 syntax, compares supplied identities, and supplies only internal test doubles for future observation and authority capabilities. + +## What We're Building + +We will define normative v1 schemas and strict TypeScript contracts for review, triage, and adjudication evidence. Review and adjudication each follow the same trust ladder: raw observed output is semantically derived, then wrapped as agent-declared, server-attested, or degraded evidence. Semantic correctness does not imply provenance or authority. Every persisted or transported evidence value uses the non-self-referential `ReferencedEvidence` wrapper, whose digest identifies the enclosed evidence but is never embedded in that evidence. An internal trust module derives bindings from the observed envelope before it can mint server attestation; a separate future-owner authority capability qualifies every provenance variant and mints the exact `CurrentReviewSet` needed by triage. + +We will also freeze an independent nine-kind gate catalogue with object-shaped, kind-correlated decision payloads; separate exhaustive project and protocol error registries; exactly five literal-keyed request/success contract pairs; and immutable transport-neutral connection/invocation contexts. Canonical renderers consume only qualified or branded validated JSON and produce deterministic Markdown. These contracts deliberately contain no persistence, durable state or artifact schema, authority implementation, dispatcher, MCP adapter, or wire projection. + +**External dependency surface**: none. Phase 2 uses only the exact Phase 1 dependency graph. + +## Files + +| Action | File | Purpose | +|--------|------|---------| +| Modify | `src/contracts/index.ts`, `src/contracts/versions.ts` | Export the public Phase 2 contract surface and register every independently addressable Phase 2 schema ID. | +| Create | `src/contracts/evidence.ts`, `src/contracts/review.ts`, `src/contracts/adjudication.ts`, `src/contracts/triage.ts`, `src/contracts/supplemental.ts` | Define canonical digest syntax, raw/derived/provenance evidence, structured evidence slots, exact-set triage, external evidence references, supplemental choices, and opaque qualification seams. | +| Create | `src/contracts/trust.ts`, `src/contracts/internal/test-capabilities.ts` | Define observation/authority capability consumers and non-public fixture factories; only the internal test module can create fake capabilities. | +| Create | `src/contracts/renderers.ts` | Render qualified review/adjudication evidence and branded triage deterministically from validated JSON. | +| Create | `src/contracts/gates.ts`, `src/contracts/errors.ts`, `src/contracts/tool-names.ts`, `src/contracts/mcp-tools.ts`, `src/contracts/contexts.ts`, `src/contracts/path-claims.ts` | Freeze the single gate catalogue, per-code error registries, shared five-name vocabulary, five correlated tool pairs, lexical path claims, and branded transport-neutral contexts. | +| Create | `src/contracts/schemas/v1/{review,review-evidence,adjudication,adjudication-evidence,evidence-reference,authority-link,evidence-slots,triage,supplemental-review,gate-contract,gate-decision,project-error,protocol-error,mcp-tools,result-expectation,path-claim}.schema.json` | Publish the complete, independently addressable strict JSON Schema 2020-12 authority without introducing state or artifact schemas. | +| Create | `test/unit/{review,adjudication,triage,supplemental,renderers,gates,errors,mcp-tools,contexts,path-claims}.test.ts` | Verify semantic derivation, capability barriers, exact coverage, deterministic rendering, decision/result correlation, registry exhaustiveness, and immutable context behavior. | +| Create | `test/contracts/{review-schema-agreement,authority-schema-agreement,mcp-contract-agreement}.test.ts`, `test/fixtures/contracts/{review,adjudication,triage,supplemental,gates,errors,mcp-tools}/**` | Exercise JSON Schema/Zod agreement, non-mutation, closed-shape negative corpora, all provenance/gate/supplemental variants, and cross-contract substitutions. | +| Modify | `scripts/smoke-temp-bundle.mjs` | Exercise representative Phase 2 parsing/rendering, both error registries, and all five definitions through the temporary ESM bundle. | + +No `package.json`, lockfile, dependency policy, notice, CI, release-build script, `src/main.ts`, `src/mcp/`, `src/repository/`, `src/state/`, `src/dispatch/`, `src/decisions/`, `src/init/`, `src/local/`, `dist/`, live protocol fixture, install, registration, or skill file changes in this phase. No durable `state.json`, artifact/import/checkpoint/snapshot, receipt, decision-file, repository identity, or resolved-safe-path schema enters the Phase 2 schema tree. + +The listed JSON Schemas cover only serializable public values: raw/derived/provenance evidence, external evidence references, authority-link data, triage candidates/results, gate request contexts and decision envelopes, error values, the five tool request/result contracts, and unbranded result-expectation data. `ObservationCapability`, `VerifiedReferencedEvidence`, branded `AuthorityLink`, qualified evidence, `CurrentReviewSetAuthority`, `CurrentReviewSet`, parsed-call/result brands, branded `ResultExpectation`, immutable connection/invocation objects, and `AbortSignal` are runtime-only values with no JSON representation; their underlying serializable link/context/expectation data is validated before a later owner mints the opaque runtime form. + +## Contract Interfaces + +### Evidence identities and trust ladder + +The external wrapper is the only serializable value that pairs an evidence payload with its digest. It is deliberately non-self-referential: canonical repository code in Phase 4 computes the digest over `evidence`, not over the wrapper. Authority links and finding references may repeat that digest as an identity but never embed another evidence payload. Phase 2 validates digest syntax and compares identities but never claims to calculate repository-canonical bytes or currentness. + +`Sha256Digest` has one canonical lexical representation: exactly 64 lowercase ASCII hexadecimal characters matching `^[0-9a-f]{64}$`, with no prefix, whitespace, or Unicode lookalikes. JSON Schema, Zod, and `parseSha256Digest` reject uppercase, `sha256:`-prefixed, padded, short, and long aliases. + +```ts +declare const sha256DigestBrand: unique symbol; +export type Sha256Digest = string & { readonly [sha256DigestBrand]: true }; +export function parseSha256Digest(value: unknown): Sha256Digest; + +export interface ReferencedEvidence { + readonly evidence_digest: Sha256Digest; + readonly evidence: T; +} + +export type ReviewVerdict = "pass" | "advisory" | "fail"; +export interface FindingRef { + readonly review_evidence_digest: Sha256Digest; + readonly finding_id: string; +} + +export function parseAndDeriveReview(value: unknown): DerivedReview; +export function parseAndDeriveAdjudication(value: unknown): DerivedAdjudication; + +export type ReviewEvidence = + | AgentDeclaredReview + | ServerAttestedReview + | DegradedReview; +export type AdjudicationEvidence = + | AgentDeclaredAdjudication + | ServerAttestedAdjudication + | DegradedAdjudication; +``` + +`RawReview` contains model/agent-authored findings and untrusted claims only. Derivation recomputes blocking count and verdict from closed finding severity/blocking semantics, rejects contradictions, and does not mutate input. `RawAdjudication` is similarly checked into `DerivedAdjudication`: it binds supplied subject, declared-input, pinned-constitution, approved-upstream, and source-evidence identities; retains per-rule/version compliance findings and every `enforced_by` state (`current`, `missing`, `stale`, `unknown`, `failed`, or `digest-mismatch`); and keeps constitution compliance, drift (`aligned`, `incidental`, or `material`), and matched/uncertain triggers independent. Missing or suspect mechanical evidence cannot be upgraded to compliance. + +Both families then use distinct closed provenance variants. Agent-declared evidence records model/effort as declared values or `unknown`; server-attested evidence records adapter, CLI, canonical family/model, effort, invocation, envelope-input, observed-output, and result linkage derived from one observed envelope; degraded evidence records a reason and can never claim server assurance. Variant tags and fields cannot be substituted across families or assurance levels. + +```ts +declare const observationCapabilityBrand: unique symbol; +declare const authorityLinkBrand: unique symbol; +declare const verifiedReferencedEvidenceBrand: unique symbol; +declare const currentReviewSetAuthorityBrand: unique symbol; + +export type EvidenceKind = "review" | "adjudication"; +export type Assurance = "agent-declared" | "server-attested" | "degraded"; +export interface EvidenceValueByKindAndAssurance { + readonly review: { + readonly "agent-declared": AgentDeclaredReview; + readonly "server-attested": ServerAttestedReview; + readonly degraded: DegradedReview; + }; + readonly adjudication: { + readonly "agent-declared": AgentDeclaredAdjudication; + readonly "server-attested": ServerAttestedAdjudication; + readonly degraded: DegradedAdjudication; + }; +} +export interface EvidenceRoleByKind { + readonly review: ReviewRole; + readonly adjudication: "adjudication"; +} +export interface ObservationRoleByKind { + readonly review: "counter-review" | "gate-counter-review"; + readonly adjudication: "adjudication"; +} +export type AdapterId = "claude-cli" | "codex-cli"; +export type ModelFamily = "claude" | "codex"; +export interface ObservationBindingBase { + readonly kind: K; + readonly task_id: string; + readonly phase_instance: PhaseInstanceId; + readonly role: ObservationRoleByKind[K]; + readonly subject_digest: Sha256Digest; + readonly input_fingerprint: Sha256Digest; + readonly invocation_id: string; + readonly envelope_input_digest: Sha256Digest; + readonly result_id: string; + readonly adapter: AdapterId; + readonly cli_version: string; + readonly family: ModelFamily; + readonly model: string; + readonly effort: (typeof REASONING_EFFORTS)[number]; +} +export interface ObservationBindingByKind { + readonly review: ObservationBindingBase<"review"> & ({ + readonly role: "counter-review"; + } | { + readonly role: "gate-counter-review"; + readonly gate_id: string; + }) & { + readonly rubric_digest: Sha256Digest; + readonly producer_family: ModelFamily; + }; + readonly adjudication: ObservationBindingBase<"adjudication"> & { + readonly pinned_constitution_digest: Sha256Digest; + readonly approved_upstream_digests: readonly Sha256Digest[]; + readonly source_evidence_set_digest: Sha256Digest; + }; +} +export type ObservationCapability = { + readonly kind: K; + readonly [observationCapabilityBrand]: K; +}; +export type AdapterObservation = { + readonly [P in K]: ObservationBindingByKind[P] & { + readonly raw_output_bytes: Uint8Array; + readonly raw_output_digest: Sha256Digest; + }; +}[K]; +export interface ObservationSource { + readonly observeReview: ( + capability: ObservationCapability<"review">, + observed_output_bytes: Uint8Array + ) => Readonly<{ observation: AdapterObservation<"review">; evidence: ServerAttestedReview }>; + readonly observeAdjudication: ( + capability: ObservationCapability<"adjudication">, + observed_output_bytes: Uint8Array + ) => Readonly<{ observation: AdapterObservation<"adjudication">; evidence: ServerAttestedAdjudication }>; +} + +export interface ServerAuthorityReferences { + readonly kind: "server"; + readonly invocation_id: string; + readonly result_id: string; + readonly receipt_id: string; + readonly state_revision: number; + readonly envelope_input_digest: Sha256Digest; + readonly observed_output_digest: Sha256Digest; + readonly result_digest: Sha256Digest; +} +export interface AgentDeclaredAuthorityReferences { + readonly kind: "agent-declared"; + readonly result_id: string; + readonly result_digest: Sha256Digest; + readonly state_revision: number; +} +export interface DegradedAuthorityReferences { + readonly kind: "degraded"; + readonly checkpoint_digest: Sha256Digest; + readonly checkpoint_revision: number; +} +export interface AuthorityReferencesByAssurance { + readonly "agent-declared": AgentDeclaredAuthorityReferences; + readonly "server-attested": ServerAuthorityReferences; + readonly degraded: DegradedAuthorityReferences; +} +export interface AuthorityLinkBase { + readonly schema_version: "1"; + readonly evidence_kind: K; + readonly assurance: A; + readonly role: EvidenceRoleByKind[K]; + readonly task_id: string; + readonly phase_instance: PhaseInstanceId; + readonly subject_digest: Sha256Digest; + readonly input_fingerprint: Sha256Digest; + readonly evidence_digest: Sha256Digest; + readonly authority: AuthorityReferencesByAssurance[A]; +} +export type AuthorityLinkData< + K extends EvidenceKind = EvidenceKind, + A extends Assurance = Assurance +> = { readonly [P in K]: { readonly [Q in A]: AuthorityLinkBase }[A] }[K]; +export type AuthorityLink< + K extends EvidenceKind = EvidenceKind, + A extends Assurance = Assurance +> = { readonly [P in K]: { + readonly [Q in A]: AuthorityLinkBase & { + readonly [authorityLinkBrand]: `${P}:${Q}`; + }; +}[A] }[K]; +export type VerifiedReferencedEvidence< + K extends EvidenceKind = EvidenceKind, + A extends Assurance = Assurance +> = { readonly [P in K]: { + readonly [Q in A]: ReferencedEvidence & { + readonly [verifiedReferencedEvidenceBrand]: `${P}:${Q}`; + }; +}[A] }[K]; +export type ReviewEvidenceSlot = + | Readonly<{ + role: "self-review"; + evidence_digest: Sha256Digest; + assurance: "agent-declared"; + producer_family: ModelFamily; + reviewer_family: ModelFamily; + independence: "same-family-self"; + }> + | Readonly<{ + role: "counter-review"; + evidence_digest: Sha256Digest; + assurance: "server-attested" | "degraded"; + producer_family: ModelFamily; + reviewer_family: ModelFamily; + independence: "opposite-family"; + }> + | Readonly<{ + role: "gate-counter-review"; + evidence_digest: Sha256Digest; + assurance: "server-attested" | "degraded"; + producer_family: ModelFamily; + reviewer_family: ModelFamily; + independence: "opposite-family"; + gate_id: string; + }>; +export type RequiredReviewSlots = + | readonly [Extract, Extract] + | readonly [Extract, Extract, Extract]; +export interface CurrentReviewSetAuthority { + readonly task_id: string; + readonly phase_instance: PhaseInstanceId; + readonly subject_digest: Sha256Digest; + readonly input_fingerprint: Sha256Digest; + readonly slots: RequiredReviewSlots; + readonly [currentReviewSetAuthorityBrand]: true; +} +export interface CurrentEvidenceSetRef { + readonly set_digest: Sha256Digest; + readonly slots: RequiredReviewSlots; +} + +export interface AuthorityQualifier { + readonly qualifyReview: ( + link: AuthorityLink<"review", A>, + value: NoInfer> + ) => QualifiedReviewEvidenceByAssurance[A]; + readonly qualifyAdjudication: ( + link: AuthorityLink<"adjudication", A>, + value: NoInfer> + ) => QualifiedAdjudicationEvidenceByAssurance[A]; + readonly currentReviews: ( + authority: CurrentReviewSetAuthority, + reviews: readonly QualifiedReviewEvidence[] + ) => CurrentReviewSet; +} +``` + +Later dispatch mints one `ObservationCapability` from immutable `ObservationBindingByKind[K]`; the caller of `observe*` supplies only the output bytes actually read from that invocation. The trust module copies those bytes, computes `raw_output_digest` as SHA-256 over the exact unmodified byte sequence, parses/derives internally, and compares every model-supplied identity against the capability's expected bindings. Adjudication additionally compares the exact pinned constitution, sorted approved-upstream, and source-evidence-set identities. Review checks the rubric and producer/reviewer family relation; the observed role is closed to `counter-review` or gate-bound `gate-counter-review`, so this seam cannot mint a server-attested self-review. Self-review is agent-declared only. The resulting `AdapterObservation` and attestation therefore share one invocation scope; arbitrary adapter/family/effort strings or separately claimed digests cannot enter. The module never creates `ReferencedEvidence`; Phase 4's canonical-content authority hashes the derived evidence payload, creates the public wrapper, verifies wrapper/payload equality on read, and alone mints runtime-only `VerifiedReferencedEvidence`. + +`AuthorityLink` is scope-bound rather than a reusable global capability. Its mapped discriminants make evidence kind determine the legal role/value family and assurance determine the only legal authority-reference shape. Later state/checkpoint owners validate those references and mint a link for exactly one evidence digest, kind, role, task, phase, subject, and input fingerprint. Qualification requires both that matching link and Phase 4's `VerifiedReferencedEvidence`, checks every scope field, preserves the provenance tag, and is idempotent for the identical link plus verified wrapper. Reuse with different bytes, digest, scope, or provenance fails; process-local consumption state is never authority. A separate `CurrentReviewSetAuthority` names the exact common scope and slot set described below. Current-set construction accepts that set exactly—never an arbitrary qualified array. + +Public JSON, an altered payload under a retained digest, mutually consistent forged objects, independently supplied bindings, a link from another scope, or copied brand-shaped values cannot mint verified references, capabilities, authority links, qualified evidence, or a current set. Internal test factories are reachable only by direct internal test import and absent from `src/contracts/index.ts`. Phase 2 proves type/runtime correlation and replay/substitution rejection with those fixtures; it does not verify live dispatch observations, persisted receipts/state, manual checkpoint authority, repository digest bytes, or currentness. + +The digest domains are closed and non-self-referential: + +| Digest | Exact byte domain | Owner / exclusion | +|--------|-------------------|-------------------| +| `raw_output_digest` | Exact CLI stdout result bytes before parsing or newline normalization | Observation trust computes it; it excludes the observation and attestation. | +| `evidence_digest` | Phase 4 canonical JSON bytes of the derived provenance evidence payload only | Excludes `ReferencedEvidence`, authority links, result manifests, receipts, and state. | +| `result_digest` | Phase 4 canonical JSON bytes of the closed version-1 `ResultIdentityPayload` defined below | Includes tool, task, intent, input fingerprint, request digest, result ID, resulting revision, and exact success; excludes its own digest, authority links, intent receipts, and state references. | +| `authority_link_digest` | Phase 4 canonical bytes of serializable `AuthorityLinkData` | The digest is carried only by `AuthorityLinkRef`, never inside `AuthorityLinkData`. | +| `context_digest` | Phase 4 canonical bytes of the kind-correlated gate context only | Excludes common `GateInput` fields, `gate_id`, and the decision envelope. | +| `request_digest` | The architecture's closed canonical request field list, including common request fields and context digest | Excludes `intent_id`, `expected_revision`, connection metadata, `gate_id`, decisions, receipts, and state. | + +Retained result/receipt/state/checkpoint validators, not object identity or a consumed-token cache, establish replay authority after restart. + +### Exact triage and canonical rendering + +```ts +export type TriageDisposition = AcceptedDisposition | RejectedDisposition; +export function validateTriage( + current: CurrentReviewSet, + candidate: unknown +): ValidatedTriage; + +export function renderReviewEvidence(value: QualifiedReviewEvidence): Uint8Array; +export function renderTriage(value: ValidatedTriage): Uint8Array; +export function renderAdjudicationEvidence( + value: QualifiedAdjudicationEvidence +): Uint8Array; +``` + +`CurrentReviewSetAuthority.slots` is a canonical tuple ordered self, counter, then optional gate-counter. Roles are unique; self-review is same-family agent-declared, while counter and gate-counter slots are cross-family even when degraded, and a gate-counter slot binds the exact gate ID. The producer and reviewer families must differ for both counter slots. `CurrentEvidenceSetRef` is the serializable structured gate binding; bare or reordered digest arrays are invalid. + +`validateTriage(CurrentReviewSet, unknown)` treats every finding from every required current slot as applicable, including advisory/non-blocking findings. It requires each `(review_evidence_digest, finding_id)` exactly once and rejects duplicate composite references, omissions, foreign reviews, stale-set identities, duplicate slots, and duplicate finding IDs within one review. Equal local IDs in different review digests are valid. A zero-finding pass has an empty disposition list; an advisory review dispositions all advisory findings. Rejected dispositions require evidence; accepted dispositions express revision-producing intent and do not authorize advancement. + +Renderers accept only qualified evidence or branded validated triage—not raw, derived, or merely schema-valid public values. Each begins with the literal H1 and metadata keys below, in this order; optional values render as the literal `none`, never by omitting or reordering a key. + +| Artifact | Literal H1 | Ordered metadata keys | +|----------|------------|-----------------------| +| Review | `# ArchFlow Review Evidence` | `schema_version`, `task_id`, `phase_instance`, `step`, `role`, `subject_digest`, `input_fingerprint`, `evidence_digest`, `verdict`, `blocking_count`, `matched_rule_versions`, `assurance`, `adapter`, `cli_version`, `model_family`, `model`, `effort`, `invocation_id`, `result_id` | +| Triage | `# ArchFlow Review Triage` | `schema_version`, `task_id`, `phase_instance`, `step`, `subject_digest`, `input_fingerprint`, `current_evidence_set_digest`, `source_evidence_digests`, `accepted_count`, `rejected_count` | +| Adjudication | `# ArchFlow Adjudication Evidence` | `schema_version`, `task_id`, `phase_instance`, `step`, `subject_digest`, `input_fingerprint`, `evidence_digest`, `pinned_constitution_digest`, `approved_upstream_digests`, `source_evidence_set_digest`, `constitution`, `drift`, `matched_rule_versions`, `uncertain_rule_versions`, `assurance`, `adapter`, `cli_version`, `model_family`, `model`, `effort`, `invocation_id`, `result_id` | + +Trusted metadata is rendered as canonical scalar or JSON values beneath that header. Every untrusted prose field is emitted only as an indented canonical JSON string under a fixed trusted label; CR, LF, tab, C0/C1 controls, bidi controls, backticks, `<`, `>`, and `&` are visibly `\u`-escaped, so prose cannot create headings, tables, links, fences, or raw HTML. Collections use schema-defined canonical ordering, arrays render as canonical JSON, output is UTF-8 with LF line endings and exactly one terminal LF. Renderers preserve assurance distinctions and render from the qualified validated JSON value only; they do not parse Markdown, compute digests, query repository state, infer provenance, or decide currentness. + +### Gate, waiver, and supplemental authority + +`gate-contract.schema.json` is the one normative nine-kind catalogue. Each kind contains its exact context schema and decision variants; every decision variant carries its own `x-archflow-effect` annotation (`advance`, `retry`, `redirect-waiver`, `redirect-upstream`, or `non-advancing`). TypeScript, Zod, runtime effect lookup, and fixtures mirror and agreement-check that file; no parallel prose effect registry is authoritative. `GateInput` owns task, phase, subject, input fingerprint, and structured current evidence exactly once. Kind context contains only the fields below and never `gate_id`. The later gate service derives `gate_id` after hashing the closed request. + +```ts +export interface RuleVersionRef { readonly rule_id: string; readonly rule_version: number } +export type EvidenceIdentityKind = "prd" | "architecture" | "phase-design" | "implementation-result" | "review" | "adjudication" | "constitution" | "workflow" | "import"; +export interface EvidenceIdentityRef { readonly kind: EvidenceIdentityKind; readonly digest: Sha256Digest } +export type WaivableOperation = "review-trigger" | "adjudication-failure"; +export interface WaiverScope { readonly operation: WaivableOperation; readonly boundary: "subject" | "phase" | "task" } +export interface HumanRuleResolution { readonly rule: RuleVersionRef; readonly resolution: string } +// PipelineStep is reused from Phase 1's src/contracts/vocabulary.ts. +export type HumanDecisionProvenance = + | Readonly<{ + schema_version: "1"; + actor_class: "human" | "archforge"; + assurance: "declared-local-trace"; + channel: "connected-host"; + decision_event_id: string; + connection_id: string; + request_id_digest: Sha256Digest; + recorded_at: string; + }> + | Readonly<{ + schema_version: "1"; + actor_class: "human" | "archforge"; + assurance: "declared-local-trace"; + channel: "archflow-local"; + decision_event_id: string; + helper_invocation_id: string; + recorded_at: string; + }>; +export interface AuthorityLinkRef { + readonly link_digest: Sha256Digest; + readonly purpose: "restore-adoption"; + readonly proposed_generation_digest: Sha256Digest; + readonly changed_input_fingerprint: Sha256Digest; +} + +export interface GateContractByKind { + readonly "artifact-approval": { + readonly context: { readonly artifact_kind: "prd" | "design" | "phase-design" | "phase-implementation" }; + readonly decision: + | { readonly decision: "approve"; readonly reason: string } + | { readonly decision: "revise" | "reject"; readonly reason: string }; + }; + readonly "review-trigger": { + readonly context: { readonly matched_rules: readonly RuleVersionRef[]; readonly uncertain_rules: readonly RuleVersionRef[]; readonly eligible_waiver_rules: readonly RuleVersionRef[]; readonly waiver_scope: WaiverScope }; + readonly decision: + | { readonly decision: "approve"; readonly reason: string } + | { readonly decision: "revise" | "reject"; readonly reason: string } + | { readonly decision: "waiver-requested"; readonly reason: string; readonly rule: RuleVersionRef; readonly rationale: string }; + }; + readonly "material-drift": { + readonly context: { readonly affected_upstream: EvidenceIdentityRef; readonly drift: "material"; readonly affected_claim_ids: readonly string[] }; + readonly decision: { readonly decision: "amend-upstream" | "revise-current" | "reject"; readonly reason: string }; + }; + readonly "adjudication-failure": { + readonly context: { readonly constitution: "fail" | "uncertain"; readonly failed_rules: readonly RuleVersionRef[]; readonly uncertain_rules: readonly RuleVersionRef[]; readonly eligible_waiver_rules: readonly RuleVersionRef[]; readonly waiver_scope: WaiverScope }; + readonly decision: + | { readonly decision: "approve"; readonly reason: string; readonly resolutions: readonly HumanRuleResolution[] } + | { readonly decision: "revise" | "reject"; readonly reason: string } + | { readonly decision: "waiver-requested"; readonly reason: string; readonly rule: RuleVersionRef; readonly rationale: string }; + }; + readonly "attempts-exhausted": { + readonly context: { readonly step: PipelineStep; readonly attempts: number; readonly maximum_attempts: number }; + readonly decision: { readonly decision: "retry-once" | "revise" | "abort"; readonly reason: string }; + }; + readonly "constitution-edit": { + readonly context: { readonly pinned_constitution_digest: Sha256Digest; readonly current_constitution_digest: Sha256Digest; readonly changed_path_class: "task-branch-constitution" }; + readonly decision: { readonly decision: "revert-edit" | "start-base-amendment" | "abort"; readonly reason: string }; + }; + readonly "commit-authorization": { + readonly context: { readonly target_ref: string; readonly diff_digest: Sha256Digest; readonly current_artifact_digests: readonly Sha256Digest[]; readonly parent_document_digests: readonly Sha256Digest[] }; + readonly decision: + | { readonly decision: "authorize-commit"; readonly reason: string } + | { readonly decision: "revise" | "abort"; readonly reason: string }; + }; + readonly "restore-collision": { + readonly context: { readonly path: TaskPathClaim; readonly recorded_generation_digest: Sha256Digest; readonly current_generation_digest: Sha256Digest; readonly adoption_candidate?: AuthorityLinkRef }; + readonly decision: + | { readonly decision: "discard-and-restore" | "abort"; readonly reason: string } + | { readonly decision: "adopt-as-new-generation"; readonly reason: string; readonly adoption_authority: AuthorityLinkRef; readonly rationale: string }; + }; + readonly "migration-audit": { + readonly context: { readonly source_identity_digest: Sha256Digest; readonly destination_identity_digest: Sha256Digest; readonly import_digest: Sha256Digest; readonly code_baseline_digest: Sha256Digest; readonly policy_baseline_digest: Sha256Digest }; + readonly decision: + | { readonly decision: "accept-import-audit"; readonly reason: string } + | { readonly decision: "revise" | "abort"; readonly reason: string }; + }; +} +export type GateKind = keyof GateContractByKind; +export type GateContext = GateContractByKind[K]["context"]; +export type GateDecisionPayload = GateContractByKind[K]["decision"]; +export type GateEffect = "advance" | "retry" | "redirect-waiver" | "redirect-upstream" | "non-advancing"; + +export interface GateDecisionEnvelopeBase { + readonly schema_version: "1"; + readonly gate_id: string; + readonly task_id: string; + readonly phase_instance: PhaseInstanceId; + readonly subject_digest: Sha256Digest; + readonly context_digest: Sha256Digest; + readonly human_provenance: HumanDecisionProvenance; +} +export type GateDecisionEnvelope = { + readonly [P in K]: GateDecisionEnvelopeBase & { readonly kind: P; readonly payload: GateDecisionPayload

}; +}[K]; + +export interface WaiverOriginRef { + readonly origin_gate_id: string; + readonly origin_decision_digest: Sha256Digest; + readonly origin_context_digest: Sha256Digest; + readonly task_id: string; + readonly phase_instance: PhaseInstanceId; + readonly subject_digest: Sha256Digest; + readonly current_evidence_set_digest: Sha256Digest; + readonly rule: RuleVersionRef; + readonly scope: WaiverScope; +} +export interface SupplementalGateRef { + readonly prior_gate_id: string; + readonly task_id: string; + readonly phase_instance: PhaseInstanceId; + readonly subject_digest: Sha256Digest; + readonly input_fingerprint: Sha256Digest; +} +export interface SupplementalReviewRef extends SupplementalGateRef { + readonly evidence_slot: Extract; +} +export interface GateSupersessionRef { + readonly superseded_gate_id: string; + readonly accepted_triage_digest: Sha256Digest; + readonly old_subject_digest: Sha256Digest; +} +export type SupplementalReviewOutcome = + | { readonly action: "decline"; readonly gate: SupplementalGateRef; readonly reason: string } + | { readonly action: "ingest"; readonly review: SupplementalReviewRef; readonly reason: string } + | { readonly action: "triage-no-change"; readonly review: SupplementalReviewRef; readonly triage_digest: Sha256Digest; readonly reason: string } + | { readonly action: "supersede"; readonly review: SupplementalReviewRef; readonly accepted_triage_digest: Sha256Digest; readonly old_subject_digest: Sha256Digest; readonly new_subject_digest: Sha256Digest; readonly reason: string }; +``` + +Arrays are canonical sorted unique sets. `eligible_waiver_rules` is a subset of the matched/uncertain rules, adjudication resolutions cover exactly every failed/uncertain rule not redirected to waiver, `attempts >= maximum_attempts`, and `retry-once` authorizes exactly one additional attempt. `HumanDecisionProvenance` lives in `gate-decision.schema.json`; IDs use bounded identifier syntax and `recorded_at` is canonical UTC RFC 3339 with milliseconds. The later gate owner mints it from an actual connected-host submission or validated `archflow-local` invocation, retaining the submitter's declared actor class (`human` or `archforge`) and local traceability only. It never claims cryptographic or independently verified human identity; authorization policy evaluates the exact pending gate and accepted actor class. Public JSON carrying the same fields has no authority. The provenance is an immutable part of the envelope: replay of the identical retained `decision_event_id` must have identical actor/channel-specific fields and payload, while reuse with any changed gate, payload, time, connection/request, or helper invocation is rejected. The retained `GateDecisionEnvelope` is therefore the sole explicit-decision evidence; no orphan evidence digest exists. Commit authorization's outer subject is the implementation-output result identity, while its context binds the exact final diff, current artifact set, and parent documents. Mandatory artifact approval is never waivable. Restore adoption requires the context candidate and decision reference to match exactly. + +Waiver sequencing is separately exact. `WaiverOriginRef` binds the archived origin gate, decision, context, subject, evidence set, and selected rule/scope; `WaiverInput` carries that reference plus rationale and repeats no free authority. The later gate owner verifies the archived `waiver-requested` payload selected the same rule and scope. `WaiverSuccess` distinguishes `origin_gate_id` from the newly derived `waiver_gate_id`; grant and denial retain the same subject/evidence/rule/scope/provenance binding, and denial is a successful explicit decision rather than an error. + +Supplemental review separates a gate-only `SupplementalGateRef` from evidence-bearing `SupplementalReviewRef`; an explicit decline therefore records no fabricated review slot or digest. Evidence-bearing actions require a gate-counter slot whose `gate_id` equals `prior_gate_id`. `triage-no-change` cites its validated triage. An accepted change is represented directly by `supersede`: it closes the prior gate non-advancing and records the accepted triage and old/new subject pair, with `old_subject_digest === review.subject_digest` and `new_subject_digest !== old_subject_digest`; it does not predict a future gate ID. If the rerun later creates a gate for the new subject, that new `GateInput` carries `GateSupersessionRef` back to this prior gate/triage/old subject, with its outer `subject_digest` equal to the recorded new subject. These values live in `supplemental-review.schema.json`, cannot enter `GateDecisionPayload`, and become runtime behavior only in later gate/state owners. Cancellation remains a lifecycle outcome, not a decision. + +### Error registries + +```ts +export type ErrorOwner = + | "contracts" | "config" | "repository" | "paths" | "policy" + | "state" | "intent" | "snapshot" | "gate" | "routing" + | "dispatch" | "sandbox" | "protocol" | "integrity"; +export type ErrorProjection = "project" | "protocol"; +// Table notation: SafeId is 1–128 ASCII `[A-Za-z0-9][A-Za-z0-9._:-]*`; +// SafeCode is 1–64 lowercase `[a-z0-9][a-z0-9_-]*`; SafeVersion is 1–64 +// ASCII alphanumeric/dot/hyphen characters; SafeInteger is 0..Number.MAX_SAFE_INTEGER. +export interface StrictParameterParser

>> { + readonly parse: (value: unknown) => P; +} +export interface ErrorDefinition< + P extends Readonly>, + O extends ErrorOwner, + R extends boolean, + A extends string, + X extends ErrorProjection +> { + readonly owner: O; + readonly retryable: R; + readonly parameter_parser: StrictParameterParser

; + readonly action: A; + readonly projection: X; +} +export type CompleteErrorRegistry< + C extends string, + O extends ErrorOwner, + X extends ErrorProjection +> = Readonly<{ + [K in C]: ErrorDefinition>, O, boolean, string, X>; +}>; +export type ProjectErrorCode = + | "CONTRACT_INVALID" | "RESULT_INVALID" | "CONTRACT_VERSION_UNSUPPORTED" + | "WORKFLOW_INVALID" | "CONFIG_INVALID" | "CONFIG_MODEL_UNSUPPORTED" + | "CONFIG_FAMILY_UNSUPPORTED" | "RUNTIME_VERSION_UNSUPPORTED" + | "REPOSITORY_NOT_FOUND" | "REPOSITORY_MISMATCH" | "TASK_INVALID" + | "PATH_INVALID" | "PATH_ESCAPE" | "TASK_SCOPE_VIOLATION" + | "GIT_CONFLICT" | "GIT_DIVERGED" | "HANDOFF_REQUIRED" + | "POLICY_BASE_INVALID" | "WORKFLOW_MISMATCH" | "PINNED_CONFIG_MISMATCH" | "STALE_SKILLS" + | "STATE_MISSING" | "STATE_INVALID" | "TRANSITION_INVALID" | "INPUT_FINGERPRINT_MISMATCH" + | "STATE_CONFLICT" | "SUPPLEMENTAL_REVIEW_REQUIRED" | "INTENT_MISMATCH" + | "SNAPSHOT_LIMIT" | "SNAPSHOT_INVALID" | "RESTORE_COLLISION" | "RECONCILIATION_REQUIRED" | "SECRET_DETECTED" + | "GATE_ACTIVE" | "GATE_DECISION_INVALID" | "GATE_CANCELLED" + | "UNSUPPORTED_HOST" | "UNSUPPORTED_MODEL" | "FAMILY_MISMATCH" + | "CLI_VERSION_UNSUPPORTED" | "AUTH_UNAVAILABLE" | "CLI_MISSING" + | "SANDBOX_UNAVAILABLE" | "SANDBOX_PROBE_FAILED" + | "RATE_LIMITED" | "TIMEOUT" | "CANCELLED" | "MODEL_OUTPUT_INVALID" | "IO_ERROR" + | "OUTPUT_OVERFLOW" | "PROCESS_FAILED" | "INTERNAL_ERROR"; +export type ProtocolErrorCode = + | "TOOL_NOT_FOUND" | "TOOL_DISABLED" | "UNSUPPORTED_PROTOCOL" | "INITIALIZATION_REPEATED"; +declare function defineError< + P extends Readonly>, + O extends ErrorOwner, + R extends boolean, + A extends string, + X extends ErrorProjection +>(owner: O, retryable: R, parser: StrictParameterParser

, action: A, projection: X): ErrorDefinition; +export const PROJECT_ERROR_DEFINITIONS = { + CONTRACT_INVALID: defineError("contracts", false, CONTRACT_INVALID_PARAMETERS, "correct-contract", "project"), + RESULT_INVALID: defineError("integrity", false, RESULT_INVALID_PARAMETERS, "repair-retained-result", "project"), + CONTRACT_VERSION_UNSUPPORTED: defineError("contracts", false, CONTRACT_VERSION_UNSUPPORTED_PARAMETERS, "upgrade-caller", "project"), + WORKFLOW_INVALID: defineError("config", false, WORKFLOW_INVALID_PARAMETERS, "repair-workflow", "project"), + CONFIG_INVALID: defineError("config", false, CONFIG_INVALID_PARAMETERS, "repair-config", "project"), + CONFIG_MODEL_UNSUPPORTED: defineError("config", false, CONFIG_MODEL_UNSUPPORTED_PARAMETERS, "select-supported-model", "project"), + CONFIG_FAMILY_UNSUPPORTED: defineError("config", false, CONFIG_FAMILY_UNSUPPORTED_PARAMETERS, "select-supported-family", "project"), + RUNTIME_VERSION_UNSUPPORTED: defineError("config", false, RUNTIME_VERSION_UNSUPPORTED_PARAMETERS, "upgrade-runtime", "project"), + REPOSITORY_NOT_FOUND: defineError("repository", false, REPOSITORY_NOT_FOUND_PARAMETERS, "open-repository", "project"), + REPOSITORY_MISMATCH: defineError("repository", false, REPOSITORY_MISMATCH_PARAMETERS, "reopen-task-worktree", "project"), + TASK_INVALID: defineError("repository", false, TASK_INVALID_PARAMETERS, "repair-task", "project"), + PATH_INVALID: defineError("paths", false, PATH_INVALID_PARAMETERS, "use-valid-path-claim", "project"), + PATH_ESCAPE: defineError("paths", false, PATH_ESCAPE_PARAMETERS, "use-task-relative-path", "project"), + TASK_SCOPE_VIOLATION: defineError("paths", false, TASK_SCOPE_VIOLATION_PARAMETERS, "use-task-scoped-path", "project"), + GIT_CONFLICT: defineError("repository", false, GIT_CONFLICT_PARAMETERS, "resolve-git-conflict", "project"), + GIT_DIVERGED: defineError("repository", false, GIT_DIVERGED_PARAMETERS, "reconcile-git-history", "project"), + HANDOFF_REQUIRED: defineError("repository", false, HANDOFF_REQUIRED_PARAMETERS, "complete-clean-handoff", "project"), + POLICY_BASE_INVALID: defineError("policy", false, POLICY_BASE_INVALID_PARAMETERS, "restore-policy-base", "project"), + WORKFLOW_MISMATCH: defineError("policy", false, WORKFLOW_MISMATCH_PARAMETERS, "restore-pinned-workflow", "project"), + PINNED_CONFIG_MISMATCH: defineError("policy", false, PINNED_CONFIG_MISMATCH_PARAMETERS, "restore-pinned-config", "project"), + STALE_SKILLS: defineError("policy", false, STALE_SKILLS_PARAMETERS, "refresh-skills", "project"), + STATE_MISSING: defineError("state", false, STATE_MISSING_PARAMETERS, "initialize-state", "project"), + STATE_INVALID: defineError("state", false, STATE_INVALID_PARAMETERS, "repair-state", "project"), + TRANSITION_INVALID: defineError("state", false, TRANSITION_INVALID_PARAMETERS, "select-valid-transition", "project"), + INPUT_FINGERPRINT_MISMATCH: defineError("state", false, INPUT_FINGERPRINT_MISMATCH_PARAMETERS, "create-fresh-intent", "project"), + STATE_CONFLICT: defineError("state", true, STATE_CONFLICT_PARAMETERS, "reread-and-retry-intent", "project"), + SUPPLEMENTAL_REVIEW_REQUIRED: defineError("state", false, SUPPLEMENTAL_REVIEW_REQUIRED_PARAMETERS, "triage-supplemental-review", "project"), + INTENT_MISMATCH: defineError("intent", false, INTENT_MISMATCH_PARAMETERS, "create-fresh-intent", "project"), + SNAPSHOT_LIMIT: defineError("snapshot", false, SNAPSHOT_LIMIT_PARAMETERS, "reduce-snapshot", "project"), + SNAPSHOT_INVALID: defineError("snapshot", false, SNAPSHOT_INVALID_PARAMETERS, "repair-snapshot", "project"), + RESTORE_COLLISION: defineError("snapshot", false, RESTORE_COLLISION_PARAMETERS, "resolve-restore-gate", "project"), + RECONCILIATION_REQUIRED: defineError("snapshot", false, RECONCILIATION_REQUIRED_PARAMETERS, "run-reconciliation", "project"), + SECRET_DETECTED: defineError("snapshot", false, SECRET_DETECTED_PARAMETERS, "remove-secret", "project"), + GATE_ACTIVE: defineError("gate", false, GATE_ACTIVE_PARAMETERS, "resolve-recorded-gate", "project"), + GATE_DECISION_INVALID: defineError("gate", false, GATE_DECISION_INVALID_PARAMETERS, "record-valid-gate-decision", "project"), + GATE_CANCELLED: defineError("gate", false, GATE_CANCELLED_PARAMETERS, "restart-gate-flow", "project"), + UNSUPPORTED_HOST: defineError("routing", false, UNSUPPORTED_HOST_PARAMETERS, "select-supported-host", "project"), + UNSUPPORTED_MODEL: defineError("routing", false, UNSUPPORTED_MODEL_PARAMETERS, "select-supported-model", "project"), + FAMILY_MISMATCH: defineError("routing", false, FAMILY_MISMATCH_PARAMETERS, "select-correct-family", "project"), + CLI_VERSION_UNSUPPORTED: defineError("dispatch", false, CLI_VERSION_UNSUPPORTED_PARAMETERS, "upgrade-cli", "project"), + AUTH_UNAVAILABLE: defineError("dispatch", false, AUTH_UNAVAILABLE_PARAMETERS, "repair-authentication", "project"), + CLI_MISSING: defineError("dispatch", false, CLI_MISSING_PARAMETERS, "install-cli", "project"), + SANDBOX_UNAVAILABLE: defineError("sandbox", false, SANDBOX_UNAVAILABLE_PARAMETERS, "repair-sandbox", "project"), + SANDBOX_PROBE_FAILED: defineError("sandbox", false, SANDBOX_PROBE_FAILED_PARAMETERS, "repair-sandbox", "project"), + RATE_LIMITED: defineError("dispatch", true, RATE_LIMITED_PARAMETERS, "retry-after-backoff", "project"), + TIMEOUT: defineError("dispatch", true, TIMEOUT_PARAMETERS, "retry-unchanged-attempt", "project"), + CANCELLED: defineError("dispatch", true, CANCELLED_PARAMETERS, "restart-child-attempt", "project"), + MODEL_OUTPUT_INVALID: defineError("dispatch", true, MODEL_OUTPUT_INVALID_PARAMETERS, "retry-unchanged-attempt", "project"), + IO_ERROR: defineError("dispatch", true, IO_ERROR_PARAMETERS, "retry-unchanged-attempt", "project"), + OUTPUT_OVERFLOW: defineError("dispatch", false, OUTPUT_OVERFLOW_PARAMETERS, "reduce-output", "project"), + PROCESS_FAILED: defineError("dispatch", false, PROCESS_FAILED_PARAMETERS, "repair-before-fresh-attempt", "project"), + INTERNAL_ERROR: defineError("integrity", false, INTERNAL_ERROR_PARAMETERS, "stop-and-inspect", "project"), +} as const satisfies CompleteErrorRegistry; +export const PROTOCOL_ERROR_DEFINITIONS = { + TOOL_NOT_FOUND: defineError("protocol", false, TOOL_NOT_FOUND_PARAMETERS, "call-advertised-tool", "protocol"), + TOOL_DISABLED: defineError("protocol", false, TOOL_DISABLED_PARAMETERS, "wait-for-tool-enable", "protocol"), + UNSUPPORTED_PROTOCOL: defineError("protocol", false, UNSUPPORTED_PROTOCOL_PARAMETERS, "negotiate-supported-protocol", "protocol"), + INITIALIZATION_REPEATED: defineError("protocol", false, INITIALIZATION_REPEATED_PARAMETERS, "open-new-connection", "protocol"), +} as const satisfies CompleteErrorRegistry; +export type ProjectErrorDefinitionByCode = typeof PROJECT_ERROR_DEFINITIONS; +export type ProtocolErrorDefinitionByCode = typeof PROTOCOL_ERROR_DEFINITIONS; +export type ErrorValue = Readonly<{ + schema_version: "1"; + code: K; + owner: R[K] extends ErrorDefinition ? O : never; + retryable: R[K] extends ErrorDefinition ? B : never; + diagnostic: Readonly<{ + template_id: K; + parameters: R[K] extends ErrorDefinition ? P : never; + }>; + next_action: R[K] extends ErrorDefinition ? A : never; +}>; +export type ProjectError = { + readonly [K in ProjectErrorCode]: ErrorValue; +}[ProjectErrorCode]; +export type ProtocolError = { + readonly [K in ProtocolErrorCode]: ErrorValue; +}[ProtocolErrorCode]; +export type ProjectResult = + | { readonly schema_version: "1"; readonly ok: true; readonly value: T } + | { readonly schema_version: "1"; readonly ok: false; readonly error: ProjectError }; +``` + +`ProjectErrorCode` and `ProtocolErrorCode` are distinct, non-overlapping literal unions. The implementation transcribes every row below into the two source objects using `as const satisfies CompleteErrorRegistry` and `as const satisfies CompleteErrorRegistry`, without a widening annotation; `ProjectErrorDefinitionByCode` and `ProtocolErrorDefinitionByCode` are inferred from those objects. Missing/extra keys fail `satisfies`, while code-specific owner/retryability/parser/action/projection literals remain correlated in `ErrorValue`. Each `parameter_parser` is a strict non-transforming parser for its row's closed parameter object; definitions never carry a duplicate example `parameters` value. The two objects are recursively frozen after construction. The following rows are exhaustive and specify each literal property independently. Braced parameter shapes use only the bounded table primitives defined above or named contract types and never accept arbitrary exception text, paths, peer input, stdout, or stderr. + +| Code | Owner | Retryable | Exact safe parameters | Action | Projection | +|------|-------|-----------|-----------------------|--------|------------| +| `CONTRACT_INVALID` | contracts | false | `{tool?: ToolName, issue_code: SafeCode, schema_version?: SafeVersion}` | `correct-contract` | project | +| `RESULT_INVALID` | integrity | false | `{tool: ToolName, result_id: SafeId, expected_digest?: Sha256Digest, observed_digest?: Sha256Digest}` | `repair-retained-result` | project | +| `CONTRACT_VERSION_UNSUPPORTED` | contracts | false | `{schema_version: SafeVersion, supported_version: SafeVersion}` | `upgrade-caller` | project | +| `WORKFLOW_INVALID` | config | false | `{issue_code: SafeCode}` | `repair-workflow` | project | +| `CONFIG_INVALID` | config | false | `{issue_code: SafeCode}` | `repair-config` | project | +| `CONFIG_MODEL_UNSUPPORTED` | config | false | `{model: SafeId}` | `select-supported-model` | project | +| `CONFIG_FAMILY_UNSUPPORTED` | config | false | `{family: SafeId}` | `select-supported-family` | project | +| `RUNTIME_VERSION_UNSUPPORTED` | config | false | `{component: SafeId, version: SafeVersion}` | `upgrade-runtime` | project | +| `REPOSITORY_NOT_FOUND` | repository | false | `{repository_candidate_digest: Sha256Digest}` | `open-repository` | project | +| `REPOSITORY_MISMATCH` | repository | false | `{expected_digest: Sha256Digest, observed_digest: Sha256Digest}` | `reopen-task-worktree` | project | +| `TASK_INVALID` | repository | false | `{task_id: SafeId, issue_code: SafeCode}` | `repair-task` | project | +| `PATH_INVALID` | paths | false | `{task_id: SafeId, path_class: SafeCode}` | `use-valid-path-claim` | project | +| `PATH_ESCAPE` | paths | false | `{task_id: SafeId, path_class: SafeCode}` | `use-task-relative-path` | project | +| `TASK_SCOPE_VIOLATION` | paths | false | `{task_id: SafeId, path_class: SafeCode}` | `use-task-scoped-path` | project | +| `GIT_CONFLICT` | repository | false | `{operation: SafeCode}` | `resolve-git-conflict` | project | +| `GIT_DIVERGED` | repository | false | `{expected_digest: Sha256Digest, observed_digest: Sha256Digest}` | `reconcile-git-history` | project | +| `HANDOFF_REQUIRED` | repository | false | `{phase_instance: PhaseInstanceId}` | `complete-clean-handoff` | project | +| `POLICY_BASE_INVALID` | policy | false | `{expected_digest: Sha256Digest, observed_digest?: Sha256Digest}` | `restore-policy-base` | project | +| `WORKFLOW_MISMATCH` | policy | false | `{expected_digest: Sha256Digest, observed_digest: Sha256Digest}` | `restore-pinned-workflow` | project | +| `PINNED_CONFIG_MISMATCH` | policy | false | `{expected_digest: Sha256Digest, observed_digest: Sha256Digest}` | `restore-pinned-config` | project | +| `STALE_SKILLS` | policy | false | `{expected_digest: Sha256Digest, observed_digest: Sha256Digest}` | `refresh-skills` | project | +| `STATE_MISSING` | state | false | `{phase_instance: PhaseInstanceId}` | `initialize-state` | project | +| `STATE_INVALID` | state | false | `{phase_instance: PhaseInstanceId, issue_code: SafeCode}` | `repair-state` | project | +| `TRANSITION_INVALID` | state | false | `{phase_instance: PhaseInstanceId, from: SafeCode, to: SafeCode}` | `select-valid-transition` | project | +| `INPUT_FINGERPRINT_MISMATCH` | state | false | `{expected_digest: Sha256Digest, observed_digest: Sha256Digest}` | `create-fresh-intent` | project | +| `STATE_CONFLICT` | state | true | `{expected_revision: SafeInteger, observed_revision: SafeInteger}` | `reread-and-retry-intent` | project | +| `SUPPLEMENTAL_REVIEW_REQUIRED` | state | false | `{gate_id: SafeId, evidence_digest: Sha256Digest}` | `triage-supplemental-review` | project | +| `INTENT_MISMATCH` | intent | false | `{expected_digest: Sha256Digest, observed_digest: Sha256Digest}` | `create-fresh-intent` | project | +| `SNAPSHOT_LIMIT` | snapshot | false | `{limit_scope: "result" | "task", offending_paths: nonempty readonly TaskPathClaim[] (all exact offending paths, sorted unique), current_bytes: SafeInteger, byte_cap: SafeInteger}` | `reduce-snapshot` | project | +| `SNAPSHOT_INVALID` | snapshot | false | `{snapshot_digest: Sha256Digest, issue_code: SafeCode}` | `repair-snapshot` | project | +| `RESTORE_COLLISION` | snapshot | false | `{gate_id: SafeId, path_class: SafeCode}` | `resolve-restore-gate` | project | +| `RECONCILIATION_REQUIRED` | snapshot | false | `{recorded_digest: Sha256Digest, observed_digest: Sha256Digest}` | `run-reconciliation` | project | +| `SECRET_DETECTED` | snapshot | false | `{path_class: SafeCode, detector_id: SafeId}` | `remove-secret` | project | +| `GATE_ACTIVE` | gate | false | `{gate_id: SafeId, gate_kind: GateKind}` | `resolve-recorded-gate` | project | +| `GATE_DECISION_INVALID` | gate | false | `{gate_id: SafeId, gate_kind: GateKind, issue_code: SafeCode}` | `record-valid-gate-decision` | project | +| `GATE_CANCELLED` | gate | false | `{gate_id: SafeId, gate_kind: GateKind}` | `restart-gate-flow` | project | +| `UNSUPPORTED_HOST` | routing | false | `{host: SafeId}` | `select-supported-host` | project | +| `UNSUPPORTED_MODEL` | routing | false | `{model: SafeId}` | `select-supported-model` | project | +| `FAMILY_MISMATCH` | routing | false | `{expected_family: ModelFamily, observed_family: ModelFamily}` | `select-correct-family` | project | +| `CLI_VERSION_UNSUPPORTED` | dispatch | false | `{adapter: AdapterId, version: SafeVersion}` | `upgrade-cli` | project | +| `AUTH_UNAVAILABLE` | dispatch | false | `{adapter: AdapterId}` | `repair-authentication` | project | +| `CLI_MISSING` | dispatch | false | `{adapter: AdapterId}` | `install-cli` | project | +| `SANDBOX_UNAVAILABLE` | sandbox | false | `{capability: SafeId}` | `repair-sandbox` | project | +| `SANDBOX_PROBE_FAILED` | sandbox | false | `{capability: SafeId, failure_class: SafeCode}` | `repair-sandbox` | project | +| `RATE_LIMITED` | dispatch | true | `{adapter: AdapterId, attempt: SafeInteger}` | `retry-after-backoff` | project | +| `TIMEOUT` | dispatch | true | `{adapter: AdapterId, attempt: SafeInteger, limit_ms: SafeInteger}` | `retry-unchanged-attempt` | project | +| `CANCELLED` | dispatch | true | `{source: "client" | "transport", attempt: SafeInteger}` | `restart-child-attempt` | project | +| `MODEL_OUTPUT_INVALID` | dispatch | true | `{adapter: AdapterId, attempt: SafeInteger, issue_code: SafeCode}` | `retry-unchanged-attempt` | project | +| `IO_ERROR` | dispatch | true | `{operation: SafeCode, attempt: SafeInteger}` | `retry-unchanged-attempt` | project | +| `OUTPUT_OVERFLOW` | dispatch | false | `{adapter: AdapterId, byte_count: SafeInteger, byte_cap: SafeInteger}` | `reduce-output` | project | +| `PROCESS_FAILED` | dispatch | false | `{adapter: AdapterId, exit_class: SafeCode}` | `repair-before-fresh-attempt` | project | +| `INTERNAL_ERROR` | integrity | false | `{correlation_id: SafeId}` | `stop-and-inspect` | project | +| `TOOL_NOT_FOUND` | protocol | false | `{tool_name_digest: Sha256Digest}` | `call-advertised-tool` | protocol | +| `TOOL_DISABLED` | protocol | false | `{tool: ToolName, lifecycle_state: SafeCode}` | `wait-for-tool-enable` | protocol | +| `UNSUPPORTED_PROTOCOL` | protocol | false | `{offered_version: SafeVersion, supported_version: SafeVersion}` | `negotiate-supported-protocol` | protocol | +| `INITIALIZATION_REPEATED` | protocol | false | `{connection_id: SafeId}` | `open-new-connection` | protocol | + +Standard MCP/JSON-RPC parse, invalid-request, invalid-params, internal-error, method-not-found, and request-cancelled values are SDK-owned wire errors and are intentionally not duplicated in the ArchFlow registries. The adapter mapping is fixed: malformed JSON/JSON-RPC maps to the corresponding SDK error; an unknown tool maps to `TOOL_NOT_FOUND`; a known tool with invalid Phase 2 input returns project `CONTRACT_INVALID`; a disabled tool maps to `TOOL_DISABLED`; repeated initialization maps to `INITIALIZATION_REPEATED`; a malformed or cross-correlated handler result is logged and projected as safe project `INTERNAL_ERROR`; client/transport cancellation also drives SDK request cancellation while a spawned child attempt records project `CANCELLED`; durable gate cancellation alone records `GATE_CANCELLED`. Waiver denial remains a successful `WaiverSuccess`, never an error. Protocol diagnostics never include a raw unknown tool name or arbitrary peer input. Registry mutation and constructor/parser tests fail on overlap, wrong code-specific parameters, a missing/extra code, wrong owner/retryability/action, arbitrary interpolation, or illegal projection. + +### Correlated tool contracts and transport-neutral contexts + +```ts +declare const taskPathClaimBrand: unique symbol; +export type TaskPathClaim = string & { readonly [taskPathClaimBrand]: true }; +export function parseTaskPathClaim(value: unknown): TaskPathClaim; + +export interface CommonToolInput { + readonly schema_version: "1"; + readonly task_id: string; + readonly intent_id: string; + readonly expected_revision: number; + readonly input_fingerprint: Sha256Digest; +} + +export interface StateInput extends CommonToolInput { + readonly phase_instance: PhaseInstanceId; + readonly step: "produce" | "self_review" | "counter_review" | "triage" | "adjudicate"; + readonly status: "running" | "succeeded" | "failed"; + // `artifact` is intentionally absent and rejected by the closed schema. +} +export interface StateSuccess { + readonly path: TaskPathClaim; + readonly revision: number; + readonly status: StateInput["status"]; +} +export interface CounterReviewInput extends CommonToolInput { + readonly artifact_path: TaskPathClaim; + readonly rubric: RubricV1; +} +export interface CounterReviewSuccess { + readonly path: TaskPathClaim; + readonly verdict: ReviewVerdict; + readonly blocking_count: number; + readonly revision: number; +} +export interface AdjudicateInput extends CommonToolInput { + readonly artifact_path: TaskPathClaim; + readonly upstream_paths: readonly TaskPathClaim[]; +} +export interface AdjudicateSuccess { + readonly path: TaskPathClaim; + readonly constitution: ConstitutionResult; + readonly drift: DriftResult; + readonly triggers: readonly RuleVersionRef[]; + readonly revision: number; +} +export type GateInput = { + readonly [K in GateKind]: CommonToolInput & { + readonly phase_instance: PhaseInstanceId; + readonly summary: string; + readonly subject_digest: Sha256Digest; + readonly current_evidence: CurrentEvidenceSetRef; + readonly supersedes?: GateSupersessionRef; + readonly kind: K; + readonly context: GateContext; + } +}[GateKind]; +export type GateSuccess = { + readonly [K in GateKind]: { + readonly kind: K; + readonly decision: GateDecisionEnvelope; + readonly notes: string; + readonly revision: number; + } +}[GateKind]; +export interface WaiverInput extends CommonToolInput { + readonly origin: WaiverOriginRef; + readonly rationale: string; +} +export interface WaiverDecisionBinding { + readonly origin_gate_id: string; + readonly waiver_gate_id: string; + readonly task_id: string; + readonly rule_id: string; + readonly rule_version: number; + readonly subject_digest: Sha256Digest; + readonly current_evidence_set_digest: Sha256Digest; + readonly scope: WaiverScope; + readonly human_provenance: HumanDecisionProvenance; +} +export type WaiverSuccess = + | (WaiverDecisionBinding & { readonly granted: true; readonly expires: "task-complete"; readonly notes: string; readonly revision: number }) + | (WaiverDecisionBinding & { readonly granted: false; readonly notes: string; readonly revision: number }); + +export interface ToolContract { + readonly input: Input; + readonly success: Success; +} +export interface ToolContractMap { + readonly archflow_state: ToolContract; + readonly archflow_counter_review: ToolContract; + readonly archflow_adjudicate: ToolContract; + readonly archflow_gate: ToolContract; + readonly archflow_waiver: ToolContract; +} +export const TOOL_NAMES = ["archflow_state", "archflow_counter_review", "archflow_adjudicate", "archflow_gate", "archflow_waiver"] as const; +export type ToolName = (typeof TOOL_NAMES)[number]; +// ToolContractMap must satisfy Record> exactly. +export type ToolInput = ToolContractMap[K]["input"]; +export type ToolSuccess = ToolContractMap[K]["success"]; +export type ResultIdentityPayload = { + readonly [P in K]: Readonly<{ + schema_version: "1"; + tool: P; + task_id: string; + intent_id: string; + input_fingerprint: Sha256Digest; + request_digest: Sha256Digest; + result_id: string; + resulting_revision: number; + success: ToolSuccess

; + }>; +}[K]; +export interface ToolDefinition { + readonly name: K; + readonly input_schema_id: `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${K}/input`; + readonly result_schema_id: `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${K}/result`; +} +export const TOOL_DEFINITIONS: { + readonly [K in keyof ToolContractMap]: ToolDefinition; +}; +declare const parsedToolInputBrand: unique symbol; +declare const structuralResultBrand: unique symbol; +declare const resultExpectationBrand: unique symbol; +export type ParsedToolInput = + ToolInput & { readonly [parsedToolInputBrand]: K }; +export type ParsedToolCall = { + readonly [P in K]: Readonly<{ name: P; input: ParsedToolInput

}>; +}[K]; +export function parseToolCall( + name: K, + value: unknown +): Extract; +export type StructurallyValidProjectResult = + ProjectResult> & { readonly [structuralResultBrand]: K }; +export function validateProjectResultStructure( + call: Extract, + value: unknown +): StructurallyValidProjectResult; +export type ResultExpectationDataByTool = { + readonly [P in ToolName]: ResultIdentityPayload

; +}; +export type ResultExpectation = ResultExpectationDataByTool[K] & { + readonly [resultExpectationBrand]: K; +}; +export function correlateProjectResult( + call: Extract, + expectation: NoInfer>, + result: NoInfer> +): ProjectResult>; +``` + +The exact pairs above match the architecture table and add authority fields required by the PRD. Numeric revisions/counts are non-negative safe integers; task, intent, rule, reason, and summary values use bounded validated primitives. `TaskPathClaim` is only a bounded (1–1024 UTF-8 bytes) slash-separated lexical claim: it rejects empty paths, leading `/`, drive/UNC prefixes, backslashes, NUL/control characters, and empty, `.` or `..` components, but it does not resolve symlinks, case, repository roots, or task containment. Phase 4 alone converts a claim into a resolved-safe-path authority. Shared `ReviewRole`/review result types live in `review.ts`, `ConstitutionResult`/`DriftResult` in `adjudication.ts`, `RuleVersionRef` in `gates.ts`, canonical `PipelineStep` remains the Phase 1 export from `vocabulary.ts`, and digest/path/five-tool-name primitives live in `evidence.ts`, `path-claims.ts`, and `tool-names.ts`; all public names are re-exported by `src/contracts/index.ts`. + +`archflow_state` has no `artifact` field in Phase 2: present, `null`, or unknown artifact data is rejected until the durable union exists. `GateInput.supersedes` is absent normally; when present, the retained supplemental supersession must match its prior gate, accepted triage, and old subject, while the input's outer subject is the recorded new subject. The key-first parser returns a mapped discriminated `ParsedToolCall`, so a widened `ToolName` remains a correlated union rather than a widened input/brand pair. Each definition names the exact input and versioned `ProjectResult` schema fragments. Structural validation checks closed shape, code ownership, direct request/result equalities (including state status and gate kind), and internal envelope consistency only. It cannot authorize a minted path, revision, semantic summary, gate/waiver ID, context digest, or result identity. + +Later transaction/result owners create a `ResultExpectation` only after deriving the canonical request digest and complete `ResultIdentityPayload`, including projection path, resulting revision, review/adjudication semantics, and exact gate or waiver envelope. Phase 2 freezes that non-self-referential result hash domain and exposes the correlation consumer and unbranded JSON shape but no public mint; its internal test capability supplies expectations. `correlateProjectResult` requires call, expectation, and structural result to share the same literal tool, verifies the expectation's task/intent/input/request identity against the parsed call, and compares every success field to `expectation.success`; the payload's `resulting_revision` must also equal the success revision. An expectation from another invocation or same-kind gate therefore fails. Until a later phase can mint that authority, Phase 3 performs only structural/direct-field validation and cannot claim authoritative correlation. `WaiverInput.task_id` must equal `origin.task_id`; the archived origin fixes rule, scope, subject, phase, and current evidence set. Gate success also requires `notes === decision.payload.reason`; waiver grant and denial retain exact origin/waiver gate, task/rule-version/subject/current-evidence/scope/human bindings, while only a grant carries task-bound expiry. A malformed handler result or failed authoritative correlation becomes a newly constructed safe `INTERNAL_ERROR`; a corrupted retained result discovered independently is `RESULT_INVALID`. No SDK-owned or wire-protocol type appears here. + +```ts +declare const connectionContextBrand: unique symbol; +declare const invocationContextBrand: unique symbol; +export interface ConnectionContext { + readonly connection_id: string; + readonly startup_repository_candidate: Readonly<{ + readonly working_directory: string; + }>; + readonly initialization_candidates: Readonly<{ + readonly client: Readonly<{ readonly name: string; readonly version: string }>; + readonly host: "claude" | "codex" | "unknown"; + readonly protocol_version: string; + }>; + readonly [connectionContextBrand]: true; +} + +export interface InvocationContext { + readonly invocation_id: string; + readonly connection: ConnectionContext; + readonly signal: AbortSignal; + readonly transport_metadata: Readonly<{ + readonly request_id: string | number; + readonly operation: "tools/call"; + }>; + readonly [invocationContextBrand]: true; +} +export interface ConnectionContextFactory { + readonly captureStartup: (seed: unknown) => Readonly<{ + initialize: (candidates: unknown) => ConnectionContext; + }>; +} +export function createInvocationContext( + connection: ConnectionContext, + seed: unknown, + signal: AbortSignal +): InvocationContext; +``` + +The internal `ConnectionContextFactory` captures and validates a startup repository candidate before initialization, then accepts client/host/protocol candidates exactly once; a repeated call fails with protocol `INITIALIZATION_REPEATED`. Both constructor stages defensively copy and recursively freeze plain data before minting the runtime brand, so mutating the source or returned nested views cannot change the snapshot. `createInvocationContext` requires a branded connection, copies/freezes invocation ID and transport metadata, and retains the supplied `AbortSignal` by identity as an explicitly live externally owned cancellation capability; the signal is neither cloned nor frozen. Request bodies have no repository/client/host/protocol override field. Constructors and test factories are internal and absent from the public barrel except for read-only branded context types and the invocation consumer required by Phase 3. Phase 3 adopts these interfaces and proves transport behavior; Phase 4 resolves and validates repository identity. + +## Work Breakdown + +1. **Establish shared primitives and lexical claims**: Add canonical lowercase SHA-256 parsing, `ReferencedEvidence`, bounded IDs, `TaskPathClaim`, exact `TOOL_NAMES`/`ToolName`, schema IDs, and concrete module/barrel ownership; reuse Phase 1's `PipelineStep`. Prove that a lexical claim is not a Phase 4 resolved-safe-path brand. This shared chunk is the only dependency of both the error and tool-contract chunks. +2. **Implement review and adjudication semantics**: Add raw findings/reviews and adjudications, strict derivation for verdict/count, compliance, mechanical evidence, drift, and trigger consistency, plus all three closed provenance variants without treating semantic validation as authority. +3. **Freeze observation and authority-link seams**: Implement invocation-scoped observation capabilities that own immutable expected bindings and observed bytes. Define Phase 4-owned verified wrappers and scope-bound nested-mapped authority links; qualification is idempotent for an identical link/wrapper and rejects different payload, digest, assurance, or scope. Keep fixture factories internal. +4. **Add exact-set triage and supplemental contracts**: Implement canonical evidence slots, `CurrentReviewSetAuthority`, composite finding references, `validateTriage`, waiver-origin references, and all supplemental outcomes. Cover advisory and zero-finding sets, same local IDs across distinct reviews, and wrong-gate supplemental substitution. +5. **Implement canonical anti-spoofing renderers**: Implement the three exact H1/header inventories and non-structural canonical-JSON encoding for untrusted prose. Golden-test fixed order, exact LF bytes, and heading/table/fence/link/HTML/control/bidi injection. +6. **Freeze gate, waiver, and decision authority**: Implement the single nine-kind catalogue, exact context and object-payload mappings, effect annotations, semantic constraints, decision envelopes, commit subject, restore authority, and waiver sequencing. Keep cancellation and supplemental actions outside the decision map. +7. **Freeze exhaustive error ownership**: Against chunk 1's `ToolName`, encode every per-code row in the two literal registries, strict serialized values, safe parameters, unique action, and project/protocol projection. Test the SDK mapping matrix, denial/cancellation distinctions, and registry mutations; this chunk does not import tool request/result contracts. +8. **Define five tool pairs, result expectations, and contexts**: Against chunks 1 and 7, publish the exact `ToolContractMap`, mapped `ParsedToolCall`, structural validator, closed result identity payload, opaque later-owner `ResultExpectation`, authoritative correlator, exact schema fragment IDs, and branded defensive-copy connection/invocation constructors. Reject state artifacts, identity overrides, widened-name substitutions, repeated initialization, and source mutation. +9. **Run an early whole-contract and bundle checkpoint**: Typecheck the public barrel and literal maps, load every schema by `SCHEMA_IDS`, run initial agreement/correlation tests, and update `scripts/smoke-temp-bundle.mjs` to execute representative Phase 2 parsing/rendering, both registries, and all five definitions through the temporary ESM bundle. +10. **Close adversarial verification**: Complete positive/negative/non-mutation corpora for every variant, brand, slot, gate, supplemental action, error, tool, expectation, path claim, and context; rerun all project checks and a scoped diff proving Phase 3+ and dependency surfaces remain untouched. + +## Requirement Traceability + +| Requirements | Phase 2 evidence | Verification focus | +|--------------|------------------|--------------------| +| REQ-04, REQ-05 | Versioned strict schemas, pinned identity/digest fields, closed phase/step/config error vocabulary | Schema/Zod agreement, unknown-field rejection, registry mutation | +| REQ-10, REQ-11, REQ-12 | Rubric-bound review derivation, exact finding/verdict semantics, structured triage, anti-spoofing canonical projections | Contradiction and exact-coverage corpora; renderer attack goldens | +| REQ-13, REQ-23 | Subject/input/current-slot authority, digest domains, idempotent identical qualification, intent/revision/fingerprint inputs and result expectations | Stale/substituted evidence and same/different-intent correlation cases | +| REQ-15, REQ-17, REQ-19, REQ-33 | Pinned-constitution/upstream/mechanical-evidence adjudication, scoped observation capability, server-attested provenance | Wrong-policy/upstream/invocation/family/output substitution fixtures | +| REQ-18, REQ-20 | Origin-bound waiver and exact nine-kind human decision catalogue | Wrong gate/rule/scope/subject decisions and non-advancing denial tests | +| REQ-27 | Literal five-entry `ToolContractMap` and per-tool schema fragments | Missing/extra/sixth-tool and temporary-bundle smoke checks | +| REQ-36, REQ-37 | Gate request/decision/cancellation/resume contracts without implementing lifecycle | Cross-kind/stale/replay envelope rejection and SDK cancellation ownership | +| REQ-41 | Gate-bound supplemental review reference and closed disposition/supersession outcomes | Wrong-gate/subject slot, decline, no-change, accepted-change, supersession cases | +| REQ-50 | Exact migration-audit context/payload within the existing gate/tool set | Import/code/policy identity substitution and no-sixth-tool checks | + +## Success Criteria + +- [ ] Closed schemas and strict non-transforming parsers distinguish raw, semantically derived, agent-declared, server-attested, and degraded review and adjudication values; derivation recomputes claims but never grants authority. +- [ ] `ReferencedEvidence` is the only serializable wrapper pairing evidence with its digest; links/references repeat identities only. Phase 4 alone verifies repository-canonical payload bytes and mints opaque `VerifiedReferencedEvidence`; altered payload under a retained digest cannot qualify. +- [ ] Observation trust parses exact raw output bytes and derives bindings from one kind-correlated envelope before minting attestation. Its review role is counter or gate-counter only, so self-review remains agent-declared. Mapped types correlate evidence kind, legal role/value family, assurance, and authority references; qualification is idempotent for the identical scoped link/wrapper but rejects payload, digest, provenance, or scope substitution, and exact-role authority alone mints `CurrentReviewSet`. +- [ ] `validateTriage(CurrentReviewSet, unknown)` dispositions every applicable composite finding identity exactly once, rejects duplicate IDs within one review plus duplicate/omitted/foreign/stale composite references, and allows equal local IDs across different review digests. +- [ ] Renderers accept qualified/branded validated JSON only, emit the exact three header inventories, encode untrusted prose as visibly escaped non-structural canonical JSON, and produce deterministic UTF-8/LF bytes with one terminal LF; spoofing cannot create trusted Markdown structure. +- [ ] The single exhaustive `gate-contract.schema.json` catalogue covers exactly nine kinds and derives context, object payload, effect, TypeScript, Zod, and runtime narrowing. Common task/phase/subject/input/evidence scope occurs once in `GateInput`; exact channel-specific decision provenance retains declared human/Archforge actor and local traceability without identity-proof claims, and envelopes preserve complete commit, waiver, restore, migration, and supplemental authority without fabricating evidence for decline or predicting a later gate ID. +- [ ] Separate exhaustive project/ArchFlow-protocol registries contain every listed code once with per-code owner, boolean retryability, exact safe parameters, one action token, and legal projection. SDK-standard error ownership and mappings are explicit; waiver denial, child cancellation, gate cancellation, retained corruption, and malformed handler output are not conflated. +- [ ] A strict literal-keyed `ToolContractMap` contains exactly five pairs and exact schema fragment IDs. Mapped `ParsedToolCall` preserves widened-name correlation; structural validation makes no minted-authority claim; the exact non-self-referential `ResultIdentityPayload` is the result hash domain and a scoped opaque `ResultExpectation` is required to reject wrong invocation/gate/revision/path/semantic results. State artifacts are rejected and `ProjectResult` is versioned. +- [ ] `TaskPathClaim` is explicitly lexical and untrusted. Internal branded constructors copy/deep-freeze connection and invocation snapshots, reject repeated initialization, retain only `AbortSignal` as a live identity, and expose no request identity override path. +- [ ] Every normative schema is independently loadable from `SCHEMA_IDS`; JSON Schema and strict Zod accept/reject the same plain JSON without mutation, and all project typechecks/tests pass with no new dependency or Phase 3+ surface. + +## Verification Steps + +1. Run `npm run typecheck`, the Phase 2 unit suites, and all contract agreement suites. Confirm each public `unknown` parser rejects non-plain prototypes, accessors, cycles, dangerous keys, non-JSON values, and unknown fields before semantic handling, and confirm no input is mutated. +2. Exercise review/adjudication corpora for contradictory verdict/count, invalid rule/version or digest links, every mechanical-evidence state, inconsistent compliance/drift/triggers, all provenance tags, server-attested-self-review rejection, and cross-family substitutions. Compile-time fixtures instantiate both narrow and broad-union `AuthorityLink`/`VerifiedReferencedEvidence` types and reject assurance/reference and kind/role/value mixing. Runtime attempts cover direct brands, observation-created wrappers, payload changes under a retained digest, reused/wrong-scope links, incomplete/wrong-role current sets, and mutually consistent forged JSON. +3. Exercise triage against two reviews sharing local finding IDs and against duplicate, missing, extra, foreign, stale, wrong-assurance/family, reordered, and wrong-gate references. Render every golden twice; compare exact header inventory and bytes, and attack headings, tables, fences, links, raw HTML, CR/LF, controls, and bidi characters. +4. Assert the one gate catalogue has exactly nine keys and JSON Schema, Zod, mapped-union TypeScript, runtime narrowing, and effect classification agree. Prove common scope occurs once; reject duplicate common fields, `gate_id` in contexts, cross-kind envelopes, forged/mutated/reused human provenance, incomplete commit subjects, orphan rule resolutions, mismatched restore authority, wrong waiver origins, evidence-bearing declines, and under-bound supplemental supersession. +5. Mutation-test both error registries for every code-specific owner, retryability, exact parameter parser, action, and projection, including compile-time preservation after `typeof` inference. Exercise `SNAPSHOT_LIMIT` result/task scope, the complete sorted set of exact offending paths, and current/cap bytes, plus the SDK/project mapping matrix for malformed protocol input, unknown/disabled/known-invalid tools, repeated initialization, malformed handlers, retained corruption, child cancellation, durable gate cancellation, and waiver denial. +6. Assert chunk 1's five-name tuple, `ToolContractMap`, and exact schema fragments agree. Compile-time and runtime fixtures reject widened-name, unbranded, cross-tool, same-tool/different-request, wrong-expectation, wrong revision/path/semantic/gate/waiver, corrupt error, and state-artifact substitutions. Canonicalize `ResultIdentityPayload` twice to the same bytes, prove each included field changes its digest, and prove excluded links/receipts/state cannot enter it. Exercise `TaskPathClaim` lexical attacks and confirm it never becomes resolved path authority. +7. Mutate source and nested data around both context constructors, verify defensive copy/deep freeze and one-shot initialization, and prove the live `AbortSignal` still changes cancellation state. Confirm request schemas expose no repository/client/host/protocol override and the public barrel exports no capability/link/expectation/context fixture mint. +8. Run the complete existing project check, dependency/license policy, updated temporary-bundle smoke, and scoped `git diff --check`/status review. Confirm package/lock/dependency/CI/main/MCP/protocol/dist/persistence/dispatch/state/artifact/decision lifecycle surfaces are unchanged and every Phase 2 schema is registered and independently loadable. + +--- +*Designed: 2026-07-27* diff --git a/.archflow/tasks/mcp-integration/reviews/phase-2-design-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-2-design-counter-review.md new file mode 100644 index 00000000..76c49f7f --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-2-design-counter-review.md @@ -0,0 +1,132 @@ +# Phase 2 Design Counter-Review + +Reviewed against `.archflow/tasks/mcp-integration/architecture.md`, `.archflow/tasks/mcp-integration/prd.md`, the Phase 1 design and implementation log, and the current contract implementation. `.archflow/context/` is not present. + +## Findings + +### 1. Blocker — The promised request/result authority correlation is not implementable from the proposed validator inputs + +`validateProjectResult(name, parsedInput, value)` receives only a parsed public request and an untrusted result (phase design lines 541–549). That is insufficient to validate several success fields which are minted only after request processing: projection `path`, resulting `revision`, derived review/adjudication summaries, waiver `gate_id`, and especially a gate decision's `gate_id` and `context_digest`. `GateInput` deliberately contains neither gate ID nor context digest (lines 478–487), while those values require canonical repository identity and canonical request/context hashing owned by later phases. Consequently, a structurally valid success from another invocation of the same tool—most critically another same-kind gate—cannot be distinguished from the current result. `NoInfer` and the parsed-input brand prevent some compile-time mixups but do not provide the missing runtime authority. + +This contradicts the architecture's Phase 2 criterion that successes are correlated to the parsed request and that wrong gate decisions are rejected before Phase 3 projects an inert handler result. + +**Suggested resolution:** Separate structural result validation from authoritative correlation. Introduce an opaque, handler/transaction-minted `ResultExpectation` (or a definition-bound parsed-call handle) containing the exact expected projection identity, revision, semantic summary, gate ID, request/context digest, and other operation-derived bindings. Require that expectation for authoritative validation. If those values cannot be minted until Phases 4–5, explicitly narrow Phase 2/3 to structural and directly comparable-field checks and move the authority-correlation guarantee to the owning phase. + +### 2. Blocker — Server attestation is authorized by an unscoped capability while the caller supplies the facts being attested + +`ObservationCapability` carries no invocation or envelope scope, while `AdapterObservationBase` supplies task, phase, role, subject, input fingerprint, invocation/result IDs, envelope and output digests, adapter/CLI/family/model/effort, and the raw output (lines 101–121). Possession of the capability therefore authorizes arbitrary bindings; it does not prove that those bindings were observed together. The trust module also cannot verify `observed_output_digest` because this phase computes no digest. For adjudication, the problem is stronger: the design says raw output supplies pinned-constitution, approved-upstream, and source-evidence identities, but those expected identities are absent from `AdapterObservationBase`, so a model's mutually consistent wrong-policy claim can become server-attested. + +That does not meet REQ-17/REQ-33 or the phase criterion that wrong-invocation and wrong-digest provenance cannot qualify. + +**Suggested resolution:** Make observation authority invocation-scoped and mint it from immutable expected envelope bindings. The observer must own the observed bytes and their digest, not accept the digest as an independent claim. Add kind-specific trusted bindings for adjudication's exact constitution, upstream, and source-evidence identities, and compare every model-supplied identity to them before attestation. Close adapter/family/effort vocabularies where they are canonical rather than leaving them as arbitrary strings. + +### 3. Blocker — The gate and error “frozen contracts” still contain central placeholders + +All nine `*Context` types are referenced but never defined (lines 254–263); the prose table at lines 341–351 does not fix field names, cardinality, ordering, bounds, or cross-field constraints. `ProjectErrorDefinitionByCode` is likewise a comment placeholder and `ProjectErrorValue` is used without a defined serialized shape (lines 387–402). The contexts, decision effects, error values, and safe parameters are exactly the seams separate implementation chunks and Phase 3 must consume. + +The gate design also regresses from the parent requirement for one exhaustive authority: `GateContextByKind`, `GateDecisionPayloadByKind`, and the prose-only effect classification are independent sources that can drift even if their key sets agree. + +**Suggested resolution:** Define the exact nine context interfaces and semantic invariants, the complete error definition/value types, and one `GateContractByKind` catalogue from which context, payload, allowed effect, schema, Zod mirror, and runtime narrowing are derived. Do not hand implementation a prose table plus multiple parallel registries for trust-bearing decisions. + +### 4. Major — Waiver and supplemental authority are neither single-sourced nor tied to the originating gate + +`WaiverRequestPayload.scope` repeats phase/subject/evidence authority already present in the outer `GateInput`, but no equality rule prevents the human payload from naming another subject or evidence set. `WaiverDecisionBinding` repeats subject/evidence both outside and inside `scope` (lines 502–510), again without an equality invariant. `WaiverInput` contains no reference to the archived `waiver-requested` gate decision that authorized the sequential waiver gate, despite REQ-18 and the architecture requiring exact gate identity and a recorded request. The meaning of the success `gate_id`—originating review gate or new waiver gate—is consequently ambiguous. + +The design also says waiver decisions and supplemental ingestion/triage/decline/supersession are separate contracts (line 357), but no exact supplemental contract, schema, file owner, or correlation interface is included. This falls short of the architecture's Phase 2 criterion that waiver and supplemental choices cannot be substituted across kinds. + +**Suggested resolution:** Derive waiver scope from the originating gate's common authority instead of repeating it in a human payload, or require exact equality in one normative contract. Add a digest-bound origin gate/decision reference and distinguish origin versus waiver gate IDs. Define the exact supplemental request/outcome contracts and their current gate/subject bindings now, or remove the claim that Phase 2 freezes them and assign them explicitly to a later owner. + +### 5. Major — Current-review and gate evidence sets omit assurance, independence, gate identity, and exact-slot semantics + +`CurrentReviewSetAuthority.allowed_evidence` records only `{role, evidence_digest}` (lines 194–204). It cannot express that normal counter-review must be server-attested and opposite-family, that degraded counter-review must still be cross-family, or that a `gate-counter-review` belongs to the exact current gate rather than another gate with the same task/phase/subject/input. `required_roles` and `allowed_evidence` are arrays with no pinned uniqueness/cardinality rules. Similarly, `GateInput.current_evidence_digests` is an untyped digest array with no role mapping, duplicate rule, or canonical set ordering. + +The triage text also never makes “applicable” exact: REQ-11–REQ-13 require every current finding, including advisory/non-blocking findings, to receive one disposition, but the design does not state that or define zero-finding behavior. + +**Suggested resolution:** Define a canonical unique slot set whose entries include role, digest, acceptable assurance, verified family/independence authority, and exact `gate_id` for supplemental slots. Bind gates to that structured set rather than a bare digest array. State that all findings from every required current slot are applicable, define empty/pass/advisory behavior, and test duplicate slots, wrong assurance/family, stale evidence, reordered sets, and same-subject/different-gate substitution. + +### 6. Major — Authority-link hashing and reuse semantics are not safe for persistence and replay + +The serializable authority link contains `evidence_digest` plus authority-side `result_digest`, but the design never fixes the byte domain of `result_digest` or whether the serialized link is inside that result. If it is, the result becomes self-referential; if it is not, the retained location and verification owner are unspecified. This is precisely the digest-ownership boundary the phase is intended to freeze. + +The design also promises to reject reuse of an `AuthorityLink` (lines 225 and 607). A process-local consumed-token/`WeakSet` interpretation conflicts with idempotent retries, restart, reconciliation, and rebuilding canonical projections from the same retained evidence. Durable authority cannot depend on whether a link object happened to be consumed in one process. + +**Suggested resolution:** Define every hash domain and containment boundary explicitly, including whether the result digest covers raw model output, derived evidence, wrapper, link, manifest, or some closed subset; keep self-references outside the hashed object. Make qualification idempotent for the identical link plus verified wrapper and reject only reuse with a different digest, value, or scope. Persisted state/result/checkpoint validation—not process-local token consumption—must establish replay authority. + +### 7. Major — The error registries are neither behaviorally exhaustive nor internally consistent + +Several row-wide profiles/actions cannot carry the architecture-required safe diagnostics or recovery action. For example, `SNAPSHOT_LIMIT` needs offending paths and current/cap byte counts, but all snapshot errors receive only the digest profile and `reduce-or-repair-snapshot`; that action is wrong for `RESTORE_COLLISION`, `SECRET_DETECTED`, and `RECONCILIATION_REQUIRED`. `SUPPLEMENTAL_REVIEW_REQUIRED` requires triage/reject/accepted-change handling before retry, not merely “reread and retry.” `WAIVER_DENIED` is registered as an error even though denial is also a valid `WaiverSuccess`, and `RESULT_INVALID` points to caller correction while malformed handler results are said to become `INTERNAL_ERROR`. + +Cancellation and protocol ownership remain ambiguous: `CANCELLED` and `GATE_CANCELLED` do not distinguish child/MCP cancellation from explicit non-advancing gate cancellation, and an “exhaustive” protocol registry with only `TOOL_NOT_FOUND` and `UNSUPPORTED_PROTOCOL` does not say who owns standard parse/invalid-request/invalid-params/internal/cancellation errors, repeated initialization, or Phase 3 disabled operations. + +**Suggested resolution:** Define parameters and one safe next action per code, not per broad row. Add a source/projection matrix covering SDK protocol, known-tool contract errors, handler integrity failures, child dispatch, and durable gate lifecycle. Resolve denial/cancellation/result-invalid duplication, and either enumerate the full ArchFlow protocol registry or explicitly scope out standard MCP/JSON-RPC errors and define their adapter mapping. + +### 8. Major — The five-tool boundary consumes path and generic types whose authority is not owned + +`TaskRelativePath` is used in four success/request shapes (lines 453–475), but it does not exist in Phase 1, this phase explicitly excludes path schemas, and Phase 4 owns path safety. A Phase 2 parser cannot honestly mint a safe task-relative-path brand, while Phase 3 must already parse and advertise these schemas. Several other shared names (`ReviewRole`, `RuleVersionRef`, `ConstitutionResult`, `DriftResult`, and qualified evidence types) are referenced without a concrete module/export definition. + +The generic seam also remains unsafe when `name` is widened to `ToolName`: `ParsedToolInput` becomes a union/intersection shape whose brand does not preserve a single correlated call, and `ToolDefinition` types both schemas merely as `object`, with no type/schema-ID relation to `ToolInput` and `ProjectResult>`. + +**Suggested resolution:** Introduce a lexical, explicitly untrusted bounded path claim for Phase 2 and reserve a distinct Phase 4 resolved-safe-path brand. Assign every shared primitive/type to a concrete file and public export. Represent a parsed call as a mapped discriminated pair `{name: P, input: ParsedToolInput

}` (or return a definition-bound validator closure), and bind each definition to exact input and wrapped-output schema IDs. Test widened-name and same-tool cross-request substitutions. + +### 9. Major — Connection and invocation “immutability” has no runtime minting boundary + +Lines 555–575 expose constructible structural interfaces only. TypeScript `readonly` and `Readonly` do not copy or freeze runtime objects, and the existing Phase 1 validators return the original input. A caller can therefore forge or mutate host/protocol/working-directory candidates after construction. A blanket deep-freeze promise is also incompatible with treating `AbortSignal` as a live cancellation object. + +**Suggested resolution:** Define internal branded constructors that validate, copy, and deep-freeze startup and initialization data exactly once; expose only read views. State that `AbortSignal` is a live externally owned capability excluded from cloning/freezing, while transport metadata is snapshotted. Test mutation of both source objects and nested context objects after construction, plus repeated initialization rejection. + +### 10. Major — Human override and commit-authorization evidence do not bind a complete decision subject + +`adjudication-failure/approve` requires `human_evidence_digest`, but there is no human-evidence value/reference schema, retention path, renderer, or mint/verification owner. Digest syntax alone cannot establish that the evidence exists, applies to the exact unresolved rules, or was retained with the decision. + +Commit authorization binds the canonical diff as outer `subject_digest` and repeats `authorized_diff_digest`, but the PRD requires authorization of the final implementation diff **and current artifact digests**. `current_evidence_digests` are review evidence, not the implementation manifest, parent-document outputs, or other current artifact identities. The context table intentionally contains only commit target/ref metadata, leaving the exact artifact set unrepresented. + +**Suggested resolution:** Define a retained versioned human-override evidence contract correlated to the exact gate and unresolved rule set, or make the retained decision record itself the sole evidence and remove the orphan digest. Define commit authorization over the implementation-output manifest/result identity plus its exact diff and current parent/artifact digests, with one canonical decision subject rather than loosely related fields. + +### 11. Major — Canonical Markdown is byte-deterministic but not yet a trustworthy human projection + +The renderer contract promises fixed headings/order and “defined Markdown escaping,” but does not enumerate REQ-11's required header fields per artifact or specify how untrusted model prose is prevented from rendering counterfeit headings, tables, links, fences, or raw HTML. Unicode coverage does not address bidi/control-character spoofing. A byte-stable projection can still mislead the human at the review gate. + +**Suggested resolution:** Pin exact per-artifact templates and field inventories. Render untrusted prose in a visibly delimited, non-structural representation; reject or visibly encode control/bidi characters and raw HTML. Add golden cases for heading/table/fence/link/HTML injection, embedded CR/LF, and bidi controls, not just generic escaping and Unicode. + +### 12. Major — The phase is still oversized and its requirement traceability understates what it freezes + +The design contains eight nominal chunks but covers roughly ten production modules, twelve normative schemas, eleven named test suites plus large fixture corpora, and six tightly coupled subsystems. Chunks 2, 4, 5, and 6 are each subsystem-sized and depend on many of the undefined seams above. The “close adversarial verification” chunk then multiplies every variant across JSON Schema, Zod, runtime, compile-time, mutation, and rendering tests. This is high risk for one implementation/review/verification session even with delegation. + +The requirement list also omits contracts this phase normatively freezes: at least REQ-13, REQ-18–REQ-20, REQ-23, REQ-36–REQ-37, REQ-41, and REQ-50 are directly implicated by current-set authority, waiver/gate decisions, replay, supplemental behavior, and migration decisions. The architecture coverage table names Phase 2 for several of them, while the phase header does not, making approval evidence incomplete. + +**Suggested resolution:** Split evidence/authority/triage/rendering from gate/error/tool/context authority, or demonstrate a finer independently implementable breakdown that fits the phase budget after resolving the blockers. With explicit user approval, update both the architecture and phase requirement lists to reflect the normative contracts Phase 2 actually owns, and map each to success and verification evidence; otherwise narrow the phase's freeze claims. + +### 13. Minor — The established bundle-smoke convention is omitted from the file plan + +Phase 1's implementation log records behavioral exercise of the temporary ESM bundle as a durable convention. The current smoke script exercises only YAML, generic Ajv, and phase-number APIs. Phase 2 changes the public barrel with JSON-schema imports, renderers, registries, and all five tool definitions, but the file plan says build scripts remain unchanged. Source-level Vitest success will not prove those exports initialize and behave through esbuild. + +**Suggested resolution:** Include `scripts/smoke-temp-bundle.mjs` in the file plan and exercise representative Phase 2 parsing/rendering, both registries, and all five tool definitions from the emitted `.tmp/archflow-contracts.mjs`; modify the build script only if the new resource imports require it. + +### 14. Minor — Canonical SHA-256 lexical identity is not pinned + +`Sha256Digest` is shown only as a branded string and the prose says syntax will be validated, but it never chooses a canonical lowercase/prefix representation. Uppercase, prefixed, or whitespace variants can create unequal aliases for the same digest in paths, finding references, gate inputs, and sets. + +**Suggested resolution:** Specify one exact lexical form (for example, exactly 64 lowercase hexadecimal characters with no prefix), use it consistently in JSON Schema/Zod/runtime parsing, and reject uppercase, prefixed, and whitespace variants in agreement fixtures. + +## Dependency currency + +No substantive dependency finding remains. Phase 2 genuinely adds no package, the inherited exact Phase 1 graph is sufficient for this work, and live npm metadata confirms the direct pins remain current within their intentional Node-24/Vite-7 compatibility lines. The reviewed Vitest version still supports Vite 7. This does not reduce the sizing or contract-authority findings above. + +## Triage + +| Finding | Disposition | Design response | +|---------|-------------|-----------------| +| 1. Request/result authority correlation | Accepted | Split result handling into `validateProjectResultStructure` and expectation-based `correlateProjectResult`. Added a mapped `ParsedToolCall`, opaque later-owner `ResultExpectation`, complete expected success/request/revision identity, an internal-only test mint, and an explicit Phase 3 structural-only boundary. | +| 2. Unscoped observation authority | Accepted | Replaced caller-supplied attestation facts with invocation-scoped capabilities minted from immutable kind-specific expected bindings. The observer now owns/copies exact output bytes, computes their raw SHA-256 digest, checks policy/evidence bindings, and uses closed adapter/family/effort vocabularies. | +| 3. Placeholder gate/error contracts | Accepted | Replaced the gate placeholders with one exact nine-kind `GateContractByKind`/`gate-contract.schema.json` authority and semantic invariants. Replaced error placeholders/grouped behavior with complete serialized value types, literal code unions, and one exhaustive per-code source table. | +| 4. Waiver and supplemental authority | Accepted | Added exact `WaiverOriginRef`, `SupplementalReviewRef`, and `SupplementalReviewOutcome` contracts. Waivers bind the archived origin decision/context/subject/evidence/rule/scope and distinguish origin from waiver gate IDs; supplemental actions bind the exact prior gate and subject. | +| 5. Current-review slot semantics | Accepted | Added canonical tuple-shaped review slots carrying role, digest, assurance, producer/reviewer family, independence, and exact gate ID where applicable. Gates consume a structured set reference; triage covers every advisory/blocking finding and defines zero-finding behavior. | +| 6. Hash domains and replay | Accepted | Defined raw-output, evidence, result, authority-link, context, and request byte domains with self-reference exclusions. Qualification is now idempotent for the identical verified wrapper/link and rejects only payload, digest, provenance, or scope substitution; durable validators own replay authority. | +| 7. Error behavior and protocol ownership | Accepted | Assigned exact safe parameters and a single recovery action to every code, removed `WAIVER_DENIED`, separated child from durable-gate cancellation and retained corruption from handler integrity failure, added disabled/repeated-initialization protocol codes, and fixed the SDK/MCP mapping matrix. | +| 8. Path/type/generic authority | Accepted | Introduced lexical-only `TaskPathClaim` with an explicit Phase 4 safety boundary, assigned shared types to concrete modules/barrel exports, replaced the generic parsed input with a mapped discriminated call, and bound definitions to exact schema fragments. | +| 9. Runtime context immutability | Accepted | Added internal branded one-shot constructors that validate, defensively copy, and deep-freeze plain connection/invocation data. `AbortSignal` is explicitly retained by identity as the sole live non-frozen capability; repeated initialization is rejected. | +| 10. Human and commit evidence | Accepted | Made the retained decision envelope itself the human override evidence and removed the orphan evidence digest. Commit authorization now uses the implementation-result identity as subject and binds the final diff, current artifacts, parent documents, and target ref. | +| 11. Canonical Markdown trust | Accepted | Pinned exact H1/header inventories for review, triage, and adjudication. Untrusted prose is rendered only as visibly escaped canonical JSON under trusted labels, with explicit heading/table/fence/link/HTML/control/bidi attack cases. | +| 12. Sizing and traceability | Accepted in part | Added all omitted requirement IDs to the architecture and phase design and expanded the breakdown from eight compound chunks to ten independently delegable chunks. A second split was not adopted: the user already approved separating this contract-authority phase from the inert MCP boundary, and the revised ten-chunk phase fits the skill's delegated 8–12 chunk calibration. | +| 13. Temporary-bundle smoke | Accepted | Added `scripts/smoke-temp-bundle.mjs` to the file plan, work breakdown, success evidence, and verification so representative Phase 2 exports, both registries, and all five definitions execute from the emitted temporary ESM bundle. | +| 14. SHA-256 lexical identity | Accepted | Fixed the only valid spelling to exactly 64 lowercase ASCII hex characters with no prefix or whitespace and added agreement fixtures for uppercase, prefixed, padded, short, and long aliases. | From 8e3144c9225e6c53f50b0eae524c1e388a2ef1bf Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 13:24:25 -0500 Subject: [PATCH 007/124] MCP Integration Phase 2: Review Evidence and Contract Authority Freeze transport-neutral evidence, trust, gate, error, tool, and context contracts with strict JSON Schema/Zod agreement and identity-backed authority. Add exhaustive adversarial coverage and triage counter-review findings without entering MCP transport or persistence scope. --- .../tasks/mcp-integration/architecture.md | 2 +- ...iew-evidence-and-contract-authority-log.md | 50 + ...-review-evidence-and-contract-authority.md | 3 +- .../reviews/phase-2-impl-counter-review.md | 78 + scripts/smoke-temp-bundle.mjs | 90 + src/contracts/adjudication.ts | 156 + src/contracts/contexts.ts | 24 + src/contracts/errors.ts | 104 + src/contracts/evidence.ts | 51 + src/contracts/gates.ts | 194 ++ src/contracts/index.ts | 47 + src/contracts/internal/test-capabilities.ts | 44 + src/contracts/internal/trust-brands.ts | 67 + src/contracts/mcp-tools.ts | 94 + src/contracts/path-claims.ts | 30 + src/contracts/renderers.ts | 79 + src/contracts/review.ts | 184 ++ .../v1/adjudication-evidence.schema.json | 21 + .../schemas/v1/adjudication.schema.json | 22 + .../schemas/v1/authority-link.schema.json | 26 + .../schemas/v1/evidence-reference.schema.json | 13 + .../schemas/v1/evidence-slots.schema.json | 14 + .../schemas/v1/gate-contract.schema.json | 544 ++++ .../schemas/v1/gate-decision.schema.json | 350 +++ .../schemas/v1/mcp-tools.schema.json | 468 +++ .../schemas/v1/path-claim.schema.json | 8 + .../schemas/v1/primitives.schema.json | 21 + .../schemas/v1/project-error.schema.json | 2632 +++++++++++++++++ .../schemas/v1/protocol-error.schema.json | 242 ++ .../schemas/v1/result-expectation.schema.json | 122 + .../schemas/v1/review-evidence.schema.json | 35 + src/contracts/schemas/v1/review.schema.json | 43 + .../v1/supplemental-review.schema.json | 147 + src/contracts/schemas/v1/triage.schema.json | 12 + src/contracts/supplemental.ts | 33 + src/contracts/tool-names.ts | 13 + src/contracts/triage.ts | 76 + src/contracts/trust.ts | 245 ++ src/contracts/validators.ts | 178 +- src/contracts/versions.ts | 18 +- .../gate-error-schema-agreement.test.ts | 73 + ...gate-error-supplemental-exhaustive.test.ts | 196 ++ test/contracts/mcp-contract-agreement.test.ts | 66 + .../contracts/review-schema-agreement.test.ts | 80 + test/contracts/schema-registry.test.ts | 74 + ...shared-primitives-schema-agreement.test.ts | 49 + .../contracts/adjudication/valid.json | 1 + .../mcp-tools/state-invalid-artifact.json | 11 + .../contracts/mcp-tools/state-valid.json | 10 + .../path-claims/invalid-traversal.json | 1 + .../fixtures/contracts/path-claims/valid.json | 1 + .../review/invalid-contradiction.json | 1 + test/fixtures/contracts/review/valid.json | 1 + test/unit/adjudication.test.ts | 12 + test/unit/contexts.test.ts | 31 + test/unit/errors.test.ts | 42 + test/unit/evidence.test.ts | 63 + test/unit/gates.test.ts | 48 + test/unit/mcp-tools.test.ts | 55 + test/unit/path-claims.test.ts | 52 + test/unit/renderers.test.ts | 72 + test/unit/review.test.ts | 10 + test/unit/supplemental.test.ts | 20 + test/unit/tool-names.test.ts | 25 + test/unit/triage.test.ts | 40 + test/unit/trust.test.ts | 144 + 66 files changed, 7747 insertions(+), 11 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority-log.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-2-impl-counter-review.md create mode 100644 src/contracts/adjudication.ts create mode 100644 src/contracts/contexts.ts create mode 100644 src/contracts/errors.ts create mode 100644 src/contracts/evidence.ts create mode 100644 src/contracts/gates.ts create mode 100644 src/contracts/internal/test-capabilities.ts create mode 100644 src/contracts/internal/trust-brands.ts create mode 100644 src/contracts/mcp-tools.ts create mode 100644 src/contracts/path-claims.ts create mode 100644 src/contracts/renderers.ts create mode 100644 src/contracts/review.ts create mode 100644 src/contracts/schemas/v1/adjudication-evidence.schema.json create mode 100644 src/contracts/schemas/v1/adjudication.schema.json create mode 100644 src/contracts/schemas/v1/authority-link.schema.json create mode 100644 src/contracts/schemas/v1/evidence-reference.schema.json create mode 100644 src/contracts/schemas/v1/evidence-slots.schema.json create mode 100644 src/contracts/schemas/v1/gate-contract.schema.json create mode 100644 src/contracts/schemas/v1/gate-decision.schema.json create mode 100644 src/contracts/schemas/v1/mcp-tools.schema.json create mode 100644 src/contracts/schemas/v1/path-claim.schema.json create mode 100644 src/contracts/schemas/v1/project-error.schema.json create mode 100644 src/contracts/schemas/v1/protocol-error.schema.json create mode 100644 src/contracts/schemas/v1/result-expectation.schema.json create mode 100644 src/contracts/schemas/v1/review-evidence.schema.json create mode 100644 src/contracts/schemas/v1/review.schema.json create mode 100644 src/contracts/schemas/v1/supplemental-review.schema.json create mode 100644 src/contracts/schemas/v1/triage.schema.json create mode 100644 src/contracts/supplemental.ts create mode 100644 src/contracts/tool-names.ts create mode 100644 src/contracts/triage.ts create mode 100644 src/contracts/trust.ts create mode 100644 test/contracts/gate-error-schema-agreement.test.ts create mode 100644 test/contracts/gate-error-supplemental-exhaustive.test.ts create mode 100644 test/contracts/mcp-contract-agreement.test.ts create mode 100644 test/contracts/review-schema-agreement.test.ts create mode 100644 test/contracts/schema-registry.test.ts create mode 100644 test/contracts/shared-primitives-schema-agreement.test.ts create mode 100644 test/fixtures/contracts/adjudication/valid.json create mode 100644 test/fixtures/contracts/mcp-tools/state-invalid-artifact.json create mode 100644 test/fixtures/contracts/mcp-tools/state-valid.json create mode 100644 test/fixtures/contracts/path-claims/invalid-traversal.json create mode 100644 test/fixtures/contracts/path-claims/valid.json create mode 100644 test/fixtures/contracts/review/invalid-contradiction.json create mode 100644 test/fixtures/contracts/review/valid.json create mode 100644 test/unit/adjudication.test.ts create mode 100644 test/unit/contexts.test.ts create mode 100644 test/unit/errors.test.ts create mode 100644 test/unit/evidence.test.ts create mode 100644 test/unit/gates.test.ts create mode 100644 test/unit/mcp-tools.test.ts create mode 100644 test/unit/path-claims.test.ts create mode 100644 test/unit/renderers.test.ts create mode 100644 test/unit/review.test.ts create mode 100644 test/unit/supplemental.test.ts create mode 100644 test/unit/tool-names.test.ts create mode 100644 test/unit/triage.test.ts create mode 100644 test/unit/trust.test.ts diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index 4f47ee73..ab2b91e0 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -726,7 +726,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali | Phase | Name | Status | |-------|------|--------| | 1 | Contracts, Assets, and Package Scaffold | COMPLETE (2026-07-27) | -| 2 | Review Evidence and Contract Authority | Not Started | +| 2 | Review Evidence and Contract Authority | COMPLETE (2026-07-27) | | 3 | Inert MCP Boundary and Offline Bundle | Not Started | | 4 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | | 5 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | diff --git a/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority-log.md b/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority-log.md new file mode 100644 index 00000000..32832ad3 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority-log.md @@ -0,0 +1,50 @@ +## Implementation Log: Phase 2 - Review Evidence and Contract Authority + +### Decisions Made + +- Kept the Phase 2 boundary transport-neutral and dependency-neutral: no MCP SDK, server lifecycle, persistence, dispatch, state, artifact, package, lockfile, CI, or release surface was added. +- Made every trust-bearing runtime value identity-backed. Observation capabilities, verified evidence wrappers, authority links, qualified evidence, current review sets, validated triage, immutable contexts, parsed request identities, structural results, and result expectations are accepted only when minted by their private owner; schema-shaped objects, casts, and spread clones cannot acquire authority. +- Kept JSON Schema 2020-12 normative while registering narrowly scoped `x-archflow-*` keywords in the central strict Ajv factory for cross-field semantics JSON Schema cannot express natively. Zod/runtime and JSON Schema agreement tests cover each keyword without transforming input. +- Bound server-attested evidence to exact adapter/family, invocation, envelope, output, result, task, phase, subject, fingerprint, assurance, role, and optional gate identities. Gate-counter evidence cannot be reused across gates with otherwise identical scope. +- Split tool result handling into structural validation and authoritative correlation. `bindParsedToolCallRequest` attaches the canonical request digest to an authentic parsed call; `correlateProjectResult` then requires authentic request, expectation, and result identities and compares every invocation and success field. +- Used the shared `SafeId`, canonical lowercase SHA-256, lexical-only `TaskPathClaim`, and exact five-name `TOOL_NAMES` vocabulary across correlated contracts. +- Rendered review, triage, and adjudication Markdown only from authenticated qualified/validated values. Public bundle smoke proves forged values are rejected; positive rendering uses internal test-only authority fixtures. + +### Deviations from Plan + +- The counter-review found that enumerable symbol brands and structural-only consumers allowed forged authority. The implementation replaced those brands with private WeakMap/WeakSet identity registries and non-enumerable test-only mints, while preserving the planned public types and later-owner boundaries. +- Added central semantic schema keywords for review summaries, adjudication claims, gate decisions, supplemental outcomes, MCP correlations, result expectations, sorted unique arrays, and UTF-8 byte limits. These are required to make the approved cross-field contract genuinely normative and agreement-testable rather than leaving semantics only in Zod. +- Added `bindParsedToolCallRequest` and `RequestIdentifiedToolCall` to carry the canonical request digest into result correlation. This closes the approved same-tool/different-request rejection requirement that a parsed input alone could not satisfy. +- Expanded the planned adversarial verification into exhaustive table-driven coverage: all 15 decision effect annotations, 29 gate kind/decision pairs, 56 error definitions, and four supplemental outcomes are checked rather than sampled. +- No PRD requirement or remaining phase scope changed. `architecture.md` required only its Phase 2 progress update. + +### Patterns Established + +- Runtime brands protect authority only when the owner authenticates object identity at every consumer. TypeScript brands or enumerable symbols alone are never a trust boundary. +- Minted trust graphs are defensively copied and recursively frozen. Mutable byte sequences remain private and are returned only as copies so retained digests cannot outlive mutable content. +- Every public `unknown` parser still performs the recursive plain-JSON preflight; semantic evidence parsers compose the complete raw validator rather than reusing a structural `.shape` that drops refinements. +- Cross-field schema rules that JSON Schema 2020-12 cannot express use a narrowly named, centrally registered Ajv keyword with strict metadata plus positive, negative, agreement, and non-mutation tests. +- Schema/runtime registries are checked exhaustively when they are closed catalogues. Gate effects, error ownership/actions, supplemental variants, schema IDs, and tool names cannot rely on representative samples. +- Bundle smoke exercises public capability boundaries: it verifies internal mints are absent and that public consumers reject fabricated authority. + +### Gotchas + +- Object spread copies enumerable symbol properties, so a symbol-branded value is forgeable unless consumers also authenticate identity; non-enumerability alone is insufficient without an owner registry. +- `Uint8Array` cannot be made deeply immutable by `Object.freeze` in the same way as plain JSON. Observation bytes require private storage and copy-on-read. +- Standard JSON Schema cannot express derived review aggregates, subject-to-mechanical-evidence equality, canonical lexicographic array ordering, or most gate/tool cross-field correlations. Relaxing Ajv would hide these gaps; strict custom keywords keep one validation boundary. +- JSON object property order is not semantic authority. Error correlation uses structural equality and preserves the validated input rather than comparing `JSON.stringify` output. +- The available verification runtime is Node `24.11.1`, below the architecture's eventual `24.15.0` functional floor. Phase 2 typecheck, 183 tests, strict contract suites, and the temporary bundle all pass, but release/CI floor verification remains a later-phase responsibility. + +### Key Interfaces + +- `src/contracts/evidence.ts`: `parseSha256Digest`, `parseSafeId`, `parseSafeCode`, `parseSafeVersion`, `parseSafeInteger`, and `ReferencedEvidence` own shared lexical identities. +- `src/contracts/review.ts` and `adjudication.ts`: `parseAndDeriveReview`, `parseReviewEvidence`, `parseReferencedReviewEvidence`, `parseAndDeriveAdjudication`, `parseAdjudicationEvidence`, and `parseReferencedAdjudicationEvidence` own complete semantic parsing. +- `src/contracts/trust.ts`: `observationSource`, `parseAuthorityLinkData`, `parseCurrentEvidenceSetRef`, `parseReferencedEvidence`, `authorityQualifier`, and the qualified/current-set types define the future dispatch, repository, and state authority seams. +- `src/contracts/triage.ts`: `validateTriage(current: CurrentReviewSet, candidate: unknown): ValidatedTriage` requires exact composite finding coverage. +- `src/contracts/renderers.ts`: `renderReviewEvidence`, `renderTriage`, and `renderAdjudicationEvidence` accept authenticated values and emit deterministic UTF-8/LF Markdown. +- `src/contracts/gates.ts`: `GATE_KINDS`, `GATE_CONTRACTS`, `parseGateContract`, `validateGateDecision`, `parseGateDecisionEnvelope`, and `gateDecisionEffect` own the nine-kind decision catalogue. +- `src/contracts/errors.ts`: `PROJECT_ERROR_DEFINITIONS`, `PROTOCOL_ERROR_DEFINITIONS`, `createProjectError`, `createProtocolError`, `parseProjectError`, and `parseProtocolError` own the closed error registries. +- `src/contracts/mcp-tools.ts`: `TOOL_DEFINITIONS`, `parseToolCall`, `bindParsedToolCallRequest`, `validateProjectResultStructure`, and `correlateProjectResult` define the exact five transport-neutral pairs and correlation seam. +- `src/contracts/contexts.ts`: `createInvocationContext` consumes an authentic immutable connection context while retaining `AbortSignal` as the only live external capability; connection minting remains internal. +- `src/contracts/versions.ts`: `SCHEMA_IDS` registers all 22 independently loadable v1 schemas, including the HTTPS MCP tool and result-expectation authorities. +- `src/contracts/internal/test-capabilities.ts`: direct-import-only factories exercise later-owner authority in tests and are absent from `src/contracts/index.ts` and the temporary public bundle. diff --git a/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority.md b/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority.md index 5e0a26d2..c5990bcb 100644 --- a/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority.md +++ b/.archflow/tasks/mcp-integration/phases/phase-2-review-evidence-and-contract-authority.md @@ -1,6 +1,7 @@ # Phase 2: Review Evidence and Contract Authority -**Status**: DESIGNED +**Status**: COMPLETE +**Implemented**: 2026-07-27 **Task**: mcp-integration **Goal**: Freeze the trust-bearing semantic, provenance, gate, error, tool, connection, and invocation contracts before any MCP transport or durable workflow implementation adopts them. **Requirements**: REQ-04, REQ-05, REQ-10, REQ-11, REQ-12, REQ-13, REQ-15, REQ-17, REQ-18, REQ-19, REQ-20, REQ-23, REQ-27, REQ-33, REQ-36, REQ-37, REQ-41, REQ-50 diff --git a/.archflow/tasks/mcp-integration/reviews/phase-2-impl-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-2-impl-counter-review.md new file mode 100644 index 00000000..2c32f79d --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-2-impl-counter-review.md @@ -0,0 +1,78 @@ +# Phase 2 Implementation Counter-Review + +1. **Blocker — Opaque trust brands are not authenticated before minting qualified evidence.** `assertLinkMatches` compares only ordinary fields, and `authorityQualifier.qualifyReview` / `qualifyAdjudication` never check `authorityLinkBrand` or `verifiedReferencedEvidenceBrand`; `currentReviews` likewise never checks `qualifiedEvidenceBrand` (`src/contracts/trust.ts:143-175`). Mutually consistent plain objects can therefore be passed at the JavaScript boundary and receive the real qualified/current-set brands, violating the central rule that schema-valid or forged JSON cannot mint authority. + + **Suggested resolution:** Require exact internal brand identities and kind/assurance values at every authority consumer, use non-copyable identity-backed brands, and add runtime tests proving that mutually consistent unbranded, cast, spread-cloned, and cross-kind objects cannot qualify or enter a current review set. + +2. **Blocker — Result correlation does not bind the canonical request digest.** `correlateProjectResult` checks tool, task, intent, input fingerprint, revision, and success but never compares `expectation.request_digest` (`src/contracts/mcp-tools.ts:96`). `ParsedToolCall` contains no trusted request digest to compare, so same-tool/different-request expectations can correlate successfully; the internal test factory also creates an enumerable symbol brand that survives object spread (`src/contracts/internal/test-capabilities.ts:19-20`). + + **Suggested resolution:** Bind a canonical request digest to the parsed call or pass a separately branded request identity, compare it during correlation, make authority brands non-enumerable or identity-backed, and add same-tool/different-request and spread-clone replay tests. + +3. **Blocker — `archflow_gate` input parsing falsely mints the strong current-evidence type from a loose slot array.** The MCP Zod mirror accepts an unordered `array(union).min(2).max(3)` and does not enforce canonical roles, family independence, unique evidence digests, or the exact tuple (`src/contracts/mcp-tools.ts:29-34,64,68-72`). The normative MCP schema is looser still: `current_evidence` is only an object (`src/contracts/schemas/v1/mcp-tools.schema.json:270`). `parseToolCall` nevertheless returns `CurrentEvidenceSetRef`, allowing duplicate, reordered, same-family, or otherwise invalid evidence slots into the gate contract. + + **Suggested resolution:** Reuse `parseCurrentEvidenceSetRef` / `currentEvidenceSetRefSchema` in the tool parser, reference the normative evidence-slot schema from the MCP schema, and add agreement tests for role order, tuple cardinality, family relation, gate slot shape, and digest uniqueness. + +4. **Major — Exact gate identity is lost between observation and current-set qualification.** A gate-counter observation binding carries `gate_id` (`src/contracts/trust.ts:43-45`), but `ServerAttestedReview` and `AuthorityLinkBase` do not (`src/contracts/review.ts:129-139`, `src/contracts/trust.ts:91-98`). `currentReviews` therefore compares role, digest, assurance, families, and common scope but cannot prove that a gate-counter review came from the `gate_id` asserted by the slot (`src/contracts/trust.ts:167-175`). Evidence from another gate with the same common scope can be substituted unless a future owner performs an unspecified out-of-band lookup. + + **Suggested resolution:** Carry the gate identity in the attestation/authority binding or require a gate-correlated authority token when constructing the current set. Pin any receipt lookup responsibility explicitly and test same-scope evidence from a different gate. + +5. **Major — Server authority links are not correlated with server-attested provenance.** `assertLinkMatches` does not compare the link's `invocation_id`, `result_id`, `envelope_input_digest`, or `observed_output_digest` with the corresponding fields on server-attested evidence (`src/contracts/trust.ts:91-98,143-148`). Even after adding missing brand checks, a branded link and wrapper from different invocations/results can qualify when their outer scope and digest agree. Observation minting also does not enforce the adapter-to-family relation; a capability can label `claude-cli` as family `codex` or vice versa (`src/contracts/trust.ts:64-87`). + + **Suggested resolution:** Branch qualification by assurance and compare every duplicated provenance field, enforce the fixed adapter/family mapping at observation, and add wrong-invocation, result, envelope, output, adapter, and family substitution tests. + +6. **Major — Renderers accept forged structural values as trusted projections.** `renderReviewEvidence`, `renderAdjudicationEvidence`, and `renderTriage` never verify their runtime brands (`src/contracts/renderers.ts:33-72`). The renderer unit test explicitly casts a hand-built object with `authority: {}` and successfully renders it (`test/unit/renderers.test.ts:5-9`). Consequently, raw or fabricated metadata can be displayed under trusted ArchFlow headings even though prose escaping itself is effective. + + **Suggested resolution:** Add internal runtime brand assertions to all renderers, use genuinely qualified/validated fixtures for positive tests, and add explicit raw, schema-valid-but-unqualified, cast, and spread-clone rejection cases. + +7. **Major — Minted trust and context values are mutable or cloneable after minting.** Observation results are only shallow-frozen, leaving `raw_output_bytes` and nested findings/arrays mutable under fixed digests (`src/contracts/trust.ts:73-87`). `currentReviews` retains authority slots and review objects directly (`src/contracts/trust.ts:167-175`), and test capability factories shallow-copy bindings (`src/contracts/internal/test-capabilities.ts:7-20`). Separately, context brands are enumerable symbol properties; spreading a legitimate `ConnectionContext`, changing its ordinary fields, and retaining the copied brand passes `createInvocationContext`'s sole brand check (`src/contracts/contexts.ts:5-22`). + + **Suggested resolution:** Defensively copy and recursively freeze every plain-data graph, encapsulate mutable byte arrays with copy-on-read/private storage, and use WeakSet/WeakMap or non-enumerable identity brands for contexts and other capabilities. Test source mutation, returned nested mutation, byte mutation, and spread-cloned branded objects. + +8. **Major — Evidence parsers bypass required semantic validation and disagree with the normative schemas.** `provenanceBase` spreads `rawReviewSchema.shape`, discarding its duplicate-finding/rule and role-to-step refinements; `parseReviewEvidence` rechecks only verdict/count (`src/contracts/review.ts:86-100,146-175`). `parseReferencedEvidence` performs no review/adjudication semantic derivation at all (`src/contracts/trust.ts:128-135`), so a wrapper containing contradictory evidence can be returned as typed evidence. There are also direct agreement gaps: the review-evidence JSON schema rejects duplicate finding IDs that Zod accepts, while Zod enforces opposite-family server reviews that the JSON schema does not. + + **Suggested resolution:** Compose evidence parsing through the complete raw semantic validators rather than `.shape`, route referenced payloads through `parseReviewEvidence` / `parseAdjudicationEvidence`, mirror every semantic rule in the normative validation path, and add negative agreement cases for duplicates, role/step, family, and contradictory aggregates. + +9. **Major — Adjudication can claim compliance when mechanical evidence is absent.** `validateAdjudicationClaims` rejects suspect states only while iterating `enforced_by`; an empty array therefore permits `compliance: "pass"` (`src/contracts/adjudication.ts:108-120`). This contradicts the design requirement that missing mechanical evidence cannot be upgraded to compliance. + + **Suggested resolution:** Require at least one current, correctly subject-bound mechanism before permitting `pass` (and define the legal mixed-state rule), encode the same constraint in both schema and Zod validation, and add empty and mixed mechanical-evidence cases. + +10. **Major — Gate and supplemental JSON Schema authority omits the runtime semantic contract.** `parseGateContract` runs only the discriminated structural union and never calls `validateGateDecision` (`src/contracts/gates.ts:159-187`), so ineligible waiver requests, incomplete adjudication resolutions, and mismatched restore adoption authority can parse. The normative gate schema also accepts unsorted canonical sets, `attempts < maximum_attempts`, empty commit digest sets, and non-lexical restore paths that Zod rejects. The supplemental schema independently accepts mismatched `prior_gate_id`/slot `gate_id` and invalid old/new supersession subjects that Zod rejects (`src/contracts/supplemental.ts:23-30`). + + **Suggested resolution:** Make semantic correlation mandatory in the public gate parser and normative validation path, share/customize schema constraints for ordering and cross-field equality, and add bidirectional agreement fixtures for every gate and supplemental variant. + +11. **Major — MCP JSON Schema and runtime parsing diverge beyond current-evidence slots.** Gate `context` is unconstrained in the MCP schema while runtime invokes `parseGateContext`; waiver `human_provenance` is unconstrained in JSON and runtime accepts any `recorded_at` string instead of canonical UTC milliseconds (`src/contracts/mcp-tools.ts:25-27,64-70,83`). The embedded path schema uses 1,024 characters and omits C1 controls, while `TaskPathClaim` uses 1,024 UTF-8 bytes and rejects U+0080-U+009F (`src/contracts/schemas/v1/mcp-tools.schema.json:21-26`, `src/contracts/path-claims.ts:9-21`). A 600-character two-byte path is therefore schema-valid but parser-invalid. + + **Suggested resolution:** Compose/reference the authoritative gate, provenance, evidence-slot, and path schemas and reuse their Zod parsers. Add positive/negative agreement corpora for all five tool inputs/results, including multibyte and C1 path cases. + +12. **Major — Error parsing treats JSON property order as authority, while the error schema is looser in other trust-bearing fields.** `parseSerializedError` compares `JSON.stringify` output to a reconstructed object (`src/contracts/errors.ts:90-97`), rejecting otherwise identical schema-valid errors whose top-level or parameter keys are reordered. Conversely, `project-error.schema.json` accepts arbitrary, unsorted 1-1,024-character `SNAPSHOT_LIMIT.offending_paths`, whereas the Zod registry requires sorted unique lexical `TaskPathClaim`s (`src/contracts/errors.ts:30,45`). + + **Suggested resolution:** Compare correlated error fields structurally and order-insensitively while preserving the original value, reuse the normative path claim plus canonical ordering validation, and agreement-test reordered objects, traversal/control paths, and unsorted offending-path sets. + +13. **Major — Correlated identifiers use incompatible grammars across the phase.** Gate decisions and MCP contracts accept the broad `SafeId` grammar, including uppercase, colon, underscore, and dot (`src/contracts/gates.ts:61`, `src/contracts/mcp-tools.ts:19`), while supplemental gate/task references and trust links use a lowercase hyphen-only slug (`src/contracts/supplemental.ts:16`, `src/contracts/trust.ts:108`). A valid gate such as `Gate:1` can be decided but cannot be referenced by supplemental evidence, and the same incompatibility affects task identity across tools and evidence. + + **Suggested resolution:** Use one shared identifier primitive for each correlated identity category across TypeScript, Zod, and JSON Schema, or explicitly tighten the minting boundary everywhere to the narrowest grammar. Add cross-contract round-trip fixtures. + +14. **Minor — The claimed single gate-effect authority and adversarial coverage are not implemented.** Runtime effects are hard-coded in a parallel map rather than derived or exhaustively agreement-checked against `x-archflow-effect` in `gate-contract.schema.json` (`src/contracts/gates.ts:110-112`). The phase-planned gate, supplemental, and error fixture directories are absent, and agreement tests sample only one gate, one envelope, and one error from each registry (`test/contracts/gate-error-schema-agreement.test.ts:16-37`). The review/adjudication and MCP agreement suites are similarly sparse, which is why the defects above pass all 157 tests and the full `npm run check`. + + **Suggested resolution:** Derive or exhaustively compare every runtime effect against schema annotations and add the planned positive/negative fixture corpora for every provenance, gate, supplemental, error, and tool variant, including all required substitution and non-mutation cases. + +The internal test-capability factories are not re-exported by `src/contracts/index.ts`, and the temporary bundle smoke confirms their names are absent. No public-barrel leak was found; the problem is that several public consumers fail to authenticate the opaque brands they are supposed to consume. + +## Triage + +| Finding | Disposition | Resolution | +|---------|-------------|------------| +| 1. Trust-brand authentication | Accepted | Replaced copyable symbol authority with private identity registries and authenticated link, wrapper, qualified-evidence, and current-set identities, kinds, and assurances at every consumer. Added cast, plain-object, spread-clone, and cross-kind rejection tests. | +| 2. Request-digest correlation | Accepted | Added identity-backed request binding for parsed calls, required it during result correlation, compared the canonical request digest, and made result expectations identity-backed and non-copyable. Added same-tool/different-request and spread-clone tests. | +| 3. Current-evidence parsing | Accepted | `archflow_gate` now reuses the authoritative current-evidence parser and schema, enforcing canonical tuple order/cardinality, unique digests, family independence, and gate-counter shape. | +| 4. Gate-counter identity | Accepted | Gate-counter attestations and authority links now retain the exact gate ID, and current-set construction rejects same-scope evidence from another gate. | +| 5. Server provenance correlation | Accepted | Qualification now compares invocation, result, envelope-input, and observed-output identities and enforces the fixed CLI-adapter/model-family mapping. Substitution coverage was added. | +| 6. Renderer authority | Accepted | All renderers authenticate qualified/validated runtime identities. Positive tests use genuine internal fixtures; public bundle smoke proves forged review, triage, and adjudication values are rejected. | +| 7. Mutability and cloneability | Accepted | Minted plain graphs are defensively copied and recursively frozen, observed bytes are private with copy-on-read, and contexts/capabilities use identity registries that spread clones cannot preserve. Mutation tests cover sources, returned values, nested values, and bytes. | +| 8. Evidence semantic parsing | Accepted | Evidence variants compose the complete raw semantic validators, referenced evidence dispatches through family-specific semantic parsers, and strict schema keywords/agreement tests cover aggregates, duplicates, role/step, family, and nested unknown fields. | +| 9. Mechanical evidence for compliance | Accepted | Adjudication pass now requires nonempty, exclusively current, correctly subject-bound mechanical evidence; empty, suspect, mixed, and mismatched cases fail in both runtime and normative schema validation. | +| 10. Gate and supplemental schema semantics | Accepted | Public parsers now require all gate/supplemental correlations, and strict semantic schema keywords enforce canonical sets, attempt bounds, commit subjects, waiver eligibility, restore equality, gate binding, and supersession identities. | +| 11. MCP schema/runtime agreement | Accepted | MCP schemas now compose the authoritative gate, provenance, evidence-slot, and path contracts; strict semantic validation covers direct correlations, canonical UTC-millisecond provenance, UTF-8 path limits, controls, and all five tool families. | +| 12. Error authority and property order | Accepted | Error correlation is structural and order-insensitive while preserving the original value. `SNAPSHOT_LIMIT` paths use authoritative lexical path claims and strict sorted-unique validation. | +| 13. Identifier grammars | Accepted | Correlated task, gate, invocation, and result identities now consistently use the shared `SafeId` primitive across trust, supplemental, gate, tool, Zod, and JSON Schema contracts. | +| 14. Effect authority and exhaustive coverage | Accepted | Added exhaustive schema-to-runtime effect agreement for all 15 decision annotations, all 29 gate decision pairs, all 56 error definitions, and all four supplemental outcomes with substitution and non-mutation attacks. | diff --git a/scripts/smoke-temp-bundle.mjs b/scripts/smoke-temp-bundle.mjs index ca9375e3..24aec7d7 100644 --- a/scripts/smoke-temp-bundle.mjs +++ b/scripts/smoke-temp-bundle.mjs @@ -24,4 +24,94 @@ assert.deepEqual(validator.assert({ id: 1, uri: "https://example.test/contract" assert.throws(() => validator.assert({ id: 0, uri: "not a URI" }, "bundle-smoke")); assert.equal(contracts.parsePositiveSafePhaseNumber(1), 1); +const digest = "a".repeat(64); +const review = contracts.parseAndDeriveReview({ + schema_version: "1", + task_id: "bundle-smoke", + phase_instance: "phase-impl-2", + step: "counter_review", + role: "counter-review", + subject_digest: digest, + input_fingerprint: "b".repeat(64), + rubric_digest: "c".repeat(64), + producer_family: "claude", + findings: [], + matched_rule_versions: [], + verdict: "pass", + blocking_count: 0 +}); +assert.equal(review.verdict, "pass"); +assert.deepEqual( + contracts.parseAndDeriveAdjudication({ + schema_version: "1", + task_id: "bundle-smoke", + phase_instance: "phase-impl-2", + step: "adjudicate", + subject_digest: digest, + input_fingerprint: "b".repeat(64), + pinned_constitution_digest: "d".repeat(64), + approved_upstream_digests: [], + source_evidence_set_digest: "e".repeat(64), + rule_findings: [], + drift_findings: [], + constitution: "pass", + drift: "aligned", + matched_rule_versions: [], + uncertain_rule_versions: [] + }).constitution, + "pass" +); +const forgedReview = { + evidence_digest: "f".repeat(64), + evidence: { + ...review, + assurance: "degraded", + model_family: "codex", + model: "bundle-smoke", + effort: "unknown", + reason: "temporary bundle smoke" + }, + authority: {} +}; +assert.throws(() => contracts.renderReviewEvidence(forgedReview), /qualified review evidence/u); +assert.throws(() => contracts.renderAdjudicationEvidence({ evidence_digest: digest, evidence: {}, authority: {} }), /qualified adjudication evidence/u); +assert.throws(() => contracts.renderTriage({ schema_version: "1" }), /validated triage/u); + +assert.equal(Object.keys(contracts.PROJECT_ERROR_DEFINITIONS).length, 52); +assert.equal(Object.keys(contracts.PROTOCOL_ERROR_DEFINITIONS).length, 4); +assert.equal( + contracts.createProjectError("STATE_CONFLICT", { expected_revision: 1, observed_revision: 2 }).next_action, + "reread-and-retry-intent" +); +assert.equal( + contracts.createProtocolError("TOOL_NOT_FOUND", { tool_name_digest: digest }).owner, + "protocol" +); + +assert.deepEqual(Object.keys(contracts.TOOL_DEFINITIONS), [ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver" +]); +for (const [name, definition] of Object.entries(contracts.TOOL_DEFINITIONS)) { + assert.equal(definition.name, name); + assert.equal( + definition.input_schema_id, + `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${name}/input` + ); + assert.equal( + definition.result_schema_id, + `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${name}/result` + ); +} +assert.equal("resultExpectationBrand" in contracts, false); +assert.equal("connectionContextFactory" in contracts, false); +assert.equal("createTestResultExpectation" in contracts, false); +assert.equal("createTestObservationCapability" in contracts, false); +assert.equal("createTestAuthorityLink" in contracts, false); +assert.equal("createTestVerifiedReferencedEvidence" in contracts, false); +assert.equal("createTestCurrentReviewSetAuthority" in contracts, false); + console.log(`Temporary contract bundle loaded and exercised under ${process.version}.`); diff --git a/src/contracts/adjudication.ts b/src/contracts/adjudication.ts new file mode 100644 index 00000000..a5898e6d --- /dev/null +++ b/src/contracts/adjudication.ts @@ -0,0 +1,156 @@ +import { z } from "zod"; + +import type { ReferencedEvidence, Sha256Digest } from "./evidence.js"; +import { assertPlainJson } from "./plain-json.js"; +import { ADAPTER_IDS, EFFORT_VALUES, MODEL_FAMILIES, ruleVersionRefSchema, type AdapterId, type ModelFamily, type RuleVersionRef } from "./review.js"; + +export const CONSTITUTION_RESULTS = ["pass", "fail", "uncertain"] as const; +export const DRIFT_RESULTS = ["aligned", "incidental", "material"] as const; +export const COMPLIANCE_RESULTS = ["pass", "fail", "uncertain"] as const; +export const TRIGGER_RESULTS = ["not-matched", "matched", "uncertain"] as const; +export const MECHANICAL_EVIDENCE_STATES = ["current", "missing", "stale", "unknown", "failed", "digest-mismatch"] as const; + +export type ConstitutionResult = (typeof CONSTITUTION_RESULTS)[number]; +export type DriftResult = (typeof DRIFT_RESULTS)[number]; +export type ComplianceResult = (typeof COMPLIANCE_RESULTS)[number]; +export type TriggerResult = (typeof TRIGGER_RESULTS)[number]; +export type MechanicalEvidenceState = (typeof MECHANICAL_EVIDENCE_STATES)[number]; + +export interface MechanicalEvidence { + readonly mechanism: string; + readonly state: MechanicalEvidenceState; + readonly subject_digest?: Sha256Digest | undefined; + readonly evidence_digest?: Sha256Digest | undefined; + readonly details: string; +} +export interface ConstitutionRuleFinding extends RuleVersionRef { + readonly compliance: ComplianceResult; + readonly rationale: string; + readonly trigger: TriggerResult; + readonly trigger_evidence: string; + readonly enforced_by: readonly MechanicalEvidence[]; +} +export interface DriftFinding { + readonly upstream_digest: Sha256Digest; + readonly drift: DriftResult; + readonly affected_claim_ids: readonly string[]; + readonly rationale: string; +} +export interface RawAdjudication { + readonly schema_version: "1"; + readonly task_id: string; + readonly phase_instance: string; + readonly step: "adjudicate"; + readonly subject_digest: Sha256Digest; + readonly input_fingerprint: Sha256Digest; + readonly pinned_constitution_digest: Sha256Digest; + readonly approved_upstream_digests: readonly Sha256Digest[]; + readonly source_evidence_set_digest: Sha256Digest; + readonly rule_findings: readonly ConstitutionRuleFinding[]; + readonly drift_findings: readonly DriftFinding[]; + readonly constitution: ConstitutionResult; + readonly drift: DriftResult; + readonly matched_rule_versions: readonly RuleVersionRef[]; + readonly uncertain_rule_versions: readonly RuleVersionRef[]; +} +/** Semantically checked adjudication data. This type intentionally carries no authority brand. */ +export interface DerivedAdjudication extends RawAdjudication {} + +const nonBlank = z.string().min(1).refine((value) => value.trim().length > 0, "must contain a non-whitespace character"); +const id = z.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u); +const digest = z.string().regex(/^[0-9a-f]{64}$/u) as unknown as z.ZodType; +const mechanicalEvidenceSchema = z.object({ + mechanism: nonBlank, + state: z.enum(MECHANICAL_EVIDENCE_STATES), + subject_digest: digest.optional(), + evidence_digest: digest.optional(), + details: nonBlank, +}).strict().superRefine((evidence, context) => { + const hasBindings = evidence.subject_digest !== undefined && evidence.evidence_digest !== undefined; + if ((evidence.state === "current" || evidence.state === "stale") && !hasBindings) context.addIssue({ code: "custom", message: `${evidence.state} evidence requires subject and evidence digests` }); + if ((evidence.state === "missing" || evidence.state === "unknown") && (evidence.subject_digest !== undefined || evidence.evidence_digest !== undefined)) context.addIssue({ code: "custom", message: `${evidence.state} evidence cannot claim digests` }); +}); +const constitutionRuleFindingSchema = ruleVersionRefSchema.extend({ + compliance: z.enum(COMPLIANCE_RESULTS), + rationale: nonBlank, + trigger: z.enum(TRIGGER_RESULTS), + trigger_evidence: nonBlank, + enforced_by: z.array(mechanicalEvidenceSchema), +}).strict(); +const driftFindingSchema = z.object({ + upstream_digest: digest, + drift: z.enum(DRIFT_RESULTS), + affected_claim_ids: z.array(id), + rationale: nonBlank, +}).strict().superRefine((finding, context) => { + if ((finding.drift === "aligned") !== (finding.affected_claim_ids.length === 0)) context.addIssue({ code: "custom", path: ["affected_claim_ids"], message: "aligned drift has no affected claims; other drift must identify claims" }); + if (new Set(finding.affected_claim_ids).size !== finding.affected_claim_ids.length) context.addIssue({ code: "custom", path: ["affected_claim_ids"], message: "duplicate affected claim" }); +}); + +export const rawAdjudicationSchema = z.object({ + schema_version: z.literal("1"), task_id: id, + phase_instance: z.string().regex(/^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$/u), + step: z.literal("adjudicate"), subject_digest: digest, input_fingerprint: digest, + pinned_constitution_digest: digest, approved_upstream_digests: z.array(digest), source_evidence_set_digest: digest, + rule_findings: z.array(constitutionRuleFindingSchema), drift_findings: z.array(driftFindingSchema), + constitution: z.enum(CONSTITUTION_RESULTS), drift: z.enum(DRIFT_RESULTS), + matched_rule_versions: z.array(ruleVersionRefSchema), uncertain_rule_versions: z.array(ruleVersionRefSchema), +}).strict().superRefine((adjudication, context) => { + try { validateAdjudicationClaims(adjudication); } + catch (error) { context.addIssue({ code: "custom", message: error instanceof Error ? error.message : "invalid adjudication semantics" }); } +}); + +const ruleKey = (rule: RuleVersionRef) => `${rule.rule_id}:${rule.rule_version}`; +function assertSortedUnique(values: readonly string[], label: string): void { + if (new Set(values).size !== values.length || values.some((value, index) => index > 0 && values[index - 1]! >= value)) throw new TypeError(`${label} must be sorted and unique`); +} +function sameRuleSet(actual: readonly RuleVersionRef[], expected: readonly RuleVersionRef[]): boolean { + return actual.length === expected.length && actual.every((rule, index) => ruleKey(rule) === ruleKey(expected[index]!)); +} + +function validateAdjudicationClaims(parsed: RawAdjudication): void { + assertSortedUnique(parsed.approved_upstream_digests, "approved_upstream_digests"); + assertSortedUnique(parsed.rule_findings.map(ruleKey), "rule_findings"); + assertSortedUnique(parsed.drift_findings.map((finding) => finding.upstream_digest), "drift_findings"); + if (parsed.drift_findings.length !== parsed.approved_upstream_digests.length || parsed.drift_findings.some((finding, index) => finding.upstream_digest !== parsed.approved_upstream_digests[index])) throw new TypeError("drift_findings must exactly cover approved_upstream_digests"); + for (const finding of parsed.rule_findings) { + if (finding.compliance === "pass" && finding.enforced_by.length === 0) throw new TypeError(`compliance pass for ${ruleKey(finding)} requires current mechanical evidence`); + for (const evidence of finding.enforced_by) { + if (evidence.state === "current" && evidence.subject_digest !== parsed.subject_digest) throw new TypeError(`current mechanical evidence for ${ruleKey(finding)} binds the wrong subject`); + if (evidence.state !== "current" && finding.compliance === "pass") throw new TypeError(`suspect mechanical evidence cannot establish compliance for ${ruleKey(finding)}`); + } + } + const expectedConstitution: ConstitutionResult = parsed.rule_findings.some((finding) => finding.compliance === "fail") ? "fail" : parsed.rule_findings.some((finding) => finding.compliance === "uncertain") ? "uncertain" : "pass"; + if (parsed.constitution !== expectedConstitution) throw new TypeError(`constitution must be ${expectedConstitution}`); + const expectedDrift: DriftResult = parsed.drift_findings.some((finding) => finding.drift === "material") ? "material" : parsed.drift_findings.some((finding) => finding.drift === "incidental") ? "incidental" : "aligned"; + if (parsed.drift !== expectedDrift) throw new TypeError(`drift must be ${expectedDrift}`); + const matched = parsed.rule_findings.filter((finding) => finding.trigger === "matched").map(({ rule_id, rule_version }) => ({ rule_id, rule_version })); + const uncertain = parsed.rule_findings.filter((finding) => finding.trigger === "uncertain").map(({ rule_id, rule_version }) => ({ rule_id, rule_version })); + if (!sameRuleSet(parsed.matched_rule_versions, matched)) throw new TypeError("matched_rule_versions contradict rule findings"); + if (!sameRuleSet(parsed.uncertain_rule_versions, uncertain)) throw new TypeError("uncertain_rule_versions contradict rule findings"); +} + +export function parseAndDeriveAdjudication(value: unknown): DerivedAdjudication { + assertPlainJson(value, "adjudication"); + const parsed = rawAdjudicationSchema.parse(value); + validateAdjudicationClaims(parsed); + return parsed; +} + +interface AdjudicationProvenanceBase extends DerivedAdjudication { readonly model_family: ModelFamily | "unknown"; readonly model: string; readonly effort: (typeof EFFORT_VALUES)[number] | "unknown" } +export interface AgentDeclaredAdjudication extends AdjudicationProvenanceBase { readonly assurance: "agent-declared" } +export interface ServerAttestedAdjudication extends Omit { readonly assurance: "server-attested"; readonly adapter: AdapterId; readonly cli_version: string; readonly model_family: ModelFamily; readonly effort: (typeof EFFORT_VALUES)[number]; readonly invocation_id: string; readonly envelope_input_digest: Sha256Digest; readonly observed_output_digest: Sha256Digest; readonly result_id: string } +export interface DegradedAdjudication extends AdjudicationProvenanceBase { readonly assurance: "degraded"; readonly reason: string } +export type AdjudicationEvidence = AgentDeclaredAdjudication | ServerAttestedAdjudication | DegradedAdjudication; + +const provenanceBase = rawAdjudicationSchema.safeExtend({ model_family: z.union([z.enum(MODEL_FAMILIES), z.literal("unknown")]), model: nonBlank, effort: z.union([z.enum(EFFORT_VALUES), z.literal("unknown")]) }); +const agentSchema = provenanceBase.safeExtend({ assurance: z.literal("agent-declared") }).strict(); +const serverSchema = provenanceBase.safeExtend({ assurance: z.literal("server-attested"), adapter: z.enum(ADAPTER_IDS), cli_version: nonBlank, model_family: z.enum(MODEL_FAMILIES), effort: z.enum(EFFORT_VALUES), invocation_id: id, envelope_input_digest: digest, observed_output_digest: digest, result_id: id }).strict(); +const degradedSchema = provenanceBase.safeExtend({ assurance: z.literal("degraded"), reason: nonBlank }).strict(); +export const adjudicationEvidenceSchema = z.discriminatedUnion("assurance", [agentSchema, serverSchema, degradedSchema]); +export function parseAdjudicationEvidence(value: unknown): AdjudicationEvidence { assertPlainJson(value, "adjudication evidence"); const parsed = adjudicationEvidenceSchema.parse(value); validateAdjudicationClaims(parsed); return parsed; } +export function parseReferencedAdjudicationEvidence(value: unknown): ReferencedEvidence { + assertPlainJson(value, "referenced adjudication evidence"); + const wrapper = z.object({ evidence_digest: digest, evidence: z.unknown() }).strict().parse(value); + return { evidence_digest: wrapper.evidence_digest, evidence: parseAdjudicationEvidence(wrapper.evidence) }; +} diff --git a/src/contracts/contexts.ts b/src/contracts/contexts.ts new file mode 100644 index 00000000..8c37688e --- /dev/null +++ b/src/contracts/contexts.ts @@ -0,0 +1,24 @@ +import { z } from "zod"; +import { createProtocolError, type ProtocolError } from "./errors.js"; +import { assertPlainJson, type PlainJsonValue } from "./plain-json.js"; + +const connectionContextBrand: unique symbol = Symbol("ConnectionContext"); +const invocationContextBrand: unique symbol = Symbol("InvocationContext"); +const authenticConnections = new WeakSet(); +const authenticInvocations = new WeakSet(); +export interface ConnectionContext { readonly connection_id: string; readonly startup_repository_candidate: Readonly<{ readonly working_directory: string }>; readonly initialization_candidates: Readonly<{ readonly client: Readonly<{ readonly name: string; readonly version: string }>; readonly host: "claude" | "codex" | "unknown"; readonly protocol_version: string }>; readonly [connectionContextBrand]: true } +export interface InvocationContext { readonly invocation_id: string; readonly connection: ConnectionContext; readonly signal: AbortSignal; readonly transport_metadata: Readonly<{ readonly request_id: string | number; readonly operation: "tools/call" }>; readonly [invocationContextBrand]: true } +export interface ConnectionContextFactory { readonly captureStartup: (seed: unknown) => Readonly<{ initialize: (candidates: unknown) => ConnectionContext }> } +export class ProtocolContextError extends Error { public constructor(public readonly protocol_error: ProtocolError) { super(protocol_error.code); this.name = "ProtocolContextError"; } } + +const id = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); +const text = z.string().min(1).max(4096).regex(/\S/u); +const version = z.string().regex(/^[A-Za-z0-9.-]{1,64}$/u); +const startupSchema = z.object({ connection_id: id, startup_repository_candidate: z.object({ working_directory: text }).strict() }).strict(); +const initializationSchema = z.object({ client: z.object({ name: text, version }).strict(), host: z.enum(["claude", "codex", "unknown"]), protocol_version: version }).strict(); +const invocationSchema = z.object({ invocation_id: id, transport_metadata: z.object({ request_id: z.union([text, z.number().int().safe()]), operation: z.literal("tools/call") }).strict() }).strict(); +function deepFreeze(value: T): T { if (value !== null && typeof value === "object") { for (const nested of Object.values(value)) deepFreeze(nested); Object.freeze(value); } return value; } +function copy(value: T): T { return structuredClone(value as PlainJsonValue) as T; } + +export const connectionContextFactory: ConnectionContextFactory = Object.freeze({ captureStartup(seed: unknown) { assertPlainJson(seed, "connection startup"); const startup = deepFreeze(copy(startupSchema.parse(seed))); let initialized = false; return Object.freeze({ initialize(candidates: unknown): ConnectionContext { if (initialized) throw new ProtocolContextError(createProtocolError("INITIALIZATION_REPEATED", { connection_id: startup.connection_id })); assertPlainJson(candidates, "connection initialization"); const initialization = deepFreeze(copy(initializationSchema.parse(candidates))); initialized = true; const connection = deepFreeze({ connection_id: startup.connection_id, startup_repository_candidate: startup.startup_repository_candidate, initialization_candidates: initialization }) as ConnectionContext; authenticConnections.add(connection); return connection; } }); } }); +export function createInvocationContext(connection: ConnectionContext, seed: unknown, signal: AbortSignal): InvocationContext { if (!authenticConnections.has(connection)) throw new TypeError("a branded connection context is required"); if (!(signal instanceof AbortSignal)) throw new TypeError("an AbortSignal is required"); assertPlainJson(seed, "invocation context"); const invocation = deepFreeze(copy(invocationSchema.parse(seed))); const context = Object.freeze({ invocation_id: invocation.invocation_id, connection, signal, transport_metadata: invocation.transport_metadata }) as InvocationContext; authenticInvocations.add(context); return context; } diff --git a/src/contracts/errors.ts b/src/contracts/errors.ts new file mode 100644 index 00000000..98294b9e --- /dev/null +++ b/src/contracts/errors.ts @@ -0,0 +1,104 @@ +import { z } from "zod"; +import { isDeepStrictEqual } from "node:util"; + +import { safeCodeV1Schema, safeIdV1Schema, safeIntegerV1Schema, safeVersionV1Schema, sha256DigestV1Schema } from "./evidence.js"; +import type { Sha256Digest } from "./evidence.js"; +import { assertPlainJson } from "./plain-json.js"; +import { decodePhaseInstance, type PhaseInstanceId } from "./phase-instance.js"; +import { taskPathClaimV1Schema, type TaskPathClaim } from "./path-claims.js"; +import { GATE_KINDS, type GateKind } from "./gates.js"; +import type { AdapterId, ModelFamily } from "./review.js"; +import { TOOL_NAMES, type ToolName } from "./tool-names.js"; + +export type ErrorOwner = "contracts" | "config" | "repository" | "paths" | "policy" | "state" | "intent" | "snapshot" | "gate" | "routing" | "dispatch" | "sandbox" | "protocol" | "integrity"; +export type ErrorProjection = "project" | "protocol"; +export interface StrictParameterParser

>> { readonly parse: (value: unknown) => P } +export interface ErrorDefinition

>, O extends ErrorOwner, R extends boolean, A extends string, X extends ErrorProjection> { readonly owner: O; readonly retryable: R; readonly parameter_parser: StrictParameterParser

; readonly action: A; readonly projection: X } +export type CompleteErrorRegistry = Readonly<{ [K in C]: ErrorDefinition>, O, boolean, string, X> }>; + +export type ProjectErrorCode = "CONTRACT_INVALID" | "RESULT_INVALID" | "CONTRACT_VERSION_UNSUPPORTED" | "WORKFLOW_INVALID" | "CONFIG_INVALID" | "CONFIG_MODEL_UNSUPPORTED" | "CONFIG_FAMILY_UNSUPPORTED" | "RUNTIME_VERSION_UNSUPPORTED" | "REPOSITORY_NOT_FOUND" | "REPOSITORY_MISMATCH" | "TASK_INVALID" | "PATH_INVALID" | "PATH_ESCAPE" | "TASK_SCOPE_VIOLATION" | "GIT_CONFLICT" | "GIT_DIVERGED" | "HANDOFF_REQUIRED" | "POLICY_BASE_INVALID" | "WORKFLOW_MISMATCH" | "PINNED_CONFIG_MISMATCH" | "STALE_SKILLS" | "STATE_MISSING" | "STATE_INVALID" | "TRANSITION_INVALID" | "INPUT_FINGERPRINT_MISMATCH" | "STATE_CONFLICT" | "SUPPLEMENTAL_REVIEW_REQUIRED" | "INTENT_MISMATCH" | "SNAPSHOT_LIMIT" | "SNAPSHOT_INVALID" | "RESTORE_COLLISION" | "RECONCILIATION_REQUIRED" | "SECRET_DETECTED" | "GATE_ACTIVE" | "GATE_DECISION_INVALID" | "GATE_CANCELLED" | "UNSUPPORTED_HOST" | "UNSUPPORTED_MODEL" | "FAMILY_MISMATCH" | "CLI_VERSION_UNSUPPORTED" | "AUTH_UNAVAILABLE" | "CLI_MISSING" | "SANDBOX_UNAVAILABLE" | "SANDBOX_PROBE_FAILED" | "RATE_LIMITED" | "TIMEOUT" | "CANCELLED" | "MODEL_OUTPUT_INVALID" | "IO_ERROR" | "OUTPUT_OVERFLOW" | "PROCESS_FAILED" | "INTERNAL_ERROR"; +export type ProtocolErrorCode = "TOOL_NOT_FOUND" | "TOOL_DISABLED" | "UNSUPPORTED_PROTOCOL" | "INITIALIZATION_REPEATED"; + +const tool = z.enum(TOOL_NAMES); +const adapter = z.enum(["claude-cli", "codex-cli"] satisfies readonly AdapterId[]); +const family = z.enum(["claude", "codex"] satisfies readonly ModelFamily[]); +const gateKind = z.enum(GATE_KINDS); +const phaseInstance = z.string().refine((value) => { try { decodePhaseInstance(value); return true; } catch { return false; } }); +const object = (shape: T) => z.object(shape).strict(); +const digestPair = { expected_digest: sha256DigestV1Schema, observed_digest: sha256DigestV1Schema } as const; +const taskPathClass = { task_id: safeIdV1Schema, path_class: safeCodeV1Schema } as const; +const adapterAttempt = { adapter, attempt: safeIntegerV1Schema } as const; +const sortedPaths = z.array(taskPathClaimV1Schema).min(1).superRefine((items, context) => { for (let index = 1; index < items.length; index += 1) if (items[index - 1]!.localeCompare(items[index]!) >= 0) context.addIssue({ code: "custom", message: "offending_paths must be sorted and unique" }); }); + +const PROJECT_PARAMETER_SCHEMAS = { + CONTRACT_INVALID: object({ tool: tool.optional(), issue_code: safeCodeV1Schema, schema_version: safeVersionV1Schema.optional() }), + RESULT_INVALID: object({ tool, result_id: safeIdV1Schema, expected_digest: sha256DigestV1Schema.optional(), observed_digest: sha256DigestV1Schema.optional() }), + CONTRACT_VERSION_UNSUPPORTED: object({ schema_version: safeVersionV1Schema, supported_version: safeVersionV1Schema }), + WORKFLOW_INVALID: object({ issue_code: safeCodeV1Schema }), CONFIG_INVALID: object({ issue_code: safeCodeV1Schema }), + CONFIG_MODEL_UNSUPPORTED: object({ model: safeIdV1Schema }), CONFIG_FAMILY_UNSUPPORTED: object({ family: safeIdV1Schema }), + RUNTIME_VERSION_UNSUPPORTED: object({ component: safeIdV1Schema, version: safeVersionV1Schema }), + REPOSITORY_NOT_FOUND: object({ repository_candidate_digest: sha256DigestV1Schema }), REPOSITORY_MISMATCH: object(digestPair), + TASK_INVALID: object({ task_id: safeIdV1Schema, issue_code: safeCodeV1Schema }), PATH_INVALID: object(taskPathClass), PATH_ESCAPE: object(taskPathClass), TASK_SCOPE_VIOLATION: object(taskPathClass), + GIT_CONFLICT: object({ operation: safeCodeV1Schema }), GIT_DIVERGED: object(digestPair), HANDOFF_REQUIRED: object({ phase_instance: phaseInstance }), + POLICY_BASE_INVALID: object({ expected_digest: sha256DigestV1Schema, observed_digest: sha256DigestV1Schema.optional() }), WORKFLOW_MISMATCH: object(digestPair), PINNED_CONFIG_MISMATCH: object(digestPair), STALE_SKILLS: object(digestPair), + STATE_MISSING: object({ phase_instance: phaseInstance }), STATE_INVALID: object({ phase_instance: phaseInstance, issue_code: safeCodeV1Schema }), TRANSITION_INVALID: object({ phase_instance: phaseInstance, from: safeCodeV1Schema, to: safeCodeV1Schema }), + INPUT_FINGERPRINT_MISMATCH: object(digestPair), STATE_CONFLICT: object({ expected_revision: safeIntegerV1Schema, observed_revision: safeIntegerV1Schema }), SUPPLEMENTAL_REVIEW_REQUIRED: object({ gate_id: safeIdV1Schema, evidence_digest: sha256DigestV1Schema }), INTENT_MISMATCH: object(digestPair), + SNAPSHOT_LIMIT: object({ limit_scope: z.enum(["result", "task"]), offending_paths: sortedPaths, current_bytes: safeIntegerV1Schema, byte_cap: safeIntegerV1Schema }), SNAPSHOT_INVALID: object({ snapshot_digest: sha256DigestV1Schema, issue_code: safeCodeV1Schema }), RESTORE_COLLISION: object({ gate_id: safeIdV1Schema, path_class: safeCodeV1Schema }), RECONCILIATION_REQUIRED: object({ recorded_digest: sha256DigestV1Schema, observed_digest: sha256DigestV1Schema }), SECRET_DETECTED: object({ path_class: safeCodeV1Schema, detector_id: safeIdV1Schema }), + GATE_ACTIVE: object({ gate_id: safeIdV1Schema, gate_kind: gateKind }), GATE_DECISION_INVALID: object({ gate_id: safeIdV1Schema, gate_kind: gateKind, issue_code: safeCodeV1Schema }), GATE_CANCELLED: object({ gate_id: safeIdV1Schema, gate_kind: gateKind }), + UNSUPPORTED_HOST: object({ host: safeIdV1Schema }), UNSUPPORTED_MODEL: object({ model: safeIdV1Schema }), FAMILY_MISMATCH: object({ expected_family: family, observed_family: family }), + CLI_VERSION_UNSUPPORTED: object({ adapter, version: safeVersionV1Schema }), AUTH_UNAVAILABLE: object({ adapter }), CLI_MISSING: object({ adapter }), SANDBOX_UNAVAILABLE: object({ capability: safeIdV1Schema }), SANDBOX_PROBE_FAILED: object({ capability: safeIdV1Schema, failure_class: safeCodeV1Schema }), + RATE_LIMITED: object(adapterAttempt), TIMEOUT: object({ ...adapterAttempt, limit_ms: safeIntegerV1Schema }), CANCELLED: object({ source: z.enum(["client", "transport"]), attempt: safeIntegerV1Schema }), MODEL_OUTPUT_INVALID: object({ ...adapterAttempt, issue_code: safeCodeV1Schema }), IO_ERROR: object({ operation: safeCodeV1Schema, attempt: safeIntegerV1Schema }), OUTPUT_OVERFLOW: object({ adapter, byte_count: safeIntegerV1Schema, byte_cap: safeIntegerV1Schema }), PROCESS_FAILED: object({ adapter, exit_class: safeCodeV1Schema }), INTERNAL_ERROR: object({ correlation_id: safeIdV1Schema }), +} as const satisfies Record>>>; + +const PROTOCOL_PARAMETER_SCHEMAS = { + TOOL_NOT_FOUND: object({ tool_name_digest: sha256DigestV1Schema }), TOOL_DISABLED: object({ tool, lifecycle_state: safeCodeV1Schema }), UNSUPPORTED_PROTOCOL: object({ offered_version: safeVersionV1Schema, supported_version: safeVersionV1Schema }), INITIALIZATION_REPEATED: object({ connection_id: safeIdV1Schema }), +} as const satisfies Record>>>; + +function parser

>>(schema: z.ZodType

): StrictParameterParser

{ return Object.freeze({ parse(value: unknown): P { assertPlainJson(value, "error parameters"); return schema.parse(value); } }); } +function defineError

>, O extends ErrorOwner, R extends boolean, A extends string, X extends ErrorProjection>(owner: O, retryable: R, schema: z.ZodType

, action: A, projection: X): ErrorDefinition { return Object.freeze({ owner, retryable, parameter_parser: parser(schema), action, projection }); } + +export const PROJECT_ERROR_DEFINITIONS = Object.freeze({ + CONTRACT_INVALID: defineError("contracts", false, PROJECT_PARAMETER_SCHEMAS.CONTRACT_INVALID, "correct-contract", "project"), RESULT_INVALID: defineError("integrity", false, PROJECT_PARAMETER_SCHEMAS.RESULT_INVALID, "repair-retained-result", "project"), CONTRACT_VERSION_UNSUPPORTED: defineError("contracts", false, PROJECT_PARAMETER_SCHEMAS.CONTRACT_VERSION_UNSUPPORTED, "upgrade-caller", "project"), + WORKFLOW_INVALID: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.WORKFLOW_INVALID, "repair-workflow", "project"), CONFIG_INVALID: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.CONFIG_INVALID, "repair-config", "project"), CONFIG_MODEL_UNSUPPORTED: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.CONFIG_MODEL_UNSUPPORTED, "select-supported-model", "project"), CONFIG_FAMILY_UNSUPPORTED: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.CONFIG_FAMILY_UNSUPPORTED, "select-supported-family", "project"), RUNTIME_VERSION_UNSUPPORTED: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.RUNTIME_VERSION_UNSUPPORTED, "upgrade-runtime", "project"), + REPOSITORY_NOT_FOUND: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.REPOSITORY_NOT_FOUND, "open-repository", "project"), REPOSITORY_MISMATCH: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.REPOSITORY_MISMATCH, "reopen-task-worktree", "project"), TASK_INVALID: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.TASK_INVALID, "repair-task", "project"), PATH_INVALID: defineError("paths", false, PROJECT_PARAMETER_SCHEMAS.PATH_INVALID, "use-valid-path-claim", "project"), PATH_ESCAPE: defineError("paths", false, PROJECT_PARAMETER_SCHEMAS.PATH_ESCAPE, "use-task-relative-path", "project"), TASK_SCOPE_VIOLATION: defineError("paths", false, PROJECT_PARAMETER_SCHEMAS.TASK_SCOPE_VIOLATION, "use-task-scoped-path", "project"), GIT_CONFLICT: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.GIT_CONFLICT, "resolve-git-conflict", "project"), GIT_DIVERGED: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.GIT_DIVERGED, "reconcile-git-history", "project"), HANDOFF_REQUIRED: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.HANDOFF_REQUIRED, "complete-clean-handoff", "project"), + POLICY_BASE_INVALID: defineError("policy", false, PROJECT_PARAMETER_SCHEMAS.POLICY_BASE_INVALID, "restore-policy-base", "project"), WORKFLOW_MISMATCH: defineError("policy", false, PROJECT_PARAMETER_SCHEMAS.WORKFLOW_MISMATCH, "restore-pinned-workflow", "project"), PINNED_CONFIG_MISMATCH: defineError("policy", false, PROJECT_PARAMETER_SCHEMAS.PINNED_CONFIG_MISMATCH, "restore-pinned-config", "project"), STALE_SKILLS: defineError("policy", false, PROJECT_PARAMETER_SCHEMAS.STALE_SKILLS, "refresh-skills", "project"), + STATE_MISSING: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.STATE_MISSING, "initialize-state", "project"), STATE_INVALID: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.STATE_INVALID, "repair-state", "project"), TRANSITION_INVALID: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.TRANSITION_INVALID, "select-valid-transition", "project"), INPUT_FINGERPRINT_MISMATCH: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.INPUT_FINGERPRINT_MISMATCH, "create-fresh-intent", "project"), STATE_CONFLICT: defineError("state", true, PROJECT_PARAMETER_SCHEMAS.STATE_CONFLICT, "reread-and-retry-intent", "project"), SUPPLEMENTAL_REVIEW_REQUIRED: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.SUPPLEMENTAL_REVIEW_REQUIRED, "triage-supplemental-review", "project"), INTENT_MISMATCH: defineError("intent", false, PROJECT_PARAMETER_SCHEMAS.INTENT_MISMATCH, "create-fresh-intent", "project"), + SNAPSHOT_LIMIT: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.SNAPSHOT_LIMIT, "reduce-snapshot", "project"), SNAPSHOT_INVALID: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.SNAPSHOT_INVALID, "repair-snapshot", "project"), RESTORE_COLLISION: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.RESTORE_COLLISION, "resolve-restore-gate", "project"), RECONCILIATION_REQUIRED: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.RECONCILIATION_REQUIRED, "run-reconciliation", "project"), SECRET_DETECTED: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.SECRET_DETECTED, "remove-secret", "project"), + GATE_ACTIVE: defineError("gate", false, PROJECT_PARAMETER_SCHEMAS.GATE_ACTIVE, "resolve-recorded-gate", "project"), GATE_DECISION_INVALID: defineError("gate", false, PROJECT_PARAMETER_SCHEMAS.GATE_DECISION_INVALID, "record-valid-gate-decision", "project"), GATE_CANCELLED: defineError("gate", false, PROJECT_PARAMETER_SCHEMAS.GATE_CANCELLED, "restart-gate-flow", "project"), + UNSUPPORTED_HOST: defineError("routing", false, PROJECT_PARAMETER_SCHEMAS.UNSUPPORTED_HOST, "select-supported-host", "project"), UNSUPPORTED_MODEL: defineError("routing", false, PROJECT_PARAMETER_SCHEMAS.UNSUPPORTED_MODEL, "select-supported-model", "project"), FAMILY_MISMATCH: defineError("routing", false, PROJECT_PARAMETER_SCHEMAS.FAMILY_MISMATCH, "select-correct-family", "project"), CLI_VERSION_UNSUPPORTED: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.CLI_VERSION_UNSUPPORTED, "upgrade-cli", "project"), AUTH_UNAVAILABLE: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.AUTH_UNAVAILABLE, "repair-authentication", "project"), CLI_MISSING: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.CLI_MISSING, "install-cli", "project"), SANDBOX_UNAVAILABLE: defineError("sandbox", false, PROJECT_PARAMETER_SCHEMAS.SANDBOX_UNAVAILABLE, "repair-sandbox", "project"), SANDBOX_PROBE_FAILED: defineError("sandbox", false, PROJECT_PARAMETER_SCHEMAS.SANDBOX_PROBE_FAILED, "repair-sandbox", "project"), + RATE_LIMITED: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.RATE_LIMITED, "retry-after-backoff", "project"), TIMEOUT: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.TIMEOUT, "retry-unchanged-attempt", "project"), CANCELLED: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.CANCELLED, "restart-child-attempt", "project"), MODEL_OUTPUT_INVALID: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.MODEL_OUTPUT_INVALID, "retry-unchanged-attempt", "project"), IO_ERROR: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.IO_ERROR, "retry-unchanged-attempt", "project"), OUTPUT_OVERFLOW: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.OUTPUT_OVERFLOW, "reduce-output", "project"), PROCESS_FAILED: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.PROCESS_FAILED, "repair-before-fresh-attempt", "project"), INTERNAL_ERROR: defineError("integrity", false, PROJECT_PARAMETER_SCHEMAS.INTERNAL_ERROR, "stop-and-inspect", "project"), +} as const satisfies CompleteErrorRegistry); + +export const PROTOCOL_ERROR_DEFINITIONS = Object.freeze({ + TOOL_NOT_FOUND: defineError("protocol", false, PROTOCOL_PARAMETER_SCHEMAS.TOOL_NOT_FOUND, "call-advertised-tool", "protocol"), TOOL_DISABLED: defineError("protocol", false, PROTOCOL_PARAMETER_SCHEMAS.TOOL_DISABLED, "wait-for-tool-enable", "protocol"), UNSUPPORTED_PROTOCOL: defineError("protocol", false, PROTOCOL_PARAMETER_SCHEMAS.UNSUPPORTED_PROTOCOL, "negotiate-supported-protocol", "protocol"), INITIALIZATION_REPEATED: defineError("protocol", false, PROTOCOL_PARAMETER_SCHEMAS.INITIALIZATION_REPEATED, "open-new-connection", "protocol"), +} as const satisfies CompleteErrorRegistry); + +export type ProjectErrorDefinitionByCode = typeof PROJECT_ERROR_DEFINITIONS; +export type ProtocolErrorDefinitionByCode = typeof PROTOCOL_ERROR_DEFINITIONS; +export type ErrorValue = Readonly<{ schema_version: "1"; code: K; owner: R[K] extends ErrorDefinition ? O : never; retryable: R[K] extends ErrorDefinition ? B : never; diagnostic: Readonly<{ template_id: K; parameters: R[K] extends ErrorDefinition ? P : never }>; next_action: R[K] extends ErrorDefinition ? A : never }>; +export type ProjectError = { readonly [K in ProjectErrorCode]: ErrorValue }[ProjectErrorCode]; +export type ProtocolError = { readonly [K in ProtocolErrorCode]: ErrorValue }[ProtocolErrorCode]; +export type ProjectResult = { readonly schema_version: "1"; readonly ok: true; readonly value: T } | { readonly schema_version: "1"; readonly ok: false; readonly error: ProjectError }; + +function constructError>>, K extends keyof R>(registry: R, code: K, parameters: unknown): ErrorValue { + const definition = registry[code]!; + const parsed = definition.parameter_parser.parse(parameters); + return Object.freeze({ schema_version: "1", code, owner: definition.owner, retryable: definition.retryable, diagnostic: Object.freeze({ template_id: code, parameters: parsed }), next_action: definition.action }) as ErrorValue; +} +export function createProjectError(code: K, parameters: z.input<(typeof PROJECT_PARAMETER_SCHEMAS)[K]>): ErrorValue { return constructError(PROJECT_ERROR_DEFINITIONS, code, parameters); } +export function createProtocolError(code: K, parameters: z.input<(typeof PROTOCOL_PARAMETER_SCHEMAS)[K]>): ErrorValue { return constructError(PROTOCOL_ERROR_DEFINITIONS, code, parameters); } + +function parseSerializedError>>>(registry: R, value: unknown, label: string): ErrorValue { + assertPlainJson(value, label); + const shell = object({ schema_version: z.literal("1"), code: z.string(), owner: z.string(), retryable: z.boolean(), diagnostic: object({ template_id: z.string(), parameters: z.record(z.string(), z.unknown()) }), next_action: z.string() }).parse(value); + if (!Object.hasOwn(registry, shell.code)) throw new TypeError(`${label}: unknown code`); + const code = shell.code as keyof R; + const expected = constructError(registry, code, shell.diagnostic.parameters); + if (!isDeepStrictEqual(shell, expected)) throw new TypeError(`${label}: fields do not match the error registry`); + return value as ErrorValue; +} +export function parseProjectError(value: unknown): ProjectError { return parseSerializedError(PROJECT_ERROR_DEFINITIONS, value, "project error") as ProjectError; } +export function parseProtocolError(value: unknown): ProtocolError { return parseSerializedError(PROTOCOL_ERROR_DEFINITIONS, value, "protocol error") as ProtocolError; } + +// Type-only exports make the exact table primitives discoverable without granting authority. +export type ErrorParameterPrimitives = { readonly digest: Sha256Digest; readonly tool: ToolName; readonly phase: PhaseInstanceId; readonly path: TaskPathClaim; readonly gate: GateKind; readonly adapter: AdapterId; readonly family: ModelFamily }; diff --git a/src/contracts/evidence.ts b/src/contracts/evidence.ts new file mode 100644 index 00000000..d3f6d3cf --- /dev/null +++ b/src/contracts/evidence.ts @@ -0,0 +1,51 @@ +import { z } from "zod"; + +import { assertPlainJson } from "./plain-json.js"; + +declare const sha256DigestBrand: unique symbol; +declare const safeIdBrand: unique symbol; +declare const safeCodeBrand: unique symbol; +declare const safeVersionBrand: unique symbol; +declare const safeIntegerBrand: unique symbol; + +export type Sha256Digest = string & { readonly [sha256DigestBrand]: true }; +export type SafeId = string & { readonly [safeIdBrand]: true }; +export type SafeCode = string & { readonly [safeCodeBrand]: true }; +export type SafeVersion = string & { readonly [safeVersionBrand]: true }; +export type SafeInteger = number & { readonly [safeIntegerBrand]: true }; + +export interface ReferencedEvidence { + readonly evidence_digest: Sha256Digest; + readonly evidence: T; +} + +export const sha256DigestV1Schema = z.string().regex(/^[0-9a-f]{64}$/u); +export const safeIdV1Schema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); +export const safeCodeV1Schema = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/u); +export const safeVersionV1Schema = z.string().regex(/^[A-Za-z0-9.-]{1,64}$/u); +export const safeIntegerV1Schema = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER); + +export function parseSha256Digest(value: unknown): Sha256Digest { + assertPlainJson(value, "SHA-256 digest"); + return sha256DigestV1Schema.parse(value) as Sha256Digest; +} + +export function parseSafeId(value: unknown): SafeId { + assertPlainJson(value, "safe identifier"); + return safeIdV1Schema.parse(value) as SafeId; +} + +export function parseSafeCode(value: unknown): SafeCode { + assertPlainJson(value, "safe code"); + return safeCodeV1Schema.parse(value) as SafeCode; +} + +export function parseSafeVersion(value: unknown): SafeVersion { + assertPlainJson(value, "safe version"); + return safeVersionV1Schema.parse(value) as SafeVersion; +} + +export function parseSafeInteger(value: unknown): SafeInteger { + assertPlainJson(value, "safe integer"); + return safeIntegerV1Schema.parse(value) as SafeInteger; +} diff --git a/src/contracts/gates.ts b/src/contracts/gates.ts new file mode 100644 index 00000000..5cbd7d4a --- /dev/null +++ b/src/contracts/gates.ts @@ -0,0 +1,194 @@ +import { z } from "zod"; + +import type { Sha256Digest } from "./evidence.js"; +import { safeIdV1Schema } from "./evidence.js"; +import { assertPlainJson } from "./plain-json.js"; +import { decodePhaseInstance, type PhaseInstanceId } from "./phase-instance.js"; +import { taskPathClaimV1Schema, type TaskPathClaim } from "./path-claims.js"; +import { PIPELINE_STEPS, type PipelineStep } from "./vocabulary.js"; + +export interface RuleVersionRef { readonly rule_id: string; readonly rule_version: number } +export type EvidenceIdentityKind = "prd" | "architecture" | "phase-design" | "implementation-result" | "review" | "adjudication" | "constitution" | "workflow" | "import"; +export interface EvidenceIdentityRef { readonly kind: EvidenceIdentityKind; readonly digest: Sha256Digest } +export type WaivableOperation = "review-trigger" | "adjudication-failure"; +export interface WaiverScope { readonly operation: WaivableOperation; readonly boundary: "subject" | "phase" | "task" } +export interface HumanRuleResolution { readonly rule: RuleVersionRef; readonly resolution: string } + +export type HumanDecisionProvenance = + | Readonly<{ schema_version: "1"; actor_class: "human" | "archforge"; assurance: "declared-local-trace"; channel: "connected-host"; decision_event_id: string; connection_id: string; request_id_digest: Sha256Digest; recorded_at: string }> + | Readonly<{ schema_version: "1"; actor_class: "human" | "archforge"; assurance: "declared-local-trace"; channel: "archflow-local"; decision_event_id: string; helper_invocation_id: string; recorded_at: string }>; + +export interface AuthorityLinkRef { + readonly link_digest: Sha256Digest; + readonly purpose: "restore-adoption"; + readonly proposed_generation_digest: Sha256Digest; + readonly changed_input_fingerprint: Sha256Digest; +} + +export interface GateContractByKind { + readonly "artifact-approval": { readonly context: { readonly artifact_kind: "prd" | "design" | "phase-design" | "phase-implementation" }; readonly decision: { readonly decision: "approve" | "revise" | "reject"; readonly reason: string } }; + readonly "review-trigger": { readonly context: { readonly matched_rules: readonly RuleVersionRef[]; readonly uncertain_rules: readonly RuleVersionRef[]; readonly eligible_waiver_rules: readonly RuleVersionRef[]; readonly waiver_scope: WaiverScope }; readonly decision: { readonly decision: "approve" | "revise" | "reject"; readonly reason: string } | { readonly decision: "waiver-requested"; readonly reason: string; readonly rule: RuleVersionRef; readonly rationale: string } }; + readonly "material-drift": { readonly context: { readonly affected_upstream: EvidenceIdentityRef; readonly drift: "material"; readonly affected_claim_ids: readonly string[] }; readonly decision: { readonly decision: "amend-upstream" | "revise-current" | "reject"; readonly reason: string } }; + readonly "adjudication-failure": { readonly context: { readonly constitution: "fail" | "uncertain"; readonly failed_rules: readonly RuleVersionRef[]; readonly uncertain_rules: readonly RuleVersionRef[]; readonly eligible_waiver_rules: readonly RuleVersionRef[]; readonly waiver_scope: WaiverScope }; readonly decision: { readonly decision: "approve"; readonly reason: string; readonly resolutions: readonly HumanRuleResolution[] } | { readonly decision: "revise" | "reject"; readonly reason: string } | { readonly decision: "waiver-requested"; readonly reason: string; readonly rule: RuleVersionRef; readonly rationale: string } }; + readonly "attempts-exhausted": { readonly context: { readonly step: PipelineStep; readonly attempts: number; readonly maximum_attempts: number }; readonly decision: { readonly decision: "retry-once" | "revise" | "abort"; readonly reason: string } }; + readonly "constitution-edit": { readonly context: { readonly pinned_constitution_digest: Sha256Digest; readonly current_constitution_digest: Sha256Digest; readonly changed_path_class: "task-branch-constitution" }; readonly decision: { readonly decision: "revert-edit" | "start-base-amendment" | "abort"; readonly reason: string } }; + readonly "commit-authorization": { readonly context: { readonly target_ref: string; readonly diff_digest: Sha256Digest; readonly current_artifact_digests: readonly Sha256Digest[]; readonly parent_document_digests: readonly Sha256Digest[] }; readonly decision: { readonly decision: "authorize-commit" | "revise" | "abort"; readonly reason: string } }; + readonly "restore-collision": { readonly context: { readonly path: TaskPathClaim; readonly recorded_generation_digest: Sha256Digest; readonly current_generation_digest: Sha256Digest; readonly adoption_candidate?: AuthorityLinkRef }; readonly decision: { readonly decision: "discard-and-restore" | "abort"; readonly reason: string } | { readonly decision: "adopt-as-new-generation"; readonly reason: string; readonly adoption_authority: AuthorityLinkRef; readonly rationale: string } }; + readonly "migration-audit": { readonly context: { readonly source_identity_digest: Sha256Digest; readonly destination_identity_digest: Sha256Digest; readonly import_digest: Sha256Digest; readonly code_baseline_digest: Sha256Digest; readonly policy_baseline_digest: Sha256Digest }; readonly decision: { readonly decision: "accept-import-audit" | "revise" | "abort"; readonly reason: string } }; +} + +export const GATE_KINDS = ["artifact-approval", "review-trigger", "material-drift", "adjudication-failure", "attempts-exhausted", "constitution-edit", "commit-authorization", "restore-collision", "migration-audit"] as const; +export type GateKind = keyof GateContractByKind; +export type GateContext = GateContractByKind[K]["context"]; +export type GateDecisionPayload = GateContractByKind[K]["decision"]; +export type GateEffect = "advance" | "retry" | "redirect-waiver" | "redirect-upstream" | "non-advancing"; + +export interface GateDecisionEnvelopeBase { readonly schema_version: "1"; readonly gate_id: string; readonly task_id: string; readonly phase_instance: PhaseInstanceId; readonly subject_digest: Sha256Digest; readonly context_digest: Sha256Digest; readonly human_provenance: HumanDecisionProvenance } +export type GateDecisionEnvelope = { readonly [P in K]: GateDecisionEnvelopeBase & { readonly kind: P; readonly payload: GateDecisionPayload

} }[K]; + +/** Exact archived origin binding consumed by the later waiver owner. */ +export interface WaiverOriginRef { + readonly origin_gate_id: string; + readonly origin_decision_digest: Sha256Digest; + readonly origin_context_digest: Sha256Digest; + readonly task_id: string; + readonly phase_instance: PhaseInstanceId; + readonly subject_digest: Sha256Digest; + readonly current_evidence_set_digest: Sha256Digest; + readonly rule: RuleVersionRef; + readonly scope: WaiverScope; +} + +const safeId = safeIdV1Schema; +const boundedText = z.string().min(1).max(4096).regex(/\S/u); +const digest = z.string().regex(/^[0-9a-f]{64}$/u); +const safeInteger = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const rule = z.object({ rule_id: safeId, rule_version: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) }).strict(); +const ruleResolution = z.object({ rule, resolution: boundedText }).strict(); +const waiverScope = z.object({ operation: z.enum(["review-trigger", "adjudication-failure"]), boundary: z.enum(["subject", "phase", "task"]) }).strict(); +const authorityLink = z.object({ link_digest: digest, purpose: z.literal("restore-adoption"), proposed_generation_digest: digest, changed_input_fingerprint: digest }).strict(); +const reason = boundedText; +const decision = (values: T) => z.object({ decision: z.enum(values), reason }).strict(); +const sortedUnique = (items: readonly T[], compare: (left: T, right: T) => number): boolean => items.every((item, index) => index === 0 || compare(items[index - 1]!, item) < 0); +const compareRules = (left: RuleVersionRef, right: RuleVersionRef): number => left.rule_id.localeCompare(right.rule_id) || left.rule_version - right.rule_version; +const canonicalRules = z.array(rule).superRefine((items, context) => { if (!sortedUnique(items, compareRules)) context.addIssue({ code: "custom", message: "rules must be sorted and unique" }); }); +const canonicalStrings = z.array(safeId).superRefine((items, context) => { if (!sortedUnique(items, (a, b) => a.localeCompare(b))) context.addIssue({ code: "custom", message: "values must be sorted and unique" }); }); +const canonicalDigests = z.array(digest).superRefine((items, context) => { if (!sortedUnique(items, (a, b) => a.localeCompare(b))) context.addIssue({ code: "custom", message: "digests must be sorted and unique" }); }); + +const contexts = { + "artifact-approval": z.object({ artifact_kind: z.enum(["prd", "design", "phase-design", "phase-implementation"]) }).strict(), + "review-trigger": z.object({ matched_rules: canonicalRules, uncertain_rules: canonicalRules, eligible_waiver_rules: canonicalRules, waiver_scope: waiverScope }).strict().superRefine((value, context) => { + if (value.waiver_scope.operation !== "review-trigger") context.addIssue({ code: "custom", message: "waiver operation must match gate kind" }); + const available = new Set([...value.matched_rules, ...value.uncertain_rules].map(ruleKey)); + for (const item of value.eligible_waiver_rules) if (!available.has(ruleKey(item))) context.addIssue({ code: "custom", message: "eligible waiver rule must be matched or uncertain" }); + }), + "material-drift": z.object({ affected_upstream: z.object({ kind: z.enum(["prd", "architecture", "phase-design", "implementation-result", "review", "adjudication", "constitution", "workflow", "import"]), digest }).strict(), drift: z.literal("material"), affected_claim_ids: canonicalStrings.min(1) }).strict(), + "adjudication-failure": z.object({ constitution: z.enum(["fail", "uncertain"]), failed_rules: canonicalRules, uncertain_rules: canonicalRules, eligible_waiver_rules: canonicalRules, waiver_scope: waiverScope }).strict().superRefine((value, context) => { + if (value.waiver_scope.operation !== "adjudication-failure") context.addIssue({ code: "custom", message: "waiver operation must match gate kind" }); + const available = new Set([...value.failed_rules, ...value.uncertain_rules].map(ruleKey)); + for (const item of value.eligible_waiver_rules) if (!available.has(ruleKey(item))) context.addIssue({ code: "custom", message: "eligible waiver rule must be failed or uncertain" }); + if (available.size === 0) context.addIssue({ code: "custom", message: "adjudication failure must identify a rule" }); + }), + "attempts-exhausted": z.object({ step: z.enum(PIPELINE_STEPS), attempts: safeInteger, maximum_attempts: safeInteger }).strict().refine((value) => value.attempts >= value.maximum_attempts, "attempts must be at least maximum_attempts"), + "constitution-edit": z.object({ pinned_constitution_digest: digest, current_constitution_digest: digest, changed_path_class: z.literal("task-branch-constitution") }).strict(), + "commit-authorization": z.object({ target_ref: boundedText, diff_digest: digest, current_artifact_digests: canonicalDigests.min(1), parent_document_digests: canonicalDigests.min(1) }).strict(), + "restore-collision": z.object({ path: taskPathClaimV1Schema, recorded_generation_digest: digest, current_generation_digest: digest, adoption_candidate: authorityLink.optional() }).strict(), + "migration-audit": z.object({ source_identity_digest: digest, destination_identity_digest: digest, import_digest: digest, code_baseline_digest: digest, policy_baseline_digest: digest }).strict(), +} as const; + +const decisions = { + "artifact-approval": decision(["approve", "revise", "reject"]), + "review-trigger": z.union([decision(["approve", "revise", "reject"]), z.object({ decision: z.literal("waiver-requested"), reason, rule, rationale: boundedText }).strict()]), + "material-drift": decision(["amend-upstream", "revise-current", "reject"]), + "adjudication-failure": z.union([z.object({ decision: z.literal("approve"), reason, resolutions: z.array(ruleResolution) }).strict(), decision(["revise", "reject"]), z.object({ decision: z.literal("waiver-requested"), reason, rule, rationale: boundedText }).strict()]), + "attempts-exhausted": decision(["retry-once", "revise", "abort"]), + "constitution-edit": decision(["revert-edit", "start-base-amendment", "abort"]), + "commit-authorization": decision(["authorize-commit", "revise", "abort"]), + "restore-collision": z.union([decision(["discard-and-restore", "abort"]), z.object({ decision: z.literal("adopt-as-new-generation"), reason, adoption_authority: authorityLink, rationale: boundedText }).strict()]), + "migration-audit": decision(["accept-import-audit", "revise", "abort"]), +} as const; + +const effects = Object.freeze({ + approve: "advance", revise: "retry", reject: "non-advancing", "waiver-requested": "redirect-waiver", "amend-upstream": "redirect-upstream", "revise-current": "retry", "retry-once": "retry", abort: "non-advancing", "revert-edit": "retry", "start-base-amendment": "redirect-upstream", "authorize-commit": "advance", "discard-and-restore": "advance", "adopt-as-new-generation": "advance", "accept-import-audit": "advance", +} as const satisfies Readonly["decision"], GateEffect>>); + +export const GATE_CONTRACTS = Object.freeze(Object.fromEntries(GATE_KINDS.map((kind) => [kind, Object.freeze({ context: contexts[kind], decision: decisions[kind] })]))) as Readonly<{ [K in GateKind]: { readonly context: (typeof contexts)[K]; readonly decision: (typeof decisions)[K] } }>; + +const connectedProvenance = z.object({ schema_version: z.literal("1"), actor_class: z.enum(["human", "archforge"]), assurance: z.literal("declared-local-trace"), channel: z.literal("connected-host"), decision_event_id: safeId, connection_id: safeId, request_id_digest: digest, recorded_at: z.string().datetime({ offset: false, local: false, precision: 3 }) }).strict(); +const localProvenance = z.object({ schema_version: z.literal("1"), actor_class: z.enum(["human", "archforge"]), assurance: z.literal("declared-local-trace"), channel: z.literal("archflow-local"), decision_event_id: safeId, helper_invocation_id: safeId, recorded_at: z.string().datetime({ offset: false, local: false, precision: 3 }) }).strict(); +export const humanDecisionProvenanceV1Schema = z.union([connectedProvenance, localProvenance]); +const envelopeBase = { schema_version: z.literal("1"), gate_id: safeId, task_id: safeId, phase_instance: z.string().refine((value) => { try { decodePhaseInstance(value); return true; } catch { return false; } }), subject_digest: digest, context_digest: digest, human_provenance: z.union([connectedProvenance, localProvenance]) } as const; + +export const gateContractV1Schema = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("artifact-approval"), context: contexts["artifact-approval"], payload: decisions["artifact-approval"] }).strict(), + z.object({ kind: z.literal("review-trigger"), context: contexts["review-trigger"], payload: decisions["review-trigger"] }).strict(), + z.object({ kind: z.literal("material-drift"), context: contexts["material-drift"], payload: decisions["material-drift"] }).strict(), + z.object({ kind: z.literal("adjudication-failure"), context: contexts["adjudication-failure"], payload: decisions["adjudication-failure"] }).strict(), + z.object({ kind: z.literal("attempts-exhausted"), context: contexts["attempts-exhausted"], payload: decisions["attempts-exhausted"] }).strict(), + z.object({ kind: z.literal("constitution-edit"), context: contexts["constitution-edit"], payload: decisions["constitution-edit"] }).strict(), + z.object({ kind: z.literal("commit-authorization"), context: contexts["commit-authorization"], payload: decisions["commit-authorization"] }).strict(), + z.object({ kind: z.literal("restore-collision"), context: contexts["restore-collision"], payload: decisions["restore-collision"] }).strict(), + z.object({ kind: z.literal("migration-audit"), context: contexts["migration-audit"], payload: decisions["migration-audit"] }).strict(), +]); + +export const gateDecisionEnvelopeV1Schema = z.discriminatedUnion("kind", [ + z.object({ ...envelopeBase, kind: z.literal("artifact-approval"), payload: decisions["artifact-approval"] }).strict(), + z.object({ ...envelopeBase, kind: z.literal("review-trigger"), payload: decisions["review-trigger"] }).strict(), + z.object({ ...envelopeBase, kind: z.literal("material-drift"), payload: decisions["material-drift"] }).strict(), + z.object({ ...envelopeBase, kind: z.literal("adjudication-failure"), payload: decisions["adjudication-failure"] }).strict(), + z.object({ ...envelopeBase, kind: z.literal("attempts-exhausted"), payload: decisions["attempts-exhausted"] }).strict(), + z.object({ ...envelopeBase, kind: z.literal("constitution-edit"), payload: decisions["constitution-edit"] }).strict(), + z.object({ ...envelopeBase, kind: z.literal("commit-authorization"), payload: decisions["commit-authorization"] }).strict(), + z.object({ ...envelopeBase, kind: z.literal("restore-collision"), payload: decisions["restore-collision"] }).strict(), + z.object({ ...envelopeBase, kind: z.literal("migration-audit"), payload: decisions["migration-audit"] }).strict(), +]); + +function ruleKey(value: RuleVersionRef): string { return `${value.rule_id}:${value.rule_version}`; } + +export function parseGateContext(kind: K, value: unknown): GateContext { + assertPlainJson(value, `${kind} gate context`); + return contexts[kind].parse(value) as GateContext; +} + +export function parseGateDecisionEnvelope(value: unknown): GateDecisionEnvelope { + assertPlainJson(value, "gate decision envelope"); + const parsed = gateDecisionEnvelopeV1Schema.parse(value) as GateDecisionEnvelope; + if (parsed.kind === "restore-collision" && parsed.payload.decision === "adopt-as-new-generation") return parsed; + return parsed; +} + +export function parseGateContract(value: unknown): Readonly<{ [K in GateKind]: { readonly kind: K; readonly context: GateContext; readonly payload: GateDecisionPayload } }[GateKind]> { + assertPlainJson(value, "gate contract"); + const parsed = gateContractV1Schema.parse(value) as Readonly<{ [K in GateKind]: { readonly kind: K; readonly context: GateContext; readonly payload: GateDecisionPayload } }[GateKind]>; + validateGateDecision(parsed.kind, parsed.context, parsed.payload); + return parsed; +} + +export function validateGateDecision(kind: K, context: GateContext, payload: GateDecisionPayload): GateDecisionPayload { + parseGateContext(kind, context); + assertPlainJson(payload, `${kind} gate decision`); + const parsed = decisions[kind].parse(payload) as GateDecisionPayload; + if (kind === "review-trigger" && parsed.decision === "waiver-requested") { + const eligible = (context as GateContext<"review-trigger">).eligible_waiver_rules; + if (!eligible.some((item) => ruleKey(item) === ruleKey(parsed.rule))) throw new TypeError("waiver-requested rule must be eligible"); + } + if (kind === "adjudication-failure") { + const adjudicationContext = context as GateContext<"adjudication-failure">; + const adjudicationPayload = parsed as GateDecisionPayload<"adjudication-failure">; + const eligible = new Set(adjudicationContext.eligible_waiver_rules.map(ruleKey)); + if (adjudicationPayload.decision === "waiver-requested" && !eligible.has(ruleKey(adjudicationPayload.rule))) throw new TypeError("waiver-requested rule must be eligible"); + if (adjudicationPayload.decision === "approve") { + const required = new Set([...adjudicationContext.failed_rules, ...adjudicationContext.uncertain_rules].map(ruleKey).filter((key) => !eligible.has(key))); + const actual = adjudicationPayload.resolutions.map((item) => ruleKey(item.rule)); + if (!sortedUnique(adjudicationPayload.resolutions, (a, b) => compareRules(a.rule, b.rule)) || actual.length !== required.size || actual.some((key) => !required.has(key))) throw new TypeError("resolutions must be a sorted exact set of non-waived failed and uncertain rules"); + } + } + if (kind === "restore-collision" && parsed.decision === "adopt-as-new-generation") { + const candidate = (context as GateContext<"restore-collision">).adoption_candidate; + const adoptionPayload = parsed as Extract, { decision: "adopt-as-new-generation" }>; + if (candidate === undefined || JSON.stringify(candidate) !== JSON.stringify(adoptionPayload.adoption_authority)) throw new TypeError("restore adoption authority must exactly match the context candidate"); + } + return parsed; +} + +export function gateDecisionEffect(payload: GateDecisionPayload): GateEffect { return effects[payload.decision]; } diff --git a/src/contracts/index.ts b/src/contracts/index.ts index fdd218a9..9829990f 100644 --- a/src/contracts/index.ts +++ b/src/contracts/index.ts @@ -8,3 +8,50 @@ export type { IterationPolicy } from "./vocabulary.js"; export * from "./config.js"; export * from "./rubric.js"; export * from "./constitution.js"; +export * from "./evidence.js"; +export * from "./path-claims.js"; +export * from "./tool-names.js"; +export * from "./review.js"; +export * from "./adjudication.js"; +export * from "./trust.js"; +export * from "./triage.js"; +export * from "./supplemental.js"; +export * from "./renderers.js"; +export type { RuleVersionRef } from "./gates.js"; +export * from "./gates.js"; +export * from "./errors.js"; +export { + TOOL_DEFINITIONS, + bindParsedToolCallRequest, + correlateProjectResult, + parseToolCall, + validateProjectResultStructure, +} from "./mcp-tools.js"; +export type { + AdjudicateInput, + AdjudicateSuccess, + CommonToolInput, + CounterReviewInput, + CounterReviewSuccess, + GateInput, + GateSuccess, + ParsedToolCall, + ParsedToolInput, + ResultExpectation, + ResultExpectationDataByTool, + ResultIdentityPayload, + RequestIdentifiedToolCall, + StateInput, + StateSuccess, + StructurallyValidProjectResult, + ToolContract, + ToolContractMap, + ToolDefinition, + ToolInput, + ToolSuccess, + WaiverDecisionBinding, + WaiverInput, + WaiverSuccess, +} from "./mcp-tools.js"; +export type { ConnectionContext, InvocationContext } from "./contexts.js"; +export { createInvocationContext } from "./contexts.js"; diff --git a/src/contracts/internal/test-capabilities.ts b/src/contracts/internal/test-capabilities.ts new file mode 100644 index 00000000..a40aa4d9 --- /dev/null +++ b/src/contracts/internal/test-capabilities.ts @@ -0,0 +1,44 @@ +import type { Assurance, AuthorityLink, AuthorityLinkData, CurrentReviewSetAuthority, EvidenceKind, ObservationBindingByKind, ObservationCapability, RequiredReviewSlots, VerifiedReferencedEvidence } from "../trust.js"; +import { + currentReviewSetAuthorityBrand, + registerAuthorityLink, + registerCurrentReviewSetAuthority, + registerObservationCapability, + registerVerifiedEvidence, +} from "./trust-brands.js"; +import type { ReferencedEvidence } from "../evidence.js"; +import { createInternalResultExpectation, type ResultExpectation, type ResultIdentityPayload } from "../mcp-tools.js"; +import type { ToolName } from "../tool-names.js"; + +export function createTestObservationCapability(binding: ObservationBindingByKind[K]): ObservationCapability { + const copiedBinding = deepFreeze(structuredClone(binding)); + const capability = Object.freeze({ kind: copiedBinding.kind }) as ObservationCapability; + registerObservationCapability(capability, copiedBinding); + return capability; +} +export function createTestAuthorityLink(data: AuthorityLinkData): AuthorityLink { + const link = deepFreeze(structuredClone(data)) as AuthorityLink; + registerAuthorityLink(link, { kind: data.evidence_kind, assurance: data.assurance }); + return link; +} +export function createTestVerifiedReferencedEvidence(kind: K, value: ReferencedEvidence["evidence"]>): VerifiedReferencedEvidence { + const verified = deepFreeze(structuredClone(value)) as VerifiedReferencedEvidence; + registerVerifiedEvidence(verified, { kind, assurance: value.evidence.assurance }); + return verified; +} +export function createTestCurrentReviewSetAuthority(value: Omit & { readonly slots: RequiredReviewSlots }): CurrentReviewSetAuthority { + const authority = deepFreeze(structuredClone(value)) as CurrentReviewSetAuthority; + registerCurrentReviewSetAuthority(authority); + return authority; +} +export function createTestResultExpectation(value: ResultIdentityPayload): ResultExpectation { + return createInternalResultExpectation(value); +} + +function deepFreeze(value: T): T { + if (value !== null && typeof value === "object") { + for (const nested of Object.values(value)) deepFreeze(nested); + Object.freeze(value); + } + return value; +} diff --git a/src/contracts/internal/trust-brands.ts b/src/contracts/internal/trust-brands.ts new file mode 100644 index 00000000..7f8eb88f --- /dev/null +++ b/src/contracts/internal/trust-brands.ts @@ -0,0 +1,67 @@ +import type { + Assurance, + EvidenceKind, + ObservationBindingByKind, +} from "../trust.js"; + +export const observationCapabilityBrand: unique symbol = Symbol("ObservationCapability"); +export const authorityLinkBrand: unique symbol = Symbol("AuthorityLink"); +export const verifiedReferencedEvidenceBrand: unique symbol = Symbol("VerifiedReferencedEvidence"); +export const currentReviewSetAuthorityBrand: unique symbol = Symbol("CurrentReviewSetAuthority"); +export const qualifiedEvidenceBrand: unique symbol = Symbol("QualifiedEvidence"); +export const currentReviewSetBrand: unique symbol = Symbol("CurrentReviewSet"); +export const validatedTriageBrand: unique symbol = Symbol("ValidatedTriage"); + +type TrustIdentity = Readonly<{ kind: EvidenceKind; assurance: Assurance }>; + +const observationCapabilities = new WeakMap(); +const authorityLinks = new WeakMap(); +const verifiedEvidence = new WeakMap(); +const currentReviewAuthorities = new WeakSet(); +const qualifiedEvidence = new WeakMap(); +const currentReviewSets = new WeakSet(); +const validatedTriages = new WeakSet(); + +export function registerObservationCapability(value: object, binding: ObservationBindingByKind[K]): void { + observationCapabilities.set(value, binding); +} + +export function observationCapabilityBinding(value: object, kind: K): ObservationBindingByKind[K] | undefined { + const binding = observationCapabilities.get(value); + return binding?.kind === kind ? binding as ObservationBindingByKind[K] : undefined; +} + +export function registerAuthorityLink(value: object, identity: TrustIdentity): void { + authorityLinks.set(value, Object.freeze({ ...identity })); +} + +export function authenticAuthorityLink(value: object, identity: TrustIdentity): boolean { + const actual = authorityLinks.get(value); + return actual?.kind === identity.kind && actual.assurance === identity.assurance; +} + +export function registerVerifiedEvidence(value: object, identity: TrustIdentity): void { + verifiedEvidence.set(value, Object.freeze({ ...identity })); +} + +export function authenticVerifiedEvidence(value: object, identity: TrustIdentity): boolean { + const actual = verifiedEvidence.get(value); + return actual?.kind === identity.kind && actual.assurance === identity.assurance; +} + +export function registerCurrentReviewSetAuthority(value: object): void { currentReviewAuthorities.add(value); } +export function authenticCurrentReviewSetAuthority(value: object): boolean { return currentReviewAuthorities.has(value); } + +export function registerQualifiedEvidence(value: object, identity: TrustIdentity): void { + qualifiedEvidence.set(value, Object.freeze({ ...identity })); +} + +export function authenticQualifiedEvidence(value: object, kind: EvidenceKind, assurance?: Assurance): boolean { + const actual = qualifiedEvidence.get(value); + return actual?.kind === kind && (assurance === undefined || actual.assurance === assurance); +} + +export function registerCurrentReviewSet(value: object): void { currentReviewSets.add(value); } +export function authenticCurrentReviewSet(value: object): boolean { return currentReviewSets.has(value); } +export function registerValidatedTriage(value: object): void { validatedTriages.add(value); } +export function authenticValidatedTriage(value: object): boolean { return validatedTriages.has(value); } diff --git a/src/contracts/mcp-tools.ts b/src/contracts/mcp-tools.ts new file mode 100644 index 00000000..316ad286 --- /dev/null +++ b/src/contracts/mcp-tools.ts @@ -0,0 +1,94 @@ +import { isDeepStrictEqual } from "node:util"; +import { z } from "zod"; +import { CONSTITUTION_RESULTS, DRIFT_RESULTS, type ConstitutionResult, type DriftResult } from "./adjudication.js"; +import { parseProjectError, type ProjectResult } from "./errors.js"; +import type { Sha256Digest } from "./evidence.js"; +import { GATE_KINDS, humanDecisionProvenanceV1Schema, parseGateContext, parseGateDecisionEnvelope, type GateContext, type GateDecisionEnvelope, type GateKind, type HumanDecisionProvenance, type RuleVersionRef, type WaiverOriginRef, type WaiverScope } from "./gates.js"; +import { assertPlainJson } from "./plain-json.js"; +import { decodePhaseInstance, type PhaseInstanceId } from "./phase-instance.js"; +import { taskPathClaimV1Schema, type TaskPathClaim } from "./path-claims.js"; +import { rubricV1Schema, type RubricV1 } from "./rubric.js"; +import type { GateSupersessionRef } from "./supplemental.js"; +import { TOOL_NAMES, type ToolName } from "./tool-names.js"; +import { parseCurrentEvidenceSetRef, type CurrentEvidenceSetRef } from "./trust.js"; + +const parsedToolInputBrand: unique symbol = Symbol("ParsedToolInput"); +const structuralResultBrand: unique symbol = Symbol("StructurallyValidProjectResult"); +export const resultExpectationBrand: unique symbol = Symbol("ResultExpectation"); +const parsedCalls = new WeakSet(); +const structuralResults = new WeakSet(); +const resultExpectations = new WeakSet(); +const requestDigests = new WeakMap(); +const digest = z.string().regex(/^[0-9a-f]{64}$/u) as unknown as z.ZodType; +const safeId = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); +const text = z.string().min(1).max(4096).regex(/\S/u); +const safeInteger = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +const phase = z.string().refine((v) => { try { decodePhaseInstance(v); return true; } catch { return false; } }) as unknown as z.ZodType; +const rule = z.object({ rule_id: safeId, rule_version: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) }).strict(); +const scope = z.object({ operation: z.enum(["review-trigger", "adjudication-failure"]), boundary: z.enum(["subject", "phase", "task"]) }).strict(); +const provenance = humanDecisionProvenanceV1Schema as z.ZodType; +const common = { schema_version: z.literal("1"), task_id: safeId, intent_id: safeId, expected_revision: safeInteger, input_fingerprint: digest } as const; + +export interface CommonToolInput { readonly schema_version: "1"; readonly task_id: string; readonly intent_id: string; readonly expected_revision: number; readonly input_fingerprint: Sha256Digest } +export interface StateInput extends CommonToolInput { readonly phase_instance: PhaseInstanceId; readonly step: "produce" | "self_review" | "counter_review" | "triage" | "adjudicate"; readonly status: "running" | "succeeded" | "failed" } +export interface StateSuccess { readonly path: TaskPathClaim; readonly revision: number; readonly status: StateInput["status"] } +export interface CounterReviewInput extends CommonToolInput { readonly artifact_path: TaskPathClaim; readonly rubric: RubricV1 } +export interface CounterReviewSuccess { readonly path: TaskPathClaim; readonly verdict: "pass" | "advisory" | "fail"; readonly blocking_count: number; readonly revision: number } +export interface AdjudicateInput extends CommonToolInput { readonly artifact_path: TaskPathClaim; readonly upstream_paths: readonly TaskPathClaim[] } +export interface AdjudicateSuccess { readonly path: TaskPathClaim; readonly constitution: ConstitutionResult; readonly drift: DriftResult; readonly triggers: readonly RuleVersionRef[]; readonly revision: number } +export type GateInput = { readonly [K in GateKind]: CommonToolInput & { readonly phase_instance: PhaseInstanceId; readonly summary: string; readonly subject_digest: Sha256Digest; readonly current_evidence: CurrentEvidenceSetRef; readonly supersedes?: GateSupersessionRef; readonly kind: K; readonly context: GateContext } }[GateKind]; +export type GateSuccess = { readonly [K in GateKind]: { readonly kind: K; readonly decision: GateDecisionEnvelope; readonly notes: string; readonly revision: number } }[GateKind]; +export interface WaiverInput extends CommonToolInput { readonly origin: WaiverOriginRef; readonly rationale: string } +export interface WaiverDecisionBinding { readonly origin_gate_id: string; readonly waiver_gate_id: string; readonly task_id: string; readonly rule_id: string; readonly rule_version: number; readonly subject_digest: Sha256Digest; readonly current_evidence_set_digest: Sha256Digest; readonly scope: WaiverScope; readonly human_provenance: HumanDecisionProvenance } +export type WaiverSuccess = (WaiverDecisionBinding & { readonly granted: true; readonly expires: "task-complete"; readonly notes: string; readonly revision: number }) | (WaiverDecisionBinding & { readonly granted: false; readonly notes: string; readonly revision: number }); +export interface ToolContract { readonly input: Input; readonly success: Success } +export interface ToolContractMap { readonly archflow_state: ToolContract; readonly archflow_counter_review: ToolContract; readonly archflow_adjudicate: ToolContract; readonly archflow_gate: ToolContract; readonly archflow_waiver: ToolContract } +type Exact = ToolContractMap extends Record> ? Exclude extends never ? true : never : never; +const exact: Exact = true; void exact; +export type ToolInput = ToolContractMap[K]["input"]; +export type ToolSuccess = ToolContractMap[K]["success"]; +export type ResultIdentityPayload = { readonly [P in K]: Readonly<{ schema_version: "1"; tool: P; task_id: string; intent_id: string; input_fingerprint: Sha256Digest; request_digest: Sha256Digest; result_id: string; resulting_revision: number; success: ToolSuccess

}> }[K]; +export interface ToolDefinition { readonly name: K; readonly input_schema_id: `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${K}/input`; readonly result_schema_id: `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${K}/result` } +const def = (name: K): ToolDefinition => Object.freeze({ name, input_schema_id: `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${name}/input`, result_schema_id: `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${name}/result` }); +export const TOOL_DEFINITIONS = Object.freeze({ archflow_state: def("archflow_state"), archflow_counter_review: def("archflow_counter_review"), archflow_adjudicate: def("archflow_adjudicate"), archflow_gate: def("archflow_gate"), archflow_waiver: def("archflow_waiver") }) satisfies { readonly [K in keyof ToolContractMap]: ToolDefinition }; + +const stateInput = z.object({ ...common, phase_instance: phase, step: z.enum(["produce", "self_review", "counter_review", "triage", "adjudicate"]), status: z.enum(["running", "succeeded", "failed"]) }).strict(); +const counterInput = z.object({ ...common, artifact_path: taskPathClaimV1Schema, rubric: rubricV1Schema }).strict(); +const adjudicateInput = z.object({ ...common, artifact_path: taskPathClaimV1Schema, upstream_paths: z.array(taskPathClaimV1Schema) }).strict(); +const supersedes = z.object({ superseded_gate_id: safeId, accepted_triage_digest: digest, old_subject_digest: digest }).strict(); +const gateInput = z.object({ ...common, phase_instance: phase, summary: text, subject_digest: digest, current_evidence: z.unknown(), supersedes: supersedes.optional(), kind: z.enum(GATE_KINDS), context: z.unknown() }).strict(); +const waiverOrigin = z.object({ origin_gate_id: safeId, origin_decision_digest: digest, origin_context_digest: digest, task_id: safeId, phase_instance: phase, subject_digest: digest, current_evidence_set_digest: digest, rule, scope }).strict(); +const waiverInput = z.object({ ...common, origin: waiverOrigin, rationale: text }).strict(); + +function inputFor(name: K, value: unknown): ToolInput { + const parsed = name === "archflow_state" ? stateInput.parse(value) : name === "archflow_counter_review" ? counterInput.parse(value) : name === "archflow_adjudicate" ? adjudicateInput.parse(value) : name === "archflow_waiver" ? waiverInput.parse(value) : gateInput.parse(value); + if (name === "archflow_gate") { const v = parsed as z.infer; parseGateContext(v.kind, v.context); return { ...v, current_evidence: parseCurrentEvidenceSetRef(v.current_evidence) } as ToolInput; } + if (name === "archflow_waiver") { const v = parsed as z.infer; if (v.task_id !== v.origin.task_id) throw new TypeError("waiver task_id must match origin task_id"); } + return parsed as ToolInput; +} +export type ParsedToolInput = ToolInput & { readonly [parsedToolInputBrand]: K }; +export type ParsedToolCall = { readonly [P in K]: Readonly<{ name: P; input: ParsedToolInput

}> }[K]; +export function parseToolCall(name: K, value: unknown): Extract { if (!(TOOL_NAMES as readonly string[]).includes(name)) throw new TypeError("unknown tool"); assertPlainJson(value, `${name} input`); const call = Object.freeze({ name, input: Object.freeze({ ...inputFor(name, value), [parsedToolInputBrand]: name }) }) as unknown as Extract; parsedCalls.add(call); return call; } +export type RequestIdentifiedToolCall = ParsedToolCall & { readonly request_digest: Sha256Digest }; +export function bindParsedToolCallRequest(call: Extract, requestDigest: Sha256Digest): Extract { if (!parsedCalls.has(call)) throw new TypeError("an authentic parsed tool call is required"); digest.parse(requestDigest); requestDigests.set(call, requestDigest); return call as Extract; } + +const successSchemas = { + archflow_state: z.object({ path: taskPathClaimV1Schema, revision: safeInteger, status: z.enum(["running", "succeeded", "failed"]) }).strict(), + archflow_counter_review: z.object({ path: taskPathClaimV1Schema, verdict: z.enum(["pass", "advisory", "fail"]), blocking_count: safeInteger, revision: safeInteger }).strict(), + archflow_adjudicate: z.object({ path: taskPathClaimV1Schema, constitution: z.enum(CONSTITUTION_RESULTS), drift: z.enum(DRIFT_RESULTS), triggers: z.array(rule), revision: safeInteger }).strict(), + archflow_gate: z.object({ kind: z.enum(GATE_KINDS), decision: z.unknown(), notes: text, revision: safeInteger }).strict(), + archflow_waiver: z.union([z.object({ origin_gate_id: safeId, waiver_gate_id: safeId, task_id: safeId, rule_id: safeId, rule_version: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), subject_digest: digest, current_evidence_set_digest: digest, scope, human_provenance: provenance, granted: z.literal(true), expires: z.literal("task-complete"), notes: text, revision: safeInteger }).strict(), z.object({ origin_gate_id: safeId, waiver_gate_id: safeId, task_id: safeId, rule_id: safeId, rule_version: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), subject_digest: digest, current_evidence_set_digest: digest, scope, human_provenance: provenance, granted: z.literal(false), notes: text, revision: safeInteger }).strict()]) +} as const; +function successFor(call: Extract, value: unknown): ToolSuccess { + const parsed = successSchemas[call.name].parse(value) as ToolSuccess; + if (call.name === "archflow_state" && (parsed as StateSuccess).status !== (call.input as ParsedToolInput<"archflow_state">).status) throw new TypeError("state status mismatch"); + if (call.name === "archflow_gate") { const input = call.input as ParsedToolInput<"archflow_gate">; const result = parsed as GateSuccess; const decision = parseGateDecisionEnvelope(result.decision); if (result.kind !== input.kind || decision.kind !== input.kind || decision.task_id !== input.task_id || decision.phase_instance !== input.phase_instance || decision.subject_digest !== input.subject_digest || result.notes !== decision.payload.reason) throw new TypeError("gate result mismatch"); } + if (call.name === "archflow_waiver") { const input = call.input as ParsedToolInput<"archflow_waiver">; const result = parsed as WaiverSuccess; if (result.origin_gate_id !== input.origin.origin_gate_id || result.task_id !== input.task_id || result.rule_id !== input.origin.rule.rule_id || result.rule_version !== input.origin.rule.rule_version || result.subject_digest !== input.origin.subject_digest || result.current_evidence_set_digest !== input.origin.current_evidence_set_digest || !isDeepStrictEqual(result.scope, input.origin.scope)) throw new TypeError("waiver result mismatch"); } + return parsed; +} +export type StructurallyValidProjectResult = ProjectResult> & { readonly [structuralResultBrand]: K }; +export function validateProjectResultStructure(call: Extract, value: unknown): StructurallyValidProjectResult { if (!parsedCalls.has(call)) throw new TypeError("an authentic parsed tool call is required"); assertPlainJson(value, `${call.name} result`); const base = z.object({ schema_version: z.literal("1"), ok: z.boolean() }).passthrough().parse(value); const result: ProjectResult> = base.ok ? (() => { const e = z.object({ schema_version: z.literal("1"), ok: z.literal(true), value: z.unknown() }).strict().parse(value); return { ...e, value: successFor(call, e.value) }; })() : (() => { const e = z.object({ schema_version: z.literal("1"), ok: z.literal(false), error: z.unknown() }).strict().parse(value); return { ...e, error: parseProjectError(e.error) }; })(); const branded = Object.freeze({ ...result, [structuralResultBrand]: call.name }) as StructurallyValidProjectResult; structuralResults.add(branded); return branded; } +export type ResultExpectationDataByTool = { readonly [P in ToolName]: ResultIdentityPayload

}; +export type ResultExpectation = ResultExpectationDataByTool[K] & { readonly [resultExpectationBrand]: K }; +export function createInternalResultExpectation(value: ResultIdentityPayload): ResultExpectation { assertPlainJson(value, "result expectation"); const base = z.object({ schema_version: z.literal("1"), tool: z.enum(TOOL_NAMES), task_id: safeId, intent_id: safeId, input_fingerprint: digest, request_digest: digest, result_id: safeId, resulting_revision: safeInteger, success: z.unknown() }).strict().parse(value); const success = successSchemas[base.tool].parse(base.success) as ToolSuccess; if (base.resulting_revision !== success.revision) throw new TypeError("expectation resulting revision must equal success revision"); const expectation = Object.assign({}, base, { success }) as unknown as ResultExpectation; Object.defineProperty(expectation, resultExpectationBrand, { value: value.tool, enumerable: false, writable: false, configurable: false }); Object.freeze(expectation); resultExpectations.add(expectation); return expectation; } +export function correlateProjectResult(call: Extract, expectation: NoInfer>, result: NoInfer>): ProjectResult> { const requestDigest = requestDigests.get(call); if (requestDigest === undefined || !parsedCalls.has(call) || !resultExpectations.has(expectation) || !structuralResults.has(result)) throw new TypeError("authentic request/result identities are required"); if (expectation[resultExpectationBrand] !== call.name || result[structuralResultBrand] !== call.name || expectation.tool !== call.name) throw new TypeError("result correlation tool mismatch"); if (expectation.request_digest !== requestDigest || expectation.task_id !== call.input.task_id || expectation.intent_id !== call.input.intent_id || expectation.input_fingerprint !== call.input.input_fingerprint) throw new TypeError("expectation invocation mismatch"); if (result.ok && (expectation.resulting_revision !== result.value.revision || !isDeepStrictEqual(expectation.success, result.value))) throw new TypeError("result expectation mismatch"); return result; } diff --git a/src/contracts/path-claims.ts b/src/contracts/path-claims.ts new file mode 100644 index 00000000..d3389571 --- /dev/null +++ b/src/contracts/path-claims.ts @@ -0,0 +1,30 @@ +import { z } from "zod"; + +import { assertPlainJson } from "./plain-json.js"; + +declare const taskPathClaimBrand: unique symbol; + +export type TaskPathClaim = string & { readonly [taskPathClaimBrand]: true }; + +const utf8Length = (value: string): number => Buffer.byteLength(value, "utf8"); +const containsControl = (value: string): boolean => /[\u0000-\u001f\u007f-\u009f]/u.test(value); +const hasDriveOrUncPrefix = (value: string): boolean => /^[A-Za-z]:/u.test(value) || value.startsWith("//"); +const hasInvalidComponent = (value: string): boolean => value.split("/").some((component) => component === "" || component === "." || component === ".."); + +export const taskPathClaimV1Schema = z.string() + .min(1) + .refine((value) => utf8Length(value) <= 1024, "path claim must be at most 1024 UTF-8 bytes") + .refine((value) => !value.startsWith("/"), "path claim must be relative") + .refine((value) => !hasDriveOrUncPrefix(value), "path claim must not use a drive or UNC prefix") + .refine((value) => !value.includes("\\"), "path claim must use forward slashes") + .refine((value) => !containsControl(value), "path claim must not contain control characters") + .refine((value) => !hasInvalidComponent(value), "path claim components must be non-empty and may not be . or .."); + +/** + * Parses a bounded task-relative lexical claim. This does not inspect a file + * system or grant repository/task containment authority. + */ +export function parseTaskPathClaim(value: unknown): TaskPathClaim { + assertPlainJson(value, "task path claim"); + return taskPathClaimV1Schema.parse(value) as TaskPathClaim; +} diff --git a/src/contracts/renderers.ts b/src/contracts/renderers.ts new file mode 100644 index 00000000..33d204b1 --- /dev/null +++ b/src/contracts/renderers.ts @@ -0,0 +1,79 @@ +import type { AdjudicationEvidence, MechanicalEvidence } from "./adjudication.js"; +import type { ReviewEvidence, ReviewFinding, RuleVersionRef } from "./review.js"; +import type { QualifiedAdjudicationEvidence, QualifiedReviewEvidence } from "./trust.js"; +import type { TriageDisposition, ValidatedTriage } from "./triage.js"; +import { authenticQualifiedEvidence, authenticValidatedTriage } from "./internal/trust-brands.js"; + +const encoder = new TextEncoder(); +const ESCAPE = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069`<>&]/gu; +const visibleJsonString = (value: string): string => JSON.stringify(value) + .replace(/\\n/gu, "\\u000a").replace(/\\r/gu, "\\u000d").replace(/\\t/gu, "\\u0009") + .replace(/\\b/gu, "\\u0008").replace(/\\f/gu, "\\u000c") + .replace(ESCAPE, (character) => `\\u${character.codePointAt(0)!.toString(16).padStart(4, "0")}`); +const canonical = (value: unknown): string => typeof value === "string" ? visibleJsonString(value) : JSON.stringify(value); +const optional = (value: unknown): string => value === undefined ? "none" : canonical(value); +const ruleVersions = (values: readonly RuleVersionRef[]): string => canonical(values.map((value) => `${value.rule_id}@${value.rule_version}`)); +const linesToBytes = (lines: readonly string[]): Uint8Array => encoder.encode(`${lines.join("\n")}\n`); +const metadata = (entries: readonly (readonly [string, unknown])[]): string[] => entries.map(([key, value]) => `${key}: ${optional(value)}`); +const prose = (label: string, value: string, indent = " "): string => `${indent}${label}: ${visibleJsonString(value)}`; + +function provenanceMetadata(evidence: ReviewEvidence | AdjudicationEvidence): readonly (readonly [string, unknown])[] { + return [ + ["assurance", evidence.assurance], + ["adapter", evidence.assurance === "server-attested" ? evidence.adapter : undefined], + ["cli_version", evidence.assurance === "server-attested" ? evidence.cli_version : undefined], + ["model_family", evidence.model_family], ["model", evidence.model], ["effort", evidence.effort], + ["invocation_id", evidence.assurance === "server-attested" ? evidence.invocation_id : undefined], + ["result_id", evidence.assurance === "server-attested" ? evidence.result_id : undefined], + ]; +} +function renderReviewFinding(finding: ReviewFinding): string[] { + return [`### Finding ${visibleJsonString(finding.finding_id)}`, `severity: ${canonical(finding.severity)}`, `blocking: ${canonical(finding.blocking)}`, prose("summary", finding.summary), prose("evidence", finding.evidence), prose("suggested_resolution", finding.suggested_resolution)]; +} + +export function renderReviewEvidence(value: QualifiedReviewEvidence): Uint8Array { + if (!authenticQualifiedEvidence(value, "review")) throw new TypeError("qualified review evidence is required"); + const evidence = value.evidence; + if (!authenticQualifiedEvidence(value, "review", evidence.assurance)) throw new TypeError("qualified review evidence assurance is invalid"); + const lines = ["# ArchFlow Review Evidence", ...metadata([ + ["schema_version", evidence.schema_version], ["task_id", evidence.task_id], ["phase_instance", evidence.phase_instance], ["step", evidence.step], ["role", evidence.role], ["subject_digest", evidence.subject_digest], ["input_fingerprint", evidence.input_fingerprint], ["evidence_digest", value.evidence_digest], ["verdict", evidence.verdict], ["blocking_count", evidence.blocking_count], ["matched_rule_versions", evidence.matched_rule_versions.map((rule) => `${rule.rule_id}@${rule.rule_version}`)], ...provenanceMetadata(evidence), + ]), "", "## Findings"]; + for (const finding of evidence.findings) lines.push("", ...renderReviewFinding(finding)); + if (evidence.assurance === "degraded") lines.push("", "## Degraded Assurance", prose("reason", evidence.reason)); + return linesToBytes(lines); +} + +function renderDisposition(disposition: TriageDisposition): string[] { + const lines = [`### ${canonical(disposition.disposition)} ${visibleJsonString(disposition.review_evidence_digest)} ${visibleJsonString(disposition.finding_id)}`, prose("rationale", disposition.rationale)]; + if (disposition.disposition === "accepted") lines.push(prose("revision_intent", disposition.revision_intent)); + else lines.push(prose("evidence", disposition.evidence)); + return lines; +} +export function renderTriage(value: ValidatedTriage): Uint8Array { + if (!authenticValidatedTriage(value)) throw new TypeError("validated triage is required"); + const lines = ["# ArchFlow Review Triage", ...metadata([ + ["schema_version", value.schema_version], ["task_id", value.task_id], ["phase_instance", value.phase_instance], ["step", value.step], ["subject_digest", value.subject_digest], ["input_fingerprint", value.input_fingerprint], ["current_evidence_set_digest", value.current_evidence_set_digest], ["source_evidence_digests", value.source_evidence_digests], ["accepted_count", value.accepted_count], ["rejected_count", value.rejected_count], + ]), "", "## Dispositions"]; + for (const disposition of value.dispositions) lines.push("", ...renderDisposition(disposition)); + return linesToBytes(lines); +} + +function renderMechanicalEvidence(value: MechanicalEvidence): string[] { + return [` mechanism: ${visibleJsonString(value.mechanism)}`, ` state: ${canonical(value.state)}`, ` subject_digest: ${optional(value.subject_digest)}`, ` evidence_digest: ${optional(value.evidence_digest)}`, prose("details", value.details, " ")]; +} +export function renderAdjudicationEvidence(value: QualifiedAdjudicationEvidence): Uint8Array { + if (!authenticQualifiedEvidence(value, "adjudication")) throw new TypeError("qualified adjudication evidence is required"); + const evidence = value.evidence; + if (!authenticQualifiedEvidence(value, "adjudication", evidence.assurance)) throw new TypeError("qualified adjudication evidence assurance is invalid"); + const lines = ["# ArchFlow Adjudication Evidence", ...metadata([ + ["schema_version", evidence.schema_version], ["task_id", evidence.task_id], ["phase_instance", evidence.phase_instance], ["step", evidence.step], ["subject_digest", evidence.subject_digest], ["input_fingerprint", evidence.input_fingerprint], ["evidence_digest", value.evidence_digest], ["pinned_constitution_digest", evidence.pinned_constitution_digest], ["approved_upstream_digests", evidence.approved_upstream_digests], ["source_evidence_set_digest", evidence.source_evidence_set_digest], ["constitution", evidence.constitution], ["drift", evidence.drift], ["matched_rule_versions", evidence.matched_rule_versions.map((rule) => `${rule.rule_id}@${rule.rule_version}`)], ["uncertain_rule_versions", evidence.uncertain_rule_versions.map((rule) => `${rule.rule_id}@${rule.rule_version}`)], ...provenanceMetadata(evidence), + ]), "", "## Constitution Findings"]; + for (const finding of evidence.rule_findings) { + lines.push("", `### Rule ${visibleJsonString(`${finding.rule_id}@${finding.rule_version}`)}`, `compliance: ${canonical(finding.compliance)}`, `trigger: ${canonical(finding.trigger)}`, prose("rationale", finding.rationale), prose("trigger_evidence", finding.trigger_evidence), " enforced_by:"); + for (const mechanism of finding.enforced_by) lines.push(...renderMechanicalEvidence(mechanism)); + } + lines.push("", "## Drift Findings"); + for (const finding of evidence.drift_findings) lines.push("", `### Upstream ${visibleJsonString(finding.upstream_digest)}`, `drift: ${canonical(finding.drift)}`, `affected_claim_ids: ${canonical(finding.affected_claim_ids)}`, prose("rationale", finding.rationale)); + if (evidence.assurance === "degraded") lines.push("", "## Degraded Assurance", prose("reason", evidence.reason)); + return linesToBytes(lines); +} diff --git a/src/contracts/review.ts b/src/contracts/review.ts new file mode 100644 index 00000000..c7781625 --- /dev/null +++ b/src/contracts/review.ts @@ -0,0 +1,184 @@ +import { z } from "zod"; + +import type { ReferencedEvidence, Sha256Digest } from "./evidence.js"; +import { assertPlainJson } from "./plain-json.js"; + +export const REVIEW_VERDICTS = ["pass", "advisory", "fail"] as const; +export const REVIEW_ROLES = ["self-review", "counter-review", "gate-counter-review"] as const; +export const REVIEW_FINDING_SEVERITIES = ["blocker", "major", "minor"] as const; +export const MODEL_FAMILIES = ["claude", "codex"] as const; +export const ADAPTER_IDS = ["claude-cli", "codex-cli"] as const; +export const EFFORT_VALUES = ["low", "medium", "high", "xhigh", "max", "ultra"] as const; + +export type ReviewVerdict = (typeof REVIEW_VERDICTS)[number]; +export type ReviewRole = (typeof REVIEW_ROLES)[number]; +export type ReviewFindingSeverity = (typeof REVIEW_FINDING_SEVERITIES)[number]; +export type ModelFamily = (typeof MODEL_FAMILIES)[number]; +export type AdapterId = (typeof ADAPTER_IDS)[number]; +export type DeclaredEffort = (typeof EFFORT_VALUES)[number] | "unknown"; + +export interface RuleVersionRef { + readonly rule_id: string; + readonly rule_version: number; +} + +export interface ReviewFinding { + readonly finding_id: string; + readonly severity: ReviewFindingSeverity; + readonly blocking: boolean; + readonly summary: string; + readonly evidence: string; + readonly suggested_resolution: string; +} + +export interface RawReview { + readonly schema_version: "1"; + readonly task_id: string; + readonly phase_instance: string; + readonly step: "self_review" | "counter_review"; + readonly role: ReviewRole; + readonly subject_digest: Sha256Digest; + readonly input_fingerprint: Sha256Digest; + readonly rubric_digest: Sha256Digest; + readonly producer_family: ModelFamily; + readonly findings: readonly ReviewFinding[]; + readonly matched_rule_versions: readonly RuleVersionRef[]; + readonly verdict: ReviewVerdict; + readonly blocking_count: number; +} + +/** Semantically checked review data. This type intentionally carries no authority brand. */ +export interface DerivedReview extends RawReview {} + +const nonBlank = z.string().min(1).refine((value) => value.trim().length > 0, "must contain a non-whitespace character"); +const id = z.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u); +const digest = z.string().regex(/^[0-9a-f]{64}$/u) as unknown as z.ZodType; +const safePositive = z.number().int().positive().safe(); + +export const ruleVersionRefSchema = z.object({ rule_id: id, rule_version: safePositive }).strict(); +export const reviewFindingSchema = z.object({ + finding_id: id, + severity: z.enum(REVIEW_FINDING_SEVERITIES), + blocking: z.boolean(), + summary: nonBlank, + evidence: nonBlank, + suggested_resolution: nonBlank, +}).strict().superRefine((finding, context) => { + if (finding.blocking !== (finding.severity === "blocker")) { + context.addIssue({ code: "custom", path: ["blocking"], message: "only blocker findings are blocking" }); + } +}); + +export const rawReviewSchema = z.object({ + schema_version: z.literal("1"), + task_id: id, + phase_instance: z.string().regex(/^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$/u), + step: z.enum(["self_review", "counter_review"]), + role: z.enum(REVIEW_ROLES), + subject_digest: digest, + input_fingerprint: digest, + rubric_digest: digest, + producer_family: z.enum(MODEL_FAMILIES), + findings: z.array(reviewFindingSchema), + matched_rule_versions: z.array(ruleVersionRefSchema), + verdict: z.enum(REVIEW_VERDICTS), + blocking_count: z.number().int().nonnegative().safe(), +}).strict().superRefine((review, context) => { + const findingIds = new Set(); + review.findings.forEach((finding, index) => { + if (findingIds.has(finding.finding_id)) context.addIssue({ code: "custom", path: ["findings", index, "finding_id"], message: "duplicate finding_id" }); + findingIds.add(finding.finding_id); + }); + const rules = new Set(); + review.matched_rule_versions.forEach((rule, index) => { + const key = `${rule.rule_id}:${rule.rule_version}`; + if (rules.has(key)) context.addIssue({ code: "custom", path: ["matched_rule_versions", index], message: "duplicate rule version" }); + rules.add(key); + }); + if (review.role === "self-review" && review.step !== "self_review") context.addIssue({ code: "custom", path: ["step"], message: "self-review role requires self_review step" }); + if (review.role !== "self-review" && review.step !== "counter_review") context.addIssue({ code: "custom", path: ["step"], message: "counter-review roles require counter_review step" }); + const expected = expectedReviewSummary(review.findings); + if (review.blocking_count !== expected.blocking_count) context.addIssue({ code: "custom", path: ["blocking_count"], message: `review blocking_count must be ${expected.blocking_count}` }); + if (review.verdict !== expected.verdict) context.addIssue({ code: "custom", path: ["verdict"], message: `review verdict must be ${expected.verdict}` }); +}); + +function expectedReviewSummary(findings: readonly ReviewFinding[]): Readonly<{ blocking_count: number; verdict: ReviewVerdict }> { + const blocking_count = findings.filter((finding) => finding.blocking).length; + return { blocking_count, verdict: blocking_count > 0 ? "fail" : findings.length > 0 ? "advisory" : "pass" }; +} + +function validateReviewClaims(parsed: RawReview): void { + const expected = expectedReviewSummary(parsed.findings); + if (parsed.blocking_count !== expected.blocking_count) throw new TypeError(`review blocking_count must be ${expected.blocking_count}`); + if (parsed.verdict !== expected.verdict) throw new TypeError(`review verdict must be ${expected.verdict}`); +} + +export function parseAndDeriveReview(value: unknown): DerivedReview { + assertPlainJson(value, "review"); + const parsed = rawReviewSchema.parse(value); + validateReviewClaims(parsed); + return parsed; +} + +interface ReviewProvenanceBase extends DerivedReview { + readonly model_family: ModelFamily | "unknown"; + readonly model: string; + readonly effort: DeclaredEffort; +} + +export interface AgentDeclaredReview extends ReviewProvenanceBase { + readonly assurance: "agent-declared"; +} +export interface ServerAttestedReview extends Omit { + readonly assurance: "server-attested"; + readonly adapter: AdapterId; + readonly cli_version: string; + readonly model_family: ModelFamily; + readonly effort: Exclude; + readonly invocation_id: string; + readonly envelope_input_digest: Sha256Digest; + readonly observed_output_digest: Sha256Digest; + readonly result_id: string; +} +export interface DegradedReview extends ReviewProvenanceBase { + readonly assurance: "degraded"; + readonly reason: string; +} +export type ReviewEvidence = AgentDeclaredReview | ServerAttestedReview | DegradedReview; + +const provenanceBase = rawReviewSchema.safeExtend({ + model_family: z.union([z.enum(MODEL_FAMILIES), z.literal("unknown")]), + model: nonBlank, + effort: z.union([z.enum(EFFORT_VALUES), z.literal("unknown")]), +}); +const agentDeclaredReviewSchema = provenanceBase.safeExtend({ assurance: z.literal("agent-declared") }).strict(); +const serverAttestedReviewSchema = provenanceBase.safeExtend({ + assurance: z.literal("server-attested"), + adapter: z.enum(ADAPTER_IDS), + cli_version: nonBlank, + model_family: z.enum(MODEL_FAMILIES), + effort: z.enum(EFFORT_VALUES), + invocation_id: id, + envelope_input_digest: digest, + observed_output_digest: digest, + result_id: id, +}).strict().superRefine((review, context) => { + if (review.role === "self-review") context.addIssue({ code: "custom", path: ["role"], message: "self-review cannot be server-attested" }); + const expectedReviewer = review.producer_family === "claude" ? "codex" : "claude"; + if (review.model_family !== expectedReviewer) context.addIssue({ code: "custom", path: ["model_family"], message: "server-attested review must be opposite-family" }); +}); +const degradedReviewSchema = provenanceBase.safeExtend({ assurance: z.literal("degraded"), reason: nonBlank }).strict(); +export const reviewEvidenceSchema = z.discriminatedUnion("assurance", [agentDeclaredReviewSchema, serverAttestedReviewSchema, degradedReviewSchema]); + +export function parseReviewEvidence(value: unknown): ReviewEvidence { + assertPlainJson(value, "review evidence"); + const parsed = reviewEvidenceSchema.parse(value); + validateReviewClaims(parsed); + return parsed; +} + +export function parseReferencedReviewEvidence(value: unknown): ReferencedEvidence { + assertPlainJson(value, "referenced review evidence"); + const wrapper = z.object({ evidence_digest: digest, evidence: z.unknown() }).strict().parse(value); + return { evidence_digest: wrapper.evidence_digest, evidence: parseReviewEvidence(wrapper.evidence) }; +} diff --git a/src/contracts/schemas/v1/adjudication-evidence.schema.json b/src/contracts/schemas/v1/adjudication-evidence.schema.json new file mode 100644 index 00000000..4d236061 --- /dev/null +++ b/src/contracts/schemas/v1/adjudication-evidence.schema.json @@ -0,0 +1,21 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:adjudication-evidence", + "oneOf": [ + { "$ref": "#/$defs/agentDeclared" }, { "$ref": "#/$defs/serverAttested" }, { "$ref": "#/$defs/degraded" } + ], + "$defs": { + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "id": { "type": "string", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }, "nonBlank": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "ruleVersion": { "type": "object", "additionalProperties": false, "required": ["rule_id", "rule_version"], "properties": { "rule_id": { "$ref": "#/$defs/id" }, "rule_version": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } } }, + "mechanical": { "type": "object", "additionalProperties": false, "required": ["mechanism", "state", "details"], "properties": { "mechanism": { "$ref": "#/$defs/nonBlank" }, "state": { "enum": ["current", "missing", "stale", "unknown", "failed", "digest-mismatch"] }, "subject_digest": { "$ref": "#/$defs/digest" }, "evidence_digest": { "$ref": "#/$defs/digest" }, "details": { "$ref": "#/$defs/nonBlank" } }, "allOf": [{ "if": { "properties": { "state": { "enum": ["current", "stale"] } }, "required": ["state"] }, "then": { "properties": { "subject_digest": true, "evidence_digest": true }, "required": ["subject_digest", "evidence_digest"] } }, { "if": { "properties": { "state": { "enum": ["missing", "unknown"] } }, "required": ["state"] }, "then": { "not": { "anyOf": [{ "required": ["subject_digest"] }, { "required": ["evidence_digest"] }] } } }] }, + "ruleFinding": { "type": "object", "additionalProperties": false, "required": ["rule_id", "rule_version", "compliance", "rationale", "trigger", "trigger_evidence", "enforced_by"], "properties": { "rule_id": { "$ref": "#/$defs/id" }, "rule_version": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, "compliance": { "enum": ["pass", "fail", "uncertain"] }, "rationale": { "$ref": "#/$defs/nonBlank" }, "trigger": { "enum": ["not-matched", "matched", "uncertain"] }, "trigger_evidence": { "$ref": "#/$defs/nonBlank" }, "enforced_by": { "type": "array", "items": { "$ref": "#/$defs/mechanical" } } }, "allOf": [{ "if": { "properties": { "compliance": { "const": "pass" } }, "required": ["compliance"] }, "then": { "properties": { "enforced_by": { "type": "array", "minItems": 1, "items": { "allOf": [{ "$ref": "#/$defs/mechanical" }, { "type": "object", "properties": { "state": { "const": "current" } } }] } } } } }] }, + "driftFinding": { "type": "object", "additionalProperties": false, "required": ["upstream_digest", "drift", "affected_claim_ids", "rationale"], "properties": { "upstream_digest": { "$ref": "#/$defs/digest" }, "drift": { "enum": ["aligned", "incidental", "material"] }, "affected_claim_ids": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/id" } }, "rationale": { "$ref": "#/$defs/nonBlank" } }, "allOf": [{ "if": { "properties": { "drift": { "const": "aligned" } }, "required": ["drift"] }, "then": { "properties": { "affected_claim_ids": { "type": "array", "maxItems": 0 } } }, "else": { "properties": { "affected_claim_ids": { "type": "array", "minItems": 1 } } } }] }, + "base": { "type": "object", "x-archflow-adjudication-semantics": true, "required": ["schema_version", "task_id", "phase_instance", "step", "subject_digest", "input_fingerprint", "pinned_constitution_digest", "approved_upstream_digests", "source_evidence_set_digest", "rule_findings", "drift_findings", "constitution", "drift", "matched_rule_versions", "uncertain_rule_versions", "model_family", "model", "effort"], "properties": { "schema_version": { "const": "1" }, "task_id": { "$ref": "#/$defs/id" }, "phase_instance": { "type": "string", "pattern": "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" }, "step": { "const": "adjudicate" }, "subject_digest": { "$ref": "#/$defs/digest" }, "input_fingerprint": { "$ref": "#/$defs/digest" }, "pinned_constitution_digest": { "$ref": "#/$defs/digest" }, "approved_upstream_digests": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/digest" } }, "source_evidence_set_digest": { "$ref": "#/$defs/digest" }, "rule_findings": { "type": "array", "items": { "$ref": "#/$defs/ruleFinding" } }, "drift_findings": { "type": "array", "x-archflow-unique-by": "upstream_digest", "items": { "$ref": "#/$defs/driftFinding" } }, "constitution": { "enum": ["pass", "fail", "uncertain"] }, "drift": { "enum": ["aligned", "incidental", "material"] }, "matched_rule_versions": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/ruleVersion" } }, "uncertain_rule_versions": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/ruleVersion" } }, "model_family": { "enum": ["claude", "codex", "unknown"] }, "model": { "$ref": "#/$defs/nonBlank" }, "effort": { "enum": ["low", "medium", "high", "xhigh", "max", "ultra", "unknown"] } } }, + "agentDeclared": { "type": "object", "unevaluatedProperties": false, "allOf": [{ "$ref": "#/$defs/base" }, { "$ref": "#/$defs/closedCommon" }, { "type": "object", "properties": { "assurance": { "const": "agent-declared" } } }] }, + "degraded": { "type": "object", "unevaluatedProperties": false, "allOf": [{ "$ref": "#/$defs/base" }, { "$ref": "#/$defs/closedDegraded" }, { "type": "object", "properties": { "assurance": { "const": "degraded" } } }] }, + "serverAttested": { "type": "object", "unevaluatedProperties": false, "allOf": [{ "$ref": "#/$defs/base" }, { "$ref": "#/$defs/closedServer" }, { "type": "object", "properties": { "assurance": { "const": "server-attested" } } }] }, + "closedCommon": { "type": "object", "required": ["assurance"], "properties": { "assurance": true } }, + "closedDegraded": { "type": "object", "required": ["assurance", "reason"], "properties": { "assurance": true, "reason": { "$ref": "#/$defs/nonBlank" } } }, + "closedServer": { "type": "object", "required": ["assurance", "adapter", "cli_version", "invocation_id", "envelope_input_digest", "observed_output_digest", "result_id"], "properties": { "assurance": true, "adapter": { "enum": ["claude-cli", "codex-cli"] }, "cli_version": { "$ref": "#/$defs/nonBlank" }, "model_family": { "enum": ["claude", "codex"] }, "effort": { "enum": ["low", "medium", "high", "xhigh", "max", "ultra"] }, "invocation_id": { "$ref": "#/$defs/id" }, "envelope_input_digest": { "$ref": "#/$defs/digest" }, "observed_output_digest": { "$ref": "#/$defs/digest" }, "result_id": { "$ref": "#/$defs/id" } } } + } +} diff --git a/src/contracts/schemas/v1/adjudication.schema.json b/src/contracts/schemas/v1/adjudication.schema.json new file mode 100644 index 00000000..5f4a5c1c --- /dev/null +++ b/src/contracts/schemas/v1/adjudication.schema.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:adjudication", + "type": "object", "additionalProperties": false, "x-archflow-adjudication-semantics": true, + "required": ["schema_version", "task_id", "phase_instance", "step", "subject_digest", "input_fingerprint", "pinned_constitution_digest", "approved_upstream_digests", "source_evidence_set_digest", "rule_findings", "drift_findings", "constitution", "drift", "matched_rule_versions", "uncertain_rule_versions"], + "properties": { + "schema_version": { "const": "1" }, "task_id": { "$ref": "#/$defs/id" }, "phase_instance": { "type": "string", "pattern": "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" }, "step": { "const": "adjudicate" }, + "subject_digest": { "$ref": "#/$defs/digest" }, "input_fingerprint": { "$ref": "#/$defs/digest" }, "pinned_constitution_digest": { "$ref": "#/$defs/digest" }, + "approved_upstream_digests": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/digest" } }, "source_evidence_set_digest": { "$ref": "#/$defs/digest" }, + "rule_findings": { "type": "array", "items": { "$ref": "#/$defs/ruleFinding" } }, "drift_findings": { "type": "array", "x-archflow-unique-by": "upstream_digest", "items": { "$ref": "#/$defs/driftFinding" } }, + "constitution": { "$ref": "#/$defs/compliance" }, "drift": { "$ref": "#/$defs/drift" }, + "matched_rule_versions": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/ruleVersion" } }, "uncertain_rule_versions": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/ruleVersion" } } + }, + "$defs": { + "id": { "type": "string", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }, "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "nonBlank": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "compliance": { "enum": ["pass", "fail", "uncertain"] }, "drift": { "enum": ["aligned", "incidental", "material"] }, + "ruleVersion": { "type": "object", "additionalProperties": false, "required": ["rule_id", "rule_version"], "properties": { "rule_id": { "$ref": "#/$defs/id" }, "rule_version": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } } }, + "mechanical": { "type": "object", "additionalProperties": false, "required": ["mechanism", "state", "details"], "properties": { "mechanism": { "$ref": "#/$defs/nonBlank" }, "state": { "enum": ["current", "missing", "stale", "unknown", "failed", "digest-mismatch"] }, "subject_digest": { "$ref": "#/$defs/digest" }, "evidence_digest": { "$ref": "#/$defs/digest" }, "details": { "$ref": "#/$defs/nonBlank" } }, "allOf": [{ "if": { "properties": { "state": { "enum": ["current", "stale"] } }, "required": ["state"] }, "then": { "properties": { "subject_digest": true, "evidence_digest": true }, "required": ["subject_digest", "evidence_digest"] } }, { "if": { "properties": { "state": { "enum": ["missing", "unknown"] } }, "required": ["state"] }, "then": { "not": { "anyOf": [{ "required": ["subject_digest"] }, { "required": ["evidence_digest"] }] } } }] }, + "ruleFinding": { "type": "object", "additionalProperties": false, "required": ["rule_id", "rule_version", "compliance", "rationale", "trigger", "trigger_evidence", "enforced_by"], "properties": { "rule_id": { "$ref": "#/$defs/id" }, "rule_version": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, "compliance": { "$ref": "#/$defs/compliance" }, "rationale": { "$ref": "#/$defs/nonBlank" }, "trigger": { "enum": ["not-matched", "matched", "uncertain"] }, "trigger_evidence": { "$ref": "#/$defs/nonBlank" }, "enforced_by": { "type": "array", "items": { "$ref": "#/$defs/mechanical" } } }, "allOf": [{ "if": { "properties": { "compliance": { "const": "pass" } }, "required": ["compliance"] }, "then": { "properties": { "enforced_by": { "type": "array", "minItems": 1, "items": { "allOf": [{ "$ref": "#/$defs/mechanical" }, { "type": "object", "properties": { "state": { "const": "current" } } }] } } } } }] }, + "driftFinding": { "type": "object", "additionalProperties": false, "required": ["upstream_digest", "drift", "affected_claim_ids", "rationale"], "properties": { "upstream_digest": { "$ref": "#/$defs/digest" }, "drift": { "$ref": "#/$defs/drift" }, "affected_claim_ids": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/id" } }, "rationale": { "$ref": "#/$defs/nonBlank" } }, "allOf": [{ "if": { "properties": { "drift": { "const": "aligned" } }, "required": ["drift"] }, "then": { "properties": { "affected_claim_ids": { "type": "array", "maxItems": 0 } } }, "else": { "properties": { "affected_claim_ids": { "type": "array", "minItems": 1 } } } }] } + } +} diff --git a/src/contracts/schemas/v1/authority-link.schema.json b/src/contracts/schemas/v1/authority-link.schema.json new file mode 100644 index 00000000..fdf39b74 --- /dev/null +++ b/src/contracts/schemas/v1/authority-link.schema.json @@ -0,0 +1,26 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:authority-link", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "evidence_kind", "assurance", "role", "task_id", "phase_instance", "subject_digest", "input_fingerprint", "evidence_digest", "authority"], + "properties": { + "schema_version": { "const": "1" }, "evidence_kind": { "enum": ["review", "adjudication"] }, "assurance": { "enum": ["agent-declared", "server-attested", "degraded"] }, + "role": { "enum": ["self-review", "counter-review", "gate-counter-review", "adjudication"] }, "task_id": { "$ref": "#/$defs/id" }, "phase_instance": { "$ref": "#/$defs/phase" }, + "subject_digest": { "$ref": "#/$defs/digest" }, "input_fingerprint": { "$ref": "#/$defs/digest" }, "evidence_digest": { "$ref": "#/$defs/digest" }, "gate_id": { "$ref": "#/$defs/id" }, + "authority": { "oneOf": [{ "$ref": "#/$defs/agent" }, { "$ref": "#/$defs/server" }, { "$ref": "#/$defs/degraded" }] } + }, + "allOf": [ + { "if": { "properties": { "evidence_kind": { "const": "adjudication" } }, "required": ["evidence_kind"] }, "then": { "properties": { "role": { "const": "adjudication" } } }, "else": { "properties": { "role": { "enum": ["self-review", "counter-review", "gate-counter-review"] } } } }, + { "if": { "properties": { "assurance": { "const": "agent-declared" } }, "required": ["assurance"] }, "then": { "properties": { "authority": { "$ref": "#/$defs/agent" } } } }, + { "if": { "properties": { "assurance": { "const": "server-attested" } }, "required": ["assurance"] }, "then": { "properties": { "authority": { "$ref": "#/$defs/server" } } } }, + { "if": { "properties": { "assurance": { "const": "degraded" } }, "required": ["assurance"] }, "then": { "properties": { "authority": { "$ref": "#/$defs/degraded" } } } }, + { "if": { "properties": { "role": { "const": "gate-counter-review" } }, "required": ["role"] }, "then": { "properties": { "gate_id": true }, "required": ["gate_id"] }, "else": { "not": { "required": ["gate_id"] } } } + ], + "$defs": { + "id": { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" }, "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "phase": { "type": "string", "pattern": "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" }, "safe": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, + "agent": { "type": "object", "additionalProperties": false, "required": ["kind", "result_id", "result_digest", "state_revision"], "properties": { "kind": { "const": "agent-declared" }, "result_id": { "$ref": "#/$defs/id" }, "result_digest": { "$ref": "#/$defs/digest" }, "state_revision": { "$ref": "#/$defs/safe" } } }, + "server": { "type": "object", "additionalProperties": false, "required": ["kind", "invocation_id", "result_id", "receipt_id", "state_revision", "envelope_input_digest", "observed_output_digest", "result_digest"], "properties": { "kind": { "const": "server" }, "invocation_id": { "$ref": "#/$defs/id" }, "result_id": { "$ref": "#/$defs/id" }, "receipt_id": { "$ref": "#/$defs/id" }, "state_revision": { "$ref": "#/$defs/safe" }, "envelope_input_digest": { "$ref": "#/$defs/digest" }, "observed_output_digest": { "$ref": "#/$defs/digest" }, "result_digest": { "$ref": "#/$defs/digest" } } }, + "degraded": { "type": "object", "additionalProperties": false, "required": ["kind", "checkpoint_digest", "checkpoint_revision"], "properties": { "kind": { "const": "degraded" }, "checkpoint_digest": { "$ref": "#/$defs/digest" }, "checkpoint_revision": { "$ref": "#/$defs/safe" } } } + } +} diff --git a/src/contracts/schemas/v1/evidence-reference.schema.json b/src/contracts/schemas/v1/evidence-reference.schema.json new file mode 100644 index 00000000..16ba3b12 --- /dev/null +++ b/src/contracts/schemas/v1/evidence-reference.schema.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:evidence-reference", + "oneOf": [ + { "$ref": "#/$defs/review" }, + { "$ref": "#/$defs/adjudication" } + ], + "$defs": { + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "review": { "type": "object", "additionalProperties": false, "required": ["evidence_digest", "evidence"], "properties": { "evidence_digest": { "$ref": "#/$defs/digest" }, "evidence": { "$ref": "urn:archflow:schema:v1:review-evidence" } } }, + "adjudication": { "type": "object", "additionalProperties": false, "required": ["evidence_digest", "evidence"], "properties": { "evidence_digest": { "$ref": "#/$defs/digest" }, "evidence": { "$ref": "urn:archflow:schema:v1:adjudication-evidence" } } } + } +} diff --git a/src/contracts/schemas/v1/evidence-slots.schema.json b/src/contracts/schemas/v1/evidence-slots.schema.json new file mode 100644 index 00000000..d090e4ca --- /dev/null +++ b/src/contracts/schemas/v1/evidence-slots.schema.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:evidence-slots", + "oneOf": [ + { "type": "array", "prefixItems": [{ "$ref": "#/$defs/self" }, { "$ref": "#/$defs/counter" }], "minItems": 2, "maxItems": 2 }, + { "type": "array", "prefixItems": [{ "$ref": "#/$defs/self" }, { "$ref": "#/$defs/counter" }, { "$ref": "#/$defs/gateCounter" }], "minItems": 3, "maxItems": 3 } + ], + "$defs": { + "id": { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" }, "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "family": { "enum": ["claude", "codex"] }, + "self": { "type": "object", "additionalProperties": false, "required": ["role", "evidence_digest", "assurance", "producer_family", "reviewer_family", "independence"], "properties": { "role": { "const": "self-review" }, "evidence_digest": { "$ref": "#/$defs/digest" }, "assurance": { "const": "agent-declared" }, "producer_family": { "$ref": "#/$defs/family" }, "reviewer_family": { "$ref": "#/$defs/family" }, "independence": { "const": "same-family-self" } }, "oneOf": [{ "properties": { "producer_family": { "const": "claude" }, "reviewer_family": { "const": "claude" } } }, { "properties": { "producer_family": { "const": "codex" }, "reviewer_family": { "const": "codex" } } }] }, + "counter": { "type": "object", "additionalProperties": false, "required": ["role", "evidence_digest", "assurance", "producer_family", "reviewer_family", "independence"], "properties": { "role": { "const": "counter-review" }, "evidence_digest": { "$ref": "#/$defs/digest" }, "assurance": { "enum": ["server-attested", "degraded"] }, "producer_family": { "$ref": "#/$defs/family" }, "reviewer_family": { "$ref": "#/$defs/family" }, "independence": { "const": "opposite-family" } }, "oneOf": [{ "properties": { "producer_family": { "const": "claude" }, "reviewer_family": { "const": "codex" } } }, { "properties": { "producer_family": { "const": "codex" }, "reviewer_family": { "const": "claude" } } }] }, + "gateCounter": { "type": "object", "additionalProperties": false, "required": ["role", "evidence_digest", "assurance", "producer_family", "reviewer_family", "independence", "gate_id"], "properties": { "role": { "const": "gate-counter-review" }, "evidence_digest": { "$ref": "#/$defs/digest" }, "assurance": { "enum": ["server-attested", "degraded"] }, "producer_family": { "$ref": "#/$defs/family" }, "reviewer_family": { "$ref": "#/$defs/family" }, "independence": { "const": "opposite-family" }, "gate_id": { "$ref": "#/$defs/id" } }, "oneOf": [{ "properties": { "producer_family": { "const": "claude" }, "reviewer_family": { "const": "codex" } } }, { "properties": { "producer_family": { "const": "codex" }, "reviewer_family": { "const": "claude" } } }] } + } +} diff --git a/src/contracts/schemas/v1/gate-contract.schema.json b/src/contracts/schemas/v1/gate-contract.schema.json new file mode 100644 index 00000000..d1c4d127 --- /dev/null +++ b/src/contracts/schemas/v1/gate-contract.schema.json @@ -0,0 +1,544 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:gate-contract", + "type": "object", + "x-archflow-gate-semantics": true, + "$defs": { + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "safeId": { "$ref": "urn:archflow:schema:v1:primitives#/$defs/safeId" }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "pattern": "\\S" + }, + "safeInteger": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "rule": { + "type": "object", + "additionalProperties": false, + "required": ["rule_id", "rule_version"], + "properties": { + "rule_id": { "$ref": "#/$defs/safeId" }, + "rule_version": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + } + }, + "rules": { + "type": "array", + "uniqueItems": true, + "items": { "$ref": "#/$defs/rule" } + }, + "digests": { + "type": "array", + "uniqueItems": true, + "items": { "$ref": "#/$defs/digest" } + }, + "waiverScope": { + "type": "object", + "additionalProperties": false, + "required": ["operation", "boundary"], + "properties": { + "operation": { "enum": ["review-trigger", "adjudication-failure"] }, + "boundary": { "enum": ["subject", "phase", "task"] } + } + }, + "authorityLink": { + "type": "object", + "additionalProperties": false, + "required": [ + "link_digest", + "purpose", + "proposed_generation_digest", + "changed_input_fingerprint" + ], + "properties": { + "link_digest": { "$ref": "#/$defs/digest" }, + "purpose": { "const": "restore-adoption" }, + "proposed_generation_digest": { "$ref": "#/$defs/digest" }, + "changed_input_fingerprint": { "$ref": "#/$defs/digest" } + } + }, + "artifactApproval": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "artifact-approval" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": ["artifact_kind"], + "properties": { + "artifact_kind": { + "enum": ["prd", "design", "phase-design", "phase-implementation"] + } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/approve" }, + { "$ref": "#/$defs/revise" }, + { "$ref": "#/$defs/reject" } + ] + } + } + }, + "reviewTrigger": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "review-trigger" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": [ + "matched_rules", + "uncertain_rules", + "eligible_waiver_rules", + "waiver_scope" + ], + "properties": { + "matched_rules": { "$ref": "#/$defs/rules" }, + "uncertain_rules": { "$ref": "#/$defs/rules" }, + "eligible_waiver_rules": { "$ref": "#/$defs/rules" }, + "waiver_scope": { "$ref": "#/$defs/waiverScope" } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/approve" }, + { "$ref": "#/$defs/revise" }, + { "$ref": "#/$defs/reject" }, + { "$ref": "#/$defs/waiverRequested" } + ] + } + } + }, + "materialDrift": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "material-drift" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": ["affected_upstream", "drift", "affected_claim_ids"], + "properties": { + "affected_upstream": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "digest"], + "properties": { + "kind": { + "enum": [ + "prd", + "architecture", + "phase-design", + "implementation-result", + "review", + "adjudication", + "constitution", + "workflow", + "import" + ] + }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "drift": { "const": "material" }, + "affected_claim_ids": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { "$ref": "#/$defs/safeId" } + } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/amendUpstream" }, + { "$ref": "#/$defs/reviseCurrent" }, + { "$ref": "#/$defs/reject" } + ] + } + } + }, + "adjudicationFailure": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "adjudication-failure" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": [ + "constitution", + "failed_rules", + "uncertain_rules", + "eligible_waiver_rules", + "waiver_scope" + ], + "properties": { + "constitution": { "enum": ["fail", "uncertain"] }, + "failed_rules": { "$ref": "#/$defs/rules" }, + "uncertain_rules": { "$ref": "#/$defs/rules" }, + "eligible_waiver_rules": { "$ref": "#/$defs/rules" }, + "waiver_scope": { "$ref": "#/$defs/waiverScope" } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/adjudicationApprove" }, + { "$ref": "#/$defs/revise" }, + { "$ref": "#/$defs/reject" }, + { "$ref": "#/$defs/waiverRequested" } + ] + } + } + }, + "attemptsExhausted": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "attempts-exhausted" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": ["step", "attempts", "maximum_attempts"], + "properties": { + "step": { + "enum": [ + "produce", + "self_review", + "counter_review", + "triage", + "adjudicate" + ] + }, + "attempts": { "$ref": "#/$defs/safeInteger" }, + "maximum_attempts": { "$ref": "#/$defs/safeInteger" } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/retryOnce" }, + { "$ref": "#/$defs/revise" }, + { "$ref": "#/$defs/abort" } + ] + } + } + }, + "constitutionEdit": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "constitution-edit" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": [ + "pinned_constitution_digest", + "current_constitution_digest", + "changed_path_class" + ], + "properties": { + "pinned_constitution_digest": { "$ref": "#/$defs/digest" }, + "current_constitution_digest": { "$ref": "#/$defs/digest" }, + "changed_path_class": { "const": "task-branch-constitution" } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/revertEdit" }, + { "$ref": "#/$defs/startBaseAmendment" }, + { "$ref": "#/$defs/abort" } + ] + } + } + }, + "commitAuthorization": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "commit-authorization" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": [ + "target_ref", + "diff_digest", + "current_artifact_digests", + "parent_document_digests" + ], + "properties": { + "target_ref": { "$ref": "#/$defs/text" }, + "diff_digest": { "$ref": "#/$defs/digest" }, + "current_artifact_digests": { "$ref": "#/$defs/digests" }, + "parent_document_digests": { "$ref": "#/$defs/digests" } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/authorizeCommit" }, + { "$ref": "#/$defs/revise" }, + { "$ref": "#/$defs/abort" } + ] + } + } + }, + "restoreCollision": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "restore-collision" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": [ + "path", + "recorded_generation_digest", + "current_generation_digest" + ], + "properties": { + "path": { "type": "string", "minLength": 1, "maxLength": 1024 }, + "recorded_generation_digest": { "$ref": "#/$defs/digest" }, + "current_generation_digest": { "$ref": "#/$defs/digest" }, + "adoption_candidate": { "$ref": "#/$defs/authorityLink" } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/discardAndRestore" }, + { "$ref": "#/$defs/adoptGeneration" }, + { "$ref": "#/$defs/abort" } + ] + } + } + }, + "migrationAudit": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "context", "payload"], + "properties": { + "kind": { "const": "migration-audit" }, + "context": { + "type": "object", + "additionalProperties": false, + "required": [ + "source_identity_digest", + "destination_identity_digest", + "import_digest", + "code_baseline_digest", + "policy_baseline_digest" + ], + "properties": { + "source_identity_digest": { "$ref": "#/$defs/digest" }, + "destination_identity_digest": { "$ref": "#/$defs/digest" }, + "import_digest": { "$ref": "#/$defs/digest" }, + "code_baseline_digest": { "$ref": "#/$defs/digest" }, + "policy_baseline_digest": { "$ref": "#/$defs/digest" } + } + }, + "payload": { + "oneOf": [ + { "$ref": "#/$defs/acceptImportAudit" }, + { "$ref": "#/$defs/revise" }, + { "$ref": "#/$defs/abort" } + ] + } + } + }, + "approve": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "approve" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "advance" + }, + "revise": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "revise" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "retry" + }, + "reject": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "reject" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "non-advancing" + }, + "abort": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "abort" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "non-advancing" + }, + "waiverRequested": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason", "rule", "rationale"], + "properties": { + "decision": { "const": "waiver-requested" }, + "reason": { "$ref": "#/$defs/text" }, + "rule": { "$ref": "#/$defs/rule" }, + "rationale": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "redirect-waiver" + }, + "adjudicationApprove": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason", "resolutions"], + "properties": { + "decision": { "const": "approve" }, + "reason": { "$ref": "#/$defs/text" }, + "resolutions": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["rule", "resolution"], + "properties": { + "rule": { "$ref": "#/$defs/rule" }, + "resolution": { "$ref": "#/$defs/text" } + } + } + } + }, + "x-archflow-effect": "advance" + }, + "amendUpstream": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "amend-upstream" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "redirect-upstream" + }, + "reviseCurrent": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "revise-current" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "retry" + }, + "retryOnce": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "retry-once" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "retry" + }, + "revertEdit": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "revert-edit" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "retry" + }, + "startBaseAmendment": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "start-base-amendment" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "redirect-upstream" + }, + "authorizeCommit": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "authorize-commit" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "advance" + }, + "discardAndRestore": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "discard-and-restore" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "advance" + }, + "adoptGeneration": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason", "adoption_authority", "rationale"], + "properties": { + "decision": { "const": "adopt-as-new-generation" }, + "reason": { "$ref": "#/$defs/text" }, + "adoption_authority": { "$ref": "#/$defs/authorityLink" }, + "rationale": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "advance" + }, + "acceptImportAudit": { + "type": "object", + "additionalProperties": false, + "required": ["decision", "reason"], + "properties": { + "decision": { "const": "accept-import-audit" }, + "reason": { "$ref": "#/$defs/text" } + }, + "x-archflow-effect": "advance" + } + }, + "oneOf": [ + { "$ref": "#/$defs/artifactApproval" }, + { "$ref": "#/$defs/reviewTrigger" }, + { "$ref": "#/$defs/materialDrift" }, + { "$ref": "#/$defs/adjudicationFailure" }, + { "$ref": "#/$defs/attemptsExhausted" }, + { "$ref": "#/$defs/constitutionEdit" }, + { "$ref": "#/$defs/commitAuthorization" }, + { "$ref": "#/$defs/restoreCollision" }, + { "$ref": "#/$defs/migrationAudit" } + ] +} diff --git a/src/contracts/schemas/v1/gate-decision.schema.json b/src/contracts/schemas/v1/gate-decision.schema.json new file mode 100644 index 00000000..82e7b076 --- /dev/null +++ b/src/contracts/schemas/v1/gate-decision.schema.json @@ -0,0 +1,350 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:gate-decision", + "type": "object", + "$defs": { + "digest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "safeId": { "$ref": "urn:archflow:schema:v1:primitives#/$defs/safeId" }, + "recordedAt": { + "type": "string", + "format": "date-time", + "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" + }, + "connected": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "actor_class", + "assurance", + "channel", + "decision_event_id", + "connection_id", + "request_id_digest", + "recorded_at" + ], + "properties": { + "schema_version": { + "const": "1" + }, + "actor_class": { + "enum": ["human", "archforge"] + }, + "assurance": { + "const": "declared-local-trace" + }, + "channel": { + "const": "connected-host" + }, + "decision_event_id": { + "$ref": "#/$defs/safeId" + }, + "connection_id": { + "$ref": "#/$defs/safeId" + }, + "request_id_digest": { + "$ref": "#/$defs/digest" + }, + "recorded_at": { + "$ref": "#/$defs/recordedAt" + } + } + }, + "local": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "actor_class", + "assurance", + "channel", + "decision_event_id", + "helper_invocation_id", + "recorded_at" + ], + "properties": { + "schema_version": { + "const": "1" + }, + "actor_class": { + "enum": ["human", "archforge"] + }, + "assurance": { + "const": "declared-local-trace" + }, + "channel": { + "const": "archflow-local" + }, + "decision_event_id": { + "$ref": "#/$defs/safeId" + }, + "helper_invocation_id": { + "$ref": "#/$defs/safeId" + }, + "recorded_at": { + "$ref": "#/$defs/recordedAt" + } + } + }, + "base": { + "type": "object", + "required": [ + "schema_version", + "gate_id", + "task_id", + "phase_instance", + "subject_digest", + "context_digest", + "human_provenance" + ], + "properties": { + "schema_version": { + "const": "1" + }, + "gate_id": { + "$ref": "#/$defs/safeId" + }, + "task_id": { + "$ref": "#/$defs/safeId" + }, + "phase_instance": { + "type": "string", + "pattern": "^(prd|design|phase-design-[1-9][0-9]*|phase-impl-[1-9][0-9]*)$" + }, + "subject_digest": { + "$ref": "#/$defs/digest" + }, + "context_digest": { + "$ref": "#/$defs/digest" + }, + "human_provenance": { + "oneOf": [ + { + "$ref": "#/$defs/connected" + }, + { + "$ref": "#/$defs/local" + } + ] + } + } + } + }, + "allOf": [ + { + "$ref": "#/$defs/base" + }, + { + "oneOf": [ + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "artifact-approval" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/approve" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/reject" + } + ] + } + } + }, + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "review-trigger" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/approve" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/reject" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/waiverRequested" + } + ] + } + } + }, + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "material-drift" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/amendUpstream" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/reviseCurrent" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/reject" + } + ] + } + } + }, + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "adjudication-failure" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/adjudicationApprove" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/reject" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/waiverRequested" + } + ] + } + } + }, + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "attempts-exhausted" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/retryOnce" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + }, + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "constitution-edit" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/revertEdit" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/startBaseAmendment" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + }, + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "commit-authorization" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/authorizeCommit" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + }, + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "restore-collision" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/discardAndRestore" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/adoptGeneration" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + }, + { + "type": "object", + "required": ["kind", "payload"], + "properties": { + "kind": { + "const": "migration-audit" + }, + "payload": { + "oneOf": [ + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/acceptImportAudit" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + } + ] + } + ], + "unevaluatedProperties": false +} diff --git a/src/contracts/schemas/v1/mcp-tools.schema.json b/src/contracts/schemas/v1/mcp-tools.schema.json new file mode 100644 index 00000000..ed7b243a --- /dev/null +++ b/src/contracts/schemas/v1/mcp-tools.schema.json @@ -0,0 +1,468 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://archflow.dev/schemas/v1/mcp-tools", + "type": "object", + "x-archflow-mcp-semantics": true, + "$defs": { + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "id": { "$ref": "urn:archflow:schema:v1:primitives#/$defs/safeId" }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "pattern": "\\S" + }, + "integer": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, + "phase": { + "type": "string", + "pattern": "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" + }, + "path": { "$ref": "urn:archflow:schema:v1:path-claim" }, + "rule": { + "type": "object", + "additionalProperties": false, + "required": ["rule_id", "rule_version"], + "properties": { + "rule_id": { "$ref": "#/$defs/id" }, + "rule_version": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + } + } + }, + "scope": { + "type": "object", + "additionalProperties": false, + "required": ["operation", "boundary"], + "properties": { + "operation": { "enum": ["review-trigger", "adjudication-failure"] }, + "boundary": { "enum": ["subject", "phase", "task"] } + } + }, + "currentEvidence": { + "type": "object", + "additionalProperties": false, + "required": ["set_digest", "slots"], + "properties": { + "set_digest": { "$ref": "#/$defs/digest" }, + "slots": { "$ref": "urn:archflow:schema:v1:evidence-slots" } + } + }, + "common": { + "type": "object", + "required": [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint" + ], + "properties": { + "schema_version": { "const": "1" }, + "task_id": { "$ref": "#/$defs/id" }, + "intent_id": { "$ref": "#/$defs/id" }, + "expected_revision": { "$ref": "#/$defs/integer" }, + "input_fingerprint": { "$ref": "#/$defs/digest" } + } + }, + "failure": { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "ok", "error"], + "properties": { + "schema_version": { "const": "1" }, + "ok": { "const": false }, + "error": { "$ref": "urn:archflow:schema:v1:project-error" } + } + }, + "archflow_state": { + "input": { + "allOf": [ + { "$ref": "#/$defs/common" }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "phase_instance", + "step", + "status" + ], + "properties": { + "schema_version": { "const": "1" }, + "task_id": { "$ref": "#/$defs/id" }, + "intent_id": { "$ref": "#/$defs/id" }, + "expected_revision": { "$ref": "#/$defs/integer" }, + "input_fingerprint": { "$ref": "#/$defs/digest" }, + "phase_instance": { "$ref": "#/$defs/phase" }, + "step": { + "enum": [ + "produce", + "self_review", + "counter_review", + "triage", + "adjudicate" + ] + }, + "status": { "enum": ["running", "succeeded", "failed"] } + } + } + ] + }, + "success": { + "type": "object", + "additionalProperties": false, + "required": ["path", "revision", "status"], + "properties": { + "path": { "$ref": "#/$defs/path" }, + "revision": { "$ref": "#/$defs/integer" }, + "status": { "enum": ["running", "succeeded", "failed"] } + } + }, + "result": { + "oneOf": [ + { "$ref": "#/$defs/failure" }, + { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "ok", "value"], + "properties": { + "schema_version": { "const": "1" }, + "ok": { "const": true }, + "value": { "$ref": "#/$defs/archflow_state/success" } + } + } + ] + } + }, + "archflow_counter_review": { + "input": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "artifact_path", + "rubric" + ], + "properties": { + "schema_version": { "const": "1" }, + "task_id": { "$ref": "#/$defs/id" }, + "intent_id": { "$ref": "#/$defs/id" }, + "expected_revision": { "$ref": "#/$defs/integer" }, + "input_fingerprint": { "$ref": "#/$defs/digest" }, + "artifact_path": { "$ref": "#/$defs/path" }, + "rubric": { "$ref": "urn:archflow:schema:v1:rubric" } + } + }, + "success": { + "type": "object", + "additionalProperties": false, + "required": ["path", "verdict", "blocking_count", "revision"], + "properties": { + "path": { "$ref": "#/$defs/path" }, + "verdict": { "enum": ["pass", "advisory", "fail"] }, + "blocking_count": { "$ref": "#/$defs/integer" }, + "revision": { "$ref": "#/$defs/integer" } + } + }, + "result": { + "oneOf": [ + { "$ref": "#/$defs/failure" }, + { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "ok", "value"], + "properties": { + "schema_version": { "const": "1" }, + "ok": { "const": true }, + "value": { "$ref": "#/$defs/archflow_counter_review/success" } + } + } + ] + } + }, + "archflow_adjudicate": { + "input": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "artifact_path", + "upstream_paths" + ], + "properties": { + "schema_version": { "const": "1" }, + "task_id": { "$ref": "#/$defs/id" }, + "intent_id": { "$ref": "#/$defs/id" }, + "expected_revision": { "$ref": "#/$defs/integer" }, + "input_fingerprint": { "$ref": "#/$defs/digest" }, + "artifact_path": { "$ref": "#/$defs/path" }, + "upstream_paths": { + "type": "array", + "items": { "$ref": "#/$defs/path" } + } + } + }, + "success": { + "type": "object", + "additionalProperties": false, + "required": ["path", "constitution", "drift", "triggers", "revision"], + "properties": { + "path": { "$ref": "#/$defs/path" }, + "constitution": { "enum": ["pass", "fail", "uncertain"] }, + "drift": { "enum": ["aligned", "incidental", "material"] }, + "triggers": { "type": "array", "items": { "$ref": "#/$defs/rule" } }, + "revision": { "$ref": "#/$defs/integer" } + } + }, + "result": { + "oneOf": [ + { "$ref": "#/$defs/failure" }, + { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "ok", "value"], + "properties": { + "schema_version": { "const": "1" }, + "ok": { "const": true }, + "value": { "$ref": "#/$defs/archflow_adjudicate/success" } + } + } + ] + } + }, + "archflow_gate": { + "input": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "phase_instance", + "summary", + "subject_digest", + "current_evidence", + "kind", + "context" + ], + "properties": { + "schema_version": { "const": "1" }, + "task_id": { "$ref": "#/$defs/id" }, + "intent_id": { "$ref": "#/$defs/id" }, + "expected_revision": { "$ref": "#/$defs/integer" }, + "input_fingerprint": { "$ref": "#/$defs/digest" }, + "phase_instance": { "$ref": "#/$defs/phase" }, + "summary": { "$ref": "#/$defs/text" }, + "subject_digest": { "$ref": "#/$defs/digest" }, + "current_evidence": { "$ref": "#/$defs/currentEvidence" }, + "supersedes": { + "type": "object", + "additionalProperties": false, + "required": [ + "superseded_gate_id", + "accepted_triage_digest", + "old_subject_digest" + ], + "properties": { + "superseded_gate_id": { "$ref": "#/$defs/id" }, + "accepted_triage_digest": { "$ref": "#/$defs/digest" }, + "old_subject_digest": { "$ref": "#/$defs/digest" } + } + }, + "kind": { + "enum": [ + "artifact-approval", + "review-trigger", + "material-drift", + "adjudication-failure", + "attempts-exhausted", + "constitution-edit", + "commit-authorization", + "restore-collision", + "migration-audit" + ] + }, + "context": { "type": "object" } + }, + "allOf": [{ + "oneOf": [ + { "properties": { "kind": { "const": "artifact-approval" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/artifactApproval/properties/context" } } }, + { "properties": { "kind": { "const": "review-trigger" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/reviewTrigger/properties/context" } } }, + { "properties": { "kind": { "const": "material-drift" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/materialDrift/properties/context" } } }, + { "properties": { "kind": { "const": "adjudication-failure" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/adjudicationFailure/properties/context" } } }, + { "properties": { "kind": { "const": "attempts-exhausted" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/attemptsExhausted/properties/context" } } }, + { "properties": { "kind": { "const": "constitution-edit" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/constitutionEdit/properties/context" } } }, + { "properties": { "kind": { "const": "commit-authorization" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/commitAuthorization/properties/context" } } }, + { "properties": { "kind": { "const": "restore-collision" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/restoreCollision/properties/context" } } }, + { "properties": { "kind": { "const": "migration-audit" }, "context": { "$ref": "urn:archflow:schema:v1:gate-contract#/$defs/migrationAudit/properties/context" } } } + ] + }] + }, + "success": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "decision", "notes", "revision"], + "properties": { + "kind": { + "enum": [ + "artifact-approval", + "review-trigger", + "material-drift", + "adjudication-failure", + "attempts-exhausted", + "constitution-edit", + "commit-authorization", + "restore-collision", + "migration-audit" + ] + }, + "decision": { "$ref": "urn:archflow:schema:v1:gate-decision" }, + "notes": { "$ref": "#/$defs/text" }, + "revision": { "$ref": "#/$defs/integer" } + } + }, + "result": { + "oneOf": [ + { "$ref": "#/$defs/failure" }, + { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "ok", "value"], + "properties": { + "schema_version": { "const": "1" }, + "ok": { "const": true }, + "value": { "$ref": "#/$defs/archflow_gate/success" } + } + } + ] + } + }, + "archflow_waiver": { + "input": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "origin", + "rationale" + ], + "properties": { + "schema_version": { "const": "1" }, + "task_id": { "$ref": "#/$defs/id" }, + "intent_id": { "$ref": "#/$defs/id" }, + "expected_revision": { "$ref": "#/$defs/integer" }, + "input_fingerprint": { "$ref": "#/$defs/digest" }, + "origin": { + "type": "object", + "additionalProperties": false, + "required": [ + "origin_gate_id", + "origin_decision_digest", + "origin_context_digest", + "task_id", + "phase_instance", + "subject_digest", + "current_evidence_set_digest", + "rule", + "scope" + ], + "properties": { + "origin_gate_id": { "$ref": "#/$defs/id" }, + "origin_decision_digest": { "$ref": "#/$defs/digest" }, + "origin_context_digest": { "$ref": "#/$defs/digest" }, + "task_id": { "$ref": "#/$defs/id" }, + "phase_instance": { "$ref": "#/$defs/phase" }, + "subject_digest": { "$ref": "#/$defs/digest" }, + "current_evidence_set_digest": { "$ref": "#/$defs/digest" }, + "rule": { "$ref": "#/$defs/rule" }, + "scope": { "$ref": "#/$defs/scope" } + } + }, + "rationale": { "$ref": "#/$defs/text" } + } + }, + "success": { + "type": "object", + "required": [ + "origin_gate_id", + "waiver_gate_id", + "task_id", + "rule_id", + "rule_version", + "subject_digest", + "current_evidence_set_digest", + "scope", + "human_provenance", + "granted", + "notes", + "revision" + ], + "properties": { + "origin_gate_id": { "$ref": "#/$defs/id" }, + "waiver_gate_id": { "$ref": "#/$defs/id" }, + "task_id": { "$ref": "#/$defs/id" }, + "rule_id": { "$ref": "#/$defs/id" }, + "rule_version": { "type": "integer", "minimum": 1 }, + "subject_digest": { "$ref": "#/$defs/digest" }, + "current_evidence_set_digest": { "$ref": "#/$defs/digest" }, + "scope": { "$ref": "#/$defs/scope" }, + "human_provenance": { "oneOf": [{ "$ref": "urn:archflow:schema:v1:gate-decision#/$defs/connected" }, { "$ref": "urn:archflow:schema:v1:gate-decision#/$defs/local" }] }, + "granted": { "type": "boolean" }, + "expires": { "const": "task-complete" }, + "notes": { "$ref": "#/$defs/text" }, + "revision": { "$ref": "#/$defs/integer" } + }, + "allOf": [ + { + "if": { "properties": { "granted": { "const": true } } }, + "then": { "properties": { "expires": {} }, "required": ["expires"] }, + "else": { "not": { "properties": { "expires": {} }, "required": ["expires"] } } + } + ], + "unevaluatedProperties": false + }, + "result": { + "oneOf": [ + { "$ref": "#/$defs/failure" }, + { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "ok", "value"], + "properties": { + "schema_version": { "const": "1" }, + "ok": { "const": true }, + "value": { "$ref": "#/$defs/archflow_waiver/success" } + } + } + ] + } + } + }, + "oneOf": [ + { "$ref": "#/$defs/archflow_state/input" }, + { "$ref": "#/$defs/archflow_counter_review/input" }, + { "$ref": "#/$defs/archflow_adjudicate/input" }, + { "$ref": "#/$defs/archflow_gate/input" }, + { "$ref": "#/$defs/archflow_waiver/input" } + ] +} diff --git a/src/contracts/schemas/v1/path-claim.schema.json b/src/contracts/schemas/v1/path-claim.schema.json new file mode 100644 index 00000000..b83c9d1a --- /dev/null +++ b/src/contracts/schemas/v1/path-claim.schema.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:path-claim", + "type": "string", + "minLength": 1, + "x-archflow-max-utf8-bytes": 1024, + "pattern": "^(?!/)(?![A-Za-z]:)(?!//)(?!.*\\\\)(?!.*[\\u0000-\\u001F\\u007F-\\u009F])(?!\\.\\.?(?:/|$))(?!.*\\/\\.\\.?(?:/|$))(?!.*//).+$" +} diff --git a/src/contracts/schemas/v1/primitives.schema.json b/src/contracts/schemas/v1/primitives.schema.json index e730bde0..390b374a 100644 --- a/src/contracts/schemas/v1/primitives.schema.json +++ b/src/contracts/schemas/v1/primitives.schema.json @@ -6,6 +6,27 @@ "type": "integer", "minimum": 1, "maximum": 9007199254740991 + }, + "safeInteger": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "sha256Digest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "safeId": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" + }, + "safeCode": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$" + }, + "safeVersion": { + "type": "string", + "pattern": "^[A-Za-z0-9.-]{1,64}$" } } } diff --git a/src/contracts/schemas/v1/project-error.schema.json b/src/contracts/schemas/v1/project-error.schema.json new file mode 100644 index 00000000..42cac2f4 --- /dev/null +++ b/src/contracts/schemas/v1/project-error.schema.json @@ -0,0 +1,2632 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:project-error", + "$defs": { + "digest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" + }, + "code": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$" + }, + "version": { + "type": "string", + "pattern": "^[A-Za-z0-9.-]{1,64}$" + }, + "integer": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "tool": { + "enum": [ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver" + ] + }, + "adapter": { + "enum": [ + "claude-cli", + "codex-cli" + ] + }, + "family": { + "enum": [ + "claude", + "codex" + ] + }, + "gate": { + "enum": [ + "artifact-approval", + "review-trigger", + "material-drift", + "adjudication-failure", + "attempts-exhausted", + "constitution-edit", + "commit-authorization", + "restore-collision", + "migration-audit" + ] + }, + "phase": { + "type": "string", + "pattern": "^(prd|design|phase-design-[1-9][0-9]*|phase-impl-[1-9][0-9]*)$" + }, + "path": { + "type": "string", + "minLength": 1, + "x-archflow-max-utf8-bytes": 1024, + "pattern": "^(?!/)(?![A-Za-z]:)(?!//)(?!.*\\\\)(?!.*[\\u0000-\\u001F\\u007F-\\u009F])(?!\\.\\.?(?:/|$))(?!.*\\/\\.\\.?(?:/|$))(?!.*//).+$" + }, + "issue": { + "type": "object", + "additionalProperties": false, + "required": [ + "issue_code" + ], + "properties": { + "issue_code": { + "$ref": "#/$defs/code" + } + } + }, + "digests": { + "type": "object", + "additionalProperties": false, + "required": [ + "expected_digest", + "observed_digest" + ], + "properties": { + "expected_digest": { + "$ref": "#/$defs/digest" + }, + "observed_digest": { + "$ref": "#/$defs/digest" + } + } + }, + "taskPath": { + "type": "object", + "additionalProperties": false, + "required": [ + "task_id", + "path_class" + ], + "properties": { + "task_id": { + "$ref": "#/$defs/id" + }, + "path_class": { + "$ref": "#/$defs/code" + } + } + }, + "E_CONTRACT_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "CONTRACT_INVALID" + }, + "owner": { + "const": "contracts" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "CONTRACT_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "issue_code" + ], + "properties": { + "tool": { + "$ref": "#/$defs/tool" + }, + "issue_code": { + "$ref": "#/$defs/code" + }, + "schema_version": { + "$ref": "#/$defs/version" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "correct-contract" + } + }, + "type": "object" + } + ] + }, + "E_RESULT_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "RESULT_INVALID" + }, + "owner": { + "const": "integrity" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "RESULT_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "tool", + "result_id" + ], + "properties": { + "tool": { + "$ref": "#/$defs/tool" + }, + "result_id": { + "$ref": "#/$defs/id" + }, + "expected_digest": { + "$ref": "#/$defs/digest" + }, + "observed_digest": { + "$ref": "#/$defs/digest" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-retained-result" + } + }, + "type": "object" + } + ] + }, + "E_CONTRACT_VERSION_UNSUPPORTED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "CONTRACT_VERSION_UNSUPPORTED" + }, + "owner": { + "const": "contracts" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "CONTRACT_VERSION_UNSUPPORTED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "supported_version" + ], + "properties": { + "schema_version": { + "$ref": "#/$defs/version" + }, + "supported_version": { + "$ref": "#/$defs/version" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "upgrade-caller" + } + }, + "type": "object" + } + ] + }, + "E_WORKFLOW_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "WORKFLOW_INVALID" + }, + "owner": { + "const": "config" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "WORKFLOW_INVALID" + }, + "parameters": { + "$ref": "#/$defs/issue" + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-workflow" + } + }, + "type": "object" + } + ] + }, + "E_CONFIG_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "CONFIG_INVALID" + }, + "owner": { + "const": "config" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "CONFIG_INVALID" + }, + "parameters": { + "$ref": "#/$defs/issue" + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-config" + } + }, + "type": "object" + } + ] + }, + "E_CONFIG_MODEL_UNSUPPORTED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "CONFIG_MODEL_UNSUPPORTED" + }, + "owner": { + "const": "config" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "CONFIG_MODEL_UNSUPPORTED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "model" + ], + "properties": { + "model": { + "$ref": "#/$defs/id" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "select-supported-model" + } + }, + "type": "object" + } + ] + }, + "E_CONFIG_FAMILY_UNSUPPORTED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "CONFIG_FAMILY_UNSUPPORTED" + }, + "owner": { + "const": "config" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "CONFIG_FAMILY_UNSUPPORTED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "family" + ], + "properties": { + "family": { + "$ref": "#/$defs/id" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "select-supported-family" + } + }, + "type": "object" + } + ] + }, + "E_RUNTIME_VERSION_UNSUPPORTED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "RUNTIME_VERSION_UNSUPPORTED" + }, + "owner": { + "const": "config" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "RUNTIME_VERSION_UNSUPPORTED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "component", + "version" + ], + "properties": { + "component": { + "$ref": "#/$defs/id" + }, + "version": { + "$ref": "#/$defs/version" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "upgrade-runtime" + } + }, + "type": "object" + } + ] + }, + "E_REPOSITORY_NOT_FOUND": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "REPOSITORY_NOT_FOUND" + }, + "owner": { + "const": "repository" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "REPOSITORY_NOT_FOUND" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "repository_candidate_digest" + ], + "properties": { + "repository_candidate_digest": { + "$ref": "#/$defs/digest" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "open-repository" + } + }, + "type": "object" + } + ] + }, + "E_REPOSITORY_MISMATCH": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "REPOSITORY_MISMATCH" + }, + "owner": { + "const": "repository" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "REPOSITORY_MISMATCH" + }, + "parameters": { + "$ref": "#/$defs/digests" + } + }, + "type": "object" + }, + "next_action": { + "const": "reopen-task-worktree" + } + }, + "type": "object" + } + ] + }, + "E_TASK_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "TASK_INVALID" + }, + "owner": { + "const": "repository" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "TASK_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "task_id", + "issue_code" + ], + "properties": { + "task_id": { + "$ref": "#/$defs/id" + }, + "issue_code": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-task" + } + }, + "type": "object" + } + ] + }, + "E_PATH_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "PATH_INVALID" + }, + "owner": { + "const": "paths" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "PATH_INVALID" + }, + "parameters": { + "$ref": "#/$defs/taskPath" + } + }, + "type": "object" + }, + "next_action": { + "const": "use-valid-path-claim" + } + }, + "type": "object" + } + ] + }, + "E_PATH_ESCAPE": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "PATH_ESCAPE" + }, + "owner": { + "const": "paths" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "PATH_ESCAPE" + }, + "parameters": { + "$ref": "#/$defs/taskPath" + } + }, + "type": "object" + }, + "next_action": { + "const": "use-task-relative-path" + } + }, + "type": "object" + } + ] + }, + "E_TASK_SCOPE_VIOLATION": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "TASK_SCOPE_VIOLATION" + }, + "owner": { + "const": "paths" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "TASK_SCOPE_VIOLATION" + }, + "parameters": { + "$ref": "#/$defs/taskPath" + } + }, + "type": "object" + }, + "next_action": { + "const": "use-task-scoped-path" + } + }, + "type": "object" + } + ] + }, + "E_GIT_CONFLICT": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "GIT_CONFLICT" + }, + "owner": { + "const": "repository" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "GIT_CONFLICT" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "operation" + ], + "properties": { + "operation": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "resolve-git-conflict" + } + }, + "type": "object" + } + ] + }, + "E_GIT_DIVERGED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "GIT_DIVERGED" + }, + "owner": { + "const": "repository" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "GIT_DIVERGED" + }, + "parameters": { + "$ref": "#/$defs/digests" + } + }, + "type": "object" + }, + "next_action": { + "const": "reconcile-git-history" + } + }, + "type": "object" + } + ] + }, + "E_HANDOFF_REQUIRED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "HANDOFF_REQUIRED" + }, + "owner": { + "const": "repository" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "HANDOFF_REQUIRED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "phase_instance" + ], + "properties": { + "phase_instance": { + "$ref": "#/$defs/phase" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "complete-clean-handoff" + } + }, + "type": "object" + } + ] + }, + "E_POLICY_BASE_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "POLICY_BASE_INVALID" + }, + "owner": { + "const": "policy" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "POLICY_BASE_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "expected_digest" + ], + "properties": { + "expected_digest": { + "$ref": "#/$defs/digest" + }, + "observed_digest": { + "$ref": "#/$defs/digest" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "restore-policy-base" + } + }, + "type": "object" + } + ] + }, + "E_WORKFLOW_MISMATCH": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "WORKFLOW_MISMATCH" + }, + "owner": { + "const": "policy" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "WORKFLOW_MISMATCH" + }, + "parameters": { + "$ref": "#/$defs/digests" + } + }, + "type": "object" + }, + "next_action": { + "const": "restore-pinned-workflow" + } + }, + "type": "object" + } + ] + }, + "E_PINNED_CONFIG_MISMATCH": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "PINNED_CONFIG_MISMATCH" + }, + "owner": { + "const": "policy" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "PINNED_CONFIG_MISMATCH" + }, + "parameters": { + "$ref": "#/$defs/digests" + } + }, + "type": "object" + }, + "next_action": { + "const": "restore-pinned-config" + } + }, + "type": "object" + } + ] + }, + "E_STALE_SKILLS": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "STALE_SKILLS" + }, + "owner": { + "const": "policy" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "STALE_SKILLS" + }, + "parameters": { + "$ref": "#/$defs/digests" + } + }, + "type": "object" + }, + "next_action": { + "const": "refresh-skills" + } + }, + "type": "object" + } + ] + }, + "E_STATE_MISSING": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "STATE_MISSING" + }, + "owner": { + "const": "state" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "STATE_MISSING" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "phase_instance" + ], + "properties": { + "phase_instance": { + "$ref": "#/$defs/phase" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "initialize-state" + } + }, + "type": "object" + } + ] + }, + "E_STATE_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "STATE_INVALID" + }, + "owner": { + "const": "state" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "STATE_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "phase_instance", + "issue_code" + ], + "properties": { + "phase_instance": { + "$ref": "#/$defs/phase" + }, + "issue_code": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-state" + } + }, + "type": "object" + } + ] + }, + "E_TRANSITION_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "TRANSITION_INVALID" + }, + "owner": { + "const": "state" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "TRANSITION_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "phase_instance", + "from", + "to" + ], + "properties": { + "phase_instance": { + "$ref": "#/$defs/phase" + }, + "from": { + "$ref": "#/$defs/code" + }, + "to": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "select-valid-transition" + } + }, + "type": "object" + } + ] + }, + "E_INPUT_FINGERPRINT_MISMATCH": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "INPUT_FINGERPRINT_MISMATCH" + }, + "owner": { + "const": "state" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "INPUT_FINGERPRINT_MISMATCH" + }, + "parameters": { + "$ref": "#/$defs/digests" + } + }, + "type": "object" + }, + "next_action": { + "const": "create-fresh-intent" + } + }, + "type": "object" + } + ] + }, + "E_STATE_CONFLICT": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "STATE_CONFLICT" + }, + "owner": { + "const": "state" + }, + "retryable": { + "const": true + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "STATE_CONFLICT" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "expected_revision", + "observed_revision" + ], + "properties": { + "expected_revision": { + "$ref": "#/$defs/integer" + }, + "observed_revision": { + "$ref": "#/$defs/integer" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "reread-and-retry-intent" + } + }, + "type": "object" + } + ] + }, + "E_SUPPLEMENTAL_REVIEW_REQUIRED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "SUPPLEMENTAL_REVIEW_REQUIRED" + }, + "owner": { + "const": "state" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "SUPPLEMENTAL_REVIEW_REQUIRED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "gate_id", + "evidence_digest" + ], + "properties": { + "gate_id": { + "$ref": "#/$defs/id" + }, + "evidence_digest": { + "$ref": "#/$defs/digest" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "triage-supplemental-review" + } + }, + "type": "object" + } + ] + }, + "E_INTENT_MISMATCH": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "INTENT_MISMATCH" + }, + "owner": { + "const": "intent" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "INTENT_MISMATCH" + }, + "parameters": { + "$ref": "#/$defs/digests" + } + }, + "type": "object" + }, + "next_action": { + "const": "create-fresh-intent" + } + }, + "type": "object" + } + ] + }, + "E_SNAPSHOT_LIMIT": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "SNAPSHOT_LIMIT" + }, + "owner": { + "const": "snapshot" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "SNAPSHOT_LIMIT" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "limit_scope", + "offending_paths", + "current_bytes", + "byte_cap" + ], + "properties": { + "limit_scope": { + "enum": [ + "result", + "task" + ] + }, + "offending_paths": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "x-archflow-sorted-unique": true, + "items": { + "$ref": "#/$defs/path" + } + }, + "current_bytes": { + "$ref": "#/$defs/integer" + }, + "byte_cap": { + "$ref": "#/$defs/integer" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "reduce-snapshot" + } + }, + "type": "object" + } + ] + }, + "E_SNAPSHOT_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "SNAPSHOT_INVALID" + }, + "owner": { + "const": "snapshot" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "SNAPSHOT_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "snapshot_digest", + "issue_code" + ], + "properties": { + "snapshot_digest": { + "$ref": "#/$defs/digest" + }, + "issue_code": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-snapshot" + } + }, + "type": "object" + } + ] + }, + "E_RESTORE_COLLISION": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "RESTORE_COLLISION" + }, + "owner": { + "const": "snapshot" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "RESTORE_COLLISION" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "gate_id", + "path_class" + ], + "properties": { + "gate_id": { + "$ref": "#/$defs/id" + }, + "path_class": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "resolve-restore-gate" + } + }, + "type": "object" + } + ] + }, + "E_RECONCILIATION_REQUIRED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "RECONCILIATION_REQUIRED" + }, + "owner": { + "const": "snapshot" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "RECONCILIATION_REQUIRED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "recorded_digest", + "observed_digest" + ], + "properties": { + "recorded_digest": { + "$ref": "#/$defs/digest" + }, + "observed_digest": { + "$ref": "#/$defs/digest" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "run-reconciliation" + } + }, + "type": "object" + } + ] + }, + "E_SECRET_DETECTED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "SECRET_DETECTED" + }, + "owner": { + "const": "snapshot" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "SECRET_DETECTED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "path_class", + "detector_id" + ], + "properties": { + "path_class": { + "$ref": "#/$defs/code" + }, + "detector_id": { + "$ref": "#/$defs/id" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "remove-secret" + } + }, + "type": "object" + } + ] + }, + "E_GATE_ACTIVE": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "GATE_ACTIVE" + }, + "owner": { + "const": "gate" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "GATE_ACTIVE" + }, + "parameters": { + "$ref": "#/$defs/gateParams" + } + }, + "type": "object" + }, + "next_action": { + "const": "resolve-recorded-gate" + } + }, + "type": "object" + } + ] + }, + "E_GATE_DECISION_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "GATE_DECISION_INVALID" + }, + "owner": { + "const": "gate" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "GATE_DECISION_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "gate_id", + "gate_kind", + "issue_code" + ], + "properties": { + "gate_id": { + "$ref": "#/$defs/id" + }, + "gate_kind": { + "$ref": "#/$defs/gate" + }, + "issue_code": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "record-valid-gate-decision" + } + }, + "type": "object" + } + ] + }, + "E_GATE_CANCELLED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "GATE_CANCELLED" + }, + "owner": { + "const": "gate" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "GATE_CANCELLED" + }, + "parameters": { + "$ref": "#/$defs/gateParams" + } + }, + "type": "object" + }, + "next_action": { + "const": "restart-gate-flow" + } + }, + "type": "object" + } + ] + }, + "gateParams": { + "type": "object", + "additionalProperties": false, + "required": [ + "gate_id", + "gate_kind" + ], + "properties": { + "gate_id": { + "$ref": "#/$defs/id" + }, + "gate_kind": { + "$ref": "#/$defs/gate" + } + } + }, + "E_UNSUPPORTED_HOST": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "UNSUPPORTED_HOST" + }, + "owner": { + "const": "routing" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "UNSUPPORTED_HOST" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "host" + ], + "properties": { + "host": { + "$ref": "#/$defs/id" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "select-supported-host" + } + }, + "type": "object" + } + ] + }, + "E_UNSUPPORTED_MODEL": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "UNSUPPORTED_MODEL" + }, + "owner": { + "const": "routing" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "UNSUPPORTED_MODEL" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "model" + ], + "properties": { + "model": { + "$ref": "#/$defs/id" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "select-supported-model" + } + }, + "type": "object" + } + ] + }, + "E_FAMILY_MISMATCH": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "FAMILY_MISMATCH" + }, + "owner": { + "const": "routing" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "FAMILY_MISMATCH" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "expected_family", + "observed_family" + ], + "properties": { + "expected_family": { + "$ref": "#/$defs/family" + }, + "observed_family": { + "$ref": "#/$defs/family" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "select-correct-family" + } + }, + "type": "object" + } + ] + }, + "E_CLI_VERSION_UNSUPPORTED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "CLI_VERSION_UNSUPPORTED" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "CLI_VERSION_UNSUPPORTED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "adapter", + "version" + ], + "properties": { + "adapter": { + "$ref": "#/$defs/adapter" + }, + "version": { + "$ref": "#/$defs/version" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "upgrade-cli" + } + }, + "type": "object" + } + ] + }, + "E_AUTH_UNAVAILABLE": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "AUTH_UNAVAILABLE" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "AUTH_UNAVAILABLE" + }, + "parameters": { + "$ref": "#/$defs/adapterOnly" + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-authentication" + } + }, + "type": "object" + } + ] + }, + "E_CLI_MISSING": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "CLI_MISSING" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "CLI_MISSING" + }, + "parameters": { + "$ref": "#/$defs/adapterOnly" + } + }, + "type": "object" + }, + "next_action": { + "const": "install-cli" + } + }, + "type": "object" + } + ] + }, + "adapterOnly": { + "type": "object", + "additionalProperties": false, + "required": [ + "adapter" + ], + "properties": { + "adapter": { + "$ref": "#/$defs/adapter" + } + } + }, + "adapterAttempt": { + "type": "object", + "additionalProperties": false, + "required": [ + "adapter", + "attempt" + ], + "properties": { + "adapter": { + "$ref": "#/$defs/adapter" + }, + "attempt": { + "$ref": "#/$defs/integer" + } + } + }, + "E_SANDBOX_UNAVAILABLE": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "SANDBOX_UNAVAILABLE" + }, + "owner": { + "const": "sandbox" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "SANDBOX_UNAVAILABLE" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "capability" + ], + "properties": { + "capability": { + "$ref": "#/$defs/id" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-sandbox" + } + }, + "type": "object" + } + ] + }, + "E_SANDBOX_PROBE_FAILED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "SANDBOX_PROBE_FAILED" + }, + "owner": { + "const": "sandbox" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "SANDBOX_PROBE_FAILED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "capability", + "failure_class" + ], + "properties": { + "capability": { + "$ref": "#/$defs/id" + }, + "failure_class": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-sandbox" + } + }, + "type": "object" + } + ] + }, + "E_RATE_LIMITED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "RATE_LIMITED" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": true + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "RATE_LIMITED" + }, + "parameters": { + "$ref": "#/$defs/adapterAttempt" + } + }, + "type": "object" + }, + "next_action": { + "const": "retry-after-backoff" + } + }, + "type": "object" + } + ] + }, + "E_TIMEOUT": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "TIMEOUT" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": true + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "TIMEOUT" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "adapter", + "attempt", + "limit_ms" + ], + "properties": { + "adapter": { + "$ref": "#/$defs/adapter" + }, + "attempt": { + "$ref": "#/$defs/integer" + }, + "limit_ms": { + "$ref": "#/$defs/integer" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "retry-unchanged-attempt" + } + }, + "type": "object" + } + ] + }, + "E_CANCELLED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "CANCELLED" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": true + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "CANCELLED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "source", + "attempt" + ], + "properties": { + "source": { + "enum": [ + "client", + "transport" + ] + }, + "attempt": { + "$ref": "#/$defs/integer" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "restart-child-attempt" + } + }, + "type": "object" + } + ] + }, + "E_MODEL_OUTPUT_INVALID": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "MODEL_OUTPUT_INVALID" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": true + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "MODEL_OUTPUT_INVALID" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "adapter", + "attempt", + "issue_code" + ], + "properties": { + "adapter": { + "$ref": "#/$defs/adapter" + }, + "attempt": { + "$ref": "#/$defs/integer" + }, + "issue_code": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "retry-unchanged-attempt" + } + }, + "type": "object" + } + ] + }, + "E_IO_ERROR": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "IO_ERROR" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": true + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "IO_ERROR" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "operation", + "attempt" + ], + "properties": { + "operation": { + "$ref": "#/$defs/code" + }, + "attempt": { + "$ref": "#/$defs/integer" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "retry-unchanged-attempt" + } + }, + "type": "object" + } + ] + }, + "E_OUTPUT_OVERFLOW": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "OUTPUT_OVERFLOW" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "OUTPUT_OVERFLOW" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "adapter", + "byte_count", + "byte_cap" + ], + "properties": { + "adapter": { + "$ref": "#/$defs/adapter" + }, + "byte_count": { + "$ref": "#/$defs/integer" + }, + "byte_cap": { + "$ref": "#/$defs/integer" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "reduce-output" + } + }, + "type": "object" + } + ] + }, + "E_PROCESS_FAILED": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "PROCESS_FAILED" + }, + "owner": { + "const": "dispatch" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "PROCESS_FAILED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "adapter", + "exit_class" + ], + "properties": { + "adapter": { + "$ref": "#/$defs/adapter" + }, + "exit_class": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "repair-before-fresh-attempt" + } + }, + "type": "object" + } + ] + }, + "E_INTERNAL_ERROR": { + "allOf": [ + { + "$ref": "#/$defs/errorBase" + }, + { + "properties": { + "code": { + "const": "INTERNAL_ERROR" + }, + "owner": { + "const": "integrity" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "INTERNAL_ERROR" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "correlation_id" + ], + "properties": { + "correlation_id": { + "$ref": "#/$defs/id" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "stop-and-inspect" + } + }, + "type": "object" + } + ] + }, + "errorBase": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "code", + "owner", + "retryable", + "diagnostic", + "next_action" + ], + "properties": { + "schema_version": { + "const": "1" + }, + "code": {}, + "owner": {}, + "retryable": {}, + "diagnostic": { + "type": "object", + "additionalProperties": false, + "required": [ + "template_id", + "parameters" + ], + "properties": { + "template_id": {}, + "parameters": {} + } + }, + "next_action": {} + } + } + }, + "oneOf": [ + { + "$ref": "#/$defs/E_CONTRACT_INVALID" + }, + { + "$ref": "#/$defs/E_RESULT_INVALID" + }, + { + "$ref": "#/$defs/E_CONTRACT_VERSION_UNSUPPORTED" + }, + { + "$ref": "#/$defs/E_WORKFLOW_INVALID" + }, + { + "$ref": "#/$defs/E_CONFIG_INVALID" + }, + { + "$ref": "#/$defs/E_CONFIG_MODEL_UNSUPPORTED" + }, + { + "$ref": "#/$defs/E_CONFIG_FAMILY_UNSUPPORTED" + }, + { + "$ref": "#/$defs/E_RUNTIME_VERSION_UNSUPPORTED" + }, + { + "$ref": "#/$defs/E_REPOSITORY_NOT_FOUND" + }, + { + "$ref": "#/$defs/E_REPOSITORY_MISMATCH" + }, + { + "$ref": "#/$defs/E_TASK_INVALID" + }, + { + "$ref": "#/$defs/E_PATH_INVALID" + }, + { + "$ref": "#/$defs/E_PATH_ESCAPE" + }, + { + "$ref": "#/$defs/E_TASK_SCOPE_VIOLATION" + }, + { + "$ref": "#/$defs/E_GIT_CONFLICT" + }, + { + "$ref": "#/$defs/E_GIT_DIVERGED" + }, + { + "$ref": "#/$defs/E_HANDOFF_REQUIRED" + }, + { + "$ref": "#/$defs/E_POLICY_BASE_INVALID" + }, + { + "$ref": "#/$defs/E_WORKFLOW_MISMATCH" + }, + { + "$ref": "#/$defs/E_PINNED_CONFIG_MISMATCH" + }, + { + "$ref": "#/$defs/E_STALE_SKILLS" + }, + { + "$ref": "#/$defs/E_STATE_MISSING" + }, + { + "$ref": "#/$defs/E_STATE_INVALID" + }, + { + "$ref": "#/$defs/E_TRANSITION_INVALID" + }, + { + "$ref": "#/$defs/E_INPUT_FINGERPRINT_MISMATCH" + }, + { + "$ref": "#/$defs/E_STATE_CONFLICT" + }, + { + "$ref": "#/$defs/E_SUPPLEMENTAL_REVIEW_REQUIRED" + }, + { + "$ref": "#/$defs/E_INTENT_MISMATCH" + }, + { + "$ref": "#/$defs/E_SNAPSHOT_LIMIT" + }, + { + "$ref": "#/$defs/E_SNAPSHOT_INVALID" + }, + { + "$ref": "#/$defs/E_RESTORE_COLLISION" + }, + { + "$ref": "#/$defs/E_RECONCILIATION_REQUIRED" + }, + { + "$ref": "#/$defs/E_SECRET_DETECTED" + }, + { + "$ref": "#/$defs/E_GATE_ACTIVE" + }, + { + "$ref": "#/$defs/E_GATE_DECISION_INVALID" + }, + { + "$ref": "#/$defs/E_GATE_CANCELLED" + }, + { + "$ref": "#/$defs/E_UNSUPPORTED_HOST" + }, + { + "$ref": "#/$defs/E_UNSUPPORTED_MODEL" + }, + { + "$ref": "#/$defs/E_FAMILY_MISMATCH" + }, + { + "$ref": "#/$defs/E_CLI_VERSION_UNSUPPORTED" + }, + { + "$ref": "#/$defs/E_AUTH_UNAVAILABLE" + }, + { + "$ref": "#/$defs/E_CLI_MISSING" + }, + { + "$ref": "#/$defs/E_SANDBOX_UNAVAILABLE" + }, + { + "$ref": "#/$defs/E_SANDBOX_PROBE_FAILED" + }, + { + "$ref": "#/$defs/E_RATE_LIMITED" + }, + { + "$ref": "#/$defs/E_TIMEOUT" + }, + { + "$ref": "#/$defs/E_CANCELLED" + }, + { + "$ref": "#/$defs/E_MODEL_OUTPUT_INVALID" + }, + { + "$ref": "#/$defs/E_IO_ERROR" + }, + { + "$ref": "#/$defs/E_OUTPUT_OVERFLOW" + }, + { + "$ref": "#/$defs/E_PROCESS_FAILED" + }, + { + "$ref": "#/$defs/E_INTERNAL_ERROR" + } + ] +} diff --git a/src/contracts/schemas/v1/protocol-error.schema.json b/src/contracts/schemas/v1/protocol-error.schema.json new file mode 100644 index 00000000..fac81123 --- /dev/null +++ b/src/contracts/schemas/v1/protocol-error.schema.json @@ -0,0 +1,242 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:protocol-error", + "$defs": { + "digest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" + }, + "code": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]{0,63}$" + }, + "version": { + "type": "string", + "pattern": "^[A-Za-z0-9.-]{1,64}$" + }, + "tool": { + "enum": [ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver" + ] + }, + "base": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "code", + "owner", + "retryable", + "diagnostic", + "next_action" + ], + "properties": { + "schema_version": { + "const": "1" + }, + "code": {}, + "owner": { + "const": "protocol" + }, + "retryable": { + "const": false + }, + "diagnostic": { + "type": "object", + "additionalProperties": false, + "required": [ + "template_id", + "parameters" + ], + "properties": { + "template_id": {}, + "parameters": {} + } + }, + "next_action": {} + } + }, + "notFound": { + "allOf": [ + { + "$ref": "#/$defs/base" + }, + { + "properties": { + "code": { + "const": "TOOL_NOT_FOUND" + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "TOOL_NOT_FOUND" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "tool_name_digest" + ], + "properties": { + "tool_name_digest": { + "$ref": "#/$defs/digest" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "call-advertised-tool" + } + }, + "type": "object" + } + ] + }, + "disabled": { + "allOf": [ + { + "$ref": "#/$defs/base" + }, + { + "properties": { + "code": { + "const": "TOOL_DISABLED" + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "TOOL_DISABLED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "tool", + "lifecycle_state" + ], + "properties": { + "tool": { + "$ref": "#/$defs/tool" + }, + "lifecycle_state": { + "$ref": "#/$defs/code" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "wait-for-tool-enable" + } + }, + "type": "object" + } + ] + }, + "unsupported": { + "allOf": [ + { + "$ref": "#/$defs/base" + }, + { + "properties": { + "code": { + "const": "UNSUPPORTED_PROTOCOL" + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "UNSUPPORTED_PROTOCOL" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "offered_version", + "supported_version" + ], + "properties": { + "offered_version": { + "$ref": "#/$defs/version" + }, + "supported_version": { + "$ref": "#/$defs/version" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "negotiate-supported-protocol" + } + }, + "type": "object" + } + ] + }, + "repeated": { + "allOf": [ + { + "$ref": "#/$defs/base" + }, + { + "properties": { + "code": { + "const": "INITIALIZATION_REPEATED" + }, + "diagnostic": { + "properties": { + "template_id": { + "const": "INITIALIZATION_REPEATED" + }, + "parameters": { + "type": "object", + "additionalProperties": false, + "required": [ + "connection_id" + ], + "properties": { + "connection_id": { + "$ref": "#/$defs/id" + } + } + } + }, + "type": "object" + }, + "next_action": { + "const": "open-new-connection" + } + }, + "type": "object" + } + ] + } + }, + "oneOf": [ + { + "$ref": "#/$defs/notFound" + }, + { + "$ref": "#/$defs/disabled" + }, + { + "$ref": "#/$defs/unsupported" + }, + { + "$ref": "#/$defs/repeated" + } + ] +} diff --git a/src/contracts/schemas/v1/result-expectation.schema.json b/src/contracts/schemas/v1/result-expectation.schema.json new file mode 100644 index 00000000..2af328f2 --- /dev/null +++ b/src/contracts/schemas/v1/result-expectation.schema.json @@ -0,0 +1,122 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://archflow.dev/schemas/v1/result-expectation", + "type": "object", + "x-archflow-result-expectation-semantics": true, + "$defs": { + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "id": { "$ref": "urn:archflow:schema:v1:primitives#/$defs/safeId" }, + "integer": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, + "identity": { + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "tool", + "task_id", + "intent_id", + "input_fingerprint", + "request_digest", + "result_id", + "resulting_revision", + "success" + ], + "properties": { + "schema_version": { "const": "1" }, + "tool": { + "enum": [ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver" + ] + }, + "task_id": { "$ref": "#/$defs/id" }, + "intent_id": { "$ref": "#/$defs/id" }, + "input_fingerprint": { "$ref": "#/$defs/digest" }, + "request_digest": { "$ref": "#/$defs/digest" }, + "result_id": { "$ref": "#/$defs/id" }, + "resulting_revision": { "$ref": "#/$defs/integer" }, + "success": { "type": "object" } + } + }, + "archflow_state": { + "allOf": [ + { "$ref": "#/$defs/identity" }, + { + "type": "object", + "properties": { + "tool": { "const": "archflow_state" }, + "success": { + "$ref": "https://archflow.dev/schemas/v1/mcp-tools#/$defs/archflow_state/success" + } + } + } + ] + }, + "archflow_counter_review": { + "allOf": [ + { "$ref": "#/$defs/identity" }, + { + "type": "object", + "properties": { + "tool": { "const": "archflow_counter_review" }, + "success": { + "$ref": "https://archflow.dev/schemas/v1/mcp-tools#/$defs/archflow_counter_review/success" + } + } + } + ] + }, + "archflow_adjudicate": { + "allOf": [ + { "$ref": "#/$defs/identity" }, + { + "type": "object", + "properties": { + "tool": { "const": "archflow_adjudicate" }, + "success": { + "$ref": "https://archflow.dev/schemas/v1/mcp-tools#/$defs/archflow_adjudicate/success" + } + } + } + ] + }, + "archflow_gate": { + "allOf": [ + { "$ref": "#/$defs/identity" }, + { + "type": "object", + "properties": { + "tool": { "const": "archflow_gate" }, + "success": { + "$ref": "https://archflow.dev/schemas/v1/mcp-tools#/$defs/archflow_gate/success" + } + } + } + ] + }, + "archflow_waiver": { + "allOf": [ + { "$ref": "#/$defs/identity" }, + { + "type": "object", + "properties": { + "tool": { "const": "archflow_waiver" }, + "success": { + "$ref": "https://archflow.dev/schemas/v1/mcp-tools#/$defs/archflow_waiver/success" + } + } + } + ] + } + }, + "oneOf": [ + { "$ref": "#/$defs/archflow_state" }, + { "$ref": "#/$defs/archflow_counter_review" }, + { "$ref": "#/$defs/archflow_adjudicate" }, + { "$ref": "#/$defs/archflow_gate" }, + { "$ref": "#/$defs/archflow_waiver" } + ] +} diff --git a/src/contracts/schemas/v1/review-evidence.schema.json b/src/contracts/schemas/v1/review-evidence.schema.json new file mode 100644 index 00000000..5c4f1ef9 --- /dev/null +++ b/src/contracts/schemas/v1/review-evidence.schema.json @@ -0,0 +1,35 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:review-evidence", + "oneOf": [ + { "$ref": "#/$defs/agentDeclared" }, + { "$ref": "#/$defs/serverAttested" }, + { "$ref": "#/$defs/degraded" } + ], + "$defs": { + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "id": { "type": "string", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }, + "nonBlank": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "familyOrUnknown": { "enum": ["claude", "codex", "unknown"] }, + "effortOrUnknown": { "enum": ["low", "medium", "high", "xhigh", "max", "ultra", "unknown"] }, + "reviewProperties": { + "type": "object", + "x-archflow-review-summary": true, + "required": ["schema_version", "task_id", "phase_instance", "step", "role", "subject_digest", "input_fingerprint", "rubric_digest", "producer_family", "findings", "matched_rule_versions", "verdict", "blocking_count", "model_family", "model", "effort"], + "properties": { + "schema_version": { "const": "1" }, "task_id": { "$ref": "#/$defs/id" }, "phase_instance": { "type": "string", "pattern": "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" }, "step": { "enum": ["self_review", "counter_review"] }, "role": { "enum": ["self-review", "counter-review", "gate-counter-review"] }, + "subject_digest": { "$ref": "#/$defs/digest" }, "input_fingerprint": { "$ref": "#/$defs/digest" }, "rubric_digest": { "$ref": "#/$defs/digest" }, "producer_family": { "enum": ["claude", "codex"] }, + "findings": { "type": "array", "x-archflow-unique-by": "finding_id", "items": { "type": "object", "additionalProperties": false, "required": ["finding_id", "severity", "blocking", "summary", "evidence", "suggested_resolution"], "properties": { "finding_id": { "$ref": "#/$defs/id" }, "severity": { "enum": ["blocker", "major", "minor"] }, "blocking": { "type": "boolean" }, "summary": { "$ref": "#/$defs/nonBlank" }, "evidence": { "$ref": "#/$defs/nonBlank" }, "suggested_resolution": { "$ref": "#/$defs/nonBlank" } }, "allOf": [{ "if": { "properties": { "severity": { "const": "blocker" } }, "required": ["severity"] }, "then": { "properties": { "blocking": { "const": true } } }, "else": { "properties": { "blocking": { "const": false } } } }] } }, + "matched_rule_versions": { "type": "array", "uniqueItems": true, "items": { "type": "object", "additionalProperties": false, "required": ["rule_id", "rule_version"], "properties": { "rule_id": { "$ref": "#/$defs/id" }, "rule_version": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } } } }, + "verdict": { "enum": ["pass", "advisory", "fail"] }, "blocking_count": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, + "model_family": { "$ref": "#/$defs/familyOrUnknown" }, "model": { "$ref": "#/$defs/nonBlank" }, "effort": { "$ref": "#/$defs/effortOrUnknown" } + }, + "allOf": [ + { "if": { "properties": { "role": { "const": "self-review" } }, "required": ["role"] }, "then": { "properties": { "step": { "const": "self_review" } } }, "else": { "properties": { "step": { "const": "counter_review" } } } } + ] + }, + "agentDeclared": { "type": "object", "unevaluatedProperties": false, "allOf": [{ "$ref": "#/$defs/reviewProperties" }, { "type": "object", "required": ["assurance"], "properties": { "assurance": { "const": "agent-declared" } } }] }, + "degraded": { "type": "object", "unevaluatedProperties": false, "allOf": [{ "$ref": "#/$defs/reviewProperties" }, { "type": "object", "required": ["assurance", "reason"], "properties": { "assurance": { "const": "degraded" }, "reason": { "$ref": "#/$defs/nonBlank" } } }] }, + "serverAttested": { "type": "object", "unevaluatedProperties": false, "allOf": [{ "$ref": "#/$defs/reviewProperties" }, { "type": "object", "required": ["assurance", "adapter", "cli_version", "invocation_id", "envelope_input_digest", "observed_output_digest", "result_id"], "properties": { "assurance": { "const": "server-attested" }, "adapter": { "enum": ["claude-cli", "codex-cli"] }, "cli_version": { "$ref": "#/$defs/nonBlank" }, "model_family": { "enum": ["claude", "codex"] }, "effort": { "enum": ["low", "medium", "high", "xhigh", "max", "ultra"] }, "invocation_id": { "$ref": "#/$defs/id" }, "envelope_input_digest": { "$ref": "#/$defs/digest" }, "observed_output_digest": { "$ref": "#/$defs/digest" }, "result_id": { "$ref": "#/$defs/id" } }, "not": { "properties": { "role": { "const": "self-review" } }, "required": ["role"] }, "allOf": [{ "if": { "properties": { "producer_family": { "const": "claude" } }, "required": ["producer_family"] }, "then": { "properties": { "model_family": { "const": "codex" } } }, "else": { "properties": { "model_family": { "const": "claude" } } } }] }] } + } +} diff --git a/src/contracts/schemas/v1/review.schema.json b/src/contracts/schemas/v1/review.schema.json new file mode 100644 index 00000000..ba0a8aa2 --- /dev/null +++ b/src/contracts/schemas/v1/review.schema.json @@ -0,0 +1,43 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:review", + "type": "object", + "additionalProperties": false, + "x-archflow-review-summary": true, + "required": ["schema_version", "task_id", "phase_instance", "step", "role", "subject_digest", "input_fingerprint", "rubric_digest", "producer_family", "findings", "matched_rule_versions", "verdict", "blocking_count"], + "properties": { + "schema_version": { "const": "1" }, + "task_id": { "$ref": "#/$defs/id" }, + "phase_instance": { "$ref": "#/$defs/phaseInstance" }, + "step": { "enum": ["self_review", "counter_review"] }, + "role": { "enum": ["self-review", "counter-review", "gate-counter-review"] }, + "subject_digest": { "$ref": "#/$defs/digest" }, + "input_fingerprint": { "$ref": "#/$defs/digest" }, + "rubric_digest": { "$ref": "#/$defs/digest" }, + "producer_family": { "$ref": "#/$defs/family" }, + "findings": { "type": "array", "x-archflow-unique-by": "finding_id", "items": { "$ref": "#/$defs/finding" } }, + "matched_rule_versions": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/ruleVersion" } }, + "verdict": { "enum": ["pass", "advisory", "fail"] }, + "blocking_count": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 } + }, + "allOf": [ + { "if": { "properties": { "role": { "const": "self-review" } }, "required": ["role"] }, "then": { "properties": { "step": { "const": "self_review" } } }, "else": { "properties": { "step": { "const": "counter_review" } } } } + ], + "$defs": { + "id": { "type": "string", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }, + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "family": { "enum": ["claude", "codex"] }, + "phaseInstance": { "type": "string", "pattern": "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" }, + "nonBlank": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "ruleVersion": { "type": "object", "additionalProperties": false, "required": ["rule_id", "rule_version"], "properties": { "rule_id": { "$ref": "#/$defs/id" }, "rule_version": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } } }, + "finding": { + "type": "object", "additionalProperties": false, + "required": ["finding_id", "severity", "blocking", "summary", "evidence", "suggested_resolution"], + "properties": { + "finding_id": { "$ref": "#/$defs/id" }, "severity": { "enum": ["blocker", "major", "minor"] }, "blocking": { "type": "boolean" }, + "summary": { "$ref": "#/$defs/nonBlank" }, "evidence": { "$ref": "#/$defs/nonBlank" }, "suggested_resolution": { "$ref": "#/$defs/nonBlank" } + }, + "allOf": [{ "if": { "properties": { "severity": { "const": "blocker" } }, "required": ["severity"] }, "then": { "properties": { "blocking": { "const": true } } }, "else": { "properties": { "blocking": { "const": false } } } }] + } + } +} diff --git a/src/contracts/schemas/v1/supplemental-review.schema.json b/src/contracts/schemas/v1/supplemental-review.schema.json new file mode 100644 index 00000000..74bcc553 --- /dev/null +++ b/src/contracts/schemas/v1/supplemental-review.schema.json @@ -0,0 +1,147 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:supplemental-review", + "type": "object", + "x-archflow-supplemental-semantics": true, + "oneOf": [ + { "$ref": "#/$defs/decline" }, + { "$ref": "#/$defs/ingest" }, + { "$ref": "#/$defs/noChange" }, + { "$ref": "#/$defs/supersede" } + ], + "$defs": { + "id": { "$ref": "urn:archflow:schema:v1:primitives#/$defs/safeId" }, + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "phase": { + "type": "string", + "pattern": "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" + }, + "family": { "enum": ["claude", "codex"] }, + "nonBlank": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "gate": { + "type": "object", + "additionalProperties": false, + "required": [ + "prior_gate_id", + "task_id", + "phase_instance", + "subject_digest", + "input_fingerprint" + ], + "properties": { + "prior_gate_id": { "$ref": "#/$defs/id" }, + "task_id": { "$ref": "#/$defs/id" }, + "phase_instance": { "$ref": "#/$defs/phase" }, + "subject_digest": { "$ref": "#/$defs/digest" }, + "input_fingerprint": { "$ref": "#/$defs/digest" } + } + }, + "slot": { + "type": "object", + "additionalProperties": false, + "required": [ + "role", + "evidence_digest", + "assurance", + "producer_family", + "reviewer_family", + "independence", + "gate_id" + ], + "properties": { + "role": { "const": "gate-counter-review" }, + "evidence_digest": { "$ref": "#/$defs/digest" }, + "assurance": { "enum": ["server-attested", "degraded"] }, + "producer_family": { "$ref": "#/$defs/family" }, + "reviewer_family": { "$ref": "#/$defs/family" }, + "independence": { "const": "opposite-family" }, + "gate_id": { "$ref": "#/$defs/id" } + }, + "oneOf": [ + { + "properties": { + "producer_family": { "const": "claude" }, + "reviewer_family": { "const": "codex" } + } + }, + { + "properties": { + "producer_family": { "const": "codex" }, + "reviewer_family": { "const": "claude" } + } + } + ] + }, + "review": { + "type": "object", + "additionalProperties": false, + "required": [ + "prior_gate_id", + "task_id", + "phase_instance", + "subject_digest", + "input_fingerprint", + "evidence_slot" + ], + "properties": { + "prior_gate_id": { "$ref": "#/$defs/id" }, + "task_id": { "$ref": "#/$defs/id" }, + "phase_instance": { "$ref": "#/$defs/phase" }, + "subject_digest": { "$ref": "#/$defs/digest" }, + "input_fingerprint": { "$ref": "#/$defs/digest" }, + "evidence_slot": { "$ref": "#/$defs/slot" } + } + }, + "decline": { + "type": "object", + "additionalProperties": false, + "required": ["action", "gate", "reason"], + "properties": { + "action": { "const": "decline" }, + "gate": { "$ref": "#/$defs/gate" }, + "reason": { "$ref": "#/$defs/nonBlank" } + } + }, + "ingest": { + "type": "object", + "additionalProperties": false, + "required": ["action", "review", "reason"], + "properties": { + "action": { "const": "ingest" }, + "review": { "$ref": "#/$defs/review" }, + "reason": { "$ref": "#/$defs/nonBlank" } + } + }, + "noChange": { + "type": "object", + "additionalProperties": false, + "required": ["action", "review", "triage_digest", "reason"], + "properties": { + "action": { "const": "triage-no-change" }, + "review": { "$ref": "#/$defs/review" }, + "triage_digest": { "$ref": "#/$defs/digest" }, + "reason": { "$ref": "#/$defs/nonBlank" } + } + }, + "supersede": { + "type": "object", + "additionalProperties": false, + "required": [ + "action", + "review", + "accepted_triage_digest", + "old_subject_digest", + "new_subject_digest", + "reason" + ], + "properties": { + "action": { "const": "supersede" }, + "review": { "$ref": "#/$defs/review" }, + "accepted_triage_digest": { "$ref": "#/$defs/digest" }, + "old_subject_digest": { "$ref": "#/$defs/digest" }, + "new_subject_digest": { "$ref": "#/$defs/digest" }, + "reason": { "$ref": "#/$defs/nonBlank" } + } + } + } +} diff --git a/src/contracts/schemas/v1/triage.schema.json b/src/contracts/schemas/v1/triage.schema.json new file mode 100644 index 00000000..db2292a9 --- /dev/null +++ b/src/contracts/schemas/v1/triage.schema.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "urn:archflow:schema:v1:triage", "type": "object", "additionalProperties": false, + "required": ["schema_version", "task_id", "phase_instance", "step", "subject_digest", "input_fingerprint", "current_evidence_set_digest", "source_evidence_digests", "dispositions", "accepted_count", "rejected_count"], + "properties": { + "schema_version": { "const": "1" }, "task_id": { "$ref": "#/$defs/id" }, "phase_instance": { "type": "string", "pattern": "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" }, "step": { "const": "triage" }, "subject_digest": { "$ref": "#/$defs/digest" }, "input_fingerprint": { "$ref": "#/$defs/digest" }, "current_evidence_set_digest": { "$ref": "#/$defs/digest" }, "source_evidence_digests": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/digest" } }, "dispositions": { "type": "array", "x-archflow-unique-by": ["review_evidence_digest", "finding_id"], "items": { "oneOf": [{ "$ref": "#/$defs/accepted" }, { "$ref": "#/$defs/rejected" }] } }, "accepted_count": { "$ref": "#/$defs/safe" }, "rejected_count": { "$ref": "#/$defs/safe" } + }, + "$defs": { + "id": { "type": "string", "pattern": "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }, "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "safe": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "nonBlank": { "type": "string", "minLength": 1, "pattern": "\\S" }, + "accepted": { "type": "object", "additionalProperties": false, "required": ["review_evidence_digest", "finding_id", "disposition", "rationale", "revision_intent"], "properties": { "review_evidence_digest": { "$ref": "#/$defs/digest" }, "finding_id": { "$ref": "#/$defs/id" }, "disposition": { "const": "accepted" }, "rationale": { "$ref": "#/$defs/nonBlank" }, "revision_intent": { "$ref": "#/$defs/nonBlank" } } }, + "rejected": { "type": "object", "additionalProperties": false, "required": ["review_evidence_digest", "finding_id", "disposition", "rationale", "evidence"], "properties": { "review_evidence_digest": { "$ref": "#/$defs/digest" }, "finding_id": { "$ref": "#/$defs/id" }, "disposition": { "const": "rejected" }, "rationale": { "$ref": "#/$defs/nonBlank" }, "evidence": { "$ref": "#/$defs/nonBlank" } } } + } +} diff --git a/src/contracts/supplemental.ts b/src/contracts/supplemental.ts new file mode 100644 index 00000000..839258b2 --- /dev/null +++ b/src/contracts/supplemental.ts @@ -0,0 +1,33 @@ +import { z } from "zod"; + +import { safeIdV1Schema, type Sha256Digest } from "./evidence.js"; +import { assertPlainJson } from "./plain-json.js"; +import type { ReviewEvidenceSlot } from "./trust.js"; + +export interface SupplementalGateRef { readonly prior_gate_id: string; readonly task_id: string; readonly phase_instance: string; readonly subject_digest: Sha256Digest; readonly input_fingerprint: Sha256Digest } +export interface SupplementalReviewRef extends SupplementalGateRef { readonly evidence_slot: Extract } +export interface GateSupersessionRef { readonly superseded_gate_id: string; readonly accepted_triage_digest: Sha256Digest; readonly old_subject_digest: Sha256Digest } +export type SupplementalReviewOutcome = + | { readonly action: "decline"; readonly gate: SupplementalGateRef; readonly reason: string } + | { readonly action: "ingest"; readonly review: SupplementalReviewRef; readonly reason: string } + | { readonly action: "triage-no-change"; readonly review: SupplementalReviewRef; readonly triage_digest: Sha256Digest; readonly reason: string } + | { readonly action: "supersede"; readonly review: SupplementalReviewRef; readonly accepted_triage_digest: Sha256Digest; readonly old_subject_digest: Sha256Digest; readonly new_subject_digest: Sha256Digest; readonly reason: string }; + +const id = safeIdV1Schema; +const digest = z.string().regex(/^[0-9a-f]{64}$/u) as unknown as z.ZodType; +const nonBlank = z.string().min(1).refine((value) => value.trim().length > 0, "must contain a non-whitespace character"); +const family = z.enum(["claude", "codex"]); +const phase = z.string().regex(/^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$/u); +const gateShape = { prior_gate_id: id, task_id: id, phase_instance: phase, subject_digest: digest, input_fingerprint: digest }; +export const supplementalGateRefSchema = z.object(gateShape).strict(); +const gateCounterSlotSchema = z.object({ role: z.literal("gate-counter-review"), evidence_digest: digest, assurance: z.enum(["server-attested", "degraded"]), producer_family: family, reviewer_family: family, independence: z.literal("opposite-family"), gate_id: id }).strict().superRefine((slot, context) => { if (slot.producer_family === slot.reviewer_family) context.addIssue({ code: "custom", message: "gate counter-review must be opposite-family" }); }); +export const supplementalReviewRefSchema = z.object({ ...gateShape, evidence_slot: gateCounterSlotSchema }).strict().superRefine((review, context) => { if (review.evidence_slot.gate_id !== review.prior_gate_id) context.addIssue({ code: "custom", path: ["evidence_slot", "gate_id"], message: "gate-counter slot must bind prior_gate_id" }); }); +const decline = z.object({ action: z.literal("decline"), gate: supplementalGateRefSchema, reason: nonBlank }).strict(); +const ingest = z.object({ action: z.literal("ingest"), review: supplementalReviewRefSchema, reason: nonBlank }).strict(); +const noChange = z.object({ action: z.literal("triage-no-change"), review: supplementalReviewRefSchema, triage_digest: digest, reason: nonBlank }).strict(); +const supersede = z.object({ action: z.literal("supersede"), review: supplementalReviewRefSchema, accepted_triage_digest: digest, old_subject_digest: digest, new_subject_digest: digest, reason: nonBlank }).strict().superRefine((outcome, context) => { + if (outcome.old_subject_digest !== outcome.review.subject_digest) context.addIssue({ code: "custom", path: ["old_subject_digest"], message: "old subject must match supplemental review subject" }); + if (outcome.new_subject_digest === outcome.old_subject_digest) context.addIssue({ code: "custom", path: ["new_subject_digest"], message: "new subject must differ" }); +}); +export const supplementalReviewOutcomeSchema = z.discriminatedUnion("action", [decline, ingest, noChange, supersede]); +export function parseSupplementalReviewOutcome(value: unknown): SupplementalReviewOutcome { assertPlainJson(value, "supplemental review outcome"); return supplementalReviewOutcomeSchema.parse(value); } diff --git a/src/contracts/tool-names.ts b/src/contracts/tool-names.ts new file mode 100644 index 00000000..fd6f48c1 --- /dev/null +++ b/src/contracts/tool-names.ts @@ -0,0 +1,13 @@ +export const TOOL_NAMES = Object.freeze([ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver" +] as const); + +export type ToolName = (typeof TOOL_NAMES)[number]; + +export function isToolName(value: unknown): value is ToolName { + return typeof value === "string" && (TOOL_NAMES as readonly string[]).includes(value); +} diff --git a/src/contracts/triage.ts b/src/contracts/triage.ts new file mode 100644 index 00000000..7ed68713 --- /dev/null +++ b/src/contracts/triage.ts @@ -0,0 +1,76 @@ +import { z } from "zod"; + +import type { Sha256Digest } from "./evidence.js"; +import { assertPlainJson } from "./plain-json.js"; +import type { CurrentReviewSet } from "./trust.js"; +import { authenticCurrentReviewSet, registerValidatedTriage, validatedTriageBrand } from "./internal/trust-brands.js"; + + +export interface FindingRef { readonly review_evidence_digest: Sha256Digest; readonly finding_id: string } +export interface AcceptedDisposition extends FindingRef { readonly disposition: "accepted"; readonly rationale: string; readonly revision_intent: string } +export interface RejectedDisposition extends FindingRef { readonly disposition: "rejected"; readonly rationale: string; readonly evidence: string } +export type TriageDisposition = AcceptedDisposition | RejectedDisposition; +export interface TriageCandidate { + readonly schema_version: "1"; + readonly task_id: string; + readonly phase_instance: string; + readonly step: "triage"; + readonly subject_digest: Sha256Digest; + readonly input_fingerprint: Sha256Digest; + readonly current_evidence_set_digest: Sha256Digest; + readonly source_evidence_digests: readonly Sha256Digest[]; + readonly dispositions: readonly TriageDisposition[]; + readonly accepted_count: number; + readonly rejected_count: number; +} +export type ValidatedTriage = TriageCandidate & { readonly [validatedTriageBrand]: true }; + +const id = z.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u); +const digest = z.string().regex(/^[0-9a-f]{64}$/u) as unknown as z.ZodType; +const nonBlank = z.string().min(1).refine((value) => value.trim().length > 0, "must contain a non-whitespace character"); +const findingRefShape = { review_evidence_digest: digest, finding_id: id }; +const acceptedDispositionSchema = z.object({ ...findingRefShape, disposition: z.literal("accepted"), rationale: nonBlank, revision_intent: nonBlank }).strict(); +const rejectedDispositionSchema = z.object({ ...findingRefShape, disposition: z.literal("rejected"), rationale: nonBlank, evidence: nonBlank }).strict(); +export const triageDispositionSchema = z.discriminatedUnion("disposition", [acceptedDispositionSchema, rejectedDispositionSchema]); +export const triageCandidateSchema = z.object({ + schema_version: z.literal("1"), task_id: id, + phase_instance: z.string().regex(/^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$/u), + step: z.literal("triage"), subject_digest: digest, input_fingerprint: digest, + current_evidence_set_digest: digest, source_evidence_digests: z.array(digest), + dispositions: z.array(triageDispositionSchema), + accepted_count: z.number().int().nonnegative().safe(), rejected_count: z.number().int().nonnegative().safe(), +}).strict(); + +const refKey = (value: FindingRef): string => `${value.review_evidence_digest}:${value.finding_id}`; + +export function validateTriage(current: CurrentReviewSet, candidate: unknown): ValidatedTriage { + if (!authenticCurrentReviewSet(current)) throw new TypeError("an authenticated current review set is required"); + assertPlainJson(candidate, "review triage"); + const parsed = triageCandidateSchema.parse(candidate); + if (parsed.task_id !== current.task_id || parsed.phase_instance !== current.phase_instance || parsed.subject_digest !== current.subject_digest || parsed.input_fingerprint !== current.input_fingerprint || parsed.current_evidence_set_digest !== current.current_evidence_set.set_digest) throw new TypeError("triage scope does not match current review set"); + const expectedDigests = current.current_evidence_set.slots.map((slot) => slot.evidence_digest); + if (parsed.source_evidence_digests.length !== expectedDigests.length || parsed.source_evidence_digests.some((digestValue, index) => digestValue !== expectedDigests[index])) throw new TypeError("source_evidence_digests must exactly match canonical current slots"); + const expected = new Set(); + for (const review of current.reviews) { + const localIds = new Set(); + for (const finding of review.evidence.findings) { + if (localIds.has(finding.finding_id)) throw new TypeError(`review ${review.evidence_digest} has duplicate finding_id ${finding.finding_id}`); + localIds.add(finding.finding_id); + expected.add(refKey({ review_evidence_digest: review.evidence_digest, finding_id: finding.finding_id })); + } + } + const actual = new Set(); + for (const disposition of parsed.dispositions) { + const key = refKey(disposition); + if (actual.has(key)) throw new TypeError(`duplicate triage disposition ${key}`); + if (!expected.has(key)) throw new TypeError(`foreign or stale triage disposition ${key}`); + actual.add(key); + } + if (actual.size !== expected.size || [...expected].some((key) => !actual.has(key))) throw new TypeError("triage dispositions must exactly cover every current finding"); + const accepted = parsed.dispositions.filter((value) => value.disposition === "accepted").length; + const rejected = parsed.dispositions.length - accepted; + if (parsed.accepted_count !== accepted || parsed.rejected_count !== rejected) throw new TypeError("triage disposition counts are contradictory"); + const validated = Object.freeze({ ...parsed, source_evidence_digests: Object.freeze([...parsed.source_evidence_digests]), dispositions: Object.freeze(parsed.dispositions.map((value) => Object.freeze({ ...value }))) }) as ValidatedTriage; + registerValidatedTriage(validated); + return validated; +} diff --git a/src/contracts/trust.ts b/src/contracts/trust.ts new file mode 100644 index 00000000..79dfd808 --- /dev/null +++ b/src/contracts/trust.ts @@ -0,0 +1,245 @@ +import { createHash } from "node:crypto"; +import { z } from "zod"; + +import type { AdjudicationEvidence, DegradedAdjudication, AgentDeclaredAdjudication, ServerAttestedAdjudication } from "./adjudication.js"; +import { adjudicationEvidenceSchema, parseAndDeriveAdjudication, parseReferencedAdjudicationEvidence } from "./adjudication.js"; +import type { ReferencedEvidence, Sha256Digest } from "./evidence.js"; +import { parseSha256Digest } from "./evidence.js"; +import { + authenticAuthorityLink, + authenticCurrentReviewSetAuthority, + authenticQualifiedEvidence, + authenticVerifiedEvidence, + authorityLinkBrand, + currentReviewSetAuthorityBrand, + currentReviewSetBrand, + observationCapabilityBinding, + observationCapabilityBrand, + qualifiedEvidenceBrand, + registerCurrentReviewSet, + registerQualifiedEvidence, + verifiedReferencedEvidenceBrand, +} from "./internal/trust-brands.js"; +import type { PhaseInstanceId } from "./phase-instance.js"; +import { decodePhaseInstance, encodePhaseInstance } from "./phase-instance.js"; +import type { AgentDeclaredReview, AdapterId, DegradedReview, ModelFamily, ReviewEvidence, ReviewRole, ServerAttestedReview } from "./review.js"; +import { EFFORT_VALUES, parseAndDeriveReview, parseReferencedReviewEvidence, reviewEvidenceSchema } from "./review.js"; +import { assertPlainJson } from "./plain-json.js"; + +export type EvidenceKind = "review" | "adjudication"; +export type Assurance = "agent-declared" | "server-attested" | "degraded"; +export interface EvidenceValueByKindAndAssurance { + readonly review: { readonly "agent-declared": AgentDeclaredReview; readonly "server-attested": ServerAttestedReview; readonly degraded: DegradedReview }; + readonly adjudication: { readonly "agent-declared": AgentDeclaredAdjudication; readonly "server-attested": ServerAttestedAdjudication; readonly degraded: DegradedAdjudication }; +} +export interface EvidenceRoleByKind { readonly review: ReviewRole; readonly adjudication: "adjudication" } +export interface ObservationRoleByKind { readonly review: "counter-review" | "gate-counter-review"; readonly adjudication: "adjudication" } + +export interface ObservationBindingBase { + readonly kind: K; + readonly task_id: string; + readonly phase_instance: PhaseInstanceId; + readonly role: ObservationRoleByKind[K]; + readonly subject_digest: Sha256Digest; + readonly input_fingerprint: Sha256Digest; + readonly invocation_id: string; + readonly envelope_input_digest: Sha256Digest; + readonly result_id: string; + readonly adapter: AdapterId; + readonly cli_version: string; + readonly family: ModelFamily; + readonly model: string; + readonly effort: (typeof EFFORT_VALUES)[number]; +} +export interface ObservationBindingByKind { + readonly review: ObservationBindingBase<"review"> & ({ readonly role: "counter-review" } | { readonly role: "gate-counter-review"; readonly gate_id: string }) & { readonly rubric_digest: Sha256Digest; readonly producer_family: ModelFamily }; + readonly adjudication: ObservationBindingBase<"adjudication"> & { readonly pinned_constitution_digest: Sha256Digest; readonly approved_upstream_digests: readonly Sha256Digest[]; readonly source_evidence_set_digest: Sha256Digest }; +} +export type ObservationCapability = { readonly kind: K; readonly [observationCapabilityBrand]: ObservationBindingByKind[K] }; +export type AdapterObservation = { readonly [P in K]: ObservationBindingByKind[P] & { readonly raw_output_bytes: Uint8Array; readonly raw_output_digest: Sha256Digest } }[K]; + +const sameArray = (left: readonly T[], right: readonly T[]): boolean => left.length === right.length && left.every((value, index) => value === right[index]); +const assertEqual = (actual: unknown, expected: unknown, name: string): void => { if (actual !== expected) throw new TypeError(`${name} does not match observation capability`); }; +function deepFreezeJson(value: T): T { + if (value !== null && typeof value === "object") { + for (const nested of Object.values(value)) deepFreezeJson(nested); + Object.freeze(value); + } + return value; +} +const copyFreezeJson = (value: T): T => deepFreezeJson(structuredClone(value)); +function decodeJson(bytes: Uint8Array): unknown { + const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + return JSON.parse(text) as unknown; +} +const digestBytes = (bytes: Uint8Array): Sha256Digest => parseSha256Digest(createHash("sha256").update(bytes).digest("hex")); +const copiedBytes = (bytes: Uint8Array): Uint8Array => Uint8Array.from(bytes); +function assertAdapterFamily(adapter: AdapterId, family: ModelFamily): void { + const expected = adapter === "claude-cli" ? "claude" : "codex"; + if (family !== expected) throw new TypeError("adapter and model family do not match"); +} +function createObservation(binding: ObservationBindingByKind[K], bytes: Uint8Array, rawOutputDigest: Sha256Digest): AdapterObservation { + const storedBytes = copiedBytes(bytes); + const observation = { ...binding, raw_output_digest: rawOutputDigest } as ObservationBindingByKind[K] & { readonly raw_output_digest: Sha256Digest; readonly raw_output_bytes: Uint8Array }; + Object.defineProperty(observation, "raw_output_bytes", { enumerable: true, configurable: false, get: () => copiedBytes(storedBytes) }); + return Object.freeze(observation) as AdapterObservation; +} + +export interface ObservationSource { + readonly observeReview: (capability: ObservationCapability<"review">, observed_output_bytes: Uint8Array) => Readonly<{ observation: AdapterObservation<"review">; evidence: ServerAttestedReview }>; + readonly observeAdjudication: (capability: ObservationCapability<"adjudication">, observed_output_bytes: Uint8Array) => Readonly<{ observation: AdapterObservation<"adjudication">; evidence: ServerAttestedAdjudication }>; +} + +export const observationSource: ObservationSource = Object.freeze({ + observeReview(capability: ObservationCapability<"review">, observedOutputBytes: Uint8Array) { + const binding = observationCapabilityBinding(capability, "review"); + if (binding === undefined || capability.kind !== "review") throw new TypeError("invalid review observation capability"); + assertAdapterFamily(binding.adapter, binding.family); + const bytes = copiedBytes(observedOutputBytes); + const derived = parseAndDeriveReview(decodeJson(bytes)); + for (const [key, expected] of [["task_id", binding.task_id], ["phase_instance", binding.phase_instance], ["role", binding.role], ["subject_digest", binding.subject_digest], ["input_fingerprint", binding.input_fingerprint], ["rubric_digest", binding.rubric_digest], ["producer_family", binding.producer_family]] as const) assertEqual(derived[key], expected, key); + if (binding.family === binding.producer_family) throw new TypeError("review observation must be opposite-family"); + const raw_output_digest = digestBytes(bytes); + const observation = createObservation<"review">(binding, bytes, raw_output_digest); + const evidence: ServerAttestedReview = copyFreezeJson({ ...derived, assurance: "server-attested", adapter: binding.adapter, cli_version: binding.cli_version, model_family: binding.family, model: binding.model, effort: binding.effort, invocation_id: binding.invocation_id, envelope_input_digest: binding.envelope_input_digest, observed_output_digest: raw_output_digest, result_id: binding.result_id }); + return Object.freeze({ observation, evidence }); + }, + observeAdjudication(capability: ObservationCapability<"adjudication">, observedOutputBytes: Uint8Array) { + const binding = observationCapabilityBinding(capability, "adjudication"); + if (binding === undefined || capability.kind !== "adjudication") throw new TypeError("invalid adjudication observation capability"); + assertAdapterFamily(binding.adapter, binding.family); + const bytes = copiedBytes(observedOutputBytes); + const derived = parseAndDeriveAdjudication(decodeJson(bytes)); + for (const [key, expected] of [["task_id", binding.task_id], ["phase_instance", binding.phase_instance], ["subject_digest", binding.subject_digest], ["input_fingerprint", binding.input_fingerprint], ["pinned_constitution_digest", binding.pinned_constitution_digest], ["source_evidence_set_digest", binding.source_evidence_set_digest]] as const) assertEqual(derived[key], expected, key); + if (!sameArray(derived.approved_upstream_digests, binding.approved_upstream_digests)) throw new TypeError("approved_upstream_digests do not match observation capability"); + const raw_output_digest = digestBytes(bytes); + const observation = createObservation<"adjudication">(binding, bytes, raw_output_digest); + const evidence: ServerAttestedAdjudication = copyFreezeJson({ ...derived, assurance: "server-attested", adapter: binding.adapter, cli_version: binding.cli_version, model_family: binding.family, model: binding.model, effort: binding.effort, invocation_id: binding.invocation_id, envelope_input_digest: binding.envelope_input_digest, observed_output_digest: raw_output_digest, result_id: binding.result_id }); + return Object.freeze({ observation, evidence }); + }, +}); + +export interface ServerAuthorityReferences { readonly kind: "server"; readonly invocation_id: string; readonly result_id: string; readonly receipt_id: string; readonly state_revision: number; readonly envelope_input_digest: Sha256Digest; readonly observed_output_digest: Sha256Digest; readonly result_digest: Sha256Digest } +export interface AgentDeclaredAuthorityReferences { readonly kind: "agent-declared"; readonly result_id: string; readonly result_digest: Sha256Digest; readonly state_revision: number } +export interface DegradedAuthorityReferences { readonly kind: "degraded"; readonly checkpoint_digest: Sha256Digest; readonly checkpoint_revision: number } +export interface AuthorityReferencesByAssurance { readonly "agent-declared": AgentDeclaredAuthorityReferences; readonly "server-attested": ServerAuthorityReferences; readonly degraded: DegradedAuthorityReferences } +export interface AuthorityLinkBase { readonly schema_version: "1"; readonly evidence_kind: K; readonly assurance: A; readonly role: EvidenceRoleByKind[K]; readonly task_id: string; readonly phase_instance: PhaseInstanceId; readonly subject_digest: Sha256Digest; readonly input_fingerprint: Sha256Digest; readonly evidence_digest: Sha256Digest; readonly gate_id?: string; readonly authority: AuthorityReferencesByAssurance[A] } +export type AuthorityLinkData = { readonly [P in K]: { readonly [Q in A]: AuthorityLinkBase }[A] }[K]; +export type AuthorityLink = { readonly [P in K]: { readonly [Q in A]: AuthorityLinkBase & { readonly [authorityLinkBrand]: `${P}:${Q}` } }[A] }[K]; +export type VerifiedReferencedEvidence = { readonly [P in K]: { readonly [Q in A]: ReferencedEvidence & { readonly [verifiedReferencedEvidenceBrand]: `${P}:${Q}` } }[A] }[K]; + +export type ReviewEvidenceSlot = + | Readonly<{ role: "self-review"; evidence_digest: Sha256Digest; assurance: "agent-declared"; producer_family: ModelFamily; reviewer_family: ModelFamily; independence: "same-family-self" }> + | Readonly<{ role: "counter-review"; evidence_digest: Sha256Digest; assurance: "server-attested" | "degraded"; producer_family: ModelFamily; reviewer_family: ModelFamily; independence: "opposite-family" }> + | Readonly<{ role: "gate-counter-review"; evidence_digest: Sha256Digest; assurance: "server-attested" | "degraded"; producer_family: ModelFamily; reviewer_family: ModelFamily; independence: "opposite-family"; gate_id: string }>; +export type RequiredReviewSlots = readonly [Extract, Extract] | readonly [Extract, Extract, Extract]; +export interface CurrentReviewSetAuthority { readonly task_id: string; readonly phase_instance: PhaseInstanceId; readonly subject_digest: Sha256Digest; readonly input_fingerprint: Sha256Digest; readonly slots: RequiredReviewSlots; readonly [currentReviewSetAuthorityBrand]: true } +export interface CurrentEvidenceSetRef { readonly set_digest: Sha256Digest; readonly slots: RequiredReviewSlots } + +const idSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); +const digestSchema = z.string().regex(/^[0-9a-f]{64}$/u) as unknown as z.ZodType; +const phaseSchema = z.string().regex(/^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$/u) as unknown as z.ZodType; +const familySchema = z.enum(["claude", "codex"]); +const safeInteger = z.number().int().nonnegative().safe(); +const agentAuthoritySchema = z.object({ kind: z.literal("agent-declared"), result_id: idSchema, result_digest: digestSchema, state_revision: safeInteger }).strict(); +const serverAuthoritySchema = z.object({ kind: z.literal("server"), invocation_id: idSchema, result_id: idSchema, receipt_id: idSchema, state_revision: safeInteger, envelope_input_digest: digestSchema, observed_output_digest: digestSchema, result_digest: digestSchema }).strict(); +const degradedAuthoritySchema = z.object({ kind: z.literal("degraded"), checkpoint_digest: digestSchema, checkpoint_revision: safeInteger }).strict(); +const authorityReferencesSchema = z.discriminatedUnion("kind", [agentAuthoritySchema, serverAuthoritySchema, degradedAuthoritySchema]); +export const authorityLinkDataSchema = z.object({ schema_version: z.literal("1"), evidence_kind: z.enum(["review", "adjudication"]), assurance: z.enum(["agent-declared", "server-attested", "degraded"]), role: z.enum(["self-review", "counter-review", "gate-counter-review", "adjudication"]), task_id: idSchema, phase_instance: phaseSchema, subject_digest: digestSchema, input_fingerprint: digestSchema, evidence_digest: digestSchema, gate_id: idSchema.optional(), authority: authorityReferencesSchema }).strict().superRefine((link, context) => { + if ((link.evidence_kind === "adjudication") !== (link.role === "adjudication")) context.addIssue({ code: "custom", path: ["role"], message: "role must match evidence kind" }); + const expectedAuthorityKind = link.assurance === "server-attested" ? "server" : link.assurance; + if (link.authority.kind !== expectedAuthorityKind) context.addIssue({ code: "custom", path: ["authority", "kind"], message: "authority references must match assurance" }); + if ((link.role === "gate-counter-review") !== (link.gate_id !== undefined)) context.addIssue({ code: "custom", path: ["gate_id"], message: "gate_id is required only for gate-counter-review authority" }); +}); +const slotBase = { evidence_digest: digestSchema, producer_family: familySchema, reviewer_family: familySchema }; +const selfSlotSchema = z.object({ ...slotBase, role: z.literal("self-review"), assurance: z.literal("agent-declared"), independence: z.literal("same-family-self") }).strict().superRefine((slot, context) => { if (slot.producer_family !== slot.reviewer_family) context.addIssue({ code: "custom", message: "self-review families must match" }); }); +const counterSlotSchema = z.object({ ...slotBase, role: z.literal("counter-review"), assurance: z.enum(["server-attested", "degraded"]), independence: z.literal("opposite-family") }).strict().superRefine((slot, context) => { if (slot.producer_family === slot.reviewer_family) context.addIssue({ code: "custom", message: "counter-review families must differ" }); }); +const gateCounterSlotSchema = z.object({ ...slotBase, role: z.literal("gate-counter-review"), assurance: z.enum(["server-attested", "degraded"]), independence: z.literal("opposite-family"), gate_id: idSchema }).strict().superRefine((slot, context) => { if (slot.producer_family === slot.reviewer_family) context.addIssue({ code: "custom", message: "gate-counter-review families must differ" }); }); +export const requiredReviewSlotsSchema = z.union([z.tuple([selfSlotSchema, counterSlotSchema]), z.tuple([selfSlotSchema, counterSlotSchema, gateCounterSlotSchema])]); +export const currentEvidenceSetRefSchema = z.object({ set_digest: digestSchema, slots: requiredReviewSlotsSchema }).strict(); +export const referencedEvidenceSchema = z.union([ + z.object({ evidence_digest: digestSchema, evidence: reviewEvidenceSchema }).strict(), + z.object({ evidence_digest: digestSchema, evidence: adjudicationEvidenceSchema }).strict(), +]); +export function parseAuthorityLinkData(value: unknown): AuthorityLinkData { assertPlainJson(value, "authority link data"); return authorityLinkDataSchema.parse(value) as AuthorityLinkData; } +export function parseRequiredReviewSlots(value: unknown): RequiredReviewSlots { assertPlainJson(value, "required review slots"); const slots = requiredReviewSlotsSchema.parse(value) as RequiredReviewSlots; validateSlots(slots); return slots; } +export function parseCurrentEvidenceSetRef(value: unknown): CurrentEvidenceSetRef { assertPlainJson(value, "current evidence set reference"); const parsed = currentEvidenceSetRefSchema.parse(value); validateSlots(parsed.slots); return parsed as CurrentEvidenceSetRef; } +export function parseReferencedEvidence(value: unknown): ReferencedEvidence { + assertPlainJson(value, "referenced evidence"); + if (typeof value !== "object" || value === null || !("evidence" in value)) throw new TypeError("referenced evidence wrapper is required"); + const evidence = value.evidence; + if (typeof evidence !== "object" || evidence === null || !("step" in evidence)) throw new TypeError("referenced evidence kind is required"); + return evidence.step === "adjudicate" ? parseReferencedAdjudicationEvidence(value) : parseReferencedReviewEvidence(value); +} + +export type QualifiedReviewEvidenceByAssurance = { readonly [A in Assurance]: VerifiedReferencedEvidence<"review", A> & { readonly authority: AuthorityLink<"review", A>; readonly [qualifiedEvidenceBrand]: `review:${A}` } }; +export type QualifiedReviewEvidence = QualifiedReviewEvidenceByAssurance[Assurance]; +export type QualifiedAdjudicationEvidenceByAssurance = { readonly [A in Assurance]: VerifiedReferencedEvidence<"adjudication", A> & { readonly authority: AuthorityLink<"adjudication", A>; readonly [qualifiedEvidenceBrand]: `adjudication:${A}` } }; +export type QualifiedAdjudicationEvidence = QualifiedAdjudicationEvidenceByAssurance[Assurance]; +export interface CurrentReviewSet { readonly task_id: string; readonly phase_instance: PhaseInstanceId; readonly subject_digest: Sha256Digest; readonly input_fingerprint: Sha256Digest; readonly current_evidence_set: CurrentEvidenceSetRef; readonly reviews: readonly QualifiedReviewEvidence[]; readonly [currentReviewSetBrand]: true } + +function assertLinkMatches(kind: K, link: AuthorityLink, value: VerifiedReferencedEvidence): void { + const authenticatedAssurance = (["agent-declared", "server-attested", "degraded"] as const).find((assurance) => + authenticAuthorityLink(link, { kind, assurance }) && authenticVerifiedEvidence(value, { kind, assurance }) + ); + if (authenticatedAssurance === undefined) throw new TypeError("untrusted authority link or verified evidence"); + const evidence = value.evidence as ReviewEvidence | AdjudicationEvidence; + if (evidence.assurance !== authenticatedAssurance || link.assurance !== authenticatedAssurance) throw new TypeError("authority assurance does not match authenticated identity"); + const expectedAuthorityKind = evidence.assurance === "server-attested" ? "server" : evidence.assurance; + if (link.authority.kind !== expectedAuthorityKind) throw new TypeError("authority references do not match assurance"); + const phaseInstance = encodePhaseInstance(decodePhaseInstance(evidence.phase_instance)); + if (link.evidence_kind !== kind || link.assurance !== evidence.assurance || link.evidence_digest !== value.evidence_digest || link.task_id !== evidence.task_id || link.phase_instance !== phaseInstance || link.subject_digest !== evidence.subject_digest || link.input_fingerprint !== evidence.input_fingerprint) throw new TypeError("authority link does not match verified evidence"); + if (link.role !== (kind === "review" ? (evidence as ReviewEvidence).role : "adjudication")) throw new TypeError("authority role does not match evidence"); + if ((link.role === "gate-counter-review") !== (link.gate_id !== undefined)) throw new TypeError("authority gate binding does not match role"); + if (evidence.assurance === "server-attested") { + if (link.authority.kind !== "server" + || link.authority.invocation_id !== evidence.invocation_id + || link.authority.result_id !== evidence.result_id + || link.authority.envelope_input_digest !== evidence.envelope_input_digest + || link.authority.observed_output_digest !== evidence.observed_output_digest) { + throw new TypeError("server authority provenance does not match evidence"); + } + } +} +function validateSlots(slots: readonly ReviewEvidenceSlot[]): asserts slots is RequiredReviewSlots { + if ((slots.length !== 2 && slots.length !== 3) || slots[0]?.role !== "self-review" || slots[1]?.role !== "counter-review" || (slots.length === 3 && slots[2]?.role !== "gate-counter-review")) throw new TypeError("review slots must use canonical role order"); + for (const slot of slots) { + if (slot.role === "self-review") { if (slot.assurance !== "agent-declared" || slot.independence !== "same-family-self" || slot.producer_family !== slot.reviewer_family) throw new TypeError("invalid self-review slot"); } + else if (slot.independence !== "opposite-family" || slot.producer_family === slot.reviewer_family) throw new TypeError("invalid opposite-family review slot"); + } + if (new Set(slots.map((slot) => slot.evidence_digest)).size !== slots.length) throw new TypeError("review slot evidence digests must be unique"); +} +const currentSetDigest = (slots: RequiredReviewSlots): Sha256Digest => parseSha256Digest(createHash("sha256").update(JSON.stringify(slots)).digest("hex")); + +export interface AuthorityQualifier { + readonly qualifyReview: (link: AuthorityLink<"review", A>, value: NoInfer>) => QualifiedReviewEvidenceByAssurance[A]; + readonly qualifyAdjudication: (link: AuthorityLink<"adjudication", A>, value: NoInfer>) => QualifiedAdjudicationEvidenceByAssurance[A]; + readonly currentReviews: (authority: CurrentReviewSetAuthority, reviews: readonly QualifiedReviewEvidence[]) => CurrentReviewSet; +} +export const authorityQualifier: AuthorityQualifier = Object.freeze({ + qualifyReview(link: AuthorityLink<"review", A>, value: NoInfer>): QualifiedReviewEvidenceByAssurance[A] { + assertLinkMatches("review", link, value); + const qualified = Object.freeze({ ...value, authority: link }) as QualifiedReviewEvidenceByAssurance[A]; + registerQualifiedEvidence(qualified, { kind: "review", assurance: link.assurance }); + return qualified; + }, + qualifyAdjudication(link: AuthorityLink<"adjudication", A>, value: NoInfer>): QualifiedAdjudicationEvidenceByAssurance[A] { + assertLinkMatches("adjudication", link, value); + const qualified = Object.freeze({ ...value, authority: link }) as QualifiedAdjudicationEvidenceByAssurance[A]; + registerQualifiedEvidence(qualified, { kind: "adjudication", assurance: link.assurance }); + return qualified; + }, + currentReviews(authority: CurrentReviewSetAuthority, reviews: readonly QualifiedReviewEvidence[]): CurrentReviewSet { + if (!authenticCurrentReviewSetAuthority(authority)) throw new TypeError("invalid current review set authority"); + validateSlots(authority.slots); + if (reviews.length !== authority.slots.length) throw new TypeError("reviews must exactly cover required slots"); + authority.slots.forEach((slot, index) => { + const review = reviews[index]; + if (review === undefined || !authenticQualifiedEvidence(review, "review") || !authenticQualifiedEvidence(review, "review", review.evidence.assurance) || review.evidence_digest !== slot.evidence_digest || review.evidence.role !== slot.role || review.evidence.assurance !== slot.assurance || review.evidence.producer_family !== slot.producer_family || review.evidence.model_family !== slot.reviewer_family || review.authority.task_id !== authority.task_id || review.authority.phase_instance !== authority.phase_instance || review.authority.subject_digest !== authority.subject_digest || review.authority.input_fingerprint !== authority.input_fingerprint || (slot.role === "gate-counter-review" && review.authority.gate_id !== slot.gate_id)) throw new TypeError(`review does not match slot ${index}`); + }); + const slots = copyFreezeJson(authority.slots); + const current = Object.freeze({ task_id: authority.task_id, phase_instance: authority.phase_instance, subject_digest: authority.subject_digest, input_fingerprint: authority.input_fingerprint, current_evidence_set: Object.freeze({ set_digest: currentSetDigest(slots), slots }), reviews: Object.freeze([...reviews]) }) as CurrentReviewSet; + registerCurrentReviewSet(current); + return current; + }, +}); diff --git a/src/contracts/validators.ts b/src/contracts/validators.ts index 19121cba..9788af6d 100644 --- a/src/contracts/validators.ts +++ b/src/contracts/validators.ts @@ -25,18 +25,127 @@ function formatAjvErrors(errors: ErrorObject[] | null | undefined): string { return errors.map((error) => `${error.instancePath || "/"} ${error.message ?? error.keyword}`).join("; "); } -function hasUniqueObjectPropertyValues(property: string, data: unknown[]): boolean { - const seen = new Set(); +function hasUniqueObjectPropertyValues(properties: string | readonly string[], data: unknown[]): boolean { + const propertyNames = typeof properties === "string" ? [properties] : properties; + const seen: unknown[][] = []; for (const item of data) { if (typeof item !== "object" || item === null) continue; - const descriptor = Object.getOwnPropertyDescriptor(item, property); - const value = descriptor !== undefined && "value" in descriptor ? descriptor.value : undefined; - if (seen.has(value)) return false; - seen.add(value); + const values = propertyNames.map((property) => { + const descriptor = Object.getOwnPropertyDescriptor(item, property); + return descriptor !== undefined && "value" in descriptor ? descriptor.value : undefined; + }); + if (seen.some((candidate) => isDeepStrictEqual(candidate, values))) return false; + seen.push(values); + } + return true; +} + +function hasBoundedUtf8Length(maximumBytes: number, data: string): boolean { + return Buffer.byteLength(data, "utf8") <= maximumBytes; +} + +function isOrdinalSortedUnique(_enabled: true, data: string[]): boolean { + return data.every((value, index) => index === 0 || data[index - 1]! < value); +} + +function hasConsistentReviewSummary(_enabled: true, data: Record): boolean { + if (!Array.isArray(data.findings)) return true; + const blockingCount = data.findings.filter((finding) => typeof finding === "object" && finding !== null && (finding as Record).blocking === true).length; + const verdict = blockingCount > 0 ? "fail" : data.findings.length > 0 ? "advisory" : "pass"; + return data.blocking_count === blockingCount && data.verdict === verdict; +} + +function hasConsistentAdjudicationSemantics(_enabled: true, data: Record): boolean { + if (!Array.isArray(data.rule_findings) || !Array.isArray(data.drift_findings) || !Array.isArray(data.approved_upstream_digests)) return true; + const ruleKey = (rule: Record): string => `${String(rule.rule_id)}:${String(rule.rule_version)}`; + const sortedUnique = (values: readonly string[]): boolean => values.every((value, index) => index === 0 || values[index - 1]! < value); + const ruleFindings = data.rule_findings as Record[]; + const driftFindings = data.drift_findings as Record[]; + const upstream = data.approved_upstream_digests as string[]; + if (!sortedUnique(upstream) || !sortedUnique(ruleFindings.map(ruleKey)) || !sortedUnique(driftFindings.map((finding) => String(finding.upstream_digest)))) return false; + if (driftFindings.length !== upstream.length || driftFindings.some((finding, index) => finding.upstream_digest !== upstream[index])) return false; + for (const finding of ruleFindings) { + if (!Array.isArray(finding.enforced_by)) return false; + if (finding.compliance === "pass" && finding.enforced_by.length === 0) return false; + for (const evidence of finding.enforced_by as Record[]) { + if (evidence.state === "current" && evidence.subject_digest !== data.subject_digest) return false; + if (evidence.state !== "current" && finding.compliance === "pass") return false; + } } + const constitution = ruleFindings.some((finding) => finding.compliance === "fail") ? "fail" : ruleFindings.some((finding) => finding.compliance === "uncertain") ? "uncertain" : "pass"; + if (data.constitution !== constitution) return false; + const drift = driftFindings.some((finding) => finding.drift === "material") ? "material" : driftFindings.some((finding) => finding.drift === "incidental") ? "incidental" : "aligned"; + if (data.drift !== drift) return false; + const matched = ruleFindings.filter((finding) => finding.trigger === "matched").map(ruleKey); + const uncertain = ruleFindings.filter((finding) => finding.trigger === "uncertain").map(ruleKey); + const actualMatched = Array.isArray(data.matched_rule_versions) ? (data.matched_rule_versions as Record[]).map(ruleKey) : []; + const actualUncertain = Array.isArray(data.uncertain_rule_versions) ? (data.uncertain_rule_versions as Record[]).map(ruleKey) : []; + return isDeepStrictEqual(actualMatched, matched) && isDeepStrictEqual(actualUncertain, uncertain); +} + +const record = (value: unknown): Record | undefined => typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : undefined; +const ruleKey = (value: unknown): string => { const item = record(value); return `${String(item?.rule_id)}:${String(item?.rule_version)}`; }; +const sortedUniqueBy = (values: unknown, key: (value: unknown) => string = String): boolean => Array.isArray(values) && values.every((value, index) => index === 0 || key(values[index - 1]) < key(value)); + +function hasGateContextSemantics(kind: unknown, contextValue: unknown): boolean { + const context = record(contextValue); + if (context === undefined) return true; + if (kind === "review-trigger" || kind === "adjudication-failure") { + const primary = kind === "review-trigger" ? context.matched_rules : context.failed_rules; + if (!sortedUniqueBy(primary, ruleKey) || !sortedUniqueBy(context.uncertain_rules, ruleKey) || !sortedUniqueBy(context.eligible_waiver_rules, ruleKey)) return false; + const available = new Set([...(primary as unknown[]), ...(context.uncertain_rules as unknown[])].map(ruleKey)); + if ((context.eligible_waiver_rules as unknown[]).some((item) => !available.has(ruleKey(item)))) return false; + if (kind === "adjudication-failure" && available.size === 0) return false; + return record(context.waiver_scope)?.operation === kind; + } + if (kind === "attempts-exhausted") return typeof context.attempts === "number" && typeof context.maximum_attempts === "number" && context.attempts >= context.maximum_attempts; + if (kind === "material-drift") return sortedUniqueBy(context.affected_claim_ids); + if (kind === "commit-authorization") return sortedUniqueBy(context.current_artifact_digests) && sortedUniqueBy(context.parent_document_digests); + return true; +} + +function hasGateSemantics(_enabled: true, data: Record): boolean { + if (!hasGateContextSemantics(data.kind, data.context)) return false; + const context = record(data.context); const payload = record(data.payload); + if (context === undefined || payload === undefined) return true; + if ((data.kind === "review-trigger" || data.kind === "adjudication-failure") && payload.decision === "waiver-requested") { + return Array.isArray(context.eligible_waiver_rules) && context.eligible_waiver_rules.some((item) => ruleKey(item) === ruleKey(payload.rule)); + } + if (data.kind === "adjudication-failure" && payload.decision === "approve") { + const eligible = new Set((context.eligible_waiver_rules as unknown[]).map(ruleKey)); + const required = new Set([...(context.failed_rules as unknown[]), ...(context.uncertain_rules as unknown[])].map(ruleKey).filter((key) => !eligible.has(key))); + if (!sortedUniqueBy(payload.resolutions, (item) => ruleKey(record(item)?.rule))) return false; + const actual = (payload.resolutions as unknown[]).map((item) => ruleKey(record(item)?.rule)); + return actual.length === required.size && actual.every((key) => required.has(key)); + } + if (data.kind === "restore-collision" && payload.decision === "adopt-as-new-generation") return isDeepStrictEqual(payload.adoption_authority, context.adoption_candidate); + return true; +} + +function hasSupplementalSemantics(_enabled: true, data: Record): boolean { + const review = record(data.review); + if (review === undefined) return true; + const slot = record(review.evidence_slot); + if (slot === undefined || slot.gate_id !== review.prior_gate_id || slot.producer_family === slot.reviewer_family) return false; + return data.action !== "supersede" || (data.old_subject_digest === review.subject_digest && data.new_subject_digest !== data.old_subject_digest); +} + +function hasExactCurrentEvidence(value: unknown): boolean { + const current = record(value); if (current === undefined || !Array.isArray(current.slots)) return false; + const slots = current.slots.map(record); if (slots.some((slot) => slot === undefined) || (slots.length !== 2 && slots.length !== 3)) return false; + if (slots[0]!.role !== "self-review" || slots[1]!.role !== "counter-review" || (slots.length === 3 && slots[2]!.role !== "gate-counter-review")) return false; + if (slots[0]!.producer_family !== slots[0]!.reviewer_family || slots.slice(1).some((slot) => slot!.producer_family === slot!.reviewer_family)) return false; + return new Set(slots.map((slot) => slot!.evidence_digest)).size === slots.length; +} + +function hasMcpSemantics(_enabled: true, data: Record): boolean { + if ("kind" in data && "current_evidence" in data) return hasExactCurrentEvidence(data.current_evidence) && hasGateContextSemantics(data.kind, data.context); + if ("origin" in data) return record(data.origin)?.task_id === data.task_id; return true; } +function hasResultExpectationSemantics(_enabled: true, data: Record): boolean { return record(data.success)?.revision === data.resulting_revision; } + export function createJsonSchemaValidator( schema: AnySchema, referencedSchemas: readonly AnySchema[] = [] @@ -54,12 +163,65 @@ export function createJsonSchemaValidator( addFormats(ajv); ajv.addKeyword({ keyword: "x-archflow-unique-by", - schemaType: "string", - metaSchema: { type: "string", minLength: 1 }, + schemaType: ["string", "array"], + metaSchema: { + oneOf: [ + { type: "string", minLength: 1 }, + { type: "array", minItems: 1, uniqueItems: true, items: { type: "string", minLength: 1 } } + ] + }, type: "array", errors: false, validate: hasUniqueObjectPropertyValues }); + ajv.addKeyword({ + keyword: "x-archflow-max-utf8-bytes", + schemaType: "number", + metaSchema: { type: "integer", minimum: 0 }, + type: "string", + errors: false, + validate: hasBoundedUtf8Length + }); + ajv.addKeyword({ + keyword: "x-archflow-effect", + schemaType: "string", + metaSchema: { + type: "string", + enum: ["advance", "retry", "redirect-waiver", "redirect-upstream", "non-advancing"] + }, + errors: false, + valid: true + }); + ajv.addKeyword({ + keyword: "x-archflow-sorted-unique", + schemaType: "boolean", + metaSchema: { const: true }, + type: "array", + errors: false, + validate: isOrdinalSortedUnique + }); + ajv.addKeyword({ + keyword: "x-archflow-review-summary", + schemaType: "boolean", + metaSchema: { const: true }, + type: "object", + errors: false, + validate: hasConsistentReviewSummary + }); + ajv.addKeyword({ + keyword: "x-archflow-adjudication-semantics", + schemaType: "boolean", + metaSchema: { const: true }, + type: "object", + errors: false, + validate: hasConsistentAdjudicationSemantics + }); + for (const [keyword, validate] of [ + ["x-archflow-gate-semantics", hasGateSemantics], + ["x-archflow-supplemental-semantics", hasSupplementalSemantics], + ["x-archflow-mcp-semantics", hasMcpSemantics], + ["x-archflow-result-expectation-semantics", hasResultExpectationSemantics] + ] as const) ajv.addKeyword({ keyword, schemaType: "boolean", metaSchema: { const: true }, type: "object", errors: false, validate }); for (const referencedSchema of referencedSchemas) ajv.addSchema(referencedSchema); const validate = ajv.compile(schema); const assert = (value: unknown, label = "value"): T => { diff --git a/src/contracts/versions.ts b/src/contracts/versions.ts index 2bb5e2bf..40c5c542 100644 --- a/src/contracts/versions.ts +++ b/src/contracts/versions.ts @@ -6,5 +6,21 @@ export const SCHEMA_IDS = { workflow: "urn:archflow:schema:v1:workflow", config: "urn:archflow:schema:v1:config", rubric: "urn:archflow:schema:v1:rubric", - constitutionRule: "urn:archflow:schema:v1:constitution-rule" + constitutionRule: "urn:archflow:schema:v1:constitution-rule", + review: "urn:archflow:schema:v1:review", + reviewEvidence: "urn:archflow:schema:v1:review-evidence", + adjudication: "urn:archflow:schema:v1:adjudication", + adjudicationEvidence: "urn:archflow:schema:v1:adjudication-evidence", + evidenceReference: "urn:archflow:schema:v1:evidence-reference", + authorityLink: "urn:archflow:schema:v1:authority-link", + evidenceSlots: "urn:archflow:schema:v1:evidence-slots", + triage: "urn:archflow:schema:v1:triage", + supplementalReview: "urn:archflow:schema:v1:supplemental-review", + gateContract: "urn:archflow:schema:v1:gate-contract", + gateDecision: "urn:archflow:schema:v1:gate-decision", + projectError: "urn:archflow:schema:v1:project-error", + protocolError: "urn:archflow:schema:v1:protocol-error", + mcpTools: "https://archflow.dev/schemas/v1/mcp-tools", + resultExpectation: "https://archflow.dev/schemas/v1/result-expectation", + pathClaim: "urn:archflow:schema:v1:path-claim" } as const; diff --git a/test/contracts/gate-error-schema-agreement.test.ts b/test/contracts/gate-error-schema-agreement.test.ts new file mode 100644 index 00000000..d3153f01 --- /dev/null +++ b/test/contracts/gate-error-schema-agreement.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vitest"; + +import { createJsonSchemaValidator } from "../../src/contracts/validators.js"; +import gateContractSchema from "../../src/contracts/schemas/v1/gate-contract.schema.json" with { type: "json" }; +import gateDecisionSchema from "../../src/contracts/schemas/v1/gate-decision.schema.json" with { type: "json" }; +import projectErrorSchema from "../../src/contracts/schemas/v1/project-error.schema.json" with { type: "json" }; +import protocolErrorSchema from "../../src/contracts/schemas/v1/protocol-error.schema.json" with { type: "json" }; +import primitivesSchema from "../../src/contracts/schemas/v1/primitives.schema.json" with { type: "json" }; +import supplementalSchema from "../../src/contracts/schemas/v1/supplemental-review.schema.json" with { type: "json" }; +import { createProjectError, createProtocolError, parseProjectError } from "../../src/contracts/errors.js"; +import { parseGateContract } from "../../src/contracts/gates.js"; +import { parseSupplementalReviewOutcome } from "../../src/contracts/supplemental.js"; + +const D = "a".repeat(64); +const gateValidator = createJsonSchemaValidator(gateContractSchema, [primitivesSchema]); +const decisionValidator = createJsonSchemaValidator(gateDecisionSchema, [primitivesSchema, gateContractSchema]); +const projectValidator = createJsonSchemaValidator(projectErrorSchema); +const protocolValidator = createJsonSchemaValidator(protocolErrorSchema); +const supplementalValidator = createJsonSchemaValidator(supplementalSchema, [primitivesSchema]); + +describe("gate and error JSON Schema authority", () => { + it("accepts a correlated gate contract and rejects cross-kind/unknown fields", () => { + const value = { kind: "commit-authorization", context: { target_ref: "refs-heads-task", diff_digest: D, current_artifact_digests: [D], parent_document_digests: [D] }, payload: { decision: "authorize-commit", reason: "Approved" } }; + expect(gateValidator.validate(value)).toBe(true); + expect(gateValidator.validate({ ...value, payload: { decision: "waiver-requested", reason: "No", rule: { rule_id: "rule", rule_version: 1 }, rationale: "No" } })).toBe(false); + expect(gateValidator.validate({ ...value, context: { ...value.context, gate_id: "forged" } })).toBe(false); + }); + + it("enforces semantic gate correlations in both authorities", () => { + const invalid = [ + { kind: "attempts-exhausted", context: { step: "produce", attempts: 1, maximum_attempts: 2 }, payload: { decision: "abort", reason: "Stop" } }, + { kind: "review-trigger", context: { matched_rules: [{ rule_id: "z", rule_version: 1 }, { rule_id: "a", rule_version: 1 }], uncertain_rules: [], eligible_waiver_rules: [], waiver_scope: { operation: "review-trigger", boundary: "subject" } }, payload: { decision: "approve", reason: "No" } }, + { kind: "adjudication-failure", context: { constitution: "fail", failed_rules: [{ rule_id: "rule", rule_version: 1 }], uncertain_rules: [], eligible_waiver_rules: [], waiver_scope: { operation: "adjudication-failure", boundary: "phase" } }, payload: { decision: "approve", reason: "Handled", resolutions: [] } } + ]; + for (const value of invalid) { expect(gateValidator.validate(value)).toBe(false); expect(() => parseGateContract(value)).toThrow(); } + }); + + it("enforces supplemental gate and subject correlations in both authorities", () => { + const review = { prior_gate_id: "Gate:1", task_id: "Task_1", phase_instance: "phase-impl-2", subject_digest: D, input_fingerprint: D, evidence_slot: { role: "gate-counter-review", evidence_digest: "b".repeat(64), assurance: "degraded", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family", gate_id: "Gate:1" } }; + const valid = { action: "supersede", review, accepted_triage_digest: D, old_subject_digest: D, new_subject_digest: "c".repeat(64), reason: "Revise" }; + expect(supplementalValidator.validate(valid)).toBe(true); + expect(parseSupplementalReviewOutcome(valid).action).toBe("supersede"); + for (const value of [{ ...valid, review: { ...review, evidence_slot: { ...review.evidence_slot, gate_id: "Gate:2" } } }, { ...valid, new_subject_digest: D }, { ...valid, old_subject_digest: "d".repeat(64) }]) { + expect(supplementalValidator.validate(value)).toBe(false); + expect(() => parseSupplementalReviewOutcome(value)).toThrow(); + } + }); + + it("accepts a closed kind-correlated decision envelope", () => { + const envelope = { schema_version: "1", gate_id: "gate-1", task_id: "task-1", phase_instance: "phase-impl-2", subject_digest: D, context_digest: D, human_provenance: { schema_version: "1", actor_class: "human", assurance: "declared-local-trace", channel: "archflow-local", decision_event_id: "decision-1", helper_invocation_id: "helper-1", recorded_at: "2026-07-27T12:00:00.000Z" }, kind: "artifact-approval", payload: { decision: "approve", reason: "Approved" } }; + expect(decisionValidator.validate(envelope)).toBe(true); + expect(decisionValidator.validate({ ...envelope, payload: { decision: "authorize-commit", reason: "No" } })).toBe(false); + }); + + it("agrees with both exhaustive serialized error registries", () => { + const project = createProjectError("STATE_CONFLICT", { expected_revision: 1, observed_revision: 2 }); + const protocol = createProtocolError("TOOL_NOT_FOUND", { tool_name_digest: D }); + expect(projectValidator.validate(project)).toBe(true); + expect(protocolValidator.validate(protocol)).toBe(true); + expect(projectValidator.validate({ ...project, owner: "protocol" })).toBe(false); + expect(protocolValidator.validate({ ...protocol, diagnostic: { ...protocol.diagnostic, parameters: { tool_name_digest: D, raw_name: "secret" } } })).toBe(false); + }); + + it("makes SNAPSHOT_LIMIT paths lexical, sorted, and unique in both authorities", () => { + const error = (offending_paths: string[]) => ({ schema_version: "1", code: "SNAPSHOT_LIMIT", owner: "snapshot", retryable: false, diagnostic: { template_id: "SNAPSHOT_LIMIT", parameters: { limit_scope: "task", offending_paths, current_bytes: 2, byte_cap: 1 } }, next_action: "reduce-snapshot" }); + expect(projectValidator.validate(error(["a/file", "z/file"]))).toBe(true); + for (const paths of [["z/file", "a/file"], ["a/file", "a/file"], ["../escape"], ["a/../escape"], ["a/\u0080bad"]]) { + const value = error(paths); + expect(projectValidator.validate(value), JSON.stringify(projectValidator.validate.errors)).toBe(false); + expect(() => parseProjectError(value)).toThrow(); + } + }); +}); diff --git a/test/contracts/gate-error-supplemental-exhaustive.test.ts b/test/contracts/gate-error-supplemental-exhaustive.test.ts new file mode 100644 index 00000000..c60a10a2 --- /dev/null +++ b/test/contracts/gate-error-supplemental-exhaustive.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, it } from "vitest"; + +import { PROJECT_ERROR_DEFINITIONS, PROTOCOL_ERROR_DEFINITIONS, parseProjectError, parseProtocolError } from "../../src/contracts/errors.js"; +import { gateDecisionEffect, parseGateContract, parseGateDecisionEnvelope, type GateEffect } from "../../src/contracts/gates.js"; +import gateContractSchema from "../../src/contracts/schemas/v1/gate-contract.schema.json" with { type: "json" }; +import gateDecisionSchema from "../../src/contracts/schemas/v1/gate-decision.schema.json" with { type: "json" }; +import primitivesSchema from "../../src/contracts/schemas/v1/primitives.schema.json" with { type: "json" }; +import projectErrorSchema from "../../src/contracts/schemas/v1/project-error.schema.json" with { type: "json" }; +import protocolErrorSchema from "../../src/contracts/schemas/v1/protocol-error.schema.json" with { type: "json" }; +import supplementalSchema from "../../src/contracts/schemas/v1/supplemental-review.schema.json" with { type: "json" }; +import { parseSupplementalReviewOutcome } from "../../src/contracts/supplemental.js"; +import { createJsonSchemaValidator } from "../../src/contracts/validators.js"; + +type JsonObject = Record; +type ErrorDefinition = { readonly owner: string; readonly retryable: boolean; readonly action: string; readonly projection: string; readonly parameter_parser: { readonly parse: (value: unknown) => Readonly> } }; + +const D = (character = "a"): string => character.repeat(64); +const RULE = { rule_id: "trust-boundary", rule_version: 1 }; +const AUTHORITY = { link_digest: D("a"), purpose: "restore-adoption", proposed_generation_digest: D("b"), changed_input_fingerprint: D("c") }; +const gateValidator = createJsonSchemaValidator(gateContractSchema, [primitivesSchema]); +const decisionValidator = createJsonSchemaValidator(gateDecisionSchema, [primitivesSchema, gateContractSchema]); +const projectValidator = createJsonSchemaValidator(projectErrorSchema); +const protocolValidator = createJsonSchemaValidator(protocolErrorSchema); +const supplementalValidator = createJsonSchemaValidator(supplementalSchema, [primitivesSchema]); + +const gateCases: readonly JsonObject[] = [ + ...["approve", "revise", "reject"].map((decision) => ({ kind: "artifact-approval", context: { artifact_kind: "prd" }, payload: { decision, reason: "Reviewed" } })), + ...["approve", "revise", "reject"].map((decision) => ({ kind: "review-trigger", context: { matched_rules: [RULE], uncertain_rules: [], eligible_waiver_rules: [RULE], waiver_scope: { operation: "review-trigger", boundary: "subject" } }, payload: { decision, reason: "Reviewed" } })), + { kind: "review-trigger", context: { matched_rules: [RULE], uncertain_rules: [], eligible_waiver_rules: [RULE], waiver_scope: { operation: "review-trigger", boundary: "subject" } }, payload: { decision: "waiver-requested", reason: "Exception", rule: RULE, rationale: "Task-scoped exception" } }, + ...["amend-upstream", "revise-current", "reject"].map((decision) => ({ kind: "material-drift", context: { affected_upstream: { kind: "architecture", digest: D("a") }, drift: "material", affected_claim_ids: ["claim-one"] }, payload: { decision, reason: "Reviewed" } })), + { kind: "adjudication-failure", context: { constitution: "fail", failed_rules: [RULE], uncertain_rules: [], eligible_waiver_rules: [RULE], waiver_scope: { operation: "adjudication-failure", boundary: "phase" } }, payload: { decision: "approve", reason: "Resolved", resolutions: [] } }, + ...["revise", "reject"].map((decision) => ({ kind: "adjudication-failure", context: { constitution: "fail", failed_rules: [RULE], uncertain_rules: [], eligible_waiver_rules: [RULE], waiver_scope: { operation: "adjudication-failure", boundary: "phase" } }, payload: { decision, reason: "Reviewed" } })), + { kind: "adjudication-failure", context: { constitution: "fail", failed_rules: [RULE], uncertain_rules: [], eligible_waiver_rules: [RULE], waiver_scope: { operation: "adjudication-failure", boundary: "phase" } }, payload: { decision: "waiver-requested", reason: "Exception", rule: RULE, rationale: "Task-scoped exception" } }, + ...["retry-once", "revise", "abort"].map((decision) => ({ kind: "attempts-exhausted", context: { step: "counter_review", attempts: 2, maximum_attempts: 2 }, payload: { decision, reason: "Reviewed" } })), + ...["revert-edit", "start-base-amendment", "abort"].map((decision) => ({ kind: "constitution-edit", context: { pinned_constitution_digest: D("a"), current_constitution_digest: D("b"), changed_path_class: "task-branch-constitution" }, payload: { decision, reason: "Reviewed" } })), + ...["authorize-commit", "revise", "abort"].map((decision) => ({ kind: "commit-authorization", context: { target_ref: "refs/heads/task", diff_digest: D("a"), current_artifact_digests: [D("b")], parent_document_digests: [D("c")] }, payload: { decision, reason: "Reviewed" } })), + ...["discard-and-restore", "abort"].map((decision) => ({ kind: "restore-collision", context: { path: "task/file.md", recorded_generation_digest: D("a"), current_generation_digest: D("b"), adoption_candidate: AUTHORITY }, payload: { decision, reason: "Reviewed" } })), + { kind: "restore-collision", context: { path: "task/file.md", recorded_generation_digest: D("a"), current_generation_digest: D("b"), adoption_candidate: AUTHORITY }, payload: { decision: "adopt-as-new-generation", reason: "Adopt", adoption_authority: AUTHORITY, rationale: "Reviewed local changes" } }, + ...["accept-import-audit", "revise", "abort"].map((decision) => ({ kind: "migration-audit", context: { source_identity_digest: D("a"), destination_identity_digest: D("b"), import_digest: D("c"), code_baseline_digest: D("d"), policy_baseline_digest: D("e") }, payload: { decision, reason: "Reviewed" } })), +]; + +function localRef(root: JsonObject, reference: string): JsonObject { + const name = reference.replace("#/$defs/", ""); + return (root.$defs as JsonObject)[name] as JsonObject; +} + +function sampleFromSchema(schema: JsonObject, root: JsonObject): unknown { + if (typeof schema.$ref === "string") return sampleFromSchema(localRef(root, schema.$ref), root); + if (Object.hasOwn(schema, "const")) return schema.const; + if (Array.isArray(schema.enum)) return schema.enum[0]; + if (Array.isArray(schema.oneOf)) return sampleFromSchema(schema.oneOf[0] as JsonObject, root); + if (schema.type === "array") { + const count = typeof schema.minItems === "number" ? schema.minItems : 1; + return Array.from({ length: Math.max(1, count) }, () => sampleFromSchema(schema.items as JsonObject, root)); + } + if (schema.type === "object" || typeof schema.properties === "object") { + const result: JsonObject = {}; + const required = Array.isArray(schema.required) ? schema.required as string[] : []; + const properties = schema.properties as JsonObject; + for (const name of required) result[name] = sampleFromSchema(properties[name] as JsonObject, root); + return result; + } + if (schema.type === "integer" || schema.type === "number") return typeof schema.minimum === "number" ? schema.minimum : 1; + if (schema.type === "boolean") return true; + if (schema.type === "string") { + const pattern = String(schema.pattern ?? ""); + if (pattern.includes("64}")) return D("a"); + if (pattern.includes("phase-design")) return "phase-impl-2"; + if (pattern.includes("a-z0-9_")) return "safe-code"; + if (pattern.includes("A-Za-z0-9.-")) return "1.0"; + if (pattern.includes("A-Za-z0-9._:-")) return "id-1"; + return "value"; + } + throw new TypeError(`cannot synthesize schema sample: ${JSON.stringify(schema)}`); +} + +function errorBranches(root: JsonObject): readonly JsonObject[] { + return (root.oneOf as JsonObject[]).map((reference) => localRef(root, reference.$ref as string)); +} + +function branchContract(branch: JsonObject, root: JsonObject): { code: string; parameters: unknown } { + const overlay = (branch.allOf as JsonObject[])[1]!; + const properties = overlay.properties as JsonObject; + const code = ((properties.code as JsonObject).const) as string; + const diagnostic = properties.diagnostic as JsonObject; + const parameterSchema = ((diagnostic.properties as JsonObject).parameters) as JsonObject; + return { code, parameters: sampleFromSchema(parameterSchema, root) }; +} + +describe("exhaustive gate, error, and supplemental authority", () => { + it("checks every runtime decision effect against every normative annotation", () => { + const root = gateContractSchema as unknown as JsonObject; + const definitions = root.$defs as JsonObject; + const annotated = Object.values(definitions).filter((definition): definition is JsonObject => typeof definition === "object" && definition !== null && Object.hasOwn(definition, "x-archflow-effect")); + const annotatedPairs = annotated.map((definition) => ({ decision: (((definition.properties as JsonObject).decision as JsonObject).const) as string, effect: definition["x-archflow-effect"] as GateEffect })); + expect(annotatedPairs).toHaveLength(15); + for (const pair of annotatedPairs) expect(gateDecisionEffect({ decision: pair.decision } as never)).toBe(pair.effect); + + const schemaPairs = new Set(); + for (const rootRef of root.oneOf as JsonObject[]) { + const contract = localRef(root, rootRef.$ref as string); + const kind = (((contract.properties as JsonObject).kind as JsonObject).const) as string; + const payload = ((contract.properties as JsonObject).payload) as JsonObject; + for (const payloadRef of payload.oneOf as JsonObject[]) { + const definition = localRef(root, payloadRef.$ref as string); + schemaPairs.add(`${kind}:${String(((definition.properties as JsonObject).decision as JsonObject).const)}`); + } + } + expect(new Set(gateCases.map((value) => `${String(value.kind)}:${String((value.payload as JsonObject).decision)}`))).toEqual(schemaPairs); + }); + + it("accepts every gate decision variant without mutation and rejects trust-boundary substitutions", () => { + expect(gateCases).toHaveLength(29); + for (const value of gateCases) { + const before = structuredClone(value); + expect(gateValidator.validate(value), `${String(value.kind)}:${JSON.stringify(gateValidator.validate.errors)}`).toBe(true); + expect(parseGateContract(value)).toEqual(value); + expect(value).toEqual(before); + const envelope = { schema_version: "1", gate_id: "Gate:1", task_id: "Task_1", phase_instance: "phase-impl-2", subject_digest: D("a"), context_digest: D("b"), human_provenance: { schema_version: "1", actor_class: "human", assurance: "declared-local-trace", channel: "archflow-local", decision_event_id: `event-${String(value.kind)}`, helper_invocation_id: "helper-1", recorded_at: "2026-07-27T12:00:00.000Z" }, kind: value.kind, payload: value.payload }; + const envelopeBefore = structuredClone(envelope); + expect(decisionValidator.validate(envelope), `${String(value.kind)}:${JSON.stringify(decisionValidator.validate.errors)}`).toBe(true); + expect(parseGateDecisionEnvelope(envelope)).toEqual(envelope); + expect(envelope).toEqual(envelopeBefore); + const unknownContext = { ...value, context: { ...(value.context as JsonObject), gate_id: "forged-gate" } }; + expect(gateValidator.validate(unknownContext)).toBe(false); + expect(() => parseGateContract(unknownContext)).toThrow(); + } + const restore = gateCases.find((value) => (value.payload as JsonObject).decision === "adopt-as-new-generation")!; + const wrongAuthority = { ...restore, payload: { ...(restore.payload as JsonObject), adoption_authority: { ...AUTHORITY, link_digest: D("f") } } }; + expect(gateValidator.validate(wrongAuthority)).toBe(false); + expect(() => parseGateContract(wrongAuthority)).toThrow(); + }); + + it("exercises all 56 exact error rows and rejects every correlated-field mutation", () => { + const roots = [projectErrorSchema as unknown as JsonObject, protocolErrorSchema as unknown as JsonObject] as const; + const exercisedCodes = new Set(); + let exercised = 0; + for (const root of roots) { + const isProject = root.$id === "urn:archflow:schema:v1:project-error"; + const registry = (isProject ? PROJECT_ERROR_DEFINITIONS : PROTOCOL_ERROR_DEFINITIONS) as unknown as Readonly>; + const validator = isProject ? projectValidator : protocolValidator; + for (const branch of errorBranches(root)) { + const { code, parameters } = branchContract(branch, root); + const definition = registry[code]!; + expect(definition.projection).toBe(isProject ? "project" : "protocol"); + expect(Object.isFrozen(definition)).toBe(true); + expect(Object.isFrozen(definition.parameter_parser)).toBe(true); + const before = structuredClone(parameters); + const parsedParameters = definition.parameter_parser.parse(parameters); + expect(parameters).toEqual(before); + const value = { schema_version: "1", code, owner: definition.owner, retryable: definition.retryable, diagnostic: { template_id: code, parameters: parsedParameters }, next_action: definition.action }; + const valueBefore = structuredClone(value); + expect(validator.validate(value), `${code}:${JSON.stringify(validator.validate.errors)}`).toBe(true); + expect(isProject ? parseProjectError(value) : parseProtocolError(value)).toBe(value); + expect(value).toEqual(valueBefore); + expect(() => definition.parameter_parser.parse({ ...parsedParameters, unsafe_detail: "raw peer data" })).toThrow(); + for (const mutation of [{ ...value, owner: "wrong-owner" }, { ...value, retryable: !value.retryable }, { ...value, next_action: "wrong-action" }, { ...value, diagnostic: { ...value.diagnostic, template_id: "WRONG_CODE" } }]) { + expect(validator.validate(mutation)).toBe(false); + expect(() => isProject ? parseProjectError(mutation) : parseProtocolError(mutation)).toThrow(); + } + exercisedCodes.add(code); + exercised += 1; + } + } + expect(exercised).toBe(56); + expect(exercisedCodes).toEqual(new Set([...Object.keys(PROJECT_ERROR_DEFINITIONS), ...Object.keys(PROTOCOL_ERROR_DEFINITIONS)])); + }); + + it("covers every supplemental variant, gate binding, decline shape, and supersession invariant", () => { + const gate = { prior_gate_id: "Gate:1", task_id: "Task_1", phase_instance: "phase-impl-2", subject_digest: D("a"), input_fingerprint: D("b") }; + const review = { ...gate, evidence_slot: { role: "gate-counter-review", evidence_digest: D("c"), assurance: "degraded", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family", gate_id: "Gate:1" } }; + const cases = [ + { action: "decline", gate, reason: "Declined" }, + { action: "ingest", review, reason: "Ingested" }, + { action: "triage-no-change", review, triage_digest: D("d"), reason: "No change" }, + { action: "supersede", review, accepted_triage_digest: D("d"), old_subject_digest: D("a"), new_subject_digest: D("e"), reason: "Changed" }, + ]; + for (const value of cases) { + const before = structuredClone(value); + expect(supplementalValidator.validate(value), JSON.stringify(supplementalValidator.validate.errors)).toBe(true); + expect(parseSupplementalReviewOutcome(value)).toEqual(value); + expect(value).toEqual(before); + } + const invalid = [ + { ...cases[0], review }, + { ...cases[1], review: { ...review, evidence_slot: { ...review.evidence_slot, gate_id: "Gate:2" } } }, + { ...cases[1], review: { ...review, evidence_slot: { ...review.evidence_slot, reviewer_family: "claude" } } }, + { ...cases[3], old_subject_digest: D("f") }, + { ...cases[3], new_subject_digest: D("a") }, + ]; + for (const value of invalid) { + expect(supplementalValidator.validate(value)).toBe(false); + expect(() => parseSupplementalReviewOutcome(value)).toThrow(); + } + }); +}); diff --git a/test/contracts/mcp-contract-agreement.test.ts b/test/contracts/mcp-contract-agreement.test.ts new file mode 100644 index 00000000..f3267e7a --- /dev/null +++ b/test/contracts/mcp-contract-agreement.test.ts @@ -0,0 +1,66 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; +import { parseToolCall, TOOL_DEFINITIONS } from "../../src/contracts/mcp-tools.js"; +import { createJsonSchemaValidator } from "../../src/contracts/validators.js"; + +const load = async (path: string) => JSON.parse(await readFile(new URL(path, import.meta.url), "utf8")) as object; + +describe("MCP contract schema agreement", () => { + it("compiles every exact tool input fragment and agrees on closed state fixtures", async () => { + const mcp = await load("../../src/contracts/schemas/v1/mcp-tools.schema.json") as { $defs: Record }; + const references = [await load("../../src/contracts/schemas/v1/primitives.schema.json"), await load("../../src/contracts/schemas/v1/project-error.schema.json"), await load("../../src/contracts/schemas/v1/rubric.schema.json"), await load("../../src/contracts/schemas/v1/path-claim.schema.json"), await load("../../src/contracts/schemas/v1/evidence-slots.schema.json"), await load("../../src/contracts/schemas/v1/gate-contract.schema.json"), await load("../../src/contracts/schemas/v1/gate-decision.schema.json")]; + const valid = await load("../fixtures/contracts/mcp-tools/state-valid.json"); + const invalid = await load("../fixtures/contracts/mcp-tools/state-invalid-artifact.json"); + const state = createJsonSchemaValidator(mcp, references); + expect(state.assert(valid)).toBe(valid); + expect(() => state.assert(invalid)).toThrow(); + expect(parseToolCall("archflow_state", valid).name).toBe("archflow_state"); + expect(() => parseToolCall("archflow_state", invalid)).toThrow(); + expect(Object.values(TOOL_DEFINITIONS).every((definition) => definition.input_schema_id.startsWith("https://archflow.dev/schemas/v1/mcp-tools#/$defs/"))).toBe(true); + }); + + it("compiles the closed correlated result-expectation union", async () => { + const mcp = await load("../../src/contracts/schemas/v1/mcp-tools.schema.json"); + const expectation = await load("../../src/contracts/schemas/v1/result-expectation.schema.json"); + const references = [mcp, await load("../../src/contracts/schemas/v1/primitives.schema.json"), await load("../../src/contracts/schemas/v1/project-error.schema.json"), await load("../../src/contracts/schemas/v1/rubric.schema.json"), await load("../../src/contracts/schemas/v1/path-claim.schema.json"), await load("../../src/contracts/schemas/v1/evidence-slots.schema.json"), await load("../../src/contracts/schemas/v1/gate-contract.schema.json"), await load("../../src/contracts/schemas/v1/gate-decision.schema.json")]; + const validator = createJsonSchemaValidator(expectation, references); + const value = { schema_version: "1", tool: "archflow_state", task_id: "task-1", intent_id: "intent-1", input_fingerprint: "a".repeat(64), request_digest: "b".repeat(64), result_id: "result-1", resulting_revision: 3, success: { path: "phases/2/result.json", revision: 3, status: "succeeded" } }; + expect(validator.assert(value)).toBe(value); + expect(() => validator.assert({ ...value, receipt_id: "not-in-hash-domain" })).toThrow(); + expect(() => validator.assert({ ...value, tool: "archflow_counter_review" })).toThrow(); + expect(() => validator.assert({ ...value, resulting_revision: 4 })).toThrow(); + }); + + it("agrees on exact gate tuples, authoritative contexts, and path bytes", async () => { + const mcp = await load("../../src/contracts/schemas/v1/mcp-tools.schema.json"); + const references = [await load("../../src/contracts/schemas/v1/primitives.schema.json"), await load("../../src/contracts/schemas/v1/project-error.schema.json"), await load("../../src/contracts/schemas/v1/rubric.schema.json"), await load("../../src/contracts/schemas/v1/path-claim.schema.json"), await load("../../src/contracts/schemas/v1/evidence-slots.schema.json"), await load("../../src/contracts/schemas/v1/gate-contract.schema.json"), await load("../../src/contracts/schemas/v1/gate-decision.schema.json")]; + const validator = createJsonSchemaValidator(mcp, references); + const self = { role: "self-review", evidence_digest: "1".repeat(64), assurance: "agent-declared", producer_family: "claude", reviewer_family: "claude", independence: "same-family-self" }; + const counter = { role: "counter-review", evidence_digest: "2".repeat(64), assurance: "server-attested", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family" }; + const gate = { schema_version: "1", task_id: "Task:1", intent_id: "Intent:1", expected_revision: 0, input_fingerprint: "a".repeat(64), phase_instance: "phase-impl-2", summary: "Review", subject_digest: "a".repeat(64), current_evidence: { set_digest: "3".repeat(64), slots: [self, counter] }, kind: "artifact-approval", context: { artifact_kind: "phase-implementation" } }; + expect(validator.validate(gate)).toBe(true); + for (const invalid of [{ ...gate, current_evidence: { ...gate.current_evidence, slots: [counter, self] } }, { ...gate, current_evidence: { ...gate.current_evidence, slots: [self, { ...counter, evidence_digest: self.evidence_digest }] } }, { ...gate, kind: "attempts-exhausted", context: { step: "produce", attempts: 1, maximum_attempts: 2 } }]) { + expect(validator.validate(invalid)).toBe(false); + expect(() => parseToolCall("archflow_gate", invalid)).toThrow(); + } + const rubric = { schema_version: "1", kind: "implementation", mode: "adversarial", criteria: [{ id: "paths", text: "Check paths", blocking: true }] }; + for (const artifact_path of [`${"é".repeat(600)}.md`, `bad\u0080path`]) { + const input = { schema_version: "1", task_id: "task", intent_id: "intent", expected_revision: 0, input_fingerprint: "a".repeat(64), artifact_path, rubric }; + expect(validator.validate(input)).toBe(false); + expect(() => parseToolCall("archflow_counter_review", input)).toThrow(); + } + const common = { schema_version: "1", task_id: "Task:1", intent_id: "Intent:1", expected_revision: 0, input_fingerprint: "a".repeat(64) }; + const waiverOrigin = { origin_gate_id: "Gate:1", origin_decision_digest: "1".repeat(64), origin_context_digest: "2".repeat(64), task_id: "Task:1", phase_instance: "phase-impl-2", subject_digest: "3".repeat(64), current_evidence_set_digest: "4".repeat(64), rule: { rule_id: "Rule:1", rule_version: 1 }, scope: { operation: "review-trigger", boundary: "subject" } }; + const examples = [ + ["archflow_state", { ...common, phase_instance: "phase-impl-2", step: "produce", status: "running" }], + ["archflow_counter_review", { ...common, artifact_path: "phases/2/result.md", rubric }], + ["archflow_adjudicate", { ...common, artifact_path: "phases/2/result.md", upstream_paths: ["prd.md", "design.md"] }], + ["archflow_gate", gate], + ["archflow_waiver", { ...common, origin: waiverOrigin, rationale: "Needed" }] + ] as const; + for (const [name, input] of examples) { expect(validator.validate(input), name).toBe(true); expect(parseToolCall(name, input).name).toBe(name); } + const wrongWaiver = { ...examples[4][1], task_id: "Other" }; + expect(validator.validate(wrongWaiver)).toBe(false); + expect(() => parseToolCall("archflow_waiver", wrongWaiver)).toThrow(); + }); +}); diff --git a/test/contracts/review-schema-agreement.test.ts b/test/contracts/review-schema-agreement.test.ts new file mode 100644 index 00000000..ce4e5733 --- /dev/null +++ b/test/contracts/review-schema-agreement.test.ts @@ -0,0 +1,80 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; +import { adjudicationEvidenceSchema, rawAdjudicationSchema } from "../../src/contracts/adjudication.js"; +import { rawReviewSchema, reviewEvidenceSchema } from "../../src/contracts/review.js"; +import { assertZodAgreement, createJsonSchemaValidator } from "../../src/contracts/validators.js"; + +const json = async (url: URL) => JSON.parse(await readFile(url, "utf8")) as unknown; +const schema = async (name: string) => await json(new URL(`../../src/contracts/schemas/v1/${name}.schema.json`, import.meta.url)) as object; +describe("review and adjudication schema agreement", () => { + it("accepts the same review corpus without mutation", async () => { const value = await json(new URL("../fixtures/contracts/review/valid.json", import.meta.url)); const before = structuredClone(value); expect(assertZodAgreement(value, createJsonSchemaValidator(await schema("review")), rawReviewSchema)).toBe(value); expect(value).toEqual(before); }); + it("accepts the same adjudication corpus without mutation", async () => { const value = await json(new URL("../fixtures/contracts/adjudication/valid.json", import.meta.url)); const before = structuredClone(value); expect(assertZodAgreement(value, createJsonSchemaValidator(await schema("adjudication")), rawAdjudicationSchema)).toBe(value); expect(value).toEqual(before); }); + it("rejects closed-shape substitutions", async () => { const value = await json(new URL("../fixtures/contracts/review/valid.json", import.meta.url)) as Record; const validator = createJsonSchemaValidator(await schema("review")); expect(() => assertZodAgreement({ ...value, authority: true }, validator, rawReviewSchema)).toThrow(); }); + + it("agrees across every evidence variant without mutation", async () => { + const review = await json(new URL("../fixtures/contracts/review/valid.json", import.meta.url)) as Record; + const adjudication = await json(new URL("../fixtures/contracts/adjudication/valid.json", import.meta.url)) as Record; + const reviewValidator = createJsonSchemaValidator(await schema("review-evidence")); + const adjudicationValidator = createJsonSchemaValidator(await schema("adjudication-evidence")); + const variants = [ + [reviewValidator, reviewEvidenceSchema, { ...review, assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }], + [reviewValidator, reviewEvidenceSchema, { ...review, assurance: "degraded", model_family: "unknown", model: "unknown", effort: "unknown", reason: "Manual fallback." }], + [reviewValidator, reviewEvidenceSchema, { ...review, assurance: "server-attested", adapter: "codex-cli", cli_version: "1.0.0", model_family: "codex", model: "gpt-5", effort: "high", invocation_id: "invocation-1", envelope_input_digest: "d".repeat(64), observed_output_digest: "e".repeat(64), result_id: "result-1" }], + [adjudicationValidator, adjudicationEvidenceSchema, { ...adjudication, assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }], + [adjudicationValidator, adjudicationEvidenceSchema, { ...adjudication, assurance: "degraded", model_family: "unknown", model: "unknown", effort: "unknown", reason: "Manual fallback." }], + [adjudicationValidator, adjudicationEvidenceSchema, { ...adjudication, assurance: "server-attested", adapter: "codex-cli", cli_version: "1.0.0", model_family: "codex", model: "gpt-5", effort: "high", invocation_id: "invocation-1", envelope_input_digest: "d".repeat(64), observed_output_digest: "e".repeat(64), result_id: "result-1" }], + ] as const; + + for (const [validator, mirror, value] of variants) { + const before = structuredClone(value); + expect(validator.validate(value), JSON.stringify(validator.validate.errors)).toBe(true); + expect(assertZodAgreement(value, validator, mirror, String(value.assurance))).toBe(value); + expect(value).toEqual(before); + } + }); + + it("rejects cross-family, cross-assurance, and nested closed-shape substitutions", async () => { + const review = await json(new URL("../fixtures/contracts/review/valid.json", import.meta.url)) as Record; + const adjudication = await json(new URL("../fixtures/contracts/adjudication/valid.json", import.meta.url)) as Record; + const reviewValidator = createJsonSchemaValidator(await schema("review-evidence")); + const adjudicationValidator = createJsonSchemaValidator(await schema("adjudication-evidence")); + const declaredReview = { ...review, assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }; + const declaredAdjudication = { ...adjudication, assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }; + const finding = (review.findings as Array>)[0]!; + + expect(() => reviewValidator.assert(declaredAdjudication)).toThrow(); + expect(() => adjudicationValidator.assert(declaredReview)).toThrow(); + expect(() => assertZodAgreement({ ...declaredReview, adapter: "codex-cli" }, reviewValidator, reviewEvidenceSchema)).toThrow(); + expect(() => assertZodAgreement({ ...declaredAdjudication, reason: "degraded-only" }, adjudicationValidator, adjudicationEvidenceSchema)).toThrow(); + expect(() => assertZodAgreement({ ...declaredReview, findings: [{ ...finding, internal_authority: true }] }, reviewValidator, reviewEvidenceSchema)).toThrow(); + }); + + it("agrees on duplicate IDs, role/step, opposite family, and review contradictions", async () => { + const review = await json(new URL("../fixtures/contracts/review/valid.json", import.meta.url)) as Record; + const validator = createJsonSchemaValidator(await schema("review-evidence")); + const base = { ...review, assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }; + const server = { ...review, assurance: "server-attested", adapter: "codex-cli", cli_version: "1", model_family: "codex", model: "gpt", effort: "high", invocation_id: "invocation-1", envelope_input_digest: "d".repeat(64), observed_output_digest: "e".repeat(64), result_id: "result-1" }; + const cases = [ + { ...base, findings: [...(review.findings as unknown[]), ...(review.findings as unknown[])] }, + { ...base, role: "self-review", step: "counter_review" }, + { ...server, model_family: "claude" }, + { ...base, verdict: "pass" }, + { ...base, blocking_count: 2 }, + ]; + for (const value of cases) { expect(validator.validate(value)).toBe(false); expect(reviewEvidenceSchema.safeParse(value).success).toBe(false); } + }); + + it("agrees on absent, mixed, and wrong-subject mechanical pass evidence", async () => { + const adjudication = await json(new URL("../fixtures/contracts/adjudication/valid.json", import.meta.url)) as Record; + const validator = createJsonSchemaValidator(await schema("adjudication-evidence")); + const finding = structuredClone((adjudication.rule_findings as Array>)[0]!); + const current = structuredClone((finding.enforced_by as Array>)[0]!); + const base = { ...adjudication, assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }; + const cases = [ + { ...base, rule_findings: [{ ...finding, enforced_by: [] }] }, + { ...base, rule_findings: [{ ...finding, enforced_by: [current, { mechanism: "manual", state: "unknown", details: "Unavailable." }] }] }, + { ...base, rule_findings: [{ ...finding, enforced_by: [{ ...current, subject_digest: "0".repeat(64) }] }] }, + ]; + for (const value of cases) { expect(validator.validate(value), JSON.stringify(validator.validate.errors)).toBe(false); expect(adjudicationEvidenceSchema.safeParse(value).success).toBe(false); } + }); +}); diff --git a/test/contracts/schema-registry.test.ts b/test/contracts/schema-registry.test.ts new file mode 100644 index 00000000..67611e41 --- /dev/null +++ b/test/contracts/schema-registry.test.ts @@ -0,0 +1,74 @@ +import { readFile } from "node:fs/promises"; + +import { describe, expect, it } from "vitest"; + +import { createJsonSchemaValidator } from "../../src/contracts/validators.js"; +import { SCHEMA_IDS } from "../../src/contracts/versions.js"; +import * as publicContracts from "../../src/contracts/index.js"; + +const SCHEMA_FILES = { + primitives: "primitives", + phaseInstance: "phase-instance", + workflow: "workflow", + config: "config", + rubric: "rubric", + constitutionRule: "constitution-rule", + review: "review", + reviewEvidence: "review-evidence", + adjudication: "adjudication", + adjudicationEvidence: "adjudication-evidence", + evidenceReference: "evidence-reference", + authorityLink: "authority-link", + evidenceSlots: "evidence-slots", + triage: "triage", + supplementalReview: "supplemental-review", + gateContract: "gate-contract", + gateDecision: "gate-decision", + projectError: "project-error", + protocolError: "protocol-error", + mcpTools: "mcp-tools", + resultExpectation: "result-expectation", + pathClaim: "path-claim", +} as const satisfies Record; + +const loadSchema = async (name: string): Promise> => + JSON.parse( + await readFile( + new URL(`../../src/contracts/schemas/v1/${name}.schema.json`, import.meta.url), + "utf8", + ), + ) as Record; + +describe("SCHEMA_IDS registry", () => { + it("matches every normative schema and loads each entry independently", async () => { + const entries = await Promise.all( + Object.entries(SCHEMA_FILES).map(async ([key, filename]) => [key, await loadSchema(filename)] as const), + ); + + expect(Object.keys(SCHEMA_IDS).sort()).toEqual(Object.keys(SCHEMA_FILES).sort()); + + for (const [key, target] of entries) { + expect(target.$id).toBe(SCHEMA_IDS[key as keyof typeof SCHEMA_IDS]); + const references = entries.filter(([otherKey]) => otherKey !== key).map(([, schema]) => schema); + expect(() => createJsonSchemaValidator(target, references)).not.toThrow(); + } + }); + + it("enforces composite x-archflow-unique-by identities", async () => { + const validator = createJsonSchemaValidator(await loadSchema("triage")); + const disposition = { review_evidence_digest: "a".repeat(64), finding_id: "same-id", disposition: "rejected", rationale: "Not applicable.", evidence: "The finding is stale." }; + const value = { schema_version: "1", task_id: "task-1", phase_instance: "phase-impl-2", step: "triage", subject_digest: "b".repeat(64), input_fingerprint: "c".repeat(64), current_evidence_set_digest: "d".repeat(64), source_evidence_digests: ["a".repeat(64)], dispositions: [disposition, { ...disposition }], accepted_count: 0, rejected_count: 2 }; + expect(() => validator.assert(value)).toThrow(/x-archflow-unique-by/iu); + expect(validator.assert({ ...value, source_evidence_digests: ["a".repeat(64), "e".repeat(64)], dispositions: [disposition, { ...disposition, review_evidence_digest: "e".repeat(64) }] })).toEqual(expect.any(Object)); + }); + + it("does not expose internal authority mint factories from the public barrel", () => { + expect(Object.keys(publicContracts)).not.toEqual(expect.arrayContaining([ + "createTestObservationCapability", + "createTestAuthorityLink", + "createTestVerifiedReferencedEvidence", + "createTestCurrentReviewSetAuthority", + "createTestResultExpectation", + ])); + }); +}); diff --git a/test/contracts/shared-primitives-schema-agreement.test.ts b/test/contracts/shared-primitives-schema-agreement.test.ts new file mode 100644 index 00000000..14924a9d --- /dev/null +++ b/test/contracts/shared-primitives-schema-agreement.test.ts @@ -0,0 +1,49 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; +import { z } from "zod"; + +import { + safeCodeV1Schema, + safeIdV1Schema, + safeIntegerV1Schema, + safeVersionV1Schema, + sha256DigestV1Schema +} from "../../src/contracts/evidence.js"; +import { taskPathClaimV1Schema } from "../../src/contracts/path-claims.js"; +import { assertZodAgreement, createJsonSchemaValidator } from "../../src/contracts/validators.js"; + +const schema = async (name: string) => JSON.parse(await readFile(new URL(`../../src/contracts/schemas/v1/${name}.schema.json`, import.meta.url), "utf8")) as object; + +describe("normative shared primitive schemas agree with Zod mirrors", () => { + it.each([ + ["sha256Digest", sha256DigestV1Schema, "0".repeat(64), "A".repeat(64)], + ["safeId", safeIdV1Schema, "task-1:phase", "-task"], + ["safeCode", safeCodeV1Schema, "invalid_contract", "INVALID"], + ["safeVersion", safeVersionV1Schema, "1.2-rc1", "1_2"], + ["safeInteger", safeIntegerV1Schema, Number.MAX_SAFE_INTEGER, -1] + ] as const)("agrees for the %s definition", async (definition, zodSchema, valid, invalid) => { + const primitiveSchema = await schema("primitives") as { $defs: Record }; + const validator = createJsonSchemaValidator({ + $schema: "https://json-schema.org/draft/2020-12/schema", + ...primitiveSchema.$defs[definition] + }); + expect(assertZodAgreement(valid, validator, zodSchema)).toBe(valid); + expect(() => assertZodAgreement(invalid, validator, zodSchema)).toThrow(); + }); + + it("agrees on lexical structure and exact UTF-8 byte bounds", async () => { + const validator = createJsonSchemaValidator(await schema("path-claim")); + for (const valid of ["review.md", "資料/設計.md", "é".repeat(512)]) { + expect(assertZodAgreement(valid, validator, taskPathClaimV1Schema)).toBe(valid); + } + for (const invalid of ["/absolute", "./relative", "x/../escape", "é".repeat(513)]) { + expect(() => assertZodAgreement(invalid, validator, taskPathClaimV1Schema)).toThrow(); + } + }); + + it("does not mutate values and rejects non-plain inputs before either validator", async () => { + const validator = createJsonSchemaValidator(await schema("path-claim")); + const boxed = new String("review.md"); + expect(() => assertZodAgreement(boxed, validator, z.string())).toThrow(/plain prototype/iu); + }); +}); diff --git a/test/fixtures/contracts/adjudication/valid.json b/test/fixtures/contracts/adjudication/valid.json new file mode 100644 index 00000000..08256d02 --- /dev/null +++ b/test/fixtures/contracts/adjudication/valid.json @@ -0,0 +1 @@ +{"schema_version":"1","task_id":"mcp-integration","phase_instance":"phase-impl-2","step":"adjudicate","subject_digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","input_fingerprint":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","pinned_constitution_digest":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","approved_upstream_digests":["dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"],"source_evidence_set_digest":"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee","rule_findings":[{"rule_id":"safe-paths","rule_version":2,"compliance":"pass","rationale":"Current evidence confirms compliance.","trigger":"not-matched","trigger_evidence":"No unsafe path was observed.","enforced_by":[{"mechanism":"path-contract","state":"current","subject_digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","evidence_digest":"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff","details":"Contract suite passed."}]}],"drift_findings":[{"upstream_digest":"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd","drift":"aligned","affected_claim_ids":[],"rationale":"Implementation follows the approved design."}],"constitution":"pass","drift":"aligned","matched_rule_versions":[],"uncertain_rule_versions":[]} diff --git a/test/fixtures/contracts/mcp-tools/state-invalid-artifact.json b/test/fixtures/contracts/mcp-tools/state-invalid-artifact.json new file mode 100644 index 00000000..cbd857dc --- /dev/null +++ b/test/fixtures/contracts/mcp-tools/state-invalid-artifact.json @@ -0,0 +1,11 @@ +{ + "schema_version": "1", + "task_id": "task-1", + "intent_id": "intent-1", + "expected_revision": 2, + "input_fingerprint": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "phase_instance": "phase-impl-2", + "step": "produce", + "status": "succeeded", + "artifact": null +} diff --git a/test/fixtures/contracts/mcp-tools/state-valid.json b/test/fixtures/contracts/mcp-tools/state-valid.json new file mode 100644 index 00000000..0fd8b578 --- /dev/null +++ b/test/fixtures/contracts/mcp-tools/state-valid.json @@ -0,0 +1,10 @@ +{ + "schema_version": "1", + "task_id": "task-1", + "intent_id": "intent-1", + "expected_revision": 2, + "input_fingerprint": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "phase_instance": "phase-impl-2", + "step": "produce", + "status": "succeeded" +} diff --git a/test/fixtures/contracts/path-claims/invalid-traversal.json b/test/fixtures/contracts/path-claims/invalid-traversal.json new file mode 100644 index 00000000..c163b56a --- /dev/null +++ b/test/fixtures/contracts/path-claims/invalid-traversal.json @@ -0,0 +1 @@ +"reviews/../outside.md" diff --git a/test/fixtures/contracts/path-claims/valid.json b/test/fixtures/contracts/path-claims/valid.json new file mode 100644 index 00000000..67405d15 --- /dev/null +++ b/test/fixtures/contracts/path-claims/valid.json @@ -0,0 +1 @@ +"reviews/phase-2.md" diff --git a/test/fixtures/contracts/review/invalid-contradiction.json b/test/fixtures/contracts/review/invalid-contradiction.json new file mode 100644 index 00000000..449d2490 --- /dev/null +++ b/test/fixtures/contracts/review/invalid-contradiction.json @@ -0,0 +1 @@ +{"schema_version":"1","task_id":"mcp-integration","phase_instance":"phase-impl-2","step":"counter_review","role":"counter-review","subject_digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","input_fingerprint":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","rubric_digest":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","producer_family":"claude","findings":[{"finding_id":"unsafe-path","severity":"blocker","blocking":true,"summary":"Path is unsafe.","evidence":"The path escapes its task.","suggested_resolution":"Reject traversal."}],"matched_rule_versions":[],"verdict":"pass","blocking_count":0} diff --git a/test/fixtures/contracts/review/valid.json b/test/fixtures/contracts/review/valid.json new file mode 100644 index 00000000..adf7eb36 --- /dev/null +++ b/test/fixtures/contracts/review/valid.json @@ -0,0 +1 @@ +{"schema_version":"1","task_id":"mcp-integration","phase_instance":"phase-impl-2","step":"counter_review","role":"counter-review","subject_digest":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","input_fingerprint":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","rubric_digest":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","producer_family":"claude","findings":[{"finding_id":"unsafe-path","severity":"blocker","blocking":true,"summary":"Path is unsafe.","evidence":"The path escapes its task.","suggested_resolution":"Reject traversal."}],"matched_rule_versions":[{"rule_id":"safe-paths","rule_version":2}],"verdict":"fail","blocking_count":1} diff --git a/test/unit/adjudication.test.ts b/test/unit/adjudication.test.ts new file mode 100644 index 00000000..0448fb7f --- /dev/null +++ b/test/unit/adjudication.test.ts @@ -0,0 +1,12 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; +import { parseAdjudicationEvidence, parseAndDeriveAdjudication, parseReferencedAdjudicationEvidence } from "../../src/contracts/adjudication.js"; + +const valid = async () => JSON.parse(await readFile(new URL("../fixtures/contracts/adjudication/valid.json", import.meta.url), "utf8")) as Record; +describe("adjudication semantics", () => { + it("derives independent constitution, drift, and trigger summaries", async () => { const value = await valid(); const before = structuredClone(value); expect(parseAndDeriveAdjudication(value).constitution).toBe("pass"); expect(value).toEqual(before); expect(() => parseAndDeriveAdjudication({ ...value, drift: "material" })).toThrow(/drift must be aligned/); }); + it("cannot upgrade missing, stale, failed, unknown, or mismatched evidence to compliance", async () => { for (const state of ["missing", "stale", "unknown", "failed", "digest-mismatch"]) { const value = await valid(); const finding = structuredClone((value.rule_findings as Array>)[0]!); finding.enforced_by = [{ mechanism: "path-contract", state, details: "Not current.", ...(state === "stale" ? { subject_digest: "0".repeat(64), evidence_digest: "f".repeat(64) } : {}) }]; expect(() => parseAndDeriveAdjudication({ ...value, rule_findings: [finding] })).toThrow(); } }); + it("rejects trigger list and current-subject contradictions", async () => { const value = await valid(); expect(() => parseAndDeriveAdjudication({ ...value, matched_rule_versions: [{ rule_id: "safe-paths", rule_version: 2 }] })).toThrow(/contradict/); const finding = structuredClone((value.rule_findings as Array>)[0]!); (finding.enforced_by as Array>)[0]!.subject_digest = "0".repeat(64); expect(() => parseAndDeriveAdjudication({ ...value, rule_findings: [finding] })).toThrow(/wrong subject/); }); + it("requires pass to have only current subject-bound mechanical evidence", async () => { const value = await valid(); const finding = structuredClone((value.rule_findings as Array>)[0]!); finding.enforced_by = []; expect(() => parseAndDeriveAdjudication({ ...value, rule_findings: [finding] })).toThrow(/requires current mechanical evidence/); finding.enforced_by = [structuredClone(((value.rule_findings as Array>)[0]!.enforced_by as unknown[])[0]), { mechanism: "manual-check", state: "unknown", details: "Not current." }]; expect(() => parseAndDeriveAdjudication({ ...value, rule_findings: [finding] })).toThrow(/suspect mechanical evidence/); }); + it("composes provenance and reference parsers through adjudication semantics", async () => { const value = await valid(); const finding = structuredClone((value.rule_findings as Array>)[0]!); finding.enforced_by = []; const evidence = { ...value, rule_findings: [finding], assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }; expect(() => parseAdjudicationEvidence(evidence)).toThrow(/requires current mechanical evidence/); expect(() => parseReferencedAdjudicationEvidence({ evidence_digest: "f".repeat(64), evidence })).toThrow(/requires current mechanical evidence/); }); +}); diff --git a/test/unit/contexts.test.ts b/test/unit/contexts.test.ts new file mode 100644 index 00000000..5696ff11 --- /dev/null +++ b/test/unit/contexts.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vitest"; +import { connectionContextFactory, createInvocationContext, ProtocolContextError } from "../../src/contracts/contexts.js"; + +describe("transport-neutral contexts", () => { + it("defensively copies, deeply freezes, and initializes once", () => { + const startup = { connection_id: "connection-1", startup_repository_candidate: { working_directory: "/work/repo" } }; + const initialization = { client: { name: "Codex", version: "1.0" }, host: "codex", protocol_version: "2026-01" } as const; + const captured = connectionContextFactory.captureStartup(startup); + startup.startup_repository_candidate.working_directory = "/changed"; + const connection = captured.initialize(initialization); + expect(connection.startup_repository_candidate.working_directory).toBe("/work/repo"); + expect(Object.isFrozen(connection.initialization_candidates.client)).toBe(true); + expect(() => captured.initialize(initialization)).toThrow(ProtocolContextError); + }); + it("retains AbortSignal identity while freezing copied transport metadata", () => { + const connection = connectionContextFactory.captureStartup({ connection_id: "connection-2", startup_repository_candidate: { working_directory: "/work/repo" } }).initialize({ client: { name: "Claude", version: "1.0" }, host: "claude", protocol_version: "2026-01" }); + const controller = new AbortController(); + const seed = { invocation_id: "invocation-1", transport_metadata: { request_id: "request-1", operation: "tools/call" } } as const; + const invocation = createInvocationContext(connection, seed, controller.signal); + expect(invocation.signal).toBe(controller.signal); + expect(Object.isFrozen(invocation.transport_metadata)).toBe(true); + controller.abort(); + expect(invocation.signal.aborted).toBe(true); + }); + it("rejects unbranded and spread-cloned connection contexts", () => { + const connection = connectionContextFactory.captureStartup({ connection_id: "connection-3", startup_repository_candidate: { working_directory: "/work/repo" } }).initialize({ client: { name: "Codex", version: "1.0" }, host: "codex", protocol_version: "2026-01" }); + const seed = { invocation_id: "invocation-2", transport_metadata: { request_id: "request-2", operation: "tools/call" } } as const; + expect(() => createInvocationContext({ ...connection } as never, seed, new AbortController().signal)).toThrow(/branded connection/); + expect(() => createInvocationContext({ connection_id: connection.connection_id, startup_repository_candidate: connection.startup_repository_candidate, initialization_candidates: connection.initialization_candidates } as never, seed, new AbortController().signal)).toThrow(/branded connection/); + }); +}); diff --git a/test/unit/errors.test.ts b/test/unit/errors.test.ts new file mode 100644 index 00000000..dd2623e7 --- /dev/null +++ b/test/unit/errors.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; + +import { PROJECT_ERROR_DEFINITIONS, PROTOCOL_ERROR_DEFINITIONS, createProjectError, createProtocolError, parseProjectError, parseProtocolError } from "../../src/contracts/errors.js"; + +const D = "a".repeat(64); + +describe("error registries", () => { + it("are exhaustive, separate, and recursively immutable at definition boundaries", () => { + expect(Object.keys(PROJECT_ERROR_DEFINITIONS)).toHaveLength(52); + expect(Object.keys(PROTOCOL_ERROR_DEFINITIONS)).toEqual(["TOOL_NOT_FOUND", "TOOL_DISABLED", "UNSUPPORTED_PROTOCOL", "INITIALIZATION_REPEATED"]); + expect(Object.keys(PROJECT_ERROR_DEFINITIONS).some((code) => Object.hasOwn(PROTOCOL_ERROR_DEFINITIONS, code))).toBe(false); + expect(Object.isFrozen(PROJECT_ERROR_DEFINITIONS)).toBe(true); + expect(Object.isFrozen(PROJECT_ERROR_DEFINITIONS.STATE_CONFLICT)).toBe(true); + expect(Object.isFrozen(PROJECT_ERROR_DEFINITIONS.STATE_CONFLICT.parameter_parser)).toBe(true); + }); + + it("constructs only registry-correlated serialized values", () => { + const conflict = createProjectError("STATE_CONFLICT", { expected_revision: 2, observed_revision: 3 }); + expect(conflict).toEqual({ schema_version: "1", code: "STATE_CONFLICT", owner: "state", retryable: true, diagnostic: { template_id: "STATE_CONFLICT", parameters: { expected_revision: 2, observed_revision: 3 } }, next_action: "reread-and-retry-intent" }); + expect(parseProjectError(conflict)).toBe(conflict); + expect(() => parseProjectError({ ...conflict, retryable: false })).toThrow(); + expect(() => createProjectError("STATE_CONFLICT", { expected_revision: 2, observed_revision: 3, raw_exception: "secret" } as never)).toThrow(); + const reordered = { next_action: conflict.next_action, diagnostic: { parameters: { observed_revision: 3, expected_revision: 2 }, template_id: conflict.code }, retryable: conflict.retryable, owner: conflict.owner, code: conflict.code, schema_version: conflict.schema_version }; + expect(parseProjectError(reordered)).toBe(reordered); + }); + + it("keeps protocol diagnostics safe and distinct from project errors", () => { + const missing = createProtocolError("TOOL_NOT_FOUND", { tool_name_digest: D }); + expect(missing.diagnostic.parameters).toEqual({ tool_name_digest: D }); + expect(parseProtocolError(missing)).toBe(missing); + expect(() => createProtocolError("TOOL_NOT_FOUND", { tool_name_digest: D, tool_name: "unknown-secret-name" } as never)).toThrow(); + expect(() => parseProjectError(missing)).toThrow(); + }); + + it("requires sorted exact snapshot paths and preserves cancellation ownership", () => { + expect(() => createProjectError("SNAPSHOT_LIMIT", { limit_scope: "task", offending_paths: ["z/file", "a/file"], current_bytes: 2, byte_cap: 1 })).toThrow(); + const child = createProjectError("CANCELLED", { source: "client", attempt: 1 }); + const gate = createProjectError("GATE_CANCELLED", { gate_id: "gate-1", gate_kind: "artifact-approval" }); + expect([child.owner, child.retryable, child.next_action]).toEqual(["dispatch", true, "restart-child-attempt"]); + expect([gate.owner, gate.retryable, gate.next_action]).toEqual(["gate", false, "restart-gate-flow"]); + }); +}); diff --git a/test/unit/evidence.test.ts b/test/unit/evidence.test.ts new file mode 100644 index 00000000..f88d4bf3 --- /dev/null +++ b/test/unit/evidence.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; + +import { + parseSafeCode, + parseSafeId, + parseSafeInteger, + parseSafeVersion, + parseSha256Digest, + type ReferencedEvidence, + type SafeCode, + type SafeId, + type SafeInteger, + type SafeVersion, + type Sha256Digest +} from "../../src/contracts/index.js"; + +describe("shared evidence primitives", () => { + it("accepts only canonical lowercase SHA-256 syntax", () => { + const digest = "0123456789abcdef".repeat(4); + expect(parseSha256Digest(digest)).toBe(digest); + for (const invalid of [ + digest.toUpperCase(), + `sha256:${digest}`, + ` ${digest}`, + `${digest} `, + digest.slice(1), + `${digest}0`, + "0".repeat(64) + ]) expect(() => parseSha256Digest(invalid)).toThrow(); + }); + + it("enforces the bounded identifier, code, version, and integer vocabularies", () => { + expect(parseSafeId(`a${"-".repeat(127)}`)).toHaveLength(128); + expect(parseSafeCode(`a${"_".repeat(63)}`)).toHaveLength(64); + expect(parseSafeVersion(`1${".".repeat(63)}`)).toHaveLength(64); + expect(parseSafeInteger(Number.MAX_SAFE_INTEGER)).toBe(Number.MAX_SAFE_INTEGER); + + for (const invalid of ["", "-leading", `a${".".repeat(128)}`, "é"]) expect(() => parseSafeId(invalid)).toThrow(); + for (const invalid of ["", "UPPER", "-leading", `a${"_".repeat(64)}`]) expect(() => parseSafeCode(invalid)).toThrow(); + for (const invalid of ["", "v_1", `1${".".repeat(64)}`, "é"]) expect(() => parseSafeVersion(invalid)).toThrow(); + for (const invalid of [-1, 1.5, Number.MAX_SAFE_INTEGER + 1, "1"]) expect(() => parseSafeInteger(invalid)).toThrow(); + }); + + it("keeps identities and evidence references opaque at compile time", () => { + expectTypeOf().toMatchTypeOf(); + expectTypeOf().toMatchTypeOf(); + expectTypeOf().toMatchTypeOf(); + expectTypeOf().toMatchTypeOf(); + expectTypeOf().toMatchTypeOf(); + // @ts-expect-error unparsed strings cannot mint a digest brand + const untrustedDigest: Sha256Digest = "0".repeat(64); + const reference: ReferencedEvidence<{ readonly value: string }> = { + evidence_digest: parseSha256Digest("0".repeat(64)), + evidence: { value: "payload" } + }; + expect(reference.evidence.value).toBe("payload"); + expect(untrustedDigest).toHaveLength(64); + }); + + it("runs recursive plain-JSON preflight before primitive parsing", () => { + expect(() => parseSha256Digest(new String("0".repeat(64)))).toThrow(/plain prototype/iu); + }); +}); diff --git a/test/unit/gates.test.ts b/test/unit/gates.test.ts new file mode 100644 index 00000000..812cd010 --- /dev/null +++ b/test/unit/gates.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest"; + +import { GATE_KINDS, gateDecisionEffect, parseGateContext, parseGateContract, parseGateDecisionEnvelope, validateGateDecision } from "../../src/contracts/gates.js"; + +const D = "a".repeat(64); +const RULE = { rule_id: "trust-boundary", rule_version: 1 }; + +describe("gate catalogue", () => { + it("contains exactly the nine independent kinds", () => { + expect(GATE_KINDS).toEqual(["artifact-approval", "review-trigger", "material-drift", "adjudication-failure", "attempts-exhausted", "constitution-edit", "commit-authorization", "restore-collision", "migration-audit"]); + }); + + it("keeps cancellation and supplemental outcomes outside decisions", () => { + expect(() => validateGateDecision("artifact-approval", { artifact_kind: "prd" }, { decision: "approve", reason: "Ready" })).not.toThrow(); + expect(() => validateGateDecision("artifact-approval", { artifact_kind: "prd" }, { decision: "cancelled", reason: "No" } as never)).toThrow(); + expect(() => validateGateDecision("artifact-approval", { artifact_kind: "prd" }, { action: "decline", reason: "No" } as never)).toThrow(); + }); + + it("enforces waiver, attempt, adjudication, and restore sequencing", () => { + const trigger = parseGateContext("review-trigger", { matched_rules: [RULE], uncertain_rules: [], eligible_waiver_rules: [RULE], waiver_scope: { operation: "review-trigger", boundary: "subject" } }); + expect(validateGateDecision("review-trigger", trigger, { decision: "waiver-requested", reason: "Exception", rule: RULE, rationale: "Temporary" })).toBeTruthy(); + expect(() => parseGateContext("attempts-exhausted", { step: "produce", attempts: 1, maximum_attempts: 2 })).toThrow(); + + const adjudication = parseGateContext("adjudication-failure", { constitution: "fail", failed_rules: [RULE], uncertain_rules: [], eligible_waiver_rules: [], waiver_scope: { operation: "adjudication-failure", boundary: "phase" } }); + expect(() => validateGateDecision("adjudication-failure", adjudication, { decision: "approve", reason: "Handled", resolutions: [] })).toThrow(); + expect(validateGateDecision("adjudication-failure", adjudication, { decision: "approve", reason: "Handled", resolutions: [{ rule: RULE, resolution: "Accepted mitigation" }] })).toBeTruthy(); + + const authority = { link_digest: D, purpose: "restore-adoption" as const, proposed_generation_digest: D, changed_input_fingerprint: D }; + const restore = parseGateContext("restore-collision", { path: "task/file.md", recorded_generation_digest: D, current_generation_digest: D, adoption_candidate: authority }); + expect(validateGateDecision("restore-collision", restore, { decision: "adopt-as-new-generation", reason: "Keep edits", adoption_authority: restore.adoption_candidate!, rationale: "Reviewed" })).toBeTruthy(); + expect(() => validateGateDecision("restore-collision", restore, { decision: "adopt-as-new-generation", reason: "Keep edits", adoption_authority: { ...authority, link_digest: "b".repeat(64) }, rationale: "Reviewed" } as never)).toThrow(); + }); + + it("makes semantic decision correlation mandatory in the public gate parser", () => { + const context = { matched_rules: [RULE], uncertain_rules: [], eligible_waiver_rules: [], waiver_scope: { operation: "review-trigger", boundary: "subject" } } as const; + expect(() => parseGateContract({ kind: "review-trigger", context, payload: { decision: "waiver-requested", reason: "Exception", rule: RULE, rationale: "Temporary" } })).toThrow(/eligible/); + expect(() => parseGateContract({ kind: "attempts-exhausted", context: { step: "produce", attempts: 1, maximum_attempts: 2 }, payload: { decision: "abort", reason: "Stop" } })).toThrow(/attempts/); + }); + + it("parses kind-correlated envelopes and exposes effects", () => { + const envelope = parseGateDecisionEnvelope({ schema_version: "1", gate_id: "gate-1", task_id: "task-1", phase_instance: "phase-impl-2", subject_digest: D, context_digest: D, human_provenance: { schema_version: "1", actor_class: "human", assurance: "declared-local-trace", channel: "archflow-local", decision_event_id: "decision-1", helper_invocation_id: "helper-1", recorded_at: "2026-07-27T12:00:00.000Z" }, kind: "commit-authorization", payload: { decision: "authorize-commit", reason: "Approved" } }); + expect(envelope.kind).toBe("commit-authorization"); + expect(gateDecisionEffect(envelope.payload)).toBe("advance"); + expect(gateDecisionEffect({ decision: "waiver-requested", reason: "x", rule: RULE, rationale: "x" })).toBe("redirect-waiver"); + expect(() => parseGateDecisionEnvelope({ ...envelope, human_provenance: { ...envelope.human_provenance, recorded_at: "2026-07-27T12:00:00Z" } })).toThrow(); + expect(() => parseGateDecisionEnvelope({ ...envelope, human_provenance: { ...envelope.human_provenance, recorded_at: "2026-07-27T07:00:00.000-05:00" } })).toThrow(); + }); +}); diff --git a/test/unit/mcp-tools.test.ts b/test/unit/mcp-tools.test.ts new file mode 100644 index 00000000..b5c7b472 --- /dev/null +++ b/test/unit/mcp-tools.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vitest"; +import { parseSha256Digest } from "../../src/contracts/evidence.js"; +import { bindParsedToolCallRequest, correlateProjectResult, createInternalResultExpectation, parseToolCall, TOOL_DEFINITIONS, validateProjectResultStructure } from "../../src/contracts/mcp-tools.js"; +import { parseTaskPathClaim } from "../../src/contracts/path-claims.js"; + +const digest = parseSha256Digest("a".repeat(64)); +const stateInput = { schema_version: "1", task_id: "task-1", intent_id: "intent-1", expected_revision: 2, input_fingerprint: digest, phase_instance: "phase-impl-2", step: "produce", status: "succeeded" } as const; + +describe("correlated MCP tool contracts", () => { + it("publishes exactly five exact schema fragment pairs", () => { + expect(Object.keys(TOOL_DEFINITIONS)).toEqual(["archflow_state", "archflow_counter_review", "archflow_adjudicate", "archflow_gate", "archflow_waiver"]); + for (const [name, definition] of Object.entries(TOOL_DEFINITIONS)) { + expect(definition.input_schema_id).toBe(`https://archflow.dev/schemas/v1/mcp-tools#/$defs/${name}/input`); + expect(definition.result_schema_id).toBe(`https://archflow.dev/schemas/v1/mcp-tools#/$defs/${name}/result`); + } + }); + it("rejects state artifacts and checks direct request/result equalities", () => { + expect(() => parseToolCall("archflow_state", { ...stateInput, artifact: null })).toThrow(); + const call = bindParsedToolCallRequest(parseToolCall("archflow_state", stateInput), parseSha256Digest("b".repeat(64))); + expect(() => validateProjectResultStructure(call, { schema_version: "1", ok: true, value: { path: "phases/2/result.json", revision: 3, status: "failed" } })).toThrow(/status mismatch/); + }); + it("keeps structural validation distinct from authoritative expectation correlation", () => { + const call = bindParsedToolCallRequest(parseToolCall("archflow_state", stateInput), parseSha256Digest("b".repeat(64))); + const value = { path: parseTaskPathClaim("phases/2/result.json"), revision: 3, status: "succeeded" } as const; + const structural = validateProjectResultStructure(call, { schema_version: "1", ok: true, value }); + const expectation = createInternalResultExpectation({ schema_version: "1", tool: "archflow_state", task_id: "task-1", intent_id: "intent-1", input_fingerprint: digest, request_digest: parseSha256Digest("b".repeat(64)), result_id: "result-1", resulting_revision: 3, success: value }); + expect(correlateProjectResult(call, expectation, structural)).toEqual(expect.objectContaining({ ok: true, value })); + const wrong = createInternalResultExpectation({ ...expectation, result_id: "result-2", resulting_revision: 4, success: { ...value, revision: 4 } }); + expect(() => correlateProjectResult(call, wrong, structural)).toThrow(/expectation mismatch/); + const otherRequest = bindParsedToolCallRequest(parseToolCall("archflow_state", stateInput), parseSha256Digest("c".repeat(64))); + expect(() => correlateProjectResult(otherRequest, expectation, validateProjectResultStructure(otherRequest, { schema_version: "1", ok: true, value }))).toThrow(/invocation mismatch/); + expect(() => correlateProjectResult(call, { ...expectation }, structural)).toThrow(/authentic/); + expect(() => correlateProjectResult({ ...call }, expectation, structural)).toThrow(/authentic/); + }); + + it("uses the authoritative exact current-evidence tuple parser for gates", () => { + const self = { role: "self-review", evidence_digest: "1".repeat(64), assurance: "agent-declared", producer_family: "claude", reviewer_family: "claude", independence: "same-family-self" }; + const counter = { role: "counter-review", evidence_digest: "2".repeat(64), assurance: "server-attested", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family" }; + const base = { schema_version: "1", task_id: "Task:1", intent_id: "Intent:1", expected_revision: 0, input_fingerprint: digest, phase_instance: "phase-impl-2", summary: "Review", subject_digest: digest, current_evidence: { set_digest: "3".repeat(64), slots: [self, counter] }, kind: "artifact-approval", context: { artifact_kind: "phase-implementation" } }; + expect(parseToolCall("archflow_gate", base).input.task_id).toBe("Task:1"); + expect(() => parseToolCall("archflow_gate", { ...base, current_evidence: { ...base.current_evidence, slots: [counter, self] } })).toThrow(); + expect(() => parseToolCall("archflow_gate", { ...base, current_evidence: { ...base.current_evidence, slots: [self, { ...counter, evidence_digest: self.evidence_digest }] } })).toThrow(); + expect(() => parseToolCall("archflow_gate", { ...base, current_evidence: { ...base.current_evidence, slots: [self, { ...counter, reviewer_family: "claude" }] } })).toThrow(); + }); + + it("enforces waiver origin identity and canonical UTC-millisecond provenance", () => { + const origin = { origin_gate_id: "Gate:1", origin_decision_digest: "1".repeat(64), origin_context_digest: "2".repeat(64), task_id: "Task_1", phase_instance: "phase-impl-2", subject_digest: "3".repeat(64), current_evidence_set_digest: "4".repeat(64), rule: { rule_id: "Rule:1", rule_version: 1 }, scope: { operation: "review-trigger", boundary: "subject" } }; + const input = { schema_version: "1", task_id: "Task_1", intent_id: "Intent:1", expected_revision: 0, input_fingerprint: digest, origin, rationale: "Needed" }; + expect(() => parseToolCall("archflow_waiver", { ...input, task_id: "Other" })).toThrow(/task_id/); + const call = parseToolCall("archflow_waiver", input); + const success = { origin_gate_id: "Gate:1", waiver_gate_id: "Gate:2", task_id: "Task_1", rule_id: "Rule:1", rule_version: 1, subject_digest: "3".repeat(64), current_evidence_set_digest: "4".repeat(64), scope: origin.scope, human_provenance: { schema_version: "1", actor_class: "human", assurance: "declared-local-trace", channel: "archflow-local", decision_event_id: "Decision:1", helper_invocation_id: "Helper:1", recorded_at: "2026-07-27T12:00:00.000Z" }, granted: false, notes: "Denied", revision: 1 }; + expect(validateProjectResultStructure(call, { schema_version: "1", ok: true, value: success }).ok).toBe(true); + expect(() => validateProjectResultStructure(call, { schema_version: "1", ok: true, value: { ...success, human_provenance: { ...success.human_provenance, recorded_at: "2026-07-27T12:00:00Z" } } })).toThrow(); + }); +}); diff --git a/test/unit/path-claims.test.ts b/test/unit/path-claims.test.ts new file mode 100644 index 00000000..4b1d9fba --- /dev/null +++ b/test/unit/path-claims.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; + +import { parseTaskPathClaim, type TaskPathClaim } from "../../src/contracts/index.js"; + +describe("task path claims", () => { + it.each([ + "artifact.md", + "reviews/phase-2.md", + ".archflow/tasks/example/prd.md", + "資料/設計.md" + ])("accepts bounded slash-separated lexical claim %s", (value) => { + expect(parseTaskPathClaim(value)).toBe(value); + }); + + it.each([ + "", + "/absolute", + "//server/share", + "C:/drive/path", + "c:relative-drive", + "back\\slash", + "double//slash", + ".", + "..", + "./child", + "../child", + "child/.", + "child/..", + "child/../escape", + "control\u0000byte", + "line\nbreak" + ])("rejects unsafe lexical alias %s", (value) => { + expect(() => parseTaskPathClaim(value)).toThrow(); + }); + + it("bounds UTF-8 bytes rather than JavaScript string length", () => { + expect(parseTaskPathClaim("é".repeat(512))).toHaveLength(512); + expect(() => parseTaskPathClaim("é".repeat(513))).toThrow(/1024 UTF-8 bytes/iu); + }); + + it("does not let a string mint lexical or resolved path authority", () => { + expectTypeOf().toMatchTypeOf(); + // @ts-expect-error a plain string is not a validated lexical claim + const untrusted: TaskPathClaim = "reviews/result.md"; + type ResolvedSafePath = string & { readonly __resolvedSafePath: unique symbol }; + const lexical = parseTaskPathClaim("reviews/result.md"); + // @ts-expect-error a lexical claim is not Phase 4 resolved-safe-path authority + const resolved: ResolvedSafePath = lexical; + expect(untrusted).toBe(lexical); + expect(resolved).toBe(lexical); + }); +}); diff --git a/test/unit/renderers.test.ts b/test/unit/renderers.test.ts new file mode 100644 index 00000000..4b55dc0c --- /dev/null +++ b/test/unit/renderers.test.ts @@ -0,0 +1,72 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +import { parseSha256Digest } from "../../src/contracts/evidence.js"; +import { createTestAuthorityLink, createTestCurrentReviewSetAuthority, createTestVerifiedReferencedEvidence } from "../../src/contracts/internal/test-capabilities.js"; +import { encodePhaseInstance } from "../../src/contracts/phase-instance.js"; +import { renderAdjudicationEvidence, renderReviewEvidence, renderTriage } from "../../src/contracts/renderers.js"; +import type { AgentDeclaredReview, DegradedReview } from "../../src/contracts/review.js"; +import { authorityQualifier, type QualifiedAdjudicationEvidence, type QualifiedReviewEvidence } from "../../src/contracts/trust.js"; +import { validateTriage } from "../../src/contracts/triage.js"; + +const digest = (character: string) => parseSha256Digest(character.repeat(64)); +const phase = encodePhaseInstance({ kind: "phase-impl", phase: 2 as never }); + +const reviewEvidence = (role: "self-review" | "counter-review", evidenceDigest: ReturnType): AgentDeclaredReview | DegradedReview => ({ + schema_version: "1", task_id: "task", phase_instance: phase, step: role === "self-review" ? "self_review" : "counter_review", role, + subject_digest: digest("a"), input_fingerprint: digest("b"), rubric_digest: digest("c"), producer_family: "claude", + findings: role === "self-review" ? [] : [{ finding_id: "spoof", severity: "minor", blocking: false, summary: "# injected\n| table |\n```&\u202e", evidence: "ok", suggested_resolution: "none" }], + matched_rule_versions: [], verdict: role === "self-review" ? "pass" : "advisory", blocking_count: 0, + ...(role === "self-review" + ? { assurance: "agent-declared", model_family: "claude", model: "self", effort: "high" } + : { assurance: "degraded", model_family: "codex", model: "unknown", effort: "unknown", reason: "manual" }), +}) as AgentDeclaredReview | DegradedReview; + +function qualifyReview(role: "self-review" | "counter-review", evidenceDigest: ReturnType): QualifiedReviewEvidence { + const evidence = reviewEvidence(role, evidenceDigest); + const verified = createTestVerifiedReferencedEvidence<"review", "agent-declared" | "degraded">("review", { evidence_digest: evidenceDigest, evidence } as never); + const authority = evidence.assurance === "agent-declared" + ? { kind: "agent-declared", result_id: "result-1", result_digest: digest("8"), state_revision: 1 } as const + : { kind: "degraded", checkpoint_digest: digest("8"), checkpoint_revision: 1 } as const; + const link = createTestAuthorityLink({ schema_version: "1", evidence_kind: "review", assurance: evidence.assurance, role, task_id: "task", phase_instance: phase, subject_digest: digest("a"), input_fingerprint: digest("b"), evidence_digest: evidenceDigest, authority } as never); + return authorityQualifier.qualifyReview(link as never, verified as never); +} + +describe("anti-spoofing renderers", () => { + it("renders genuinely qualified review evidence and visibly escapes prose", () => { + const value = qualifyReview("counter-review", digest("2")); + const bytes = renderReviewEvidence(value); + const rendered = new TextDecoder().decode(bytes); + expect(rendered.startsWith("# ArchFlow Review Evidence\nschema_version:")).toBe(true); + expect(rendered).toContain("\\u000a"); expect(rendered).toContain("\\u0060"); expect(rendered).toContain("\\u003c"); expect(rendered).toContain("\\u202e"); + expect(rendered.endsWith("\n")).toBe(true); expect(rendered.endsWith("\n\n")).toBe(false); expect(rendered).not.toContain("\r"); + expect(() => renderReviewEvidence({ ...value } as never)).toThrow(/qualified review/); + expect(() => renderReviewEvidence({ evidence_digest: digest("2"), evidence: value.evidence, authority: value.authority } as never)).toThrow(/qualified review/); + }); + + it("rejects forged and spread-cloned adjudication evidence", async () => { + const raw = JSON.parse(await readFile(new URL("../fixtures/contracts/adjudication/valid.json", import.meta.url), "utf8")) as Record; + const evidence = { ...raw, assurance: "degraded", model_family: "unknown", model: "unknown", effort: "unknown", reason: "manual" }; + const verified = createTestVerifiedReferencedEvidence<"adjudication", "degraded">("adjudication", { evidence_digest: digest("4"), evidence } as never); + const link = createTestAuthorityLink({ schema_version: "1", evidence_kind: "adjudication", assurance: "degraded", role: "adjudication", task_id: "mcp-integration", phase_instance: phase, subject_digest: digest("a"), input_fingerprint: digest("b"), evidence_digest: digest("4"), authority: { kind: "degraded", checkpoint_digest: digest("8"), checkpoint_revision: 1 } }); + const qualified = authorityQualifier.qualifyAdjudication(link, verified) as QualifiedAdjudicationEvidence; + expect(new TextDecoder().decode(renderAdjudicationEvidence(qualified))).toMatch(/^# ArchFlow Adjudication Evidence/mu); + expect(() => renderAdjudicationEvidence({ ...qualified } as never)).toThrow(/qualified adjudication/); + expect(() => renderAdjudicationEvidence({ evidence_digest: digest("4"), evidence, authority: link } as never)).toThrow(/qualified adjudication/); + }); + + it("renders only identity-authenticated validated triage", () => { + const self = qualifyReview("self-review", digest("1")); + const counter = qualifyReview("counter-review", digest("2")); + const slots = [ + { role: "self-review", evidence_digest: digest("1"), assurance: "agent-declared", producer_family: "claude", reviewer_family: "claude", independence: "same-family-self" }, + { role: "counter-review", evidence_digest: digest("2"), assurance: "degraded", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family" }, + ] as const; + const set = authorityQualifier.currentReviews(createTestCurrentReviewSetAuthority({ task_id: "task", phase_instance: phase, subject_digest: digest("a"), input_fingerprint: digest("b"), slots }), [self, counter]); + const candidate = { schema_version: "1", task_id: "task", phase_instance: phase, step: "triage", subject_digest: digest("a"), input_fingerprint: digest("b"), current_evidence_set_digest: set.current_evidence_set.set_digest, source_evidence_digests: [digest("1"), digest("2")], dispositions: [{ review_evidence_digest: digest("2"), finding_id: "spoof", disposition: "rejected", rationale: "not applicable", evidence: "source confirms" }], accepted_count: 0, rejected_count: 1 }; + const validated = validateTriage(set, candidate); + expect(new TextDecoder().decode(renderTriage(validated))).toMatch(/^# ArchFlow Review Triage/mu); + expect(() => renderTriage({ ...validated } as never)).toThrow(/validated triage/); + expect(() => renderTriage(candidate as never)).toThrow(/validated triage/); + }); +}); diff --git a/test/unit/review.test.ts b/test/unit/review.test.ts new file mode 100644 index 00000000..57ca1b0f --- /dev/null +++ b/test/unit/review.test.ts @@ -0,0 +1,10 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; +import { parseAndDeriveReview, parseReferencedReviewEvidence, parseReviewEvidence } from "../../src/contracts/review.js"; + +const fixture = async (name: string) => JSON.parse(await readFile(new URL(`../fixtures/contracts/review/${name}`, import.meta.url), "utf8")) as unknown; +describe("review semantics", () => { + it("checks exact verdict and count without mutating raw claims", async () => { const value = await fixture("valid.json"); const invalid = await fixture("invalid-contradiction.json"); const before = structuredClone(value); expect(parseAndDeriveReview(value).verdict).toBe("fail"); expect(value).toEqual(before); expect(() => parseAndDeriveReview(invalid)).toThrow(/blocking_count/); }); + it("keeps provenance variants closed and disallows server-attested self-review", async () => { const review = await fixture("valid.json") as Record; const declared = { ...review, assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }; expect(parseReviewEvidence(declared).assurance).toBe("agent-declared"); expect(() => parseReviewEvidence({ ...declared, adapter: "codex-cli" })).toThrow(); expect(() => parseReviewEvidence({ ...declared, assurance: "server-attested", adapter: "codex-cli", cli_version: "1", model_family: "codex", model: "gpt", effort: "high", invocation_id: "invocation-1", envelope_input_digest: "d".repeat(64), observed_output_digest: "e".repeat(64), result_id: "result-1", role: "self-review", step: "self_review" })).toThrow(/server-attested/); }); + it("composes evidence and referenced-evidence parsing through all raw semantics", async () => { const review = await fixture("valid.json") as Record; const declared = { ...review, assurance: "agent-declared", model_family: "unknown", model: "unknown", effort: "unknown" }; const duplicate = { ...declared, findings: [...(review.findings as unknown[]), ...(review.findings as unknown[])] }; expect(() => parseReviewEvidence(duplicate)).toThrow(/duplicate finding_id/); expect(() => parseReferencedReviewEvidence({ evidence_digest: "d".repeat(64), evidence: duplicate })).toThrow(/duplicate finding_id/); expect(() => parseReviewEvidence({ ...declared, verdict: "pass" })).toThrow(/verdict/); expect(() => parseReviewEvidence({ ...declared, role: "self-review", step: "counter_review" })).toThrow(/self-review role/); }); +}); diff --git a/test/unit/supplemental.test.ts b/test/unit/supplemental.test.ts new file mode 100644 index 00000000..f9e8d441 --- /dev/null +++ b/test/unit/supplemental.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { parseSupplementalReviewOutcome } from "../../src/contracts/supplemental.js"; + +const digest = (character: string) => character.repeat(64); +const review = { prior_gate_id: "gate-1", task_id: "task", phase_instance: "phase-impl-2", subject_digest: digest("a"), input_fingerprint: digest("b"), evidence_slot: { role: "gate-counter-review", evidence_digest: digest("c"), assurance: "degraded", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family", gate_id: "gate-1" } }; +describe("supplemental review outcomes", () => { + it("keeps decline gate-only and enforces gate-bound evidence", () => { + expect(parseSupplementalReviewOutcome({ action: "decline", gate: { prior_gate_id: "gate-1", task_id: "task", phase_instance: "phase-impl-2", subject_digest: digest("a"), input_fingerprint: digest("b") }, reason: "declined" }).action).toBe("decline"); + expect(() => parseSupplementalReviewOutcome({ action: "ingest", review: { ...review, evidence_slot: { ...review.evidence_slot, gate_id: "gate-2" } }, reason: "late evidence" })).toThrow(/prior_gate_id/); + }); + it("requires supersession to change the bound subject", () => { + expect(parseSupplementalReviewOutcome({ action: "supersede", review, accepted_triage_digest: digest("d"), old_subject_digest: digest("a"), new_subject_digest: digest("e"), reason: "revision required" }).action).toBe("supersede"); + expect(() => parseSupplementalReviewOutcome({ action: "supersede", review, accepted_triage_digest: digest("d"), old_subject_digest: digest("a"), new_subject_digest: digest("a"), reason: "revision required" })).toThrow(/new subject/); + }); + it("round-trips the shared broad safe identifier grammar", () => { + const broad = { ...review, prior_gate_id: "Gate:1", task_id: "Task_1", evidence_slot: { ...review.evidence_slot, gate_id: "Gate:1" } }; + const parsed = parseSupplementalReviewOutcome({ action: "ingest", review: broad, reason: "late evidence" }); + expect(parsed.action === "ingest" && parsed.review.prior_gate_id).toBe("Gate:1"); + }); +}); diff --git a/test/unit/tool-names.test.ts b/test/unit/tool-names.test.ts new file mode 100644 index 00000000..82cde1f0 --- /dev/null +++ b/test/unit/tool-names.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; + +import { isToolName, TOOL_NAMES, type ToolName } from "../../src/contracts/index.js"; + +describe("five-tool vocabulary", () => { + it("contains exactly the five architecture names in canonical order", () => { + expect(TOOL_NAMES).toEqual([ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver" + ]); + expect(Object.isFrozen(TOOL_NAMES)).toBe(true); + expect(new Set(TOOL_NAMES)).toHaveLength(5); + }); + + it("narrows only exact names", () => { + for (const name of TOOL_NAMES) expect(isToolName(name)).toBe(true); + for (const value of ["archflow_init", "ARCHFLOW_STATE", " archflow_state", 1, null]) { + expect(isToolName(value)).toBe(false); + } + expectTypeOf().toEqualTypeOf<(typeof TOOL_NAMES)[number]>(); + }); +}); diff --git a/test/unit/triage.test.ts b/test/unit/triage.test.ts new file mode 100644 index 00000000..4617e531 --- /dev/null +++ b/test/unit/triage.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; + +import { parseSha256Digest } from "../../src/contracts/evidence.js"; +import { createTestAuthorityLink, createTestCurrentReviewSetAuthority, createTestVerifiedReferencedEvidence } from "../../src/contracts/internal/test-capabilities.js"; +import { encodePhaseInstance } from "../../src/contracts/phase-instance.js"; +import { authorityQualifier, type QualifiedReviewEvidence } from "../../src/contracts/trust.js"; +import { validateTriage } from "../../src/contracts/triage.js"; + +const digest = (character: string) => parseSha256Digest(character.repeat(64)); +const phase = encodePhaseInstance({ kind: "phase-impl", phase: 2 as never }); + +function qualify(role: "self-review" | "counter-review", evidenceDigest: ReturnType): QualifiedReviewEvidence { + const self = role === "self-review"; + const evidence = { schema_version: "1", task_id: "task", phase_instance: phase, step: self ? "self_review" : "counter_review", role, subject_digest: digest("a"), input_fingerprint: digest("b"), rubric_digest: digest("c"), producer_family: "claude", findings: [{ finding_id: "same-id", severity: "minor", blocking: false, summary: "summary", evidence: "evidence", suggested_resolution: "resolution" }], matched_rule_versions: [], verdict: "advisory", blocking_count: 0, ...(self ? { assurance: "agent-declared", model_family: "claude", model: "model", effort: "high" } : { assurance: "degraded", model_family: "codex", model: "model", effort: "unknown", reason: "manual" }) } as const; + const verified = createTestVerifiedReferencedEvidence<"review", "agent-declared" | "degraded">("review", { evidence_digest: evidenceDigest, evidence } as never); + const authority = self ? { kind: "agent-declared", result_id: "result-1", result_digest: digest("f"), state_revision: 1 } as const : { kind: "degraded", checkpoint_digest: digest("f"), checkpoint_revision: 1 } as const; + const link = createTestAuthorityLink({ schema_version: "1", evidence_kind: "review", assurance: evidence.assurance, role, task_id: "task", phase_instance: phase, subject_digest: digest("a"), input_fingerprint: digest("b"), evidence_digest: evidenceDigest, authority } as never); + return authorityQualifier.qualifyReview(link as never, verified as never); +} + +const reviews = [qualify("self-review", digest("1")), qualify("counter-review", digest("2"))] as const; +const slots = [ + { role: "self-review", evidence_digest: digest("1"), assurance: "agent-declared", producer_family: "claude", reviewer_family: "claude", independence: "same-family-self" }, + { role: "counter-review", evidence_digest: digest("2"), assurance: "degraded", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family" }, +] as const; +const current = authorityQualifier.currentReviews(createTestCurrentReviewSetAuthority({ task_id: "task", phase_instance: phase, subject_digest: digest("a"), input_fingerprint: digest("b"), slots }), reviews); +const disposition = (reviewDigest: ReturnType) => ({ review_evidence_digest: reviewDigest, finding_id: "same-id", disposition: "rejected", rationale: "not applicable", evidence: "source confirms" }); +const candidate = { schema_version: "1", task_id: "task", phase_instance: phase, step: "triage", subject_digest: digest("a"), input_fingerprint: digest("b"), current_evidence_set_digest: current.current_evidence_set.set_digest, source_evidence_digests: [digest("1"), digest("2")], dispositions: [disposition(digest("1")), disposition(digest("2"))], accepted_count: 0, rejected_count: 2 }; + +describe("exact-set triage", () => { + it("uses composite finding identities", () => { expect(validateTriage(current, candidate).dispositions).toHaveLength(2); }); + it("rejects omissions, duplicates, and foreign review digests", () => { + expect(() => validateTriage(current, { ...candidate, dispositions: candidate.dispositions.slice(1), rejected_count: 1 })).toThrow(/exactly cover/); + expect(() => validateTriage(current, { ...candidate, dispositions: [candidate.dispositions[0], candidate.dispositions[0]], rejected_count: 2 })).toThrow(/duplicate/); + expect(() => validateTriage(current, { ...candidate, dispositions: [disposition(digest("3")), candidate.dispositions[1]] })).toThrow(/foreign or stale/); + }); + it("rejects cast and spread-cloned current review sets", () => { + expect(() => validateTriage({ ...current } as never, candidate)).toThrow(/authenticated/); + }); +}); diff --git a/test/unit/trust.test.ts b/test/unit/trust.test.ts new file mode 100644 index 00000000..13967dc3 --- /dev/null +++ b/test/unit/trust.test.ts @@ -0,0 +1,144 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +import { parseSha256Digest } from "../../src/contracts/evidence.js"; +import { + createTestAuthorityLink, + createTestCurrentReviewSetAuthority, + createTestObservationCapability, + createTestVerifiedReferencedEvidence, +} from "../../src/contracts/internal/test-capabilities.js"; +import { encodePhaseInstance } from "../../src/contracts/phase-instance.js"; +import type { DegradedReview, ServerAttestedReview } from "../../src/contracts/review.js"; +import { + authorityQualifier, + observationSource, + parseAuthorityLinkData, + type AuthorityLinkData, + type ObservationBindingByKind, + type QualifiedReviewEvidence, + type ReviewEvidenceSlot, +} from "../../src/contracts/trust.js"; + +const digest = (character: string) => parseSha256Digest(character.repeat(64)); +const phase = encodePhaseInstance({ kind: "phase-impl", phase: 2 as never }); + +async function rawReview(): Promise> { + return JSON.parse(await readFile(new URL("../fixtures/contracts/review/valid.json", import.meta.url), "utf8")) as Record; +} + +const degradedReview = (role: "counter-review" | "gate-counter-review" = "counter-review"): DegradedReview => ({ + schema_version: "1", task_id: "mcp-integration", phase_instance: phase, step: "counter_review", role, + subject_digest: digest("a"), input_fingerprint: digest("b"), rubric_digest: digest("c"), producer_family: "claude", + findings: [{ finding_id: "unsafe-path", severity: "blocker", blocking: true, summary: "Path is unsafe.", evidence: "The path escapes its task.", suggested_resolution: "Reject traversal." }], + matched_rule_versions: [{ rule_id: "safe-paths", rule_version: 2 }], verdict: "fail", blocking_count: 1, + assurance: "degraded", model_family: "codex", model: "unknown", effort: "unknown", reason: "Manual fallback.", +}); + +function degradedLink(evidence: DegradedReview, evidenceDigest = digest("9"), gateId?: string): AuthorityLinkData<"review", "degraded"> { + return { + schema_version: "1", evidence_kind: "review", assurance: "degraded", role: evidence.role, + task_id: evidence.task_id, phase_instance: phase, subject_digest: evidence.subject_digest, + input_fingerprint: evidence.input_fingerprint, evidence_digest: evidenceDigest, + ...(gateId === undefined ? {} : { gate_id: gateId }), + authority: { kind: "degraded", checkpoint_digest: digest("8"), checkpoint_revision: 1 }, + }; +} + +function qualifyDegraded(role: "counter-review" | "gate-counter-review" = "counter-review", gateId?: string, evidenceDigest = digest("9")): QualifiedReviewEvidence { + const evidence = degradedReview(role); + const verified = createTestVerifiedReferencedEvidence<"review", "degraded">("review", { evidence_digest: evidenceDigest, evidence }); + return authorityQualifier.qualifyReview(createTestAuthorityLink(degradedLink(evidence, evidenceDigest, gateId)), verified); +} + +describe("invocation-scoped observation trust", () => { + it("hashes exact private output bytes, deep-freezes evidence, and binds attestation", async () => { + const raw = await rawReview(); + const bytes = new TextEncoder().encode(JSON.stringify(raw)); + const binding: ObservationBindingByKind["review"] = { kind: "review", task_id: "mcp-integration", phase_instance: phase, role: "counter-review", subject_digest: parseSha256Digest(raw.subject_digest), input_fingerprint: parseSha256Digest(raw.input_fingerprint), invocation_id: "invocation-1", envelope_input_digest: digest("d"), result_id: "result-1", adapter: "codex-cli", cli_version: "1.0.0", family: "codex", model: "gpt-5", effort: "high", rubric_digest: parseSha256Digest(raw.rubric_digest), producer_family: "claude" }; + const capability = createTestObservationCapability<"review">(binding); + (binding as { model: string }).model = "changed-after-mint"; + const result = observationSource.observeReview(capability, bytes); + bytes.fill(0); + const exposed = result.observation.raw_output_bytes; + exposed.fill(0); + expect(result.observation.raw_output_bytes).not.toEqual(exposed); + expect(result.evidence.model).toBe("gpt-5"); + expect(result.evidence.observed_output_digest).toBe(result.observation.raw_output_digest); + expect(Object.isFrozen(result.evidence.findings)).toBe(true); + expect(Object.isFrozen(result.evidence.findings[0])).toBe(true); + expect(() => observationSource.observeReview({ ...capability } as never, result.observation.raw_output_bytes)).toThrow(/capability/); + const altered = { ...raw, subject_digest: "f".repeat(64) }; + expect(() => observationSource.observeReview(capability, new TextEncoder().encode(JSON.stringify(altered)))).toThrow(/subject_digest/); + }); + + it("enforces the fixed adapter-family relation", async () => { + const raw = await rawReview(); + const capability = createTestObservationCapability<"review">({ kind: "review", task_id: "mcp-integration", phase_instance: phase, role: "counter-review", subject_digest: parseSha256Digest(raw.subject_digest), input_fingerprint: parseSha256Digest(raw.input_fingerprint), invocation_id: "invocation-1", envelope_input_digest: digest("d"), result_id: "result-1", adapter: "claude-cli", cli_version: "1.0.0", family: "codex", model: "gpt-5", effort: "high", rubric_digest: parseSha256Digest(raw.rubric_digest), producer_family: "claude" }); + expect(() => observationSource.observeReview(capability, new TextEncoder().encode(JSON.stringify(raw)))).toThrow(/adapter and model family/); + }); +}); + +describe("identity-backed authority", () => { + it("rejects plain, cast, spread-cloned, cross-kind, and cross-assurance values", () => { + const evidence = degradedReview(); + const link = createTestAuthorityLink(degradedLink(evidence)); + const verified = createTestVerifiedReferencedEvidence<"review", "degraded">("review", { evidence_digest: digest("9"), evidence }); + (evidence as { reason: string }).reason = "changed-after-mint"; + expect(verified.evidence.reason).toBe("Manual fallback."); + expect(authorityQualifier.qualifyReview(link, verified).evidence.assurance).toBe("degraded"); + expect(() => authorityQualifier.qualifyReview({ ...link } as never, verified)).toThrow(/untrusted/); + expect(() => authorityQualifier.qualifyReview(link, { ...verified } as never)).toThrow(/untrusted/); + expect(() => authorityQualifier.qualifyReview(degradedLink(evidence) as never, { evidence_digest: digest("9"), evidence } as never)).toThrow(/untrusted/); + const wrongKind = createTestVerifiedReferencedEvidence<"adjudication", "degraded">("adjudication", { evidence_digest: digest("9"), evidence } as never); + expect(() => authorityQualifier.qualifyReview(link, wrongKind as never)).toThrow(/untrusted/); + const wrongAssurance = createTestAuthorityLink({ ...degradedLink(evidence), assurance: "agent-declared", authority: { kind: "agent-declared", result_id: "result-1", result_digest: digest("7"), state_revision: 1 } } as AuthorityLinkData<"review", "agent-declared">); + expect(() => authorityQualifier.qualifyReview(wrongAssurance, verified as never)).toThrow(/untrusted|does not match/); + }); + + it("correlates every duplicated server provenance field", async () => { + const raw = await rawReview(); + const capability = createTestObservationCapability<"review">({ kind: "review", task_id: "mcp-integration", phase_instance: phase, role: "counter-review", subject_digest: parseSha256Digest(raw.subject_digest), input_fingerprint: parseSha256Digest(raw.input_fingerprint), invocation_id: "invocation-1", envelope_input_digest: digest("d"), result_id: "result-1", adapter: "codex-cli", cli_version: "1.0.0", family: "codex", model: "gpt-5", effort: "high", rubric_digest: parseSha256Digest(raw.rubric_digest), producer_family: "claude" }); + const evidence = observationSource.observeReview(capability, new TextEncoder().encode(JSON.stringify(raw))).evidence; + const verified = createTestVerifiedReferencedEvidence<"review", "server-attested">("review", { evidence_digest: digest("9"), evidence }); + const authority = { kind: "server", invocation_id: evidence.invocation_id, result_id: evidence.result_id, receipt_id: "receipt-1", state_revision: 1, envelope_input_digest: evidence.envelope_input_digest, observed_output_digest: evidence.observed_output_digest, result_digest: digest("7") } as const; + const base: AuthorityLinkData<"review", "server-attested"> = { schema_version: "1", evidence_kind: "review", assurance: "server-attested", role: "counter-review", task_id: evidence.task_id, phase_instance: phase, subject_digest: evidence.subject_digest, input_fingerprint: evidence.input_fingerprint, evidence_digest: digest("9"), authority }; + expect(authorityQualifier.qualifyReview(createTestAuthorityLink(base), verified).evidence).toBe(verified.evidence); + for (const [field, value] of [["invocation_id", "invocation-2"], ["result_id", "result-2"], ["envelope_input_digest", digest("e")], ["observed_output_digest", digest("f")]] as const) { + const substituted = createTestAuthorityLink({ ...base, authority: { ...authority, [field]: value } }); + expect(() => authorityQualifier.qualifyReview(substituted, verified)).toThrow(/provenance/); + } + }); + + it("requires authentic qualified reviews and exact gate identity for current sets", () => { + const gateReview = qualifyDegraded("gate-counter-review", "Gate:1", digest("3")); + const selfEvidence = { + schema_version: "1", task_id: "mcp-integration", phase_instance: phase, step: "self_review", role: "self-review", + subject_digest: digest("a"), input_fingerprint: digest("b"), rubric_digest: digest("c"), producer_family: "claude", + findings: [], matched_rule_versions: [], verdict: "pass", blocking_count: 0, + assurance: "agent-declared", model_family: "claude", model: "self", effort: "high", + } as const; + const selfDigest = digest("1"); + const selfVerified = createTestVerifiedReferencedEvidence<"review", "agent-declared">("review", { evidence_digest: selfDigest, evidence: selfEvidence }); + const selfLink = createTestAuthorityLink({ schema_version: "1", evidence_kind: "review", assurance: "agent-declared", role: "self-review", task_id: selfEvidence.task_id, phase_instance: phase, subject_digest: selfEvidence.subject_digest, input_fingerprint: selfEvidence.input_fingerprint, evidence_digest: selfDigest, authority: { kind: "agent-declared", result_id: "result-self", result_digest: digest("6"), state_revision: 1 } }); + const self = authorityQualifier.qualifyReview(selfLink, selfVerified); + const counter = qualifyDegraded(); + const slots = [ + { role: "self-review", evidence_digest: selfDigest, assurance: "agent-declared", producer_family: "claude", reviewer_family: "claude", independence: "same-family-self" }, + { role: "counter-review", evidence_digest: digest("9"), assurance: "degraded", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family" }, + { role: "gate-counter-review", evidence_digest: digest("3"), assurance: "degraded", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family", gate_id: "Gate:2" }, + ] as unknown as readonly ReviewEvidenceSlot[]; + const wrongGateAuthority = createTestCurrentReviewSetAuthority({ task_id: "mcp-integration", phase_instance: phase, subject_digest: digest("a"), input_fingerprint: digest("b"), slots: slots as never }); + expect(() => authorityQualifier.currentReviews(wrongGateAuthority, [self, counter, gateReview])).toThrow(/slot 2|unique/); + expect(() => authorityQualifier.currentReviews({ ...wrongGateAuthority } as never, [self, counter, gateReview])).toThrow(/authority/); + expect(() => authorityQualifier.currentReviews(wrongGateAuthority, [self, { ...counter } as never, gateReview])).toThrow(/slot 1/); + }); + + it("requires gate identity exactly on gate-counter authority links", () => { + const gate = degradedLink(degradedReview("gate-counter-review"), digest("3"), "Gate:1"); + expect(parseAuthorityLinkData(gate).gate_id).toBe("Gate:1"); + const { gate_id: _omitted, ...missingGate } = gate; + expect(() => parseAuthorityLinkData(missingGate)).toThrow(/gate_id/); + expect(() => parseAuthorityLinkData({ ...degradedLink(degradedReview()), gate_id: "Gate:1" })).toThrow(/gate_id/); + }); +}); From f089022d9f3a6f6617e3d54ee828827dc8f77171 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 13:27:40 -0500 Subject: [PATCH 008/124] Archflow: Explore Codebase Context --- .archflow/context/architecture.md | 113 ++++++++++++++++++++++++++++++ .archflow/context/dependencies.md | 72 +++++++++++++++++++ .archflow/context/patterns.md | 59 ++++++++++++++++ 3 files changed, 244 insertions(+) create mode 100644 .archflow/context/architecture.md create mode 100644 .archflow/context/dependencies.md create mode 100644 .archflow/context/patterns.md diff --git a/.archflow/context/architecture.md b/.archflow/context/architecture.md new file mode 100644 index 00000000..cf368b66 --- /dev/null +++ b/.archflow/context/architecture.md @@ -0,0 +1,113 @@ +# Architecture Context + +**Explored:** 2026-07-27 +**Commit:** `8e3144c` + +## Current shape + +This repository is the ArchFlow skills distribution plus an in-progress, contract-first TypeScript implementation of the planned local MCP integration. The implemented runtime code is currently a reusable contract library under `src/contracts/`; there is no MCP transport entry point, stdio server, persistent state engine, or tracked `dist/` bundle yet. The normative future design and phase plan live in `.archflow/tasks/mcp-integration/architecture.md`, while this document describes the code that exists at the stamped commit. + +The package is private, ESM-only, and targets Node 24 / ES2024. `src/contracts/index.ts` is its sole aggregate entry point. A temporary bundle is built from that file for compatibility smoke testing, but the package does not currently declare a public `exports`, `bin`, or production build artifact. + +## Repository map + +| Path | Responsibility | +|---|---| +| `src/contracts/` | TypeScript domain contracts, parsers, validators, trust/provenance rules, canonical renderers, MCP tool request/result shapes, and error catalogues. | +| `src/contracts/schemas/v1/` | Versioned JSON Schema counterparts for the TypeScript/Zod contracts. Contract-agreement tests keep both representations aligned. | +| `src/contracts/internal/` | Non-public capability/branding seams. Test capabilities can construct otherwise unforgeable trust objects without exporting those constructors from `index.ts`. | +| `assets/workflow.yaml` | Shipped fixed ArchFlow phase graph and gate policy. | +| `assets/constitution/` | Shipped repository-wide policy rule templates, one stable/versioned rule per numbered Markdown file. | +| `skills/` | Portable source of truth for the six Claude Code/Codex Agent Skills. This layer is installed by `install.sh` and is not wired to a server executable yet. | +| `test/unit/` | Behavioral tests for individual contract modules and cross-module invariants. | +| `test/contracts/` | Zod/JSON-Schema agreement, schema registry, MCP surface, and exhaustive catalogue tests. | +| `test/fixtures/` | Valid and invalid serialized contract examples used by both test layers. | +| `scripts/` | Temporary bundling/smoke checks and dependency/license/NOTICE policy enforcement. | +| `docs/` | User/process documentation and the preserved originating MCP integration design. | +| `.archflow/tasks/mcp-integration/` | Tracked workflow planning, phase designs/logs, and reviews for the MCP implementation itself. | +| `.github/workflows/ci.yml` | Node-version matrix verification pipeline. | +| `notices/`, `THIRD_PARTY_NOTICES.md` | Retained third-party notice material and the lockfile-derived license inventory. | + +Generated `.tmp/` bundles and installed `node_modules/` are local build products, not architecture sources. `dist/` is deliberately absent at this stage. + +## Entry points and wiring + +### Public contract surface + +`src/contracts/index.ts` re-exports the supported library surface. Consumers are expected to enter through it rather than importing internal trust-brand machinery. Notably, connection contexts are type-exported and only invocation-context derivation is public; server-owned/test-only constructors remain internal. + +The temporary build demonstrates the intended library boundary: + +```js +entryPoints: ["src/contracts/index.ts"], +outfile: ".tmp/archflow-contracts.mjs", +platform: "node", +format: "esm" +``` + +`scripts/smoke-temp-bundle.mjs` dynamically imports that bundle and exercises YAML parsing, JSON Schema validation, review/adjudication derivation, render anti-spoofing, error creation, phase parsing, and the exact five-tool catalogue. + +### Contract layering + +The source dependency flow is mostly inward from generic serialization primitives toward workflow semantics: + +1. `plain-json.ts`, `versions.ts`, `vocabulary.ts`, and `phase-instance.ts` establish safe values, version constants, fixed vocabulary, and canonical phase identifiers. +2. `yaml.ts` and `validators.ts` provide strict YAML parsing and non-mutating Ajv 2020 validation; other parsers preflight input through the plain-JSON boundary. +3. `workflow.ts`, `config.ts`, `rubric.ts`, and `constitution.ts` validate repository configuration and shipped policy assets. +4. `evidence.ts`, `path-claims.ts`, `review.ts`, and `adjudication.ts` define digest-bound evidence, task-scoped paths, review findings, and policy/drift results. +5. `trust.ts` qualifies evidence using invocation/result/authority bindings. `internal/trust-brands.ts` guards authentic branded values; `internal/test-capabilities.ts` exposes controlled fixture seams only to tests. +6. `triage.ts`, `supplemental.ts`, and `renderers.ts` consume qualified evidence to validate exact review-set dispositions and produce canonical human-readable artifacts. +7. `gates.ts` defines gate contexts and decision effects. `errors.ts` composes the domain types into exhaustive project and protocol error catalogues. +8. `mcp-tools.ts` binds the five fixed tool names to versioned request/result schemas, validates calls, correlates results with expected identity, and exports immutable tool definitions. +9. `contexts.ts` creates immutable invocation-scoped context from connection data and maps invalid context to protocol errors; live MCP handshake/transport ownership is intentionally not implemented yet. + +The five frozen tool names are `archflow_state`, `archflow_counter_review`, `archflow_adjudicate`, `archflow_gate`, and `archflow_waiver`. They are data contracts only at this commit—there are no handlers behind them. + +### Assets to contracts + +`assets/workflow.yaml` is parsed against a fixed workflow shape: explore is optional/ungated; PRD and design always gate; phase design and implementation gate on triggers. Constitution Markdown combines strict YAML frontmatter with normative prose. The contract tests load these assets directly, so shipped configuration and parser expectations are checked together. + +### Skills and installation + +`install.sh` copies the same `skills/` tree to `~/.claude/skills/` and/or `~/.agents/skills/`, optionally selected with `--claude` or `--codex`. It currently installs prompt/skill content only. MCP launchers, host registration, initialization, and offline helper installation remain planned later phases. + +## Build and verification + +`package.json` provides no production build command yet. The principal commands are: + +| Command | Purpose | +|---|---| +| `npm run typecheck` | Strict TypeScript check with no emission. | +| `npm test` | Run all Vitest unit and contract-agreement tests. | +| `npm run test:unit` | Run module-level behavioral tests. | +| `npm run test:contracts` | Run schema and catalogue agreement tests. This is also run after the full suite in CI as an explicit gate. | +| `npm run build:temp` | Bundle `src/contracts/index.ts` with esbuild, then import and exercise the Node-targeted ESM bundle. | +| `npm run check:dependencies` | Enforce exact direct dependencies, exact lock metadata, approved licenses, and phase-boundary exclusions. | +| `npm run check:notices` | Verify the lockfile license inventory and retained notice digests. | +| `npm run test:notices-policy` | Mutation-test the NOTICE checks. | +| `npm run check` | Run the repository's complete local verification chain. | + +GitHub Actions repeats these checks on Node `24.15.0` and `24.18.0`, using `npm ci`, and asserts that no tracked-release `dist/` bundle is produced prematurely. + +## Configuration + +- `package.json`: private ESM package, exact runtime/development versions, and verification scripts. +- `package-lock.json`: npm lockfile v3; policy scripts treat exact resolution and license metadata as architectural constraints. +- `tsconfig.json`: `NodeNext` modules/resolution, ES2024 target, strict mode, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, and `noEmit`. +- `vitest.config.ts`: Node test environment, `test/**/*.test.ts`, coverage output under `coverage/`. +- `.github/workflows/ci.yml`: read-only CI permissions and supported Node matrix. +- `.gitattributes`: automatic text detection and LF normalization. +- `assets/workflow.yaml`: canonical application phase topology. +- `assets/constitution/*.md`: canonical initial policy rules. + +There are currently no runtime environment variables, network endpoints, database settings, authentication provider settings, or MCP host configuration consumed by the implemented TypeScript code. Host CLI/auth/sandbox configuration belongs to future adapter and installer phases, not the present contract package. + +## Architectural boundaries to preserve + +- Keep serialized inputs at a strict plain-JSON boundary before domain validation. +- Keep Zod behavior and shipped JSON Schemas demonstrably equivalent. +- Preserve digest-, task-, phase-, invocation-, and authority-bound evidence; schema-shaped objects alone must not acquire trust. +- Keep internal trust brands/capability constructors out of the aggregate public entry point. +- Preserve exactly five MCP tools; local maintenance/helper operations are designed for a separate CLI rather than expanding `tools/list`. +- Keep MCP SDK/transport concerns isolated from the contract layer when the server adapter arrives. +- Treat `.archflow/tasks/mcp-integration/architecture.md` as the implementation plan, but verify current code before assuming a planned subsystem exists. diff --git a/.archflow/context/dependencies.md b/.archflow/context/dependencies.md new file mode 100644 index 00000000..b9ff093f --- /dev/null +++ b/.archflow/context/dependencies.md @@ -0,0 +1,72 @@ +# Dependencies and Integrations + +**Explored:** 2026-07-27 +**Commit:** `8e3144c` + +## Package and runtime baseline + +- `package.json` defines a private ESM package (`"type": "module"`) named `archflow-mcp-server`; `package-lock.json` is the npm lockfile-v3 source of the fully resolved graph. +- The code targets Node.js 24. `tsconfig.json` targets `ES2024` with NodeNext modules, while `scripts/build-temp.mjs` emits a Node 24 ESM smoke bundle. CI exercises the exact Node versions `24.15.0` and `24.18.0` (`.github/workflows/ci.yml`). +- Every direct dependency is exactly pinned. `scripts/check-dependency-policy.mjs` treats the package list, versions, lock metadata, and accepted licenses as policy rather than allowing semver ranges or arbitrary additions. + +## Runtime dependencies + +| Dependency | Pin | Use | +| --- | --- | --- | +| `zod` | `4.4.3` | Primary TypeScript-side structural and semantic validation throughout `src/contracts/`, including configuration, workflow, gates, evidence, reviews, errors, MCP tool envelopes, and trust records. | +| `ajv` | `8.20.0` | JSON Schema 2020-12 compilation and validation in `src/contracts/validators.ts`; loaded through `ajv/dist/2020.js`. | +| `ajv-formats` | `3.0.1` | Adds standard JSON Schema formats to the Ajv validator in `src/contracts/validators.ts`. | +| `yaml` | `2.9.0` | Strict YAML 1.2 parsing in `src/contracts/yaml.ts`, including rejection of multiple documents, warnings, duplicate keys, merges, aliases, and non-plain-JSON values. This parser feeds configuration, workflow, and rubric loading. | + +The contract layer also uses only built-in Node modules: `node:crypto` for SHA-256 trust/evidence digests and `node:util` for deep equality. Scripts use built-in filesystem, path, process, OS, assertion, and child-process APIs. + +## Development and build dependencies + +| Dependency | Pin | Use | +| --- | --- | --- | +| `typescript` | `7.0.2` | Strict, no-emit checking via `npm run typecheck`; options include `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, and `verbatimModuleSyntax` (`tsconfig.json`). | +| `@types/node` | `24.13.3` | Node API typings for source, tests, and scripts. The typing patch is intentionally independent of the two tested runtime patches (`docs/dependency-upgrades.md`). | +| `vitest` | `4.1.10` | Node-environment unit and contract tests under `test/**/*.test.ts`; configured in `vitest.config.ts`. | +| `vite` | `7.3.6` | Vitest's pinned toolchain dependency. Vite 7 is intentional: `docs/dependency-upgrades.md` excludes Vite 8 because its reviewed graph brings in MPL-2.0 Lightning CSS. | +| `esbuild` | `0.28.1` | Produces the temporary bundled contract artifact `.tmp/archflow-contracts.mjs`; `scripts/smoke-temp-bundle.mjs` dynamically imports and exercises it. No release `dist/` artifact is produced. | + +No ESLint, Prettier, Biome, or separate coverage package/configuration is present. Formatting and import organization are maintained by repository convention and TypeScript checks; Vitest's config reserves `coverage/` as the reports directory but the standard scripts do not run coverage. + +## Application configuration + +- `src/contracts/config.ts` and `src/contracts/schemas/v1/config.schema.json` define configuration data, not process-environment loading. Version 1 contains per-role model routes (`producer`, `self-reviewer`, `counter-reviewer`, `adjudicator`) with a model name and one of `low`, `medium`, `high`, `xhigh`, `max`, or `ultra`; optional skill-specific overrides exist for `explore`, `prd`, `design`, `phase-design`, and `phase-impl`. +- `assets/workflow.yaml` is the bundled workflow policy. `assets/constitution/*.md` is the bundled layered constitution, with ordering documented by `assets/constitution/README.md`. +- The source contains no `process.env` access and the repository has no `.env` template or runtime environment-variable contract. `install.sh` uses shell environment only to resolve `$HOME` and install skills into `~/.claude/skills/` and `~/.agents/skills/`. + +## External integrations and persistence + +At this commit, `src/` contains the shared contract and validation layer only. There is no executable MCP server entry point, transport binding, HTTP client, database driver, filesystem-backed state store, or cloud service integration. There are no calls to `fetch`, no database/auth-provider packages, and no application secrets or API-key requirements. + +The future MCP integration is described in `docs/mcp-integration-design.md`: it is intended to dispatch short-lived `claude -p` and `codex exec` processes using the user's existing subscription authentication. The design explicitly avoids requiring or forwarding `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`, because those variables can switch child processes to metered API authentication. That behavior is design intent, not implemented runtime behavior in the current source tree. + +`scripts/check-dependency-policy.mjs` additionally rejects packages reserved for later implementation phases: `@anthropic-ai/sandbox-runtime`, `@modelcontextprotocol/server`, `execa`, `proper-lockfile`, and `write-file-atomic`. Their absence is deliberate and confirms that MCP transport/dispatch, sandboxing, locking, and atomic state persistence have not yet landed. + +Schema identifiers such as `https://archflow.dev/schemas/v1/mcp-tools` in `src/contracts/versions.ts` and `src/contracts/schemas/v1/*.json` are stable identifiers/references; the current validators register and resolve the bundled local schemas rather than fetching them over the network. + +## Dependency, license, and notice policy + +- `scripts/check-dependency-policy.mjs` enforces the exact direct allowlist, exact versions, npm lockfile v3 metadata, and permissive-license allowlist (`0BSD`, Apache-2.0, BSD-2-Clause, BSD-3-Clause, ISC, MIT). It rejects Lightning CSS, later-phase packages, direct optional/peer/bundled dependencies, incomplete resolution metadata, and unreviewed licenses. +- `THIRD_PARTY_NOTICES.md` inventories the resolved graph. `scripts/check-notices.mjs` reconciles it against the lockfile and installed packages and verifies retained NOTICE digests; `notices/typescript-7.0.2-NOTICE.txt` is the retained asset currently under policy. +- `scripts/test-notices-policy.mjs` mutation-tests that changed, missing, and unreviewed notice content is rejected. +- `docs/dependency-upgrades.md` records the reviewed pins and the upgrade procedure. Dependency upgrades require deliberate lock regeneration, notice refresh, policy checks, and verification on both supported Node versions. + +## CI/CD and verification + +GitHub Actions is the only CI/CD integration (`.github/workflows/ci.yml`). On every push and pull request, an Ubuntu job runs for each supported Node version with read-only repository contents permission: + +1. `npm ci` +2. `npm run typecheck` +3. `npm test` +4. `npm run test:contracts` +5. `npm run build:temp` +6. `npm run check:dependencies` +7. `npm run check:notices` +8. `npm run test:notices-policy` +9. Assert that no tracked/release `dist` directory was produced + +`npm run check` provides the corresponding local aggregate, though it invokes the broad `npm test` and then the contract subset again. There is no deployment, package publication, container build, release workflow, or external CI service configured. diff --git a/.archflow/context/patterns.md b/.archflow/context/patterns.md new file mode 100644 index 00000000..c5726f65 --- /dev/null +++ b/.archflow/context/patterns.md @@ -0,0 +1,59 @@ +# Patterns and Conventions + +**Explored:** 2026-07-27 +**Commit:** `8e3144c` + +## Package and module conventions + +- The package is strict TypeScript and native ESM (`package.json` has `"type": "module"`; `tsconfig.json` uses `NodeNext`). Relative imports therefore include the emitted `.js` extension even in `.ts` sources, for example `import { assertPlainJson } from "./plain-json.js"` in `src/contracts/config.ts`. +- Source code currently lives under `src/contracts/`; each file owns one contract area such as configuration, evidence, gates, review, or trust. Public consumers use the curated barrel at `src/contracts/index.ts`. +- Internal trust-minting helpers live below `src/contracts/internal/` and are deliberately excluded from the public barrel. `test/contracts/schema-registry.test.ts` asserts that test authority factories are not exported. +- Names expose version and role explicitly: runtime schemas use names such as `configV1Schema`, parsers use `parseConfigV1` / `parseConfigYaml`, fixed vocabularies use uppercase constants such as `ROUTING_ROLES`, and public data types use PascalCase names such as `ConfigV1` and `ProjectResult`. +- JSON keys and serialized vocabulary use `snake_case` and lowercase hyphenated literals (`schema_version`, `input_fingerprint`, `counter-reviewer`). TypeScript-only identifiers use `camelCase` / `PascalCase`. +- Constants commonly combine literal preservation with compile-time completeness checks: `as const satisfies ...`. Read-only data is favored in public types (`readonly` properties and arrays), while branded string/number types prevent raw values from acquiring validated authority. +- Imports are generally grouped as external or Node built-ins, a blank line, then local imports. Type-only dependencies use `import type` or inline `type` specifiers because `verbatimModuleSyntax` is enabled. There is no configured ESLint or Prettier command; formatting is maintained by source convention and the TypeScript compiler. + +## Boundary validation and data handling + +- Untrusted values are checked as plain JSON before domain parsing. Typical entry points call `assertPlainJson(value, "config")` and then a strict Zod schema (`src/contracts/config.ts`). `src/contracts/plain-json.ts` rejects cycles, accessors, inherited/symbol/dangerous properties, sparse arrays, non-finite numbers, and mutation during inspection. +- Zod object schemas are closed with `.strict()`. Cross-field semantics are expressed through `.refine()` / `.superRefine()` and, where useful, an additional explicit validation function. This makes unknown fields and inconsistent derived fields fail instead of being silently stripped. +- Normative JSON Schemas under `src/contracts/schemas/v1/` are mirrored by TypeScript/Zod contracts. `src/contracts/validators.ts` configures AJV in strict, non-coercing, non-defaulting mode and provides `assertZodAgreement` so the two representations cannot silently diverge. +- Parsers return the original value when validation does not require derivation, preserving identity and avoiding mutation. Tests commonly clone input first and assert it remains equal afterward, for example `test/contracts/foundational-schema-agreement.test.ts` and `test/unit/plain-json.test.ts`. +- Canonical order and exact-set invariants are common: arrays are required to be sorted and unique, review slots have a fixed role order, and count/verdict fields must match their contents. Helpers in `src/contracts/validators.ts` and domain modules enforce these rules. +- Rendering is deterministic and byte-oriented. `src/contracts/renderers.ts` escapes invisible or markup-sensitive characters, emits fields in fixed order, and returns UTF-8 `Uint8Array` values rather than loosely formatted objects. +- There is no database or general data-access layer in the current repository. Runtime code is predominantly pure contract parsing, validation, derivation, and rendering. Filesystem reads appear mainly in tests and asset-loading paths, using `node:fs/promises` and `new URL(..., import.meta.url)` rather than process-relative paths. + +## State, identity, and immutability + +- State is represented as explicit validated values, not mutable application stores. Discriminated unions and correlated generic maps encode legal result, error, gate, evidence, and workflow variants at compile time. +- Security- or trust-sensitive values require unforgeable identity in addition to matching structure. Unique-symbol brands and internal `WeakSet`/capability machinery in `src/contracts/internal/trust-brands.ts` distinguish authentic values from spread copies; tests in `test/unit/trust.test.ts` and `test/unit/mcp-tools.test.ts` verify copied objects lose authority. +- Registries and capabilities are frozen with `Object.freeze`, including nested parser/definition objects where relevant. `src/contracts/errors.ts` is representative: definitions are immutable, parameter schemas are correlated by error code, and construction emits frozen, serializable envelopes. +- Functions generally avoid ambient state. When stateful behavior is necessary, it is scoped to an invocation/capability and authenticated before use rather than exposed as a global mutable singleton. + +## Error handling + +- Boundary failures throw typed built-in subclasses with useful labels and paths: `PlainJsonError extends TypeError` (`src/contracts/plain-json.ts`) and `ContractValidationError extends TypeError` (`src/contracts/validators.ts`). YAML syntax failures use `SyntaxError` with source label, line, and column (`src/contracts/yaml.ts`). +- Domain validation usually throws `TypeError` for structurally or semantically invalid values. Errors are fail-fast; parsing does not coerce or repair caller data. +- Operational/project failures intended for transport are values rather than exceptions. `src/contracts/errors.ts` defines exhaustive `PROJECT_ERROR_DEFINITIONS` and `PROTOCOL_ERROR_DEFINITIONS`, with each code correlated to an owner, retryability, a strict parameter parser, a next action, and a projection. +- Serialized diagnostics intentionally contain bounded, validated parameters instead of raw exceptions or sensitive names. `test/unit/errors.test.ts` verifies extra diagnostic fields are rejected and project/protocol error spaces remain distinct. +- Narrow `try`/`catch` blocks are used only when converting a predicate or preserving a validation boundary; broad swallowing is not a convention. For example, `isPlainJsonValue` converts `assertPlainJson` failure into `false`, while most public parsers allow actionable validation errors to propagate. + +## Testing conventions + +- Vitest is the sole test framework, configured for Node in `vitest.config.ts`; files match `test/**/*.test.ts`. Commands split fast domain tests (`npm run test:unit`) from schema/representation agreement tests (`npm run test:contracts`). +- Tests mirror the source boundary: + - `test/unit/` exercises individual TypeScript contract modules and semantic invariants. + - `test/contracts/` checks JSON Schema compilation, registry completeness, exhaustive vocabulary, and agreement with Zod/runtime behavior. + - `test/fixtures/` contains small valid and deliberately invalid JSON, YAML, and Markdown examples grouped by `foundation/` or `contracts/` and domain. +- Tests use `describe` / `it` with behavioral sentences, direct `expect` assertions, and `it.each` or compact loops for rejection matrices. Compile-time guarantees use Vitest's `expectTypeOf` and `// @ts-expect-error`, as shown in `test/unit/path-claims.test.ts`. +- Fixture helpers are local to the test file and load through `readFile(new URL(..., import.meta.url), "utf8")`; JSON fixtures are explicitly parsed and cast from `unknown`. There is no shared global setup or mock-heavy fixture framework. +- Negative and adversarial coverage is a first-class pattern: unknown keys, prototype/accessor attacks, malformed Unicode, duplicate IDs, stale/foreign evidence, copied branded values, and Zod/JSON Schema disagreement all receive explicit tests. +- Tests frequently verify non-mutation and identity semantics, not only value equality. `structuredClone` captures before-state; authentic-object tests also assert that a spread copy is rejected. + +## Practical checklist for new code + +1. Put the contract in the domain-specific `src/contracts/.ts` module and export only the intended surface through `src/contracts/index.ts`. +2. Treat every `unknown` input as hostile: plain-JSON preflight it, apply a strict schema, then enforce semantic/cross-field invariants without mutation. +3. Keep serialized names in the established `snake_case` vocabulary, TypeScript names idiomatic, and version public schemas/types explicitly when they are wire contracts. +4. Add unit tests for happy paths, rejection matrices, non-mutation, and type/brand boundaries. Add or update contract-agreement tests whenever normative JSON Schema is involved. +5. Use `.js` suffixes for relative imports, type-only imports where applicable, immutable public types, and deterministic ordering for serialized collections and output. From 5effa7de73cd50630c699c66484dacbccb60b0a0 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 16:00:33 -0500 Subject: [PATCH 009/124] MCP Integration: Design Phase 3 --- .../tasks/mcp-integration/architecture.md | 196 +++++++++++------- ...tract-boundary-and-dependency-admission.md | 182 ++++++++++++++++ .../reviews/phase-3-design-counter-review.md | 111 ++++++++++ 3 files changed, 412 insertions(+), 77 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-3-design-counter-review.md diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index ab2b91e0..3c79895b 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -18,7 +18,7 @@ | Packaging | esbuild `0.28.1`, exact npm lockfile, single host-neutral server/local-helper bundle | `install.sh` installs both `archflow-mcp` and `archflow-local` without an unpinned startup download. | | Verification | Vitest `4.1.10` with direct dev pin Vite `7.3.6`, fixture CLIs, fault injection, protocol fixtures, and black-box host/sandbox suites | The exact Vite 7 pin constrains Vitest to its supported permissive line; the lock must prove no `lightningcss` or other copyleft dependency before acceptance. Critical persistence, host, process, protocol, and manual-mode behavior is exercised at its real boundaries. | -All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. Direct pins are permissively licensed, and the complete lock must independently prove a permissive-only graph. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 8 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. +All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. Direct pins are permissively licensed, and the complete lock must independently prove a permissive-only graph. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 10 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. ## System Architecture @@ -301,7 +301,7 @@ Each dispatch creates a fresh, non-resumed child in a temporary directory outsid - use an OS containment primitive capable of terminating every descendant on abort, timeout, server shutdown, or output overflow even if a descendant creates a new process group/session—PID namespace/cgroup, Windows job object, or a proven equivalent, not Execa best effort alone; and - return a capability proof tied to the OS, provider, CLI/runtime versions, exact allowed-read manifest, and randomized denied canaries. -At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 8 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. +At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 10 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. The Claude adapter uses fresh `--safe-mode`, `--tools ""`, a strict empty MCP config, disabled slash commands, no persistence, and schema-constrained output. It preflights subscription authentication and managed hooks/policy. Host setup configures and validates the Claude server entry's persistent per-server `timeout` when supported; otherwise a newly started host must inherit `MCP_TOOL_TIMEOUT` as described below. Cancellation or host timeout always leaves a durable resumable gate; timeout-then-resume is supported normal behavior. The Codex adapter uses exact fixture-proven ephemeral, ignore-user-config, `--ignore-rules`, read-only, and output-schema behavior while preserving first-party auth; `--ignore-rules` is inherited-context isolation only, never security confinement. It configures/tests `project_doc_max_bytes=0` or a proven equivalent and rejects managed instruction injection. An ArchFlow deny-all Codex execpolicy remains an early feasibility candidate, and the design does not claim it works. Both adapters still require OS sandbox proof, are version-gated from real fixtures, and spawn with `shell: false`, scrubbed environment, no provider keys/routing or unrelated secrets, `killDescendants`, cancellation, timeout/output bounds, forced escalation, and provider-owned descendant containment. Stable failures cover missing CLI, auth, unsupported host/model, family mismatch, rate limit, timeout, cancellation, overflow, invalid output, nonzero exit, and I/O failure. @@ -371,22 +371,22 @@ Release is blocked unless all applicable tests pass and the supported matrix is | Coverage area | Requirements | Validation | Primary phases | Proof boundary | |---------------|--------------|------------|----------------|----------------| -| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 11, 12, 17 | Strict assets/schemas, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | -| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 10, 12, 16, 17 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | -| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 2, 4, 5, 6, 9, 12, 13, 15, 16 | Structured JSON/projections, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | -| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 2, 9, 14, 15, 16 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | -| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 2, 7, 9, 14, 16 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | -| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 4, 5, 6, 7, 13, 15, 16 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | -| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 4, 5, 6, 7, 13, 14, 15 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | -| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 4, 5, 6, 8, 14, 15, 16 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | -| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 2, 3, 10, 11, 15, 16 | Correlated five-tool contracts and v2 fixtures expose only the stdio boundary; the separate offline helper is not an MCP tool. | -| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 8, 10, 15, 16 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | -| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 2, 3, 8, 9, 10, 15, 16 | Hashed envelopes, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | -| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 8, 11, 15, 16, 17 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | -| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 2, 7, 10, 13, 15, 16 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | -| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 10, 11, 13, 14, 16 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | -| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 2, 7, 12, 13, 16 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | -| Legacy migration | REQ-50 | VAL-17 | 4, 5, 6, 7, 14, 15, 16 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | +| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 5, 13, 14, 19 | Strict assets/schemas, dependency-complete offline packaging, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | +| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 12, 14, 18, 19 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | +| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 2, 5, 6, 7, 8, 11, 14, 15, 17, 18 | Structured JSON/projections, manifest evidence, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | +| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 2, 11, 16, 17, 18 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | +| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 2, 9, 11, 16, 18 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | +| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 6, 7, 8, 9, 15, 17, 18 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | +| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 6, 7, 8, 9, 15, 16, 17 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | +| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 6, 7, 8, 10, 16, 17, 18 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | +| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 2, 3, 4, 5, 12, 13, 17, 18 | Correlated five-tool contracts, v2 fixtures, and the license-complete deterministic offline payload expose only the stdio boundary; the separate offline helper is not an MCP tool. | +| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 10, 12, 17, 18 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | +| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 2, 3, 4, 5, 10, 11, 12, 17, 18 | Hashed envelopes, portable manifest evidence, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | +| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 10, 13, 17, 18, 19 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | +| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 2, 9, 12, 15, 17, 18 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | +| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 12, 13, 15, 16, 18 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | +| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 2, 9, 14, 15, 18 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | +| Legacy migration | REQ-50 | VAL-17 | 6, 7, 8, 9, 16, 17, 18 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release validations `VAL-01` through `VAL-17`, appear above. `REQ-52` remains explicitly outside the v1 architecture. @@ -400,7 +400,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali **Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-15, REQ-17 -**Scope**: First add the visible lineage/supersession banner to `docs/mcp-integration-design.md`, preserving it as originating design and linking the normative PRD/architecture; Phase 17 later updates surrounding documentation. Establish a private ESM package, exact lockfile, scripts, Node matrix CI, dependency notices/policy, and only Phase-1 direct dependencies: Zod, Ajv, `ajv-formats`, YAML, TypeScript, Node typings, esbuild, Vitest, and direct Vite `7.3.6`. Implement recursive plain-JSON preflight, strict non-mutating Ajv2020, explicit Zod agreement infrastructure, branded canonical phase-instance codec, safe YAML parsing, fixed workflow/config/rubric/constitution rule contracts, shipped workflow/constitution assets, and append-only constitution evolution fixtures. This phase has no review/triage/adjudication contracts or renderers, error registry, tool schemas, MCP SDK/server, or tracked offline bundle. +**Scope**: First add the visible lineage/supersession banner to `docs/mcp-integration-design.md`, preserving it as originating design and linking the normative PRD/architecture; Phase 19 later updates surrounding documentation. Establish a private ESM package, exact lockfile, scripts, Node matrix CI, dependency notices/policy, and only Phase-1 direct dependencies: Zod, Ajv, `ajv-formats`, YAML, TypeScript, Node typings, esbuild, Vitest, and direct Vite `7.3.6`. Implement recursive plain-JSON preflight, strict non-mutating Ajv2020, explicit Zod agreement infrastructure, branded canonical phase-instance codec, safe YAML parsing, fixed workflow/config/rubric/constitution rule contracts, shipped workflow/constitution assets, and append-only constitution evolution fixtures. This phase has no review/triage/adjudication contracts or renderers, error registry, tool schemas, MCP SDK/server, or tracked offline bundle. **Success Criteria**: @@ -424,7 +424,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali **Success Criteria**: - [ ] Closed schemas/interfaces enumerate every field and trust source for raw finding/review, derived review, `AgentDeclaredReview`, `ServerAttestedReview`, `DegradedReview`, `ReviewEvidence`, `FindingRef`, `TriageDisposition`, `ValidatedTriage`, `AdapterObservation`, and scope-bound `AuthorityLink`; verdict/count/binding fields are recomputed, untrusted, or internally minted as specified. -- [ ] Server attestation is minted only from an invocation-scoped observation capability containing immutable expected envelope bindings and observer-owned output bytes. Phase 2 freezes scope-bound receipt/state/result/checkpoint authority-link contracts and proves the capability seams with internal fixtures; Phase 4 and later owners verify live links/currentness. Forged, schema-shaped, wrong-policy, wrong-scope, wrong-invocation, and wrong-digest provenance cannot qualify. +- [ ] Server attestation is minted only from an invocation-scoped observation capability containing immutable expected envelope bindings and observer-owned output bytes. Phase 2 freezes scope-bound receipt/state/result/checkpoint authority-link contracts and proves the capability seams with internal fixtures; Phase 6 and later owners verify live links/currentness. Forged, schema-shaped, wrong-policy, wrong-scope, wrong-invocation, and wrong-digest provenance cannot qualify. - [ ] Composite `(review_evidence_digest, finding_id)` dispositions cover the exact applicable current finding set once and only once, reject stale/foreign/duplicate/missing findings, and digest-bound `ValidatedAdjudication` retains per-rule compliance findings, all `enforced_by` states, separate drift, triggers, and canonical byte-stable rendering. - [ ] One normative gate contract catalogue defines all nine exact contexts, decision payloads, effect classes, decision envelopes, waiver origin/binding, supplemental actions, restore/migration subjects, and commit authorization over the implementation result/diff/current artifacts; cross-kind or cross-gate substitution fails. - [ ] Exactly five correlated request/result definitions exist for `archflow_state`, `archflow_counter_review`, `archflow_adjudicate`, `archflow_gate`, and `archflow_waiver`, with no sixth tool and `archflow_state.artifact` rejected until its durable union exists. Structural result validation is distinct from expectation-based authoritative correlation; wrong invocation/gate/revision/path/semantic results fail when a later owner supplies the scoped expectation. @@ -432,31 +432,71 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Internal constructors validate, copy, and freeze initialization-established connection data and per-invocation metadata exactly once while preserving `AbortSignal` as the sole live capability; repeated initialization and request identity overrides fail. No SDK or transport-owned type leaks into these interfaces. - [ ] No MCP SDK package, MCP server, protocol fixture, tracked bundle, persistence implementation, dispatch implementation, durable gate lifecycle, or durable state/artifact schema is introduced in this phase. -### Phase 3: Inert MCP Boundary and Offline Bundle +### Phase 3: MCP Contract Boundary and Dependency Admission -**Goal**: Adopt the exact MCP dependency and prove a low-level, isolated, stdio-only transport and offline release bundle over injected inert handlers. +**Goal**: Admit the exact reviewed MCP dependency surface and freeze a complete SDK-free five-tool catalogue and authenticated handler/error boundary for a later transport owner. **Depends on**: Phase 2 +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-33 + +**Scope**: Before dependency mutation, recheck exact direct `@modelcontextprotocol/server@2.0.0-beta.5`, exact locked `@modelcontextprotocol/core@2.0.0-beta.5`, protocol `2025-11-25`, required public exports/declarations, current guidance, and only that both root packages declare allowed `MIT`. Record both root entries in existing dependency notices; a changed/disallowed root declaration or incompatible dependency/public surface returns for phase-design review without dependency changes. Phase-design approval is not commit authorization. Phase 3 performs no tarball, transitive, embedded-component, documentation-classification, or bundle-wide legal audit. Extend Phase 2 with a failure-only result validator, one shared request-ID schema consumed by parser and authentic invocation mint, and one shared client-implementation schema consumed by parser and direct-only connection mint; full SDK Implementation metadata is projected to exact `{name, version}` before both client consumers. Build the exact five-tool portable catalogue in supported direct-import module `src/mcp/tools.ts` from the exact eight-schema closure, validate tests only through public-root `specTypeSchemas`, and compile with strict Ajv/formats. `src/contracts/index.ts` remains contract-only; `src/mcp/tools.ts` owns and exports `AdvertisedToolDescriptor` and `ADVERTISED_TOOL_CATALOGUE` for Phase 4; no `src/mcp/index.ts`, package/barrel catalogue export, or internal builder exists. Implement the SDK-free authenticated handler/error boundary with exact input classification, return revalidation, and safe fallback. This phase creates no SDK adapter, transport, lifecycle, cancellation, runnable server, release bundle, or REQ-28 claim. + +**Success Criteria**: + +- [ ] Implementation-start evidence confirms exact server/core beta.5, protocol `2025-11-25`, required public exports/declarations, and allowed root `MIT` declarations before package/lock mutation; a mismatch returns for phase-design review without dependency changes, and phase-design approval does not authorize a commit. +- [ ] Existing dependency notices contain both root package entries. Phase 3 adds no retained MCP legal assets or tarball/transitive/embedded/documentation-class legal audit; Phase 5 independently owns bundle-wide legal completeness. +- [ ] The Phase 2 seam adds only the failure-only project-result validator, one shared internal request-ID schema consumed by parser and authentic invocation mint, and one shared internal client-implementation schema consumed by parser and direct-only authentic connection mint. Arbitrary strings and finite safe integers, including negative values, `-0`, and both safe bounds, are preserved; adjacent unsafe integers fail. Full SDK Implementation metadata is projected to exact `{name, version}` before both client-schema consumers, parser-to-mint fixtures preserve admitted values, the factory remains absent from `src/contracts/index.ts`, and no SDK-owned type crosses or appears in production source outside tests. +- [ ] `src/contracts/index.ts` remains contract-only. Supported direct-import `src/mcp/tools.ts` owns and exports `AdvertisedToolDescriptor` and `ADVERTISED_TOOL_CATALOGUE`; Phase 4 imports both only from that exact module, no `src/mcp/index.ts` or catalogue barrel/package export exists, and no internal builder or ownership cycle is introduced. The exact five-tool catalogue passes public-root `ListToolsResult`, strict Ajv/formats, and frozen-2025 object-root invariants without core-root or SDK-internal schema imports. +- [ ] Every advertised schema compiles in strict `ajv@8.20.0` plus pinned `ajv-formats@3.0.1` with an otherwise empty registry and no ArchFlow schemas or custom keywords; a classified corpus separately proves portable structural validation and all runtime-only semantic constraints. +- [ ] The authenticated SDK-free boundary fixes handler registry, invocation context, project outcome, authenticated protocol error, boundary outcome, exact known/unknown-tool and argument classification, handler-result revalidation, and safe `INTERNAL_ERROR` fallback without transport or lifecycle assumptions. +- [ ] Focused unit, contract, dependency-policy, schema-portability, and authenticity fixtures pass; there is no `src/main.ts`, `src/mcp/sdk-adapter.ts`, transport, cancellation, live transcript, tracked release output, persistence, dispatch, or claim that a local MCP service exists. + +### Phase 4: Guarded MCP Runtime and SDK Compatibility + +**Goal**: Consume Phase 3's frozen seam to implement and prove the complete inert low-level beta.5 stdio runtime. + +**Depends on**: Phase 3 + **Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28, REQ-33 -**Scope**: Recheck and adopt the exact MCP SDK and protocol pins, update dependency/license evidence, and isolate the low-level adapter behind the Phase 2 contracts. Implement singleton protocol `2025-11-25` negotiation, owned stdio lifecycle, `tools/list` and `tools/call` validation over inert injected handlers, definition-bound structural project-result projection, and cancellation without business-state side effects. Exercise the expectation consumer with internal fixtures, but leave production expectation minting to the later repository/transaction owners. Add real protocol fixtures and track `dist/archflow-mcp.js` plus `dist/manifest.json` for copy-only clean-checkout offline startup under a Node-core network/listener guard. This phase implements no persistence, dispatch, durable gate lifecycle, durable state schema, or durable artifact schema. +**Scope**: Isolate the deprecated low-level SDK `Server` as a documented advanced-use exception wholly inside `src/mcp/sdk-adapter.ts`, starting with a stop-on-failure public-hook compatibility gate. Intercept ingress before SDK validation or identity mutation with method-aware lifecycle and request maps, singleton `2025-11-25` negotiation, alternate-version counter-offer, initialize-cancellation suppression, repeated/concurrent initialization rejection, and exact client-metadata projection/context-mint ordering through direct imports of Phase 3's `connectionContextFactory` and `createInvocationContext` seams. Own external/internal request-ID mapping, normalize numeric `-0` to `0`, treat concurrent `-0`/`0` as duplicate reuse, and route cancellation without fabricated success. Pin pre-SDK `tools/call` precedence for malformed outer calls, unknown names, known malformed arguments, and the three protocol/project/SDK error domains; absent or empty `tools/list` params return the fixed catalogue without `nextCursor`, while any present cursor returns fixed bounded `-32602 Invalid params`. Own stdio through an adapter-owned cancellable `Writable` bridge with scoped close guarantees: after `CLOSING` no new destination write occurs, already accepted caller-stream bytes may flush, SDK-facing listeners are removed without destroying the caller stream, and never-settling or late handlers cannot emit post-close frames. Add `src/main.ts`, process/signal ownership, stdout/stderr purity, and adversarial live fixtures. Stop for architecture review if public hooks cannot prove the contract. **Success Criteria**: -- [ ] Live protocol `2025-11-25` fixtures negotiate exactly once and expose exactly the five Phase 2 tools with their closed schemas; unsupported or repeated negotiation, unknown tools, and disabled operations use the protocol error path without invoking a project handler. -- [ ] The low-level adapter owns stdio startup/shutdown and protocol-only stdout, accepts only immutable connection/invocation contexts and injected inert handlers, and keeps SDK types confined to the adapter seam. -- [ ] Known-tool parse failures return stable projected `CONTRACT_*` project results with zero handler calls; every handler result is definition-correlated and structurally revalidated before projection, while malformed or cross-tool results project a safe validated `INTERNAL_ERROR`. Internal fixtures prove expectation-based authoritative rejection without claiming that the inert production boundary can mint repository paths, revisions, gate IDs, or result identities. -- [ ] Protocol cancellation reaches the injected invocation signal, returns no fabricated success, and leaves no listener, background transport, or durable side effect after shutdown. -- [ ] Live protocol fixtures cover initialization, `tools/list`, every request/result and protocol-error path, result projection, cancellation, stderr diagnostics, and stdout purity without requiring persistence or dispatch. -- [ ] Exact SDK/protocol currency evidence records the checked version, release/source, lockfile identity, adapter fixture expectations, and permissive license result; pin/lock/fixture drift fails verification. -- [ ] Tracked `dist/manifest.json` binds bundle SHA-256, Node target, package/lock, source entry, and schema/assets digests. A clean checkout copy starts the bundle without `node_modules`, npm, cache, network, or startup build, while a Node-core guard proves no network or listener API is opened. +- [ ] A public-hook compatibility gate proves outer validation interception, initialize cancellation, repeated/concurrent guard-before-SDK precedence, `-0`/`0` identity behavior, stream interception, and permanently backpressured teardown; inability to prove any required invariant stops implementation rather than adding a private-SDK patch. +- [ ] The deprecated low-level `Server` import and every SDK/transport-owned type remain isolated inside the adapter. The adapter consumes Phase 3's frozen SDK-free seam without weakening it, and initialization guards run before any SDK identity or lifecycle mutation. +- [ ] Unsupported versions receive the alternate-version counter-offer; repeated or concurrent initialization cannot mutate SDK identity; cancellation targeting active `initialize` is ignored without releasing its mapping; startup capture, initialize response, one `initialized` connection mint, and per-call invocation creation occur in the pinned order with exact `{name, version}` projection. +- [ ] External/internal ID mapping preserves legal string/numeric identities except that numeric `-0` normalizes to `0`; concurrent `-0`/`0` is duplicate numeric reuse. Live response, cancellation, collision, and reuse fixtures cover all beta.5 request-ID cases. +- [ ] Missing `tools/call` params or missing/non-string name, and unknown names paired with malformed arguments, return fixed bounded SDK-domain `-32602`; known names with missing/non-object/invalid arguments reach the frozen boundary's `CONTRACT_*` classification; unknown names with structurally valid arguments return `TOOL_NOT_FOUND`. Protocol errors, project results, and SDK errors remain distinct and byte-stable. +- [ ] Post-`READY` `tools/list` accepts absent or empty params and returns the full fixed catalogue without `nextCursor`; any present cursor, including `""`, returns fixed bounded `-32602 Invalid params`, echoes no cursor, and invokes neither catalogue nor tool boundary. +- [ ] The adapter-owned cancellable `Writable` bridge leaves no owned listener or pending send after close, performs no new destination write after `CLOSING`, allows only caller-stream bytes already accepted before close to flush, and never destroys the caller-owned stream. Never-settling and late handlers, cancellation, signals, backpressure, and close races emit no post-close frame or business side effect. +- [ ] `src/main.ts` produces a runnable inert stdio server with exactly five listed tools and disabled injected handlers; actual-process and both-Node-version fixtures cover negotiation, list/call/error/cancel races, safe stderr diagnostics, stdout purity, signal shutdown, and handle/listener cleanup without persistence, dispatch, or a tracked release bundle. -### Phase 4: Repository Identity, Paths, Schemas, and Canonical Digests +### Phase 5: Offline Bundle and Release Integrity + +**Goal**: Produce a license-complete deterministic tracked offline payload and prove hostile clean-copy startup. + +**Depends on**: Phase 4 + +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28, REQ-33 + +**Scope**: Define a strict versioned release-manifest schema and build the inert server payload deterministically. Independently inventory every component and transitive input present in the final bundle, verify its applicable license and attribution requirements, and track the complete bundle, manifest, and legal payload. Prove startup from a hostile clean copy with no `node_modules`, npm, cache, startup build, network, or listener access, while preserving protocol-only stdout and enforcing the release proof in CI. This phase adds no persistence, dispatch, durable gate lifecycle, durable state schema, durable artifact schema, or production handler authority. + +**Success Criteria**: + +- [ ] A strict, versioned `dist/manifest.json` schema rejects unknown fields, unsupported versions, missing or contradictory evidence, and binds the bundle SHA-256, Node target, package/lock, source entry, schema/assets, full esbuild metafile, and every metafile input to canonical digests. +- [ ] The tracked legal payload independently inventories every bundled component and transitive input, binding exact version/source, applicable license, required notice/attribution text, and corresponding bundle input; missing, disallowed, unreviewed, or mismatched entries fail the build. +- [ ] Repeated builds from the exact lock and declared inputs produce byte-identical bundle, manifest, metafile evidence, and legal payload, with no undeclared input or timestamp/environment variation. +- [ ] A hostile clean-copy smoke starts the tracked bundle without `node_modules`, npm, package cache, network, startup build, or repository-local undeclared input and completes live initialize, `tools/list`, and shutdown over stdio. +- [ ] Node-core guards prove startup and protocol exercise open no network connection or listener, emit only MCP traffic on stdout, route diagnostics to stderr, and leave no background handle. +- [ ] CI validates the manifest schema and all input/hash/license bindings, reproduces the payload, runs the hostile clean-copy smoke, and fails on bundle, lock, schema, asset, metafile, legal-inventory, attribution, or protocol-fixture drift. + +### Phase 6: Repository Identity, Paths, Schemas, and Canonical Digests **Goal**: Establish the repository/task identity, path safety, durable schemas, immutable task configuration, and byte-stable digest contracts used by every mutation. -**Depends on**: Phases 1–3 +**Depends on**: Phases 1–5 **Requirements**: REQ-04, REQ-05, REQ-11, REQ-13, REQ-14, REQ-21, REQ-26, REQ-33, REQ-39, REQ-50 @@ -470,15 +510,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Valid state/initialization/document/implementation/import/checkpoint/maintenance samples round-trip through normative schemas; predecessor gaps, unknown fields, digest mismatches, invalid phase IDs, and contradictory accounting fail with stable errors. - [ ] Startup and pull/handoff detection identifies divergent histories and `.archflow/**` conflicts as non-authoritative without claiming it can detect independent-clone concurrency before divergence. -### Phase 5: Transaction Kernel, Intent/CAS, and Crash Recovery +### Phase 7: Transaction Kernel, Intent/CAS, and Crash Recovery **Goal**: Commit one task's transitions exactly once under races, crashes, retries, config drift, and bounded reconciliation. -**Depends on**: Phase 4 +**Depends on**: Phase 6 **Requirements**: REQ-04, REQ-08, REQ-13, REQ-14, REQ-21, REQ-22, REQ-23, REQ-24, REQ-26, REQ-39, REQ-50 -**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 6. +**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 8. **Success Criteria**: @@ -489,15 +529,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Mature-task step boundaries and status reconcile only current state projections, the relevant active/prepared intent, and active gate/checkpoint head; only explicit repair/import/audit walks history. - [ ] Divergent/conflicted clones remain non-authoritative until preserve-both-heads repair selects/replays one successor chain and records a clean one-writer handoff. -### Phase 6: Snapshots, Implementation Manifests, and Restore +### Phase 8: Snapshots, Implementation Manifests, and Restore **Goal**: Retain and restore deterministic declared outputs within explicit storage, retention, collision, and secret-safety bounds. -**Depends on**: Phase 5 +**Depends on**: Phase 7 **Requirements**: REQ-08, REQ-11, REQ-13, REQ-21, REQ-22, REQ-23, REQ-25, REQ-26, REQ-33, REQ-39, REQ-50 -**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 7 connects collision decisions to the gate service. +**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 9 connects collision decisions to the gate service. **Success Criteria**: @@ -508,11 +548,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Secret fixtures in any candidate Git-tracked snapshot/checkpoint projection fail before projection with safe remediation warning that later `.archflow/` deletion cannot erase branch history; clean binary/text fixtures pass without logging secret values. - [ ] Snapshot/projection/restore fault injection preserves prior/next authority or exact repair, and the three `restore-collision` outcomes are representable without silent overwrite. -### Phase 7: Durable Gates, Waivers, and Manual Decisions +### Phase 9: Durable Gates, Waivers, and Manual Decisions **Goal**: Persist every human authority boundary independently of a live MCP request. -**Depends on**: Phase 6 +**Depends on**: Phase 8 **Requirements**: REQ-09, REQ-13, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -528,11 +568,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] `waiver-requested` is non-advancing and archives the current gate before the sole waiver gate opens; grant resumes only the recorded rule/scope, denial remains non-advancing, and no nested gate exists. `restore-collision` exposes only discard-and-restore, adopt-as-new-generation with changed inputs/fingerprint and rationale, or abort. - [ ] A real Claude host timeout leaves one pending gate, and a later invocation resumes and resolves that gate exactly once; timeout-then-resume is normal supported behavior. -### Phase 8: Host Identity, Sandbox, and CLI Dispatch +### Phase 10: Host Identity, Sandbox, and CLI Dispatch **Goal**: Prove fresh opposite-family reviewer processes receive only declared envelopes and are safe to dispatch on every claimed environment. -**Depends on**: Phases 1–7 +**Depends on**: Phases 1–9 **Requirements**: REQ-26, REQ-29, REQ-30, REQ-31, REQ-32, REQ-34, REQ-35 @@ -549,11 +589,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Any external sandbox dependency and license is presented for explicit acceptance before adoption; copyleft is never silently bundled. - [ ] The Anthropic subscription-authenticated dispatch path remains release-disabled until written clarification or a qualified legal determination satisfies `VAL-14`; implementation or fixture success is not legal approval. -### Phase 9: Constitution Adjudication, Drift, and Review Fixed Point +### Phase 11: Constitution Adjudication, Drift, and Review Fixed Point **Goal**: Turn validated reviewer output and pinned policy/upstream inputs into current-digest advancement evidence. -**Depends on**: Phases 1–8 +**Depends on**: Phases 1–10 **Requirements**: REQ-10, REQ-11, REQ-12, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-32, REQ-33 @@ -566,15 +606,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Positive, negative, and uncertain triggers plus current/missing/stale/failed mechanical evidence behave fail-closed against the approved policy-base constitution. - [ ] Aligned and incidental drift are recorded correctly; material drift gates and an accepted change reopens the affected upstream approval/evidence chain. -### Phase 10: Five-Tool MCP Assembly and Offline Local CLI +### Phase 12: Five-Tool MCP Assembly and Offline Local CLI **Goal**: Assemble persistence, dispatch, adjudication, and decisions behind the complete and only MCP workflow surface. -**Depends on**: Phases 1–9 +**Depends on**: Phases 1–11 **Requirements**: REQ-07, REQ-08, REQ-11, REQ-13, REQ-21, REQ-23, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40 -**Scope**: Wire exactly five handlers through the v2 adapter and implement `archflow-local` for validate, hash, render, snapshot/restore, human-approved maintenance with immutable records, atomic decisions, degraded status, reconcile/import, upgrade staging, and immutable checkpoint creation/chain validation. Connect mutation/replay, dispatch, evidence, supplemental interruption, cancellation, protocol-only stdout, and public errors. Rebuild the Phase 3 tracked bundle and `dist/manifest.json` for the full server/helper assembly. Init and upgrade remain outside the tool list. +**Scope**: Wire exactly five handlers through the v2 adapter and implement `archflow-local` for validate, hash, render, snapshot/restore, human-approved maintenance with immutable records, atomic decisions, degraded status, reconcile/import, upgrade staging, and immutable checkpoint creation/chain validation. Connect mutation/replay, dispatch, evidence, supplemental interruption, cancellation, protocol-only stdout, and public errors. Rebuild the Phase 5 tracked bundle and `dist/manifest.json` for the full server/helper assembly. Init and upgrade remain outside the tool list. **Success Criteria**: @@ -586,15 +626,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] `archflow-local checkpoint` atomically extends only a valid reconciled chain, and server adoption imports only its greatest valid checkpoint via the closed union tag. - [ ] The updated tracked manifest binds the complete server/helper bundle to current package/lock/source/schema/assets digests and passes clean-checkout offline startup before installer work. -### Phase 11: Installer, Initialization, and Host Registration +### Phase 13: Installer, Initialization, and Host Registration **Goal**: Install the offline bundle and initialize supported repositories repeatedly without damaging host or project configuration. -**Depends on**: Phases 1, 8, and 10 +**Depends on**: Phases 1, 10, and 12 **Requirements**: REQ-01, REQ-02, REQ-28, REQ-29, REQ-34, REQ-37, REQ-40 -**Scope**: Verify the Phase 10 tracked bundle/manifest, then extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. +**Scope**: Verify the Phase 12 tracked bundle/manifest, then extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. **Success Criteria**: @@ -606,11 +646,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Initialized state is Git-trackable/shareable, contains no machine-specific executable path in portable task state, and works after repository relocation and in linked/space/Unicode worktrees. - [ ] `archflow-init` creates no task state and no commit. Fresh task creation refuses to start until workflow/constitution assets resolve from an explicitly approved immutable commit and then stages the normal initialization manifest. -### Phase 12: Normal-Mode Thin Phase Skills and Truthful Status +### Phase 14: Normal-Mode Thin Phase Skills and Truthful Status **Goal**: Drive the normal MCP workflow from host-neutral phase skills and report only reconciled durable truth. -**Depends on**: Phases 1–11 +**Depends on**: Phases 1–13 **Requirements**: REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-13, REQ-14, REQ-20, REQ-41 @@ -624,11 +664,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] The server sees only complete supplemental projections through filesystem notification plus bounded polling fallback. The gate-pending transition table admits only supplemental ingestion, triage, explicit decline/decision, cancellation, or supersession; `SUPPLEMENTAL_REVIEW_REQUIRED` rejection resumes the gate and accepted change supersedes it and re-enters the fixed point. - [ ] Status verifies the immutable whole-config digest before recommending work; `PINNED_CONFIG_MISMATCH` reports no config content and recommends only a distinct new task or explicit upgrade for intentional routing/model/effort changes. -### Phase 13: Manual and Degraded Recovery Workflow +### Phase 15: Manual and Degraded Recovery Workflow **Goal**: Complete and recover the workflow conservatively when individual MCP tools or the server are unavailable. -**Depends on**: Phases 1–12 +**Depends on**: Phases 1–14 **Requirements**: REQ-08, REQ-09, REQ-11, REQ-12, REQ-13, REQ-14, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41 @@ -642,11 +682,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Supplemental-review arrival, rejection/resume, accepted-change supersession, explicit decline, cancellation, and restart behave identically to normal-mode milestones. - [ ] Manual operation never auto-commits/pushes and documents clean human-approved checkpoint handoff between writers. -### Phase 14: Legacy Upgrade Workflow +### Phase 16: Legacy Upgrade Workflow **Goal**: Migrate selected legacy material into a distinct canonical task without changing or implicitly approving the source. -**Depends on**: Phases 4–7, 9, 10, 12, and 13 +**Depends on**: Phases 6–9, 11, 12, 14, and 15 **Requirements**: REQ-02, REQ-04, REQ-09, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -661,11 +701,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Pure manual upgrade begins with a validating legacy-initialization checkpoint and later server recovery adopts its chain without changing the source or replaying decisions. - [ ] The repository's current legacy task layout upgrades through the same fixture path, and release guidance tells users with in-flight tasks how to finish in legacy tooling or checkpoint/handoff into a distinct upgraded task without silent in-place conversion. -### Phase 15: Reliability and Security Matrices +### Phase 17: Reliability and Security Matrices **Goal**: Prove persistence, race, path, process, and isolation invariants under adversarial failures. -**Depends on**: Phases 1–14 +**Depends on**: Phases 1–16 **Requirements**: REQ-04, REQ-05, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-50 @@ -681,11 +721,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Binary/mode/rename/delete restore, manual recovery, and legacy staging remain collision-safe under fault injection; tracked canonical blob/tree identities remain stable across attributes, LF/CRLF and `core.autocrlf`, `core.fileMode`, executable-bit, and symlink checkout cases. - [ ] Boundary and over-limit payload matrices prove 25 MiB/result and 250 MiB/task enforcement, no truncation/hidden authority, authoritative/evidence retention, maintenance reachability records, and pre-projection secret rejection under crashes and retries. -### Phase 16: Real-Host E2E and Review-Quality Validation +### Phase 18: Real-Host E2E and Review-Quality Validation **Goal**: Validate useful independent review and complete normal, manual, and migration journeys in both producer directions. -**Depends on**: Phases 1–15 +**Depends on**: Phases 1–17 **Requirements**: REQ-01, REQ-02, REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -702,11 +742,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] A real task reaches the snapshot boundaries, receives `SNAPSHOT_LIMIT` above either cap without partial authority, retains all current/evidence chains, records a safe maintenance prune, and rejects a secret-bearing checkpoint before Git projection. - [ ] The approved corpus thresholds demonstrate substantive defect detection and acceptable false blockers; failure of `VAL-02` reopens the automation premise. -### Phase 17: Release Packaging, Support Matrix, and Documentation Consistency +### Phase 19: Release Packaging, Support Matrix, and Documentation Consistency **Goal**: Produce a coherent beta release candidate and an explicit report of any remaining external release blockers. -**Depends on**: Phases 1–16 +**Depends on**: Phases 1–18 **Requirements**: REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -727,21 +767,23 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali |-------|------|--------| | 1 | Contracts, Assets, and Package Scaffold | COMPLETE (2026-07-27) | | 2 | Review Evidence and Contract Authority | COMPLETE (2026-07-27) | -| 3 | Inert MCP Boundary and Offline Bundle | Not Started | -| 4 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | -| 5 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | -| 6 | Snapshots, Implementation Manifests, and Restore | Not Started | -| 7 | Durable Gates, Waivers, and Manual Decisions | Not Started | -| 8 | Host Identity, Sandbox, and CLI Dispatch | Not Started | -| 9 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | -| 10 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | -| 11 | Installer, Initialization, and Host Registration | Not Started | -| 12 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | -| 13 | Manual and Degraded Recovery Workflow | Not Started | -| 14 | Legacy Upgrade Workflow | Not Started | -| 15 | Reliability and Security Matrices | Not Started | -| 16 | Real-Host E2E and Review-Quality Validation | Not Started | -| 17 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | +| 3 | MCP Contract Boundary and Dependency Admission | Not Started | +| 4 | Guarded MCP Runtime and SDK Compatibility | Not Started | +| 5 | Offline Bundle and Release Integrity | Not Started | +| 6 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | +| 7 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | +| 8 | Snapshots, Implementation Manifests, and Restore | Not Started | +| 9 | Durable Gates, Waivers, and Manual Decisions | Not Started | +| 10 | Host Identity, Sandbox, and CLI Dispatch | Not Started | +| 11 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | +| 12 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | +| 13 | Installer, Initialization, and Host Registration | Not Started | +| 14 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | +| 15 | Manual and Degraded Recovery Workflow | Not Started | +| 16 | Legacy Upgrade Workflow | Not Started | +| 17 | Reliability and Security Matrices | Not Started | +| 18 | Real-Host E2E and Review-Quality Validation | Not Started | +| 19 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | --- *Created: 2026-07-26* diff --git a/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission.md b/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission.md new file mode 100644 index 00000000..0316a348 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission.md @@ -0,0 +1,182 @@ +# Phase 3: MCP Contract Boundary and Dependency Admission + +**Status**: DESIGNED +**Task**: mcp-integration +**Goal**: Admit the exact MCP dependency surface and freeze a complete SDK-free five-tool catalogue and authenticated handler/error boundary for a later transport owner. +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-33 + +## Context + +Phase 2 established the normative five-tool contracts, closed project/protocol errors, and authentic immutable connection and invocation contexts without adopting MCP. Phase 3 adds the smallest MCP-facing contract layer that can be exercised entirely in process. The SDK adapter, transport, lifecycle, cancellation, process entry, and live transcript remain Phase 4; release packaging remains Phase 5. + +The dependency target is exact `@modelcontextprotocol/server@2.0.0-beta.5`, exact locked `@modelcontextprotocol/core@2.0.0-beta.5`, and protocol `2025-11-25`. Before changing the package or lock, implementation must recheck the package identities, protocol support, maintenance/deprecation guidance, and these public exports/declarations: root `Server`, `StdioServerTransport` from `@modelcontextprotocol/server/stdio`, singleton `supportedProtocolVersions`, method-string request handlers and request signal, `Server.projectCallToolResult`, `close`, and root `specTypeSchemas` with `ListToolsResult` and `RequestId`. Tests import the neutral schemas exactly as `import { specTypeSchemas } from "@modelcontextprotocol/server"`; core-root and internal schema imports are not substitutes. + +Phase 3 legal admission is deliberately shallow. Before dependency mutation, verify only that the exact server and core root packages each declare `MIT`, confirm `MIT` remains allowed by existing license policy, and record both root entries in the existing dependency notices. If either root declaration is not `MIT` or is no longer allowed, leave dependency changes unmade and return for phase-design review. Phase 3 performs no tarball-level, transitive, embedded-component, documentation-classification, or bundle-wide legal audit. Phase 5 independently owns legal completeness for the distributed bundle. Phase-design approval is not commit authorization; implementation still requires the workflow's separate explicit commit gate. + +## What We're Building + +Phase 3 extends the contract layer with one shared internal request-ID schema consumed by both `parseTransportRequestId` and authentic `createInvocationContext`. It accepts arbitrary strings and finite safe integers, including negative integers, `-0`, `Number.MIN_SAFE_INTEGER`, and `Number.MAX_SAFE_INTEGER`; rejects adjacent unsafe integers, fractions, and nonfinite/non-JSON values; and preserves admitted JavaScript values exactly. Phase 4 owns wire mapping and `-0` normalization. + +One shared internal client-implementation schema is consumed by `parseClientImplementation` and direct-only `connectionContextFactory.initialize`. It accepts and freezes exact `{ name, version }` with arbitrary strings. Phase 4 must project a full SDK Implementation object to exact `{ name, version }` before either consumer, discarding optional SDK metadata. Parser-to-mint fixtures prove admitted request IDs and client strings survive unchanged into authentic frozen contexts. + +The interoperating contract exports are: + +```ts +export function validateProjectFailureStructure( + name: K, + value: unknown +): StructurallyValidProjectResult; + +export function parseTransportRequestId(value: unknown): string | number; + +export function parseClientImplementation(value: unknown): Readonly<{ + readonly name: string; + readonly version: string; +}>; + +export function assertAuthenticInvocationContext( + value: unknown +): asserts value is InvocationContext; +``` + +`validateProjectFailureStructure` accepts only a closed `ok: false` project result, reparses/freezes it, and registers it in the existing structural-result identity owner; it cannot mint a success. `src/contracts/index.ts` remains contract-only. It exports the failure validator, candidate parsers, invocation constructor, and invocation assertion, but not `connectionContextFactory`, which remains a deliberate direct import from `src/contracts/contexts.ts`. + +`src/mcp/tools.ts` is the supported direct catalogue import for Phase 4 and owns these exports: + +```ts +export interface AdvertisedToolDescriptor { + readonly name: ToolName; + readonly inputSchema: Readonly>; + readonly outputSchema: Readonly>; +} + +export const ADVERTISED_TOOL_CATALOGUE: + readonly AdvertisedToolDescriptor[]; +``` + +There is no `src/mcp/index.ts`, package export, or contracts-barrel re-export for the catalogue. Phase 4 imports both `ADVERTISED_TOOL_CATALOGUE` and `AdvertisedToolDescriptor` only from `src/mcp/tools.ts`. + +The catalogue contains exactly five deeply frozen descriptors in `TOOL_NAMES` order. It is derived from exactly `mcp-tools.schema.json`, `primitives.schema.json`, `path-claim.schema.json`, `evidence-slots.schema.json`, `rubric.schema.json`, `gate-contract.schema.json`, `gate-decision.schema.json`, and `project-error.schema.json`. Projection localizes references, removes embedded identifiers and `x-archflow-*` assertions, retains JSON Schema 2020-12, and proves object-root input/output schemas without weakening branches. Each schema compiles under strict `ajv@8.20.0` plus `ajv-formats@3.0.1` with an otherwise empty registry. Tests validate the catalogue through public-root `specTypeSchemas.ListToolsResult` and separately pin the fixed five-name/order/object-root/no-cursor surface. A classified corpus distinguishes portable structure from semantic checks retained by Phase 2 runtime validators. + +`src/mcp/server.ts` owns the SDK-free authenticated handler/error boundary: + +```ts +export type ToolHandler = ( + call: Extract, + context: InvocationContext +) => unknown | Promise; + +export type ToolHandlerRegistry = Readonly; +}>>; + +declare const authenticatedProtocolErrorBrand: unique symbol; +export type AuthenticatedProtocolError = Readonly<{ + readonly value: ProtocolError; + readonly [authenticatedProtocolErrorBrand]: true; +}>; + +export function authenticateProtocolError( + value: unknown +): AuthenticatedProtocolError; + +export type ToolProjectOutcome = { + readonly [K in ToolName]: Readonly<{ + readonly kind: "project-result"; + readonly tool: K; + readonly result: StructurallyValidProjectResult; + }>; +}[ToolName]; + +export type ToolBoundaryOutcome = + | ToolProjectOutcome + | Readonly<{ + readonly kind: "protocol-error"; + readonly error: AuthenticatedProtocolError; + }>; + +export interface ToolBoundary { + readonly invoke: ( + name: string, + args: unknown, + context: InvocationContext + ) => Promise; +} + +export function createToolBoundary( + handlers: ToolHandlerRegistry +): ToolBoundary; + +export function assertAuthenticToolBoundary( + value: unknown +): asserts value is ToolBoundary; + +export function assertAuthenticToolBoundaryOutcome( + value: unknown +): asserts value is ToolBoundaryOutcome; +``` + +The copied registry, boundary, authenticated protocol-error wrappers, and outcomes are deeply frozen and process-authenticated through private identity sets. Casts, structural fakes, and spread clones fail. The boundary accepts only a string name and authentic invocation context. Unknown names return authenticated `TOOL_NOT_FOUND` with a lowercase SHA-256 digest of the exact UTF-8 name; known tools without a handler return authenticated `TOOL_DISABLED` with `lifecycle_state: "inert-no-handler"`. + +Known-tool argument failures use this closed classification and `validateProjectFailureStructure`; parser exception text never escapes: + +| Input condition | Generated project error | +|-----------------|-------------------------| +| Non-plain JSON or not an object | `CONTRACT_INVALID`, `issue_code: "input-not-object"`, selected `tool` | +| Object missing `schema_version` | `CONTRACT_INVALID`, `issue_code: "schema-version-missing"`, selected `tool` | +| Present version is non-string or fails Phase 2 safe-version syntax | `CONTRACT_INVALID`, `issue_code: "schema-version-invalid"`, selected `tool` | +| Safe supplied version is not `"1"` | `CONTRACT_VERSION_UNSUPPORTED`, exact supplied version, `supported_version: "1"` | +| Version is `"1"` but any other parse/semantic check fails | `CONTRACT_INVALID`, `issue_code: "input-invalid"`, selected `tool` | + +A valid handler is called at most once and its `unknown` return is structurally revalidated. Tool-neutral closed project failures may be accepted on any known-tool path. Malformed output, detectable cross-tool success substitution, or handler throw/rejection becomes a validated correlation-only `INTERNAL_ERROR` result; raw exception and handler prose do not escape. Transport precedence, cancellation, numeric error projection, `CallToolResult`, and wire serialization remain Phase 4. + +## Files + +| Action | File | Purpose | +|--------|------|---------| +| Modify | `package.json`, `package-lock.json` | Admit exact server beta.5, retain exact core beta.5 in the lock, and keep Node `24.15.0` as compatibility floor. | +| Modify | `scripts/check-dependency-policy.mjs`, `scripts/check-notices.mjs` | Enforce exact root server/core identities, their root package-declared licenses through existing allowed-license policy, and absence of later-phase dependencies. | +| Modify | `THIRD_PARTY_NOTICES.md`, `docs/dependency-upgrades.md` | Record both root package entries, protocol/public-surface currency evidence, and Node compatibility versus production patch guidance. | +| Modify | `src/contracts/mcp-tools.ts` | Add the failure-only structural validator without granting success authenticity. | +| Modify | `src/contracts/contexts.ts`, `src/contracts/index.ts` | Add shared request-ID/client schemas, parsers, and invocation assertion while keeping the connection factory direct-only and the barrel contract-only. | +| Create | `src/mcp/tools.ts` | Own and export the catalogue descriptor type and deterministic deeply frozen five-tool catalogue as the supported direct Phase 4 import. | +| Create | `src/mcp/server.ts` | Export the frozen authenticated SDK-free handler/error/outcome boundary and exact input classification. | +| Modify | `test/unit/mcp-tools.test.ts`, `test/contracts/mcp-contract-agreement.test.ts`, `test/unit/contexts.test.ts` | Prove failure-only construction, shared parser/mint agreement, exact safe request IDs, full Implementation projection, authenticity, and freezing. | +| Create | `test/unit/mcp-server.test.ts`, `test/contracts/mcp-advertised-schema.test.ts`, `test/fixtures/mcp/{catalogue,boundary}/**` | Exercise boundary behavior and catalogue portability/public-root agreement without a live transport. | +| Modify | `.github/workflows/ci.yml` | Run focused checks on the Node matrix and enforce the Phase 3 no-runtime boundary. | + +Phase 3 creates no `src/main.ts`, SDK adapter, transport, lifecycle, cancellation, request-ID map, `-0` wire normalization, live protocol fixture, or runnable server. Those are Phase 4. It creates no release bundle, manifest, clean-copy smoke, or bundle-wide legal inventory. Those are Phase 5. Persistence, dispatch, durable gates, CLI, installer, registration, and skills remain out of scope. + +## Work Breakdown + +1. **Admit the exact root dependencies**: Before repository mutation, recheck exact server/core beta.5 identities, protocol/public declarations, guidance, and both root `MIT` declarations. Proceed only when they match the approved basis and existing allowed-license policy; otherwise leave dependency changes unmade and return for phase-design review. Update package/lock, root notices, currency guidance, and focused policy checks without deeper legal inventory. +2. **Extend the Phase 2 seams**: Add the failure-only result validator, one shared request-ID schema for parser and invocation mint, one shared client schema for parser and direct connection mint, and the narrow invocation assertion. Prove safe bounds, `-0`, arbitrary strings, exact full-Implementation projection, parser-to-mint preservation, freezing, and fake rejection. +3. **Freeze the portable catalogue**: Implement `src/mcp/tools.ts` from the exact eight-schema closure. Prove five-tool order, reference closure, object roots, deep freezing, strict Ajv compilation, public-root `specTypeSchemas.ListToolsResult` acceptance, frozen-2025 invariants, and the portable-versus-semantic corpus. +4. **Freeze the authenticated boundary**: Implement the handler/registry/error/outcome/boundary exports and private authenticity consumers. Classify unknown, disabled, and known-invalid calls exactly; invoke handlers at most once; revalidate returns; and reduce malformed/substituted/thrown results to safe closed outcomes. +5. **Verify phase boundaries**: Run focused unit, contract, schema, dependency, notice, and CI checks. Prove production Phase 3 source has no SDK import and runtime/release-only files remain absent. + +## Success Criteria + +- [ ] Implementation-start evidence confirms exact server/core beta.5, protocol `2025-11-25`, required public exports, and allowed root `MIT` declarations before package/lock mutation; a mismatch returns for phase-design review without dependency changes, and phase-design approval does not authorize a commit. +- [ ] Existing notices contain both root package entries, and Phase 3 adds no tarball, embedded-component, documentation-class, transitive, or bundle-wide legal audit. +- [ ] One shared request-ID schema is consumed by parser and authentic invocation mint, preserving arbitrary strings, negative safe integers, `-0`, and both safe bounds while rejecting adjacent unsafe integers, fractions, and nonfinite values; public-root `specTypeSchemas.RequestId` is a test-only agreement oracle. +- [ ] One shared client schema is consumed by parser and direct-only authentic connection mint; full SDK Implementation fixtures are projected to exact `{ name, version }`, admitted values survive parser-to-mint unchanged, and fake/spread contexts fail. +- [ ] `validateProjectFailureStructure` authenticates only closed known-tool failures and cannot mint success. +- [ ] `src/contracts/index.ts` remains contract-only. `src/mcp/tools.ts` is the only supported catalogue seam and owns/exports `AdvertisedToolDescriptor` plus `ADVERTISED_TOOL_CATALOGUE`; there is no `src/mcp/index.ts` or package/barrel catalogue export, and Phase 4 imports only from the exact tools module. +- [ ] Exactly five deeply frozen descriptors derive from the exact eight schemas, compile with strict Ajv/formats from an empty registry, pass public-root `ListToolsResult`, and retain the direct frozen-2025 surface without SDK internal imports. +- [ ] The SDK-free boundary and every outcome/error wrapper are frozen and process-authenticated; known/unknown/disabled/invalid/success/failure/substitution/throw cases produce the exact safe outcomes with at most one handler call and no raw error leakage. +- [ ] Focused checks pass on both Node versions; no Phase 4 runtime or Phase 5 release artifact is introduced. + +## Verification Steps + +1. Before any package/lock/policy/notice edit, check exact server/core beta.5 identities, protocol support, required public declarations/exports, current guidance, and both root `MIT` declarations against existing allowed-license policy. If either identity/public surface differs or either root declaration is not allowed `MIT`, leave dependency changes unmade and return for phase-design review; do not treat phase-design approval as commit authorization. +2. On Node `24.15.0` and `24.18.0`, run `npm ci`, typecheck, unit/contract tests, dependency policy, notices check, and the repository aggregate check. +3. Inspect `package-lock.json`, policy output, and `THIRD_PARTY_NOTICES.md` for exact server/core root entries and absence of later-phase dependencies. Confirm Phase 3 introduced no retained MCP legal assets or embedded/transitive legal inventory. +4. Exercise the failure-only validator across every tool and closed failure plus success, malformed/open values, casts, and substitutions. +5. Exercise both shared schemas through their parsers and authentic mints. Cover arbitrary strings, `-0`, negative values, both safe bounds, adjacent unsafe integers, fractions/nonfinite candidates, exact full-Implementation projection, one-shot connection minting, freezing, and fake/spread rejection. +6. Validate the catalogue through exact public-root `specTypeSchemas.ListToolsResult`; compile every schema with fresh strict Ajv 2020 plus formats and no preloaded project schemas/custom keywords; assert five names/order, local references, object roots, no custom keywords/identifiers/cursor, and deep freezing. +7. Invoke the boundary directly with authentic contexts and assert the exact unknown/disabled/input-classification/handler-result/fallback cases, zero-or-one calls, safe correlation-only errors, freezing, and authenticity rejection. +8. Verify module boundaries: `src/contracts/index.ts` exports only contract seams and excludes `connectionContextFactory` and all catalogue exports; `src/mcp/tools.ts` owns and exports only the supported catalogue type/constant; `src/mcp/index.ts` does not exist; Phase 4's planned import is exactly `src/mcp/tools.ts`; production `src/` has no MCP SDK import; and Phase 4 runtime plus Phase 5 release files remain absent. + +--- +*Designed: 2026-07-27* diff --git a/.archflow/tasks/mcp-integration/reviews/phase-3-design-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-3-design-counter-review.md new file mode 100644 index 00000000..5d9b9dcc --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-3-design-counter-review.md @@ -0,0 +1,111 @@ +# Phase 3 Design Counter-Review + +The design still has substantive issues. The exact `@modelcontextprotocol/server@2.0.0-beta.5` tarball and tagged upstream sources were checked on 2026-07-27 in addition to the PRD, architecture, Phase 2 design/log, current contracts, schemas, and dependency-policy code. + +## Findings + +### 1. Initialize cancellation can strand the lifecycle after SDK identity has already mutated + +**Severity:** major + +The design says every active request ID is normalized and every cancellation notification is translated through that map (lines 151–155, 184, 188, and 203–208), but it never carves out the initialize request. MCP 2025-11-25 says a client must not cancel initialize and invalid cancellation notifications should be ignored. Beta.5 does not enforce that method restriction: its cancellation handler aborts whichever request controller matches the supplied ID. In a same-buffer `initialize` followed by `notifications/cancelled` race, beta.5 can set negotiated version/client identity and then suppress the initialize response. The guard therefore never observes the success response that moves it out of `INITIALIZING`, leaving a mutated SDK identity behind a permanently wedged adapter state. This is distinct from the falsey-ID defect the design already handles. See the [MCP cancellation rules](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation) and beta.5's tagged [`Protocol` implementation](https://github.com/modelcontextprotocol/typescript-sdk/blob/%40modelcontextprotocol/server%402.0.0-beta.5/packages/core-internal/src/shared/protocol.ts). + +**Suggested resolution:** Make request-map records method-aware. Explicitly ignore/drop cancellation targeting the active initialize request without changing lifecycle or releasing its mapping, and add a same-buffer initialize-plus-cancel fixture that must still emit exactly one initialize response and proceed through `initialized` to `READY`. + +### 2. Beta.5 validates the outer call before the designed known-tool error boundary can run + +**Severity:** major + +Lines 139–147 and 205 require a known tool whose arguments are non-plain JSON or not an object to return the closed project `CONTRACT_INVALID/input-not-object` result. Lines 137 and 231 simultaneously leave outer malformed `tools/call` parameters on the SDK path. Beta.5's low-level `Server._wrapHandler` validates the complete `CallToolRequest` before invoking the registered handler, and its schema requires `arguments` to be a record. The SDK therefore returns `InvalidParams` before `ToolBoundary.invoke`, making the first classification-table row unreachable through normal registration. Its error message is also `Invalid tools/call request: ${validatedRequest.message}`, so a malformed-name call returns `-32602` with the formatted validator issue/path text despite the no-parser-text criterion. See beta.5's tagged [`Server._wrapHandler`](https://github.com/modelcontextprotocol/typescript-sdk/blob/%40modelcontextprotocol/server%402.0.0-beta.5/packages/server/src/server/server.ts). + +**Suggested resolution:** Pin an adapter/guard precedence table before SDK validation. At minimum, missing/non-string names need a fixed bounded SDK-domain `InvalidParams`, while a known string name with invalid/non-object `arguments` must be routed to the boundary if the project-result table is retained. Also state the precedence for an unknown string name combined with malformed arguments. Add byte-exact fixtures for absent params, absent name, non-string name, unknown name plus malformed arguments, and each known-tool malformed-arguments class. + +### 3. Beta.5 does not expose the “actual 2025 ListToolsResult parser” required by the design + +**Severity:** major + +Lines 157, 166, 176, 186, 196, and 229 repeatedly make acceptance depend on parsing the catalogue with beta.5's “actual 2025” list-result parser. The public SDK/core schema surface is the neutral model; beta.5 deliberately keeps its revision-specific wire codecs and validators internal. Importing `@modelcontextprotocol/core/internal` or reaching `codecForVersion` would violate the public-hook compatibility gate and create another unstable dependency seam. As written, the contract test and success criterion are not implementable using the allowed public API. The SDK's tagged [`specTypeSchemas` source](https://github.com/modelcontextprotocol/typescript-sdk/blob/%40modelcontextprotocol/server%402.0.0-beta.5/packages/core-internal/src/types/specTypeSchema.ts) documents the neutral-versus-wire distinction. + +**Suggested resolution:** Require the public neutral `ListToolsResult` schema for direct catalogue validation, and prove 2025 wire compatibility through the live pinned low-level `Server` transcript, which exercises the internal negotiated codec without importing it. Rename every “actual 2025 parser” criterion accordingly and add an explicit prohibition on internal SDK imports. + +### 4. “Fresh stock Ajv 2020” cannot compile the projected closure as specified + +**Severity:** major + +Lines 157, 196, and 229 require every descriptor to compile in a fresh stock Ajv 2020 instance with no additional registrations. The exact schema closure includes `gate-decision.schema.json`, whose `recordedAt` definition uses `format: "date-time"`. Strict Ajv 2020 treats that format as unknown unless the separately pinned `ajv-formats` plugin is installed; stripping only `x-archflow-*` does not change it. The advertised-schema acceptance criterion will therefore fail before any instance corpus is evaluated. + +**Suggested resolution:** Define the portability validator as fresh strict Ajv 2020 plus the pinned `ajv-formats` standard-format plugin, with no ArchFlow schemas or custom keywords, or deliberately remove/rewrite `format` during projection and classify the lost constraint as runtime-only. Add a test proving the selected validator setup from an empty registry. + +### 5. Shutdown quarantine omits writes already blocked inside `StdioServerTransport.send()` + +**Severity:** major + +Lines 155, 188, 208, and 234 require close to clear listeners, resolve without waiting for arbitrary work, and prevent every late frame. In beta.5, a `StdioServerTransport.send()` whose `Writable.write()` returns `false` installs per-send `error` and `drain` listeners. `StdioServerTransport.close()` removes its long-lived stream listeners and clears its read buffer, but it neither cancels pending sends nor removes those per-send listeners. Closing the guard can therefore leave a pending write/listeners behind, and a later drain can complete a frame after the runtime entered `CLOSING`. The injected `Writable` interface does not establish that the runtime may destroy the caller-owned stream. See beta.5's tagged [`StdioServerTransport`](https://github.com/modelcontextprotocol/typescript-sdk/blob/%40modelcontextprotocol/server%402.0.0-beta.5/packages/server/src/server/stdio.ts). + +**Suggested resolution:** Define an outbound-write ownership contract and add a permanently backpressured `Writable` fixture. Either use a transport implementation whose pending sends are adapter-owned and cancellable, or explicitly grant/encode stream-destruction ownership and prove close settles/removes all pending write listeners without a post-close frame. If neither is possible through public beta.5 hooks, the compatibility gate must stop for approval rather than claiming quarantine. + +### 6. Exact request-ID preservation omits negative zero + +**Severity:** major + +Lines 133, 153, 198, 204, 213, and 233 adopt every number accepted by beta.5's `z.number().int()` and promise exact parsed-value restoration, but never address `-0`. `JSON.parse("-0")` produces JavaScript negative zero and beta.5 accepts it; `Map` key equality treats `-0` and `0` as the same key, while `JSON.stringify(-0)` emits `0`. The proposed bijection therefore cannot be both collision-free for parsed numeric identity and exactly restore negative zero through `StdioServerTransport`. + +**Suggested resolution:** With explicit approval, define JSON-RPC numeric `-0` as normalized/protocol-equivalent to `0` and narrow the exact-preservation language, or choose a wire representation/serializer that actually preserves the distinction. Add `Object.is`-based parser tests plus live `-0`/`0` collision, response, cancellation, and reuse fixtures. + +### 7. The “exact SDK-free exports” omit the constructors needed to mint authentic contexts + +**Severity:** major + +The adapter chunk is responsible for connection and invocation minting (lines 151, 168, and 188), but the supposedly exact inter-chunk export list at lines 18–131 exposes only parsers and `assertAuthenticInvocationContext`. In the current code, `createInvocationContext` is in the public barrel, while the one-shot `connectionContextFactory` is exported only from `src/contracts/contexts.ts` and intentionally absent from that barrel. The design neither pins those existing imports as part of the adapter seam nor introduces an adapter-only context-mint interface. It also does not pin whether the adapter extracts only `name` and `version` from beta.5's full `ImplementationSchema` before calling `parseClientImplementation`; passing the SDK-valid object through directly would encounter optional `title`, `icons`, `websiteUrl`, and `description` fields that the current strict context shape does not accept. Independent implementation of chunks 2 and 5 can therefore diverge on access, one-shot timing, and valid metadata projection. + +**Suggested resolution:** Extend the pinned seam inventory to name the exact existing context constructors the adapter consumes, their module ownership, the explicit full-implementation-to-`{name, version}` projection, and the call order from startup capture through initialize response, initialized notification, and per-call invocation creation. Test every optional beta.5 implementation metadata field. Preserve the non-public mint boundary; do not solve this by broadly exporting the connection factory from `src/contracts/index.ts`. + +### 8. The phase is too large for one implementation session despite having only seven nominal chunks + +**Severity:** major + +Chunk 5 alone combines a custom transport wrapper, six-state lifecycle, initialization interception, ID bijection, cancellation routing, context minting, three-domain error projection, shutdown ordering, and late-settlement quarantine. Chunk 3 is a cyclic eight-schema resolver and portability corpus; chunk 4 adds a second identity-backed authority subsystem; chunk 6 is effectively a full adversarial protocol matrix rather than a bounded verification step. The file table spans contract-owner changes, three new runtime modules, dependency/license policy, build smoke, CI, and multiple unit/contract/integration suites. The risk is not raw file count: the SDK race/backpressure findings above show that the adapter will require iterative live-spike work before the broad matrix can pass. This exceeds the phase-implementation budget described by the ArchFlow skill even with delegation. + +**Suggested resolution:** Split the architecture phase, with explicit user approval, at a stable seam—for example (a) dependency admission, Phase 2 seam extensions, portable catalogue, and SDK-free tool boundary; then (b) guarded beta.5 transport, lifecycle/cancellation/error projection, process entry, and live protocol fixtures. Each resulting phase should own its corresponding tests and leave no half-adopted runtime entry. + +### 9. Transition-license evidence omits the separately locked core package + +**Severity:** minor + +The file plan retains and digest-checks only `@modelcontextprotocol/server@2.0.0-beta.5`'s transition license (lines 170–171 and 190), but that package has an exact runtime dependency on `@modelcontextprotocol/core@2.0.0-beta.5`. Both registry tarballs contain the same MIT/Apache transition `LICENSE` (SHA-256 `0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a`), while npm metadata labels both simply MIT. A lock-visible SPDX check plus one server-only retained mapping does not prove the core package's applicable transition text was reviewed. + +**Suggested resolution:** Map both exact server and core identities to the retained license asset (or retain both files), digest-check both installed/tarball sources, and mutation-test that either missing mapping fails. Keep Phase 4 responsible for bundle-component attribution, but make Phase 3's admitted lock evidence complete for both MCP runtime packages. + +### 10. “Unsupported cursor” has no pinned wire behavior + +**Severity:** minor + +Chunk 6 says to test an unsupported `tools/list` cursor (line 189), but the boundary and error matrix never say whether a cursor is ignored, returns a fixed SDK `InvalidParams`, or uses another response. Beta.5 accepts the cursor structurally, so this is application policy rather than an automatic SDK result. Different implementations can satisfy the rest of the design while producing incompatible transcripts. + +**Suggested resolution:** Pin the post-`READY` `tools/list` request contract: accept absent params/empty params, state the exact behavior for a present cursor, and add the corresponding byte-stable transcript and zero-boundary-call assertion. + +## Triage + +1. **Initialize cancellation — accepted.** The guarded runtime design will make active request records method-aware and ignore cancellation targeting the active `initialize` request without releasing its mapping or changing lifecycle. A same-buffer initialize-plus-cancel fixture will require one initialize response followed by a successful `initialized` transition to `READY`. + +2. **`tools/call` validation precedence — accepted.** The guarded runtime will own a pre-SDK precedence table so raw SDK validator text cannot escape. Missing params or a missing/non-string name will receive a fixed bounded SDK-domain `InvalidParams`; an unknown string name combined with malformed arguments will also receive that outer-call error; a known name with missing/non-object/otherwise invalid arguments will reach the frozen tool boundary and its closed `CONTRACT_*` classification; an unknown name with structurally valid arguments will receive `TOOL_NOT_FOUND`. + +3. **Public list-result validation — accepted with a proof correction.** The catalogue phase will validate through the public neutral `specTypeSchemas.ListToolsResult`, enforce the explicit object-root and other frozen-2025 subset invariants itself, and use a live negotiated transcript only to prove the emitted 2025 wire object. It will explicitly prohibit imports from SDK internal codec/schema paths and will not claim that the live server validates `tools/list` output. + +4. **Ajv portability setup — accepted.** “Fresh stock” will mean strict `ajv@8.20.0` plus the already pinned `ajv-formats@3.0.1`, with an otherwise empty registry and no ArchFlow schemas or custom keywords. An empty-registry compile fixture will pin this setup. + +5. **Backpressured stdio teardown — partially accepted.** The ownership/listener gap is real: beta.5 can leave per-send listeners and a pending promise after close on a permanently backpressured stream. The finding overstates the `drain` mechanism, because `write()` already accepted the bytes and `drain` settles that send rather than initiating another write. The guarded runtime design will introduce an adapter-owned cancellable `Writable` bridge, promise no new destination write after `CLOSING`, allow bytes already accepted by the caller-owned destination to flush, remove bridge/SDK-facing listeners without destroying the caller stream, and stop at the compatibility gate if public hooks cannot prove that scoped contract. + +6. **Negative zero — accepted.** The guarded runtime design will normalize numeric `-0` to protocol-equivalent `0`, narrow exact-preservation language accordingly, and treat concurrent `-0`/`0` as duplicate numeric ID reuse. `Object.is` parser tests and live response/cancellation/reuse fixtures will pin the behavior; approval of that phase design will be the explicit approval for this normalization. + +7. **Context constructor seam — accepted.** The phase boundary will name direct adapter imports of the non-barrel `connectionContextFactory` and `createInvocationContext`, keep the connection mint non-public, project the SDK implementation object explicitly to `{ name, version }`, and pin startup capture → initialize response → one `initialized` mint → per-call invocation ordering. Optional SDK metadata fields will be covered by fixtures. + +8. **Phase sizing — accepted; architecture approval required.** The current Phase 3 exceeds the implementation budget even with delegation. The proposed split is Phase 3, **MCP Contract Boundary and Dependency Admission**, followed by Phase 4, **Guarded MCP Runtime and SDK Compatibility**. The current Offline Bundle phase and all later phases shift by one. No architecture or design revision will be made until the user explicitly approves this second split; approval authorizes planning only, not implementation. + +9. **Core transition-license evidence — accepted.** Phase 3 will map both exact `@modelcontextprotocol/server@2.0.0-beta.5` and `@modelcontextprotocol/core@2.0.0-beta.5` identities to the reviewed byte-identical transition-license asset, verify both source digests, and mutation-test that either missing mapping fails. Distributed bundle attribution remains in the later offline-bundle phase. + +10. **`tools/list` cursor behavior — accepted.** The guarded runtime will accept absent or empty params, return the full fixed catalogue without `nextCursor`, and reject any present cursor—including `""`—with fixed bounded `-32602 Invalid params`, no cursor echo, and zero catalogue/boundary invocation. Byte-stable transcripts will pin the policy. + +## Human scope adjustment + +After triage, the user explicitly narrowed Phase 3 legal admission to checking only the exact server and core root package-declared licenses against the existing allowed-license policy and recording those two root entries. This supersedes finding 9's retained transition-license evidence plan and any later proposal for tarball, embedded-component, documentation-class, or forensic legal inventory in Phase 3. Phase 5 independently owns legal completeness for the distributed bundle. From a82a66b4f7b617b0a5def73de032261b5e53719e Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 16:52:20 -0500 Subject: [PATCH 010/124] MCP Integration Phase 3: MCP Contract Boundary and Dependency Admission Admit the exact MCP beta roots and add the portable five-tool catalogue plus authenticated SDK-free handler boundary. Extend context, failure, and result validation with exhaustive schema/runtime agreement and tested Phase 3 boundary policy, including all accepted counter-review fixes without introducing transport or release artifacts. --- .../tasks/mcp-integration/architecture.md | 2 +- ...t-boundary-and-dependency-admission-log.md | 43 +++ ...tract-boundary-and-dependency-admission.md | 5 +- .../reviews/phase-3-impl-counter-review.md | 33 ++ .github/workflows/ci.yml | 4 +- THIRD_PARTY_NOTICES.md | 2 + docs/dependency-upgrades.md | 9 + package-lock.json | 29 ++ package.json | 8 +- scripts/check-dependency-policy.mjs | 51 ++- scripts/check-notices.mjs | 8 + scripts/check-phase-3-mcp-boundary.mjs | 79 +++++ scripts/test-phase-3-mcp-boundary-policy.mjs | 75 ++++ src/contracts/contexts.ts | 9 +- src/contracts/index.ts | 8 +- src/contracts/mcp-tools.ts | 41 ++- .../schemas/v1/mcp-tools.schema.json | 2 +- src/mcp/server.ts | 248 +++++++++++++ src/mcp/tools.ts | 93 +++++ test/contracts/mcp-advertised-schema.test.ts | 330 ++++++++++++++++++ test/contracts/mcp-contract-agreement.test.ts | 47 ++- .../mcp/boundary/input-classification.json | 10 + .../mcp/catalogue/classified-corpus.json | 50 +++ test/unit/contexts.test.ts | 78 ++++- test/unit/mcp-server.test.ts | 322 +++++++++++++++++ test/unit/mcp-tools.test.ts | 198 ++++++++++- 26 files changed, 1762 insertions(+), 22 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission-log.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-3-impl-counter-review.md create mode 100644 scripts/check-phase-3-mcp-boundary.mjs create mode 100644 scripts/test-phase-3-mcp-boundary-policy.mjs create mode 100644 src/mcp/server.ts create mode 100644 src/mcp/tools.ts create mode 100644 test/contracts/mcp-advertised-schema.test.ts create mode 100644 test/fixtures/mcp/boundary/input-classification.json create mode 100644 test/fixtures/mcp/catalogue/classified-corpus.json create mode 100644 test/unit/mcp-server.test.ts diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index 3c79895b..2ccff01e 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -767,7 +767,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali |-------|------|--------| | 1 | Contracts, Assets, and Package Scaffold | COMPLETE (2026-07-27) | | 2 | Review Evidence and Contract Authority | COMPLETE (2026-07-27) | -| 3 | MCP Contract Boundary and Dependency Admission | Not Started | +| 3 | MCP Contract Boundary and Dependency Admission | COMPLETE (2026-07-27) | | 4 | Guarded MCP Runtime and SDK Compatibility | Not Started | | 5 | Offline Bundle and Release Integrity | Not Started | | 6 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | diff --git a/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission-log.md b/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission-log.md new file mode 100644 index 00000000..fcc01710 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission-log.md @@ -0,0 +1,43 @@ +## Implementation Log: Phase 3 - MCP Contract Boundary and Dependency Admission + +### Decisions Made + +- Admitted exact direct `@modelcontextprotocol/server@2.0.0-beta.5` with exact locked `@modelcontextprotocol/core@2.0.0-beta.5` only after rechecking both root identities, root `MIT` declarations, protocol `2025-11-25`, the required public declarations, and current upstream beta/deprecation guidance. The dependency policy admits only those two MCP package identities and continues to reject later-phase MCP adapters/frameworks and runtime dependencies. +- Kept every production contract and MCP boundary module SDK-free. Public-root `specTypeSchemas.RequestId` and `specTypeSchemas.ListToolsResult` are test-only agreement oracles; the Phase 3 catalogue and handler boundary import only ArchFlow-owned contracts. +- Used one internal request-ID schema for both `parseTransportRequestId` and authentic invocation minting, preserving arbitrary strings and every finite safe integer including negative values and `-0`. Used one exact client-implementation schema for both its parser and direct-only connection mint, requiring the future adapter to project SDK metadata to `{ name, version }` first. +- Added failure-only structural authentication without granting success authority. `validateProjectFailureStructure` defensively reparses, copies, freezes, and identity-registers only closed known-tool failures. +- Materialized each advertised tool as a standalone JSON Schema 2020-12 object with an exact eight-document local `$defs` closure. Projection removes document identifiers and ArchFlow-only semantic keywords while retaining every portable branch; an explicit input/output corpus records each validation rule intentionally retained only by the Phase 2 runtime. +- Made the SDK-free handler boundary own exact input classification and safe outcome construction. Boundaries, protocol-error wrappers, project/protocol outcomes, and copied registries are frozen and authenticated by private identity sets; handler exceptions and malformed or substituted outputs reduce to correlation-only `INTERNAL_ERROR` failures. + +### Deviations from Plan + +- The integrated fresh-context review found that the first catalogue corpus covered only path byte length and rubric uniqueness and never exercised output schemas. The implementation added input/output-aware fixtures for MCP waiver/task and current-evidence relations, gate-context relations, project-error path byte limits, and sorted-unique error paths, plus an exact category-coverage assertion. Production catalogue behavior did not change. +- The optional cross-client implementation counter-review found three major contract/test gaps and one minor CI enforcement gap. All were accepted: failure diagnostics with a `tool` field are now correlated to the selected tool; waiver success reuses the shared safe-positive rule-version bound; the classified corpus now covers every removed validating keyword branch and call-correlated output; and the Phase 3 SDK-free control is an executable scanner with mutation tests rather than a partial grep. +- Exhaustive output-corpus work exposed an adjacent runtime omission: gate success reparsed decision envelopes but did not validate decision payload semantics against the authentic gate context. `successFor` now calls `validateGateDecision` before accepting a gate result, covering waiver eligibility, adjudication resolution order/coverage, and restore-adoption authority. +- Fixing the normative/runtime agreement required adding `src/contracts/schemas/v1/mcp-tools.schema.json` and the Phase 3 boundary-policy scripts to the implementation file set. This corrects the approved contract rather than expanding the Phase 3 runtime surface. +- No architectural scope, public interface, PRD requirement, or later phase changed. Phase 3 added no SDK adapter, transport, lifecycle, runnable server, tracked release payload, persistence, dispatch, durable gate lifecycle, or legal inventory beyond the two approved root notice entries. + +### Patterns Established + +- MCP SDK compatibility is proven at test boundaries through public package exports. Production contract and catalogue code does not import SDK types or runtime values; Phase 4 owns the isolated adapter seam. +- Trust-bearing wrappers use owner-private object identity in addition to frozen validated structure. Casts, structural fakes, serialized copies, and spread clones do not acquire authority. +- Portable advertised schemas are closed standalone projections of normative schemas. Every removed validating semantic keyword must have a named corpus case proving portable acceptance and runtime rejection; annotations are asserted absent but are not misrepresented as validation rules. +- Handler boundaries copy the registry, validate before invocation, invoke at most once, revalidate returned data, copy/freeze accepted results, and replace raw exceptions or malformed output with bounded correlation-only failures. +- A project failure is tool-neutral only when its validated diagnostic has no `tool` parameter. Any present binding must match the selected tool before structural authenticity can be granted. + +### Gotchas + +- Zod's safe-integer parser preserves JavaScript negative zero, but JSON serialization does not. Phase 3 preserves `-0` in process; Phase 4 remains responsible for the approved wire normalization to `0` and duplicate `-0`/`0` handling. +- The public SDK `specTypeSchemas` surface is neutral rather than a revision-specific wire codec. Phase 3 uses it only for neutral `RequestId` and `ListToolsResult` agreement; live negotiated 2025 wire proof remains Phase 4. +- Removing `x-archflow-*` keywords makes the advertised schema portable but deliberately moves several cross-field rules out of the portable validator. The classified corpus must evolve whenever the exact eight normative schemas add or remove such validating semantics. +- Schema projection tests must exercise both failure and success outputs. Successful outputs require a companion authentic parsed call so call-dependent state, gate, and waiver correlations are actually evaluated. +- The ambient shell uses Node `24.11.1`, below the supported floor. Exact Node packages placed first on `PATH` were required to run clean-install verification under `24.15.0` and `24.18.0` with npm `11.11.0`. + +### Key Interfaces + +- `src/contracts/contexts.ts`: `parseTransportRequestId(value: unknown): string | number`, `parseClientImplementation(value: unknown): Readonly<{ name: string; version: string }>`, `createInvocationContext(...)`, and `assertAuthenticInvocationContext(value: unknown): asserts value is InvocationContext`; `connectionContextFactory` remains a direct-only export from this module. +- `src/contracts/mcp-tools.ts`: `validateProjectFailureStructure(name: K, value: unknown): StructurallyValidProjectResult` authenticates only a closed failure for the selected known tool; `validateProjectResultStructure` applies the same diagnostic-tool correlation and validates gate decisions against the authentic gate context. +- `src/mcp/tools.ts`: `AdvertisedToolDescriptor` and `ADVERTISED_TOOL_CATALOGUE` are the exact supported direct imports for Phase 4; there is no `src/mcp/index.ts` or contract-barrel/package re-export. +- `src/mcp/server.ts`: `ToolHandler`, `ToolHandlerRegistry`, `AuthenticatedProtocolError`, `ToolProjectOutcome`, `ToolBoundaryOutcome`, `ToolBoundary`, `authenticateProtocolError`, `createToolBoundary`, `assertAuthenticToolBoundary`, and `assertAuthenticToolBoundaryOutcome` define the frozen authenticated SDK-free execution boundary. +- `package.json` and `package-lock.json`: exact direct server beta.5 and exact locked core beta.5 with Node `>=24.15.0`; `scripts/check-dependency-policy.mjs` and `scripts/check-notices.mjs` enforce their identities, licenses, and notice presence. +- `scripts/check-phase-3-mcp-boundary.mjs` and `scripts/test-phase-3-mcp-boundary-policy.mjs`: scan all production TypeScript for any MCP SDK reference, reject premature Phase 4/5 paths, and mutation-test static, type, side-effect, dynamic, and re-export forms. diff --git a/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission.md b/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission.md index 0316a348..8f810aeb 100644 --- a/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission.md +++ b/.archflow/tasks/mcp-integration/phases/phase-3-mcp-contract-boundary-and-dependency-admission.md @@ -1,9 +1,10 @@ # Phase 3: MCP Contract Boundary and Dependency Admission -**Status**: DESIGNED +**Status**: COMPLETE **Task**: mcp-integration **Goal**: Admit the exact MCP dependency surface and freeze a complete SDK-free five-tool catalogue and authenticated handler/error boundary for a later transport owner. **Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-33 +**Implemented**: 2026-07-27 ## Context @@ -138,9 +139,11 @@ A valid handler is called at most once and its `unknown` return is structurally | Modify | `scripts/check-dependency-policy.mjs`, `scripts/check-notices.mjs` | Enforce exact root server/core identities, their root package-declared licenses through existing allowed-license policy, and absence of later-phase dependencies. | | Modify | `THIRD_PARTY_NOTICES.md`, `docs/dependency-upgrades.md` | Record both root package entries, protocol/public-surface currency evidence, and Node compatibility versus production patch guidance. | | Modify | `src/contracts/mcp-tools.ts` | Add the failure-only structural validator without granting success authenticity. | +| Modify | `src/contracts/schemas/v1/mcp-tools.schema.json` | Keep advertised waiver-success rule versions aligned with the shared positive safe-integer contract. | | Modify | `src/contracts/contexts.ts`, `src/contracts/index.ts` | Add shared request-ID/client schemas, parsers, and invocation assertion while keeping the connection factory direct-only and the barrel contract-only. | | Create | `src/mcp/tools.ts` | Own and export the catalogue descriptor type and deterministic deeply frozen five-tool catalogue as the supported direct Phase 4 import. | | Create | `src/mcp/server.ts` | Export the frozen authenticated SDK-free handler/error/outcome boundary and exact input classification. | +| Create | `scripts/check-phase-3-mcp-boundary.mjs`, `scripts/test-phase-3-mcp-boundary-policy.mjs` | Enforce and mutation-test the temporary Phase 3 no-SDK/no-runtime/no-release boundary. | | Modify | `test/unit/mcp-tools.test.ts`, `test/contracts/mcp-contract-agreement.test.ts`, `test/unit/contexts.test.ts` | Prove failure-only construction, shared parser/mint agreement, exact safe request IDs, full Implementation projection, authenticity, and freezing. | | Create | `test/unit/mcp-server.test.ts`, `test/contracts/mcp-advertised-schema.test.ts`, `test/fixtures/mcp/{catalogue,boundary}/**` | Exercise boundary behavior and catalogue portability/public-root agreement without a live transport. | | Modify | `.github/workflows/ci.yml` | Run focused checks on the Node matrix and enforce the Phase 3 no-runtime boundary. | diff --git a/.archflow/tasks/mcp-integration/reviews/phase-3-impl-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-3-impl-counter-review.md new file mode 100644 index 00000000..91f6d0d3 --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-3-impl-counter-review.md @@ -0,0 +1,33 @@ +# Phase 3 Implementation Counter-Review + +1. **Severity: major — Tool-bound project failures can be substituted across tools.** `validateProjectFailureStructure(name, value)` uses `name` only to brand the result and accepts a closed `CONTRACT_INVALID` or `RESULT_INVALID` whose diagnostic `tool` names a different tool. `createToolBoundary` then accepts the same mismatch from a handler because its failure path delegates to `validateProjectResultStructure`, which likewise does not compare an error's optional/required `tool` parameter with `call.name`. For example, an `archflow_state` handler can return a valid `CONTRACT_INVALID` naming `archflow_gate`, and the authenticated boundary emits that contradictory result instead of the required safe `INTERNAL_ERROR`. This exceeds the design's allowance for *tool-neutral* failures and leaves a detectable cross-tool substitution unhandled. + + **Suggested resolution:** Centralize failure-to-tool correlation in the structural-result owner. Permit failures without a tool binding on any known path, require every present tool binding to equal the selected/called tool, and make the boundary reduce a mismatch to correlation-only `INTERNAL_ERROR`. Add direct validator and boundary tests for both `CONTRACT_INVALID` and `RESULT_INVALID`, including matching, neutral, and cross-tool cases. + +2. **Severity: major — The advertised waiver output schema accepts an unsafe integer that runtime revalidation rejects.** The projected `archflow_waiver` output inherits `mcp-tools.schema.json`'s `success.rule_version`, which specifies only `type: "integer"` and `minimum: 1`; unlike the shared rule definition and the Zod success schema, it has no `maximum: 9007199254740991`. Fresh strict Ajv therefore accepts `rule_version: 9007199254740992`, while `validateProjectResultStructure` rejects the same otherwise-valid result through `.max(Number.MAX_SAFE_INTEGER)`. The catalogue consequently advertises a structurally valid output that the authenticated boundary can never admit, violating schema/runtime agreement and the requirement not to weaken projected branches. + + **Suggested resolution:** Correct the normative waiver-success schema to reuse the shared bounded rule-version definition (updating the phase file scope first if needed), then add an agreement fixture at both safe bounds and both adjacent unsafe values. Exercise the same cases through the standalone advertised output schema and authentic runtime result validation. + +3. **Severity: major — The classified corpus cannot prove the required success-output semantics and covers only a subset of removed runtime checks.** In `mcp-advertised-schema.test.ts`, every output corpus entry is sent to `validateProjectFailureStructure`; the harness therefore cannot test even one success output or any success-to-request correlation. Its self-declared semantic category list also treats one `attempts-exhausted` case as coverage for all gate-context semantics, omitting the distinct review/adjudication rule-set, waiver eligibility/scope, material-drift ordering, and commit-authorization ordering checks. It likewise omits gate-decision relations and the state, gate, and waiver success correlations enforced by `successFor`. This is why the unsafe waiver output in finding 2 passed despite the success criterion requiring the corpus to distinguish all portable structure from runtime-only semantic constraints. + + **Suggested resolution:** Give output-success corpus cases a companion authentic parsed call and validate them with `validateProjectResultStructure`; retain the failure-only validator only for failure cases. Add positive coverage for every tool's success plus differential portable-accept/runtime-reject cases for each removed validating semantic family and each call-correlated result rule. Make the expected semantic inventory derive from, or be exhaustively reconciled with, the exact eight source documents/custom-keyword behaviors instead of letting a hand-written subset certify itself. + +4. **Severity: minor — The CI SDK-free check is bypassable by valid TypeScript import forms.** The workflow grep matches `from "@modelcontextprotocol/..."` and dynamic `import(...)`, but not a side-effect import such as `import "@modelcontextprotocol/server"` or a re-export such as `export * from "@modelcontextprotocol/server"`. The current production source is clean, but the added CI control does not fully enforce the Phase 3 no-SDK-import boundary it claims to enforce. + + **Suggested resolution:** For Phase 3, reject any `@modelcontextprotocol/` occurrence in production TypeScript (or use an AST-based import/re-export check), with a small mutation test covering static imports, side-effect imports, dynamic imports, and re-exports. Phase 4 can then replace the blanket rule with the exact adapter-only allowlist required by its design. + +## Triage + +1. **Accepted — fixed.** Project-failure parsing is now centralized in `src/contracts/mcp-tools.ts`. Both `validateProjectFailureStructure` and the failure branch of `validateProjectResultStructure` accept tool-neutral errors, require any present diagnostic `tool` to match the selected/authentic call tool, and reject cross-tool `CONTRACT_INVALID` and `RESULT_INVALID` substitutions. Boundary regression tests prove matching and neutral failures pass, mismatches invoke the handler only once, and the mismatch becomes a correlation-only `INTERNAL_ERROR` without leaking the contradictory result. + +2. **Accepted — fixed.** The normative waiver-success `rule_version` now references the shared bounded rule-version schema in `src/contracts/schemas/v1/mcp-tools.schema.json`. Agreement tests exercise `1`, `Number.MAX_SAFE_INTEGER`, `0`, and `Number.MAX_SAFE_INTEGER + 1` through the normative schema, the standalone advertised output, and authentic runtime result validation. + +3. **Accepted — fixed.** The catalogue corpus is now input/output-aware: failure outputs use `validateProjectFailureStructure`, successful outputs carry an authentic companion call and use `validateProjectResultStructure`, and all five tools have positive success controls. The corpus contains 46 cases, including 38 runtime-semantic differentials covering every validating `x-archflow-*` family in the exact eight-schema source set plus failure/state/gate/waiver call correlations. Its keyword inventory is collected from those eight documents and explicitly distinguishes annotation-only `x-archflow-effect`. During this fix, output differentials exposed that gate success parsed decision envelopes without applying gate-context semantics; `successFor` now calls `validateGateDecision`, with regressions for waiver eligibility, adjudication resolution order/coverage, and restore-adoption authority. + +4. **Accepted — fixed.** The partial CI grep was replaced by `scripts/check-phase-3-mcp-boundary.mjs`, which rejects any `@modelcontextprotocol/` occurrence in production TypeScript and all premature Phase 4/5 paths. `scripts/test-phase-3-mcp-boundary-policy.mjs` mutation-tests aliased static, type-only, side-effect, dynamic, and re-export forms plus `src/main.ts`, the SDK adapter/barrel, and `dist`. Both checks are part of the local aggregate and both-node CI matrix. + +### Verification after triage + +- Focused Node `24.15.0` verification: typecheck, 4 affected test files / 30 tests, production boundary scan, and boundary mutation policy all passed. +- Clean `npm ci && npm run check` passed on Node `24.15.0` and `24.18.0` with npm `11.11.0`: 28 test files / 209 tests, 8 contract files / 42 tests, temporary bundle smoke, dependency policy, notices, notice mutation policy, Phase 3 production boundary scan, and boundary mutation policy. +- `git diff --check` passed after the fixes. No commit was created. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 455f7c5c..84709ebb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,5 +29,5 @@ jobs: - run: npm run check:dependencies - run: npm run check:notices - run: npm run test:notices-policy - - name: Assert no tracked-release bundle was produced - run: test ! -e dist + - run: npm run check:phase3-mcp-boundary + - run: npm run test:phase3-mcp-boundary-policy diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 714ed438..f1288a65 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -33,6 +33,8 @@ This inventory is generated from and checked against `package-lock.json`. Option | `@esbuild/win32-ia32@0.28.1` | `MIT` | | `@esbuild/win32-x64@0.28.1` | `MIT` | | `@jridgewell/sourcemap-codec@1.5.5` | `MIT` | +| `@modelcontextprotocol/core@2.0.0-beta.5` | `MIT` | +| `@modelcontextprotocol/server@2.0.0-beta.5` | `MIT` | | `@rollup/rollup-android-arm-eabi@4.62.3` | `MIT` | | `@rollup/rollup-android-arm64@4.62.3` | `MIT` | | `@rollup/rollup-darwin-arm64@4.62.3` | `MIT` | diff --git a/docs/dependency-upgrades.md b/docs/dependency-upgrades.md index acd51512..f9d4aaa6 100644 --- a/docs/dependency-upgrades.md +++ b/docs/dependency-upgrades.md @@ -8,6 +8,7 @@ Registry metadata was reviewed for every Phase 1 direct pin. The selected versio | Package | Pin | Review result | | --- | --- | --- | +| `@modelcontextprotocol/server` | `2.0.0-beta.5` | Current v2 beta/latest tag; root package declares MIT. Its exact dependency `@modelcontextprotocol/core@2.0.0-beta.5` also declares MIT. | | `zod` | `4.4.3` | Current; MIT | | `ajv` | `8.20.0` | Current; MIT | | `ajv-formats` | `3.0.1` | Current; MIT | @@ -18,6 +19,14 @@ Registry metadata was reviewed for every Phase 1 direct pin. The selected versio | `vitest` | `4.1.10` | Current; MIT | | `vite` | `7.3.6` | Current supported Vite 7 line; MIT. Vite 8 is intentionally excluded because its current graph introduces MPL-2.0 Lightning CSS. | +### MCP beta compatibility evidence + +The exact `@modelcontextprotocol/server@2.0.0-beta.5` and locked `@modelcontextprotocol/core@2.0.0-beta.5` roots were rechecked on 2026-07-27 before admission. The public server root exports `Server` and `specTypeSchemas`; `@modelcontextprotocol/server/stdio` exports `StdioServerTransport`. The public declarations retain method-string request handlers with `ctx.mcpReq.signal`, a configurable `supportedProtocolVersions` list that accepts the singleton `["2025-11-25"]`, `Server.projectCallToolResult`, and `close`. The neutral public `specTypeSchemas` includes `ListToolsResult` and `RequestId`, and the package names `2025-11-25` as its latest supported 2025 protocol revision. + +The package remains explicitly beta and warns that breaking changes are possible before v2 stabilizes. [Upstream's current maintenance guidance](https://github.com/modelcontextprotocol/typescript-sdk#readme) still identifies v1.x as the production-supported release until v2 stabilizes and promises v1 bug and security fixes for at least six months after v2 ships. This project deliberately accepts the exact reviewed beta instead of installing the monolithic `@modelcontextprotocol/sdk` v1 as a fallback. The low-level `Server` class is deprecated in favor of `McpServer` for ordinary high-level use but remains documented for advanced use; Phase 4 may isolate that deliberate exception only after its compatibility gate passes. No optional MCP framework or Node adapter package is admitted. + +Node `24.15.0` remains the functional package floor and lower CI matrix entry. Production and release verification should use the current Node 24 LTS security patch (`24.18.0` at this review); the separately pinned `@types/node` patch need only remain compatible with the Node 24 major. + ## Upgrade procedure 1. Review official registry/repository release and license metadata for each proposed direct update and its resolved graph. diff --git a/package-lock.json b/package-lock.json index 1609372a..0deb4d83 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "archflow-mcp-server", "version": "0.0.0", "dependencies": { + "@modelcontextprotocol/server": "2.0.0-beta.5", "ajv": "8.20.0", "ajv-formats": "3.0.1", "yaml": "2.9.0", @@ -19,6 +20,9 @@ "typescript": "7.0.2", "vite": "7.3.6", "vitest": "4.1.10" + }, + "engines": { + "node": ">=24.15.0" } }, "node_modules/@esbuild/aix-ppc64": { @@ -470,6 +474,31 @@ "dev": true, "license": "MIT" }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.0.0-beta.5", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0-beta.5.tgz", + "integrity": "sha512-HKbY9XTbsDy1Y6r2I55TGE3JEapM0vg96e1MUmBIF9LGjos5gjhcIrTz1yvBPLg2aFKHjwhUAQfRdrCEnPxNew==", + "license": "MIT", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.0.0-beta.5", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0-beta.5.tgz", + "integrity": "sha512-i1E5l75rQKsgY/AKAIspgMBH1vEL7dqiK7tHr0L+raYcb0SWOziqNGJXGIG6NY4AlXDWIKGJQGB7Nqfs3oUi5g==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/core": "2.0.0-beta.5", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.62.3", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.3.tgz", diff --git a/package.json b/package.json index 1e028b05..43ba1f30 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,9 @@ "version": "0.0.0", "private": true, "type": "module", + "engines": { + "node": ">=24.15.0" + }, "scripts": { "typecheck": "tsc --noEmit", "test": "vitest run", @@ -12,9 +15,12 @@ "check:dependencies": "node scripts/check-dependency-policy.mjs", "check:notices": "node scripts/check-notices.mjs", "test:notices-policy": "node scripts/test-notices-policy.mjs", - "check": "npm run typecheck && npm test && npm run test:contracts && npm run build:temp && npm run check:dependencies && npm run check:notices && npm run test:notices-policy" + "check:phase3-mcp-boundary": "node scripts/check-phase-3-mcp-boundary.mjs", + "test:phase3-mcp-boundary-policy": "node scripts/test-phase-3-mcp-boundary-policy.mjs", + "check": "npm run typecheck && npm test && npm run test:contracts && npm run build:temp && npm run check:dependencies && npm run check:notices && npm run test:notices-policy && npm run check:phase3-mcp-boundary && npm run test:phase3-mcp-boundary-policy" }, "dependencies": { + "@modelcontextprotocol/server": "2.0.0-beta.5", "ajv": "8.20.0", "ajv-formats": "3.0.1", "yaml": "2.9.0", diff --git a/scripts/check-dependency-policy.mjs b/scripts/check-dependency-policy.mjs index 0d764587..107491bb 100644 --- a/scripts/check-dependency-policy.mjs +++ b/scripts/check-dependency-policy.mjs @@ -1,6 +1,7 @@ import { readFile } from "node:fs/promises"; const expectedRuntime = Object.freeze({ + "@modelcontextprotocol/server": "2.0.0-beta.5", ajv: "8.20.0", "ajv-formats": "3.0.1", yaml: "2.9.0", @@ -23,7 +24,10 @@ const approvedLicenses = new Set([ ]); const prohibitedLaterPhasePackages = new Set([ "@anthropic-ai/sandbox-runtime", - "@modelcontextprotocol/server", + "@modelcontextprotocol/client", + "@modelcontextprotocol/express", + "@modelcontextprotocol/hono", + "@modelcontextprotocol/node", "execa", "proper-lockfile", "write-file-atomic" @@ -49,6 +53,9 @@ function compareDirect(actual, expected, label) { if (packageJson.private !== true || packageJson.type !== "module") { failures.push("package.json must describe a private ESM package"); } +if (packageJson.engines?.node !== ">=24.15.0") { + failures.push("package.json must keep Node 24.15.0 as the functional runtime floor"); +} compareDirect(packageJson.dependencies, expectedRuntime, "runtime"); compareDirect(packageJson.devDependencies, expectedDevelopment, "development"); for (const field of ["optionalDependencies", "peerDependencies", "bundledDependencies", "bundleDependencies"]) { @@ -61,6 +68,9 @@ if (lock.lockfileVersion !== 3 || lock.requires !== true) { failures.push("package-lock.json must be an npm lockfileVersion 3 exact lock"); } const root = lock.packages?.[""]; +if (root?.engines?.node !== ">=24.15.0") { + failures.push("lockfile root must keep Node 24.15.0 as the functional runtime floor"); +} compareDirect(root?.dependencies, expectedRuntime, "lockfile root runtime"); compareDirect(root?.devDependencies, expectedDevelopment, "lockfile root development"); for (const field of ["optionalDependencies", "peerDependencies", "bundledDependencies", "bundleDependencies"]) { @@ -76,6 +86,37 @@ function packageNameFromPath(path, metadata) { return index === -1 ? "" : path.slice(index + marker.length); } +const expectedMcpRoots = Object.freeze({ + "node_modules/@modelcontextprotocol/core": Object.freeze({ + name: "@modelcontextprotocol/core", + version: "2.0.0-beta.5", + license: "MIT" + }), + "node_modules/@modelcontextprotocol/server": Object.freeze({ + name: "@modelcontextprotocol/server", + version: "2.0.0-beta.5", + license: "MIT" + }) +}); +const expectedMcpRootsByName = new Map(Object.values(expectedMcpRoots).map((root) => [root.name, root])); +for (const [path, expected] of Object.entries(expectedMcpRoots)) { + const metadata = lock.packages?.[path]; + const actual = metadata === undefined + ? undefined + : { + name: packageNameFromPath(path, metadata), + version: metadata.version, + license: metadata.license + }; + if (JSON.stringify(actual) !== JSON.stringify(expected)) { + failures.push(`${path} must resolve exactly to ${expected.name}@${expected.version} with ${expected.license}`); + } +} +const lockedServer = lock.packages?.["node_modules/@modelcontextprotocol/server"]; +if (lockedServer?.dependencies?.["@modelcontextprotocol/core"] !== "2.0.0-beta.5") { + failures.push("the exact MCP server root must lock exact @modelcontextprotocol/core@2.0.0-beta.5"); +} + for (const [path, metadata] of Object.entries(lock.packages ?? {})) { if (path === "") continue; const name = packageNameFromPath(path, metadata); @@ -89,6 +130,14 @@ for (const [path, metadata] of Object.entries(lock.packages ?? {})) { if (prohibitedLaterPhasePackages.has(name)) { failures.push(`later-phase package resolved early: ${name}@${metadata.version}`); } + if (name.startsWith("@modelcontextprotocol/")) { + const expected = expectedMcpRootsByName.get(name); + if (expected === undefined) { + failures.push(`unreviewed MCP package resolved: ${name}@${metadata.version}`); + } else if (metadata.version !== expected.version || metadata.license !== expected.license) { + failures.push(`MCP package identity drift: ${name}@${metadata.version} with ${String(metadata.license)}`); + } + } if (!approvedLicenses.has(metadata.license)) { failures.push(`unreviewed or non-permissive license ${String(metadata.license)} at ${name}@${metadata.version}`); } diff --git a/scripts/check-notices.mjs b/scripts/check-notices.mjs index 96015508..783f6892 100644 --- a/scripts/check-notices.mjs +++ b/scripts/check-notices.mjs @@ -58,6 +58,14 @@ for (const [path, metadata] of Object.entries(lock.packages ?? {})) { const recordedSpdx = new Set( [...inventory.matchAll(/^\| `([^`]+)` \| `([^`]+)` \|$/gm)].map((match) => `${match[1]} | ${match[2]}`) ); +const requiredMcpRoots = new Set([ + "@modelcontextprotocol/core@2.0.0-beta.5 | MIT", + "@modelcontextprotocol/server@2.0.0-beta.5 | MIT" +]); +for (const entry of requiredMcpRoots) { + if (!expectedSpdx.has(entry)) failures.push(`missing exact MCP root from lock: ${entry}`); + if (!recordedSpdx.has(entry)) failures.push(`missing exact MCP root notice entry: ${entry}`); +} for (const entry of [...expectedSpdx].filter((value) => !recordedSpdx.has(value)).sort()) { failures.push(`missing SPDX inventory entry: ${entry}`); } diff --git a/scripts/check-phase-3-mcp-boundary.mjs b/scripts/check-phase-3-mcp-boundary.mjs new file mode 100644 index 00000000..6dd1e02e --- /dev/null +++ b/scripts/check-phase-3-mcp-boundary.mjs @@ -0,0 +1,79 @@ +import { readFile, readdir, stat } from "node:fs/promises"; +import { relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const defaultRepositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); +const repositoryRoot = parseRepositoryRoot(process.argv.slice(2)); +const sourceRoot = resolve(repositoryRoot, "src"); +const prohibitedFragment = "@modelcontextprotocol/"; +const prohibitedPaths = Object.freeze([ + "src/main.ts", + "src/mcp/sdk-adapter.ts", + "src/mcp/index.ts", + "dist" +]); +const failures = []; + +function parseRepositoryRoot(args) { + if (args.length === 0) return defaultRepositoryRoot; + if (args.length !== 2 || args[0] !== "--root") { + throw new Error("usage: node scripts/check-phase-3-mcp-boundary.mjs [--root ]"); + } + return resolve(args[1]); +} + +async function exists(path) { + try { + await stat(path); + return true; + } catch (error) { + if (error?.code === "ENOENT") return false; + throw error; + } +} + +async function collectTypeScriptFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const paths = []; + for (const entry of entries) { + const path = resolve(directory, entry.name); + if (entry.isDirectory()) { + paths.push(...await collectTypeScriptFiles(path)); + } else if (entry.isFile() && entry.name.endsWith(".ts")) { + paths.push(path); + } + } + return paths; +} + +let sourceFiles; +try { + sourceFiles = await collectTypeScriptFiles(sourceRoot); +} catch (error) { + if (error?.code === "ENOENT") { + failures.push("src must exist so the Phase 3 production boundary can be checked"); + sourceFiles = []; + } else { + throw error; + } +} + +for (const path of sourceFiles.sort()) { + const content = await readFile(path, "utf8"); + if (content.includes(prohibitedFragment)) { + failures.push(`${relative(repositoryRoot, path)} contains prohibited ${prohibitedFragment}`); + } +} + +for (const path of prohibitedPaths) { + if (await exists(resolve(repositoryRoot, path))) { + failures.push(`${path} must not exist before its owning phase`); + } +} + +if (failures.length > 0) { + console.error(failures.map((failure) => `- ${failure}`).join("\n")); + process.exitCode = 1; +} else { + console.log(`Phase 3 MCP boundary passed for ${sourceFiles.length} production TypeScript files.`); +} diff --git a/scripts/test-phase-3-mcp-boundary-policy.mjs b/scripts/test-phase-3-mcp-boundary-policy.mjs new file mode 100644 index 00000000..7380a9e7 --- /dev/null +++ b/scripts/test-phase-3-mcp-boundary-policy.mjs @@ -0,0 +1,75 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, unlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); +const checkerPath = `${repositoryRoot}/scripts/check-phase-3-mcp-boundary.mjs`; +const temporaryRoot = await mkdtemp(resolve(tmpdir(), "archflow-phase-3-mcp-boundary-")); +const probePath = `${temporaryRoot}/src/nested/probe.ts`; + +function runCheck() { + return spawnSync(process.execPath, [checkerPath, "--root", temporaryRoot], { encoding: "utf8" }); +} + +async function assertSourceMutationRejected(label, source) { + await writeFile(probePath, source); + const result = runCheck(); + assert.notEqual(result.status, 0, `${label} must fail the Phase 3 MCP boundary`); + assert.match(result.stderr, /src\/nested\/probe\.ts contains prohibited @modelcontextprotocol\//u); + await unlink(probePath); +} + +async function assertPrematurePathRejected(path, kind = "file") { + const absolutePath = `${temporaryRoot}/${path}`; + if (kind === "directory") { + await mkdir(absolutePath, { recursive: true }); + } else { + await mkdir(resolve(absolutePath, ".."), { recursive: true }); + await writeFile(absolutePath, "export {};\n"); + } + const result = runCheck(); + assert.notEqual(result.status, 0, `${path} must fail the Phase 3 MCP boundary`); + assert.match(result.stderr, new RegExp(`${path.replaceAll(".", "\\.")} must not exist before its owning phase`, "u")); + await rm(absolutePath, { recursive: true, force: true }); +} + +try { + await mkdir(`${temporaryRoot}/src/nested`, { recursive: true }); + await writeFile(`${temporaryRoot}/src/nested/clean.ts`, "export const clean = true;\n"); + assert.equal(runCheck().status, 0, "clean production source must pass the Phase 3 MCP boundary"); + + await assertSourceMutationRejected( + "aliased static import", + 'import { Server as ProtocolServer } from "@modelcontextprotocol/server";\n' + ); + await assertSourceMutationRejected( + "type import", + 'import type { RequestId } from "@modelcontextprotocol/core";\n' + ); + await assertSourceMutationRejected( + "side-effect import", + 'import "@modelcontextprotocol/server";\n' + ); + await assertSourceMutationRejected( + "dynamic import", + 'const sdk = await import("@modelcontextprotocol/server");\n' + ); + await assertSourceMutationRejected( + "re-export", + 'export * from "@modelcontextprotocol/server";\n' + ); + + await assertPrematurePathRejected("src/main.ts"); + await assertPrematurePathRejected("src/mcp/sdk-adapter.ts"); + await assertPrematurePathRejected("src/mcp/index.ts"); + await assertPrematurePathRejected("dist", "directory"); + + console.log( + "Phase 3 MCP boundary mutation checks rejected all SDK reference forms and premature runtime/release paths." + ); +} finally { + await rm(temporaryRoot, { recursive: true, force: true }); +} diff --git a/src/contracts/contexts.ts b/src/contracts/contexts.ts index 8c37688e..d20c423d 100644 --- a/src/contracts/contexts.ts +++ b/src/contracts/contexts.ts @@ -14,11 +14,16 @@ export class ProtocolContextError extends Error { public constructor(public read const id = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); const text = z.string().min(1).max(4096).regex(/\S/u); const version = z.string().regex(/^[A-Za-z0-9.-]{1,64}$/u); +const requestIdSchema = z.union([z.string(), z.number().int().safe()]); +const clientImplementationSchema = z.object({ name: z.string(), version: z.string() }).strict(); const startupSchema = z.object({ connection_id: id, startup_repository_candidate: z.object({ working_directory: text }).strict() }).strict(); -const initializationSchema = z.object({ client: z.object({ name: text, version }).strict(), host: z.enum(["claude", "codex", "unknown"]), protocol_version: version }).strict(); -const invocationSchema = z.object({ invocation_id: id, transport_metadata: z.object({ request_id: z.union([text, z.number().int().safe()]), operation: z.literal("tools/call") }).strict() }).strict(); +const initializationSchema = z.object({ client: clientImplementationSchema, host: z.enum(["claude", "codex", "unknown"]), protocol_version: version }).strict(); +const invocationSchema = z.object({ invocation_id: id, transport_metadata: z.object({ request_id: requestIdSchema, operation: z.literal("tools/call") }).strict() }).strict(); function deepFreeze(value: T): T { if (value !== null && typeof value === "object") { for (const nested of Object.values(value)) deepFreeze(nested); Object.freeze(value); } return value; } function copy(value: T): T { return structuredClone(value as PlainJsonValue) as T; } export const connectionContextFactory: ConnectionContextFactory = Object.freeze({ captureStartup(seed: unknown) { assertPlainJson(seed, "connection startup"); const startup = deepFreeze(copy(startupSchema.parse(seed))); let initialized = false; return Object.freeze({ initialize(candidates: unknown): ConnectionContext { if (initialized) throw new ProtocolContextError(createProtocolError("INITIALIZATION_REPEATED", { connection_id: startup.connection_id })); assertPlainJson(candidates, "connection initialization"); const initialization = deepFreeze(copy(initializationSchema.parse(candidates))); initialized = true; const connection = deepFreeze({ connection_id: startup.connection_id, startup_repository_candidate: startup.startup_repository_candidate, initialization_candidates: initialization }) as ConnectionContext; authenticConnections.add(connection); return connection; } }); } }); export function createInvocationContext(connection: ConnectionContext, seed: unknown, signal: AbortSignal): InvocationContext { if (!authenticConnections.has(connection)) throw new TypeError("a branded connection context is required"); if (!(signal instanceof AbortSignal)) throw new TypeError("an AbortSignal is required"); assertPlainJson(seed, "invocation context"); const invocation = deepFreeze(copy(invocationSchema.parse(seed))); const context = Object.freeze({ invocation_id: invocation.invocation_id, connection, signal, transport_metadata: invocation.transport_metadata }) as InvocationContext; authenticInvocations.add(context); return context; } +export function parseTransportRequestId(value: unknown): string | number { assertPlainJson(value, "transport request ID"); return requestIdSchema.parse(value); } +export function parseClientImplementation(value: unknown): Readonly<{ readonly name: string; readonly version: string }> { assertPlainJson(value, "client implementation"); return deepFreeze(copy(clientImplementationSchema.parse(value))); } +export function assertAuthenticInvocationContext(value: unknown): asserts value is InvocationContext { if (value === null || typeof value !== "object" || !authenticInvocations.has(value)) throw new TypeError("an authentic invocation context is required"); } diff --git a/src/contracts/index.ts b/src/contracts/index.ts index 9829990f..239a10d1 100644 --- a/src/contracts/index.ts +++ b/src/contracts/index.ts @@ -25,6 +25,7 @@ export { bindParsedToolCallRequest, correlateProjectResult, parseToolCall, + validateProjectFailureStructure, validateProjectResultStructure, } from "./mcp-tools.js"; export type { @@ -54,4 +55,9 @@ export type { WaiverSuccess, } from "./mcp-tools.js"; export type { ConnectionContext, InvocationContext } from "./contexts.js"; -export { createInvocationContext } from "./contexts.js"; +export { + assertAuthenticInvocationContext, + createInvocationContext, + parseClientImplementation, + parseTransportRequestId, +} from "./contexts.js"; diff --git a/src/contracts/mcp-tools.ts b/src/contracts/mcp-tools.ts index 316ad286..933e620e 100644 --- a/src/contracts/mcp-tools.ts +++ b/src/contracts/mcp-tools.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import { CONSTITUTION_RESULTS, DRIFT_RESULTS, type ConstitutionResult, type DriftResult } from "./adjudication.js"; import { parseProjectError, type ProjectResult } from "./errors.js"; import type { Sha256Digest } from "./evidence.js"; -import { GATE_KINDS, humanDecisionProvenanceV1Schema, parseGateContext, parseGateDecisionEnvelope, type GateContext, type GateDecisionEnvelope, type GateKind, type HumanDecisionProvenance, type RuleVersionRef, type WaiverOriginRef, type WaiverScope } from "./gates.js"; +import { GATE_KINDS, humanDecisionProvenanceV1Schema, parseGateContext, parseGateDecisionEnvelope, validateGateDecision, type GateContext, type GateDecisionEnvelope, type GateKind, type HumanDecisionProvenance, type RuleVersionRef, type WaiverOriginRef, type WaiverScope } from "./gates.js"; import { assertPlainJson } from "./plain-json.js"; import { decodePhaseInstance, type PhaseInstanceId } from "./phase-instance.js"; import { taskPathClaimV1Schema, type TaskPathClaim } from "./path-claims.js"; @@ -82,12 +82,47 @@ const successSchemas = { function successFor(call: Extract, value: unknown): ToolSuccess { const parsed = successSchemas[call.name].parse(value) as ToolSuccess; if (call.name === "archflow_state" && (parsed as StateSuccess).status !== (call.input as ParsedToolInput<"archflow_state">).status) throw new TypeError("state status mismatch"); - if (call.name === "archflow_gate") { const input = call.input as ParsedToolInput<"archflow_gate">; const result = parsed as GateSuccess; const decision = parseGateDecisionEnvelope(result.decision); if (result.kind !== input.kind || decision.kind !== input.kind || decision.task_id !== input.task_id || decision.phase_instance !== input.phase_instance || decision.subject_digest !== input.subject_digest || result.notes !== decision.payload.reason) throw new TypeError("gate result mismatch"); } + if (call.name === "archflow_gate") { + const input = call.input as ParsedToolInput<"archflow_gate">; + const result = parsed as GateSuccess; + const decision = parseGateDecisionEnvelope(result.decision); + if (result.kind !== input.kind || decision.kind !== input.kind || decision.task_id !== input.task_id || decision.phase_instance !== input.phase_instance || decision.subject_digest !== input.subject_digest || result.notes !== decision.payload.reason) throw new TypeError("gate result mismatch"); + validateGateDecision(input.kind, input.context, decision.payload); + } if (call.name === "archflow_waiver") { const input = call.input as ParsedToolInput<"archflow_waiver">; const result = parsed as WaiverSuccess; if (result.origin_gate_id !== input.origin.origin_gate_id || result.task_id !== input.task_id || result.rule_id !== input.origin.rule.rule_id || result.rule_version !== input.origin.rule.rule_version || result.subject_digest !== input.origin.subject_digest || result.current_evidence_set_digest !== input.origin.current_evidence_set_digest || !isDeepStrictEqual(result.scope, input.origin.scope)) throw new TypeError("waiver result mismatch"); } return parsed; } export type StructurallyValidProjectResult = ProjectResult> & { readonly [structuralResultBrand]: K }; -export function validateProjectResultStructure(call: Extract, value: unknown): StructurallyValidProjectResult { if (!parsedCalls.has(call)) throw new TypeError("an authentic parsed tool call is required"); assertPlainJson(value, `${call.name} result`); const base = z.object({ schema_version: z.literal("1"), ok: z.boolean() }).passthrough().parse(value); const result: ProjectResult> = base.ok ? (() => { const e = z.object({ schema_version: z.literal("1"), ok: z.literal(true), value: z.unknown() }).strict().parse(value); return { ...e, value: successFor(call, e.value) }; })() : (() => { const e = z.object({ schema_version: z.literal("1"), ok: z.literal(false), error: z.unknown() }).strict().parse(value); return { ...e, error: parseProjectError(e.error) }; })(); const branded = Object.freeze({ ...result, [structuralResultBrand]: call.name }) as StructurallyValidProjectResult; structuralResults.add(branded); return branded; } +function projectFailureForTool( + name: K, + value: unknown, + label: string +): Extract>, { readonly ok: false }> { + assertPlainJson(value, label); + const failure = z.object({ schema_version: z.literal("1"), ok: z.literal(false), error: z.unknown() }).strict().parse(value); + const error = parseProjectError(failure.error); + const parameters = error.diagnostic.parameters; + if (Object.hasOwn(parameters, "tool") && Reflect.get(parameters, "tool") !== name) { + throw new TypeError("project failure tool mismatch"); + } + return { schema_version: "1", ok: false, error }; +} +export function validateProjectResultStructure(call: Extract, value: unknown): StructurallyValidProjectResult { if (!parsedCalls.has(call)) throw new TypeError("an authentic parsed tool call is required"); assertPlainJson(value, `${call.name} result`); const base = z.object({ schema_version: z.literal("1"), ok: z.boolean() }).passthrough().parse(value); const result: ProjectResult> = base.ok ? (() => { const e = z.object({ schema_version: z.literal("1"), ok: z.literal(true), value: z.unknown() }).strict().parse(value); return { ...e, value: successFor(call, e.value) }; })() : projectFailureForTool(call.name, value, `${call.name} result`); const branded = Object.freeze({ ...result, [structuralResultBrand]: call.name }) as StructurallyValidProjectResult; structuralResults.add(branded); return branded; } +export function validateProjectFailureStructure(name: K, value: unknown): StructurallyValidProjectResult { + if (!(TOOL_NAMES as readonly string[]).includes(name)) throw new TypeError("unknown tool"); + const failure = projectFailureForTool(name, value, `${name} failure result`); + const error = structuredClone(failure.error) as typeof failure.error; + const freeze = (candidate: unknown): void => { + if (candidate !== null && typeof candidate === "object") { + for (const nested of Object.values(candidate)) freeze(nested); + Object.freeze(candidate); + } + }; + freeze(error); + const branded = Object.freeze({ schema_version: "1", ok: false, error, [structuralResultBrand]: name }) as StructurallyValidProjectResult; + structuralResults.add(branded); + return branded; +} export type ResultExpectationDataByTool = { readonly [P in ToolName]: ResultIdentityPayload

}; export type ResultExpectation = ResultExpectationDataByTool[K] & { readonly [resultExpectationBrand]: K }; export function createInternalResultExpectation(value: ResultIdentityPayload): ResultExpectation { assertPlainJson(value, "result expectation"); const base = z.object({ schema_version: z.literal("1"), tool: z.enum(TOOL_NAMES), task_id: safeId, intent_id: safeId, input_fingerprint: digest, request_digest: digest, result_id: safeId, resulting_revision: safeInteger, success: z.unknown() }).strict().parse(value); const success = successSchemas[base.tool].parse(base.success) as ToolSuccess; if (base.resulting_revision !== success.revision) throw new TypeError("expectation resulting revision must equal success revision"); const expectation = Object.assign({}, base, { success }) as unknown as ResultExpectation; Object.defineProperty(expectation, resultExpectationBrand, { value: value.tool, enumerable: false, writable: false, configurable: false }); Object.freeze(expectation); resultExpectations.add(expectation); return expectation; } diff --git a/src/contracts/schemas/v1/mcp-tools.schema.json b/src/contracts/schemas/v1/mcp-tools.schema.json index ed7b243a..326c4e79 100644 --- a/src/contracts/schemas/v1/mcp-tools.schema.json +++ b/src/contracts/schemas/v1/mcp-tools.schema.json @@ -422,7 +422,7 @@ "waiver_gate_id": { "$ref": "#/$defs/id" }, "task_id": { "$ref": "#/$defs/id" }, "rule_id": { "$ref": "#/$defs/id" }, - "rule_version": { "type": "integer", "minimum": 1 }, + "rule_version": { "$ref": "#/$defs/rule/properties/rule_version" }, "subject_digest": { "$ref": "#/$defs/digest" }, "current_evidence_set_digest": { "$ref": "#/$defs/digest" }, "scope": { "$ref": "#/$defs/scope" }, diff --git a/src/mcp/server.ts b/src/mcp/server.ts new file mode 100644 index 00000000..809b6aee --- /dev/null +++ b/src/mcp/server.ts @@ -0,0 +1,248 @@ +import { createHash } from "node:crypto"; + +import { assertAuthenticInvocationContext, type InvocationContext } from "../contracts/contexts.js"; +import { createProjectError, createProtocolError, parseProtocolError, type ProtocolError } from "../contracts/errors.js"; +import { safeVersionV1Schema } from "../contracts/evidence.js"; +import { + parseToolCall, + validateProjectFailureStructure, + validateProjectResultStructure, + type ParsedToolCall, + type StructurallyValidProjectResult +} from "../contracts/mcp-tools.js"; +import { assertPlainJson, type PlainJsonValue } from "../contracts/plain-json.js"; +import { isToolName, type ToolName } from "../contracts/tool-names.js"; + +export type ToolHandler = ( + call: Extract, + context: InvocationContext +) => unknown | Promise; + +export type ToolHandlerRegistry = Readonly; +}>>; + +declare const authenticatedProtocolErrorBrand: unique symbol; +export type AuthenticatedProtocolError = Readonly<{ + readonly value: ProtocolError; + readonly [authenticatedProtocolErrorBrand]: true; +}>; + +export type ToolProjectOutcome = { + readonly [K in ToolName]: Readonly<{ + readonly kind: "project-result"; + readonly tool: K; + readonly result: StructurallyValidProjectResult; + }>; +}[ToolName]; + +export type ToolBoundaryOutcome = + | ToolProjectOutcome + | Readonly<{ + readonly kind: "protocol-error"; + readonly error: AuthenticatedProtocolError; + }>; + +export interface ToolBoundary { + readonly invoke: ( + name: string, + args: unknown, + context: InvocationContext + ) => Promise; +} + +const protocolErrors = new WeakSet(); +const boundaries = new WeakSet(); +const outcomes = new WeakSet(); +const protocolErrorBrand = Symbol("AuthenticatedProtocolError"); + +function deepFreeze(value: T): T { + if ((typeof value === "object" && value !== null) || typeof value === "function") { + for (const child of Object.values(value)) deepFreeze(child); + Object.freeze(value); + } + return value; +} + +function copyJson(value: T): T { + return structuredClone(value as PlainJsonValue) as T; +} + +export function authenticateProtocolError(value: unknown): AuthenticatedProtocolError { + const parsed = parseProtocolError(value); + const copied = deepFreeze(copyJson(parsed)); + const wrapper = { value: copied } as { value: ProtocolError; [protocolErrorBrand]?: true }; + Object.defineProperty(wrapper, protocolErrorBrand, { + value: true, + enumerable: false, + writable: false, + configurable: false + }); + deepFreeze(wrapper); + protocolErrors.add(wrapper); + return wrapper as unknown as AuthenticatedProtocolError; +} + +function protocolOutcome(error: ProtocolError): ToolBoundaryOutcome { + const wrapper = authenticateProtocolError(error); + const outcome = deepFreeze({ kind: "protocol-error" as const, error: wrapper }); + outcomes.add(outcome); + return outcome; +} + +function projectOutcome( + tool: K, + result: StructurallyValidProjectResult +): ToolBoundaryOutcome { + const outcome = deepFreeze({ kind: "project-result" as const, tool, result }); + outcomes.add(outcome); + return outcome as ToolProjectOutcome; +} + +function projectFailure( + tool: K, + code: "CONTRACT_INVALID" | "CONTRACT_VERSION_UNSUPPORTED" | "INTERNAL_ERROR", + parameters: Readonly> +): ToolBoundaryOutcome { + const error = code === "CONTRACT_INVALID" + ? createProjectError(code, parameters as Parameters>[1]) + : code === "CONTRACT_VERSION_UNSUPPORTED" + ? createProjectError(code, parameters as Parameters>[1]) + : createProjectError(code, parameters as Parameters>[1]); + const result = validateProjectFailureStructure(tool, { schema_version: "1", ok: false, error }); + return projectOutcome(tool, result); +} + +function invalidInput(tool: K, issueCode: string): ToolBoundaryOutcome { + return projectFailure(tool, "CONTRACT_INVALID", { tool, issue_code: issueCode }); +} + +function internalFailure(tool: K, context: InvocationContext): ToolBoundaryOutcome { + return projectFailure(tool, "INTERNAL_ERROR", { correlation_id: context.invocation_id }); +} + +function copyRegistry(handlers: ToolHandlerRegistry): ToolHandlerRegistry { + if (handlers === null || typeof handlers !== "object" || Array.isArray(handlers)) { + throw new TypeError("a handler registry object is required"); + } + const prototype = Object.getPrototypeOf(handlers); + if (prototype !== Object.prototype && prototype !== null) { + throw new TypeError("the handler registry must have a plain prototype"); + } + const copied: Partial>> = {}; + for (const key of Reflect.ownKeys(handlers)) { + if (typeof key !== "string" || !isToolName(key)) throw new TypeError("the handler registry contains an unknown tool"); + const descriptor = Object.getOwnPropertyDescriptor(handlers, key); + if (descriptor === undefined || !("value" in descriptor) || !descriptor.enumerable) { + throw new TypeError("handler registry entries must be enumerable data properties"); + } + if (typeof descriptor.value !== "function") throw new TypeError("tool handlers must be functions"); + const handler = descriptor.value as ToolHandler; + copied[key] = Object.freeze((call, context) => handler(call, context)); + } + return deepFreeze(copied) as ToolHandlerRegistry; +} + +function classifyVersionedArgs( + tool: K, + args: unknown +): { readonly call: Extract } | { readonly outcome: ToolBoundaryOutcome } { + try { + assertPlainJson(args, `${tool} input`); + } catch { + return { outcome: invalidInput(tool, "input-not-object") }; + } + if (args === null || typeof args !== "object" || Array.isArray(args)) { + return { outcome: invalidInput(tool, "input-not-object") }; + } + let hasSchemaVersion: boolean; + let descriptor: PropertyDescriptor | undefined; + try { + hasSchemaVersion = Object.hasOwn(args, "schema_version"); + descriptor = Object.getOwnPropertyDescriptor(args, "schema_version"); + } catch { + return { outcome: invalidInput(tool, "input-not-object") }; + } + if (!hasSchemaVersion) { + return { outcome: invalidInput(tool, "schema-version-missing") }; + } + const supplied = descriptor !== undefined && "value" in descriptor ? descriptor.value : undefined; + if (typeof supplied !== "string" || !safeVersionV1Schema.safeParse(supplied).success) { + return { outcome: invalidInput(tool, "schema-version-invalid") }; + } + if (supplied !== "1") { + return { + outcome: projectFailure(tool, "CONTRACT_VERSION_UNSUPPORTED", { + schema_version: supplied, + supported_version: "1" + }) + }; + } + try { + return { call: parseToolCall(tool, args) }; + } catch { + return { outcome: invalidInput(tool, "input-invalid") }; + } +} + +export function createToolBoundary(handlers: ToolHandlerRegistry): ToolBoundary { + const registry = copyRegistry(handlers); + const boundary: ToolBoundary = { + invoke: async (name, args, context): Promise => { + if (typeof name !== "string") throw new TypeError("a string tool name is required"); + assertAuthenticInvocationContext(context); + + if (!isToolName(name)) { + const toolNameDigest = createHash("sha256").update(name, "utf8").digest("hex"); + return protocolOutcome(createProtocolError("TOOL_NOT_FOUND", { tool_name_digest: toolNameDigest })); + } + + const handler = registry[name] as ToolHandler | undefined; + if (handler === undefined) { + return protocolOutcome(createProtocolError("TOOL_DISABLED", { + tool: name, + lifecycle_state: "inert-no-handler" + })); + } + + const classified = classifyVersionedArgs(name, args); + if ("outcome" in classified) return classified.outcome; + + let returned: unknown; + try { + returned = await handler(classified.call, context); + } catch { + return internalFailure(name, context); + } + + try { + validateProjectResultStructure(classified.call, returned); + const copied = copyJson(returned as PlainJsonValue); + return projectOutcome(name, validateProjectResultStructure(classified.call, copied)); + } catch { + return internalFailure(name, context); + } + } + }; + deepFreeze(boundary); + boundaries.add(boundary); + return boundary; +} + +export function assertAuthenticToolBoundary(value: unknown): asserts value is ToolBoundary { + if (value === null || typeof value !== "object" || !boundaries.has(value)) { + throw new TypeError("an authentic tool boundary is required"); + } +} + +export function assertAuthenticToolBoundaryOutcome(value: unknown): asserts value is ToolBoundaryOutcome { + if (value === null || typeof value !== "object" || !outcomes.has(value)) { + throw new TypeError("an authentic tool boundary outcome is required"); + } + if ("kind" in value && value.kind === "protocol-error") { + const error = (value as { readonly error?: unknown }).error; + if (error === null || typeof error !== "object" || !protocolErrors.has(error)) { + throw new TypeError("an authentic protocol error wrapper is required"); + } + } +} diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts new file mode 100644 index 00000000..b4114020 --- /dev/null +++ b/src/mcp/tools.ts @@ -0,0 +1,93 @@ +import evidenceSlotsSchema from "../contracts/schemas/v1/evidence-slots.schema.json" with { type: "json" }; +import gateContractSchema from "../contracts/schemas/v1/gate-contract.schema.json" with { type: "json" }; +import gateDecisionSchema from "../contracts/schemas/v1/gate-decision.schema.json" with { type: "json" }; +import mcpToolsSchema from "../contracts/schemas/v1/mcp-tools.schema.json" with { type: "json" }; +import pathClaimSchema from "../contracts/schemas/v1/path-claim.schema.json" with { type: "json" }; +import primitivesSchema from "../contracts/schemas/v1/primitives.schema.json" with { type: "json" }; +import projectErrorSchema from "../contracts/schemas/v1/project-error.schema.json" with { type: "json" }; +import rubricSchema from "../contracts/schemas/v1/rubric.schema.json" with { type: "json" }; +import { TOOL_NAMES, type ToolName } from "../contracts/tool-names.js"; + +export interface AdvertisedToolDescriptor { + readonly name: ToolName; + readonly inputSchema: Readonly>; + readonly outputSchema: Readonly>; +} + +type JsonObject = Record; + +const JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema"; +const MCP_SCHEMA_ID = "https://archflow.dev/schemas/v1/mcp-tools"; + +const schemaDocuments = Object.freeze([ + Object.freeze({ key: "mcp-tools", id: MCP_SCHEMA_ID, schema: mcpToolsSchema }), + Object.freeze({ key: "primitives", id: "urn:archflow:schema:v1:primitives", schema: primitivesSchema }), + Object.freeze({ key: "path-claim", id: "urn:archflow:schema:v1:path-claim", schema: pathClaimSchema }), + Object.freeze({ key: "evidence-slots", id: "urn:archflow:schema:v1:evidence-slots", schema: evidenceSlotsSchema }), + Object.freeze({ key: "rubric", id: "urn:archflow:schema:v1:rubric", schema: rubricSchema }), + Object.freeze({ key: "gate-contract", id: "urn:archflow:schema:v1:gate-contract", schema: gateContractSchema }), + Object.freeze({ key: "gate-decision", id: "urn:archflow:schema:v1:gate-decision", schema: gateDecisionSchema }), + Object.freeze({ key: "project-error", id: "urn:archflow:schema:v1:project-error", schema: projectErrorSchema }) +] as const); + +const documentKeysById = new Map(schemaDocuments.map(({ id, key }) => [id, key])); + +function isObject(value: unknown): value is JsonObject { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function localReference(sourceKey: string, reference: string): string { + const hash = reference.indexOf("#"); + const documentId = hash === -1 ? reference : reference.slice(0, hash); + const fragment = hash === -1 ? "" : reference.slice(hash + 1); + const targetKey = documentId === "" ? sourceKey : documentKeysById.get(documentId); + if (targetKey === undefined) throw new TypeError(`unknown normative schema reference: ${reference}`); + if (fragment !== "" && !fragment.startsWith("/")) throw new TypeError(`unsupported normative schema fragment: ${reference}`); + return `#/$defs/${targetKey}${fragment}`; +} + +function project(value: unknown, sourceKey: string): unknown { + if (Array.isArray(value)) return value.map((entry) => project(entry, sourceKey)); + if (!isObject(value)) return value; + + const projected: JsonObject = {}; + for (const [key, entry] of Object.entries(value)) { + if (key === "$id" || key === "$schema" || key === "$anchor" || key === "$dynamicAnchor" || key.startsWith("x-archflow-")) continue; + projected[key] = key === "$ref" && typeof entry === "string" ? localReference(sourceKey, entry) : project(entry, sourceKey); + } + return projected; +} + +function schemaFragment(name: ToolName, member: "input" | "result"): JsonObject { + const definitions = (mcpToolsSchema as JsonObject).$defs; + const tool = isObject(definitions) ? definitions[name] : undefined; + const fragment = isObject(tool) ? tool[member] : undefined; + if (!isObject(fragment)) throw new TypeError(`missing normative schema fragment for ${name}/${member}`); + return fragment; +} + +function standaloneSchema(name: ToolName, member: "input" | "result"): Readonly { + const definitions = Object.fromEntries( + schemaDocuments.map(({ key, schema }) => [key, project(schema, key)]) + ); + return deepFreeze({ + $schema: JSON_SCHEMA_2020_12, + ...project(schemaFragment(name, member), "mcp-tools") as JsonObject, + type: "object", + $defs: definitions + }); +} + +function deepFreeze(value: T): T { + if ((typeof value !== "object" && typeof value !== "function") || value === null || Object.isFrozen(value)) return value; + for (const child of Object.values(value as Record)) deepFreeze(child); + return Object.freeze(value); +} + +export const ADVERTISED_TOOL_CATALOGUE: readonly AdvertisedToolDescriptor[] = deepFreeze( + TOOL_NAMES.map((name) => ({ + name, + inputSchema: standaloneSchema(name, "input"), + outputSchema: standaloneSchema(name, "result") + })) +); diff --git a/test/contracts/mcp-advertised-schema.test.ts b/test/contracts/mcp-advertised-schema.test.ts new file mode 100644 index 00000000..e10db7c0 --- /dev/null +++ b/test/contracts/mcp-advertised-schema.test.ts @@ -0,0 +1,330 @@ +import { readFile } from "node:fs/promises"; +import { specTypeSchemas } from "@modelcontextprotocol/server"; +import { Ajv2020 } from "ajv/dist/2020.js"; +import * as formatsModule from "ajv-formats"; +import type { FormatsPlugin } from "ajv-formats"; +import { describe, expect, it } from "vitest"; + +import { parseToolCall, validateProjectFailureStructure, validateProjectResultStructure } from "../../src/contracts/mcp-tools.js"; +import { TOOL_NAMES, type ToolName } from "../../src/contracts/tool-names.js"; +import { ADVERTISED_TOOL_CATALOGUE } from "../../src/mcp/tools.js"; + +interface CorpusCase { + readonly label: string; + readonly tool: ToolName; + readonly member: "input" | "output"; + readonly classification: "portable-structure" | "runtime-semantic"; + readonly semantic_category?: string; + readonly materialization: string; + readonly call_fixture?: ToolName; + readonly portable: boolean; + readonly runtime: boolean; +} + +interface MaterializedCase { + readonly value: unknown; + readonly call?: unknown; +} + +const expectedSchemaDocuments = [ + "mcp-tools", + "primitives", + "path-claim", + "evidence-slots", + "rubric", + "gate-contract", + "gate-decision", + "project-error" +] as const; + +const schemaDocumentPaths = [ + "../../src/contracts/schemas/v1/mcp-tools.schema.json", + "../../src/contracts/schemas/v1/primitives.schema.json", + "../../src/contracts/schemas/v1/path-claim.schema.json", + "../../src/contracts/schemas/v1/evidence-slots.schema.json", + "../../src/contracts/schemas/v1/rubric.schema.json", + "../../src/contracts/schemas/v1/gate-contract.schema.json", + "../../src/contracts/schemas/v1/gate-decision.schema.json", + "../../src/contracts/schemas/v1/project-error.schema.json" +] as const; + +const validatingKeywordCoverage = { + "x-archflow-max-utf8-bytes": ["path-utf8-input", "path-utf8-output", "project-error-path-utf8"], + "x-archflow-unique-by": ["rubric-unique-by"], + "x-archflow-mcp-semantics": [ + "mcp-current-evidence", + "mcp-waiver-origin-task", + "gate-review-rule-order", + "gate-adjudication-rule-order", + "gate-review-eligible-subset", + "gate-adjudication-eligible-subset", + "gate-review-waiver-scope", + "gate-adjudication-waiver-scope", + "gate-adjudication-nonempty", + "gate-attempts-exhausted", + "gate-material-drift-order", + "gate-commit-artifact-order", + "gate-commit-parent-order" + ], + "x-archflow-gate-semantics": [ + "gate-review-rule-order", + "gate-adjudication-rule-order", + "gate-review-eligible-subset", + "gate-adjudication-eligible-subset", + "gate-review-waiver-scope", + "gate-adjudication-waiver-scope", + "gate-adjudication-nonempty", + "gate-attempts-exhausted", + "gate-material-drift-order", + "gate-commit-artifact-order", + "gate-commit-parent-order", + "gate-review-waiver-eligibility", + "gate-adjudication-waiver-eligibility", + "gate-adjudication-resolution-order", + "gate-adjudication-resolution-coverage", + "gate-restore-adoption-authority" + ], + "x-archflow-sorted-unique": ["project-error-sorted-unique"] +} as const; + +const resultCorrelationCoverage = [ + "failure-tool-correlation", + "state-success-status-correlation", + "gate-success-kind-correlation", + "gate-success-decision-kind-correlation", + "gate-success-task-correlation", + "gate-success-phase-correlation", + "gate-success-subject-correlation", + "gate-success-notes-correlation", + "waiver-success-origin-correlation", + "waiver-success-task-correlation", + "waiver-success-rule-id-correlation", + "waiver-success-rule-version-correlation", + "waiver-success-subject-correlation", + "waiver-success-evidence-correlation", + "waiver-success-scope-correlation" +] as const; + +const annotationKeywords = ["x-archflow-effect"] as const; +const expectedRuntimeSemanticCategories = [...new Set([ + ...Object.values(validatingKeywordCoverage).flat(), + ...resultCorrelationCoverage +])].sort(); + +const D = (character: string): string => character.repeat(64); +const RULE_A = Object.freeze({ rule_id: "Rule:A", rule_version: 1 }); +const RULE_B = Object.freeze({ rule_id: "Rule:B", rule_version: 1 }); +const PROVENANCE = Object.freeze({ schema_version: "1", actor_class: "human", assurance: "declared-local-trace", channel: "archflow-local", decision_event_id: "Decision:1", helper_invocation_id: "Helper:1", recorded_at: "2026-07-27T12:00:00.000Z" }); +const COMMON = Object.freeze({ schema_version: "1", task_id: "Task:1", intent_id: "Intent:1", expected_revision: 0, input_fingerprint: D("a") }); +const SELF = Object.freeze({ role: "self-review", evidence_digest: D("1"), assurance: "agent-declared", producer_family: "claude", reviewer_family: "claude", independence: "same-family-self" }); +const COUNTER = Object.freeze({ role: "counter-review", evidence_digest: D("2"), assurance: "server-attested", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family" }); +const CURRENT_EVIDENCE = Object.freeze({ set_digest: D("3"), slots: [SELF, COUNTER] }); +const AUTHORITY = Object.freeze({ link_digest: D("4"), purpose: "restore-adoption", proposed_generation_digest: D("5"), changed_input_fingerprint: D("6") }); +const SCOPE = Object.freeze({ operation: "review-trigger", boundary: "subject" }); + +const stateCall = (status = "running") => ({ ...COMMON, phase_instance: "phase-impl-3", step: "produce", status }); +const counterCall = (artifactPath = "phases/phase-3.md", criteria = [{ id: "paths", text: "Check paths", blocking: true }]) => ({ ...COMMON, artifact_path: artifactPath, rubric: { schema_version: "1", kind: "implementation", mode: "adversarial", criteria } }); +const adjudicateCall = () => ({ ...COMMON, artifact_path: "phases/phase-3.md", upstream_paths: ["architecture.md"] }); +const gateCall = (kind: string, context: unknown) => ({ ...COMMON, phase_instance: "phase-impl-3", summary: "Review", subject_digest: D("b"), current_evidence: CURRENT_EVIDENCE, kind, context }); +const waiverCall = () => ({ ...COMMON, origin: { origin_gate_id: "Gate:1", origin_decision_digest: D("1"), origin_context_digest: D("2"), task_id: COMMON.task_id, phase_instance: "phase-impl-3", subject_digest: D("3"), current_evidence_set_digest: D("4"), rule: RULE_A, scope: SCOPE }, rationale: "Needed" }); +const reviewContext = () => ({ matched_rules: [RULE_A], uncertain_rules: [], eligible_waiver_rules: [RULE_A], waiver_scope: SCOPE }); +const adjudicationContext = () => ({ constitution: "fail", failed_rules: [RULE_A, RULE_B], uncertain_rules: [], eligible_waiver_rules: [], waiver_scope: { operation: "adjudication-failure", boundary: "phase" } }); +const restoreContext = () => ({ path: "task/file.md", recorded_generation_digest: D("7"), current_generation_digest: D("8"), adoption_candidate: AUTHORITY }); +const result = (value: unknown) => ({ schema_version: "1", ok: true, value }); +const decisionEnvelope = (kind: string, payload: unknown, overrides: Record = {}) => ({ schema_version: "1", gate_id: "Gate:1", task_id: COMMON.task_id, phase_instance: "phase-impl-3", subject_digest: D("b"), context_digest: D("9"), human_provenance: PROVENANCE, kind, payload, ...overrides }); +const gateResult = (kind: string, payload: Record, overrides: Record = {}) => result({ kind, decision: decisionEnvelope(kind, payload), notes: payload.reason, revision: 1, ...overrides }); +const waiverResult = (overrides: Record = {}) => result({ origin_gate_id: "Gate:1", waiver_gate_id: "Gate:2", task_id: COMMON.task_id, rule_id: RULE_A.rule_id, rule_version: RULE_A.rule_version, subject_digest: D("3"), current_evidence_set_digest: D("4"), scope: SCOPE, human_provenance: PROVENANCE, granted: false, notes: "Denied", revision: 1, ...overrides }); + +function freshAjv(): Ajv2020 { + const ajv = new Ajv2020({ strict: true, allErrors: true, allowUnionTypes: false, coerceTypes: false, removeAdditional: false, useDefaults: false, validateFormats: true }); + const addFormats = formatsModule.default as unknown as FormatsPlugin; + addFormats(ajv); + return ajv; +} + +function visit(value: unknown, callback: (value: unknown, path: string) => void, path = "$"): void { + callback(value, path); + if (Array.isArray(value)) value.forEach((entry, index) => visit(entry, callback, `${path}[${index}]`)); + else if (typeof value === "object" && value !== null) for (const [key, entry] of Object.entries(value)) visit(entry, callback, `${path}.${key}`); +} + +async function corpus(): Promise { + return JSON.parse(await readFile(new URL("../fixtures/mcp/catalogue/classified-corpus.json", import.meta.url), "utf8")) as CorpusCase[]; +} + +function materialize(entry: CorpusCase): MaterializedCase { + const longPath = `${"é".repeat(600)}.md`; + const artifactGateCall = gateCall("artifact-approval", { artifact_kind: "phase-implementation" }); + const artifactGateResult = gateResult("artifact-approval", { decision: "approve", reason: "Approved" }); + switch (entry.materialization) { + case "valid-state-input": return { value: stateCall() }; + case "invalid-state-extra": return { value: { ...stateCall(), unexpected: true } }; + case "path-utf8-input": return { value: counterCall(longPath) }; + case "rubric-unique": return { value: counterCall("phases/phase-3.md", [{ id: "paths", text: "First", blocking: true }, { id: "paths", text: "Second", blocking: false }]) }; + case "waiver-origin-task": return { value: { ...waiverCall(), task_id: "Other" } }; + case "current-evidence": return { value: { ...artifactGateCall, current_evidence: { ...CURRENT_EVIDENCE, slots: [SELF, { ...COUNTER, evidence_digest: SELF.evidence_digest }] } } }; + case "review-rule-order": return { value: gateCall("review-trigger", { ...reviewContext(), matched_rules: [RULE_B, RULE_A], eligible_waiver_rules: [] }) }; + case "adjudication-rule-order": return { value: gateCall("adjudication-failure", { ...adjudicationContext(), failed_rules: [RULE_B, RULE_A] }) }; + case "review-eligible-subset": return { value: gateCall("review-trigger", { ...reviewContext(), eligible_waiver_rules: [RULE_B] }) }; + case "adjudication-eligible-subset": return { value: gateCall("adjudication-failure", { ...adjudicationContext(), eligible_waiver_rules: [{ rule_id: "Rule:C", rule_version: 1 }] }) }; + case "review-waiver-scope": return { value: gateCall("review-trigger", { ...reviewContext(), waiver_scope: { operation: "adjudication-failure", boundary: "subject" } }) }; + case "adjudication-waiver-scope": return { value: gateCall("adjudication-failure", { ...adjudicationContext(), waiver_scope: { operation: "review-trigger", boundary: "phase" } }) }; + case "adjudication-nonempty": return { value: gateCall("adjudication-failure", { ...adjudicationContext(), failed_rules: [], eligible_waiver_rules: [] }) }; + case "attempts-exhausted": return { value: gateCall("attempts-exhausted", { step: "produce", attempts: 1, maximum_attempts: 2 }) }; + case "material-drift-order": return { value: gateCall("material-drift", { affected_upstream: { kind: "architecture", digest: D("4") }, drift: "material", affected_claim_ids: ["z", "a"] }) }; + case "commit-artifact-order": return { value: gateCall("commit-authorization", { target_ref: "HEAD", diff_digest: D("4"), current_artifact_digests: [D("b"), D("a")], parent_document_digests: [D("c")] }) }; + case "commit-parent-order": return { value: gateCall("commit-authorization", { target_ref: "HEAD", diff_digest: D("4"), current_artifact_digests: [D("a")], parent_document_digests: [D("c"), D("b")] }) }; + case "valid-state-success": return { call: stateCall(), value: result({ path: "phases/state.json", revision: 1, status: "running" }) }; + case "valid-counter-success": return { call: counterCall(), value: result({ path: "reviews/counter.md", verdict: "pass", blocking_count: 0, revision: 1 }) }; + case "valid-adjudicate-success": return { call: adjudicateCall(), value: result({ path: "reviews/adjudication.md", constitution: "pass", drift: "aligned", triggers: [], revision: 1 }) }; + case "valid-gate-success": return { call: artifactGateCall, value: artifactGateResult }; + case "valid-waiver-success": return { call: waiverCall(), value: waiverResult() }; + case "valid-failure": return { value: snapshotFailure(["a/file", "z/file"]) }; + case "path-utf8-output": return { call: stateCall(), value: result({ path: longPath, revision: 1, status: "running" }) }; + case "project-error-path-utf8": return { value: snapshotFailure([longPath]) }; + case "project-error-order": return { value: snapshotFailure(["z/file", "a/file"]) }; + case "failure-tool-correlation": return { value: { schema_version: "1", ok: false, error: { schema_version: "1", code: "CONTRACT_INVALID", owner: "contracts", retryable: false, diagnostic: { template_id: "CONTRACT_INVALID", parameters: { tool: "archflow_gate", issue_code: "input-invalid" } }, next_action: "correct-contract" } } }; + case "review-waiver-eligibility": return { call: gateCall("review-trigger", reviewContext()), value: gateResult("review-trigger", { decision: "waiver-requested", reason: "Exception", rule: RULE_B, rationale: "Needed" }) }; + case "adjudication-waiver-eligibility": return { call: gateCall("adjudication-failure", adjudicationContext()), value: gateResult("adjudication-failure", { decision: "waiver-requested", reason: "Exception", rule: { rule_id: "Rule:C", rule_version: 1 }, rationale: "Needed" }) }; + case "adjudication-resolution-order": return { call: gateCall("adjudication-failure", adjudicationContext()), value: gateResult("adjudication-failure", { decision: "approve", reason: "Resolved", resolutions: [{ rule: RULE_B, resolution: "B" }, { rule: RULE_A, resolution: "A" }] }) }; + case "adjudication-resolution-coverage": return { call: gateCall("adjudication-failure", adjudicationContext()), value: gateResult("adjudication-failure", { decision: "approve", reason: "Resolved", resolutions: [{ rule: RULE_A, resolution: "A" }] }) }; + case "restore-adoption-authority": return { call: gateCall("restore-collision", restoreContext()), value: gateResult("restore-collision", { decision: "adopt-as-new-generation", reason: "Adopt", adoption_authority: { ...AUTHORITY, link_digest: D("a") }, rationale: "Reviewed" }) }; + case "state-status-correlation": return { call: stateCall(), value: result({ path: "phases/state.json", revision: 1, status: "failed" }) }; + case "gate-kind-correlation": return { call: artifactGateCall, value: gateResult("artifact-approval", { decision: "approve", reason: "Approved" }, { kind: "review-trigger" }) }; + case "gate-decision-kind-correlation": return { call: artifactGateCall, value: result({ kind: "artifact-approval", decision: decisionEnvelope("material-drift", { decision: "reject", reason: "Approved" }), notes: "Approved", revision: 1 }) }; + case "gate-task-correlation": return { call: artifactGateCall, value: artifactGateResultWithDecision({ task_id: "Other" }) }; + case "gate-phase-correlation": return { call: artifactGateCall, value: artifactGateResultWithDecision({ phase_instance: "phase-impl-4" }) }; + case "gate-subject-correlation": return { call: artifactGateCall, value: artifactGateResultWithDecision({ subject_digest: D("c") }) }; + case "gate-notes-correlation": return { call: artifactGateCall, value: result({ ...(artifactGateResult.value as object), notes: "Different" }) }; + case "waiver-origin-correlation": return { call: waiverCall(), value: waiverResult({ origin_gate_id: "Gate:Other" }) }; + case "waiver-task-correlation": return { call: waiverCall(), value: waiverResult({ task_id: "Other" }) }; + case "waiver-rule-id-correlation": return { call: waiverCall(), value: waiverResult({ rule_id: "Rule:Other" }) }; + case "waiver-rule-version-correlation": return { call: waiverCall(), value: waiverResult({ rule_version: 2 }) }; + case "waiver-subject-correlation": return { call: waiverCall(), value: waiverResult({ subject_digest: D("c") }) }; + case "waiver-evidence-correlation": return { call: waiverCall(), value: waiverResult({ current_evidence_set_digest: D("c") }) }; + case "waiver-scope-correlation": return { call: waiverCall(), value: waiverResult({ scope: { ...SCOPE, boundary: "phase" } }) }; + default: throw new TypeError(`unknown corpus materialization: ${entry.materialization}`); + } +} + +function snapshotFailure(paths: string[]): unknown { + return { schema_version: "1", ok: false, error: { schema_version: "1", code: "SNAPSHOT_LIMIT", owner: "snapshot", retryable: false, diagnostic: { template_id: "SNAPSHOT_LIMIT", parameters: { limit_scope: "task", offending_paths: paths, current_bytes: 2, byte_cap: 1 } }, next_action: "reduce-snapshot" } }; +} + +function artifactGateResultWithDecision(overrides: Record): unknown { + const payload = { decision: "approve", reason: "Approved" }; + return result({ kind: "artifact-approval", decision: decisionEnvelope("artifact-approval", payload, overrides), notes: "Approved", revision: 1 }); +} + +function validateAuthenticSuccess(tool: ToolName, rawCall: unknown, value: unknown): void { + switch (tool) { + case "archflow_state": void validateProjectResultStructure(parseToolCall(tool, rawCall), value); break; + case "archflow_counter_review": void validateProjectResultStructure(parseToolCall(tool, rawCall), value); break; + case "archflow_adjudicate": void validateProjectResultStructure(parseToolCall(tool, rawCall), value); break; + case "archflow_gate": void validateProjectResultStructure(parseToolCall(tool, rawCall), value); break; + case "archflow_waiver": void validateProjectResultStructure(parseToolCall(tool, rawCall), value); break; + } +} + +describe("advertised MCP tool catalogue", () => { + it("passes the public-root neutral ListToolsResult schema with the fixed non-paginated surface", () => { + const listed = { tools: ADVERTISED_TOOL_CATALOGUE }; + const validation = specTypeSchemas.ListToolsResult["~standard"].validate(listed); + expect(validation).not.toHaveProperty("issues"); + expect(validation).toHaveProperty("value"); + expect(listed).not.toHaveProperty("nextCursor"); + expect(ADVERTISED_TOOL_CATALOGUE.map(({ name }) => name)).toEqual(TOOL_NAMES); + expect(ADVERTISED_TOOL_CATALOGUE).toHaveLength(5); + }); + + it("compiles every standalone input and output with strict Ajv 2020 and standard formats only", () => { + for (const descriptor of ADVERTISED_TOOL_CATALOGUE) { + expect(() => freshAjv().compile(descriptor.inputSchema), `${descriptor.name} input`).not.toThrow(); + expect(() => freshAjv().compile(descriptor.outputSchema), `${descriptor.name} output`).not.toThrow(); + } + }); + + it("pins object roots, the exact source closure, local references, and portable keywords", async () => { + const sourceDocuments = await Promise.all(schemaDocumentPaths.map(async (path) => JSON.parse(await readFile(new URL(path, import.meta.url), "utf8")) as object)); + const sourceKeywords = new Set(); + for (const document of sourceDocuments) visit(document, (value) => { + if (typeof value !== "object" || value === null || Array.isArray(value)) return; + for (const key of Object.keys(value)) if (key.startsWith("x-archflow-")) sourceKeywords.add(key); + }); + expect([...sourceKeywords].sort()).toEqual([...Object.keys(validatingKeywordCoverage), ...annotationKeywords].sort()); + + for (const descriptor of ADVERTISED_TOOL_CATALOGUE) { + for (const [member, schema] of [["input", descriptor.inputSchema], ["output", descriptor.outputSchema]] as const) { + expect(schema.type, `${descriptor.name} ${member} root`).toBe("object"); + expect(schema.$schema).toBe("https://json-schema.org/draft/2020-12/schema"); + expect(Object.keys(schema.$defs as object)).toEqual(expectedSchemaDocuments); + visit(schema, (value, path) => { + if (typeof value !== "object" || value === null || Array.isArray(value)) return; + for (const [key, nested] of Object.entries(value)) { + expect(key, `${descriptor.name} ${member} ${path}`).not.toBe("$id"); + expect(key, `${descriptor.name} ${member} ${path}`).not.toMatch(/^x-archflow-/u); + if (key === "$ref") expect(nested, `${descriptor.name} ${member} ${path}`).toMatch(/^#\//u); + if (key === "$schema" && path !== "$") throw new TypeError(`${descriptor.name} ${member} has embedded $schema at ${path}`); + } + }); + } + } + }); + + it("deeply freezes the catalogue, descriptors, schemas, and schema descendants", () => { + visit(ADVERTISED_TOOL_CATALOGUE, (value, path) => { + if ((typeof value === "object" && value !== null) || typeof value === "function") expect(Object.isFrozen(value), path).toBe(true); + }); + }); + + it("classifies every removed validation branch and call correlation separately from portable structure", async () => { + const cases = await corpus(); + const runtimeCases = cases.filter(({ classification }) => classification === "runtime-semantic"); + expect(new Set(cases.map(({ classification }) => classification))).toEqual(new Set(["portable-structure", "runtime-semantic"])); + expect(runtimeCases.map(({ semantic_category }) => semantic_category).sort()).toEqual(expectedRuntimeSemanticCategories); + expect(new Set(runtimeCases.map(({ semantic_category }) => semantic_category)).size).toBe(runtimeCases.length); + + const validSuccessTools = cases.filter(({ classification, member, portable, runtime, call_fixture }) => classification === "portable-structure" && member === "output" && portable && runtime && call_fixture !== undefined).map(({ tool }) => tool); + expect(validSuccessTools).toEqual(TOOL_NAMES); + + for (const entry of cases) { + const descriptor = ADVERTISED_TOOL_CATALOGUE.find(({ name }) => name === entry.tool); + expect(descriptor, entry.label).toBeDefined(); + const { value, call } = materialize(entry); + const schema = entry.member === "input" ? descriptor!.inputSchema : descriptor!.outputSchema; + expect(freshAjv().compile(schema)(value), `${entry.label} portable`).toBe(entry.portable); + const isSuccessOutput = entry.member === "output" && (value as { ok?: unknown }).ok === true; + if (isSuccessOutput) { + expect(entry.call_fixture, `${entry.label} companion call fixture`).toBe(entry.tool); + expect(call, `${entry.label} companion call`).toBeDefined(); + } + let runtime = true; + try { + if (entry.member === "input") parseToolCall(entry.tool, value); + else if ((value as { ok?: unknown }).ok === false) validateProjectFailureStructure(entry.tool, value); + else validateAuthenticSuccess(entry.tool, call, value); + } catch { + runtime = false; + } + expect(runtime, `${entry.label} runtime`).toBe(entry.runtime); + if (entry.classification === "runtime-semantic") { + expect(entry.portable).toBe(true); + expect(entry.runtime).toBe(false); + } + } + }); + + it("keeps the catalogue on its direct SDK-free seam", async () => { + const [source, contractBarrel, packageManifest] = await Promise.all([ + readFile(new URL("../../src/mcp/tools.ts", import.meta.url), "utf8"), + readFile(new URL("../../src/contracts/index.ts", import.meta.url), "utf8"), + readFile(new URL("../../package.json", import.meta.url), "utf8") + ]); + expect(source).not.toMatch(/@modelcontextprotocol\/(?:core|server)/u); + expect(source).not.toMatch(/\/internal(?:[/'"]|$)/u); + expect(contractBarrel).not.toMatch(/ADVERTISED_TOOL_CATALOGUE|AdvertisedToolDescriptor|mcp\/tools/u); + expect(JSON.parse(packageManifest) as object).not.toHaveProperty("exports"); + await expect(readFile(new URL("../../src/mcp/index.ts", import.meta.url), "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + expect(Object.keys(await import("../../src/mcp/tools.js"))).toEqual(["ADVERTISED_TOOL_CATALOGUE"]); + }); +}); diff --git a/test/contracts/mcp-contract-agreement.test.ts b/test/contracts/mcp-contract-agreement.test.ts index f3267e7a..500b8205 100644 --- a/test/contracts/mcp-contract-agreement.test.ts +++ b/test/contracts/mcp-contract-agreement.test.ts @@ -1,11 +1,30 @@ import { readFile } from "node:fs/promises"; +import { specTypeSchemas } from "@modelcontextprotocol/server"; import { describe, expect, it } from "vitest"; -import { parseToolCall, TOOL_DEFINITIONS } from "../../src/contracts/mcp-tools.js"; +import { parseTransportRequestId } from "../../src/contracts/contexts.js"; +import { parseToolCall, TOOL_DEFINITIONS, validateProjectResultStructure } from "../../src/contracts/mcp-tools.js"; import { createJsonSchemaValidator } from "../../src/contracts/validators.js"; +import { ADVERTISED_TOOL_CATALOGUE } from "../../src/mcp/tools.js"; const load = async (path: string) => JSON.parse(await readFile(new URL(path, import.meta.url), "utf8")) as object; describe("MCP contract schema agreement", () => { + it("agrees with the public SDK RequestId schema across safe boundaries", () => { + const admitted = ["", "arbitrary \n string \u0000", -0, -1, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER] as const; + const rejected: readonly unknown[] = [Number.MIN_SAFE_INTEGER - 1, Number.MAX_SAFE_INTEGER + 1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, null, true, {}, []]; + for (const candidate of admitted) { + const sdkResult = specTypeSchemas.RequestId["~standard"].validate(candidate); + if (sdkResult.issues !== undefined) throw new Error("SDK RequestId rejected an admitted boundary fixture"); + expect(Object.is(sdkResult.value, candidate)).toBe(true); + expect(Object.is(parseTransportRequestId(candidate), candidate)).toBe(true); + } + for (const candidate of rejected) { + const sdkResult = specTypeSchemas.RequestId["~standard"].validate(candidate); + expect(sdkResult.issues).toBeDefined(); + expect(() => parseTransportRequestId(candidate)).toThrow(); + } + }); + it("compiles every exact tool input fragment and agrees on closed state fixtures", async () => { const mcp = await load("../../src/contracts/schemas/v1/mcp-tools.schema.json") as { $defs: Record }; const references = [await load("../../src/contracts/schemas/v1/primitives.schema.json"), await load("../../src/contracts/schemas/v1/project-error.schema.json"), await load("../../src/contracts/schemas/v1/rubric.schema.json"), await load("../../src/contracts/schemas/v1/path-claim.schema.json"), await load("../../src/contracts/schemas/v1/evidence-slots.schema.json"), await load("../../src/contracts/schemas/v1/gate-contract.schema.json"), await load("../../src/contracts/schemas/v1/gate-decision.schema.json")]; @@ -19,6 +38,32 @@ describe("MCP contract schema agreement", () => { expect(Object.values(TOOL_DEFINITIONS).every((definition) => definition.input_schema_id.startsWith("https://archflow.dev/schemas/v1/mcp-tools#/$defs/"))).toBe(true); }); + it("keeps waiver success rule versions within the shared positive safe-integer bounds", async () => { + const mcp = await load("../../src/contracts/schemas/v1/mcp-tools.schema.json") as { $defs: Record }; + const references = [await load("../../src/contracts/schemas/v1/primitives.schema.json"), await load("../../src/contracts/schemas/v1/project-error.schema.json"), await load("../../src/contracts/schemas/v1/rubric.schema.json"), await load("../../src/contracts/schemas/v1/path-claim.schema.json"), await load("../../src/contracts/schemas/v1/evidence-slots.schema.json"), await load("../../src/contracts/schemas/v1/gate-contract.schema.json"), await load("../../src/contracts/schemas/v1/gate-decision.schema.json")]; + const normative = createJsonSchemaValidator({ $schema: "https://json-schema.org/draft/2020-12/schema", ...mcp.$defs.archflow_waiver!.result, $defs: mcp.$defs }, references); + const advertisedSchema = ADVERTISED_TOOL_CATALOGUE.find(({ name }) => name === "archflow_waiver")!.outputSchema; + const advertised = createJsonSchemaValidator(advertisedSchema); + const digest = (character: string) => character.repeat(64); + const provenance = { schema_version: "1", actor_class: "human", assurance: "declared-local-trace", channel: "archflow-local", decision_event_id: "Decision:1", helper_invocation_id: "Helper:1", recorded_at: "2026-07-27T12:00:00.000Z" }; + const scope = { operation: "review-trigger", boundary: "subject" } as const; + const rawCall = (ruleVersion: number) => ({ schema_version: "1", task_id: "Task:1", intent_id: "Intent:1", expected_revision: 0, input_fingerprint: digest("a"), origin: { origin_gate_id: "Gate:1", origin_decision_digest: digest("1"), origin_context_digest: digest("2"), task_id: "Task:1", phase_instance: "phase-impl-3", subject_digest: digest("3"), current_evidence_set_digest: digest("4"), rule: { rule_id: "Rule:1", rule_version: ruleVersion }, scope }, rationale: "Needed" }); + const output = (ruleVersion: number) => ({ schema_version: "1", ok: true, value: { origin_gate_id: "Gate:1", waiver_gate_id: "Gate:2", task_id: "Task:1", rule_id: "Rule:1", rule_version: ruleVersion, subject_digest: digest("3"), current_evidence_set_digest: digest("4"), scope, human_provenance: provenance, granted: false, notes: "Denied", revision: 1 } }); + + for (const boundary of [1, Number.MAX_SAFE_INTEGER]) { + const candidate = output(boundary); + expect(normative.validate(candidate), `normative ${boundary}`).toBe(true); + expect(advertised.validate(candidate), `advertised ${boundary}`).toBe(true); + expect(validateProjectResultStructure(parseToolCall("archflow_waiver", rawCall(boundary)), candidate).ok, `runtime ${boundary}`).toBe(true); + } + for (const adjacent of [0, Number.MAX_SAFE_INTEGER + 1]) { + const candidate = output(adjacent); + expect(normative.validate(candidate), `normative ${adjacent}`).toBe(false); + expect(advertised.validate(candidate), `advertised ${adjacent}`).toBe(false); + expect(() => validateProjectResultStructure(parseToolCall("archflow_waiver", rawCall(1)), candidate), `runtime ${adjacent}`).toThrow(); + } + }); + it("compiles the closed correlated result-expectation union", async () => { const mcp = await load("../../src/contracts/schemas/v1/mcp-tools.schema.json"); const expectation = await load("../../src/contracts/schemas/v1/result-expectation.schema.json"); diff --git a/test/fixtures/mcp/boundary/input-classification.json b/test/fixtures/mcp/boundary/input-classification.json new file mode 100644 index 00000000..efb972f6 --- /dev/null +++ b/test/fixtures/mcp/boundary/input-classification.json @@ -0,0 +1,10 @@ +{ + "not_object": [null, [], "1", 42, true], + "missing_schema_version": {}, + "invalid_schema_versions": [null, 1, "", "version_2", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"], + "unsupported_schema_version": "2.0-beta.1", + "version_one_but_invalid": { + "schema_version": "1", + "unexpected": "handler must not see this" + } +} diff --git a/test/fixtures/mcp/catalogue/classified-corpus.json b/test/fixtures/mcp/catalogue/classified-corpus.json new file mode 100644 index 00000000..8afbc297 --- /dev/null +++ b/test/fixtures/mcp/catalogue/classified-corpus.json @@ -0,0 +1,50 @@ +[ + { "label": "portable-valid-state-input", "tool": "archflow_state", "member": "input", "classification": "portable-structure", "materialization": "valid-state-input", "portable": true, "runtime": true }, + { "label": "portable-invalid-state-extra-field", "tool": "archflow_state", "member": "input", "classification": "portable-structure", "materialization": "invalid-state-extra", "portable": false, "runtime": false }, + { "label": "portable-valid-state-success", "tool": "archflow_state", "member": "output", "classification": "portable-structure", "materialization": "valid-state-success", "call_fixture": "archflow_state", "portable": true, "runtime": true }, + { "label": "portable-valid-counter-review-success", "tool": "archflow_counter_review", "member": "output", "classification": "portable-structure", "materialization": "valid-counter-success", "call_fixture": "archflow_counter_review", "portable": true, "runtime": true }, + { "label": "portable-valid-adjudicate-success", "tool": "archflow_adjudicate", "member": "output", "classification": "portable-structure", "materialization": "valid-adjudicate-success", "call_fixture": "archflow_adjudicate", "portable": true, "runtime": true }, + { "label": "portable-valid-gate-success", "tool": "archflow_gate", "member": "output", "classification": "portable-structure", "materialization": "valid-gate-success", "call_fixture": "archflow_gate", "portable": true, "runtime": true }, + { "label": "portable-valid-waiver-success", "tool": "archflow_waiver", "member": "output", "classification": "portable-structure", "materialization": "valid-waiver-success", "call_fixture": "archflow_waiver", "portable": true, "runtime": true }, + { "label": "portable-valid-project-failure", "tool": "archflow_state", "member": "output", "classification": "portable-structure", "materialization": "valid-failure", "portable": true, "runtime": true }, + + { "label": "runtime-only-input-path-byte-limit", "tool": "archflow_counter_review", "member": "input", "classification": "runtime-semantic", "semantic_category": "path-utf8-input", "materialization": "path-utf8-input", "portable": true, "runtime": false }, + { "label": "runtime-only-success-path-byte-limit", "tool": "archflow_state", "member": "output", "classification": "runtime-semantic", "semantic_category": "path-utf8-output", "materialization": "path-utf8-output", "call_fixture": "archflow_state", "portable": true, "runtime": false }, + { "label": "runtime-only-project-error-path-byte-limit", "tool": "archflow_state", "member": "output", "classification": "runtime-semantic", "semantic_category": "project-error-path-utf8", "materialization": "project-error-path-utf8", "portable": true, "runtime": false }, + { "label": "runtime-only-rubric-criterion-id-uniqueness", "tool": "archflow_counter_review", "member": "input", "classification": "runtime-semantic", "semantic_category": "rubric-unique-by", "materialization": "rubric-unique", "portable": true, "runtime": false }, + { "label": "runtime-only-waiver-origin-task-mismatch", "tool": "archflow_waiver", "member": "input", "classification": "runtime-semantic", "semantic_category": "mcp-waiver-origin-task", "materialization": "waiver-origin-task", "portable": true, "runtime": false }, + { "label": "runtime-only-current-evidence-duplicate-digest", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "mcp-current-evidence", "materialization": "current-evidence", "portable": true, "runtime": false }, + { "label": "runtime-only-review-trigger-rule-order", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-review-rule-order", "materialization": "review-rule-order", "portable": true, "runtime": false }, + { "label": "runtime-only-adjudication-rule-order", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-adjudication-rule-order", "materialization": "adjudication-rule-order", "portable": true, "runtime": false }, + { "label": "runtime-only-review-trigger-eligible-waiver-subset", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-review-eligible-subset", "materialization": "review-eligible-subset", "portable": true, "runtime": false }, + { "label": "runtime-only-adjudication-eligible-waiver-subset", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-adjudication-eligible-subset", "materialization": "adjudication-eligible-subset", "portable": true, "runtime": false }, + { "label": "runtime-only-review-trigger-waiver-scope", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-review-waiver-scope", "materialization": "review-waiver-scope", "portable": true, "runtime": false }, + { "label": "runtime-only-adjudication-waiver-scope", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-adjudication-waiver-scope", "materialization": "adjudication-waiver-scope", "portable": true, "runtime": false }, + { "label": "runtime-only-adjudication-nonempty-rule-set", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-adjudication-nonempty", "materialization": "adjudication-nonempty", "portable": true, "runtime": false }, + { "label": "runtime-only-attempts-exhausted-relation", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-attempts-exhausted", "materialization": "attempts-exhausted", "portable": true, "runtime": false }, + { "label": "runtime-only-material-drift-claim-order", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-material-drift-order", "materialization": "material-drift-order", "portable": true, "runtime": false }, + { "label": "runtime-only-commit-artifact-digest-order", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-commit-artifact-order", "materialization": "commit-artifact-order", "portable": true, "runtime": false }, + { "label": "runtime-only-commit-parent-digest-order", "tool": "archflow_gate", "member": "input", "classification": "runtime-semantic", "semantic_category": "gate-commit-parent-order", "materialization": "commit-parent-order", "portable": true, "runtime": false }, + { "label": "runtime-only-review-waiver-decision-eligibility", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-review-waiver-eligibility", "materialization": "review-waiver-eligibility", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-adjudication-waiver-decision-eligibility", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-adjudication-waiver-eligibility", "materialization": "adjudication-waiver-eligibility", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-adjudication-resolution-order", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-adjudication-resolution-order", "materialization": "adjudication-resolution-order", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-adjudication-resolution-coverage", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-adjudication-resolution-coverage", "materialization": "adjudication-resolution-coverage", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-restore-adoption-authority", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-restore-adoption-authority", "materialization": "restore-adoption-authority", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-project-error-path-order", "tool": "archflow_state", "member": "output", "classification": "runtime-semantic", "semantic_category": "project-error-sorted-unique", "materialization": "project-error-order", "portable": true, "runtime": false }, + { "label": "runtime-only-project-failure-tool-correlation", "tool": "archflow_state", "member": "output", "classification": "runtime-semantic", "semantic_category": "failure-tool-correlation", "materialization": "failure-tool-correlation", "portable": true, "runtime": false }, + + { "label": "runtime-only-state-status-correlation", "tool": "archflow_state", "member": "output", "classification": "runtime-semantic", "semantic_category": "state-success-status-correlation", "materialization": "state-status-correlation", "call_fixture": "archflow_state", "portable": true, "runtime": false }, + { "label": "runtime-only-gate-result-kind-correlation", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-success-kind-correlation", "materialization": "gate-kind-correlation", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-gate-decision-kind-correlation", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-success-decision-kind-correlation", "materialization": "gate-decision-kind-correlation", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-gate-task-correlation", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-success-task-correlation", "materialization": "gate-task-correlation", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-gate-phase-correlation", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-success-phase-correlation", "materialization": "gate-phase-correlation", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-gate-subject-correlation", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-success-subject-correlation", "materialization": "gate-subject-correlation", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-gate-notes-correlation", "tool": "archflow_gate", "member": "output", "classification": "runtime-semantic", "semantic_category": "gate-success-notes-correlation", "materialization": "gate-notes-correlation", "call_fixture": "archflow_gate", "portable": true, "runtime": false }, + { "label": "runtime-only-waiver-origin-correlation", "tool": "archflow_waiver", "member": "output", "classification": "runtime-semantic", "semantic_category": "waiver-success-origin-correlation", "materialization": "waiver-origin-correlation", "call_fixture": "archflow_waiver", "portable": true, "runtime": false }, + { "label": "runtime-only-waiver-task-correlation", "tool": "archflow_waiver", "member": "output", "classification": "runtime-semantic", "semantic_category": "waiver-success-task-correlation", "materialization": "waiver-task-correlation", "call_fixture": "archflow_waiver", "portable": true, "runtime": false }, + { "label": "runtime-only-waiver-rule-id-correlation", "tool": "archflow_waiver", "member": "output", "classification": "runtime-semantic", "semantic_category": "waiver-success-rule-id-correlation", "materialization": "waiver-rule-id-correlation", "call_fixture": "archflow_waiver", "portable": true, "runtime": false }, + { "label": "runtime-only-waiver-rule-version-correlation", "tool": "archflow_waiver", "member": "output", "classification": "runtime-semantic", "semantic_category": "waiver-success-rule-version-correlation", "materialization": "waiver-rule-version-correlation", "call_fixture": "archflow_waiver", "portable": true, "runtime": false }, + { "label": "runtime-only-waiver-subject-correlation", "tool": "archflow_waiver", "member": "output", "classification": "runtime-semantic", "semantic_category": "waiver-success-subject-correlation", "materialization": "waiver-subject-correlation", "call_fixture": "archflow_waiver", "portable": true, "runtime": false }, + { "label": "runtime-only-waiver-current-evidence-correlation", "tool": "archflow_waiver", "member": "output", "classification": "runtime-semantic", "semantic_category": "waiver-success-evidence-correlation", "materialization": "waiver-evidence-correlation", "call_fixture": "archflow_waiver", "portable": true, "runtime": false }, + { "label": "runtime-only-waiver-scope-correlation", "tool": "archflow_waiver", "member": "output", "classification": "runtime-semantic", "semantic_category": "waiver-success-scope-correlation", "materialization": "waiver-scope-correlation", "call_fixture": "archflow_waiver", "portable": true, "runtime": false } +] diff --git a/test/unit/contexts.test.ts b/test/unit/contexts.test.ts index 5696ff11..c45fed4b 100644 --- a/test/unit/contexts.test.ts +++ b/test/unit/contexts.test.ts @@ -1,16 +1,21 @@ +import type { Implementation } from "@modelcontextprotocol/server"; import { describe, expect, it } from "vitest"; -import { connectionContextFactory, createInvocationContext, ProtocolContextError } from "../../src/contracts/contexts.js"; +import * as publicContracts from "../../src/contracts/index.js"; +import { assertAuthenticInvocationContext, connectionContextFactory, createInvocationContext, parseClientImplementation, parseTransportRequestId, ProtocolContextError } from "../../src/contracts/contexts.js"; + +const startup = (connection_id: string) => connectionContextFactory.captureStartup({ connection_id, startup_repository_candidate: { working_directory: "/work/repo" } }); +const initialization = (client: { readonly name: string; readonly version: string }) => ({ client, host: "codex", protocol_version: "2026-01" } as const); describe("transport-neutral contexts", () => { it("defensively copies, deeply freezes, and initializes once", () => { - const startup = { connection_id: "connection-1", startup_repository_candidate: { working_directory: "/work/repo" } }; - const initialization = { client: { name: "Codex", version: "1.0" }, host: "codex", protocol_version: "2026-01" } as const; - const captured = connectionContextFactory.captureStartup(startup); - startup.startup_repository_candidate.working_directory = "/changed"; - const connection = captured.initialize(initialization); + const startupSeed = { connection_id: "connection-1", startup_repository_candidate: { working_directory: "/work/repo" } }; + const candidates = initialization({ name: "Codex", version: "1.0" }); + const captured = connectionContextFactory.captureStartup(startupSeed); + startupSeed.startup_repository_candidate.working_directory = "/changed"; + const connection = captured.initialize(candidates); expect(connection.startup_repository_candidate.working_directory).toBe("/work/repo"); expect(Object.isFrozen(connection.initialization_candidates.client)).toBe(true); - expect(() => captured.initialize(initialization)).toThrow(ProtocolContextError); + expect(() => captured.initialize(candidates)).toThrow(ProtocolContextError); }); it("retains AbortSignal identity while freezing copied transport metadata", () => { const connection = connectionContextFactory.captureStartup({ connection_id: "connection-2", startup_repository_candidate: { working_directory: "/work/repo" } }).initialize({ client: { name: "Claude", version: "1.0" }, host: "claude", protocol_version: "2026-01" }); @@ -28,4 +33,63 @@ describe("transport-neutral contexts", () => { expect(() => createInvocationContext({ ...connection } as never, seed, new AbortController().signal)).toThrow(/branded connection/); expect(() => createInvocationContext({ connection_id: connection.connection_id, startup_repository_candidate: connection.startup_repository_candidate, initialization_candidates: connection.initialization_candidates } as never, seed, new AbortController().signal)).toThrow(/branded connection/); }); + + it("preserves every admitted transport request ID through parser and authentic mint", () => { + const connection = startup("connection-request-ids").initialize(initialization({ name: "", version: "" })); + const admitted = ["", " arbitrary \n string \u0000 ", -0, -1, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER] as const; + for (const [index, candidate] of admitted.entries()) { + const parsed = parseTransportRequestId(candidate); + expect(Object.is(parsed, candidate), String(candidate)).toBe(true); + const invocation = createInvocationContext(connection, { invocation_id: `invocation-${index}`, transport_metadata: { request_id: parsed, operation: "tools/call" } }, new AbortController().signal); + expect(Object.is(invocation.transport_metadata.request_id, candidate), String(candidate)).toBe(true); + expect(Object.isFrozen(invocation)).toBe(true); + expect(Object.isFrozen(invocation.transport_metadata)).toBe(true); + expect(() => assertAuthenticInvocationContext(invocation)).not.toThrow(); + } + }); + + it("rejects adjacent unsafe, fractional, nonfinite, and non-JSON request IDs in both consumers", () => { + const connection = startup("connection-bad-request-ids").initialize(initialization({ name: "client", version: "version" })); + const rejected: readonly unknown[] = [Number.MIN_SAFE_INTEGER - 1, Number.MAX_SAFE_INTEGER + 1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, null, true, undefined, 1n, {}, [], new String("request")]; + for (const [index, candidate] of rejected.entries()) { + expect(() => parseTransportRequestId(candidate), `${index}`).toThrow(); + expect(() => createInvocationContext(connection, { invocation_id: `invocation-bad-${index}`, transport_metadata: { request_id: candidate, operation: "tools/call" } }, new AbortController().signal), `${index}`).toThrow(); + } + }); + + it("projects full client metadata to an exact frozen arbitrary-string pair", () => { + const sdkImplementation = { + name: "", + title: "Client title", + version: " version with spaces \n and \u0000 ", + description: "Optional SDK metadata", + icons: [{ src: "https://example.test/icon.png", mimeType: "image/png", sizes: ["64x64"] }], + websiteUrl: "https://example.test", + } as const satisfies Implementation; + expect(() => parseClientImplementation(sdkImplementation)).toThrow(); + const projected: { name: string; version: string } = { name: sdkImplementation.name, version: sdkImplementation.version }; + const parsed = parseClientImplementation(projected); + projected.name = "changed"; + expect(parsed).toEqual({ name: "", version: sdkImplementation.version }); + expect(Object.isFrozen(parsed)).toBe(true); + + const connection = startup("connection-client-projection").initialize(initialization(parsed)); + expect(connection.initialization_candidates.client).toEqual(parsed); + expect(connection.initialization_candidates.client).not.toBe(parsed); + expect(Object.isFrozen(connection.initialization_candidates.client)).toBe(true); + expect(() => startup("connection-full-client").initialize(initialization(sdkImplementation))).toThrow(); + }); + + it("rejects fake and spread invocation contexts and keeps the connection factory direct-only", () => { + const connection = startup("connection-invocation-auth").initialize(initialization({ name: "client", version: "version" })); + const invocation = createInvocationContext(connection, { invocation_id: "invocation-auth", transport_metadata: { request_id: -0, operation: "tools/call" } }, new AbortController().signal); + expect(() => assertAuthenticInvocationContext(invocation)).not.toThrow(); + expect(() => assertAuthenticInvocationContext({ ...invocation })).toThrow(/authentic invocation/); + expect(() => assertAuthenticInvocationContext({ invocation_id: invocation.invocation_id, connection, signal: invocation.signal, transport_metadata: invocation.transport_metadata })).toThrow(/authentic invocation/); + expect("connectionContextFactory" in publicContracts).toBe(false); + expect(publicContracts.createInvocationContext).toBe(createInvocationContext); + expect(publicContracts.parseTransportRequestId).toBe(parseTransportRequestId); + expect(publicContracts.parseClientImplementation).toBe(parseClientImplementation); + expect(publicContracts.assertAuthenticInvocationContext).toBe(assertAuthenticInvocationContext); + }); }); diff --git a/test/unit/mcp-server.test.ts b/test/unit/mcp-server.test.ts new file mode 100644 index 00000000..4d34d18d --- /dev/null +++ b/test/unit/mcp-server.test.ts @@ -0,0 +1,322 @@ +import { readFile } from "node:fs/promises"; + +import { describe, expect, it } from "vitest"; + +import { connectionContextFactory, createInvocationContext } from "../../src/contracts/contexts.js"; +import { createProjectError, createProtocolError } from "../../src/contracts/errors.js"; +import type { InvocationContext } from "../../src/contracts/contexts.js"; +import { + assertAuthenticToolBoundary, + assertAuthenticToolBoundaryOutcome, + authenticateProtocolError, + createToolBoundary, + type ToolBoundaryOutcome +} from "../../src/mcp/server.js"; + +const digest = "a".repeat(64); +const stateInput = { + schema_version: "1", + task_id: "task-1", + intent_id: "intent-1", + expected_revision: 2, + input_fingerprint: digest, + phase_instance: "phase-impl-3", + step: "produce", + status: "succeeded" +} as const; +const stateSuccess = { + schema_version: "1", + ok: true, + value: { path: "phases/3/result.json", revision: 3, status: "succeeded" } +} as const; + +interface ClassificationFixtures { + readonly not_object: readonly unknown[]; + readonly missing_schema_version: unknown; + readonly invalid_schema_versions: readonly unknown[]; + readonly unsupported_schema_version: string; + readonly version_one_but_invalid: unknown; +} + +async function loadClassificationFixtures(): Promise { + return JSON.parse(await readFile(new URL("../fixtures/mcp/boundary/input-classification.json", import.meta.url), "utf8")) as ClassificationFixtures; +} + +function context(invocationId = "boundary-correlation-1"): InvocationContext { + const connection = connectionContextFactory.captureStartup({ + connection_id: `connection-${invocationId}`, + startup_repository_candidate: { working_directory: "/repo" } + }).initialize({ + client: { name: "test-client", version: "1" }, + host: "codex", + protocol_version: "2025-11-25" + }); + return createInvocationContext(connection, { + invocation_id: invocationId, + transport_metadata: { request_id: `request-${invocationId}`, operation: "tools/call" } + }, new AbortController().signal); +} + +function expectProjectFailure( + outcome: ToolBoundaryOutcome, + tool: "archflow_state", + code: string, + parameters: Readonly> +): void { + expect(outcome.kind).toBe("project-result"); + if (outcome.kind !== "project-result") throw new Error("expected project result"); + expect(outcome.tool).toBe(tool); + expect(outcome.result.ok).toBe(false); + if (outcome.result.ok) throw new Error("expected project failure"); + expect(outcome.result.error.code).toBe(code); + expect(outcome.result.error.diagnostic.parameters).toEqual(parameters); + expect(Object.isFrozen(outcome)).toBe(true); + expect(Object.isFrozen(outcome.result)).toBe(true); + expect(Object.isFrozen(outcome.result.error)).toBe(true); + expect(Object.isFrozen(outcome.result.error.diagnostic)).toBe(true); + expect(Object.isFrozen(outcome.result.error.diagnostic.parameters)).toBe(true); + expect(() => assertAuthenticToolBoundaryOutcome(outcome)).not.toThrow(); +} + +describe("SDK-free MCP tool boundary", () => { + it("copies and authenticates protocol errors without mutating the source", () => { + const source = createProtocolError("TOOL_DISABLED", { + tool: "archflow_state", + lifecycle_state: "inert-no-handler" + }); + const authenticated = authenticateProtocolError(source); + expect(authenticated.value).toEqual(source); + expect(authenticated.value).not.toBe(source); + expect(Object.isFrozen(authenticated)).toBe(true); + expect(Object.isFrozen(authenticated.value)).toBe(true); + expect(Object.isFrozen(authenticated.value.diagnostic.parameters)).toBe(true); + expect(() => authenticateProtocolError({ ...authenticated })).toThrow(); + expect(() => authenticateProtocolError({ ...source, retryable: true })).toThrow(); + }); + + it("authenticates and freezes boundaries while copied registries ignore later mutation", async () => { + const handlers = { + archflow_state: () => stateSuccess + }; + const boundary = createToolBoundary(handlers); + handlers.archflow_state = () => { throw new Error("replacement must not run"); }; + + expect(Object.isFrozen(boundary)).toBe(true); + expect(Object.isFrozen(boundary.invoke)).toBe(true); + expect(() => assertAuthenticToolBoundary(boundary)).not.toThrow(); + expect(() => assertAuthenticToolBoundary({ ...boundary })).toThrow(/authentic tool boundary/); + expect(() => assertAuthenticToolBoundary({ invoke: boundary.invoke })).toThrow(/authentic tool boundary/); + const outcome = await boundary.invoke("archflow_state", stateInput, context()); + expect(outcome.kind).toBe("project-result"); + if (outcome.kind === "project-result") expect(outcome.result.ok).toBe(true); + }); + + it("rejects invalid registry surfaces without reading accessors", () => { + let getterCalls = 0; + const accessor = Object.defineProperty({}, "archflow_state", { + enumerable: true, + get() { getterCalls += 1; return () => stateSuccess; } + }); + expect(() => createToolBoundary(accessor as never)).toThrow(/data properties/); + expect(getterCalls).toBe(0); + expect(() => createToolBoundary({ unknown_tool: () => stateSuccess } as never)).toThrow(/unknown tool/); + expect(() => createToolBoundary({ archflow_state: 1 } as never)).toThrow(/functions/); + }); + + it("requires a string name and an authentic invocation context", async () => { + const boundary = createToolBoundary({}); + const authentic = context("boundary-auth-1"); + await expect(boundary.invoke(1 as never, {}, authentic)).rejects.toThrow(/string tool name/); + await expect(boundary.invoke("unknown", {}, { ...authentic } as never)).rejects.toThrow(/authentic invocation/); + await expect(boundary.invoke("unknown", {}, { + invocation_id: authentic.invocation_id, + connection: authentic.connection, + signal: authentic.signal, + transport_metadata: authentic.transport_metadata + } as never)).rejects.toThrow(/authentic invocation/); + }); + + it("returns exact authenticated protocol outcomes for unknown and disabled tools", async () => { + const boundary = createToolBoundary({}); + const invocation = context("boundary-protocol-1"); + const unknown = await boundary.invoke("Ü\u0000tool", { secret: "arguments are irrelevant" }, invocation); + expect(unknown).toMatchObject({ + kind: "protocol-error", + error: { + value: { + code: "TOOL_NOT_FOUND", + diagnostic: { + parameters: { tool_name_digest: "cc0ce9406e03db1f4ade8582fb75373ed26e9cf7bc19cb496b548fc3aab0cd21" } + } + } + } + }); + expect(JSON.stringify(unknown)).not.toContain("Ü"); + expect(Object.isFrozen(unknown)).toBe(true); + if (unknown.kind !== "protocol-error") throw new Error("expected protocol outcome"); + expect(Object.isFrozen(unknown.error)).toBe(true); + expect(Object.isFrozen(unknown.error.value.diagnostic.parameters)).toBe(true); + expect(() => assertAuthenticToolBoundaryOutcome(unknown)).not.toThrow(); + + const disabled = await boundary.invoke("archflow_gate", null, invocation); + expect(disabled).toMatchObject({ + kind: "protocol-error", + error: { + value: { + code: "TOOL_DISABLED", + diagnostic: { parameters: { tool: "archflow_gate", lifecycle_state: "inert-no-handler" } } + } + } + }); + expect(() => assertAuthenticToolBoundaryOutcome({ ...disabled })).toThrow(/authentic tool boundary outcome/); + expect(() => assertAuthenticToolBoundaryOutcome(structuredClone(disabled) as never)).toThrow(/authentic tool boundary outcome/); + }); + + it("classifies every known-tool argument failure before calling the handler", async () => { + const fixtures = await loadClassificationFixtures(); + let calls = 0; + const boundary = createToolBoundary({ archflow_state: () => { calls += 1; return stateSuccess; } }); + const invocation = context("boundary-input-1"); + + for (const candidate of fixtures.not_object) { + expectProjectFailure(await boundary.invoke("archflow_state", candidate, invocation), "archflow_state", "CONTRACT_INVALID", { + tool: "archflow_state", issue_code: "input-not-object" + }); + } + const nonPlain: readonly unknown[] = [ + new Map(), + Object.create({ schema_version: "1" }), + { schema_version: "1", nested: undefined }, + Object.defineProperty({}, "schema_version", { enumerable: true, get: () => "1" }), + (() => { const value: Record = { schema_version: "1" }; value.self = value; return value; })() + ]; + for (const candidate of nonPlain) { + expectProjectFailure(await boundary.invoke("archflow_state", candidate, invocation), "archflow_state", "CONTRACT_INVALID", { + tool: "archflow_state", issue_code: "input-not-object" + }); + } + expectProjectFailure(await boundary.invoke("archflow_state", fixtures.missing_schema_version, invocation), "archflow_state", "CONTRACT_INVALID", { + tool: "archflow_state", issue_code: "schema-version-missing" + }); + for (const schema_version of fixtures.invalid_schema_versions) { + expectProjectFailure(await boundary.invoke("archflow_state", { schema_version }, invocation), "archflow_state", "CONTRACT_INVALID", { + tool: "archflow_state", issue_code: "schema-version-invalid" + }); + } + expectProjectFailure(await boundary.invoke("archflow_state", { schema_version: fixtures.unsupported_schema_version }, invocation), "archflow_state", "CONTRACT_VERSION_UNSUPPORTED", { + schema_version: fixtures.unsupported_schema_version, supported_version: "1" + }); + expectProjectFailure(await boundary.invoke("archflow_state", fixtures.version_one_but_invalid, invocation), "archflow_state", "CONTRACT_INVALID", { + tool: "archflow_state", issue_code: "input-invalid" + }); + expect(calls).toBe(0); + }); + + it("calls a valid handler once and deeply freezes an authenticated correlated success", async () => { + let calls = 0; + const boundary = createToolBoundary({ + archflow_state: (call, invocation) => { + calls += 1; + expect(call.name).toBe("archflow_state"); + expect(call.input.status).toBe("succeeded"); + expect(invocation.invocation_id).toBe("boundary-success-1"); + return stateSuccess; + } + }); + const outcome = await boundary.invoke("archflow_state", stateInput, context("boundary-success-1")); + expect(calls).toBe(1); + expect(outcome).toMatchObject({ kind: "project-result", tool: "archflow_state", result: stateSuccess }); + expect(Object.isFrozen(outcome)).toBe(true); + if (outcome.kind !== "project-result" || !outcome.result.ok) throw new Error("expected success"); + expect(Object.isFrozen(outcome.result)).toBe(true); + expect(Object.isFrozen(outcome.result.value)).toBe(true); + expect(() => assertAuthenticToolBoundaryOutcome(outcome)).not.toThrow(); + expect(() => assertAuthenticToolBoundaryOutcome({ ...outcome })).toThrow(/authentic tool boundary outcome/); + expect(() => assertAuthenticToolBoundaryOutcome({ kind: "project-result", tool: "archflow_state", result: outcome.result })).toThrow(/authentic tool boundary outcome/); + }); + + it("accepts a closed tool-neutral failure returned on a known path", async () => { + const returned = { + schema_version: "1", + ok: false, + error: createProjectError("WORKFLOW_INVALID", { issue_code: "workflow-broken" }) + } as const; + const boundary = createToolBoundary({ archflow_state: () => returned }); + const outcome = await boundary.invoke("archflow_state", stateInput, context("boundary-failure-1")); + expectProjectFailure(outcome, "archflow_state", "WORKFLOW_INVALID", { issue_code: "workflow-broken" }); + if (outcome.kind === "project-result" && !outcome.result.ok) { + expect(outcome.result).not.toBe(returned); + expect(outcome.result.error).not.toBe(returned.error); + } + }); + + it("accepts matching and neutral failure bindings but contains cross-tool substitutions", async () => { + const cases = [ + { + label: "contract-neutral", + returned: { schema_version: "1", ok: false, error: createProjectError("CONTRACT_INVALID", { issue_code: "input-invalid" }) }, + expectedCode: "CONTRACT_INVALID", + expectedParameters: { issue_code: "input-invalid" } + }, + { + label: "contract-matching", + returned: { schema_version: "1", ok: false, error: createProjectError("CONTRACT_INVALID", { tool: "archflow_state", issue_code: "input-invalid" }) }, + expectedCode: "CONTRACT_INVALID", + expectedParameters: { tool: "archflow_state", issue_code: "input-invalid" } + }, + { + label: "result-matching", + returned: { schema_version: "1", ok: false, error: createProjectError("RESULT_INVALID", { tool: "archflow_state", result_id: "result-1" }) }, + expectedCode: "RESULT_INVALID", + expectedParameters: { tool: "archflow_state", result_id: "result-1" } + } + ] as const; + for (const item of cases) { + let calls = 0; + const boundary = createToolBoundary({ archflow_state: () => { calls += 1; return item.returned; } }); + const outcome = await boundary.invoke("archflow_state", stateInput, context(`boundary-binding-${item.label}`)); + expect(calls).toBe(1); + expectProjectFailure(outcome, "archflow_state", item.expectedCode, item.expectedParameters); + } + + for (const item of [ + { label: "contract", returned: { schema_version: "1", ok: false, error: createProjectError("CONTRACT_INVALID", { tool: "archflow_gate", issue_code: "input-invalid" }) } }, + { label: "result", returned: { schema_version: "1", ok: false, error: createProjectError("RESULT_INVALID", { tool: "archflow_gate", result_id: "result-1" }) } }, + { + label: "result-required-tool-missing", + returned: (() => { + const error = createProjectError("RESULT_INVALID", { tool: "archflow_state", result_id: "result-1" }); + return { schema_version: "1", ok: false, error: { ...error, diagnostic: { ...error.diagnostic, parameters: { result_id: "result-1" } } } }; + })() + } + ] as const) { + let calls = 0; + const boundary = createToolBoundary({ archflow_state: () => { calls += 1; return item.returned; } }); + const invocationId = `boundary-cross-tool-${item.label}`; + const outcome = await boundary.invoke("archflow_state", stateInput, context(invocationId)); + expect(calls).toBe(1); + expectProjectFailure(outcome, "archflow_state", "INTERNAL_ERROR", { correlation_id: invocationId }); + expect(JSON.stringify(outcome)).not.toContain("archflow_gate"); + } + }); + + it("reduces malformed, substituted, thrown, and rejected handler results to correlation-only internal errors", async () => { + const cases = [ + { label: "malformed", handler: () => ({ schema_version: "1", ok: true, value: { secret: "handler prose" } }) }, + { label: "cross-tool", handler: () => ({ schema_version: "1", ok: true, value: { path: "phases/3/review.md", verdict: "pass", blocking_count: 0, revision: 3 } }) }, + { label: "throw", handler: () => { throw new Error("raw synchronous secret"); } }, + { label: "reject", handler: async () => { throw new Error("raw asynchronous secret"); } } + ] as const; + for (const item of cases) { + let calls = 0; + const boundary = createToolBoundary({ archflow_state: () => { calls += 1; return item.handler(); } }); + const invocationId = `boundary-internal-${item.label}`; + const outcome = await boundary.invoke("archflow_state", stateInput, context(invocationId)); + expect(calls).toBe(1); + expectProjectFailure(outcome, "archflow_state", "INTERNAL_ERROR", { correlation_id: invocationId }); + const serialized = JSON.stringify(outcome); + expect(serialized).not.toContain("secret"); + expect(serialized).not.toContain("handler prose"); + } + }); +}); diff --git a/test/unit/mcp-tools.test.ts b/test/unit/mcp-tools.test.ts index b5c7b472..bcb22f0e 100644 --- a/test/unit/mcp-tools.test.ts +++ b/test/unit/mcp-tools.test.ts @@ -1,7 +1,10 @@ import { describe, expect, it } from "vitest"; +import * as publicContracts from "../../src/contracts/index.js"; +import { createProjectError } from "../../src/contracts/errors.js"; import { parseSha256Digest } from "../../src/contracts/evidence.js"; -import { bindParsedToolCallRequest, correlateProjectResult, createInternalResultExpectation, parseToolCall, TOOL_DEFINITIONS, validateProjectResultStructure } from "../../src/contracts/mcp-tools.js"; +import { bindParsedToolCallRequest, correlateProjectResult, createInternalResultExpectation, parseToolCall, TOOL_DEFINITIONS, validateProjectFailureStructure, validateProjectResultStructure } from "../../src/contracts/mcp-tools.js"; import { parseTaskPathClaim } from "../../src/contracts/path-claims.js"; +import { TOOL_NAMES } from "../../src/contracts/tool-names.js"; const digest = parseSha256Digest("a".repeat(64)); const stateInput = { schema_version: "1", task_id: "task-1", intent_id: "intent-1", expected_revision: 2, input_fingerprint: digest, phase_instance: "phase-impl-2", step: "produce", status: "succeeded" } as const; @@ -33,6 +36,88 @@ describe("correlated MCP tool contracts", () => { expect(() => correlateProjectResult({ ...call }, expectation, structural)).toThrow(/authentic/); }); + it("authenticates only copied, closed failure results for known tools", () => { + const source = { + schema_version: "1", + ok: false, + error: createProjectError("CONTRACT_INVALID", { issue_code: "input-invalid" }), + } as const; + for (const name of TOOL_NAMES) { + const result = validateProjectFailureStructure(name, source); + expect(result).not.toBe(source); + expect(result).toMatchObject(source); + if (result.ok) throw new Error("failure validator minted a success"); + expect(result.error).not.toBe(source.error); + expect(result.error.diagnostic.parameters).not.toBe(source.error.diagnostic.parameters); + expect(Object.isFrozen(result)).toBe(true); + expect(Object.isFrozen(result.error)).toBe(true); + expect(Object.isFrozen(result.error.diagnostic)).toBe(true); + expect(Object.isFrozen(result.error.diagnostic.parameters)).toBe(true); + } + expect(() => validateProjectFailureStructure("archflow_state", { schema_version: "1", ok: true, value: {} })).toThrow(); + expect(() => validateProjectFailureStructure("archflow_state", { ...source, extra: true })).toThrow(); + expect(() => validateProjectFailureStructure("not-a-tool" as never, source)).toThrow(/unknown tool/); + expect(() => validateProjectFailureStructure("archflow_state", new Map())).toThrow(); + expect(publicContracts.validateProjectFailureStructure).toBe(validateProjectFailureStructure); + }); + + it("correlates optional and required diagnostic tool bindings in both structural validators", () => { + const call = parseToolCall("archflow_state", stateInput); + const neutralContractFailure = { + schema_version: "1", + ok: false, + error: createProjectError("CONTRACT_INVALID", { issue_code: "input-invalid" }) + } as const; + const matchingContractFailure = { + schema_version: "1", + ok: false, + error: createProjectError("CONTRACT_INVALID", { tool: "archflow_state", issue_code: "input-invalid" }) + } as const; + const crossToolContractFailure = { + schema_version: "1", + ok: false, + error: createProjectError("CONTRACT_INVALID", { tool: "archflow_gate", issue_code: "input-invalid" }) + } as const; + const matchingResultFailure = { + schema_version: "1", + ok: false, + error: createProjectError("RESULT_INVALID", { tool: "archflow_state", result_id: "result-1" }) + } as const; + const crossToolResultFailure = { + schema_version: "1", + ok: false, + error: createProjectError("RESULT_INVALID", { tool: "archflow_gate", result_id: "result-1" }) + } as const; + + for (const candidate of [neutralContractFailure, matchingContractFailure, matchingResultFailure]) { + expect(validateProjectFailureStructure("archflow_state", candidate).ok).toBe(false); + expect(validateProjectResultStructure(call, candidate).ok).toBe(false); + } + for (const candidate of [crossToolContractFailure, crossToolResultFailure]) { + expect(() => validateProjectFailureStructure("archflow_state", candidate)).toThrow(/tool mismatch/); + expect(() => validateProjectResultStructure(call, candidate)).toThrow(/tool mismatch/); + } + const toolNeutralResultFailure = { + schema_version: "1", + ok: false, + error: { ...matchingResultFailure.error, diagnostic: { ...matchingResultFailure.error.diagnostic, parameters: { result_id: "result-1" } } } + } as const; + expect(() => validateProjectFailureStructure("archflow_state", toolNeutralResultFailure)).toThrow(); + expect(() => validateProjectResultStructure(call, toolNeutralResultFailure)).toThrow(); + }); + + it("registers failure authenticity without allowing spread clones or tool substitution", () => { + const call = bindParsedToolCallRequest(parseToolCall("archflow_state", stateInput), parseSha256Digest("b".repeat(64))); + const success = { path: parseTaskPathClaim("phases/2/result.json"), revision: 3, status: "succeeded" } as const; + const expectation = createInternalResultExpectation({ schema_version: "1", tool: "archflow_state", task_id: "task-1", intent_id: "intent-1", input_fingerprint: digest, request_digest: parseSha256Digest("b".repeat(64)), result_id: "result-1", resulting_revision: 3, success }); + const source = { schema_version: "1", ok: false, error: createProjectError("INTERNAL_ERROR", { correlation_id: "correlation-1" }) } as const; + const failure = validateProjectFailureStructure("archflow_state", source); + expect(correlateProjectResult(call, expectation, failure)).toBe(failure); + expect(() => correlateProjectResult(call, expectation, { ...failure } as never)).toThrow(/authentic/); + const substituted = validateProjectFailureStructure("archflow_counter_review", source); + expect(() => correlateProjectResult(call, expectation, substituted as never)).toThrow(/tool mismatch/); + }); + it("uses the authoritative exact current-evidence tuple parser for gates", () => { const self = { role: "self-review", evidence_digest: "1".repeat(64), assurance: "agent-declared", producer_family: "claude", reviewer_family: "claude", independence: "same-family-self" }; const counter = { role: "counter-review", evidence_digest: "2".repeat(64), assurance: "server-attested", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family" }; @@ -43,6 +128,117 @@ describe("correlated MCP tool contracts", () => { expect(() => parseToolCall("archflow_gate", { ...base, current_evidence: { ...base.current_evidence, slots: [self, { ...counter, reviewer_family: "claude" }] } })).toThrow(); }); + it("revalidates gate success decisions against the authentic call context", () => { + const ruleA = { rule_id: "Rule:A", rule_version: 1 } as const; + const ruleB = { rule_id: "Rule:B", rule_version: 1 } as const; + const self = { role: "self-review", evidence_digest: "1".repeat(64), assurance: "agent-declared", producer_family: "claude", reviewer_family: "claude", independence: "same-family-self" } as const; + const counter = { role: "counter-review", evidence_digest: "2".repeat(64), assurance: "server-attested", producer_family: "claude", reviewer_family: "codex", independence: "opposite-family" } as const; + const commonInput = { + schema_version: "1", + task_id: "Task:1", + intent_id: "Intent:1", + expected_revision: 0, + input_fingerprint: digest, + phase_instance: "phase-impl-2", + summary: "Review", + subject_digest: digest, + current_evidence: { set_digest: "3".repeat(64), slots: [self, counter] } + } as const; + const humanProvenance = { + schema_version: "1", + actor_class: "human", + assurance: "declared-local-trace", + channel: "archflow-local", + decision_event_id: "Decision:1", + helper_invocation_id: "Helper:1", + recorded_at: "2026-07-27T12:00:00.000Z" + } as const; + const envelope = (kind: string, payload: Readonly>) => ({ + schema_version: "1", + gate_id: "Gate:1", + task_id: commonInput.task_id, + phase_instance: commonInput.phase_instance, + subject_digest: commonInput.subject_digest, + context_digest: "4".repeat(64), + human_provenance: humanProvenance, + kind, + payload + }); + const result = (kind: string, payload: Readonly>) => ({ + schema_version: "1", + ok: true, + value: { kind, decision: envelope(kind, payload), notes: payload.reason, revision: 1 } + }); + + const reviewCall = parseToolCall("archflow_gate", { + ...commonInput, + kind: "review-trigger", + context: { + matched_rules: [ruleA, ruleB], + uncertain_rules: [], + eligible_waiver_rules: [ruleA], + waiver_scope: { operation: "review-trigger", boundary: "subject" } + } + }); + expect(validateProjectResultStructure(reviewCall, result("review-trigger", { + decision: "waiver-requested", reason: "Eligible exception", rule: ruleA, rationale: "Temporary" + })).ok).toBe(true); + expect(() => validateProjectResultStructure(reviewCall, result("review-trigger", { + decision: "waiver-requested", reason: "Ineligible exception", rule: ruleB, rationale: "Temporary" + }))).toThrow(/eligible/); + + const adjudicationCall = parseToolCall("archflow_gate", { + ...commonInput, + kind: "adjudication-failure", + context: { + constitution: "fail", + failed_rules: [ruleA, ruleB], + uncertain_rules: [], + eligible_waiver_rules: [], + waiver_scope: { operation: "adjudication-failure", boundary: "phase" } + } + }); + const validResolutions = [ + { rule: ruleA, resolution: "Accepted mitigation A" }, + { rule: ruleB, resolution: "Accepted mitigation B" } + ] as const; + expect(validateProjectResultStructure(adjudicationCall, result("adjudication-failure", { + decision: "approve", reason: "Resolved", resolutions: validResolutions + })).ok).toBe(true); + expect(() => validateProjectResultStructure(adjudicationCall, result("adjudication-failure", { + decision: "approve", reason: "Incomplete", resolutions: validResolutions.slice(0, 1) + }))).toThrow(/resolutions/); + expect(() => validateProjectResultStructure(adjudicationCall, result("adjudication-failure", { + decision: "approve", reason: "Unsorted", resolutions: [...validResolutions].reverse() + }))).toThrow(/resolutions/); + + const authority = { + link_digest: "5".repeat(64), + purpose: "restore-adoption", + proposed_generation_digest: "6".repeat(64), + changed_input_fingerprint: "7".repeat(64) + } as const; + const restoreCall = parseToolCall("archflow_gate", { + ...commonInput, + kind: "restore-collision", + context: { + path: "task/file.md", + recorded_generation_digest: "8".repeat(64), + current_generation_digest: "9".repeat(64), + adoption_candidate: authority + } + }); + expect(validateProjectResultStructure(restoreCall, result("restore-collision", { + decision: "adopt-as-new-generation", reason: "Adopt", adoption_authority: authority, rationale: "Reviewed" + })).ok).toBe(true); + expect(() => validateProjectResultStructure(restoreCall, result("restore-collision", { + decision: "adopt-as-new-generation", + reason: "Adopt mismatched", + adoption_authority: { ...authority, link_digest: "a".repeat(64) }, + rationale: "Reviewed" + }))).toThrow(/authority/); + }); + it("enforces waiver origin identity and canonical UTC-millisecond provenance", () => { const origin = { origin_gate_id: "Gate:1", origin_decision_digest: "1".repeat(64), origin_context_digest: "2".repeat(64), task_id: "Task_1", phase_instance: "phase-impl-2", subject_digest: "3".repeat(64), current_evidence_set_digest: "4".repeat(64), rule: { rule_id: "Rule:1", rule_version: 1 }, scope: { operation: "review-trigger", boundary: "subject" } }; const input = { schema_version: "1", task_id: "Task_1", intent_id: "Intent:1", expected_revision: 0, input_fingerprint: digest, origin, rationale: "Needed" }; From 682d9c622e747101db8e950ac688993169049f12 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 16:56:19 -0500 Subject: [PATCH 011/124] Document prototype engineering priorities Make simplicity, working behavior, maintainability, and proportional verification the default. Discourage speculative release, compliance, and abstraction machinery while preserving ArchFlow's human trust boundaries. --- CLAUDE.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index 0c7f3bef..2213ef25 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,6 +46,30 @@ All working files live in `.archflow/`. Tracked in git during development to pre Installs the shared skills to `~/.claude/skills/` and `~/.agents/skills/` for global availability. +## Engineering Priorities + +ArchFlow is an open-source prototype. Optimize for a useful, working, maintainable implementation—not hypothetical production, commercial, monetization, or release requirements. + +Use this priority order when making tradeoffs: + +1. Make the current user workflow work. +2. Choose the simplest design that meets the current requirement. +3. Keep the code readable, maintainable, and easy to change. +4. Add tests and safeguards proportional to the real risk. +5. Pursue exhaustive correctness, generality, or release polish only when the user explicitly asks for it or a demonstrated blocker requires it. + +Default guidance: + +- Prefer direct code and existing patterns over new abstractions, frameworks, layers, registries, or generalized machinery. +- Do not build for speculative future requirements. Avoid compatibility layers, migration systems, extension points, exhaustive matrices, and release infrastructure until they are actually needed. +- Validate important boundaries and representative failure cases, but do not attempt to prove every theoretical permutation. Tests should buy confidence, not completeness for its own sake. +- Treat licensing proportionally. Respect licenses and obvious attribution obligations, but default to package metadata and ordinary notices. Do not audit every file, build forensic license validators, or create release-grade legal inventories unless distribution makes them necessary, the user requests them, or a concrete legal issue blocks the prototype. +- A documented limitation or TODO is often better than a large subsystem. Prefer a reversible simple decision over an elaborate attempt to eliminate all uncertainty. +- Existing plans are revisable. If a planned phase is disproportionate to prototype goals, propose a simpler scope at the next design/review gate instead of implementing complexity merely because an older document mentions it. +- Before adding substantial complexity, explain the concrete current problem it solves and ask the user when the tradeoff materially expands scope. + +Working and maintainable beats perfect. Simplicity does not override the human trust boundaries below, but those boundaries should be implemented with the least machinery that reliably preserves them. + ## Design Principles ArchFlow is written for models that keep improving. Skills must encode *intent and trust boundaries*, not workarounds for model weaknesses — workarounds become ceilings as models get better. When writing or editing any skill, apply this litmus test to every rule: **is it here because the model used to be bad at something, or because the human needs it?** Only the second kind gets "never/must/exact" language. From 13a413a7923f0d046902c44348d68be8f421d4fb Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 18:09:37 -0500 Subject: [PATCH 012/124] MCP Integration: Design Phase 4 --- .../tasks/mcp-integration/architecture.md | 30 +-- ...arded-mcp-runtime-and-sdk-compatibility.md | 200 ++++++++++++++++++ .../reviews/phase-4-design-counter-review.md | 89 ++++++++ 3 files changed, 306 insertions(+), 13 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-4-design-counter-review.md diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index 2ccff01e..67affc59 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -86,11 +86,15 @@ package-lock.json tsconfig.json vitest.config.ts src/ - main.ts # stdio entry; protocol-only stdout + main.ts # thin real-process binding; protocol-only stdout mcp/ - server.ts # MCP v2 lifecycle and connection context + server.ts # SDK-free authenticated tool boundary tools.ts # exactly five registrations - sdk-adapter.ts # beta SDK isolation seam + framing.ts # strict bounded SDK-free JSONL byte framer + session.ts # SDK-free lifecycle, routing, IDs, and request records + send-queue.ts # bounded FIFO and caller-stream write ownership + sdk-adapter.ts # sole beta SDK import; Server/Transport isolation + process-runner.ts # SDK-free termination, diagnostics, and exit arbitration local/ cli.ts # archflow-local command surface operations.ts # shared validation/reconcile/manual operations @@ -458,20 +462,20 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali **Depends on**: Phase 3 -**Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28, REQ-33 +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28 -**Scope**: Isolate the deprecated low-level SDK `Server` as a documented advanced-use exception wholly inside `src/mcp/sdk-adapter.ts`, starting with a stop-on-failure public-hook compatibility gate. Intercept ingress before SDK validation or identity mutation with method-aware lifecycle and request maps, singleton `2025-11-25` negotiation, alternate-version counter-offer, initialize-cancellation suppression, repeated/concurrent initialization rejection, and exact client-metadata projection/context-mint ordering through direct imports of Phase 3's `connectionContextFactory` and `createInvocationContext` seams. Own external/internal request-ID mapping, normalize numeric `-0` to `0`, treat concurrent `-0`/`0` as duplicate reuse, and route cancellation without fabricated success. Pin pre-SDK `tools/call` precedence for malformed outer calls, unknown names, known malformed arguments, and the three protocol/project/SDK error domains; absent or empty `tools/list` params return the fixed catalogue without `nextCursor`, while any present cursor returns fixed bounded `-32602 Invalid params`. Own stdio through an adapter-owned cancellable `Writable` bridge with scoped close guarantees: after `CLOSING` no new destination write occurs, already accepted caller-stream bytes may flush, SDK-facing listeners are removed without destroying the caller stream, and never-settling or late handlers cannot emit post-close frames. Add `src/main.ts`, process/signal ownership, stdout/stderr purity, and adversarial live fixtures. Stop for architecture review if public hooks cannot prove the contract. +**Scope**: Isolate the deprecated low-level SDK `Server` as a documented advanced-use exception wholly inside `src/mcp/sdk-adapter.ts`, beginning and ending with live currency/public-hook gates. Repair the SDK-free `src/mcp/server.ts` seam so known-tool arguments are classified before handler availability while unknown-name precedence remains fixed. Split raw strict/bounded JSONL framing, session lifecycle/routing, session-lifetime seen-ID and monotonic internal-ID ownership, universal bounded output FIFO, and process termination into SDK-free modules. Construct the exact low-level server identity/capability/handler/connect sequence behind a public `Transport` facade; make SDK initialize validation transactional, pin singleton `2025-11-25` counter-offer behavior, context-mint ordering, cancellation tombstones, and a closed request/notification/response routing table. Normalize numeric `-0` to `0` and reject every previously seen request ID for the entire session—response/cancellation/rejection “reuse” fixtures prove rejection, never legal reuse. Reject unknown top-level request members and unknown method-parameter keys before SDK stripping. For list/call, preserve permitted `_meta` and legacy `task` only for SDK validation/lifting and exclude them from ArchFlow boundary input. Missing call arguments are SDK-valid and pass unchanged; use the exact surrogate only for a present non-object argument, while unchanged objects reach the boundary as sole semantic authority. Retain authentic boundary outcomes across SDK projection so the facade restores exact ArchFlow protocol codes, and keep protocol/project/SDK domains byte-stable. Bound ingress/output/ID state, pause input under backpressure, expose runtime termination to an SDK-free process runner, and add a thin inert `src/main.ts`. Phase 4 only preserves/projects already-authenticated outcomes; model-result validation remains later. Stop for architecture review on dependency/API drift or any failed public-hook invariant. **Success Criteria**: -- [ ] A public-hook compatibility gate proves outer validation interception, initialize cancellation, repeated/concurrent guard-before-SDK precedence, `-0`/`0` identity behavior, stream interception, and permanently backpressured teardown; inability to prove any required invariant stops implementation rather than adding a private-SDK patch. -- [ ] The deprecated low-level `Server` import and every SDK/transport-owned type remain isolated inside the adapter. The adapter consumes Phase 3's frozen SDK-free seam without weakening it, and initialization guards run before any SDK identity or lifecycle mutation. -- [ ] Unsupported versions receive the alternate-version counter-offer; repeated or concurrent initialization cannot mutate SDK identity; cancellation targeting active `initialize` is ignored without releasing its mapping; startup capture, initialize response, one `initialized` connection mint, and per-call invocation creation occur in the pinned order with exact `{name, version}` projection. -- [ ] External/internal ID mapping preserves legal string/numeric identities except that numeric `-0` normalizes to `0`; concurrent `-0`/`0` is duplicate numeric reuse. Live response, cancellation, collision, and reuse fixtures cover all beta.5 request-ID cases. -- [ ] Missing `tools/call` params or missing/non-string name, and unknown names paired with malformed arguments, return fixed bounded SDK-domain `-32602`; known names with missing/non-object/invalid arguments reach the frozen boundary's `CONTRACT_*` classification; unknown names with structurally valid arguments return `TOOL_NOT_FOUND`. Protocol errors, project results, and SDK errors remain distinct and byte-stable. -- [ ] Post-`READY` `tools/list` accepts absent or empty params and returns the full fixed catalogue without `nextCursor`; any present cursor, including `""`, returns fixed bounded `-32602 Invalid params`, echoes no cursor, and invokes neither catalogue nor tool boundary. -- [ ] The adapter-owned cancellable `Writable` bridge leaves no owned listener or pending send after close, performs no new destination write after `CLOSING`, allows only caller-stream bytes already accepted before close to flush, and never destroys the caller-owned stream. Never-settling and late handlers, cancellation, signals, backpressure, and close races emit no post-close frame or business side effect. -- [ ] `src/main.ts` produces a runnable inert stdio server with exactly five listed tools and disabled injected handlers; actual-process and both-Node-version fixtures cover negotiation, list/call/error/cancel races, safe stderr diagnostics, stdout purity, signal shutdown, and handle/listener cleanup without persistence, dispatch, or a tracked release bundle. +- [ ] Live currency/public API gates run before mutation and immediately before final verification; drift or any failed facade/initialize/projection/teardown invariant stops without dependency mutation or private workaround. +- [ ] `src/mcp/server.ts` classifies known arguments before handler availability; missing arguments pass unchanged, only present non-object arguments use a surrogate, and object semantics retain one boundary authority across inert and enabled fixtures. +- [ ] Exact `Server({name:"archflow-mcp",version:"0.0.0"})`, singleton versions, `registerCapabilities({tools:{}})`, two tool handlers, then facade connection produce pinned initialize bytes and transactional malformed-retry/success behavior. +- [ ] Strict bounded framing, lifetime seen-ID rejection, monotonic non-recycled internal IDs, cancellation tombstones, and the closed initialize/ping/list/call/notification/response table enforce all lifecycle and same-chunk races without unbounded state. “Reuse” fixtures assert rejection after every terminal path. +- [ ] The exact request/list/call member allowlists reject unknown keys before SDK stripping; permitted `_meta`/legacy `task` are SDK-only inputs; missing/present-non-object/object argument routes reach `CONTRACT_*`, `TOOL_NOT_FOUND`, or `TOOL_DISABLED` exactly. Retained authentic outcomes restore all ArchFlow mappings despite SDK rewriting, while project/SDK/direct/fallback bytes remain distinct and bounded. +- [ ] The universal capped FIFO separates write admission, callback completion, and backpressure; pauses/resumes ingress, rejects all entries on close, performs no adapter-owned state/output effect after `CLOSING`, quarantines late results, and never destroys caller streams. Injected handlers must honor `AbortSignal`. +- [ ] The runtime exposes SDK-free termination to the process runner; `src/main.ts` is a thin inert binding with exact stdout, diagnostics, exit, signal, and cleanup behavior. +- [ ] Focused and live fixtures pass on Node `24.15.0` and `24.18.0` without a new dependency, schema, tracked release output, persistence, dispatch, model-result authority, or REQ-33 completion claim. ### Phase 5: Offline Bundle and Release Integrity diff --git a/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility.md b/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility.md new file mode 100644 index 00000000..fa292cec --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility.md @@ -0,0 +1,200 @@ +# Phase 4: Guarded MCP Runtime and SDK Compatibility + +**Status**: DESIGNED +**Task**: mcp-integration +**Goal**: Consume Phase 3's authenticated seam to implement and prove the complete inert low-level beta.5 stdio runtime. +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28 + +## Context + +Phases 1–3 established the exact dependencies, durable/MCP contracts, five-tool catalogue, authentic connection and invocation contexts, and SDK-free authenticated tool boundary. Phase 4 is the first runnable MCP phase. It preserves and projects already-authenticated outcomes; full model-result production and validation remain in later dispatch/assembly phases, so this phase does not claim REQ-33. + +The target is protocol `2025-11-25` with exact `@modelcontextprotocol/server@2.0.0-beta.5` and locked core beta.5. Both were current and MIT on 2026-07-27, but v2 remains beta. Live dist tags, official guidance, and every required public API are checked before the first implementation mutation and again immediately before final verification/review. Any tag, stable-status, guidance, or public-surface drift stops for design/architecture review without package mutation; no continuous polling is required. Low-level `Server` is a documented advanced-use exception and `src/mcp/sdk-adapter.ts` is the sole production SDK import owner. Raw framing, session policy, output queueing, and process ownership are separate SDK-free modules using Node streams only; there is no SDK stdio/framing owner, private import/patch, or new framing dependency. + +Phase 4 also repairs the Phase 3 boundary in `src/mcp/server.ts`: unknown names keep existing name-first `TOOL_NOT_FOUND` precedence, but known-tool arguments are classified before handler availability. Thus malformed known inputs produce `CONTRACT_*` even with the inert registry, while a valid known call with no handler produces `TOOL_DISABLED`. Missing `tools/call.arguments` is SDK-valid and passes unchanged; the boundary receives the tagged missing candidate as `undefined` and classifies a known tool as `input-not-object`. The adapter substitutes only a present non-object `arguments` value that the SDK would reject; object arguments pass unchanged and the boundary remains the sole semantic classifier. Inert and enabled-handler fixtures include missing, present non-object, and object inputs accepted by the portable advertised schema but rejected by runtime semantics. + +## What We're Building + +### SDK-free module contracts + +```ts +// src/mcp/framing.ts +export type IngressFrame = + | Readonly<{ kind: "json"; value: unknown }> + | Readonly<{ kind: "parse-error"; fatal: boolean }>; +export interface JsonLineFramer { + readonly retainedBytes: number; + readonly append: (chunk: Uint8Array) => void; + readonly next: () => IngressFrame | undefined; + readonly finish: () => IngressFrame | undefined; +} +export function createJsonLineFramer(): JsonLineFramer; + +// src/mcp/send-queue.ts +export type SendSource = "direct" | "sdk" | "fallback"; +export interface SendEntry { + readonly source: SendSource; + readonly frame: Uint8Array; + readonly requestToken?: string; +} +export interface SendReceipt { + readonly admitted: Promise; + readonly completed: Promise; +} +export interface SendQueue { + readonly backpressured: boolean; + readonly enqueue: (entry: SendEntry) => SendReceipt; + readonly close: () => Promise; +} +export function createSendQueue( + output: Writable, + onBackpressureChange: (paused: boolean) => void, + onFatal: () => void +): SendQueue; + +// src/mcp/session.ts +export type SessionState = + | "PRE_INIT" | "INITIALIZING" | "INIT_RESPONSE_ACCEPTED" + | "READY" | "CLOSING" | "CLOSED"; +export type RequestState = "executing" | "cancelling" | "response-queued"; +export interface SessionController { + readonly state: SessionState; + readonly accept: (message: unknown) => readonly SessionAction[]; + readonly acceptSdkMessage: (message: unknown) => readonly SessionAction[]; + readonly onSendAdmitted: (requestToken?: string) => void; + readonly onRouteSettled: (requestToken: string) => void; + readonly close: () => void; +} +export function createSessionController(options: SessionOptions): SessionController; + +// src/mcp/sdk-adapter.ts +export interface McpRuntimeOptions { + readonly input: Readable; + readonly output: Writable; + readonly workingDirectory: string; + readonly handlers?: ToolHandlerRegistry; +} +export type RuntimeTermination = Readonly<{ + reason: "caller-close" | "input-eof" | "input-error" | "output-error" | "protocol-fatal"; + close_failed: boolean; +}>; +export interface McpRuntimeHandle { + readonly close: () => Promise; + readonly closed: Promise; +} +export function startMcpRuntime(options: McpRuntimeOptions): Promise; + +// src/mcp/process-runner.ts +export interface SignalSource { + readonly on: (signal: "SIGINT" | "SIGTERM", listener: () => void) => void; + readonly off: (signal: "SIGINT" | "SIGTERM", listener: () => void) => void; +} +export interface ProcessBindings { + readonly input: Readable; + readonly output: Writable; + readonly diagnostic: Writable; + readonly workingDirectory: string; + readonly signals: SignalSource; + readonly setExitCode: (code: number) => void; +} +export type RuntimeStarter = (options: McpRuntimeOptions) => Promise; +export function runMcpProcess(bindings: ProcessBindings, start: RuntimeStarter): Promise; +``` + +`SessionAction`/`SessionOptions` are closed SDK-free tagged unions owned by `session.ts`; they carry only normalized JSON-RPC candidates, request tokens, route decisions, authentic boundary outcomes, and lifecycle/close actions. No SDK type crosses these seams. `src/main.ts` only supplies real process bindings and `startMcpRuntime` to `runMcpProcess`. + +### Framing, ledgers, and admission + +The framer consumes bytes with fatal UTF-8 decoding, strips exactly one CR before LF, and treats each LF-terminated segment independently. Empty lines and malformed JSON produce fixed `-32700 Parse error`; a partial final line at EOF produces the same error and then closes. Invalid UTF-8 or a frame/retained-buffer size above 10 MiB queues that fixed error when capacity permits and then closes; otherwise it closes with bounded transport failure. At the first output `write(false)`, the runtime pauses input and stops pulling frames; the framer retains the current chunk remainder within the same 10 MiB cap, then resumes only on `drain` while open. + +For syntactically valid requests, admission order is: envelope/safe-ID validity; session-lifetime seen-ID ledger; lifecycle; method/shape; boundary semantics. The outer request member allowlist is exactly `jsonrpc`, `id`, `method`, `params`; any other top-level request key is fixed `-32600 Invalid Request` rather than being silently stripped. Numeric `-0` normalizes to `0`, while string `"0"` is distinct. Every new safe request ID is added to the ledger before lifecycle/method/shape handling and remains spent after success, direct rejection, protocol/project error, cancellation, send failure, or close. The ledger caps at 65,536 IDs and 10 MiB aggregate UTF-8 canonical key bytes; exceeding either cap closes protocol-fatal before SDK/boundary work. Internal IDs are positive, monotonically increasing, non-recycled safe integers; exhaustion also closes fail-closed. “Reuse” in architecture/tests means rejection after every terminal path, including `-0` versus previously seen `0`. + +Active records are separate from the seen ledger. Each retains a request token, normalized external ID, internal ID, method, route kind, tagged original name/arguments candidates, state `executing`/`cancelling`/`response-queued`, and any authentic `ToolBoundaryOutcome` plus expected projection. Missing arguments are `{present:false}`, never `undefined`. Ordinary cancellation moves an executing record to `cancelling`, rewrites to the internal ID, and retains the tombstone until the route wrapper observes its authentic signal aborted or settles; this preserves same-chunk request/cancel ordering. Response queue admission moves it to `response-queued`, making later cancellation a completed-request no-op while retaining collision/projection ownership until write admission. Close clears all records/tombstones; internal IDs are never recycled. + +### Closed routing and lifecycle + +| Message | `PRE_INIT` | `INITIALIZING` | `INIT_RESPONSE_ACCEPTED` | `READY` | +|---|---|---|---|---| +| Request `initialize` | Guard envelope/ID, allocate, forward SDK | Distinct unseen ID: `-32004`; seen ID: `-32600/null` | same | same | +| Request `ping` | `-32600 Invalid Request` (initialize must be first) | Allocate and pass SDK | Allocate and pass SDK | Allocate and pass SDK | +| Request `tools/list` or `tools/call` | `-32600`, echo safe ID | same | same | Apply fixed route/shape policy and forward | +| Unknown request method | `-32600`, echo safe ID | same | same | `-32601 Method not found`, echo ID | +| Notification `initialized` | ignore | ignore | synchronously mint connection, enter `READY` before next same-chunk frame | ignore | +| Notification `notifications/cancelled` | ignore malformed/unknown/completed/initialize target; route active ordinary target as above | same | same | same | +| Unknown/invalid notification | ignore; notifications never receive responses | same | same | same | +| Syntactically valid unmatched inbound response | silently drop; Phase 4 initiates no requests and never responds to a response | same | same | same | + +Initialization is a transaction whose semantic validator is the public SDK. The outer guard checks only obvious JSON-RPC envelope and ID validity. Construct `Server` with `{name:"archflow-mcp", version:"0.0.0"}` and singleton supported versions, call `registerCapabilities({tools:{}})`, register documented two-argument `tools/list` and `tools/call` handlers, then connect the public `Transport` facade. Fixtures pin initialize `serverInfo` to that identity and `capabilities` to `{tools:{}}`. + +A malformed initialize is forwarded for SDK validation; its SDK error is canonicalized to fixed bounded `-32602 Invalid params` with no validator prose/data. Only error-frame write admission releases the record/candidate and returns to `PRE_INIT`, requiring a new unseen ID for retry. A successful canonical initialize response advances to `INIT_RESPONSE_ACCEPTED` only on its write admission. Projection/serialization/write failure after any SDK initialize mutation is terminal close; the public compatibility probe proves malformed-then-valid behavior and the boundary between pre-mutation retry and terminal mutation failure. + +After `READY`, `tools/list` params may be absent or an object whose only key is `_meta`; `{}` is therefore valid. Any own `cursor` or any key other than `_meta` is fixed `-32602` before catalogue access. `_meta` is forwarded unchanged to public SDK validation; invalid metadata is canonical bounded `-32602`, and `_meta` never enters an ArchFlow boundary input. A valid list returns the exact catalogue/order with no `nextCursor`. + +For `tools/call`, params must be an object whose keys are drawn exactly from `_meta`, `task`, `name`, and `arguments`; any other key is fixed `-32602`. Missing params or missing/non-string `name` is fixed `-32602`. `_meta` and legacy `task` are preserved unchanged for SDK validation/lifting, including canonical bounded `-32602` on invalid values, but neither enters the ArchFlow argument boundary. Missing `arguments` is forwarded unchanged to the two-argument handler; its record preserves `{present:false}`, and the boundary receives only that original candidate (`undefined`). A present object `arguments` value—including one that is semantically invalid—also passes unchanged. Only a present non-object `arguments` value for a known name uses the exact surrogate `{name: , arguments: {}}` under the internal ID, while the handler recovers and supplies the original value by `ctx.mcpReq.id`. A present non-object value with an unknown name is direct `-32602`; an unknown name with missing or object arguments reaches unchanged name-first `TOOL_NOT_FOUND` precedence. SDK validator failures for `_meta`, `task`, or the preserved request are always canonical bounded `-32602` without validator prose. + +The four ArchFlow mappings are `TOOL_NOT_FOUND -32001`, `TOOL_DISABLED -32002`, `UNSUPPORTED_PROTOCOL -32003`, and `INITIALIZATION_REPEATED -32004`; each message is the code string and `data` is the complete retained authenticated `ProtocolError`. `TOOL_NOT_FOUND`/`TOOL_DISABLED` originate at the boundary, `INITIALIZATION_REPEATED` at the lifecycle guard through the authentic constructor/wrapper, and `UNSUPPORTED_PROTOCOL` has no live Phase 4 route because version mismatch counter-offers successfully, but its mapping is unit-tested exhaustively. Before a handler throws public `ProtocolError(code,message,data)`, its record retains the authentic boundary outcome/expected projection. The facade matches the SDK response to that expectation and canonicalizes from the retained authentic value—never by reauthenticating SDK data—so beta.5's rewrite of `TOOL_DISABLED` to `-32602` is restored to `-32002`. Unexpected projection failure becomes fixed `-32603` associated to the record before cleanup. + +Project outcomes use public `Server.projectCallToolResult`, complete `structuredContent`, one text block equal to `JSON.stringify(result)` without newline, and `isError === !result.ok`. Every output frame is `JSON.stringify` plus one LF with success key order `jsonrpc,id,result`, error order `jsonrpc,id,error`, and inner `code,message,data` when data exists. + +### Output and process ownership + +Every direct, SDK, or fallback frame creates an independent FIFO `SendEntry` with optional request association. The queue caps at 1,024 entries and 10 MiB aggregate queued output; a single frame also caps at 10 MiB. Overflow closes fail-closed. `SendReceipt.admitted` records a normal return from `destination.write`; request release and initialization transitions use this event. `SendReceipt.completed` records the write callback. `write(false)` still admits the current entry but pauses input/later writes; `drain` only reopens the FIFO and never completes a write. Callback error is always fatal, even after admission or drain; it rejects incomplete completion, enters `CLOSING`, and quarantines later output. Close rejects every queued/incomplete entry and removes listeners without ending/destroying caller streams. Fallback entries are associated before affected record cleanup. + +After `CLOSING`, no adapter-owned state/output effect, serialization, new write, or boundary invocation occurs; late results are quarantined. Injected handlers must honor `AbortSignal`; the adapter cannot revoke private effects from a non-cooperating handler. The runtime's `closed` promise is the sole adapter-to-runner fatal/termination seam. The runner alone owns fixed once-only diagnostics (`ARCHFLOW_MCP_START_FAILED`, `ARCHFLOW_MCP_TRANSPORT_ERROR`, `ARCHFLOW_MCP_CLOSE_FAILED`) and exits: startup/unsolicited transport/protocol fatal `1`, EOF `0`, SIGINT `130`, SIGTERM `143`; first reason wins, except close failure preserves selected signal codes and otherwise yields `1`. + +## Files + +| Action | File | Purpose | +|--------|------|---------| +| Modify | `src/mcp/server.ts`, `test/unit/mcp-server.test.ts` | Classify known arguments before handler availability; preserve unknown-name precedence; prove inert/enabled missing/non-object/object semantic cases. | +| Create | `src/mcp/framing.ts`, `test/unit/mcp-framing.test.ts` | SDK-free strict bounded JSONL byte framing and retained-chunk behavior. | +| Create | `src/mcp/session.ts`, `test/unit/mcp-session.test.ts` | SDK-free lifecycle, routing, seen ledger, monotonic IDs, records/tombstones, and authentic expected projections. | +| Create | `src/mcp/send-queue.ts`, `test/unit/mcp-send-queue.test.ts` | SDK-free bounded FIFO, write admission/completion, backpressure, and close ownership. | +| Create | `src/mcp/sdk-adapter.ts`, `test/unit/mcp-sdk-adapter.test.ts` | Sole SDK owner, exact Server construction, public facade/handlers, initialization transaction, and outbound canonicalization. | +| Create | `src/mcp/process-runner.ts`, `test/unit/mcp-process-runner.test.ts`, `src/main.ts` | SDK-free termination/diagnostic/exit arbitration plus thin real-process binding. | +| Create | `scripts/probe-phase-4-mcp-compatibility.mjs` | Stop-on-failure currency/public-hook/mutation-boundary probe. | +| Create | `test/integration/mcp-stdio.test.ts`, `test/fixtures/mcp/runtime/*.json` | Self-built isolated live transcripts and byte-exact adversarial fixtures. | +| Create | `scripts/build-temp-helper.mjs` | Shared explicit-output temporary builder for build script and unique OS-temp integration suites. | +| Modify | `scripts/build-temp.mjs`, `scripts/smoke-temp-bundle.mjs` | Build/smoke the inert runtime under untracked temporary output. | +| Delete/Create | Phase 3/4 MCP boundary policy scripts | Replace blanket SDK prohibition with adapter-only public-import allowlist and mutation tests. | +| Modify | `package.json`, `.github/workflows/ci.yml` | Add focused probe/runtime/policy commands and exact Node jobs without dependencies. | + +No dependency/lock, contract schema, catalogue, tracked `dist`, persistence, dispatch, gate, local helper, installer, or release bundle change belongs here. + +## Work Breakdown + +1. **Compatibility and currency gate**: Check live currency before mutation; prove exact public construction, malformed/retry mutation boundary, handler/projection behavior (including beta.5 `TOOL_DISABLED` rewrite/restoration), custom facade, and teardown on both Node patches. Stop on drift or failed invariant. +2. **Boundary repair**: Move known argument classification before handler availability in `server.ts` and prove unknown, inert, enabled, portable/runtime semantic, and at-most-once behavior. +3. **Bounded framing**: Implement/test strict UTF-8 JSONL, CRLF/empty/partial EOF, 10 MiB caps, retained current-chunk remainder, and fatal parse/overflow behavior. +4. **Session and routing**: Implement/test closed route table, exact top-level and list/call params allowlists, SDK metadata/task preservation, initialization transaction state, lifetime ledger/caps, monotonic IDs, active/cancelling/queued records, same-chunk order, and authentic expected outcomes. +5. **Send queue**: Implement/test universal FIFO entries, 10 MiB/1,024 caps, admission versus callback completion, false/drain flow control, fatal callbacks, association, and close cleanup. +6. **SDK adapter**: Implement exact Server/capability/handler/connect order, context minting, missing-argument pass-through, present-non-object surrogate recovery, SDK `_meta`/task validation, three-domain projection, retained-authentic canonicalization, and terminal mutation failures. +7. **Process/runtime assembly**: Implement runner/main/termination seam, once-only diagnostics/exits, shared temporary builder, and self-contained integration harness. +8. **Live/adversarial verification**: Complete all transcripts/races/caps, exact Node verification, second currency check immediately before final review, and aggregate checks. + +Eight bounded delegated chunks fit the implementation budget because each owns a distinct module/test seam; an immediate architecture phase split is unnecessary. + +## Success Criteria + +- [ ] Currency/public API checks pass before mutation and immediately before final verification; any drift or public-hook failure stops without package mutation/private workaround. +- [ ] Known malformed inputs produce `CONTRACT_*` before disabled handling; missing arguments pass unchanged, only present non-objects use a surrogate, object arguments have one semantic authority, and inert/enabled fixtures preserve unknown-name and at-most-once behavior. +- [ ] Strict framing, request/member and params allowlists, SDK `_meta`/task validation, seen-ID/internal-ID caps, normalized non-reuse, closed routing, initialization retry/terminal boundaries, cancellation tombstones, and same-chunk sequences match the pinned contracts without stripping or unbounded memory. +- [ ] Exact Server identity/capabilities/order and initialize bytes are pinned; malformed initialize can retry only after error write admission, while post-mutation projection/write failure closes. +- [ ] All four protocol mappings are unit-proven, live routes use retained authentic outcomes, beta.5 `TOOL_DISABLED` rewriting is restored, and SDK/project/direct/fallback frames remain byte-stable with safe `-32603` containment. +- [ ] Universal bounded FIFO/framer flow control pauses/resumes input correctly and leaves no queued entry, record/tombstone, listener, pending completion, post-close adapter effect, or caller-stream destruction. +- [ ] Runtime termination is observable through `closed`; the SDK-free runner alone emits fixed diagnostics/exits, and main is a thin binding. +- [ ] Focused/full/live/policy/dependency/notices/aggregate checks pass under exact Node `24.15.0` and `24.18.0` with no new dependency, schema, tracked release, persistence, dispatch, or REQ-33 completion claim. + +## Verification Steps + +1. Before mutation and again immediately before final verification/review, use live official/npm sources to verify beta.5/core tags, status/guidance, MIT roots, protocol support, and required public declarations. Stop on any drift. +2. Under pre-provisioned exact Node `24.15.0` and `24.18.0`, run `npm run probe:phase4-mcp-compatibility`, `npm run typecheck`, `npm run test:mcp-runtime`, `npm test`, `npm run test:contracts`, Phase 4 boundary-policy/mutation checks, `npm run build:temp`, dependency/notices checks, and `npm run check`. +3. Prove boundary precedence with inert and enabled registries: unknown names; missing arguments passed unchanged and classified as `input-not-object` for known tools; present non-object arguments through the exact surrogate; unchanged object arguments including portable-accepted/runtime-rejected semantics; valid disabled calls, valid handler results, and at-most-once invocation. +4. Exercise split Unicode, invalid UTF-8, LF/CRLF, empty/malformed/partial final lines, exactly/over 10 MiB frames and retained chunks, many-line chunks, permanent backpressure, input pause/resume, 1,024-entry/10 MiB output boundaries, drain/callback races, overflow, and close while paused. +5. Cover every routing row/state and shape: unknown top-level request keys; list params absent/empty, valid/invalid `_meta`, cursor, and other keys; call params with valid/invalid `_meta`, valid/invalid legacy `task`, unknown keys, missing arguments, present non-object arguments, and object arguments. Assert metadata/task is preserved to SDK validation/lifting but never enters the ArchFlow boundary. Also cover exact initialize serverInfo/capabilities, malformed-then-valid initialize with a new ID, SDK mutation/projection/write failures, same-chunk initialized/call and request/cancel, ping states, unexpected responses, and notification silence. +6. Reject normalized ID reuse after success, direct/project/protocol error, cancellation, send failure, and close; hit both ledger caps and internal-ID exhaustion without SDK/boundary work; prove cancelling tombstones and close cleanup. +7. Unit-test all four mapping entries and live `TOOL_NOT_FOUND`, `TOOL_DISABLED` rewrite/restoration, `INITIALIZATION_REPEATED`, project results, fallback association, exact bytes/LF, and every projection throw point without reauthentication or peer/exception prose. +8. Spawn isolated OS-temp bundles for transcripts, EOF/input/output/protocol fatal, SIGINT/SIGTERM, startup/close failure overlaps, diagnostic once-only behavior, exit codes, stdout purity, cleanup, and absence of `.tmp` prerequisites or tracked `dist`. + +--- +*Designed: 2026-07-27* diff --git a/.archflow/tasks/mcp-integration/reviews/phase-4-design-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-4-design-counter-review.md new file mode 100644 index 00000000..ecb4f3a6 --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-4-design-counter-review.md @@ -0,0 +1,89 @@ +# Phase 4 Design Counter-Review + +Reviewed against the PRD, architecture, all current context references, the Phase 3 design and implementation log, the Phase 3 implementation/tests, the installed beta.5 declarations/runtime, and live official dependency guidance on 2026-07-27. + +## Findings + +1. **Severity: blocker — The required malformed-known-call result is impossible through the frozen Phase 3 boundary.** Phase 4 says a known tool with missing, non-object, or semantically invalid arguments reaches `createToolBoundary` and receives the boundary's `CONTRACT_*` classification. In the actual Phase 3 implementation, however, `src/mcp/server.ts` checks whether a handler exists before it calls `classifyVersionedArgs`; the inert empty registry therefore returns `TOOL_DISABLED` for every known tool regardless of its arguments. This directly contradicts the architecture's requirement that known malformed arguments reach `CONTRACT_*`, while Phase 4 explicitly excludes Phase 3 changes. The pre-SDK “semantically invalid” surrogate also has no legitimate oracle: the complete semantic classifier belongs to the frozen boundary, and the advertised schema intentionally omits runtime-only `x-archflow-*` rules. Duplicating that classifier in the adapter would create two authorities and weaken the Phase 3 seam. + + **Suggested resolution:** Reopen the Phase 3 seam and move known-tool argument classification ahead of handler availability, or explicitly revise the architecture to disabled-first precedence. In Phase 4, use the surrogate only for shapes the SDK itself would reject before the handler (for example, non-object arguments); forward object arguments unchanged and let the boundary remain the sole semantic classifier. Add inert/enabled fixtures for portable-schema-accepted but runtime-rejected objects. + +2. **Severity: blocker — The design permits terminal request-ID reuse, which protocol `2025-11-25` forbids for the full session.** The record rules release an external-ID collision guard after response write acceptance or cancellation, and the success criteria explicitly require “terminal ID reuse.” MCP instead says a request ID “MUST NOT have been previously used by the requestor within the same session”; cancellation does not make the ID reusable. See the official [2025-11-25 base protocol](https://modelcontextprotocol.io/specification/2025-11-25/basic). This is not just an active-request race: a completed, cancelled, failed, or directly rejected valid request ID must remain spent for the connection. + + **Suggested resolution:** Separate active request records from a connection-lifetime seen-ID ledger, reject every reuse after normalization (including `-0`/`0`) with the pinned direct error, and define a fail-closed connection/request-count bound plus internal-ID exhaustion behavior so the ledger and allocator cannot grow or wrap indefinitely. Revise the architecture's ambiguous “reuse fixtures” language and test reuse after success, project/protocol error, cancellation, direct rejection, and output failure. + +3. **Severity: blocker — Required SDK construction and capability registration are absent.** The design configures supported protocol versions and handlers but never pins the exact `Server` implementation identity `{ name, version }`, capabilities, or construction order. In beta.5, registering `tools/list` or `tools/call` on a low-level `Server` before `registerCapabilities({ tools: {} })` fails because the server does not support that capability. The omitted identity and capability object also make the claimed byte-pinned initialize response undefined. + + **Suggested resolution:** Specify and probe the exact order: construct `Server` with a fixed implementation identity/options, register the exact tools capability, register the two tool routes (and any other approved pass-through route), then connect the facade. Pin the resulting initialize `serverInfo` and capabilities bytes in fixtures. + +4. **Severity: blocker — Initialization error and rollback transitions are missing.** `PRE_INIT` refers to a “valid” initialize without defining whether the raw guard or SDK establishes validity, while `INITIALIZING` advances on interception of “the initialize response” without distinguishing success from error. The error table has no malformed-initialize row. Beta.5 can answer malformed initialize input with an SDK error and then accept a later valid initialize, so advancing on any response would strand or falsely initialize the adapter; releasing the record after an initialize projection failure similarly leaves `INITIALIZING` without recoverable state. Raw SDK validation errors can also contain validator prose, contrary to the bounded-wire-error policy. + + **Suggested resolution:** Define the exact public validation seam and canonical error for malformed initialize, success-versus-error interception, candidate cleanup, record release, and retry transition back to `PRE_INIT`. Treat projection/write failure after SDK initialization mutation as terminal close unless a public, probed reset exists. Add malformed-then-valid, error projection, backpressured error, and same-ID overlap fixtures. + +5. **Severity: major — The method-aware route contract is not closed, and `sdk-pass-through` has no defined members.** The design defines that route kind but only specifies initialize, `tools/list`, `tools/call`, initialized, and cancellation. It does not say whether `ping` passes through even though the 2025-11-25 ping receiver [MUST respond promptly](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/ping) and beta.5 registers a ping handler. It also does not define how syntactically valid inbound JSON-RPC responses are handled; stdio explicitly carries requests, notifications, *and responses*, and replying to a response as though it were an invalid request risks a response loop. Malformed initialize and the sources of `UNSUPPORTED_PROTOCOL` and `INITIALIZATION_REPEATED` projection are likewise not assigned to exact routes. + + **Suggested resolution:** Add a closed request/notification/response routing table covering initialize, ping, list, call, initialized, cancelled, unexpected responses, and all unknown/malformed cases. For each row pin lifecycle states, outer validation, allocation/tombstoning, SDK forwarding, exact response/no-response, and cleanup. Either provide a real route for each claimed protocol mapping or narrow the success criterion. + +6. **Severity: major — Beta.5 rewrites `TOOL_DISABLED`, but the request record does not retain the authenticated value needed to restore it.** ArchFlow assigns `TOOL_DISABLED` JSON-RPC code `-32002`. The exact beta.5 2025 codec unconditionally maps a handler-thrown `-32002` to `-32602` (`node_modules/@modelcontextprotocol/server/dist/src-D86MbS1I.mjs`, `encodeErrorCode`) because that number is legacy resource-not-found territory. The facade therefore cannot reconstruct the original authenticated Phase 3 outcome from the outbound SDK message alone, yet the listed request-record fields retain neither that outcome nor an expected projection. Structurally reparsing `data` after the WeakSet-authenticated wrapper is lost would not preserve provenance. + + **Suggested resolution:** Before throwing `ProtocolError`, bind the authentic boundary outcome (or an adapter-derived frozen expected projection) to the request record. Require the outbound facade to match the record and canonicalize from that retained value, not from the SDK-mutated error. The compatibility gate should assert both the observed SDK `-32602` and the restored ArchFlow `-32002`. Alternatively, revise the ArchFlow numeric allocation in the parent contracts. + +7. **Severity: major — Cancellation release occurs before the public SDK surface can prove cancellation ran.** The public `Transport.onmessage` returns `void`, and beta.5 defers notification handlers with `Promise.resolve().then(...)`. Returning from the facade call proves handoff only, not that the SDK abort controller has fired. For a request and cancellation in the same input chunk, releasing the record immediately can make the later-scheduled tool handler fail record recovery; recycling an internal ID could let the delayed cancellation target a newer request. “Fresh positive nonzero” does not explicitly prohibit recycling. + + **Suggested resolution:** Define an adapter-owned `cancelling`/tombstone state and keep the record until an observable handler/signal settlement, while using connection-lifetime monotonic non-recycled internal IDs with fail-closed exhaustion. Pin same-chunk request→cancel ordering, cancellation before the handler begins, late handler start, immediate later request admission, and close during cancellation. Do not call synchronous facade return “SDK cancellation admission.” + +8. **Severity: major — Queue ownership covers record-indexed responses but not direct frames or fallback frames.** Direct parse/lifecycle/method/shape errors intentionally allocate no request mapping, while close only rejects “record-indexed” queued/pending sends. A direct `-32600/-32601/-32602` arriving behind a `write(false)` therefore has no defined FIFO owner, close settlement, or listener cleanup. Projection failure has the inverse problem: the design releases the affected record before attempting `-32603`, allowing its fallback to be queued without the collision/send state that normal responses retain. The statement that the losing event in a `drain`/callback-error race is ignored also conflicts with the later rule that every callback error is fatal; Node documents the callback as the chunk's eventual success/failure signal and `drain` only as permission to resume writing. See [Node Writable semantics](https://nodejs.org/api/stream.html). + + **Suggested resolution:** Model `SendEntry` independently from semantic request records, with an optional record association, and put every direct, SDK, and fallback frame through the same FIFO. Pin acceptance, backpressure clearance, late callback error, close rejection, and record release separately. A callback error that arrives after `drain` may not retroactively un-accept bytes, but it must still trigger the single fatal-output path. + +9. **Severity: major — Raw ingress and backpressure have no bounded byte/flow contract.** Once output returns false, the design keeps accepting input and accumulating later frames/handler results; it pauses ingress only during `CLOSING`. A client can therefore drive unbounded request maps and output queues under permanent backpressure, including many complete lines already present in one chunk. The replacement raw framer also omits a maximum incomplete-line/buffer size, fragmented multibyte UTF-8 behavior, invalid UTF-8 behavior, CRLF, empty lines, and partial EOF. The official stdio transport requires newline-delimited UTF-8 messages, and the bypassed SDK framer itself uses a 10 MiB buffer limit. See [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports). + + **Suggested resolution:** Pin a byte-oriented bounded framer and exact malformed/EOF behavior. Pause ingress at the first `write(false)`, define how the unconsumed remainder of the current chunk is retained within a bound, resume only after `drain` while still open, and close/fail safely on overflow. Test split Unicode code points, invalid UTF-8, over-limit unterminated lines, CRLF/empty/partial-final lines, a many-line chunk, flood under permanent false, and close while paused. + +10. **Severity: major — The runtime handle cannot report the fatal lifecycle that `src/main.ts` must arbitrate.** `McpRuntimeHandle` exposes only `close()`, but main must distinguish unsolicited input/output transport failure, startup failure, explicit close, EOF, and signals, preserve the first termination reason, classify close failure, emit one diagnostic, and choose an exit code. With no `closed`/fatal result or callback, the adapter must either mutate process state/duplicate diagnostic ownership or leave main unaware. The same omission makes deterministic spawned tests for startup, unsolicited transport, and close-failure overlaps infeasible through the declared interface. + + **Suggested resolution:** Add one SDK-free termination/fatal settlement to the handle (or a single callback with a closed result), give diagnostics to exactly one layer, and pin reason arbitration through that seam. Add an injectable process-runner/stdio/signal seam for unit tests; keep actual-process tests for real transcripts, EOF, and signals. + +11. **Severity: major — The phase design weakens an impossible parent success criterion without reconciling the architecture.** Architecture line 473 promises that late or never-settling handlers produce no post-close “business side effect.” The phase correctly admits that an injected handler ignoring `AbortSignal` can still perform private effects and narrows the guarantee to adapter-owned effects/output. The original unqualified promise cannot be enforced by this runtime, and ArchFlow requires parent plans to reflect implementation reality. + + **Suggested resolution:** Before approval, revise the architecture criterion to prohibit adapter-owned state/output effects after `CLOSING`, quarantine late results, and require injected handlers to cooperate with `AbortSignal`; if arbitrary handler side effects truly must be prevented, add an authority/commit barrier in the owning later phase instead of claiming cancellation can revoke them. + +12. **Severity: major — The dependency currency gate has a date-boundary race.** Live checks on 2026-07-27 confirm `@modelcontextprotocol/server@2.0.0-beta.5` is still the npm `latest`/`beta` tag and that the cited public APIs exist; `Server` alone is explicitly deprecated but documented for advanced use. However, upstream schedules stable v2 for 2026-07-28, while the design rechecks only if implementation *starts* on or after that date. A run begun on July 27 may finish after stable supersedes beta.5 without triggering the intended stop. See the [current npm package](https://www.npmjs.com/package/@modelcontextprotocol/server), the upstream [v2 status](https://github.com/modelcontextprotocol/typescript-sdk), and the official [2026-07-28 release-candidate notice](https://blog.modelcontextprotocol.io/posts/2026-07-28-release-candidate/). + + **Suggested resolution:** Run the live dist-tag/guidance check both before any implementation and immediately before final verification/review, and repeat it whenever the UTC date or tag changes during the phase. Stop for architecture/design review if stable appears at either point. + +13. **Severity: major — The phase is not divided into implementable chunks at its actual complexity.** Work chunks 2–4 all own the same `src/mcp/sdk-adapter.ts` and overlapping unit matrix without pinned internal interfaces. Chunk 2 alone includes byte framing, lifecycle, session-ID ledger, internal-ID allocation, direct errors, record/send queues, serialization, backpressure, and close. Chunk 5 combines process control, a build refactor, and the integration harness, while chunk 6 is a large combinatorial race matrix. That prevents useful parallel delegation and makes one highly coupled implementation/review session the integration point for nearly every risk above. + + **Suggested resolution:** Split the architecture phase after the compatibility gate, or define SDK-free internal modules/interfaces with non-overlapping file ownership (for example framing/admission, send queue/lifecycle, SDK facade/projection, and process runner) while keeping SDK imports confined to the adapter. Re-size only after the corrected transition and route tables make the real work visible. + +14. **Severity: minor — The normative repository map assigns lifecycle ownership to the wrong existing file.** `architecture.md` describes `src/mcp/server.ts` as the “MCP v2 lifecycle and connection context” owner, but Phase 3 implemented it as the SDK-free authenticated tool boundary and Phase 4 assigns lifecycle to `sdk-adapter.ts`. Leaving both descriptions encourages a later implementation to blur the frozen boundary. + + **Suggested resolution:** Update the architecture tree comment during design triage so `server.ts` remains the SDK-free tool boundary and `sdk-adapter.ts` owns transport/lifecycle. + +15. **Severity: minor — REQ-33 completion is overstated for an inert runtime.** The phase header claims REQ-33 (“Validated model results”), but Phase 4 has no model dispatch or server-attested model-result validation; those arrive in later phases. Phase 4 contributes only transport projection of already authenticated project/protocol outcomes. + + **Suggested resolution:** State the narrow REQ-33 slice Phase 4 proves, or remove it from this phase's direct requirements and leave full satisfaction to the model-dispatch/assembly phases. Do not let Phase 4 completion imply the whole requirement is met. + +## Triage + +| Finding | Disposition | Change | +|---:|---|---| +| 1 | Accepted | Phase 4 now modifies `src/mcp/server.ts` and its tests so known-tool argument classification precedes handler availability while unknown-name precedence is unchanged. Missing `arguments` is SDK-valid and passes unchanged for boundary `input-not-object` classification; the exact surrogate is limited to a present non-object SDK-rejected value. Object arguments pass unchanged to the sole semantic boundary, with inert and enabled fixtures for all three routes. | +| 2 | Accepted | Added a session-lifetime normalized seen-ID ledger separate from active records, permanent rejection after every terminal/direct path, non-recycled monotonic positive internal IDs, 65,536-ID and 10 MiB ID-key caps, and fail-closed exhaustion. Parent architecture now states that “reuse” fixtures prove rejection. | +| 3 | Accepted | Pinned exact construction order: `Server` identity `{name:"archflow-mcp",version:"0.0.0"}`, singleton supported versions, `registerCapabilities({tools:{}})`, list/call registration, then facade connection. Initialize serverInfo/capabilities bytes are explicit fixtures. | +| 4 | Accepted | Made initialization transactional: the outer guard owns only obvious envelope/ID checks; public SDK validation owns initialize semantics; canonical error write admission cleans up and restores `PRE_INIT`; success write admission advances; post-mutation projection/serialization/write failure closes. Added malformed-then-valid and mutation-boundary probes. | +| 5 | Accepted | Added a closed state/method table for initialize, ping, list, call, unknown requests, initialized/cancelled/unknown notifications, and unmatched inbound responses. The post-triage refinement pins the top-level request allowlist and exact list/call params keys, rejects unknown keys before SDK stripping, preserves permitted `_meta`/legacy `task` only through SDK validation/lifting, and sends only the original arguments candidate to the ArchFlow boundary. Mapping sources remain assigned; `UNSUPPORTED_PROTOCOL` is exhaustively unit-tested with no live Phase 4 route because version mismatch counter-offers successfully. | +| 6 | Accepted | Request records now retain the authentic `ToolBoundaryOutcome`/expected projection before public `ProtocolError` is thrown. Facade canonicalization matches the SDK response but projects from retained authority, restoring beta.5's rewritten `TOOL_DISABLED -32602` to ArchFlow `-32002` without reauthentication. | +| 7 | Accepted | Added a `cancelling` tombstone retained until authentic signal abortion or route settlement, same-chunk request/cancel ordering, non-recycled internal IDs, and close cleanup. Removed the inaccurate synchronous “SDK cancellation admission” assumption. | +| 8 | Accepted | Replaced record-only output ownership with independent FIFO `SendEntry` values for direct, SDK, and fallback frames, each with optional record association. Write admission, callback completion, drain/backpressure, fatal callback error, fallback association, and close rejection are now separate contracts. | +| 9 | Accepted | Added strict UTF-8 byte framing, one-CR stripping, empty/partial/invalid/oversize behavior, 10 MiB ingress bounds, input pause at first `write(false)`, bounded current-chunk retention, drain-only resume, and 10 MiB/1,024-entry output caps with adversarial fixtures. | +| 10 | Accepted | Removed diagnostics from adapter options and added SDK-free `RuntimeTermination`, `McpRuntimeHandle.closed`, `SignalSource`, `ProcessBindings`, `RuntimeStarter`, and `runMcpProcess`. The runner owns diagnostics/exits; `main.ts` is only the real-process binding. | +| 11 | Accepted | Revised the parent architecture criterion to prohibit adapter-owned state/output effects after `CLOSING`, quarantine late results, and require injected handlers to honor `AbortSignal`; no speculative authority subsystem was added. | +| 12 | Accepted | Currency/public-surface checks now run before the first mutation and immediately before final verification/review regardless of start date, stopping on tag, stable-status, guidance, or API drift. Continuous polling is not required. | +| 13 | Accepted in part | Accepted modularization and pinned SDK-free ownership/interfaces for `framing.ts`, `session.ts`, `send-queue.ts`, and `process-runner.ts`, with the adapter as sole SDK owner and boundary in `server.ts`. Rejected an immediate phase split because eight bounded delegated chunks now have distinct file/test seams and fit the implementation budget. | +| 14 | Accepted | Updated the architecture directory map so `server.ts` is the SDK-free authenticated tool boundary, `sdk-adapter.ts` owns SDK/transport isolation, and the four new SDK-free modules have explicit ownership comments. | +| 15 | Accepted | Removed REQ-33 from the Phase 4 design and parent architecture requirements. Both now state that Phase 4 only preserves/projects already-authenticated outcomes; full model-result validation remains later. | + +### Post-triage review + +Both follow-up corrections were accepted: missing `tools/call.arguments` now follows the SDK-valid unchanged route and only a present non-object value uses the surrogate; exact top-level/list/call member allowlists now reject unknown keys before SDK stripping while `_meta` and legacy `task` remain SDK-only inputs. From 5d1a9d701f685b653399840f9f18f8533d728bed Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 19:50:28 -0500 Subject: [PATCH 013/124] MCP Integration Phase 4: Guarded MCP Runtime and SDK Compatibility Implement the bounded low-level stdio runtime, SDK adapter, lifecycle and cancellation policy, output queue, and process runner with focused and live integration coverage. Pin the reviewed stable MCP SDK 2.0.0 public surface, record counter-review triage and implementation evidence, and complete the Phase 4 architecture state. --- .../tasks/mcp-integration/architecture.md | 24 +- ...d-mcp-runtime-and-sdk-compatibility-log.md | 52 ++ ...arded-mcp-runtime-and-sdk-compatibility.md | 47 +- .../reviews/phase-4-impl-counter-review.md | 40 ++ .github/workflows/ci.yml | 7 +- THIRD_PARTY_NOTICES.md | 4 +- package-lock.json | 16 +- package.json | 12 +- scripts/build-temp-helper.mjs | 54 ++ scripts/build-temp.mjs | 28 +- scripts/check-dependency-policy.mjs | 10 +- scripts/check-notices.mjs | 4 +- scripts/check-phase-3-mcp-boundary.mjs | 79 --- scripts/check-phase-4-mcp-boundary.mjs | 82 +++ scripts/probe-phase-4-mcp-compatibility.mjs | 249 ++++++++ scripts/smoke-temp-bundle.mjs | 16 +- scripts/test-phase-3-mcp-boundary-policy.mjs | 75 --- scripts/test-phase-4-mcp-boundary-policy.mjs | 80 +++ src/main.ts | 18 + src/mcp/framing.ts | 125 ++++ src/mcp/process-runner.ts | 208 +++++++ src/mcp/sdk-adapter.ts | 492 ++++++++++++++++ src/mcp/send-queue.ts | 267 +++++++++ src/mcp/server.ts | 6 +- src/mcp/session.ts | 554 ++++++++++++++++++ .../mcp/runtime/adversarial-bytes.json | 6 + test/fixtures/mcp/runtime/calls.json | 52 ++ test/fixtures/mcp/runtime/initialize.json | 54 ++ test/integration/mcp-stdio.test.ts | 293 +++++++++ test/types/mcp-sdk-public-surface.ts | 63 ++ test/unit/mcp-framing.test.ts | 108 ++++ test/unit/mcp-process-runner.test.ts | 298 ++++++++++ test/unit/mcp-sdk-adapter.test.ts | 316 ++++++++++ test/unit/mcp-send-queue.test.ts | 188 ++++++ test/unit/mcp-server.test.ts | 46 +- test/unit/mcp-session.test.ts | 417 +++++++++++++ 36 files changed, 4161 insertions(+), 229 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility-log.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-4-impl-counter-review.md create mode 100644 scripts/build-temp-helper.mjs delete mode 100644 scripts/check-phase-3-mcp-boundary.mjs create mode 100644 scripts/check-phase-4-mcp-boundary.mjs create mode 100644 scripts/probe-phase-4-mcp-compatibility.mjs delete mode 100644 scripts/test-phase-3-mcp-boundary-policy.mjs create mode 100644 scripts/test-phase-4-mcp-boundary-policy.mjs create mode 100644 src/main.ts create mode 100644 src/mcp/framing.ts create mode 100644 src/mcp/process-runner.ts create mode 100644 src/mcp/sdk-adapter.ts create mode 100644 src/mcp/send-queue.ts create mode 100644 src/mcp/session.ts create mode 100644 test/fixtures/mcp/runtime/adversarial-bytes.json create mode 100644 test/fixtures/mcp/runtime/calls.json create mode 100644 test/fixtures/mcp/runtime/initialize.json create mode 100644 test/integration/mcp-stdio.test.ts create mode 100644 test/types/mcp-sdk-public-surface.ts create mode 100644 test/unit/mcp-framing.test.ts create mode 100644 test/unit/mcp-process-runner.test.ts create mode 100644 test/unit/mcp-sdk-adapter.test.ts create mode 100644 test/unit/mcp-send-queue.test.ts create mode 100644 test/unit/mcp-session.test.ts diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index 67affc59..23c68c1c 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -9,7 +9,7 @@ | Layer | Choice | Rationale | |-------|--------|-----------| | Runtime and language | Node.js `24.15.0` functional minimum; TypeScript `7.0.2`; `@types/node` `24.13.3`; ECMAScript modules | `write-file-atomic` 8 sets the functional Node floor. Release and CI use the current Node 24 LTS security patch (`24.18.0` at design time), while `@types/node` `24.13.3` is the current compatible Node-24 major typing line pinned independently; runtime and typings patch numbers need not match. | -| MCP | Protocol `2025-11-25`; `@modelcontextprotocol/server@2.0.0-beta.5` | The user accepted the current v2 beta. The SDK is isolated behind an adapter and protected by protocol fixtures and a controlled upgrade procedure. There is no `@modelcontextprotocol/node` dependency and SDK v1 is not a runtime fallback. | +| MCP | Protocol `2025-11-25`; exact `@modelcontextprotocol/server@2.0.0` with locked `@modelcontextprotocol/core@2.0.0` | Stable server/core were published `2026-07-27T23:55Z`; the completed currency review found unchanged consumed public signatures, legacy runtime behavior, MIT metadata, and transition-license text. The hand-built low-level `Server` remains on the 2025-era path without modern opt-in, so protocol `2026-07-28` adoption is deferred. The SDK is isolated behind the adapter; production imports of core/internal paths are prohibited, there is no `@modelcontextprotocol/node` dependency, and SDK v1 is not a fallback. | | Tool schemas | Zod `4.4.3` | MCP-facing schemas are derived or wrapped from the normative durable contracts wherever shapes overlap, with only transport-specific wrappers defined locally. | | Durable schemas | JSON Schema 2020-12 with Ajv `8.20.0` in strict mode | The versioned durable JSON Schema is normative for every persisted shape and every overlapping MCP/persisted shape; files remain independently readable and fail closed on unknown or contradictory data. | | YAML contracts | `yaml` `2.9.0` | Parses workflow/config files with actionable source locations. | @@ -93,7 +93,7 @@ src/ framing.ts # strict bounded SDK-free JSONL byte framer session.ts # SDK-free lifecycle, routing, IDs, and request records send-queue.ts # bounded FIFO and caller-stream write ownership - sdk-adapter.ts # sole beta SDK import; Server/Transport isolation + sdk-adapter.ts # sole stable SDK import; Server/Transport isolation process-runner.ts # SDK-free termination, diagnostics, and exit arbitration local/ cli.ts # archflow-local command surface @@ -327,7 +327,7 @@ Imported PRD, design, and phase documents map to the existing `prd`, `design`, ` | Decision | Options Considered | Choice | Rationale | |----------|--------------------|--------|-----------| -| MCP generation | SDK v1; v2 beta; direct protocol implementation | Exact-pinned MCP v2 beta behind an adapter | The user accepted beta churn for the current API. Contract fixtures and a controlled upgrade procedure contain that risk better than designing against the superseded surface. | +| MCP generation | SDK v1; v2 stable; direct protocol implementation | Exact-pinned MCP v2 stable `2.0.0` behind an adapter, retaining the 2025-era protocol | Stable retained the consumed public API and legacy behavior. Contract fixtures, public compatibility probes, and adapter isolation preserve the trust boundary while `2026-07-28` modern opt-in remains a separate future design. | | Workflow authority | Conversation/artifact inference; SQLite; repository files | Strict, file-native state and evidence tracked on the task branch | Human and agents can inspect/share it with Git; there is no hidden database authority. | | Task creation | Directory presence; init-created state; manifest adoption | Separate normal/legacy initialization tags adopted by `archflow_state` | Both pin a human-approved immutable policy base; repository init never silently creates task authority or commits. | | Deterministic rerun | Seed model calls; regenerate/merge; retain exact results | Immutable content-addressed snapshots and canonical projections | Supported CLIs do not promise seeded output. Exact bytes are reusable without touching unrelated dirty files. | @@ -368,7 +368,7 @@ Release is blocked unless all applicable tests pass and the supported matrix is 1. A sandbox provider/OS combination has current black-box proof and an explicitly acceptable license. Unsupported environments fail closed rather than receiving reduced isolation. 2. Real minimum supported Claude/Codex host and CLI versions have fixtures; initialization validates the persistent per-server timeout or inherited `MCP_TOOL_TIMEOUT`, Claude safe-mode/tool/MCP/slash-command/persistence constraints, Codex config/rules/project-document suppression, and official registration behavior. 3. Written Anthropic clarification or a qualified legal determination establishes that third-party local subscription-authenticated Claude dispatch is permitted (`VAL-14`). Internal risk acceptance alone does not satisfy this gate. Until then, the integration may be implemented and tested with fixtures, but no release may advertise or enable that Claude dispatch path. -4. The exact dependency lock, licenses/notices, MCP beta migration notes, and offline bundle are reproducible. Any selected sandbox license is surfaced explicitly. +4. The exact dependency lock, licenses/notices, MCP stable migration notes, and offline bundle are reproducible. Any selected sandbox license is surfaced explicitly. 5. `VAL-01` through `VAL-06` pass in terminal runs before Archforge implementation begins. If `VAL-02` does not demonstrate useful independent review, the automation premise is revisited rather than compensated for with more mechanics. ## Requirement and Validation Coverage @@ -458,24 +458,26 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali ### Phase 4: Guarded MCP Runtime and SDK Compatibility -**Goal**: Consume Phase 3's frozen seam to implement and prove the complete inert low-level beta.5 stdio runtime. +**Goal**: Consume Phase 3's frozen seam to implement and prove the complete inert low-level stable `2.0.0` stdio runtime. **Depends on**: Phase 3 **Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28 -**Scope**: Isolate the deprecated low-level SDK `Server` as a documented advanced-use exception wholly inside `src/mcp/sdk-adapter.ts`, beginning and ending with live currency/public-hook gates. Repair the SDK-free `src/mcp/server.ts` seam so known-tool arguments are classified before handler availability while unknown-name precedence remains fixed. Split raw strict/bounded JSONL framing, session lifecycle/routing, session-lifetime seen-ID and monotonic internal-ID ownership, universal bounded output FIFO, and process termination into SDK-free modules. Construct the exact low-level server identity/capability/handler/connect sequence behind a public `Transport` facade; make SDK initialize validation transactional, pin singleton `2025-11-25` counter-offer behavior, context-mint ordering, cancellation tombstones, and a closed request/notification/response routing table. Normalize numeric `-0` to `0` and reject every previously seen request ID for the entire session—response/cancellation/rejection “reuse” fixtures prove rejection, never legal reuse. Reject unknown top-level request members and unknown method-parameter keys before SDK stripping. For list/call, preserve permitted `_meta` and legacy `task` only for SDK validation/lifting and exclude them from ArchFlow boundary input. Missing call arguments are SDK-valid and pass unchanged; use the exact surrogate only for a present non-object argument, while unchanged objects reach the boundary as sole semantic authority. Retain authentic boundary outcomes across SDK projection so the facade restores exact ArchFlow protocol codes, and keep protocol/project/SDK domains byte-stable. Bound ingress/output/ID state, pause input under backpressure, expose runtime termination to an SDK-free process runner, and add a thin inert `src/main.ts`. Phase 4 only preserves/projects already-authenticated outcomes; model-result validation remains later. Stop for architecture review on dependency/API drift or any failed public-hook invariant. +**Design Revision (2026-07-27, approved)**: Stable server/core `2.0.0` replaced the prior prerelease target after the completed currency review found unchanged consumed public signatures, legacy runtime behavior, MIT metadata, and transition-license text. The user approved the revision before dependency mutation; the migration changed only exact pins, lockfile, dependency-policy/notices evidence, and probe expectations, not the runtime architecture. + +**Scope**: Isolate the low-level SDK `Server` as a documented advanced-use exception wholly inside `src/mcp/sdk-adapter.ts`, beginning and ending with live currency/public-hook gates. The current target is exact stable server/core `2.0.0`, published `2026-07-27T23:55Z`, with unchanged consumed public signatures, legacy runtime behavior, MIT metadata, and transition-license text. The approved stable migration updates only exact package/lock pins, dependency policy/notices evidence, and compatibility-probe expectations; it requires no runtime architecture rewrite. Production imports of core or SDK internal/private paths remain prohibited. Retain singleton protocol `2025-11-25`; official hand-built-Server guidance keeps this legacy path unless modern behavior is explicitly selected, so protocol `2026-07-28` adoption is deferred to a later design. Repair the SDK-free `src/mcp/server.ts` seam so known-tool arguments are classified before handler availability while unknown-name precedence remains fixed. Split raw strict/bounded JSONL framing, session lifecycle/routing, session-lifetime seen-ID and monotonic internal-ID ownership, universal bounded output FIFO, and process termination into SDK-free modules. Construct the exact low-level server identity/capability/handler/connect sequence behind a public `Transport` facade; make SDK initialize validation transactional, pin context-mint ordering, cancellation tombstones, and a closed request/notification/response routing table. Normalize numeric `-0` to `0` and reject every previously seen request ID for the entire session—response/cancellation/rejection “reuse” fixtures prove rejection, never legal reuse. Reject unknown top-level request members and unknown method-parameter keys before SDK stripping. For list/call, preserve permitted `_meta` and legacy `task` only for SDK validation/lifting and exclude them from ArchFlow boundary input. Missing call arguments are SDK-valid and pass unchanged; use the exact surrogate only for a present non-object argument, while unchanged objects reach the boundary as sole semantic authority. Retain authentic boundary outcomes across SDK projection so the facade restores exact ArchFlow protocol codes, including stable legacy `TOOL_DISABLED` rewriting; preserve malformed-initialize canonicalization, public result projection, protocol/project/SDK byte separation, and post-close quarantine. Bound ingress/output/ID state, pause input under backpressure, expose runtime termination to an SDK-free process runner, and add a thin inert `src/main.ts`. Phase 4 only preserves/projects already-authenticated outcomes; model-result validation remains later. Stop for architecture review on dependency/API drift or any failed public-hook invariant. **Success Criteria**: -- [ ] Live currency/public API gates run before mutation and immediately before final verification; drift or any failed facade/initialize/projection/teardown invariant stops without dependency mutation or private workaround. +- [ ] The stable `2.0.0` currency/public API evidence is reconfirmed after explicit design approval and before dependency mutation, then immediately before final verification; drift or any failed facade/initialize/projection/teardown invariant stops without dependency mutation, core/internal import, or private workaround. - [ ] `src/mcp/server.ts` classifies known arguments before handler availability; missing arguments pass unchanged, only present non-object arguments use a surrogate, and object semantics retain one boundary authority across inert and enabled fixtures. - [ ] Exact `Server({name:"archflow-mcp",version:"0.0.0"})`, singleton versions, `registerCapabilities({tools:{}})`, two tool handlers, then facade connection produce pinned initialize bytes and transactional malformed-retry/success behavior. - [ ] Strict bounded framing, lifetime seen-ID rejection, monotonic non-recycled internal IDs, cancellation tombstones, and the closed initialize/ping/list/call/notification/response table enforce all lifecycle and same-chunk races without unbounded state. “Reuse” fixtures assert rejection after every terminal path. -- [ ] The exact request/list/call member allowlists reject unknown keys before SDK stripping; permitted `_meta`/legacy `task` are SDK-only inputs; missing/present-non-object/object argument routes reach `CONTRACT_*`, `TOOL_NOT_FOUND`, or `TOOL_DISABLED` exactly. Retained authentic outcomes restore all ArchFlow mappings despite SDK rewriting, while project/SDK/direct/fallback bytes remain distinct and bounded. -- [ ] The universal capped FIFO separates write admission, callback completion, and backpressure; pauses/resumes ingress, rejects all entries on close, performs no adapter-owned state/output effect after `CLOSING`, quarantines late results, and never destroys caller streams. Injected handlers must honor `AbortSignal`. +- [ ] The exact request/list/call member allowlists reject unknown keys before SDK stripping; permitted `_meta`/legacy `task` are SDK-only inputs; missing/present-non-object/object argument routes reach `CONTRACT_*`, `TOOL_NOT_FOUND`, or `TOOL_DISABLED` exactly. Retained authentic outcomes restore all ArchFlow mappings despite stable legacy SDK rewriting; malformed initialize remains bounded/retryable only before mutation, while public projection and project/SDK/direct/fallback bytes remain distinct and bounded. +- [ ] The universal capped FIFO separates write admission, callback completion, and backpressure; pauses/resumes ingress, rejects all entries on close, performs no adapter-owned state/output effect after `CLOSING`, preserves post-close late-result quarantine under stable `2.0.0`, and never destroys caller streams. Injected handlers must honor `AbortSignal`. - [ ] The runtime exposes SDK-free termination to the process runner; `src/main.ts` is a thin inert binding with exact stdout, diagnostics, exit, signal, and cleanup behavior. -- [ ] Focused and live fixtures pass on Node `24.15.0` and `24.18.0` without a new dependency, schema, tracked release output, persistence, dispatch, model-result authority, or REQ-33 completion claim. +- [ ] Exact stable package/lock pins, dependency-policy and unchanged-license notices, public compatibility probes, and focused/live fixtures pass on Node `24.15.0` and `24.18.0` without a dependency beyond the approved stable transition, schema, tracked release output, persistence, dispatch, model-result authority, or REQ-33 completion claim. ### Phase 5: Offline Bundle and Release Integrity @@ -772,7 +774,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali | 1 | Contracts, Assets, and Package Scaffold | COMPLETE (2026-07-27) | | 2 | Review Evidence and Contract Authority | COMPLETE (2026-07-27) | | 3 | MCP Contract Boundary and Dependency Admission | COMPLETE (2026-07-27) | -| 4 | Guarded MCP Runtime and SDK Compatibility | Not Started | +| 4 | Guarded MCP Runtime and SDK Compatibility | COMPLETE (2026-07-27) | | 5 | Offline Bundle and Release Integrity | Not Started | | 6 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | | 7 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | diff --git a/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility-log.md b/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility-log.md new file mode 100644 index 00000000..07d39ef6 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility-log.md @@ -0,0 +1,52 @@ +# Implementation Log: Phase 4 - Guarded MCP Runtime and SDK Compatibility + +**Implemented**: 2026-07-27 +**Status**: COMPLETE + +## Decisions + +- Retained the low-level public SDK `Server` behind `src/mcp/sdk-adapter.ts` as the only production SDK import owner. Framing, lifecycle/routing, output queueing, and process ownership remain SDK-free modules. +- Migrated the approved exact server/core dependency evidence from beta.5 to stable `2.0.0` after a stop-on-drift review showed the consumed public declarations, schemas, hooks, legacy behavior, and license metadata were unchanged. +- Kept singleton protocol `2025-11-25`. Protocol `2026-07-28` requires a later explicit design because the hand-built low-level server remains on the legacy path unless modern behavior is selected. +- Preserved authentic Phase 3 boundary outcomes across SDK projection, including restoration of `TOOL_DISABLED -32002` when the stable SDK rewrites it to `-32602`. +- Made cancellation a validate-then-transition operation: public SDK schema validation occurs before session state mutation, preventing malformed cancellation from suppressing a valid response. +- Kept the approved `append(chunk): void` bounded-framer contract. A delivered chunk whose retained remainder exceeds 10 MiB fails closed; removing delivery-partition dependence requires a design-level streaming interface revision. + +## Deviations from Design + +- Stable `2.0.0` was published during implementation review. Work stopped, the phase design and parent architecture were revised and reviewed, and the user approved the stable migration before package mutation. No runtime rewrite was needed. +- Counter-review reproduced malformed-cancellation response suppression. The session/adapter contract and composed tests were strengthened before approval. +- Counter-review requested broader composed coverage. Representative enabled-handler cancellation, late-result quarantine, terminal ID reuse, and all protocol mappings were added; a redundant exhaustive cross-product harness was not added because component and integration suites already cover the remaining bounded queue/session invariants. + +## Patterns Established + +- SDK compatibility is proved at three layers: an exact dependency/currency probe, compile-time public-surface fixtures, and composed runtime behavior tests. +- State mutations that depend on SDK validity use a two-step action: emit a validation request, then accept a closed validated event. +- Outbound request ownership is retained until write admission, while completion and backpressure are tracked independently. +- Integration bundles are built in unique OS temporary directories so tests do not depend on or leave tracked release output. + +## Gotchas + +- Stable `2.0.0` intentionally retains legacy low-level behavior used here, including malformed-initialize prose and `TOOL_DISABLED` rewriting; the adapter canonicalizes only the explicitly retained authenticated cases. +- `Writable.write(false)` means the entry was admitted but backpressure is active; it is not write completion. Callback errors remain fatal even after admission or drain. +- With the approved pull-based framer interface, accepting one aggregate delivered chunk above the retention cap would require unbounded retention or eager unbounded frame queueing. +- Exact Node patch verification matters because the project floor is Node `24.15.0` while developer ambient runtimes may differ. + +## Key Interfaces + +- `src/mcp/framing.ts`: strict bounded byte-to-JSONL framing. +- `src/mcp/session.ts`: closed lifecycle, route, request-ledger, cancellation, and projection actions. +- `src/mcp/send-queue.ts`: bounded FIFO with separate admission, completion, and backpressure ownership. +- `src/mcp/sdk-adapter.ts`: sole public SDK boundary and canonical response projection. +- `src/mcp/process-runner.ts`: SDK-free termination, diagnostic, signal, and exit arbitration. +- `src/main.ts`: thin real-process binding. + +## Verification + +- Public SDK currency, schema, hook, declaration, projection, and teardown probe against exact stable server/core `2.0.0`. +- Typecheck, 86 focused MCP runtime tests, 276 full tests, 42 contract tests, isolated build/smoke, dependency/notices checks, SDK boundary policy and policy-mutation checks. +- Full `npm run check` under exact Node `24.15.0` and `24.18.0`. + +## Durable Convention Proposal + +No new project-wide `CLAUDE.md` convention is proposed. The public-SDK isolation and protocol behavior are specific to this MCP task and are already recorded in its architecture and tests. diff --git a/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility.md b/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility.md index fa292cec..1fd9d17d 100644 --- a/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility.md +++ b/.archflow/tasks/mcp-integration/phases/phase-4-guarded-mcp-runtime-and-sdk-compatibility.md @@ -1,15 +1,20 @@ # Phase 4: Guarded MCP Runtime and SDK Compatibility -**Status**: DESIGNED +**Status**: COMPLETE +**Implemented**: 2026-07-27 **Task**: mcp-integration -**Goal**: Consume Phase 3's authenticated seam to implement and prove the complete inert low-level beta.5 stdio runtime. +**Goal**: Consume Phase 3's authenticated seam to implement and prove the complete inert low-level stable `2.0.0` stdio runtime. **Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28 ## Context Phases 1–3 established the exact dependencies, durable/MCP contracts, five-tool catalogue, authentic connection and invocation contexts, and SDK-free authenticated tool boundary. Phase 4 is the first runnable MCP phase. It preserves and projects already-authenticated outcomes; full model-result production and validation remain in later dispatch/assembly phases, so this phase does not claim REQ-33. -The target is protocol `2025-11-25` with exact `@modelcontextprotocol/server@2.0.0-beta.5` and locked core beta.5. Both were current and MIT on 2026-07-27, but v2 remains beta. Live dist tags, official guidance, and every required public API are checked before the first implementation mutation and again immediately before final verification/review. Any tag, stable-status, guidance, or public-surface drift stops for design/architecture review without package mutation; no continuous polling is required. Low-level `Server` is a documented advanced-use exception and `src/mcp/sdk-adapter.ts` is the sole production SDK import owner. Raw framing, session policy, output queueing, and process ownership are separate SDK-free modules using Node streams only; there is no SDK stdio/framing owner, private import/patch, or new framing dependency. +The target is protocol `2025-11-25` with exact `@modelcontextprotocol/server@2.0.0` and exact locked `@modelcontextprotocol/core@2.0.0`. The stable packages were published at `2026-07-27T23:55Z`; the completed 2026-07-27 currency review confirmed both root packages retain MIT metadata with unchanged transition-license text, and that all consumed public exports, declarations, handler signatures, and legacy runtime behaviors remain compatible. Official guidance confirms a hand-built low-level `Server` remains on the 2025-era path unless the application explicitly opts into the modern path. Phase 4 therefore retains singleton protocol `2025-11-25` and explicitly defers protocol `2026-07-28` adoption to a later approved design. Low-level `Server` remains a documented advanced-use exception and `src/mcp/sdk-adapter.ts` remains the sole production SDK import owner. Production code must not import `@modelcontextprotocol/core`, SDK internal/private paths, or patch SDK runtime behavior. Raw framing, session policy, output queueing, and process ownership remain separate SDK-free modules using Node streams only; there is no SDK stdio/framing owner, private import/patch, or new framing dependency. + +### Design Revision — 2026-07-27 + +Stable `2.0.0` replaced the prior prerelease target after the stop-on-drift currency gate found that server/core had completed their stable transition without changing the public surface or legacy runtime behavior Phase 4 consumes. The user approved this revision on 2026-07-27. The completed migration is limited to exact pins, lockfile, dependency-policy/notices evidence, and compatibility-probe expectations; it required no runtime architecture rewrite. Malformed-initialize canonicalization, `TOOL_DISABLED` restoration, public result projection, and post-close quarantine remain required unchanged. Phase 4 also repairs the Phase 3 boundary in `src/mcp/server.ts`: unknown names keep existing name-first `TOOL_NOT_FOUND` precedence, but known-tool arguments are classified before handler availability. Thus malformed known inputs produce `CONTRACT_*` even with the inert registry, while a valid known call with no handler produces `TOOL_DISABLED`. Missing `tools/call.arguments` is SDK-valid and passes unchanged; the boundary receives the tagged missing candidate as `undefined` and classifies a known tool as `input-not-object`. The adapter substitutes only a present non-object `arguments` value that the SDK would reject; object arguments pass unchanged and the boundary remains the sole semantic classifier. Inert and enabled-handler fixtures include missing, present non-object, and object inputs accepted by the portable advertised schema but rejected by runtime semantics. @@ -132,7 +137,7 @@ After `READY`, `tools/list` params may be absent or an object whose only key is For `tools/call`, params must be an object whose keys are drawn exactly from `_meta`, `task`, `name`, and `arguments`; any other key is fixed `-32602`. Missing params or missing/non-string `name` is fixed `-32602`. `_meta` and legacy `task` are preserved unchanged for SDK validation/lifting, including canonical bounded `-32602` on invalid values, but neither enters the ArchFlow argument boundary. Missing `arguments` is forwarded unchanged to the two-argument handler; its record preserves `{present:false}`, and the boundary receives only that original candidate (`undefined`). A present object `arguments` value—including one that is semantically invalid—also passes unchanged. Only a present non-object `arguments` value for a known name uses the exact surrogate `{name: , arguments: {}}` under the internal ID, while the handler recovers and supplies the original value by `ctx.mcpReq.id`. A present non-object value with an unknown name is direct `-32602`; an unknown name with missing or object arguments reaches unchanged name-first `TOOL_NOT_FOUND` precedence. SDK validator failures for `_meta`, `task`, or the preserved request are always canonical bounded `-32602` without validator prose. -The four ArchFlow mappings are `TOOL_NOT_FOUND -32001`, `TOOL_DISABLED -32002`, `UNSUPPORTED_PROTOCOL -32003`, and `INITIALIZATION_REPEATED -32004`; each message is the code string and `data` is the complete retained authenticated `ProtocolError`. `TOOL_NOT_FOUND`/`TOOL_DISABLED` originate at the boundary, `INITIALIZATION_REPEATED` at the lifecycle guard through the authentic constructor/wrapper, and `UNSUPPORTED_PROTOCOL` has no live Phase 4 route because version mismatch counter-offers successfully, but its mapping is unit-tested exhaustively. Before a handler throws public `ProtocolError(code,message,data)`, its record retains the authentic boundary outcome/expected projection. The facade matches the SDK response to that expectation and canonicalizes from the retained authentic value—never by reauthenticating SDK data—so beta.5's rewrite of `TOOL_DISABLED` to `-32602` is restored to `-32002`. Unexpected projection failure becomes fixed `-32603` associated to the record before cleanup. +The four ArchFlow mappings are `TOOL_NOT_FOUND -32001`, `TOOL_DISABLED -32002`, `UNSUPPORTED_PROTOCOL -32003`, and `INITIALIZATION_REPEATED -32004`; each message is the code string and `data` is the complete retained authenticated `ProtocolError`. `TOOL_NOT_FOUND`/`TOOL_DISABLED` originate at the boundary, `INITIALIZATION_REPEATED` at the lifecycle guard through the authentic constructor/wrapper, and `UNSUPPORTED_PROTOCOL` has no live Phase 4 route because version mismatch counter-offers successfully, but its mapping is unit-tested exhaustively. Before a handler throws public `ProtocolError(code,message,data)`, its record retains the authentic boundary outcome/expected projection. The facade matches the SDK response to that expectation and canonicalizes from the retained authentic value—never by reauthenticating SDK data—so stable `2.0.0`'s retained legacy rewrite of `TOOL_DISABLED` to `-32602` is restored to `-32002`. Unexpected projection failure becomes fixed `-32603` associated to the record before cleanup. Project outcomes use public `Server.projectCallToolResult`, complete `structuredContent`, one text block equal to `JSON.stringify(result)` without newline, and `isError === !result.ok`. Every output frame is `JSON.stringify` plus one LF with success key order `jsonrpc,id,result`, error order `jsonrpc,id,error`, and inner `code,message,data` when data exists. @@ -157,37 +162,39 @@ After `CLOSING`, no adapter-owned state/output effect, serialization, new write, | Create | `scripts/build-temp-helper.mjs` | Shared explicit-output temporary builder for build script and unique OS-temp integration suites. | | Modify | `scripts/build-temp.mjs`, `scripts/smoke-temp-bundle.mjs` | Build/smoke the inert runtime under untracked temporary output. | | Delete/Create | Phase 3/4 MCP boundary policy scripts | Replace blanket SDK prohibition with adapter-only public-import allowlist and mutation tests. | -| Modify | `package.json`, `.github/workflows/ci.yml` | Add focused probe/runtime/policy commands and exact Node jobs without dependencies. | +| Modify | `package.json`, `package-lock.json` | Replace the prior prerelease server/core lock entries with exact stable `2.0.0` pins after design approval. | +| Modify | `scripts/check-dependency-policy.mjs`, `THIRD_PARTY_NOTICES.md`, `.github/workflows/ci.yml` | Update stable pin policy, unchanged MIT/transition-license evidence, notices, and exact Node verification jobs. | -No dependency/lock, contract schema, catalogue, tracked `dist`, persistence, dispatch, gate, local helper, installer, or release bundle change belongs here. +Beyond the approved exact stable pin/lock/policy/notices migration, no dependency addition, contract schema, catalogue, tracked `dist`, persistence, dispatch, gate, local helper, installer, or release bundle change belongs here. `@modelcontextprotocol/core` remains lock/evidence-only and is never a production import. ## Work Breakdown -1. **Compatibility and currency gate**: Check live currency before mutation; prove exact public construction, malformed/retry mutation boundary, handler/projection behavior (including beta.5 `TOOL_DISABLED` rewrite/restoration), custom facade, and teardown on both Node patches. Stop on drift or failed invariant. -2. **Boundary repair**: Move known argument classification before handler availability in `server.ts` and prove unknown, inert, enabled, portable/runtime semantic, and at-most-once behavior. -3. **Bounded framing**: Implement/test strict UTF-8 JSONL, CRLF/empty/partial EOF, 10 MiB caps, retained current-chunk remainder, and fatal parse/overflow behavior. -4. **Session and routing**: Implement/test closed route table, exact top-level and list/call params allowlists, SDK metadata/task preservation, initialization transaction state, lifetime ledger/caps, monotonic IDs, active/cancelling/queued records, same-chunk order, and authentic expected outcomes. -5. **Send queue**: Implement/test universal FIFO entries, 10 MiB/1,024 caps, admission versus callback completion, false/drain flow control, fatal callbacks, association, and close cleanup. -6. **SDK adapter**: Implement exact Server/capability/handler/connect order, context minting, missing-argument pass-through, present-non-object surrogate recovery, SDK `_meta`/task validation, three-domain projection, retained-authentic canonicalization, and terminal mutation failures. -7. **Process/runtime assembly**: Implement runner/main/termination seam, once-only diagnostics/exits, shared temporary builder, and self-contained integration harness. -8. **Live/adversarial verification**: Complete all transcripts/races/caps, exact Node verification, second currency check immediately before final review, and aggregate checks. +1. **Compatibility and currency gate**: Use the completed stable review and refresh it immediately before final review; prove exact public construction, malformed/retry mutation boundary, handler/projection behavior (including stable `2.0.0` legacy `TOOL_DISABLED` rewrite/restoration), custom facade, and teardown on both Node patches. Stop on drift or failed invariant. +2. **Stable pin and evidence update**: After explicit design approval, update exact server/core `2.0.0` pins in `package.json`/`package-lock.json`, stable expectations in the compatibility probe and dependency-policy check, and unchanged MIT/transition-license evidence in notices. Do not mutate stable dependencies before approval; do not add a core/internal production import. +3. **Boundary repair**: Move known argument classification before handler availability in `server.ts` and prove unknown, inert, enabled, portable/runtime semantic, and at-most-once behavior. +4. **Bounded framing**: Implement/test strict UTF-8 JSONL, CRLF/empty/partial EOF, 10 MiB caps, retained current-chunk remainder, and fatal parse/overflow behavior. +5. **Session and routing**: Implement/test closed route table, exact top-level and list/call params allowlists, SDK metadata/task preservation, initialization transaction state, lifetime ledger/caps, monotonic IDs, active/cancelling/queued records, same-chunk order, and authentic expected outcomes. +6. **Send queue**: Implement/test universal FIFO entries, 10 MiB/1,024 caps, admission versus callback completion, false/drain flow control, fatal callbacks, association, and close cleanup. +7. **SDK adapter**: Implement exact Server/capability/handler/connect order, context minting, missing-argument pass-through, present-non-object surrogate recovery, SDK `_meta`/task validation, three-domain projection, retained-authentic canonicalization, and terminal mutation failures without core/internal imports. +8. **Process/runtime assembly**: Implement runner/main/termination seam, once-only diagnostics/exits, shared temporary builder, and self-contained integration harness. +9. **Live/adversarial verification**: Complete all transcripts/races/caps, exact Node verification, second stable currency check immediately before final review, and aggregate checks. -Eight bounded delegated chunks fit the implementation budget because each owns a distinct module/test seam; an immediate architecture phase split is unnecessary. +Nine bounded work areas, including the small stable pin/evidence update, fit the implementation budget; an immediate architecture phase split is unnecessary. ## Success Criteria -- [ ] Currency/public API checks pass before mutation and immediately before final verification; any drift or public-hook failure stops without package mutation/private workaround. +- [ ] The completed stable `2.0.0` currency/public API review is reconfirmed immediately before dependency mutation and final verification; any drift or public-hook failure stops without package mutation, core/internal import, or private workaround, and no stable mutation occurs before this design revision is user-approved. - [ ] Known malformed inputs produce `CONTRACT_*` before disabled handling; missing arguments pass unchanged, only present non-objects use a surrogate, object arguments have one semantic authority, and inert/enabled fixtures preserve unknown-name and at-most-once behavior. - [ ] Strict framing, request/member and params allowlists, SDK `_meta`/task validation, seen-ID/internal-ID caps, normalized non-reuse, closed routing, initialization retry/terminal boundaries, cancellation tombstones, and same-chunk sequences match the pinned contracts without stripping or unbounded memory. - [ ] Exact Server identity/capabilities/order and initialize bytes are pinned; malformed initialize can retry only after error write admission, while post-mutation projection/write failure closes. -- [ ] All four protocol mappings are unit-proven, live routes use retained authentic outcomes, beta.5 `TOOL_DISABLED` rewriting is restored, and SDK/project/direct/fallback frames remain byte-stable with safe `-32603` containment. -- [ ] Universal bounded FIFO/framer flow control pauses/resumes input correctly and leaves no queued entry, record/tombstone, listener, pending completion, post-close adapter effect, or caller-stream destruction. +- [ ] All four protocol mappings are unit-proven, live routes use retained authentic outcomes, stable `2.0.0` legacy `TOOL_DISABLED` rewriting is restored, and malformed-initialize canonicalization plus SDK/project/direct/fallback frames remain byte-stable with safe `-32603` containment. +- [ ] Universal bounded FIFO/framer flow control pauses/resumes input correctly and leaves no queued entry, record/tombstone, listener, pending completion, post-close adapter effect, or caller-stream destruction; projection and post-close late-result quarantine remain unchanged under stable `2.0.0`. - [ ] Runtime termination is observable through `closed`; the SDK-free runner alone emits fixed diagnostics/exits, and main is a thin binding. -- [ ] Focused/full/live/policy/dependency/notices/aggregate checks pass under exact Node `24.15.0` and `24.18.0` with no new dependency, schema, tracked release, persistence, dispatch, or REQ-33 completion claim. +- [ ] Exact stable server/core pins, regenerated lockfile, dependency policy, unchanged-license notices, compatibility probe, and focused/full/live/policy/aggregate checks pass under exact Node `24.15.0` and `24.18.0` with no dependency beyond the approved pin transition, schema, tracked release, persistence, dispatch, or REQ-33 completion claim. ## Verification Steps -1. Before mutation and again immediately before final verification/review, use live official/npm sources to verify beta.5/core tags, status/guidance, MIT roots, protocol support, and required public declarations. Stop on any drift. +1. After user approval and immediately before stable dependency mutation, then again immediately before final verification/review, use live official/npm sources to reconfirm exact server/core `2.0.0`, the `2026-07-27T23:55Z` publication, MIT roots and unchanged transition-license text, official hand-built-Server legacy guidance, protocol `2025-11-25` support, deferred `2026-07-28` opt-in, and every consumed public declaration/runtime hook. Stop on any drift; never import core/internal surfaces. 2. Under pre-provisioned exact Node `24.15.0` and `24.18.0`, run `npm run probe:phase4-mcp-compatibility`, `npm run typecheck`, `npm run test:mcp-runtime`, `npm test`, `npm run test:contracts`, Phase 4 boundary-policy/mutation checks, `npm run build:temp`, dependency/notices checks, and `npm run check`. 3. Prove boundary precedence with inert and enabled registries: unknown names; missing arguments passed unchanged and classified as `input-not-object` for known tools; present non-object arguments through the exact surrogate; unchanged object arguments including portable-accepted/runtime-rejected semantics; valid disabled calls, valid handler results, and at-most-once invocation. 4. Exercise split Unicode, invalid UTF-8, LF/CRLF, empty/malformed/partial final lines, exactly/over 10 MiB frames and retained chunks, many-line chunks, permanent backpressure, input pause/resume, 1,024-entry/10 MiB output boundaries, drain/callback races, overflow, and close while paused. diff --git a/.archflow/tasks/mcp-integration/reviews/phase-4-impl-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-4-impl-counter-review.md new file mode 100644 index 00000000..3871a98f --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-4-impl-counter-review.md @@ -0,0 +1,40 @@ +# Phase 4 Implementation Counter-Review + +1. **Severity: major — An SDK-invalid cancellation can consume a live request without aborting it, permanently suppressing its eventual response.** `src/mcp/session.ts:339-353` marks an executing record `cancelling` after checking only that `params` is plain JSON and `requestId` is safe. It does not validate the optional `reason`, even though beta.5's public `specTypeSchemas.CancelledNotification` rejects non-string reasons. `src/mcp/sdk-adapter.ts:279-305` prevalidates only list/call requests, so the malformed cancellation is handed to the SDK after the state mutation. The SDK rejects it without aborting the handler; when the handler later settles, `src/mcp/sdk-adapter.ts:385-388` calls `onRouteSettled`, which deletes the cancelling record at `src/mcp/session.ts:467-471`, and the SDK's valid eventual response is then dropped at `src/mcp/session.ts:405-408`. I reproduced this with an enabled delayed `archflow_state` handler and `reason: { invalid: true }`: the handler was not aborted, returned a valid success, and stdout contained no call response. This violates the design's rule to ignore malformed cancellation and leaves the client waiting indefinitely. + + **Suggested resolution:** Validate the complete cancellation through the pinned public SDK schema before mutating the session record (or add an SDK-free exact shape guard proven equivalent to that schema). Add a composed runtime test with a pending enabled handler showing that malformed cancellation neither aborts nor suppresses the normal response, alongside the valid-cancellation case. + +2. **Severity: major — The framer applies the 10 MiB limit to an arbitrary input chunk rather than to each JSONL frame and the retained incomplete suffix.** `src/mcp/framing.ts:40-45` rejects whenever the compacted retained bytes plus the newly delivered chunk exceed `MAX_FRAME_BYTES + 2`, before it searches the chunk for line feeds. A single chunk containing more than 10 MiB total of small, independently valid JSON lines therefore produces one fatal parse error and discards every frame, while the same byte stream split into smaller `Readable` chunks succeeds. I reproduced this with repeated `{}\n` records. This violates segment-independent framing and makes protocol behavior depend on Node's arbitrary chunk partitioning. The "many lines" test at `test/unit/mcp-framing.test.ts:88-97` is too small to cross the aggregate boundary. + + **Suggested resolution:** Split/consume complete LF-delimited segments incrementally and enforce 10 MiB only on an individual frame and the genuinely unconsumed suffix. Add equivalent-byte-stream tests using different chunk partitions, including one greater-than-10-MiB chunk made entirely of short valid frames. + +3. **Severity: major — The required composed runtime verification is materially incomplete, so several Phase 4 success criteria are not proven.** The adapter suite at `test/unit/mcp-sdk-adapter.test.ts:67-173` covers only inert initialization/list/call/metadata/parse-error paths; the integration suite at `test/integration/mcp-stdio.test.ts:180-289` covers basic transcripts, byte errors, signals, and a closed stdout pipe. Neither exercises an enabled asynchronous handler, valid or malformed SDK cancellation, adapter-level backpressure and input pause/resume, close while paused, initialize post-mutation projection/write failure, projection throw points, callback failure with active records, or post-close late-handler quarantine. The session tests also do not cover ID non-reuse after all of success, project/protocol error, send failure, and close, and there is no test of the `UNSUPPORTED_PROTOCOL` mapping despite the explicit four-mapping criterion. Component queue/session tests cannot prove these cross-layer behaviors; the malformed-cancellation defect above demonstrates the gap. + + **Suggested resolution:** Add controlled-stream adapter tests and live enabled-handler races for the omitted Phase 4 verification steps, including every terminal ID path and all four protocol mappings. Keep component tests, but prove the state/SDK/queue interactions at the composed boundary where ordering defects occur. + +4. **Severity: major — The compatibility probe is narrower than the stop-on-drift gate specified by the design.** `scripts/probe-phase-4-mcp-compatibility.mjs:65-95` checks npm dist-tags, package metadata, and runtime existence of a few `Server` methods, but it does not check official beta/stable status or guidance, the required public TypeScript declaration signatures/two-argument handlers, the consumed Call/List/Cancelled schema surfaces, or all required `Transport` hooks. The script and CI can therefore pass after a relevant public-surface or guidance drift that the phase says must stop implementation/review. + + **Suggested resolution:** Extend the compatibility gate with compile-time public-declaration fixtures and runtime assertions for every consumed schema/hook, including cancellation. Record and enforce the immediately-before-review official-source status/guidance check (or make the documented manual portion explicit and retain its evidence) so the automated probe is not presented as the complete gate. + +5. **Severity: minor — `SessionAction` is not the closed route-specific tagged union promised by the design.** The single `forward-sdk` member at `src/mcp/session.ts:57-66` makes `route`, token, IDs, and name/argument candidates independently optional, so impossible values such as a `tools-call` route without recovery candidates type-check. `src/mcp/sdk-adapter.ts:270-277` compensates with presence checks and would silently omit `forwardedCalls` state if an internal producer regressed instead of making that state unrepresentable. + + **Suggested resolution:** Split `forward-sdk` into discriminated variants for request routes, cancellation, and initialized notification, with route-specific required fields. Add compile-time negative cases for incomplete combinations. + +## Triage + +| Finding | Disposition | Resolution | +|---:|---|---| +| 1 | Accepted and fixed | Cancellation is now a two-step operation. `session.ts` emits a non-mutating `validate-cancellation` action; `sdk-adapter.ts` validates the complete notification with public `specTypeSchemas.CancelledNotification`; only the closed `cancellation-accepted` event changes the record to `cancelling` and rewrites the request ID. Composed delayed-handler tests prove a malformed reason is ignored and the normal response is delivered, while a valid cancellation aborts and quarantines the late result. | +| 2 | Rejected | The approved `JsonLineFramer.append(chunk): void` contract and the explicit 10 MiB retained-current-chunk bound cannot both accept an arbitrarily large delivered chunk and yield all of its frames later without retaining that oversized chunk or eagerly queueing an unbounded number of decoded frames. Either choice violates the phase's bounded-memory/backpressure contract. The implementation therefore intentionally fails closed when the current retained delivery exceeds the cap. Removing delivery-partition dependence would require a design-level streaming interface revision, such as returning consumed bytes or driving frames through a bounded callback; that scope is not inferred during implementation triage. | +| 3 | Accepted in part and fixed proportionally | Added composed enabled-handler races for malformed and valid cancellation, post-close late-result quarantine, and representative permanent ID reuse after success, project error, protocol error, and cancellation. All four protocol numeric mappings are now pinned by an exact exhaustive typed table, with live routes for `TOOL_NOT_FOUND`, `TOOL_DISABLED`, and `INITIALIZATION_REPEATED`; `UNSUPPORTED_PROTOCOL` remains a no-live-route mapping as designed. Existing controlled send-queue/session tests cover backpressure, callback failure, close cleanup, caps, and state transitions, while spawned integration tests cover EPIPE and signals. Rejected building a second exhaustive cross-product harness for already-covered component invariants because it is disproportionate to the prototype after the reproduced cross-layer defect and representative terminal paths are now covered. | +| 4 | Accepted and fixed after design review | Added runtime checks for every consumed public schema and transport/server hook, including `CancelledNotification` and `Server.oninitialized`, plus `test/types/mcp-sdk-public-surface.ts` for compile-time handler/context and transport signatures. The probe states that official status/guidance remains a dated manual gate. At `2026-07-28T00:06:53Z`, live npm metadata showed both `@modelcontextprotocol/server` and `@modelcontextprotocol/core` stable `2.0.0` published at approximately `2026-07-27T23:55Z` and moved to `latest`; the official SDK `main` README simultaneously changed to state that v2 is the stable release line. Work stopped for architecture/design review. The revised stable design was approved, exact stable pins and evidence were updated, and the strengthened probe now passes under both supported Node patches while retaining protocol `2025-11-25`. Official evidence: [SDK repository](https://github.com/modelcontextprotocol/typescript-sdk), [server package](https://www.npmjs.com/package/@modelcontextprotocol/server), and [2026-07-28 specification](https://modelcontextprotocol.io/specification/2026-07-28). | +| 5 | Accepted and fixed | `SessionAction` now uses route-specific `forward-sdk` variants with required fields for initialize, ping, list, call, cancellation, and initialized notification paths. Impossible combinations no longer type-check; compile-negative cases cover incomplete tools-call, initialized, and cancellation actions. The adapter no longer uses optional-field presence checks to reconstruct route authority. | + +### Verification after triage + +- `npm run typecheck` passed, including the public SDK surface fixture. +- `npm run test:mcp-runtime` passed: 86 tests across 8 files. +- `npm test` passed: 276 tests across 34 files. +- Contract, temporary build/smoke, dependency, notice, SDK-boundary, and policy-mutation checks passed. +- After the approved stable revision, the compatibility probe, dependency/notices checks, and Phase 4 boundary-policy/mutation checks pass against exact server/core `2.0.0`. +- Full `npm run check` passes under exact Node `24.15.0` and `24.18.0`, retaining 86 focused runtime tests, 276 full tests, and 42 contract tests. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 84709ebb..4e6577ca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,12 +22,15 @@ jobs: node-version: ${{ matrix.node-version }} cache: npm - run: npm ci + - run: npm run probe:phase4-mcp-compatibility - run: npm run typecheck + - run: npm run test:mcp-runtime - run: npm test - run: npm run test:contracts - run: npm run build:temp - run: npm run check:dependencies - run: npm run check:notices - run: npm run test:notices-policy - - run: npm run check:phase3-mcp-boundary - - run: npm run test:phase3-mcp-boundary-policy + - run: npm run check:phase4-mcp-boundary + - run: npm run test:phase4-mcp-boundary-policy + - run: test ! -e dist && test ! -e .tmp diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index f1288a65..bd48eb9f 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -33,8 +33,8 @@ This inventory is generated from and checked against `package-lock.json`. Option | `@esbuild/win32-ia32@0.28.1` | `MIT` | | `@esbuild/win32-x64@0.28.1` | `MIT` | | `@jridgewell/sourcemap-codec@1.5.5` | `MIT` | -| `@modelcontextprotocol/core@2.0.0-beta.5` | `MIT` | -| `@modelcontextprotocol/server@2.0.0-beta.5` | `MIT` | +| `@modelcontextprotocol/core@2.0.0` | `MIT` | +| `@modelcontextprotocol/server@2.0.0` | `MIT` | | `@rollup/rollup-android-arm-eabi@4.62.3` | `MIT` | | `@rollup/rollup-android-arm64@4.62.3` | `MIT` | | `@rollup/rollup-darwin-arm64@4.62.3` | `MIT` | diff --git a/package-lock.json b/package-lock.json index 0deb4d83..044ce829 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,7 @@ "name": "archflow-mcp-server", "version": "0.0.0", "dependencies": { - "@modelcontextprotocol/server": "2.0.0-beta.5", + "@modelcontextprotocol/server": "2.0.0", "ajv": "8.20.0", "ajv-formats": "3.0.1", "yaml": "2.9.0", @@ -475,9 +475,9 @@ "license": "MIT" }, "node_modules/@modelcontextprotocol/core": { - "version": "2.0.0-beta.5", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0-beta.5.tgz", - "integrity": "sha512-HKbY9XTbsDy1Y6r2I55TGE3JEapM0vg96e1MUmBIF9LGjos5gjhcIrTz1yvBPLg2aFKHjwhUAQfRdrCEnPxNew==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", "license": "MIT", "dependencies": { "zod": "^4.2.0" @@ -487,12 +487,12 @@ } }, "node_modules/@modelcontextprotocol/server": { - "version": "2.0.0-beta.5", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0-beta.5.tgz", - "integrity": "sha512-i1E5l75rQKsgY/AKAIspgMBH1vEL7dqiK7tHr0L+raYcb0SWOziqNGJXGIG6NY4AlXDWIKGJQGB7Nqfs3oUi5g==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz", + "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==", "license": "MIT", "dependencies": { - "@modelcontextprotocol/core": "2.0.0-beta.5", + "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" }, "engines": { diff --git a/package.json b/package.json index 43ba1f30..847134b9 100644 --- a/package.json +++ b/package.json @@ -11,16 +11,18 @@ "test": "vitest run", "test:unit": "vitest run test/unit", "test:contracts": "vitest run test/contracts", - "build:temp": "node scripts/build-temp.mjs && node scripts/smoke-temp-bundle.mjs", + "test:mcp-runtime": "vitest run test/unit/mcp-*.test.ts test/integration/mcp-stdio.test.ts", + "probe:phase4-mcp-compatibility": "node scripts/probe-phase-4-mcp-compatibility.mjs", + "build:temp": "node scripts/build-temp.mjs", "check:dependencies": "node scripts/check-dependency-policy.mjs", "check:notices": "node scripts/check-notices.mjs", "test:notices-policy": "node scripts/test-notices-policy.mjs", - "check:phase3-mcp-boundary": "node scripts/check-phase-3-mcp-boundary.mjs", - "test:phase3-mcp-boundary-policy": "node scripts/test-phase-3-mcp-boundary-policy.mjs", - "check": "npm run typecheck && npm test && npm run test:contracts && npm run build:temp && npm run check:dependencies && npm run check:notices && npm run test:notices-policy && npm run check:phase3-mcp-boundary && npm run test:phase3-mcp-boundary-policy" + "check:phase4-mcp-boundary": "node scripts/check-phase-4-mcp-boundary.mjs", + "test:phase4-mcp-boundary-policy": "node scripts/test-phase-4-mcp-boundary-policy.mjs", + "check": "npm run probe:phase4-mcp-compatibility && npm run typecheck && npm run test:mcp-runtime && npm test && npm run test:contracts && npm run build:temp && npm run check:dependencies && npm run check:notices && npm run test:notices-policy && npm run check:phase4-mcp-boundary && npm run test:phase4-mcp-boundary-policy" }, "dependencies": { - "@modelcontextprotocol/server": "2.0.0-beta.5", + "@modelcontextprotocol/server": "2.0.0", "ajv": "8.20.0", "ajv-formats": "3.0.1", "yaml": "2.9.0", diff --git a/scripts/build-temp-helper.mjs b/scripts/build-temp-helper.mjs new file mode 100644 index 00000000..bbb97690 --- /dev/null +++ b/scripts/build-temp-helper.mjs @@ -0,0 +1,54 @@ +import { mkdir } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { isAbsolute, relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { build } from "esbuild"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); +const temporaryRoot = resolve(tmpdir()); +const sharedBuildOptions = Object.freeze({ + bundle: true, + platform: "node", + format: "esm", + target: "node24", + sourcemap: true, + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' + } +}); + +export async function buildTemporaryBundles(outputDirectory) { + if (typeof outputDirectory !== "string" || !isAbsolute(outputDirectory)) { + throw new TypeError("temporary bundle output directory must be an explicit absolute path"); + } + const resolvedOutput = resolve(outputDirectory); + const relativeToTemporaryRoot = relative(temporaryRoot, resolvedOutput); + if ( + resolvedOutput === temporaryRoot || + relativeToTemporaryRoot === "" || + relativeToTemporaryRoot.startsWith("..") || + isAbsolute(relativeToTemporaryRoot) + ) { + throw new TypeError(`temporary bundle output must be a unique child of ${temporaryRoot}`); + } + + await mkdir(resolvedOutput, { recursive: true }); + const contractsBundle = resolve(resolvedOutput, "archflow-contracts.mjs"); + const runtimeBundle = resolve(resolvedOutput, "archflow-mcp.mjs"); + await Promise.all([ + build({ + ...sharedBuildOptions, + absWorkingDir: repositoryRoot, + entryPoints: ["src/contracts/index.ts"], + outfile: contractsBundle + }), + build({ + ...sharedBuildOptions, + absWorkingDir: repositoryRoot, + entryPoints: ["src/main.ts"], + outfile: runtimeBundle + }) + ]); + return Object.freeze({ contractsBundle, runtimeBundle }); +} diff --git a/scripts/build-temp.mjs b/scripts/build-temp.mjs index 47dc8356..e02978c6 100644 --- a/scripts/build-temp.mjs +++ b/scripts/build-temp.mjs @@ -1,14 +1,16 @@ -import { build } from "esbuild"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; -await build({ - entryPoints: ["src/contracts/index.ts"], - outfile: ".tmp/archflow-contracts.mjs", - bundle: true, - platform: "node", - format: "esm", - target: "node24", - sourcemap: true, - banner: { - js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' - } -}); +import { buildTemporaryBundles } from "./build-temp-helper.mjs"; +import { smokeTemporaryBundles } from "./smoke-temp-bundle.mjs"; + +const outputDirectory = await mkdtemp(resolve(tmpdir(), "archflow-mcp-build-")); + +try { + const bundles = await buildTemporaryBundles(outputDirectory); + await smokeTemporaryBundles(bundles); + console.log(`Temporary contract and inert runtime bundles built and exercised under ${process.version}.`); +} finally { + await rm(outputDirectory, { recursive: true, force: true }); +} diff --git a/scripts/check-dependency-policy.mjs b/scripts/check-dependency-policy.mjs index 107491bb..36de87c8 100644 --- a/scripts/check-dependency-policy.mjs +++ b/scripts/check-dependency-policy.mjs @@ -1,7 +1,7 @@ import { readFile } from "node:fs/promises"; const expectedRuntime = Object.freeze({ - "@modelcontextprotocol/server": "2.0.0-beta.5", + "@modelcontextprotocol/server": "2.0.0", ajv: "8.20.0", "ajv-formats": "3.0.1", yaml: "2.9.0", @@ -89,12 +89,12 @@ function packageNameFromPath(path, metadata) { const expectedMcpRoots = Object.freeze({ "node_modules/@modelcontextprotocol/core": Object.freeze({ name: "@modelcontextprotocol/core", - version: "2.0.0-beta.5", + version: "2.0.0", license: "MIT" }), "node_modules/@modelcontextprotocol/server": Object.freeze({ name: "@modelcontextprotocol/server", - version: "2.0.0-beta.5", + version: "2.0.0", license: "MIT" }) }); @@ -113,8 +113,8 @@ for (const [path, expected] of Object.entries(expectedMcpRoots)) { } } const lockedServer = lock.packages?.["node_modules/@modelcontextprotocol/server"]; -if (lockedServer?.dependencies?.["@modelcontextprotocol/core"] !== "2.0.0-beta.5") { - failures.push("the exact MCP server root must lock exact @modelcontextprotocol/core@2.0.0-beta.5"); +if (lockedServer?.dependencies?.["@modelcontextprotocol/core"] !== "2.0.0") { + failures.push("the exact MCP server root must lock exact @modelcontextprotocol/core@2.0.0"); } for (const [path, metadata] of Object.entries(lock.packages ?? {})) { diff --git a/scripts/check-notices.mjs b/scripts/check-notices.mjs index 783f6892..70eab00d 100644 --- a/scripts/check-notices.mjs +++ b/scripts/check-notices.mjs @@ -59,8 +59,8 @@ const recordedSpdx = new Set( [...inventory.matchAll(/^\| `([^`]+)` \| `([^`]+)` \|$/gm)].map((match) => `${match[1]} | ${match[2]}`) ); const requiredMcpRoots = new Set([ - "@modelcontextprotocol/core@2.0.0-beta.5 | MIT", - "@modelcontextprotocol/server@2.0.0-beta.5 | MIT" + "@modelcontextprotocol/core@2.0.0 | MIT", + "@modelcontextprotocol/server@2.0.0 | MIT" ]); for (const entry of requiredMcpRoots) { if (!expectedSpdx.has(entry)) failures.push(`missing exact MCP root from lock: ${entry}`); diff --git a/scripts/check-phase-3-mcp-boundary.mjs b/scripts/check-phase-3-mcp-boundary.mjs deleted file mode 100644 index 6dd1e02e..00000000 --- a/scripts/check-phase-3-mcp-boundary.mjs +++ /dev/null @@ -1,79 +0,0 @@ -import { readFile, readdir, stat } from "node:fs/promises"; -import { relative, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const defaultRepositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); -const repositoryRoot = parseRepositoryRoot(process.argv.slice(2)); -const sourceRoot = resolve(repositoryRoot, "src"); -const prohibitedFragment = "@modelcontextprotocol/"; -const prohibitedPaths = Object.freeze([ - "src/main.ts", - "src/mcp/sdk-adapter.ts", - "src/mcp/index.ts", - "dist" -]); -const failures = []; - -function parseRepositoryRoot(args) { - if (args.length === 0) return defaultRepositoryRoot; - if (args.length !== 2 || args[0] !== "--root") { - throw new Error("usage: node scripts/check-phase-3-mcp-boundary.mjs [--root ]"); - } - return resolve(args[1]); -} - -async function exists(path) { - try { - await stat(path); - return true; - } catch (error) { - if (error?.code === "ENOENT") return false; - throw error; - } -} - -async function collectTypeScriptFiles(directory) { - const entries = await readdir(directory, { withFileTypes: true }); - const paths = []; - for (const entry of entries) { - const path = resolve(directory, entry.name); - if (entry.isDirectory()) { - paths.push(...await collectTypeScriptFiles(path)); - } else if (entry.isFile() && entry.name.endsWith(".ts")) { - paths.push(path); - } - } - return paths; -} - -let sourceFiles; -try { - sourceFiles = await collectTypeScriptFiles(sourceRoot); -} catch (error) { - if (error?.code === "ENOENT") { - failures.push("src must exist so the Phase 3 production boundary can be checked"); - sourceFiles = []; - } else { - throw error; - } -} - -for (const path of sourceFiles.sort()) { - const content = await readFile(path, "utf8"); - if (content.includes(prohibitedFragment)) { - failures.push(`${relative(repositoryRoot, path)} contains prohibited ${prohibitedFragment}`); - } -} - -for (const path of prohibitedPaths) { - if (await exists(resolve(repositoryRoot, path))) { - failures.push(`${path} must not exist before its owning phase`); - } -} - -if (failures.length > 0) { - console.error(failures.map((failure) => `- ${failure}`).join("\n")); - process.exitCode = 1; -} else { - console.log(`Phase 3 MCP boundary passed for ${sourceFiles.length} production TypeScript files.`); -} diff --git a/scripts/check-phase-4-mcp-boundary.mjs b/scripts/check-phase-4-mcp-boundary.mjs new file mode 100644 index 00000000..63b1a8f0 --- /dev/null +++ b/scripts/check-phase-4-mcp-boundary.mjs @@ -0,0 +1,82 @@ +import { readFile, readdir } from "node:fs/promises"; +import { relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const defaultRepositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); +const repositoryRoot = parseRepositoryRoot(process.argv.slice(2)); +const sourceRoot = resolve(repositoryRoot, "src"); +const adapterPath = "src/mcp/sdk-adapter.ts"; +const packagePrefix = "@modelcontextprotocol/"; +const publicRoots = new Set([ + "@modelcontextprotocol/core", + "@modelcontextprotocol/server" +]); +const failures = []; + +function parseRepositoryRoot(args) { + if (args.length === 0) return defaultRepositoryRoot; + if (args.length !== 2 || args[0] !== "--root") { + throw new Error("usage: node scripts/check-phase-4-mcp-boundary.mjs [--root ]"); + } + return resolve(args[1]); +} + +async function collectTypeScriptFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const paths = []; + for (const entry of entries) { + const path = resolve(directory, entry.name); + if (entry.isDirectory()) { + paths.push(...await collectTypeScriptFiles(path)); + } else if (entry.isFile() && entry.name.endsWith(".ts")) { + paths.push(path); + } + } + return paths; +} + +function inspectSource(path, content) { + const repositoryPath = relative(repositoryRoot, path).replaceAll("\\", "/"); + const staticImports = []; + const staticImportPattern = /(?:^|\n)\s*import\s+(?!["'])[^;]+?\s+from\s+["'](@modelcontextprotocol\/[^"']*)["']\s*;/gu; + for (const match of content.matchAll(staticImportPattern)) { + staticImports.push({ start: match.index, end: match.index + match[0].length, specifier: match[1] }); + } + + const referencePattern = /["'](@modelcontextprotocol\/[^"']*)["']/gu; + for (const match of content.matchAll(referencePattern)) { + const declaration = staticImports.find(({ start, end }) => match.index >= start && match.index < end); + const specifier = match[1]; + if (repositoryPath !== adapterPath) { + failures.push(`${repositoryPath} imports MCP SDK package ${specifier}; only ${adapterPath} may import the SDK`); + } else if (declaration === undefined) { + failures.push(`${adapterPath} may use only declared static imports from MCP public roots`); + } else if (!publicRoots.has(specifier)) { + failures.push(`${adapterPath} imports non-public or unapproved MCP path ${specifier}`); + } + } + + if (content.includes(packagePrefix) && !referencePattern.test(content)) { + failures.push(`${repositoryPath} contains an MCP SDK reference outside a recognized string-literal import`); + } +} + +let sourceFiles; +try { + sourceFiles = await collectTypeScriptFiles(sourceRoot); +} catch (error) { + if (error?.code !== "ENOENT") throw error; + failures.push("src must exist so the Phase 4 production boundary can be checked"); + sourceFiles = []; +} + +for (const path of sourceFiles.sort()) { + inspectSource(path, await readFile(path, "utf8")); +} + +if (failures.length > 0) { + console.error(failures.map((failure) => `- ${failure}`).join("\n")); + process.exitCode = 1; +} else { + console.log(`Phase 4 MCP boundary passed for ${sourceFiles.length} production TypeScript files; SDK imports are isolated to ${adapterPath}.`); +} diff --git a/scripts/probe-phase-4-mcp-compatibility.mjs b/scripts/probe-phase-4-mcp-compatibility.mjs new file mode 100644 index 00000000..ffe617b5 --- /dev/null +++ b/scripts/probe-phase-4-mcp-compatibility.mjs @@ -0,0 +1,249 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { + LATEST_PROTOCOL_VERSION, + ProtocolError, + Server, + SUPPORTED_PROTOCOL_VERSIONS, + specTypeSchemas +} from "@modelcontextprotocol/server"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); +const expectedVersion = "2.0.0"; +const protocolVersion = "2025-11-25"; +const packageNames = ["@modelcontextprotocol/server", "@modelcontextprotocol/core"]; + +console.log( + "MANUAL GATE REQUIRED: immediately before review, verify official MCP SDK stable status and legacy hand-built Server guidance from dated official sources; npm dist-tags alone are not sufficient." +); + +class ProbeTransport { + sent = []; + started = false; + closed = false; + supportedVersions; + protocolVersion; + onclose; + onerror; + onmessage; + + async start() { + this.started = true; + } + + async send(message) { + this.sent.push(structuredClone(message)); + } + + async close() { + this.closed = true; + this.onclose?.(); + } + + setProtocolVersion = (version) => { + this.protocolVersion = version; + }; + + setSupportedProtocolVersions = (versions) => { + this.supportedVersions = [...versions]; + }; + + receive(message) { + assert.equal(typeof this.onmessage, "function", "Server.connect must install Transport.onmessage"); + this.onmessage(message); + } +} + +async function waitFor(predicate, label) { + const deadline = Date.now() + 2_000; + while (!predicate()) { + if (Date.now() >= deadline) throw new Error(`timed out waiting for ${label}`); + await new Promise((resolvePromise) => setTimeout(resolvePromise, 5)); + } +} + +function checkRegistryCurrency(packageName) { + const result = spawnSync("npm", ["view", packageName, "dist-tags", "--json"], { + cwd: repositoryRoot, + encoding: "utf8", + timeout: 30_000 + }); + assert.equal(result.status, 0, `could not read live npm dist-tags for ${packageName}: ${result.stderr}`); + const tags = JSON.parse(result.stdout); + assert.equal(tags.latest, expectedVersion, `${packageName} latest tag drifted; stop for design review`); +} + +for (const packageName of packageNames) { + const packageJson = JSON.parse( + await readFile(resolve(repositoryRoot, "node_modules", packageName, "package.json"), "utf8") + ); + assert.equal(packageJson.name, packageName); + assert.equal(packageJson.version, expectedVersion); + assert.equal(packageJson.license, "MIT"); + assert.ok(packageJson.exports?.["."], `${packageName} must retain its public root export`); +} + +assert.equal(LATEST_PROTOCOL_VERSION, protocolVersion); +assert.ok(SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)); +assert.equal(typeof Server, "function"); +assert.equal(typeof ProtocolError, "function"); +const publicSchemaNames = [ + "InitializeRequest", + "ListToolsRequest", + "CallToolRequest", + "CancelledNotification" +]; +for (const schemaName of publicSchemaNames) { + assert.equal( + typeof specTypeSchemas[schemaName]?.safeParse, + "function", + `public specTypeSchemas.${schemaName} hook drifted` + ); +} +assert.equal(specTypeSchemas.InitializeRequest.safeParse({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion, + capabilities: {}, + clientInfo: { name: "phase-4-probe", version: "0.0.0" } + } +}).success, true); +assert.equal(specTypeSchemas.ListToolsRequest.safeParse({ + jsonrpc: "2.0", + id: 2, + method: "tools/list" +}).success, true); +assert.equal(specTypeSchemas.CallToolRequest.safeParse({ + jsonrpc: "2.0", + id: 3, + method: "tools/call", + params: { name: "archflow_state", arguments: {} } +}).success, true); +assert.equal(specTypeSchemas.CancelledNotification.safeParse({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { requestId: 3, reason: "probe" } +}).success, true); +assert.equal(specTypeSchemas.CancelledNotification.safeParse({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { requestId: 3, reason: { invalid: true } } +}).success, false); +for (const method of ["registerCapabilities", "setRequestHandler", "connect", "close", "projectCallToolResult"]) { + assert.equal(typeof Server.prototype[method], "function", `public Server.${method} declaration/runtime hook drifted`); +} + +const transport = new ProbeTransport(); +const server = new Server( + { name: "archflow-mcp", version: "0.0.0" }, + { supportedProtocolVersions: [protocolVersion] } +); +server.registerCapabilities({ tools: {} }); +let initializedCount = 0; +server.oninitialized = () => { + initializedCount += 1; +}; +server.setRequestHandler("tools/list", async () => ({ tools: [] })); +server.setRequestHandler("tools/call", async () => { + throw new ProtocolError(-32002, "TOOL_DISABLED", { + code: "TOOL_DISABLED", + owner: "protocol", + retryable: false, + next_action: "enable-tool", + diagnostic: { tool: "archflow_state" } + }); +}); +await server.connect(transport); +assert.equal(transport.started, true); +assert.deepEqual(transport.supportedVersions, [protocolVersion]); +for (const hook of ["onmessage", "onclose", "onerror", "setProtocolVersion", "setSupportedProtocolVersions"]) { + assert.equal(typeof transport[hook], "function", `public Transport.${hook} hook drifted`); +} + +transport.receive({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion, + capabilities: {}, + clientInfo: { name: 1, version: "invalid" } + } +}); +await waitFor(() => transport.sent.length === 1, "malformed initialize response"); +assert.equal(transport.sent[0].id, 1); +assert.equal( + transport.sent[0].error.code, + -32603, + "stable 2.0.0 must retain malformed initialize behavior required for adapter canonicalization" +); +assert.equal(server.getClientVersion(), undefined, "malformed initialize must not mutate client identity"); +assert.equal(server.getNegotiatedProtocolVersion(), undefined, "malformed initialize must remain retryable"); + +transport.receive({ + jsonrpc: "2.0", + id: 2, + method: "initialize", + params: { + protocolVersion, + capabilities: {}, + clientInfo: { name: "phase-4-probe", version: "0.0.0" } + } +}); +await waitFor(() => transport.sent.length === 2, "valid initialize response after malformed retry"); +assert.deepEqual(transport.sent[1], { + jsonrpc: "2.0", + id: 2, + result: { + protocolVersion, + capabilities: { tools: {} }, + serverInfo: { name: "archflow-mcp", version: "0.0.0" } + } +}); +assert.deepEqual(server.getClientVersion(), { name: "phase-4-probe", version: "0.0.0" }); +assert.equal(server.getNegotiatedProtocolVersion(), protocolVersion); +assert.equal(transport.protocolVersion, protocolVersion); + +transport.receive({ jsonrpc: "2.0", method: "notifications/initialized" }); +await waitFor(() => initializedCount === 1, "Server.oninitialized callback"); +transport.receive({ + jsonrpc: "2.0", + id: 3, + method: "tools/call", + params: { name: "archflow_state", arguments: {} } +}); +await waitFor(() => transport.sent.length === 3, "tools/call ProtocolError response"); +assert.equal( + transport.sent[2].error.code, + -32602, + "stable 2.0.0 must retain legacy TOOL_DISABLED rewriting for adapter restoration" +); +assert.equal(transport.sent[2].error.message, "TOOL_DISABLED"); + +assert.deepEqual( + server.projectCallToolResult({ content: [], structuredContent: [1, 2] }, undefined), + { + content: [{ type: "text", text: "[1,2]" }], + structuredContent: { result: [1, 2] } + } +); + +await server.close(); +assert.equal(transport.closed, true); +assert.equal( + typeof transport.onmessage, + "function", + "stable 2.0.0 must retain the observed Transport teardown behavior guarded by adapter quarantine" +); + +for (const packageName of packageNames) checkRegistryCurrency(packageName); + +console.log( + `Phase 4 MCP compatibility probe passed for stable server/core 2.0.0 public Server, Transport, projection, mutation, rewrite, and teardown behavior under ${process.version}.` +); diff --git a/scripts/smoke-temp-bundle.mjs b/scripts/smoke-temp-bundle.mjs index 24aec7d7..08bcc36f 100644 --- a/scripts/smoke-temp-bundle.mjs +++ b/scripts/smoke-temp-bundle.mjs @@ -1,6 +1,9 @@ import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; -const contracts = await import(new URL("../.tmp/archflow-contracts.mjs", import.meta.url)); +export async function smokeTemporaryBundles({ contractsBundle, runtimeBundle }) { +const contracts = await import(pathToFileURL(contractsBundle)); assert.deepEqual( contracts.parseSingleYamlDocument("name: archflow\nenabled: true\n", "bundle-smoke.yaml"), @@ -114,4 +117,13 @@ assert.equal("createTestAuthorityLink" in contracts, false); assert.equal("createTestVerifiedReferencedEvidence" in contracts, false); assert.equal("createTestCurrentReviewSetAuthority" in contracts, false); -console.log(`Temporary contract bundle loaded and exercised under ${process.version}.`); +const runtime = spawnSync(process.execPath, [runtimeBundle], { + encoding: "utf8", + input: "", + timeout: 10_000 +}); +assert.equal(runtime.error, undefined, "inert runtime must terminate after stdin EOF"); +assert.equal(runtime.status, 0, `inert runtime exited unsuccessfully: ${runtime.stderr}`); +assert.equal(runtime.stdout, "", "runtime stdout must contain protocol frames only"); +assert.equal(runtime.stderr, "", "clean inert EOF must not emit diagnostics"); +} diff --git a/scripts/test-phase-3-mcp-boundary-policy.mjs b/scripts/test-phase-3-mcp-boundary-policy.mjs deleted file mode 100644 index 7380a9e7..00000000 --- a/scripts/test-phase-3-mcp-boundary-policy.mjs +++ /dev/null @@ -1,75 +0,0 @@ -import assert from "node:assert/strict"; -import { mkdir, mkdtemp, rm, unlink, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { resolve } from "node:path"; -import { spawnSync } from "node:child_process"; -import { fileURLToPath } from "node:url"; - -const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); -const checkerPath = `${repositoryRoot}/scripts/check-phase-3-mcp-boundary.mjs`; -const temporaryRoot = await mkdtemp(resolve(tmpdir(), "archflow-phase-3-mcp-boundary-")); -const probePath = `${temporaryRoot}/src/nested/probe.ts`; - -function runCheck() { - return spawnSync(process.execPath, [checkerPath, "--root", temporaryRoot], { encoding: "utf8" }); -} - -async function assertSourceMutationRejected(label, source) { - await writeFile(probePath, source); - const result = runCheck(); - assert.notEqual(result.status, 0, `${label} must fail the Phase 3 MCP boundary`); - assert.match(result.stderr, /src\/nested\/probe\.ts contains prohibited @modelcontextprotocol\//u); - await unlink(probePath); -} - -async function assertPrematurePathRejected(path, kind = "file") { - const absolutePath = `${temporaryRoot}/${path}`; - if (kind === "directory") { - await mkdir(absolutePath, { recursive: true }); - } else { - await mkdir(resolve(absolutePath, ".."), { recursive: true }); - await writeFile(absolutePath, "export {};\n"); - } - const result = runCheck(); - assert.notEqual(result.status, 0, `${path} must fail the Phase 3 MCP boundary`); - assert.match(result.stderr, new RegExp(`${path.replaceAll(".", "\\.")} must not exist before its owning phase`, "u")); - await rm(absolutePath, { recursive: true, force: true }); -} - -try { - await mkdir(`${temporaryRoot}/src/nested`, { recursive: true }); - await writeFile(`${temporaryRoot}/src/nested/clean.ts`, "export const clean = true;\n"); - assert.equal(runCheck().status, 0, "clean production source must pass the Phase 3 MCP boundary"); - - await assertSourceMutationRejected( - "aliased static import", - 'import { Server as ProtocolServer } from "@modelcontextprotocol/server";\n' - ); - await assertSourceMutationRejected( - "type import", - 'import type { RequestId } from "@modelcontextprotocol/core";\n' - ); - await assertSourceMutationRejected( - "side-effect import", - 'import "@modelcontextprotocol/server";\n' - ); - await assertSourceMutationRejected( - "dynamic import", - 'const sdk = await import("@modelcontextprotocol/server");\n' - ); - await assertSourceMutationRejected( - "re-export", - 'export * from "@modelcontextprotocol/server";\n' - ); - - await assertPrematurePathRejected("src/main.ts"); - await assertPrematurePathRejected("src/mcp/sdk-adapter.ts"); - await assertPrematurePathRejected("src/mcp/index.ts"); - await assertPrematurePathRejected("dist", "directory"); - - console.log( - "Phase 3 MCP boundary mutation checks rejected all SDK reference forms and premature runtime/release paths." - ); -} finally { - await rm(temporaryRoot, { recursive: true, force: true }); -} diff --git a/scripts/test-phase-4-mcp-boundary-policy.mjs b/scripts/test-phase-4-mcp-boundary-policy.mjs new file mode 100644 index 00000000..a8a8cfad --- /dev/null +++ b/scripts/test-phase-4-mcp-boundary-policy.mjs @@ -0,0 +1,80 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); +const checkerPath = resolve(repositoryRoot, "scripts/check-phase-4-mcp-boundary.mjs"); +const temporaryRoot = await mkdtemp(resolve(tmpdir(), "archflow-phase-4-mcp-boundary-")); +const adapterPath = resolve(temporaryRoot, "src/mcp/sdk-adapter.ts"); +const probePath = resolve(temporaryRoot, "src/nested/probe.ts"); + +function runCheck() { + return spawnSync(process.execPath, [checkerPath, "--root", temporaryRoot], { encoding: "utf8" }); +} + +function assertRejected(label, expected) { + const result = runCheck(); + assert.notEqual(result.status, 0, `${label} must fail the Phase 4 MCP boundary`); + assert.match(result.stderr, expected); +} + +async function assertOutsideAdapterRejected(label, source) { + await writeFile(probePath, source); + assertRejected(label, /only src\/mcp\/sdk-adapter\.ts may import the SDK/u); + await writeFile(probePath, "export const clean = true;\n"); +} + +try { + await mkdir(resolve(temporaryRoot, "src/mcp"), { recursive: true }); + await mkdir(resolve(temporaryRoot, "src/nested"), { recursive: true }); + await writeFile( + adapterPath, + 'import { Server, type Transport } from "@modelcontextprotocol/server";\n' + + 'import type { RequestId } from "@modelcontextprotocol/core";\n' + + "export const publicImports = [Server, null as Transport | RequestId | null];\n" + ); + await writeFile(probePath, "export const clean = true;\n"); + const cleanResult = runCheck(); + assert.equal( + cleanResult.status, + 0, + `public static adapter imports and SDK-free production source must pass:\n${cleanResult.stderr}` + ); + + await assertOutsideAdapterRejected( + "static import", + 'import { Server } from "@modelcontextprotocol/server";\n' + ); + await assertOutsideAdapterRejected( + "type import", + 'import type { RequestId } from "@modelcontextprotocol/core";\n' + ); + await assertOutsideAdapterRejected( + "side-effect import", + 'import "@modelcontextprotocol/server";\n' + ); + await assertOutsideAdapterRejected( + "dynamic import", + 'const sdk = await import("@modelcontextprotocol/server");\n' + ); + await assertOutsideAdapterRejected( + "re-export", + 'export * from "@modelcontextprotocol/server";\n' + ); + + await writeFile(adapterPath, 'import "@modelcontextprotocol/server";\n'); + assertRejected("adapter side-effect import", /only declared static imports/u); + await writeFile(adapterPath, 'const sdk = await import("@modelcontextprotocol/server");\n'); + assertRejected("adapter dynamic import", /only declared static imports/u); + await writeFile(adapterPath, 'export * from "@modelcontextprotocol/server";\n'); + assertRejected("adapter re-export", /only declared static imports/u); + await writeFile(adapterPath, 'import { Server } from "@modelcontextprotocol/server/dist/index.mjs";\n'); + assertRejected("adapter private import", /non-public or unapproved MCP path/u); + + console.log("Phase 4 MCP boundary mutation checks rejected static, type, side-effect, dynamic, re-export, and private-path violations."); +} finally { + await rm(temporaryRoot, { recursive: true, force: true }); +} diff --git a/src/main.ts b/src/main.ts new file mode 100644 index 00000000..0791f201 --- /dev/null +++ b/src/main.ts @@ -0,0 +1,18 @@ +import process from "node:process"; + +import { runMcpProcess } from "./mcp/process-runner.js"; +import { startMcpRuntime } from "./mcp/sdk-adapter.js"; + +void runMcpProcess( + { + input: process.stdin, + output: process.stdout, + diagnostic: process.stderr, + workingDirectory: process.cwd(), + signals: process, + setExitCode: (code) => { + process.exitCode = code; + }, + }, + startMcpRuntime, +); diff --git a/src/mcp/framing.ts b/src/mcp/framing.ts new file mode 100644 index 00000000..4c28b497 --- /dev/null +++ b/src/mcp/framing.ts @@ -0,0 +1,125 @@ +export type IngressFrame = + | Readonly<{ kind: "json"; value: unknown }> + | Readonly<{ kind: "parse-error"; fatal: boolean }>; + +export interface JsonLineFramer { + readonly retainedBytes: number; + readonly append: (chunk: Uint8Array) => void; + readonly next: () => IngressFrame | undefined; + readonly finish: () => IngressFrame | undefined; +} + +const MAX_FRAME_BYTES = 10 * 1024 * 1024; +const LINE_FEED = 0x0a; +const CARRIAGE_RETURN = 0x0d; + +const nonfatalParseError = (): IngressFrame => ({ kind: "parse-error", fatal: false }); +const fatalParseError = (): IngressFrame => ({ kind: "parse-error", fatal: true }); + +export function createJsonLineFramer(): JsonLineFramer { + let retained = new Uint8Array(); + let offset = 0; + let fatalPending = false; + let stopped = false; + + const compact = (): void => { + if (offset === 0) return; + retained = retained.slice(offset); + offset = 0; + }; + + const fail = (): void => { + retained = new Uint8Array(); + offset = 0; + fatalPending = true; + }; + + const append = (chunk: Uint8Array): void => { + if (stopped || fatalPending || chunk.byteLength === 0) return; + + compact(); + // A maximum-size frame may still have the two-byte CRLF delimiter. + if (retained.byteLength + chunk.byteLength > MAX_FRAME_BYTES + 2) { + fail(); + return; + } + + const combined = new Uint8Array(retained.byteLength + chunk.byteLength); + combined.set(retained); + combined.set(chunk, retained.byteLength); + retained = combined; + }; + + const next = (): IngressFrame | undefined => { + if (stopped) return undefined; + if (fatalPending) { + fatalPending = false; + stopped = true; + return fatalParseError(); + } + + const lineFeed = retained.indexOf(LINE_FEED, offset); + if (lineFeed === -1) { + if (retained.byteLength - offset > MAX_FRAME_BYTES) { + fail(); + return next(); + } + return undefined; + } + + let end = lineFeed; + if (end > offset && retained[end - 1] === CARRIAGE_RETURN) end -= 1; + const frameBytes = retained.subarray(offset, end); + offset = lineFeed + 1; + + if (frameBytes.byteLength > MAX_FRAME_BYTES) { + fail(); + return next(); + } + + try { + const source = new TextDecoder("utf-8", { fatal: true }).decode(frameBytes); + return { kind: "json", value: JSON.parse(source) as unknown }; + } catch (error) { + if (error instanceof TypeError && frameBytes.byteLength !== 0) { + // TextDecoder uses TypeError for malformed UTF-8. JSON.parse also throws + // SyntaxError, keeping ordinary malformed JSON nonfatal. + fail(); + return next(); + } + return nonfatalParseError(); + } + }; + + const finish = (): IngressFrame | undefined => { + const frame = next(); + if (frame !== undefined) return frame; + if (stopped) return undefined; + + if (retained.byteLength - offset > 0) { + const partial = retained.subarray(offset); + try { + new TextDecoder("utf-8", { fatal: true }).decode(partial); + } catch { + fail(); + return next(); + } + retained = new Uint8Array(); + offset = 0; + stopped = true; + return nonfatalParseError(); + } + + stopped = true; + return undefined; + }; + + return { + get retainedBytes() { + return retained.byteLength - offset; + }, + append, + next, + finish + }; +} diff --git a/src/mcp/process-runner.ts b/src/mcp/process-runner.ts new file mode 100644 index 00000000..27b12256 --- /dev/null +++ b/src/mcp/process-runner.ts @@ -0,0 +1,208 @@ +import type { Readable, Writable } from "node:stream"; + +import type { + McpRuntimeHandle, + McpRuntimeOptions, + RuntimeTermination, +} from "./sdk-adapter.js"; + +export interface SignalSource { + readonly on: (signal: "SIGINT" | "SIGTERM", listener: () => void) => void; + readonly off: (signal: "SIGINT" | "SIGTERM", listener: () => void) => void; +} + +export interface ProcessBindings { + readonly input: Readable; + readonly output: Writable; + readonly diagnostic: Writable; + readonly workingDirectory: string; + readonly signals: SignalSource; + readonly setExitCode: (code: number) => void; +} + +export type RuntimeStarter = ( + options: McpRuntimeOptions, +) => Promise; + +type ExitReason = + | Readonly<{ kind: "startup" }> + | Readonly<{ kind: "runtime-fatal" }> + | Readonly<{ kind: "eof" }> + | Readonly<{ kind: "signal"; code: 130 | 143 }>; + +interface Deferred { + readonly promise: Promise; + readonly resolve: (value: T) => void; +} + +type StartupResult = + | Readonly<{ kind: "started"; runtime: McpRuntimeHandle }> + | Readonly<{ kind: "failed" }>; + +function deferred(): Deferred { + let resolvePromise!: (value: T) => void; + const promise = new Promise((resolve) => { + resolvePromise = resolve; + }); + return { promise, resolve: resolvePromise }; +} + +function reasonForRuntime(termination: RuntimeTermination): ExitReason { + return termination.reason === "input-eof" + ? { kind: "eof" } + : { kind: "runtime-fatal" }; +} + +export async function runMcpProcess( + bindings: ProcessBindings, + start: RuntimeStarter, +): Promise { + const selected = deferred(); + let firstReason: ExitReason | undefined; + let diagnosticWritten = false; + let exitCodeSet = false; + + function select(reason: ExitReason): void { + if (firstReason === undefined) { + firstReason = reason; + selected.resolve(reason); + } + } + + function writeDiagnostic(code: string): void { + if (diagnosticWritten) { + return; + } + diagnosticWritten = true; + try { + bindings.diagnostic.write(`${code}\n`); + } catch { + // Diagnostics are best effort and never replace the selected exit reason. + } + } + + function setExitCode(code: number): void { + if (exitCodeSet) { + return; + } + exitCodeSet = true; + bindings.setExitCode(code); + } + + const onSigint = (): void => select({ kind: "signal", code: 130 }); + const onSigterm = (): void => select({ kind: "signal", code: 143 }); + + bindings.signals.on("SIGINT", onSigint); + bindings.signals.on("SIGTERM", onSigterm); + + let runtime: McpRuntimeHandle | undefined; + let termination: RuntimeTermination | undefined; + let closePromise: Promise | undefined; + + function closeOnce(handle: McpRuntimeHandle): Promise { + closePromise ??= Promise.resolve() + .then(() => handle.close()) + .then( + () => false, + () => true, + ); + return closePromise; + } + + try { + let startup: Promise; + try { + startup = start({ + input: bindings.input, + output: bindings.output, + workingDirectory: bindings.workingDirectory, + }).then( + (startedRuntime): StartupResult => ({ + kind: "started", + runtime: startedRuntime, + }), + (): StartupResult => ({ kind: "failed" }), + ); + } catch { + startup = Promise.resolve({ kind: "failed" }); + } + + const startupRace = await Promise.race([ + startup, + selected.promise.then(() => undefined), + ]); + + if (startupRace === undefined) { + void startup.then((result) => { + if (result.kind === "started") { + void result.runtime.closed.catch(() => undefined); + void closeOnce(result.runtime).then((closeFailed) => { + if (closeFailed) { + writeDiagnostic("ARCHFLOW_MCP_CLOSE_FAILED"); + } + }); + } + }); + } else if (startupRace.kind === "failed") { + select({ kind: "startup" }); + } else { + runtime = startupRace.runtime; + } + + if (runtime !== undefined) { + void runtime.closed.then( + (result: RuntimeTermination) => { + termination = result; + select(reasonForRuntime(result)); + }, + () => select({ kind: "runtime-fatal" }), + ); + } + + const reason = await selected.promise; + let closeFailed = termination?.close_failed ?? false; + + if (runtime !== undefined) { + const closeRejected = await closeOnce(runtime); + closeFailed ||= closeRejected; + + if (termination === undefined) { + try { + termination = await runtime.closed; + closeFailed ||= termination.close_failed; + } catch { + closeFailed = true; + } + } + } + + let exitCode: number; + switch (reason.kind) { + case "startup": + writeDiagnostic("ARCHFLOW_MCP_START_FAILED"); + exitCode = 1; + break; + case "runtime-fatal": + writeDiagnostic("ARCHFLOW_MCP_TRANSPORT_ERROR"); + exitCode = 1; + break; + case "eof": + exitCode = closeFailed ? 1 : 0; + if (closeFailed) { + writeDiagnostic("ARCHFLOW_MCP_CLOSE_FAILED"); + } + break; + case "signal": + exitCode = reason.code; + if (closeFailed) { + writeDiagnostic("ARCHFLOW_MCP_CLOSE_FAILED"); + } + break; + } + + setExitCode(exitCode); + } finally { + bindings.signals.off("SIGINT", onSigint); + bindings.signals.off("SIGTERM", onSigterm); + } +} diff --git a/src/mcp/sdk-adapter.ts b/src/mcp/sdk-adapter.ts new file mode 100644 index 00000000..fe7ade17 --- /dev/null +++ b/src/mcp/sdk-adapter.ts @@ -0,0 +1,492 @@ +import { Buffer } from "node:buffer"; +import type { Readable, Writable } from "node:stream"; +import { isDeepStrictEqual } from "node:util"; + +import { + ProtocolError as SdkProtocolError, + Server, + specTypeSchemas, + type JSONRPCMessage, + type ListToolsResult, + type Transport +} from "@modelcontextprotocol/server"; + +import { + connectionContextFactory, + createInvocationContext, + type ConnectionContext +} from "../contracts/contexts.js"; +import type { ProtocolError } from "../contracts/errors.js"; +import { createJsonLineFramer, type IngressFrame } from "./framing.js"; +import { createSendQueue, type SendSource } from "./send-queue.js"; +import { + createToolBoundary, + type ToolBoundaryOutcome, + type ToolHandlerRegistry +} from "./server.js"; +import { + createSessionController, + type ArgumentsCandidate, + type ExpectedProjection, + type JsonRpcId, + type NameCandidate, + type SessionAction +} from "./session.js"; +import { ADVERTISED_TOOL_CATALOGUE } from "./tools.js"; + +export interface McpRuntimeOptions { + readonly input: Readable; + readonly output: Writable; + readonly workingDirectory: string; + readonly handlers?: ToolHandlerRegistry; +} + +export type RuntimeTermination = Readonly<{ + reason: "caller-close" | "input-eof" | "input-error" | "output-error" | "protocol-fatal"; + close_failed: boolean; +}>; + +export interface McpRuntimeHandle { + readonly close: () => Promise; + readonly closed: Promise; +} + +const PROTOCOL_VERSION = "2025-11-25"; +const CONNECTION_ID = "connection-1"; +const JSON_RPC = "2.0"; + +interface ForwardedCall { + readonly requestToken: string; + readonly externalId: JsonRpcId; + readonly nameCandidate: NameCandidate; + readonly argumentsCandidate: ArgumentsCandidate; +} + +interface Deferred { + readonly promise: Promise; + readonly resolve: (value: T) => void; +} + +function deferred(): Deferred { + let resolve!: (value: T) => void; + const promise = new Promise((settle) => { resolve = settle; }); + return { promise, resolve }; +} + +function isObject(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function canonicalMessage(value: Readonly>): Uint8Array { + const message: Record = { jsonrpc: JSON_RPC }; + if (Object.hasOwn(value, "id")) message.id = value.id; + if (Object.hasOwn(value, "result")) { + message.result = value.result; + } else if (Object.hasOwn(value, "error")) { + const supplied = value.error; + if (!isObject(supplied)) throw new TypeError("an error response must contain an error object"); + const error: Record = { code: supplied.code, message: supplied.message }; + if (Object.hasOwn(supplied, "data")) error.data = supplied.data; + message.error = error; + } else { + throw new TypeError("a response must contain a result or error"); + } + return Buffer.from(`${JSON.stringify(message)}\n`, "utf8"); +} + +const PROTOCOL_CODES = Object.freeze({ + TOOL_NOT_FOUND: -32001, + TOOL_DISABLED: -32002, + UNSUPPORTED_PROTOCOL: -32003, + INITIALIZATION_REPEATED: -32004 +} satisfies { + readonly TOOL_NOT_FOUND: -32001; + readonly TOOL_DISABLED: -32002; + readonly UNSUPPORTED_PROTOCOL: -32003; + readonly INITIALIZATION_REPEATED: -32004; +}); + +function protocolCode(error: ProtocolError): number { + return PROTOCOL_CODES[error.code]; +} + +function protocolResponse(id: JsonRpcId, error: ProtocolError): Readonly> { + return { jsonrpc: JSON_RPC, id, error: { code: protocolCode(error), message: error.code, data: error } }; +} + +function internalResponse(id: JsonRpcId): Readonly> { + return { jsonrpc: JSON_RPC, id, error: { code: -32603, message: "Internal error" } }; +} + +function wireResult(outcome: Extract): unknown { + return JSON.parse(JSON.stringify(outcome.result)) as unknown; +} + +function projectOutcome( + server: Server, + id: JsonRpcId, + expected: ExpectedProjection +): Readonly> { + const outcome = expected.outcome; + if (outcome.kind === "protocol-error") return protocolResponse(id, outcome.error.value); + const descriptor = ADVERTISED_TOOL_CATALOGUE.find(({ name }) => name === outcome.tool); + if (descriptor === undefined) throw new TypeError("the projected tool is not advertised"); + const result = outcome.result; + const structuredContent = wireResult(outcome); + const projected = server.projectCallToolResult({ + structuredContent, + content: [{ type: "text", text: JSON.stringify(structuredContent) }], + isError: !result.ok + }, descriptor.outputSchema); + return { jsonrpc: JSON_RPC, id, result: projected }; +} + +function matchesExpectedProjection( + server: Server, + message: Readonly>, + expected: ExpectedProjection +): boolean { + const outcome = expected.outcome; + if (outcome.kind === "protocol-error") { + const error = message.error; + return isObject(error) && error.message === outcome.error.value.code && + isDeepStrictEqual(error.data, outcome.error.value); + } + if (!Object.hasOwn(message, "result")) return false; + const expectedMessage = projectOutcome(server, 0, expected); + return isDeepStrictEqual(message.result, expectedMessage.result); +} + +export async function startMcpRuntime(options: McpRuntimeOptions): Promise { + if (!isObject(options) || typeof options.workingDirectory !== "string") { + throw new TypeError("valid MCP runtime options are required"); + } + + const handlers = options.handlers ?? {}; + const boundary = createToolBoundary(handlers); + const session = createSessionController({ connectionId: CONNECTION_ID }); + const startup = connectionContextFactory.captureStartup({ + connection_id: CONNECTION_ID, + startup_repository_candidate: { working_directory: options.workingDirectory } + }); + const server = new Server( + { name: "archflow-mcp", version: "0.0.0" }, + { supportedProtocolVersions: [PROTOCOL_VERSION] } + ); + server.registerCapabilities({ tools: {} }); + + const framer = createJsonLineFramer(); + const forwardedCalls = new Map(); + const sdkValidationCandidates = new Set(); + const closed = deferred(); + let connection: ConnectionContext | undefined; + let closing = false; + let terminated = false; + let processing = false; + let eofPending = false; + let closePromise: Promise | undefined; + + const onObservedOutputError = (): void => { void terminate("output-error"); }; + options.output.on("error", onObservedOutputError); + + const removeInputListeners = (): void => { + options.input.off("data", onData); + options.input.off("end", onEnd); + options.input.off("error", onInputError); + }; + + const queue = createSendQueue( + options.output, + (paused) => { + if (closing) return; + if (paused) options.input.pause(); + else { + options.input.resume(); + drainFrames(); + } + }, + () => { void terminate("output-error"); } + ); + + const enqueue = ( + source: SendSource, + message: Readonly>, + requestToken?: string, + expectedProjection?: ExpectedProjection + ): Promise => { + if (closing) return Promise.reject(new Error("MCP runtime is closing")); + let selected = message; + try { + if (expectedProjection !== undefined) { + const id = message.id; + if (typeof id !== "string" && typeof id !== "number") throw new TypeError("missing response ID"); + selected = matchesExpectedProjection(server, message, expectedProjection) + ? projectOutcome(server, id, expectedProjection) + : internalResponse(id); + } + const receipt = queue.enqueue({ source, frame: canonicalMessage(selected), ...(requestToken === undefined ? {} : { requestToken }) }); + void receipt.admitted.then( + () => { + session.onSendAdmitted(requestToken); + drainFrames(); + }, + () => undefined + ); + void receipt.completed.then( + () => { if (requestToken !== undefined) session.onRouteSettled(requestToken); }, + () => undefined + ); + return receipt.completed; + } catch { + if (requestToken !== undefined && typeof message.id !== "undefined") { + try { + const fallback = queue.enqueue({ source: "fallback", frame: canonicalMessage(internalResponse(message.id as JsonRpcId)), requestToken }); + void fallback.admitted.then(() => session.onSendAdmitted(requestToken), () => undefined); + void fallback.completed.then(() => session.onRouteSettled(requestToken), () => undefined); + return fallback.completed; + } catch { + // The terminal path below owns cleanup. + } + } + void terminate("protocol-fatal"); + return Promise.reject(new Error("MCP response projection failed")); + } + }; + + const applyActions = (actions: readonly SessionAction[]): void => { + if (closing) return; + for (const action of actions) { + if (closing) return; + if (action.kind === "protocol-fatal") { + void terminate("protocol-fatal"); + } else if (action.kind === "connection-ready") { + const client = server.getClientVersion(); + const protocolVersion = server.getNegotiatedProtocolVersion(); + if (client === undefined || protocolVersion === undefined) { + void terminate("protocol-fatal"); + return; + } + try { + connection = startup.initialize({ client, host: "unknown", protocol_version: protocolVersion }); + } catch { + void terminate("protocol-fatal"); + } + } else if (action.kind === "send") { + void enqueue(action.source, action.message, action.requestToken, action.expectedProjection).catch(() => undefined); + } else if (action.kind === "validate-cancellation") { + if (specTypeSchemas.CancelledNotification["~standard"].validate(action.message).issues === undefined) { + applyActions(session.acceptSdkMessage({ + kind: "cancellation-accepted", + requestToken: action.requestToken + })); + } + } else { + if (action.route === "tools-call") { + forwardedCalls.set(action.internalId, { + requestToken: action.requestToken, + externalId: action.externalId, + nameCandidate: action.nameCandidate, + argumentsCandidate: action.argumentsCandidate + }); + } + if (action.route === "tools-call" || action.route === "tools-list") { + sdkValidationCandidates.add(action.internalId); + const schema = action.route === "tools-call" + ? specTypeSchemas.CallToolRequest + : specTypeSchemas.ListToolsRequest; + if (schema["~standard"].validate(action.message).issues !== undefined) { + sdkValidationCandidates.delete(action.internalId); + forwardedCalls.delete(action.internalId); + const rejected = session.acceptSdkMessage({ + jsonrpc: JSON_RPC, + id: action.internalId, + error: { code: -32602, message: "Invalid params" } + }); + for (const response of rejected) { + if (response.kind === "send") { + void enqueue("sdk", { + jsonrpc: JSON_RPC, + id: response.message.id, + error: { code: -32602, message: "Invalid params" } + }, response.requestToken).catch(() => undefined); + } else { + applyActions([response]); + } + } + continue; + } + } + transport.onmessage?.(action.message as JSONRPCMessage); + } + } + }; + + const transport: Transport = { + start: async () => undefined, + send: async (message) => { + if (closing) throw new Error("MCP runtime is closing"); + const rawMessage = message as unknown as Record; + const id = Object.hasOwn(rawMessage, "id") ? rawMessage.id : undefined; + if (server.getNegotiatedProtocolVersion() !== undefined && typeof id === "number") { + const token = `request-${id}`; + applyActions(session.acceptSdkMessage({ kind: "initialize-mutated", requestToken: token })); + } + const actions = session.acceptSdkMessage(message); + const completions: Promise[] = []; + for (const action of actions) { + if (action.kind === "send") { + if (typeof id === "number" && sdkValidationCandidates.delete(id) && Object.hasOwn(rawMessage, "error")) { + forwardedCalls.delete(id); + completions.push(enqueue("sdk", { + jsonrpc: JSON_RPC, + id: action.message.id, + error: { code: -32602, message: "Invalid params" } + }, action.requestToken)); + } else { + completions.push(enqueue(action.source, action.message, action.requestToken, action.expectedProjection)); + } + } else { + applyActions([action]); + } + } + await Promise.all(completions); + }, + close: async () => { transport.onclose?.(); } + }; + + server.setRequestHandler("tools/list", async (_request, ctx) => { + if (typeof ctx.mcpReq.id === "number") sdkValidationCandidates.delete(ctx.mcpReq.id); + const token = `request-${String(ctx.mcpReq.id)}`; + try { + return { tools: structuredClone(ADVERTISED_TOOL_CATALOGUE) } as unknown as ListToolsResult; + } finally { + session.onRouteSettled(token); + } + }); + server.setRequestHandler("tools/call", async (_request, ctx) => { + const internalId = ctx.mcpReq.id; + if (typeof internalId === "number") sdkValidationCandidates.delete(internalId); + const record = typeof internalId === "number" ? forwardedCalls.get(internalId) : undefined; + if (record === undefined || connection === undefined || !record.nameCandidate.present) { + throw new SdkProtocolError(-32603, "Internal error"); + } + try { + const args = record.argumentsCandidate.present ? record.argumentsCandidate.value : undefined; + const invocation = createInvocationContext(connection, { + invocation_id: record.requestToken, + transport_metadata: { request_id: record.externalId, operation: "tools/call" } + }, ctx.mcpReq.signal); + const outcome = await boundary.invoke(record.nameCandidate.value, args, invocation); + applyActions(session.acceptSdkMessage({ + kind: "tool-boundary-outcome", + requestToken: record.requestToken, + outcome + })); + if (outcome.kind === "protocol-error") { + const error = outcome.error.value; + throw new SdkProtocolError(protocolCode(error), error.code, error); + } + const descriptor = ADVERTISED_TOOL_CATALOGUE.find(({ name }) => name === outcome.tool); + if (descriptor === undefined) throw new SdkProtocolError(-32603, "Internal error"); + const result = outcome.result; + const structuredContent = wireResult(outcome); + return server.projectCallToolResult({ + structuredContent, + content: [{ type: "text", text: JSON.stringify(structuredContent) }], + isError: !result.ok + }, descriptor.outputSchema); + } finally { + forwardedCalls.delete(Number(internalId)); + session.onRouteSettled(record.requestToken); + } + }); + + function handleFrame(frame: IngressFrame): void { + if (closing) return; + if (frame.kind === "parse-error") { + void enqueue("direct", { jsonrpc: JSON_RPC, id: null, error: { code: -32700, message: "Parse error" } }) + .catch(() => undefined); + if (frame.fatal) void terminate("protocol-fatal"); + return; + } + applyActions(session.accept(frame.value)); + } + + function drainFrames(): void { + if (processing || closing || queue.backpressured || session.state === "INITIALIZING") return; + processing = true; + try { + const frame = framer.next(); + if (frame !== undefined) { + handleFrame(frame); + // SDK dispatch and send admission settle through promises. Yield between + // frames so initialized and a following request in one chunk observe + // the admitted initialize response in protocol order. + queueMicrotask(drainFrames); + } else if (eofPending && !closing && !queue.backpressured) { + const final = framer.finish(); + if (final !== undefined) { + handleFrame(final); + queueMicrotask(drainFrames); + } else if (!closing) { + void terminate("input-eof"); + } + } + } finally { + processing = false; + } + } + + function onData(chunk: Buffer | string): void { + if (closing) return; + const bytes = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk; + framer.append(bytes); + drainFrames(); + } + + function onEnd(): void { + eofPending = true; + drainFrames(); + } + + function onInputError(): void { + void terminate("input-error"); + } + + async function terminate(reason: RuntimeTermination["reason"]): Promise { + if (closePromise !== undefined) return closePromise; + closing = true; + session.close(); + removeInputListeners(); + options.input.pause(); + forwardedCalls.clear(); + sdkValidationCandidates.clear(); + closePromise = (async () => { + let closeFailed = false; + try { await server.close(); } catch { closeFailed = true; } + try { await queue.close(); } catch { closeFailed = true; } + options.output.off("error", onObservedOutputError); + if (!terminated) { + terminated = true; + closed.resolve(Object.freeze({ reason, close_failed: closeFailed })); + } + })(); + return closePromise; + } + + server.oninitialized = () => { + applyActions(session.acceptSdkMessage({ kind: "initialized-accepted" })); + drainFrames(); + }; + + await server.connect(transport); + options.input.on("data", onData); + options.input.on("end", onEnd); + options.input.on("error", onInputError); + options.input.resume(); + + return Object.freeze({ + close: async (): Promise => terminate("caller-close"), + closed: closed.promise + }); +} diff --git a/src/mcp/send-queue.ts b/src/mcp/send-queue.ts new file mode 100644 index 00000000..291248d3 --- /dev/null +++ b/src/mcp/send-queue.ts @@ -0,0 +1,267 @@ +import type { Writable } from "node:stream"; + +export type SendSource = "direct" | "sdk" | "fallback"; + +export interface SendEntry { + readonly source: SendSource; + readonly frame: Uint8Array; + readonly requestToken?: string; +} + +export interface SendReceipt { + readonly admitted: Promise; + readonly completed: Promise; +} + +export interface SendQueue { + readonly backpressured: boolean; + readonly enqueue: (entry: SendEntry) => SendReceipt; + readonly close: () => Promise; +} + +const MAX_ENTRIES = 1_024; +const MAX_BYTES = 10 * 1_024 * 1_024; + +interface Deferred { + readonly promise: Promise; + readonly resolve: () => void; + readonly reject: (reason: unknown) => void; +} + +interface PendingSend { + readonly entry: SendEntry; + readonly admitted: Deferred; + readonly completed: Deferred; + writeReturned: boolean; + callbackCalled: boolean; + callbackError: Error | null | undefined; +} + +function deferred(): Deferred { + let resolvePromise!: () => void; + let rejectPromise!: (reason: unknown) => void; + const promise = new Promise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + + return { promise, resolve: resolvePromise, reject: rejectPromise }; +} + +function asError(value: unknown, fallback: string): Error { + return value instanceof Error ? value : new Error(fallback); +} + +export function createSendQueue( + output: Writable, + onBackpressureChange: (paused: boolean) => void, + onFatal: () => void, +): SendQueue { + const waiting: PendingSend[] = []; + const incomplete = new Set(); + let incompleteBytes = 0; + let paused = false; + let closed = false; + let pumping = false; + + const closeError = new Error("Send queue closed"); + + function notifyBackpressure(value: boolean): boolean { + if (paused === value) { + return true; + } + + paused = value; + try { + onBackpressureChange(value); + return true; + } catch (error: unknown) { + fail(asError(error, "Backpressure notification failed")); + return false; + } + } + + function removeListeners(): void { + output.off("drain", handleDrain); + output.off("error", handleOutputError); + } + + function rejectIncomplete(error: Error): void { + waiting.length = 0; + for (const pending of incomplete) { + if (!pending.writeReturned) { + pending.admitted.reject(error); + } + pending.completed.reject(error); + } + incomplete.clear(); + incompleteBytes = 0; + } + + function shutDown(error: Error, fatal: boolean): void { + if (closed) { + return; + } + + closed = true; + removeListeners(); + const wasPaused = paused; + paused = false; + rejectIncomplete(error); + + if (wasPaused) { + try { + onBackpressureChange(false); + } catch { + // Shutdown is already final; a notification failure cannot widen it. + } + } + + if (fatal) { + try { + onFatal(); + } catch { + // The queue remains closed even if its fatal observer fails. + } + } + } + + function fail(error: Error): void { + shutDown(error, true); + } + + function finish(pending: PendingSend, error?: Error | null): void { + if (!incomplete.has(pending)) { + return; + } + + if (error != null) { + pending.completed.reject(error); + fail(error); + return; + } + + incomplete.delete(pending); + incompleteBytes -= pending.entry.frame.byteLength; + pending.completed.resolve(); + pump(); + } + + function handleWriteCallback( + pending: PendingSend, + error?: Error | null, + ): void { + if (!pending.writeReturned) { + pending.callbackCalled = true; + pending.callbackError = error; + return; + } + finish(pending, error); + } + + function pump(): void { + if (pumping || paused || closed) { + return; + } + + pumping = true; + try { + while (!paused && !closed) { + const pending = waiting.shift(); + if (pending === undefined) { + break; + } + + let accepted: boolean; + try { + accepted = output.write(pending.entry.frame, (error?: Error | null) => { + handleWriteCallback(pending, error); + }); + pending.writeReturned = true; + pending.admitted.resolve(); + } catch (error: unknown) { + pending.writeReturned = true; + const writeError = asError(error, "Output write failed"); + pending.admitted.reject(writeError); + pending.completed.reject(writeError); + incomplete.delete(pending); + incompleteBytes -= pending.entry.frame.byteLength; + fail(writeError); + break; + } + + if (!accepted && !closed) { + notifyBackpressure(true); + } + + if (pending.callbackCalled && !closed) { + finish(pending, pending.callbackError); + } + } + } finally { + pumping = false; + } + } + + function handleDrain(): void { + if (!closed && paused && notifyBackpressure(false)) { + pump(); + } + } + + function handleOutputError(error: Error): void { + fail(asError(error, "Output stream failed")); + } + + output.on("drain", handleDrain); + output.on("error", handleOutputError); + + return { + get backpressured(): boolean { + return paused; + }, + + enqueue(entry: SendEntry): SendReceipt { + const admitted = deferred(); + const completed = deferred(); + const receipt = { admitted: admitted.promise, completed: completed.promise }; + + if (closed) { + admitted.reject(closeError); + completed.reject(closeError); + return receipt; + } + + const nextBytes = incompleteBytes + entry.frame.byteLength; + if ( + entry.frame.byteLength > MAX_BYTES || + incomplete.size >= MAX_ENTRIES || + nextBytes > MAX_BYTES + ) { + const overflowError = new Error("Send queue capacity exceeded"); + admitted.reject(overflowError); + completed.reject(overflowError); + fail(overflowError); + return receipt; + } + + const pending: PendingSend = { + entry, + admitted, + completed, + writeReturned: false, + callbackCalled: false, + callbackError: undefined, + }; + waiting.push(pending); + incomplete.add(pending); + incompleteBytes = nextBytes; + pump(); + return receipt; + }, + + async close(): Promise { + shutDown(closeError, false); + }, + }; +} diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 809b6aee..2d0bbe75 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -197,6 +197,9 @@ export function createToolBoundary(handlers: ToolHandlerRegistry): ToolBoundary return protocolOutcome(createProtocolError("TOOL_NOT_FOUND", { tool_name_digest: toolNameDigest })); } + const classified = classifyVersionedArgs(name, args); + if ("outcome" in classified) return classified.outcome; + const handler = registry[name] as ToolHandler | undefined; if (handler === undefined) { return protocolOutcome(createProtocolError("TOOL_DISABLED", { @@ -205,9 +208,6 @@ export function createToolBoundary(handlers: ToolHandlerRegistry): ToolBoundary })); } - const classified = classifyVersionedArgs(name, args); - if ("outcome" in classified) return classified.outcome; - let returned: unknown; try { returned = await handler(classified.call, context); diff --git a/src/mcp/session.ts b/src/mcp/session.ts new file mode 100644 index 00000000..329ef550 --- /dev/null +++ b/src/mcp/session.ts @@ -0,0 +1,554 @@ +import { Buffer } from "node:buffer"; + +import { createProtocolError } from "../contracts/errors.js"; +import { assertPlainJson, type PlainJsonValue } from "../contracts/plain-json.js"; +import { isToolName } from "../contracts/tool-names.js"; +import { + assertAuthenticToolBoundaryOutcome, + authenticateProtocolError, + type ToolBoundaryOutcome +} from "./server.js"; + +export type SessionState = + | "PRE_INIT" + | "INITIALIZING" + | "INIT_RESPONSE_ACCEPTED" + | "READY" + | "CLOSING" + | "CLOSED"; + +export type RequestState = "executing" | "cancelling" | "response-queued"; +export type JsonRpcId = string | number; +export type SessionRoute = "initialize" | "ping" | "tools-list" | "tools-call"; + +export type NameCandidate = + | Readonly<{ present: false }> + | Readonly<{ present: true; value: string }>; + +export type ArgumentsCandidate = + | Readonly<{ present: false }> + | Readonly<{ present: true; value: unknown }>; + +export type ExpectedProjection = Readonly<{ + kind: "tool-boundary"; + outcome: ToolBoundaryOutcome; +}>; + +export type SessionSdkEvent = + | Readonly<{ + kind: "tool-boundary-outcome"; + requestToken: string; + outcome: ToolBoundaryOutcome; + }> + | Readonly<{ + kind: "initialize-mutated"; + requestToken: string; + }> + | Readonly<{ kind: "initialized-accepted" }> + | Readonly<{ kind: "cancellation-accepted"; requestToken: string }>; + +type BasicRequestRoute = "initialize" | "ping" | "tools-list"; +type BasicRequestForwardAction = { + readonly [R in BasicRequestRoute]: Readonly<{ + kind: "forward-sdk"; + route: R; + message: Readonly>; + requestToken: string; + externalId: JsonRpcId; + internalId: number; + }>; +}[BasicRequestRoute]; + +type RequestForwardAction = + | BasicRequestForwardAction + | Readonly<{ + kind: "forward-sdk"; + route: "tools-call"; + message: Readonly>; + requestToken: string; + externalId: JsonRpcId; + internalId: number; + nameCandidate: NameCandidate; + argumentsCandidate: ArgumentsCandidate; + }>; + +export type SessionAction = + | Readonly<{ + kind: "send"; + source: "direct" | "sdk" | "fallback"; + message: Readonly>; + requestToken?: string; + expectedProjection?: ExpectedProjection; + }> + | RequestForwardAction + | Readonly<{ + kind: "forward-sdk"; + route: "notifications/initialized"; + message: Readonly>; + }> + | Readonly<{ + kind: "validate-cancellation"; + message: Readonly>; + requestToken: string; + externalId: JsonRpcId; + internalId: number; + }> + | Readonly<{ + kind: "forward-sdk"; + route: "cancel"; + message: Readonly>; + requestToken: string; + internalId: number; + }> + | Readonly<{ kind: "connection-ready" }> + | Readonly<{ kind: "protocol-fatal" }>; + +export interface SessionOptions { + readonly connectionId: string; + /** Production defaults are the protocol caps; lower values permit bounded harnesses. */ + readonly limits?: Readonly<{ + readonly seenIds?: number; + readonly seenIdBytes?: number; + readonly internalId?: number; + }>; +} + +export interface SessionController { + readonly state: SessionState; + readonly accept: (message: unknown) => readonly SessionAction[]; + readonly acceptSdkMessage: (message: unknown) => readonly SessionAction[]; + readonly onSendAdmitted: (requestToken?: string) => void; + readonly onRouteSettled: (requestToken: string) => void; + readonly close: () => void; +} + +type AdmissionTransition = "initialize-success" | "initialize-error" | "ordinary"; + +interface RequestRecord { + readonly token: string; + readonly externalId: JsonRpcId; + readonly internalId: number; + readonly method: string; + readonly route: SessionRoute; + readonly nameCandidate: NameCandidate; + readonly argumentsCandidate: ArgumentsCandidate; + state: RequestState; + initializeMutated: boolean; + admissionTransition?: AdmissionTransition; + outcome?: ToolBoundaryOutcome; +} + +const JSON_RPC = "2.0"; +const MAX_SEEN_IDS = 65_536; +const MAX_SEEN_ID_BYTES = 10 * 1024 * 1024; +const REQUEST_KEYS = new Set(["jsonrpc", "id", "method", "params"]); +const NOTIFICATION_KEYS = new Set(["jsonrpc", "method", "params"]); +const LIST_KEYS = new Set(["_meta"]); +const CALL_KEYS = new Set(["_meta", "task", "name", "arguments"]); + +function deepFreeze(value: T): T { + if (value !== null && typeof value === "object" && !Object.isFrozen(value)) { + for (const child of Object.values(value)) deepFreeze(child); + Object.freeze(value); + } + return value; +} + +function copiedObject(value: Record): Readonly> { + return deepFreeze(structuredClone(value as PlainJsonValue) as Record); +} + +function plainObject(value: unknown): value is Record { + if (value === null || typeof value !== "object" || Array.isArray(value)) return false; + try { + assertPlainJson(value, "JSON-RPC message"); + return true; + } catch { + return false; + } +} + +function hasOnlyKeys(value: Record, allowed: ReadonlySet): boolean { + return Object.keys(value).every((key) => allowed.has(key)); +} + +function normalizeId(value: unknown): JsonRpcId | undefined { + if (typeof value === "string") return value; + if (typeof value !== "number" || !Number.isSafeInteger(value)) return undefined; + return Object.is(value, -0) ? 0 : value; +} + +function idKey(id: JsonRpcId): string { + return typeof id === "string" ? `s:${id}` : `n:${id}`; +} + +function errorMessage(id: JsonRpcId | null, code: number, message: string, data?: unknown): Readonly> { + const error: Record = { code, message }; + if (data !== undefined) error.data = data; + return deepFreeze({ jsonrpc: JSON_RPC, id, error: deepFreeze(error) }); +} + +function direct(message: Readonly>): readonly SessionAction[] { + return [deepFreeze({ kind: "send" as const, source: "direct" as const, message })]; +} + +function invalidRequest(id: JsonRpcId | null): readonly SessionAction[] { + return direct(errorMessage(id, -32600, "Invalid Request")); +} + +function invalidParams(id: JsonRpcId): readonly SessionAction[] { + return direct(errorMessage(id, -32602, "Invalid params")); +} + +function methodNotFound(id: JsonRpcId): readonly SessionAction[] { + return direct(errorMessage(id, -32601, "Method not found")); +} + +function limits(options: SessionOptions): { seenIds: number; seenIdBytes: number; internalId: number } { + const supplied = options.limits ?? {}; + const bounded = (value: number | undefined, maximum: number, label: string): number => { + const selected = value ?? maximum; + if (!Number.isSafeInteger(selected) || selected < 1 || selected > maximum) { + throw new TypeError(`${label} must be a positive safe integer no greater than ${maximum}`); + } + return selected; + }; + return { + seenIds: bounded(supplied.seenIds, MAX_SEEN_IDS, "seen ID limit"), + seenIdBytes: bounded(supplied.seenIdBytes, MAX_SEEN_ID_BYTES, "seen ID byte limit"), + internalId: bounded(supplied.internalId, Number.MAX_SAFE_INTEGER, "internal ID limit") + }; +} + +export function createSessionController(options: SessionOptions): SessionController { + if (!plainObject(options as unknown)) throw new TypeError("session options must be a plain object"); + if (typeof options.connectionId !== "string") throw new TypeError("a connection ID is required"); + // The protocol constructor is the authority for the exact safe connection-ID vocabulary. + createProtocolError("INITIALIZATION_REPEATED", { connection_id: options.connectionId }); + const caps = limits(options); + const seen = new Set(); + const byToken = new Map(); + const byInternalId = new Map(); + const byExternalId = new Map(); + const pendingCancellations = new Map>>(); + let currentState: SessionState = "PRE_INIT"; + let seenBytes = 0; + let nextInternalId = 1; + + const fatal = (): readonly SessionAction[] => { + if (currentState === "CLOSING" || currentState === "CLOSED") return []; + currentState = "CLOSING"; + byToken.clear(); + byInternalId.clear(); + byExternalId.clear(); + pendingCancellations.clear(); + return [deepFreeze({ kind: "protocol-fatal" as const })]; + }; + + const admitId = (id: JsonRpcId): "new" | "seen" | "fatal" => { + const key = idKey(id); + if (seen.has(key)) return "seen"; + const bytes = Buffer.byteLength(key, "utf8"); + if (seen.size >= caps.seenIds || seenBytes + bytes > caps.seenIdBytes) return "fatal"; + seen.add(key); + seenBytes += bytes; + return "new"; + }; + + const allocate = ( + externalId: JsonRpcId, + method: string, + route: SessionRoute, + nameCandidate: NameCandidate = deepFreeze({ present: false }), + argumentsCandidate: ArgumentsCandidate = deepFreeze({ present: false }) + ): RequestRecord | undefined => { + if (nextInternalId > caps.internalId || !Number.isSafeInteger(nextInternalId)) return undefined; + const internalId = nextInternalId; + nextInternalId += 1; + const token = `request-${internalId}`; + const record: RequestRecord = { + token, + externalId, + internalId, + method, + route, + nameCandidate, + argumentsCandidate, + state: "executing", + initializeMutated: false + }; + byToken.set(token, record); + byInternalId.set(internalId, record); + byExternalId.set(idKey(externalId), record); + return record; + }; + + const forward = (record: RequestRecord, message: Record): readonly SessionAction[] => { + const rewritten = copiedObject({ ...message, id: record.internalId }); + if (record.route === "tools-call") { + return [deepFreeze({ + kind: "forward-sdk" as const, + route: "tools-call" as const, + message: rewritten, + requestToken: record.token, + externalId: record.externalId, + internalId: record.internalId, + nameCandidate: record.nameCandidate, + argumentsCandidate: record.argumentsCandidate + })]; + } + return [deepFreeze({ + kind: "forward-sdk" as const, + route: record.route, + message: rewritten, + requestToken: record.token, + externalId: record.externalId, + internalId: record.internalId + }) as RequestForwardAction]; + }; + + const acceptRequest = (message: Record): readonly SessionAction[] => { + const normalizedId = normalizeId(message.id); + if (message.jsonrpc !== JSON_RPC || typeof message.method !== "string" || normalizedId === undefined) { + return invalidRequest(null); + } + const idAdmission = admitId(normalizedId); + if (idAdmission === "seen") return invalidRequest(null); + if (idAdmission === "fatal") return fatal(); + if (!hasOnlyKeys(message, REQUEST_KEYS)) return invalidRequest(normalizedId); + + const method = message.method; + if (method === "initialize") { + if (currentState !== "PRE_INIT") { + const error = authenticateProtocolError(createProtocolError("INITIALIZATION_REPEATED", { + connection_id: options.connectionId + })); + return direct(errorMessage(normalizedId, -32004, "INITIALIZATION_REPEATED", error.value)); + } + const record = allocate(normalizedId, method, "initialize"); + if (record === undefined) return fatal(); + currentState = "INITIALIZING"; + return forward(record, message); + } + + if (currentState === "PRE_INIT") return invalidRequest(normalizedId); + + if (method === "ping") { + const record = allocate(normalizedId, method, "ping"); + return record === undefined ? fatal() : forward(record, message); + } + + if (method === "tools/list") { + if (currentState !== "READY") return invalidRequest(normalizedId); + if (Object.hasOwn(message, "params")) { + if (!plainObject(message.params) || !hasOnlyKeys(message.params, LIST_KEYS)) return invalidParams(normalizedId); + } + const record = allocate(normalizedId, method, "tools-list"); + return record === undefined ? fatal() : forward(record, message); + } + + if (method === "tools/call") { + if (currentState !== "READY") return invalidRequest(normalizedId); + if (!plainObject(message.params) || !hasOnlyKeys(message.params, CALL_KEYS)) return invalidParams(normalizedId); + const params = message.params; + if (typeof params.name !== "string") return invalidParams(normalizedId); + const nameCandidate = deepFreeze({ present: true as const, value: params.name }); + const argumentsCandidate: ArgumentsCandidate = Object.hasOwn(params, "arguments") + ? deepFreeze({ present: true as const, value: structuredClone(params.arguments as PlainJsonValue) }) + : deepFreeze({ present: false as const }); + if (argumentsCandidate.present && !plainObject(argumentsCandidate.value) && !isToolName(params.name)) { + return invalidParams(normalizedId); + } + const record = allocate(normalizedId, method, "tools-call", nameCandidate, argumentsCandidate); + if (record === undefined) return fatal(); + let forwarded = message; + if (argumentsCandidate.present && !plainObject(argumentsCandidate.value)) { + forwarded = { + ...message, + params: { ...params, name: params.name, arguments: {} } + }; + } + return forward(record, forwarded); + } + + return currentState === "READY" ? methodNotFound(normalizedId) : invalidRequest(normalizedId); + }; + + const acceptNotification = (message: Record): readonly SessionAction[] => { + if (message.jsonrpc !== JSON_RPC || typeof message.method !== "string" || !hasOnlyKeys(message, NOTIFICATION_KEYS)) return []; + if (message.method === "notifications/initialized") { + if (currentState !== "INIT_RESPONSE_ACCEPTED") return []; + return [deepFreeze({ + kind: "forward-sdk" as const, + message: copiedObject(message), + route: "notifications/initialized" as const + })]; + } + if (message.method !== "notifications/cancelled" || !plainObject(message.params)) return []; + const target = normalizeId(message.params.requestId); + if (target === undefined) return []; + const record = byExternalId.get(idKey(target)); + if (record === undefined || record.route === "initialize" || record.state !== "executing") return []; + const candidate = copiedObject(message); + pendingCancellations.set(record.token, candidate); + return [deepFreeze({ + kind: "validate-cancellation" as const, + message: candidate, + requestToken: record.token, + externalId: record.externalId, + internalId: record.internalId + })]; + }; + + const accept = (message: unknown): readonly SessionAction[] => { + if (currentState === "CLOSING" || currentState === "CLOSED") return []; + if (!plainObject(message)) return invalidRequest(null); + if (Object.hasOwn(message, "id") && Object.hasOwn(message, "method")) return acceptRequest(message); + if (!Object.hasOwn(message, "id") && Object.hasOwn(message, "method")) return acceptNotification(message); + // This runtime initiates no requests. Any syntactically valid response is unmatched, + // and malformed response-like input is also silent to avoid response loops. + if (Object.hasOwn(message, "id") && message.jsonrpc === JSON_RPC) return []; + return invalidRequest(null); + }; + + const acceptSdkEvent = (event: SessionSdkEvent): readonly SessionAction[] => { + if (event.kind === "initialized-accepted") { + if (currentState !== "INIT_RESPONSE_ACCEPTED") return []; + currentState = "READY"; + return [deepFreeze({ kind: "connection-ready" as const })]; + } + const record = byToken.get(event.requestToken); + if (record === undefined || record.state === "response-queued") return []; + if (event.kind === "cancellation-accepted") { + const candidate = pendingCancellations.get(record.token); + if (candidate === undefined || record.route === "initialize" || record.state !== "executing") return []; + pendingCancellations.delete(record.token); + record.state = "cancelling"; + const params = candidate.params as Record; + return [deepFreeze({ + kind: "forward-sdk" as const, + route: "cancel" as const, + message: copiedObject({ ...candidate, params: { ...params, requestId: record.internalId } }), + requestToken: record.token, + internalId: record.internalId + })]; + } + if (event.kind === "initialize-mutated") { + if (record.route === "initialize") record.initializeMutated = true; + return []; + } + assertAuthenticToolBoundaryOutcome(event.outcome); + if (record.route !== "tools-call") return fatal(); + record.outcome = event.outcome; + return []; + }; + + const isSdkEvent = (value: unknown): value is SessionSdkEvent => { + if (value === null || typeof value !== "object" || Array.isArray(value)) return false; + try { + const candidate = value as Record; + const kind = Object.getOwnPropertyDescriptor(candidate, "kind"); + if (kind === undefined || !("value" in kind)) return false; + if (kind.value === "initialized-accepted") return true; + const token = Object.getOwnPropertyDescriptor(candidate, "requestToken"); + if (token === undefined || !("value" in token)) return false; + if (typeof token.value !== "string") return false; + return kind.value === "initialize-mutated" || kind.value === "tool-boundary-outcome" || + kind.value === "cancellation-accepted"; + } catch { + return false; + } + }; + + const acceptSdkMessage = (message: unknown): readonly SessionAction[] => { + if (currentState === "CLOSING" || currentState === "CLOSED") return []; + if (isSdkEvent(message)) return acceptSdkEvent(message); + if (!plainObject(message)) return fatal(); + const internalId = normalizeId(message.id); + if (typeof internalId !== "number" || internalId <= 0) return []; + const record = byInternalId.get(internalId); + if (record === undefined || record.state === "response-queued") return []; + const hasResult = Object.hasOwn(message, "result"); + const hasError = Object.hasOwn(message, "error"); + if (message.jsonrpc !== JSON_RPC || hasResult === hasError) return fatal(); + + let projected: Readonly>; + let source: "sdk" | "fallback" = "sdk"; + if (record.route === "initialize") { + if (hasError) { + if (record.initializeMutated) return fatal(); + projected = errorMessage(record.externalId, -32602, "Invalid params"); + record.admissionTransition = "initialize-error"; + } else { + projected = copiedObject({ jsonrpc: JSON_RPC, id: record.externalId, result: message.result }); + record.admissionTransition = "initialize-success"; + } + } else { + projected = copiedObject(hasResult + ? { jsonrpc: JSON_RPC, id: record.externalId, result: message.result } + : { jsonrpc: JSON_RPC, id: record.externalId, error: message.error }); + record.admissionTransition = "ordinary"; + if (record.route === "tools-call" && record.outcome === undefined) { + projected = errorMessage(record.externalId, -32603, "Internal error"); + source = "fallback"; + } + } + record.state = "response-queued"; + const expectedProjection = record.outcome === undefined + ? undefined + : deepFreeze({ kind: "tool-boundary" as const, outcome: record.outcome }); + const action = { + kind: "send" as const, + source, + message: projected, + requestToken: record.token, + ...(expectedProjection === undefined ? {} : { expectedProjection }) + }; + return [deepFreeze(action)]; + }; + + const removeRecord = (record: RequestRecord): void => { + byToken.delete(record.token); + byInternalId.delete(record.internalId); + byExternalId.delete(idKey(record.externalId)); + pendingCancellations.delete(record.token); + }; + + const onSendAdmitted = (requestToken?: string): void => { + if (currentState === "CLOSING" || currentState === "CLOSED" || requestToken === undefined) return; + const record = byToken.get(requestToken); + if (record === undefined || record.state !== "response-queued") return; + const transition = record.admissionTransition; + removeRecord(record); + if (transition === "initialize-success" && currentState === "INITIALIZING") { + currentState = "INIT_RESPONSE_ACCEPTED"; + } else if (transition === "initialize-error" && currentState === "INITIALIZING") { + currentState = "PRE_INIT"; + } + }; + + const onRouteSettled = (requestToken: string): void => { + if (currentState === "CLOSING" || currentState === "CLOSED") return; + const record = byToken.get(requestToken); + if (record?.state === "cancelling") removeRecord(record); + }; + + const controller: SessionController = { + get state(): SessionState { + return currentState; + }, + accept, + acceptSdkMessage, + onSendAdmitted, + onRouteSettled, + close: (): void => { + if (currentState === "CLOSED") return; + currentState = "CLOSED"; + byToken.clear(); + byInternalId.clear(); + byExternalId.clear(); + pendingCancellations.clear(); + } + }; + return Object.freeze(controller); +} diff --git a/test/fixtures/mcp/runtime/adversarial-bytes.json b/test/fixtures/mcp/runtime/adversarial-bytes.json new file mode 100644 index 00000000..8dbaaecb --- /dev/null +++ b/test/fixtures/mcp/runtime/adversarial-bytes.json @@ -0,0 +1,6 @@ +{ + "malformed_json_utf8": "bm90LWpzb24K", + "invalid_utf8": "wyh7fQo=", + "partial_json_utf8": "eyJqc29ucnBjIjoiMi4wIiw=", + "parse_error_frame_utf8": "eyJqc29ucnBjIjoiMi4wIiwiaWQiOm51bGwsImVycm9yIjp7ImNvZGUiOi0zMjcwMCwibWVzc2FnZSI6IlBhcnNlIGVycm9yIn19Cg==" +} diff --git a/test/fixtures/mcp/runtime/calls.json b/test/fixtures/mcp/runtime/calls.json new file mode 100644 index 00000000..a7974b45 --- /dev/null +++ b/test/fixtures/mcp/runtime/calls.json @@ -0,0 +1,52 @@ +{ + "list": { + "jsonrpc": "2.0", + "id": "list-1", + "method": "tools/list", + "params": {} + }, + "unknown": { + "jsonrpc": "2.0", + "id": "call-unknown", + "method": "tools/call", + "params": { + "name": "unknown_tool", + "arguments": {} + } + }, + "missing_arguments": { + "jsonrpc": "2.0", + "id": "call-missing", + "method": "tools/call", + "params": { + "name": "archflow_state" + } + }, + "non_object_arguments": { + "jsonrpc": "2.0", + "id": "call-non-object", + "method": "tools/call", + "params": { + "name": "archflow_state", + "arguments": "not-an-object" + } + }, + "valid_disabled": { + "jsonrpc": "2.0", + "id": "call-disabled", + "method": "tools/call", + "params": { + "name": "archflow_state", + "arguments": { + "schema_version": "1", + "task_id": "task-1", + "intent_id": "intent-1", + "expected_revision": 2, + "input_fingerprint": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "phase_instance": "phase-impl-2", + "step": "produce", + "status": "succeeded" + } + } + } +} diff --git a/test/fixtures/mcp/runtime/initialize.json b/test/fixtures/mcp/runtime/initialize.json new file mode 100644 index 00000000..9912f385 --- /dev/null +++ b/test/fixtures/mcp/runtime/initialize.json @@ -0,0 +1,54 @@ +{ + "request": { + "jsonrpc": "2.0", + "id": "initialize-1", + "method": "initialize", + "params": { + "protocolVersion": "2025-11-25", + "capabilities": {}, + "clientInfo": { + "name": "archflow-integration-test", + "version": "1.0.0" + } + } + }, + "response": { + "jsonrpc": "2.0", + "id": "initialize-1", + "result": { + "protocolVersion": "2025-11-25", + "capabilities": { + "tools": {} + }, + "serverInfo": { + "name": "archflow-mcp", + "version": "0.0.0" + } + } + }, + "initialized": { + "jsonrpc": "2.0", + "method": "notifications/initialized" + }, + "malformed_request": { + "jsonrpc": "2.0", + "id": "malformed-initialize", + "method": "initialize", + "params": { + "protocolVersion": "2025-11-25", + "capabilities": {}, + "clientInfo": { + "name": 1, + "version": "invalid" + } + } + }, + "malformed_response": { + "jsonrpc": "2.0", + "id": "malformed-initialize", + "error": { + "code": -32602, + "message": "Invalid params" + } + } +} diff --git a/test/integration/mcp-stdio.test.ts b/test/integration/mcp-stdio.test.ts new file mode 100644 index 00000000..e3ad5c3f --- /dev/null +++ b/test/integration/mcp-stdio.test.ts @@ -0,0 +1,293 @@ +import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import { createProjectError, createProtocolError } from "../../src/contracts/errors.js"; +import { ADVERTISED_TOOL_CATALOGUE } from "../../src/mcp/tools.js"; +import adversarial from "../fixtures/mcp/runtime/adversarial-bytes.json" with { type: "json" }; +import calls from "../fixtures/mcp/runtime/calls.json" with { type: "json" }; +import initialize from "../fixtures/mcp/runtime/initialize.json" with { type: "json" }; + +const TEST_TIMEOUT_MS = 20_000; +const PROCESS_TIMEOUT_MS = 8_000; +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); +const jsonLine = (value: unknown): string => `${JSON.stringify(value)}\n`; + +function expectExactBytes(actual: Buffer, expected: Buffer): void { + if (actual.equals(expected)) return; + const commonLength = Math.min(actual.length, expected.length); + let offset = 0; + while (offset < commonLength && actual[offset] === expected[offset]) offset += 1; + const start = Math.max(0, offset - 80); + const end = offset + 160; + throw new Error( + `byte mismatch at offset ${offset}: received ${actual.length} bytes, expected ${expected.length}\n` + + `received: ${JSON.stringify(actual.toString("utf8", start, end))}\n` + + `expected: ${JSON.stringify(expected.toString("utf8", start, end))}`, + ); +} + +interface RunningRuntime { + readonly child: ChildProcessWithoutNullStreams; + readonly stdout: Buffer[]; + readonly stderr: Buffer[]; + readonly waitForLines: (count: number) => Promise; + readonly waitForExit: () => Promise>; + readonly stop: () => void; +} + +let outputDirectory = ""; +let runtimeBundle = ""; + +function startRuntime(): RunningRuntime { + const child = spawn(process.execPath, [runtimeBundle], { + cwd: repositoryRoot, + stdio: ["pipe", "pipe", "pipe"], + }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + child.stdin.on("error", () => undefined); + child.stdout.on("data", (chunk: Buffer) => stdout.push(Buffer.from(chunk))); + child.stderr.on("data", (chunk: Buffer) => stderr.push(Buffer.from(chunk))); + + const exited = new Promise>( + (resolveExit, rejectExit) => { + child.once("error", rejectExit); + child.once("exit", (code, signal) => resolveExit({ code, signal })); + }, + ); + + return { + child, + stdout, + stderr, + waitForLines: async (count) => { + const currentCount = (): number => Buffer.concat(stdout).reduce( + (total, byte) => total + (byte === 0x0a ? 1 : 0), + 0, + ); + if (currentCount() >= count) return; + await new Promise((resolveWait, rejectWait) => { + const timeout = setTimeout(() => finish(new Error(`timed out waiting for ${count} stdout lines`)), PROCESS_TIMEOUT_MS); + const onData = (): void => { + if (currentCount() >= count) finish(); + }; + const onExit = (): void => finish(new Error(`runtime exited after ${currentCount()} stdout lines`)); + const finish = (error?: Error): void => { + clearTimeout(timeout); + child.stdout.off("data", onData); + child.off("exit", onExit); + if (error === undefined) resolveWait(); + else rejectWait(error); + }; + child.stdout.on("data", onData); + child.on("exit", onExit); + }); + }, + waitForExit: async () => { + let timer: NodeJS.Timeout | undefined; + try { + return await Promise.race([ + exited, + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error("runtime did not exit")), PROCESS_TIMEOUT_MS); + }), + ]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } + }, + stop: () => { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + }, + }; +} + +async function complete( + chunks: readonly Uint8Array[], +): Promise> { + const runtime = startRuntime(); + try { + for (const chunk of chunks) runtime.child.stdin.write(chunk); + runtime.child.stdin.end(); + const exit = await runtime.waitForExit(); + return { + stdout: Buffer.concat(runtime.stdout), + stderr: Buffer.concat(runtime.stderr), + ...exit, + }; + } finally { + runtime.stop(); + } +} + +function projectFailure(issueCode: string): Record { + const result = { + schema_version: "1", + ok: false, + error: createProjectError("CONTRACT_INVALID", { + tool: "archflow_state", + issue_code: issueCode, + }), + } as const; + return { + structuredContent: result, + content: [{ type: "text", text: JSON.stringify(result) }], + isError: true, + }; +} + +beforeAll(async () => { + outputDirectory = await mkdtemp(resolve(tmpdir(), "archflow-mcp-integration-")); + const buildProgram = [ + 'import { resolve } from "node:path";', + 'import { pathToFileURL } from "node:url";', + 'const root = process.argv[1];', + 'const output = process.argv[2];', + 'const helper = await import(pathToFileURL(resolve(root, "scripts/build-temp-helper.mjs")));', + 'const bundles = await helper.buildTemporaryBundles(output);', + 'process.stdout.write(bundles.runtimeBundle);', + ].join(""); + const built = spawnSync(process.execPath, ["--input-type=module", "--eval", buildProgram, repositoryRoot, outputDirectory], { + cwd: repositoryRoot, + encoding: "utf8", + timeout: PROCESS_TIMEOUT_MS, + }); + if (built.error !== undefined || built.status !== 0) { + throw built.error ?? new Error(`temporary runtime build failed: ${built.stderr}`); + } + runtimeBundle = built.stdout; + expect(relative(repositoryRoot, runtimeBundle).startsWith("..")).toBe(true); + + const trackedBuildOutput = spawnSync("git", ["ls-files", "--", ".tmp", "dist"], { + cwd: repositoryRoot, + encoding: "utf8", + timeout: PROCESS_TIMEOUT_MS, + }); + expect(trackedBuildOutput.status).toBe(0); + expect(trackedBuildOutput.stdout).toBe(""); +}, TEST_TIMEOUT_MS); + +afterAll(async () => { + if (outputDirectory !== "") await rm(outputDirectory, { recursive: true, force: true }); +}); + +describe("bundled MCP stdio runtime", () => { + it("emits the byte-exact initialize response and exits cleanly on EOF", async () => { + const result = await complete([Buffer.from(jsonLine(initialize.request))]); + + expect(result.stdout).toEqual(Buffer.from(jsonLine(initialize.response))); + expect(result.stderr).toEqual(Buffer.alloc(0)); + expect(result).toMatchObject({ code: 0, signal: null }); + }); + + it("retries initialization after a bounded SDK validation error", async () => { + const retryRequest = { ...initialize.request, id: "initialize-retry" }; + const retryResponse = { ...initialize.response, id: "initialize-retry" }; + const result = await complete([ + Buffer.from(jsonLine(initialize.malformed_request)), + Buffer.from(jsonLine(retryRequest)), + ]); + + expect(result.stdout).toEqual(Buffer.from([ + jsonLine(initialize.malformed_response), + jsonLine(retryResponse), + ].join(""))); + expect(result.stderr).toEqual(Buffer.alloc(0)); + expect(result).toMatchObject({ code: 0, signal: null }); + }); + + it("becomes ready before a same-chunk initialized notification and tool requests", async () => { + const runtime = startRuntime(); + try { + runtime.child.stdin.write(jsonLine(initialize.request)); + await runtime.waitForLines(1); + expect(Buffer.concat(runtime.stdout)).toEqual(Buffer.from(jsonLine(initialize.response))); + + runtime.child.stdin.end([ + jsonLine(initialize.initialized), + jsonLine(calls.list), + jsonLine(calls.unknown), + jsonLine(calls.missing_arguments), + jsonLine(calls.non_object_arguments), + jsonLine(calls.valid_disabled), + ].join("")); + const exit = await runtime.waitForExit(); + + const unknownError = createProtocolError("TOOL_NOT_FOUND", { + tool_name_digest: createHash("sha256").update("unknown_tool").digest("hex"), + }); + const disabledError = createProtocolError("TOOL_DISABLED", { + tool: "archflow_state", + lifecycle_state: "inert-no-handler", + }); + const expected = [ + initialize.response, + { jsonrpc: "2.0", id: "list-1", result: { tools: ADVERTISED_TOOL_CATALOGUE } }, + { jsonrpc: "2.0", id: "call-unknown", error: { code: -32001, message: "TOOL_NOT_FOUND", data: unknownError } }, + { jsonrpc: "2.0", id: "call-missing", result: projectFailure("input-not-object") }, + { jsonrpc: "2.0", id: "call-non-object", result: projectFailure("input-not-object") }, + { jsonrpc: "2.0", id: "call-disabled", error: { code: -32002, message: "TOOL_DISABLED", data: disabledError } }, + ].map(jsonLine).join(""); + + expectExactBytes(Buffer.concat(runtime.stdout), Buffer.from(expected)); + expect(Buffer.concat(runtime.stderr)).toEqual(Buffer.alloc(0)); + expect(exit).toEqual({ code: 0, signal: null }); + } finally { + runtime.stop(); + } + }); + + it.each([ + ["malformed_json_utf8", 0, ""], + ["partial_json_utf8", 0, ""], + ["invalid_utf8", 1, "ARCHFLOW_MCP_TRANSPORT_ERROR\n"], + ] as const)("contains the %s failure without leaking non-protocol stdout", async (fixture, code, diagnostic) => { + const result = await complete([Buffer.from(adversarial[fixture], "base64")]); + + expect(result.stdout).toEqual(Buffer.from(adversarial.parse_error_frame_utf8, "base64")); + expect(result.stderr).toEqual(Buffer.from(diagnostic)); + expect(result).toMatchObject({ code, signal: null }); + }); + + it.each([ + ["SIGINT", 130], + ["SIGTERM", 143], + ] as const)("maps %s to its conventional exit without diagnostics", async (signal, code) => { + const runtime = startRuntime(); + try { + runtime.child.stdin.write(jsonLine(initialize.request)); + await runtime.waitForLines(1); + expect(runtime.child.kill(signal)).toBe(true); + const exit = await runtime.waitForExit(); + + expect(Buffer.concat(runtime.stdout)).toEqual(Buffer.from(jsonLine(initialize.response))); + expect(Buffer.concat(runtime.stderr)).toEqual(Buffer.alloc(0)); + expect(exit).toEqual({ code, signal: null }); + } finally { + runtime.stop(); + } + }); + + it("contains a closed stdout pipe as one transport diagnostic", async () => { + const runtime = startRuntime(); + try { + runtime.child.stdin.write(jsonLine(initialize.request)); + await runtime.waitForLines(1); + runtime.child.stdout.destroy(); + runtime.child.stdin.write(Buffer.from(adversarial.malformed_json_utf8, "base64")); + const exit = await runtime.waitForExit(); + + expect(Buffer.concat(runtime.stdout)).toEqual(Buffer.from(jsonLine(initialize.response))); + expect(Buffer.concat(runtime.stderr)).toEqual(Buffer.from("ARCHFLOW_MCP_TRANSPORT_ERROR\n")); + expect(exit).toEqual({ code: 1, signal: null }); + } finally { + runtime.stop(); + } + }); +}, TEST_TIMEOUT_MS); diff --git a/test/types/mcp-sdk-public-surface.ts b/test/types/mcp-sdk-public-surface.ts new file mode 100644 index 00000000..76f0545c --- /dev/null +++ b/test/types/mcp-sdk-public-surface.ts @@ -0,0 +1,63 @@ +import { + Server, + type CallToolRequest, + type CallToolResult, + type CancelledNotification, + type InitializeRequest, + type JSONRPCMessage, + type ListToolsRequest, + type ListToolsResult, + type MessageExtraInfo, + type ServerContext, + type Transport, + type TransportSendOptions +} from "@modelcontextprotocol/server"; + +const transport = { + start: async (): Promise => undefined, + send: async (_message: JSONRPCMessage, _options?: TransportSendOptions): Promise => undefined, + close: async (): Promise => undefined, + onmessage: (_message: T, _extra?: MessageExtraInfo): void => undefined, + onclose: (): void => undefined, + onerror: (_error: Error): void => undefined, + setProtocolVersion: (_version: string): void => undefined, + setSupportedProtocolVersions: (_versions: string[]): void => undefined +} satisfies Transport; + +const server = new Server( + { name: "phase-4-type-probe", version: "0.0.0" }, + { supportedProtocolVersions: ["2025-11-25"] } +); +server.oninitialized = (): void => undefined; +server.registerCapabilities({ tools: {} }); + +server.setRequestHandler("tools/list", async ( + request: ListToolsRequest, + context: ServerContext +): Promise => { + const id: string | number = context.mcpReq.id; + void request; + void id; + return { tools: [] }; +}); + +server.setRequestHandler("tools/call", async ( + request: CallToolRequest, + context: ServerContext +): Promise => { + const signal: AbortSignal = context.mcpReq.signal; + void request; + void signal; + return { content: [], structuredContent: {} }; +}); + +declare const initializeRequest: InitializeRequest; +declare const listToolsRequest: ListToolsRequest; +declare const callToolRequest: CallToolRequest; +declare const cancelledNotification: CancelledNotification; + +void transport; +void initializeRequest; +void listToolsRequest; +void callToolRequest; +void cancelledNotification; diff --git a/test/unit/mcp-framing.test.ts b/test/unit/mcp-framing.test.ts new file mode 100644 index 00000000..5ca1f94f --- /dev/null +++ b/test/unit/mcp-framing.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from "vitest"; + +import { createJsonLineFramer, type IngressFrame } from "../../src/mcp/framing.js"; + +const MAX_FRAME_BYTES = 10 * 1024 * 1024; +const encoder = new TextEncoder(); + +function bytes(value: string): Uint8Array { + return encoder.encode(value); +} + +function drain(framer: ReturnType): IngressFrame[] { + const frames: IngressFrame[] = []; + let frame: IngressFrame | undefined; + while ((frame = framer.next()) !== undefined) frames.push(frame); + return frames; +} + +describe("JSON-line framing", () => { + it("decodes split Unicode and treats LF and CRLF segments independently", () => { + const framer = createJsonLineFramer(); + const input = bytes('{"message":"🙂"}\n{"line":2}\r\n'); + const split = input.indexOf(0xf0) + 2; + + framer.append(input.subarray(0, split)); + expect(framer.next()).toBeUndefined(); + framer.append(input.subarray(split)); + + expect(drain(framer)).toEqual([ + { kind: "json", value: { message: "🙂" } }, + { kind: "json", value: { line: 2 } } + ]); + expect(framer.retainedBytes).toBe(0); + }); + + it("strips exactly one CR and keeps empty or malformed lines nonfatal", () => { + const framer = createJsonLineFramer(); + framer.append(bytes('\nnot-json\n{"ok":true}\r\n{}\r\r\n')); + + expect(drain(framer)).toEqual([ + { kind: "parse-error", fatal: false }, + { kind: "parse-error", fatal: false }, + { kind: "json", value: { ok: true } }, + { kind: "json", value: {} } + ]); + }); + + it("makes invalid UTF-8 fatal and discards later segments", () => { + const framer = createJsonLineFramer(); + framer.append(new Uint8Array([0x7b, 0x7d, 0x0a, 0xc3, 0x28, 0x0a, 0x7b, 0x7d, 0x0a])); + + expect(framer.next()).toEqual({ kind: "json", value: {} }); + expect(framer.next()).toEqual({ kind: "parse-error", fatal: true }); + expect(framer.next()).toBeUndefined(); + expect(framer.retainedBytes).toBe(0); + + const invalidFinal = createJsonLineFramer(); + invalidFinal.append(new Uint8Array([0xc3])); + expect(invalidFinal.finish()).toEqual({ kind: "parse-error", fatal: true }); + }); + + it("accepts an exact 10 MiB frame and rejects an over-limit frame", () => { + const exact = createJsonLineFramer(); + exact.append(bytes(`"${"a".repeat(MAX_FRAME_BYTES - 2)}"\r\n`)); + const exactFrame = exact.next(); + expect(exactFrame?.kind).toBe("json"); + if (exactFrame?.kind !== "json") throw new Error("expected exact-size JSON frame"); + expect((exactFrame.value as string).length).toBe(MAX_FRAME_BYTES - 2); + + const over = createJsonLineFramer(); + over.append(bytes(`"${"a".repeat(MAX_FRAME_BYTES - 1)}"\n`)); + expect(over.next()).toEqual({ kind: "parse-error", fatal: true }); + expect(over.next()).toBeUndefined(); + }); + + it("bounds retained partial input at exactly 10 MiB", () => { + const exact = createJsonLineFramer(); + exact.append(new Uint8Array(MAX_FRAME_BYTES)); + expect(exact.retainedBytes).toBe(MAX_FRAME_BYTES); + expect(exact.next()).toBeUndefined(); + + const over = createJsonLineFramer(); + over.append(new Uint8Array(MAX_FRAME_BYTES + 1)); + expect(over.next()).toEqual({ kind: "parse-error", fatal: true }); + expect(over.retainedBytes).toBe(0); + }); + + it("drains many lines from one chunk without coupling their results", () => { + const framer = createJsonLineFramer(); + const count = 2_000; + framer.append(bytes(Array.from({ length: count }, (_, index) => `${JSON.stringify(index)}\n`).join(""))); + + const frames = drain(framer); + expect(frames).toHaveLength(count); + expect(frames[0]).toEqual({ kind: "json", value: 0 }); + expect(frames.at(-1)).toEqual({ kind: "json", value: count - 1 }); + }); + + it("reports one nonfatal parse error for a partial final line", () => { + const framer = createJsonLineFramer(); + framer.append(bytes('{"complete":true}\n{"partial":')); + + expect(framer.finish()).toEqual({ kind: "json", value: { complete: true } }); + expect(framer.finish()).toEqual({ kind: "parse-error", fatal: false }); + expect(framer.finish()).toBeUndefined(); + expect(framer.retainedBytes).toBe(0); + }); +}); diff --git a/test/unit/mcp-process-runner.test.ts b/test/unit/mcp-process-runner.test.ts new file mode 100644 index 00000000..fbe9bf6a --- /dev/null +++ b/test/unit/mcp-process-runner.test.ts @@ -0,0 +1,298 @@ +import { EventEmitter } from "node:events"; +import { PassThrough } from "node:stream"; + +import { describe, expect, it, vi } from "vitest"; + +import { + runMcpProcess, + type ProcessBindings, + type RuntimeStarter, +} from "../../src/mcp/process-runner.js"; +import type { + McpRuntimeHandle, + RuntimeTermination, +} from "../../src/mcp/sdk-adapter.js"; + +interface Deferred { + readonly promise: Promise; + readonly resolve: (value: T) => void; + readonly reject: (reason: unknown) => void; +} + +function deferred(): Deferred { + let resolvePromise!: (value: T) => void; + let rejectPromise!: (reason: unknown) => void; + const promise = new Promise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + return { promise, resolve: resolvePromise, reject: rejectPromise }; +} + +function harness(): { + readonly bindings: ProcessBindings; + readonly signals: EventEmitter; + readonly diagnostics: string[]; + readonly exits: number[]; +} { + const signals = new EventEmitter(); + const diagnostic = new PassThrough(); + const diagnostics: string[] = []; + diagnostic.setEncoding("utf8"); + diagnostic.on("data", (chunk: string) => diagnostics.push(chunk)); + const exits: number[] = []; + + return { + bindings: { + input: new PassThrough(), + output: new PassThrough(), + diagnostic, + workingDirectory: "/workspace/project", + signals, + setExitCode: (code) => exits.push(code), + }, + signals, + diagnostics, + exits, + }; +} + +function runtime( + termination: Promise, + close: () => Promise = async () => undefined, +): McpRuntimeHandle { + return { close, closed: termination }; +} + +async function flush(): Promise { + await Promise.resolve(); + await Promise.resolve(); +} + +describe("MCP process runner", () => { + it("passes only runtime options and reports startup failure once", async () => { + const { bindings, signals, diagnostics, exits } = harness(); + const start = vi.fn().mockRejectedValue(new Error("secret")); + + await runMcpProcess(bindings, start); + + expect(start).toHaveBeenCalledWith({ + input: bindings.input, + output: bindings.output, + workingDirectory: "/workspace/project", + }); + expect(diagnostics).toEqual(["ARCHFLOW_MCP_START_FAILED\n"]); + expect(exits).toEqual([1]); + expect(signals.listenerCount("SIGINT")).toBe(0); + expect(signals.listenerCount("SIGTERM")).toBe(0); + }); + + it.each([ + ["input-eof", false, 0, []], + ["input-error", false, 1, ["ARCHFLOW_MCP_TRANSPORT_ERROR\n"]], + ["output-error", false, 1, ["ARCHFLOW_MCP_TRANSPORT_ERROR\n"]], + ["protocol-fatal", false, 1, ["ARCHFLOW_MCP_TRANSPORT_ERROR\n"]], + ["caller-close", false, 1, ["ARCHFLOW_MCP_TRANSPORT_ERROR\n"]], + ["input-eof", true, 1, ["ARCHFLOW_MCP_CLOSE_FAILED\n"]], + ] as const)( + "maps runtime reason %s (close_failed=%s) to exit %s", + async (reason, closeFailed, expectedExit, expectedDiagnostics) => { + const { bindings, signals, diagnostics, exits } = harness(); + const close = vi.fn(async () => undefined); + const start = vi.fn().mockResolvedValue( + runtime(Promise.resolve({ reason, close_failed: closeFailed }), close), + ); + + await runMcpProcess(bindings, start); + + expect(close).toHaveBeenCalledTimes(1); + expect(diagnostics).toEqual(expectedDiagnostics); + expect(exits).toEqual([expectedExit]); + expect(signals.listenerCount("SIGINT")).toBe(0); + expect(signals.listenerCount("SIGTERM")).toBe(0); + }, + ); + + it.each([ + ["SIGINT", 130], + ["SIGTERM", 143], + ] as const)("closes once and preserves the %s exit", async (signal, exit) => { + const { bindings, signals, diagnostics, exits } = harness(); + const closed = deferred(); + const close = vi.fn(async () => { + closed.resolve({ reason: "caller-close", close_failed: false }); + }); + const task = runMcpProcess( + bindings, + vi.fn().mockResolvedValue(runtime(closed.promise, close)), + ); + await flush(); + + signals.emit(signal); + await task; + + expect(close).toHaveBeenCalledTimes(1); + expect(diagnostics).toEqual([]); + expect(exits).toEqual([exit]); + expect(signals.listenerCount("SIGINT")).toBe(0); + expect(signals.listenerCount("SIGTERM")).toBe(0); + }); + + it("keeps the first signal when later fatal events overlap", async () => { + const { bindings, signals, diagnostics, exits } = harness(); + const closed = deferred(); + const close = vi.fn(async () => { + closed.resolve({ reason: "output-error", close_failed: false }); + }); + const task = runMcpProcess( + bindings, + vi.fn().mockResolvedValue(runtime(closed.promise, close)), + ); + await flush(); + + signals.emit("SIGINT"); + signals.emit("SIGTERM"); + await task; + + expect(exits).toEqual([130]); + expect(diagnostics).toEqual([]); + expect(close).toHaveBeenCalledTimes(1); + }); + + it("keeps the first runtime fatal when a later signal overlaps", async () => { + const { bindings, signals, diagnostics, exits } = harness(); + const closed = deferred(); + const close = vi.fn(async () => undefined); + const task = runMcpProcess( + bindings, + vi.fn().mockResolvedValue(runtime(closed.promise, close)), + ); + await flush(); + + closed.resolve({ reason: "input-error", close_failed: false }); + await flush(); + signals.emit("SIGINT"); + await task; + + expect(exits).toEqual([1]); + expect(diagnostics).toEqual(["ARCHFLOW_MCP_TRANSPORT_ERROR\n"]); + expect(close).toHaveBeenCalledTimes(1); + }); + + it("preserves a selected signal but diagnoses a close rejection once", async () => { + const { bindings, signals, diagnostics, exits } = harness(); + const closed = deferred(); + const close = vi.fn(async () => { + closed.resolve({ reason: "caller-close", close_failed: true }); + throw new Error("private close detail"); + }); + const task = runMcpProcess( + bindings, + vi.fn().mockResolvedValue(runtime(closed.promise, close)), + ); + await flush(); + + signals.emit("SIGTERM"); + await task; + + expect(close).toHaveBeenCalledTimes(1); + expect(diagnostics).toEqual(["ARCHFLOW_MCP_CLOSE_FAILED\n"]); + expect(exits).toEqual([143]); + }); + + it("turns EOF plus close rejection into one close diagnostic and exit 1", async () => { + const { bindings, diagnostics, exits } = harness(); + const close = vi.fn().mockRejectedValue(new Error("private close detail")); + + await runMcpProcess( + bindings, + vi.fn().mockResolvedValue( + runtime(Promise.resolve({ reason: "input-eof", close_failed: false }), close), + ), + ); + + expect(close).toHaveBeenCalledTimes(1); + expect(diagnostics).toEqual(["ARCHFLOW_MCP_CLOSE_FAILED\n"]); + expect(exits).toEqual([1]); + }); + + it("keeps a signal selected while startup is pending and cleans listeners", async () => { + const { bindings, signals, diagnostics, exits } = harness(); + const starting = deferred(); + const closed = deferred(); + const close = vi.fn(async () => { + closed.resolve({ reason: "caller-close", close_failed: false }); + }); + const task = runMcpProcess( + bindings, + vi.fn().mockReturnValue(starting.promise), + ); + + signals.emit("SIGINT"); + starting.resolve(runtime(closed.promise, close)); + await task; + await flush(); + + expect(close).toHaveBeenCalledTimes(1); + expect(diagnostics).toEqual([]); + expect(exits).toEqual([130]); + expect(signals.listenerCount("SIGINT")).toBe(0); + expect(signals.listenerCount("SIGTERM")).toBe(0); + }); + + it("completes promptly on a signal when startup never settles", async () => { + const { bindings, signals, diagnostics, exits } = harness(); + const start = vi.fn().mockReturnValue(new Promise(() => undefined)); + const task = runMcpProcess(bindings, start); + + signals.emit("SIGTERM"); + await task; + + expect(start).toHaveBeenCalledTimes(1); + expect(diagnostics).toEqual([]); + expect(exits).toEqual([143]); + expect(signals.listenerCount("SIGINT")).toBe(0); + expect(signals.listenerCount("SIGTERM")).toBe(0); + }); + + it("closes a runtime once when startup resolves after signal completion", async () => { + const { bindings, signals, diagnostics, exits } = harness(); + const starting = deferred(); + const closed = deferred(); + const close = vi.fn(async () => { + closed.resolve({ reason: "caller-close", close_failed: false }); + }); + const task = runMcpProcess( + bindings, + vi.fn().mockReturnValue(starting.promise), + ); + + signals.emit("SIGINT"); + await task; + expect(exits).toEqual([130]); + expect(signals.listenerCount("SIGINT")).toBe(0); + expect(signals.listenerCount("SIGTERM")).toBe(0); + + starting.resolve(runtime(closed.promise, close)); + await flush(); + await flush(); + + expect(close).toHaveBeenCalledTimes(1); + expect(diagnostics).toEqual([]); + }); + + it("does not destroy caller-owned streams", async () => { + const { bindings } = harness(); + + await runMcpProcess( + bindings, + vi.fn().mockResolvedValue( + runtime(Promise.resolve({ reason: "input-eof", close_failed: false })), + ), + ); + + expect(bindings.input.destroyed).toBe(false); + expect(bindings.output.destroyed).toBe(false); + expect(bindings.diagnostic.destroyed).toBe(false); + }); +}); diff --git a/test/unit/mcp-sdk-adapter.test.ts b/test/unit/mcp-sdk-adapter.test.ts new file mode 100644 index 00000000..190e0f18 --- /dev/null +++ b/test/unit/mcp-sdk-adapter.test.ts @@ -0,0 +1,316 @@ +import { PassThrough } from "node:stream"; + +import { describe, expect, it } from "vitest"; + +import { ADVERTISED_TOOL_CATALOGUE } from "../../src/mcp/tools.js"; +import { startMcpRuntime, type McpRuntimeHandle } from "../../src/mcp/sdk-adapter.js"; +import type { ToolHandlerRegistry } from "../../src/mcp/server.js"; + +const digest = "a".repeat(64); +const stateInput = { + schema_version: "1", + task_id: "task-1", + intent_id: "intent-1", + expected_revision: 2, + input_fingerprint: digest, + phase_instance: "phase-impl-3", + step: "produce", + status: "succeeded" +} as const; +const stateSuccess = { + schema_version: "1", + ok: true, + value: { path: "phases/3/result.json", revision: 3, status: "succeeded" } +} as const; + +const initialize = (id: string | number, clientInfo: unknown = { name: "Codex", version: "1" }) => ({ + jsonrpc: "2.0", + id, + method: "initialize", + params: { + protocolVersion: "2025-11-25", + capabilities: {}, + clientInfo + } +}); + +interface Harness { + readonly input: PassThrough; + readonly output: PassThrough; + readonly handle: McpRuntimeHandle; + readonly lines: string[]; + readonly send: (message: unknown) => void; + readonly waitForLines: (count: number) => Promise; +} + +async function harness(handlers?: ToolHandlerRegistry): Promise { + const input = new PassThrough(); + const output = new PassThrough(); + const lines: string[] = []; + let buffered = ""; + output.on("data", (chunk: Buffer) => { + buffered += chunk.toString("utf8"); + for (;;) { + const newline = buffered.indexOf("\n"); + if (newline < 0) break; + lines.push(buffered.slice(0, newline)); + buffered = buffered.slice(newline + 1); + } + }); + const handle = await startMcpRuntime({ + input, + output, + workingDirectory: "/work", + ...(handlers === undefined ? {} : { handlers }) + }); + return { + input, + output, + handle, + lines, + send: (message) => { input.write(`${JSON.stringify(message)}\n`); }, + waitForLines: async (count) => { + const deadline = Date.now() + 2_000; + while (lines.length < count) { + if (Date.now() >= deadline) throw new Error(`timed out waiting for ${count} output lines: ${JSON.stringify(lines)}`); + await new Promise((resolve) => setTimeout(resolve, 5)); + } + await Promise.resolve(); + await Promise.resolve(); + } + }; +} + +async function ready(runtime: Harness): Promise { + runtime.send(initialize("init")); + await runtime.waitForLines(1); + runtime.send({ jsonrpc: "2.0", method: "notifications/initialized" }); +} + +describe("MCP SDK adapter", () => { + it("pins canonical initialize bytes and retries after a prose-free malformed initialize", async () => { + const runtime = await harness(); + runtime.send(initialize(1, { name: 1, version: "bad" })); + await runtime.waitForLines(1); + expect(runtime.lines[0]).toBe('{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid params"}}'); + + runtime.send(initialize(2)); + await runtime.waitForLines(2); + expect(runtime.lines[1]).toBe('{"jsonrpc":"2.0","id":2,"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{}},"serverInfo":{"name":"archflow-mcp","version":"0.0.0"}}}'); + await runtime.handle.close(); + await expect(runtime.handle.closed).resolves.toEqual({ reason: "caller-close", close_failed: false }); + }); + + it("returns the exact advertised catalogue and one LF per response", async () => { + const runtime = await harness(); + await ready(runtime); + runtime.send({ jsonrpc: "2.0", id: "list", method: "tools/list", params: {} }); + await runtime.waitForLines(2); + expect(JSON.parse(runtime.lines[1]!)).toEqual({ jsonrpc: "2.0", id: "list", result: { tools: ADVERTISED_TOOL_CATALOGUE } }); + expect(runtime.lines.every((line) => !line.includes("\n"))).toBe(true); + await runtime.handle.close(); + }); + + it("enters READY only through the SDK initialized hook and preserves same-chunk order", async () => { + const malformed = await harness(); + malformed.send(initialize("init")); + await malformed.waitForLines(1); + malformed.input.write( + `${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized", params: null })}\n` + + `${JSON.stringify({ jsonrpc: "2.0", id: "blocked", method: "tools/list", params: {} })}\n` + ); + await malformed.waitForLines(2); + expect(malformed.lines[1]).toBe( + '{"jsonrpc":"2.0","id":"blocked","error":{"code":-32600,"message":"Invalid Request"}}' + ); + await malformed.handle.close(); + + const valid = await harness(); + valid.send(initialize("init")); + await valid.waitForLines(1); + valid.input.write( + `${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n` + + `${JSON.stringify({ jsonrpc: "2.0", id: "list", method: "tools/list", params: {} })}\n` + ); + await valid.waitForLines(2); + expect(JSON.parse(valid.lines[1]!)).toEqual({ + jsonrpc: "2.0", + id: "list", + result: { tools: ADVERTISED_TOOL_CATALOGUE } + }); + await valid.handle.close(); + }); + + it("recovers missing and non-object arguments at the authentic boundary", async () => { + const runtime = await harness(); + await ready(runtime); + runtime.send({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "archflow_state" } }); + runtime.send({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "archflow_state", arguments: "bad" } }); + runtime.send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "unknown", arguments: {} } }); + runtime.send({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "archflow_state", arguments: stateInput } }); + await runtime.waitForLines(5); + const responses = runtime.lines.slice(1).map((line) => JSON.parse(line) as Record); + for (const response of responses.slice(0, 2)) { + const result = response.result as { structuredContent: { ok: boolean; error: { code: string } }; isError: boolean }; + expect(result.structuredContent.error.code).toBe("CONTRACT_INVALID"); + expect(result.isError).toBe(true); + } + expect(responses[2]).toMatchObject({ + jsonrpc: "2.0", + id: 3, + error: { code: -32001, message: "TOOL_NOT_FOUND", data: { code: "TOOL_NOT_FOUND" } } + }); + expect(responses[3]).toMatchObject({ + jsonrpc: "2.0", + id: 4, + error: { code: -32002, message: "TOOL_DISABLED", data: { code: "TOOL_DISABLED" } } + }); + runtime.send({ jsonrpc: "2.0", id: 1, method: "ping" }); + await runtime.waitForLines(6); + expect(runtime.lines[5]).toBe( + '{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Invalid Request"}}' + ); + await runtime.handle.close(); + }); + + it("bounds SDK metadata validator errors without leaking validator prose", async () => { + const runtime = await harness(); + await ready(runtime); + runtime.send({ jsonrpc: "2.0", id: 1, method: "tools/list", params: { _meta: null } }); + runtime.send({ + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { name: "archflow_state", task: "invalid", arguments: {} } + }); + await runtime.waitForLines(3); + expect(runtime.lines.slice(1)).toEqual([ + '{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid params"}}', + '{"jsonrpc":"2.0","id":2,"error":{"code":-32602,"message":"Invalid params"}}' + ]); + await runtime.handle.close(); + }); + + it("ignores malformed cancellation without aborting or suppressing the normal response", async () => { + let release!: () => void; + let started!: () => void; + const didStart = new Promise((resolve) => { started = resolve; }); + const gate = new Promise((resolve) => { release = resolve; }); + let signal: AbortSignal | undefined; + const runtime = await harness({ + archflow_state: async (_call, context) => { + signal = context.signal; + started(); + await gate; + return stateSuccess; + } + }); + await ready(runtime); + runtime.send({ + jsonrpc: "2.0", + id: "call", + method: "tools/call", + params: { name: "archflow_state", arguments: stateInput } + }); + await didStart; + runtime.send({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { requestId: "call", reason: { invalid: true } } + }); + await Promise.resolve(); + expect(signal?.aborted).toBe(false); + release(); + await runtime.waitForLines(2); + expect(JSON.parse(runtime.lines[1]!)).toMatchObject({ + id: "call", + result: { structuredContent: { schema_version: "1", ok: true } } + }); + runtime.send({ jsonrpc: "2.0", id: "call", method: "ping" }); + await runtime.waitForLines(3); + expect(runtime.lines[2]).toBe( + '{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Invalid Request"}}' + ); + await runtime.handle.close(); + }); + + it("accepts valid cancellation through the SDK schema, aborts, and retains the ID tombstone", async () => { + let started!: () => void; + const didStart = new Promise((resolve) => { started = resolve; }); + let aborted!: () => void; + const didAbort = new Promise((resolve) => { aborted = resolve; }); + const runtime = await harness({ + archflow_state: async (_call, context) => { + started(); + await new Promise((_resolve, reject) => { + context.signal.addEventListener("abort", () => { + aborted(); + reject(new Error("cancelled")); + }, { once: true }); + }); + } + }); + await ready(runtime); + runtime.send({ + jsonrpc: "2.0", + id: 7, + method: "tools/call", + params: { name: "archflow_state", arguments: stateInput } + }); + await didStart; + runtime.send({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { requestId: 7, reason: "stop" } + }); + await didAbort; + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(runtime.lines).toHaveLength(1); + runtime.send({ jsonrpc: "2.0", id: 7, method: "ping" }); + await runtime.waitForLines(2); + expect(runtime.lines[1]).toBe( + '{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Invalid Request"}}' + ); + await runtime.handle.close(); + }); + + it("quarantines a delayed enabled-handler result after caller close", async () => { + let release!: () => void; + let started!: () => void; + const didStart = new Promise((resolve) => { started = resolve; }); + const gate = new Promise((resolve) => { release = resolve; }); + const runtime = await harness({ + archflow_state: async () => { + started(); + await gate; + return stateSuccess; + } + }); + await ready(runtime); + runtime.send({ + jsonrpc: "2.0", + id: "late", + method: "tools/call", + params: { name: "archflow_state", arguments: stateInput } + }); + await didStart; + await runtime.handle.close(); + release(); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(runtime.lines).toHaveLength(1); + }); + + it("emits fixed parse errors, preserves ID spending, and terminates without owning streams", async () => { + const runtime = await harness(); + runtime.input.write("not-json\n"); + runtime.send(initialize(-0)); + await runtime.waitForLines(2); + runtime.send({ jsonrpc: "2.0", id: 0, method: "ping" }); + await runtime.waitForLines(3); + expect(runtime.lines[0]).toBe('{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}}'); + expect(runtime.lines[2]).toBe('{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Invalid Request"}}'); + await runtime.handle.close(); + expect(runtime.input.destroyed).toBe(false); + expect(runtime.output.destroyed).toBe(false); + }); +}); diff --git a/test/unit/mcp-send-queue.test.ts b/test/unit/mcp-send-queue.test.ts new file mode 100644 index 00000000..27a00883 --- /dev/null +++ b/test/unit/mcp-send-queue.test.ts @@ -0,0 +1,188 @@ +import { EventEmitter } from "node:events"; +import { Writable } from "node:stream"; + +import { describe, expect, it, vi } from "vitest"; + +import { createSendQueue, type SendEntry } from "../../src/mcp/send-queue.js"; + +const MiB = 1_024 * 1_024; + +class ControlledWritable extends Writable { + readonly frames: Uint8Array[] = []; + readonly callbacks: Array<(error?: Error | null) => void> = []; + accept = true; + + override write( + chunk: Uint8Array, + callback?: (error?: Error | null) => void, + ): boolean; + override write( + chunk: Uint8Array, + encoding?: BufferEncoding, + callback?: (error?: Error | null) => void, + ): boolean; + override write( + chunk: Uint8Array, + encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void), + maybeCallback?: (error?: Error | null) => void, + ): boolean { + this.frames.push(chunk); + const callback = + typeof encodingOrCallback === "function" ? encodingOrCallback : maybeCallback; + if (callback !== undefined) { + this.callbacks.push(callback); + } + return this.accept; + } +} + +function entry(size: number, source: SendEntry["source"] = "direct"): SendEntry { + return { source, frame: new Uint8Array(size) }; +} + +async function rejectionHandled(promise: Promise): Promise { + return promise.then( + () => { + throw new Error("Expected rejection"); + }, + (error: unknown) => error as Error, + ); +} + +describe("MCP send queue", () => { + it("preserves a universal FIFO and separates admission from completion", async () => { + const output = new ControlledWritable(); + const queue = createSendQueue(output, vi.fn(), vi.fn()); + const receipts = [ + queue.enqueue(entry(1, "sdk")), + queue.enqueue(entry(2, "fallback")), + queue.enqueue(entry(3, "direct")), + ]; + + await Promise.all(receipts.map(({ admitted }) => admitted)); + expect(output.frames.map(({ byteLength }) => byteLength)).toEqual([1, 2, 3]); + + let complete = false; + void receipts[0]?.completed.then(() => { + complete = true; + }); + await Promise.resolve(); + expect(complete).toBe(false); + + output.callbacks[0]?.(); + output.callbacks[1]?.(); + output.callbacks[2]?.(); + await Promise.all(receipts.map(({ completed }) => completed)); + }); + + it("admits the write that returns false and waits for drain before later writes", async () => { + const output = new ControlledWritable(); + output.accept = false; + const changes: boolean[] = []; + const queue = createSendQueue(output, (paused) => changes.push(paused), vi.fn()); + + const first = queue.enqueue(entry(1)); + await first.admitted; + expect(queue.backpressured).toBe(true); + expect(changes).toEqual([true]); + + output.accept = true; + const second = queue.enqueue(entry(2)); + expect(output.frames).toHaveLength(1); + output.callbacks[0]?.(); + await first.completed; + expect(output.frames).toHaveLength(1); + + output.emit("drain"); + await second.admitted; + expect(changes).toEqual([true, false]); + expect(output.frames).toHaveLength(2); + output.callbacks[1]?.(); + await second.completed; + }); + + it("accepts exact entry and aggregate byte boundaries and fail-closes overflow", async () => { + const output = new ControlledWritable(); + output.accept = false; + const fatal = vi.fn(); + const queue = createSendQueue(output, vi.fn(), fatal); + + const exact = queue.enqueue(entry(10 * MiB)); + await exact.admitted; + const overflow = queue.enqueue(entry(1)); + await expect(overflow.admitted).rejects.toThrow("capacity exceeded"); + await expect(overflow.completed).rejects.toThrow("capacity exceeded"); + await expect(exact.completed).rejects.toThrow("capacity exceeded"); + expect(fatal).toHaveBeenCalledTimes(1); + + const countOutput = new ControlledWritable(); + countOutput.accept = false; + const countQueue = createSendQueue(countOutput, vi.fn(), vi.fn()); + const receipts = Array.from({ length: 1_024 }, () => countQueue.enqueue(entry(0))); + const pendingSettlements = receipts.flatMap(({ admitted, completed }) => [ + admitted.catch((error: unknown) => error), + completed.catch((error: unknown) => error), + ]); + await receipts[0]?.admitted; + const countOverflow = countQueue.enqueue(entry(0)); + const countOverflowCompletion = rejectionHandled(countOverflow.completed); + await expect(countOverflow.admitted).rejects.toThrow("capacity exceeded"); + await Promise.all(pendingSettlements); + await countOverflowCompletion; + }); + + it("fail-closes on a late callback error after admission and drain", async () => { + const output = new ControlledWritable(); + output.accept = false; + const fatal = vi.fn(); + const queue = createSendQueue(output, vi.fn(), fatal); + const first = queue.enqueue(entry(1)); + await first.admitted; + + output.accept = true; + output.emit("drain"); + const second = queue.enqueue(entry(1)); + await second.admitted; + const lateError = new Error("late failure"); + output.callbacks[0]?.(lateError); + + await expect(first.completed).rejects.toBe(lateError); + await expect(second.completed).rejects.toBe(lateError); + expect(fatal).toHaveBeenCalledTimes(1); + expect(queue.backpressured).toBe(false); + }); + + it("close rejects queued and incomplete entries, cleans listeners, and leaves the stream owned by its caller", async () => { + const output = new ControlledWritable(); + output.accept = false; + const queue = createSendQueue(output, vi.fn(), vi.fn()); + const first = queue.enqueue(entry(1)); + await first.admitted; + const queued = queue.enqueue(entry(1)); + expect(output.listenerCount("drain")).toBe(1); + expect(output.listenerCount("error")).toBe(1); + + await queue.close(); + await expect(first.completed).rejects.toThrow("Send queue closed"); + await expect(queued.admitted).rejects.toThrow("Send queue closed"); + await expect(queued.completed).rejects.toThrow("Send queue closed"); + expect(output.listenerCount("drain")).toBe(0); + expect(output.listenerCount("error")).toBe(0); + expect(output.destroyed).toBe(false); + expect(output.writableEnded).toBe(false); + }); + + it("handles unsolicited output errors through the same once-only fatal path", async () => { + const output = new ControlledWritable(); + const fatal = vi.fn(); + const queue = createSendQueue(output, vi.fn(), fatal); + const receipt = queue.enqueue(entry(1)); + await receipt.admitted; + const completionError = rejectionHandled(receipt.completed); + + output.emit("error", new Error("stream failed")); + + await expect(completionError).resolves.toMatchObject({ message: "stream failed" }); + expect(fatal).toHaveBeenCalledTimes(1); + }); +}); diff --git a/test/unit/mcp-server.test.ts b/test/unit/mcp-server.test.ts index 4d34d18d..1b1dad27 100644 --- a/test/unit/mcp-server.test.ts +++ b/test/unit/mcp-server.test.ts @@ -29,6 +29,15 @@ const stateSuccess = { ok: true, value: { path: "phases/3/result.json", revision: 3, status: "succeeded" } } as const; +const counterReviewInput = { + schema_version: "1", + task_id: "task-1", + intent_id: "intent-1", + expected_revision: 2, + input_fingerprint: digest, + artifact_path: `${"é".repeat(600)}.md`, + rubric: { schema_version: "1", criteria: [{ id: "paths", text: "Paths are correct", blocking: true }] } +} as const; interface ClassificationFixtures { readonly not_object: readonly unknown[]; @@ -157,14 +166,19 @@ describe("SDK-free MCP tool boundary", () => { expect(Object.isFrozen(unknown.error)).toBe(true); expect(Object.isFrozen(unknown.error.value.diagnostic.parameters)).toBe(true); expect(() => assertAuthenticToolBoundaryOutcome(unknown)).not.toThrow(); + const unknownWithMissingArgs = await boundary.invoke("Ü\u0000tool", undefined, invocation); + expect(unknownWithMissingArgs).toMatchObject({ + kind: "protocol-error", + error: { value: { code: "TOOL_NOT_FOUND" } } + }); - const disabled = await boundary.invoke("archflow_gate", null, invocation); + const disabled = await boundary.invoke("archflow_state", stateInput, invocation); expect(disabled).toMatchObject({ kind: "protocol-error", error: { value: { code: "TOOL_DISABLED", - diagnostic: { parameters: { tool: "archflow_gate", lifecycle_state: "inert-no-handler" } } + diagnostic: { parameters: { tool: "archflow_state", lifecycle_state: "inert-no-handler" } } } } }); @@ -172,12 +186,40 @@ describe("SDK-free MCP tool boundary", () => { expect(() => assertAuthenticToolBoundaryOutcome(structuredClone(disabled) as never)).toThrow(/authentic tool boundary outcome/); }); + it("classifies missing, non-object, and portable-shaped runtime-invalid known input before inert availability", async () => { + const boundary = createToolBoundary({}); + const invocation = context("boundary-inert-precedence-1"); + + for (const candidate of [undefined, 42] as const) { + expectProjectFailure(await boundary.invoke("archflow_state", candidate, invocation), "archflow_state", "CONTRACT_INVALID", { + tool: "archflow_state", issue_code: "input-not-object" + }); + } + const semantic = await boundary.invoke("archflow_counter_review", counterReviewInput, invocation); + expect(semantic.kind).toBe("project-result"); + if (semantic.kind !== "project-result" || semantic.result.ok) throw new Error("expected project failure"); + expect(semantic.result.error.code).toBe("CONTRACT_INVALID"); + expect(semantic.result.error.diagnostic.parameters).toEqual({ + tool: "archflow_counter_review", issue_code: "input-invalid" + }); + + const valid = await boundary.invoke("archflow_state", stateInput, invocation); + expect(valid).toMatchObject({ + kind: "protocol-error", + error: { value: { code: "TOOL_DISABLED" } } + }); + }); + it("classifies every known-tool argument failure before calling the handler", async () => { const fixtures = await loadClassificationFixtures(); let calls = 0; const boundary = createToolBoundary({ archflow_state: () => { calls += 1; return stateSuccess; } }); const invocation = context("boundary-input-1"); + expectProjectFailure(await boundary.invoke("archflow_state", undefined, invocation), "archflow_state", "CONTRACT_INVALID", { + tool: "archflow_state", issue_code: "input-not-object" + }); + for (const candidate of fixtures.not_object) { expectProjectFailure(await boundary.invoke("archflow_state", candidate, invocation), "archflow_state", "CONTRACT_INVALID", { tool: "archflow_state", issue_code: "input-not-object" diff --git a/test/unit/mcp-session.test.ts b/test/unit/mcp-session.test.ts new file mode 100644 index 00000000..56ca7297 --- /dev/null +++ b/test/unit/mcp-session.test.ts @@ -0,0 +1,417 @@ +import { describe, expect, it } from "vitest"; + +import { connectionContextFactory, createInvocationContext } from "../../src/contracts/contexts.js"; +import { createSessionController, type SessionAction, type SessionController } from "../../src/mcp/session.js"; +import { createToolBoundary } from "../../src/mcp/server.js"; + +if (false) { + // @ts-expect-error tools-call forwards require both recovery candidates + const incompleteToolsCall: SessionAction = { + kind: "forward-sdk", route: "tools-call", message: {}, requestToken: "request-1", externalId: 1, internalId: 1 + }; + const identifiedInitialized: SessionAction = { + kind: "forward-sdk", route: "notifications/initialized", message: {}, + // @ts-expect-error initialized forwards carry no request identity + requestToken: "request-1" + }; + const externalCancellation: SessionAction = { + kind: "forward-sdk", route: "cancel", message: {}, requestToken: "request-1", internalId: 1, + // @ts-expect-error cancellation forwards expose only their internal route identity + externalId: 1 + }; + void incompleteToolsCall; + void identifiedInitialized; + void externalCancellation; +} + +const request = (id: string | number, method: string, params?: unknown): Record => ({ + jsonrpc: "2.0", + id, + method, + ...(params === undefined ? {} : { params }) +}); + +const notification = (method: string, params?: unknown): Record => ({ + jsonrpc: "2.0", + method, + ...(params === undefined ? {} : { params }) +}); + +const first = (actions: readonly SessionAction[]): SessionAction => { + expect(actions).toHaveLength(1); + return actions[0]!; +}; + +type RequestForward = Extract & { + readonly requestToken: string; + readonly externalId: string | number; + readonly internalId: number; + readonly nameCandidate?: unknown; + readonly argumentsCandidate?: unknown; +}; + +const forwarded = (actions: readonly SessionAction[]): RequestForward => { + const action = first(actions); + expect(action.kind).toBe("forward-sdk"); + return action as RequestForward; +}; + +const sent = (actions: readonly SessionAction[]): Extract => { + const action = first(actions); + expect(action.kind).toBe("send"); + return action as Extract; +}; + +const cancellationCandidate = ( + actions: readonly SessionAction[] +): Extract => { + const action = first(actions); + expect(action.kind).toBe("validate-cancellation"); + return action as Extract; +}; + +function initialize(controller: SessionController, id: string | number = "init"): string { + const action = forwarded(controller.accept(request(id, "initialize", { + protocolVersion: "2025-11-25", + capabilities: {}, + clientInfo: { name: "Codex", version: "1" } + }))); + const response = sent(controller.acceptSdkMessage({ + jsonrpc: "2.0", + id: action.internalId, + result: { + protocolVersion: "2025-11-25", + capabilities: { tools: {} }, + serverInfo: { name: "archflow-mcp", version: "0.0.0" } + } + })); + controller.onSendAdmitted(response.requestToken); + expect(controller.state).toBe("INIT_RESPONSE_ACCEPTED"); + const initialized = controller.accept(notification("notifications/initialized")); + expect(forwarded(initialized).route).toBe("notifications/initialized"); + expect(controller.state).toBe("INIT_RESPONSE_ACCEPTED"); + const ready = controller.acceptSdkMessage({ kind: "initialized-accepted" }); + expect(ready).toEqual([{ kind: "connection-ready" }]); + expect(controller.state).toBe("READY"); + return action.requestToken!; +} + +describe("MCP session admission and lifecycle", () => { + it("normalizes IDs, rewrites internal IDs, and becomes ready before the next message", () => { + const controller = createSessionController({ connectionId: "connection-1" }); + const init = forwarded(controller.accept(request(-0, "initialize", {}))); + expect(init).toMatchObject({ route: "initialize", externalId: 0, internalId: 1, requestToken: "request-1" }); + expect(init.message.id).toBe(1); + expect(controller.state).toBe("INITIALIZING"); + + const response = sent(controller.acceptSdkMessage({ jsonrpc: "2.0", id: 1, result: { ok: true } })); + expect(response.message).toEqual({ jsonrpc: "2.0", id: 0, result: { ok: true } }); + controller.onSendAdmitted(response.requestToken); + expect(controller.state).toBe("INIT_RESPONSE_ACCEPTED"); + + const initialized = controller.accept(notification("notifications/initialized")); + expect(forwarded(initialized).route).toBe("notifications/initialized"); + expect(controller.state).toBe("INIT_RESPONSE_ACCEPTED"); + const ready = controller.acceptSdkMessage({ kind: "initialized-accepted" }); + expect(ready).toEqual([{ kind: "connection-ready" }]); + expect(controller.state).toBe("READY"); + expect(forwarded(controller.accept(request("call", "tools/list"))).internalId).toBe(2); + }); + + it("makes malformed initialization retry transactional only after error send admission", () => { + const controller = createSessionController({ connectionId: "connection-2" }); + const initial = forwarded(controller.accept(request(1, "initialize", { malformed: true }))); + const response = sent(controller.acceptSdkMessage({ + jsonrpc: "2.0", + id: initial.internalId, + error: { code: -32602, message: "SDK validator prose", data: { arbitrary: "input" } } + })); + expect(response.message).toEqual({ + jsonrpc: "2.0", + id: 1, + error: { code: -32602, message: "Invalid params" } + }); + expect(controller.state).toBe("INITIALIZING"); + controller.onSendAdmitted(response.requestToken); + expect(controller.state).toBe("PRE_INIT"); + expect(forwarded(controller.accept(request(2, "initialize", {}))).internalId).toBe(2); + }); + + it("fails closed when an initialize error follows an observed SDK mutation", () => { + const controller = createSessionController({ connectionId: "connection-3" }); + const action = forwarded(controller.accept(request(1, "initialize", {}))); + expect(controller.acceptSdkMessage({ kind: "initialize-mutated", requestToken: action.requestToken })).toEqual([]); + expect(controller.acceptSdkMessage({ jsonrpc: "2.0", id: action.internalId, error: { code: -32602 } })).toEqual([ + { kind: "protocol-fatal" } + ]); + expect(controller.state).toBe("CLOSING"); + }); + + it("mints readiness only after SDK acceptance of the exact initialized notification", () => { + const controller = createSessionController({ connectionId: "initialized" }); + const init = forwarded(controller.accept(request(1, "initialize", {}))); + const response = sent(controller.acceptSdkMessage({ jsonrpc: "2.0", id: init.internalId, result: {} })); + controller.onSendAdmitted(response.requestToken); + expect(controller.state).toBe("INIT_RESPONSE_ACCEPTED"); + + expect(controller.accept(notification("initialized"))).toEqual([]); + expect(controller.state).toBe("INIT_RESPONSE_ACCEPTED"); + const malformed = forwarded(controller.accept(notification("notifications/initialized", { unexpected: true }))); + expect(malformed.route).toBe("notifications/initialized"); + expect(controller.state).toBe("INIT_RESPONSE_ACCEPTED"); + + const valid = forwarded(controller.accept(notification("notifications/initialized"))); + expect(valid.message).toEqual({ jsonrpc: "2.0", method: "notifications/initialized" }); + expect(controller.state).toBe("INIT_RESPONSE_ACCEPTED"); + expect(controller.acceptSdkMessage({ kind: "initialized-accepted" })).toEqual([{ kind: "connection-ready" }]); + expect(controller.state).toBe("READY"); + expect(controller.acceptSdkMessage({ kind: "initialized-accepted" })).toEqual([]); + }); + + it("uses authentic INITIALIZATION_REPEATED projection and spends the repeated ID", () => { + const controller = createSessionController({ connectionId: "connection-4" }); + controller.accept(request("first", "initialize", {})); + const repeated = sent(controller.accept(request("second", "initialize", {}))); + expect(repeated.message).toMatchObject({ + id: "second", + error: { + code: -32004, + message: "INITIALIZATION_REPEATED", + data: { code: "INITIALIZATION_REPEATED", diagnostic: { parameters: { connection_id: "connection-4" } } } + } + }); + expect(sent(controller.accept(request("second", "initialize", {}))).message).toEqual({ + jsonrpc: "2.0", + id: null, + error: { code: -32600, message: "Invalid Request" } + }); + }); + + it("implements ping and closed request routing in every lifecycle class", () => { + const pre = createSessionController({ connectionId: "pre" }); + expect(sent(pre.accept(request(1, "ping"))).message).toMatchObject({ id: 1, error: { code: -32600 } }); + expect(sent(pre.accept(request(2, "tools/list"))).message).toMatchObject({ id: 2, error: { code: -32600 } }); + expect(sent(pre.accept(request(3, "other"))).message).toMatchObject({ id: 3, error: { code: -32600 } }); + + const active = createSessionController({ connectionId: "active" }); + active.accept(request("i", "initialize", {})); + expect(forwarded(active.accept(request("p", "ping"))).route).toBe("ping"); + expect(sent(active.accept(request("l", "tools/list"))).message).toMatchObject({ error: { code: -32600 } }); + + const ready = createSessionController({ connectionId: "ready" }); + initialize(ready); + expect(forwarded(ready.accept(request("p", "ping"))).route).toBe("ping"); + expect(sent(ready.accept(request("x", "unknown/method"))).message).toMatchObject({ + id: "x", + error: { code: -32601, message: "Method not found" } + }); + }); + + it("rejects unsafe envelopes and exact extra request members before routing", () => { + const controller = createSessionController({ connectionId: "envelopes" }); + expect(sent(controller.accept([])).message).toMatchObject({ id: null, error: { code: -32600 } }); + expect(sent(controller.accept({ jsonrpc: "1.0", id: 1, method: "initialize" })).message).toMatchObject({ id: null }); + expect(sent(controller.accept({ jsonrpc: "2.0", id: Number.MAX_SAFE_INTEGER + 1, method: "initialize" })).message).toMatchObject({ id: null }); + expect(sent(controller.accept({ ...request("spent", "initialize"), extra: true })).message).toMatchObject({ id: "spent" }); + expect(sent(controller.accept(request("spent", "initialize"))).message).toMatchObject({ id: null }); + }); +}); + +describe("MCP session tool routing", () => { + it("enforces the exact tools/list params allowlist while preserving _meta", () => { + const controller = createSessionController({ connectionId: "list" }); + initialize(controller); + expect(forwarded(controller.accept(request(1, "tools/list"))).message).not.toHaveProperty("params"); + expect(forwarded(controller.accept(request(2, "tools/list", {}))).message.params).toEqual({}); + const metadata = { progressToken: "token" }; + expect(forwarded(controller.accept(request(3, "tools/list", { _meta: metadata }))).message.params).toEqual({ _meta: metadata }); + expect(sent(controller.accept(request(4, "tools/list", { cursor: "x" }))).message).toMatchObject({ error: { code: -32602 } }); + expect(sent(controller.accept(request(5, "tools/list", { other: true }))).message).toMatchObject({ error: { code: -32602 } }); + expect(sent(controller.accept(request(6, "tools/list", null))).message).toMatchObject({ error: { code: -32602 } }); + }); + + it("preserves SDK-only call fields and tags missing and object argument candidates", () => { + const controller = createSessionController({ connectionId: "calls" }); + initialize(controller); + const missing = forwarded(controller.accept(request(1, "tools/call", { + _meta: { progressToken: 1 }, + task: { id: "legacy" }, + name: "archflow_state" + }))); + expect(missing.message.params).toEqual({ + _meta: { progressToken: 1 }, + task: { id: "legacy" }, + name: "archflow_state" + }); + expect(missing.nameCandidate).toEqual({ present: true, value: "archflow_state" }); + expect(missing.argumentsCandidate).toEqual({ present: false }); + + const object = { schema_version: "1", extra: "boundary-owned" }; + const present = forwarded(controller.accept(request(2, "tools/call", { + name: "archflow_state", + arguments: object + }))); + expect((present.message.params as Record).arguments).toEqual(object); + expect(present.argumentsCandidate).toEqual({ present: true, value: object }); + }); + + it("uses a surrogate only for known present non-object arguments", () => { + const controller = createSessionController({ connectionId: "surrogate" }); + initialize(controller); + for (const [id, value] of [[1, null], [2, "bad"], [3, []]] as const) { + const action = forwarded(controller.accept(request(id, "tools/call", { + name: "archflow_state", + arguments: value + }))); + expect((action.message.params as Record).arguments).toEqual({}); + expect(action.argumentsCandidate).toEqual({ present: true, value }); + } + expect(sent(controller.accept(request(4, "tools/call", { name: "not-a-tool", arguments: 1 }))).message) + .toMatchObject({ error: { code: -32602 } }); + expect(forwarded(controller.accept(request(5, "tools/call", { name: "not-a-tool", arguments: {} }))).argumentsCandidate) + .toEqual({ present: true, value: {} }); + }); + + it("rejects missing names, missing params, and every extra call key", () => { + const controller = createSessionController({ connectionId: "call-shape" }); + initialize(controller); + expect(sent(controller.accept(request(1, "tools/call"))).message).toMatchObject({ error: { code: -32602 } }); + expect(sent(controller.accept(request(2, "tools/call", {}))).message).toMatchObject({ error: { code: -32602 } }); + expect(sent(controller.accept(request(3, "tools/call", { name: 1 }))).message).toMatchObject({ error: { code: -32602 } }); + expect(sent(controller.accept(request(4, "tools/call", { name: "archflow_state", extra: true }))).message) + .toMatchObject({ error: { code: -32602 } }); + }); + + it("retains authentic outcomes as expected projections and falls back when absent", async () => { + const controller = createSessionController({ connectionId: "outcomes" }); + initialize(controller); + const call = forwarded(controller.accept(request(1, "tools/call", { name: "unknown", arguments: {} }))); + const connection = connectionContextFactory.captureStartup({ + connection_id: "outcomes", + startup_repository_candidate: { working_directory: "/work" } + }).initialize({ client: { name: "Codex", version: "1" }, host: "codex", protocol_version: "2025-11-25" }); + const context = createInvocationContext(connection, { + invocation_id: "request-1", + transport_metadata: { request_id: 1, operation: "tools/call" } + }, new AbortController().signal); + const outcome = await createToolBoundary({}).invoke("unknown", {}, context); + expect(controller.acceptSdkMessage({ + kind: "tool-boundary-outcome", + requestToken: call.requestToken, + outcome + })).toEqual([]); + const projected = sent(controller.acceptSdkMessage({ + jsonrpc: "2.0", + id: call.internalId, + error: { code: -32602, message: "SDK rewrite" } + })); + expect(projected.expectedProjection).toEqual({ kind: "tool-boundary", outcome }); + expect(projected.source).toBe("sdk"); + controller.onSendAdmitted(projected.requestToken); + expect(sent(controller.accept(request(1, "ping"))).message).toMatchObject({ + id: null, + error: { code: -32600 } + }); + + const missing = forwarded(controller.accept(request(2, "tools/call", { name: "unknown", arguments: {} }))); + const fallback = sent(controller.acceptSdkMessage({ jsonrpc: "2.0", id: missing.internalId, result: {} })); + expect(fallback.source).toBe("fallback"); + expect(fallback.message).toMatchObject({ id: 2, error: { code: -32603, message: "Internal error" } }); + controller.onSendAdmitted(fallback.requestToken); + expect(sent(controller.accept(request(2, "ping"))).message).toMatchObject({ + id: null, + error: { code: -32600 } + }); + }); +}); + +describe("MCP session cancellation, ledgers, and shutdown", () => { + it("keeps cancelling tombstones, ignores initialize/completed targets, and never frees seen IDs", () => { + const controller = createSessionController({ connectionId: "cancel" }); + const init = forwarded(controller.accept(request("init", "initialize", {}))); + expect(controller.accept(notification("notifications/cancelled", { requestId: "init" }))).toEqual([]); + controller.acceptSdkMessage({ jsonrpc: "2.0", id: init.internalId, result: {} }); + controller.onSendAdmitted(init.requestToken); + controller.accept(notification("notifications/initialized")); + controller.acceptSdkMessage({ kind: "initialized-accepted" }); + + const active = forwarded(controller.accept(request(-0, "ping"))); + const candidate = cancellationCandidate(controller.accept(notification("notifications/cancelled", { requestId: 0, reason: "stop" }))); + expect(candidate).toMatchObject({ internalId: active.internalId, requestToken: active.requestToken }); + expect(candidate.message).toMatchObject({ params: { requestId: 0, reason: "stop" } }); + const cancellation = forwarded(controller.acceptSdkMessage({ + kind: "cancellation-accepted", + requestToken: candidate.requestToken + })); + expect(cancellation).toMatchObject({ route: "cancel", internalId: active.internalId, requestToken: active.requestToken }); + expect(cancellation.message).toMatchObject({ params: { requestId: active.internalId, reason: "stop" } }); + expect(controller.accept(notification("notifications/cancelled", { requestId: 0 }))).toEqual([]); + controller.onRouteSettled(active.requestToken!); + expect(sent(controller.accept(request(0, "ping"))).message).toMatchObject({ id: null, error: { code: -32600 } }); + + const queued = forwarded(controller.accept(request("queued", "ping"))); + const send = sent(controller.acceptSdkMessage({ jsonrpc: "2.0", id: queued.internalId, result: {} })); + expect(controller.accept(notification("notifications/cancelled", { requestId: "queued" }))).toEqual([]); + controller.onSendAdmitted(send.requestToken); + }); + + it("does not mutate a request until a cancellation candidate is accepted", () => { + const controller = createSessionController({ connectionId: "candidate" }); + initialize(controller); + const active = forwarded(controller.accept(request(1, "ping"))); + const malformed = cancellationCandidate(controller.accept(notification("notifications/cancelled", { + requestId: 1, + reason: { invalid: true } + }))); + const response = sent(controller.acceptSdkMessage({ jsonrpc: "2.0", id: active.internalId, result: {} })); + expect(response.message).toEqual({ jsonrpc: "2.0", id: 1, result: {} }); + expect(controller.acceptSdkMessage({ + kind: "cancellation-accepted", + requestToken: malformed.requestToken + })).toEqual([]); + }); + + it("distinguishes string and numeric IDs and rejects normalized reuse permanently", () => { + const controller = createSessionController({ connectionId: "ids" }); + controller.accept(request(-0, "initialize", {})); + expect(sent(controller.accept(request(0, "ping"))).message).toMatchObject({ id: null, error: { code: -32600 } }); + expect(forwarded(controller.accept(request("0", "ping"))).externalId).toBe("0"); + }); + + it("fails closed at the seen-count, seen-byte, and monotonic internal-ID boundaries", () => { + const count = createSessionController({ connectionId: "count", limits: { seenIds: 2 } }); + count.accept(request(1, "initialize", {})); + count.accept(request(2, "ping")); + expect(count.accept(request(3, "ping"))).toEqual([{ kind: "protocol-fatal" }]); + expect(count.state).toBe("CLOSING"); + + const byte = createSessionController({ connectionId: "byte", limits: { seenIdBytes: 4 } }); + expect(byte.accept(request("abc", "initialize", {}))).toEqual([{ kind: "protocol-fatal" }]); + + const internal = createSessionController({ connectionId: "internal", limits: { internalId: 1 } }); + internal.accept(request(1, "initialize", {})); + expect(internal.accept(request(2, "ping"))).toEqual([{ kind: "protocol-fatal" }]); + }); + + it("silently drops notifications and unmatched responses", () => { + const controller = createSessionController({ connectionId: "silence" }); + expect(controller.accept(notification("unknown", { arbitrary: true }))).toEqual([]); + expect(controller.accept({ ...notification("unknown"), extra: true })).toEqual([]); + expect(controller.accept({ jsonrpc: "2.0", id: 10, result: {} })).toEqual([]); + expect(controller.accept({ jsonrpc: "2.0", id: "x", error: { code: -1 } })).toEqual([]); + expect(controller.acceptSdkMessage({ jsonrpc: "2.0", id: 999, result: {} })).toEqual([]); + }); + + it("quarantines every late effect and clears active records on close", () => { + const controller = createSessionController({ connectionId: "close" }); + const active = forwarded(controller.accept(request(1, "initialize", {}))); + controller.close(); + expect(controller.state).toBe("CLOSED"); + expect(controller.accept(request(2, "ping"))).toEqual([]); + expect(controller.acceptSdkMessage({ jsonrpc: "2.0", id: active.internalId, result: {} })).toEqual([]); + controller.onRouteSettled(active.requestToken!); + controller.onSendAdmitted(active.requestToken); + controller.close(); + expect(controller.state).toBe("CLOSED"); + }); +}); From 2d86b123e571d946eb3e45075d6855caff035fab Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Mon, 27 Jul 2026 21:51:05 -0500 Subject: [PATCH 014/124] MCP Integration: Design Phase 5 --- ...-5-offline-bundle-and-release-integrity.md | 201 ++++++++++++++++++ .../reviews/phase-5-design-counter-review.md | 49 +++++ 2 files changed, 250 insertions(+) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-5-design-counter-review.md diff --git a/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity.md b/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity.md new file mode 100644 index 00000000..8cf8187b --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity.md @@ -0,0 +1,201 @@ +# Phase 5: Offline Bundle and Release Integrity + +**Status**: DESIGNED +**Task**: mcp-integration +**Goal**: Produce a license-complete deterministic tracked offline payload and prove hostile clean-copy startup. +**Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28, REQ-33 + +## Context + +Phase 4 completed the inert stdio runtime behind a thin `src/main.ts`, with SDK ownership isolated under `src/mcp/`, byte-exact live protocol fixtures, unique-OS-temporary smoke builds, exact package/lock policy, and two-patch Node CI. Its temporary builder deliberately emits no tracked release output, and the repository currently has no `dist/`. The context snapshots predate Phases 3 and 4, so the current runtime, Phase 4 design, and implementation log are authoritative here. + +**Implementation-start dependency gate:** a live advisory sweep must cover every component embedded in the candidate bundle, not only direct packages. The current `@modelcontextprotocol/server@2.0.0` artifact embeds `fast-uri@3.1.0`, which is affected by four current high-severity advisories: `GHSA-q3j6-qgpj-74h6` (fixed in `3.1.1`), `GHSA-v39h-62p7-jpjc` (fixed in `3.1.2`), `GHSA-4c8g-83qw-93j6` (fixed in `3.1.3`), and `GHSA-v2hh-gcrm-f6hx` (fixed in `3.1.4`). There is no workaround; the safe 3.x floor is `3.1.4`. As of the 2026-07-27 design review, the current MCP server still embeds `3.1.0` and no compatible patched server artifact is available. Before implementation or any tracked-payload mutation, live official sources must confirm the complete advisory snapshot and artifact availability. Prefer a compatible patched artifact followed by design and compatibility review. Otherwise implementation stops unless the user separately accepts a documented prototype-only risk decision that names all current advisories and the focused inert-runtime reachability result. Design approval is not risk acceptance. + +This phase packages only the existing inert runtime. It adds no persistence, dispatch, durable gate/state/artifact schema, local helper, installer, runtime dependency, model-result validation, or production handler authority. REQ-11 and REQ-33 remain in the requirement list because the normative architecture assigns them to Phase 5, but this phase supplies release-evidence plumbing only and claims zero behavioral completion for either; later phases retain behavioral ownership. + +## What We're Building + +Add a separate release build that uses esbuild with `write: false` and a fully explicit Node 24 ESM profile to produce one tracked `dist/archflow-mcp.mjs`. The profile has a stable repository-relative logical output, the existing `createRequire` banner, no splitting, plugins, minification, or release source map, and explicit legal-comment handling. Generated JSON recursively sorts object keys, preserves source-defined semantic array order, sorts set-derived arrays by ordinal repository-relative path/key, uses UTF-8/LF, and ends with one newline. The final output may statically import only `node:process`, `node:buffer`, `node:util`, and `node:crypto`, plus the banner's `node:module`; all other built-in and external imports and dynamic built-in loading fail validation. + +Track two strict structural contracts: a release manifest and a release legal-review receipt. One semantic validator correlates their collection algebra, references, digests, canonical bytes, provenance, and recursive payload closure. The manifest records every scanned physical bundle input, every dependency provenance input actually consulted, a closed proof-input set, and the exact generated artifact set. Legal review conservatively inventories recognized third-party roots from contributing prebundles and adjacent source maps without claiming exact embedded physical-byte attribution or constructing composed source-map ranges. + +An explicit tracked writer never promotes a stage on its own authority. It validates the candidate, independently materializes a new source root, runs `npm ci`, verifies installed dependency bytes and provenance, rebuilds into a separate stage, byte-compares both closed payloads, and only then replaces the fixed repository `dist/` target. The read-only checker can validate one payload and optionally compare two already-materialized payloads. + +## Interfaces and Command Contract + +These types and signatures are the shared seams for separately implemented chunks; their algorithms remain implementation choices: + +```ts +type Sha256 = string; // validated lowercase 64-character hexadecimal digest + +type CanonicalDocument = Readonly<{ + bytes: Uint8Array; + value: Readonly; + digest: Sha256; +}>; + +type ReleaseFile = Readonly<{ + path: string; + size: number; + digest: Sha256; +}>; + +type ReleasePayloadSummary = Readonly<{ + payloadRoot: string; + files: readonly ReleaseFile[]; + bundleDigest: Sha256; + dependencyInventoryDigest: Sha256; + manifest: CanonicalDocument; + legalReview: CanonicalDocument; +}>; + +type CurrentRiskDecisionBinding = Readonly<{ + dependencyInventoryDigest: Sha256; + advisorySnapshotDigest: Sha256; + reachabilityEvidenceDigest: Sha256; +}>; + +type ValidatedReleaseStage = Readonly<{ + stageRoot: string; + summary: ReleasePayloadSummary; +}>; + +type ReproductionProof = Readonly<{ + candidate: ReleasePayloadSummary; + reproduced: ReleasePayloadSummary; + comparedFiles: readonly string[]; + proofInputsDigest: Sha256; + launchProfileDigest: Sha256; +}>; + +buildReleasePayload(options: { + repositoryRoot: string; + stageRoot: string; +}): Promise; + +validateReleaseSemantics(options: { + repositoryRoot: string; + payloadRoot: string; + manifest: CanonicalDocument; + legalReview: CanonicalDocument; +}): Promise; + +materializeReleaseSourceRoot(options: { + repositoryRoot: string; + stage: ValidatedReleaseStage; + materializationRoot: string; +}): Promise; + +reproduceReleasePayload(options: { + repositoryRoot: string; + stage: ValidatedReleaseStage; + materializationRoot: string; + comparisonRoot: string; +}): Promise; + +checkReleasePayload(options: { + repositoryRoot: string; + payloadRoot: string; + comparisonRoot?: string; +}): Promise; + +writeTrackedReleasePayload(options: { + repositoryRoot: string; + candidateStageRoot: string; +}): Promise; +``` + +The CLI forms are fixed as `npm run release:stage -- --output `, `npm run release:check -- --payload [--compare ]`, `npm run release:write -- --stage `, `npm run release:smoke -- --payload `, and `npm run release:mutations`. On success, each command writes one canonical JSON summary to stdout. Diagnostics go to stderr. Exit status is `0` for success, `1` for an operation or validation failure, and `2` for invalid usage. The tracked-write command creates its own dedicated materialization and comparison roots and must complete the independent reproduction path above before touching `dist/`. + +## Files + +| Action | File | Purpose | +|--------|------|---------| +| Create | `src/contracts/schemas/v1/release-manifest.schema.json` | Define the closed/versioned manifest shape, input/artifact collections, build entries and roles, launch profile, and evidence bindings. | +| Create | `src/contracts/schemas/v1/release-legal-review.schema.json` | Define the closed/versioned legal receipt, current-component, gate-decision, amendment, and supersession shapes. | +| Modify | `src/contracts/versions.ts` | Register both stable release schema identifiers without changing unrelated contract authority. | +| Modify | `test/contracts/schema-registry.test.ts` | Compile and register both release schemas from their JSON Schema authorities. | +| Create | `test/contracts/release-contracts.test.ts` | Prove strict shape, canonical-document rules, collection algebra, legal correlation, and representative invalid records. | +| Create | `release/legal-review.json` | Store the canonical reviewed current component inventory, retained dependency gate decisions, amendments/supersessions, and exact provenance evidence; map byte-identically to `dist/legal/review.json`. | +| Create | `release/legal/upstream/**` | Retain exact applicable upstream license/notice source bytes and map each relative path byte-identically below `dist/legal/upstream/`, without creating a first-party license grant. | +| Create | `scripts/release-support.mjs` | Own the profile, path codec, canonical documents, hashes, sole semantic validator, materializer, provenance checks, and shared interfaces. | +| Create | `scripts/build-release.mjs` | Expose the external empty-stage build form and validate the complete in-memory payload before materialization. | +| Create | `scripts/write-tracked-release.mjs` | Independently materialize, install, verify, rebuild, compare, and only then replace the fixed tracked payload. | +| Create | `scripts/check-release.mjs` | Read-only validation of one payload and optional comparison of two validated payloads. | +| Create | `scripts/test-release-integrity.mjs` | Mutation-test representative schema, graph, provenance, path, write, normalization, and proof-input failures. | +| Create | `scripts/smoke-release-bundle.mjs` | Run exact-payload and guarded hostile-copy protocol exercises through direct Node. | +| Create | `test/fixtures/release/hostile-runtime-guard.cjs` | Instrument the declared global runtime surfaces before bundle import and report violations on inherited fd 3. | +| Create | `test/integration/release-offline.test.ts` | Exercise tracked hostile-copy startup, path/root safety, proof binding, and independent-root byte reproduction. | +| Modify | `test/integration/mcp-stdio.test.ts` | Preserve temporary-build isolation while removing the obsolete no-tracked-`dist/` assertion. | +| Create | `dist/archflow-mcp.mjs`, `dist/metafile.json`, `dist/manifest.json` | Track the inert executable and its canonical graph and integrity evidence. | +| Create | `dist/legal/review.json`, `dist/legal/THIRD_PARTY_NOTICES.md`, `dist/legal/upstream/**` | Track the canonical reviewed receipt, sole generated human-readable legal projection, and byte-identical upstream legal sources; these are the exact `dist/legal/` closure. | +| Modify | `.gitattributes` | Force generated `dist/` text to LF while marking exact retained upstream legal source bytes `-text`. | +| Modify | `package.json` | Add the fixed stage/check/write/smoke/mutation commands and aggregate release verification without changing dependencies. | +| Modify | `.github/workflows/ci.yml` | Pin action identities, disable package-manager caching for reproduction, and compare true clean-checkout payloads on both Node patches. | + +## Contract and Evidence Rules + +- JSON Schema is the only structural authority: `release-manifest.schema.json` owns the closed/versioned manifest shapes, and `release-legal-review.schema.json` owns the closed/versioned legal receipt, current-component, gate-decision, amendment, and supersession shapes. `validateReleaseSemantics(...)` is the one semantic authority correlating the two canonical documents; there is no Zod mirror, TypeScript parser, or second shape model. +- `bundle_inputs` contains every scanned `metafile.inputs` physical path exactly once with repository/dependency origin, size, and digest. `contributing_inputs` is exactly the sorted subset of sole-output input keys whose `bytesInOutput > 0`; zero-byte and scanned-only inputs remain bound but do not support physical-presence claims. Repository-owned bundle records and `release_control_inputs` use portable repository-relative paths with whole-file size/digests. Bundle-owned repository paths remain bundle inputs and are never duplicated in controls. +- `release_control_inputs` is the closed union of every non-bundle repository file needed to reproduce or substantiate the release: `package.json`, `package-lock.json`, `.gitattributes`, `.github/workflows/ci.yml`; all release support/build/check/write/smoke/mutation scripts; `release/legal-review.json` and `release/legal/upstream/**`; both new release schemas, `src/contracts/versions.ts`, `test/contracts/schema-registry.test.ts`, and `test/contracts/release-contracts.test.ts`; all proof scripts/tests/fixtures; and every non-bundle declared schema/workflow/constitution asset. `proof_inputs` and declared-content collections are sorted reference subsets resolving to repository bundle/control records, never duplicate physical-input authorities. This closed repository-owned union is the exact preinstall materialization allowlist. +- Declared content coverage is all tracked `src/contracts/schemas/v1/*.schema.json`, including both new release schemas; `assets/workflow.yaml`; and exactly `assets/constitution/README.md`, `00-process.md`, `10-architecture.md`, `20-data.md`, and `30-product.md`. The current eight bundled schemas are `evidence-slots.schema.json`, `gate-contract.schema.json`, `gate-decision.schema.json`, `mcp-tools.schema.json`, `path-claim.schema.json`, `primitives.schema.json`, `project-error.schema.json`, and `rubric.schema.json`; every other tracked schema and declared asset is a release control unless the actual metafile makes it a bundle input. No path may appear in both. +- `dependency_provenance_inputs` uses a separate installed-package namespace. Every record binds exact package name, exact package version, package-relative forward-slash path, size, and digest for each adjacent source map, package manifest, license/notice file, and other installed dependency file actually consulted. Records resolve only beneath that exact package's post-`npm ci` installed root; repository-relative paths and retained repository evidence never enter this collection. `package-lock.json` is the repository control for registry/tarball identity. Every installed record is re-read and verified before legal derivation, rebuild, or byte comparison; omission, substitution, package-root escape, or stale bytes fail. +- For every dependency-owned contributing prebundle, discover and bind its adjacent source map when present and record whether that map is expected. Conservatively inventory every recognized mapped third-party component/root, distinguish an embedded version from an installed same-name version, fail unknown mapped roots and missing expected maps, and retain the empty-Ajv-JSON/source-content limitation. The known current embedded closure is `ajv@8.18.0`, `ajv-formats@3.0.1`, `fast-uri@3.1.0`, `fast-deep-equal@3.1.3`, `json-schema-traverse@1.0.0`, and `content-type@1.0.5`. This evidence does not claim exact physical-byte attribution to an embedded component and does not compose source-map ranges. +- `proof_inputs` is the exact sorted reference set for `scripts/smoke-release-bundle.mjs`, `scripts/test-release-integrity.mjs`, `test/fixtures/release/hostile-runtime-guard.cjs`, `test/integration/release-offline.test.ts`, `test/integration/mcp-stdio.test.ts`, `test/fixtures/mcp/runtime/initialize.json`, `calls.json`, and `adversarial-bytes.json`, plus `package.json` command wiring and `.github/workflows/ci.yml`. Those files are repository bundle/control records with one physical owner; omission, substitution, or staleness invalidates the proof. +- Build entries and executable roles are closed and sorted. Phase 5 permits exactly one `mcp-stdio` entry/output with handler authority `inert-no-handler`; schema v1 reserves the planned `local-cli` role for Phase 12 without building it or introducing a plugin framework. +- Each current vulnerability disposition binds the exact bundle digest, entry/role set, `inert-no-handler` authority, `dependency_inventory_digest`, complete live advisory-snapshot digest, focused reachability-evidence digest, and prototype-only scope. Semantic validation recomputes `dependency_inventory_digest` over canonical dependency-origin `bundle_inputs`, `dependency_provenance_inputs`, and `current_components`. Advisory snapshots and reachability evidence are canonical records referenced by digest. Any bundle, dependency inventory, handler-authority, or entry change invalidates the decision. Phase 12 must rerun the advisory sweep and reachability decision before adding its handler or entry. +- Gate decisions have stable IDs and canonical lowercase 64-character digests. The sole carry-forward baseline is `HEAD:release/legal-review.json`: when present, every accepted decision in it remains byte-identical in the candidate; when it and all prior release legal artifacts are absent, the initial baseline is empty. A missing or inconsistent HEAD source/output pair—including `HEAD:dist/legal/review.json` not matching the canonical source bytes or missing/mismatched upstream counterparts—fails closed. Corrections append typed amendment/supersession records rather than mutating retained decisions. This is one narrow HEAD comparison for retained audit records, not a history subsystem. +- Canonical `release/legal-review.json` maps byte-identically to `dist/legal/review.json`. Each `release/legal/upstream/` maps byte-identically to `dist/legal/upstream/`. `dist/legal/THIRD_PARTY_NOTICES.md` is the only generated human projection; these paths are the exact `dist/legal/` closure. +- The inventory explicitly records that this repository currently has no project license and therefore has unresolved public-distribution status. It makes no first-party license grant and no unsupported documentation-license or copyleft determination. + +## Filesystem, Runtime, and CI Boundaries + +- One portable repository-relative path codec emits forward slashes and rejects absolute paths, drive-qualified paths, UNC paths, backslashes, empty paths or segments, and `.`/`..` segments. All input/output roots are canonicalized and proven non-overlapping by realpath. Filesystem roots, symlinks at any traversed component, and non-regular files fail through `lstat` checks. +- Stage, materialization, and comparison roots are new, empty, dedicated roots. The tracked target is fixed to the real repository `dist/`; the writer uses safe exact traversal of the validated generated closure and cannot redirect it. Mutation coverage includes symlink ancestors and pre-existing external targets. +- Hostile smoke children use a cwd inside the copied payload and launch only `process.execPath` with explicit arguments and a minimal explicit environment. The launcher removes `NODE_OPTIONS`, `NODE_PATH`, preload/loader variables, package-manager variables, and inherited environment not on the allowlist; supplies controlled empty or unusable HOME, XDG, npm-cache, and temp locations; and places repository/module canaries that must remain unread/unresolved. The manifest binds this launch profile, executable/argv/env keys, cwd class, stdio/fd mapping, guard identity, canary identities, and transcript/fixture digests. +- Before bundle import, the guarded run patches Node-core connection/listener surfaces in `net`, `tls`, `dgram`, `http`, `https`, and `http2`, plus `globalThis.fetch`, `WebSocket`, and `EventSource`, and reports attempted use on inherited fd 3. Negative fixtures exercise DNS and WebSocket attempts. Together, the fixed five-builtin allowlist, rejection of dynamic built-in loading, pre-import Node-core/global guards, empty fd-3 oracle, and exact transcript behaviorally prove that the exercised hostile startup/protocol run opens no network connection or listener, satisfying the architecture's Node-core behavioral proof. This is not a claim of general OS capability isolation. +- `.gitattributes` treats canonical generated `.mjs`, JSON, and generated notice text below `dist/` as LF. Later, more-specific `release/legal/upstream/** -text` and `dist/legal/upstream/** -text` rules preserve exact upstream retained source bytes without disabling normalization for generated legal JSON. Verification checks clean-checkout normalization and mutates attributes/line endings to prove drift is detected. +- CI pins `actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1` and `actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0` after runner-compatibility review. Package-manager caching is disabled for the independent-install proof. The manifest binds workflow and action identities, while byte reproducibility is explicitly scoped to the payload and not the mutable hosted-runner executor. + +## Work Breakdown + +1. **Complete dependency safety gate**: Immediately before implementation, sweep live official advisories for every direct and embedded candidate component, confirm all four `fast-uri@3.1.0` advisories, the `3.1.4` safe 3.x floor, exact embedded path, and compatible patched-artifact availability. Prefer a patched artifact and return for design/compatibility review; otherwise stop for a separate risk decision that binds all required evidence. +2. **Release contracts and shared seams**: Add and register the strict manifest and legal-review JSON Schemas, canonical-document types, exact shared signatures, and fixed CLI/output/exit contract. Implement only one cross-document semantic validator and test representative structural and relationship failures. +3. **Portable paths and root safety**: Centralize the forward-slash path codec, canonical non-overlap rules, `lstat` traversal, empty dedicated-root preconditions, and fixed real-repository `dist/` target. Cover symlink ancestors, non-regular files, filesystem roots, pre-existing external targets, and overlapping roots. +4. **Deterministic staged builder and declared coverage**: Build only `src/main.ts` under the fixed Node-24 ESM profile, bind all scanned/contributing inputs and the exact closed repository-control/materialization union, and reject imports outside the five allowed `node:` specifiers or dynamic built-in loading. Keep proof and declared-content collections as references to their sole repository owners and validate the in-memory payload before writing the external stage. +5. **Provenance and exact legal mapping**: Populate package-scoped dependency-provenance records, bind adjacent source maps and the known embedded closure, distinguish installed from embedded versions, and fail unknown roots or missing maps. Map canonical review and upstream sources exactly into the fixed `dist/legal/` closure, generate only `THIRD_PARTY_NOTICES.md`, and avoid source-map range composition, exact physical-byte attribution claims, or a first-party license grant. +6. **Independent reproduction and tracked writer**: Materialize only the validated repository-owned allowlist into a fresh root, require no `node_modules`, run `npm ci`, verify every installed dependency/provenance input, rebuild to a distinct comparison root, and byte-compare closed payloads. Make `writeTrackedReleasePayload` execute this path itself before replacing only the fixed `dist/` closure; keep ordinary check read-only. +7. **HEAD baseline, decisions, and proof binding**: Bind the closed proof-input references and stable vulnerability decision IDs/digests, including the recomputed dependency-inventory digest. Compare only the consistent HEAD legal source/output baseline, enforce byte-identical accepted-decision retention, use amendments/supersessions for corrections, and preserve the Phase 12 rerun requirement. +8. **Hostile clean-copy proof**: Run the exact copied payload uninstrumented and then with pre-import Node-core/global guards, direct `process.execPath`, child cwd, minimal scrubbed environment, unusable ambient roots, repository/module canaries, bound launch profile, fd-3 oracle, and exact transcript. Exercise DNS/WebSocket negatives and prove the exercised run opens no network connection or listener without claiming OS sandboxing. +9. **Tracked-byte and CI normalization proof**: Add `.gitattributes` ordering for canonical LF generated text and byte-exact legal sources, verify clean-checkout and mutation behavior, pin the two action SHAs after compatibility review, disable install caching, and reproduce under exact Node `24.15.0` and `24.18.0` clean checkouts. +10. **Commands and aggregate verification**: Wire the fixed stage/check/write/smoke/mutation commands, schema tests, release integration test, existing stdio integration, temporary-build isolation, and aggregate local/CI checks. Add no dependency, SBOM/signing/publishing system, installer, helper, OS sandbox, or runtime subsystem. + +## Success Criteria + +- [ ] Before implementation or tracked output mutation, a live complete advisory sweep confirms the current embedded closure and resolves all four `fast-uri@3.1.0` advisories through a compatible patched artifact and reviewed design revision, or implementation stops pending separate explicit prototype-risk acceptance naming the full snapshot and inert reachability result. +- [ ] Both release documents validate against their sole strict JSON Schema shape authorities and the sole semantic correlation authority; canonical bytes/digests, all closed collections, exact schema/asset ownership, recursive artifacts, and representative zero-byte/scanned-only cases reject unknown, overlapping, unresolved, stale, partial, or extra data. +- [ ] The release build produces exactly one `mcp-stdio` Node-24 ESM executable with `inert-no-handler`, no release source map, no local helper, no dynamic built-in loading, and only `node:process`, `node:buffer`, `node:util`, `node:crypto`, and banner `node:module` imports. +- [ ] The repository-control union is complete, whole-file digest-bound, and the exact preinstall materialization authority; bundle paths have one owner, while declared content and proof inputs are reference subsets. Dependency provenance uses exact package/version/package-relative records resolved and reverified only inside the post-`npm ci` package root. +- [ ] Every dependency provenance input actually consulted is reverified after independent `npm ci`; adjacent maps and the known embedded closure are conservatively inventoried with unknown/missing roots rejected, installed and embedded versions distinguished, and no unsupported exact-byte/source-map attribution claim. +- [ ] The exact proof-input set and launch profile are digest-bound. Each current risk decision carries the recomputed canonical dependency-inventory digest plus canonical advisory-snapshot and reachability-evidence references; omission, substitution, staleness, bundle/dependency/handler/entry changes, or Phase 12 expansion invalidates it. +- [ ] `writeTrackedReleasePayload` independently materializes, installs, verifies dependency and legal provenance, rebuilds, and byte-compares before replacing fixed real-repository `dist/`; a validated candidate stage cannot authenticate itself, while read-only check may compare two payloads without mutation. +- [ ] The sole consistent HEAD legal baseline governs carry-forward: prior accepted decisions remain byte-identical, corrections use amendment/supersession records, source review/upstream bytes map exactly to the fixed `dist/legal/` closure, and the sole generated projection is `THIRD_PARTY_NOTICES.md`. The inventory records the missing project license, unresolved distribution status, and empty-Ajv-JSON limitation. +- [ ] Path/root validation rejects non-portable paths, roots, overlaps, symlinks, non-regular files, pre-existing external targets, and unsafe traversal; all intermediate roots are new, empty, dedicated, and outside each other and the repository. +- [ ] Exact-payload and guarded hostile-copy runs use direct Node, a copied-payload cwd, scrubbed minimal environment, controlled ambient roots, canaries, the fixed import policy, pre-import Node-core/global guards, empty fd 3, and exact transcript to prove behaviorally that the exercised run opens no network connection or listener; no general OS-isolation claim is made. +- [ ] Clean-checkout normalization preserves canonical LF generated text and exact upstream legal bytes; true clean CI checkouts with pinned action SHAs, disabled install caching, and both exact Node patches reproduce a byte-identical payload, while the runner itself is outside the byte-reproducibility claim. +- [ ] Release contracts, mutations, reproduction, hostile-copy, Phase 4 compatibility/runtime, temporary-build, full aggregate, and CI checks pass with no dependency or behavior beyond inert packaging; REQ-11/REQ-33 behavioral completion remains unclaimed. + +## Verification Steps + +1. Before implementation mutation, use live official advisory, registry, SDK-release, and source evidence to enumerate the full current embedded closure and all four `fast-uri@3.1.0` advisories, verify the `3.1.4` safe 3.x floor and lack/presence of a compatible patched server, and either return for a patch design revision or obtain a separate fully bound prototype-risk decision. +2. Compile both strict schemas and exercise the sole semantic validator against unknown shape, overlaps, duplicate ownership, incomplete repository controls, broken proof/content references, package-root provenance escape, stale canonical bytes/digests, scanned/contributing mismatch, zero-byte inputs, artifact self-reference, and recursive extra/missing files. Confirm no second shape model exists. +3. Stage twice into new empty non-overlapping roots. Inspect the manifest for the sole `mcp-stdio` entry, exact eight current bundled schemas, complete repository-control/materialization union and declared-content references, every scanned input, the exact `bytesInOutput > 0` subset, five allowed imports, no dynamic loader, and no source map or `local-cli` output. +4. Verify exact package/version/package-relative dependency records only below fresh post-`npm ci` package roots, the six embedded versions, installed/embedded distinctions, map/root failures, retained bytes, and the empty-Ajv-JSON limitation without composed-range or exact embedded-byte claims. +5. Verify exact review/upstream source mappings, the fixed `dist/legal/` closure, and sole generated notice. Test empty and consistent HEAD baselines, missing/mismatched HEAD counterparts, decision retention/amendment, and recomputation of `dependency_inventory_digest` from its three canonical collections. +6. Prove tracked writing independently materializes, installs, verifies, rebuilds, and compares before fixed `dist/`; mutate candidate, proof reference, dependency record, symlink/target/path/root, and comparison output to confirm fail-closed behavior. +7. Run both hostile modes through direct Node and verify the fixed import policy, dynamic-load rejection, pre-import Node-core/global guards, DNS/WebSocket negatives, empty fd 3, exact transcript, and clean shutdown behaviorally prove the exercised run opens no connection or listener. +8. Check `.gitattributes` normalization and clean-checkout reproduction on both pinned Node/action versions with caching disabled. +9. Run the fixed CLI forms and full aggregate, asserting canonical stdout, stderr diagnostics, exit codes, release/runtime tests, mutations, reproduction, hostile-copy, temporary builds, dependency/notices, and CI-equivalent checks. + +--- +*Designed: 2026-07-27* diff --git a/.archflow/tasks/mcp-integration/reviews/phase-5-design-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-5-design-counter-review.md new file mode 100644 index 00000000..97810e2d --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-5-design-counter-review.md @@ -0,0 +1,49 @@ +# Phase 5 Design Counter-Review + +1. **Blocker — the `fast-uri` security gate covers only one of four current high-severity advisories and names an obsolete safe floor.** The current SDK source map identifies embedded `fast-uri@3.1.0`, and the measured release build contributes the enclosing `ajvProvider-CEoC__sr.mjs` chunk. The design checks only [GHSA-q3j6-qgpj-74h6](https://github.com/advisories/GHSA-q3j6-qgpj-74h6), fixed in `3.1.1`. The same embedded version is also affected by [GHSA-v39h-62p7-jpjc](https://github.com/advisories/GHSA-v39h-62p7-jpjc), fixed in `3.1.2`; [GHSA-4c8g-83qw-93j6](https://github.com/advisories/GHSA-4c8g-83qw-93j6), fixed in `3.1.3`; and [GHSA-v2hh-gcrm-f6hx](https://github.com/advisories/GHSA-v2hh-gcrm-f6hx), fixed in `3.1.4`. All four advisories say there is no workaround. Registry evidence shows `3.1.4` is the current safe 3.x release and `4.1.1` is latest overall. `@modelcontextprotocol/server@2.0.0` is current and still embeds `3.1.0`, so no patched MCP artifact presently exists. A review or risk acceptance that addresses only the named advisory could authorize a payload still affected by three undisposed vulnerabilities. **Suggested resolution:** make the implementation-start gate perform a current advisory sweep for every embedded component, enumerate all four `fast-uri` advisories, and require at least `3.1.4` for a 3.x replacement. Until a patched MCP artifact exists, stop for a separate explicit prototype-risk decision that names all four advisories and binds the focused inert-runtime reachability analysis; never treat `3.1.1` as resolved. + +2. **Major — the tracked-write path can promote a self-authenticating stage without mandatory independent reproduction.** `checkReleasePayload` makes `comparisonRoot` optional, and the tracked writer is described as validating an external stage before copying it. A stage produced from tampered `node_modules` can consistently describe and hash its own altered bundle, metafile, and legal receipt. The clean-root `npm ci` reproduction is a separate verification activity, so the write command can acquire tracked authority before that independent check runs. Esbuild's [metafile contract](https://esbuild.github.io/api/#metafile) reports build inputs and outputs, not every resolution-controlling read or proof that installed bytes came from the lock tarballs. **Suggested resolution:** require `write-tracked-release` to consume a validated independent-reproduction receipt (or perform materialization, `npm ci`, rebuild, and byte comparison itself) before replacing tracked output. Bind and verify resolution-controlling package manifests and exact tarball identities as part of that proof; keep comparison optional only for read-only checking. + +3. **Major — `release/legal-review.json` has no strict structural/version authority.** It is a trust-bearing machine-readable format, but the only new schema is `release-manifest.schema.json`; the design simultaneously says that schema is solely the manifest shape authority and that `validateReleaseSemantics` is not a second shape model. This leaves no owner for the receipt's version, closed keys, field types, `current_components`, or `dependency_gate_decisions`, contrary to REQ-04's strict versioning requirement. **Suggested resolution:** add and register a strict versioned legal-review schema, or place its complete closed shape in an anchored `$defs` section of the release-manifest schema and compile that exact subschema against the external receipt before semantic correlation. Include unknown-key rejection and exact current/history record variants. + +4. **Major — dependency-owned legal/provenance inputs fall outside the clean-root verification contract.** Post-`npm ci` verification covers only dependency-owned `bundle_inputs`. The actual esbuild metafile includes the SDK's contributing `.mjs` chunk but not its adjacent `.mjs.map`, package manifests, or license files. Those omitted files are exactly what the design needs to discover embedded versions, registry/tarball provenance, and applicable texts. A clean root can therefore validate every dependency bundle input while deriving legal evidence from unbound installed files. **Suggested resolution:** add a closed dependency-owned provenance/control collection for every source map, package manifest, license/notice file, and other evidence input. Record path, byte count, and digest in the manifest and verify all of them after `npm ci` before legal derivation, rebuilding, or comparison. + +5. **Major — the claimed exact embedded-component closure is not derivable from the specified outer metafile/map evidence.** Esbuild attributes final bytes to prebundled SDK chunks, not to the packages embedded inside them. The current contributing AJV provider map names sources from `ajv@8.18.0`, `ajv-formats@3.0.1`, `fast-uri@3.1.0`, `fast-deep-equal@3.1.3`, and `json-schema-traverse@1.0.0`; other contributing SDK maps add further nested roots such as `content-type@1.0.5`. These versions differ from or are absent from the npm lock graph. Binding an outer chunk and adjacent map does not establish which mapped sources survived the second esbuild pass, and 17 mapped AJV JSON sources have empty `sourcesContent`. The document nevertheless claims exact physical contribution and graph closure. **Suggested resolution:** define a general exhaustive adjacent-map discovery and nested component-mapping contract for every contributing prebundle; pin the known Phase 5 closure, tarball integrities, licenses, and retained texts; distinguish embedded from installed same-name versions; and fail on unrecognized roots or missing maps. Either add composed-range/fingerprint evidence tying final output to embedded sources or conservatively inventory all mapped components and narrow the claim from exact physical contribution. Preserve the empty-AJV-JSON limitation explicitly instead of combining it with an unqualified exactness claim. + +6. **Major — the exact schema and asset coverage is undefined.** The architecture requires schema/asset bindings and CI failure on their drift, but the phase repeatedly refers only to "declared schema/assets." The current release metafile contains eight JSON schemas and no `assets/**`, while the repository contains a larger schema and shipped-asset set. Separate chunks could reasonably choose embedded-only files, all v1 schemas, or all shipped assets and each believe it implements the design. **Suggested resolution:** enumerate the exact v1 schema and asset namespaces or paths covered in this phase, state which are bundle inputs versus release controls, and define how non-bundled shipped members enter or intentionally do not enter the offline payload. + +7. **Major — the proof harness and protocol fixtures are not required to be manifest-bound.** The control list names build/check/write/materializer scripts but omits `scripts/smoke-release-bundle.mjs`, `scripts/test-release-integrity.mjs`, `test/fixtures/release/hostile-runtime-guard.cjs`, the release integration test, and the existing byte-exact MCP runtime fixtures. The guard is the sole non-payload executable in the hostile run, yet weakening it or a transcript need not cause manifest drift, conflicting with the architecture's requirement that CI fail on protocol-fixture drift. **Suggested resolution:** define a closed digest-bound proof-input subset containing the complete smoke/mutation harness, guard, CI command wiring, and exact transcript fixtures, and mutation-test omission, substitution, and stale digests. + +8. **Major — the JavaScript guard cannot support the universal "no network connection or listener" claim.** The build accepts every `node:` external, while the closed interception list omits `node:dns`/`node:dns/promises`, `dns.Resolver`, Node's WebSocket/EventSource/Undici entry points, and child-process- or worker-mediated networking. Patching selected public JS methods is not equivalent to running without network capability. **Suggested resolution:** for the inert Phase 5 payload, reject every builtin outside a pinned measured allowlist (currently the bundle reports only `node:process`, `node:buffer`, `node:util`, and `node:crypto`, plus the banner's `node:module`) and add negative DNS/WebSocket fixtures. If the claim remains universal, add OS/syscall-level network denial or observation and retain the JS guard only as a diagnostic oracle; otherwise narrow the success criterion to the exact guarded surfaces. + +9. **Major — hostile-copy launch isolation is underspecified and the existing integration convention would violate it.** The phase does not pin the child's `cwd`, inherited environment, `HOME`/cache locations, or Node bootstrap variables. Existing `mcp-stdio.test.ts` launches its temporary bundle with the repository root as `cwd` and inherits the ambient environment. `NODE_OPTIONS`, `NODE_PATH`, preload/loaders, or repository-relative discovery can therefore add executable/input bytes outside the claimed payload and guard. **Suggested resolution:** require `cwd` inside the isolated hostile copy, an explicit minimal environment with Node preload/module-resolution/package-manager variables removed, controlled nonexistent home/cache paths, direct `process.execPath`, and canaries proving repository-local files/modules are unavailable. Bind this launch profile as a release control. + +10. **Major — a `fast-uri` reachability/risk disposition is not bound tightly enough to the code whose risk it evaluates.** The proposed record binds SDK/chunk/map/advisory evidence, but not the exact final bundle, entry/handler authority, or reachability-test digest. A prototype acceptance based on the inert Phase 5 route could remain present when Phase 12 rebuilds the payload with real handlers and new attacker-controlled flows. **Suggested resolution:** bind every current vulnerability disposition to the exact bundle digest, entry set, handler-authority state, reachability evidence digest, and approved prototype scope. Any rebuild, dependency change, or handler-authority change must invalidate it and rerun the gate; a retained historical record must never satisfy the current-payload check. + +11. **Major — `dependency_gate_decisions` is called immutable history without an enforceable carry-forward rule.** The checker can prove only that the current receipt and manifest agree. Deleting or editing an old decision and regenerating both can still pass on a fresh checkout, so the promised retention of a superseded `fast-uri@3.1.0` decision is not enforced. **Suggested resolution:** give decisions stable IDs and content digests, require the previously tracked accepted decision set to be a byte-identical subset of every successor, and represent corrections with explicit amendment/supersession records. If no prior-baseline comparison is intended, call this retained current-checkout evidence rather than immutable history. + +12. **Major — chunk boundary contracts are too incomplete for this nine-part phase.** `ReleasePayloadSummary` is undefined, `validateReleaseSemantics(...)` has no signature, and `stageManifest` has no pinned type. The design does not fix the validated-stage authority flow, canonical bytes versus parsed values, exact shared exports, or CLI arguments/exit behavior even though builder, checker, writer, materializer, mutation suite, and CI are separate chunks. Divergent implementations can create the second shape/canonicalization authorities the design forbids. **Suggested resolution:** define exact exported signatures and closed argument/return shapes for all shared seams, including canonical manifest bytes, parsed values, validated closed file sets/digests, provenance collections, and CLI flags/stdout/stderr/exit contracts. Leave algorithms to implementation. + +13. **Major — path, root-containment, and file-kind safety are not specified strongly enough for the materializer and writer.** Requiring absolute roots and lexical "outside the repository" checks does not reject symlink aliases, a staged symlink, filesystem roots, non-regular files, or an output ancestor redirected into the repository. The existing temporary-build helper is lexical-only, so reusing that pattern would make this concrete. **Suggested resolution:** define one portable repository-relative path codec (`/` separators; no absolute, drive, UNC, backslash, empty, or dot segments), canonical/realpath non-overlap checks, `lstat`-based rejection of symlinks and non-regular files, and new-empty-dedicated-root preconditions for source, stage, comparison, and tracked-write traversal. Mutation-test symlink ancestors and attempts to overwrite pre-existing external files. + +14. **Major — CI dependency currency and supply-chain pinning are omitted from a release-integrity phase.** The actual workflow still uses `actions/checkout@v4` and `actions/setup-node@v4`; current official releases are [checkout v6.0.2](https://github.com/actions/checkout/releases/tag/v6.0.2) and [setup-node v6.4.0](https://github.com/actions/setup-node/releases/tag/v6.4.0). Moving major tags are also mutable dependencies, so even updating to `@v6` would not make the release proof reproducible or supply-chain pinned. **Suggested resolution:** review runner compatibility, move to the current supported majors, pin each action to a reviewed full commit SHA with a version comment, and include those identities in the release-control evidence or explicitly scope the reproducibility claim to payload bytes rather than the CI executor. + +15. **Minor — tracked-byte reproducibility does not control Git checkout conversion.** `.gitattributes` currently contains only `* text=auto`. Generated `.mjs`, JSON, and legal text may therefore be checked out with CRLF under `core.autocrlf`, while the builder mandates LF and performs byte comparison. Two Ubuntu jobs with default Git settings do not exercise this boundary. **Suggested resolution:** add explicit attributes for `dist/**` and retained legal files (`text eol=lf` for canonical text, or `-text` where exact upstream bytes must be retained) and add a checkout-normalization fixture or mutation test. + +## Triage + +1. **Accepted.** The design now requires a live advisory sweep for every embedded component, enumerates all four current high-severity `fast-uri@3.1.0` advisories, establishes `3.1.4` as the safe 3.x floor, records that no compatible patched MCP server currently exists, and requires any separate prototype-risk decision to name the complete advisory snapshot and inert reachability result. +2. **Accepted.** `writeTrackedReleasePayload` can no longer promote a candidate stage after self-validation. It must independently materialize source, run `npm ci`, verify installed dependency and provenance bytes, rebuild into another root, and byte-compare the two closed payloads before touching `dist/`. +3. **Accepted.** The design adds and registers a separate strict versioned `release-legal-review.schema.json` for the receipt, current-component, decision, amendment, and supersession shapes; the single semantic validator correlates it with the manifest. +4. **Accepted.** A closed `dependency_provenance_inputs` collection now binds every consulted map, dependency package manifest, retained registry/tarball identity record, and license/notice file by path, size, and digest and re-verifies them after the independent install. +5. **Accepted in part.** The design adopts exhaustive adjacent-map discovery for contributing dependency prebundles, pins the known embedded closure, distinguishes installed from embedded versions, and fails unknown roots or missing expected maps. It deliberately rejects composed source-map/range machinery as disproportionate and narrows the claim to conservative component inventory rather than exact embedded physical-byte attribution; the empty-Ajv-JSON limitation remains explicit. +6. **Accepted.** Declared coverage is now the complete tracked `src/contracts/schemas/v1/*.schema.json` namespace plus `assets/workflow.yaml` and the five exact constitution files. The eight currently bundled schemas are named; every other schema/asset is a release control unless the actual metafile makes it a bundle input. +7. **Accepted.** A closed `proof_inputs` reference set now binds the release smoke/mutation harness, guard, release and stdio integration tests, exact runtime fixtures, package command wiring, and CI workflow. Each physical file still has one bundle/control owner; omission, substitution, or staleness invalidates proof. +8. **Accepted in part.** The design rejects all imports outside the measured inert allowlist (`node:process`, `node:buffer`, `node:util`, `node:crypto`, plus banner `node:module`), rejects dynamic built-in loading, extends guarded globals to `fetch`, `WebSocket`, and `EventSource`, and adds DNS/WebSocket negatives. It rejects a new OS/syscall sandbox as out of scope and narrows the claim to measured imports and declared guarded surfaces rather than universal capability isolation. +9. **Accepted.** The hostile launch profile now fixes a copied-payload cwd, direct `process.execPath`, explicit argv and stdio, a minimal scrubbed environment, controlled unusable HOME/XDG/npm-cache/temp locations, and repository/module canaries; the profile and fixtures are digest-bound. +10. **Accepted.** A current vulnerability disposition now binds the exact bundle digest, entry/role set, `inert-no-handler` authority, complete advisory snapshot, reachability evidence, and prototype scope. Bundle, dependency, handler, or entry changes invalidate it, and Phase 12 must rerun the gate. +11. **Accepted in part.** Decisions now have stable IDs/digests; the tracked writer requires prior accepted decisions to remain a byte-identical subset, and corrections append typed amendment/supersession records. The design calls these retained audit records and does not add a generalized Git-history subsystem. +12. **Accepted.** The interface section now pins canonical document, payload summary, validated stage, and reproduction proof shapes; exact shared function signatures; candidate-to-reproduction authority flow; and CLI flags, stdout/stderr ownership, and exit statuses while leaving algorithms to implementation. +13. **Accepted.** The design adds one portable path codec, canonical realpath non-overlap, filesystem-root rejection, `lstat`-based symlink/non-regular-file rejection, new empty dedicated intermediate roots, and a fixed real-repository `dist/` target with adversarial path/root mutations. +14. **Accepted in principle; proposed versions corrected as stale.** Live official release pages on 2026-07-27 show `actions/checkout@v7.0.1` and `actions/setup-node@v7.0.0`, newer than the review's v6 suggestions. The design pins their reviewed full SHAs (`3d3c42e5aac5ba805825da76410c181273ba90b1` and `820762786026740c76f36085b0efc47a31fe5020`), requires runner-compatibility review, disables package-manager caching for the independent proof, binds workflow/action identities, and scopes reproducibility to payload bytes rather than the hosted executor. +15. **Accepted.** The Files, boundaries, and verification sections now require `.gitattributes` rules that force canonical generated release text to LF while preserving exact upstream legal source bytes as `-text`, with clean-checkout and mutation coverage. From c334d2ffcaf1057ec6b68581800b14018520f426 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Tue, 28 Jul 2026 00:35:44 -0500 Subject: [PATCH 015/124] MCP Integration Phase 5: Offline Bundle and Release Integrity Builds and tracks the deterministic inert MCP bundle with canonical manifest, legal/risk evidence, and hostile-copy verification. Adds fresh-install reproduction and crash-recoverable dist promotion, with the accepted local-only fast-uri risk bound to immutable evidence. --- .../tasks/mcp-integration/architecture.md | 2 +- ...ffline-bundle-and-release-integrity-log.md | 54 + ...-5-offline-bundle-and-release-integrity.md | 6 +- .../reviews/phase-5-impl-counter-review.md | 47 + .gitattributes | 13 + .github/workflows/ci.yml | 13 +- dist/archflow-mcp.mjs | 34194 ++++++++++++++++ dist/legal/THIRD_PARTY_NOTICES.md | 16 + dist/legal/review.json | 462 + dist/legal/upstream/ajv-8.18.0/LICENSE | 22 + dist/legal/upstream/ajv-formats-3.0.1/LICENSE | 21 + .../legal/upstream/content-type-1.0.5/LICENSE | 22 + .../upstream/fast-deep-equal-3.1.3/LICENSE | 21 + dist/legal/upstream/fast-uri-3.1.0/LICENSE | 32 + .../json-schema-traverse-1.0.0/LICENSE | 21 + .../modelcontextprotocol-core-2.0.0/LICENSE | 216 + .../modelcontextprotocol-server-2.0.0/LICENSE | 216 + dist/legal/upstream/zod-4.4.3/LICENSE | 21 + dist/manifest.json | 2174 + dist/metafile.json | 2584 ++ package.json | 9 +- release/evidence/advisory-snapshot.json | 38 + .../evidence/focused-inert-reachability.json | 20 + .../patched-artifact-availability.json | 12 + release/evidence/user-risk-acceptance.json | 26 + release/legal-review.json | 462 + release/legal/upstream/ajv-8.18.0/LICENSE | 22 + .../legal/upstream/ajv-formats-3.0.1/LICENSE | 21 + .../legal/upstream/content-type-1.0.5/LICENSE | 22 + .../upstream/fast-deep-equal-3.1.3/LICENSE | 21 + release/legal/upstream/fast-uri-3.1.0/LICENSE | 32 + .../json-schema-traverse-1.0.0/LICENSE | 21 + .../modelcontextprotocol-core-2.0.0/LICENSE | 216 + .../modelcontextprotocol-server-2.0.0/LICENSE | 216 + release/legal/upstream/zod-4.4.3/LICENSE | 21 + scripts/build-release.mjs | 20 + scripts/check-release.mjs | 21 + scripts/release-support.mjs | 1536 + scripts/reproduce-release.mjs | 19 + scripts/smoke-release-bundle.mjs | 322 + scripts/test-release-integrity.mjs | 271 + scripts/write-tracked-release.mjs | 20 + .../v1/release-legal-review.schema.json | 392 + .../schemas/v1/release-manifest.schema.json | 379 + src/contracts/versions.ts | 4 +- test/contracts/release-contracts.test.ts | 396 + test/contracts/schema-registry.test.ts | 2 + .../release/hostile-runtime-guard.cjs | 89 + test/integration/mcp-stdio.test.ts | 2 +- test/integration/release-offline.test.ts | 88 + 50 files changed, 44867 insertions(+), 10 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity-log.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-5-impl-counter-review.md create mode 100644 dist/archflow-mcp.mjs create mode 100644 dist/legal/THIRD_PARTY_NOTICES.md create mode 100644 dist/legal/review.json create mode 100644 dist/legal/upstream/ajv-8.18.0/LICENSE create mode 100644 dist/legal/upstream/ajv-formats-3.0.1/LICENSE create mode 100644 dist/legal/upstream/content-type-1.0.5/LICENSE create mode 100644 dist/legal/upstream/fast-deep-equal-3.1.3/LICENSE create mode 100644 dist/legal/upstream/fast-uri-3.1.0/LICENSE create mode 100644 dist/legal/upstream/json-schema-traverse-1.0.0/LICENSE create mode 100644 dist/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE create mode 100644 dist/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE create mode 100644 dist/legal/upstream/zod-4.4.3/LICENSE create mode 100644 dist/manifest.json create mode 100644 dist/metafile.json create mode 100644 release/evidence/advisory-snapshot.json create mode 100644 release/evidence/focused-inert-reachability.json create mode 100644 release/evidence/patched-artifact-availability.json create mode 100644 release/evidence/user-risk-acceptance.json create mode 100644 release/legal-review.json create mode 100644 release/legal/upstream/ajv-8.18.0/LICENSE create mode 100644 release/legal/upstream/ajv-formats-3.0.1/LICENSE create mode 100644 release/legal/upstream/content-type-1.0.5/LICENSE create mode 100644 release/legal/upstream/fast-deep-equal-3.1.3/LICENSE create mode 100644 release/legal/upstream/fast-uri-3.1.0/LICENSE create mode 100644 release/legal/upstream/json-schema-traverse-1.0.0/LICENSE create mode 100644 release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE create mode 100644 release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE create mode 100644 release/legal/upstream/zod-4.4.3/LICENSE create mode 100644 scripts/build-release.mjs create mode 100644 scripts/check-release.mjs create mode 100644 scripts/release-support.mjs create mode 100644 scripts/reproduce-release.mjs create mode 100644 scripts/smoke-release-bundle.mjs create mode 100644 scripts/test-release-integrity.mjs create mode 100644 scripts/write-tracked-release.mjs create mode 100644 src/contracts/schemas/v1/release-legal-review.schema.json create mode 100644 src/contracts/schemas/v1/release-manifest.schema.json create mode 100644 test/contracts/release-contracts.test.ts create mode 100644 test/fixtures/release/hostile-runtime-guard.cjs create mode 100644 test/integration/release-offline.test.ts diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index 23c68c1c..3a548198 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -775,7 +775,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali | 2 | Review Evidence and Contract Authority | COMPLETE (2026-07-27) | | 3 | MCP Contract Boundary and Dependency Admission | COMPLETE (2026-07-27) | | 4 | Guarded MCP Runtime and SDK Compatibility | COMPLETE (2026-07-27) | -| 5 | Offline Bundle and Release Integrity | Not Started | +| 5 | Offline Bundle and Release Integrity | COMPLETE (2026-07-28) | | 6 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | | 7 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | | 8 | Snapshots, Implementation Manifests, and Restore | Not Started | diff --git a/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity-log.md b/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity-log.md new file mode 100644 index 00000000..055f6eef --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity-log.md @@ -0,0 +1,54 @@ +## Implementation Log: Phase 5 - Offline Bundle and Release Integrity + +**Implemented**: 2026-07-28 +**Status**: COMPLETE + +### Decisions Made + +- Kept the release executable limited to the existing inert `mcp-stdio` entry with `inert-no-handler`; no local helper, persistence, dispatch, or production handler authority was introduced. +- Recorded the user's explicit local-only, non-production risk acceptance for embedded `fast-uri@3.1.0` in canonical evidence bound to all four current high-severity advisories, patched-artifact availability, and focused inert-runtime reachability. Bundle, dependency, entry, or handler-authority changes invalidate the decision. +- Used strict JSON Schema as the structural authority and one release semantic validator for manifest/legal collection algebra, physical metafile inputs, dependency provenance, component/license closure, launch profile, evidence references, and generated payload closure. +- Added a non-promoting `release:reproduce` command so the aggregate and CI exercise fresh source materialization, `npm ci`, installed-byte verification, rebuild, and byte comparison without mutating tracked output. +- Made tracked `dist/` replacement recoverable through deterministic promotion/backup paths and a canonical transaction marker checked by every release operation. + +### Deviations from Plan + +- Added `scripts/reproduce-release.mjs` and `npm run release:reproduce`. The original command list exposed reproduction only inside the writer; counter-review showed that aggregate and CI verification otherwise could pass without exercising the fresh-install path. +- Added four canonical files below `release/evidence/` rather than retaining risk-evidence digests without resolvable records. This makes the accepted prototype exception durable and independently verifiable. +- Strengthened the planned tracked replacement with deterministic crash recovery and fault probes after counter-review identified a rename interruption window. +- Expanded hostile smoke from initialization-only coverage to initialization, every call fixture, and all adversarial byte sequences in exact and guarded modes. + +### Patterns Established + +- Release evidence references resolve to canonical tracked records and are recomputed; digest-shaped strings alone never establish authority. +- Repository, candidate, materialization, and comparison roots are canonicalized and checked pairwise before work; validated candidates are rechecked before proof issuance. +- Generated release projections are checked against their sources: legal review and upstream licenses map byte-identically, while the notice is regenerated from the canonical receipt. +- Residual executable loader syntax is checked independently of esbuild's static metafile so computed built-in loading cannot bypass the import allowlist. + +### Gotchas + +- `npm audit` cannot see `fast-uri@3.1.0` embedded inside the MCP server prebundle; the live advisory sweep and source-map inventory are separate release evidence. +- TypeScript `7.0.2` exposes its scanner through the unstable AST surface rather than the former root parser API. The narrow emitted-loader scanner enforces forward progress and has nested-template regressions. +- The ambient developer Node was below the project floor, so final aggregate verification explicitly invoked exact Node `24.15.0` and `24.18.0` binaries. +- Retained upstream legal bytes may intentionally omit a final newline; `.gitattributes` marks those paths `-text` while generated release text is canonical LF. + +### Key Interfaces + +- `scripts/release-support.mjs`: `buildReleasePayload(options)`, `validateReleaseSemantics(options)`, `materializeReleaseSourceRoot(options)`, `reproduceReleasePayload(options)`, `checkReleasePayload(options)`, `writeTrackedReleasePayload(options)`, `recoverTrackedRelease(repositoryRoot)`, and `assertReleaseLoaderPolicy(source)`. +- `scripts/reproduce-release.mjs`: non-promoting fresh-install reproduction CLI used by `check:release` and CI. +- `src/contracts/schemas/v1/release-manifest.schema.json`: sole structural authority for manifest, provenance, adjacent-map, launch-profile, and artifact records. +- `src/contracts/schemas/v1/release-legal-review.schema.json`: sole structural authority for component, legal-source, risk-decision, amendment, and supersession records. +- `release/legal-review.json` and `release/evidence/*.json`: canonical legal/risk source records mapped and referenced by the generated payload. +- `dist/manifest.json`: tracked payload authority; bundle digest `16faf6365bc502ec0c0e00f150b43c300e65dfa9dcace1cce3d98d850b8cbbd0`, dependency-inventory digest `1f93c687b91691f3afb99d657246504a9b369311333ecd4e8c77abab1a23c046`. + +### Verification + +- Full aggregate passed under exact Node `24.15.0` and `24.18.0`. +- 292 full tests, 55 release/contract tests, and 86 focused MCP runtime tests passed. +- Fresh-`npm ci` reproduction compared 14 payload files byte-for-byte. +- Exact and guarded hostile copies exercised initialization, calls, malformed JSON, partial JSON, and invalid UTF-8 with byte-equal transcripts and zero network-oracle bytes. +- Seventeen release-integrity mutations covered schema, graph, provenance, root/path, map expectation, launch profile, legal mapping, loader policy, nested roots, and transaction recovery. + +### Durable Convention Proposal + +No new project-wide `CLAUDE.md` convention is proposed. The canonical release-evidence, embedded-advisory, and transaction-recovery rules are specific to this MCP release task and are enforced by its scripts and tests. diff --git a/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity.md b/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity.md index 8cf8187b..9dc5abfa 100644 --- a/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity.md +++ b/.archflow/tasks/mcp-integration/phases/phase-5-offline-bundle-and-release-integrity.md @@ -1,6 +1,7 @@ # Phase 5: Offline Bundle and Release Integrity -**Status**: DESIGNED +**Status**: COMPLETE +**Implemented**: 2026-07-28 **Task**: mcp-integration **Goal**: Produce a license-complete deterministic tracked offline payload and prove hostile clean-copy startup. **Requirements**: REQ-04, REQ-05, REQ-11, REQ-27, REQ-28, REQ-33 @@ -105,7 +106,7 @@ writeTrackedReleasePayload(options: { }): Promise; ``` -The CLI forms are fixed as `npm run release:stage -- --output `, `npm run release:check -- --payload [--compare ]`, `npm run release:write -- --stage `, `npm run release:smoke -- --payload `, and `npm run release:mutations`. On success, each command writes one canonical JSON summary to stdout. Diagnostics go to stderr. Exit status is `0` for success, `1` for an operation or validation failure, and `2` for invalid usage. The tracked-write command creates its own dedicated materialization and comparison roots and must complete the independent reproduction path above before touching `dist/`. +The CLI forms are fixed as `npm run release:stage -- --output `, `npm run release:check -- --payload [--compare ]`, `npm run release:reproduce`, `npm run release:write -- --stage `, `npm run release:smoke -- --payload `, and `npm run release:mutations`. On success, each command writes one canonical JSON summary to stdout. Diagnostics go to stderr. Exit status is `0` for success, `1` for an operation or validation failure, and `2` for invalid usage. The non-promoting reproduction command independently stages, materializes, installs, rebuilds, and compares without touching `dist/`. The tracked-write command creates its own dedicated materialization and comparison roots and must complete the same independent reproduction path before touching `dist/`. ## Files @@ -122,6 +123,7 @@ The CLI forms are fixed as `npm run release:stage -- --output `, `npm | Create | `scripts/build-release.mjs` | Expose the external empty-stage build form and validate the complete in-memory payload before materialization. | | Create | `scripts/write-tracked-release.mjs` | Independently materialize, install, verify, rebuild, compare, and only then replace the fixed tracked payload. | | Create | `scripts/check-release.mjs` | Read-only validation of one payload and optional comparison of two validated payloads. | +| Create | `scripts/reproduce-release.mjs` | Exercise the fresh-`npm ci` materialization/rebuild proof without promoting tracked output. | | Create | `scripts/test-release-integrity.mjs` | Mutation-test representative schema, graph, provenance, path, write, normalization, and proof-input failures. | | Create | `scripts/smoke-release-bundle.mjs` | Run exact-payload and guarded hostile-copy protocol exercises through direct Node. | | Create | `test/fixtures/release/hostile-runtime-guard.cjs` | Instrument the declared global runtime surfaces before bundle import and report violations on inherited fd 3. | diff --git a/.archflow/tasks/mcp-integration/reviews/phase-5-impl-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-5-impl-counter-review.md new file mode 100644 index 00000000..956b7850 --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-5-impl-counter-review.md @@ -0,0 +1,47 @@ +# Phase 5 Implementation Counter-Review + +Focused verification (`release:check`, the release contract tests, and the release offline integration tests) passes, but the implementation still has the following substantive gaps. + +1. **blocker — The accepted `fast-uri` risk decision is backed only by unresolvable digest strings.** `release/legal-review.json` contains `advisory_snapshot_digest` and `reachability_evidence_digest`, but those digests occur nowhere except the source/payload copies of that receipt. The schema only checks that they look like SHA-256 values (`src/contracts/schemas/v1/release-legal-review.schema.json:127-163`), and `validateLegalCorrelation` never resolves or hashes canonical advisory-snapshot or reachability records (`scripts/release-support.mjs:516-539`). Consequently arbitrary 64-hex values can satisfy the release gate, and the tracked payload has no durable evidence for the separate prototype-risk acceptance required before implementation. **Suggested resolution:** add closed canonical advisory-snapshot, patched-artifact-availability, focused reachability, and explicit acceptance records as repository controls; reference them by path and digest from the decision; resolve and hash them in the sole semantic validator; and mutation-test missing, stale, and substituted evidence. + +2. **major — Manifest input records are not required to identify the physical metafile input they claim to describe.** Validation reads each `bundle_input` from its `origin`, but never requires a repository record's `key` to equal `origin.path` or a dependency record's `key` to equal `node_modules//` (`scripts/release-support.mjs:567-575`). Metafile correlation checks key membership and `bytesInOutput`, but not `metafile.inputs[key].bytes === bundle_input.size` (`scripts/release-support.mjs:620-629`). A canonical manifest can therefore bind metafile key A to the digest of physical file B and can forge scanned-input sizes while passing `release:check`. **Suggested resolution:** enforce exact key/origin algebra and metafile input-byte equality, then add aliasing and size mutations to both semantic and integration tests. + +3. **major — Dependency provenance and legal component closure are not derived as exact closed sets.** `verifyDependencyRecords` verifies only records the manifest elects to list (`scripts/release-support.mjs:431-450`), while legal correlation requires the six hard-coded embedded components but never derives the exact installed-component set from dependency-origin contributors, rejects extra ungrounded components, or requires every component to have applicable retained legal evidence (`scripts/release-support.mjs:485-514`). Embedded license files are bound only as repository bytes; they are not tied to an immutable upstream tarball/commit/package manifest for the embedded name and version. A regenerated receipt can omit installed `zod`/SDK components, add invented components, or substitute supposedly applicable embedded license text after rebinding its digest. **Suggested resolution:** derive the exact installed and mapped component sets from bundle/provenance evidence, require one closed component-to-license/provenance mapping with no omissions or extras, and bind embedded legal sources to immutable upstream package identity and exact bytes. + +4. **major — Adjacent source-map discovery fails open.** For a contributing dependency `.mjs`, `collectDependencyProvenance` silently continues when the adjacent map is missing, and it records no per-prebundle expected/present/expected-absent state (`scripts/release-support.mjs:309-348`). It also ignores every source path that does not match one specific pnpm-layout regex, so a newly shaped third-party mapped root is not necessarily rejected. The current contributing `chunk-Br0eD_fh.mjs` has no adjacent map and leaves no evidence explaining why absence is expected. **Suggested resolution:** bind an explicit adjacent-map expectation for every contributing prebundle, classify every map source as reviewed first-party or recognized third-party regardless of package-manager layout, fail unknown shapes and missing expected maps, and mutation-test deletion, unexpected addition, and alternate-root syntax. + +5. **major — The supposedly exact hostile launch profile is largely unchecked.** The release validator constructs raw Ajv with `strict: false`, so the project's `x-archflow-sorted-unique`/`x-archflow-unique-by` annotations are ignored there (`scripts/release-support.mjs:392-405`). Semantic validation pins only `allowed_imports`; it does not derive or compare `argv`, environment/removal sets, guard identity, canary identities, or fixture paths/digests (`scripts/release-support.mjs:640-643`). Schema-valid changes, duplicates, stale fixture digests, or a substituted guard path therefore pass `release:check`, while `reproductionProof` merely hashes whatever profile the manifest supplied. **Suggested resolution:** compile with the established custom-keyword validator and compare the entire launch profile against exact derived constants and current proof-input digests; add mutations for every launch field and ordering/uniqueness rule. + +6. **major — Computed dynamic built-in loading bypasses the five-builtin policy.** The builder rejects only literal `import("node:...")`/`require("node:...")` forms with one regex (`scripts/release-support.mjs:770-775`), and payload validation checks only static metafile imports (`scripts/release-support.mjs:620-631`). Computed `require(specifier)`, `require("node:" + name)`, `import(specifier)`, `process.getBuiltinModule(...)`, and equivalent `createRequire` aliases can produce no metafile import and evade the regex, allowing undeclared `node:net`, `node:child_process`, or other built-ins through both build and independent reproduction. **Suggested resolution:** use a parser or an explicit emitted-code loader policy that rejects all residual runtime loaders except the fixed banner, and add mutations/probe sources for computed `require`, computed `import`, `getBuiltinModule`, and loader aliases. + +7. **major — Exact legal source/output mapping and the generated notice are not semantically verified.** Legal correlation verifies each retained repository source against the digest in the receipt, while artifact validation independently verifies payload files against manifest digests; it never requires `dist/legal/upstream/**` bytes to equal the corresponding `release/legal/upstream/**` bytes (`scripts/release-support.mjs:500-514,602-648`). It likewise never regenerates and compares `legal/THIRD_PARTY_NOTICES.md`. A payload can contain altered license or notice bytes with correspondingly updated artifact records and still pass the read-only checker. **Suggested resolution:** byte-compare every source/output legal pair, recompute the sole notice projection from the canonical receipt, enforce its exact bytes/digest, and add payload-only license/notice substitution mutations. + +8. **major — The independent `npm ci` reproduction and tracked-writer paths are absent from aggregate and CI verification.** The integration test's “independent roots” are two builds from the same checkout and existing `node_modules` (`test/integration/release-offline.test.ts:56-67`). `check:release` never calls `reproduceReleasePayload` or the writer (`package.json:22`), and CI likewise stages once from the already-installed checkout and performs only a read-only comparison (`.github/workflows/ci.yml:35-39`). Regressions in materialization, fresh install, post-install provenance checks, promotion, or rollback can therefore ship while every required check stays green. **Suggested resolution:** expose a non-promoting reproduction command that exercises materialization plus fresh `npm ci`, run it in `check:release` and both CI matrix jobs, and test tracked replacement/failure recovery against a disposable repository copy. + +9. **major — Reproduction roots can overlap and mutate the validated candidate.** `reproduceReleasePayload` checks the comparison root only against the materialization root (`scripts/release-support.mjs:901-906`); `buildReleasePayload` then checks it only against the materialized repository. A `comparisonRoot` nested below `stage.stageRoot` succeeds, creates a new directory inside the already-validated candidate, and can still return a reproduction proof based on the stale candidate summary. **Suggested resolution:** canonicalize all repository, candidate, materialization, and comparison roots before work starts; reject equality or ancestor/descendant overlap across every pair; re-walk the candidate before proof issuance; and add the nested-comparison regression. + +10. **major — HEAD carry-forward checks do not preserve the complete legal audit history.** If both HEAD review files are absent, `verifyHeadLegalBaseline` returns without checking for any prior `release/legal/upstream/**` or `dist/legal/**` artifacts; when reviews exist, it checks only release-to-dist upstream counterparts and ignores orphan dist files (`scripts/release-support.mjs:928-946`). It retains prior decisions byte-for-byte but does not retain prior amendments or supersessions, so the append-only correction trail can be deleted or rewritten. **Suggested resolution:** enumerate both HEAD legal namespaces first and require either complete absence or bidirectionally identical closure; carry forward decisions, amendments, and supersessions byte-identically; reject self/cyclic/conflicting supersessions; and seed tests for every one-sided/orphan/history-mutation case. + +11. **major — The hostile-copy proof does not exercise the protocol fixtures it claims to bind, and its module canary is not on a real lookup path.** The manifest binds `initialize.json`, `calls.json`, and `adversarial-bytes.json`, but the release smoke reads and sends only initialization (`scripts/smoke-release-bundle.mjs:138-159`). The module canary is created under `/module-canary/node_modules`, which is not an ancestor search path of child cwd `/payload`; its negative control is intercepted unconditionally by the preload before Node attempts ordinary resolution (`scripts/smoke-release-bundle.mjs:112-119,133-164`; `test/fixtures/release/hostile-runtime-guard.cjs:71-76`). Thus the tracked bundle never proves call/adversarial framing or meaningful ambient module isolation. **Suggested resolution:** drive the complete byte-exact fixture sequence through both copied-payload modes, place a canary where it demonstrably resolves under the hostile ambient setup, then prove the declared scrubbed launch makes it unavailable while the guard observes rather than preempts resolution. + +12. **major — Replacement of an existing `dist/` is not crash-preserving.** The writer first renames `dist` to a random backup and then renames the promotion into place (`scripts/release-support.mjs:1005-1009`). Its catch block restores ordinary JavaScript failures, but termination or power loss between the renames leaves the fixed `dist/` absent and the prior payload stranded under an undiscoverable random name; no startup recovery or fault-injection test exists. **Suggested resolution:** use a supported atomic exchange/indirection, or add a durable transaction marker and deterministic recovery before any subsequent release operation; fault-inject between each filesystem step and prove the old payload remains available or recovery is automatic. + +13. **minor — The build can consult unbound ambient TypeScript configuration.** `tsconfig.json` is absent from `REQUIRED_CONTROLS` and the materialization allowlist, while esbuild is invoked without `tsconfigRaw` or another explicit mechanism disabling tsconfig discovery (`scripts/release-support.mjs:80-102,705-717,746-765`). Ordinary staging may therefore consult repository configuration that the fresh reproduction root does not contain, contradicting the claimed closed reproduction-input set even if today's settings happen not to change emitted bytes. **Suggested resolution:** either digest and materialize `tsconfig.json` as a release control or pass a complete explicit `tsconfigRaw` profile that prevents ambient discovery, with a mutation proving repository tsconfig drift cannot silently affect the release. + +## Triage + +1. **Accepted and fixed.** Added four closed canonical controls under `release/evidence/` for the live advisory snapshot, patched-artifact availability, focused inert reachability, and the user's explicit local-only risk acceptance. The legal decision now binds each by path and digest, and semantic validation resolves, hashes, correlates, and mutation-tests them. +2. **Accepted and fixed.** Bundle records now require exact key/origin identity and exact agreement with `metafile.inputs[key].bytes`. Alias and forged-size mutations are rejected. +3. **Accepted and fixed.** Semantic validation derives the exact installed and mapped component closure, rejects missing/extra components, and requires one component-to-provenance/legal-source mapping. Embedded components bind official npm tarball URLs/integrities and exact retained license bytes. +4. **Accepted and fixed.** Every contributing dependency prebundle now has a derived `present` or `expected-absent` adjacent-map record. Map sources are classified into reviewed first-party roots or recognized third-party components; unknown layouts, stale maps, missing expected maps, and expectation drift fail closed. +5. **Accepted and fixed.** Release validation now enforces the custom sorted/unique keywords and compares the complete launch profile with values derived from current fixtures, guard, canaries, environment policy, argv, stdio, and import policy. Launch-profile mutations are rejected. +6. **Accepted and fixed.** A TypeScript 7 token-policy pass examines emitted executable tokens, rejects computed/dynamic `require`, `import()`, `process.getBuiltinModule`, and extra `createRequire` paths, and distinguishes inert strings/comments. Direct, alias, and nested-template probes cover the bypasses. +7. **Accepted and fixed.** Every retained legal source is byte-compared with its payload counterpart, and `THIRD_PARTY_NOTICES.md` is regenerated from the canonical receipt and compared byte-for-byte. Payload-only legal and notice substitutions are rejected. +8. **Accepted and fixed.** Added the non-promoting `release:reproduce` command, which materializes the closed source set, runs fresh `npm ci`, revalidates provenance, rebuilds, and compares the 14-file payload. It is part of `check:release` and both CI matrix jobs; disposable transaction-recovery probes cover replacement recovery. +9. **Accepted and fixed.** Repository, candidate, materialization, and comparison roots are canonicalized and checked pairwise for equality or ancestor/descendant overlap before work. Candidate closure is revalidated before proof issuance, and the nested-comparison regression is rejected. +10. **Accepted and fixed.** HEAD checking now enumerates both legal namespaces bidirectionally, requires complete absence or identical closure, preserves decisions/amendments/supersessions byte-identically, validates their reference graph, and rejects orphan or conflicting history. +11. **Accepted and fixed.** Hostile smoke now drives initialization, every call, and all adversarial-byte fixtures in exact and guarded modes with byte-equal transcripts. A real `NODE_PATH` control proves the canary resolves before the hostile environment removes that path; the guard observes native resolution failure without preempting it. +12. **Accepted and fixed.** Tracked replacement now uses deterministic promotion/backup paths plus a canonical durable transaction marker. Every release operation recovers interrupted pre-install or installed states before proceeding; fault probes cover both recovery branches. +13. **Accepted and fixed.** The esbuild profile supplies complete explicit `tsconfigRaw`, preventing ambient `tsconfig.json` discovery from affecting the release. + +Post-triage verification passed under exact Node `24.15.0` and `24.18.0`: 292 full tests, 55 contract tests, 86 focused MCP runtime tests, 17 release-integrity mutations, hostile exact/guarded fixture sequences with an empty network oracle, and fresh-`npm ci` 14-file reproduction. Final bundle digest is `16faf6365bc502ec0c0e00f150b43c300e65dfa9dcace1cce3d98d850b8cbbd0`; final dependency-inventory digest is `1f93c687b91691f3afb99d657246504a9b369311333ecd4e8c77abab1a23c046`. diff --git a/.gitattributes b/.gitattributes index dfe07704..a6d2e9f4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,15 @@ # Auto detect text files and perform LF normalization * text=auto + +# Canonical generated release text is byte-reproducible with LF endings. +dist/*.mjs text eol=lf +dist/archflow-mcp.mjs -whitespace +dist/*.json text eol=lf +dist/legal/*.json text eol=lf +dist/legal/*.md text eol=lf + +# Retained upstream legal evidence preserves the exact reviewed source bytes. +release/legal/upstream/** -text +release/legal/upstream/** -whitespace +dist/legal/upstream/** -text +dist/legal/upstream/** -whitespace diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e6577ca..09c40c15 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,11 +16,10 @@ jobs: matrix: node-version: ["24.15.0", "24.18.0"] steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: node-version: ${{ matrix.node-version }} - cache: npm - run: npm ci - run: npm run probe:phase4-mcp-compatibility - run: npm run typecheck @@ -33,4 +32,10 @@ jobs: - run: npm run test:notices-policy - run: npm run check:phase4-mcp-boundary - run: npm run test:phase4-mcp-boundary-policy - - run: test ! -e dist && test ! -e .tmp + - run: npm run release:check -- --payload dist + - run: npm run release:smoke -- --payload dist + - run: npm run release:mutations + - run: npm run release:reproduce + - run: npm run release:stage -- --output "${RUNNER_TEMP}/archflow-release-stage" + - run: npm run release:check -- --payload dist --compare "${RUNNER_TEMP}/archflow-release-stage" + - run: test ! -e .tmp diff --git a/dist/archflow-mcp.mjs b/dist/archflow-mcp.mjs new file mode 100644 index 00000000..cf9bd270 --- /dev/null +++ b/dist/archflow-mcp.mjs @@ -0,0 +1,34194 @@ +import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url); +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// src/main.ts +import process2 from "node:process"; + +// src/mcp/process-runner.ts +function deferred() { + let resolvePromise; + const promise2 = new Promise((resolve) => { + resolvePromise = resolve; + }); + return { promise: promise2, resolve: resolvePromise }; +} +function reasonForRuntime(termination) { + return termination.reason === "input-eof" ? { kind: "eof" } : { kind: "runtime-fatal" }; +} +async function runMcpProcess(bindings, start) { + const selected = deferred(); + let firstReason; + let diagnosticWritten = false; + let exitCodeSet = false; + function select(reason2) { + if (firstReason === void 0) { + firstReason = reason2; + selected.resolve(reason2); + } + } + function writeDiagnostic(code) { + if (diagnosticWritten) { + return; + } + diagnosticWritten = true; + try { + bindings.diagnostic.write(`${code} +`); + } catch { + } + } + function setExitCode(code) { + if (exitCodeSet) { + return; + } + exitCodeSet = true; + bindings.setExitCode(code); + } + const onSigint = () => select({ kind: "signal", code: 130 }); + const onSigterm = () => select({ kind: "signal", code: 143 }); + bindings.signals.on("SIGINT", onSigint); + bindings.signals.on("SIGTERM", onSigterm); + let runtime; + let termination; + let closePromise; + function closeOnce(handle) { + closePromise ??= Promise.resolve().then(() => handle.close()).then( + () => false, + () => true + ); + return closePromise; + } + try { + let startup; + try { + startup = start({ + input: bindings.input, + output: bindings.output, + workingDirectory: bindings.workingDirectory + }).then( + (startedRuntime) => ({ + kind: "started", + runtime: startedRuntime + }), + () => ({ kind: "failed" }) + ); + } catch { + startup = Promise.resolve({ kind: "failed" }); + } + const startupRace = await Promise.race([ + startup, + selected.promise.then(() => void 0) + ]); + if (startupRace === void 0) { + void startup.then((result) => { + if (result.kind === "started") { + void result.runtime.closed.catch(() => void 0); + void closeOnce(result.runtime).then((closeFailed2) => { + if (closeFailed2) { + writeDiagnostic("ARCHFLOW_MCP_CLOSE_FAILED"); + } + }); + } + }); + } else if (startupRace.kind === "failed") { + select({ kind: "startup" }); + } else { + runtime = startupRace.runtime; + } + if (runtime !== void 0) { + void runtime.closed.then( + (result) => { + termination = result; + select(reasonForRuntime(result)); + }, + () => select({ kind: "runtime-fatal" }) + ); + } + const reason2 = await selected.promise; + let closeFailed = termination?.close_failed ?? false; + if (runtime !== void 0) { + const closeRejected = await closeOnce(runtime); + closeFailed ||= closeRejected; + if (termination === void 0) { + try { + termination = await runtime.closed; + closeFailed ||= termination.close_failed; + } catch { + closeFailed = true; + } + } + } + let exitCode; + switch (reason2.kind) { + case "startup": + writeDiagnostic("ARCHFLOW_MCP_START_FAILED"); + exitCode = 1; + break; + case "runtime-fatal": + writeDiagnostic("ARCHFLOW_MCP_TRANSPORT_ERROR"); + exitCode = 1; + break; + case "eof": + exitCode = closeFailed ? 1 : 0; + if (closeFailed) { + writeDiagnostic("ARCHFLOW_MCP_CLOSE_FAILED"); + } + break; + case "signal": + exitCode = reason2.code; + if (closeFailed) { + writeDiagnostic("ARCHFLOW_MCP_CLOSE_FAILED"); + } + break; + } + setExitCode(exitCode); + } finally { + bindings.signals.off("SIGINT", onSigint); + bindings.signals.off("SIGTERM", onSigterm); + } +} + +// src/mcp/sdk-adapter.ts +import { Buffer as Buffer3 } from "node:buffer"; +import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util"; + +// node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs +var __create = Object.create; +var __defProp2 = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __exportAll = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp2(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp2(target, Symbol.toStringTag, { value: "Module" }); + } + return target; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp2(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +// node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs +var DRAFT_2020_12_URIS = /* @__PURE__ */ new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); +var DRAFT_2019_09_URIS = /* @__PURE__ */ new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); +var DRAFT_07_URIS = /* @__PURE__ */ new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); +var DRAFT_06_URIS = /* @__PURE__ */ new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); +function declares2019Dialect($schema) { + return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); +} +function declaredDialect(schema, remedy) { + if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; + const declared = schema.$schema.replace(/#$/, ""); + if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; + if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; + if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; + throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); +} + +// node_modules/zod/v4/classic/external.js +var external_exports = {}; +__export(external_exports, { + $brand: () => $brand, + $input: () => $input, + $output: () => $output, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPreprocess: () => ZodPreprocess, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRealError: () => ZodRealError, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + clone: () => clone, + codec: () => codec, + coerce: () => coerce_exports, + config: () => config, + core: () => core_exports2, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + decode: () => decode2, + decodeAsync: () => decodeAsync2, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + encode: () => encode2, + encodeAsync: () => encodeAsync2, + endsWith: () => _endsWith, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + flattenError: () => flattenError, + float32: () => float32, + float64: () => float64, + formatError: () => formatError, + fromJSONSchema: () => fromJSONSchema, + function: () => _function, + getErrorMap: () => getErrorMap, + globalRegistry: () => globalRegistry, + gt: () => _gt, + gte: () => _gte, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + includes: () => _includes, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + invertCodec: () => invertCodec, + ipv4: () => ipv42, + ipv6: () => ipv62, + iso: () => iso_exports, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + length: () => _length, + literal: () => literal, + locales: () => locales_exports, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + mac: () => mac2, + map: () => map, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + meta: () => meta2, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + negative: () => _negative, + never: () => never, + nonnegative: () => _nonnegative, + nonoptional: () => nonoptional, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + overwrite: () => _overwrite, + parse: () => parse2, + parseAsync: () => parseAsync2, + partialRecord: () => partialRecord, + pipe: () => pipe, + positive: () => _positive, + prefault: () => prefault, + preprocess: () => preprocess, + prettifyError: () => prettifyError, + promise: () => promise, + property: () => _property, + readonly: () => readonly, + record: () => record, + refine: () => refine, + regex: () => _regex, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode2, + safeDecodeAsync: () => safeDecodeAsync2, + safeEncode: () => safeEncode2, + safeEncodeAsync: () => safeEncodeAsync2, + safeParse: () => safeParse2, + safeParseAsync: () => safeParseAsync2, + set: () => set, + setErrorMap: () => setErrorMap, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + toJSONSchema: () => toJSONSchema, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + transform: () => transform, + treeifyError: () => treeifyError, + trim: () => _trim, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + uppercase: () => _uppercase, + url: () => url, + util: () => util_exports, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor +}); + +// node_modules/zod/v4/core/index.js +var core_exports2 = {}; +__export(core_exports2, { + $ZodAny: () => $ZodAny, + $ZodArray: () => $ZodArray, + $ZodAsyncError: () => $ZodAsyncError, + $ZodBase64: () => $ZodBase64, + $ZodBase64URL: () => $ZodBase64URL, + $ZodBigInt: () => $ZodBigInt, + $ZodBigIntFormat: () => $ZodBigIntFormat, + $ZodBoolean: () => $ZodBoolean, + $ZodCIDRv4: () => $ZodCIDRv4, + $ZodCIDRv6: () => $ZodCIDRv6, + $ZodCUID: () => $ZodCUID, + $ZodCUID2: () => $ZodCUID2, + $ZodCatch: () => $ZodCatch, + $ZodCheck: () => $ZodCheck, + $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, + $ZodCheckEndsWith: () => $ZodCheckEndsWith, + $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, + $ZodCheckIncludes: () => $ZodCheckIncludes, + $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, + $ZodCheckLessThan: () => $ZodCheckLessThan, + $ZodCheckLowerCase: () => $ZodCheckLowerCase, + $ZodCheckMaxLength: () => $ZodCheckMaxLength, + $ZodCheckMaxSize: () => $ZodCheckMaxSize, + $ZodCheckMimeType: () => $ZodCheckMimeType, + $ZodCheckMinLength: () => $ZodCheckMinLength, + $ZodCheckMinSize: () => $ZodCheckMinSize, + $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, + $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, + $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperty: () => $ZodCheckProperty, + $ZodCheckRegex: () => $ZodCheckRegex, + $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, + $ZodCheckStartsWith: () => $ZodCheckStartsWith, + $ZodCheckStringFormat: () => $ZodCheckStringFormat, + $ZodCheckUpperCase: () => $ZodCheckUpperCase, + $ZodCodec: () => $ZodCodec, + $ZodCustom: () => $ZodCustom, + $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodDate: () => $ZodDate, + $ZodDefault: () => $ZodDefault, + $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, + $ZodE164: () => $ZodE164, + $ZodEmail: () => $ZodEmail, + $ZodEmoji: () => $ZodEmoji, + $ZodEncodeError: () => $ZodEncodeError, + $ZodEnum: () => $ZodEnum, + $ZodError: () => $ZodError, + $ZodExactOptional: () => $ZodExactOptional, + $ZodFile: () => $ZodFile, + $ZodFunction: () => $ZodFunction, + $ZodGUID: () => $ZodGUID, + $ZodIPv4: () => $ZodIPv4, + $ZodIPv6: () => $ZodIPv6, + $ZodISODate: () => $ZodISODate, + $ZodISODateTime: () => $ZodISODateTime, + $ZodISODuration: () => $ZodISODuration, + $ZodISOTime: () => $ZodISOTime, + $ZodIntersection: () => $ZodIntersection, + $ZodJWT: () => $ZodJWT, + $ZodKSUID: () => $ZodKSUID, + $ZodLazy: () => $ZodLazy, + $ZodLiteral: () => $ZodLiteral, + $ZodMAC: () => $ZodMAC, + $ZodMap: () => $ZodMap, + $ZodNaN: () => $ZodNaN, + $ZodNanoID: () => $ZodNanoID, + $ZodNever: () => $ZodNever, + $ZodNonOptional: () => $ZodNonOptional, + $ZodNull: () => $ZodNull, + $ZodNullable: () => $ZodNullable, + $ZodNumber: () => $ZodNumber, + $ZodNumberFormat: () => $ZodNumberFormat, + $ZodObject: () => $ZodObject, + $ZodObjectJIT: () => $ZodObjectJIT, + $ZodOptional: () => $ZodOptional, + $ZodPipe: () => $ZodPipe, + $ZodPrefault: () => $ZodPrefault, + $ZodPreprocess: () => $ZodPreprocess, + $ZodPromise: () => $ZodPromise, + $ZodReadonly: () => $ZodReadonly, + $ZodRealError: () => $ZodRealError, + $ZodRecord: () => $ZodRecord, + $ZodRegistry: () => $ZodRegistry, + $ZodSet: () => $ZodSet, + $ZodString: () => $ZodString, + $ZodStringFormat: () => $ZodStringFormat, + $ZodSuccess: () => $ZodSuccess, + $ZodSymbol: () => $ZodSymbol, + $ZodTemplateLiteral: () => $ZodTemplateLiteral, + $ZodTransform: () => $ZodTransform, + $ZodTuple: () => $ZodTuple, + $ZodType: () => $ZodType, + $ZodULID: () => $ZodULID, + $ZodURL: () => $ZodURL, + $ZodUUID: () => $ZodUUID, + $ZodUndefined: () => $ZodUndefined, + $ZodUnion: () => $ZodUnion, + $ZodUnknown: () => $ZodUnknown, + $ZodVoid: () => $ZodVoid, + $ZodXID: () => $ZodXID, + $ZodXor: () => $ZodXor, + $brand: () => $brand, + $constructor: () => $constructor, + $input: () => $input, + $output: () => $output, + Doc: () => Doc, + JSONSchema: () => json_schema_exports, + JSONSchemaGenerator: () => JSONSchemaGenerator, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + _any: () => _any, + _array: () => _array, + _base64: () => _base64, + _base64url: () => _base64url, + _bigint: () => _bigint, + _boolean: () => _boolean, + _catch: () => _catch, + _check: () => _check, + _cidrv4: () => _cidrv4, + _cidrv6: () => _cidrv6, + _coercedBigint: () => _coercedBigint, + _coercedBoolean: () => _coercedBoolean, + _coercedDate: () => _coercedDate, + _coercedNumber: () => _coercedNumber, + _coercedString: () => _coercedString, + _cuid: () => _cuid, + _cuid2: () => _cuid2, + _custom: () => _custom, + _date: () => _date, + _decode: () => _decode, + _decodeAsync: () => _decodeAsync, + _default: () => _default, + _discriminatedUnion: () => _discriminatedUnion, + _e164: () => _e164, + _email: () => _email, + _emoji: () => _emoji2, + _encode: () => _encode, + _encodeAsync: () => _encodeAsync, + _endsWith: () => _endsWith, + _enum: () => _enum, + _file: () => _file, + _float32: () => _float32, + _float64: () => _float64, + _gt: () => _gt, + _gte: () => _gte, + _guid: () => _guid, + _includes: () => _includes, + _int: () => _int, + _int32: () => _int32, + _int64: () => _int64, + _intersection: () => _intersection, + _ipv4: () => _ipv4, + _ipv6: () => _ipv6, + _isoDate: () => _isoDate, + _isoDateTime: () => _isoDateTime, + _isoDuration: () => _isoDuration, + _isoTime: () => _isoTime, + _jwt: () => _jwt, + _ksuid: () => _ksuid, + _lazy: () => _lazy, + _length: () => _length, + _literal: () => _literal, + _lowercase: () => _lowercase, + _lt: () => _lt, + _lte: () => _lte, + _mac: () => _mac, + _map: () => _map, + _max: () => _lte, + _maxLength: () => _maxLength, + _maxSize: () => _maxSize, + _mime: () => _mime, + _min: () => _gte, + _minLength: () => _minLength, + _minSize: () => _minSize, + _multipleOf: () => _multipleOf, + _nan: () => _nan, + _nanoid: () => _nanoid, + _nativeEnum: () => _nativeEnum, + _negative: () => _negative, + _never: () => _never, + _nonnegative: () => _nonnegative, + _nonoptional: () => _nonoptional, + _nonpositive: () => _nonpositive, + _normalize: () => _normalize, + _null: () => _null2, + _nullable: () => _nullable, + _number: () => _number, + _optional: () => _optional, + _overwrite: () => _overwrite, + _parse: () => _parse, + _parseAsync: () => _parseAsync, + _pipe: () => _pipe, + _positive: () => _positive, + _promise: () => _promise, + _property: () => _property, + _readonly: () => _readonly, + _record: () => _record, + _refine: () => _refine, + _regex: () => _regex, + _safeDecode: () => _safeDecode, + _safeDecodeAsync: () => _safeDecodeAsync, + _safeEncode: () => _safeEncode, + _safeEncodeAsync: () => _safeEncodeAsync, + _safeParse: () => _safeParse, + _safeParseAsync: () => _safeParseAsync, + _set: () => _set, + _size: () => _size, + _slugify: () => _slugify, + _startsWith: () => _startsWith, + _string: () => _string, + _stringFormat: () => _stringFormat, + _stringbool: () => _stringbool, + _success: () => _success, + _superRefine: () => _superRefine, + _symbol: () => _symbol, + _templateLiteral: () => _templateLiteral, + _toLowerCase: () => _toLowerCase, + _toUpperCase: () => _toUpperCase, + _transform: () => _transform, + _trim: () => _trim, + _tuple: () => _tuple, + _uint32: () => _uint32, + _uint64: () => _uint64, + _ulid: () => _ulid, + _undefined: () => _undefined2, + _union: () => _union, + _unknown: () => _unknown, + _uppercase: () => _uppercase, + _url: () => _url, + _uuid: () => _uuid, + _uuidv4: () => _uuidv4, + _uuidv6: () => _uuidv6, + _uuidv7: () => _uuidv7, + _void: () => _void, + _xid: () => _xid, + _xor: () => _xor, + clone: () => clone, + config: () => config, + createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, + createToJSONSchemaMethod: () => createToJSONSchemaMethod, + decode: () => decode, + decodeAsync: () => decodeAsync, + describe: () => describe, + encode: () => encode, + encodeAsync: () => encodeAsync, + extractDefs: () => extractDefs, + finalize: () => finalize, + flattenError: () => flattenError, + formatError: () => formatError, + globalConfig: () => globalConfig, + globalRegistry: () => globalRegistry, + initializeContext: () => initializeContext, + isValidBase64: () => isValidBase64, + isValidBase64URL: () => isValidBase64URL, + isValidJWT: () => isValidJWT, + locales: () => locales_exports, + meta: () => meta, + parse: () => parse, + parseAsync: () => parseAsync, + prettifyError: () => prettifyError, + process: () => process, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode, + safeDecodeAsync: () => safeDecodeAsync, + safeEncode: () => safeEncode, + safeEncodeAsync: () => safeEncodeAsync, + safeParse: () => safeParse, + safeParseAsync: () => safeParseAsync, + toDotPath: () => toDotPath, + toJSONSchema: () => toJSONSchema, + treeifyError: () => treeifyError, + util: () => util_exports, + version: () => version +}); + +// node_modules/zod/v4/core/core.js +var _a; +var NEVER = /* @__PURE__ */ Object.freeze({ + status: "aborted" +}); +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, params) { + function init(inst, def2) { + if (!inst._zod) { + Object.defineProperty(inst, "_zod", { + value: { + def: def2, + constr: _, + traits: /* @__PURE__ */ new Set() + }, + enumerable: false + }); + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def2); + const proto = _.prototype; + const keys = Object.keys(proto); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def2) { + var _a3; + const inst = params?.Parent ? new Definition() : this; + init(inst, def2); + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = /* @__PURE__ */ Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +var globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + base64ToUint8Array: () => base64ToUint8Array, + base64urlToUint8Array: () => base64urlToUint8Array, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + cloneDef: () => cloneDef, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + explicitlyAborted: () => explicitlyAborted, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType, + getSizableOrigin: () => getSizableOrigin, + hexToUint8Array: () => hexToUint8Array, + isObject: () => isObject, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + mergeDefs: () => mergeDefs, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + objectClone: () => objectClone, + omit: () => omit, + optionalKeys: () => optionalKeys, + parsedType: () => parsedType, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + safeExtend: () => safeExtend, + shallowClone: () => shallowClone, + slugify: () => slugify, + stringifyPrimitive: () => stringifyPrimitive, + uint8ArrayToBase64: () => uint8ArrayToBase64, + uint8ArrayToBase64url: () => uint8ArrayToBase64url, + uint8ArrayToHex: () => uint8ArrayToHex, + unwrapMessage: () => unwrapMessage +}); +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { +} +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { +} +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); + return values; +} +function joinValues(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set2 = false; + return { + get value() { + if (!set2) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + } + }; +} +function nullish(input) { + return input === null || input === void 0; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +var EVALUATING = /* @__PURE__ */ Symbol("evaluating"); +function defineLazy(object3, key, getter) { + let value = void 0; + Object.defineProperty(object3, key, { + get() { + if (value === EVALUATING) { + return void 0; + } + if (value === void 0) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object3, key, { + value: v + // configurable: true, + }); + }, + configurable: true + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def2 of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def2); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +} +var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { +}; +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +var allowsEval = /* @__PURE__ */ cached(() => { + if (globalConfig.jitless) { + return false; + } + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (isObject(o) === false) + return false; + const ctor = o.constructor; + if (ctor === void 0) + return true; + if (typeof ctor !== "function") + return true; + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +var getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); +var primitiveTypes = /* @__PURE__ */ new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined" +]); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function clone(inst, def2, params) { + const cl = new inst._zod.constr(def2 ?? inst._zod.def); + if (!def2 || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + } + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); +} +var NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] +}; +var BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def2 = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + }); + return clone(schema, def2); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def2 = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + }); + return clone(schema, def2); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + const existingShape = schema._zod.def.shape; + for (const key in shape) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def2 = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone(schema, def2); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def2 = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone(schema, def2); +} +function merge(a, b) { + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const def2 = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [] + }); + return clone(a, def2); +} +function partial(Class2, schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".partial() cannot be used on object schemas containing refinements"); + } + const def2 = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + assignProp(this, "shape", shape); + return shape; + }, + checks: [] + }); + return clone(schema, def2); +} +function required(Class2, schema, mask) { + const def2 = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } + assignProp(this, "shape", shape); + return shape; + } + }); + return clone(schema, def2); +} +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a3; + (_a3 = iss).path ?? (_a3.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue(iss, ctx, config2) { + const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + const { inst: _inst, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message; + if (ctx?.reportInput) { + rest.input = _input; + } + return rest; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj).filter(([k, _]) => { + return Number.isNaN(Number.parseInt(k, 10)); + }).map((el) => el[1]); +} +function base64ToUint8Array(base643) { + const binaryString = atob(base643); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url3) { + const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - base643.length % 4) % 4); + return base64ToUint8Array(base643 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex3) { + const cleanHex = hex3.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +var Class = class { + constructor(..._args) { + } +}; + +// node_modules/zod/v4/core/errors.js +var initializer = (inst, def2) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def2, + enumerable: false + }); + inst.message = JSON.stringify(def2, jsonStringifyReplacer, 2); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); +}; +var $ZodError = $constructor("$ZodError", initializer); +var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); +function flattenError(error51, mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error51.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error51, mapper = (issue2) => issue2.message) { + const fieldErrors = { _errors: [] }; + const processError = (error52, path = []) => { + for (const issue2 of error52.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }, [...path, ...issue2.path]); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }, [...path, ...issue2.path]); + } else { + const fullpath = [...path, ...issue2.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i++; + } + } + } + } + }; + processError(error51); + return fieldErrors; +} +function treeifyError(error51, mapper = (issue2) => issue2.message) { + const result = { errors: [] }; + const processError = (error52, path = []) => { + var _a3, _b; + for (const issue2 of error52.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues }, [...path, ...issue2.path])); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }, [...path, ...issue2.path]); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }, [...path, ...issue2.path]); + } else { + const fullpath = [...path, ...issue2.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue2)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + curr = curr.properties[el]; + } else { + curr.items ?? (curr.items = []); + (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue2)); + } + i++; + } + } + } + }; + processError(error51); + return result; +} +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error51) { + const lines = []; + const issues = [...error51.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + for (const issue2 of issues) { + lines.push(`\u2716 ${issue2.message}`); + if (issue2.path?.length) + lines.push(` \u2192 at ${toDotPath(issue2.path)}`); + } + return lines.join("\n"); +} + +// node_modules/zod/v4/core/parse.js +var _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; +}; +var parse = /* @__PURE__ */ _parse($ZodRealError); +var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; +}; +var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); +var _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; +}; +var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; +}; +var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); +var _encode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _parse(_Err)(schema, value, ctx); +}; +var encode = /* @__PURE__ */ _encode($ZodRealError); +var _decode = (_Err) => (schema, value, _ctx) => { + return _parse(_Err)(schema, value, _ctx); +}; +var decode = /* @__PURE__ */ _decode($ZodRealError); +var _encodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _parseAsync(_Err)(schema, value, ctx); +}; +var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); +var _decodeAsync = (_Err) => async (schema, value, _ctx) => { + return _parseAsync(_Err)(schema, value, _ctx); +}; +var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); +var _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); +var _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); +var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); +var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); + +// node_modules/zod/v4/core/regexes.js +var regexes_exports = {}; +__export(regexes_exports, { + base64: () => base64, + base64url: () => base64url, + bigint: () => bigint, + boolean: () => boolean, + browserEmail: () => browserEmail, + cidrv4: () => cidrv4, + cidrv6: () => cidrv6, + cuid: () => cuid, + cuid2: () => cuid2, + date: () => date, + datetime: () => datetime, + domain: () => domain, + duration: () => duration, + e164: () => e164, + email: () => email, + emoji: () => emoji, + extendedDuration: () => extendedDuration, + guid: () => guid, + hex: () => hex, + hostname: () => hostname, + html5Email: () => html5Email, + httpProtocol: () => httpProtocol, + idnEmail: () => idnEmail, + integer: () => integer, + ipv4: () => ipv4, + ipv6: () => ipv6, + ksuid: () => ksuid, + lowercase: () => lowercase, + mac: () => mac, + md5_base64: () => md5_base64, + md5_base64url: () => md5_base64url, + md5_hex: () => md5_hex, + nanoid: () => nanoid, + null: () => _null, + number: () => number, + rfc5322Email: () => rfc5322Email, + sha1_base64: () => sha1_base64, + sha1_base64url: () => sha1_base64url, + sha1_hex: () => sha1_hex, + sha256_base64: () => sha256_base64, + sha256_base64url: () => sha256_base64url, + sha256_hex: () => sha256_hex, + sha384_base64: () => sha384_base64, + sha384_base64url: () => sha384_base64url, + sha384_hex: () => sha384_hex, + sha512_base64: () => sha512_base64, + sha512_base64url: () => sha512_base64url, + sha512_hex: () => sha512_hex, + string: () => string, + time: () => time, + ulid: () => ulid, + undefined: () => _undefined, + unicodeEmail: () => unicodeEmail, + uppercase: () => uppercase, + uuid: () => uuid, + uuid4: () => uuid4, + uuid6: () => uuid6, + uuid7: () => uuid7, + xid: () => xid +}); +var cuid = /^[cC][0-9a-z]{6,}$/; +var cuid2 = /^[0-9a-z]+$/; +var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var xid = /^[0-9a-vA-V]{20}$/; +var ksuid = /^[A-Za-z0-9]{27}$/; +var nanoid = /^[a-zA-Z0-9_-]{21}$/; +var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +var uuid = (version3) => { + if (!version3) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +var uuid4 = /* @__PURE__ */ uuid(4); +var uuid6 = /* @__PURE__ */ uuid(6); +var uuid7 = /* @__PURE__ */ uuid(7); +var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +var idnEmail = unicodeEmail; +var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; +var mac = (delimiter) => { + const escapedDelim = escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +var base64url = /^[A-Za-z0-9_-]*$/; +var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var httpProtocol = /^https?$/; +var e164 = /^\+[1-9]\d{6,14}$/; +var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; +var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +function datetime(args) { + const time3 = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + const timeRegex = `${time3}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +var string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +var bigint = /^-?\d+n?$/; +var integer = /^-?\d+$/; +var number = /^-?\d+(?:\.\d+)?$/; +var boolean = /^(?:true|false)$/i; +var _null = /^null$/i; +var _undefined = /^undefined$/i; +var lowercase = /^[^A-Z]*$/; +var uppercase = /^[^a-z]*$/; +var hex = /^[0-9a-fA-F]*$/; +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +var md5_hex = /^[0-9a-fA-F]{32}$/; +var md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); +var md5_base64url = /* @__PURE__ */ fixedBase64url(22); +var sha1_hex = /^[0-9a-fA-F]{40}$/; +var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); +var sha1_base64url = /* @__PURE__ */ fixedBase64url(27); +var sha256_hex = /^[0-9a-fA-F]{64}$/; +var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); +var sha256_base64url = /* @__PURE__ */ fixedBase64url(43); +var sha384_hex = /^[0-9a-fA-F]{96}$/; +var sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); +var sha384_base64url = /* @__PURE__ */ fixedBase64url(64); +var sha512_hex = /^[0-9a-fA-F]{128}$/; +var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); +var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); + +// node_modules/zod/v4/core/checks.js +var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def2) => { + var _a3; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def2; + (_a3 = inst._zod).onattach ?? (_a3.onattach = []); +}); +var numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" +}; +var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def2) => { + $ZodCheck.init(inst, def2); + const origin = numericOriginMap[typeof def2.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def2.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def2.value < curr) { + if (def2.inclusive) + bag.maximum = def2.value; + else + bag.exclusiveMaximum = def2.value; + } + }); + inst._zod.check = (payload) => { + if (def2.inclusive ? payload.value <= def2.value : payload.value < def2.value) { + return; + } + payload.issues.push({ + origin, + code: "too_big", + maximum: typeof def2.value === "object" ? def2.value.getTime() : def2.value, + input: payload.value, + inclusive: def2.inclusive, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def2) => { + $ZodCheck.init(inst, def2); + const origin = numericOriginMap[typeof def2.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def2.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def2.value > curr) { + if (def2.inclusive) + bag.minimum = def2.value; + else + bag.exclusiveMinimum = def2.value; + } + }); + inst._zod.check = (payload) => { + if (def2.inclusive ? payload.value >= def2.value : payload.value > def2.value) { + return; + } + payload.issues.push({ + origin, + code: "too_small", + minimum: typeof def2.value === "object" ? def2.value.getTime() : def2.value, + input: payload.value, + inclusive: def2.inclusive, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def2) => { + $ZodCheck.init(inst, def2); + inst._zod.onattach.push((inst2) => { + var _a3; + (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def2.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def2.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" ? payload.value % def2.value === BigInt(0) : floatSafeRemainder(payload.value, def2.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def2.value, + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def2) => { + $ZodCheck.init(inst, def2); + def2.format = def2.format || "float64"; + const isInt = def2.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def2.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def2.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + payload.issues.push({ + expected: origin, + format: def2.format, + code: "invalid_type", + continue: false, + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def2.abort + }); + } else { + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def2.abort + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def2.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def2.abort + }); + } + }; +}); +var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def2) => { + $ZodCheck.init(inst, def2); + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def2.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def2.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def2.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def2.abort + }); + } + }; +}); +var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def2) => { + var _a3; + $ZodCheck.init(inst, def2); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def2.maximum < curr) + inst2._zod.bag.maximum = def2.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def2.maximum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_big", + maximum: def2.maximum, + inclusive: true, + input, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def2) => { + var _a3; + $ZodCheck.init(inst, def2); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def2.minimum > curr) + inst2._zod.bag.minimum = def2.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def2.minimum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_small", + minimum: def2.minimum, + inclusive: true, + input, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def2) => { + var _a3; + $ZodCheck.init(inst, def2); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def2.size; + bag.maximum = def2.size; + bag.size = def2.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def2.size) + return; + const tooBig = size > def2.size; + payload.issues.push({ + origin: getSizableOrigin(input), + ...tooBig ? { code: "too_big", maximum: def2.size } : { code: "too_small", minimum: def2.size }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def2) => { + var _a3; + $ZodCheck.init(inst, def2); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def2.maximum < curr) + inst2._zod.bag.maximum = def2.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def2.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def2.maximum, + inclusive: true, + input, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def2) => { + var _a3; + $ZodCheck.init(inst, def2); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def2.minimum > curr) + inst2._zod.bag.minimum = def2.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def2.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def2.minimum, + inclusive: true, + input, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def2) => { + var _a3; + $ZodCheck.init(inst, def2); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def2.length; + bag.maximum = def2.length; + bag.length = def2.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def2.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def2.length; + payload.issues.push({ + origin, + ...tooBig ? { code: "too_big", maximum: def2.length } : { code: "too_small", minimum: def2.length }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def2) => { + var _a3, _b; + $ZodCheck.init(inst, def2); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def2.format; + if (def2.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def2.pattern); + } + }); + if (def2.pattern) + (_a3 = inst._zod).check ?? (_a3.check = (payload) => { + def2.pattern.lastIndex = 0; + if (def2.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def2.format, + input: payload.value, + ...def2.pattern ? { pattern: def2.pattern.toString() } : {}, + inst, + continue: !def2.abort + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { + }); +}); +var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def2) => { + $ZodCheckStringFormat.init(inst, def2); + inst._zod.check = (payload) => { + def2.pattern.lastIndex = 0; + if (def2.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def2.pattern.toString(), + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def2) => { + def2.pattern ?? (def2.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def2); +}); +var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def2) => { + def2.pattern ?? (def2.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def2); +}); +var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def2) => { + $ZodCheck.init(inst, def2); + const escapedRegex = escapeRegex(def2.includes); + const pattern = new RegExp(typeof def2.position === "number" ? `^.{${def2.position}}${escapedRegex}` : escapedRegex); + def2.pattern = pattern; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def2.includes, def2.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def2.includes, + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def2) => { + $ZodCheck.init(inst, def2); + const pattern = new RegExp(`^${escapeRegex(def2.prefix)}.*`); + def2.pattern ?? (def2.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def2.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def2.prefix, + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def2) => { + $ZodCheck.init(inst, def2); + const pattern = new RegExp(`.*${escapeRegex(def2.suffix)}$`); + def2.pattern ?? (def2.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def2.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def2.suffix, + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...prefixIssues(property, result.issues)); + } +} +var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def2) => { + $ZodCheck.init(inst, def2); + inst._zod.check = (payload) => { + const result = def2.schema._zod.run({ + value: payload.value[def2.property], + issues: [] + }, {}); + if (result instanceof Promise) { + return result.then((result2) => handleCheckPropertyResult(result2, payload, def2.property)); + } + handleCheckPropertyResult(result, payload, def2.property); + return; + }; +}); +var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def2) => { + $ZodCheck.init(inst, def2); + const mimeSet = new Set(def2.mime); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.mime = def2.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def2.mime, + input: payload.value.type, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def2) => { + $ZodCheck.init(inst, def2); + inst._zod.check = (payload) => { + payload.value = def2.tx(payload.value); + }; +}); + +// node_modules/zod/v4/core/doc.js +var Doc = class { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + return new F(...args, lines.join("\n")); + } +}; + +// node_modules/zod/v4/core/versions.js +var version = { + major: 4, + minor: 4, + patch: 3 +}; + +// node_modules/zod/v4/core/schemas.js +var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def2) => { + var _a3; + inst ?? (inst = {}); + inst._zod.def = def2; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks2, ctx) => { + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks2) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary2) => { + return handleCanaryResult(canary2, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + defineLazy(inst, "~standard", () => ({ + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); + } + }, + vendor: "zod", + version: 1 + })); +}); +var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def2.coerce) + try { + payload.value = String(payload.value); + } catch (_2) { + } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def2) => { + $ZodCheckStringFormat.init(inst, def2); + $ZodString.init(inst, def2); +}); +var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def2) => { + def2.pattern ?? (def2.pattern = guid); + $ZodStringFormat.init(inst, def2); +}); +var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def2) => { + if (def2.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }; + const v = versionMap[def2.version]; + if (v === void 0) + throw new Error(`Invalid UUID version: "${def2.version}"`); + def2.pattern ?? (def2.pattern = uuid(v)); + } else + def2.pattern ?? (def2.pattern = uuid()); + $ZodStringFormat.init(inst, def2); +}); +var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def2) => { + def2.pattern ?? (def2.pattern = email); + $ZodStringFormat.init(inst, def2); +}); +var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def2) => { + $ZodStringFormat.init(inst, def2); + inst._zod.check = (payload) => { + try { + const trimmed = payload.value.trim(); + if (!def2.normalize && def2.protocol?.source === httpProtocol.source) { + if (!/^https?:\/\//i.test(trimmed)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def2.abort + }); + return; + } + } + const url2 = new URL(trimmed); + if (def2.hostname) { + def2.hostname.lastIndex = 0; + if (!def2.hostname.test(url2.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def2.hostname.source, + input: payload.value, + inst, + continue: !def2.abort + }); + } + } + if (def2.protocol) { + def2.protocol.lastIndex = 0; + if (!def2.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def2.protocol.source, + input: payload.value, + inst, + continue: !def2.abort + }); + } + } + if (def2.normalize) { + payload.value = url2.href; + } else { + payload.value = trimmed; + } + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def2.abort + }); + } + }; +}); +var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def2) => { + def2.pattern ?? (def2.pattern = emoji()); + $ZodStringFormat.init(inst, def2); +}); +var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def2) => { + def2.pattern ?? (def2.pattern = nanoid); + $ZodStringFormat.init(inst, def2); +}); +var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def2) => { + def2.pattern ?? (def2.pattern = cuid); + $ZodStringFormat.init(inst, def2); +}); +var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def2) => { + def2.pattern ?? (def2.pattern = cuid2); + $ZodStringFormat.init(inst, def2); +}); +var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def2) => { + def2.pattern ?? (def2.pattern = ulid); + $ZodStringFormat.init(inst, def2); +}); +var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def2) => { + def2.pattern ?? (def2.pattern = xid); + $ZodStringFormat.init(inst, def2); +}); +var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def2) => { + def2.pattern ?? (def2.pattern = ksuid); + $ZodStringFormat.init(inst, def2); +}); +var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def2) => { + def2.pattern ?? (def2.pattern = datetime(def2)); + $ZodStringFormat.init(inst, def2); +}); +var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def2) => { + def2.pattern ?? (def2.pattern = date); + $ZodStringFormat.init(inst, def2); +}); +var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def2) => { + def2.pattern ?? (def2.pattern = time(def2)); + $ZodStringFormat.init(inst, def2); +}); +var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def2) => { + def2.pattern ?? (def2.pattern = duration); + $ZodStringFormat.init(inst, def2); +}); +var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def2) => { + def2.pattern ?? (def2.pattern = ipv4); + $ZodStringFormat.init(inst, def2); + inst._zod.bag.format = `ipv4`; +}); +var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def2) => { + def2.pattern ?? (def2.pattern = ipv6); + $ZodStringFormat.init(inst, def2); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def2.abort + }); + } + }; +}); +var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def2) => { + def2.pattern ?? (def2.pattern = mac(def2.delimiter)); + $ZodStringFormat.init(inst, def2); + inst._zod.bag.format = `mac`; +}); +var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def2) => { + def2.pattern ?? (def2.pattern = cidrv4); + $ZodStringFormat.init(inst, def2); +}); +var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def2) => { + def2.pattern ?? (def2.pattern = cidrv6); + $ZodStringFormat.init(inst, def2); + inst._zod.check = (payload) => { + const parts = payload.value.split("/"); + try { + if (parts.length !== 2) + throw new Error(); + const [address, prefix] = parts; + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def2.abort + }); + } + }; +}); +function isValidBase64(data) { + if (data === "") + return true; + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; + } catch { + return false; + } +} +var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def2) => { + def2.pattern ?? (def2.pattern = base64); + $ZodStringFormat.init(inst, def2); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +function isValidBase64URL(data) { + if (!base64url.test(data)) + return false; + const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); + return isValidBase64(padded); +} +var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def2) => { + def2.pattern ?? (def2.pattern = base64url); + $ZodStringFormat.init(inst, def2); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def2) => { + def2.pattern ?? (def2.pattern = e164); + $ZodStringFormat.init(inst, def2); +}); +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } catch { + return false; + } +} +var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def2) => { + $ZodStringFormat.init(inst, def2); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def2.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def2) => { + $ZodStringFormat.init(inst, def2); + inst._zod.check = (payload) => { + if (def2.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def2.format, + input: payload.value, + inst, + continue: !def2.abort + }); + }; +}); +var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def2.coerce) + try { + payload.value = Number(payload.value); + } catch (_) { + } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} + }); + return payload; + }; +}); +var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def2) => { + $ZodCheckNumberFormat.init(inst, def2); + $ZodNumber.init(inst, def2); +}); +var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.pattern = boolean; + inst._zod.parse = (payload, _ctx) => { + if (def2.coerce) + try { + payload.value = Boolean(payload.value); + } catch (_) { + } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.pattern = bigint; + inst._zod.parse = (payload, _ctx) => { + if (def2.coerce) + try { + payload.value = BigInt(payload.value); + } catch (_) { + } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def2) => { + $ZodCheckBigIntFormat.init(inst, def2); + $ZodBigInt.init(inst, def2); +}); +var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.pattern = _undefined; + inst._zod.values = /* @__PURE__ */ new Set([void 0]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.pattern = _null; + inst._zod.values = /* @__PURE__ */ new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload) => payload; +}); +var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload) => payload; +}); +var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, _ctx) => { + if (def2.coerce) { + try { + payload.value = new Date(payload.value); + } catch (_err) { + } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...isDate ? { received: "Invalid Date" } : {}, + inst + }); + return payload; + }; +}); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def2.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); + } else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) { + const isPresent = key in input; + if (result.issues.length) { + if (isOptionalIn && isOptionalOut && !isPresent) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && !isOptionalIn) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: void 0, + path: [key] + }); + } + return; + } + if (result.value === void 0) { + if (isPresent) { + final.value[key] = void 0; + } + } else { + final.value[key] = result.value; + } +} +function normalizeDef(def2) { + const keys = Object.keys(def2.shape); + for (const k of keys) { + if (!def2.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def2.shape); + return { + ...def2, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; +} +function handleCatchall(proms, input, payload, ctx, def2, inst) { + const unrecognized = []; + const keySet = def2.keySet; + const _catchall = def2.catchall._zod; + const t = _catchall.def.type; + const isOptionalIn = _catchall.optin === "optional"; + const isOptionalOut = _catchall.optout === "optional"; + for (const key in input) { + if (key === "__proto__") + continue; + if (keySet.has(key)) + continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + } else { + handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def2) => { + $ZodType.init(inst, def2); + const desc = Object.getOwnPropertyDescriptor(def2, "shape"); + if (!desc?.get) { + const sh = def2.shape; + Object.defineProperty(def2, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def2, "shape", { + value: newSh + }); + return newSh; + } + }); + } + const _normalized = cached(() => normalizeDef(def2)); + defineLazy(inst._zod, "propValues", () => { + const shape = def2.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const isObject4 = isObject; + const catchall = def2.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject4(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = {}; + const proms = []; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const isOptionalIn = el._zod.optin === "optional"; + const isOptionalOut = el._zod.optout === "optional"; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut))); + } else { + handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def2) => { + $ZodObject.init(inst, def2); + const superParse = inst._zod.parse; + const _normalized = cached(() => normalizeDef(def2)); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k = esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = /* @__PURE__ */ Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + doc.write(`const newResult = {};`); + for (const key of normalized.keys) { + const id4 = ids[key]; + const k = esc(key); + const schema = shape[key]; + const isOptionalIn = schema?._zod?.optin === "optional"; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id4} = ${parseStr(key)};`); + if (isOptionalIn && isOptionalOut) { + doc.write(` + if (${id4}.issues.length) { + if (${k} in input) { + payload.issues = payload.issues.concat(${id4}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + } + + if (${id4}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id4}.value; + } + + `); + } else if (!isOptionalIn) { + doc.write(` + const ${id4}_present = ${k} in input; + if (${id4}.issues.length) { + payload.issues = payload.issues.concat(${id4}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + if (!${id4}_present && !${id4}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id4}_present) { + if (${id4}.value === undefined) { + newResult[${k}] = undefined; + } else { + newResult[${k}] = ${id4}.value; + } + } + + `); + } else { + doc.write(` + if (${id4}.issues.length) { + payload.issues = payload.issues.concat(${id4}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + + if (${id4}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id4}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject4 = isObject; + const jit = !globalConfig.jitless; + const allowsEval2 = allowsEval; + const fastEnabled = jit && allowsEval2.value; + const catchall = def2.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject4(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) + fastpass = generateFastpass(def2.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + return final; +} +var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def2) => { + $ZodType.init(inst, def2); + defineLazy(inst._zod, "optin", () => def2.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "optout", () => def2.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def2.options.every((o) => o._zod.values)) { + return new Set(def2.options.flatMap((option) => Array.from(option._zod.values))); + } + return void 0; + }); + defineLazy(inst._zod, "pattern", () => { + if (def2.options.every((o) => o._zod.pattern)) { + const patterns = def2.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return void 0; + }); + const first = def2.options.length === 1 ? def2.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def2.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleUnionResults(results2, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const successes = results.filter((r) => r.issues.length === 0); + if (successes.length === 1) { + final.value = successes[0].value; + return final; + } + if (successes.length === 0) { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + } else { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false + }); + } + return final; +} +var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def2) => { + $ZodUnion.init(inst, def2); + def2.inclusive = false; + const first = def2.options.length === 1 ? def2.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def2.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleExclusiveUnionResults(results2, payload, inst, ctx); + }); + }; +}); +var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def2) => { + def2.inclusive = false; + $ZodUnion.init(inst, def2); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def2.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def2.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = /* @__PURE__ */ new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = cached(() => { + const opts = def2.options; + const map2 = /* @__PURE__ */ new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def2.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def2.options.indexOf(o)}"`); + for (const v of values) { + if (map2.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map2.set(v, o); + } + } + return map2; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload; + } + const opt = disc.value.get(input?.[def2.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + if (def2.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def2.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def2.discriminator], + inst + }); + return payload; + }; +}); +var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def2.left._zod.run({ value: input, issues: [] }, ctx); + const right = def2.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left2, right2]) => { + return handleIntersectionResults(payload, left2, right2); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function mergeValues(a, b) { + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath] + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + const unrecKeys = /* @__PURE__ */ new Map(); + let unrecIssue; + for (const iss of left.issues) { + if (iss.code === "unrecognized_keys") { + unrecIssue ?? (unrecIssue = iss); + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).l = true; + } + } else { + result.issues.push(iss); + } + } + for (const iss of right.issues) { + if (iss.code === "unrecognized_keys") { + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).r = true; + } + } else { + result.issues.push(iss); + } + } + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length && unrecIssue) { + result.issues.push({ ...unrecIssue, keys: bothKeys }); + } + if (aborted(result)) + return result; + const merged = mergeValues(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def2) => { + $ZodType.init(inst, def2); + const items = def2.items; + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" + }); + return payload; + } + payload.value = []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def2.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array" + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array" + }); + } + } + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } else { + itemResults[i] = r; + } + } + if (def2.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def2.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + if (items[i]._zod[key] !== "optional") + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === void 0) { + final.value.length = i; + } else { + break; + } + } + return final; +} +var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + const values = def2.keyType._zod.values; + if (values) { + payload.value = {}; + const recordKeys = /* @__PURE__ */ new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + const keyResult = def2.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + continue; + } + const outKey = keyResult.value; + const result = def2.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[outKey] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); + } + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def2.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def2.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def2.mode === "loose") { + payload.value[key] = input[key]; + } else { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + } + continue; + } + const result = def2.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Map(); + for (const [key, value] of input) { + const keyResult = def2.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def2.valueType._zod.run({ value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { + handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + })); + } else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, keyResult.issues)); + } else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key, + issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type" + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Set(); + for (const item of input) { + const result = def2.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleSetResult(result2, payload))); + } else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def2) => { + $ZodType.init(inst, def2); + const values = getEnumValues(def2.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst + }); + return payload; + }; +}); +var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def2) => { + $ZodType.init(inst, def2); + if (def2.values.length === 0) { + throw new Error("Cannot create literal schema with no valid values"); + } + const values = new Set(def2.values); + inst._zod.values = values; + inst._zod.pattern = new RegExp(`^(${def2.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def2.values, + input, + inst + }); + return payload; + }; +}); +var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.optin = "optional"; + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def2.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output2) => { + payload.value = output2; + payload.fallback = true; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + payload.fallback = true; + return payload; + }; +}); +function handleOptionalResult(result, input) { + if (input === void 0 && (result.issues.length || result.fallback)) { + return { issues: [], value: void 0 }; + } + return result; +} +var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def2.innerType._zod.values ? /* @__PURE__ */ new Set([...def2.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def2.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def2.innerType._zod.optin === "optional") { + const input = payload.value; + const result = def2.innerType._zod.run(payload, ctx); + if (result instanceof Promise) + return result.then((r) => handleOptionalResult(r, input)); + return handleOptionalResult(result, input); + } + if (payload.value === void 0) { + return payload; + } + return def2.innerType._zod.run(payload, ctx); + }; +}); +var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def2) => { + $ZodOptional.init(inst, def2); + defineLazy(inst._zod, "values", () => def2.innerType._zod.values); + defineLazy(inst._zod, "pattern", () => def2.innerType._zod.pattern); + inst._zod.parse = (payload, ctx) => { + return def2.innerType._zod.run(payload, ctx); + }; +}); +var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def2) => { + $ZodType.init(inst, def2); + defineLazy(inst._zod, "optin", () => def2.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def2.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def2.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def2.innerType._zod.values ? /* @__PURE__ */ new Set([...def2.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def2.innerType._zod.run(payload, ctx); + }; +}); +var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def2.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def2.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + payload.value = def2.defaultValue; + return payload; + } + const result = def2.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult(result2, def2)); + } + return handleDefaultResult(result, def2); + }; +}); +function handleDefaultResult(payload, def2) { + if (payload.value === void 0) { + payload.value = def2.defaultValue; + } + return payload; +} +var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def2.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def2.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + payload.value = def2.defaultValue; + } + return def2.innerType._zod.run(payload, ctx); + }; +}); +var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def2) => { + $ZodType.init(inst, def2); + defineLazy(inst._zod, "values", () => { + const v = def2.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const result = def2.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult(result2, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + } + return payload; +} +var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError("ZodSuccess"); + } + const result = def2.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}); +var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "optout", () => def2.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def2.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def2.innerType._zod.run(payload, ctx); + } + const result = def2.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.value; + if (result2.issues.length) { + payload.value = def2.catchValue({ + ...payload, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + payload.fallback = true; + } + return payload; + }); + } + payload.value = result.value; + if (result.issues.length) { + payload.value = def2.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + payload.fallback = true; + } + return payload; + }; +}); +var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type" + }); + return payload; + } + return payload; + }; +}); +var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def2) => { + $ZodType.init(inst, def2); + defineLazy(inst._zod, "values", () => def2.in._zod.values); + defineLazy(inst._zod, "optin", () => def2.in._zod.optin); + defineLazy(inst._zod, "optout", () => def2.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def2.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def2.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handlePipeResult(right2, def2.in, ctx)); + } + return handlePipeResult(right, def2.in, ctx); + } + const left = def2.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult(left2, def2.out, ctx)); + } + return handlePipeResult(left, def2.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx); +} +var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def2) => { + $ZodType.init(inst, def2); + defineLazy(inst._zod, "values", () => def2.in._zod.values); + defineLazy(inst._zod, "optin", () => def2.in._zod.optin); + defineLazy(inst._zod, "optout", () => def2.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def2.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def2.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handleCodecAResult(left2, def2, ctx)); + } + return handleCodecAResult(left, def2, ctx); + } else { + const right = def2.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handleCodecAResult(right2, def2, ctx)); + } + return handleCodecAResult(right, def2, ctx); + } + }; +}); +function handleCodecAResult(result, def2, ctx) { + if (result.issues.length) { + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def2.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def2.out, ctx)); + } + return handleCodecTxResult(result, transformed, def2.out, ctx); + } else { + const transformed = def2.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def2.in, ctx)); + } + return handleCodecTxResult(result, transformed, def2.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def2) => { + $ZodPipe.init(inst, def2); +}); +var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def2) => { + $ZodType.init(inst, def2); + defineLazy(inst._zod, "propValues", () => def2.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def2.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def2.innerType?._zod?.optin); + defineLazy(inst._zod, "optout", () => def2.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def2.innerType._zod.run(payload, ctx); + } + const result = def2.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def2) => { + $ZodType.init(inst, def2); + const regexParts = []; + for (const part of def2.parts) { + if (typeof part === "object" && part !== null) { + if (!part._zod.pattern) { + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } else if (part === null || primitiveTypes.has(typeof part)) { + regexParts.push(escapeRegex(`${part}`)); + } else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type" + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def2.format ?? "template_literal", + pattern: inst._zod.pattern.source + }); + return payload; + } + return payload; + }; +}); +var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def2) => { + $ZodType.init(inst, def2); + inst._def = def2; + inst._zod.def = def2; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + return function(...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }; + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return async function(...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }; + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst + }); + return payload; + } + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1] + }), + output: inst._def.output + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output + }); + }; + return inst; +}); +var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def2) => { + $ZodType.init(inst, def2); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def2.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}); +var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def2) => { + $ZodType.init(inst, def2); + defineLazy(inst._zod, "innerType", () => { + const d = def2; + if (!d._cachedInner) + d._cachedInner = def2.getter(); + return d._cachedInner; + }); + defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); + defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); + defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); + defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def2) => { + $ZodCheck.init(inst, def2); + $ZodType.init(inst, def2); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def2.fn(input); + if (r instanceof Promise) { + return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + // incorporates params.error into issue reporting + path: [...inst._zod.def.path ?? []], + // incorporates params.error into issue reporting + continue: !inst._zod.def.abort + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(issue(_iss)); + } +} + +// node_modules/zod/v4/locales/index.js +var locales_exports = {}; +__export(locales_exports, { + ar: () => ar_default, + az: () => az_default, + be: () => be_default, + bg: () => bg_default, + ca: () => ca_default, + cs: () => cs_default, + da: () => da_default, + de: () => de_default, + el: () => el_default, + en: () => en_default, + eo: () => eo_default, + es: () => es_default, + fa: () => fa_default, + fi: () => fi_default, + fr: () => fr_default, + frCA: () => fr_CA_default, + he: () => he_default, + hr: () => hr_default, + hu: () => hu_default, + hy: () => hy_default, + id: () => id_default, + is: () => is_default, + it: () => it_default, + ja: () => ja_default, + ka: () => ka_default, + kh: () => kh_default, + km: () => km_default, + ko: () => ko_default, + lt: () => lt_default, + mk: () => mk_default, + ms: () => ms_default, + nl: () => nl_default, + no: () => no_default, + ota: () => ota_default, + pl: () => pl_default, + ps: () => ps_default, + pt: () => pt_default, + ro: () => ro_default, + ru: () => ru_default, + sl: () => sl_default, + sv: () => sv_default, + ta: () => ta_default, + th: () => th_default, + tr: () => tr_default, + ua: () => ua_default, + uk: () => uk_default, + ur: () => ur_default, + uz: () => uz_default, + vi: () => vi_default, + yo: () => yo_default, + zhCN: () => zh_CN_default, + zhTW: () => zh_TW_default +}); + +// node_modules/zod/v4/locales/ar.js +var error = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0645\u062F\u062E\u0644", + email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", + url: "\u0631\u0627\u0628\u0637", + emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", + ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", + cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", + base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", + base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", + json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", + e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + jwt: "JWT", + template_literal: "\u0645\u062F\u062E\u0644" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; + return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; + if (_issue.format === "ends_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; + } + case "not_multiple_of": + return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + case "invalid_union": + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + case "invalid_element": + return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + default: + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + } + }; +}; +function ar_default() { + return { + localeError: error() + }; +} + +// node_modules/zod/v4/locales/az.js +var error2 = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "element", verb: "olmal\u0131d\u0131r" }, + set: { unit: "element", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; + } + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; + return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; + if (_issue.format === "ends_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; + if (_issue.format === "includes") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; + if (_issue.format === "regex") + return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; + return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; + case "unrecognized_keys": + return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; + case "invalid_union": + return "Yanl\u0131\u015F d\u0259y\u0259r"; + case "invalid_element": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; + default: + return `Yanl\u0131\u015F d\u0259y\u0259r`; + } + }; +}; +function az_default() { + return { + localeError: error2() + }; +} + +// node_modules/zod/v4/locales/be.js +function getBelarusianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +var error3 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0456\u043C\u0432\u0430\u043B", + few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", + many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u044B", + many: "\u0431\u0430\u0439\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0443\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0430\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0447\u0430\u0441", + duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", + base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", + json_string: "JSON \u0440\u0430\u0434\u043E\u043A", + e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + jwt: "JWT", + template_literal: "\u0443\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u043B\u0456\u043A", + array: "\u043C\u0430\u0441\u0456\u045E" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; + case "invalid_element": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; + default: + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; + } + }; +}; +function be_default() { + return { + localeError: error3() + }; +} + +// node_modules/zod/v4/locales/bg.js +var error4 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u043E\u0434", + email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + json_string: "JSON \u043D\u0438\u0437", + e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + jwt: "JWT", + template_literal: "\u0432\u0445\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; + let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; + if (_issue.format === "emoji") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "datetime") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "date") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + if (_issue.format === "time") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "duration") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; + case "invalid_element": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; + } + }; +}; +function bg_default() { + return { + localeError: error4() + }; +} + +// node_modules/zod/v4/locales/ca.js +var error5 = () => { + const Sizable = { + string: { unit: "car\xE0cters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entrada", + email: "adre\xE7a electr\xF2nica", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adre\xE7a IPv4", + ipv6: "adre\xE7a IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; + } + return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; + case "too_big": { + const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; + return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Clau inv\xE0lida a ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE0lida"; + // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element inv\xE0lid a ${issue2.origin}`; + default: + return `Entrada inv\xE0lida`; + } + }; +}; +function ca_default() { + return { + localeError: error5() + }; +} + +// node_modules/zod/v4/locales/cs.js +var error6 = () => { + const Sizable = { + string: { unit: "znak\u016F", verb: "m\xEDt" }, + file: { unit: "bajt\u016F", verb: "m\xEDt" }, + array: { unit: "prvk\u016F", verb: "m\xEDt" }, + set: { unit: "prvk\u016F", verb: "m\xEDt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rn\xED v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "datum a \u010Das ve form\xE1tu ISO", + date: "datum ve form\xE1tu ISO", + time: "\u010Das ve form\xE1tu ISO", + duration: "doba trv\xE1n\xED ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", + base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", + json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", + e164: "\u010D\xEDslo E.164", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "\u0159et\u011Bzec", + function: "funkce", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function cs_default() { + return { + localeError: error6() + }; +} + +// node_modules/zod/v4/locales/da.js +var error7 = () => { + const Sizable = { + string: { unit: "tegn", verb: "havde" }, + file: { unit: "bytes", verb: "havde" }, + array: { unit: "elementer", verb: "indeholdt" }, + set: { unit: "elementer", verb: "indeholdt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-mailadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkesl\xE6t", + date: "ISO-dato", + time: "ISO-klokkesl\xE6t", + duration: "ISO-varighed", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodet streng", + base64url: "base64url-kodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + string: "streng", + number: "tal", + boolean: "boolean", + array: "liste", + object: "objekt", + set: "s\xE6t", + file: "fil" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; + } + return `Ugyldigt input: forventede ${expected}, fik ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: skal starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: skal ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: skal indeholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8gle i ${issue2.origin}`; + case "invalid_union": + return "Ugyldigt input: matcher ingen af de tilladte typer"; + case "invalid_element": + return `Ugyldig v\xE6rdi i ${issue2.origin}`; + default: + return `Ugyldigt input`; + } + }; +}; +function da_default() { + return { + localeError: error7() + }; +} + +// node_modules/zod/v4/locales/de.js +var error8 = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "Eingabe", + email: "E-Mail-Adresse", + url: "URL", + emoji: "Emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe" + }; + const TypeDictionary = { + nan: "NaN", + number: "Zahl", + array: "Array" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; + } + return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; + return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; + case "invalid_union": + return "Ung\xFCltige Eingabe"; + case "invalid_element": + return `Ung\xFCltiger Wert in ${issue2.origin}`; + default: + return `Ung\xFCltige Eingabe`; + } + }; +}; +function de_default() { + return { + localeError: error8() + }; +} + +// node_modules/zod/v4/locales/el.js +var error9 = () => { + const Sizable = { + string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, + file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, + array: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, + set: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }, + map: { unit: "\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2", + email: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1", + date: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1", + time: "ISO \u03CE\u03C1\u03B1", + duration: "ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1", + ipv4: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4", + ipv6: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6", + mac: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC", + cidrv4: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4", + cidrv6: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6", + base64: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64", + base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url", + json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON", + e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164", + jwt: "JWT", + template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (typeof issue2.expected === "string" && /^[A-Z]/.test(issue2.expected)) { + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue2.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`; + } + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue2.values[0])}`; + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`; + return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`; + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue2.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue2.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue2.origin}`; + case "invalid_union": + return "\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"; + case "invalid_element": + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue2.origin}`; + default: + return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`; + } + }; +}; +function el_default() { + return { + localeError: error9() + }; +} + +// node_modules/zod/v4/locales/en.js +var error10 = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue2.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue2.origin}`; + case "invalid_union": + if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) { + const opts = issue2.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue2.origin}`; + default: + return `Invalid input`; + } + }; +}; +function en_default() { + return { + localeError: error10() + }; +} + +// node_modules/zod/v4/locales/eo.js +var error11 = () => { + const Sizable = { + string: { unit: "karaktrojn", verb: "havi" }, + file: { unit: "bajtojn", verb: "havi" }, + array: { unit: "elementojn", verb: "havi" }, + set: { unit: "elementojn", verb: "havi" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "enigo", + email: "retadreso", + url: "URL", + emoji: "emo\u011Dio", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datotempo", + date: "ISO-dato", + time: "ISO-tempo", + duration: "ISO-da\u016Dro", + ipv4: "IPv4-adreso", + ipv6: "IPv6-adreso", + cidrv4: "IPv4-rango", + cidrv6: "IPv6-rango", + base64: "64-ume kodita karaktraro", + base64url: "URL-64-ume kodita karaktraro", + json_string: "JSON-karaktraro", + e164: "E.164-nombro", + jwt: "JWT", + template_literal: "enigo" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombro", + array: "tabelo", + null: "senvalora" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; + } + return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; + return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; + return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nevalida \u015Dlosilo en ${issue2.origin}`; + case "invalid_union": + return "Nevalida enigo"; + case "invalid_element": + return `Nevalida valoro en ${issue2.origin}`; + default: + return `Nevalida enigo`; + } + }; +}; +function eo_default() { + return { + localeError: error11() + }; +} + +// node_modules/zod/v4/locales/es.js +var error12 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entrada", + email: "direcci\xF3n de correo electr\xF3nico", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duraci\xF3n ISO", + ipv4: "direcci\xF3n IPv4", + ipv6: "direcci\xF3n IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + string: "texto", + number: "n\xFAmero", + boolean: "booleano", + array: "arreglo", + object: "objeto", + set: "conjunto", + file: "archivo", + date: "fecha", + bigint: "n\xFAmero grande", + symbol: "s\xEDmbolo", + undefined: "indefinido", + null: "nulo", + function: "funci\xF3n", + map: "mapa", + record: "registro", + tuple: "tupla", + enum: "enumeraci\xF3n", + union: "uni\xF3n", + literal: "literal", + promise: "promesa", + void: "vac\xEDo", + never: "nunca", + unknown: "desconocido", + any: "cualquiera" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; + } + return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; + return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function es_default() { + return { + localeError: error12() + }; +} + +// node_modules/zod/v4/locales/fa.js +var error13 = () => { + const Sizable = { + string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u06CC", + email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", + url: "URL", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", + time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + ipv4: "IPv4 \u0622\u062F\u0631\u0633", + ipv6: "IPv6 \u0622\u062F\u0631\u0633", + cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", + cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", + base64: "base64-encoded \u0631\u0634\u062A\u0647", + base64url: "base64url-encoded \u0631\u0634\u062A\u0647", + json_string: "JSON \u0631\u0634\u062A\u0647", + e164: "E.164 \u0639\u062F\u062F", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u06CC" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0622\u0631\u0627\u06CC\u0647" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; + } + return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; + } + if (_issue.format === "ends_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; + } + if (_issue.format === "includes") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; + } + if (_issue.format === "regex") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; + } + return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + case "not_multiple_of": + return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; + case "invalid_union": + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + case "invalid_element": + return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; + default: + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + }; +}; +function fa_default() { + return { + localeError: error13() + }; +} + +// node_modules/zod/v4/locales/fi.js +var error14 = () => { + const Sizable = { + string: { unit: "merkki\xE4", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "s\xE4\xE4nn\xF6llinen lauseke", + email: "s\xE4hk\xF6postiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; + } + return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; + return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen sy\xF6te`; + } + }; +}; +function fi_default() { + return { + localeError: error14() + }; +} + +// node_modules/zod/v4/locales/fr.js +var error15 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + string: "cha\xEEne", + number: "nombre", + int: "entier", + boolean: "bool\xE9en", + bigint: "grand entier", + symbol: "symbole", + undefined: "ind\xE9fini", + null: "null", + never: "jamais", + void: "vide", + date: "date", + array: "tableau", + object: "objet", + tuple: "tuple", + record: "enregistrement", + map: "carte", + set: "ensemble", + file: "fichier", + nonoptional: "non-optionnel", + nan: "NaN", + function: "fonction" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + } + return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; + return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; + return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; +}; +function fr_default() { + return { + localeError: error15() + }; +} + +// node_modules/zod/v4/locales/fr-CA.js +var error16 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse courriel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; + } + return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u2264" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u2265" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; +}; +function fr_CA_default() { + return { + localeError: error16() + }; +} + +// node_modules/zod/v4/locales/he.js +var error17 = () => { + const TypeNames = { + string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, + number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, + boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, + bigint: { label: "BigInt", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, + array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, + object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, + null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, + undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, + symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, + function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, + map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, + set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, + file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, + promise: { label: "Promise", gender: "m" }, + NaN: { label: "NaN", gender: "m" }, + unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, + value: { label: "\u05E2\u05E8\u05DA", gender: "m" } + }; + const Sizable = { + string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, + file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } + // no unit + }; + const typeEntry = (t) => t ? TypeNames[t] : void 0; + const typeLabel = (t) => { + const e = typeEntry(t); + if (e) + return e.label; + return t ?? TypeNames.unknown.label; + }; + const withDefinite = (t) => `\u05D4${typeLabel(t)}`; + const verbFor = (t) => { + const e = typeEntry(t); + const gender = e?.gender ?? "m"; + return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; + }; + const getSizing = (origin) => { + if (!origin) + return null; + return Sizable[origin] ?? null; + }; + const FormatDictionary = { + regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, + url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, + uuid: { label: "UUID", gender: "m" }, + nanoid: { label: "nanoid", gender: "m" }, + guid: { label: "GUID", gender: "m" }, + cuid: { label: "cuid", gender: "m" }, + cuid2: { label: "cuid2", gender: "m" }, + ulid: { label: "ULID", gender: "m" }, + xid: { label: "XID", gender: "m" }, + ksuid: { label: "KSUID", gender: "m" }, + datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, + time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, + duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, + ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, + ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, + cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, + base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, + base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, + e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + jwt: { label: "JWT", gender: "m" }, + ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expectedKey = issue2.expected; + const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + case "invalid_value": { + if (issue2.values.length === 1) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; + } + const stringified = issue2.values.map((v) => stringifyPrimitive(v)); + if (issue2.values.length === 2) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; + } + const lastValue = stringified[stringified.length - 1]; + const restValues = stringified.slice(0, -1).join(", "); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; + } + case "too_big": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite(issue2.origin ?? "value"); + if (issue2.origin === "string") { + return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? "<=" : "<"; + const be = verbFor(issue2.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + } + return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite(issue2.origin ?? "value"); + if (issue2.origin === "string") { + return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + if (issue2.minimum === 1 && issue2.inclusive) { + const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; + } + const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? ">=" : ">"; + const be = verbFor(issue2.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; + const nounEntry = FormatDictionary[_issue.format]; + const noun = nounEntry?.label ?? _issue.format; + const gender = nounEntry?.gender ?? "m"; + const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; + return `${noun} \u05DC\u05D0 ${adjective}`; + } + case "not_multiple_of": + return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; + case "unrecognized_keys": + return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": { + return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; + } + case "invalid_union": + return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; + case "invalid_element": { + const place = withDefinite(issue2.origin ?? "array"); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; + } + default: + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; + } + }; +}; +function he_default() { + return { + localeError: error17() + }; +} + +// node_modules/zod/v4/locales/hr.js +var error18 = () => { + const Sizable = { + string: { unit: "znakova", verb: "imati" }, + file: { unit: "bajtova", verb: "imati" }, + array: { unit: "stavki", verb: "imati" }, + set: { unit: "stavki", verb: "imati" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "unos", + email: "email adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum i vrijeme", + date: "ISO datum", + time: "ISO vrijeme", + duration: "ISO trajanje", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "IPv4 raspon", + cidrv6: "IPv6 raspon", + base64: "base64 kodirani tekst", + base64url: "base64url kodirani tekst", + json_string: "JSON tekst", + e164: "E.164 broj", + jwt: "JWT", + template_literal: "unos" + }; + const TypeDictionary = { + nan: "NaN", + string: "tekst", + number: "broj", + boolean: "boolean", + array: "niz", + object: "objekt", + set: "skup", + file: "datoteka", + date: "datum", + bigint: "bigint", + symbol: "simbol", + undefined: "undefined", + null: "null", + function: "funkcija", + map: "mapa" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neispravan unos: o\u010Dekuje se instanceof ${issue2.expected}, a primljeno je ${received}`; + } + return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue2.values[0])}`; + return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemenata"}`; + return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`; + return `Neispravna ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue2.divisor}`; + case "unrecognized_keys": + return `Neprepoznat${issue2.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neispravan klju\u010D u ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + case "invalid_union": + return "Neispravan unos"; + case "invalid_element": + return `Neispravna vrijednost u ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + default: + return `Neispravan unos`; + } + }; +}; +function hr_default() { + return { + localeError: error18() + }; +} + +// node_modules/zod/v4/locales/hu.js +var error19 = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "bemenet", + email: "email c\xEDm", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO id\u0151b\xE9lyeg", + date: "ISO d\xE1tum", + time: "ISO id\u0151", + duration: "ISO id\u0151intervallum", + ipv4: "IPv4 c\xEDm", + ipv6: "IPv6 c\xEDm", + cidrv4: "IPv4 tartom\xE1ny", + cidrv6: "IPv6 tartom\xE1ny", + base64: "base64-k\xF3dolt string", + base64url: "base64url-k\xF3dolt string", + json_string: "JSON string", + e164: "E.164 sz\xE1m", + jwt: "JWT", + template_literal: "bemenet" + }; + const TypeDictionary = { + nan: "NaN", + number: "sz\xE1m", + array: "t\xF6mb" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; + } + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; + return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; + if (_issue.format === "ends_with") + return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; + if (_issue.format === "includes") + return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; + if (_issue.format === "regex") + return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; + return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; + case "invalid_union": + return "\xC9rv\xE9nytelen bemenet"; + case "invalid_element": + return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; + default: + return `\xC9rv\xE9nytelen bemenet`; + } + }; +}; +function hu_default() { + return { + localeError: error19() + }; +} + +// node_modules/zod/v4/locales/hy.js +function getArmenianPlural(count, one, many) { + return Math.abs(count) === 1 ? one : many; +} +function withDefiniteArticle(word) { + if (!word) + return ""; + const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; + const lastChar = word[word.length - 1]; + return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); +} +var error20 = () => { + const Sizable = { + string: { + unit: { + one: "\u0576\u0577\u0561\u0576", + many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + file: { + unit: { + one: "\u0562\u0561\u0575\u0569", + many: "\u0562\u0561\u0575\u0569\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + array: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + set: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0574\u0578\u0582\u057F\u0584", + email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", + url: "URL", + emoji: "\u0567\u0574\u0578\u057B\u056B", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", + date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", + time: "ISO \u056A\u0561\u0574", + duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", + ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", + ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + json_string: "JSON \u057F\u0578\u0572", + e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + jwt: "JWT", + template_literal: "\u0574\u0578\u0582\u057F\u0584" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0569\u056B\u057E", + array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; + return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; + if (_issue.format === "ends_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; + if (_issue.format === "includes") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; + return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; + case "unrecognized_keys": + return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + case "invalid_union": + return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; + case "invalid_element": + return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + default: + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; + } + }; +}; +function hy_default() { + return { + localeError: error20() + }; +} + +// node_modules/zod/v4/locales/id.js +var error21 = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "alamat email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue2.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue2.origin}`; + default: + return `Input tidak valid`; + } + }; +}; +function id_default() { + return { + localeError: error21() + }; +} + +// node_modules/zod/v4/locales/is.js +var error22 = () => { + const Sizable = { + string: { unit: "stafi", verb: "a\xF0 hafa" }, + file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, + array: { unit: "hluti", verb: "a\xF0 hafa" }, + set: { unit: "hluti", verb: "a\xF0 hafa" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "gildi", + email: "netfang", + url: "vefsl\xF3\xF0", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dagsetning og t\xEDmi", + date: "ISO dagsetning", + time: "ISO t\xEDmi", + duration: "ISO t\xEDmalengd", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded strengur", + base64url: "base64url-encoded strengur", + json_string: "JSON strengur", + e164: "E.164 t\xF6lugildi", + jwt: "JWT", + template_literal: "gildi" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmer", + array: "fylki" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; + } + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; + return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`; + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; + if (_issue.format === "regex") + return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; + return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; + case "unrecognized_keys": + return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Rangur lykill \xED ${issue2.origin}`; + case "invalid_union": + return "Rangt gildi"; + case "invalid_element": + return `Rangt gildi \xED ${issue2.origin}`; + default: + return `Rangt gildi`; + } + }; +}; +function is_default() { + return { + localeError: error22() + }; +} + +// node_modules/zod/v4/locales/it.js +var error23 = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "indirizzo email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "numero", + array: "vettore" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; + } + return `Input non valido: atteso ${expected}, ricevuto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; + return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Input non valido: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; + case "unrecognized_keys": + return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue2.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue2.origin}`; + default: + return `Input non valido`; + } + }; +}; +function it_default() { + return { + localeError: error23() + }; +} + +// node_modules/zod/v4/locales/ja.js +var error24 = () => { + const Sizable = { + string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, + file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, + array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u5165\u529B\u5024", + email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", + url: "URL", + emoji: "\u7D75\u6587\u5B57", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u6642", + date: "ISO\u65E5\u4ED8", + time: "ISO\u6642\u523B", + duration: "ISO\u671F\u9593", + ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", + ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + cidrv4: "IPv4\u7BC4\u56F2", + cidrv6: "IPv6\u7BC4\u56F2", + base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + json_string: "JSON\u6587\u5B57\u5217", + e164: "E.164\u756A\u53F7", + jwt: "JWT", + template_literal: "\u5165\u529B\u5024" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5024", + array: "\u914D\u5217" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; + return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "too_big": { + const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "ends_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "includes") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "regex") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "unrecognized_keys": + return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; + case "invalid_union": + return "\u7121\u52B9\u306A\u5165\u529B"; + case "invalid_element": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; + default: + return `\u7121\u52B9\u306A\u5165\u529B`; + } + }; +}; +function ja_default() { + return { + localeError: error24() + }; +} + +// node_modules/zod/v4/locales/ka.js +var error25 = () => { + const Sizable = { + string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", + email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + url: "URL", + emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", + date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", + time: "\u10D3\u10E0\u10DD", + duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", + ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", + base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8", + json_string: "JSON \u10D5\u10D4\u10DA\u10D8", + e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + jwt: "JWT", + template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", + string: "\u10D5\u10D4\u10DA\u10D8", + boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", + function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", + array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; + } + if (_issue.format === "ends_with") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; + if (_issue.format === "includes") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; + if (_issue.format === "regex") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; + case "unrecognized_keys": + return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; + case "invalid_union": + return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; + case "invalid_element": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; + default: + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; + } + }; +}; +function ka_default() { + return { + localeError: error25() + }; +} + +// node_modules/zod/v4/locales/km.js +var error26 = () => { + const Sizable = { + string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", + email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", + url: "URL", + emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", + date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", + time: "\u1798\u17C9\u17C4\u1784 ISO", + duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", + ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", + base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", + json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", + e164: "\u179B\u17C1\u1781 E.164", + jwt: "JWT", + template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u179B\u17C1\u1781", + array: "\u17A2\u17B6\u179A\u17C1 (Array)", + null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; + return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; + return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + case "invalid_union": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + case "invalid_element": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + default: + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + } + }; +}; +function km_default() { + return { + localeError: error26() + }; +} + +// node_modules/zod/v4/locales/kh.js +function kh_default() { + return km_default(); +} + +// node_modules/zod/v4/locales/ko.js +var error27 = () => { + const Sizable = { + string: { unit: "\uBB38\uC790", verb: "to have" }, + file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, + array: { unit: "\uAC1C", verb: "to have" }, + set: { unit: "\uAC1C", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\uC785\uB825", + email: "\uC774\uBA54\uC77C \uC8FC\uC18C", + url: "URL", + emoji: "\uC774\uBAA8\uC9C0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", + date: "ISO \uB0A0\uC9DC", + time: "ISO \uC2DC\uAC04", + duration: "ISO \uAE30\uAC04", + ipv4: "IPv4 \uC8FC\uC18C", + ipv6: "IPv6 \uC8FC\uC18C", + cidrv4: "IPv4 \uBC94\uC704", + cidrv6: "IPv6 \uBC94\uC704", + base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + json_string: "JSON \uBB38\uC790\uC5F4", + e164: "E.164 \uBC88\uD638", + jwt: "JWT", + template_literal: "\uC785\uB825" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "too_big": { + const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; + const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; + const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) { + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; + } + if (_issue.format === "ends_with") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "includes") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "regex") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "unrecognized_keys": + return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; + case "invalid_union": + return `\uC798\uBABB\uB41C \uC785\uB825`; + case "invalid_element": + return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; + default: + return `\uC798\uBABB\uB41C \uC785\uB825`; + } + }; +}; +function ko_default() { + return { + localeError: error27() + }; +} + +// node_modules/zod/v4/locales/lt.js +var capitalizeFirstCharacter = (text3) => { + return text3.charAt(0).toUpperCase() + text3.slice(1); +}; +function getUnitTypeFromNumber(number4) { + const abs = Math.abs(number4); + const last = abs % 10; + const last2 = abs % 100; + if (last2 >= 11 && last2 <= 19 || last === 0) + return "many"; + if (last === 1) + return "one"; + return "few"; +} +var error28 = () => { + const Sizable = { + string: { + unit: { + one: "simbolis", + few: "simboliai", + many: "simboli\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", + notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", + notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" + } + } + }, + file: { + unit: { + one: "baitas", + few: "baitai", + many: "bait\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne didesnis kaip", + notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", + notInclusive: "turi b\u016Bti didesnis kaip" + } + } + }, + array: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + }, + set: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + } + }; + function getSizing(origin, unitType, inclusive, targetShouldBe) { + const result = Sizable[origin] ?? null; + if (result === null) + return result; + return { + unit: result.unit[unitType], + verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] + }; + } + const FormatDictionary = { + regex: "\u012Fvestis", + email: "el. pa\u0161to adresas", + url: "URL", + emoji: "jaustukas", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO data ir laikas", + date: "ISO data", + time: "ISO laikas", + duration: "ISO trukm\u0117", + ipv4: "IPv4 adresas", + ipv6: "IPv6 adresas", + cidrv4: "IPv4 tinklo prefiksas (CIDR)", + cidrv6: "IPv6 tinklo prefiksas (CIDR)", + base64: "base64 u\u017Ekoduota eilut\u0117", + base64url: "base64url u\u017Ekoduota eilut\u0117", + json_string: "JSON eilut\u0117", + e164: "E.164 numeris", + jwt: "JWT", + template_literal: "\u012Fvestis" + }; + const TypeDictionary = { + nan: "NaN", + number: "skai\u010Dius", + bigint: "sveikasis skai\u010Dius", + string: "eilut\u0117", + boolean: "login\u0117 reik\u0161m\u0117", + undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", + function: "funkcija", + symbol: "simbolis", + array: "masyvas", + object: "objektas", + null: "nulin\u0117 reik\u0161m\u0117" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; + } + return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; + return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; + case "too_big": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; + const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`; + } + case "too_small": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; + const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; + if (_issue.format === "regex") + return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; + return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; + case "unrecognized_keys": + return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Rastas klaidingas raktas"; + case "invalid_union": + return "Klaidinga \u012Fvestis"; + case "invalid_element": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; + } + default: + return "Klaidinga \u012Fvestis"; + } + }; +}; +function lt_default() { + return { + localeError: error28() + }; +} + +// node_modules/zod/v4/locales/mk.js +var error29 = () => { + const Sizable = { + string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u043D\u0435\u0441", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", + url: "URL", + emoji: "\u0435\u043C\u043E\u045F\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0443\u043C", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", + cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", + base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + json_string: "JSON \u043D\u0438\u0437\u0430", + e164: "E.164 \u0431\u0440\u043E\u0458", + jwt: "JWT", + template_literal: "\u0432\u043D\u0435\u0441" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0431\u0440\u043E\u0458", + array: "\u043D\u0438\u0437\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; + case "invalid_union": + return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; + case "invalid_element": + return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; + default: + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; + } + }; +}; +function mk_default() { + return { + localeError: error29() + }; +} + +// node_modules/zod/v4/locales/ms.js +var error30 = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "alamat e-mel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombor" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak sah: dijangka ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue2.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue2.origin}`; + default: + return `Input tidak sah`; + } + }; +}; +function ms_default() { + return { + localeError: error30() + }; +} + +// node_modules/zod/v4/locales/nl.js +var error31 = () => { + const Sizable = { + string: { unit: "tekens", verb: "heeft" }, + file: { unit: "bytes", verb: "heeft" }, + array: { unit: "elementen", verb: "heeft" }, + set: { unit: "elementen", verb: "heeft" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "invoer", + email: "emailadres", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer" + }; + const TypeDictionary = { + nan: "NaN", + number: "getal" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; + } + return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; + return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; + if (sizing) + return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; + return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; + if (sizing) { + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue2.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue2.origin}`; + default: + return `Ongeldige invoer`; + } + }; +}; +function nl_default() { + return { + localeError: error31() + }; +} + +// node_modules/zod/v4/locales/no.js +var error32 = () => { + const Sizable = { + string: { unit: "tegn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "elementer", verb: "\xE5 inneholde" }, + set: { unit: "elementer", verb: "\xE5 inneholde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tall", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; + } + return `Ugyldig input: forventet ${expected}, fikk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function no_default() { + return { + localeError: error32() + }; +} + +// node_modules/zod/v4/locales/ota.js +var error33 = () => { + const Sizable = { + string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giren", + email: "epostag\xE2h", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO heng\xE2m\u0131", + date: "ISO tarihi", + time: "ISO zaman\u0131", + duration: "ISO m\xFCddeti", + ipv4: "IPv4 ni\u015F\xE2n\u0131", + ipv6: "IPv6 ni\u015F\xE2n\u0131", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-\u015Fifreli metin", + base64url: "base64url-\u015Fifreli metin", + json_string: "JSON metin", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "giren" + }; + const TypeDictionary = { + nan: "NaN", + number: "numara", + array: "saf", + null: "gayb" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; + return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; + } + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; + if (_issue.format === "ends_with") + return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; + if (_issue.format === "regex") + return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; + return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; + case "invalid_union": + return "Giren tan\u0131namad\u0131."; + case "invalid_element": + return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; + default: + return `K\u0131ymet tan\u0131namad\u0131.`; + } + }; +}; +function ota_default() { + return { + localeError: error33() + }; +} + +// node_modules/zod/v4/locales/ps.js +var error34 = () => { + const Sizable = { + string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, + array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u064A", + email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", + date: "\u0646\u06D0\u067C\u0647", + time: "\u0648\u062E\u062A", + duration: "\u0645\u0648\u062F\u0647", + ipv4: "\u062F IPv4 \u067E\u062A\u0647", + ipv6: "\u062F IPv6 \u067E\u062A\u0647", + cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", + cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", + base64: "base64-encoded \u0645\u062A\u0646", + base64url: "base64url-encoded \u0645\u062A\u0646", + json_string: "JSON \u0645\u062A\u0646", + e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u064A" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0627\u0631\u06D0" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; + } + return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; + } + if (_issue.format === "ends_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; + } + if (_issue.format === "includes") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; + } + if (_issue.format === "regex") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; + } + return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; + } + case "not_multiple_of": + return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; + case "unrecognized_keys": + return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + case "invalid_union": + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + case "invalid_element": + return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + default: + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + } + }; +}; +function ps_default() { + return { + localeError: error34() + }; +} + +// node_modules/zod/v4/locales/pl.js +var error35 = () => { + const Sizable = { + string: { unit: "znak\xF3w", verb: "mie\u0107" }, + file: { unit: "bajt\xF3w", verb: "mie\u0107" }, + array: { unit: "element\xF3w", verb: "mie\u0107" }, + set: { unit: "element\xF3w", verb: "mie\u0107" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "wyra\u017Cenie", + email: "adres email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", + base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", + json_string: "ci\u0105g znak\xF3w w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wej\u015Bcie" + }; + const TypeDictionary = { + nan: "NaN", + number: "liczba", + array: "tablica" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; + } + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; + return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; + return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nieprawid\u0142owy klucz w ${issue2.origin}`; + case "invalid_union": + return "Nieprawid\u0142owe dane wej\u015Bciowe"; + case "invalid_element": + return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; + default: + return `Nieprawid\u0142owe dane wej\u015Bciowe`; + } + }; +}; +function pl_default() { + return { + localeError: error35() + }; +} + +// node_modules/zod/v4/locales/pt.js +var error36 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "padr\xE3o", + email: "endere\xE7o de e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "dura\xE7\xE3o ISO", + ipv4: "endere\xE7o IPv4", + ipv6: "endere\xE7o IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmero", + null: "nulo" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; + } + return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chave inv\xE1lida em ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido em ${issue2.origin}`; + default: + return `Campo inv\xE1lido`; + } + }; +}; +function pt_default() { + return { + localeError: error36() + }; +} + +// node_modules/zod/v4/locales/ro.js +var error37 = () => { + const Sizable = { + string: { unit: "caractere", verb: "s\u0103 aib\u0103" }, + file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" }, + array: { unit: "elemente", verb: "s\u0103 aib\u0103" }, + set: { unit: "elemente", verb: "s\u0103 aib\u0103" }, + map: { unit: "intr\u0103ri", verb: "s\u0103 aib\u0103" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "intrare", + email: "adres\u0103 de email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "dat\u0103 \u0219i or\u0103 ISO", + date: "dat\u0103 ISO", + time: "or\u0103 ISO", + duration: "durat\u0103 ISO", + ipv4: "adres\u0103 IPv4", + ipv6: "adres\u0103 IPv6", + mac: "adres\u0103 MAC", + cidrv4: "interval IPv4", + cidrv6: "interval IPv6", + base64: "\u0219ir codat base64", + base64url: "\u0219ir codat base64url", + json_string: "\u0219ir JSON", + e164: "num\u0103r E.164", + jwt: "JWT", + template_literal: "intrare" + }; + const TypeDictionary = { + nan: "NaN", + string: "\u0219ir", + number: "num\u0103r", + boolean: "boolean", + function: "func\u021Bie", + array: "matrice", + object: "obiect", + undefined: "nedefinit", + symbol: "simbol", + bigint: "num\u0103r mare", + void: "void", + never: "never", + map: "hart\u0103", + set: "set" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue2.values[0])}`; + return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemente"}`; + return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} s\u0103 fie ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Prea mic: a\u0219teptat ca ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Prea mic: a\u0219teptat ca ${issue2.origin} s\u0103 fie ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`; + return `Format invalid: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue2.divisor}`; + case "unrecognized_keys": + return `Chei nerecunoscute: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cheie invalid\u0103 \xEEn ${issue2.origin}`; + case "invalid_union": + return "Intrare invalid\u0103"; + case "invalid_element": + return `Valoare invalid\u0103 \xEEn ${issue2.origin}`; + default: + return `Intrare invalid\u0103`; + } + }; +}; +function ro_default() { + return { + localeError: error37() + }; +} + +// node_modules/zod/v4/locales/ru.js +function getRussianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +var error38 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0438\u043C\u0432\u043E\u043B", + few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", + many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u0430", + many: "\u0431\u0430\u0439\u0442" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u044F", + duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", + base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", + json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; + case "invalid_element": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; + } + }; +}; +function ru_default() { + return { + localeError: error38() + }; +} + +// node_modules/zod/v4/locales/sl.js +var error39 = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "vnos", + email: "e-po\u0161tni naslov", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum in \u010Das", + date: "ISO datum", + time: "ISO \u010Das", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 \u0161tevilka", + jwt: "JWT", + template_literal: "vnos" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0161tevilo", + array: "tabela" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; + } + return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; + return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neveljaven klju\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue2.origin}`; + default: + return "Neveljaven vnos"; + } + }; +}; +function sl_default() { + return { + localeError: error39() + }; +} + +// node_modules/zod/v4/locales/sv.js +var error40 = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att inneh\xE5lla" }, + set: { unit: "objekt", verb: "att inneh\xE5lla" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regulj\xE4rt uttryck", + email: "e-postadress", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad str\xE4ng", + base64url: "base64url-kodad str\xE4ng", + json_string: "JSON-str\xE4ng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal" + }; + const TypeDictionary = { + nan: "NaN", + number: "antal", + array: "lista" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; + } + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; + return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + } + return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; + return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; + default: + return `Ogiltig input`; + } + }; +}; +function sv_default() { + return { + localeError: error40() + }; +} + +// node_modules/zod/v4/locales/ta.js +var error41 = () => { + const Sizable = { + string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", + email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", + time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", + ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", + e164: "E.164 \u0B8E\u0BA3\u0BCD", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0B8E\u0BA3\u0BCD", + array: "\u0B85\u0BA3\u0BBF", + null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "ends_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "includes") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "regex") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + case "unrecognized_keys": + return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; + case "invalid_union": + return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; + case "invalid_element": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; + default: + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; + } + }; +}; +function ta_default() { + return { + localeError: error41() + }; +} + +// node_modules/zod/v4/locales/th.js +var error42 = () => { + const Sizable = { + string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", + email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", + url: "URL", + emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", + time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", + ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", + cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", + base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", + base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", + json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", + e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", + template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", + array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", + null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; + if (_issue.format === "regex") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; + case "unrecognized_keys": + return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + case "invalid_union": + return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; + case "invalid_element": + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + default: + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; + } + }; +}; +function th_default() { + return { + localeError: error42() + }; +} + +// node_modules/zod/v4/locales/tr.js +var error43 = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmal\u0131" }, + file: { unit: "bayt", verb: "olmal\u0131" }, + array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "girdi", + email: "e-posta adresi", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO s\xFCre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aral\u0131\u011F\u0131", + cidrv6: "IPv6 aral\u0131\u011F\u0131", + base64: "base64 ile \u015Fifrelenmi\u015F metin", + base64url: "base64url ile \u015Fifrelenmi\u015F metin", + json_string: "JSON dizesi", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "\u015Eablon dizesi" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; + return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; + if (_issue.format === "ends_with") + return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; + if (_issue.format === "regex") + return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; + return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; + case "invalid_union": + return "Ge\xE7ersiz de\u011Fer"; + case "invalid_element": + return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; + default: + return `Ge\xE7ersiz de\u011Fer`; + } + }; +}; +function tr_default() { + return { + localeError: error43() + }; +} + +// node_modules/zod/v4/locales/uk.js +var error44 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", + date: "\u0434\u0430\u0442\u0430 ISO", + time: "\u0447\u0430\u0441 ISO", + duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", + ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", + ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", + cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", + base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", + base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", + json_string: "\u0440\u044F\u0434\u043E\u043A JSON", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; + case "invalid_element": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; + default: + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; + } + }; +}; +function uk_default() { + return { + localeError: error44() + }; +} + +// node_modules/zod/v4/locales/ua.js +function ua_default() { + return uk_default(); +} + +// node_modules/zod/v4/locales/ur.js +var error45 = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, + file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, + array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0627\u0646 \u067E\u0679", + email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", + uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", + nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", + guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", + ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", + xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", + ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", + date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", + time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", + duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", + ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", + ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", + cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", + base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", + e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", + template_literal: "\u0627\u0646 \u067E\u0679" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0646\u0645\u0628\u0631", + array: "\u0622\u0631\u06D2", + null: "\u0646\u0644" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + } + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + } + if (_issue.format === "ends_with") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "includes") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "regex") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + case "unrecognized_keys": + return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; + case "invalid_union": + return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; + case "invalid_element": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; + default: + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; + } + }; +}; +function ur_default() { + return { + localeError: error45() + }; +} + +// node_modules/zod/v4/locales/uz.js +var error46 = () => { + const Sizable = { + string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, + file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, + array: { unit: "element", verb: "bo\u2018lishi kerak" }, + set: { unit: "element", verb: "bo\u2018lishi kerak" }, + map: { unit: "yozuv", verb: "bo\u2018lishi kerak" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "kirish", + email: "elektron pochta manzili", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sana va vaqti", + date: "ISO sana", + time: "ISO vaqt", + duration: "ISO davomiylik", + ipv4: "IPv4 manzil", + ipv6: "IPv6 manzil", + mac: "MAC manzil", + cidrv4: "IPv4 diapazon", + cidrv6: "IPv6 diapazon", + base64: "base64 kodlangan satr", + base64url: "base64url kodlangan satr", + json_string: "JSON satr", + e164: "E.164 raqam", + jwt: "JWT", + template_literal: "kirish" + }; + const TypeDictionary = { + nan: "NaN", + number: "raqam", + array: "massiv" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; + } + return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; + return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; + if (_issue.format === "ends_with") + return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; + if (_issue.format === "includes") + return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; + if (_issue.format === "regex") + return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; + return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; + case "unrecognized_keys": + return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; + case "invalid_union": + return "Noto\u2018g\u2018ri kirish"; + case "invalid_element": + return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; + default: + return `Noto\u2018g\u2018ri kirish`; + } + }; +}; +function uz_default() { + return { + localeError: error46() + }; +} + +// node_modules/zod/v4/locales/vi.js +var error47 = () => { + const Sizable = { + string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, + file: { unit: "byte", verb: "c\xF3" }, + array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0111\u1EA7u v\xE0o", + email: "\u0111\u1ECBa ch\u1EC9 email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ng\xE0y gi\u1EDD ISO", + date: "ng\xE0y ISO", + time: "gi\u1EDD ISO", + duration: "kho\u1EA3ng th\u1EDDi gian ISO", + ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", + ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + cidrv4: "d\u1EA3i IPv4", + cidrv6: "d\u1EA3i IPv6", + base64: "chu\u1ED7i m\xE3 h\xF3a base64", + base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", + json_string: "chu\u1ED7i JSON", + e164: "s\u1ED1 E.164", + jwt: "JWT", + template_literal: "\u0111\u1EA7u v\xE0o" + }; + const TypeDictionary = { + nan: "NaN", + number: "s\u1ED1", + array: "m\u1EA3ng" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; + return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; + } + case "not_multiple_of": + return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; + case "unrecognized_keys": + return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + case "invalid_union": + return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; + case "invalid_element": + return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + default: + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; + } + }; +}; +function vi_default() { + return { + localeError: error47() + }; +} + +// node_modules/zod/v4/locales/zh-CN.js +var error48 = () => { + const Sizable = { + string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, + file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, + array: { unit: "\u9879", verb: "\u5305\u542B" }, + set: { unit: "\u9879", verb: "\u5305\u542B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u8F93\u5165", + email: "\u7535\u5B50\u90AE\u4EF6", + url: "URL", + emoji: "\u8868\u60C5\u7B26\u53F7", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u671F\u65F6\u95F4", + date: "ISO\u65E5\u671F", + time: "ISO\u65F6\u95F4", + duration: "ISO\u65F6\u957F", + ipv4: "IPv4\u5730\u5740", + ipv6: "IPv6\u5730\u5740", + cidrv4: "IPv4\u7F51\u6BB5", + cidrv6: "IPv6\u7F51\u6BB5", + base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", + base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", + json_string: "JSON\u5B57\u7B26\u4E32", + e164: "E.164\u53F7\u7801", + jwt: "JWT", + template_literal: "\u8F93\u5165" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5B57", + array: "\u6570\u7EC4", + null: "\u7A7A\u503C(null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; + return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; + if (_issue.format === "ends_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; + if (_issue.format === "includes") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; + return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; + case "unrecognized_keys": + return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; + case "invalid_union": + return "\u65E0\u6548\u8F93\u5165"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; + default: + return `\u65E0\u6548\u8F93\u5165`; + } + }; +}; +function zh_CN_default() { + return { + localeError: error48() + }; +} + +// node_modules/zod/v4/locales/zh-TW.js +var error49 = () => { + const Sizable = { + string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, + file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, + array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u8F38\u5165", + email: "\u90F5\u4EF6\u5730\u5740", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u65E5\u671F\u6642\u9593", + date: "ISO \u65E5\u671F", + time: "ISO \u6642\u9593", + duration: "ISO \u671F\u9593", + ipv4: "IPv4 \u4F4D\u5740", + ipv6: "IPv6 \u4F4D\u5740", + cidrv4: "IPv4 \u7BC4\u570D", + cidrv6: "IPv6 \u7BC4\u570D", + base64: "base64 \u7DE8\u78BC\u5B57\u4E32", + base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", + json_string: "JSON \u5B57\u4E32", + e164: "E.164 \u6578\u503C", + jwt: "JWT", + template_literal: "\u8F38\u5165" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; + return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; + } + if (_issue.format === "ends_with") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; + if (_issue.format === "includes") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; + return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; + case "unrecognized_keys": + return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; + case "invalid_union": + return "\u7121\u6548\u7684\u8F38\u5165\u503C"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; + default: + return `\u7121\u6548\u7684\u8F38\u5165\u503C`; + } + }; +}; +function zh_TW_default() { + return { + localeError: error49() + }; +} + +// node_modules/zod/v4/locales/yo.js +var error50 = () => { + const Sizable = { + string: { unit: "\xE0mi", verb: "n\xED" }, + file: { unit: "bytes", verb: "n\xED" }, + array: { unit: "nkan", verb: "n\xED" }, + set: { unit: "nkan", verb: "n\xED" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", + email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\xE0k\xF3k\xF2 ISO", + date: "\u1ECDj\u1ECD\u0301 ISO", + time: "\xE0k\xF3k\xF2 ISO", + duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", + ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", + ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + cidrv4: "\xE0gb\xE8gb\xE8 IPv4", + cidrv6: "\xE0gb\xE8gb\xE8 IPv6", + base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", + base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", + json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", + e164: "n\u1ECD\u0301mb\xE0 E.164", + jwt: "JWT", + template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\u1ECD\u0301mb\xE0", + array: "akop\u1ECD" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; + return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; + return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; + case "unrecognized_keys": + return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + case "invalid_union": + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + case "invalid_element": + return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + default: + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + } + }; +}; +function yo_default() { + return { + localeError: error50() + }; +} + +// node_modules/zod/v4/core/registries.js +var _a2; +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); +var $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema, ..._meta) { + const meta3 = _meta[0]; + this._map.set(schema, meta3); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.set(meta3.id, schema); + } + return this; + } + clear() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema) { + const meta3 = this._map.get(schema); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.delete(meta3.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : void 0; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +}; +function registry() { + return new $ZodRegistry(); +} +(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); +var globalRegistry = globalThis.__zod_globalRegistry; + +// node_modules/zod/v4/core/api.js +// @__NO_SIDE_EFFECTS__ +function _string(Class2, params) { + return new Class2({ + type: "string", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class2, params) { + return new Class2({ + type: "string", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class2, params) { + return new Class2({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class2, params) { + return new Class2({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class2, params) { + return new Class2({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _emoji2(Class2, params) { + return new Class2({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class2, params) { + return new Class2({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid(Class2, params) { + return new Class2({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class2, params) { + return new Class2({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class2, params) { + return new Class2({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class2, params) { + return new Class2({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class2, params) { + return new Class2({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class2, params) { + return new Class2({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class2, params) { + return new Class2({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class2, params) { + return new Class2({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class2, params) { + return new Class2({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class2, params) { + return new Class2({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class2, params) { + return new Class2({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class2, params) { + return new Class2({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +var TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6 +}; +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class2, params) { + return new Class2({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class2, params) { + return new Class2({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class2, params) { + return new Class2({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class2, params) { + return new Class2({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class2, params) { + return new Class2({ + type: "number", + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class2, params) { + return new Class2({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class2, params) { + return new Class2({ + type: "boolean", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class2, params) { + return new Class2({ + type: "boolean", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class2, params) { + return new Class2({ + type: "bigint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class2, params) { + return new Class2({ + type: "bigint", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class2, params) { + return new Class2({ + type: "symbol", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _undefined2(Class2, params) { + return new Class2({ + type: "undefined", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _null2(Class2, params) { + return new Class2({ + type: "null", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class2) { + return new Class2({ + type: "any" + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class2, params) { + return new Class2({ + type: "void", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class2, params) { + return new Class2({ + type: "date", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class2, params) { + return new Class2({ + type: "date", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class2, params) { + return new Class2({ + type: "nan", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return /* @__PURE__ */ _gt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return /* @__PURE__ */ _lt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return /* @__PURE__ */ _lte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return /* @__PURE__ */ _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...normalizeParams(params), + size + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new $ZodCheckProperty({ + check: "property", + property, + schema, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); +} +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); +} +// @__NO_SIDE_EFFECTS__ +function _trim() { + return /* @__PURE__ */ _overwrite((input) => input.trim()); +} +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); +} +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); +} +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return /* @__PURE__ */ _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class2, element, params) { + return new Class2({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class2, options, params) { + return new Class2({ + type: "union", + options, + ...normalizeParams(params) + }); +} +function _xor(Class2, options, params) { + return new Class2({ + type: "union", + options, + inclusive: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class2, discriminator, options, params) { + return new Class2({ + type: "union", + options, + discriminator, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class2, left, right) { + return new Class2({ + type: "intersection", + left, + right + }); +} +// @__NO_SIDE_EFFECTS__ +function _tuple(Class2, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class2({ + type: "tuple", + items, + rest, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class2, keyType, valueType, params) { + return new Class2({ + type: "record", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class2, keyType, valueType, params) { + return new Class2({ + type: "map", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class2, valueType, params) { + return new Class2({ + type: "set", + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class2, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nativeEnum(Class2, entries, params) { + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class2, value, params) { + return new Class2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class2, params) { + return new Class2({ + type: "file", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class2, fn) { + return new Class2({ + type: "transform", + transform: fn + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class2, innerType) { + return new Class2({ + type: "optional", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class2, innerType) { + return new Class2({ + type: "nullable", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class2, innerType, defaultValue) { + return new Class2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class2, innerType, params) { + return new Class2({ + type: "nonoptional", + innerType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class2, innerType) { + return new Class2({ + type: "success", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class2, innerType, catchValue) { + return new Class2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class2, in_, out) { + return new Class2({ + type: "pipe", + in: in_, + out + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class2, innerType) { + return new Class2({ + type: "readonly", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class2, parts, params) { + return new Class2({ + type: "template_literal", + parts, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class2, getter) { + return new Class2({ + type: "lazy", + getter + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class2, innerType) { + return new Class2({ + type: "promise", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class2, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...norm + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _refine(Class2, fn, _params) { + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = /* @__PURE__ */ _check((payload) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(issue(issue2, payload.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params) + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); + falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? $ZodCodec; + const _Boolean = Classes.Boolean ?? $ZodBoolean; + const _String = Classes.String ?? $ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec2 = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } else if (falsySet.has(data)) { + return false; + } else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec2, + continue: false + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } else { + return falsyArray[0] || "false"; + } + }), + error: params.error + }); + return codec2; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class2, format, fnOrRegex, _params = {}) { + const params = normalizeParams(_params); + const def2 = { + ...normalizeParams(_params), + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params + }; + if (fnOrRegex instanceof RegExp) { + def2.pattern = fnOrRegex; + } + const inst = new Class2(def2); + return inst; +} + +// node_modules/zod/v4/core/to-json-schema.js +function initializeContext(params) { + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { + }), + io: params?.io ?? "output", + counter: 0, + seen: /* @__PURE__ */ new Map(), + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + external: params?.external ?? void 0 + }; +} +function process(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a3; + const def2 = schema._zod.def; + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; + ctx.seen.set(schema, result); + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } else { + const _json = result.schema; + const processor = ctx.processors[def2.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def2.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + if (!result.ref) + result.ref = parent; + process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta3 = ctx.metadataRegistry.get(schema); + if (meta3) + Object.assign(result.schema, meta3); + if (ctx.io === "input" && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if (ctx.io === "input" && "_prefault" in result.schema) + (_a3 = result.schema).default ?? (_a3.default = result.schema._prefault); + delete result.schema._prefault; + const _result = ctx.seen.get(schema); + return _result.schema; +} +function extractDefs(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const idToSchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.entries()) { + const id4 = ctx.metadataRegistry.get(entry[0])?.id; + if (id4) { + const existing = idToSchema.get(id4); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id4}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id4, entry[0]); + } + } + const makeURI = (entry) => { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; + const uriGenerator = ctx.external.uri ?? ((id5) => id5); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + const id4 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id4; + return { defId: id4, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id4}` }; + } + if (entry[1] === root) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema2 = seen.schema; + for (const key in schema2) { + delete schema2[key]; + } + schema2.$ref = ref; + }; + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + } + } + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id4 = ctx.metadataRegistry.get(entry[0])?.id; + if (id4) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + continue; + } + } + } +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + if (seen.ref === null) + return; + const schema2 = seen.def ?? seen.schema; + const _cached = { ...schema2 }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema2.allOf = schema2.allOf ?? []; + schema2.allOf.push(refSchema); + } else { + Object.assign(schema2, refSchema); + } + Object.assign(schema2, _cached); + const isParentRef = zodSchema._zod.parent === ref; + if (isParentRef) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema2[key]; + } + } + } + if (refSchema.$ref && refSeen.def) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) { + delete schema2[key]; + } + } + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema2.$ref = parentSeen.schema.$ref; + if (parentSeen.def) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema2[key]; + } + } + } + } + } + ctx.override({ + zodSchema, + jsonSchema: schema2, + path: seen.path ?? [] + }); + }; + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } else if (ctx.target === "openapi-3.0") { + } else { + } + if (ctx.external?.uri) { + const id4 = ctx.external.registry.get(schema)?.id; + if (!id4) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id4); + } + Object.assign(result, root.def ?? root.schema); + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== void 0 && result.id === rootMetaId) + delete result.id; + const defs = ctx.external?.defs ?? {}; + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + defs[seen.defId] = seen.def; + } + } + if (ctx.external) { + } else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) + } + }, + enumerable: false, + writable: false + }); + return finalized; + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def2 = _schema._zod.def; + if (def2.type === "transform") + return true; + if (def2.type === "array") + return isTransforming(def2.element, ctx); + if (def2.type === "set") + return isTransforming(def2.valueType, ctx); + if (def2.type === "lazy") + return isTransforming(def2.getter(), ctx); + if (def2.type === "promise" || def2.type === "optional" || def2.type === "nonoptional" || def2.type === "nullable" || def2.type === "readonly" || def2.type === "default" || def2.type === "prefault") { + return isTransforming(def2.innerType, ctx); + } + if (def2.type === "intersection") { + return isTransforming(def2.left, ctx) || isTransforming(def2.right, ctx); + } + if (def2.type === "record" || def2.type === "map") { + return isTransforming(def2.keyType, ctx) || isTransforming(def2.valueType, ctx); + } + if (def2.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def2.in, ctx) || isTransforming(def2.out, ctx); + } + if (def2.type === "object") { + for (const key in def2.shape) { + if (isTransforming(def2.shape[key], ctx)) + return true; + } + return false; + } + if (def2.type === "union") { + for (const option of def2.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def2.type === "tuple") { + for (const item of def2.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def2.rest && isTransforming(def2.rest, ctx)) + return true; + return false; + } + return false; +} +var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); + process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + +// node_modules/zod/v4/core/json-schema-processors.js +var formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set +}; +var stringProcessor = (schema, ctx, _json, _params) => { + const json2 = _json; + json2.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + if (typeof minimum === "number") + json2.minLength = minimum; + if (typeof maximum === "number") + json2.maxLength = maximum; + if (format) { + json2.format = formatMap[format] ?? format; + if (json2.format === "") + delete json2.format; + if (format === "time") { + delete json2.format; + } + } + if (contentEncoding) + json2.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json2.pattern = regexes[0].source; + else if (regexes.length > 1) { + json2.allOf = [ + ...regexes.map((regex) => ({ + ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } +}; +var numberProcessor = (schema, ctx, _json, _params) => { + const json2 = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json2.type = "integer"; + else + json2.type = "number"; + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json2.minimum = exclusiveMinimum; + json2.exclusiveMinimum = true; + } else { + json2.exclusiveMinimum = exclusiveMinimum; + } + } else if (typeof minimum === "number") { + json2.minimum = minimum; + } + if (exMax) { + if (legacy) { + json2.maximum = exclusiveMaximum; + json2.exclusiveMaximum = true; + } else { + json2.exclusiveMaximum = exclusiveMaximum; + } + } else if (typeof maximum === "number") { + json2.maximum = maximum; + } + if (typeof multipleOf === "number") + json2.multipleOf = multipleOf; +}; +var booleanProcessor = (_schema, _ctx, json2, _params) => { + json2.type = "boolean"; +}; +var bigintProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } +}; +var symbolProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } +}; +var nullProcessor = (_schema, ctx, json2, _params) => { + if (ctx.target === "openapi-3.0") { + json2.type = "string"; + json2.nullable = true; + json2.enum = [null]; + } else { + json2.type = "null"; + } +}; +var undefinedProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } +}; +var voidProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } +}; +var neverProcessor = (_schema, _ctx, json2, _params) => { + json2.not = {}; +}; +var anyProcessor = (_schema, _ctx, _json, _params) => { +}; +var unknownProcessor = (_schema, _ctx, _json, _params) => { +}; +var dateProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } +}; +var enumProcessor = (schema, _ctx, json2, _params) => { + const def2 = schema._zod.def; + const values = getEnumValues(def2.entries); + if (values.every((v) => typeof v === "number")) + json2.type = "number"; + if (values.every((v) => typeof v === "string")) + json2.type = "string"; + json2.enum = values; +}; +var literalProcessor = (schema, ctx, json2, _params) => { + const def2 = schema._zod.def; + const vals = []; + for (const val of def2.values) { + if (val === void 0) { + if (ctx.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } else if (typeof val === "bigint") { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json2.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.enum = [val]; + } else { + json2.const = val; + } + } else { + if (vals.every((v) => typeof v === "number")) + json2.type = "number"; + if (vals.every((v) => typeof v === "string")) + json2.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json2.type = "boolean"; + if (vals.every((v) => v === null)) + json2.type = "null"; + json2.enum = vals; + } +}; +var nanProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } +}; +var templateLiteralProcessor = (schema, _ctx, json2, _params) => { + const _json = json2; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +var fileProcessor = (schema, _ctx, json2, _params) => { + const _json = json2; + const file2 = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== void 0) + file2.minLength = minimum; + if (maximum !== void 0) + file2.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file2.contentMediaType = mime[0]; + Object.assign(_json, file2); + } else { + Object.assign(_json, file2); + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); + } + } else { + Object.assign(_json, file2); + } +}; +var successProcessor = (_schema, _ctx, json2, _params) => { + json2.type = "boolean"; +}; +var customProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } +}; +var functionProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Function types cannot be represented in JSON Schema"); + } +}; +var transformProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } +}; +var mapProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } +}; +var setProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } +}; +var arrayProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def2 = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + json2.type = "array"; + json2.items = process(def2.element, ctx, { + ...params, + path: [...params.path, "items"] + }); +}; +var objectProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def2 = schema._zod.def; + json2.type = "object"; + json2.properties = {}; + const shape = def2.shape; + for (const key in shape) { + json2.properties[key] = process(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def2.shape[key]._zod; + if (ctx.io === "input") { + return v.optin === void 0; + } else { + return v.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json2.required = Array.from(requiredKeys); + } + if (def2.catchall?._zod.def.type === "never") { + json2.additionalProperties = false; + } else if (!def2.catchall) { + if (ctx.io === "output") + json2.additionalProperties = false; + } else if (def2.catchall) { + json2.additionalProperties = process(def2.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } +}; +var unionProcessor = (schema, ctx, json2, params) => { + const def2 = schema._zod.def; + const isExclusive = def2.inclusive === false; + const options = def2.options.map((x, i) => process(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i] + })); + if (isExclusive) { + json2.oneOf = options; + } else { + json2.anyOf = options; + } +}; +var intersectionProcessor = (schema, ctx, json2, params) => { + const def2 = schema._zod.def; + const a = process(def2.left, ctx, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b = process(def2.right, ctx, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [a], + ...isSimpleIntersection(b) ? b.allOf : [b] + ]; + json2.allOf = allOf; +}; +var tupleProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def2 = schema._zod.def; + json2.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def2.items.map((x, i) => process(x, ctx, { + ...params, + path: [...params.path, prefixPath, i] + })); + const rest = def2.rest ? process(def2.rest, ctx, { + ...params, + path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def2.items.length] : []] + }) : null; + if (ctx.target === "draft-2020-12") { + json2.prefixItems = prefixItems; + if (rest) { + json2.items = rest; + } + } else if (ctx.target === "openapi-3.0") { + json2.items = { + anyOf: prefixItems + }; + if (rest) { + json2.items.anyOf.push(rest); + } + json2.minItems = prefixItems.length; + if (!rest) { + json2.maxItems = prefixItems.length; + } + } else { + json2.items = prefixItems; + if (rest) { + json2.additionalItems = rest; + } + } + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; +}; +var recordProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def2 = schema._zod.def; + json2.type = "object"; + const keyType = def2.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def2.mode === "loose" && patterns && patterns.size > 0) { + const valueSchema = process(def2.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"] + }); + json2.patternProperties = {}; + for (const pattern of patterns) { + json2.patternProperties[pattern.source] = valueSchema; + } + } else { + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json2.propertyNames = process(def2.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"] + }); + } + json2.additionalProperties = process(def2.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + const keyValues = keyType._zod.values; + if (keyValues) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json2.required = validKeyValues; + } + } +}; +var nullableProcessor = (schema, ctx, json2, params) => { + const def2 = schema._zod.def; + const inner = process(def2.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def2.innerType; + json2.nullable = true; + } else { + json2.anyOf = [inner, { type: "null" }]; + } +}; +var nonoptionalProcessor = (schema, ctx, _json, params) => { + const def2 = schema._zod.def; + process(def2.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def2.innerType; +}; +var defaultProcessor = (schema, ctx, json2, params) => { + const def2 = schema._zod.def; + process(def2.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def2.innerType; + json2.default = JSON.parse(JSON.stringify(def2.defaultValue)); +}; +var prefaultProcessor = (schema, ctx, json2, params) => { + const def2 = schema._zod.def; + process(def2.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def2.innerType; + if (ctx.io === "input") + json2._prefault = JSON.parse(JSON.stringify(def2.defaultValue)); +}; +var catchProcessor = (schema, ctx, json2, params) => { + const def2 = schema._zod.def; + process(def2.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def2.innerType; + let catchValue; + try { + catchValue = def2.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json2.default = catchValue; +}; +var pipeProcessor = (schema, ctx, _json, params) => { + const def2 = schema._zod.def; + const inIsTransform = def2.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? inIsTransform ? def2.out : def2.in : def2.out; + process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +var readonlyProcessor = (schema, ctx, json2, params) => { + const def2 = schema._zod.def; + process(def2.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def2.innerType; + json2.readOnly = true; +}; +var promiseProcessor = (schema, ctx, _json, params) => { + const def2 = schema._zod.def; + process(def2.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def2.innerType; +}; +var optionalProcessor = (schema, ctx, _json, params) => { + const def2 = schema._zod.def; + process(def2.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def2.innerType; +}; +var lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +var allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + const registry2 = input; + const ctx2 = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + for (const entry of registry2._idmap.entries()) { + const [_, schema] = entry; + process(schema, ctx2); + } + const schemas = {}; + const external = { + registry: registry2, + uri: params?.uri, + defs + }; + ctx2.external = external; + for (const entry of registry2._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx2, schema); + schemas[key] = finalize(ctx2, schema); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; + } + const ctx = initializeContext({ ...params, processors: allProcessors }); + process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + +// node_modules/zod/v4/core/json-schema-generator.js +var JSONSchemaGenerator = class { + /** @deprecated Access via ctx instead */ + get metadataRegistry() { + return this.ctx.metadataRegistry; + } + /** @deprecated Access via ctx instead */ + get target() { + return this.ctx.target; + } + /** @deprecated Access via ctx instead */ + get unrepresentable() { + return this.ctx.unrepresentable; + } + /** @deprecated Access via ctx instead */ + get override() { + return this.ctx.override; + } + /** @deprecated Access via ctx instead */ + get io() { + return this.ctx.io; + } + /** @deprecated Access via ctx instead */ + get counter() { + return this.ctx.counter; + } + set counter(value) { + this.ctx.counter = value; + } + /** @deprecated Access via ctx instead */ + get seen() { + return this.ctx.seen; + } + constructor(params) { + let normalizedTarget = params?.target ?? "draft-2020-12"; + if (normalizedTarget === "draft-4") + normalizedTarget = "draft-04"; + if (normalizedTarget === "draft-7") + normalizedTarget = "draft-07"; + this.ctx = initializeContext({ + processors: allProcessors, + target: normalizedTarget, + ...params?.metadata && { metadata: params.metadata }, + ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, + ...params?.override && { override: params.override }, + ...params?.io && { io: params.io } + }); + } + /** + * Process a schema to prepare it for JSON Schema generation. + * This must be called before emit(). + */ + process(schema, _params = { path: [], schemaPath: [] }) { + return process(schema, this.ctx, _params); + } + /** + * Emit the final JSON Schema after processing. + * Must call process() first. + */ + emit(schema, _params) { + if (_params) { + if (_params.cycles) + this.ctx.cycles = _params.cycles; + if (_params.reused) + this.ctx.reused = _params.reused; + if (_params.external) + this.ctx.external = _params.external; + } + extractDefs(this.ctx, schema); + const result = finalize(this.ctx, schema); + const { "~standard": _, ...plainResult } = result; + return plainResult; + } +}; + +// node_modules/zod/v4/core/json-schema.js +var json_schema_exports = {}; + +// node_modules/zod/v4/classic/schemas.js +var schemas_exports2 = {}; +__export(schemas_exports2, { + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFunction: () => ZodFunction, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodIntersection: () => ZodIntersection, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPreprocess: () => ZodPreprocess, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + codec: () => codec, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + float32: () => float32, + float64: () => float64, + function: () => _function, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + invertCodec: () => invertCodec, + ipv4: () => ipv42, + ipv6: () => ipv62, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + literal: () => literal, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + mac: () => mac2, + map: () => map, + meta: () => meta2, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + never: () => never, + nonoptional: () => nonoptional, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + partialRecord: () => partialRecord, + pipe: () => pipe, + prefault: () => prefault, + preprocess: () => preprocess, + promise: () => promise, + readonly: () => readonly, + record: () => record, + refine: () => refine, + set: () => set, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + transform: () => transform, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + url: () => url, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor +}); + +// node_modules/zod/v4/classic/checks.js +var checks_exports2 = {}; +__export(checks_exports2, { + endsWith: () => _endsWith, + gt: () => _gt, + gte: () => _gte, + includes: () => _includes, + length: () => _length, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + negative: () => _negative, + nonnegative: () => _nonnegative, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + overwrite: () => _overwrite, + positive: () => _positive, + property: () => _property, + regex: () => _regex, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + trim: () => _trim, + uppercase: () => _uppercase +}); + +// node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date2, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def2) => { + $ZodISODateTime.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def2) => { + $ZodISODate.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function date2(params) { + return _isoDate(ZodISODate, params); +} +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def2) => { + $ZodISOTime.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function time2(params) { + return _isoTime(ZodISOTime, params); +} +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def2) => { + $ZodISODuration.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/zod/v4/classic/errors.js +var initializer2 = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper) + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper) + // enumerable: false, + }, + addIssue: { + value: (issue2) => { + inst.issues.push(issue2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + addIssues: { + value: (issues2) => { + inst.issues.push(...issues2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + } + // enumerable: false, + } + }); +}; +var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2); +var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, { + Parent: Error +}); + +// node_modules/zod/v4/classic/parse.js +var parse2 = /* @__PURE__ */ _parse(ZodRealError); +var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); +var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); +var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); +var encode2 = /* @__PURE__ */ _encode(ZodRealError); +var decode2 = /* @__PURE__ */ _decode(ZodRealError); +var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); +var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); +var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); +var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); +var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + +// node_modules/zod/v4/classic/schemas.js +var _installedGroups = /* @__PURE__ */ new WeakMap(); +function _installLazyMethods(inst, group, methods) { + const proto = Object.getPrototypeOf(inst); + let installed = _installedGroups.get(proto); + if (!installed) { + installed = /* @__PURE__ */ new Set(); + _installedGroups.set(proto, installed); + } + if (installed.has(group)) + return; + installed.add(group); + for (const key in methods) { + const fn = methods[key]; + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const bound = fn.bind(this); + Object.defineProperty(this, key, { + configurable: true, + writable: true, + enumerable: true, + value: bound + }); + return bound; + }, + set(v) { + Object.defineProperty(this, key, { + configurable: true, + writable: true, + enumerable: true, + value: v + }); + } + }); + } +} +var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def2) => { + $ZodType.init(inst, def2); + Object.assign(inst["~standard"], { + jsonSchema: { + input: createStandardJSONSchemaMethod(inst, "input"), + output: createStandardJSONSchemaMethod(inst, "output") + } + }); + inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); + inst.def = def2; + inst.type = def2.type; + Object.defineProperty(inst, "_def", { value: def2 }); + inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse2(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.encode = (data, params) => encode2(inst, data, params); + inst.decode = (data, params) => decode2(inst, data, params); + inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); + inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); + inst.safeEncode = (data, params) => safeEncode2(inst, data, params); + inst.safeDecode = (data, params) => safeDecode2(inst, data, params); + inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); + inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); + _installLazyMethods(inst, "ZodType", { + check(...chks) { + const def3 = this.def; + return this.clone(util_exports.mergeDefs(def3, { + checks: [ + ...def3.checks ?? [], + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def3, params) { + return clone(this, def3, params); + }, + brand() { + return this; + }, + register(reg, meta3) { + reg.add(this, meta3); + return this; + }, + refine(check2, params) { + return this.check(refine(check2, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default2(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch2(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(void 0).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn) { + return fn(this); + } + }); + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + return inst; +}); +var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def2) => { + $ZodString.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + _installLazyMethods(inst, "_ZodString", { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + } + }); +}); +var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def2) => { + $ZodString.init(inst, def2); + _ZodString.init(inst, def2); + inst.email = (params) => inst.check(_email(ZodEmail, params)); + inst.url = (params) => inst.check(_url(ZodURL, params)); + inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(_xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(_e164(ZodE164, params)); + inst.datetime = (params) => inst.check(datetime2(params)); + inst.date = (params) => inst.check(date2(params)); + inst.time = (params) => inst.check(time2(params)); + inst.duration = (params) => inst.check(duration2(params)); +}); +function string2(params) { + return _string(ZodString, params); +} +var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def2) => { + $ZodStringFormat.init(inst, def2); + _ZodString.init(inst, def2); +}); +var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def2) => { + $ZodEmail.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function email2(params) { + return _email(ZodEmail, params); +} +var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def2) => { + $ZodGUID.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function guid2(params) { + return _guid(ZodGUID, params); +} +var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def2) => { + $ZodUUID.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function uuid2(params) { + return _uuid(ZodUUID, params); +} +function uuidv4(params) { + return _uuidv4(ZodUUID, params); +} +function uuidv6(params) { + return _uuidv6(ZodUUID, params); +} +function uuidv7(params) { + return _uuidv7(ZodUUID, params); +} +var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def2) => { + $ZodURL.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return _url(ZodURL, { + protocol: regexes_exports.httpProtocol, + hostname: regexes_exports.domain, + ...util_exports.normalizeParams(params) + }); +} +var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def2) => { + $ZodEmoji.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function emoji2(params) { + return _emoji2(ZodEmoji, params); +} +var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def2) => { + $ZodNanoID.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function nanoid2(params) { + return _nanoid(ZodNanoID, params); +} +var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def2) => { + $ZodCUID.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function cuid3(params) { + return _cuid(ZodCUID, params); +} +var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def2) => { + $ZodCUID2.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function cuid22(params) { + return _cuid2(ZodCUID2, params); +} +var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def2) => { + $ZodULID.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function ulid2(params) { + return _ulid(ZodULID, params); +} +var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def2) => { + $ZodXID.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function xid2(params) { + return _xid(ZodXID, params); +} +var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def2) => { + $ZodKSUID.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function ksuid2(params) { + return _ksuid(ZodKSUID, params); +} +var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def2) => { + $ZodIPv4.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function ipv42(params) { + return _ipv4(ZodIPv4, params); +} +var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def2) => { + $ZodMAC.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function mac2(params) { + return _mac(ZodMAC, params); +} +var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def2) => { + $ZodIPv6.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function ipv62(params) { + return _ipv6(ZodIPv6, params); +} +var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def2) => { + $ZodCIDRv4.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function cidrv42(params) { + return _cidrv4(ZodCIDRv4, params); +} +var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def2) => { + $ZodCIDRv6.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function cidrv62(params) { + return _cidrv6(ZodCIDRv6, params); +} +var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def2) => { + $ZodBase64.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function base642(params) { + return _base64(ZodBase64, params); +} +var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def2) => { + $ZodBase64URL.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function base64url2(params) { + return _base64url(ZodBase64URL, params); +} +var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def2) => { + $ZodE164.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function e1642(params) { + return _e164(ZodE164, params); +} +var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def2) => { + $ZodJWT.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function jwt(params) { + return _jwt(ZodJWT, params); +} +var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def2) => { + $ZodCustomStringFormat.init(inst, def2); + ZodStringFormat.init(inst, def2); +}); +function stringFormat(format, fnOrRegex, _params = {}) { + return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function hostname2(_params) { + return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); +} +function hex2(_params) { + return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); +} +function hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = regexes_exports[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return _stringFormat(ZodCustomStringFormat, format, regex, params); +} +var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def2) => { + $ZodNumber.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); + _installLazyMethods(inst, "ZodNumber", { + gt(value, params) { + return this.check(_gt(value, params)); + }, + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + int(params) { + return this.check(int(params)); + }, + safe(params) { + return this.check(int(params)); + }, + positive(params) { + return this.check(_gt(0, params)); + }, + nonnegative(params) { + return this.check(_gte(0, params)); + }, + negative(params) { + return this.check(_lt(0, params)); + }, + nonpositive(params) { + return this.check(_lte(0, params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + }, + step(value, params) { + return this.check(_multipleOf(value, params)); + }, + finite() { + return this; + } + }); + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}); +function number2(params) { + return _number(ZodNumber, params); +} +var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def2) => { + $ZodNumberFormat.init(inst, def2); + ZodNumber.init(inst, def2); +}); +function int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return _float32(ZodNumberFormat, params); +} +function float64(params) { + return _float64(ZodNumberFormat, params); +} +function int32(params) { + return _int32(ZodNumberFormat, params); +} +function uint32(params) { + return _uint32(ZodNumberFormat, params); +} +var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def2) => { + $ZodBoolean.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); +}); +function boolean2(params) { + return _boolean(ZodBoolean, params); +} +var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def2) => { + $ZodBigInt.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.positive = (params) => inst.check(_gt(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}); +function bigint2(params) { + return _bigint(ZodBigInt, params); +} +var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def2) => { + $ZodBigIntFormat.init(inst, def2); + ZodBigInt.init(inst, def2); +}); +function int64(params) { + return _int64(ZodBigIntFormat, params); +} +function uint64(params) { + return _uint64(ZodBigIntFormat, params); +} +var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def2) => { + $ZodSymbol.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); +}); +function symbol(params) { + return _symbol(ZodSymbol, params); +} +var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def2) => { + $ZodUndefined.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); +}); +function _undefined3(params) { + return _undefined2(ZodUndefined, params); +} +var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def2) => { + $ZodNull.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); +}); +function _null3(params) { + return _null2(ZodNull, params); +} +var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def2) => { + $ZodAny.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); +}); +function any() { + return _any(ZodAny); +} +var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def2) => { + $ZodUnknown.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def2) => { + $ZodNever.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); +}); +function never(params) { + return _never(ZodNever, params); +} +var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def2) => { + $ZodVoid.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); +}); +function _void2(params) { + return _void(ZodVoid, params); +} +var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def2) => { + $ZodDate.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}); +function date3(params) { + return _date(ZodDate, params); +} +var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def2) => { + $ZodArray.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); + inst.element = def2.element; + _installLazyMethods(inst, "ZodArray", { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + } + }); +}); +function array(element, params) { + return _array(ZodArray, element, params); +} +function keyof(schema) { + const shape = schema._zod.def.shape; + return _enum2(Object.keys(shape)); +} +var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def2) => { + $ZodObjectJIT.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); + util_exports.defineLazy(inst, "shape", () => { + return def2.shape; + }); + _installLazyMethods(inst, "ZodObject", { + keyof() { + return _enum2(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ ...this._zod.def, catchall }); + }, + passthrough() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + loose() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + strict() { + return this.clone({ ...this._zod.def, catchall: never() }); + }, + strip() { + return this.clone({ ...this._zod.def, catchall: void 0 }); + }, + extend(incoming) { + return util_exports.extend(this, incoming); + }, + safeExtend(incoming) { + return util_exports.safeExtend(this, incoming); + }, + merge(other) { + return util_exports.merge(this, other); + }, + pick(mask) { + return util_exports.pick(this, mask); + }, + omit(mask) { + return util_exports.omit(this, mask); + }, + partial(...args) { + return util_exports.partial(ZodOptional, this, args[0]); + }, + required(...args) { + return util_exports.required(ZodNonOptional, this, args[0]); + } + }); +}); +function object(shape, params) { + const def2 = { + type: "object", + shape: shape ?? {}, + ...util_exports.normalizeParams(params) + }; + return new ZodObject(def2); +} +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util_exports.normalizeParams(params) + }); +} +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...util_exports.normalizeParams(params) + }); +} +var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def2) => { + $ZodUnion.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); + inst.options = def2.options; +}); +function union(options, params) { + return new ZodUnion({ + type: "union", + options, + ...util_exports.normalizeParams(params) + }); +} +var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def2) => { + ZodUnion.init(inst, def2); + $ZodXor.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); + inst.options = def2.options; +}); +function xor(options, params) { + return new ZodXor({ + type: "union", + options, + inclusive: false, + ...util_exports.normalizeParams(params) + }); +} +var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def2) => { + ZodUnion.init(inst, def2); + $ZodDiscriminatedUnion.init(inst, def2); +}); +function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, + ...util_exports.normalizeParams(params) + }); +} +var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def2) => { + $ZodIntersection.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left, + right + }); +} +var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def2) => { + $ZodTuple.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest + }); +}); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items, + rest, + ...util_exports.normalizeParams(params) + }); +} +var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def2) => { + $ZodRecord.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); + inst.keyType = def2.keyType; + inst.valueType = def2.valueType; +}); +function record(keyType, valueType, params) { + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: string2(), + valueType: keyType, + ...util_exports.normalizeParams(valueType) + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function partialRecord(keyType, valueType, params) { + const k = clone(keyType); + k._zod.values = void 0; + return new ZodRecord({ + type: "record", + keyType: k, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType, + mode: "loose", + ...util_exports.normalizeParams(params) + }); +} +var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def2) => { + $ZodMap.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); + inst.keyType = def2.keyType; + inst.valueType = def2.valueType; + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); +}); +function map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def2) => { + $ZodSet.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); +}); +function set(valueType, params) { + return new ZodSet({ + type: "set", + valueType, + ...util_exports.normalizeParams(params) + }); +} +var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def2) => { + $ZodEnum.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params); + inst.enum = def2.entries; + inst.options = Object.values(def2.entries); + const keys = new Set(Object.keys(def2.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def2.entries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def2, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def2.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def2, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; +}); +function _enum2(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def2) => { + $ZodLiteral.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params); + inst.values = new Set(def2.values); + Object.defineProperty(inst, "value", { + get() { + if (def2.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def2.values[0]; + } + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util_exports.normalizeParams(params) + }); +} +var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def2) => { + $ZodFile.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); + inst.min = (size, params) => inst.check(_minSize(size, params)); + inst.max = (size, params) => inst.check(_maxSize(size, params)); + inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); +}); +function file(params) { + return _file(ZodFile, params); +} +var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def2) => { + $ZodTransform.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, def2)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + payload.issues.push(util_exports.issue(_issue)); + } + }; + const output = def2.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output2) => { + payload.value = output2; + payload.fallback = true; + return payload; + }); + } + payload.value = output; + payload.fallback = true; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); +} +var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def2) => { + $ZodOptional.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType + }); +} +var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def2) => { + $ZodExactOptional.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType + }); +} +var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def2) => { + $ZodNullable.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType + }); +} +function nullish2(innerType) { + return optional(nullable(innerType)); +} +var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def2) => { + $ZodDefault.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function _default2(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def2) => { + $ZodPrefault.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def2) => { + $ZodNonOptional.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...util_exports.normalizeParams(params) + }); +} +var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def2) => { + $ZodSuccess.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType + }); +} +var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def2) => { + $ZodCatch.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function _catch2(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def2) => { + $ZodNaN.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); +}); +function nan(params) { + return _nan(ZodNaN, params); +} +var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def2) => { + $ZodPipe.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); + inst.in = def2.in; + inst.out = def2.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + // ...util.normalizeParams(params), + }); +} +var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def2) => { + ZodPipe.init(inst, def2); + $ZodCodec.init(inst, def2); +}); +function codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out, + transform: params.decode, + reverseTransform: params.encode + }); +} +function invertCodec(codec2) { + const def2 = codec2._zod.def; + return new ZodCodec({ + type: "pipe", + in: def2.out, + out: def2.in, + transform: def2.reverseTransform, + reverseTransform: def2.transform + }); +} +var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def2) => { + ZodPipe.init(inst, def2); + $ZodPreprocess.init(inst, def2); +}); +var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def2) => { + $ZodReadonly.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType + }); +} +var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def2) => { + $ZodTemplateLiteral.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); +}); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util_exports.normalizeParams(params) + }); +} +var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def2) => { + $ZodLazy.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter + }); +} +var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def2) => { + $ZodPromise.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType + }); +} +var ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def2) => { + $ZodFunction.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); +}); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), + output: params?.output ?? unknown() + }); +} +var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def2) => { + $ZodCustom.init(inst, def2); + ZodType.init(inst, def2); + inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); +}); +function check(fn) { + const ch = new $ZodCheck({ + check: "custom" + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return _custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +function superRefine(fn, params) { + return _superRefine(fn, params); +} +var describe2 = describe; +var meta2 = meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util_exports.normalizeParams(params) + }); + inst._zod.bag.Class = cls; + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...inst._zod.def.path ?? []] + }); + } + }; + return inst; +} +var stringbool = (...args) => _stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString +}, ...args); +function json(params) { + const jsonSchema = lazy(() => { + return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); + }); + return jsonSchema; +} +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema + }); +} + +// node_modules/zod/v4/classic/compat.js +var ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom" +}; +function setErrorMap(map2) { + config({ + customError: map2 + }); +} +function getErrorMap() { + return config().customError; +} +var ZodFirstPartyTypeKind; +/* @__PURE__ */ (function(ZodFirstPartyTypeKind2) { +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); + +// node_modules/zod/v4/classic/from-json-schema.js +var z = { + ...schemas_exports2, + ...checks_exports2, + iso: iso_exports +}; +var RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ + // Schema identification + "$schema", + "$ref", + "$defs", + "definitions", + // Core schema keywords + "$id", + "id", + "$comment", + "$anchor", + "$vocabulary", + "$dynamicRef", + "$dynamicAnchor", + // Type + "type", + "enum", + "const", + // Composition + "anyOf", + "oneOf", + "allOf", + "not", + // Object + "properties", + "required", + "additionalProperties", + "patternProperties", + "propertyNames", + "minProperties", + "maxProperties", + // Array + "items", + "prefixItems", + "additionalItems", + "minItems", + "maxItems", + "uniqueItems", + "contains", + "minContains", + "maxContains", + // String + "minLength", + "maxLength", + "pattern", + "format", + // Number + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "multipleOf", + // Already handled metadata + "description", + "default", + // Content + "contentEncoding", + "contentMediaType", + "contentSchema", + // Unsupported (error-throwing) + "unevaluatedItems", + "unevaluatedProperties", + "if", + "then", + "else", + "dependentSchemas", + "dependentRequired", + // OpenAPI + "nullable", + "readOnly" +]); +function detectVersion(schema, defaultTarget) { + const $schema = schema.$schema; + if ($schema === "https://json-schema.org/draft/2020-12/schema") { + return "draft-2020-12"; + } + if ($schema === "http://json-schema.org/draft-07/schema#") { + return "draft-7"; + } + if ($schema === "http://json-schema.org/draft-04/schema#") { + return "draft-4"; + } + return defaultTarget ?? "draft-2020-12"; +} +function resolveRef(ref, ctx) { + if (!ref.startsWith("#")) { + throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); + } + const path = ref.slice(1).split("/").filter(Boolean); + if (path.length === 0) { + return ctx.rootSchema; + } + const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; + if (path[0] === defsKey) { + const key = path[1]; + if (!key || !ctx.defs[key]) { + throw new Error(`Reference not found: ${ref}`); + } + return ctx.defs[key]; + } + throw new Error(`Reference not found: ${ref}`); +} +function convertBaseSchema(schema, ctx) { + if (schema.not !== void 0) { + if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { + return z.never(); + } + throw new Error("not is not supported in Zod (except { not: {} } for never)"); + } + if (schema.unevaluatedItems !== void 0) { + throw new Error("unevaluatedItems is not supported"); + } + if (schema.unevaluatedProperties !== void 0) { + throw new Error("unevaluatedProperties is not supported"); + } + if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) { + throw new Error("Conditional schemas (if/then/else) are not supported"); + } + if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) { + throw new Error("dependentSchemas and dependentRequired are not supported"); + } + if (schema.$ref) { + const refPath = schema.$ref; + if (ctx.refs.has(refPath)) { + return ctx.refs.get(refPath); + } + if (ctx.processing.has(refPath)) { + return z.lazy(() => { + if (!ctx.refs.has(refPath)) { + throw new Error(`Circular reference not resolved: ${refPath}`); + } + return ctx.refs.get(refPath); + }); + } + ctx.processing.add(refPath); + const resolved = resolveRef(refPath, ctx); + const zodSchema2 = convertSchema(resolved, ctx); + ctx.refs.set(refPath, zodSchema2); + ctx.processing.delete(refPath); + return zodSchema2; + } + if (schema.enum !== void 0) { + const enumValues = schema.enum; + if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) { + return z.null(); + } + if (enumValues.length === 0) { + return z.never(); + } + if (enumValues.length === 1) { + return z.literal(enumValues[0]); + } + if (enumValues.every((v) => typeof v === "string")) { + return z.enum(enumValues); + } + const literalSchemas = enumValues.map((v) => z.literal(v)); + if (literalSchemas.length < 2) { + return literalSchemas[0]; + } + return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); + } + if (schema.const !== void 0) { + return z.literal(schema.const); + } + const type = schema.type; + if (Array.isArray(type)) { + const typeSchemas = type.map((t) => { + const typeSchema = { ...schema, type: t }; + return convertBaseSchema(typeSchema, ctx); + }); + if (typeSchemas.length === 0) { + return z.never(); + } + if (typeSchemas.length === 1) { + return typeSchemas[0]; + } + return z.union(typeSchemas); + } + if (!type) { + return z.any(); + } + let zodSchema; + switch (type) { + case "string": { + let stringSchema = z.string(); + if (schema.format) { + const format = schema.format; + if (format === "email") { + stringSchema = stringSchema.check(z.email()); + } else if (format === "uri" || format === "uri-reference") { + stringSchema = stringSchema.check(z.url()); + } else if (format === "uuid" || format === "guid") { + stringSchema = stringSchema.check(z.uuid()); + } else if (format === "date-time") { + stringSchema = stringSchema.check(z.iso.datetime()); + } else if (format === "date") { + stringSchema = stringSchema.check(z.iso.date()); + } else if (format === "time") { + stringSchema = stringSchema.check(z.iso.time()); + } else if (format === "duration") { + stringSchema = stringSchema.check(z.iso.duration()); + } else if (format === "ipv4") { + stringSchema = stringSchema.check(z.ipv4()); + } else if (format === "ipv6") { + stringSchema = stringSchema.check(z.ipv6()); + } else if (format === "mac") { + stringSchema = stringSchema.check(z.mac()); + } else if (format === "cidr") { + stringSchema = stringSchema.check(z.cidrv4()); + } else if (format === "cidr-v6") { + stringSchema = stringSchema.check(z.cidrv6()); + } else if (format === "base64") { + stringSchema = stringSchema.check(z.base64()); + } else if (format === "base64url") { + stringSchema = stringSchema.check(z.base64url()); + } else if (format === "e164") { + stringSchema = stringSchema.check(z.e164()); + } else if (format === "jwt") { + stringSchema = stringSchema.check(z.jwt()); + } else if (format === "emoji") { + stringSchema = stringSchema.check(z.emoji()); + } else if (format === "nanoid") { + stringSchema = stringSchema.check(z.nanoid()); + } else if (format === "cuid") { + stringSchema = stringSchema.check(z.cuid()); + } else if (format === "cuid2") { + stringSchema = stringSchema.check(z.cuid2()); + } else if (format === "ulid") { + stringSchema = stringSchema.check(z.ulid()); + } else if (format === "xid") { + stringSchema = stringSchema.check(z.xid()); + } else if (format === "ksuid") { + stringSchema = stringSchema.check(z.ksuid()); + } + } + if (typeof schema.minLength === "number") { + stringSchema = stringSchema.min(schema.minLength); + } + if (typeof schema.maxLength === "number") { + stringSchema = stringSchema.max(schema.maxLength); + } + if (schema.pattern) { + stringSchema = stringSchema.regex(new RegExp(schema.pattern)); + } + zodSchema = stringSchema; + break; + } + case "number": + case "integer": { + let numberSchema = type === "integer" ? z.number().int() : z.number(); + if (typeof schema.minimum === "number") { + numberSchema = numberSchema.min(schema.minimum); + } + if (typeof schema.maximum === "number") { + numberSchema = numberSchema.max(schema.maximum); + } + if (typeof schema.exclusiveMinimum === "number") { + numberSchema = numberSchema.gt(schema.exclusiveMinimum); + } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") { + numberSchema = numberSchema.gt(schema.minimum); + } + if (typeof schema.exclusiveMaximum === "number") { + numberSchema = numberSchema.lt(schema.exclusiveMaximum); + } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") { + numberSchema = numberSchema.lt(schema.maximum); + } + if (typeof schema.multipleOf === "number") { + numberSchema = numberSchema.multipleOf(schema.multipleOf); + } + zodSchema = numberSchema; + break; + } + case "boolean": { + zodSchema = z.boolean(); + break; + } + case "null": { + zodSchema = z.null(); + break; + } + case "object": { + const shape = {}; + const properties = schema.properties || {}; + const requiredSet = new Set(schema.required || []); + for (const [key, propSchema] of Object.entries(properties)) { + const propZodSchema = convertSchema(propSchema, ctx); + shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); + } + if (schema.propertyNames) { + const keySchema = convertSchema(schema.propertyNames, ctx); + const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any(); + if (Object.keys(shape).length === 0) { + zodSchema = z.record(keySchema, valueSchema); + break; + } + const objectSchema2 = z.object(shape).passthrough(); + const recordSchema = z.looseRecord(keySchema, valueSchema); + zodSchema = z.intersection(objectSchema2, recordSchema); + break; + } + if (schema.patternProperties) { + const patternProps = schema.patternProperties; + const patternKeys = Object.keys(patternProps); + const looseRecords = []; + for (const pattern of patternKeys) { + const patternValue = convertSchema(patternProps[pattern], ctx); + const keySchema = z.string().regex(new RegExp(pattern)); + looseRecords.push(z.looseRecord(keySchema, patternValue)); + } + const schemasToIntersect = []; + if (Object.keys(shape).length > 0) { + schemasToIntersect.push(z.object(shape).passthrough()); + } + schemasToIntersect.push(...looseRecords); + if (schemasToIntersect.length === 0) { + zodSchema = z.object({}).passthrough(); + } else if (schemasToIntersect.length === 1) { + zodSchema = schemasToIntersect[0]; + } else { + let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]); + for (let i = 2; i < schemasToIntersect.length; i++) { + result = z.intersection(result, schemasToIntersect[i]); + } + zodSchema = result; + } + break; + } + const objectSchema = z.object(shape); + if (schema.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (typeof schema.additionalProperties === "object") { + zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + } else { + zodSchema = objectSchema.passthrough(); + } + break; + } + case "array": { + const prefixItems = schema.prefixItems; + const items = schema.items; + if (prefixItems && Array.isArray(prefixItems)) { + const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); + const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; + if (rest) { + zodSchema = z.tuple(tupleItems).rest(rest); + } else { + zodSchema = z.tuple(tupleItems); + } + if (typeof schema.minItems === "number") { + zodSchema = zodSchema.check(z.minLength(schema.minItems)); + } + if (typeof schema.maxItems === "number") { + zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); + } + } else if (Array.isArray(items)) { + const tupleItems = items.map((item) => convertSchema(item, ctx)); + const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0; + if (rest) { + zodSchema = z.tuple(tupleItems).rest(rest); + } else { + zodSchema = z.tuple(tupleItems); + } + if (typeof schema.minItems === "number") { + zodSchema = zodSchema.check(z.minLength(schema.minItems)); + } + if (typeof schema.maxItems === "number") { + zodSchema = zodSchema.check(z.maxLength(schema.maxItems)); + } + } else if (items !== void 0) { + const element = convertSchema(items, ctx); + let arraySchema = z.array(element); + if (typeof schema.minItems === "number") { + arraySchema = arraySchema.min(schema.minItems); + } + if (typeof schema.maxItems === "number") { + arraySchema = arraySchema.max(schema.maxItems); + } + zodSchema = arraySchema; + } else { + zodSchema = z.array(z.any()); + } + break; + } + default: + throw new Error(`Unsupported type: ${type}`); + } + return zodSchema; +} +function convertSchema(schema, ctx) { + if (typeof schema === "boolean") { + return schema ? z.any() : z.never(); + } + let baseSchema = convertBaseSchema(schema, ctx); + const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0; + if (schema.anyOf && Array.isArray(schema.anyOf)) { + const options = schema.anyOf.map((s) => convertSchema(s, ctx)); + const anyOfUnion = z.union(options); + baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion; + } + if (schema.oneOf && Array.isArray(schema.oneOf)) { + const options = schema.oneOf.map((s) => convertSchema(s, ctx)); + const oneOfUnion = z.xor(options); + baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion; + } + if (schema.allOf && Array.isArray(schema.allOf)) { + if (schema.allOf.length === 0) { + baseSchema = hasExplicitType ? baseSchema : z.any(); + } else { + let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx); + const startIdx = hasExplicitType ? 0 : 1; + for (let i = startIdx; i < schema.allOf.length; i++) { + result = z.intersection(result, convertSchema(schema.allOf[i], ctx)); + } + baseSchema = result; + } + } + if (schema.nullable === true && ctx.version === "openapi-3.0") { + baseSchema = z.nullable(baseSchema); + } + if (schema.readOnly === true) { + baseSchema = z.readonly(baseSchema); + } + if (schema.default !== void 0) { + baseSchema = baseSchema.default(schema.default); + } + const extraMeta = {}; + const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; + for (const key of coreMetadataKeys) { + if (key in schema) { + extraMeta[key] = schema[key]; + } + } + const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; + for (const key of contentMetadataKeys) { + if (key in schema) { + extraMeta[key] = schema[key]; + } + } + for (const key of Object.keys(schema)) { + if (!RECOGNIZED_KEYS.has(key)) { + extraMeta[key] = schema[key]; + } + } + if (Object.keys(extraMeta).length > 0) { + ctx.registry.add(baseSchema, extraMeta); + } + if (schema.description) { + baseSchema = baseSchema.describe(schema.description); + } + return baseSchema; +} +function fromJSONSchema(schema, params) { + if (typeof schema === "boolean") { + return schema ? z.any() : z.never(); + } + let normalized; + try { + normalized = JSON.parse(JSON.stringify(schema)); + } catch { + throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas"); + } + const version3 = detectVersion(normalized, params?.defaultTarget); + const defs = normalized.$defs || normalized.definitions || {}; + const ctx = { + version: version3, + defs, + refs: /* @__PURE__ */ new Map(), + processing: /* @__PURE__ */ new Set(), + rootSchema: normalized, + registry: params?.registry ?? globalRegistry + }; + return convertSchema(normalized, ctx); +} + +// node_modules/zod/v4/classic/coerce.js +var coerce_exports = {}; +__export(coerce_exports, { + bigint: () => bigint3, + boolean: () => boolean3, + date: () => date4, + number: () => number3, + string: () => string3 +}); +function string3(params) { + return _coercedString(ZodString, params); +} +function number3(params) { + return _coercedNumber(ZodNumber, params); +} +function boolean3(params) { + return _coercedBoolean(ZodBoolean, params); +} +function bigint3(params) { + return _coercedBigint(ZodBigInt, params); +} +function date4(params) { + return _coercedDate(ZodDate, params); +} + +// node_modules/zod/v4/classic/external.js +config(en_default()); + +// node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs +var LATEST_PROTOCOL_VERSION = "2025-11-25"; +var SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" +]; +var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +var PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; +var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; +var SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; +var CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; +var SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; +var LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; +var JSONRPC_VERSION = "2.0"; +var JSONValueSchema = lazy(() => union([ + string2(), + number2(), + boolean2(), + _null3(), + record(string2(), JSONValueSchema), + array(JSONValueSchema) +])); +var JSONObjectSchema = record(string2(), JSONValueSchema); +var JSONArraySchema = array(JSONValueSchema); +var ProgressTokenSchema = union([string2(), number2().int()]); +var CursorSchema = string2(); +var TaskMetadataSchema = object({ ttl: number2().optional() }); +var RelatedTaskMetadataSchema = object({ taskId: string2() }); +var RequestMetaSchema = looseObject({ + progressToken: ProgressTokenSchema.optional(), + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +var BaseRequestParamsSchema = object({ _meta: RequestMetaSchema.optional() }); +var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); +var RequestSchema = object({ + method: string2(), + params: BaseRequestParamsSchema.loose().optional() +}); +var NotificationsParamsSchema = object({ _meta: RequestMetaSchema.optional() }); +var NotificationSchema = object({ + method: string2(), + params: NotificationsParamsSchema.loose().optional() +}); +var ResultMetaObjectSchema = looseObject({ get [SERVER_INFO_META_KEY]() { + return ImplementationSchema.optional().catch(void 0); +} }); +var ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); +var RequestIdSchema = union([string2(), number2().int()]); +var JSONRPCRequestSchema = object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +var JSONRPCNotificationSchema = object({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +var JSONRPCResultResponseSchema = object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +var JSONRPCErrorResponseSchema = object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: object({ + code: number2().int(), + message: string2(), + data: unknown().optional() + }) +}).strict(); +var JSONRPCMessageSchema = union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +var EmptyResultSchema = ResultSchema.strict(); +var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + requestId: RequestIdSchema.optional(), + reason: string2().optional() +}); +var CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +var IconSchema = object({ + src: string2(), + mimeType: string2().optional(), + sizes: array(string2()).optional(), + theme: _enum2(["light", "dark"]).optional() +}); +var IconsSchema = object({ icons: array(IconSchema).optional() }); +var BaseMetadataSchema = object({ + name: string2(), + title: string2().optional() +}); +var ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: string2(), + websiteUrl: string2().optional(), + description: string2().optional() +}); +var FormElicitationCapabilitySchema = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema); +var ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; +}, intersection(object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() +}), JSONObjectSchema.optional())); +var ClientTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() + }).optional() +}); +var ServerTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() +}); +var ClientCapabilitiesSchema = object({ + experimental: record(string2(), JSONObjectSchema).optional(), + sampling: object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: object({ listChanged: boolean2().optional() }).optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: record(string2(), JSONObjectSchema).optional() +}); +var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + protocolVersion: string2(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +var InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +var ServerCapabilitiesSchema = object({ + experimental: record(string2(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: object({ listChanged: boolean2().optional() }).optional(), + resources: object({ + subscribe: boolean2().optional(), + listChanged: boolean2().optional() + }).optional(), + tools: object({ listChanged: boolean2().optional() }).optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: record(string2(), JSONObjectSchema).optional() +}); +var InitializeResultSchema = ResultSchema.extend({ + protocolVersion: string2(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + instructions: string2().optional() +}); +var InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +var DiscoverRequestSchema = RequestSchema.extend({ + method: literal("server/discover"), + params: BaseRequestParamsSchema.optional() +}); +var DiscoverResultSchema = ResultSchema.extend({ + supportedVersions: array(string2()), + capabilities: ServerCapabilitiesSchema, + instructions: string2().optional() +}); +var PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +var ProgressSchema = object({ + progress: number2(), + total: optional(number2()), + message: optional(string2()) +}); +var ProgressNotificationParamsSchema = object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema +}); +var ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); +var PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); +var PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); +var ResourceContentsSchema = object({ + uri: string2(), + mimeType: optional(string2()), + _meta: record(string2(), unknown()).optional() +}); +var TextResourceContentsSchema = ResourceContentsSchema.extend({ text: string2() }); +var Base64Schema = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +var BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: Base64Schema }); +var RoleSchema = _enum2(["user", "assistant"]); +var AnnotationsSchema = object({ + audience: array(RoleSchema).optional(), + priority: number2().min(0).max(1).optional(), + lastModified: iso_exports.datetime({ offset: true }).optional() +}); +var ResourceSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: string2(), + description: optional(string2()), + mimeType: optional(string2()), + size: optional(number2()), + annotations: AnnotationsSchema.optional(), + _meta: optional(looseObject({})) +}); +var ResourceTemplateSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: string2(), + description: optional(string2()), + mimeType: optional(string2()), + annotations: AnnotationsSchema.optional(), + _meta: optional(looseObject({})) +}); +var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); +var ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: array(ResourceSchema) }); +var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); +var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); +var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: string2() }); +var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +var ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +var ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); +var ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +var SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +var UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +var SubscriptionFilterSchema = object({ + toolsListChanged: boolean2().optional(), + promptsListChanged: boolean2().optional(), + resourcesListChanged: boolean2().optional(), + resourceSubscriptions: array(string2()).optional() +}); +var SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +var SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: literal("subscriptions/listen"), + params: SubscriptionsListenRequestParamsSchema +}); +var SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +var SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/subscriptions/acknowledged"), + params: SubscriptionsAcknowledgedNotificationParamsSchema +}); +var SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); +var SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); +var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: string2() }); +var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +var PromptArgumentSchema = object({ + name: string2(), + description: optional(string2()), + required: optional(boolean2()) +}); +var PromptSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: optional(string2()), + arguments: optional(array(PromptArgumentSchema)), + _meta: optional(looseObject({})) +}); +var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); +var ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); +var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + name: string2(), + arguments: record(string2(), string2()).optional() +}); +var GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +var TextContentSchema = object({ + type: literal("text"), + text: string2(), + annotations: AnnotationsSchema.optional(), + _meta: record(string2(), unknown()).optional() +}); +var ImageContentSchema = object({ + type: literal("image"), + data: Base64Schema, + mimeType: string2(), + annotations: AnnotationsSchema.optional(), + _meta: record(string2(), unknown()).optional() +}); +var AudioContentSchema = object({ + type: literal("audio"), + data: Base64Schema, + mimeType: string2(), + annotations: AnnotationsSchema.optional(), + _meta: record(string2(), unknown()).optional() +}); +var ToolUseContentSchema = object({ + type: literal("tool_use"), + name: string2(), + id: string2(), + input: record(string2(), unknown()), + _meta: record(string2(), unknown()).optional() +}); +var EmbeddedResourceSchema = object({ + type: literal("resource"), + resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: record(string2(), unknown()).optional() +}); +var ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); +var ContentBlockSchema = union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +var PromptMessageSchema = object({ + role: RoleSchema, + content: ContentBlockSchema +}); +var GetPromptResultSchema = ResultSchema.extend({ + description: string2().optional(), + messages: array(PromptMessageSchema) +}); +var PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var ToolAnnotationsSchema = object({ + title: string2().optional(), + readOnlyHint: boolean2().optional(), + destructiveHint: boolean2().optional(), + idempotentHint: boolean2().optional(), + openWorldHint: boolean2().optional() +}); +var ToolExecutionSchema = object({ taskSupport: _enum2([ + "required", + "optional", + "forbidden" +]).optional() }); +var ToolSchema = object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: string2().optional(), + inputSchema: object({ + type: literal("object"), + properties: record(string2(), JSONValueSchema).optional(), + required: array(string2()).optional() + }).catchall(unknown()), + outputSchema: looseObject({ $schema: string2().optional() }).optional(), + annotations: ToolAnnotationsSchema.optional(), + execution: ToolExecutionSchema.optional(), + _meta: record(string2(), unknown()).optional() +}); +var ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); +var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); +var CallToolResultSchema = ResultSchema.extend({ + content: array(ContentBlockSchema).default([]), + structuredContent: unknown().optional(), + isError: boolean2().optional() +}); +var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); +var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + name: string2(), + arguments: record(string2(), unknown()).optional() +}); +var CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +var ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var ListChangedOptionsBaseSchema = object({ + autoRefresh: boolean2().default(true), + debounceMs: number2().int().nonnegative().default(300) +}); +var LoggingLevelSchema = _enum2([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); +var SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: string2().optional(), + data: unknown() +}); +var LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +var ModelHintSchema = object({ name: string2().optional() }); +var ModelPreferencesSchema = object({ + hints: array(ModelHintSchema).optional(), + costPriority: number2().min(0).max(1).optional(), + speedPriority: number2().min(0).max(1).optional(), + intelligencePriority: number2().min(0).max(1).optional() +}); +var ToolChoiceSchema = object({ mode: _enum2([ + "auto", + "required", + "none" +]).optional() }); +var ToolResultContentSchema = object({ + type: literal("tool_result"), + toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + content: array(ContentBlockSchema), + structuredContent: unknown().optional(), + isError: boolean2().optional(), + _meta: record(string2(), unknown()).optional() +}); +var SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema +]); +var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +var SamplingMessageSchema = object({ + role: RoleSchema, + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), + _meta: record(string2(), unknown()).optional() +}); +var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: string2().optional(), + includeContext: _enum2([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: number2().optional(), + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + metadata: JSONObjectSchema.optional(), + tools: array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() +}); +var CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +var CreateMessageResultSchema = ResultSchema.extend({ + model: string2(), + stopReason: optional(_enum2([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(string2())), + role: RoleSchema, + content: SamplingContentSchema +}); +var CreateMessageResultWithToolsSchema = ResultSchema.extend({ + model: string2(), + stopReason: optional(_enum2([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(string2())), + role: RoleSchema, + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) +}); +var BooleanSchemaSchema = object({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() +}); +var StringSchemaSchema = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum2([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: string2().optional() +}); +var NumberSchemaSchema = object({ + type: _enum2(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() +}); +var UntitledSingleSelectEnumSchemaSchema = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() +}); +var TitledSingleSelectEnumSchemaSchema = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object({ + const: string2(), + title: string2() + })), + default: string2().optional() +}); +var LegacyTitledEnumSchemaSchema = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() +}); +var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +var UntitledMultiSelectEnumSchemaSchema = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() +}); +var TitledMultiSelectEnumSchemaSchema = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ anyOf: array(object({ + const: string2(), + title: string2() + })) }), + default: array(string2()).optional() +}); +var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +var EnumSchemaSchema = union([ + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema +]); +var PrimitiveSchemaDefinitionSchema = union([ + EnumSchemaSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema +]); +var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + mode: literal("form").optional(), + message: string2(), + requestedSchema: object({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema), + required: array(string2()).optional() + }).catchall(unknown()) +}); +var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + mode: literal("url"), + message: string2(), + elicitationId: string2(), + url: string2().url() +}); +var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +var ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: string2() }); +var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +var ElicitResultSchema = ResultSchema.extend({ + action: _enum2([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([ + string2(), + number2(), + boolean2(), + array(string2()) + ])).optional()) +}); +var ResourceTemplateReferenceSchema = object({ + type: literal("ref/resource"), + uri: string2() +}); +var PromptReferenceSchema = object({ + type: literal("ref/prompt"), + name: string2() +}); +var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: object({ + name: string2(), + value: string2() + }), + context: object({ arguments: record(string2(), string2()).optional() }).optional() +}); +var CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +var CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + values: array(string2()).max(100), + total: optional(number2().int()), + hasMore: optional(boolean2()) +}) }); +var RootSchema = object({ + uri: string2().startsWith("file://"), + name: string2().optional(), + _meta: record(string2(), unknown()).optional() +}); +var ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +var ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); +var RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var TaskCreationParamsSchema = looseObject({ + ttl: number2().optional(), + pollInterval: number2().optional() +}); +var TaskStatusSchema = _enum2([ + "working", + "input_required", + "completed", + "failed", + "cancelled" +]); +var TaskSchema = object({ + taskId: string2(), + status: TaskStatusSchema, + ttl: union([number2(), _null3()]), + createdAt: string2(), + lastUpdatedAt: string2(), + pollInterval: optional(number2()), + statusMessage: optional(string2()) +}); +var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); +var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +var TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +var GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: string2() }) +}); +var GetTaskResultSchema = ResultSchema.merge(TaskSchema); +var GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: string2() }) +}); +var GetTaskPayloadResultSchema = ResultSchema.loose(); +var ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); +var ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: array(TaskSchema) }); +var CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: string2() }) +}); +var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +var ClientRequestSchema = union([ + PingRequestSchema, + InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); +var ClientNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); +var ClientResultSchema = union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema +]); +var ServerRequestSchema = union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema +]); +var ServerNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema +]); +var ServerResultSchema = union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema +]); +var SafeUrlSchema = url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url2) => { + const u = new URL(url2); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +var OAuthProtectedResourceMetadataSchema = looseObject({ + resource: string2().url(), + authorization_servers: array(SafeUrlSchema).optional(), + jwks_uri: string2().url().optional(), + scopes_supported: array(string2()).optional(), + bearer_methods_supported: array(string2()).optional(), + resource_signing_alg_values_supported: array(string2()).optional(), + resource_name: string2().optional(), + resource_documentation: string2().optional(), + resource_policy_uri: string2().url().optional(), + resource_tos_uri: string2().url().optional(), + tls_client_certificate_bound_access_tokens: boolean2().optional(), + authorization_details_types_supported: array(string2()).optional(), + dpop_signing_alg_values_supported: array(string2()).optional(), + dpop_bound_access_tokens_required: boolean2().optional() +}); +var OAuthMetadataSchema = looseObject({ + issuer: string2(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: array(string2()).optional(), + response_types_supported: array(string2()), + response_modes_supported: array(string2()).optional(), + grant_types_supported: array(string2()).optional(), + token_endpoint_auth_methods_supported: array(string2()).optional(), + token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: array(string2()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), + introspection_endpoint: string2().optional(), + introspection_endpoint_auth_methods_supported: array(string2()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), + code_challenge_methods_supported: array(string2()).optional(), + client_id_metadata_document_supported: boolean2().optional(), + authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0) +}); +var OpenIdProviderMetadataSchema = looseObject({ + issuer: string2(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: array(string2()).optional(), + response_types_supported: array(string2()), + response_modes_supported: array(string2()).optional(), + grant_types_supported: array(string2()).optional(), + acr_values_supported: array(string2()).optional(), + subject_types_supported: array(string2()), + id_token_signing_alg_values_supported: array(string2()), + id_token_encryption_alg_values_supported: array(string2()).optional(), + id_token_encryption_enc_values_supported: array(string2()).optional(), + userinfo_signing_alg_values_supported: array(string2()).optional(), + userinfo_encryption_alg_values_supported: array(string2()).optional(), + userinfo_encryption_enc_values_supported: array(string2()).optional(), + request_object_signing_alg_values_supported: array(string2()).optional(), + request_object_encryption_alg_values_supported: array(string2()).optional(), + request_object_encryption_enc_values_supported: array(string2()).optional(), + token_endpoint_auth_methods_supported: array(string2()).optional(), + token_endpoint_auth_signing_alg_values_supported: array(string2()).optional(), + display_values_supported: array(string2()).optional(), + claim_types_supported: array(string2()).optional(), + claims_supported: array(string2()).optional(), + service_documentation: string2().optional(), + claims_locales_supported: array(string2()).optional(), + ui_locales_supported: array(string2()).optional(), + claims_parameter_supported: boolean2().optional(), + request_parameter_supported: boolean2().optional(), + request_uri_parameter_supported: boolean2().optional(), + require_request_uri_registration: boolean2().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: boolean2().optional(), + authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0) +}); +var OpenIdProviderDiscoveryMetadataSchema = object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape +}); +var OAuthTokensSchema = object({ + access_token: string2(), + id_token: string2().optional(), + token_type: string2(), + expires_in: coerce_exports.number().optional(), + scope: string2().optional(), + refresh_token: string2().optional() +}).strip(); +var IdJagTokenExchangeResponseSchema = object({ + issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), + access_token: string2(), + token_type: string2().optional(), + expires_in: number2().optional(), + scope: string2().optional() +}).strip(); +var OAuthErrorResponseSchema = object({ + error: string2(), + error_description: string2().optional(), + error_uri: string2().optional() +}); +var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +var OAuthClientMetadataSchema = object({ + redirect_uris: array(SafeUrlSchema), + token_endpoint_auth_method: string2().optional(), + grant_types: array(string2()).optional(), + response_types: array(string2()).optional(), + application_type: string2().optional(), + client_name: string2().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: string2().optional(), + contacts: array(string2()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: string2().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: string2().optional(), + software_version: string2().optional(), + software_statement: string2().optional() +}).strip(); +var OAuthClientInformationSchema = object({ + client_id: string2(), + client_secret: string2().optional(), + client_id_issued_at: number2().optional(), + client_secret_expires_at: number2().optional() +}).strip(); +var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +var OAuthClientRegistrationErrorSchema = object({ + error: string2(), + error_description: string2().optional() +}).strip(); +var OAuthTokenRevocationRequestSchema = object({ + token: string2(), + token_type_hint: string2().optional() +}).strip(); + +// node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs +var BRANDS = /* @__PURE__ */ Symbol.for("mcp.sdk.errorBrands"); +function stampErrorBrands(instance, ctor) { + const brands = /* @__PURE__ */ new Set(); + let current = ctor; + while (typeof current === "function") { + const brand = current.mcpBrand; + if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); + current = Object.getPrototypeOf(current); + } + if (brands.size === 0) return; + Object.defineProperty(instance, BRANDS, { + value: brands, + enumerable: false, + configurable: true + }); +} +function brandedHasInstance(cls, value) { + try { + if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { + const carried = value[BRANDS]; + if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; + } + } catch { + } + return Function.prototype[Symbol.hasInstance].call(cls, value); +} +var OAuthError = class OAuthError2 extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, errorUri) { + super(message); + this.code = code; + this.errorUri = errorUri; + this.name = "OAuthError"; + stampErrorBrands(this, new.target); + } + /** + * Converts the error to a standard OAuth error response object. + */ + toResponseObject() { + const response = { + error: this.code, + error_description: this.message + }; + if (this.errorUri) response.error_uri = this.errorUri; + return response; + } + /** + * Creates an {@linkcode OAuthError} from an OAuth error response. + */ + static fromResponse(response) { + return new OAuthError2(response.error, response.error_description ?? response.error, response.error_uri); + } +}; +var SdkErrorCode = /* @__PURE__ */ (function(SdkErrorCode$1) { + SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; + SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; + SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; + SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; + SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; + SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; + SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; + SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; + SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; + SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; + SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; + SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; + SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; + SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; + SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; + SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; + SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; + SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; + SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; + return SdkErrorCode$1; +})({}); +var SdkError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "SdkError"; + stampErrorBrands(this, new.target); + } +}; +var SdkHttpError = class extends SdkError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); + } + constructor(code, message, data) { + super(code, message, data); + this.name = "SdkHttpError"; + } + get status() { + return this.data.status; + } + get statusText() { + return this.data.statusText; + } +}; +function isPlainObject$7(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function isImpliedCapabilityMember(capability, member, declaredValue) { + return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; +} +function requiredClientCapabilitiesForInputRequest(entry) { + switch (entry.method) { + case "elicitation/create": + if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; + return { elicitation: { form: {} } }; + case "sampling/createMessage": { + const params = entry.params; + if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; + return { sampling: {} }; + } + case "roots/list": + return { roots: {} }; + default: + return; + } +} +function missingClientCapabilities(required2, declared) { + const missing = {}; + for (const [capability, requirement] of Object.entries(required2)) { + if (requirement === void 0) continue; + const declaredValue = declared === void 0 ? void 0 : declared[capability]; + if (declaredValue === void 0) { + missing[capability] = requirement; + continue; + } + if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { + const missingMembers = {}; + for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; + if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; + } + } + return Object.keys(missing).length > 0 ? missing : void 0; +} +var FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; +function isModernProtocolVersion(version3) { + return version3 >= FIRST_MODERN_PROTOCOL_VERSION; +} +function legacyProtocolVersions(versions) { + return versions.filter((version3) => !isModernProtocolVersion(version3)); +} +function modernProtocolVersions(versions) { + return versions.filter((version3) => isModernProtocolVersion(version3)); +} +function appendTextFallbackForNonObject(result) { + const sc = result.structuredContent; + if (sc === void 0) return result; + if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; + if (result.content?.some((c) => c.type === "text") ?? false) return result; + return { + ...result, + content: [...result.content ?? [], { + type: "text", + text: JSON.stringify(sc) + }] + }; +} +var TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ + "task", + "inputRequests", + "requestState" +]; +function normalizeContentlessToolResult(value) { + if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; + return { + ...value, + content: [] + }; +} +function build$1() { + const JSONValueSchema$1 = lazy(() => union([ + string2(), + number2(), + boolean2(), + _null3(), + record(string2(), JSONValueSchema$1), + array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = record(string2(), JSONValueSchema$1); + const ProgressTokenSchema$1 = union([string2(), number2().int()]); + const CursorSchema$1 = string2(); + const TaskMetadataSchema$1 = object({ ttl: number2().optional() }); + const RelatedTaskMetadataSchema$1 = object({ taskId: string2() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const RequestSchema$1 = object({ + method: string2(), + params: BaseRequestParamsSchema$1.loose().optional() + }); + const NotificationsParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = object({ + method: string2(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); + const RequestIdSchema$1 = union([string2(), number2().int()]); + const EmptyResultSchema$1 = ResultSchema$1.strict(); + const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + requestId: RequestIdSchema$1.optional(), + reason: string2().optional() + }); + const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const IconSchema$1 = object({ + src: string2(), + mimeType: string2().optional(), + sizes: array(string2()).optional(), + theme: _enum2(["light", "dark"]).optional() + }); + const IconsSchema$1 = object({ icons: array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = object({ + name: string2(), + title: string2().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: string2(), + websiteUrl: string2().optional(), + description: string2().optional() + }); + const FormElicitationCapabilitySchema2 = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema2 = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(object({ + form: FormElicitationCapabilitySchema2.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + const ClientCapabilitiesSchema$1 = object({ + experimental: record(string2(), JSONObjectSchema$1).optional(), + sampling: object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema2.optional(), + roots: object({ listChanged: boolean2().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: record(string2(), JSONObjectSchema$1).optional() + }); + const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + protocolVersion: string2(), + capabilities: ClientCapabilitiesSchema$1, + clientInfo: ImplementationSchema$1 + }); + const InitializeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema$1 + }); + const ServerCapabilitiesSchema$1 = object({ + experimental: record(string2(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: object({ listChanged: boolean2().optional() }).optional(), + resources: object({ + subscribe: boolean2().optional(), + listChanged: boolean2().optional() + }).optional(), + tools: object({ listChanged: boolean2().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: record(string2(), JSONObjectSchema$1).optional() + }); + const InitializeResultSchema$1 = ResultSchema$1.extend({ + protocolVersion: string2(), + capabilities: ServerCapabilitiesSchema$1, + serverInfo: ImplementationSchema$1, + instructions: string2().optional() + }); + const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema$1.optional() + }); + const PingRequestSchema$1 = RequestSchema$1.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema$1.optional() + }); + const ProgressSchema$1 = object({ + progress: number2(), + total: optional(number2()), + message: optional(string2()) + }); + const ProgressNotificationParamsSchema$1 = object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); + const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); + const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); + const ResourceContentsSchema$1 = object({ + uri: string2(), + mimeType: optional(string2()), + _meta: record(string2(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: string2() }); + const Base64Schema2 = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema2 }); + const RoleSchema$1 = _enum2(["user", "assistant"]); + const AnnotationsSchema$1 = object({ + audience: array(RoleSchema$1).optional(), + priority: number2().min(0).max(1).optional(), + lastModified: iso_exports.datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: string2(), + description: optional(string2()), + mimeType: optional(string2()), + size: optional(number2()), + annotations: AnnotationsSchema$1.optional(), + _meta: optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: string2(), + description: optional(string2()), + mimeType: optional(string2()), + annotations: AnnotationsSchema$1.optional(), + _meta: optional(looseObject({})) + }); + const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); + const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: array(ResourceSchema$1) }); + const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); + const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: array(ResourceTemplateSchema$1) }); + const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: string2() }); + const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema$1 + }); + const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + const SubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema$1 + }); + const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema$1 + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: string2() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = object({ + name: string2(), + description: optional(string2()), + required: optional(boolean2()) + }); + const PromptSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: optional(string2()), + arguments: optional(array(PromptArgumentSchema$1)), + _meta: optional(looseObject({})) + }); + const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); + const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: array(PromptSchema$1) }); + const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + name: string2(), + arguments: record(string2(), string2()).optional() + }); + const GetPromptRequestSchema$1 = RequestSchema$1.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema$1 + }); + const TextContentSchema$1 = object({ + type: literal("text"), + text: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ImageContentSchema$1 = object({ + type: literal("image"), + data: Base64Schema2, + mimeType: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const AudioContentSchema$1 = object({ + type: literal("audio"), + data: Base64Schema2, + mimeType: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ToolUseContentSchema$1 = object({ + type: literal("tool_use"), + name: string2(), + id: string2(), + input: record(string2(), unknown()), + _meta: record(string2(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = object({ + type: literal("resource"), + resource: union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const GetPromptResultSchema$1 = ResultSchema$1.extend({ + description: string2().optional(), + messages: array(PromptMessageSchema$1) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ToolAnnotationsSchema$1 = object({ + title: string2().optional(), + readOnlyHint: boolean2().optional(), + destructiveHint: boolean2().optional(), + idempotentHint: boolean2().optional(), + openWorldHint: boolean2().optional() + }); + const ToolExecutionSchema$1 = object({ taskSupport: _enum2([ + "required", + "optional", + "forbidden" + ]).optional() }); + const ToolSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: string2().optional(), + inputSchema: object({ + type: literal("object"), + properties: record(string2(), JSONValueSchema$1).optional(), + required: array(string2()).optional() + }).catchall(unknown()), + outputSchema: object({ + type: literal("object"), + properties: record(string2(), JSONValueSchema$1).optional(), + required: array(string2()).optional() + }).catchall(unknown()).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); + const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: array(ToolSchema$1) }); + const CallToolResultSchema$1 = ResultSchema$1.extend({ + content: array(ContentBlockSchema$1), + structuredContent: record(string2(), unknown()).optional(), + isError: boolean2().optional() + }); + const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + name: string2(), + arguments: record(string2(), unknown()).optional() + }); + const CallToolRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema$1 + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const LoggingLevelSchema$1 = _enum2([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); + const SetLevelRequestSchema$1 = RequestSchema$1.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: string2().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ModelHintSchema$1 = object({ name: string2().optional() }); + const ModelPreferencesSchema$1 = object({ + hints: array(ModelHintSchema$1).optional(), + costPriority: number2().min(0).max(1).optional(), + speedPriority: number2().min(0).max(1).optional(), + intelligencePriority: number2().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = object({ mode: _enum2([ + "auto", + "required", + "none" + ]).optional() }); + const ToolResultContentSchema$1 = object({ + type: literal("tool_result"), + toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + content: array(ContentBlockSchema$1), + structuredContent: object({}).loose().optional(), + isError: boolean2().optional(), + _meta: record(string2(), unknown()).optional() + }); + const SamplingContentSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1 + ]); + const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + const SamplingMessageSchema$1 = object({ + role: RoleSchema$1, + content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]), + _meta: record(string2(), unknown()).optional() + }); + const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + messages: array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: string2().optional(), + includeContext: _enum2([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: number2().optional(), + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + const CreateMessageResultSchema$1 = ResultSchema$1.extend({ + model: string2(), + stopReason: optional(_enum2([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(string2())), + role: RoleSchema$1, + content: SamplingContentSchema$1 + }); + const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ + model: string2(), + stopReason: optional(_enum2([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(string2())), + role: RoleSchema$1, + content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]) + }); + const BooleanSchemaSchema$1 = object({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() + }); + const StringSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum2([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: string2().optional() + }); + const NumberSchemaSchema$1 = object({ + type: _enum2(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object({ + const: string2(), + title: string2() + })), + default: string2().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() + }); + const SingleSelectEnumSchemaSchema$1 = union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ anyOf: array(object({ + const: string2(), + title: string2() + })) }), + default: array(string2()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: string2(), + requestedSchema: object({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema$1), + required: array(string2()).optional() + }).catchall(unknown()) + }); + const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("url"), + message: string2(), + elicitationId: string2(), + url: string2().url() + }); + const ElicitRequestParamsSchema$1 = union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + const ElicitRequestSchema$1 = RequestSchema$1.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: string2() }); + const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema$1 + }); + const ElicitResultSchema$1 = ResultSchema$1.extend({ + action: _enum2([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([ + string2(), + number2(), + boolean2(), + array(string2()) + ])).optional()) + }); + const ResourceTemplateReferenceSchema$1 = object({ + type: literal("ref/resource"), + uri: string2() + }); + const PromptReferenceSchema$1 = object({ + type: literal("ref/prompt"), + name: string2() + }); + const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + ref: union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: object({ + name: string2(), + value: string2() + }), + context: object({ arguments: record(string2(), string2()).optional() }).optional() + }); + const CompleteRequestSchema$1 = RequestSchema$1.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema$1 + }); + const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ + values: array(string2()).max(100), + total: optional(number2().int()), + hasMore: optional(boolean2()) + }) }); + const RootSchema$1 = object({ + uri: string2().startsWith("file://"), + name: string2().optional(), + _meta: record(string2(), unknown()).optional() + }); + const ListRootsRequestSchema$1 = RequestSchema$1.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema$1.optional() + }); + const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: array(RootSchema$1) }); + const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TaskCreationParamsSchema$1 = looseObject({ + ttl: number2().optional(), + pollInterval: number2().optional() + }); + const TaskStatusSchema$1 = _enum2([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + const TaskSchema$1 = object({ + taskId: string2(), + status: TaskStatusSchema$1, + ttl: union([number2(), _null3()]), + createdAt: string2(), + lastUpdatedAt: string2(), + pollInterval: optional(number2()), + statusMessage: optional(string2()) + }); + const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); + const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); + const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema$1 + }); + const GetTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) + }); + const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); + const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) + }); + const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); + const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); + const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: array(TaskSchema$1) }); + const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema$1.extend({ taskId: string2() }) + }); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + RequestSchema: RequestSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + ResultSchema: ResultSchema$1, + RequestIdSchema: RequestIdSchema$1, + EmptyResultSchema: EmptyResultSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, + InitializeRequestSchema: InitializeRequestSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + InitializeResultSchema: InitializeResultSchema$1, + InitializedNotificationSchema: InitializedNotificationSchema$1, + PingRequestSchema: PingRequestSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, + PaginatedRequestSchema: PaginatedRequestSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + RoleSchema: RoleSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, + ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, + SubscribeRequestSchema: SubscribeRequestSchema$1, + UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, + UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolExecutionSchema: ToolExecutionSchema$1, + ToolSchema: ToolSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, + CallToolRequestSchema: CallToolRequestSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, + SetLevelRequestSchema: SetLevelRequestSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingContentSchema: SamplingContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, + ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + RootSchema: RootSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, + TaskCreationParamsSchema: TaskCreationParamsSchema$1, + TaskStatusSchema: TaskStatusSchema$1, + TaskSchema: TaskSchema$1, + CreateTaskResultSchema: CreateTaskResultSchema$1, + TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, + TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, + GetTaskRequestSchema: GetTaskRequestSchema$1, + GetTaskResultSchema: GetTaskResultSchema$1, + GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, + GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, + ListTasksRequestSchema: ListTasksRequestSchema$1, + ListTasksResultSchema: ListTasksResultSchema$1, + CancelTaskRequestSchema: CancelTaskRequestSchema$1, + CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), + ClientRequestSchema: union([ + PingRequestSchema$1, + InitializeRequestSchema$1, + CompleteRequestSchema$1, + SetLevelRequestSchema$1, + GetPromptRequestSchema$1, + ListPromptsRequestSchema$1, + ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema$1, + SubscribeRequestSchema$1, + UnsubscribeRequestSchema$1, + CallToolRequestSchema$1, + ListToolsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ClientNotificationSchema: union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + InitializedNotificationSchema$1, + RootsListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1 + ]), + ClientResultSchema: union([ + EmptyResultSchema$1, + CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema$1, + ElicitResultSchema$1, + ListRootsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + ServerRequestSchema: union([ + PingRequestSchema$1, + CreateMessageRequestSchema$1, + ElicitRequestSchema$1, + ListRootsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ServerNotificationSchema: union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + LoggingMessageNotificationSchema$1, + ResourceUpdatedNotificationSchema$1, + ResourceListChangedNotificationSchema$1, + ToolListChangedNotificationSchema$1, + PromptListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1, + ElicitationCompleteNotificationSchema$1 + ]), + ServerResultSchema: union([ + EmptyResultSchema$1, + InitializeResultSchema$1, + CompleteResultSchema$1, + GetPromptResultSchema$1, + ListPromptsResultSchema$1, + ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema$1, + CallToolResultSchema$1, + ListToolsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + CallToolResultWireSchema: unknown().superRefine((value, ctx) => { + if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; + for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { + ctx.addIssue({ + code: "custom", + message: `content is required when the body carries '${key}' \u2014 another result family cannot default into an empty tools/call success` + }); + return; + } + }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) + }; +} +var memo$1; +function buildSchemas2025() { + return memo$1 ??= build$1(); +} +function isNonObjectJsonSchemaRoot(json2) { + return json2["type"] !== "object"; +} +var REF_REWRITE_DATA_POSITION_KEYS = /* @__PURE__ */ new Set([ + "const", + "enum", + "default", + "examples" +]); +var REF_REWRITE_NAME_MAP_KEYS = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + "dependencies" +]); +function establishesNewBase(id4) { + return id4 !== void 0 && !(typeof id4 === "string" && id4.startsWith("#")); +} +function wrapOutputSchemaForLegacy(natural) { + const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; + if (establishesNewBase(natural["$id"])) return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: natural }, + required: ["result"] + }; + const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; + const rewriteRefs = (node, parentIsNameMap) => { + if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); + if (node === null || typeof node !== "object") return node; + if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; + const out = {}; + let convertedRecursion = false; + for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); + else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; + else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; + else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; + else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); + else out[k] = rewriteRefs(v, false); + if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; + else out["$ref"] = "#/properties/result"; + return out; + }; + return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: rewriteRefs(natural, false) }, + required: ["result"] + }; +} +var requestMethodKeys$1 = { + ping: null, + initialize: null, + "completion/complete": null, + "logging/setLevel": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "resources/subscribe": null, + "resources/unsubscribe": null, + "tools/call": null, + "tools/list": null, + "tasks/get": null, + "tasks/result": null, + "tasks/list": null, + "tasks/cancel": null, + "sampling/createMessage": null, + "elicitation/create": null, + "roots/list": null +}; +var notificationMethodKeys$1 = { + "notifications/cancelled": null, + "notifications/progress": null, + "notifications/initialized": null, + "notifications/roots/list_changed": null, + "notifications/tasks/status": null, + "notifications/message": null, + "notifications/resources/updated": null, + "notifications/resources/list_changed": null, + "notifications/tools/list_changed": null, + "notifications/prompts/list_changed": null, + "notifications/elicitation/complete": null +}; +var resultMethodKeys = { + ping: null, + initialize: null, + "completion/complete": null, + "logging/setLevel": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "resources/subscribe": null, + "resources/unsubscribe": null, + "tools/call": null, + "tools/list": null, + "sampling/createMessage": null, + "elicitation/create": null, + "roots/list": null +}; +var maps$1; +function registryMaps() { + if (maps$1) return maps$1; + const s = buildSchemas2025(); + maps$1 = { + requestSchemas: { + ping: s.PingRequestSchema, + initialize: s.InitializeRequestSchema, + "completion/complete": s.CompleteRequestSchema, + "logging/setLevel": s.SetLevelRequestSchema, + "prompts/get": s.GetPromptRequestSchema, + "prompts/list": s.ListPromptsRequestSchema, + "resources/list": s.ListResourcesRequestSchema, + "resources/templates/list": s.ListResourceTemplatesRequestSchema, + "resources/read": s.ReadResourceRequestSchema, + "resources/subscribe": s.SubscribeRequestSchema, + "resources/unsubscribe": s.UnsubscribeRequestSchema, + "tools/call": s.CallToolRequestSchema, + "tools/list": s.ListToolsRequestSchema, + "tasks/get": s.GetTaskRequestSchema, + "tasks/result": s.GetTaskPayloadRequestSchema, + "tasks/list": s.ListTasksRequestSchema, + "tasks/cancel": s.CancelTaskRequestSchema, + "sampling/createMessage": s.CreateMessageRequestSchema, + "elicitation/create": s.ElicitRequestSchema, + "roots/list": s.ListRootsRequestSchema + }, + notificationSchemas: { + "notifications/cancelled": s.CancelledNotificationSchema, + "notifications/progress": s.ProgressNotificationSchema, + "notifications/initialized": s.InitializedNotificationSchema, + "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, + "notifications/tasks/status": s.TaskStatusNotificationSchema, + "notifications/message": s.LoggingMessageNotificationSchema, + "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, + "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, + "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, + "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, + "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s.EmptyResultSchema, + initialize: s.InitializeResultSchema, + "completion/complete": s.CompleteResultSchema, + "logging/setLevel": s.EmptyResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "resources/subscribe": s.EmptyResultSchema, + "resources/unsubscribe": s.EmptyResultSchema, + "tools/call": s.CallToolResultWireSchema, + "tools/list": s.ListToolsResultSchema, + "sampling/createMessage": s.CreateMessageResultWithToolsSchema, + "elicitation/create": s.ElicitResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps$1; +} +function hasRequestMethod2025(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); +} +function hasNotificationMethod2025(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); +} +function hasResultMethod(method) { + return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); +} +function getResultSchema(method) { + return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; +} +function getRequestSchema(method) { + return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; +} +function getNotificationSchema(method) { + return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; +} +var rev2025RequestMethods = Object.keys(requestMethodKeys$1); +var rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); +function isPlainObject$6(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function triState$1(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +var NOT_IN_ERA$1 = { + ok: false, + reason: "not-in-era" +}; +function toolNeedsLegacyWrap(t) { + return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); +} +function toNeutralResult(value) { + return value; +} +var rev2025Codec = { + era: "2025-11-25", + hasRequestMethod: hasRequestMethod2025, + hasNotificationMethod: hasNotificationMethod2025, + validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), + validateResult: (method, raw) => triState$1(getResultSchema(method), raw), + validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), + hasInputRequestMethod: () => false, + validateInputRequest: () => NOT_IN_ERA$1, + validateInputResponse: () => NOT_IN_ERA$1, + samplingResultVariant: ((hasTools, raw) => { + const s = buildSchemas2025(); + return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); + }), + outboundEnvelope: (_material) => void 0, + validateEnvelopeMeta: (_meta) => [], + projectCallToolResult(result, advertisedOutputSchema) { + const withText = appendTextFallbackForNonObject(result); + const sc = withText.structuredContent; + if (sc === void 0) return withText; + const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); + const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); + if (!valueIsNonObject && !schemaWrapped) return withText; + return { + ...withText, + structuredContent: { result: sc } + }; + }, + decodeResult(_method, raw) { + if (isPlainObject$6(raw) && "resultType" in raw) { + const stripped = { ...raw }; + delete stripped["resultType"]; + return { + kind: "complete", + result: toNeutralResult(stripped) + }; + } + return { + kind: "complete", + result: toNeutralResult(raw) + }; + }, + encodeResult(method, result) { + if (method !== "tools/list") return result; + const tools = result.tools; + if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; + return { + ...result, + tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { + ...t, + outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) + } : t) + }; + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope: (_material) => void 0 +}; +function build() { + const JSONValueSchema$1 = lazy(() => union([ + string2(), + number2(), + boolean2(), + _null3(), + record(string2(), JSONValueSchema$1), + array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = record(string2(), JSONValueSchema$1); + const ProgressTokenSchema$1 = union([string2(), number2().int()]); + const CursorSchema$1 = string2(); + const RequestIdSchema$1 = union([string2(), number2().int()]); + const RoleSchema$1 = _enum2(["user", "assistant"]); + const LoggingLevelSchema$1 = _enum2([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + const Base64Schema2 = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const TaskMetadataSchema$1 = object({ ttl: number2().optional() }); + const RelatedTaskMetadataSchema$1 = object({ taskId: string2() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const NotificationsParamsSchema$1 = object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = object({ + method: string2(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const IconSchema$1 = object({ + src: string2(), + mimeType: string2().optional(), + sizes: array(string2()).optional(), + theme: _enum2(["light", "dark"]).optional() + }); + const IconsSchema$1 = object({ icons: array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = object({ + name: string2(), + title: string2().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: string2(), + websiteUrl: string2().optional(), + description: string2().optional() + }); + const FormElicitationCapabilitySchema2 = intersection(object({ applyDefaults: boolean2().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema2 = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(object({ + form: FormElicitationCapabilitySchema2.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + const ClientCapabilitiesSchema$1 = object({ + experimental: record(string2(), JSONObjectSchema$1).optional(), + sampling: object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema2.optional(), + roots: object({ listChanged: boolean2().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: record(string2(), JSONObjectSchema$1).optional() + }); + const ServerCapabilitiesSchema$1 = object({ + experimental: record(string2(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: object({ listChanged: boolean2().optional() }).optional(), + resources: object({ + subscribe: boolean2().optional(), + listChanged: boolean2().optional() + }).optional(), + tools: object({ listChanged: boolean2().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: record(string2(), JSONObjectSchema$1).optional() + }); + const ProgressSchema$1 = object({ + progress: number2(), + total: optional(number2()), + message: optional(string2()) + }); + const ProgressNotificationParamsSchema$1 = object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: string2().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ResourceContentsSchema$1 = object({ + uri: string2(), + mimeType: optional(string2()), + _meta: record(string2(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: string2() }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema2 }); + const AnnotationsSchema$1 = object({ + audience: array(RoleSchema$1).optional(), + priority: number2().min(0).max(1).optional(), + lastModified: iso_exports.datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: string2(), + description: optional(string2()), + mimeType: optional(string2()), + size: optional(number2()), + annotations: AnnotationsSchema$1.optional(), + _meta: optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: string2(), + description: optional(string2()), + mimeType: optional(string2()), + annotations: AnnotationsSchema$1.optional(), + _meta: optional(looseObject({})) + }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: string2() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = object({ + name: string2(), + description: optional(string2()), + required: optional(boolean2()) + }); + const PromptSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: optional(string2()), + arguments: optional(array(PromptArgumentSchema$1)), + _meta: optional(looseObject({})) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TextContentSchema$1 = object({ + type: literal("text"), + text: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ImageContentSchema$1 = object({ + type: literal("image"), + data: Base64Schema2, + mimeType: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const AudioContentSchema$1 = object({ + type: literal("audio"), + data: Base64Schema2, + mimeType: string2(), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ToolUseContentSchema$1 = object({ + type: literal("tool_use"), + name: string2(), + id: string2(), + input: record(string2(), unknown()), + _meta: record(string2(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = object({ + type: literal("resource"), + resource: union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const ToolAnnotationsSchema$1 = object({ + title: string2().optional(), + readOnlyHint: boolean2().optional(), + destructiveHint: boolean2().optional(), + idempotentHint: boolean2().optional(), + openWorldHint: boolean2().optional() + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ModelHintSchema$1 = object({ name: string2().optional() }); + const ModelPreferencesSchema$1 = object({ + hints: array(ModelHintSchema$1).optional(), + costPriority: number2().min(0).max(1).optional(), + speedPriority: number2().min(0).max(1).optional(), + intelligencePriority: number2().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = object({ mode: _enum2([ + "auto", + "required", + "none" + ]).optional() }); + const BooleanSchemaSchema$1 = object({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() + }); + const StringSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum2([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: string2().optional() + }); + const NumberSchemaSchema$1 = object({ + type: _enum2(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object({ + const: string2(), + title: string2() + })), + default: string2().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = object({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() + }); + const SingleSelectEnumSchemaSchema$1 = union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = object({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object({ anyOf: array(object({ + const: string2(), + title: string2() + })) }), + default: array(string2()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: string2(), + requestedSchema: object({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema$1), + required: array(string2()).optional() + }).catchall(unknown()) + }); + const ResourceTemplateReferenceSchema$1 = object({ + type: literal("ref/resource"), + uri: string2() + }); + const PromptReferenceSchema$1 = object({ + type: literal("ref/prompt"), + name: string2() + }); + const RootSchema$1 = object({ + uri: string2().startsWith("file://"), + name: string2().optional(), + _meta: record(string2(), unknown()).optional() + }); + const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; + const ClientCapabilities2026Schema = object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; + const ServerCapabilities2026Schema = object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + const RequestMetaEnvelopeSchema = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + [PROTOCOL_VERSION_META_KEY]: string2(), + [CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), + [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() + }); + const ToolSchema$1 = object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: string2().optional(), + inputSchema: looseObject({ + $schema: string2().optional(), + type: literal("object") + }), + outputSchema: looseObject({ $schema: string2().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + _meta: record(string2(), unknown()).optional() + }); + const ToolResultContentSchema$1 = object({ + type: literal("tool_result"), + toolUseId: string2(), + content: array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: boolean2().optional(), + _meta: record(string2(), unknown()).optional() + }); + const SamplingMessageContentBlockSchema$1 = union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + const SamplingMessageSchema$1 = object({ + role: RoleSchema$1, + content: union([SamplingMessageContentBlockSchema$1, array(SamplingMessageContentBlockSchema$1)]), + _meta: record(string2(), unknown()).optional() + }); + const ResultTypeSchema = string2(); + const ResultMetaSchema = looseObject({ [SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); + const wireMeta = ResultMetaSchema.optional(); + function wireResult2(shape) { + return looseObject({ + _meta: wireMeta, + resultType: ResultTypeSchema.default("complete"), + ...shape + }); + } + const ResultSchema$1 = wireResult2({}); + const PaginatedResultSchema$1 = wireResult2({ nextCursor: CursorSchema$1.optional() }); + const CallToolResultSchema$1 = wireResult2({ + content: array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: boolean2().optional() + }); + const ListToolsResultSchema$1 = wireResult2({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + tools: array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult2({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + prompts: array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const GetPromptResultSchema$1 = wireResult2({ + description: string2().optional(), + messages: array(PromptMessageSchema$1) + }); + const ListResourcesResultSchema$1 = wireResult2({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + resources: array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListResourceTemplatesResultSchema$1 = wireResult2({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + resourceTemplates: array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ReadResourceResultSchema$1 = wireResult2({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }); + const CompleteResultSchema$1 = wireResult2({ completion: object({ + values: array(string2()).max(100), + total: number2().int().optional(), + hasMore: boolean2().optional() + }).loose() }); + const CacheableResultSchema = wireResult2({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]) + }); + const DiscoverResultSchema$1 = wireResult2({ + ttlMs: number2().int().min(0).catch(0), + cacheScope: _enum2(["public", "private"]).catch("private"), + supportedVersions: array(string2()), + capabilities: ServerCapabilities2026Schema, + instructions: string2().optional() + }); + const CreateMessageRequestParamsSchema$1 = object({ + messages: array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: string2().optional(), + includeContext: _enum2([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: number2().optional(), + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + const CreateMessageRequestSchema$1 = object({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + const ListRootsRequestSchema$1 = object({ + method: literal("roots/list"), + params: object({ _meta: record(string2(), unknown()).optional() }).optional() + }); + const CreateMessageResultSchema$1 = object({ + ...SamplingMessageSchema$1.shape, + model: string2(), + stopReason: string2().optional() + }); + const ListRootsResultSchema$1 = object({ roots: array(RootSchema$1) }); + const ElicitResultSchema$1 = object({ + action: _enum2([ + "accept", + "decline", + "cancel" + ]), + content: record(string2(), union([ + string2(), + number2(), + boolean2(), + array(string2()) + ])).optional() + }); + const ElicitRequestURLParamsSchema$1 = object({ + mode: literal("url"), + message: string2(), + url: string2().url() + }); + const ElicitRequestParamsSchema$1 = union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + const ElicitRequestSchema$1 = object({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + const InputRequestSchema = union([ + CreateMessageRequestSchema$1, + ListRootsRequestSchema$1, + ElicitRequestSchema$1 + ]); + const InputResponseSchema = union([ + CreateMessageResultSchema$1, + ListRootsResultSchema$1, + ElicitResultSchema$1 + ]); + const InputRequestsSchema = record(string2(), InputRequestSchema); + const InputResponsesSchema = record(string2(), InputResponseSchema); + const InputRequiredResultSchema = wireResult2({ + inputRequests: InputRequestsSchema.optional(), + requestState: string2().optional() + }); + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: string2().optional() + }; + const InputResponseRequestParamsSchema = object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); + function wireRequest(method, paramsShape) { + return object({ + method: literal(method), + params: object({ + _meta: RequestMetaEnvelopeSchema, + ...paramsShape + }) + }); + } + function dispatchRequest(method, paramsShape) { + return object({ + method: literal(method), + params: object({ + _meta: DispatchRequestMetaSchema.optional(), + ...paramsShape + }).optional() + }); + } + const callToolParamsShape = { + name: string2(), + arguments: record(string2(), unknown()).optional(), + ...retryParamsShape + }; + const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; + const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); + const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); + const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); + const GetPromptRequestSchema$1 = wireRequest("prompts/get", { + name: string2(), + arguments: record(string2(), string2()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); + const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); + const ReadResourceRequestSchema$1 = wireRequest("resources/read", { + uri: string2(), + ...retryParamsShape + }); + const completeParamsShape = { + ref: union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: object({ + name: string2(), + value: string2() + }), + context: object({ arguments: record(string2(), string2()).optional() }).optional() + }; + const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); + const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); + const SubscriptionFilterSchema$1 = object({ + toolsListChanged: boolean2().optional(), + promptsListChanged: boolean2().optional(), + resourcesListChanged: boolean2().optional(), + resourceSubscriptions: array(string2()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; + const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); + const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); + const SubscriptionsListenResultSchema$1 = looseObject({ + _meta: SubscriptionsListenResultMetaSchema$1, + resultType: ResultTypeSchema.default("complete") + }); + const dispatchRequestSchemas = { + "tools/call": dispatchRequest("tools/call", callToolParamsShape), + "tools/list": dispatchRequest("tools/list", paginatedParamsShape), + "prompts/get": dispatchRequest("prompts/get", { + name: string2(), + arguments: record(string2(), string2()).optional() + }), + "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), + "resources/list": dispatchRequest("resources/list", paginatedParamsShape), + "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), + "resources/read": dispatchRequest("resources/read", { uri: string2() }), + "completion/complete": dispatchRequest("completion/complete", completeParamsShape), + "server/discover": dispatchRequest("server/discover", {}), + "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) + }; + function liftedResult(shape) { + return looseObject({ + _meta: wireMeta, + ...shape + }); + } + const dispatchResultSchemas = { + "tools/call": liftedResult({ + content: array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: boolean2().optional() + }), + "tools/list": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + tools: array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ + description: string2().optional(), + messages: array(PromptMessageSchema$1) + }), + "prompts/list": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + prompts: array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/list": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + resources: array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/templates/list": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + resourceTemplates: array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/read": liftedResult({ + ttlMs: number2().int().min(0), + cacheScope: _enum2(["public", "private"]), + contents: array(union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }), + "completion/complete": liftedResult({ completion: object({ + values: array(string2()).max(100), + total: number2().int().optional(), + hasMore: boolean2().optional() + }).loose() }), + "server/discover": liftedResult({ + ttlMs: number2().int().min(0).catch(0), + cacheScope: _enum2(["public", "private"]).catch("private"), + supportedVersions: array(string2()), + capabilities: ServerCapabilities2026Schema, + instructions: string2().optional() + }), + "subscriptions/listen": liftedResult({}) + }; + const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); + const SubscriptionsAcknowledgedNotificationSchema$1 = object({ + method: literal("notifications/subscriptions/acknowledged"), + params: object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema$1 + }) + }); + const CancelledNotificationParamsSchema$1 = object({ + _meta: NotificationMetaSchema.optional(), + requestId: RequestIdSchema$1, + reason: string2().optional() + }); + const CancelledNotificationSchema$1 = object({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const notificationSchemas2026 = { + "notifications/cancelled": CancelledNotificationSchema$1, + "notifications/progress": ProgressNotificationSchema$1, + "notifications/message": LoggingMessageNotificationSchema$1, + "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, + "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, + "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, + "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, + "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 + }; + const wireResultResponse = (result) => object({ + jsonrpc: literal("2.0"), + id: union([string2(), number2().int()]), + result + }).strict(); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + RequestIdSchema: RequestIdSchema$1, + RoleSchema: RoleSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + RootSchema: RootSchema$1, + ClientCapabilities2026Schema, + ServerCapabilities2026Schema, + RequestMetaEnvelopeSchema, + ToolSchema: ToolSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + ResultTypeSchema, + ResultMetaSchema, + ResultSchema: ResultSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + CacheableResultSchema, + DiscoverResultSchema: DiscoverResultSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + InputRequestSchema, + InputResponseSchema, + InputRequestsSchema, + InputResponsesSchema, + InputRequiredResultSchema, + InputResponseRequestParamsSchema, + CallToolRequestSchema: CallToolRequestSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + DiscoverRequestSchema: DiscoverRequestSchema$1, + SubscriptionFilterSchema: SubscriptionFilterSchema$1, + SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, + SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, + SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, + dispatchRequestSchemas, + dispatchResultSchemas, + NotificationMetaSchema, + SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + notificationSchemas2026, + JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), + CallToolResultResponseSchema: wireResultResponse(union([CallToolResultSchema$1, InputRequiredResultSchema])), + ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), + ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), + GetPromptResultResponseSchema: wireResultResponse(union([GetPromptResultSchema$1, InputRequiredResultSchema])), + ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), + ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), + ReadResourceResultResponseSchema: wireResultResponse(union([ReadResourceResultSchema$1, InputRequiredResultSchema])), + CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), + DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) + }; +} +var memo; +function buildSchemas2026() { + return memo ??= build(); +} +var CACHEABLE_RESULT_METHODS = [ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "resources/read", + "server/discover" +]; +function isCacheableResultMethod(method) { + return CACHEABLE_RESULT_METHODS.includes(method); +} +var RESULT_CACHE_HINT_FALLBACK = /* @__PURE__ */ Symbol("modelcontextprotocol.resultCacheHintFallback"); +function attachCacheHintFallback(result, hint) { + if (hint === void 0) return result; + const attached = result[RESULT_CACHE_HINT_FALLBACK]; + if (attached === void 0) return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: hint + }; + const merged = {}; + const ttlMs = attached.ttlMs ?? hint.ttlMs; + if (ttlMs !== void 0) merged.ttlMs = ttlMs; + const cacheScope = attached.cacheScope ?? hint.cacheScope; + if (cacheScope !== void 0) merged.cacheScope = cacheScope; + return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: merged + }; +} +function cacheHintFallbackOf(result) { + return result[RESULT_CACHE_HINT_FALLBACK]; +} +function isValidCacheTtlMs(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +function isValidCacheScope(value) { + return value === "public" || value === "private"; +} +function assertValidCacheHint(hint, context) { + if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); + if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); +} +var ProtocolErrorCode = /* @__PURE__ */ (function(ProtocolErrorCode$1) { + ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; + ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + return ProtocolErrorCode$1; +})({}); +var ProtocolError = class ProtocolError2 extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "ProtocolError"; + stampErrorBrands(this, new.target); + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); + } + if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data; + if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new UnsupportedProtocolVersionError({ + supported: errorData.supported, + requested: errorData.requested + }, message); + } + if (code === ProtocolErrorCode.InvalidParams || code === ProtocolErrorCode.ResourceNotFound) { + const errorData = data; + if (typeof errorData?.uri === "string" && (code === ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); + } + if (code === ProtocolErrorCode.MissingRequiredClientCapability && data) { + const errorData = data; + if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); + } + return new ProtocolError2(code, message, data); + } +}; +var ResourceNotFoundError = class extends ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); + } + constructor(uri, message = `Resource not found: ${uri}`) { + super(ProtocolErrorCode.InvalidParams, message, { uri }); + } + /** The URI that was requested and not found. */ + get uri() { + return this.data.uri; + } +}; +var UrlElicitationRequiredError = class extends ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); + } + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; +var UnsupportedProtocolVersionError = class extends ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); + } + constructor(data, message = `Unsupported protocol version: ${data.requested}`) { + super(ProtocolErrorCode.UnsupportedProtocolVersion, message, data); + } + /** + * Protocol versions the receiver supports. + */ + get supported() { + return this.data.supported; + } + /** + * The protocol version that was requested. + */ + get requested() { + return this.data.requested; + } +}; +var MissingRequiredClientCapabilityError = class extends ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); + } + constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { + super(ProtocolErrorCode.MissingRequiredClientCapability, message, data); + } + /** + * The capabilities the server requires from the client to process the + * request (only the missing capabilities are listed). + */ + get requiredCapabilities() { + return this.data.requiredCapabilities; + } +}; +var DEFAULT_CACHE_TTL_MS = 0; +var DEFAULT_CACHE_SCOPE = "private"; +var EXTENDED_RESULT_TYPE_METHODS = [ + "tools/call", + "prompts/get", + "resources/read" +]; +function stampResultType(method, result) { + const provided = result["resultType"]; + if (provided === void 0) return { + ...result, + resultType: "complete" + }; + if (provided === "complete") return result; + if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; + throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); +} +function fillCacheFields(method, result) { + const fallback = cacheHintFallbackOf(result); + if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); + const provided = result; + const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); + const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); + const filled = { + ...provided, + ttlMs, + cacheScope + }; + delete filled[RESULT_CACHE_HINT_FALLBACK]; + return filled; +} +function isPlainObject$5(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function stampServerInfoMeta(result, serverInfo) { + if (serverInfo === void 0) return result; + const meta3 = result["_meta"]; + if (meta3 === void 0) return { + ...result, + _meta: { [SERVER_INFO_META_KEY]: serverInfo } + }; + if (!isPlainObject$5(meta3)) return result; + if (meta3[SERVER_INFO_META_KEY] !== void 0) return result; + return { + ...result, + _meta: { + ...meta3, + [SERVER_INFO_META_KEY]: serverInfo + } + }; +} +function resolveTtlMs(fallback) { + return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; +} +function resolveCacheScope(fallback) { + return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; +} +function stripCacheHintFallback(result) { + const copy2 = { ...result }; + delete copy2[RESULT_CACHE_HINT_FALLBACK]; + return copy2; +} +var INPUT_REQUEST_METHODS_2026 = [ + "elicitation/create", + "sampling/createMessage", + "roots/list" +]; +var maps; +function inputSchemaMaps() { + if (maps) return maps; + const s = buildSchemas2026(); + maps = { + request: { + "elicitation/create": object({ + method: literal("elicitation/create"), + params: s.ElicitRequestParamsSchema + }), + "sampling/createMessage": object({ + method: literal("sampling/createMessage"), + params: s.CreateMessageRequestParamsSchema + }), + "roots/list": object({ + method: literal("roots/list"), + params: looseObject({}).optional() + }) + }, + response: { + "elicitation/create": s.ElicitResultSchema, + "sampling/createMessage": s.CreateMessageResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps; +} +function isInputRequestMethod2026(method) { + return INPUT_REQUEST_METHODS_2026.includes(method); +} +function getInputRequestSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; +} +function getInputResponseSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; +} +var requestMethodKeys = { + "tools/call": null, + "tools/list": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "completion/complete": null, + "server/discover": null, + "subscriptions/listen": null +}; +var notificationMethodKeys = { + "notifications/cancelled": null, + "notifications/progress": null, + "notifications/message": null, + "notifications/resources/updated": null, + "notifications/resources/list_changed": null, + "notifications/tools/list_changed": null, + "notifications/prompts/list_changed": null, + "notifications/subscriptions/acknowledged": null +}; +function hasRequestMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function hasNotificationMethod2026(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); +} +function hasResultMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function getRequestSchema2026(method) { + return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; +} +function getResultSchema2026(method) { + return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; +} +function getNotificationSchema2026(method) { + return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; +} +var rev2026RequestMethods = Object.keys(requestMethodKeys); +var rev2026NotificationMethods = Object.keys(notificationMethodKeys); +function isPlainObject$4(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function triState(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +var NOT_IN_ERA = { + ok: false, + reason: "not-in-era" +}; +var REQUIRED_ENVELOPE_KEYS = [PROTOCOL_VERSION_META_KEY, CLIENT_CAPABILITIES_META_KEY]; +function enforceDeletedFields(method, result) { + let next = result; + let copied = false; + const copy2 = () => { + if (!copied) { + next = { ...next }; + copied = true; + } + return next; + }; + const tools = result.tools; + if (method === "tools/list" && Array.isArray(tools) && tools.some((tool2) => isPlainObject$4(tool2) && "execution" in tool2)) copy2().tools = tools.map((tool2) => { + if (!isPlainObject$4(tool2) || !("execution" in tool2)) return tool2; + const rest = { ...tool2 }; + delete rest["execution"]; + return rest; + }); + const capabilities = result.capabilities; + if (isPlainObject$4(capabilities) && "tasks" in capabilities) { + const rest = { ...capabilities }; + delete rest["tasks"]; + copy2().capabilities = rest; + } + return next; +} +var rev2026Codec = { + era: "2026-07-28", + hasRequestMethod: hasRequestMethod2026, + hasNotificationMethod: hasNotificationMethod2026, + hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, + validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), + validateResult: (method, raw) => triState(getResultSchema2026(method), raw), + validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), + validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), + validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), + samplingResultVariant: () => NOT_IN_ERA, + outboundEnvelope(material) { + return { + [PROTOCOL_VERSION_META_KEY]: material.protocolVersion, + [CLIENT_INFO_META_KEY]: material.clientInfo, + [CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, + ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } + }; + }, + validateEnvelopeMeta(meta3) { + const issues = []; + for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta3)) issues.push({ + key, + problem: "missing" + }); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3); + if (!parsed.success) for (const issue2 of parsed.error.issues) { + const path = issue2.path.map(String); + const key = path.length > 0 ? path.join(".") : "_meta"; + if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; + issues.push({ + key, + problem: issue2.message + }); + } + return issues; + }, + projectCallToolResult: (result) => appendTextFallbackForNonObject(result), + inputRequestSchema: getInputRequestSchema2026, + decodeResult(method, raw) { + if (!isPlainObject$4(raw)) return { + kind: "invalid", + error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) + }; + const rawResultType = raw["resultType"]; + if (rawResultType === void 0) return { + kind: "invalid", + error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { + method, + violation: "missing-resultType" + }) + }; + if (typeof rawResultType !== "string") return { + kind: "invalid", + error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { + method, + resultType: rawResultType + }) + }; + if (rawResultType === "input_required") { + const rawInputRequests = raw["inputRequests"]; + const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; + const requestState = raw["requestState"]; + if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { + kind: "invalid", + error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { + method, + violation: "input-required-missing-both" + }) + }; + return { + kind: "input_required", + inputRequests, + ...typeof requestState === "string" && { requestState } + }; + } + if (rawResultType !== "complete") return { + kind: "invalid", + error: new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { + resultType: rawResultType, + method + }) + }; + const wireResultSchemas = getWireResultSchemas(); + const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; + if (wireSchema !== void 0) { + const parsed = wireSchema.safeParse(raw); + if (!parsed.success) return { + kind: "invalid", + error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) + }; + } + const lifted = { ...raw }; + delete lifted["resultType"]; + return { + kind: "complete", + result: lifted + }; + }, + encodeResult(method, result, serverInfo) { + return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope(material) { + if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); + if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue2) => issue2.message).join("; ")}`; + } +}; +var wireResultSchemasMemo; +function getWireResultSchemas() { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s = buildSchemas2026(); + wireResultSchemasMemo = { + "tools/call": s.CallToolResultSchema, + "tools/list": s.ListToolsResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "completion/complete": s.CompleteResultSchema, + "server/discover": s.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} +var MODERN_WIRE_REVISION = "2026-07-28"; +function codecForVersion(version3) { + return version3 !== void 0 && isModernProtocolVersion(version3) ? rev2026Codec : rev2025Codec; +} +function classifiedWireEra(classification) { + if (classification.revision !== void 0) return codecForVersion(classification.revision).era; + return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; +} +function isSpecRequestMethod(method) { + return ALL_CODECS.some((codec2) => codec2.hasRequestMethod(method)); +} +function isSpecNotificationMethod(method) { + return ALL_CODECS.some((codec2) => codec2.hasNotificationMethod(method)); +} +var ALL_CODECS = [rev2025Codec, rev2026Codec]; +var schemas_exports3 = /* @__PURE__ */ __exportAll({ + AnnotationsSchema: () => AnnotationsSchema, + AudioContentSchema: () => AudioContentSchema, + BaseMetadataSchema: () => BaseMetadataSchema, + BaseRequestParamsSchema: () => BaseRequestParamsSchema, + BlobResourceContentsSchema: () => BlobResourceContentsSchema, + BooleanSchemaSchema: () => BooleanSchemaSchema, + CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, + CallToolRequestSchema: () => CallToolRequestSchema, + CallToolResultSchema: () => CallToolResultSchema, + CancelTaskRequestSchema: () => CancelTaskRequestSchema, + CancelTaskResultSchema: () => CancelTaskResultSchema, + CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, + CancelledNotificationSchema: () => CancelledNotificationSchema, + ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, + ClientNotificationSchema: () => ClientNotificationSchema, + ClientRequestSchema: () => ClientRequestSchema, + ClientResultSchema: () => ClientResultSchema, + ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, + CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, + CompleteRequestSchema: () => CompleteRequestSchema, + CompleteResultSchema: () => CompleteResultSchema, + ContentBlockSchema: () => ContentBlockSchema, + CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, + CreateMessageRequestSchema: () => CreateMessageRequestSchema, + CreateMessageResultSchema: () => CreateMessageResultSchema, + CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, + CreateTaskResultSchema: () => CreateTaskResultSchema, + CursorSchema: () => CursorSchema, + DiscoverRequestSchema: () => DiscoverRequestSchema, + DiscoverResultSchema: () => DiscoverResultSchema, + ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, + ElicitRequestSchema: () => ElicitRequestSchema, + ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, + ElicitResultSchema: () => ElicitResultSchema, + ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, + EmbeddedResourceSchema: () => EmbeddedResourceSchema, + EmptyResultSchema: () => EmptyResultSchema, + EnumSchemaSchema: () => EnumSchemaSchema, + GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, + GetPromptRequestSchema: () => GetPromptRequestSchema, + GetPromptResultSchema: () => GetPromptResultSchema, + GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, + GetTaskRequestSchema: () => GetTaskRequestSchema, + GetTaskResultSchema: () => GetTaskResultSchema, + IconSchema: () => IconSchema, + IconsSchema: () => IconsSchema, + ImageContentSchema: () => ImageContentSchema, + ImplementationSchema: () => ImplementationSchema, + InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, + InitializeRequestSchema: () => InitializeRequestSchema, + InitializeResultSchema: () => InitializeResultSchema, + InitializedNotificationSchema: () => InitializedNotificationSchema, + JSONArraySchema: () => JSONArraySchema, + JSONObjectSchema: () => JSONObjectSchema, + JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, + JSONRPCMessageSchema: () => JSONRPCMessageSchema, + JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, + JSONRPCRequestSchema: () => JSONRPCRequestSchema, + JSONRPCResponseSchema: () => JSONRPCResponseSchema, + JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, + JSONValueSchema: () => JSONValueSchema, + LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, + ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, + ListPromptsRequestSchema: () => ListPromptsRequestSchema, + ListPromptsResultSchema: () => ListPromptsResultSchema, + ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, + ListResourcesRequestSchema: () => ListResourcesRequestSchema, + ListResourcesResultSchema: () => ListResourcesResultSchema, + ListRootsRequestSchema: () => ListRootsRequestSchema, + ListRootsResultSchema: () => ListRootsResultSchema, + ListTasksRequestSchema: () => ListTasksRequestSchema, + ListTasksResultSchema: () => ListTasksResultSchema, + ListToolsRequestSchema: () => ListToolsRequestSchema, + ListToolsResultSchema: () => ListToolsResultSchema, + LoggingLevelSchema: () => LoggingLevelSchema, + LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, + ModelHintSchema: () => ModelHintSchema, + ModelPreferencesSchema: () => ModelPreferencesSchema, + MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, + NotificationSchema: () => NotificationSchema, + NotificationsParamsSchema: () => NotificationsParamsSchema, + NumberSchemaSchema: () => NumberSchemaSchema, + PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, + PaginatedRequestSchema: () => PaginatedRequestSchema, + PaginatedResultSchema: () => PaginatedResultSchema, + PingRequestSchema: () => PingRequestSchema, + PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, + ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, + ProgressNotificationSchema: () => ProgressNotificationSchema, + ProgressSchema: () => ProgressSchema, + ProgressTokenSchema: () => ProgressTokenSchema, + PromptArgumentSchema: () => PromptArgumentSchema, + PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, + PromptMessageSchema: () => PromptMessageSchema, + PromptReferenceSchema: () => PromptReferenceSchema, + PromptSchema: () => PromptSchema, + ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, + ReadResourceRequestSchema: () => ReadResourceRequestSchema, + ReadResourceResultSchema: () => ReadResourceResultSchema, + RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, + RequestIdSchema: () => RequestIdSchema, + RequestMetaSchema: () => RequestMetaSchema, + RequestSchema: () => RequestSchema, + ResourceContentsSchema: () => ResourceContentsSchema, + ResourceLinkSchema: () => ResourceLinkSchema, + ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, + ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, + ResourceSchema: () => ResourceSchema, + ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, + ResourceTemplateSchema: () => ResourceTemplateSchema, + ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, + ResultMetaObjectSchema: () => ResultMetaObjectSchema, + ResultSchema: () => ResultSchema, + RoleSchema: () => RoleSchema, + RootSchema: () => RootSchema, + RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, + SamplingContentSchema: () => SamplingContentSchema, + SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, + SamplingMessageSchema: () => SamplingMessageSchema, + ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, + ServerNotificationSchema: () => ServerNotificationSchema, + ServerRequestSchema: () => ServerRequestSchema, + ServerResultSchema: () => ServerResultSchema, + ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, + SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, + SetLevelRequestSchema: () => SetLevelRequestSchema, + SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, + StringSchemaSchema: () => StringSchemaSchema, + SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, + SubscribeRequestSchema: () => SubscribeRequestSchema, + SubscriptionFilterSchema: () => SubscriptionFilterSchema, + SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, + SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, + SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, + SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, + TaskAugmentedRequestParamsSchema: () => TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema: () => TaskCreationParamsSchema, + TaskMetadataSchema: () => TaskMetadataSchema, + TaskSchema: () => TaskSchema, + TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, + TaskStatusSchema: () => TaskStatusSchema, + TextContentSchema: () => TextContentSchema, + TextResourceContentsSchema: () => TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema: () => ToolAnnotationsSchema, + ToolChoiceSchema: () => ToolChoiceSchema, + ToolExecutionSchema: () => ToolExecutionSchema, + ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, + ToolResultContentSchema: () => ToolResultContentSchema, + ToolSchema: () => ToolSchema, + ToolUseContentSchema: () => ToolUseContentSchema, + UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema +}); +var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +var isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; +var HEADER_MISMATCH_ERROR_CODE = -32020; +var INBOUND_VALIDATION_LADDER = [ + { + rung: "http-method", + order: 1, + evaluatedAt: "edge", + codes: [-32e3], + conformance: [], + rationale: "The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read." + }, + { + rung: "jsonrpc-shape", + order: 2, + evaluatedAt: "edge", + codes: [ProtocolErrorCode.InvalidRequest], + conformance: ["server-stateless"], + rationale: "The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic." + }, + { + rung: "era-classification", + order: 3, + evaluatedAt: "edge", + codes: [HEADER_MISMATCH_ERROR_CODE, ProtocolErrorCode.UnsupportedProtocolVersion], + conformance: [ + "server-stateless", + "http-header-validation", + "http-custom-header-server-validation" + ], + rationale: "Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions." + }, + { + rung: "envelope", + order: 4, + evaluatedAt: "edge", + codes: [ProtocolErrorCode.InvalidParams], + conformance: ["server-stateless"], + rationale: "A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." + }, + { + rung: "method-registry", + order: 5, + evaluatedAt: "dispatch", + codes: [ProtocolErrorCode.MethodNotFound], + conformance: ["server-stateless"], + rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." + }, + { + rung: "request-params", + order: 6, + evaluatedAt: "dispatch", + codes: [ProtocolErrorCode.InvalidParams], + conformance: [], + rationale: "Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table." + }, + { + rung: "standard-header-validation", + order: 7, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-header-validation"], + rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted." + }, + { + rung: "client-capabilities", + order: 8, + evaluatedAt: "pre-dispatch", + codes: [ProtocolErrorCode.MissingRequiredClientCapability], + conformance: ["server-stateless"], + rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." + }, + { + rung: "param-header-validation", + order: 9, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-custom-header-server-validation"], + rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." + } +]; +var LADDER_ERROR_HTTP_STATUS = { + [ProtocolErrorCode.ParseError]: 400, + [ProtocolErrorCode.InvalidRequest]: 400, + [ProtocolErrorCode.MethodNotFound]: 404, + [ProtocolErrorCode.UnsupportedProtocolVersion]: 400, + [ProtocolErrorCode.MissingRequiredClientCapability]: 400, + [HEADER_MISMATCH_ERROR_CODE]: 400 +}; +function parseSchema(schema, data) { + return safeParse2(schema, data); +} +function shapeKeys(schemas) { + return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); +} +function isStandardSchema(schema) { + if (schema == null) return false; + const schemaType = typeof schema; + if (schemaType !== "object" && schemaType !== "function") return false; + if (!("~standard" in schema)) return false; + return typeof schema["~standard"]?.validate === "function"; +} +var warnedZodFallback = false; +var JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; +function standardSchemaToJsonSchema(schema, io = "input") { + const std = schema["~standard"]; + let result; + if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); + else if (std.vendor === "zod") { + if (!("_zod" in schema)) throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema()."); + if (!warnedZodFallback) { + warnedZodFallback = true; + console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning."); + } + result = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io + }); + } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); + if (io === "output") { + if (result.type !== void 0) return result; + return isProvablyObjectShapedRoot(result) ? { + type: "object", + ...result + } : result; + } + if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); + return { + type: "object", + ...result + }; +} +function isProvablyObjectShapedRoot(schema) { + if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; + for (const key of [ + "oneOf", + "anyOf", + "allOf" + ]) { + const members = schema[key]; + if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); + } + return false; +} +function formatIssue(issue2) { + if (!issue2.path?.length) return issue2.message; + return `${issue2.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue2.message}`; +} +async function validateStandardSchema(schema, data) { + const result = await schema["~standard"].validate(data); + if (result.issues && result.issues.length > 0) return { + success: false, + error: result.issues.map((i) => formatIssue(i)).join(", ") + }; + return { + success: true, + data: result.value + }; +} +function zodEmittedPattern(schema) { + const jsonSchema = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io: "input" + }); + return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; +} +var DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; +function datetimeReferenceSchemas(pattern) { + const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); + const precisions = [ + void 0, + -1, + 0 + ]; + if (fractionDigits) precisions.push(Number(fractionDigits[1])); + return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_exports.datetime({ + local, + offset, + precision + })))); +} +function referencePatternsForFormat(format, pattern) { + let referenceSchemas; + switch (format) { + case "email": + referenceSchemas = [email2()]; + break; + case "uri": + referenceSchemas = [url()]; + break; + case "date": + referenceSchemas = [iso_exports.date()]; + break; + case "date-time": + referenceSchemas = datetimeReferenceSchemas(pattern); + break; + } + return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); +} +function isLibraryFormatPattern(format, pattern, vendor) { + if (vendor !== "zod") return true; + return referencePatternsForFormat(format, pattern).has(pattern); +} +function isJsonObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function convertStandardElicitationSchema(schema) { + try { + return standardSchemaToJsonSchema(schema, "input"); + } catch (error51) { + const detail = error51 instanceof Error ? error51.message : String(error51); + throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); + } +} +var ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([ + "$comment", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]); +function isAnnotationOnlyJsonSchemaKeyword(key) { + return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); +} +var ROOT_KEYS = /* @__PURE__ */ new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); +var PROPERTY_KEYS_BY_TYPE = { + string: shapeKeys([ + StringSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema + ]), + number: shapeKeys([NumberSchemaSchema]), + integer: shapeKeys([NumberSchemaSchema]), + boolean: shapeKeys([BooleanSchemaSchema]), + array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) +}; +var SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); +function walkProperty(node, path, vendor, unsupported) { + if (!isJsonObject(node)) return node; + const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; + if (allowedKeys === void 0) return node; + const pruned = {}; + for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; + else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { + if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; + else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); + } else unsupported.push(`${path}.${key}`); + return pruned; +} +function walkRequestedSchema(converted, vendor) { + const pruned = {}; + const unsupported = []; + for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); + else if (ROOT_KEYS.has(key)) pruned[key] = value; + else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); + if (unsupported.length > 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); + return pruned; +} +function describeUnsupportedProperties(pruned, fallback) { + if (!isJsonObject(pruned.properties)) return fallback; + const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); + return offenders.length > 0 ? offenders.join(", ") : fallback; +} +function findDroppedConstraintPaths(original, parsed, path = "") { + if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); + if (!isJsonObject(original) || !isJsonObject(parsed)) return []; + return Object.entries(original).flatMap(([key, value]) => { + const childPath2 = path ? `${path}.${key}` : key; + if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath2]; + return findDroppedConstraintPaths(value, parsed[key], childPath2); + }); +} +function normalizeElicitInputParams(input) { + if (!isStandardSchema(input.requestedSchema)) return { + ...input, + mode: "form", + requestedSchema: input.requestedSchema + }; + const vendor = input.requestedSchema["~standard"].vendor; + const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); + const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); + if (!parsed.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); + const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); + if (droppedConstraints.length > 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); + const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); + if (danglingRequired.length > 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); + return { + ...input, + mode: "form", + requestedSchema: parsed.data + }; +} +function buildInputRequired(spec) { + const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; + const hasRequestState = typeof spec.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)"); + return { + resultType: "input_required", + ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, + ...spec.requestState !== void 0 && { requestState: spec.requestState } + }; +} +var inputRequired = Object.assign(buildInputRequired, { + elicit(params) { + try { + return { + method: "elicitation/create", + params: normalizeElicitInputParams(params) + }; + } catch (error51) { + throw error51 instanceof ProtocolError ? new TypeError(error51.message, { cause: error51 }) : error51; + } + }, + elicitUrl(params) { + return { + method: "elicitation/create", + params: { + ...params, + mode: "url" + } + }; + }, + createMessage(params) { + return { + method: "sampling/createMessage", + params + }; + }, + listRoots() { + return { method: "roots/list" }; + } +}); +var REQUEST_STATE_ONLY_LEG_PACING_MS = 250; +function inputRequiredRoundsExceededMessage(method, maxRounds) { + return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; +} +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason))); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal?.reason))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +function linkedRoundAbort(outer) { + const controller = new AbortController(); + const onOuterAbort = () => controller.abort(outer?.reason); + outer?.addEventListener("abort", onOuterAbort, { once: true }); + if (outer?.aborted) controller.abort(outer.reason); + return { + signal: controller.signal, + abort: (reason2) => controller.abort(reason2), + dispose: () => outer?.removeEventListener("abort", onOuterAbort) + }; +} +var SPEC_SCHEMA_KEYS = [ + "AnnotationsSchema", + "AudioContentSchema", + "BaseMetadataSchema", + "BlobResourceContentsSchema", + "BooleanSchemaSchema", + "CallToolRequestSchema", + "CallToolRequestParamsSchema", + "CallToolResultSchema", + "CancelledNotificationSchema", + "CancelledNotificationParamsSchema", + "CancelTaskRequestSchema", + "CancelTaskResultSchema", + "ClientCapabilitiesSchema", + "ClientNotificationSchema", + "ClientRequestSchema", + "ClientResultSchema", + "CompatibilityCallToolResultSchema", + "CompleteRequestSchema", + "CompleteRequestParamsSchema", + "CompleteResultSchema", + "ContentBlockSchema", + "CreateMessageRequestSchema", + "CreateMessageRequestParamsSchema", + "CreateMessageResultSchema", + "CreateMessageResultWithToolsSchema", + "CreateTaskResultSchema", + "CursorSchema", + "DiscoverRequestSchema", + "DiscoverResultSchema", + "ElicitationCompleteNotificationSchema", + "ElicitationCompleteNotificationParamsSchema", + "ElicitRequestSchema", + "ElicitRequestFormParamsSchema", + "ElicitRequestParamsSchema", + "ElicitRequestURLParamsSchema", + "ElicitResultSchema", + "EmbeddedResourceSchema", + "EmptyResultSchema", + "EnumSchemaSchema", + "GetPromptRequestSchema", + "GetPromptRequestParamsSchema", + "GetPromptResultSchema", + "GetTaskPayloadRequestSchema", + "GetTaskPayloadResultSchema", + "GetTaskRequestSchema", + "GetTaskResultSchema", + "IconSchema", + "IconsSchema", + "ImageContentSchema", + "ImplementationSchema", + "InitializedNotificationSchema", + "InitializeRequestSchema", + "InitializeRequestParamsSchema", + "InitializeResultSchema", + "JSONArraySchema", + "JSONObjectSchema", + "JSONRPCErrorResponseSchema", + "JSONRPCMessageSchema", + "JSONRPCNotificationSchema", + "JSONRPCRequestSchema", + "JSONRPCResponseSchema", + "JSONRPCResultResponseSchema", + "JSONValueSchema", + "LegacyTitledEnumSchemaSchema", + "ListPromptsRequestSchema", + "ListPromptsResultSchema", + "ListResourcesRequestSchema", + "ListResourcesResultSchema", + "ListResourceTemplatesRequestSchema", + "ListResourceTemplatesResultSchema", + "ListRootsRequestSchema", + "ListRootsResultSchema", + "ListTasksRequestSchema", + "ListTasksResultSchema", + "ListToolsRequestSchema", + "ListToolsResultSchema", + "LoggingLevelSchema", + "LoggingMessageNotificationSchema", + "LoggingMessageNotificationParamsSchema", + "ModelHintSchema", + "ModelPreferencesSchema", + "MultiSelectEnumSchemaSchema", + "NotificationSchema", + "NumberSchemaSchema", + "PaginatedRequestSchema", + "PaginatedRequestParamsSchema", + "PaginatedResultSchema", + "PingRequestSchema", + "PrimitiveSchemaDefinitionSchema", + "ProgressSchema", + "ProgressNotificationSchema", + "ProgressNotificationParamsSchema", + "ProgressTokenSchema", + "PromptSchema", + "PromptArgumentSchema", + "PromptListChangedNotificationSchema", + "PromptMessageSchema", + "PromptReferenceSchema", + "ReadResourceRequestSchema", + "ReadResourceRequestParamsSchema", + "ReadResourceResultSchema", + "RelatedTaskMetadataSchema", + "RequestSchema", + "RequestIdSchema", + "RequestMetaSchema", + "ResourceSchema", + "ResourceContentsSchema", + "ResourceLinkSchema", + "ResourceListChangedNotificationSchema", + "ResourceRequestParamsSchema", + "ResourceTemplateSchema", + "ResourceTemplateReferenceSchema", + "ResourceUpdatedNotificationSchema", + "ResourceUpdatedNotificationParamsSchema", + "ResultMetaObjectSchema", + "ResultSchema", + "RoleSchema", + "RootSchema", + "RootsListChangedNotificationSchema", + "SamplingContentSchema", + "SamplingMessageSchema", + "SamplingMessageContentBlockSchema", + "ServerCapabilitiesSchema", + "ServerNotificationSchema", + "ServerRequestSchema", + "ServerResultSchema", + "SetLevelRequestSchema", + "SetLevelRequestParamsSchema", + "SingleSelectEnumSchemaSchema", + "StringSchemaSchema", + "SubscribeRequestSchema", + "SubscribeRequestParamsSchema", + "SubscriptionFilterSchema", + "SubscriptionsAcknowledgedNotificationSchema", + "SubscriptionsAcknowledgedNotificationParamsSchema", + "SubscriptionsListenRequestSchema", + "SubscriptionsListenRequestParamsSchema", + "SubscriptionsListenResultSchema", + "SubscriptionsListenResultMetaSchema", + "TaskAugmentedRequestParamsSchema", + "TaskCreationParamsSchema", + "TaskMetadataSchema", + "TaskSchema", + "TaskStatusSchema", + "TaskStatusNotificationSchema", + "TaskStatusNotificationParamsSchema", + "TextContentSchema", + "TextResourceContentsSchema", + "TitledMultiSelectEnumSchemaSchema", + "TitledSingleSelectEnumSchemaSchema", + "ToolSchema", + "ToolAnnotationsSchema", + "ToolChoiceSchema", + "ToolExecutionSchema", + "ToolListChangedNotificationSchema", + "ToolResultContentSchema", + "ToolUseContentSchema", + "UnsubscribeRequestSchema", + "UnsubscribeRequestParamsSchema", + "UntitledMultiSelectEnumSchemaSchema", + "UntitledSingleSelectEnumSchemaSchema" +]; +var authSchemas = { + IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema, + OAuthClientInformationSchema, + OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema, + OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema, + OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema +}; +var _specTypeSchemas = {}; +var _isSpecType = {}; +function register(key, schema) { + const name = key.slice(0, -6); + _specTypeSchemas[name] = schema; + _isSpecType[name] = (v) => schema.safeParse(v).success; +} +for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports3[key]); +for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); +var specTypeSchemas = Object.freeze(_specTypeSchemas); +var isSpecType = Object.freeze(_isSpecType); +function bootstrapOutboundCodec(method) { + switch (method) { + case "initialize": + case "notifications/initialized": + return codecForVersion(void 0); + case "server/discover": + return codecForVersion(MODERN_WIRE_REVISION); + default: + return; + } +} +var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +var RESERVED_ENVELOPE_META_KEYS = [ + PROTOCOL_VERSION_META_KEY, + CLIENT_INFO_META_KEY, + CLIENT_CAPABILITIES_META_KEY, + LOG_LEVEL_META_KEY +]; +var RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; +function liftWireOnlyMaterial(message, kind) { + const params = message.params; + if (!isPlainObject$1(params)) return { + message, + lifted: {} + }; + const meta3 = params._meta; + const envelopeKeys = isPlainObject$1(meta3) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta3) : []; + const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; + if (envelopeKeys.length === 0 && retryKeys.length === 0) return { + message, + lifted: {} + }; + const lifted = {}; + const nextParams = { ...params }; + if (envelopeKeys.length > 0 && isPlainObject$1(meta3)) { + const envelope = {}; + const nextMeta = { ...meta3 }; + for (const key of envelopeKeys) { + envelope[key] = meta3[key]; + delete nextMeta[key]; + } + lifted.envelope = envelope; + if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; + else delete nextParams._meta; + } + for (const key of retryKeys) { + if (key === "inputResponses") lifted.inputResponses = nextParams[key]; + if (key === "requestState") lifted.requestState = nextParams[key]; + delete nextParams[key]; + } + return { + message: { + ...message, + params: nextParams + }, + lifted + }; +} +function codecResultValidator(codec2, method) { + const probe = codec2.validateResult(method, void 0); + if (!probe.ok && probe.reason === "not-in-era") return void 0; + return { "~standard": { + version: 1, + vendor: "mcp-wire-codec", + validate(value) { + const outcome = codec2.validateResult(method, value); + if (outcome.ok) return { value: outcome.value }; + return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; + } + } }; +} +function requestStateAccessor(value) { + return () => value; +} +var NO_REQUEST_STATE = requestStateAccessor(void 0); +function withRequestStateValue(ctx, value) { + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + requestState: requestStateAccessor(value) + } + }; +} +var writeNegotiatedProtocolVersion; +var Protocol = class { + _transport; + _requestMessageId = 0; + _requestHandlers = /* @__PURE__ */ new Map(); + _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + _notificationHandlers = /* @__PURE__ */ new Map(); + _responseHandlers = /* @__PURE__ */ new Map(); + _progressHandlers = /* @__PURE__ */ new Map(); + _timeoutInfo = /* @__PURE__ */ new Map(); + _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + /** + * The protocol version negotiated for the current connection (`undefined` + * before negotiation completes), which determines the wire era this + * instance speaks. Set by the SDK's negotiation and initialize paths + * (`Client.connect`, `Server._oninitialize`). + */ + _negotiatedProtocolVersion; + static { + writeNegotiatedProtocolVersion = (instance, version3) => { + instance._negotiatedProtocolVersion = version3; + }; + } + _supportedProtocolVersions; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when {@linkcode Protocol.close | close()} is called as well. + */ + onclose; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler; + constructor(_options) { + this._options = _options; + this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; + this.setNotificationHandler("notifications/cancelled", (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler("notifications/progress", (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler("ping", (_request) => ({})); + } + /** + * Drop consult for inbound messages whose transport did not classify them + * at the edge — long-lived channels such as stdio, where a role class may + * need to decline traffic the negotiated era has no answer for (the + * client-side inbound-request drop on modern-era connections: the + * 2026-07-28 era has no server→client request channel, and on stdio the + * client must never write JSON-RPC responses). + * + * Consulted ONLY when the transport supplied no + * {@linkcode MessageExtraInfo.classification}: edge-classified traffic + * never reaches the hook. Returning `'drop'` discards the message without + * writing any response (requests are surfaced via `onerror`). The base + * implementation returns `undefined`: unclassified traffic keeps today's + * dispatch path unchanged. Era selection never happens here — era is + * instance state, owned by the serving entry that constructed and + * connected the instance. + */ + _shouldDropInbound(_message) { + } + /** + * The per-request `_meta` envelope this instance attaches to every outgoing + * request and notification, when one applies. The base implementation + * returns `undefined` (no envelope — the 2025-era posture, so legacy-era + * outbound traffic is byte-identical to a build without this seam). + * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) + * era to return the reserved protocol-version / client-info / + * client-capabilities keys. User-supplied `_meta` keys take precedence over + * the auto-attached ones. + */ + _outboundMetaEnvelope() { + } + /** + * Attach this instance's outbound `_meta` envelope (when one is configured) + * to a request or notification. A no-op when the seam returns `undefined` + * — the message returns by reference, so the legacy-era wire stays + * byte-identical. User-supplied `_meta` keys are spread last so they win + * over the auto-attached envelope keys. + */ + _envelopeOutbound(message) { + const envelope = this._outboundMetaEnvelope(); + if (envelope === void 0) return message; + const params = message.params ?? {}; + return { + ...message, + params: { + ...params, + _meta: { + ...envelope, + ...params._meta + } + } + }; + } + /** + * Extension point for non-`complete` decoded results in the response + * funnel: a result the wire codec discriminated into a kind other than + * `'complete'` or `'invalid'` is handed here for the role class to + * resolve. The base default surfaces it as a typed + * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). + * + * Intended consumers (named so the seam stays accountable): + * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils + * `'input_required'` results through the registered + * elicitation/sampling/roots handlers and retries via `flow.retry`; + * - a future client-side terminal-result handler for + * `subscriptions/listen`, when the spec defines one. + * + * `Server` instances never receive `input_required` responses on their + * outbound legs and leave the base behavior in place. + */ + _resolveNonCompleteResult(decoded, flow) { + return Promise.reject(new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { + resultType: decoded.kind, + method: flow.request.method + })); + } + /** + * Protected accessor for a registered request handler. Used by role + * classes that dispatch synthesized requests through the same stored + * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip + * input request). + */ + _getRequestHandler(method) { + return this._requestHandlers.get(method); + } + async _oncancel(notification) { + if (!notification.params.requestId) return; + this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw new SdkError(SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + try { + _onclose?.(); + } finally { + this._onclose(); + } + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error51) => { + _onerror?.(error51); + this._onerror(error51); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) this._onresponse(message); + else if (isJSONRPCRequest(message)) this._onrequest(message, extra); + else if (isJSONRPCNotification(message)) this._onnotification(message, extra); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); + }; + transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); + await this._transport.start(); + } + /** + * Transport-close hook. Subclass overrides MUST call `super._onclose()` + * after their own cleanup — base teardown (response-handler settlement, + * timeout clearing, in-flight request abort) does not run otherwise. + */ + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); + this._timeoutInfo.clear(); + const requestHandlerAbortControllers = this._requestHandlerAbortControllers; + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + const error51 = new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + try { + this.onclose?.(); + } finally { + for (const handler of responseHandlers.values()) handler(error51); + for (const controller of requestHandlerAbortControllers.values()) controller.abort(error51); + } + } + _onerror(error51) { + this.onerror?.(error51); + } + /** + * Inbound-notification dispatch. Subclass overrides MUST delegate + * unmatched traffic to `super._onnotification(rawNotification, extra)` — + * an override that consumes only what it owns and falls through to base + * dispatch for everything else. + */ + _onnotification(rawNotification, extra) { + const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); + const codec2 = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec2.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec2.era}`)); + return; + } + } + if (isSpecNotificationMethod(notification.method) && !codec2.hasNotificationMethod(notification.method)) return; + const handler = this._notificationHandlers.get(notification.method); + const fallback = this.fallbackNotificationHandler; + if (handler === void 0 && fallback === void 0) return; + Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec2)).catch((error51) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error51}`))); + } + _onrequest(rawRequest, extra) { + const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); + const codec2 = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { + this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); + return; + } + const capturedTransport = this._transport; + const sendErrorResponse = (code, message, data) => { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }; + capturedTransport?.send(errorResponse).catch((error51) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error51}`))); + }; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec2.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec2.era}`)); + const requested = extra.classification.revision ?? classified; + sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { + supported: this._supportedProtocolVersions, + requested + }); + return; + } + } + if (isSpecRequestMethod(request.method) && !codec2.hasRequestMethod(request.method)) { + sendErrorResponse(ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + if (handler === void 0) { + sendErrorResponse(ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const envelopeError = codec2.checkInboundEnvelope(lifted); + if (envelopeError !== void 0) { + sendErrorResponse(ProtocolErrorCode.InvalidParams, envelopeError); + return; + } + const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { + ...options, + relatedRequestId: request.id + }); + const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { + ...options, + relatedRequestId: request.id + }); + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); + const baseCtx = { + sessionId: capturedTransport?.sessionId, + mcpReq: { + id: request.id, + method: request.method, + _meta: request.params?._meta, + ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, + ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, + ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, + requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), + signal: abortController.signal, + send: ((r, schemaOrOptions, maybeOptions) => { + const sendCodec = this._resolveOutboundCodec(r.method); + this._assertOutboundRequestInEra(sendCodec, r.method); + if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(sendCodec, r.method); + if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); + return sendRequest(r, validate, schemaOrOptions); + }), + notify: sendNotification + }, + http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 + }; + const ctx = this.buildContext(baseCtx, extra); + Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { + if (abortController.signal.aborted) return; + let encoded; + try { + encoded = codec2.encodeResult(request.method, result, this._outboundServerInfo()); + } catch (error51) { + this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error51}`)); + sendErrorResponse(ProtocolErrorCode.InternalError, "Internal error"); + return; + } + const response = { + result: encoded, + jsonrpc: "2.0", + id: request.id + }; + await capturedTransport?.send(response); + }, async (error51) => { + if (abortController.signal.aborted) return; + const thrownCode = Number.isSafeInteger(error51["code"]) ? error51["code"] : ProtocolErrorCode.InternalError; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: codec2.encodeErrorCode(thrownCode), + message: error51.message ?? "Internal error", + ...error51["data"] !== void 0 && { data: error51["data"] } + } + }; + await capturedTransport?.send(errorResponse); + }).catch((error51) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error51}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { + this._resetTimeout(messageId); + } catch (error51) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error51); + return; + } + handler(params); + } + /** + * Inbound-response dispatch. Subclass overrides MUST delegate unmatched + * traffic to `super._onresponse(response)` — an override that consumes + * only what it owns and falls through to base dispatch for everything + * else. + */ + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._progressHandlers.delete(messageId); + if (isJSONRPCResultResponse(response)) handler(response); + else handler(ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + request(request, schemaOrOptions, maybeOptions) { + const codec2 = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec2, request.method); + if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec2, request, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(codec2, request.method); + if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); + return this._requestWithSchemaViaCodec(codec2, request, validate, schemaOrOptions); + } + /** + * The wire codec for this instance's negotiated era — the phase-2 truth: + * everything an established connection sends and receives resolves + * through it. Legacy until a version has been negotiated. + */ + _negotiatedWireCodec() { + return codecForVersion(this._negotiatedProtocolVersion); + } + /** + * Protected accessor for the instance's negotiated wire codec, for role + * classes (Client/Server/McpServer) routing era-dependent behavior + * through the codec's function-only surface — `samplingResultVariant`, + * `outboundEnvelope`, `projectCallToolResult` — instead of branching on + * the protocol version themselves. + */ + _wireCodec() { + return this._negotiatedWireCodec(); + } + /** + * Outbound codec resolution: while the negotiated version is still unset + * (the negotiation window), lifecycle messages are bootstrap-pinned BY + * METHOD — they self-identify their era (`initialize` IS the legacy + * handshake, `server/discover` IS the modern probe). Once a version has + * been negotiated, the instance era is authoritative for everything — a + * negotiated session never re-routes a method onto the other era. + */ + _resolveOutboundCodec(method) { + if (this._negotiatedProtocolVersion === void 0) { + const pinned = bootstrapOutboundCodec(method); + if (pinned) return pinned; + } + return this._negotiatedWireCodec(); + } + /** + * Era gate for outbound requests — deletions are physical in BOTH + * directions: sending a spec method that the resolved era does not define + * dies locally with a typed error before anything reaches the transport. + * Methods outside the spec universe are consumer-owned extension methods + * and stay era-blind. + */ + _assertOutboundRequestInEra(codec2, method) { + if (isSpecRequestMethod(method) && !codec2.hasRequestMethod(method)) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec2.era})`, { + method, + era: codec2.era + }); + } + /** + * Sends a request and waits for a response, using the provided schema for + * validation instead of the era registry's method-keyed entry. + * + * This is the internal implementation used by SDK methods whose result + * schema cannot be expressed as a method-keyed registry entry — the one + * surviving case is `server.createMessage`, whose result schema depends + * on the REQUEST params (tools vs no tools) — and by callers passing + * explicit compatibility schemas. Spec methods are still era-gated here: + * an explicit schema never smuggles a deleted method onto the wire. + */ + _requestWithSchema(request, resultSchema, options) { + const codec2 = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec2, request.method); + return this._requestWithSchemaViaCodec(codec2, request, resultSchema, options); + } + /** + * The request funnel proper, keyed by the resolved era codec: the codec + * owns result decoding (raw-first `resultType` discrimination — V-1 — + * and the era's lift posture) before the schema validation step. + */ + _requestWithSchemaViaCodec(codec2, request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; + const flowStartedAt = Date.now(); + let onAbort; + let cleanupMessageId; + return new Promise((resolve, reject) => { + const earlyReject = (error51) => { + reject(error51); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + } catch (error51) { + earlyReject(error51); + return; + } + if (options?.signal?.aborted) { + const reason2 = options.signal.reason; + throw reason2 instanceof SdkError ? reason2 : new SdkError(SdkErrorCode.RequestTimeout, String(reason2)); + } + const requestAbort = codec2.era === MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; + const messageId = this._requestMessageId++; + cleanupMessageId = messageId; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta, + progressToken: messageId + } + }; + } + const outbound = this._envelopeOutbound(jsonrpcRequest); + let responseReceived = false; + const cancel = (reason2) => { + if (responseReceived) return; + this._progressHandlers.delete(messageId); + if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason2) + } + }), { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error51) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error51}`))); + else requestAbort.abort(); + reject(reason2 instanceof SdkError ? reason2 : new SdkError(SdkErrorCode.RequestTimeout, String(reason2))); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) return; + responseReceived = true; + if (response instanceof Error) return reject(response); + let decoded; + try { + decoded = codec2.decodeResult(request.method, response.result); + } catch (error51) { + return reject(error51 instanceof Error ? error51 : new Error(String(error51))); + } + if (decoded.kind === "invalid") return reject(decoded.error); + if (decoded.kind === "input_required") { + if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); + const flow = { + codec: codec2, + request, + resultSchema, + options, + flowStartedAt, + retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec2, params === void 0 ? { method: request.method } : { + method: request.method, + params + }, resultSchema, legOptions) + }; + return resolve(this._resolveNonCompleteResult(decoded, flow)); + } + const result = decoded.result; + validateStandardSchema(resultSchema, result).then((parseResult) => { + if (parseResult.success) resolve(parseResult.data); + else reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); + }, reject); + }); + onAbort = () => cancel(options?.signal?.reason); + options?.signal?.addEventListener("abort", onAbort, { once: true }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(new SdkError(SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + this._transport.send(outbound, { + relatedRequestId, + resumptionToken, + onresumptiontoken, + headers, + requestSignal: requestAbort?.signal + }).catch((error51) => { + this._progressHandlers.delete(messageId); + reject(error51); + }); + }).finally(() => { + if (onAbort) options?.signal?.removeEventListener("abort", onAbort); + if (cleanupMessageId !== void 0) { + this._responseHandlers.delete(cleanupMessageId); + this._cleanupTimeout(cleanupMessageId); + } + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); + } + /** + * The notification funnel proper, keyed by the resolved era codec — + * direct sends and related notifications (`ctx.mcpReq.notify`) alike + * resolve through the instance's negotiated era at send time. + */ + async _notificationViaCodec(codec2, notification, options) { + if (!this._transport) throw new SdkError(SdkErrorCode.NotConnected, "Not connected"); + if (isSpecNotificationMethod(notification.method) && !codec2.hasNotificationMethod(notification.method)) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec2.era})`, { + method: notification.method, + era: codec2.era + }); + this.assertNotificationCapability(notification.method); + const jsonrpcNotification = this._envelopeOutbound({ + jsonrpc: "2.0", + ...notification + }); + if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { + if (this._pendingDebouncedNotifications.has(notification.method)) return; + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) return; + this._transport?.send(jsonrpcNotification, options).catch((error51) => this._onerror(error51)); + }); + return; + } + await this._transport.send(jsonrpcNotification, options); + } + setRequestHandler(method, schemasOrHandler, maybeHandler) { + this.assertRequestHandlerCapability(method); + let stored; + if (typeof schemasOrHandler === "function") { + if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); + stored = (request, ctx) => { + const dispatchCodec = this._negotiatedWireCodec(); + let outcome = dispatchCodec.validateRequest(method, request); + if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new ProtocolError(ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value, ctx)); + }; + } else if (maybeHandler) stored = async (request, ctx) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); + if (!parsed.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); + return maybeHandler(parsed.data, ctx); + }; + else throw new TypeError("setRequestHandler: handler is required"); + this._requestHandlers.set(method, this._wrapHandler(method, stored)); + } + /** + * Hook for subclasses to wrap a registered request handler with role-specific + * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` + * validates `elicitation/create` mode and result). Runs for both the 2-arg and + * 3-arg registration paths. The default implementation is identity. + * + * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. + */ + _wrapHandler(_method, handler) { + return handler; + } + /** + * Hook for subclasses to supply the implementation identity the 2026-era + * encode seam stamps into outbound result `_meta` under + * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD + * identify themselves on every response). The default is `undefined` — no + * stamp. Only `Server` overrides this: the key identifies the software + * producing a response, and the 2025-era codec never stamps anything + * regardless (the never-stamp guarantee). + */ + _outboundServerInfo() { + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + setNotificationHandler(method, schemasOrHandler, maybeHandler) { + if (typeof schemasOrHandler === "function") { + if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); + this._notificationHandlers.set(method, (notification, codec2) => { + const outcome = codec2.validateNotification(method, notification); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new ProtocolError(ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value)); + }); + return; + } + if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); + this._notificationHandlers.set(method, async (notification) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); + if (!parsed.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); + await maybeHandler(parsed.data, notification); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +}; +function isPlainObject$1(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) continue; + const baseValue = result[k]; + result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { + ...baseValue, + ...addValue + } : addValue; + } + return result; +} +function isPlainObject2(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function partitionInputResponses(inputResponses) { + const accepted = {}; + const droppedKeys = []; + if (!isPlainObject2(inputResponses)) return { + accepted, + droppedKeys + }; + for (const [key, entry] of Object.entries(inputResponses)) { + if (!isPlainObject2(entry) || "method" in entry || "result" in entry) { + droppedKeys.push(key); + continue; + } + accepted[key] = entry; + } + return { + accepted, + droppedKeys + }; +} +function manualInputRequiredValue(decoded) { + return { + resultType: "input_required", + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; +} +var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse3; + function parse3(string4) { + if (!string4) throw new TypeError("argument string is required"); + var header = typeof string4 === "object" ? getcontenttype(string4) : string4; + if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); + var index = header.indexOf(";"); + var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); + var obj = new ContentType(type.toLowerCase()); + if (index !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index) throw new TypeError("invalid parameter format"); + index += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); + } + obj.parameters[key] = value; + } + if (index !== header.length) throw new TypeError("invalid parameter format"); + } + return obj; + } + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); + else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; + if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); + return header; + } + function ContentType(type) { + this.parameters = /* @__PURE__ */ Object.create(null); + this.type = type; + } +})); +var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); +var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; + +// node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs +var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a3; + return (_a3 = this._str) !== null && _a3 !== void 0 ? _a3 : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a3; + return (_a3 = this._names) !== null && _a3 !== void 0 ? _a3 : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + const plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === '""') return a; + if (a === '""') return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === '"') return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); +var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + const code_1 = require_code$1(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a3, _b; + if (((_b = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + const line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a3; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def2 = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def2} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); +var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + const code_1 = require_code$1(); + const scope_1 = require_scope(); + var code_2 = require_code$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error51) { + super(); + this.error = error51; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode { + }; + Else.kind = "else"; + var If = class If2 extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If2 ? e : e.nodes; + if (this.nodes.length) return this; + return new If2(not(cond), e instanceof If2 ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a3; + this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a3, _b; + super.optimizeNodes(); + (_a3 = this.catch) === null || _a3 === void 0 || _a3.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a3, _b; + super.optimizeNames(names, constants); + (_a3 = this.catch) === null || _a3 === void 0 || _a3.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error51) { + super(); + this.error = error51; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error('CodeGen: "else" body without "then" body'); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error51 = this.name("e"); + this._currNode = node.catch = new Catch(error51); + catchCode(error51); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error51) { + return this._leafNode(new Throw(error51)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error('CodeGen: "else" without "if"'); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + const andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + const orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + const codegen_1 = require_codegen(); + const code_1 = require_code$1(); + function toHash(arr) { + const hash2 = {}; + for (const item of arr) hash2[item] = true; + return hash2; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues2, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues2(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + const snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type2) { + Type2[Type2["Num"] = 0] = "Num"; + Type2[Type2["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); +var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const names = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; +})); +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error51 = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error51, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error51 = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error51, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error51, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error51, errorPaths); + } + function errorObject(cxt, error51, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error51, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); +var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); +var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + const jsonTypes = /* @__PURE__ */ new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); +var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule3) => shouldUseRule(schema, rule3)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule3) { + var _a3; + return schema[rule3.keyword] !== void 0 || ((_a3 = rule3.definition.implements) === null || _a3 === void 0 ? void 0 : _a3.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); +var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + const rules_1 = require_rules(); + const applicability_1 = require_applicability(); + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error('"nullable" cannot be used without "type"'); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + const COERCIBLE = /* @__PURE__ */ new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); +var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + const newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); +var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const code_1 = require_code(); + const errors_1 = require_errors(); + function macroKeywordCode(cxt, def2) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def2.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def2) { + var _a3; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def2); + const validateRef = useKeyword(gen, keyword, !$data && def2.compile ? def2.compile.call(it.self, schema, parentSchema, it) : def2.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a3 = def2.valid) !== null && _a3 !== void 0 ? _a3 : valid); + function validateKeyword() { + if (def2.errors === false) { + assignValid(); + if (def2.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def2.async ? validateAsync() : validateSync(); + if (def2.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def2.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def2 && !$data || def2.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def2.modifying); + } + function reportErrs(errors) { + var _a$1; + gen.if((0, codegen_1.not)((_a$1 = def2.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def2) { + if (def2.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def2, keyword) { + if (Array.isArray(def2.keyword) ? !def2.keyword.includes(keyword) : def2.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def2.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def2.validateSchema) { + if (!def2.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def2.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); +var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error('both "keyword" and "schema" passed, only one allowed'); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error('both "data" and "dataProp" passed, only one allowed'); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); +var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; +})); +var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post = cb.post || function() { + }; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); +var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + const util_1 = require_util(); + const equal = require_fast_deep_equal(); + const traverse = require_json_schema_traverse(); + const SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + const REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id4 = "", normalize) { + if (normalize !== false) id4 = normalizeId2(id4); + return _getFullPath(resolver, resolver.parse(id4)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + const TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId2(id4) { + return id4 ? id4.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId2; + function resolveUrl(resolver, baseId, id4) { + id4 = normalizeId2(id4); + return resolver.resolve(baseId, id4); + } + exports.resolveUrl = resolveUrl; + const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId2(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId2(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId2(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); +var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + const boolSchema_1 = require_boolSchema(); + const dataType_1 = require_dataType(); + const applicability_1 = require_applicability(); + const dataType_2 = require_dataType(); + const defaults_1 = require_defaults(); + const keyword_1 = require_keyword(); + const subschema_1 = require_subschema(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule3 of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule3)) keywordCode(it, rule3.keyword, rule3.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule3 = rules[keyword]; + if (typeof rule3 == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule3)) { + const { type } = rule3.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def2, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def2, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def2.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def2.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def2; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def2.schemaType, def2.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def2.schemaType)}`); + } + if ("code" in def2 ? def2.trackErrors : def2.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def: def2 } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def2.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def: def2, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def2.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def2.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def2, ruleType) { + const cxt = new KeywordCxt(it, def2, keyword); + if ("code" in def2) def2.code(cxt, ruleType); + else if (cxt.$data && def2.validate) (0, keyword_1.funcKeywordCode)(cxt, def2); + else if ("macro" in def2) (0, keyword_1.macroKeywordCode)(cxt, def2); + else if (def2.compile || def2.validate) (0, keyword_1.funcKeywordCode)(cxt, def2); + } + const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); +var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); +var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); +var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + const codegen_1 = require_codegen(); + const validation_error_1 = require_validation_error(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a3; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef2(root, baseId, ref) { + var _a3; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef2; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id4 = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id4] || this.schemas[id4]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id4 === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + const PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a3; + if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); +var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { "$data": { + "type": "string", + "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] + } }, + "additionalProperties": false + }; +})); +var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) continue; + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + } + return acc; + } + const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex3 = stringArrayToHexStripped(buffer); + if (hex3 !== "") address.push(hex3); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + const address = []; + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i = 0; i < input.length; i++) { + const cursor = input[i]; + if (cursor === "[" || cursor === "]") continue; + if (cursor === ":") { + if (endipv6Encountered === true) endIpv6 = true; + if (!consume(buffer, address, output)) break; + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) break; + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); + else if (endIpv6) address.push(buffer.join("")); + else address.push(stringArrayToHexStripped(buffer)); + output.address = address.join(""); + return output; + } + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv63 = getIPV6(host); + if (!ipv63.error) { + let newHost = ipv63.address; + let escapedHost = ipv63.address; + if (ipv63.zone) { + newHost += "%" + ipv63.zone; + escapedHost += "%25" + ipv63.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) if (input === ".") break; + else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") break; + else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) output.pop(); + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) output.pop(); + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + function normalizeComponentEncoding(component, esc2) { + const func = esc2 !== true ? escape : unescape; + if (component.scheme !== void 0) component.scheme = func(component.scheme); + if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); + if (component.host !== void 0) component.host = func(component.host); + if (component.path !== void 0) component.path = func(component.path); + if (component.query !== void 0) component.query = func(component.query); + if (component.fragment !== void 0) component.fragment = func(component.fragment); + return component; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; + else host = component.host; + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; +})); +var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { isUUID } = require_utils(); + const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + const supportedSchemeNames = [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ]; + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) return true; + else if (wsComponent.secure === false) return false; + else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + else return false; + } + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; + if (!component.path) component.path = "/"; + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); + urnComponent.path = void 0; + if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); + } else urnComponent.error = urnComponent.error || "URN can not be parsed."; + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); + if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + const http = { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + }; + const https = { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + }; + const ws = { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + }; + const wss = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + }; + const urn = { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + }; + const urnuuid = { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + }; + const SCHEMES = { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + }; + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; +})); +var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + const { SCHEMES, getSchemeHandler } = require_schemes(); + function normalize(uri, options) { + if (typeof uri === "string") uri = serialize(parse3(uri, options), options); + else if (typeof uri === "object") uri = parse3(serialize(uri, options), options); + return uri; + } + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + function resolveComponent(base, relative, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse3(serialize(base, options), options); + relative = parse3(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) target.query = relative.query; + else target.query = base.query; + } else { + if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); + else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; + else if (!base.path) target.path = relative.path; + else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse3(uriA, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { + ...options, + skipEscape: true + }); + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse3(uriB, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { + ...options, + skipEscape: true + }); + return uriA.toLowerCase() === uriB.toLowerCase(); + } + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); + } else component.path = unescape(component.path); + if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") uriTokens.push("//"); + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") uriTokens.push("/"); + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); + if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); + uriTokens.push(s); + } + if (component.query !== void 0) uriTokens.push("?", component.query); + if (component.fragment !== void 0) uriTokens.push("#", component.fragment); + return uriTokens.join(""); + } + const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + function parse3(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; + else uri = "//" + uri; + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) parsed.port = matches[5]; + if (parsed.host) if (isIPv4(parsed.host) === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else isIP = true; + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; + else if (parsed.scheme === void 0) parsed.reference = "relative"; + else if (parsed.fragment === void 0) parsed.reference = "absolute"; + else parsed.reference = "uri"; + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); + if (parsed.host !== void 0) parsed.host = unescape(parsed.host); + } + if (parsed.path) parsed.path = escape(unescape(parsed.path)); + if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); + } else parsed.error = parsed.error || "URI can not be parsed."; + return parsed; + } + const fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse: parse3 + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; +})); +var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; +})); +var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + const validation_error_1 = require_validation_error(); + const ref_error_1 = require_ref_error(); + const rules_1 = require_rules(); + const compile_1 = require_compile(); + const codegen_2 = require_codegen(); + const resolve_1 = require_resolve(); + const dataType_1 = require_dataType(); + const util_1 = require_util(); + const $dataRefSchema = require_data(); + const uri_1 = require_uri(); + const defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + const META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + const EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + const removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' + }; + const MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a3 = o.code) === null || _a3 === void 0 ? void 0 : _a3.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv2 = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta: meta3, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta3 && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta: meta3, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta3) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta3); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta3); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id4; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id4 = schema[schemaId]; + if (id4 !== void 0 && typeof id4 != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id4); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id4 = schemaKeyRef[this.opts.schemaId]; + if (id4) { + id4 = (0, resolve_1.normalizeId)(id4); + delete this.schemas[id4]; + delete this.refs[id4]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def2 of definitions) this.addKeyword(def2); + return this; + } + addKeyword(kwdOrDef, def2) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def2 == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def2.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def2 === void 0) { + def2 = kwdOrDef; + keyword = def2.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def2); + if (!def2) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def2); + const definition = { + ...def2, + type: (0, dataType_1.getJSONTypes)(def2.type), + schemaType: (0, dataType_1.getJSONTypes)(def2.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule3 = this.RULES.all[keyword]; + return typeof rule3 == "object" ? rule3.definition : !!rule3; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule3) => rule3.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text3, msg) => text3 + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule3 = rules[key]; + if (typeof rule3 != "object") continue; + const { $data } = rule3.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id4; + const { schemaId } = this.opts; + if (typeof schema == "object") id4 = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id4 || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta: meta3, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id4) { + if (this.schemas[id4] || this.refs[id4]) throw new Error(`schema with key or id "${id4}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv2.ValidationError = validation_error_1.default; + Ajv2.MissingRefError = ref_error_1.default; + exports.default = Ajv2; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def2 = defs[keyword]; + if (!def2.keyword) def2.keyword = keyword; + this.addKeyword(def2); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + const noLogs = { + log() { + }, + warn() { + }, + error() { + } + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def2) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def2) return; + if (def2.$data && !("code" in def2 || "validate" in def2)) throw new Error('$data keyword must have "code" or "validate" function'); + } + function addRule(keyword, definition, dataType) { + var _a3; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule3 = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule3, definition.before); + else ruleGroup.rules.push(rule3); + RULES.all[keyword] = rule3; + (_a3 = definition.implements) === null || _a3 === void 0 || _a3.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule3, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule3); + else { + ruleGroup.rules.push(rule3); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def2) { + let { metaSchema } = def2; + if (metaSchema === void 0) return; + if (def2.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def2.validateSchema = this.compile(metaSchema, true); + } + const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); +var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def2 = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } + }; + exports.default = def2; +})); +var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + const ref_error_1 = require_ref_error(); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const util_1 = require_util(); + const def2 = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a3; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def2; +})); +var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const id_1 = require_id(); + const ref_1 = require_ref(); + const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; +})); +var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const def2 = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def2; +})); +var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def2 = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def2; +})); +var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; +})); +var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const ucs2length_1 = require_ucs2length(); + const def2 = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def2; +})); +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const util_1 = require_util(); + const codegen_1 = require_codegen(); + const def2 = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def2; +})); +var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def2 = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def2; +})); +var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def2 = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def2; +})); +var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def2 = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def2; +})); +var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; +})); +var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dataType_1 = require_dataType(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def2 = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def2; +})); +var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def2 = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; + exports.default = def2; +})); +var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def2 = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def2; +})); +var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const limitNumber_1 = require_limitNumber(); + const multipleOf_1 = require_multipleOf(); + const limitLength_1 = require_limitLength(); + const pattern_1 = require_pattern(); + const limitProperties_1 = require_limitProperties(); + const required_1 = require_required(); + const limitItems_1 = require_limitItems(); + const uniqueItems_1 = require_uniqueItems(); + const const_1 = require_const(); + const enum_1 = require_enum(); + const validation = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; + exports.default = validation; +})); +var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def2 = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def2; +})); +var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const def2 = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def2; +})); +var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const items_1 = require_items(); + const def2 = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def2; +})); +var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const additionalItems_1 = require_additionalItems(); + const def2 = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def2; +})); +var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def2 = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def2; +})); +var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + const def2 = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def2; +})); +var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def2 = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def2; +})); +var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const util_1 = require_util(); + const def2 = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def2; +})); +var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const validate_1 = require_validate(); + const code_1 = require_code(); + const util_1 = require_util(); + const additionalProperties_1 = require_additionalProperties(); + const def2 = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def2; +})); +var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const util_2 = require_util(); + const def2 = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; + exports.default = def2; +})); +var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def2 = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def2; +})); +var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def2 = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code().validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def2; +})); +var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def2 = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def2; +})); +var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def2 = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def2; +})); +var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def2 = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def2; +})); +var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def2 = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def2; +})); +var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const additionalItems_1 = require_additionalItems(); + const prefixItems_1 = require_prefixItems(); + const items_1 = require_items(); + const items2020_1 = require_items2020(); + const contains_1 = require_contains(); + const dependencies_1 = require_dependencies(); + const propertyNames_1 = require_propertyNames(); + const additionalProperties_1 = require_additionalProperties(); + const properties_1 = require_properties(); + const patternProperties_1 = require_patternProperties(); + const not_1 = require_not(); + const anyOf_1 = require_anyOf(); + const oneOf_1 = require_oneOf(); + const allOf_1 = require_allOf(); + const if_1 = require_if(); + const thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); +var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def2 = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def2; +})); +var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const format = [require_format$2().default]; + exports.default = format; +})); +var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); +var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; +})); +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); +var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const types_1 = require_types(); + const compile_1 = require_compile(); + const ref_error_1 = require_ref_error(); + const util_1 = require_util(); + const def2 = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a3; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a3 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a3 === void 0 ? void 0 : _a3[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required: required2 }) { + return Array.isArray(required2) && required2.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def2; +})); +var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { "type": "string" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": true + }; +})); +var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const discriminator_1 = require_discriminator(); + const draft7MetaSchema = require_json_schema_draft_07(); + const META_SUPPORT_DATA = ["/properties"]; + const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv2 = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv2; + module.exports = exports = Ajv2; + module.exports.Ajv = Ajv2; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); +var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicAnchor = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const ref_1 = require_ref(); + const def2 = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema) + }; + function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); + } + exports.dynamicAnchor = dynamicAnchor; + function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta: meta3 } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ + schema, + schemaId, + root, + baseId, + localRefs, + meta: meta3 + }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); + } + exports.default = def2; +})); +var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicRef = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const ref_1 = require_ref(); + const def2 = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema) + }; + function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) _dynamicRef(); + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } else _callRef(it.validateName, valid)(); + } + function _callRef(validate, valid) { + return valid ? () => gen.block(() => { + (0, ref_1.callRef)(cxt, validate); + gen.let(valid, true); + }) : () => (0, ref_1.callRef)(cxt, validate); + } + } + exports.dynamicRef = dynamicRef; + exports.default = def2; +})); +var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const util_1 = require_util(); + const def2 = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); + else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + } + }; + exports.default = def2; +})); +var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicRef_1 = require_dynamicRef(); + const def2 = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) + }; + exports.default = def2; +})); +var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const dynamicRef_1 = require_dynamicRef(); + const recursiveAnchor_1 = require_recursiveAnchor(); + const recursiveRef_1 = require_recursiveRef(); + const dynamic = [ + dynamicAnchor_1.default, + dynamicRef_1.default, + recursiveAnchor_1.default, + recursiveRef_1.default + ]; + exports.default = dynamic; +})); +var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def2 = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1.error, + code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) + }; + exports.default = def2; +})); +var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def2 = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) + }; + exports.default = def2; +})); +var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def2 = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }; + exports.default = def2; +})); +var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependentRequired_1 = require_dependentRequired(); + const dependentSchemas_1 = require_dependentSchemas(); + const limitContains_1 = require_limitContains(); + const next = [ + dependentRequired_1.default, + dependentSchemas_1.default, + limitContains_1.default + ]; + exports.default = next; +})); +var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const def2 = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error: { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` + }, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + it.props = true; + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (!(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); + return (0, codegen_1.and)(...ps); + } + } + }; + exports.default = def2; +})); +var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def2 = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) return; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1._)`${len} > ${items}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ + keyword: "unevaluatedItems", + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + }; + exports.default = def2; +})); +var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const unevaluatedProperties_1 = require_unevaluatedProperties(); + const unevaluatedItems_1 = require_unevaluatedItems(); + const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; + exports.default = unevaluated; +})); +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "title": "Core and Validation specifications meta-schema", + "allOf": [ + { "$ref": "meta/core" }, + { "$ref": "meta/applicator" }, + { "$ref": "meta/validation" }, + { "$ref": "meta/meta-data" }, + { "$ref": "meta/format" }, + { "$ref": "meta/content" } + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "dependencies": { + "$comment": '"dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"', + "type": "object", + "additionalProperties": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "meta/validation#/$defs/stringArray" }] } + } + } + }; +})); +var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, + "$recursiveAnchor": true, + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": { "$recursiveRef": "#" }, + "unevaluatedItems": { "$recursiveRef": "#" }, + "items": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "#/$defs/schemaArray" }] }, + "contains": { "$recursiveRef": "#" }, + "additionalProperties": { "$recursiveRef": "#" }, + "unevaluatedProperties": { "$recursiveRef": "#" }, + "properties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" } + }, + "propertyNames": { "$recursiveRef": "#" }, + "if": { "$recursiveRef": "#" }, + "then": { "$recursiveRef": "#" }, + "else": { "$recursiveRef": "#" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$recursiveRef": "#" } + }, + "$defs": { "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$recursiveRef": "#" } + } } + }; +})); +var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, + "$recursiveAnchor": true, + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } + }; +})); +var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, + "$recursiveAnchor": true, + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } + }; +})); +var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, + "$recursiveAnchor": true, + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); +var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, + "$recursiveAnchor": true, + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); +var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, + "$recursiveAnchor": true, + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/stringArray" } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }; +})); +var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema$1(); + const applicator = require_applicator$1(); + const content = require_content$1(); + const core = require_core$1(); + const format = require_format(); + const metadata = require_meta_data$1(); + const validation = require_validation$1(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2019($data) { + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2019; +})); +var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const discriminator_1 = require_discriminator(); + const json_schema_2019_09_1 = require_json_schema_2019_09(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; + var Ajv2019 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(dynamic_1.default); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + this.addVocabulary(next_1.default); + this.addVocabulary(unevaluated_1.default); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta: meta3 } = this.opts; + if (!meta3) return; + json_schema_2019_09_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2019 = Ajv2019; + module.exports = exports = Ajv2019; + module.exports.Ajv2019 = Ajv2019; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2019; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); +var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft2020Vocabularies = [ + dynamic_1.default, + core_1.default, + validation_1.default, + (0, applicator_1.default)(true), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default + ]; + exports.default = draft2020Vocabularies; +})); +var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + "title": "Core and Validation specifications meta-schema", + "allOf": [ + { "$ref": "meta/core" }, + { "$ref": "meta/applicator" }, + { "$ref": "meta/unevaluated" }, + { "$ref": "meta/validation" }, + { "$ref": "meta/meta-data" }, + { "$ref": "meta/format-annotation" }, + { "$ref": "meta/content" } + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": '"definitions" has been replaced by "$defs".', + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": '"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.', + "type": "object", + "additionalProperties": { "anyOf": [{ "$dynamicRef": "#meta" }, { "$ref": "meta/validation#/$defs/stringArray" }] }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": '"$recursiveAnchor" has been replaced by "$dynamicAnchor".', + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": '"$recursiveRef" has been replaced by "$dynamicRef".', + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } + }; +})); +var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, + "$dynamicAnchor": "meta", + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": { "$ref": "#/$defs/schemaArray" }, + "items": { "$dynamicRef": "#meta" }, + "contains": { "$dynamicRef": "#meta" }, + "additionalProperties": { "$dynamicRef": "#meta" }, + "properties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "propertyNames": { "$dynamicRef": "#meta" }, + "if": { "$dynamicRef": "#meta" }, + "then": { "$dynamicRef": "#meta" }, + "else": { "$dynamicRef": "#meta" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$dynamicRef": "#meta" } + }, + "$defs": { "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$dynamicRef": "#meta" } + } } + }; +})); +var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, + "$dynamicAnchor": "meta", + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } + }; +})); +var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, + "$dynamicAnchor": "meta", + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } + }; +})); +var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, + "$dynamicAnchor": "meta", + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { "$ref": "#/$defs/uriString" }, + "$ref": { "$ref": "#/$defs/uriReferenceString" }, + "$anchor": { "$ref": "#/$defs/anchorString" }, + "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, + "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, + "$vocabulary": { + "type": "object", + "propertyNames": { "$ref": "#/$defs/uriString" }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" } + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } + }; +})); +var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); +var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, + "$dynamicAnchor": "meta", + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); +var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, + "$dynamicAnchor": "meta", + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/stringArray" } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }; +})); +var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema(); + const applicator = require_applicator(); + const unevaluated = require_unevaluated(); + const content = require_content(); + const core = require_core(); + const format = require_format_annotation(); + const metadata = require_meta_data(); + const validation = require_validation(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2020($data) { + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2020; +})); +var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; + const core_1 = require_core$3(); + const draft2020_1 = require_draft2020(); + const discriminator_1 = require_discriminator(); + const json_schema_2020_12_1 = require_json_schema_2020_12(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; + var Ajv2020 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta: meta3 } = this.opts; + if (!meta3) return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2020 = Ajv2020; + module.exports = exports = Ajv2020; + module.exports.Ajv2020 = Ajv2020; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2020; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); +var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { + validate, + compare + }; + } + exports.fullFormats = { + date: fmtDef(date5, compareDate), + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + byte, + int32: { + type: "number", + validate: validateInt32 + }, + int64: { + type: "number", + validate: validateInt64 + }, + float: { + type: "number", + validate: validateNumber + }, + double: { + type: "number", + validate: validateNumber + }, + password: true, + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + const DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + function date5(str) { + const matches = DATE.exec(str); + if (!matches) return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) return void 0; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + return 0; + } + const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time3(str) { + const matches = TIME.exec(str); + if (!matches) return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; + if (hr <= 23 && min <= 59 && sec < 60) return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) return 1; + if (t1 < t2) return -1; + return 0; + } + const DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time3 = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date5(dateTime[0]) && time3(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) return void 0; + return res || compareTime(t1, t2); + } + const NOT_URI_FRAGMENT = /\/|:/; + const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + const MIN_INT32 = -(2 ** 31); + const MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + const Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } +})); +var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + const ajv_1 = require_ajv(); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + formatMaximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + formatMinimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + formatExclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + formatExclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const error51 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error: error51, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + const formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; +})); +var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const formats_1 = require_formats(); + const limit_1 = require_limit(); + const codegen_1 = require_codegen(); + const fullName = new codegen_1.Name("fullFormats"); + const fastName = new codegen_1.Name("fastFormats"); + const formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats2(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats2(ajv, opts.formats || formats_1.formatNames, formats, exportName); + if (opts.keywords) (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; + if (!f) throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats2(ajv, list, fs, exportName) { + var _a3; + var _b; + (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) ajv.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; +})); +var import_ajv = require_ajv(); +var import__2019 = require__2019(); +var import__2020 = require__2020(); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +var addFormats = import_dist.default; +function createDefaultAjvInstance(engineClass) { + const ajv = new engineClass({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + addFormats(ajv); + return ajv; +} +var AjvJsonSchemaValidator = class { + _ajv; + /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ + _ajvDraft7; + /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ + _ajv2019; + /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ + _userAjv; + /** + * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is + * used for **every** schema regardless of its declared `$schema` (the caller owns dialect + * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, + * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with + * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so + * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never + * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter + * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. + */ + constructor(ajv) { + this._userAjv = ajv !== void 0; + this._ajv = ajv; + } + /** The underlying 2020-12 engine — the default instance is created on first use. */ + get ajv() { + return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); + } + /** + * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for + * every schema — do not second-guess by `$schema` (bring-your-own-validator means + * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → + * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. + */ + _engineFor(schema) { + if (this._userAjv) return this.ajv; + const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); + if (dialect === "2020-12") return this.ajv; + if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); + return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); + } + getValidator(schema) { + const engine = this._engineFor(schema); + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); + return (input) => { + return ajvValidator(input) ? { + valid: true, + data: input, + errorMessage: void 0 + } : { + valid: false, + data: void 0, + errorMessage: engine.errorsText(ajvValidator.errors) + }; + }; + } +}; +var Ajv = import_ajv.Ajv; + +// node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs +var MAX_TIMER_DELAY_MS = 2 ** 31 - 1; +var DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; +var DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; +function resolveLegacyShimOptions(options) { + if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); + if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); + return { + maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, + roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, + legacyShim: options?.legacyShim ?? true + }; +} +function coerceEmbeddedInputRequest(method, key, entry) { + if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); + const embedded = entry; + const required2 = requiredClientCapabilitiesForInputRequest(embedded); + if (required2 === void 0) throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); + return { + embedded, + required: required2 + }; +} +function syntheticElicitationId() { + const webCrypto = globalThis.crypto; + if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); + const bytes = new Uint8Array(16); + webCrypto.getRandomValues(bytes); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + const hex3 = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`; +} +function legacyShimFailure(method, message) { + if (method === "tools/call") return { + content: [{ + type: "text", + text: message + }], + isError: true + }; + throw new ProtocolError(ProtocolErrorCode.InternalError, message); +} +var LegacyInputRequiredShim = class { + constructor(_host) { + this._host = _host; + } + async fulfill(method, handler, request, ctx, firstResult) { + const { maxRounds, roundTimeoutMs } = this._host; + const outerSignal = ctx.mcpReq.signal; + let current = firstResult; + let round = 0; + while (true) { + round += 1; + if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); + const inputRequests = current.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const requestState = typeof current.requestState === "string" ? current.requestState : void 0; + if (!hasInputRequests && requestState === void 0) throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + let responses; + if (hasInputRequests) { + const declared = this._host.resolvedClientCapabilities(ctx); + const coerced = []; + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required: required2 } = coerceEmbeddedInputRequest(method, key, entry); + if (embedded.method !== "roots/list" && embedded.params === void 0) throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); + if (missingClientCapabilities(required2, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection \u2014 per-request legacy serving cannot receive server-to-client requests)" : ""}`); + coerced.push([key, embedded]); + } + const roundAbort = linkedRoundAbort(outerSignal); + try { + const legOptions = { + relatedRequestId: ctx.mcpReq.id, + timeout: roundTimeoutMs, + resetTimeoutOnProgress: true, + onprogress: () => { + }, + signal: roundAbort.signal + }; + const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { + try { + return [key, await this._dispatchLeg(embedded, legOptions)]; + } catch (error51) { + roundAbort.abort(error51); + throw error51; + } + })); + responses = Object.fromEntries(fulfilled); + } catch (error51) { + if (outerSignal.aborted) throw error51; + return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error51 instanceof Error ? error51.message : String(error51)}`); + } finally { + roundAbort.dispose(); + } + } else await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS, outerSignal); + let ctxNext = { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + inputResponses: responses, + droppedInputResponseKeys: void 0, + requestState: requestStateAccessor(requestState) + } + }; + if (requestState !== void 0) { + const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); + if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); + } + const next = await handler(request, ctxNext); + if (!isInputRequiredResult(next)) return next; + current = next; + } + } + /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ + async _dispatchLeg(embedded, options) { + switch (embedded.method) { + case "elicitation/create": { + let params = embedded.params; + if (params.mode === "url" && params.elicitationId === void 0) params = { + ...params, + elicitationId: syntheticElicitationId() + }; + return await this._host.sendElicitation(params, options); + } + case "sampling/createMessage": + return await this._host.sendSampling(embedded.params, options); + case "roots/list": + return await this._host.listRoots(embedded.params, options); + } + } +}; +var INPUT_REQUIRED_CAPABLE_METHODS = /* @__PURE__ */ new Set([ + "tools/call", + "prompts/get", + "resources/read" +]); +var writeClientIdentity; +var installDiscoverHandler; +var readServerIdentity; +var Server = class extends Protocol { + _clientCapabilities; + _clientVersion; + static { + writeClientIdentity = (server, identity) => { + if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; + if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; + }; + installDiscoverHandler = (server, servedModernVersions) => { + const missing = servedModernVersions.filter((version3) => !server._supportedProtocolVersions.includes(version3)); + if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; + server.setRequestHandler("server/discover", () => server._ondiscover()); + }; + readServerIdentity = (server) => server._serverInfo; + } + _capabilities; + _instructions; + _jsonSchemaValidator; + _cacheHints; + _requestStateVerify; + _inputRequiredServing; + _legacyShim; + /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ + _legacyInputRequiredShim() { + return this._legacyShim ??= new LegacyInputRequiredShim({ + maxRounds: this._inputRequiredServing.maxRounds, + roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, + resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), + verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), + sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), + sendSampling: (params, options) => this.createMessage(params, options), + listRoots: (params, options) => this.listRoots(params, options) + }); + } + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). + */ + oninitialized; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this._requestStateVerify = options?.requestState?.verify; + this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); + if (options?.cacheHints !== void 0) { + for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); + this._cacheHints = options.cacheHints; + } + this.setRequestHandler("initialize", (request) => this._oninitialize(request)); + this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); + if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); + if (this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Registers the built-in `logging/setLevel` request handler. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + _registerLoggingHandler() { + this.setRequestHandler("logging/setLevel", async (request, ctx) => { + const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; + const { level } = request.params; + const parseResult = parseSchema(LoggingLevelSchema, level); + if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); + return {}; + }); + } + buildContext(ctx, transportInfo) { + const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + log: (level, data, logger) => { + if (!this._capabilities.logging) return Promise.resolve(); + let threshold; + if (this._servedModernEra()) { + threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; + if (threshold === void 0) return Promise.resolve(); + } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); + if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); + return ctx.mcpReq.notify({ + method: "notifications/message", + params: { + level, + data, + logger + } + }); + }, + elicitInput: (params, options) => this.elicitInput(params, options), + requestSampling: (params, options) => this.createMessage(params, options) + }, + http: hasHttpInfo ? { + ...ctx.http, + req: transportInfo?.request, + closeSSE: transportInfo?.closeSSEStream, + closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream + } : void 0 + }; + } + _loggingLevels = /* @__PURE__ */ new Map(); + LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) throw new SdkError(SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); + const hadLogging = !!this._capabilities.logging; + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Enforces server-side validation for `tools/call` results regardless of how the + * handler was registered, attaches the configured per-operation cache hint + * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` + * for results that do not provide their own, and owns the multi-round-trip + * seam: on the methods whose 2026-07-28 result vocabulary includes + * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an + * input-required return skips result-schema validation and is checked + * against the served era, the at-least-one rule, and the request's own + * declared client capabilities; on every other method an input-required + * return is a server bug and fails loudly. The hint rides a symbol-keyed + * property that is never serialized, so 2025-era responses are unaffected. + */ + _wrapHandler(method, handler) { + if (method !== "tools/call") { + const cacheHint = this._cacheHints?.[method]; + const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); + if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { + const result = await handler(request, ctx); + if (isInputRequiredResult(result)) throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + }; + return async (request, ctx) => { + const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); + if (isInputRequiredResult(result)) { + if (!isInputRequiredCapable) throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + } + return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); + }; + } + return async (request, ctx) => { + const codec2 = codecForVersion(this._negotiatedProtocolVersion); + const validatedRequest = codec2.validateRequest("tools/call", request); + if (!validatedRequest.ok) throw new ProtocolError(validatedRequest.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); + const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); + if (isInputRequiredResult(result)) return result; + const normalizedResult = normalizeContentlessToolResult(result); + const validationResult = codec2.validateResult("tools/call", normalizedResult); + if (!validationResult.ok) throw new ProtocolError(validationResult.reason === "not-in-era" ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); + return validationResult.value; + }; + } + /** + * Whether this instance is bound to a 2026-07-28-or-later protocol + * revision. Era is instance state — a serving entry (`createMcpHandler`, + * `serveStdio`) marks the instance modern at construction; a 2025-era + * `initialize` handshake binds it legacy. The multi-round-trip seam reads + * this directly: there is no per-request era consult. + */ + _servedModernEra() { + return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); + } + /** + * Invokes a handler for one of the multi-round-trip methods and applies + * the input-required seam: + * + * - a `UrlElicitationRequiredError` (or any 2025-style server→client + * request idiom) escaping the handler on a request served on the + * 2026-07-28 era fails LOUDLY with a clear steer to + * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the + * 2026-07-28 wire and the throw is not silently converted. Requests + * served on the 2025 era keep today's `-32042` behavior byte-exact (the + * error is rethrown unchanged). + * - an input-required RETURN toward a 2026-07-28 request must satisfy + * the at-least-one rule, and every embedded request must be covered by + * the capabilities declared on the request's envelope (violations + * answer the typed `-32021` error). Toward a 2025-era request the + * return is fulfilled by the default-on legacy shim, whose own gate + * consults the initialize-declared capabilities and surfaces + * violations per family; `inputRequired.legacyShim: false` restores + * the pre-shim loud failure. + */ + async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { + const servedModern = this._servedModernEra(); + const rawRequestState = ctx.mcpReq.requestState(); + if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + let ctxForHandler = ctx; + if (typeof rawRequestState === "string") { + const decoded = await this._verifyRequestState(rawRequestState, ctx, method); + if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); + } + let result; + try { + result = await handler(request, ctxForHandler); + } catch (error51) { + if (error51 instanceof ProtocolError && error51.code === ProtocolErrorCode.UrlElicitationRequired) { + if (!servedModern) throw error51; + throw new ProtocolError(ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { \u2026: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); + } + throw error51; + } + if (!isInputRequiredResult(result)) return result; + if (!servedModern) { + if (!this._inputRequiredServing.legacyShim) throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); + return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); + } + const inputRequests = result.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const hasRequestState = typeof result.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new ProtocolError(ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + if (hasInputRequests) { + const declared = this._inputRequestCapabilityView(ctx); + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required: required2 } = coerceEmbeddedInputRequest(method, key, entry); + const missing = missingClientCapabilities(required2, declared); + if (missing !== void 0) throw new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); + } + } + return result; + } + /** + * Runs the configured `requestState.verify` hook and returns its + * resolved value (`undefined` when unconfigured or the hook returns + * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; + * the reason goes to `onerror` only. + */ + async _verifyRequestState(state, ctx, method) { + if (this._requestStateVerify === void 0) return; + try { + return await this._requestStateVerify(state, ctx); + } catch (error51) { + this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error51 instanceof Error ? error51.message : String(error51)}`)); + throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + } + } + /** + * The per-request resolved client-capabilities view: the request's own + * `_meta` envelope on the 2026 era; the `initialize`-declared state on a + * 2025-era connection. Per-request instances that never saw an + * initialize (stateless legacy) hold nothing, so gates refuse there. + */ + _inputRequestCapabilityView(ctx) { + return this._servedModernEra() ? ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; + } + /** + * Guard for the push-style server→client request APIs ({@linkcode createMessage}, + * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a + * modern-era instance: the 2026-07-28 revision has no server→client request + * channel, so the call fails before any wire traffic with a typed error + * whose message steers to `inputRequired(...)`. The base era gate would + * also reject it; this guard runs first to carry the steer. + */ + _assertPushApiInServedEra(method) { + if (this._servedModernEra()) throw new SdkError(SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead \u2014 the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { + method, + era: "2026-07-28" + }); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); + break; + case "roots/list": + if (!this._clientCapabilities?.roots) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); + break; + case "ping": + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); + break; + case "notifications/cancelled": + break; + case "notifications/progress": + break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); + break; + case "logging/setLevel": + if (!this._capabilities.logging) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); + break; + case "ping": + case "initialize": + break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); + const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; + this._negotiatedProtocolVersion = protocolVersion; + this.transport?.setProtocolVersion?.(protocolVersion); + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` + * lists only modern revisions (2025-era versions are negotiated via `initialize`); + * the capabilities are advertised as-is, listChanged/subscribe bits included + * (see {@linkcode discoverAdvertisedCapabilities}). + */ + _ondiscover() { + return { + supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), + capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * The identity the 2026-era encode seam stamps into every outbound + * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR + * #3002: servers SHOULD identify themselves on every response). + */ + _outboundServerInfo() { + return this._serverInfo; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * declared capabilities, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * name and version, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientVersion() { + return this._clientVersion; + } + /** + * After initialization has completed, this will be populated with the protocol version negotiated + * with the client (the version the server responded with during the initialize handshake), or + * `undefined` before initialization. + * + * @deprecated Read the protocol revision from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the + * request was sent for, while on 2025-era connections this accessor keeps returning the + * `initialize`-negotiated version. The accessor remains functional — instances serving the + * 2026-07-28 era report that revision. + */ + getNegotiatedProtocolVersion() { + return this._negotiatedProtocolVersion; + } + /** + * Project a `tools/call` result through this instance's negotiated wire + * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on + * the 2025 era the `{result:…}` wrap when `structuredContent` is a + * non-object value or the advertised `outputSchema` had a non-object root. + * Identity for object-shaped `structuredContent` on the 2026 era. + * + * `McpServer`'s built-in `tools/call` handler routes through this method. + * Low-level `setRequestHandler('tools/call', …)` authors call it + * themselves so the projection lives in one place (the codec) and the + * server-side handler stays era-blind. + * + * This is the only codec function exposed on `Server` — the full + * `WireCodec` is intentionally not part of the public surface. + */ + projectCallToolResult(result, advertisedOutputSchema) { + return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); + } + /** + * Returns the current server capabilities. + */ + getCapabilities() { + return this._capabilities; + } + /** + * Sends a `ping` request to the connected client. + * + * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. + * If your factory serves both eras, this only works on the legacy path. + */ + async ping() { + this._assertPushApiInServedEra("ping"); + return this.request({ method: "ping" }); + } + async createMessage(params, options) { + this._assertPushApiInServedEra("sampling/createMessage"); + if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new SdkError(SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); + if (params.messages.length > 0) { + const lastMessage = params.messages.at(-1); + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); + if (!hasPreviousToolUse) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id4) => toolResultIds.has(id4))) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + const hasTools = Boolean(params.tools || params.toolChoice); + const wide = await this.request({ + method: "sampling/createMessage", + params + }, options); + const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); + if (!outcome.ok) throw new SdkError(SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); + return outcome.value; + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + * + * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) + * instead. The 2025 push-style server-to-client request model is replaced by input_required + * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the + * legacy path. + */ + async elicitInput(params, options) { + this._assertPushApiInServedEra("elicitation/create"); + switch (params.mode ?? "form") { + case "url": + if (!this._clientCapabilities?.elicitation?.url) throw new SdkError(SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); + break; + case "form": + if (!this._clientCapabilities?.elicitation?.form) throw new SdkError(SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); + break; + } + return this._sendElicitationLeg(params, options); + } + /** + * The capability-check-free core of {@linkcode elicitInput}. The shim + * uses it because its gate differs from the public checks: a bare + * `elicitation: {}` counts as form support (the pre-mode rule), and + * accepted content passes through unvalidated for parity with the + * modern client driver (handlers validate via the schema-aware + * `acceptedContent` overload and can re-ask). + */ + async _sendElicitationLeg(params, options, behavior) { + const mode = params.mode ?? "form"; + const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; + switch (mode) { + case "url": { + const urlParams = params; + return this.request({ + method: "elicitation/create", + params: urlParams + }, options); + } + case "form": { + const formParams = params.mode === "form" ? params : { + ...params, + mode: "form" + }; + const result = await this.request({ + method: "elicitation/create", + params: formParams + }, options); + if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { + const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); + if (!validationResult.valid) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } catch (error51) { + if (error51 instanceof ProtocolError) throw error51; + throw new ProtocolError(ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error51 instanceof Error ? error51.message : String(error51)}`); + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * The notification (and the `elicitationId` it references) exists only on protocol revision + * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the + * returned callback rejects with a typed local error before anything reaches the transport + * (the method is not part of that revision's wire registry). + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) throw new SdkError(SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { elicitationId } + }, options); + } + /** + * Requests the list of roots from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, + * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 + * push-style server-to-client request model is replaced by input_required results in the + * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. + */ + async listRoots(params, options) { + this._assertPushApiInServedEra("roots/list"); + return this.request({ + method: "roots/list", + params + }, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ + method: "notifications/message", + params + }); + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + async sendResourceListChanged() { + return this.notification({ method: "notifications/resources/list_changed" }); + } + async sendToolListChanged() { + return this.notification({ method: "notifications/tools/list_changed" }); + } + async sendPromptListChanged() { + return this.notification({ method: "notifications/prompts/list_changed" }); + } +}; +function discoverAdvertisedCapabilities(capabilities) { + return { ...capabilities }; +} + +// src/contracts/errors.ts +import { isDeepStrictEqual } from "node:util"; + +// src/contracts/plain-json.ts +var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]); +var PlainJsonError = class extends TypeError { + constructor(message, path) { + super(`${message} at ${path}`); + this.path = path; + this.name = "PlainJsonError"; + } + path; +}; +function childPath(path, key) { + return /^[A-Za-z_$][\w$]*$/u.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`; +} +function fail(message, path) { + throw new PlainJsonError(message, path); +} +function assertDescriptorStable(object3, key, before, path) { + const after = Object.getOwnPropertyDescriptor(object3, key); + if (after === void 0 || after.configurable !== before.configurable || after.enumerable !== before.enumerable || after.writable !== before.writable || after.value !== before.value || after.get !== before.get || after.set !== before.set) { + fail("value mutated while it was being inspected", path); + } +} +function inspect(value, path, ancestors) { + if (value === null || typeof value === "string" || typeof value === "boolean") return; + if (typeof value === "number") { + if (!Number.isFinite(value)) fail("non-finite numbers are not JSON values", path); + return; + } + if (typeof value !== "object") fail(`unsupported ${typeof value} value`, path); + const object3 = value; + if (ancestors.has(object3)) fail("cyclic references are not JSON values", path); + const isArray = Array.isArray(object3); + const prototype = Object.getPrototypeOf(object3); + if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) { + fail("objects must have a plain prototype", path); + } + const keys = Reflect.ownKeys(object3); + if (keys.some((key) => typeof key === "symbol")) fail("symbol keys are not JSON object keys", path); + ancestors.add(object3); + try { + if (isArray) { + const array2 = object3; + const expectedKeys = /* @__PURE__ */ new Set(["length", ...Array.from({ length: array2.length }, (_, index) => String(index))]); + for (const key of keys) { + if (typeof key !== "string" || !expectedKeys.has(key)) fail("arrays may only contain indexed elements", path); + } + for (let index = 0; index < array2.length; index += 1) { + if (!Object.prototype.hasOwnProperty.call(array2, index)) fail("sparse array holes are not JSON values", `${path}[${index}]`); + const descriptor = Object.getOwnPropertyDescriptor(array2, String(index)); + if (descriptor === void 0 || !("value" in descriptor)) fail("accessor properties are not JSON values", `${path}[${index}]`); + inspect(descriptor.value, `${path}[${index}]`, ancestors); + assertDescriptorStable(array2, String(index), descriptor, `${path}[${index}]`); + } + } else { + for (const key of keys) { + const propertyPath = childPath(path, key); + if (DANGEROUS_KEYS.has(key)) fail(`dangerous own key ${JSON.stringify(key)} is forbidden`, propertyPath); + const descriptor = Object.getOwnPropertyDescriptor(object3, key); + if (descriptor === void 0 || !("value" in descriptor)) fail("accessor properties are not JSON values", propertyPath); + if (!descriptor.enumerable) fail("non-enumerable properties are not JSON values", propertyPath); + inspect(descriptor.value, propertyPath, ancestors); + assertDescriptorStable(object3, key, descriptor, propertyPath); + } + } + const afterKeys = Reflect.ownKeys(object3); + if (keys.length !== afterKeys.length || keys.some((key, index) => key !== afterKeys[index])) { + fail("value mutated while it was being inspected", path); + } + } finally { + ancestors.delete(object3); + } +} +function assertPlainJson(value, label = "value") { + inspect(value, label, /* @__PURE__ */ new WeakSet()); +} + +// src/contracts/evidence.ts +var sha256DigestV1Schema = external_exports.string().regex(/^[0-9a-f]{64}$/u); +var safeIdV1Schema = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); +var safeCodeV1Schema = external_exports.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/u); +var safeVersionV1Schema = external_exports.string().regex(/^[A-Za-z0-9.-]{1,64}$/u); +var safeIntegerV1Schema = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER); +function parseSha256Digest(value) { + assertPlainJson(value, "SHA-256 digest"); + return sha256DigestV1Schema.parse(value); +} + +// src/contracts/phase-instance.ts +function parsePositiveSafePhaseNumber(value) { + if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) { + throw new TypeError("phase number must be a positive safe integer"); + } + return value; +} +function encodePhaseInstance(value) { + switch (value.kind) { + case "prd": + case "design": + return value.kind; + case "phase-design": + case "phase-impl": { + const phase2 = parsePositiveSafePhaseNumber(value.phase); + return `${value.kind}-${phase2}`; + } + } +} +var ITERATED_PHASE = /^(phase-design|phase-impl)-([1-9][0-9]*)$/u; +function decodePhaseInstance(value) { + if (value === "prd" || value === "design") return { kind: value }; + if (typeof value !== "string") throw new TypeError("phase instance must be a canonical string"); + const match = ITERATED_PHASE.exec(value); + if (match === null) throw new TypeError("phase instance must use a canonical phase encoding"); + const phase2 = parsePositiveSafePhaseNumber(Number(match[2])); + return match[1] === "phase-design" ? { kind: "phase-design", phase: phase2 } : { kind: "phase-impl", phase: phase2 }; +} + +// src/contracts/path-claims.ts +var utf8Length = (value) => Buffer.byteLength(value, "utf8"); +var containsControl = (value) => /[\u0000-\u001f\u007f-\u009f]/u.test(value); +var hasDriveOrUncPrefix = (value) => /^[A-Za-z]:/u.test(value) || value.startsWith("//"); +var hasInvalidComponent = (value) => value.split("/").some((component) => component === "" || component === "." || component === ".."); +var taskPathClaimV1Schema = external_exports.string().min(1).refine((value) => utf8Length(value) <= 1024, "path claim must be at most 1024 UTF-8 bytes").refine((value) => !value.startsWith("/"), "path claim must be relative").refine((value) => !hasDriveOrUncPrefix(value), "path claim must not use a drive or UNC prefix").refine((value) => !value.includes("\\"), "path claim must use forward slashes").refine((value) => !containsControl(value), "path claim must not contain control characters").refine((value) => !hasInvalidComponent(value), "path claim components must be non-empty and may not be . or .."); + +// src/contracts/vocabulary.ts +var PIPELINE_STEPS = ["produce", "self_review", "counter_review", "triage", "adjudicate"]; + +// src/contracts/gates.ts +var GATE_KINDS = ["artifact-approval", "review-trigger", "material-drift", "adjudication-failure", "attempts-exhausted", "constitution-edit", "commit-authorization", "restore-collision", "migration-audit"]; +var safeId = safeIdV1Schema; +var boundedText = external_exports.string().min(1).max(4096).regex(/\S/u); +var digest = external_exports.string().regex(/^[0-9a-f]{64}$/u); +var safeInteger = external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +var rule = external_exports.object({ rule_id: safeId, rule_version: external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER) }).strict(); +var ruleResolution = external_exports.object({ rule, resolution: boundedText }).strict(); +var waiverScope = external_exports.object({ operation: external_exports.enum(["review-trigger", "adjudication-failure"]), boundary: external_exports.enum(["subject", "phase", "task"]) }).strict(); +var authorityLink = external_exports.object({ link_digest: digest, purpose: external_exports.literal("restore-adoption"), proposed_generation_digest: digest, changed_input_fingerprint: digest }).strict(); +var reason = boundedText; +var decision = (values) => external_exports.object({ decision: external_exports.enum(values), reason }).strict(); +var sortedUnique = (items, compare) => items.every((item, index) => index === 0 || compare(items[index - 1], item) < 0); +var compareRules = (left, right) => left.rule_id.localeCompare(right.rule_id) || left.rule_version - right.rule_version; +var canonicalRules = external_exports.array(rule).superRefine((items, context) => { + if (!sortedUnique(items, compareRules)) context.addIssue({ code: "custom", message: "rules must be sorted and unique" }); +}); +var canonicalStrings = external_exports.array(safeId).superRefine((items, context) => { + if (!sortedUnique(items, (a, b) => a.localeCompare(b))) context.addIssue({ code: "custom", message: "values must be sorted and unique" }); +}); +var canonicalDigests = external_exports.array(digest).superRefine((items, context) => { + if (!sortedUnique(items, (a, b) => a.localeCompare(b))) context.addIssue({ code: "custom", message: "digests must be sorted and unique" }); +}); +var contexts = { + "artifact-approval": external_exports.object({ artifact_kind: external_exports.enum(["prd", "design", "phase-design", "phase-implementation"]) }).strict(), + "review-trigger": external_exports.object({ matched_rules: canonicalRules, uncertain_rules: canonicalRules, eligible_waiver_rules: canonicalRules, waiver_scope: waiverScope }).strict().superRefine((value, context) => { + if (value.waiver_scope.operation !== "review-trigger") context.addIssue({ code: "custom", message: "waiver operation must match gate kind" }); + const available = new Set([...value.matched_rules, ...value.uncertain_rules].map(ruleKey)); + for (const item of value.eligible_waiver_rules) if (!available.has(ruleKey(item))) context.addIssue({ code: "custom", message: "eligible waiver rule must be matched or uncertain" }); + }), + "material-drift": external_exports.object({ affected_upstream: external_exports.object({ kind: external_exports.enum(["prd", "architecture", "phase-design", "implementation-result", "review", "adjudication", "constitution", "workflow", "import"]), digest }).strict(), drift: external_exports.literal("material"), affected_claim_ids: canonicalStrings.min(1) }).strict(), + "adjudication-failure": external_exports.object({ constitution: external_exports.enum(["fail", "uncertain"]), failed_rules: canonicalRules, uncertain_rules: canonicalRules, eligible_waiver_rules: canonicalRules, waiver_scope: waiverScope }).strict().superRefine((value, context) => { + if (value.waiver_scope.operation !== "adjudication-failure") context.addIssue({ code: "custom", message: "waiver operation must match gate kind" }); + const available = new Set([...value.failed_rules, ...value.uncertain_rules].map(ruleKey)); + for (const item of value.eligible_waiver_rules) if (!available.has(ruleKey(item))) context.addIssue({ code: "custom", message: "eligible waiver rule must be failed or uncertain" }); + if (available.size === 0) context.addIssue({ code: "custom", message: "adjudication failure must identify a rule" }); + }), + "attempts-exhausted": external_exports.object({ step: external_exports.enum(PIPELINE_STEPS), attempts: safeInteger, maximum_attempts: safeInteger }).strict().refine((value) => value.attempts >= value.maximum_attempts, "attempts must be at least maximum_attempts"), + "constitution-edit": external_exports.object({ pinned_constitution_digest: digest, current_constitution_digest: digest, changed_path_class: external_exports.literal("task-branch-constitution") }).strict(), + "commit-authorization": external_exports.object({ target_ref: boundedText, diff_digest: digest, current_artifact_digests: canonicalDigests.min(1), parent_document_digests: canonicalDigests.min(1) }).strict(), + "restore-collision": external_exports.object({ path: taskPathClaimV1Schema, recorded_generation_digest: digest, current_generation_digest: digest, adoption_candidate: authorityLink.optional() }).strict(), + "migration-audit": external_exports.object({ source_identity_digest: digest, destination_identity_digest: digest, import_digest: digest, code_baseline_digest: digest, policy_baseline_digest: digest }).strict() +}; +var decisions = { + "artifact-approval": decision(["approve", "revise", "reject"]), + "review-trigger": external_exports.union([decision(["approve", "revise", "reject"]), external_exports.object({ decision: external_exports.literal("waiver-requested"), reason, rule, rationale: boundedText }).strict()]), + "material-drift": decision(["amend-upstream", "revise-current", "reject"]), + "adjudication-failure": external_exports.union([external_exports.object({ decision: external_exports.literal("approve"), reason, resolutions: external_exports.array(ruleResolution) }).strict(), decision(["revise", "reject"]), external_exports.object({ decision: external_exports.literal("waiver-requested"), reason, rule, rationale: boundedText }).strict()]), + "attempts-exhausted": decision(["retry-once", "revise", "abort"]), + "constitution-edit": decision(["revert-edit", "start-base-amendment", "abort"]), + "commit-authorization": decision(["authorize-commit", "revise", "abort"]), + "restore-collision": external_exports.union([decision(["discard-and-restore", "abort"]), external_exports.object({ decision: external_exports.literal("adopt-as-new-generation"), reason, adoption_authority: authorityLink, rationale: boundedText }).strict()]), + "migration-audit": decision(["accept-import-audit", "revise", "abort"]) +}; +var effects = Object.freeze({ + approve: "advance", + revise: "retry", + reject: "non-advancing", + "waiver-requested": "redirect-waiver", + "amend-upstream": "redirect-upstream", + "revise-current": "retry", + "retry-once": "retry", + abort: "non-advancing", + "revert-edit": "retry", + "start-base-amendment": "redirect-upstream", + "authorize-commit": "advance", + "discard-and-restore": "advance", + "adopt-as-new-generation": "advance", + "accept-import-audit": "advance" +}); +var GATE_CONTRACTS = Object.freeze(Object.fromEntries(GATE_KINDS.map((kind) => [kind, Object.freeze({ context: contexts[kind], decision: decisions[kind] })]))); +var connectedProvenance = external_exports.object({ schema_version: external_exports.literal("1"), actor_class: external_exports.enum(["human", "archforge"]), assurance: external_exports.literal("declared-local-trace"), channel: external_exports.literal("connected-host"), decision_event_id: safeId, connection_id: safeId, request_id_digest: digest, recorded_at: external_exports.string().datetime({ offset: false, local: false, precision: 3 }) }).strict(); +var localProvenance = external_exports.object({ schema_version: external_exports.literal("1"), actor_class: external_exports.enum(["human", "archforge"]), assurance: external_exports.literal("declared-local-trace"), channel: external_exports.literal("archflow-local"), decision_event_id: safeId, helper_invocation_id: safeId, recorded_at: external_exports.string().datetime({ offset: false, local: false, precision: 3 }) }).strict(); +var humanDecisionProvenanceV1Schema = external_exports.union([connectedProvenance, localProvenance]); +var envelopeBase = { schema_version: external_exports.literal("1"), gate_id: safeId, task_id: safeId, phase_instance: external_exports.string().refine((value) => { + try { + decodePhaseInstance(value); + return true; + } catch { + return false; + } +}), subject_digest: digest, context_digest: digest, human_provenance: external_exports.union([connectedProvenance, localProvenance]) }; +var gateContractV1Schema = external_exports.discriminatedUnion("kind", [ + external_exports.object({ kind: external_exports.literal("artifact-approval"), context: contexts["artifact-approval"], payload: decisions["artifact-approval"] }).strict(), + external_exports.object({ kind: external_exports.literal("review-trigger"), context: contexts["review-trigger"], payload: decisions["review-trigger"] }).strict(), + external_exports.object({ kind: external_exports.literal("material-drift"), context: contexts["material-drift"], payload: decisions["material-drift"] }).strict(), + external_exports.object({ kind: external_exports.literal("adjudication-failure"), context: contexts["adjudication-failure"], payload: decisions["adjudication-failure"] }).strict(), + external_exports.object({ kind: external_exports.literal("attempts-exhausted"), context: contexts["attempts-exhausted"], payload: decisions["attempts-exhausted"] }).strict(), + external_exports.object({ kind: external_exports.literal("constitution-edit"), context: contexts["constitution-edit"], payload: decisions["constitution-edit"] }).strict(), + external_exports.object({ kind: external_exports.literal("commit-authorization"), context: contexts["commit-authorization"], payload: decisions["commit-authorization"] }).strict(), + external_exports.object({ kind: external_exports.literal("restore-collision"), context: contexts["restore-collision"], payload: decisions["restore-collision"] }).strict(), + external_exports.object({ kind: external_exports.literal("migration-audit"), context: contexts["migration-audit"], payload: decisions["migration-audit"] }).strict() +]); +var gateDecisionEnvelopeV1Schema = external_exports.discriminatedUnion("kind", [ + external_exports.object({ ...envelopeBase, kind: external_exports.literal("artifact-approval"), payload: decisions["artifact-approval"] }).strict(), + external_exports.object({ ...envelopeBase, kind: external_exports.literal("review-trigger"), payload: decisions["review-trigger"] }).strict(), + external_exports.object({ ...envelopeBase, kind: external_exports.literal("material-drift"), payload: decisions["material-drift"] }).strict(), + external_exports.object({ ...envelopeBase, kind: external_exports.literal("adjudication-failure"), payload: decisions["adjudication-failure"] }).strict(), + external_exports.object({ ...envelopeBase, kind: external_exports.literal("attempts-exhausted"), payload: decisions["attempts-exhausted"] }).strict(), + external_exports.object({ ...envelopeBase, kind: external_exports.literal("constitution-edit"), payload: decisions["constitution-edit"] }).strict(), + external_exports.object({ ...envelopeBase, kind: external_exports.literal("commit-authorization"), payload: decisions["commit-authorization"] }).strict(), + external_exports.object({ ...envelopeBase, kind: external_exports.literal("restore-collision"), payload: decisions["restore-collision"] }).strict(), + external_exports.object({ ...envelopeBase, kind: external_exports.literal("migration-audit"), payload: decisions["migration-audit"] }).strict() +]); +function ruleKey(value) { + return `${value.rule_id}:${value.rule_version}`; +} +function parseGateContext(kind, value) { + assertPlainJson(value, `${kind} gate context`); + return contexts[kind].parse(value); +} +function parseGateDecisionEnvelope(value) { + assertPlainJson(value, "gate decision envelope"); + const parsed = gateDecisionEnvelopeV1Schema.parse(value); + if (parsed.kind === "restore-collision" && parsed.payload.decision === "adopt-as-new-generation") return parsed; + return parsed; +} +function validateGateDecision(kind, context, payload) { + parseGateContext(kind, context); + assertPlainJson(payload, `${kind} gate decision`); + const parsed = decisions[kind].parse(payload); + if (kind === "review-trigger" && parsed.decision === "waiver-requested") { + const eligible = context.eligible_waiver_rules; + if (!eligible.some((item) => ruleKey(item) === ruleKey(parsed.rule))) throw new TypeError("waiver-requested rule must be eligible"); + } + if (kind === "adjudication-failure") { + const adjudicationContext = context; + const adjudicationPayload = parsed; + const eligible = new Set(adjudicationContext.eligible_waiver_rules.map(ruleKey)); + if (adjudicationPayload.decision === "waiver-requested" && !eligible.has(ruleKey(adjudicationPayload.rule))) throw new TypeError("waiver-requested rule must be eligible"); + if (adjudicationPayload.decision === "approve") { + const required2 = new Set([...adjudicationContext.failed_rules, ...adjudicationContext.uncertain_rules].map(ruleKey).filter((key) => !eligible.has(key))); + const actual = adjudicationPayload.resolutions.map((item) => ruleKey(item.rule)); + if (!sortedUnique(adjudicationPayload.resolutions, (a, b) => compareRules(a.rule, b.rule)) || actual.length !== required2.size || actual.some((key) => !required2.has(key))) throw new TypeError("resolutions must be a sorted exact set of non-waived failed and uncertain rules"); + } + } + if (kind === "restore-collision" && parsed.decision === "adopt-as-new-generation") { + const candidate = context.adoption_candidate; + const adoptionPayload = parsed; + if (candidate === void 0 || JSON.stringify(candidate) !== JSON.stringify(adoptionPayload.adoption_authority)) throw new TypeError("restore adoption authority must exactly match the context candidate"); + } + return parsed; +} + +// src/contracts/tool-names.ts +var TOOL_NAMES = Object.freeze([ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver" +]); +function isToolName(value) { + return typeof value === "string" && TOOL_NAMES.includes(value); +} + +// src/contracts/errors.ts +var tool = external_exports.enum(TOOL_NAMES); +var adapter = external_exports.enum(["claude-cli", "codex-cli"]); +var family = external_exports.enum(["claude", "codex"]); +var gateKind = external_exports.enum(GATE_KINDS); +var phaseInstance = external_exports.string().refine((value) => { + try { + decodePhaseInstance(value); + return true; + } catch { + return false; + } +}); +var object2 = (shape) => external_exports.object(shape).strict(); +var digestPair = { expected_digest: sha256DigestV1Schema, observed_digest: sha256DigestV1Schema }; +var taskPathClass = { task_id: safeIdV1Schema, path_class: safeCodeV1Schema }; +var adapterAttempt = { adapter, attempt: safeIntegerV1Schema }; +var sortedPaths = external_exports.array(taskPathClaimV1Schema).min(1).superRefine((items, context) => { + for (let index = 1; index < items.length; index += 1) if (items[index - 1].localeCompare(items[index]) >= 0) context.addIssue({ code: "custom", message: "offending_paths must be sorted and unique" }); +}); +var PROJECT_PARAMETER_SCHEMAS = { + CONTRACT_INVALID: object2({ tool: tool.optional(), issue_code: safeCodeV1Schema, schema_version: safeVersionV1Schema.optional() }), + RESULT_INVALID: object2({ tool, result_id: safeIdV1Schema, expected_digest: sha256DigestV1Schema.optional(), observed_digest: sha256DigestV1Schema.optional() }), + CONTRACT_VERSION_UNSUPPORTED: object2({ schema_version: safeVersionV1Schema, supported_version: safeVersionV1Schema }), + WORKFLOW_INVALID: object2({ issue_code: safeCodeV1Schema }), + CONFIG_INVALID: object2({ issue_code: safeCodeV1Schema }), + CONFIG_MODEL_UNSUPPORTED: object2({ model: safeIdV1Schema }), + CONFIG_FAMILY_UNSUPPORTED: object2({ family: safeIdV1Schema }), + RUNTIME_VERSION_UNSUPPORTED: object2({ component: safeIdV1Schema, version: safeVersionV1Schema }), + REPOSITORY_NOT_FOUND: object2({ repository_candidate_digest: sha256DigestV1Schema }), + REPOSITORY_MISMATCH: object2(digestPair), + TASK_INVALID: object2({ task_id: safeIdV1Schema, issue_code: safeCodeV1Schema }), + PATH_INVALID: object2(taskPathClass), + PATH_ESCAPE: object2(taskPathClass), + TASK_SCOPE_VIOLATION: object2(taskPathClass), + GIT_CONFLICT: object2({ operation: safeCodeV1Schema }), + GIT_DIVERGED: object2(digestPair), + HANDOFF_REQUIRED: object2({ phase_instance: phaseInstance }), + POLICY_BASE_INVALID: object2({ expected_digest: sha256DigestV1Schema, observed_digest: sha256DigestV1Schema.optional() }), + WORKFLOW_MISMATCH: object2(digestPair), + PINNED_CONFIG_MISMATCH: object2(digestPair), + STALE_SKILLS: object2(digestPair), + STATE_MISSING: object2({ phase_instance: phaseInstance }), + STATE_INVALID: object2({ phase_instance: phaseInstance, issue_code: safeCodeV1Schema }), + TRANSITION_INVALID: object2({ phase_instance: phaseInstance, from: safeCodeV1Schema, to: safeCodeV1Schema }), + INPUT_FINGERPRINT_MISMATCH: object2(digestPair), + STATE_CONFLICT: object2({ expected_revision: safeIntegerV1Schema, observed_revision: safeIntegerV1Schema }), + SUPPLEMENTAL_REVIEW_REQUIRED: object2({ gate_id: safeIdV1Schema, evidence_digest: sha256DigestV1Schema }), + INTENT_MISMATCH: object2(digestPair), + SNAPSHOT_LIMIT: object2({ limit_scope: external_exports.enum(["result", "task"]), offending_paths: sortedPaths, current_bytes: safeIntegerV1Schema, byte_cap: safeIntegerV1Schema }), + SNAPSHOT_INVALID: object2({ snapshot_digest: sha256DigestV1Schema, issue_code: safeCodeV1Schema }), + RESTORE_COLLISION: object2({ gate_id: safeIdV1Schema, path_class: safeCodeV1Schema }), + RECONCILIATION_REQUIRED: object2({ recorded_digest: sha256DigestV1Schema, observed_digest: sha256DigestV1Schema }), + SECRET_DETECTED: object2({ path_class: safeCodeV1Schema, detector_id: safeIdV1Schema }), + GATE_ACTIVE: object2({ gate_id: safeIdV1Schema, gate_kind: gateKind }), + GATE_DECISION_INVALID: object2({ gate_id: safeIdV1Schema, gate_kind: gateKind, issue_code: safeCodeV1Schema }), + GATE_CANCELLED: object2({ gate_id: safeIdV1Schema, gate_kind: gateKind }), + UNSUPPORTED_HOST: object2({ host: safeIdV1Schema }), + UNSUPPORTED_MODEL: object2({ model: safeIdV1Schema }), + FAMILY_MISMATCH: object2({ expected_family: family, observed_family: family }), + CLI_VERSION_UNSUPPORTED: object2({ adapter, version: safeVersionV1Schema }), + AUTH_UNAVAILABLE: object2({ adapter }), + CLI_MISSING: object2({ adapter }), + SANDBOX_UNAVAILABLE: object2({ capability: safeIdV1Schema }), + SANDBOX_PROBE_FAILED: object2({ capability: safeIdV1Schema, failure_class: safeCodeV1Schema }), + RATE_LIMITED: object2(adapterAttempt), + TIMEOUT: object2({ ...adapterAttempt, limit_ms: safeIntegerV1Schema }), + CANCELLED: object2({ source: external_exports.enum(["client", "transport"]), attempt: safeIntegerV1Schema }), + MODEL_OUTPUT_INVALID: object2({ ...adapterAttempt, issue_code: safeCodeV1Schema }), + IO_ERROR: object2({ operation: safeCodeV1Schema, attempt: safeIntegerV1Schema }), + OUTPUT_OVERFLOW: object2({ adapter, byte_count: safeIntegerV1Schema, byte_cap: safeIntegerV1Schema }), + PROCESS_FAILED: object2({ adapter, exit_class: safeCodeV1Schema }), + INTERNAL_ERROR: object2({ correlation_id: safeIdV1Schema }) +}; +var PROTOCOL_PARAMETER_SCHEMAS = { + TOOL_NOT_FOUND: object2({ tool_name_digest: sha256DigestV1Schema }), + TOOL_DISABLED: object2({ tool, lifecycle_state: safeCodeV1Schema }), + UNSUPPORTED_PROTOCOL: object2({ offered_version: safeVersionV1Schema, supported_version: safeVersionV1Schema }), + INITIALIZATION_REPEATED: object2({ connection_id: safeIdV1Schema }) +}; +function parser(schema) { + return Object.freeze({ parse(value) { + assertPlainJson(value, "error parameters"); + return schema.parse(value); + } }); +} +function defineError(owner, retryable, schema, action, projection) { + return Object.freeze({ owner, retryable, parameter_parser: parser(schema), action, projection }); +} +var PROJECT_ERROR_DEFINITIONS = Object.freeze({ + CONTRACT_INVALID: defineError("contracts", false, PROJECT_PARAMETER_SCHEMAS.CONTRACT_INVALID, "correct-contract", "project"), + RESULT_INVALID: defineError("integrity", false, PROJECT_PARAMETER_SCHEMAS.RESULT_INVALID, "repair-retained-result", "project"), + CONTRACT_VERSION_UNSUPPORTED: defineError("contracts", false, PROJECT_PARAMETER_SCHEMAS.CONTRACT_VERSION_UNSUPPORTED, "upgrade-caller", "project"), + WORKFLOW_INVALID: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.WORKFLOW_INVALID, "repair-workflow", "project"), + CONFIG_INVALID: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.CONFIG_INVALID, "repair-config", "project"), + CONFIG_MODEL_UNSUPPORTED: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.CONFIG_MODEL_UNSUPPORTED, "select-supported-model", "project"), + CONFIG_FAMILY_UNSUPPORTED: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.CONFIG_FAMILY_UNSUPPORTED, "select-supported-family", "project"), + RUNTIME_VERSION_UNSUPPORTED: defineError("config", false, PROJECT_PARAMETER_SCHEMAS.RUNTIME_VERSION_UNSUPPORTED, "upgrade-runtime", "project"), + REPOSITORY_NOT_FOUND: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.REPOSITORY_NOT_FOUND, "open-repository", "project"), + REPOSITORY_MISMATCH: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.REPOSITORY_MISMATCH, "reopen-task-worktree", "project"), + TASK_INVALID: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.TASK_INVALID, "repair-task", "project"), + PATH_INVALID: defineError("paths", false, PROJECT_PARAMETER_SCHEMAS.PATH_INVALID, "use-valid-path-claim", "project"), + PATH_ESCAPE: defineError("paths", false, PROJECT_PARAMETER_SCHEMAS.PATH_ESCAPE, "use-task-relative-path", "project"), + TASK_SCOPE_VIOLATION: defineError("paths", false, PROJECT_PARAMETER_SCHEMAS.TASK_SCOPE_VIOLATION, "use-task-scoped-path", "project"), + GIT_CONFLICT: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.GIT_CONFLICT, "resolve-git-conflict", "project"), + GIT_DIVERGED: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.GIT_DIVERGED, "reconcile-git-history", "project"), + HANDOFF_REQUIRED: defineError("repository", false, PROJECT_PARAMETER_SCHEMAS.HANDOFF_REQUIRED, "complete-clean-handoff", "project"), + POLICY_BASE_INVALID: defineError("policy", false, PROJECT_PARAMETER_SCHEMAS.POLICY_BASE_INVALID, "restore-policy-base", "project"), + WORKFLOW_MISMATCH: defineError("policy", false, PROJECT_PARAMETER_SCHEMAS.WORKFLOW_MISMATCH, "restore-pinned-workflow", "project"), + PINNED_CONFIG_MISMATCH: defineError("policy", false, PROJECT_PARAMETER_SCHEMAS.PINNED_CONFIG_MISMATCH, "restore-pinned-config", "project"), + STALE_SKILLS: defineError("policy", false, PROJECT_PARAMETER_SCHEMAS.STALE_SKILLS, "refresh-skills", "project"), + STATE_MISSING: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.STATE_MISSING, "initialize-state", "project"), + STATE_INVALID: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.STATE_INVALID, "repair-state", "project"), + TRANSITION_INVALID: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.TRANSITION_INVALID, "select-valid-transition", "project"), + INPUT_FINGERPRINT_MISMATCH: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.INPUT_FINGERPRINT_MISMATCH, "create-fresh-intent", "project"), + STATE_CONFLICT: defineError("state", true, PROJECT_PARAMETER_SCHEMAS.STATE_CONFLICT, "reread-and-retry-intent", "project"), + SUPPLEMENTAL_REVIEW_REQUIRED: defineError("state", false, PROJECT_PARAMETER_SCHEMAS.SUPPLEMENTAL_REVIEW_REQUIRED, "triage-supplemental-review", "project"), + INTENT_MISMATCH: defineError("intent", false, PROJECT_PARAMETER_SCHEMAS.INTENT_MISMATCH, "create-fresh-intent", "project"), + SNAPSHOT_LIMIT: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.SNAPSHOT_LIMIT, "reduce-snapshot", "project"), + SNAPSHOT_INVALID: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.SNAPSHOT_INVALID, "repair-snapshot", "project"), + RESTORE_COLLISION: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.RESTORE_COLLISION, "resolve-restore-gate", "project"), + RECONCILIATION_REQUIRED: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.RECONCILIATION_REQUIRED, "run-reconciliation", "project"), + SECRET_DETECTED: defineError("snapshot", false, PROJECT_PARAMETER_SCHEMAS.SECRET_DETECTED, "remove-secret", "project"), + GATE_ACTIVE: defineError("gate", false, PROJECT_PARAMETER_SCHEMAS.GATE_ACTIVE, "resolve-recorded-gate", "project"), + GATE_DECISION_INVALID: defineError("gate", false, PROJECT_PARAMETER_SCHEMAS.GATE_DECISION_INVALID, "record-valid-gate-decision", "project"), + GATE_CANCELLED: defineError("gate", false, PROJECT_PARAMETER_SCHEMAS.GATE_CANCELLED, "restart-gate-flow", "project"), + UNSUPPORTED_HOST: defineError("routing", false, PROJECT_PARAMETER_SCHEMAS.UNSUPPORTED_HOST, "select-supported-host", "project"), + UNSUPPORTED_MODEL: defineError("routing", false, PROJECT_PARAMETER_SCHEMAS.UNSUPPORTED_MODEL, "select-supported-model", "project"), + FAMILY_MISMATCH: defineError("routing", false, PROJECT_PARAMETER_SCHEMAS.FAMILY_MISMATCH, "select-correct-family", "project"), + CLI_VERSION_UNSUPPORTED: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.CLI_VERSION_UNSUPPORTED, "upgrade-cli", "project"), + AUTH_UNAVAILABLE: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.AUTH_UNAVAILABLE, "repair-authentication", "project"), + CLI_MISSING: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.CLI_MISSING, "install-cli", "project"), + SANDBOX_UNAVAILABLE: defineError("sandbox", false, PROJECT_PARAMETER_SCHEMAS.SANDBOX_UNAVAILABLE, "repair-sandbox", "project"), + SANDBOX_PROBE_FAILED: defineError("sandbox", false, PROJECT_PARAMETER_SCHEMAS.SANDBOX_PROBE_FAILED, "repair-sandbox", "project"), + RATE_LIMITED: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.RATE_LIMITED, "retry-after-backoff", "project"), + TIMEOUT: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.TIMEOUT, "retry-unchanged-attempt", "project"), + CANCELLED: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.CANCELLED, "restart-child-attempt", "project"), + MODEL_OUTPUT_INVALID: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.MODEL_OUTPUT_INVALID, "retry-unchanged-attempt", "project"), + IO_ERROR: defineError("dispatch", true, PROJECT_PARAMETER_SCHEMAS.IO_ERROR, "retry-unchanged-attempt", "project"), + OUTPUT_OVERFLOW: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.OUTPUT_OVERFLOW, "reduce-output", "project"), + PROCESS_FAILED: defineError("dispatch", false, PROJECT_PARAMETER_SCHEMAS.PROCESS_FAILED, "repair-before-fresh-attempt", "project"), + INTERNAL_ERROR: defineError("integrity", false, PROJECT_PARAMETER_SCHEMAS.INTERNAL_ERROR, "stop-and-inspect", "project") +}); +var PROTOCOL_ERROR_DEFINITIONS = Object.freeze({ + TOOL_NOT_FOUND: defineError("protocol", false, PROTOCOL_PARAMETER_SCHEMAS.TOOL_NOT_FOUND, "call-advertised-tool", "protocol"), + TOOL_DISABLED: defineError("protocol", false, PROTOCOL_PARAMETER_SCHEMAS.TOOL_DISABLED, "wait-for-tool-enable", "protocol"), + UNSUPPORTED_PROTOCOL: defineError("protocol", false, PROTOCOL_PARAMETER_SCHEMAS.UNSUPPORTED_PROTOCOL, "negotiate-supported-protocol", "protocol"), + INITIALIZATION_REPEATED: defineError("protocol", false, PROTOCOL_PARAMETER_SCHEMAS.INITIALIZATION_REPEATED, "open-new-connection", "protocol") +}); +function constructError(registry2, code, parameters) { + const definition = registry2[code]; + const parsed = definition.parameter_parser.parse(parameters); + return Object.freeze({ schema_version: "1", code, owner: definition.owner, retryable: definition.retryable, diagnostic: Object.freeze({ template_id: code, parameters: parsed }), next_action: definition.action }); +} +function createProjectError(code, parameters) { + return constructError(PROJECT_ERROR_DEFINITIONS, code, parameters); +} +function createProtocolError(code, parameters) { + return constructError(PROTOCOL_ERROR_DEFINITIONS, code, parameters); +} +function parseSerializedError(registry2, value, label) { + assertPlainJson(value, label); + const shell = object2({ schema_version: external_exports.literal("1"), code: external_exports.string(), owner: external_exports.string(), retryable: external_exports.boolean(), diagnostic: object2({ template_id: external_exports.string(), parameters: external_exports.record(external_exports.string(), external_exports.unknown()) }), next_action: external_exports.string() }).parse(value); + if (!Object.hasOwn(registry2, shell.code)) throw new TypeError(`${label}: unknown code`); + const code = shell.code; + const expected = constructError(registry2, code, shell.diagnostic.parameters); + if (!isDeepStrictEqual(shell, expected)) throw new TypeError(`${label}: fields do not match the error registry`); + return value; +} +function parseProjectError(value) { + return parseSerializedError(PROJECT_ERROR_DEFINITIONS, value, "project error"); +} +function parseProtocolError(value) { + return parseSerializedError(PROTOCOL_ERROR_DEFINITIONS, value, "protocol error"); +} + +// src/contracts/contexts.ts +var authenticConnections = /* @__PURE__ */ new WeakSet(); +var authenticInvocations = /* @__PURE__ */ new WeakSet(); +var ProtocolContextError = class extends Error { + constructor(protocol_error) { + super(protocol_error.code); + this.protocol_error = protocol_error; + this.name = "ProtocolContextError"; + } + protocol_error; +}; +var id = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); +var text = external_exports.string().min(1).max(4096).regex(/\S/u); +var version2 = external_exports.string().regex(/^[A-Za-z0-9.-]{1,64}$/u); +var requestIdSchema = external_exports.union([external_exports.string(), external_exports.number().int().safe()]); +var clientImplementationSchema = external_exports.object({ name: external_exports.string(), version: external_exports.string() }).strict(); +var startupSchema = external_exports.object({ connection_id: id, startup_repository_candidate: external_exports.object({ working_directory: text }).strict() }).strict(); +var initializationSchema = external_exports.object({ client: clientImplementationSchema, host: external_exports.enum(["claude", "codex", "unknown"]), protocol_version: version2 }).strict(); +var invocationSchema = external_exports.object({ invocation_id: id, transport_metadata: external_exports.object({ request_id: requestIdSchema, operation: external_exports.literal("tools/call") }).strict() }).strict(); +function deepFreeze(value) { + if (value !== null && typeof value === "object") { + for (const nested of Object.values(value)) deepFreeze(nested); + Object.freeze(value); + } + return value; +} +function copy(value) { + return structuredClone(value); +} +var connectionContextFactory = Object.freeze({ captureStartup(seed) { + assertPlainJson(seed, "connection startup"); + const startup = deepFreeze(copy(startupSchema.parse(seed))); + let initialized = false; + return Object.freeze({ initialize(candidates) { + if (initialized) throw new ProtocolContextError(createProtocolError("INITIALIZATION_REPEATED", { connection_id: startup.connection_id })); + assertPlainJson(candidates, "connection initialization"); + const initialization = deepFreeze(copy(initializationSchema.parse(candidates))); + initialized = true; + const connection = deepFreeze({ connection_id: startup.connection_id, startup_repository_candidate: startup.startup_repository_candidate, initialization_candidates: initialization }); + authenticConnections.add(connection); + return connection; + } }); +} }); +function createInvocationContext(connection, seed, signal) { + if (!authenticConnections.has(connection)) throw new TypeError("a branded connection context is required"); + if (!(signal instanceof AbortSignal)) throw new TypeError("an AbortSignal is required"); + assertPlainJson(seed, "invocation context"); + const invocation = deepFreeze(copy(invocationSchema.parse(seed))); + const context = Object.freeze({ invocation_id: invocation.invocation_id, connection, signal, transport_metadata: invocation.transport_metadata }); + authenticInvocations.add(context); + return context; +} +function assertAuthenticInvocationContext(value) { + if (value === null || typeof value !== "object" || !authenticInvocations.has(value)) throw new TypeError("an authentic invocation context is required"); +} + +// src/mcp/framing.ts +var MAX_FRAME_BYTES = 10 * 1024 * 1024; +var LINE_FEED = 10; +var CARRIAGE_RETURN = 13; +var nonfatalParseError = () => ({ kind: "parse-error", fatal: false }); +var fatalParseError = () => ({ kind: "parse-error", fatal: true }); +function createJsonLineFramer() { + let retained = new Uint8Array(); + let offset = 0; + let fatalPending = false; + let stopped = false; + const compact = () => { + if (offset === 0) return; + retained = retained.slice(offset); + offset = 0; + }; + const fail2 = () => { + retained = new Uint8Array(); + offset = 0; + fatalPending = true; + }; + const append = (chunk) => { + if (stopped || fatalPending || chunk.byteLength === 0) return; + compact(); + if (retained.byteLength + chunk.byteLength > MAX_FRAME_BYTES + 2) { + fail2(); + return; + } + const combined = new Uint8Array(retained.byteLength + chunk.byteLength); + combined.set(retained); + combined.set(chunk, retained.byteLength); + retained = combined; + }; + const next = () => { + if (stopped) return void 0; + if (fatalPending) { + fatalPending = false; + stopped = true; + return fatalParseError(); + } + const lineFeed = retained.indexOf(LINE_FEED, offset); + if (lineFeed === -1) { + if (retained.byteLength - offset > MAX_FRAME_BYTES) { + fail2(); + return next(); + } + return void 0; + } + let end = lineFeed; + if (end > offset && retained[end - 1] === CARRIAGE_RETURN) end -= 1; + const frameBytes = retained.subarray(offset, end); + offset = lineFeed + 1; + if (frameBytes.byteLength > MAX_FRAME_BYTES) { + fail2(); + return next(); + } + try { + const source = new TextDecoder("utf-8", { fatal: true }).decode(frameBytes); + return { kind: "json", value: JSON.parse(source) }; + } catch (error51) { + if (error51 instanceof TypeError && frameBytes.byteLength !== 0) { + fail2(); + return next(); + } + return nonfatalParseError(); + } + }; + const finish = () => { + const frame = next(); + if (frame !== void 0) return frame; + if (stopped) return void 0; + if (retained.byteLength - offset > 0) { + const partial2 = retained.subarray(offset); + try { + new TextDecoder("utf-8", { fatal: true }).decode(partial2); + } catch { + fail2(); + return next(); + } + retained = new Uint8Array(); + offset = 0; + stopped = true; + return nonfatalParseError(); + } + stopped = true; + return void 0; + }; + return { + get retainedBytes() { + return retained.byteLength - offset; + }, + append, + next, + finish + }; +} + +// src/mcp/send-queue.ts +var MAX_ENTRIES = 1024; +var MAX_BYTES = 10 * 1024 * 1024; +function deferred2() { + let resolvePromise; + let rejectPromise; + const promise2 = new Promise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + return { promise: promise2, resolve: resolvePromise, reject: rejectPromise }; +} +function asError(value, fallback) { + return value instanceof Error ? value : new Error(fallback); +} +function createSendQueue(output, onBackpressureChange, onFatal) { + const waiting = []; + const incomplete = /* @__PURE__ */ new Set(); + let incompleteBytes = 0; + let paused = false; + let closed = false; + let pumping = false; + const closeError = new Error("Send queue closed"); + function notifyBackpressure(value) { + if (paused === value) { + return true; + } + paused = value; + try { + onBackpressureChange(value); + return true; + } catch (error51) { + fail2(asError(error51, "Backpressure notification failed")); + return false; + } + } + function removeListeners() { + output.off("drain", handleDrain); + output.off("error", handleOutputError); + } + function rejectIncomplete(error51) { + waiting.length = 0; + for (const pending of incomplete) { + if (!pending.writeReturned) { + pending.admitted.reject(error51); + } + pending.completed.reject(error51); + } + incomplete.clear(); + incompleteBytes = 0; + } + function shutDown(error51, fatal) { + if (closed) { + return; + } + closed = true; + removeListeners(); + const wasPaused = paused; + paused = false; + rejectIncomplete(error51); + if (wasPaused) { + try { + onBackpressureChange(false); + } catch { + } + } + if (fatal) { + try { + onFatal(); + } catch { + } + } + } + function fail2(error51) { + shutDown(error51, true); + } + function finish(pending, error51) { + if (!incomplete.has(pending)) { + return; + } + if (error51 != null) { + pending.completed.reject(error51); + fail2(error51); + return; + } + incomplete.delete(pending); + incompleteBytes -= pending.entry.frame.byteLength; + pending.completed.resolve(); + pump(); + } + function handleWriteCallback(pending, error51) { + if (!pending.writeReturned) { + pending.callbackCalled = true; + pending.callbackError = error51; + return; + } + finish(pending, error51); + } + function pump() { + if (pumping || paused || closed) { + return; + } + pumping = true; + try { + while (!paused && !closed) { + const pending = waiting.shift(); + if (pending === void 0) { + break; + } + let accepted; + try { + accepted = output.write(pending.entry.frame, (error51) => { + handleWriteCallback(pending, error51); + }); + pending.writeReturned = true; + pending.admitted.resolve(); + } catch (error51) { + pending.writeReturned = true; + const writeError = asError(error51, "Output write failed"); + pending.admitted.reject(writeError); + pending.completed.reject(writeError); + incomplete.delete(pending); + incompleteBytes -= pending.entry.frame.byteLength; + fail2(writeError); + break; + } + if (!accepted && !closed) { + notifyBackpressure(true); + } + if (pending.callbackCalled && !closed) { + finish(pending, pending.callbackError); + } + } + } finally { + pumping = false; + } + } + function handleDrain() { + if (!closed && paused && notifyBackpressure(false)) { + pump(); + } + } + function handleOutputError(error51) { + fail2(asError(error51, "Output stream failed")); + } + output.on("drain", handleDrain); + output.on("error", handleOutputError); + return { + get backpressured() { + return paused; + }, + enqueue(entry) { + const admitted = deferred2(); + const completed = deferred2(); + const receipt = { admitted: admitted.promise, completed: completed.promise }; + if (closed) { + admitted.reject(closeError); + completed.reject(closeError); + return receipt; + } + const nextBytes = incompleteBytes + entry.frame.byteLength; + if (entry.frame.byteLength > MAX_BYTES || incomplete.size >= MAX_ENTRIES || nextBytes > MAX_BYTES) { + const overflowError = new Error("Send queue capacity exceeded"); + admitted.reject(overflowError); + completed.reject(overflowError); + fail2(overflowError); + return receipt; + } + const pending = { + entry, + admitted, + completed, + writeReturned: false, + callbackCalled: false, + callbackError: void 0 + }; + waiting.push(pending); + incomplete.add(pending); + incompleteBytes = nextBytes; + pump(); + return receipt; + }, + async close() { + shutDown(closeError, false); + } + }; +} + +// src/mcp/server.ts +import { createHash as createHash2 } from "node:crypto"; + +// src/contracts/mcp-tools.ts +import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util"; + +// src/contracts/review.ts +var REVIEW_VERDICTS = ["pass", "advisory", "fail"]; +var REVIEW_ROLES = ["self-review", "counter-review", "gate-counter-review"]; +var REVIEW_FINDING_SEVERITIES = ["blocker", "major", "minor"]; +var MODEL_FAMILIES = ["claude", "codex"]; +var ADAPTER_IDS = ["claude-cli", "codex-cli"]; +var EFFORT_VALUES = ["low", "medium", "high", "xhigh", "max", "ultra"]; +var nonBlank = external_exports.string().min(1).refine((value) => value.trim().length > 0, "must contain a non-whitespace character"); +var id2 = external_exports.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u); +var digest2 = external_exports.string().regex(/^[0-9a-f]{64}$/u); +var safePositive = external_exports.number().int().positive().safe(); +var ruleVersionRefSchema = external_exports.object({ rule_id: id2, rule_version: safePositive }).strict(); +var reviewFindingSchema = external_exports.object({ + finding_id: id2, + severity: external_exports.enum(REVIEW_FINDING_SEVERITIES), + blocking: external_exports.boolean(), + summary: nonBlank, + evidence: nonBlank, + suggested_resolution: nonBlank +}).strict().superRefine((finding, context) => { + if (finding.blocking !== (finding.severity === "blocker")) { + context.addIssue({ code: "custom", path: ["blocking"], message: "only blocker findings are blocking" }); + } +}); +var rawReviewSchema = external_exports.object({ + schema_version: external_exports.literal("1"), + task_id: id2, + phase_instance: external_exports.string().regex(/^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$/u), + step: external_exports.enum(["self_review", "counter_review"]), + role: external_exports.enum(REVIEW_ROLES), + subject_digest: digest2, + input_fingerprint: digest2, + rubric_digest: digest2, + producer_family: external_exports.enum(MODEL_FAMILIES), + findings: external_exports.array(reviewFindingSchema), + matched_rule_versions: external_exports.array(ruleVersionRefSchema), + verdict: external_exports.enum(REVIEW_VERDICTS), + blocking_count: external_exports.number().int().nonnegative().safe() +}).strict().superRefine((review, context) => { + const findingIds = /* @__PURE__ */ new Set(); + review.findings.forEach((finding, index) => { + if (findingIds.has(finding.finding_id)) context.addIssue({ code: "custom", path: ["findings", index, "finding_id"], message: "duplicate finding_id" }); + findingIds.add(finding.finding_id); + }); + const rules = /* @__PURE__ */ new Set(); + review.matched_rule_versions.forEach((rule3, index) => { + const key = `${rule3.rule_id}:${rule3.rule_version}`; + if (rules.has(key)) context.addIssue({ code: "custom", path: ["matched_rule_versions", index], message: "duplicate rule version" }); + rules.add(key); + }); + if (review.role === "self-review" && review.step !== "self_review") context.addIssue({ code: "custom", path: ["step"], message: "self-review role requires self_review step" }); + if (review.role !== "self-review" && review.step !== "counter_review") context.addIssue({ code: "custom", path: ["step"], message: "counter-review roles require counter_review step" }); + const expected = expectedReviewSummary(review.findings); + if (review.blocking_count !== expected.blocking_count) context.addIssue({ code: "custom", path: ["blocking_count"], message: `review blocking_count must be ${expected.blocking_count}` }); + if (review.verdict !== expected.verdict) context.addIssue({ code: "custom", path: ["verdict"], message: `review verdict must be ${expected.verdict}` }); +}); +function expectedReviewSummary(findings) { + const blocking_count = findings.filter((finding) => finding.blocking).length; + return { blocking_count, verdict: blocking_count > 0 ? "fail" : findings.length > 0 ? "advisory" : "pass" }; +} +function validateReviewClaims(parsed) { + const expected = expectedReviewSummary(parsed.findings); + if (parsed.blocking_count !== expected.blocking_count) throw new TypeError(`review blocking_count must be ${expected.blocking_count}`); + if (parsed.verdict !== expected.verdict) throw new TypeError(`review verdict must be ${expected.verdict}`); +} +function parseAndDeriveReview(value) { + assertPlainJson(value, "review"); + const parsed = rawReviewSchema.parse(value); + validateReviewClaims(parsed); + return parsed; +} +var provenanceBase = rawReviewSchema.safeExtend({ + model_family: external_exports.union([external_exports.enum(MODEL_FAMILIES), external_exports.literal("unknown")]), + model: nonBlank, + effort: external_exports.union([external_exports.enum(EFFORT_VALUES), external_exports.literal("unknown")]) +}); +var agentDeclaredReviewSchema = provenanceBase.safeExtend({ assurance: external_exports.literal("agent-declared") }).strict(); +var serverAttestedReviewSchema = provenanceBase.safeExtend({ + assurance: external_exports.literal("server-attested"), + adapter: external_exports.enum(ADAPTER_IDS), + cli_version: nonBlank, + model_family: external_exports.enum(MODEL_FAMILIES), + effort: external_exports.enum(EFFORT_VALUES), + invocation_id: id2, + envelope_input_digest: digest2, + observed_output_digest: digest2, + result_id: id2 +}).strict().superRefine((review, context) => { + if (review.role === "self-review") context.addIssue({ code: "custom", path: ["role"], message: "self-review cannot be server-attested" }); + const expectedReviewer = review.producer_family === "claude" ? "codex" : "claude"; + if (review.model_family !== expectedReviewer) context.addIssue({ code: "custom", path: ["model_family"], message: "server-attested review must be opposite-family" }); +}); +var degradedReviewSchema = provenanceBase.safeExtend({ assurance: external_exports.literal("degraded"), reason: nonBlank }).strict(); +var reviewEvidenceSchema = external_exports.discriminatedUnion("assurance", [agentDeclaredReviewSchema, serverAttestedReviewSchema, degradedReviewSchema]); + +// src/contracts/adjudication.ts +var CONSTITUTION_RESULTS = ["pass", "fail", "uncertain"]; +var DRIFT_RESULTS = ["aligned", "incidental", "material"]; +var COMPLIANCE_RESULTS = ["pass", "fail", "uncertain"]; +var TRIGGER_RESULTS = ["not-matched", "matched", "uncertain"]; +var MECHANICAL_EVIDENCE_STATES = ["current", "missing", "stale", "unknown", "failed", "digest-mismatch"]; +var nonBlank2 = external_exports.string().min(1).refine((value) => value.trim().length > 0, "must contain a non-whitespace character"); +var id3 = external_exports.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u); +var digest3 = external_exports.string().regex(/^[0-9a-f]{64}$/u); +var mechanicalEvidenceSchema = external_exports.object({ + mechanism: nonBlank2, + state: external_exports.enum(MECHANICAL_EVIDENCE_STATES), + subject_digest: digest3.optional(), + evidence_digest: digest3.optional(), + details: nonBlank2 +}).strict().superRefine((evidence, context) => { + const hasBindings = evidence.subject_digest !== void 0 && evidence.evidence_digest !== void 0; + if ((evidence.state === "current" || evidence.state === "stale") && !hasBindings) context.addIssue({ code: "custom", message: `${evidence.state} evidence requires subject and evidence digests` }); + if ((evidence.state === "missing" || evidence.state === "unknown") && (evidence.subject_digest !== void 0 || evidence.evidence_digest !== void 0)) context.addIssue({ code: "custom", message: `${evidence.state} evidence cannot claim digests` }); +}); +var constitutionRuleFindingSchema = ruleVersionRefSchema.extend({ + compliance: external_exports.enum(COMPLIANCE_RESULTS), + rationale: nonBlank2, + trigger: external_exports.enum(TRIGGER_RESULTS), + trigger_evidence: nonBlank2, + enforced_by: external_exports.array(mechanicalEvidenceSchema) +}).strict(); +var driftFindingSchema = external_exports.object({ + upstream_digest: digest3, + drift: external_exports.enum(DRIFT_RESULTS), + affected_claim_ids: external_exports.array(id3), + rationale: nonBlank2 +}).strict().superRefine((finding, context) => { + if (finding.drift === "aligned" !== (finding.affected_claim_ids.length === 0)) context.addIssue({ code: "custom", path: ["affected_claim_ids"], message: "aligned drift has no affected claims; other drift must identify claims" }); + if (new Set(finding.affected_claim_ids).size !== finding.affected_claim_ids.length) context.addIssue({ code: "custom", path: ["affected_claim_ids"], message: "duplicate affected claim" }); +}); +var rawAdjudicationSchema = external_exports.object({ + schema_version: external_exports.literal("1"), + task_id: id3, + phase_instance: external_exports.string().regex(/^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$/u), + step: external_exports.literal("adjudicate"), + subject_digest: digest3, + input_fingerprint: digest3, + pinned_constitution_digest: digest3, + approved_upstream_digests: external_exports.array(digest3), + source_evidence_set_digest: digest3, + rule_findings: external_exports.array(constitutionRuleFindingSchema), + drift_findings: external_exports.array(driftFindingSchema), + constitution: external_exports.enum(CONSTITUTION_RESULTS), + drift: external_exports.enum(DRIFT_RESULTS), + matched_rule_versions: external_exports.array(ruleVersionRefSchema), + uncertain_rule_versions: external_exports.array(ruleVersionRefSchema) +}).strict().superRefine((adjudication, context) => { + try { + validateAdjudicationClaims(adjudication); + } catch (error51) { + context.addIssue({ code: "custom", message: error51 instanceof Error ? error51.message : "invalid adjudication semantics" }); + } +}); +var ruleKey2 = (rule3) => `${rule3.rule_id}:${rule3.rule_version}`; +function assertSortedUnique(values, label) { + if (new Set(values).size !== values.length || values.some((value, index) => index > 0 && values[index - 1] >= value)) throw new TypeError(`${label} must be sorted and unique`); +} +function sameRuleSet(actual, expected) { + return actual.length === expected.length && actual.every((rule3, index) => ruleKey2(rule3) === ruleKey2(expected[index])); +} +function validateAdjudicationClaims(parsed) { + assertSortedUnique(parsed.approved_upstream_digests, "approved_upstream_digests"); + assertSortedUnique(parsed.rule_findings.map(ruleKey2), "rule_findings"); + assertSortedUnique(parsed.drift_findings.map((finding) => finding.upstream_digest), "drift_findings"); + if (parsed.drift_findings.length !== parsed.approved_upstream_digests.length || parsed.drift_findings.some((finding, index) => finding.upstream_digest !== parsed.approved_upstream_digests[index])) throw new TypeError("drift_findings must exactly cover approved_upstream_digests"); + for (const finding of parsed.rule_findings) { + if (finding.compliance === "pass" && finding.enforced_by.length === 0) throw new TypeError(`compliance pass for ${ruleKey2(finding)} requires current mechanical evidence`); + for (const evidence of finding.enforced_by) { + if (evidence.state === "current" && evidence.subject_digest !== parsed.subject_digest) throw new TypeError(`current mechanical evidence for ${ruleKey2(finding)} binds the wrong subject`); + if (evidence.state !== "current" && finding.compliance === "pass") throw new TypeError(`suspect mechanical evidence cannot establish compliance for ${ruleKey2(finding)}`); + } + } + const expectedConstitution = parsed.rule_findings.some((finding) => finding.compliance === "fail") ? "fail" : parsed.rule_findings.some((finding) => finding.compliance === "uncertain") ? "uncertain" : "pass"; + if (parsed.constitution !== expectedConstitution) throw new TypeError(`constitution must be ${expectedConstitution}`); + const expectedDrift = parsed.drift_findings.some((finding) => finding.drift === "material") ? "material" : parsed.drift_findings.some((finding) => finding.drift === "incidental") ? "incidental" : "aligned"; + if (parsed.drift !== expectedDrift) throw new TypeError(`drift must be ${expectedDrift}`); + const matched = parsed.rule_findings.filter((finding) => finding.trigger === "matched").map(({ rule_id, rule_version }) => ({ rule_id, rule_version })); + const uncertain = parsed.rule_findings.filter((finding) => finding.trigger === "uncertain").map(({ rule_id, rule_version }) => ({ rule_id, rule_version })); + if (!sameRuleSet(parsed.matched_rule_versions, matched)) throw new TypeError("matched_rule_versions contradict rule findings"); + if (!sameRuleSet(parsed.uncertain_rule_versions, uncertain)) throw new TypeError("uncertain_rule_versions contradict rule findings"); +} +function parseAndDeriveAdjudication(value) { + assertPlainJson(value, "adjudication"); + const parsed = rawAdjudicationSchema.parse(value); + validateAdjudicationClaims(parsed); + return parsed; +} +var provenanceBase2 = rawAdjudicationSchema.safeExtend({ model_family: external_exports.union([external_exports.enum(MODEL_FAMILIES), external_exports.literal("unknown")]), model: nonBlank2, effort: external_exports.union([external_exports.enum(EFFORT_VALUES), external_exports.literal("unknown")]) }); +var agentSchema = provenanceBase2.safeExtend({ assurance: external_exports.literal("agent-declared") }).strict(); +var serverSchema = provenanceBase2.safeExtend({ assurance: external_exports.literal("server-attested"), adapter: external_exports.enum(ADAPTER_IDS), cli_version: nonBlank2, model_family: external_exports.enum(MODEL_FAMILIES), effort: external_exports.enum(EFFORT_VALUES), invocation_id: id3, envelope_input_digest: digest3, observed_output_digest: digest3, result_id: id3 }).strict(); +var degradedSchema = provenanceBase2.safeExtend({ assurance: external_exports.literal("degraded"), reason: nonBlank2 }).strict(); +var adjudicationEvidenceSchema = external_exports.discriminatedUnion("assurance", [agentSchema, serverSchema, degradedSchema]); + +// src/contracts/rubric.ts +var rubricV1Schema = external_exports.object({ + schema_version: external_exports.literal("1"), + kind: external_exports.enum(["artifact", "implementation"]), + mode: external_exports.enum(["self_review", "adversarial"]), + criteria: external_exports.array(external_exports.object({ + id: external_exports.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/), + text: external_exports.string().min(1).refine((value) => value.trim().length > 0, "criterion text must contain a non-whitespace character"), + blocking: external_exports.boolean() + }).strict()).min(1) +}).strict().superRefine((rubric, context) => { + const seen = /* @__PURE__ */ new Set(); + rubric.criteria.forEach((criterion, index) => { + if (seen.has(criterion.id)) { + context.addIssue({ code: "custom", path: ["criteria", index, "id"], message: `Duplicate criterion id: ${criterion.id}` }); + } + seen.add(criterion.id); + }); +}); + +// src/contracts/trust.ts +import { createHash } from "node:crypto"; + +// src/contracts/internal/trust-brands.ts +var observationCapabilities = /* @__PURE__ */ new WeakMap(); +var authorityLinks = /* @__PURE__ */ new WeakMap(); +var verifiedEvidence = /* @__PURE__ */ new WeakMap(); +var currentReviewAuthorities = /* @__PURE__ */ new WeakSet(); +var qualifiedEvidence = /* @__PURE__ */ new WeakMap(); +var currentReviewSets = /* @__PURE__ */ new WeakSet(); +function observationCapabilityBinding(value, kind) { + const binding = observationCapabilities.get(value); + return binding?.kind === kind ? binding : void 0; +} +function authenticAuthorityLink(value, identity) { + const actual = authorityLinks.get(value); + return actual?.kind === identity.kind && actual.assurance === identity.assurance; +} +function authenticVerifiedEvidence(value, identity) { + const actual = verifiedEvidence.get(value); + return actual?.kind === identity.kind && actual.assurance === identity.assurance; +} +function authenticCurrentReviewSetAuthority(value) { + return currentReviewAuthorities.has(value); +} +function registerQualifiedEvidence(value, identity) { + qualifiedEvidence.set(value, Object.freeze({ ...identity })); +} +function authenticQualifiedEvidence(value, kind, assurance) { + const actual = qualifiedEvidence.get(value); + return actual?.kind === kind && (assurance === void 0 || actual.assurance === assurance); +} +function registerCurrentReviewSet(value) { + currentReviewSets.add(value); +} + +// src/contracts/trust.ts +var sameArray = (left, right) => left.length === right.length && left.every((value, index) => value === right[index]); +var assertEqual2 = (actual, expected, name) => { + if (actual !== expected) throw new TypeError(`${name} does not match observation capability`); +}; +function deepFreezeJson(value) { + if (value !== null && typeof value === "object") { + for (const nested of Object.values(value)) deepFreezeJson(nested); + Object.freeze(value); + } + return value; +} +var copyFreezeJson = (value) => deepFreezeJson(structuredClone(value)); +function decodeJson(bytes) { + const text3 = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + return JSON.parse(text3); +} +var digestBytes = (bytes) => parseSha256Digest(createHash("sha256").update(bytes).digest("hex")); +var copiedBytes = (bytes) => Uint8Array.from(bytes); +function assertAdapterFamily(adapter2, family2) { + const expected = adapter2 === "claude-cli" ? "claude" : "codex"; + if (family2 !== expected) throw new TypeError("adapter and model family do not match"); +} +function createObservation(binding, bytes, rawOutputDigest) { + const storedBytes = copiedBytes(bytes); + const observation = { ...binding, raw_output_digest: rawOutputDigest }; + Object.defineProperty(observation, "raw_output_bytes", { enumerable: true, configurable: false, get: () => copiedBytes(storedBytes) }); + return Object.freeze(observation); +} +var observationSource = Object.freeze({ + observeReview(capability, observedOutputBytes) { + const binding = observationCapabilityBinding(capability, "review"); + if (binding === void 0 || capability.kind !== "review") throw new TypeError("invalid review observation capability"); + assertAdapterFamily(binding.adapter, binding.family); + const bytes = copiedBytes(observedOutputBytes); + const derived = parseAndDeriveReview(decodeJson(bytes)); + for (const [key, expected] of [["task_id", binding.task_id], ["phase_instance", binding.phase_instance], ["role", binding.role], ["subject_digest", binding.subject_digest], ["input_fingerprint", binding.input_fingerprint], ["rubric_digest", binding.rubric_digest], ["producer_family", binding.producer_family]]) assertEqual2(derived[key], expected, key); + if (binding.family === binding.producer_family) throw new TypeError("review observation must be opposite-family"); + const raw_output_digest = digestBytes(bytes); + const observation = createObservation(binding, bytes, raw_output_digest); + const evidence = copyFreezeJson({ ...derived, assurance: "server-attested", adapter: binding.adapter, cli_version: binding.cli_version, model_family: binding.family, model: binding.model, effort: binding.effort, invocation_id: binding.invocation_id, envelope_input_digest: binding.envelope_input_digest, observed_output_digest: raw_output_digest, result_id: binding.result_id }); + return Object.freeze({ observation, evidence }); + }, + observeAdjudication(capability, observedOutputBytes) { + const binding = observationCapabilityBinding(capability, "adjudication"); + if (binding === void 0 || capability.kind !== "adjudication") throw new TypeError("invalid adjudication observation capability"); + assertAdapterFamily(binding.adapter, binding.family); + const bytes = copiedBytes(observedOutputBytes); + const derived = parseAndDeriveAdjudication(decodeJson(bytes)); + for (const [key, expected] of [["task_id", binding.task_id], ["phase_instance", binding.phase_instance], ["subject_digest", binding.subject_digest], ["input_fingerprint", binding.input_fingerprint], ["pinned_constitution_digest", binding.pinned_constitution_digest], ["source_evidence_set_digest", binding.source_evidence_set_digest]]) assertEqual2(derived[key], expected, key); + if (!sameArray(derived.approved_upstream_digests, binding.approved_upstream_digests)) throw new TypeError("approved_upstream_digests do not match observation capability"); + const raw_output_digest = digestBytes(bytes); + const observation = createObservation(binding, bytes, raw_output_digest); + const evidence = copyFreezeJson({ ...derived, assurance: "server-attested", adapter: binding.adapter, cli_version: binding.cli_version, model_family: binding.family, model: binding.model, effort: binding.effort, invocation_id: binding.invocation_id, envelope_input_digest: binding.envelope_input_digest, observed_output_digest: raw_output_digest, result_id: binding.result_id }); + return Object.freeze({ observation, evidence }); + } +}); +var idSchema = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); +var digestSchema = external_exports.string().regex(/^[0-9a-f]{64}$/u); +var phaseSchema = external_exports.string().regex(/^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$/u); +var familySchema = external_exports.enum(["claude", "codex"]); +var safeInteger2 = external_exports.number().int().nonnegative().safe(); +var agentAuthoritySchema = external_exports.object({ kind: external_exports.literal("agent-declared"), result_id: idSchema, result_digest: digestSchema, state_revision: safeInteger2 }).strict(); +var serverAuthoritySchema = external_exports.object({ kind: external_exports.literal("server"), invocation_id: idSchema, result_id: idSchema, receipt_id: idSchema, state_revision: safeInteger2, envelope_input_digest: digestSchema, observed_output_digest: digestSchema, result_digest: digestSchema }).strict(); +var degradedAuthoritySchema = external_exports.object({ kind: external_exports.literal("degraded"), checkpoint_digest: digestSchema, checkpoint_revision: safeInteger2 }).strict(); +var authorityReferencesSchema = external_exports.discriminatedUnion("kind", [agentAuthoritySchema, serverAuthoritySchema, degradedAuthoritySchema]); +var authorityLinkDataSchema = external_exports.object({ schema_version: external_exports.literal("1"), evidence_kind: external_exports.enum(["review", "adjudication"]), assurance: external_exports.enum(["agent-declared", "server-attested", "degraded"]), role: external_exports.enum(["self-review", "counter-review", "gate-counter-review", "adjudication"]), task_id: idSchema, phase_instance: phaseSchema, subject_digest: digestSchema, input_fingerprint: digestSchema, evidence_digest: digestSchema, gate_id: idSchema.optional(), authority: authorityReferencesSchema }).strict().superRefine((link, context) => { + if (link.evidence_kind === "adjudication" !== (link.role === "adjudication")) context.addIssue({ code: "custom", path: ["role"], message: "role must match evidence kind" }); + const expectedAuthorityKind = link.assurance === "server-attested" ? "server" : link.assurance; + if (link.authority.kind !== expectedAuthorityKind) context.addIssue({ code: "custom", path: ["authority", "kind"], message: "authority references must match assurance" }); + if (link.role === "gate-counter-review" !== (link.gate_id !== void 0)) context.addIssue({ code: "custom", path: ["gate_id"], message: "gate_id is required only for gate-counter-review authority" }); +}); +var slotBase = { evidence_digest: digestSchema, producer_family: familySchema, reviewer_family: familySchema }; +var selfSlotSchema = external_exports.object({ ...slotBase, role: external_exports.literal("self-review"), assurance: external_exports.literal("agent-declared"), independence: external_exports.literal("same-family-self") }).strict().superRefine((slot, context) => { + if (slot.producer_family !== slot.reviewer_family) context.addIssue({ code: "custom", message: "self-review families must match" }); +}); +var counterSlotSchema = external_exports.object({ ...slotBase, role: external_exports.literal("counter-review"), assurance: external_exports.enum(["server-attested", "degraded"]), independence: external_exports.literal("opposite-family") }).strict().superRefine((slot, context) => { + if (slot.producer_family === slot.reviewer_family) context.addIssue({ code: "custom", message: "counter-review families must differ" }); +}); +var gateCounterSlotSchema = external_exports.object({ ...slotBase, role: external_exports.literal("gate-counter-review"), assurance: external_exports.enum(["server-attested", "degraded"]), independence: external_exports.literal("opposite-family"), gate_id: idSchema }).strict().superRefine((slot, context) => { + if (slot.producer_family === slot.reviewer_family) context.addIssue({ code: "custom", message: "gate-counter-review families must differ" }); +}); +var requiredReviewSlotsSchema = external_exports.union([external_exports.tuple([selfSlotSchema, counterSlotSchema]), external_exports.tuple([selfSlotSchema, counterSlotSchema, gateCounterSlotSchema])]); +var currentEvidenceSetRefSchema = external_exports.object({ set_digest: digestSchema, slots: requiredReviewSlotsSchema }).strict(); +var referencedEvidenceSchema = external_exports.union([ + external_exports.object({ evidence_digest: digestSchema, evidence: reviewEvidenceSchema }).strict(), + external_exports.object({ evidence_digest: digestSchema, evidence: adjudicationEvidenceSchema }).strict() +]); +function parseCurrentEvidenceSetRef(value) { + assertPlainJson(value, "current evidence set reference"); + const parsed = currentEvidenceSetRefSchema.parse(value); + validateSlots(parsed.slots); + return parsed; +} +function assertLinkMatches(kind, link, value) { + const authenticatedAssurance = ["agent-declared", "server-attested", "degraded"].find( + (assurance) => authenticAuthorityLink(link, { kind, assurance }) && authenticVerifiedEvidence(value, { kind, assurance }) + ); + if (authenticatedAssurance === void 0) throw new TypeError("untrusted authority link or verified evidence"); + const evidence = value.evidence; + if (evidence.assurance !== authenticatedAssurance || link.assurance !== authenticatedAssurance) throw new TypeError("authority assurance does not match authenticated identity"); + const expectedAuthorityKind = evidence.assurance === "server-attested" ? "server" : evidence.assurance; + if (link.authority.kind !== expectedAuthorityKind) throw new TypeError("authority references do not match assurance"); + const phaseInstance2 = encodePhaseInstance(decodePhaseInstance(evidence.phase_instance)); + if (link.evidence_kind !== kind || link.assurance !== evidence.assurance || link.evidence_digest !== value.evidence_digest || link.task_id !== evidence.task_id || link.phase_instance !== phaseInstance2 || link.subject_digest !== evidence.subject_digest || link.input_fingerprint !== evidence.input_fingerprint) throw new TypeError("authority link does not match verified evidence"); + if (link.role !== (kind === "review" ? evidence.role : "adjudication")) throw new TypeError("authority role does not match evidence"); + if (link.role === "gate-counter-review" !== (link.gate_id !== void 0)) throw new TypeError("authority gate binding does not match role"); + if (evidence.assurance === "server-attested") { + if (link.authority.kind !== "server" || link.authority.invocation_id !== evidence.invocation_id || link.authority.result_id !== evidence.result_id || link.authority.envelope_input_digest !== evidence.envelope_input_digest || link.authority.observed_output_digest !== evidence.observed_output_digest) { + throw new TypeError("server authority provenance does not match evidence"); + } + } +} +function validateSlots(slots) { + if (slots.length !== 2 && slots.length !== 3 || slots[0]?.role !== "self-review" || slots[1]?.role !== "counter-review" || slots.length === 3 && slots[2]?.role !== "gate-counter-review") throw new TypeError("review slots must use canonical role order"); + for (const slot of slots) { + if (slot.role === "self-review") { + if (slot.assurance !== "agent-declared" || slot.independence !== "same-family-self" || slot.producer_family !== slot.reviewer_family) throw new TypeError("invalid self-review slot"); + } else if (slot.independence !== "opposite-family" || slot.producer_family === slot.reviewer_family) throw new TypeError("invalid opposite-family review slot"); + } + if (new Set(slots.map((slot) => slot.evidence_digest)).size !== slots.length) throw new TypeError("review slot evidence digests must be unique"); +} +var currentSetDigest = (slots) => parseSha256Digest(createHash("sha256").update(JSON.stringify(slots)).digest("hex")); +var authorityQualifier = Object.freeze({ + qualifyReview(link, value) { + assertLinkMatches("review", link, value); + const qualified = Object.freeze({ ...value, authority: link }); + registerQualifiedEvidence(qualified, { kind: "review", assurance: link.assurance }); + return qualified; + }, + qualifyAdjudication(link, value) { + assertLinkMatches("adjudication", link, value); + const qualified = Object.freeze({ ...value, authority: link }); + registerQualifiedEvidence(qualified, { kind: "adjudication", assurance: link.assurance }); + return qualified; + }, + currentReviews(authority, reviews) { + if (!authenticCurrentReviewSetAuthority(authority)) throw new TypeError("invalid current review set authority"); + validateSlots(authority.slots); + if (reviews.length !== authority.slots.length) throw new TypeError("reviews must exactly cover required slots"); + authority.slots.forEach((slot, index) => { + const review = reviews[index]; + if (review === void 0 || !authenticQualifiedEvidence(review, "review") || !authenticQualifiedEvidence(review, "review", review.evidence.assurance) || review.evidence_digest !== slot.evidence_digest || review.evidence.role !== slot.role || review.evidence.assurance !== slot.assurance || review.evidence.producer_family !== slot.producer_family || review.evidence.model_family !== slot.reviewer_family || review.authority.task_id !== authority.task_id || review.authority.phase_instance !== authority.phase_instance || review.authority.subject_digest !== authority.subject_digest || review.authority.input_fingerprint !== authority.input_fingerprint || slot.role === "gate-counter-review" && review.authority.gate_id !== slot.gate_id) throw new TypeError(`review does not match slot ${index}`); + }); + const slots = copyFreezeJson(authority.slots); + const current = Object.freeze({ task_id: authority.task_id, phase_instance: authority.phase_instance, subject_digest: authority.subject_digest, input_fingerprint: authority.input_fingerprint, current_evidence_set: Object.freeze({ set_digest: currentSetDigest(slots), slots }), reviews: Object.freeze([...reviews]) }); + registerCurrentReviewSet(current); + return current; + } +}); + +// src/contracts/mcp-tools.ts +var parsedToolInputBrand = /* @__PURE__ */ Symbol("ParsedToolInput"); +var structuralResultBrand = /* @__PURE__ */ Symbol("StructurallyValidProjectResult"); +var parsedCalls = /* @__PURE__ */ new WeakSet(); +var structuralResults = /* @__PURE__ */ new WeakSet(); +var digest4 = external_exports.string().regex(/^[0-9a-f]{64}$/u); +var safeId2 = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u); +var text2 = external_exports.string().min(1).max(4096).regex(/\S/u); +var safeInteger3 = external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +var phase = external_exports.string().refine((v) => { + try { + decodePhaseInstance(v); + return true; + } catch { + return false; + } +}); +var rule2 = external_exports.object({ rule_id: safeId2, rule_version: external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER) }).strict(); +var scope = external_exports.object({ operation: external_exports.enum(["review-trigger", "adjudication-failure"]), boundary: external_exports.enum(["subject", "phase", "task"]) }).strict(); +var provenance = humanDecisionProvenanceV1Schema; +var common = { schema_version: external_exports.literal("1"), task_id: safeId2, intent_id: safeId2, expected_revision: safeInteger3, input_fingerprint: digest4 }; +var def = (name) => Object.freeze({ name, input_schema_id: `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${name}/input`, result_schema_id: `https://archflow.dev/schemas/v1/mcp-tools#/$defs/${name}/result` }); +var TOOL_DEFINITIONS = Object.freeze({ archflow_state: def("archflow_state"), archflow_counter_review: def("archflow_counter_review"), archflow_adjudicate: def("archflow_adjudicate"), archflow_gate: def("archflow_gate"), archflow_waiver: def("archflow_waiver") }); +var stateInput = external_exports.object({ ...common, phase_instance: phase, step: external_exports.enum(["produce", "self_review", "counter_review", "triage", "adjudicate"]), status: external_exports.enum(["running", "succeeded", "failed"]) }).strict(); +var counterInput = external_exports.object({ ...common, artifact_path: taskPathClaimV1Schema, rubric: rubricV1Schema }).strict(); +var adjudicateInput = external_exports.object({ ...common, artifact_path: taskPathClaimV1Schema, upstream_paths: external_exports.array(taskPathClaimV1Schema) }).strict(); +var supersedes = external_exports.object({ superseded_gate_id: safeId2, accepted_triage_digest: digest4, old_subject_digest: digest4 }).strict(); +var gateInput = external_exports.object({ ...common, phase_instance: phase, summary: text2, subject_digest: digest4, current_evidence: external_exports.unknown(), supersedes: supersedes.optional(), kind: external_exports.enum(GATE_KINDS), context: external_exports.unknown() }).strict(); +var waiverOrigin = external_exports.object({ origin_gate_id: safeId2, origin_decision_digest: digest4, origin_context_digest: digest4, task_id: safeId2, phase_instance: phase, subject_digest: digest4, current_evidence_set_digest: digest4, rule: rule2, scope }).strict(); +var waiverInput = external_exports.object({ ...common, origin: waiverOrigin, rationale: text2 }).strict(); +function inputFor(name, value) { + const parsed = name === "archflow_state" ? stateInput.parse(value) : name === "archflow_counter_review" ? counterInput.parse(value) : name === "archflow_adjudicate" ? adjudicateInput.parse(value) : name === "archflow_waiver" ? waiverInput.parse(value) : gateInput.parse(value); + if (name === "archflow_gate") { + const v = parsed; + parseGateContext(v.kind, v.context); + return { ...v, current_evidence: parseCurrentEvidenceSetRef(v.current_evidence) }; + } + if (name === "archflow_waiver") { + const v = parsed; + if (v.task_id !== v.origin.task_id) throw new TypeError("waiver task_id must match origin task_id"); + } + return parsed; +} +function parseToolCall(name, value) { + if (!TOOL_NAMES.includes(name)) throw new TypeError("unknown tool"); + assertPlainJson(value, `${name} input`); + const call = Object.freeze({ name, input: Object.freeze({ ...inputFor(name, value), [parsedToolInputBrand]: name }) }); + parsedCalls.add(call); + return call; +} +var successSchemas = { + archflow_state: external_exports.object({ path: taskPathClaimV1Schema, revision: safeInteger3, status: external_exports.enum(["running", "succeeded", "failed"]) }).strict(), + archflow_counter_review: external_exports.object({ path: taskPathClaimV1Schema, verdict: external_exports.enum(["pass", "advisory", "fail"]), blocking_count: safeInteger3, revision: safeInteger3 }).strict(), + archflow_adjudicate: external_exports.object({ path: taskPathClaimV1Schema, constitution: external_exports.enum(CONSTITUTION_RESULTS), drift: external_exports.enum(DRIFT_RESULTS), triggers: external_exports.array(rule2), revision: safeInteger3 }).strict(), + archflow_gate: external_exports.object({ kind: external_exports.enum(GATE_KINDS), decision: external_exports.unknown(), notes: text2, revision: safeInteger3 }).strict(), + archflow_waiver: external_exports.union([external_exports.object({ origin_gate_id: safeId2, waiver_gate_id: safeId2, task_id: safeId2, rule_id: safeId2, rule_version: external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER), subject_digest: digest4, current_evidence_set_digest: digest4, scope, human_provenance: provenance, granted: external_exports.literal(true), expires: external_exports.literal("task-complete"), notes: text2, revision: safeInteger3 }).strict(), external_exports.object({ origin_gate_id: safeId2, waiver_gate_id: safeId2, task_id: safeId2, rule_id: safeId2, rule_version: external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER), subject_digest: digest4, current_evidence_set_digest: digest4, scope, human_provenance: provenance, granted: external_exports.literal(false), notes: text2, revision: safeInteger3 }).strict()]) +}; +function successFor(call, value) { + const parsed = successSchemas[call.name].parse(value); + if (call.name === "archflow_state" && parsed.status !== call.input.status) throw new TypeError("state status mismatch"); + if (call.name === "archflow_gate") { + const input = call.input; + const result = parsed; + const decision2 = parseGateDecisionEnvelope(result.decision); + if (result.kind !== input.kind || decision2.kind !== input.kind || decision2.task_id !== input.task_id || decision2.phase_instance !== input.phase_instance || decision2.subject_digest !== input.subject_digest || result.notes !== decision2.payload.reason) throw new TypeError("gate result mismatch"); + validateGateDecision(input.kind, input.context, decision2.payload); + } + if (call.name === "archflow_waiver") { + const input = call.input; + const result = parsed; + if (result.origin_gate_id !== input.origin.origin_gate_id || result.task_id !== input.task_id || result.rule_id !== input.origin.rule.rule_id || result.rule_version !== input.origin.rule.rule_version || result.subject_digest !== input.origin.subject_digest || result.current_evidence_set_digest !== input.origin.current_evidence_set_digest || !isDeepStrictEqual2(result.scope, input.origin.scope)) throw new TypeError("waiver result mismatch"); + } + return parsed; +} +function projectFailureForTool(name, value, label) { + assertPlainJson(value, label); + const failure = external_exports.object({ schema_version: external_exports.literal("1"), ok: external_exports.literal(false), error: external_exports.unknown() }).strict().parse(value); + const error51 = parseProjectError(failure.error); + const parameters = error51.diagnostic.parameters; + if (Object.hasOwn(parameters, "tool") && Reflect.get(parameters, "tool") !== name) { + throw new TypeError("project failure tool mismatch"); + } + return { schema_version: "1", ok: false, error: error51 }; +} +function validateProjectResultStructure(call, value) { + if (!parsedCalls.has(call)) throw new TypeError("an authentic parsed tool call is required"); + assertPlainJson(value, `${call.name} result`); + const base = external_exports.object({ schema_version: external_exports.literal("1"), ok: external_exports.boolean() }).passthrough().parse(value); + const result = base.ok ? (() => { + const e = external_exports.object({ schema_version: external_exports.literal("1"), ok: external_exports.literal(true), value: external_exports.unknown() }).strict().parse(value); + return { ...e, value: successFor(call, e.value) }; + })() : projectFailureForTool(call.name, value, `${call.name} result`); + const branded = Object.freeze({ ...result, [structuralResultBrand]: call.name }); + structuralResults.add(branded); + return branded; +} +function validateProjectFailureStructure(name, value) { + if (!TOOL_NAMES.includes(name)) throw new TypeError("unknown tool"); + const failure = projectFailureForTool(name, value, `${name} failure result`); + const error51 = structuredClone(failure.error); + const freeze = (candidate) => { + if (candidate !== null && typeof candidate === "object") { + for (const nested of Object.values(candidate)) freeze(nested); + Object.freeze(candidate); + } + }; + freeze(error51); + const branded = Object.freeze({ schema_version: "1", ok: false, error: error51, [structuralResultBrand]: name }); + structuralResults.add(branded); + return branded; +} + +// src/mcp/server.ts +var protocolErrors = /* @__PURE__ */ new WeakSet(); +var boundaries = /* @__PURE__ */ new WeakSet(); +var outcomes = /* @__PURE__ */ new WeakSet(); +var protocolErrorBrand = /* @__PURE__ */ Symbol("AuthenticatedProtocolError"); +function deepFreeze2(value) { + if (typeof value === "object" && value !== null || typeof value === "function") { + for (const child of Object.values(value)) deepFreeze2(child); + Object.freeze(value); + } + return value; +} +function copyJson(value) { + return structuredClone(value); +} +function authenticateProtocolError(value) { + const parsed = parseProtocolError(value); + const copied = deepFreeze2(copyJson(parsed)); + const wrapper = { value: copied }; + Object.defineProperty(wrapper, protocolErrorBrand, { + value: true, + enumerable: false, + writable: false, + configurable: false + }); + deepFreeze2(wrapper); + protocolErrors.add(wrapper); + return wrapper; +} +function protocolOutcome(error51) { + const wrapper = authenticateProtocolError(error51); + const outcome = deepFreeze2({ kind: "protocol-error", error: wrapper }); + outcomes.add(outcome); + return outcome; +} +function projectOutcome(tool2, result) { + const outcome = deepFreeze2({ kind: "project-result", tool: tool2, result }); + outcomes.add(outcome); + return outcome; +} +function projectFailure(tool2, code, parameters) { + const error51 = code === "CONTRACT_INVALID" ? createProjectError(code, parameters) : code === "CONTRACT_VERSION_UNSUPPORTED" ? createProjectError(code, parameters) : createProjectError(code, parameters); + const result = validateProjectFailureStructure(tool2, { schema_version: "1", ok: false, error: error51 }); + return projectOutcome(tool2, result); +} +function invalidInput(tool2, issueCode) { + return projectFailure(tool2, "CONTRACT_INVALID", { tool: tool2, issue_code: issueCode }); +} +function internalFailure(tool2, context) { + return projectFailure(tool2, "INTERNAL_ERROR", { correlation_id: context.invocation_id }); +} +function copyRegistry(handlers) { + if (handlers === null || typeof handlers !== "object" || Array.isArray(handlers)) { + throw new TypeError("a handler registry object is required"); + } + const prototype = Object.getPrototypeOf(handlers); + if (prototype !== Object.prototype && prototype !== null) { + throw new TypeError("the handler registry must have a plain prototype"); + } + const copied = {}; + for (const key of Reflect.ownKeys(handlers)) { + if (typeof key !== "string" || !isToolName(key)) throw new TypeError("the handler registry contains an unknown tool"); + const descriptor = Object.getOwnPropertyDescriptor(handlers, key); + if (descriptor === void 0 || !("value" in descriptor) || !descriptor.enumerable) { + throw new TypeError("handler registry entries must be enumerable data properties"); + } + if (typeof descriptor.value !== "function") throw new TypeError("tool handlers must be functions"); + const handler = descriptor.value; + copied[key] = Object.freeze((call, context) => handler(call, context)); + } + return deepFreeze2(copied); +} +function classifyVersionedArgs(tool2, args) { + try { + assertPlainJson(args, `${tool2} input`); + } catch { + return { outcome: invalidInput(tool2, "input-not-object") }; + } + if (args === null || typeof args !== "object" || Array.isArray(args)) { + return { outcome: invalidInput(tool2, "input-not-object") }; + } + let hasSchemaVersion; + let descriptor; + try { + hasSchemaVersion = Object.hasOwn(args, "schema_version"); + descriptor = Object.getOwnPropertyDescriptor(args, "schema_version"); + } catch { + return { outcome: invalidInput(tool2, "input-not-object") }; + } + if (!hasSchemaVersion) { + return { outcome: invalidInput(tool2, "schema-version-missing") }; + } + const supplied = descriptor !== void 0 && "value" in descriptor ? descriptor.value : void 0; + if (typeof supplied !== "string" || !safeVersionV1Schema.safeParse(supplied).success) { + return { outcome: invalidInput(tool2, "schema-version-invalid") }; + } + if (supplied !== "1") { + return { + outcome: projectFailure(tool2, "CONTRACT_VERSION_UNSUPPORTED", { + schema_version: supplied, + supported_version: "1" + }) + }; + } + try { + return { call: parseToolCall(tool2, args) }; + } catch { + return { outcome: invalidInput(tool2, "input-invalid") }; + } +} +function createToolBoundary(handlers) { + const registry2 = copyRegistry(handlers); + const boundary = { + invoke: async (name, args, context) => { + if (typeof name !== "string") throw new TypeError("a string tool name is required"); + assertAuthenticInvocationContext(context); + if (!isToolName(name)) { + const toolNameDigest = createHash2("sha256").update(name, "utf8").digest("hex"); + return protocolOutcome(createProtocolError("TOOL_NOT_FOUND", { tool_name_digest: toolNameDigest })); + } + const classified = classifyVersionedArgs(name, args); + if ("outcome" in classified) return classified.outcome; + const handler = registry2[name]; + if (handler === void 0) { + return protocolOutcome(createProtocolError("TOOL_DISABLED", { + tool: name, + lifecycle_state: "inert-no-handler" + })); + } + let returned; + try { + returned = await handler(classified.call, context); + } catch { + return internalFailure(name, context); + } + try { + validateProjectResultStructure(classified.call, returned); + const copied = copyJson(returned); + return projectOutcome(name, validateProjectResultStructure(classified.call, copied)); + } catch { + return internalFailure(name, context); + } + } + }; + deepFreeze2(boundary); + boundaries.add(boundary); + return boundary; +} +function assertAuthenticToolBoundaryOutcome(value) { + if (value === null || typeof value !== "object" || !outcomes.has(value)) { + throw new TypeError("an authentic tool boundary outcome is required"); + } + if ("kind" in value && value.kind === "protocol-error") { + const error51 = value.error; + if (error51 === null || typeof error51 !== "object" || !protocolErrors.has(error51)) { + throw new TypeError("an authentic protocol error wrapper is required"); + } + } +} + +// src/mcp/session.ts +import { Buffer as Buffer2 } from "node:buffer"; +var JSON_RPC = "2.0"; +var MAX_SEEN_IDS = 65536; +var MAX_SEEN_ID_BYTES = 10 * 1024 * 1024; +var REQUEST_KEYS = /* @__PURE__ */ new Set(["jsonrpc", "id", "method", "params"]); +var NOTIFICATION_KEYS = /* @__PURE__ */ new Set(["jsonrpc", "method", "params"]); +var LIST_KEYS = /* @__PURE__ */ new Set(["_meta"]); +var CALL_KEYS = /* @__PURE__ */ new Set(["_meta", "task", "name", "arguments"]); +function deepFreeze3(value) { + if (value !== null && typeof value === "object" && !Object.isFrozen(value)) { + for (const child of Object.values(value)) deepFreeze3(child); + Object.freeze(value); + } + return value; +} +function copiedObject(value) { + return deepFreeze3(structuredClone(value)); +} +function plainObject(value) { + if (value === null || typeof value !== "object" || Array.isArray(value)) return false; + try { + assertPlainJson(value, "JSON-RPC message"); + return true; + } catch { + return false; + } +} +function hasOnlyKeys(value, allowed) { + return Object.keys(value).every((key) => allowed.has(key)); +} +function normalizeId(value) { + if (typeof value === "string") return value; + if (typeof value !== "number" || !Number.isSafeInteger(value)) return void 0; + return Object.is(value, -0) ? 0 : value; +} +function idKey(id4) { + return typeof id4 === "string" ? `s:${id4}` : `n:${id4}`; +} +function errorMessage(id4, code, message, data) { + const error51 = { code, message }; + if (data !== void 0) error51.data = data; + return deepFreeze3({ jsonrpc: JSON_RPC, id: id4, error: deepFreeze3(error51) }); +} +function direct(message) { + return [deepFreeze3({ kind: "send", source: "direct", message })]; +} +function invalidRequest(id4) { + return direct(errorMessage(id4, -32600, "Invalid Request")); +} +function invalidParams(id4) { + return direct(errorMessage(id4, -32602, "Invalid params")); +} +function methodNotFound(id4) { + return direct(errorMessage(id4, -32601, "Method not found")); +} +function limits(options) { + const supplied = options.limits ?? {}; + const bounded = (value, maximum, label) => { + const selected = value ?? maximum; + if (!Number.isSafeInteger(selected) || selected < 1 || selected > maximum) { + throw new TypeError(`${label} must be a positive safe integer no greater than ${maximum}`); + } + return selected; + }; + return { + seenIds: bounded(supplied.seenIds, MAX_SEEN_IDS, "seen ID limit"), + seenIdBytes: bounded(supplied.seenIdBytes, MAX_SEEN_ID_BYTES, "seen ID byte limit"), + internalId: bounded(supplied.internalId, Number.MAX_SAFE_INTEGER, "internal ID limit") + }; +} +function createSessionController(options) { + if (!plainObject(options)) throw new TypeError("session options must be a plain object"); + if (typeof options.connectionId !== "string") throw new TypeError("a connection ID is required"); + createProtocolError("INITIALIZATION_REPEATED", { connection_id: options.connectionId }); + const caps = limits(options); + const seen = /* @__PURE__ */ new Set(); + const byToken = /* @__PURE__ */ new Map(); + const byInternalId = /* @__PURE__ */ new Map(); + const byExternalId = /* @__PURE__ */ new Map(); + const pendingCancellations = /* @__PURE__ */ new Map(); + let currentState = "PRE_INIT"; + let seenBytes = 0; + let nextInternalId = 1; + const fatal = () => { + if (currentState === "CLOSING" || currentState === "CLOSED") return []; + currentState = "CLOSING"; + byToken.clear(); + byInternalId.clear(); + byExternalId.clear(); + pendingCancellations.clear(); + return [deepFreeze3({ kind: "protocol-fatal" })]; + }; + const admitId = (id4) => { + const key = idKey(id4); + if (seen.has(key)) return "seen"; + const bytes = Buffer2.byteLength(key, "utf8"); + if (seen.size >= caps.seenIds || seenBytes + bytes > caps.seenIdBytes) return "fatal"; + seen.add(key); + seenBytes += bytes; + return "new"; + }; + const allocate = (externalId, method, route, nameCandidate = deepFreeze3({ present: false }), argumentsCandidate = deepFreeze3({ present: false })) => { + if (nextInternalId > caps.internalId || !Number.isSafeInteger(nextInternalId)) return void 0; + const internalId = nextInternalId; + nextInternalId += 1; + const token = `request-${internalId}`; + const record2 = { + token, + externalId, + internalId, + method, + route, + nameCandidate, + argumentsCandidate, + state: "executing", + initializeMutated: false + }; + byToken.set(token, record2); + byInternalId.set(internalId, record2); + byExternalId.set(idKey(externalId), record2); + return record2; + }; + const forward = (record2, message) => { + const rewritten = copiedObject({ ...message, id: record2.internalId }); + if (record2.route === "tools-call") { + return [deepFreeze3({ + kind: "forward-sdk", + route: "tools-call", + message: rewritten, + requestToken: record2.token, + externalId: record2.externalId, + internalId: record2.internalId, + nameCandidate: record2.nameCandidate, + argumentsCandidate: record2.argumentsCandidate + })]; + } + return [deepFreeze3({ + kind: "forward-sdk", + route: record2.route, + message: rewritten, + requestToken: record2.token, + externalId: record2.externalId, + internalId: record2.internalId + })]; + }; + const acceptRequest = (message) => { + const normalizedId = normalizeId(message.id); + if (message.jsonrpc !== JSON_RPC || typeof message.method !== "string" || normalizedId === void 0) { + return invalidRequest(null); + } + const idAdmission = admitId(normalizedId); + if (idAdmission === "seen") return invalidRequest(null); + if (idAdmission === "fatal") return fatal(); + if (!hasOnlyKeys(message, REQUEST_KEYS)) return invalidRequest(normalizedId); + const method = message.method; + if (method === "initialize") { + if (currentState !== "PRE_INIT") { + const error51 = authenticateProtocolError(createProtocolError("INITIALIZATION_REPEATED", { + connection_id: options.connectionId + })); + return direct(errorMessage(normalizedId, -32004, "INITIALIZATION_REPEATED", error51.value)); + } + const record2 = allocate(normalizedId, method, "initialize"); + if (record2 === void 0) return fatal(); + currentState = "INITIALIZING"; + return forward(record2, message); + } + if (currentState === "PRE_INIT") return invalidRequest(normalizedId); + if (method === "ping") { + const record2 = allocate(normalizedId, method, "ping"); + return record2 === void 0 ? fatal() : forward(record2, message); + } + if (method === "tools/list") { + if (currentState !== "READY") return invalidRequest(normalizedId); + if (Object.hasOwn(message, "params")) { + if (!plainObject(message.params) || !hasOnlyKeys(message.params, LIST_KEYS)) return invalidParams(normalizedId); + } + const record2 = allocate(normalizedId, method, "tools-list"); + return record2 === void 0 ? fatal() : forward(record2, message); + } + if (method === "tools/call") { + if (currentState !== "READY") return invalidRequest(normalizedId); + if (!plainObject(message.params) || !hasOnlyKeys(message.params, CALL_KEYS)) return invalidParams(normalizedId); + const params = message.params; + if (typeof params.name !== "string") return invalidParams(normalizedId); + const nameCandidate = deepFreeze3({ present: true, value: params.name }); + const argumentsCandidate = Object.hasOwn(params, "arguments") ? deepFreeze3({ present: true, value: structuredClone(params.arguments) }) : deepFreeze3({ present: false }); + if (argumentsCandidate.present && !plainObject(argumentsCandidate.value) && !isToolName(params.name)) { + return invalidParams(normalizedId); + } + const record2 = allocate(normalizedId, method, "tools-call", nameCandidate, argumentsCandidate); + if (record2 === void 0) return fatal(); + let forwarded = message; + if (argumentsCandidate.present && !plainObject(argumentsCandidate.value)) { + forwarded = { + ...message, + params: { ...params, name: params.name, arguments: {} } + }; + } + return forward(record2, forwarded); + } + return currentState === "READY" ? methodNotFound(normalizedId) : invalidRequest(normalizedId); + }; + const acceptNotification = (message) => { + if (message.jsonrpc !== JSON_RPC || typeof message.method !== "string" || !hasOnlyKeys(message, NOTIFICATION_KEYS)) return []; + if (message.method === "notifications/initialized") { + if (currentState !== "INIT_RESPONSE_ACCEPTED") return []; + return [deepFreeze3({ + kind: "forward-sdk", + message: copiedObject(message), + route: "notifications/initialized" + })]; + } + if (message.method !== "notifications/cancelled" || !plainObject(message.params)) return []; + const target = normalizeId(message.params.requestId); + if (target === void 0) return []; + const record2 = byExternalId.get(idKey(target)); + if (record2 === void 0 || record2.route === "initialize" || record2.state !== "executing") return []; + const candidate = copiedObject(message); + pendingCancellations.set(record2.token, candidate); + return [deepFreeze3({ + kind: "validate-cancellation", + message: candidate, + requestToken: record2.token, + externalId: record2.externalId, + internalId: record2.internalId + })]; + }; + const accept = (message) => { + if (currentState === "CLOSING" || currentState === "CLOSED") return []; + if (!plainObject(message)) return invalidRequest(null); + if (Object.hasOwn(message, "id") && Object.hasOwn(message, "method")) return acceptRequest(message); + if (!Object.hasOwn(message, "id") && Object.hasOwn(message, "method")) return acceptNotification(message); + if (Object.hasOwn(message, "id") && message.jsonrpc === JSON_RPC) return []; + return invalidRequest(null); + }; + const acceptSdkEvent = (event) => { + if (event.kind === "initialized-accepted") { + if (currentState !== "INIT_RESPONSE_ACCEPTED") return []; + currentState = "READY"; + return [deepFreeze3({ kind: "connection-ready" })]; + } + const record2 = byToken.get(event.requestToken); + if (record2 === void 0 || record2.state === "response-queued") return []; + if (event.kind === "cancellation-accepted") { + const candidate = pendingCancellations.get(record2.token); + if (candidate === void 0 || record2.route === "initialize" || record2.state !== "executing") return []; + pendingCancellations.delete(record2.token); + record2.state = "cancelling"; + const params = candidate.params; + return [deepFreeze3({ + kind: "forward-sdk", + route: "cancel", + message: copiedObject({ ...candidate, params: { ...params, requestId: record2.internalId } }), + requestToken: record2.token, + internalId: record2.internalId + })]; + } + if (event.kind === "initialize-mutated") { + if (record2.route === "initialize") record2.initializeMutated = true; + return []; + } + assertAuthenticToolBoundaryOutcome(event.outcome); + if (record2.route !== "tools-call") return fatal(); + record2.outcome = event.outcome; + return []; + }; + const isSdkEvent = (value) => { + if (value === null || typeof value !== "object" || Array.isArray(value)) return false; + try { + const candidate = value; + const kind = Object.getOwnPropertyDescriptor(candidate, "kind"); + if (kind === void 0 || !("value" in kind)) return false; + if (kind.value === "initialized-accepted") return true; + const token = Object.getOwnPropertyDescriptor(candidate, "requestToken"); + if (token === void 0 || !("value" in token)) return false; + if (typeof token.value !== "string") return false; + return kind.value === "initialize-mutated" || kind.value === "tool-boundary-outcome" || kind.value === "cancellation-accepted"; + } catch { + return false; + } + }; + const acceptSdkMessage = (message) => { + if (currentState === "CLOSING" || currentState === "CLOSED") return []; + if (isSdkEvent(message)) return acceptSdkEvent(message); + if (!plainObject(message)) return fatal(); + const internalId = normalizeId(message.id); + if (typeof internalId !== "number" || internalId <= 0) return []; + const record2 = byInternalId.get(internalId); + if (record2 === void 0 || record2.state === "response-queued") return []; + const hasResult = Object.hasOwn(message, "result"); + const hasError = Object.hasOwn(message, "error"); + if (message.jsonrpc !== JSON_RPC || hasResult === hasError) return fatal(); + let projected; + let source = "sdk"; + if (record2.route === "initialize") { + if (hasError) { + if (record2.initializeMutated) return fatal(); + projected = errorMessage(record2.externalId, -32602, "Invalid params"); + record2.admissionTransition = "initialize-error"; + } else { + projected = copiedObject({ jsonrpc: JSON_RPC, id: record2.externalId, result: message.result }); + record2.admissionTransition = "initialize-success"; + } + } else { + projected = copiedObject(hasResult ? { jsonrpc: JSON_RPC, id: record2.externalId, result: message.result } : { jsonrpc: JSON_RPC, id: record2.externalId, error: message.error }); + record2.admissionTransition = "ordinary"; + if (record2.route === "tools-call" && record2.outcome === void 0) { + projected = errorMessage(record2.externalId, -32603, "Internal error"); + source = "fallback"; + } + } + record2.state = "response-queued"; + const expectedProjection = record2.outcome === void 0 ? void 0 : deepFreeze3({ kind: "tool-boundary", outcome: record2.outcome }); + const action = { + kind: "send", + source, + message: projected, + requestToken: record2.token, + ...expectedProjection === void 0 ? {} : { expectedProjection } + }; + return [deepFreeze3(action)]; + }; + const removeRecord = (record2) => { + byToken.delete(record2.token); + byInternalId.delete(record2.internalId); + byExternalId.delete(idKey(record2.externalId)); + pendingCancellations.delete(record2.token); + }; + const onSendAdmitted = (requestToken) => { + if (currentState === "CLOSING" || currentState === "CLOSED" || requestToken === void 0) return; + const record2 = byToken.get(requestToken); + if (record2 === void 0 || record2.state !== "response-queued") return; + const transition = record2.admissionTransition; + removeRecord(record2); + if (transition === "initialize-success" && currentState === "INITIALIZING") { + currentState = "INIT_RESPONSE_ACCEPTED"; + } else if (transition === "initialize-error" && currentState === "INITIALIZING") { + currentState = "PRE_INIT"; + } + }; + const onRouteSettled = (requestToken) => { + if (currentState === "CLOSING" || currentState === "CLOSED") return; + const record2 = byToken.get(requestToken); + if (record2?.state === "cancelling") removeRecord(record2); + }; + const controller = { + get state() { + return currentState; + }, + accept, + acceptSdkMessage, + onSendAdmitted, + onRouteSettled, + close: () => { + if (currentState === "CLOSED") return; + currentState = "CLOSED"; + byToken.clear(); + byInternalId.clear(); + byExternalId.clear(); + pendingCancellations.clear(); + } + }; + return Object.freeze(controller); +} + +// src/contracts/schemas/v1/evidence-slots.schema.json +var evidence_slots_schema_default = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "urn:archflow:schema:v1:evidence-slots", + oneOf: [ + { type: "array", prefixItems: [{ $ref: "#/$defs/self" }, { $ref: "#/$defs/counter" }], minItems: 2, maxItems: 2 }, + { type: "array", prefixItems: [{ $ref: "#/$defs/self" }, { $ref: "#/$defs/counter" }, { $ref: "#/$defs/gateCounter" }], minItems: 3, maxItems: 3 } + ], + $defs: { + id: { type: "string", pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" }, + digest: { type: "string", pattern: "^[0-9a-f]{64}$" }, + family: { enum: ["claude", "codex"] }, + self: { type: "object", additionalProperties: false, required: ["role", "evidence_digest", "assurance", "producer_family", "reviewer_family", "independence"], properties: { role: { const: "self-review" }, evidence_digest: { $ref: "#/$defs/digest" }, assurance: { const: "agent-declared" }, producer_family: { $ref: "#/$defs/family" }, reviewer_family: { $ref: "#/$defs/family" }, independence: { const: "same-family-self" } }, oneOf: [{ properties: { producer_family: { const: "claude" }, reviewer_family: { const: "claude" } } }, { properties: { producer_family: { const: "codex" }, reviewer_family: { const: "codex" } } }] }, + counter: { type: "object", additionalProperties: false, required: ["role", "evidence_digest", "assurance", "producer_family", "reviewer_family", "independence"], properties: { role: { const: "counter-review" }, evidence_digest: { $ref: "#/$defs/digest" }, assurance: { enum: ["server-attested", "degraded"] }, producer_family: { $ref: "#/$defs/family" }, reviewer_family: { $ref: "#/$defs/family" }, independence: { const: "opposite-family" } }, oneOf: [{ properties: { producer_family: { const: "claude" }, reviewer_family: { const: "codex" } } }, { properties: { producer_family: { const: "codex" }, reviewer_family: { const: "claude" } } }] }, + gateCounter: { type: "object", additionalProperties: false, required: ["role", "evidence_digest", "assurance", "producer_family", "reviewer_family", "independence", "gate_id"], properties: { role: { const: "gate-counter-review" }, evidence_digest: { $ref: "#/$defs/digest" }, assurance: { enum: ["server-attested", "degraded"] }, producer_family: { $ref: "#/$defs/family" }, reviewer_family: { $ref: "#/$defs/family" }, independence: { const: "opposite-family" }, gate_id: { $ref: "#/$defs/id" } }, oneOf: [{ properties: { producer_family: { const: "claude" }, reviewer_family: { const: "codex" } } }, { properties: { producer_family: { const: "codex" }, reviewer_family: { const: "claude" } } }] } + } +}; + +// src/contracts/schemas/v1/gate-contract.schema.json +var gate_contract_schema_default = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "urn:archflow:schema:v1:gate-contract", + type: "object", + "x-archflow-gate-semantics": true, + $defs: { + digest: { type: "string", pattern: "^[0-9a-f]{64}$" }, + safeId: { $ref: "urn:archflow:schema:v1:primitives#/$defs/safeId" }, + text: { + type: "string", + minLength: 1, + maxLength: 4096, + pattern: "\\S" + }, + safeInteger: { + type: "integer", + minimum: 0, + maximum: 9007199254740991 + }, + rule: { + type: "object", + additionalProperties: false, + required: ["rule_id", "rule_version"], + properties: { + rule_id: { $ref: "#/$defs/safeId" }, + rule_version: { + type: "integer", + minimum: 1, + maximum: 9007199254740991 + } + } + }, + rules: { + type: "array", + uniqueItems: true, + items: { $ref: "#/$defs/rule" } + }, + digests: { + type: "array", + uniqueItems: true, + items: { $ref: "#/$defs/digest" } + }, + waiverScope: { + type: "object", + additionalProperties: false, + required: ["operation", "boundary"], + properties: { + operation: { enum: ["review-trigger", "adjudication-failure"] }, + boundary: { enum: ["subject", "phase", "task"] } + } + }, + authorityLink: { + type: "object", + additionalProperties: false, + required: [ + "link_digest", + "purpose", + "proposed_generation_digest", + "changed_input_fingerprint" + ], + properties: { + link_digest: { $ref: "#/$defs/digest" }, + purpose: { const: "restore-adoption" }, + proposed_generation_digest: { $ref: "#/$defs/digest" }, + changed_input_fingerprint: { $ref: "#/$defs/digest" } + } + }, + artifactApproval: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "artifact-approval" }, + context: { + type: "object", + additionalProperties: false, + required: ["artifact_kind"], + properties: { + artifact_kind: { + enum: ["prd", "design", "phase-design", "phase-implementation"] + } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/approve" }, + { $ref: "#/$defs/revise" }, + { $ref: "#/$defs/reject" } + ] + } + } + }, + reviewTrigger: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "review-trigger" }, + context: { + type: "object", + additionalProperties: false, + required: [ + "matched_rules", + "uncertain_rules", + "eligible_waiver_rules", + "waiver_scope" + ], + properties: { + matched_rules: { $ref: "#/$defs/rules" }, + uncertain_rules: { $ref: "#/$defs/rules" }, + eligible_waiver_rules: { $ref: "#/$defs/rules" }, + waiver_scope: { $ref: "#/$defs/waiverScope" } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/approve" }, + { $ref: "#/$defs/revise" }, + { $ref: "#/$defs/reject" }, + { $ref: "#/$defs/waiverRequested" } + ] + } + } + }, + materialDrift: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "material-drift" }, + context: { + type: "object", + additionalProperties: false, + required: ["affected_upstream", "drift", "affected_claim_ids"], + properties: { + affected_upstream: { + type: "object", + additionalProperties: false, + required: ["kind", "digest"], + properties: { + kind: { + enum: [ + "prd", + "architecture", + "phase-design", + "implementation-result", + "review", + "adjudication", + "constitution", + "workflow", + "import" + ] + }, + digest: { $ref: "#/$defs/digest" } + } + }, + drift: { const: "material" }, + affected_claim_ids: { + type: "array", + minItems: 1, + uniqueItems: true, + items: { $ref: "#/$defs/safeId" } + } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/amendUpstream" }, + { $ref: "#/$defs/reviseCurrent" }, + { $ref: "#/$defs/reject" } + ] + } + } + }, + adjudicationFailure: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "adjudication-failure" }, + context: { + type: "object", + additionalProperties: false, + required: [ + "constitution", + "failed_rules", + "uncertain_rules", + "eligible_waiver_rules", + "waiver_scope" + ], + properties: { + constitution: { enum: ["fail", "uncertain"] }, + failed_rules: { $ref: "#/$defs/rules" }, + uncertain_rules: { $ref: "#/$defs/rules" }, + eligible_waiver_rules: { $ref: "#/$defs/rules" }, + waiver_scope: { $ref: "#/$defs/waiverScope" } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/adjudicationApprove" }, + { $ref: "#/$defs/revise" }, + { $ref: "#/$defs/reject" }, + { $ref: "#/$defs/waiverRequested" } + ] + } + } + }, + attemptsExhausted: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "attempts-exhausted" }, + context: { + type: "object", + additionalProperties: false, + required: ["step", "attempts", "maximum_attempts"], + properties: { + step: { + enum: [ + "produce", + "self_review", + "counter_review", + "triage", + "adjudicate" + ] + }, + attempts: { $ref: "#/$defs/safeInteger" }, + maximum_attempts: { $ref: "#/$defs/safeInteger" } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/retryOnce" }, + { $ref: "#/$defs/revise" }, + { $ref: "#/$defs/abort" } + ] + } + } + }, + constitutionEdit: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "constitution-edit" }, + context: { + type: "object", + additionalProperties: false, + required: [ + "pinned_constitution_digest", + "current_constitution_digest", + "changed_path_class" + ], + properties: { + pinned_constitution_digest: { $ref: "#/$defs/digest" }, + current_constitution_digest: { $ref: "#/$defs/digest" }, + changed_path_class: { const: "task-branch-constitution" } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/revertEdit" }, + { $ref: "#/$defs/startBaseAmendment" }, + { $ref: "#/$defs/abort" } + ] + } + } + }, + commitAuthorization: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "commit-authorization" }, + context: { + type: "object", + additionalProperties: false, + required: [ + "target_ref", + "diff_digest", + "current_artifact_digests", + "parent_document_digests" + ], + properties: { + target_ref: { $ref: "#/$defs/text" }, + diff_digest: { $ref: "#/$defs/digest" }, + current_artifact_digests: { $ref: "#/$defs/digests" }, + parent_document_digests: { $ref: "#/$defs/digests" } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/authorizeCommit" }, + { $ref: "#/$defs/revise" }, + { $ref: "#/$defs/abort" } + ] + } + } + }, + restoreCollision: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "restore-collision" }, + context: { + type: "object", + additionalProperties: false, + required: [ + "path", + "recorded_generation_digest", + "current_generation_digest" + ], + properties: { + path: { type: "string", minLength: 1, maxLength: 1024 }, + recorded_generation_digest: { $ref: "#/$defs/digest" }, + current_generation_digest: { $ref: "#/$defs/digest" }, + adoption_candidate: { $ref: "#/$defs/authorityLink" } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/discardAndRestore" }, + { $ref: "#/$defs/adoptGeneration" }, + { $ref: "#/$defs/abort" } + ] + } + } + }, + migrationAudit: { + type: "object", + additionalProperties: false, + required: ["kind", "context", "payload"], + properties: { + kind: { const: "migration-audit" }, + context: { + type: "object", + additionalProperties: false, + required: [ + "source_identity_digest", + "destination_identity_digest", + "import_digest", + "code_baseline_digest", + "policy_baseline_digest" + ], + properties: { + source_identity_digest: { $ref: "#/$defs/digest" }, + destination_identity_digest: { $ref: "#/$defs/digest" }, + import_digest: { $ref: "#/$defs/digest" }, + code_baseline_digest: { $ref: "#/$defs/digest" }, + policy_baseline_digest: { $ref: "#/$defs/digest" } + } + }, + payload: { + oneOf: [ + { $ref: "#/$defs/acceptImportAudit" }, + { $ref: "#/$defs/revise" }, + { $ref: "#/$defs/abort" } + ] + } + } + }, + approve: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "approve" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "advance" + }, + revise: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "revise" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "retry" + }, + reject: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "reject" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "non-advancing" + }, + abort: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "abort" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "non-advancing" + }, + waiverRequested: { + type: "object", + additionalProperties: false, + required: ["decision", "reason", "rule", "rationale"], + properties: { + decision: { const: "waiver-requested" }, + reason: { $ref: "#/$defs/text" }, + rule: { $ref: "#/$defs/rule" }, + rationale: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "redirect-waiver" + }, + adjudicationApprove: { + type: "object", + additionalProperties: false, + required: ["decision", "reason", "resolutions"], + properties: { + decision: { const: "approve" }, + reason: { $ref: "#/$defs/text" }, + resolutions: { + type: "array", + uniqueItems: true, + items: { + type: "object", + additionalProperties: false, + required: ["rule", "resolution"], + properties: { + rule: { $ref: "#/$defs/rule" }, + resolution: { $ref: "#/$defs/text" } + } + } + } + }, + "x-archflow-effect": "advance" + }, + amendUpstream: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "amend-upstream" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "redirect-upstream" + }, + reviseCurrent: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "revise-current" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "retry" + }, + retryOnce: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "retry-once" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "retry" + }, + revertEdit: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "revert-edit" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "retry" + }, + startBaseAmendment: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "start-base-amendment" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "redirect-upstream" + }, + authorizeCommit: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "authorize-commit" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "advance" + }, + discardAndRestore: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "discard-and-restore" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "advance" + }, + adoptGeneration: { + type: "object", + additionalProperties: false, + required: ["decision", "reason", "adoption_authority", "rationale"], + properties: { + decision: { const: "adopt-as-new-generation" }, + reason: { $ref: "#/$defs/text" }, + adoption_authority: { $ref: "#/$defs/authorityLink" }, + rationale: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "advance" + }, + acceptImportAudit: { + type: "object", + additionalProperties: false, + required: ["decision", "reason"], + properties: { + decision: { const: "accept-import-audit" }, + reason: { $ref: "#/$defs/text" } + }, + "x-archflow-effect": "advance" + } + }, + oneOf: [ + { $ref: "#/$defs/artifactApproval" }, + { $ref: "#/$defs/reviewTrigger" }, + { $ref: "#/$defs/materialDrift" }, + { $ref: "#/$defs/adjudicationFailure" }, + { $ref: "#/$defs/attemptsExhausted" }, + { $ref: "#/$defs/constitutionEdit" }, + { $ref: "#/$defs/commitAuthorization" }, + { $ref: "#/$defs/restoreCollision" }, + { $ref: "#/$defs/migrationAudit" } + ] +}; + +// src/contracts/schemas/v1/gate-decision.schema.json +var gate_decision_schema_default = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "urn:archflow:schema:v1:gate-decision", + type: "object", + $defs: { + digest: { + type: "string", + pattern: "^[0-9a-f]{64}$" + }, + safeId: { $ref: "urn:archflow:schema:v1:primitives#/$defs/safeId" }, + recordedAt: { + type: "string", + format: "date-time", + pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" + }, + connected: { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "actor_class", + "assurance", + "channel", + "decision_event_id", + "connection_id", + "request_id_digest", + "recorded_at" + ], + properties: { + schema_version: { + const: "1" + }, + actor_class: { + enum: ["human", "archforge"] + }, + assurance: { + const: "declared-local-trace" + }, + channel: { + const: "connected-host" + }, + decision_event_id: { + $ref: "#/$defs/safeId" + }, + connection_id: { + $ref: "#/$defs/safeId" + }, + request_id_digest: { + $ref: "#/$defs/digest" + }, + recorded_at: { + $ref: "#/$defs/recordedAt" + } + } + }, + local: { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "actor_class", + "assurance", + "channel", + "decision_event_id", + "helper_invocation_id", + "recorded_at" + ], + properties: { + schema_version: { + const: "1" + }, + actor_class: { + enum: ["human", "archforge"] + }, + assurance: { + const: "declared-local-trace" + }, + channel: { + const: "archflow-local" + }, + decision_event_id: { + $ref: "#/$defs/safeId" + }, + helper_invocation_id: { + $ref: "#/$defs/safeId" + }, + recorded_at: { + $ref: "#/$defs/recordedAt" + } + } + }, + base: { + type: "object", + required: [ + "schema_version", + "gate_id", + "task_id", + "phase_instance", + "subject_digest", + "context_digest", + "human_provenance" + ], + properties: { + schema_version: { + const: "1" + }, + gate_id: { + $ref: "#/$defs/safeId" + }, + task_id: { + $ref: "#/$defs/safeId" + }, + phase_instance: { + type: "string", + pattern: "^(prd|design|phase-design-[1-9][0-9]*|phase-impl-[1-9][0-9]*)$" + }, + subject_digest: { + $ref: "#/$defs/digest" + }, + context_digest: { + $ref: "#/$defs/digest" + }, + human_provenance: { + oneOf: [ + { + $ref: "#/$defs/connected" + }, + { + $ref: "#/$defs/local" + } + ] + } + } + } + }, + allOf: [ + { + $ref: "#/$defs/base" + }, + { + oneOf: [ + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "artifact-approval" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/approve" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/reject" + } + ] + } + } + }, + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "review-trigger" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/approve" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/reject" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/waiverRequested" + } + ] + } + } + }, + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "material-drift" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/amendUpstream" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/reviseCurrent" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/reject" + } + ] + } + } + }, + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "adjudication-failure" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/adjudicationApprove" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/reject" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/waiverRequested" + } + ] + } + } + }, + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "attempts-exhausted" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/retryOnce" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + }, + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "constitution-edit" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/revertEdit" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/startBaseAmendment" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + }, + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "commit-authorization" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/authorizeCommit" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + }, + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "restore-collision" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/discardAndRestore" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/adoptGeneration" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + }, + { + type: "object", + required: ["kind", "payload"], + properties: { + kind: { + const: "migration-audit" + }, + payload: { + oneOf: [ + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/acceptImportAudit" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/revise" + }, + { + $ref: "urn:archflow:schema:v1:gate-contract#/$defs/abort" + } + ] + } + } + } + ] + } + ], + unevaluatedProperties: false +}; + +// src/contracts/schemas/v1/mcp-tools.schema.json +var mcp_tools_schema_default = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "https://archflow.dev/schemas/v1/mcp-tools", + type: "object", + "x-archflow-mcp-semantics": true, + $defs: { + digest: { type: "string", pattern: "^[0-9a-f]{64}$" }, + id: { $ref: "urn:archflow:schema:v1:primitives#/$defs/safeId" }, + text: { + type: "string", + minLength: 1, + maxLength: 4096, + pattern: "\\S" + }, + integer: { type: "integer", minimum: 0, maximum: 9007199254740991 }, + phase: { + type: "string", + pattern: "^(?:prd|design|phase-(?:design|impl)-[1-9][0-9]*)$" + }, + path: { $ref: "urn:archflow:schema:v1:path-claim" }, + rule: { + type: "object", + additionalProperties: false, + required: ["rule_id", "rule_version"], + properties: { + rule_id: { $ref: "#/$defs/id" }, + rule_version: { + type: "integer", + minimum: 1, + maximum: 9007199254740991 + } + } + }, + scope: { + type: "object", + additionalProperties: false, + required: ["operation", "boundary"], + properties: { + operation: { enum: ["review-trigger", "adjudication-failure"] }, + boundary: { enum: ["subject", "phase", "task"] } + } + }, + currentEvidence: { + type: "object", + additionalProperties: false, + required: ["set_digest", "slots"], + properties: { + set_digest: { $ref: "#/$defs/digest" }, + slots: { $ref: "urn:archflow:schema:v1:evidence-slots" } + } + }, + common: { + type: "object", + required: [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint" + ], + properties: { + schema_version: { const: "1" }, + task_id: { $ref: "#/$defs/id" }, + intent_id: { $ref: "#/$defs/id" }, + expected_revision: { $ref: "#/$defs/integer" }, + input_fingerprint: { $ref: "#/$defs/digest" } + } + }, + failure: { + type: "object", + additionalProperties: false, + required: ["schema_version", "ok", "error"], + properties: { + schema_version: { const: "1" }, + ok: { const: false }, + error: { $ref: "urn:archflow:schema:v1:project-error" } + } + }, + archflow_state: { + input: { + allOf: [ + { $ref: "#/$defs/common" }, + { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "phase_instance", + "step", + "status" + ], + properties: { + schema_version: { const: "1" }, + task_id: { $ref: "#/$defs/id" }, + intent_id: { $ref: "#/$defs/id" }, + expected_revision: { $ref: "#/$defs/integer" }, + input_fingerprint: { $ref: "#/$defs/digest" }, + phase_instance: { $ref: "#/$defs/phase" }, + step: { + enum: [ + "produce", + "self_review", + "counter_review", + "triage", + "adjudicate" + ] + }, + status: { enum: ["running", "succeeded", "failed"] } + } + } + ] + }, + success: { + type: "object", + additionalProperties: false, + required: ["path", "revision", "status"], + properties: { + path: { $ref: "#/$defs/path" }, + revision: { $ref: "#/$defs/integer" }, + status: { enum: ["running", "succeeded", "failed"] } + } + }, + result: { + oneOf: [ + { $ref: "#/$defs/failure" }, + { + type: "object", + additionalProperties: false, + required: ["schema_version", "ok", "value"], + properties: { + schema_version: { const: "1" }, + ok: { const: true }, + value: { $ref: "#/$defs/archflow_state/success" } + } + } + ] + } + }, + archflow_counter_review: { + input: { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "artifact_path", + "rubric" + ], + properties: { + schema_version: { const: "1" }, + task_id: { $ref: "#/$defs/id" }, + intent_id: { $ref: "#/$defs/id" }, + expected_revision: { $ref: "#/$defs/integer" }, + input_fingerprint: { $ref: "#/$defs/digest" }, + artifact_path: { $ref: "#/$defs/path" }, + rubric: { $ref: "urn:archflow:schema:v1:rubric" } + } + }, + success: { + type: "object", + additionalProperties: false, + required: ["path", "verdict", "blocking_count", "revision"], + properties: { + path: { $ref: "#/$defs/path" }, + verdict: { enum: ["pass", "advisory", "fail"] }, + blocking_count: { $ref: "#/$defs/integer" }, + revision: { $ref: "#/$defs/integer" } + } + }, + result: { + oneOf: [ + { $ref: "#/$defs/failure" }, + { + type: "object", + additionalProperties: false, + required: ["schema_version", "ok", "value"], + properties: { + schema_version: { const: "1" }, + ok: { const: true }, + value: { $ref: "#/$defs/archflow_counter_review/success" } + } + } + ] + } + }, + archflow_adjudicate: { + input: { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "artifact_path", + "upstream_paths" + ], + properties: { + schema_version: { const: "1" }, + task_id: { $ref: "#/$defs/id" }, + intent_id: { $ref: "#/$defs/id" }, + expected_revision: { $ref: "#/$defs/integer" }, + input_fingerprint: { $ref: "#/$defs/digest" }, + artifact_path: { $ref: "#/$defs/path" }, + upstream_paths: { + type: "array", + items: { $ref: "#/$defs/path" } + } + } + }, + success: { + type: "object", + additionalProperties: false, + required: ["path", "constitution", "drift", "triggers", "revision"], + properties: { + path: { $ref: "#/$defs/path" }, + constitution: { enum: ["pass", "fail", "uncertain"] }, + drift: { enum: ["aligned", "incidental", "material"] }, + triggers: { type: "array", items: { $ref: "#/$defs/rule" } }, + revision: { $ref: "#/$defs/integer" } + } + }, + result: { + oneOf: [ + { $ref: "#/$defs/failure" }, + { + type: "object", + additionalProperties: false, + required: ["schema_version", "ok", "value"], + properties: { + schema_version: { const: "1" }, + ok: { const: true }, + value: { $ref: "#/$defs/archflow_adjudicate/success" } + } + } + ] + } + }, + archflow_gate: { + input: { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "phase_instance", + "summary", + "subject_digest", + "current_evidence", + "kind", + "context" + ], + properties: { + schema_version: { const: "1" }, + task_id: { $ref: "#/$defs/id" }, + intent_id: { $ref: "#/$defs/id" }, + expected_revision: { $ref: "#/$defs/integer" }, + input_fingerprint: { $ref: "#/$defs/digest" }, + phase_instance: { $ref: "#/$defs/phase" }, + summary: { $ref: "#/$defs/text" }, + subject_digest: { $ref: "#/$defs/digest" }, + current_evidence: { $ref: "#/$defs/currentEvidence" }, + supersedes: { + type: "object", + additionalProperties: false, + required: [ + "superseded_gate_id", + "accepted_triage_digest", + "old_subject_digest" + ], + properties: { + superseded_gate_id: { $ref: "#/$defs/id" }, + accepted_triage_digest: { $ref: "#/$defs/digest" }, + old_subject_digest: { $ref: "#/$defs/digest" } + } + }, + kind: { + enum: [ + "artifact-approval", + "review-trigger", + "material-drift", + "adjudication-failure", + "attempts-exhausted", + "constitution-edit", + "commit-authorization", + "restore-collision", + "migration-audit" + ] + }, + context: { type: "object" } + }, + allOf: [{ + oneOf: [ + { properties: { kind: { const: "artifact-approval" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/artifactApproval/properties/context" } } }, + { properties: { kind: { const: "review-trigger" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/reviewTrigger/properties/context" } } }, + { properties: { kind: { const: "material-drift" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/materialDrift/properties/context" } } }, + { properties: { kind: { const: "adjudication-failure" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/adjudicationFailure/properties/context" } } }, + { properties: { kind: { const: "attempts-exhausted" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/attemptsExhausted/properties/context" } } }, + { properties: { kind: { const: "constitution-edit" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/constitutionEdit/properties/context" } } }, + { properties: { kind: { const: "commit-authorization" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/commitAuthorization/properties/context" } } }, + { properties: { kind: { const: "restore-collision" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/restoreCollision/properties/context" } } }, + { properties: { kind: { const: "migration-audit" }, context: { $ref: "urn:archflow:schema:v1:gate-contract#/$defs/migrationAudit/properties/context" } } } + ] + }] + }, + success: { + type: "object", + additionalProperties: false, + required: ["kind", "decision", "notes", "revision"], + properties: { + kind: { + enum: [ + "artifact-approval", + "review-trigger", + "material-drift", + "adjudication-failure", + "attempts-exhausted", + "constitution-edit", + "commit-authorization", + "restore-collision", + "migration-audit" + ] + }, + decision: { $ref: "urn:archflow:schema:v1:gate-decision" }, + notes: { $ref: "#/$defs/text" }, + revision: { $ref: "#/$defs/integer" } + } + }, + result: { + oneOf: [ + { $ref: "#/$defs/failure" }, + { + type: "object", + additionalProperties: false, + required: ["schema_version", "ok", "value"], + properties: { + schema_version: { const: "1" }, + ok: { const: true }, + value: { $ref: "#/$defs/archflow_gate/success" } + } + } + ] + } + }, + archflow_waiver: { + input: { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "task_id", + "intent_id", + "expected_revision", + "input_fingerprint", + "origin", + "rationale" + ], + properties: { + schema_version: { const: "1" }, + task_id: { $ref: "#/$defs/id" }, + intent_id: { $ref: "#/$defs/id" }, + expected_revision: { $ref: "#/$defs/integer" }, + input_fingerprint: { $ref: "#/$defs/digest" }, + origin: { + type: "object", + additionalProperties: false, + required: [ + "origin_gate_id", + "origin_decision_digest", + "origin_context_digest", + "task_id", + "phase_instance", + "subject_digest", + "current_evidence_set_digest", + "rule", + "scope" + ], + properties: { + origin_gate_id: { $ref: "#/$defs/id" }, + origin_decision_digest: { $ref: "#/$defs/digest" }, + origin_context_digest: { $ref: "#/$defs/digest" }, + task_id: { $ref: "#/$defs/id" }, + phase_instance: { $ref: "#/$defs/phase" }, + subject_digest: { $ref: "#/$defs/digest" }, + current_evidence_set_digest: { $ref: "#/$defs/digest" }, + rule: { $ref: "#/$defs/rule" }, + scope: { $ref: "#/$defs/scope" } + } + }, + rationale: { $ref: "#/$defs/text" } + } + }, + success: { + type: "object", + required: [ + "origin_gate_id", + "waiver_gate_id", + "task_id", + "rule_id", + "rule_version", + "subject_digest", + "current_evidence_set_digest", + "scope", + "human_provenance", + "granted", + "notes", + "revision" + ], + properties: { + origin_gate_id: { $ref: "#/$defs/id" }, + waiver_gate_id: { $ref: "#/$defs/id" }, + task_id: { $ref: "#/$defs/id" }, + rule_id: { $ref: "#/$defs/id" }, + rule_version: { $ref: "#/$defs/rule/properties/rule_version" }, + subject_digest: { $ref: "#/$defs/digest" }, + current_evidence_set_digest: { $ref: "#/$defs/digest" }, + scope: { $ref: "#/$defs/scope" }, + human_provenance: { oneOf: [{ $ref: "urn:archflow:schema:v1:gate-decision#/$defs/connected" }, { $ref: "urn:archflow:schema:v1:gate-decision#/$defs/local" }] }, + granted: { type: "boolean" }, + expires: { const: "task-complete" }, + notes: { $ref: "#/$defs/text" }, + revision: { $ref: "#/$defs/integer" } + }, + allOf: [ + { + if: { properties: { granted: { const: true } } }, + then: { properties: { expires: {} }, required: ["expires"] }, + else: { not: { properties: { expires: {} }, required: ["expires"] } } + } + ], + unevaluatedProperties: false + }, + result: { + oneOf: [ + { $ref: "#/$defs/failure" }, + { + type: "object", + additionalProperties: false, + required: ["schema_version", "ok", "value"], + properties: { + schema_version: { const: "1" }, + ok: { const: true }, + value: { $ref: "#/$defs/archflow_waiver/success" } + } + } + ] + } + } + }, + oneOf: [ + { $ref: "#/$defs/archflow_state/input" }, + { $ref: "#/$defs/archflow_counter_review/input" }, + { $ref: "#/$defs/archflow_adjudicate/input" }, + { $ref: "#/$defs/archflow_gate/input" }, + { $ref: "#/$defs/archflow_waiver/input" } + ] +}; + +// src/contracts/schemas/v1/path-claim.schema.json +var path_claim_schema_default = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "urn:archflow:schema:v1:path-claim", + type: "string", + minLength: 1, + "x-archflow-max-utf8-bytes": 1024, + pattern: "^(?!/)(?![A-Za-z]:)(?!//)(?!.*\\\\)(?!.*[\\u0000-\\u001F\\u007F-\\u009F])(?!\\.\\.?(?:/|$))(?!.*\\/\\.\\.?(?:/|$))(?!.*//).+$" +}; + +// src/contracts/schemas/v1/primitives.schema.json +var primitives_schema_default = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "urn:archflow:schema:v1:primitives", + $defs: { + positiveSafePhaseNumber: { + type: "integer", + minimum: 1, + maximum: 9007199254740991 + }, + safeInteger: { + type: "integer", + minimum: 0, + maximum: 9007199254740991 + }, + sha256Digest: { + type: "string", + pattern: "^[0-9a-f]{64}$" + }, + safeId: { + type: "string", + pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" + }, + safeCode: { + type: "string", + pattern: "^[a-z0-9][a-z0-9_-]{0,63}$" + }, + safeVersion: { + type: "string", + pattern: "^[A-Za-z0-9.-]{1,64}$" + } + } +}; + +// src/contracts/schemas/v1/project-error.schema.json +var project_error_schema_default = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "urn:archflow:schema:v1:project-error", + $defs: { + digest: { + type: "string", + pattern: "^[0-9a-f]{64}$" + }, + id: { + type: "string", + pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" + }, + code: { + type: "string", + pattern: "^[a-z0-9][a-z0-9_-]{0,63}$" + }, + version: { + type: "string", + pattern: "^[A-Za-z0-9.-]{1,64}$" + }, + integer: { + type: "integer", + minimum: 0, + maximum: 9007199254740991 + }, + tool: { + enum: [ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver" + ] + }, + adapter: { + enum: [ + "claude-cli", + "codex-cli" + ] + }, + family: { + enum: [ + "claude", + "codex" + ] + }, + gate: { + enum: [ + "artifact-approval", + "review-trigger", + "material-drift", + "adjudication-failure", + "attempts-exhausted", + "constitution-edit", + "commit-authorization", + "restore-collision", + "migration-audit" + ] + }, + phase: { + type: "string", + pattern: "^(prd|design|phase-design-[1-9][0-9]*|phase-impl-[1-9][0-9]*)$" + }, + path: { + type: "string", + minLength: 1, + "x-archflow-max-utf8-bytes": 1024, + pattern: "^(?!/)(?![A-Za-z]:)(?!//)(?!.*\\\\)(?!.*[\\u0000-\\u001F\\u007F-\\u009F])(?!\\.\\.?(?:/|$))(?!.*\\/\\.\\.?(?:/|$))(?!.*//).+$" + }, + issue: { + type: "object", + additionalProperties: false, + required: [ + "issue_code" + ], + properties: { + issue_code: { + $ref: "#/$defs/code" + } + } + }, + digests: { + type: "object", + additionalProperties: false, + required: [ + "expected_digest", + "observed_digest" + ], + properties: { + expected_digest: { + $ref: "#/$defs/digest" + }, + observed_digest: { + $ref: "#/$defs/digest" + } + } + }, + taskPath: { + type: "object", + additionalProperties: false, + required: [ + "task_id", + "path_class" + ], + properties: { + task_id: { + $ref: "#/$defs/id" + }, + path_class: { + $ref: "#/$defs/code" + } + } + }, + E_CONTRACT_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "CONTRACT_INVALID" + }, + owner: { + const: "contracts" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "CONTRACT_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "issue_code" + ], + properties: { + tool: { + $ref: "#/$defs/tool" + }, + issue_code: { + $ref: "#/$defs/code" + }, + schema_version: { + $ref: "#/$defs/version" + } + } + } + }, + type: "object" + }, + next_action: { + const: "correct-contract" + } + }, + type: "object" + } + ] + }, + E_RESULT_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "RESULT_INVALID" + }, + owner: { + const: "integrity" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "RESULT_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "tool", + "result_id" + ], + properties: { + tool: { + $ref: "#/$defs/tool" + }, + result_id: { + $ref: "#/$defs/id" + }, + expected_digest: { + $ref: "#/$defs/digest" + }, + observed_digest: { + $ref: "#/$defs/digest" + } + } + } + }, + type: "object" + }, + next_action: { + const: "repair-retained-result" + } + }, + type: "object" + } + ] + }, + E_CONTRACT_VERSION_UNSUPPORTED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "CONTRACT_VERSION_UNSUPPORTED" + }, + owner: { + const: "contracts" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "CONTRACT_VERSION_UNSUPPORTED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "supported_version" + ], + properties: { + schema_version: { + $ref: "#/$defs/version" + }, + supported_version: { + $ref: "#/$defs/version" + } + } + } + }, + type: "object" + }, + next_action: { + const: "upgrade-caller" + } + }, + type: "object" + } + ] + }, + E_WORKFLOW_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "WORKFLOW_INVALID" + }, + owner: { + const: "config" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "WORKFLOW_INVALID" + }, + parameters: { + $ref: "#/$defs/issue" + } + }, + type: "object" + }, + next_action: { + const: "repair-workflow" + } + }, + type: "object" + } + ] + }, + E_CONFIG_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "CONFIG_INVALID" + }, + owner: { + const: "config" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "CONFIG_INVALID" + }, + parameters: { + $ref: "#/$defs/issue" + } + }, + type: "object" + }, + next_action: { + const: "repair-config" + } + }, + type: "object" + } + ] + }, + E_CONFIG_MODEL_UNSUPPORTED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "CONFIG_MODEL_UNSUPPORTED" + }, + owner: { + const: "config" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "CONFIG_MODEL_UNSUPPORTED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "model" + ], + properties: { + model: { + $ref: "#/$defs/id" + } + } + } + }, + type: "object" + }, + next_action: { + const: "select-supported-model" + } + }, + type: "object" + } + ] + }, + E_CONFIG_FAMILY_UNSUPPORTED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "CONFIG_FAMILY_UNSUPPORTED" + }, + owner: { + const: "config" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "CONFIG_FAMILY_UNSUPPORTED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "family" + ], + properties: { + family: { + $ref: "#/$defs/id" + } + } + } + }, + type: "object" + }, + next_action: { + const: "select-supported-family" + } + }, + type: "object" + } + ] + }, + E_RUNTIME_VERSION_UNSUPPORTED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "RUNTIME_VERSION_UNSUPPORTED" + }, + owner: { + const: "config" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "RUNTIME_VERSION_UNSUPPORTED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "component", + "version" + ], + properties: { + component: { + $ref: "#/$defs/id" + }, + version: { + $ref: "#/$defs/version" + } + } + } + }, + type: "object" + }, + next_action: { + const: "upgrade-runtime" + } + }, + type: "object" + } + ] + }, + E_REPOSITORY_NOT_FOUND: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "REPOSITORY_NOT_FOUND" + }, + owner: { + const: "repository" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "REPOSITORY_NOT_FOUND" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "repository_candidate_digest" + ], + properties: { + repository_candidate_digest: { + $ref: "#/$defs/digest" + } + } + } + }, + type: "object" + }, + next_action: { + const: "open-repository" + } + }, + type: "object" + } + ] + }, + E_REPOSITORY_MISMATCH: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "REPOSITORY_MISMATCH" + }, + owner: { + const: "repository" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "REPOSITORY_MISMATCH" + }, + parameters: { + $ref: "#/$defs/digests" + } + }, + type: "object" + }, + next_action: { + const: "reopen-task-worktree" + } + }, + type: "object" + } + ] + }, + E_TASK_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "TASK_INVALID" + }, + owner: { + const: "repository" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "TASK_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "task_id", + "issue_code" + ], + properties: { + task_id: { + $ref: "#/$defs/id" + }, + issue_code: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "repair-task" + } + }, + type: "object" + } + ] + }, + E_PATH_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "PATH_INVALID" + }, + owner: { + const: "paths" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "PATH_INVALID" + }, + parameters: { + $ref: "#/$defs/taskPath" + } + }, + type: "object" + }, + next_action: { + const: "use-valid-path-claim" + } + }, + type: "object" + } + ] + }, + E_PATH_ESCAPE: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "PATH_ESCAPE" + }, + owner: { + const: "paths" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "PATH_ESCAPE" + }, + parameters: { + $ref: "#/$defs/taskPath" + } + }, + type: "object" + }, + next_action: { + const: "use-task-relative-path" + } + }, + type: "object" + } + ] + }, + E_TASK_SCOPE_VIOLATION: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "TASK_SCOPE_VIOLATION" + }, + owner: { + const: "paths" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "TASK_SCOPE_VIOLATION" + }, + parameters: { + $ref: "#/$defs/taskPath" + } + }, + type: "object" + }, + next_action: { + const: "use-task-scoped-path" + } + }, + type: "object" + } + ] + }, + E_GIT_CONFLICT: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "GIT_CONFLICT" + }, + owner: { + const: "repository" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "GIT_CONFLICT" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "operation" + ], + properties: { + operation: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "resolve-git-conflict" + } + }, + type: "object" + } + ] + }, + E_GIT_DIVERGED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "GIT_DIVERGED" + }, + owner: { + const: "repository" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "GIT_DIVERGED" + }, + parameters: { + $ref: "#/$defs/digests" + } + }, + type: "object" + }, + next_action: { + const: "reconcile-git-history" + } + }, + type: "object" + } + ] + }, + E_HANDOFF_REQUIRED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "HANDOFF_REQUIRED" + }, + owner: { + const: "repository" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "HANDOFF_REQUIRED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "phase_instance" + ], + properties: { + phase_instance: { + $ref: "#/$defs/phase" + } + } + } + }, + type: "object" + }, + next_action: { + const: "complete-clean-handoff" + } + }, + type: "object" + } + ] + }, + E_POLICY_BASE_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "POLICY_BASE_INVALID" + }, + owner: { + const: "policy" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "POLICY_BASE_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "expected_digest" + ], + properties: { + expected_digest: { + $ref: "#/$defs/digest" + }, + observed_digest: { + $ref: "#/$defs/digest" + } + } + } + }, + type: "object" + }, + next_action: { + const: "restore-policy-base" + } + }, + type: "object" + } + ] + }, + E_WORKFLOW_MISMATCH: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "WORKFLOW_MISMATCH" + }, + owner: { + const: "policy" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "WORKFLOW_MISMATCH" + }, + parameters: { + $ref: "#/$defs/digests" + } + }, + type: "object" + }, + next_action: { + const: "restore-pinned-workflow" + } + }, + type: "object" + } + ] + }, + E_PINNED_CONFIG_MISMATCH: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "PINNED_CONFIG_MISMATCH" + }, + owner: { + const: "policy" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "PINNED_CONFIG_MISMATCH" + }, + parameters: { + $ref: "#/$defs/digests" + } + }, + type: "object" + }, + next_action: { + const: "restore-pinned-config" + } + }, + type: "object" + } + ] + }, + E_STALE_SKILLS: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "STALE_SKILLS" + }, + owner: { + const: "policy" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "STALE_SKILLS" + }, + parameters: { + $ref: "#/$defs/digests" + } + }, + type: "object" + }, + next_action: { + const: "refresh-skills" + } + }, + type: "object" + } + ] + }, + E_STATE_MISSING: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "STATE_MISSING" + }, + owner: { + const: "state" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "STATE_MISSING" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "phase_instance" + ], + properties: { + phase_instance: { + $ref: "#/$defs/phase" + } + } + } + }, + type: "object" + }, + next_action: { + const: "initialize-state" + } + }, + type: "object" + } + ] + }, + E_STATE_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "STATE_INVALID" + }, + owner: { + const: "state" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "STATE_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "phase_instance", + "issue_code" + ], + properties: { + phase_instance: { + $ref: "#/$defs/phase" + }, + issue_code: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "repair-state" + } + }, + type: "object" + } + ] + }, + E_TRANSITION_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "TRANSITION_INVALID" + }, + owner: { + const: "state" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "TRANSITION_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "phase_instance", + "from", + "to" + ], + properties: { + phase_instance: { + $ref: "#/$defs/phase" + }, + from: { + $ref: "#/$defs/code" + }, + to: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "select-valid-transition" + } + }, + type: "object" + } + ] + }, + E_INPUT_FINGERPRINT_MISMATCH: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "INPUT_FINGERPRINT_MISMATCH" + }, + owner: { + const: "state" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "INPUT_FINGERPRINT_MISMATCH" + }, + parameters: { + $ref: "#/$defs/digests" + } + }, + type: "object" + }, + next_action: { + const: "create-fresh-intent" + } + }, + type: "object" + } + ] + }, + E_STATE_CONFLICT: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "STATE_CONFLICT" + }, + owner: { + const: "state" + }, + retryable: { + const: true + }, + diagnostic: { + properties: { + template_id: { + const: "STATE_CONFLICT" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "expected_revision", + "observed_revision" + ], + properties: { + expected_revision: { + $ref: "#/$defs/integer" + }, + observed_revision: { + $ref: "#/$defs/integer" + } + } + } + }, + type: "object" + }, + next_action: { + const: "reread-and-retry-intent" + } + }, + type: "object" + } + ] + }, + E_SUPPLEMENTAL_REVIEW_REQUIRED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "SUPPLEMENTAL_REVIEW_REQUIRED" + }, + owner: { + const: "state" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "SUPPLEMENTAL_REVIEW_REQUIRED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "gate_id", + "evidence_digest" + ], + properties: { + gate_id: { + $ref: "#/$defs/id" + }, + evidence_digest: { + $ref: "#/$defs/digest" + } + } + } + }, + type: "object" + }, + next_action: { + const: "triage-supplemental-review" + } + }, + type: "object" + } + ] + }, + E_INTENT_MISMATCH: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "INTENT_MISMATCH" + }, + owner: { + const: "intent" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "INTENT_MISMATCH" + }, + parameters: { + $ref: "#/$defs/digests" + } + }, + type: "object" + }, + next_action: { + const: "create-fresh-intent" + } + }, + type: "object" + } + ] + }, + E_SNAPSHOT_LIMIT: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "SNAPSHOT_LIMIT" + }, + owner: { + const: "snapshot" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "SNAPSHOT_LIMIT" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "limit_scope", + "offending_paths", + "current_bytes", + "byte_cap" + ], + properties: { + limit_scope: { + enum: [ + "result", + "task" + ] + }, + offending_paths: { + type: "array", + minItems: 1, + uniqueItems: true, + "x-archflow-sorted-unique": true, + items: { + $ref: "#/$defs/path" + } + }, + current_bytes: { + $ref: "#/$defs/integer" + }, + byte_cap: { + $ref: "#/$defs/integer" + } + } + } + }, + type: "object" + }, + next_action: { + const: "reduce-snapshot" + } + }, + type: "object" + } + ] + }, + E_SNAPSHOT_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "SNAPSHOT_INVALID" + }, + owner: { + const: "snapshot" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "SNAPSHOT_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "snapshot_digest", + "issue_code" + ], + properties: { + snapshot_digest: { + $ref: "#/$defs/digest" + }, + issue_code: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "repair-snapshot" + } + }, + type: "object" + } + ] + }, + E_RESTORE_COLLISION: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "RESTORE_COLLISION" + }, + owner: { + const: "snapshot" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "RESTORE_COLLISION" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "gate_id", + "path_class" + ], + properties: { + gate_id: { + $ref: "#/$defs/id" + }, + path_class: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "resolve-restore-gate" + } + }, + type: "object" + } + ] + }, + E_RECONCILIATION_REQUIRED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "RECONCILIATION_REQUIRED" + }, + owner: { + const: "snapshot" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "RECONCILIATION_REQUIRED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "recorded_digest", + "observed_digest" + ], + properties: { + recorded_digest: { + $ref: "#/$defs/digest" + }, + observed_digest: { + $ref: "#/$defs/digest" + } + } + } + }, + type: "object" + }, + next_action: { + const: "run-reconciliation" + } + }, + type: "object" + } + ] + }, + E_SECRET_DETECTED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "SECRET_DETECTED" + }, + owner: { + const: "snapshot" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "SECRET_DETECTED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "path_class", + "detector_id" + ], + properties: { + path_class: { + $ref: "#/$defs/code" + }, + detector_id: { + $ref: "#/$defs/id" + } + } + } + }, + type: "object" + }, + next_action: { + const: "remove-secret" + } + }, + type: "object" + } + ] + }, + E_GATE_ACTIVE: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "GATE_ACTIVE" + }, + owner: { + const: "gate" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "GATE_ACTIVE" + }, + parameters: { + $ref: "#/$defs/gateParams" + } + }, + type: "object" + }, + next_action: { + const: "resolve-recorded-gate" + } + }, + type: "object" + } + ] + }, + E_GATE_DECISION_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "GATE_DECISION_INVALID" + }, + owner: { + const: "gate" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "GATE_DECISION_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "gate_id", + "gate_kind", + "issue_code" + ], + properties: { + gate_id: { + $ref: "#/$defs/id" + }, + gate_kind: { + $ref: "#/$defs/gate" + }, + issue_code: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "record-valid-gate-decision" + } + }, + type: "object" + } + ] + }, + E_GATE_CANCELLED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "GATE_CANCELLED" + }, + owner: { + const: "gate" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "GATE_CANCELLED" + }, + parameters: { + $ref: "#/$defs/gateParams" + } + }, + type: "object" + }, + next_action: { + const: "restart-gate-flow" + } + }, + type: "object" + } + ] + }, + gateParams: { + type: "object", + additionalProperties: false, + required: [ + "gate_id", + "gate_kind" + ], + properties: { + gate_id: { + $ref: "#/$defs/id" + }, + gate_kind: { + $ref: "#/$defs/gate" + } + } + }, + E_UNSUPPORTED_HOST: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "UNSUPPORTED_HOST" + }, + owner: { + const: "routing" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "UNSUPPORTED_HOST" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "host" + ], + properties: { + host: { + $ref: "#/$defs/id" + } + } + } + }, + type: "object" + }, + next_action: { + const: "select-supported-host" + } + }, + type: "object" + } + ] + }, + E_UNSUPPORTED_MODEL: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "UNSUPPORTED_MODEL" + }, + owner: { + const: "routing" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "UNSUPPORTED_MODEL" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "model" + ], + properties: { + model: { + $ref: "#/$defs/id" + } + } + } + }, + type: "object" + }, + next_action: { + const: "select-supported-model" + } + }, + type: "object" + } + ] + }, + E_FAMILY_MISMATCH: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "FAMILY_MISMATCH" + }, + owner: { + const: "routing" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "FAMILY_MISMATCH" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "expected_family", + "observed_family" + ], + properties: { + expected_family: { + $ref: "#/$defs/family" + }, + observed_family: { + $ref: "#/$defs/family" + } + } + } + }, + type: "object" + }, + next_action: { + const: "select-correct-family" + } + }, + type: "object" + } + ] + }, + E_CLI_VERSION_UNSUPPORTED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "CLI_VERSION_UNSUPPORTED" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "CLI_VERSION_UNSUPPORTED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "adapter", + "version" + ], + properties: { + adapter: { + $ref: "#/$defs/adapter" + }, + version: { + $ref: "#/$defs/version" + } + } + } + }, + type: "object" + }, + next_action: { + const: "upgrade-cli" + } + }, + type: "object" + } + ] + }, + E_AUTH_UNAVAILABLE: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "AUTH_UNAVAILABLE" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "AUTH_UNAVAILABLE" + }, + parameters: { + $ref: "#/$defs/adapterOnly" + } + }, + type: "object" + }, + next_action: { + const: "repair-authentication" + } + }, + type: "object" + } + ] + }, + E_CLI_MISSING: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "CLI_MISSING" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "CLI_MISSING" + }, + parameters: { + $ref: "#/$defs/adapterOnly" + } + }, + type: "object" + }, + next_action: { + const: "install-cli" + } + }, + type: "object" + } + ] + }, + adapterOnly: { + type: "object", + additionalProperties: false, + required: [ + "adapter" + ], + properties: { + adapter: { + $ref: "#/$defs/adapter" + } + } + }, + adapterAttempt: { + type: "object", + additionalProperties: false, + required: [ + "adapter", + "attempt" + ], + properties: { + adapter: { + $ref: "#/$defs/adapter" + }, + attempt: { + $ref: "#/$defs/integer" + } + } + }, + E_SANDBOX_UNAVAILABLE: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "SANDBOX_UNAVAILABLE" + }, + owner: { + const: "sandbox" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "SANDBOX_UNAVAILABLE" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "capability" + ], + properties: { + capability: { + $ref: "#/$defs/id" + } + } + } + }, + type: "object" + }, + next_action: { + const: "repair-sandbox" + } + }, + type: "object" + } + ] + }, + E_SANDBOX_PROBE_FAILED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "SANDBOX_PROBE_FAILED" + }, + owner: { + const: "sandbox" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "SANDBOX_PROBE_FAILED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "capability", + "failure_class" + ], + properties: { + capability: { + $ref: "#/$defs/id" + }, + failure_class: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "repair-sandbox" + } + }, + type: "object" + } + ] + }, + E_RATE_LIMITED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "RATE_LIMITED" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: true + }, + diagnostic: { + properties: { + template_id: { + const: "RATE_LIMITED" + }, + parameters: { + $ref: "#/$defs/adapterAttempt" + } + }, + type: "object" + }, + next_action: { + const: "retry-after-backoff" + } + }, + type: "object" + } + ] + }, + E_TIMEOUT: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "TIMEOUT" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: true + }, + diagnostic: { + properties: { + template_id: { + const: "TIMEOUT" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "adapter", + "attempt", + "limit_ms" + ], + properties: { + adapter: { + $ref: "#/$defs/adapter" + }, + attempt: { + $ref: "#/$defs/integer" + }, + limit_ms: { + $ref: "#/$defs/integer" + } + } + } + }, + type: "object" + }, + next_action: { + const: "retry-unchanged-attempt" + } + }, + type: "object" + } + ] + }, + E_CANCELLED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "CANCELLED" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: true + }, + diagnostic: { + properties: { + template_id: { + const: "CANCELLED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "source", + "attempt" + ], + properties: { + source: { + enum: [ + "client", + "transport" + ] + }, + attempt: { + $ref: "#/$defs/integer" + } + } + } + }, + type: "object" + }, + next_action: { + const: "restart-child-attempt" + } + }, + type: "object" + } + ] + }, + E_MODEL_OUTPUT_INVALID: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "MODEL_OUTPUT_INVALID" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: true + }, + diagnostic: { + properties: { + template_id: { + const: "MODEL_OUTPUT_INVALID" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "adapter", + "attempt", + "issue_code" + ], + properties: { + adapter: { + $ref: "#/$defs/adapter" + }, + attempt: { + $ref: "#/$defs/integer" + }, + issue_code: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "retry-unchanged-attempt" + } + }, + type: "object" + } + ] + }, + E_IO_ERROR: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "IO_ERROR" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: true + }, + diagnostic: { + properties: { + template_id: { + const: "IO_ERROR" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "operation", + "attempt" + ], + properties: { + operation: { + $ref: "#/$defs/code" + }, + attempt: { + $ref: "#/$defs/integer" + } + } + } + }, + type: "object" + }, + next_action: { + const: "retry-unchanged-attempt" + } + }, + type: "object" + } + ] + }, + E_OUTPUT_OVERFLOW: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "OUTPUT_OVERFLOW" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "OUTPUT_OVERFLOW" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "adapter", + "byte_count", + "byte_cap" + ], + properties: { + adapter: { + $ref: "#/$defs/adapter" + }, + byte_count: { + $ref: "#/$defs/integer" + }, + byte_cap: { + $ref: "#/$defs/integer" + } + } + } + }, + type: "object" + }, + next_action: { + const: "reduce-output" + } + }, + type: "object" + } + ] + }, + E_PROCESS_FAILED: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "PROCESS_FAILED" + }, + owner: { + const: "dispatch" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "PROCESS_FAILED" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "adapter", + "exit_class" + ], + properties: { + adapter: { + $ref: "#/$defs/adapter" + }, + exit_class: { + $ref: "#/$defs/code" + } + } + } + }, + type: "object" + }, + next_action: { + const: "repair-before-fresh-attempt" + } + }, + type: "object" + } + ] + }, + E_INTERNAL_ERROR: { + allOf: [ + { + $ref: "#/$defs/errorBase" + }, + { + properties: { + code: { + const: "INTERNAL_ERROR" + }, + owner: { + const: "integrity" + }, + retryable: { + const: false + }, + diagnostic: { + properties: { + template_id: { + const: "INTERNAL_ERROR" + }, + parameters: { + type: "object", + additionalProperties: false, + required: [ + "correlation_id" + ], + properties: { + correlation_id: { + $ref: "#/$defs/id" + } + } + } + }, + type: "object" + }, + next_action: { + const: "stop-and-inspect" + } + }, + type: "object" + } + ] + }, + errorBase: { + type: "object", + additionalProperties: false, + required: [ + "schema_version", + "code", + "owner", + "retryable", + "diagnostic", + "next_action" + ], + properties: { + schema_version: { + const: "1" + }, + code: {}, + owner: {}, + retryable: {}, + diagnostic: { + type: "object", + additionalProperties: false, + required: [ + "template_id", + "parameters" + ], + properties: { + template_id: {}, + parameters: {} + } + }, + next_action: {} + } + } + }, + oneOf: [ + { + $ref: "#/$defs/E_CONTRACT_INVALID" + }, + { + $ref: "#/$defs/E_RESULT_INVALID" + }, + { + $ref: "#/$defs/E_CONTRACT_VERSION_UNSUPPORTED" + }, + { + $ref: "#/$defs/E_WORKFLOW_INVALID" + }, + { + $ref: "#/$defs/E_CONFIG_INVALID" + }, + { + $ref: "#/$defs/E_CONFIG_MODEL_UNSUPPORTED" + }, + { + $ref: "#/$defs/E_CONFIG_FAMILY_UNSUPPORTED" + }, + { + $ref: "#/$defs/E_RUNTIME_VERSION_UNSUPPORTED" + }, + { + $ref: "#/$defs/E_REPOSITORY_NOT_FOUND" + }, + { + $ref: "#/$defs/E_REPOSITORY_MISMATCH" + }, + { + $ref: "#/$defs/E_TASK_INVALID" + }, + { + $ref: "#/$defs/E_PATH_INVALID" + }, + { + $ref: "#/$defs/E_PATH_ESCAPE" + }, + { + $ref: "#/$defs/E_TASK_SCOPE_VIOLATION" + }, + { + $ref: "#/$defs/E_GIT_CONFLICT" + }, + { + $ref: "#/$defs/E_GIT_DIVERGED" + }, + { + $ref: "#/$defs/E_HANDOFF_REQUIRED" + }, + { + $ref: "#/$defs/E_POLICY_BASE_INVALID" + }, + { + $ref: "#/$defs/E_WORKFLOW_MISMATCH" + }, + { + $ref: "#/$defs/E_PINNED_CONFIG_MISMATCH" + }, + { + $ref: "#/$defs/E_STALE_SKILLS" + }, + { + $ref: "#/$defs/E_STATE_MISSING" + }, + { + $ref: "#/$defs/E_STATE_INVALID" + }, + { + $ref: "#/$defs/E_TRANSITION_INVALID" + }, + { + $ref: "#/$defs/E_INPUT_FINGERPRINT_MISMATCH" + }, + { + $ref: "#/$defs/E_STATE_CONFLICT" + }, + { + $ref: "#/$defs/E_SUPPLEMENTAL_REVIEW_REQUIRED" + }, + { + $ref: "#/$defs/E_INTENT_MISMATCH" + }, + { + $ref: "#/$defs/E_SNAPSHOT_LIMIT" + }, + { + $ref: "#/$defs/E_SNAPSHOT_INVALID" + }, + { + $ref: "#/$defs/E_RESTORE_COLLISION" + }, + { + $ref: "#/$defs/E_RECONCILIATION_REQUIRED" + }, + { + $ref: "#/$defs/E_SECRET_DETECTED" + }, + { + $ref: "#/$defs/E_GATE_ACTIVE" + }, + { + $ref: "#/$defs/E_GATE_DECISION_INVALID" + }, + { + $ref: "#/$defs/E_GATE_CANCELLED" + }, + { + $ref: "#/$defs/E_UNSUPPORTED_HOST" + }, + { + $ref: "#/$defs/E_UNSUPPORTED_MODEL" + }, + { + $ref: "#/$defs/E_FAMILY_MISMATCH" + }, + { + $ref: "#/$defs/E_CLI_VERSION_UNSUPPORTED" + }, + { + $ref: "#/$defs/E_AUTH_UNAVAILABLE" + }, + { + $ref: "#/$defs/E_CLI_MISSING" + }, + { + $ref: "#/$defs/E_SANDBOX_UNAVAILABLE" + }, + { + $ref: "#/$defs/E_SANDBOX_PROBE_FAILED" + }, + { + $ref: "#/$defs/E_RATE_LIMITED" + }, + { + $ref: "#/$defs/E_TIMEOUT" + }, + { + $ref: "#/$defs/E_CANCELLED" + }, + { + $ref: "#/$defs/E_MODEL_OUTPUT_INVALID" + }, + { + $ref: "#/$defs/E_IO_ERROR" + }, + { + $ref: "#/$defs/E_OUTPUT_OVERFLOW" + }, + { + $ref: "#/$defs/E_PROCESS_FAILED" + }, + { + $ref: "#/$defs/E_INTERNAL_ERROR" + } + ] +}; + +// src/contracts/schemas/v1/rubric.schema.json +var rubric_schema_default = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: "urn:archflow:schema:v1:rubric", + type: "object", + additionalProperties: false, + required: ["schema_version", "kind", "mode", "criteria"], + properties: { + schema_version: { const: "1" }, + kind: { enum: ["artifact", "implementation"] }, + mode: { enum: ["self_review", "adversarial"] }, + criteria: { type: "array", minItems: 1, uniqueItems: true, "x-archflow-unique-by": "id", items: { type: "object", additionalProperties: false, required: ["id", "text", "blocking"], properties: { id: { type: "string", pattern: "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$" }, text: { type: "string", minLength: 1, pattern: "\\S" }, blocking: { type: "boolean" } } } } + } +}; + +// src/mcp/tools.ts +var JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema"; +var MCP_SCHEMA_ID = "https://archflow.dev/schemas/v1/mcp-tools"; +var schemaDocuments = Object.freeze([ + Object.freeze({ key: "mcp-tools", id: MCP_SCHEMA_ID, schema: mcp_tools_schema_default }), + Object.freeze({ key: "primitives", id: "urn:archflow:schema:v1:primitives", schema: primitives_schema_default }), + Object.freeze({ key: "path-claim", id: "urn:archflow:schema:v1:path-claim", schema: path_claim_schema_default }), + Object.freeze({ key: "evidence-slots", id: "urn:archflow:schema:v1:evidence-slots", schema: evidence_slots_schema_default }), + Object.freeze({ key: "rubric", id: "urn:archflow:schema:v1:rubric", schema: rubric_schema_default }), + Object.freeze({ key: "gate-contract", id: "urn:archflow:schema:v1:gate-contract", schema: gate_contract_schema_default }), + Object.freeze({ key: "gate-decision", id: "urn:archflow:schema:v1:gate-decision", schema: gate_decision_schema_default }), + Object.freeze({ key: "project-error", id: "urn:archflow:schema:v1:project-error", schema: project_error_schema_default }) +]); +var documentKeysById = new Map(schemaDocuments.map(({ id: id4, key }) => [id4, key])); +function isObject2(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function localReference(sourceKey, reference) { + const hash2 = reference.indexOf("#"); + const documentId = hash2 === -1 ? reference : reference.slice(0, hash2); + const fragment = hash2 === -1 ? "" : reference.slice(hash2 + 1); + const targetKey = documentId === "" ? sourceKey : documentKeysById.get(documentId); + if (targetKey === void 0) throw new TypeError(`unknown normative schema reference: ${reference}`); + if (fragment !== "" && !fragment.startsWith("/")) throw new TypeError(`unsupported normative schema fragment: ${reference}`); + return `#/$defs/${targetKey}${fragment}`; +} +function project(value, sourceKey) { + if (Array.isArray(value)) return value.map((entry) => project(entry, sourceKey)); + if (!isObject2(value)) return value; + const projected = {}; + for (const [key, entry] of Object.entries(value)) { + if (key === "$id" || key === "$schema" || key === "$anchor" || key === "$dynamicAnchor" || key.startsWith("x-archflow-")) continue; + projected[key] = key === "$ref" && typeof entry === "string" ? localReference(sourceKey, entry) : project(entry, sourceKey); + } + return projected; +} +function schemaFragment(name, member) { + const definitions = mcp_tools_schema_default.$defs; + const tool2 = isObject2(definitions) ? definitions[name] : void 0; + const fragment = isObject2(tool2) ? tool2[member] : void 0; + if (!isObject2(fragment)) throw new TypeError(`missing normative schema fragment for ${name}/${member}`); + return fragment; +} +function standaloneSchema(name, member) { + const definitions = Object.fromEntries( + schemaDocuments.map(({ key, schema }) => [key, project(schema, key)]) + ); + return deepFreeze4({ + $schema: JSON_SCHEMA_2020_12, + ...project(schemaFragment(name, member), "mcp-tools"), + type: "object", + $defs: definitions + }); +} +function deepFreeze4(value) { + if (typeof value !== "object" && typeof value !== "function" || value === null || Object.isFrozen(value)) return value; + for (const child of Object.values(value)) deepFreeze4(child); + return Object.freeze(value); +} +var ADVERTISED_TOOL_CATALOGUE = deepFreeze4( + TOOL_NAMES.map((name) => ({ + name, + inputSchema: standaloneSchema(name, "input"), + outputSchema: standaloneSchema(name, "result") + })) +); + +// src/mcp/sdk-adapter.ts +var PROTOCOL_VERSION = "2025-11-25"; +var CONNECTION_ID = "connection-1"; +var JSON_RPC2 = "2.0"; +function deferred3() { + let resolve; + const promise2 = new Promise((settle) => { + resolve = settle; + }); + return { promise: promise2, resolve }; +} +function isObject3(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function canonicalMessage(value) { + const message = { jsonrpc: JSON_RPC2 }; + if (Object.hasOwn(value, "id")) message.id = value.id; + if (Object.hasOwn(value, "result")) { + message.result = value.result; + } else if (Object.hasOwn(value, "error")) { + const supplied = value.error; + if (!isObject3(supplied)) throw new TypeError("an error response must contain an error object"); + const error51 = { code: supplied.code, message: supplied.message }; + if (Object.hasOwn(supplied, "data")) error51.data = supplied.data; + message.error = error51; + } else { + throw new TypeError("a response must contain a result or error"); + } + return Buffer3.from(`${JSON.stringify(message)} +`, "utf8"); +} +var PROTOCOL_CODES = Object.freeze({ + TOOL_NOT_FOUND: -32001, + TOOL_DISABLED: -32002, + UNSUPPORTED_PROTOCOL: -32003, + INITIALIZATION_REPEATED: -32004 +}); +function protocolCode(error51) { + return PROTOCOL_CODES[error51.code]; +} +function protocolResponse(id4, error51) { + return { jsonrpc: JSON_RPC2, id: id4, error: { code: protocolCode(error51), message: error51.code, data: error51 } }; +} +function internalResponse(id4) { + return { jsonrpc: JSON_RPC2, id: id4, error: { code: -32603, message: "Internal error" } }; +} +function wireResult(outcome) { + return JSON.parse(JSON.stringify(outcome.result)); +} +function projectOutcome2(server, id4, expected) { + const outcome = expected.outcome; + if (outcome.kind === "protocol-error") return protocolResponse(id4, outcome.error.value); + const descriptor = ADVERTISED_TOOL_CATALOGUE.find(({ name }) => name === outcome.tool); + if (descriptor === void 0) throw new TypeError("the projected tool is not advertised"); + const result = outcome.result; + const structuredContent = wireResult(outcome); + const projected = server.projectCallToolResult({ + structuredContent, + content: [{ type: "text", text: JSON.stringify(structuredContent) }], + isError: !result.ok + }, descriptor.outputSchema); + return { jsonrpc: JSON_RPC2, id: id4, result: projected }; +} +function matchesExpectedProjection(server, message, expected) { + const outcome = expected.outcome; + if (outcome.kind === "protocol-error") { + const error51 = message.error; + return isObject3(error51) && error51.message === outcome.error.value.code && isDeepStrictEqual3(error51.data, outcome.error.value); + } + if (!Object.hasOwn(message, "result")) return false; + const expectedMessage = projectOutcome2(server, 0, expected); + return isDeepStrictEqual3(message.result, expectedMessage.result); +} +async function startMcpRuntime(options) { + if (!isObject3(options) || typeof options.workingDirectory !== "string") { + throw new TypeError("valid MCP runtime options are required"); + } + const handlers = options.handlers ?? {}; + const boundary = createToolBoundary(handlers); + const session = createSessionController({ connectionId: CONNECTION_ID }); + const startup = connectionContextFactory.captureStartup({ + connection_id: CONNECTION_ID, + startup_repository_candidate: { working_directory: options.workingDirectory } + }); + const server = new Server( + { name: "archflow-mcp", version: "0.0.0" }, + { supportedProtocolVersions: [PROTOCOL_VERSION] } + ); + server.registerCapabilities({ tools: {} }); + const framer = createJsonLineFramer(); + const forwardedCalls = /* @__PURE__ */ new Map(); + const sdkValidationCandidates = /* @__PURE__ */ new Set(); + const closed = deferred3(); + let connection; + let closing = false; + let terminated = false; + let processing = false; + let eofPending = false; + let closePromise; + const onObservedOutputError = () => { + void terminate("output-error"); + }; + options.output.on("error", onObservedOutputError); + const removeInputListeners = () => { + options.input.off("data", onData); + options.input.off("end", onEnd); + options.input.off("error", onInputError); + }; + const queue = createSendQueue( + options.output, + (paused) => { + if (closing) return; + if (paused) options.input.pause(); + else { + options.input.resume(); + drainFrames(); + } + }, + () => { + void terminate("output-error"); + } + ); + const enqueue = (source, message, requestToken, expectedProjection) => { + if (closing) return Promise.reject(new Error("MCP runtime is closing")); + let selected = message; + try { + if (expectedProjection !== void 0) { + const id4 = message.id; + if (typeof id4 !== "string" && typeof id4 !== "number") throw new TypeError("missing response ID"); + selected = matchesExpectedProjection(server, message, expectedProjection) ? projectOutcome2(server, id4, expectedProjection) : internalResponse(id4); + } + const receipt = queue.enqueue({ source, frame: canonicalMessage(selected), ...requestToken === void 0 ? {} : { requestToken } }); + void receipt.admitted.then( + () => { + session.onSendAdmitted(requestToken); + drainFrames(); + }, + () => void 0 + ); + void receipt.completed.then( + () => { + if (requestToken !== void 0) session.onRouteSettled(requestToken); + }, + () => void 0 + ); + return receipt.completed; + } catch { + if (requestToken !== void 0 && typeof message.id !== "undefined") { + try { + const fallback = queue.enqueue({ source: "fallback", frame: canonicalMessage(internalResponse(message.id)), requestToken }); + void fallback.admitted.then(() => session.onSendAdmitted(requestToken), () => void 0); + void fallback.completed.then(() => session.onRouteSettled(requestToken), () => void 0); + return fallback.completed; + } catch { + } + } + void terminate("protocol-fatal"); + return Promise.reject(new Error("MCP response projection failed")); + } + }; + const applyActions = (actions) => { + if (closing) return; + for (const action of actions) { + if (closing) return; + if (action.kind === "protocol-fatal") { + void terminate("protocol-fatal"); + } else if (action.kind === "connection-ready") { + const client = server.getClientVersion(); + const protocolVersion = server.getNegotiatedProtocolVersion(); + if (client === void 0 || protocolVersion === void 0) { + void terminate("protocol-fatal"); + return; + } + try { + connection = startup.initialize({ client, host: "unknown", protocol_version: protocolVersion }); + } catch { + void terminate("protocol-fatal"); + } + } else if (action.kind === "send") { + void enqueue(action.source, action.message, action.requestToken, action.expectedProjection).catch(() => void 0); + } else if (action.kind === "validate-cancellation") { + if (specTypeSchemas.CancelledNotification["~standard"].validate(action.message).issues === void 0) { + applyActions(session.acceptSdkMessage({ + kind: "cancellation-accepted", + requestToken: action.requestToken + })); + } + } else { + if (action.route === "tools-call") { + forwardedCalls.set(action.internalId, { + requestToken: action.requestToken, + externalId: action.externalId, + nameCandidate: action.nameCandidate, + argumentsCandidate: action.argumentsCandidate + }); + } + if (action.route === "tools-call" || action.route === "tools-list") { + sdkValidationCandidates.add(action.internalId); + const schema = action.route === "tools-call" ? specTypeSchemas.CallToolRequest : specTypeSchemas.ListToolsRequest; + if (schema["~standard"].validate(action.message).issues !== void 0) { + sdkValidationCandidates.delete(action.internalId); + forwardedCalls.delete(action.internalId); + const rejected = session.acceptSdkMessage({ + jsonrpc: JSON_RPC2, + id: action.internalId, + error: { code: -32602, message: "Invalid params" } + }); + for (const response of rejected) { + if (response.kind === "send") { + void enqueue("sdk", { + jsonrpc: JSON_RPC2, + id: response.message.id, + error: { code: -32602, message: "Invalid params" } + }, response.requestToken).catch(() => void 0); + } else { + applyActions([response]); + } + } + continue; + } + } + transport.onmessage?.(action.message); + } + } + }; + const transport = { + start: async () => void 0, + send: async (message) => { + if (closing) throw new Error("MCP runtime is closing"); + const rawMessage = message; + const id4 = Object.hasOwn(rawMessage, "id") ? rawMessage.id : void 0; + if (server.getNegotiatedProtocolVersion() !== void 0 && typeof id4 === "number") { + const token = `request-${id4}`; + applyActions(session.acceptSdkMessage({ kind: "initialize-mutated", requestToken: token })); + } + const actions = session.acceptSdkMessage(message); + const completions = []; + for (const action of actions) { + if (action.kind === "send") { + if (typeof id4 === "number" && sdkValidationCandidates.delete(id4) && Object.hasOwn(rawMessage, "error")) { + forwardedCalls.delete(id4); + completions.push(enqueue("sdk", { + jsonrpc: JSON_RPC2, + id: action.message.id, + error: { code: -32602, message: "Invalid params" } + }, action.requestToken)); + } else { + completions.push(enqueue(action.source, action.message, action.requestToken, action.expectedProjection)); + } + } else { + applyActions([action]); + } + } + await Promise.all(completions); + }, + close: async () => { + transport.onclose?.(); + } + }; + server.setRequestHandler("tools/list", async (_request, ctx) => { + if (typeof ctx.mcpReq.id === "number") sdkValidationCandidates.delete(ctx.mcpReq.id); + const token = `request-${String(ctx.mcpReq.id)}`; + try { + return { tools: structuredClone(ADVERTISED_TOOL_CATALOGUE) }; + } finally { + session.onRouteSettled(token); + } + }); + server.setRequestHandler("tools/call", async (_request, ctx) => { + const internalId = ctx.mcpReq.id; + if (typeof internalId === "number") sdkValidationCandidates.delete(internalId); + const record2 = typeof internalId === "number" ? forwardedCalls.get(internalId) : void 0; + if (record2 === void 0 || connection === void 0 || !record2.nameCandidate.present) { + throw new ProtocolError(-32603, "Internal error"); + } + try { + const args = record2.argumentsCandidate.present ? record2.argumentsCandidate.value : void 0; + const invocation = createInvocationContext(connection, { + invocation_id: record2.requestToken, + transport_metadata: { request_id: record2.externalId, operation: "tools/call" } + }, ctx.mcpReq.signal); + const outcome = await boundary.invoke(record2.nameCandidate.value, args, invocation); + applyActions(session.acceptSdkMessage({ + kind: "tool-boundary-outcome", + requestToken: record2.requestToken, + outcome + })); + if (outcome.kind === "protocol-error") { + const error51 = outcome.error.value; + throw new ProtocolError(protocolCode(error51), error51.code, error51); + } + const descriptor = ADVERTISED_TOOL_CATALOGUE.find(({ name }) => name === outcome.tool); + if (descriptor === void 0) throw new ProtocolError(-32603, "Internal error"); + const result = outcome.result; + const structuredContent = wireResult(outcome); + return server.projectCallToolResult({ + structuredContent, + content: [{ type: "text", text: JSON.stringify(structuredContent) }], + isError: !result.ok + }, descriptor.outputSchema); + } finally { + forwardedCalls.delete(Number(internalId)); + session.onRouteSettled(record2.requestToken); + } + }); + function handleFrame(frame) { + if (closing) return; + if (frame.kind === "parse-error") { + void enqueue("direct", { jsonrpc: JSON_RPC2, id: null, error: { code: -32700, message: "Parse error" } }).catch(() => void 0); + if (frame.fatal) void terminate("protocol-fatal"); + return; + } + applyActions(session.accept(frame.value)); + } + function drainFrames() { + if (processing || closing || queue.backpressured || session.state === "INITIALIZING") return; + processing = true; + try { + const frame = framer.next(); + if (frame !== void 0) { + handleFrame(frame); + queueMicrotask(drainFrames); + } else if (eofPending && !closing && !queue.backpressured) { + const final = framer.finish(); + if (final !== void 0) { + handleFrame(final); + queueMicrotask(drainFrames); + } else if (!closing) { + void terminate("input-eof"); + } + } + } finally { + processing = false; + } + } + function onData(chunk) { + if (closing) return; + const bytes = typeof chunk === "string" ? Buffer3.from(chunk, "utf8") : chunk; + framer.append(bytes); + drainFrames(); + } + function onEnd() { + eofPending = true; + drainFrames(); + } + function onInputError() { + void terminate("input-error"); + } + async function terminate(reason2) { + if (closePromise !== void 0) return closePromise; + closing = true; + session.close(); + removeInputListeners(); + options.input.pause(); + forwardedCalls.clear(); + sdkValidationCandidates.clear(); + closePromise = (async () => { + let closeFailed = false; + try { + await server.close(); + } catch { + closeFailed = true; + } + try { + await queue.close(); + } catch { + closeFailed = true; + } + options.output.off("error", onObservedOutputError); + if (!terminated) { + terminated = true; + closed.resolve(Object.freeze({ reason: reason2, close_failed: closeFailed })); + } + })(); + return closePromise; + } + server.oninitialized = () => { + applyActions(session.acceptSdkMessage({ kind: "initialized-accepted" })); + drainFrames(); + }; + await server.connect(transport); + options.input.on("data", onData); + options.input.on("end", onEnd); + options.input.on("error", onInputError); + options.input.resume(); + return Object.freeze({ + close: async () => terminate("caller-close"), + closed: closed.promise + }); +} + +// src/main.ts +void runMcpProcess( + { + input: process2.stdin, + output: process2.stdout, + diagnostic: process2.stderr, + workingDirectory: process2.cwd(), + signals: process2, + setExitCode: (code) => { + process2.exitCode = code; + } + }, + startMcpRuntime +); diff --git a/dist/legal/THIRD_PARTY_NOTICES.md b/dist/legal/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..785f904f --- /dev/null +++ b/dist/legal/THIRD_PARTY_NOTICES.md @@ -0,0 +1,16 @@ +# Third-Party Notices + +This generated inventory accompanies the offline ArchFlow MCP payload. +It does not grant a license to ArchFlow itself. + +- ajv@8.18.0 — MIT +- ajv-formats@3.0.1 — MIT +- content-type@1.0.5 — MIT +- fast-deep-equal@3.1.3 — MIT +- fast-uri@3.1.0 — BSD-3-Clause +- json-schema-traverse@1.0.0 — MIT +- @modelcontextprotocol/core@2.0.0 — Apache-2.0 AND MIT +- @modelcontextprotocol/server@2.0.0 — Apache-2.0 AND MIT +- zod@4.4.3 — MIT + +See legal/upstream/ for retained applicable upstream license and notice texts. diff --git a/dist/legal/review.json b/dist/legal/review.json new file mode 100644 index 00000000..3741c936 --- /dev/null +++ b/dist/legal/review.json @@ -0,0 +1,462 @@ +{ + "amendments": [], + "current_components": [ + { + "component_id": "ajv-embedded", + "legal_source": { + "digest": "a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3", + "payload_path": "legal/upstream/ajv-8.18.0/LICENSE", + "source_path": "release/legal/upstream/ajv-8.18.0/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "tarball_url": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz" + }, + "package_name": "ajv", + "package_version": "8.18.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "ajv/lib" + }, + { + "component_id": "ajv-formats-embedded", + "legal_source": { + "digest": "9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf", + "payload_path": "legal/upstream/ajv-formats-3.0.1/LICENSE", + "source_path": "release/legal/upstream/ajv-formats-3.0.1/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "tarball_url": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz" + }, + "package_name": "ajv-formats", + "package_version": "3.0.1", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "ajv-formats/src" + }, + { + "component_id": "content-type-embedded", + "legal_source": { + "digest": "257aed98914108e91a337912727b6a802eef218248507f74b76faffaff517a38", + "payload_path": "legal/upstream/content-type-1.0.5/LICENSE", + "source_path": "release/legal/upstream/content-type-1.0.5/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "tarball_url": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz" + }, + "package_name": "content-type", + "package_version": "1.0.5", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/src-CX2iR2pK.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "content-type" + }, + { + "component_id": "fast-deep-equal-embedded", + "legal_source": { + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "payload_path": "legal/upstream/fast-deep-equal-3.1.3/LICENSE", + "source_path": "release/legal/upstream/fast-deep-equal-3.1.3/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "tarball_url": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" + }, + "package_name": "fast-deep-equal", + "package_version": "3.1.3", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "fast-deep-equal" + }, + { + "component_id": "fast-uri-embedded", + "legal_source": { + "digest": "185ef4f377743572c2bf0931f741fae52401268cbe70c880b74063799814083e", + "payload_path": "legal/upstream/fast-uri-3.1.0/LICENSE", + "source_path": "release/legal/upstream/fast-uri-3.1.0/LICENSE" + }, + "license_expression": "BSD-3-Clause", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "tarball_url": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz" + }, + "package_name": "fast-uri", + "package_version": "3.1.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "fast-uri/lib" + }, + { + "component_id": "json-schema-traverse-embedded", + "legal_source": { + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "payload_path": "legal/upstream/json-schema-traverse-1.0.0/LICENSE", + "source_path": "release/legal/upstream/json-schema-traverse-1.0.0/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "tarball_url": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz" + }, + "package_name": "json-schema-traverse", + "package_version": "1.0.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "json-schema-traverse" + }, + { + "component_id": "modelcontextprotocol-core-installed", + "legal_source": { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "payload_path": "legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE", + "source_path": "release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE" + }, + "license_expression": "Apache-2.0 AND MIT", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", + "tarball_url": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz" + }, + "package_name": "@modelcontextprotocol/core", + "package_version": "2.0.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "LICENSE", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "dist/auth-CUe6YdwF.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "package.json", + "package_version": "2.0.0" + } + ], + "provenance_kind": "installed", + "source_map_expected": true, + "source_root": "dist" + }, + { + "component_id": "modelcontextprotocol-server-installed", + "legal_source": { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "payload_path": "legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE", + "source_path": "release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE" + }, + "license_expression": "Apache-2.0 AND MIT", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==", + "tarball_url": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz" + }, + "package_name": "@modelcontextprotocol/server", + "package_version": "2.0.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "LICENSE", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/dialects-DoSzNhcb.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/mcp-DXXb3Vv3.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/src-CX2iR2pK.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "package.json", + "package_version": "2.0.0" + } + ], + "provenance_kind": "installed", + "source_map_expected": true, + "source_root": "dist" + }, + { + "component_id": "zod-installed", + "legal_source": { + "digest": "3f1189b28e3866e0d979968d466b78f813f76827cfdca1fbb124cc0a5c8841f8", + "payload_path": "legal/upstream/zod-4.4.3/LICENSE", + "source_path": "release/legal/upstream/zod-4.4.3/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "tarball_url": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz" + }, + "package_name": "zod", + "package_version": "4.4.3", + "provenance_inputs": [ + { + "package_name": "zod", + "package_relative_path": "LICENSE", + "package_version": "4.4.3" + }, + { + "package_name": "zod", + "package_relative_path": "package.json", + "package_version": "4.4.3" + } + ], + "provenance_kind": "installed", + "source_map_expected": false, + "source_root": "v4" + } + ], + "dependency_gate_decisions": [ + { + "advisories": [ + { + "affected_version": "3.1.0", + "id": "GHSA-4c8g-83qw-93j6", + "safe_version": "3.1.3", + "severity": "high" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-q3j6-qgpj-74h6", + "safe_version": "3.1.1", + "severity": "high" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-v2hh-gcrm-f6hx", + "safe_version": "3.1.4", + "severity": "high" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-v39h-62p7-jpjc", + "safe_version": "3.1.2", + "severity": "high" + } + ], + "advisory_snapshot": { + "digest": "6282adc7c1d1304f245ff5877a2824b05b53f9842dc658282610c981505f0caf", + "path": "release/evidence/advisory-snapshot.json" + }, + "bundle_digest": "16faf6365bc502ec0c0e00f150b43c300e65dfa9dcace1cce3d98d850b8cbbd0", + "decision_digest": "37aa73ae5cd3da88860c0dad199308a103e9120699a2f52f47ee31d7f5a71358", + "dependency_inventory_digest": "1f93c687b91691f3afb99d657246504a9b369311333ecd4e8c77abab1a23c046", + "entry_bindings": [ + { + "handler_authority": "inert-no-handler", + "id": "mcp-stdio", + "role": "mcp-stdio" + } + ], + "id": "fast-uri-3-1-0-local-risk", + "package_name": "fast-uri", + "package_version": "3.1.0", + "patched_artifact_availability": { + "digest": "deb867f4b505da598ea0bf483ae6ecdb116460ebac573489d7763c720ad55ee1", + "path": "release/evidence/patched-artifact-availability.json" + }, + "reachability_evidence": { + "digest": "cac675f0183bfaa2e44707c4be9e93d156c9a695bef61177f305145995165007", + "path": "release/evidence/focused-inert-reachability.json" + }, + "scope": { + "deployment": "local-only", + "handler_authority": "inert-no-handler", + "invalidated_by": [ + "bundle-change", + "dependency-change", + "entry-change", + "handler-authority-change" + ], + "operators": "user-owned-agents", + "production": false + }, + "status": "accepted", + "user_acceptance": { + "digest": "d625ac9d722a8710bb8b0f18f69207df9434953584393a80e5f66d9e2fa0122f", + "path": "release/evidence/user-risk-acceptance.json" + } + } + ], + "distribution_status": "unresolved", + "inventory_method": "conservative-mapped-component-inventory", + "limitations": [ + "AJV JSON sources may be absent from source-map source content.", + "Embedded component inventory does not claim exact physical-byte attribution or composed source-map ranges.", + "This repository has no project license and this receipt makes no first-party license grant." + ], + "project_license_status": "missing", + "schema_version": "1", + "supersessions": [], + "upstream_legal_sources": [ + { + "component_id": "ajv-embedded", + "digest": "a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "tarball_url": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz" + }, + "payload_path": "legal/upstream/ajv-8.18.0/LICENSE", + "source_path": "release/legal/upstream/ajv-8.18.0/LICENSE" + }, + { + "component_id": "ajv-formats-embedded", + "digest": "9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "tarball_url": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz" + }, + "payload_path": "legal/upstream/ajv-formats-3.0.1/LICENSE", + "source_path": "release/legal/upstream/ajv-formats-3.0.1/LICENSE" + }, + { + "component_id": "content-type-embedded", + "digest": "257aed98914108e91a337912727b6a802eef218248507f74b76faffaff517a38", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "tarball_url": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz" + }, + "payload_path": "legal/upstream/content-type-1.0.5/LICENSE", + "source_path": "release/legal/upstream/content-type-1.0.5/LICENSE" + }, + { + "component_id": "fast-deep-equal-embedded", + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "tarball_url": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" + }, + "payload_path": "legal/upstream/fast-deep-equal-3.1.3/LICENSE", + "source_path": "release/legal/upstream/fast-deep-equal-3.1.3/LICENSE" + }, + { + "component_id": "fast-uri-embedded", + "digest": "185ef4f377743572c2bf0931f741fae52401268cbe70c880b74063799814083e", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "tarball_url": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz" + }, + "payload_path": "legal/upstream/fast-uri-3.1.0/LICENSE", + "source_path": "release/legal/upstream/fast-uri-3.1.0/LICENSE" + }, + { + "component_id": "json-schema-traverse-embedded", + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "tarball_url": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz" + }, + "payload_path": "legal/upstream/json-schema-traverse-1.0.0/LICENSE", + "source_path": "release/legal/upstream/json-schema-traverse-1.0.0/LICENSE" + }, + { + "component_id": "modelcontextprotocol-core-installed", + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", + "tarball_url": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz" + }, + "payload_path": "legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE", + "source_path": "release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE" + }, + { + "component_id": "modelcontextprotocol-server-installed", + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==", + "tarball_url": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz" + }, + "payload_path": "legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE", + "source_path": "release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE" + }, + { + "component_id": "zod-installed", + "digest": "3f1189b28e3866e0d979968d466b78f813f76827cfdca1fbb124cc0a5c8841f8", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "tarball_url": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz" + }, + "payload_path": "legal/upstream/zod-4.4.3/LICENSE", + "source_path": "release/legal/upstream/zod-4.4.3/LICENSE" + } + ] +} diff --git a/dist/legal/upstream/ajv-8.18.0/LICENSE b/dist/legal/upstream/ajv-8.18.0/LICENSE new file mode 100644 index 00000000..139162ad --- /dev/null +++ b/dist/legal/upstream/ajv-8.18.0/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2021 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/dist/legal/upstream/ajv-formats-3.0.1/LICENSE b/dist/legal/upstream/ajv-formats-3.0.1/LICENSE new file mode 100644 index 00000000..a3f8ba02 --- /dev/null +++ b/dist/legal/upstream/ajv-formats-3.0.1/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dist/legal/upstream/content-type-1.0.5/LICENSE b/dist/legal/upstream/content-type-1.0.5/LICENSE new file mode 100644 index 00000000..34b1a2de --- /dev/null +++ b/dist/legal/upstream/content-type-1.0.5/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/dist/legal/upstream/fast-deep-equal-3.1.3/LICENSE b/dist/legal/upstream/fast-deep-equal-3.1.3/LICENSE new file mode 100644 index 00000000..7f154356 --- /dev/null +++ b/dist/legal/upstream/fast-deep-equal-3.1.3/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dist/legal/upstream/fast-uri-3.1.0/LICENSE b/dist/legal/upstream/fast-uri-3.1.0/LICENSE new file mode 100644 index 00000000..a8fe7895 --- /dev/null +++ b/dist/legal/upstream/fast-uri-3.1.0/LICENSE @@ -0,0 +1,32 @@ +Copyright (c) 2011-2021, Gary Court until https://github.com/garycourt/uri-js/commit/a1acf730b4bba3f1097c9f52e7d9d3aba8cdcaae +Copyright (c) 2021-present The Fastify team +All rights reserved. + +The Fastify team members are listed at https://github.com/fastify/fastify#team. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: +- https://github.com/garycourt/uri-js/graphs/contributors \ No newline at end of file diff --git a/dist/legal/upstream/json-schema-traverse-1.0.0/LICENSE b/dist/legal/upstream/json-schema-traverse-1.0.0/LICENSE new file mode 100644 index 00000000..7f154356 --- /dev/null +++ b/dist/legal/upstream/json-schema-traverse-1.0.0/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dist/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE b/dist/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE new file mode 100644 index 00000000..4a939857 --- /dev/null +++ b/dist/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/dist/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE b/dist/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE new file mode 100644 index 00000000..4a939857 --- /dev/null +++ b/dist/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/dist/legal/upstream/zod-4.4.3/LICENSE b/dist/legal/upstream/zod-4.4.3/LICENSE new file mode 100644 index 00000000..c0657962 --- /dev/null +++ b/dist/legal/upstream/zod-4.4.3/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Colin McDonnell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dist/manifest.json b/dist/manifest.json new file mode 100644 index 00000000..214fe84b --- /dev/null +++ b/dist/manifest.json @@ -0,0 +1,2174 @@ +{ + "adjacent_map_expectations": [ + { + "expectation": "present", + "input_key": "node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs", + "map": { + "digest": "92212ffee512d7c81f4476a62062dfecb43c59292628ef51d026f4491c2de6a7", + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "dist/auth-CUe6YdwF.mjs.map", + "package_version": "2.0.0" + }, + "recognized_third_party_components": [], + "reviewed_first_party_roots": [ + "../src" + ] + }, + { + "expectation": "present", + "input_key": "node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs", + "map": { + "digest": "2eb52e887d5fda7dad8191f9b1adae36d8b77566cf2c8228eb2844e0358f751e", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + }, + "recognized_third_party_components": [ + "ajv-formats@3.0.1", + "ajv@8.18.0", + "fast-deep-equal@3.1.3", + "fast-uri@3.1.0", + "json-schema-traverse@1.0.0" + ], + "reviewed_first_party_roots": [ + "../../core-internal/src" + ] + }, + { + "expectation": "expected-absent", + "input_key": "node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs", + "rationale": "The reviewed SDK bridge chunk has no published adjacent source map in @modelcontextprotocol/server@2.0.0." + }, + { + "expectation": "present", + "input_key": "node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs", + "map": { + "digest": "196fc76d86a5665c7b12ad8727ac3c68d196001d7e12bea3b6a6347405036499", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/dialects-DoSzNhcb.mjs.map", + "package_version": "2.0.0" + }, + "recognized_third_party_components": [], + "reviewed_first_party_roots": [ + "../../core-internal/src" + ] + }, + { + "expectation": "present", + "input_key": "node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs", + "map": { + "digest": "d7dfb58b7eecce56be099afc8c2551687382e084e6465889c31c933705827915", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/mcp-DXXb3Vv3.mjs.map", + "package_version": "2.0.0" + }, + "recognized_third_party_components": [], + "reviewed_first_party_roots": [ + "../src" + ] + }, + { + "expectation": "present", + "input_key": "node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs", + "map": { + "digest": "c1fdb7f323bc60b04d4a7fd81036694a11ef3057716a971a0502be4812de8102", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/src-CX2iR2pK.mjs.map", + "package_version": "2.0.0" + }, + "recognized_third_party_components": [ + "content-type@1.0.5" + ], + "reviewed_first_party_roots": [ + "../../core-internal/src" + ] + } + ], + "artifacts": [ + { + "digest": "16faf6365bc502ec0c0e00f150b43c300e65dfa9dcace1cce3d98d850b8cbbd0", + "path": "archflow-mcp.mjs", + "role": "executable", + "size": 1316957 + }, + { + "digest": "1fc9bc935d131e66af8510397d05364e32d313a1bbd2e67454f6e848cee1b153", + "path": "legal/THIRD_PARTY_NOTICES.md", + "role": "legal-notice", + "size": 542 + }, + { + "digest": "23185d9f96e4a3bc86199e3d146a7b6cc734c7f6097175007e9d2bf1c79e7e96", + "path": "legal/review.json", + "role": "legal-review", + "size": 19066 + }, + { + "digest": "a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3", + "path": "legal/upstream/ajv-8.18.0/LICENSE", + "role": "upstream-legal", + "size": 1090 + }, + { + "digest": "9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf", + "path": "legal/upstream/ajv-formats-3.0.1/LICENSE", + "role": "upstream-legal", + "size": 1074 + }, + { + "digest": "257aed98914108e91a337912727b6a802eef218248507f74b76faffaff517a38", + "path": "legal/upstream/content-type-1.0.5/LICENSE", + "role": "upstream-legal", + "size": 1089 + }, + { + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "path": "legal/upstream/fast-deep-equal-3.1.3/LICENSE", + "role": "upstream-legal", + "size": 1074 + }, + { + "digest": "185ef4f377743572c2bf0931f741fae52401268cbe70c880b74063799814083e", + "path": "legal/upstream/fast-uri-3.1.0/LICENSE", + "role": "upstream-legal", + "size": 1852 + }, + { + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "path": "legal/upstream/json-schema-traverse-1.0.0/LICENSE", + "role": "upstream-legal", + "size": 1074 + }, + { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "path": "legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE", + "role": "upstream-legal", + "size": 12227 + }, + { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "path": "legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE", + "role": "upstream-legal", + "size": 12227 + }, + { + "digest": "3f1189b28e3866e0d979968d466b78f813f76827cfdca1fbb124cc0a5c8841f8", + "path": "legal/upstream/zod-4.4.3/LICENSE", + "role": "upstream-legal", + "size": 1072 + }, + { + "path": "manifest.json", + "role": "manifest" + }, + { + "digest": "ca871d3d29ba375dcd56b8893fac72508fe165975862c24a55587e4ff03789e9", + "path": "metafile.json", + "role": "metafile", + "size": 71101 + } + ], + "build_entries": [ + { + "entry_point": "src/main.ts", + "handler_authority": "inert-no-handler", + "id": "mcp-stdio", + "output_path": "archflow-mcp.mjs", + "role": "mcp-stdio" + } + ], + "bundle_digest": "16faf6365bc502ec0c0e00f150b43c300e65dfa9dcace1cce3d98d850b8cbbd0", + "bundle_inputs": [ + { + "bytes_in_output": 34870, + "digest": "17df1168d46e8215ad9b204b0ba5061a7ff44a787bf7a8dd8ba5b20ac4499e68", + "key": "node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "dist/auth-CUe6YdwF.mjs", + "package_version": "2.0.0" + }, + "size": 68485 + }, + { + "bytes_in_output": 0, + "digest": "0cc572e7ac91e9f1a36133b83a6207fdea87cb41f9531c7f406d5eca3c355dfb", + "key": "node_modules/@modelcontextprotocol/core/dist/internal.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "dist/internal.mjs", + "package_version": "2.0.0" + }, + "size": 11434 + }, + { + "bytes_in_output": 271819, + "digest": "218157a99879a59cdea0b720a484dfe9989fa768f3d05318c2803b61705373fa", + "key": "node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs", + "package_version": "2.0.0" + }, + "size": 273658 + }, + { + "bytes_in_output": 1382, + "digest": "d4a000980e7c6a8a2ee04c12d80cf538b11e5040e8487dad7661b09d85894e74", + "key": "node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/chunk-Br0eD_fh.mjs", + "package_version": "2.0.0" + }, + "size": 1426 + }, + { + "bytes_in_output": 1284, + "digest": "9340570968ae24904805bbb0ee637f9aa1a17f7d2b87c26ba8290809b4cc7080", + "key": "node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/dialects-DoSzNhcb.mjs", + "package_version": "2.0.0" + }, + "size": 2107 + }, + { + "bytes_in_output": 0, + "digest": "4494af7ea28b45d1655df5a67dcbd6079a50cbe382f811d82441ad2004bf4d60", + "key": "node_modules/@modelcontextprotocol/server/dist/index.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/index.mjs", + "package_version": "2.0.0" + }, + "size": 80210 + }, + { + "bytes_in_output": 40127, + "digest": "b25a912ea68ae396bb3f7367fa9fdd64231899266f1dc6e243dd3d2064c0d5af", + "key": "node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/mcp-DXXb3Vv3.mjs", + "package_version": "2.0.0" + }, + "size": 87288 + }, + { + "bytes_in_output": 0, + "digest": "efa8ef680135a81cd4b3dadaa765ad5cf506523e410c8a9702ab6d9095869d8f", + "key": "node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/shimsNode.mjs", + "package_version": "2.0.0" + }, + "size": 184 + }, + { + "bytes_in_output": 184676, + "digest": "32ecc5f9aaaab5f35499fdfb11e0f1cb3f39a763d762f21e76c5cd55cc11c9c0", + "key": "node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs", + "origin": { + "kind": "dependency", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/src-CX2iR2pK.mjs", + "package_version": "2.0.0" + }, + "size": 331079 + }, + { + "bytes_in_output": 0, + "digest": "c733a1897d6b4b30dad6998597f6896b265b094a65534359ada34b08ecf8932c", + "key": "node_modules/zod/index.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "index.js", + "package_version": "4.4.3" + }, + "size": 121 + }, + { + "bytes_in_output": 858, + "digest": "78a162d29e06001b4d919e1ed08f6e7d0d665bba0ef983201373745410d7b354", + "key": "node_modules/zod/v4/classic/checks.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/checks.js", + "package_version": "4.4.3" + }, + "size": 663 + }, + { + "bytes_in_output": 540, + "digest": "fb2efe3b6eacc475c77cbb571b5fb8650d92a10f316dc869e49b722973d83c3c", + "key": "node_modules/zod/v4/classic/coerce.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/coerce.js", + "package_version": "4.4.3" + }, + "size": 550 + }, + { + "bytes_in_output": 641, + "digest": "0e948b101771cc0e7b753e54b3f5b486929d3db9bd4c09d98fe4ce86271bcf7b", + "key": "node_modules/zod/v4/classic/compat.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/compat.js", + "package_version": "4.4.3" + }, + "size": 1090 + }, + { + "bytes_in_output": 1023, + "digest": "b155316267f79068ddc2dddc7046e13785804b768ca36e6deff1691d154f7c20", + "key": "node_modules/zod/v4/classic/errors.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/errors.js", + "package_version": "4.4.3" + }, + "size": 1609 + }, + { + "bytes_in_output": 6908, + "digest": "179a03ace3d1d77895cc5b3c54a3fcbf2b7f8bad44d6f030092491c10e5d9097", + "key": "node_modules/zod/v4/classic/external.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/external.js", + "package_version": "4.4.3" + }, + "size": 907 + }, + { + "bytes_in_output": 16474, + "digest": "d8866bf5232e55d12cda032bde6a56a05a0a8b276945c2e4eed66432ef5cc9b2", + "key": "node_modules/zod/v4/classic/from-json-schema.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/from-json-schema.js", + "package_version": "4.4.3" + }, + "size": 24161 + }, + { + "bytes_in_output": 0, + "digest": "d49030b9a324bab9bcf9f663a70298391b0f5a25328409174d86617512bf3037", + "key": "node_modules/zod/v4/classic/index.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/index.js", + "package_version": "4.4.3" + }, + "size": 99 + }, + { + "bytes_in_output": 1205, + "digest": "3cc5e6b4da086b8ffc7ee3188c69e4d3c945b368092e78d2299b5321182752c5", + "key": "node_modules/zod/v4/classic/iso.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/iso.js", + "package_version": "4.4.3" + }, + "size": 1151 + }, + { + "bytes_in_output": 736, + "digest": "14cbcc416ab9169abc2cde97af77da54ca769684eac1e03a3753c16ea4a7cd95", + "key": "node_modules/zod/v4/classic/parse.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/parse.js", + "package_version": "4.4.3" + }, + "size": 997 + }, + { + "bytes_in_output": 45669, + "digest": "eb4af7946a092aff8678b9251728ea58dab40154920cd65ec4a2ca1d4df68393", + "key": "node_modules/zod/v4/classic/schemas.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/classic/schemas.js", + "package_version": "4.4.3" + }, + "size": 51378 + }, + { + "bytes_in_output": 22885, + "digest": "00cb5edcfde8098e5a169e66c1dce50c101484d21436e3d78e137e1fa87c4836", + "key": "node_modules/zod/v4/core/api.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/api.js", + "package_version": "4.4.3" + }, + "size": 28054 + }, + { + "bytes_in_output": 16479, + "digest": "5a33a20dcad372b4d18ead8d1e58b1950454f136a2216e62f247e0e5601ac838", + "key": "node_modules/zod/v4/core/checks.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/checks.js", + "package_version": "4.4.3" + }, + "size": 20005 + }, + { + "bytes_in_output": 2090, + "digest": "a5e713beaac4647151e03716a83f51ab714e5337cf66850f3b28eaf072a0bbfe", + "key": "node_modules/zod/v4/core/core.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/core.js", + "package_version": "4.4.3" + }, + "size": 2578 + }, + { + "bytes_in_output": 924, + "digest": "e084bbcc536746a8942fd33b08afe4db345554b3a0383114f1dca95261c958d9", + "key": "node_modules/zod/v4/core/doc.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/doc.js", + "package_version": "4.4.3" + }, + "size": 1088 + }, + { + "bytes_in_output": 4672, + "digest": "bdd0ed8fd4a6e9d04fe6423b0f9df3a0b403939bc7dcedd8930a4b8df1fb118c", + "key": "node_modules/zod/v4/core/errors.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/errors.js", + "package_version": "4.4.3" + }, + "size": 6413 + }, + { + "bytes_in_output": 8865, + "digest": "f9698820ee8371215e8d015cfa060230c62e65428397dce83f78e6538976301c", + "key": "node_modules/zod/v4/core/index.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/index.js", + "package_version": "4.4.3" + }, + "size": 594 + }, + { + "bytes_in_output": 2118, + "digest": "9cc884cdb535a9c87b85b66e61a593ff6b686222f038834f81c5e92552cd6e23", + "key": "node_modules/zod/v4/core/json-schema-generator.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/json-schema-generator.js", + "package_version": "4.4.3" + }, + "size": 3218 + }, + { + "bytes_in_output": 16938, + "digest": "ff15f567c9401dd7d3151ce11736283ff747c9a9e205cc08ee96f90eadc1c0c6", + "key": "node_modules/zod/v4/core/json-schema-processors.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/json-schema-processors.js", + "package_version": "4.4.3" + }, + "size": 20716 + }, + { + "bytes_in_output": 30, + "digest": "8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881", + "key": "node_modules/zod/v4/core/json-schema.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/json-schema.js", + "package_version": "4.4.3" + }, + "size": 11 + }, + { + "bytes_in_output": 3794, + "digest": "2578b8d1341c3882a6c089f9ec57ce1c1a16b8b2b477721d4d89ba3d3ee50c9c", + "key": "node_modules/zod/v4/core/parse.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/parse.js", + "package_version": "4.4.3" + }, + "size": 4444 + }, + { + "bytes_in_output": 7520, + "digest": "3cb122080c1154321331322ebc0cbe04878fe104c8c7b335891d9f85fc4b3f63", + "key": "node_modules/zod/v4/core/regexes.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/regexes.js", + "package_version": "4.4.3" + }, + "size": 9078 + }, + { + "bytes_in_output": 1330, + "digest": "620ea1a715ccc4e6e605a271343bf47942dccae90885dc71f137b1f08a972e50", + "key": "node_modules/zod/v4/core/registries.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/registries.js", + "package_version": "4.4.3" + }, + "size": 1512 + }, + { + "bytes_in_output": 66155, + "digest": "09da9b0cb9b9d2d795c349bc47c7521d5aaffe241885f0c9728f2aa7de3834c9", + "key": "node_modules/zod/v4/core/schemas.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/schemas.js", + "package_version": "4.4.3" + }, + "size": 83322 + }, + { + "bytes_in_output": 11413, + "digest": "fb3c9ab59947582f7671a53c8e20a3ced5eaa92d1c220ce8b27717a59033ad0d", + "key": "node_modules/zod/v4/core/to-json-schema.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/to-json-schema.js", + "package_version": "4.4.3" + }, + "size": 17006 + }, + { + "bytes_in_output": 19852, + "digest": "968e3433e810cf7ba5efb609a1cb6d9a6cfb51215fd1f699938228f7ac25deb3", + "key": "node_modules/zod/v4/core/util.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/util.js", + "package_version": "4.4.3" + }, + "size": 22018 + }, + { + "bytes_in_output": 54, + "digest": "bf082fde98fa7725412d713c7f56da3a5603bdef199d68d5769263f30ce9c756", + "key": "node_modules/zod/v4/core/versions.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/core/versions.js", + "package_version": "4.4.3" + }, + "size": 70 + }, + { + "bytes_in_output": 0, + "digest": "a4b634bb8c97cc700dbf165f3bb0095ec669042da72eaf28a7c5e2ddd98169ce", + "key": "node_modules/zod/v4/index.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/index.js", + "package_version": "4.4.3" + }, + "size": 92 + }, + { + "bytes_in_output": 7121, + "digest": "220ca3ca8cf67e4ccc05d789eeed2692d970269fe0cd82f05db8fd899b661b9e", + "key": "node_modules/zod/v4/locales/ar.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ar.js", + "package_version": "4.4.3" + }, + "size": 5188 + }, + { + "bytes_in_output": 4340, + "digest": "4725ffef0b2f2df947194f9698c792b69f52a8c3a5a1e1bdfabbf62259a1dd46", + "key": "node_modules/zod/v4/locales/az.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/az.js", + "package_version": "4.4.3" + }, + "size": 4511 + }, + { + "bytes_in_output": 8702, + "digest": "da4bda7fbc940dd9f50efdd914caa9397243be779a505b82bd4be5395d3b795e", + "key": "node_modules/zod/v4/locales/be.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/be.js", + "package_version": "4.4.3" + }, + "size": 6619 + }, + { + "bytes_in_output": 7825, + "digest": "48511ad2f86043f0eea6e7673d5e2b848a3295a26c9c4650e96b3884d640196d", + "key": "node_modules/zod/v4/locales/bg.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/bg.js", + "package_version": "4.4.3" + }, + "size": 5785 + }, + { + "bytes_in_output": 4154, + "digest": "796f9ba7dcd53648171aa0132c50271ef358936765cec0a44a642c41d05b3e8c", + "key": "node_modules/zod/v4/locales/ca.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ca.js", + "package_version": "4.4.3" + }, + "size": 4710 + }, + { + "bytes_in_output": 4466, + "digest": "670a75fe1db1104db090c95aabb01e4eb6decd451fe77fd830c2e4dafc79b49a", + "key": "node_modules/zod/v4/locales/cs.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/cs.js", + "package_version": "4.4.3" + }, + "size": 4772 + }, + { + "bytes_in_output": 4171, + "digest": "cdaad7a1fa370abda1943fe9c2caba961e7896b9808d51275daf33f964af49cc", + "key": "node_modules/zod/v4/locales/da.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/da.js", + "package_version": "4.4.3" + }, + "size": 4804 + }, + { + "bytes_in_output": 4003, + "digest": "521a4ed29fcaf3f781163875dc282cfb5262047773aa2b70a852996b1d8a51b9", + "key": "node_modules/zod/v4/locales/de.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/de.js", + "package_version": "4.4.3" + }, + "size": 4588 + }, + { + "bytes_in_output": 7983, + "digest": "9857a9e4909282b2efd86317fc3e67ed86e24287f32329cfa5ab833c05fc0d81", + "key": "node_modules/zod/v4/locales/el.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/el.js", + "package_version": "4.4.3" + }, + "size": 5544 + }, + { + "bytes_in_output": 4077, + "digest": "232a0828d64df8e410b23ac9825a667bd9d485fd70acdc4b4d0870539faef0a4", + "key": "node_modules/zod/v4/locales/en.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/en.js", + "package_version": "4.4.3" + }, + "size": 4805 + }, + { + "bytes_in_output": 4043, + "digest": "ebe08048aa3ee9871ce9fe1271e254cb672b1968ec40ac253066d08d176e8a65", + "key": "node_modules/zod/v4/locales/eo.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/eo.js", + "package_version": "4.4.3" + }, + "size": 4603 + }, + { + "bytes_in_output": 4783, + "digest": "4edd9302e9724c408b024220e99092fbd2f90100ac3c6407a94543b79843610c", + "key": "node_modules/zod/v4/locales/es.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/es.js", + "package_version": "4.4.3" + }, + "size": 5439 + }, + { + "bytes_in_output": 6726, + "digest": "2dc1bee1e984e8a15191fb3c69aaecaa26c922e12a0d4486ac005a0372b78565", + "key": "node_modules/zod/v4/locales/fa.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/fa.js", + "package_version": "4.4.3" + }, + "size": 5131 + }, + { + "bytes_in_output": 4247, + "digest": "3911184979f01d2ae580ce611710ee40597eff97a410d0fa823ab6ea27cee88c", + "key": "node_modules/zod/v4/locales/fi.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/fi.js", + "package_version": "4.4.3" + }, + "size": 4818 + }, + { + "bytes_in_output": 3999, + "digest": "f8716c2baaccdfd1d958743bbc5250c9bdef5152d0801470e9b9a380d618f4ab", + "key": "node_modules/zod/v4/locales/fr-CA.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/fr-CA.js", + "package_version": "4.4.3" + }, + "size": 4554 + }, + { + "bytes_in_output": 4525, + "digest": "3ea466ca5737984bb5acc9008822060272f596317004618cfe1e05109f707577", + "key": "node_modules/zod/v4/locales/fr.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/fr.js", + "package_version": "4.4.3" + }, + "size": 5137 + }, + { + "bytes_in_output": 13032, + "digest": "290512e43d2907700211da09dc3959fd98d120bfb89f8836e6e3f83a472e26fe", + "key": "node_modules/zod/v4/locales/he.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/he.js", + "package_version": "4.4.3" + }, + "size": 12005 + }, + { + "bytes_in_output": 4429, + "digest": "1ea65433c32b89bead43113ac69b3acc520bb73ae231dd2e05fedf8e8c5656d6", + "key": "node_modules/zod/v4/locales/hr.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/hr.js", + "package_version": "4.4.3" + }, + "size": 5052 + }, + { + "bytes_in_output": 4279, + "digest": "913ee94a253db79b31463ae23a337060b6fe28be73dfc7657d8a83a4942bd8a8", + "key": "node_modules/zod/v4/locales/hu.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/hu.js", + "package_version": "4.4.3" + }, + "size": 4696 + }, + { + "bytes_in_output": 8264, + "digest": "0d3bbb96c0f8bc74468a2dfc7d066e838bb56fab64fd5ec03ce9c4d89eccbe99", + "key": "node_modules/zod/v4/locales/hy.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/hy.js", + "package_version": "4.4.3" + }, + "size": 6390 + }, + { + "bytes_in_output": 3964, + "digest": "cd2c19b5c30dade3ed91ffcff3deb0b068713be24f02248e7e46b87b2b9553ee", + "key": "node_modules/zod/v4/locales/id.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/id.js", + "package_version": "4.4.3" + }, + "size": 4577 + }, + { + "bytes_in_output": 1322, + "digest": "d73f41a76614855d43eea493030a1aa05dca30c9a17015a0da5b8b70da61b6b1", + "key": "node_modules/zod/v4/locales/index.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/index.js", + "package_version": "4.4.3" + }, + "size": 2149 + }, + { + "bytes_in_output": 4144, + "digest": "ead5b14eac892229f915fe38ec94ab3b1e676f8aa2df2a8450848ba9ca9a1612", + "key": "node_modules/zod/v4/locales/is.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/is.js", + "package_version": "4.4.3" + }, + "size": 4635 + }, + { + "bytes_in_output": 3962, + "digest": "439969d199427d77ebf1e477bf2295b226712804b25437d442f9dfc78aca95e0", + "key": "node_modules/zod/v4/locales/it.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/it.js", + "package_version": "4.4.3" + }, + "size": 4582 + }, + { + "bytes_in_output": 5348, + "digest": "43ee10378cac22b0b8aee912a66c3f36a834d5b4c76e9748f88a784044f248fd", + "key": "node_modules/zod/v4/locales/ja.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ja.js", + "package_version": "4.4.3" + }, + "size": 4851 + }, + { + "bytes_in_output": 7817, + "digest": "0ab5322368f9ac6e6b58f93dac484a4f4f06cdf4c0677f4df88164e9d8b4bf81", + "key": "node_modules/zod/v4/locales/ka.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ka.js", + "package_version": "4.4.3" + }, + "size": 6202 + }, + { + "bytes_in_output": 49, + "digest": "78c3d1991041bb8c8fc0f7c5d745aae422d4c2e4e8f30bae44f3fef4765900a8", + "key": "node_modules/zod/v4/locales/kh.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/kh.js", + "package_version": "4.4.3" + }, + "size": 111 + }, + { + "bytes_in_output": 8032, + "digest": "dbdabda94dd93d4a1827e6c809505c79fa6aa7abefec91dc50fa0871382c99cc", + "key": "node_modules/zod/v4/locales/km.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/km.js", + "package_version": "4.4.3" + }, + "size": 6242 + }, + { + "bytes_in_output": 5145, + "digest": "d2efe22ac069d9b32b0109fa07713ac0695ac1c1357afc4e4277056466f2e196", + "key": "node_modules/zod/v4/locales/ko.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ko.js", + "package_version": "4.4.3" + }, + "size": 4929 + }, + { + "bytes_in_output": 7201, + "digest": "dad886e52c56a1329d22e072f8b08dc8730f69c3dc5e5acf8267cac18df1ab28", + "key": "node_modules/zod/v4/locales/lt.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/lt.js", + "package_version": "4.4.3" + }, + "size": 8082 + }, + { + "bytes_in_output": 7000, + "digest": "9eb4af0392fc5b9c438cdc6ceea446acc541b59e221dba918f7b80800d9da3d1", + "key": "node_modules/zod/v4/locales/mk.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/mk.js", + "package_version": "4.4.3" + }, + "size": 5157 + }, + { + "bytes_in_output": 3873, + "digest": "c550a9185d997e8fcd17311951aa1e29793a50b8e825e18310efd5a46c641795", + "key": "node_modules/zod/v4/locales/ms.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ms.js", + "package_version": "4.4.3" + }, + "size": 4491 + }, + { + "bytes_in_output": 4129, + "digest": "acba414579c5bbd7f83dc6661fa1a12d65f1822f9b0f5035549ac60f46d93763", + "key": "node_modules/zod/v4/locales/nl.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/nl.js", + "package_version": "4.4.3" + }, + "size": 4762 + }, + { + "bytes_in_output": 3925, + "digest": "1854483c7cf158b8f97f0faf6fd799eb1f762009018b5fde893ca33f2fb0b313", + "key": "node_modules/zod/v4/locales/no.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/no.js", + "package_version": "4.4.3" + }, + "size": 4506 + }, + { + "bytes_in_output": 4143, + "digest": "34ae496104bc17fea7d30c3d45c94cfe3d1d569b5d39a6ca51de6c177690c556", + "key": "node_modules/zod/v4/locales/ota.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ota.js", + "package_version": "4.4.3" + }, + "size": 4525 + }, + { + "bytes_in_output": 4655, + "digest": "18eab58f395e30b906e8e3fddc5f212eb19f2c4362410889a5c5e0141ebe2144", + "key": "node_modules/zod/v4/locales/pl.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/pl.js", + "package_version": "4.4.3" + }, + "size": 4966 + }, + { + "bytes_in_output": 6076, + "digest": "f977b5141fa8fb6a8459372e0b2895d74b381c9f2ff4899141f7ee3e639a4513", + "key": "node_modules/zod/v4/locales/ps.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ps.js", + "package_version": "4.4.3" + }, + "size": 4909 + }, + { + "bytes_in_output": 4004, + "digest": "df172afc585544dee7c063c484f5a07b5ed103e2c1072a782c763ad8ceb08e17", + "key": "node_modules/zod/v4/locales/pt.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/pt.js", + "package_version": "4.4.3" + }, + "size": 4568 + }, + { + "bytes_in_output": 4366, + "digest": "ecae409f4299ab91e2aff1095db14e23f3cf2c05b3654e242047655352c7f46b", + "key": "node_modules/zod/v4/locales/ro.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ro.js", + "package_version": "4.4.3" + }, + "size": 4774 + }, + { + "bytes_in_output": 8988, + "digest": "c397a473e94d7d189a9c09c7890fe379c4f6f46d9556d52a040a90ffa56f7b93", + "key": "node_modules/zod/v4/locales/ru.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ru.js", + "package_version": "4.4.3" + }, + "size": 6714 + }, + { + "bytes_in_output": 4022, + "digest": "ee2ff3a19b62cd2f89b54b165088773b937de15df7253df220bef07d9adf2d80", + "key": "node_modules/zod/v4/locales/sl.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/sl.js", + "package_version": "4.4.3" + }, + "size": 4567 + }, + { + "bytes_in_output": 4120, + "digest": "97d6718fb643e05d6fe30fa4f9f09b8d9a3eda4a3a350b57dfb2944943d19502", + "key": "node_modules/zod/v4/locales/sv.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/sv.js", + "package_version": "4.4.3" + }, + "size": 4663 + }, + { + "bytes_in_output": 8172, + "digest": "04bbde9766251f9047e786fdd77632f2ecd53aec2eb060eb2fc85bf576ad729d", + "key": "node_modules/zod/v4/locales/ta.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ta.js", + "package_version": "4.4.3" + }, + "size": 6369 + }, + { + "bytes_in_output": 8107, + "digest": "aea70c9ac2b399fe4749e19ba3aa99c3efb4dfb50eadfb62b0b2a6e005748f3d", + "key": "node_modules/zod/v4/locales/th.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/th.js", + "package_version": "4.4.3" + }, + "size": 6290 + }, + { + "bytes_in_output": 4081, + "digest": "4449f41d22c6f15ede5066f79d840a52ec45a6b694c859e16f9121062b6fad2f", + "key": "node_modules/zod/v4/locales/tr.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/tr.js", + "package_version": "4.4.3" + }, + "size": 4454 + }, + { + "bytes_in_output": 49, + "digest": "9391169ffbc72f777a83230b6ffcc3f4cf46ab5945ec540de9ef4609dca1f4cc", + "key": "node_modules/zod/v4/locales/ua.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ua.js", + "package_version": "4.4.3" + }, + "size": 111 + }, + { + "bytes_in_output": 7877, + "digest": "77136a2a60eef62f7cc803a0f9971aebbc641403af77c1b41fd5ce59abfa5de3", + "key": "node_modules/zod/v4/locales/uk.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/uk.js", + "package_version": "4.4.3" + }, + "size": 5430 + }, + { + "bytes_in_output": 7394, + "digest": "858f4f38d651073e7a3fbec7ed356692578b3ad1fae1b453cb3d85312a4f39d2", + "key": "node_modules/zod/v4/locales/ur.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/ur.js", + "package_version": "4.4.3" + }, + "size": 5271 + }, + { + "bytes_in_output": 4218, + "digest": "d540bed482d15c47cb45439cff34e053379c53019c7c7c5fbe43f222d0c81f04", + "key": "node_modules/zod/v4/locales/uz.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/uz.js", + "package_version": "4.4.3" + }, + "size": 4739 + }, + { + "bytes_in_output": 4665, + "digest": "2c61bd3f4a733f3cbb1ad85e75a053cb15a8ebeb83ab56dc21f2948b1138e12f", + "key": "node_modules/zod/v4/locales/vi.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/vi.js", + "package_version": "4.4.3" + }, + "size": 4772 + }, + { + "bytes_in_output": 4784, + "digest": "98b9cbf31bf00c8b2c00de62725a9dd7cb718ac72d6e8fd4e0a1a7c49723e0f4", + "key": "node_modules/zod/v4/locales/yo.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/yo.js", + "package_version": "4.4.3" + }, + "size": 4665 + }, + { + "bytes_in_output": 4504, + "digest": "99a4b16af598834a0b11607fcdebd1c6de026386ff1d6a5a306b364c154c5899", + "key": "node_modules/zod/v4/locales/zh-CN.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/zh-CN.js", + "package_version": "4.4.3" + }, + "size": 4452 + }, + { + "bytes_in_output": 4609, + "digest": "37dcae620e1553e9174a4b9434bbcc4e465150a627e80c9c17fd01de8baaf59a", + "key": "node_modules/zod/v4/locales/zh-TW.js", + "origin": { + "kind": "dependency", + "package_name": "zod", + "package_relative_path": "v4/locales/zh-TW.js", + "package_version": "4.4.3" + }, + "size": 4498 + }, + { + "bytes_in_output": 7747, + "digest": "d27c062a547ad878f65c6e5ac11f560c3facce05bfa2cf02e2fd883ba45e8595", + "key": "src/contracts/adjudication.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/adjudication.ts" + }, + "size": 11437 + }, + { + "bytes_in_output": 3278, + "digest": "9a9f33dc04b04c7ba3d146c524b5dd20e04df945c07ea82b0e02da67670235ff", + "key": "src/contracts/contexts.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/contexts.ts" + }, + "size": 4800 + }, + { + "bytes_in_output": 14954, + "digest": "84382e5717529315802a8ba698eb57a16202214e3170b17ed9f86a3ac2ce3b64", + "key": "src/contracts/errors.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/errors.ts" + }, + "size": 20041 + }, + { + "bytes_in_output": 566, + "digest": "1daff619c757dd0839f10ee089b15c5577aa9f16d7766402f2bb40df3560646a", + "key": "src/contracts/evidence.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/evidence.ts" + }, + "size": 1993 + }, + { + "bytes_in_output": 14100, + "digest": "211d726a22a47c06b3fe8e8afee8329dfc2d44e1030760523a4d8d9c4f20b0b6", + "key": "src/contracts/gates.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/gates.ts" + }, + "size": 20832 + }, + { + "bytes_in_output": 1368, + "digest": "964768a530102d72d6c1b861536d17e46689e9a777711526702939541df54bfc", + "key": "src/contracts/internal/trust-brands.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/internal/trust-brands.ts" + }, + "size": 3476 + }, + { + "bytes_in_output": 9327, + "digest": "149c55d5ad27a1fa2db03cb4470757a18b85c953c2b1ac799d673eba90c0fb67", + "key": "src/contracts/mcp-tools.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/mcp-tools.ts" + }, + "size": 18076 + }, + { + "bytes_in_output": 975, + "digest": "6d6c79b379f74d9455007586fccedfd7c03703a029516b55ba97dc0f04393272", + "key": "src/contracts/path-claims.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/path-claims.ts" + }, + "size": 1595 + }, + { + "bytes_in_output": 1112, + "digest": "020be1a5950242fa49dd67340f3078a49a04fffdad776f28722a1998fc93c879", + "key": "src/contracts/phase-instance.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/phase-instance.ts" + }, + "size": 1801 + }, + { + "bytes_in_output": 3767, + "digest": "6d3c496cc1c3240971944f8401987c47890043c70f4aa9526fbf51865910c393", + "key": "src/contracts/plain-json.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/plain-json.ts" + }, + "size": 4540 + }, + { + "bytes_in_output": 5775, + "digest": "9dc87ff04be02a829479ad201dec6d806f04af72f2e0bd0c721335ffbcc55240", + "key": "src/contracts/review.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/review.ts" + }, + "size": 8734 + }, + { + "bytes_in_output": 913, + "digest": "275ec6607262098fd7c7ef9184fbc3fb0ac88c06a2b66b97556615f22e9fe771", + "key": "src/contracts/rubric.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/rubric.ts" + }, + "size": 1322 + }, + { + "bytes_in_output": 2613, + "digest": "23863a2cdc37b22409125077c2c9090dd92f8305f5e1b008a6118c392d1fb21b", + "key": "src/contracts/schemas/v1/evidence-slots.schema.json", + "origin": { + "kind": "repository", + "path": "src/contracts/schemas/v1/evidence-slots.schema.json" + }, + "size": 2790 + }, + { + "bytes_in_output": 15993, + "digest": "ff9fe5fdb4cc57c678eebeb358f4a238fdb04dea902ea2e7ffde8c855f9f0b38", + "key": "src/contracts/schemas/v1/gate-contract.schema.json", + "origin": { + "kind": "repository", + "path": "src/contracts/schemas/v1/gate-contract.schema.json" + }, + "size": 16873 + }, + { + "bytes_in_output": 9098, + "digest": "fbebec077ce0d1250081ac623dcff5c02ef892f8ba05397f3f6a51807e7f8295", + "key": "src/contracts/schemas/v1/gate-decision.schema.json", + "origin": { + "kind": "repository", + "path": "src/contracts/schemas/v1/gate-decision.schema.json" + }, + "size": 9402 + }, + { + "bytes_in_output": 15803, + "digest": "fd22fb332a9d6524976f456dea60822dc193eab163da5b9f302c9ed1d5967515", + "key": "src/contracts/schemas/v1/mcp-tools.schema.json", + "origin": { + "kind": "repository", + "path": "src/contracts/schemas/v1/mcp-tools.schema.json" + }, + "size": 16657 + }, + { + "bytes_in_output": 350, + "digest": "2603575ffd5a9799e23e73a31cb7f0671ba49a0cccb03869f94de9f9d6ca8d30", + "key": "src/contracts/schemas/v1/path-claim.schema.json", + "origin": { + "kind": "repository", + "path": "src/contracts/schemas/v1/path-claim.schema.json" + }, + "size": 327 + }, + { + "bytes_in_output": 717, + "digest": "7f8875d0c91f484e70181b704d83059fc93251a0fddf4a6c762d55cee333b59a", + "key": "src/contracts/schemas/v1/primitives.schema.json", + "origin": { + "kind": "repository", + "path": "src/contracts/schemas/v1/primitives.schema.json" + }, + "size": 730 + }, + { + "bytes_in_output": 62400, + "digest": "99273bf880aaa1b7f25ca1ff77d53dee4eeca6a9f25d0661a9f599257d616def", + "key": "src/contracts/schemas/v1/project-error.schema.json", + "origin": { + "kind": "repository", + "path": "src/contracts/schemas/v1/project-error.schema.json" + }, + "size": 65252 + }, + { + "bytes_in_output": 760, + "digest": "daa63bd9ca84173bb8ad97c6c34c5e8b4411a80992d756b4bac1ae1cd15926da", + "key": "src/contracts/schemas/v1/rubric.schema.json", + "origin": { + "kind": "repository", + "path": "src/contracts/schemas/v1/rubric.schema.json" + }, + "size": 781 + }, + { + "bytes_in_output": 247, + "digest": "94bea791365f8046caf32de54f670be5ca99415419f27284b297a0acf6f45c73", + "key": "src/contracts/tool-names.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/tool-names.ts" + }, + "size": 377 + }, + { + "bytes_in_output": 14468, + "digest": "3dc2237b5a6fe40c200be9904d9e77e02c8026c15dc6c3e377e6e94e4c9836b3", + "key": "src/contracts/trust.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/trust.ts" + }, + "size": 25661 + }, + { + "bytes_in_output": 91, + "digest": "baab340034b7a26daeb2348a20fae49a7123bfda0a56b40f6bf1eb7fe85ec403", + "key": "src/contracts/vocabulary.ts", + "origin": { + "kind": "repository", + "path": "src/contracts/vocabulary.ts" + }, + "size": 569 + }, + { + "bytes_in_output": 304, + "digest": "706331c01fc14057d786a57ff581c58d5edf608e768987a527e0c15483ba98ba", + "key": "src/main.ts", + "origin": { + "kind": "repository", + "path": "src/main.ts" + }, + "size": 414 + }, + { + "bytes_in_output": 2632, + "digest": "be8099df7ace5dc3e4e657ba108145949163aec1fe79f5729a2cc471733c8bdd", + "key": "src/mcp/framing.ts", + "origin": { + "kind": "repository", + "path": "src/mcp/framing.ts" + }, + "size": 3378 + }, + { + "bytes_in_output": 3855, + "digest": "daa9009e3c27f45dd5167b29f1da5e4dabdec808a96527fece835adfd870a74b", + "key": "src/mcp/process-runner.ts", + "origin": { + "kind": "repository", + "path": "src/mcp/process-runner.ts" + }, + "size": 5511 + }, + { + "bytes_in_output": 15075, + "digest": "1e76e7a84e3997fa4091c2d31cbeec4842c98def3de4906952da3272d29eed0f", + "key": "src/mcp/sdk-adapter.ts", + "origin": { + "kind": "repository", + "path": "src/mcp/sdk-adapter.ts" + }, + "size": 18189 + }, + { + "bytes_in_output": 4962, + "digest": "51f16df62171c611425003c1cf0722793c0698c6abdc9829f58494e397946fa5", + "key": "src/mcp/send-queue.ts", + "origin": { + "kind": "repository", + "path": "src/mcp/send-queue.ts" + }, + "size": 6425 + }, + { + "bytes_in_output": 6292, + "digest": "84d5ee328076901f749755749069a4629aa3d0d05a29ad6baa94396d72e69625", + "key": "src/mcp/server.ts", + "origin": { + "kind": "repository", + "path": "src/mcp/server.ts" + }, + "size": 9506 + }, + { + "bytes_in_output": 15513, + "digest": "307167530a39cf35597f609b7cc1f19bf0156ed9342b5f3e8649f8e23c34df7c", + "key": "src/mcp/session.ts", + "origin": { + "kind": "repository", + "path": "src/mcp/session.ts" + }, + "size": 21494 + }, + { + "bytes_in_output": 3555, + "digest": "0478ce7030935539241d491291fd4fc1c7ca6896a2d1dae360e85eb14c9d19c4", + "key": "src/mcp/tools.ts", + "origin": { + "kind": "repository", + "path": "src/mcp/tools.ts" + }, + "size": 4924 + } + ], + "contributing_inputs": [ + "node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs", + "node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs", + "node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs", + "node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs", + "node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs", + "node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs", + "node_modules/zod/v4/classic/checks.js", + "node_modules/zod/v4/classic/coerce.js", + "node_modules/zod/v4/classic/compat.js", + "node_modules/zod/v4/classic/errors.js", + "node_modules/zod/v4/classic/external.js", + "node_modules/zod/v4/classic/from-json-schema.js", + "node_modules/zod/v4/classic/iso.js", + "node_modules/zod/v4/classic/parse.js", + "node_modules/zod/v4/classic/schemas.js", + "node_modules/zod/v4/core/api.js", + "node_modules/zod/v4/core/checks.js", + "node_modules/zod/v4/core/core.js", + "node_modules/zod/v4/core/doc.js", + "node_modules/zod/v4/core/errors.js", + "node_modules/zod/v4/core/index.js", + "node_modules/zod/v4/core/json-schema-generator.js", + "node_modules/zod/v4/core/json-schema-processors.js", + "node_modules/zod/v4/core/json-schema.js", + "node_modules/zod/v4/core/parse.js", + "node_modules/zod/v4/core/regexes.js", + "node_modules/zod/v4/core/registries.js", + "node_modules/zod/v4/core/schemas.js", + "node_modules/zod/v4/core/to-json-schema.js", + "node_modules/zod/v4/core/util.js", + "node_modules/zod/v4/core/versions.js", + "node_modules/zod/v4/locales/ar.js", + "node_modules/zod/v4/locales/az.js", + "node_modules/zod/v4/locales/be.js", + "node_modules/zod/v4/locales/bg.js", + "node_modules/zod/v4/locales/ca.js", + "node_modules/zod/v4/locales/cs.js", + "node_modules/zod/v4/locales/da.js", + "node_modules/zod/v4/locales/de.js", + "node_modules/zod/v4/locales/el.js", + "node_modules/zod/v4/locales/en.js", + "node_modules/zod/v4/locales/eo.js", + "node_modules/zod/v4/locales/es.js", + "node_modules/zod/v4/locales/fa.js", + "node_modules/zod/v4/locales/fi.js", + "node_modules/zod/v4/locales/fr-CA.js", + "node_modules/zod/v4/locales/fr.js", + "node_modules/zod/v4/locales/he.js", + "node_modules/zod/v4/locales/hr.js", + "node_modules/zod/v4/locales/hu.js", + "node_modules/zod/v4/locales/hy.js", + "node_modules/zod/v4/locales/id.js", + "node_modules/zod/v4/locales/index.js", + "node_modules/zod/v4/locales/is.js", + "node_modules/zod/v4/locales/it.js", + "node_modules/zod/v4/locales/ja.js", + "node_modules/zod/v4/locales/ka.js", + "node_modules/zod/v4/locales/kh.js", + "node_modules/zod/v4/locales/km.js", + "node_modules/zod/v4/locales/ko.js", + "node_modules/zod/v4/locales/lt.js", + "node_modules/zod/v4/locales/mk.js", + "node_modules/zod/v4/locales/ms.js", + "node_modules/zod/v4/locales/nl.js", + "node_modules/zod/v4/locales/no.js", + "node_modules/zod/v4/locales/ota.js", + "node_modules/zod/v4/locales/pl.js", + "node_modules/zod/v4/locales/ps.js", + "node_modules/zod/v4/locales/pt.js", + "node_modules/zod/v4/locales/ro.js", + "node_modules/zod/v4/locales/ru.js", + "node_modules/zod/v4/locales/sl.js", + "node_modules/zod/v4/locales/sv.js", + "node_modules/zod/v4/locales/ta.js", + "node_modules/zod/v4/locales/th.js", + "node_modules/zod/v4/locales/tr.js", + "node_modules/zod/v4/locales/ua.js", + "node_modules/zod/v4/locales/uk.js", + "node_modules/zod/v4/locales/ur.js", + "node_modules/zod/v4/locales/uz.js", + "node_modules/zod/v4/locales/vi.js", + "node_modules/zod/v4/locales/yo.js", + "node_modules/zod/v4/locales/zh-CN.js", + "node_modules/zod/v4/locales/zh-TW.js", + "src/contracts/adjudication.ts", + "src/contracts/contexts.ts", + "src/contracts/errors.ts", + "src/contracts/evidence.ts", + "src/contracts/gates.ts", + "src/contracts/internal/trust-brands.ts", + "src/contracts/mcp-tools.ts", + "src/contracts/path-claims.ts", + "src/contracts/phase-instance.ts", + "src/contracts/plain-json.ts", + "src/contracts/review.ts", + "src/contracts/rubric.ts", + "src/contracts/schemas/v1/evidence-slots.schema.json", + "src/contracts/schemas/v1/gate-contract.schema.json", + "src/contracts/schemas/v1/gate-decision.schema.json", + "src/contracts/schemas/v1/mcp-tools.schema.json", + "src/contracts/schemas/v1/path-claim.schema.json", + "src/contracts/schemas/v1/primitives.schema.json", + "src/contracts/schemas/v1/project-error.schema.json", + "src/contracts/schemas/v1/rubric.schema.json", + "src/contracts/tool-names.ts", + "src/contracts/trust.ts", + "src/contracts/vocabulary.ts", + "src/main.ts", + "src/mcp/framing.ts", + "src/mcp/process-runner.ts", + "src/mcp/sdk-adapter.ts", + "src/mcp/send-queue.ts", + "src/mcp/server.ts", + "src/mcp/session.ts", + "src/mcp/tools.ts" + ], + "declared_content": { + "constitution": [ + "assets/constitution/00-process.md", + "assets/constitution/10-architecture.md", + "assets/constitution/20-data.md", + "assets/constitution/30-product.md", + "assets/constitution/README.md" + ], + "schemas": [ + "src/contracts/schemas/v1/adjudication-evidence.schema.json", + "src/contracts/schemas/v1/adjudication.schema.json", + "src/contracts/schemas/v1/authority-link.schema.json", + "src/contracts/schemas/v1/config.schema.json", + "src/contracts/schemas/v1/constitution-rule.schema.json", + "src/contracts/schemas/v1/evidence-reference.schema.json", + "src/contracts/schemas/v1/evidence-slots.schema.json", + "src/contracts/schemas/v1/gate-contract.schema.json", + "src/contracts/schemas/v1/gate-decision.schema.json", + "src/contracts/schemas/v1/mcp-tools.schema.json", + "src/contracts/schemas/v1/path-claim.schema.json", + "src/contracts/schemas/v1/phase-instance.schema.json", + "src/contracts/schemas/v1/primitives.schema.json", + "src/contracts/schemas/v1/project-error.schema.json", + "src/contracts/schemas/v1/protocol-error.schema.json", + "src/contracts/schemas/v1/release-legal-review.schema.json", + "src/contracts/schemas/v1/release-manifest.schema.json", + "src/contracts/schemas/v1/result-expectation.schema.json", + "src/contracts/schemas/v1/review-evidence.schema.json", + "src/contracts/schemas/v1/review.schema.json", + "src/contracts/schemas/v1/rubric.schema.json", + "src/contracts/schemas/v1/supplemental-review.schema.json", + "src/contracts/schemas/v1/triage.schema.json", + "src/contracts/schemas/v1/workflow.schema.json" + ], + "workflow": "assets/workflow.yaml" + }, + "dependency_inventory_digest": "1f93c687b91691f3afb99d657246504a9b369311333ecd4e8c77abab1a23c046", + "dependency_provenance_inputs": [ + { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "LICENSE", + "package_version": "2.0.0", + "purpose": "license", + "size": 12227 + }, + { + "digest": "92212ffee512d7c81f4476a62062dfecb43c59292628ef51d026f4491c2de6a7", + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "dist/auth-CUe6YdwF.mjs.map", + "package_version": "2.0.0", + "purpose": "source-map", + "size": 131225 + }, + { + "digest": "dc2e8e1fc31878b0b537b0ea034d4a11284cce20fe81f4c6ea823dd6db7e7ad5", + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "package.json", + "package_version": "2.0.0", + "purpose": "package-manifest", + "size": 2282 + }, + { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "LICENSE", + "package_version": "2.0.0", + "purpose": "license", + "size": 12227 + }, + { + "digest": "2eb52e887d5fda7dad8191f9b1adae36d8b77566cf2c8228eb2844e0358f751e", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0", + "purpose": "source-map", + "size": 448931 + }, + { + "digest": "196fc76d86a5665c7b12ad8727ac3c68d196001d7e12bea3b6a6347405036499", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/dialects-DoSzNhcb.mjs.map", + "package_version": "2.0.0", + "purpose": "source-map", + "size": 3672 + }, + { + "digest": "d7dfb58b7eecce56be099afc8c2551687382e084e6465889c31c933705827915", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/mcp-DXXb3Vv3.mjs.map", + "package_version": "2.0.0", + "purpose": "source-map", + "size": 210668 + }, + { + "digest": "c1fdb7f323bc60b04d4a7fd81036694a11ef3057716a971a0502be4812de8102", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/src-CX2iR2pK.mjs.map", + "package_version": "2.0.0", + "purpose": "source-map", + "size": 713015 + }, + { + "digest": "ff7f23c4a4a3162a34a2cb21087e1844bb8631724d8e43aa14aaa86d3f7e07c2", + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "package.json", + "package_version": "2.0.0", + "purpose": "package-manifest", + "size": 4390 + }, + { + "digest": "3f1189b28e3866e0d979968d466b78f813f76827cfdca1fbb124cc0a5c8841f8", + "package_name": "zod", + "package_relative_path": "LICENSE", + "package_version": "4.4.3", + "purpose": "license", + "size": 1072 + }, + { + "digest": "c630bd10b52dcf71c112a2bf78dbf2734b9db58d62de663b8d86c2ec2c8cda2e", + "package_name": "zod", + "package_relative_path": "package.json", + "package_version": "4.4.3", + "purpose": "package-manifest", + "size": 3796 + } + ], + "launch_profile": { + "allowed_imports": [ + "node:buffer", + "node:crypto", + "node:module", + "node:process", + "node:util" + ], + "argv": [ + "--require", + "hostile-runtime-guard.cjs", + "archflow-mcp.mjs" + ], + "canary_paths": [ + "ambient/node_modules/archflow-release-canary/index.js", + "repository-canary/SECRET" + ], + "cwd_class": "copied-payload", + "environment_keys": [ + "HOME", + "LANG", + "LC_ALL", + "NPM_CONFIG_CACHE", + "PATH", + "TMPDIR", + "XDG_CACHE_HOME", + "XDG_CONFIG_HOME", + "XDG_DATA_HOME" + ], + "executable": "process.execPath", + "fixture_digests": [ + { + "digest": "33401af67624bd2bd7bf8073e50d33a3f20e2ade0bee33fadee00fc1aa3ad53e", + "path": "test/fixtures/mcp/runtime/adversarial-bytes.json" + }, + { + "digest": "39d0dc0461a2b64e0844ff119a0647cd89388191e03f5a55baccd01149f3c9ba", + "path": "test/fixtures/mcp/runtime/calls.json" + }, + { + "digest": "5547b92a1f0667ef70c712cd99800fa38074278e4470a20231893e023c1504dc", + "path": "test/fixtures/mcp/runtime/initialize.json" + } + ], + "guard_path": "test/fixtures/release/hostile-runtime-guard.cjs", + "node_major": 24, + "removed_environment_keys": [ + "NODE_OPTIONS", + "NODE_PATH" + ], + "stdio": { + "guard_fd": 3, + "stderr": "pipe", + "stdin": "pipe", + "stdout": "pipe" + } + }, + "legal_review": { + "digest": "23185d9f96e4a3bc86199e3d146a7b6cc734c7f6097175007e9d2bf1c79e7e96", + "payload_path": "legal/review.json", + "source_path": "release/legal-review.json" + }, + "proof_inputs": [ + ".github/workflows/ci.yml", + "package.json", + "scripts/smoke-release-bundle.mjs", + "scripts/test-release-integrity.mjs", + "test/fixtures/mcp/runtime/adversarial-bytes.json", + "test/fixtures/mcp/runtime/calls.json", + "test/fixtures/mcp/runtime/initialize.json", + "test/fixtures/release/hostile-runtime-guard.cjs", + "test/integration/mcp-stdio.test.ts", + "test/integration/release-offline.test.ts" + ], + "release_control_inputs": [ + { + "digest": "e07e170132a9cd967123322237aebf6ade34b912bfca125ce87eae309383f5fb", + "path": ".gitattributes", + "size": 492 + }, + { + "digest": "01d12ca38a1035b6439066ed3646ec7df46d2b82666d9a6f47531d045aaf7736", + "path": ".github/workflows/ci.yml", + "size": 1340 + }, + { + "digest": "a18054ccff3d98f0dd686f5e90a426510652d336b369e876545de8e0e9e55a01", + "path": "assets/constitution/00-process.md", + "size": 463 + }, + { + "digest": "fee43cdf00279e3b6a36ee2f13146c51961c428294f78687a81ef82ae9b32e61", + "path": "assets/constitution/10-architecture.md", + "size": 529 + }, + { + "digest": "1f835c3ec9a4125eeaf2936727ea6e79daf6a32d8132cf538ca0e94926e2b705", + "path": "assets/constitution/20-data.md", + "size": 530 + }, + { + "digest": "1a1b4411022791aba686b88ed5935f5be2440881a69554eca146f55b57156dc1", + "path": "assets/constitution/30-product.md", + "size": 499 + }, + { + "digest": "37ba4931fc7b16e093aab9228594d6194f79be1f42ce6d1de53b261196fb39e2", + "path": "assets/constitution/README.md", + "size": 509 + }, + { + "digest": "f05eaac7b1b81f736977b03284848c42743cf033e562de8d2384d7ff70f30409", + "path": "assets/workflow.yaml", + "size": 781 + }, + { + "digest": "efdad7f57217e4afbc44ccfff701237db8d3f8a43379a09e14d7bf2149ac5812", + "path": "package-lock.json", + "size": 65981 + }, + { + "digest": "0d26854c81e22b70f514f48b7b311e2c1cec877d6efed15f9a41155fb1bd2667", + "path": "package.json", + "size": 2110 + }, + { + "digest": "6282adc7c1d1304f245ff5877a2824b05b53f9842dc658282610c981505f0caf", + "path": "release/evidence/advisory-snapshot.json", + "size": 1060 + }, + { + "digest": "cac675f0183bfaa2e44707c4be9e93d156c9a695bef61177f305145995165007", + "path": "release/evidence/focused-inert-reachability.json", + "size": 835 + }, + { + "digest": "deb867f4b505da598ea0bf483ae6ecdb116460ebac573489d7763c720ad55ee1", + "path": "release/evidence/patched-artifact-availability.json", + "size": 424 + }, + { + "digest": "d625ac9d722a8710bb8b0f18f69207df9434953584393a80e5f66d9e2fa0122f", + "path": "release/evidence/user-risk-acceptance.json", + "size": 705 + }, + { + "digest": "23185d9f96e4a3bc86199e3d146a7b6cc734c7f6097175007e9d2bf1c79e7e96", + "path": "release/legal-review.json", + "size": 19066 + }, + { + "digest": "a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3", + "path": "release/legal/upstream/ajv-8.18.0/LICENSE", + "size": 1090 + }, + { + "digest": "9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf", + "path": "release/legal/upstream/ajv-formats-3.0.1/LICENSE", + "size": 1074 + }, + { + "digest": "257aed98914108e91a337912727b6a802eef218248507f74b76faffaff517a38", + "path": "release/legal/upstream/content-type-1.0.5/LICENSE", + "size": 1089 + }, + { + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "path": "release/legal/upstream/fast-deep-equal-3.1.3/LICENSE", + "size": 1074 + }, + { + "digest": "185ef4f377743572c2bf0931f741fae52401268cbe70c880b74063799814083e", + "path": "release/legal/upstream/fast-uri-3.1.0/LICENSE", + "size": 1852 + }, + { + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "path": "release/legal/upstream/json-schema-traverse-1.0.0/LICENSE", + "size": 1074 + }, + { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "path": "release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE", + "size": 12227 + }, + { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "path": "release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE", + "size": 12227 + }, + { + "digest": "3f1189b28e3866e0d979968d466b78f813f76827cfdca1fbb124cc0a5c8841f8", + "path": "release/legal/upstream/zod-4.4.3/LICENSE", + "size": 1072 + }, + { + "digest": "5d2e8237f5b41cd99e599c1d98ada3033a4845549458cfdd659af242b8272311", + "path": "scripts/build-release.mjs", + "size": 562 + }, + { + "digest": "a7a4b6db0cffdc6ab714a8dedb53aca3d257443ced3e94ed92e9996956024856", + "path": "scripts/check-release.mjs", + "size": 610 + }, + { + "digest": "8b66f2fa6716a22036a29fdd648076fc289f4fe78a9f89ad5da2926f17c6ce05", + "path": "scripts/release-support.mjs", + "size": 79892 + }, + { + "digest": "ccfbcc8df639e93b98bf292de22364e20c3f45b6e8993d2db8606160d0aa7a8e", + "path": "scripts/reproduce-release.mjs", + "size": 510 + }, + { + "digest": "b6fd01099a143412ec22b7662872c1f971fa7bc8712ed69a860a6872573670bd", + "path": "scripts/smoke-release-bundle.mjs", + "size": 13956 + }, + { + "digest": "b36e42dd28f88d8230cc6d2a5dac5ce22eedc7575ccbe63c0d84f4adfce72cf6", + "path": "scripts/test-release-integrity.mjs", + "size": 13103 + }, + { + "digest": "594a118045a89acf3b33bcca4c8bfd3d0022beed13aeef897174ce4b10c90f97", + "path": "scripts/write-tracked-release.mjs", + "size": 604 + }, + { + "digest": "9aa3796abbf42eded4c24e905ae7b31fc29cccd23bda3dd36787c04290675894", + "path": "src/contracts/schemas/v1/adjudication-evidence.schema.json", + "size": 6526 + }, + { + "digest": "5cebe476968faf9755b789574e8c0be9552626b3a4839162980540933903aa4b", + "path": "src/contracts/schemas/v1/adjudication.schema.json", + "size": 4685 + }, + { + "digest": "9b2d936b124881a9da122c44f88bfc39f68301aed02151234a9e1c78bc598384", + "path": "src/contracts/schemas/v1/authority-link.schema.json", + "size": 3628 + }, + { + "digest": "86d25924b7f091b651a515a5ea6293700f9cff98a67852fdba3b92b718d79fd5", + "path": "src/contracts/schemas/v1/config.schema.json", + "size": 1166 + }, + { + "digest": "6b98163ecbf98341d2d4e23ceeef1fda7ec46a3b48a191d33b8a3aba48ab28bf", + "path": "src/contracts/schemas/v1/constitution-rule.schema.json", + "size": 698 + }, + { + "digest": "3ff3379c5c3d623887b0566699988ad481d653f887be44e880ae596f18d858b7", + "path": "src/contracts/schemas/v1/evidence-reference.schema.json", + "size": 793 + }, + { + "digest": "efa7beb830e99ce839b2e24bfa40e9a15defda90813b42bf2c08e62685c37358", + "path": "src/contracts/schemas/v1/phase-instance.schema.json", + "size": 1002 + }, + { + "digest": "a5b3d175d1745547e3961a67eefb6e902dc410e479c552b3891ab4a2dae8c206", + "path": "src/contracts/schemas/v1/protocol-error.schema.json", + "size": 5829 + }, + { + "digest": "b85df56b0d03d24b7550a7a10d385f68b637753d0f9fb2772a0b0c37882fd023", + "path": "src/contracts/schemas/v1/release-legal-review.schema.json", + "size": 15880 + }, + { + "digest": "c74addf0733b7607ac12cbc8ca58b1d981b518c2f6f81a1175ece38be883bd09", + "path": "src/contracts/schemas/v1/release-manifest.schema.json", + "size": 12819 + }, + { + "digest": "1f1ea2cbd0a70a44654df726f0bf5bc12841e32745bdd00562715a7d0fcde23a", + "path": "src/contracts/schemas/v1/result-expectation.schema.json", + "size": 3531 + }, + { + "digest": "fbf802dfac543b8340f33a792ad86dbec2367cee5d95d085a7684aaeae986636", + "path": "src/contracts/schemas/v1/review-evidence.schema.json", + "size": 4807 + }, + { + "digest": "1e645d58cf3c38d0dd1fe772dcb31aed2c82bdb978c09529cb67dd8deae9ee65", + "path": "src/contracts/schemas/v1/review.schema.json", + "size": 2924 + }, + { + "digest": "dff331ba25bb526a64f0360d535e0d8c26232a3144c73f75eba227096ef04033", + "path": "src/contracts/schemas/v1/supplemental-review.schema.json", + "size": 4522 + }, + { + "digest": "d8b063ecb6b51279e05cf77b990635fb65074781b8d7079b902fe45d0c7040c6", + "path": "src/contracts/schemas/v1/triage.schema.json", + "size": 2283 + }, + { + "digest": "35079ed6f14b96684240998400bbe9dd5a2b91f1ff69d36d9c4eaa295a94ecb3", + "path": "src/contracts/schemas/v1/workflow.schema.json", + "size": 1269 + }, + { + "digest": "45c30c1a970d10122644ea629373f109d17b8ce92fece352c56cabfa341f5deb", + "path": "src/contracts/versions.ts", + "size": 1452 + }, + { + "digest": "12668b3bc02270962b875cf840e51489b05a6b90d60af4eecf5b03d8f992adbe", + "path": "test/contracts/release-contracts.test.ts", + "size": 16797 + }, + { + "digest": "b181c4f2c8068a968df3596cdfde288a1f0552341da8f26cf4992eb417ffdba0", + "path": "test/contracts/schema-registry.test.ts", + "size": 3499 + }, + { + "digest": "33401af67624bd2bd7bf8073e50d33a3f20e2ade0bee33fadee00fc1aa3ad53e", + "path": "test/fixtures/mcp/runtime/adversarial-bytes.json", + "size": 261 + }, + { + "digest": "39d0dc0461a2b64e0844ff119a0647cd89388191e03f5a55baccd01149f3c9ba", + "path": "test/fixtures/mcp/runtime/calls.json", + "size": 1145 + }, + { + "digest": "5547b92a1f0667ef70c712cd99800fa38074278e4470a20231893e023c1504dc", + "path": "test/fixtures/mcp/runtime/initialize.json", + "size": 1091 + }, + { + "digest": "044dfd578041d22f584729f216cf5e82644ad6b45e54a8deee61e33e79dc32ca", + "path": "test/fixtures/release/hostile-runtime-guard.cjs", + "size": 3289 + }, + { + "digest": "8af4f3d653852533985025a71fcd291d69cc9bbbc11a59012d3b1f8807ac0508", + "path": "test/integration/mcp-stdio.test.ts", + "size": 11457 + }, + { + "digest": "2314859de76f3fa2214113d84eaaa0a65e7b6ec71588fa091d27d31a3a847791", + "path": "test/integration/release-offline.test.ts", + "size": 3539 + } + ], + "schema_version": "1" +} diff --git a/dist/metafile.json b/dist/metafile.json new file mode 100644 index 00000000..34f6be2e --- /dev/null +++ b/dist/metafile.json @@ -0,0 +1,2584 @@ +{ + "inputs": { + "node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs": { + "bytes": 68485, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod/v4", + "path": "node_modules/zod/v4/index.js" + } + ] + }, + "node_modules/@modelcontextprotocol/core/dist/internal.mjs": { + "bytes": 11434, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./auth-CUe6YdwF.mjs", + "path": "node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs" + } + ] + }, + "node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs": { + "bytes": 273658, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./chunk-Br0eD_fh.mjs", + "path": "node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs" + }, + { + "kind": "import-statement", + "original": "./dialects-DoSzNhcb.mjs", + "path": "node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs" + } + ] + }, + "node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs": { + "bytes": 1426, + "format": "esm", + "imports": [] + }, + "node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs": { + "bytes": 2107, + "format": "esm", + "imports": [] + }, + "node_modules/@modelcontextprotocol/server/dist/index.mjs": { + "bytes": 80210, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./mcp-DXXb3Vv3.mjs", + "path": "node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs" + }, + { + "kind": "import-statement", + "original": "./src-CX2iR2pK.mjs", + "path": "node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs" + }, + { + "kind": "import-statement", + "original": "@modelcontextprotocol/server/_shims", + "path": "node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs" + } + ] + }, + "node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs": { + "bytes": 87288, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./src-CX2iR2pK.mjs", + "path": "node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs" + }, + { + "kind": "import-statement", + "original": "@modelcontextprotocol/server/_shims", + "path": "node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs" + } + ] + }, + "node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs": { + "bytes": 184, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./ajvProvider-CEoC__sr.mjs", + "path": "node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:process" + } + ] + }, + "node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs": { + "bytes": 331079, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./chunk-Br0eD_fh.mjs", + "path": "node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs" + }, + { + "kind": "import-statement", + "original": "./dialects-DoSzNhcb.mjs", + "path": "node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs" + }, + { + "kind": "import-statement", + "original": "@modelcontextprotocol/core/internal", + "path": "node_modules/@modelcontextprotocol/core/dist/internal.mjs" + }, + { + "kind": "import-statement", + "original": "zod/v4", + "path": "node_modules/zod/v4/index.js" + } + ] + }, + "node_modules/zod/index.js": { + "bytes": 121, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./v4/classic/external.js", + "path": "node_modules/zod/v4/classic/external.js" + }, + { + "kind": "import-statement", + "original": "./v4/classic/external.js", + "path": "node_modules/zod/v4/classic/external.js" + } + ] + }, + "node_modules/zod/v4/classic/checks.js": { + "bytes": 663, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + } + ] + }, + "node_modules/zod/v4/classic/coerce.js": { + "bytes": 550, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "./schemas.js", + "path": "node_modules/zod/v4/classic/schemas.js" + } + ] + }, + "node_modules/zod/v4/classic/compat.js": { + "bytes": 1090, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + } + ] + }, + "node_modules/zod/v4/classic/errors.js": { + "bytes": 1609, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/classic/external.js": { + "bytes": 907, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "./schemas.js", + "path": "node_modules/zod/v4/classic/schemas.js" + }, + { + "kind": "import-statement", + "original": "./checks.js", + "path": "node_modules/zod/v4/classic/checks.js" + }, + { + "kind": "import-statement", + "original": "./errors.js", + "path": "node_modules/zod/v4/classic/errors.js" + }, + { + "kind": "import-statement", + "original": "./parse.js", + "path": "node_modules/zod/v4/classic/parse.js" + }, + { + "kind": "import-statement", + "original": "./compat.js", + "path": "node_modules/zod/v4/classic/compat.js" + }, + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "../locales/en.js", + "path": "node_modules/zod/v4/locales/en.js" + }, + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "../core/json-schema-processors.js", + "path": "node_modules/zod/v4/core/json-schema-processors.js" + }, + { + "kind": "import-statement", + "original": "./from-json-schema.js", + "path": "node_modules/zod/v4/classic/from-json-schema.js" + }, + { + "kind": "import-statement", + "original": "../locales/index.js", + "path": "node_modules/zod/v4/locales/index.js" + }, + { + "kind": "import-statement", + "original": "./iso.js", + "path": "node_modules/zod/v4/classic/iso.js" + }, + { + "kind": "import-statement", + "original": "./iso.js", + "path": "node_modules/zod/v4/classic/iso.js" + }, + { + "kind": "import-statement", + "original": "./coerce.js", + "path": "node_modules/zod/v4/classic/coerce.js" + } + ] + }, + "node_modules/zod/v4/classic/from-json-schema.js": { + "bytes": 24161, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/registries.js", + "path": "node_modules/zod/v4/core/registries.js" + }, + { + "kind": "import-statement", + "original": "./checks.js", + "path": "node_modules/zod/v4/classic/checks.js" + }, + { + "kind": "import-statement", + "original": "./iso.js", + "path": "node_modules/zod/v4/classic/iso.js" + }, + { + "kind": "import-statement", + "original": "./schemas.js", + "path": "node_modules/zod/v4/classic/schemas.js" + } + ] + }, + "node_modules/zod/v4/classic/index.js": { + "bytes": 99, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./external.js", + "path": "node_modules/zod/v4/classic/external.js" + }, + { + "kind": "import-statement", + "original": "./external.js", + "path": "node_modules/zod/v4/classic/external.js" + } + ] + }, + "node_modules/zod/v4/classic/iso.js": { + "bytes": 1151, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "./schemas.js", + "path": "node_modules/zod/v4/classic/schemas.js" + } + ] + }, + "node_modules/zod/v4/classic/parse.js": { + "bytes": 997, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "./errors.js", + "path": "node_modules/zod/v4/classic/errors.js" + } + ] + }, + "node_modules/zod/v4/classic/schemas.js": { + "bytes": 51378, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "../core/index.js", + "path": "node_modules/zod/v4/core/index.js" + }, + { + "kind": "import-statement", + "original": "../core/json-schema-processors.js", + "path": "node_modules/zod/v4/core/json-schema-processors.js" + }, + { + "kind": "import-statement", + "original": "../core/to-json-schema.js", + "path": "node_modules/zod/v4/core/to-json-schema.js" + }, + { + "kind": "import-statement", + "original": "./checks.js", + "path": "node_modules/zod/v4/classic/checks.js" + }, + { + "kind": "import-statement", + "original": "./iso.js", + "path": "node_modules/zod/v4/classic/iso.js" + }, + { + "kind": "import-statement", + "original": "./parse.js", + "path": "node_modules/zod/v4/classic/parse.js" + } + ] + }, + "node_modules/zod/v4/core/api.js": { + "bytes": 28054, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./checks.js", + "path": "node_modules/zod/v4/core/checks.js" + }, + { + "kind": "import-statement", + "original": "./registries.js", + "path": "node_modules/zod/v4/core/registries.js" + }, + { + "kind": "import-statement", + "original": "./schemas.js", + "path": "node_modules/zod/v4/core/schemas.js" + }, + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/core/checks.js": { + "bytes": 20005, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./core.js", + "path": "node_modules/zod/v4/core/core.js" + }, + { + "kind": "import-statement", + "original": "./regexes.js", + "path": "node_modules/zod/v4/core/regexes.js" + }, + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/core/core.js": { + "bytes": 2578, + "format": "esm", + "imports": [] + }, + "node_modules/zod/v4/core/doc.js": { + "bytes": 1088, + "format": "esm", + "imports": [] + }, + "node_modules/zod/v4/core/errors.js": { + "bytes": 6413, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./core.js", + "path": "node_modules/zod/v4/core/core.js" + }, + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/core/index.js": { + "bytes": 594, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./core.js", + "path": "node_modules/zod/v4/core/core.js" + }, + { + "kind": "import-statement", + "original": "./parse.js", + "path": "node_modules/zod/v4/core/parse.js" + }, + { + "kind": "import-statement", + "original": "./errors.js", + "path": "node_modules/zod/v4/core/errors.js" + }, + { + "kind": "import-statement", + "original": "./schemas.js", + "path": "node_modules/zod/v4/core/schemas.js" + }, + { + "kind": "import-statement", + "original": "./checks.js", + "path": "node_modules/zod/v4/core/checks.js" + }, + { + "kind": "import-statement", + "original": "./versions.js", + "path": "node_modules/zod/v4/core/versions.js" + }, + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + }, + { + "kind": "import-statement", + "original": "./regexes.js", + "path": "node_modules/zod/v4/core/regexes.js" + }, + { + "kind": "import-statement", + "original": "../locales/index.js", + "path": "node_modules/zod/v4/locales/index.js" + }, + { + "kind": "import-statement", + "original": "./registries.js", + "path": "node_modules/zod/v4/core/registries.js" + }, + { + "kind": "import-statement", + "original": "./doc.js", + "path": "node_modules/zod/v4/core/doc.js" + }, + { + "kind": "import-statement", + "original": "./api.js", + "path": "node_modules/zod/v4/core/api.js" + }, + { + "kind": "import-statement", + "original": "./to-json-schema.js", + "path": "node_modules/zod/v4/core/to-json-schema.js" + }, + { + "kind": "import-statement", + "original": "./json-schema-processors.js", + "path": "node_modules/zod/v4/core/json-schema-processors.js" + }, + { + "kind": "import-statement", + "original": "./json-schema-generator.js", + "path": "node_modules/zod/v4/core/json-schema-generator.js" + }, + { + "kind": "import-statement", + "original": "./json-schema.js", + "path": "node_modules/zod/v4/core/json-schema.js" + } + ] + }, + "node_modules/zod/v4/core/json-schema-generator.js": { + "bytes": 3218, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./json-schema-processors.js", + "path": "node_modules/zod/v4/core/json-schema-processors.js" + }, + { + "kind": "import-statement", + "original": "./to-json-schema.js", + "path": "node_modules/zod/v4/core/to-json-schema.js" + } + ] + }, + "node_modules/zod/v4/core/json-schema-processors.js": { + "bytes": 20716, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./to-json-schema.js", + "path": "node_modules/zod/v4/core/to-json-schema.js" + }, + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/core/json-schema.js": { + "bytes": 11, + "format": "esm", + "imports": [] + }, + "node_modules/zod/v4/core/parse.js": { + "bytes": 4444, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./core.js", + "path": "node_modules/zod/v4/core/core.js" + }, + { + "kind": "import-statement", + "original": "./errors.js", + "path": "node_modules/zod/v4/core/errors.js" + }, + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/core/regexes.js": { + "bytes": 9078, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/core/registries.js": { + "bytes": 1512, + "format": "esm", + "imports": [] + }, + "node_modules/zod/v4/core/schemas.js": { + "bytes": 83322, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./checks.js", + "path": "node_modules/zod/v4/core/checks.js" + }, + { + "kind": "import-statement", + "original": "./core.js", + "path": "node_modules/zod/v4/core/core.js" + }, + { + "kind": "import-statement", + "original": "./doc.js", + "path": "node_modules/zod/v4/core/doc.js" + }, + { + "kind": "import-statement", + "original": "./parse.js", + "path": "node_modules/zod/v4/core/parse.js" + }, + { + "kind": "import-statement", + "original": "./regexes.js", + "path": "node_modules/zod/v4/core/regexes.js" + }, + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + }, + { + "kind": "import-statement", + "original": "./versions.js", + "path": "node_modules/zod/v4/core/versions.js" + }, + { + "kind": "import-statement", + "original": "./util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/core/to-json-schema.js": { + "bytes": 17006, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./registries.js", + "path": "node_modules/zod/v4/core/registries.js" + } + ] + }, + "node_modules/zod/v4/core/util.js": { + "bytes": 22018, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./core.js", + "path": "node_modules/zod/v4/core/core.js" + } + ] + }, + "node_modules/zod/v4/core/versions.js": { + "bytes": 70, + "format": "esm", + "imports": [] + }, + "node_modules/zod/v4/index.js": { + "bytes": 92, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./classic/index.js", + "path": "node_modules/zod/v4/classic/index.js" + }, + { + "kind": "import-statement", + "original": "./classic/index.js", + "path": "node_modules/zod/v4/classic/index.js" + } + ] + }, + "node_modules/zod/v4/locales/ar.js": { + "bytes": 5188, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/az.js": { + "bytes": 4511, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/be.js": { + "bytes": 6619, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/bg.js": { + "bytes": 5785, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ca.js": { + "bytes": 4710, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/cs.js": { + "bytes": 4772, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/da.js": { + "bytes": 4804, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/de.js": { + "bytes": 4588, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/el.js": { + "bytes": 5544, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/en.js": { + "bytes": 4805, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/eo.js": { + "bytes": 4603, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/es.js": { + "bytes": 5439, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/fa.js": { + "bytes": 5131, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/fi.js": { + "bytes": 4818, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/fr-CA.js": { + "bytes": 4554, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/fr.js": { + "bytes": 5137, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/he.js": { + "bytes": 12005, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/hr.js": { + "bytes": 5052, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/hu.js": { + "bytes": 4696, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/hy.js": { + "bytes": 6390, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/id.js": { + "bytes": 4577, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/index.js": { + "bytes": 2149, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./ar.js", + "path": "node_modules/zod/v4/locales/ar.js" + }, + { + "kind": "import-statement", + "original": "./az.js", + "path": "node_modules/zod/v4/locales/az.js" + }, + { + "kind": "import-statement", + "original": "./be.js", + "path": "node_modules/zod/v4/locales/be.js" + }, + { + "kind": "import-statement", + "original": "./bg.js", + "path": "node_modules/zod/v4/locales/bg.js" + }, + { + "kind": "import-statement", + "original": "./ca.js", + "path": "node_modules/zod/v4/locales/ca.js" + }, + { + "kind": "import-statement", + "original": "./cs.js", + "path": "node_modules/zod/v4/locales/cs.js" + }, + { + "kind": "import-statement", + "original": "./da.js", + "path": "node_modules/zod/v4/locales/da.js" + }, + { + "kind": "import-statement", + "original": "./de.js", + "path": "node_modules/zod/v4/locales/de.js" + }, + { + "kind": "import-statement", + "original": "./el.js", + "path": "node_modules/zod/v4/locales/el.js" + }, + { + "kind": "import-statement", + "original": "./en.js", + "path": "node_modules/zod/v4/locales/en.js" + }, + { + "kind": "import-statement", + "original": "./eo.js", + "path": "node_modules/zod/v4/locales/eo.js" + }, + { + "kind": "import-statement", + "original": "./es.js", + "path": "node_modules/zod/v4/locales/es.js" + }, + { + "kind": "import-statement", + "original": "./fa.js", + "path": "node_modules/zod/v4/locales/fa.js" + }, + { + "kind": "import-statement", + "original": "./fi.js", + "path": "node_modules/zod/v4/locales/fi.js" + }, + { + "kind": "import-statement", + "original": "./fr.js", + "path": "node_modules/zod/v4/locales/fr.js" + }, + { + "kind": "import-statement", + "original": "./fr-CA.js", + "path": "node_modules/zod/v4/locales/fr-CA.js" + }, + { + "kind": "import-statement", + "original": "./he.js", + "path": "node_modules/zod/v4/locales/he.js" + }, + { + "kind": "import-statement", + "original": "./hr.js", + "path": "node_modules/zod/v4/locales/hr.js" + }, + { + "kind": "import-statement", + "original": "./hu.js", + "path": "node_modules/zod/v4/locales/hu.js" + }, + { + "kind": "import-statement", + "original": "./hy.js", + "path": "node_modules/zod/v4/locales/hy.js" + }, + { + "kind": "import-statement", + "original": "./id.js", + "path": "node_modules/zod/v4/locales/id.js" + }, + { + "kind": "import-statement", + "original": "./is.js", + "path": "node_modules/zod/v4/locales/is.js" + }, + { + "kind": "import-statement", + "original": "./it.js", + "path": "node_modules/zod/v4/locales/it.js" + }, + { + "kind": "import-statement", + "original": "./ja.js", + "path": "node_modules/zod/v4/locales/ja.js" + }, + { + "kind": "import-statement", + "original": "./ka.js", + "path": "node_modules/zod/v4/locales/ka.js" + }, + { + "kind": "import-statement", + "original": "./kh.js", + "path": "node_modules/zod/v4/locales/kh.js" + }, + { + "kind": "import-statement", + "original": "./km.js", + "path": "node_modules/zod/v4/locales/km.js" + }, + { + "kind": "import-statement", + "original": "./ko.js", + "path": "node_modules/zod/v4/locales/ko.js" + }, + { + "kind": "import-statement", + "original": "./lt.js", + "path": "node_modules/zod/v4/locales/lt.js" + }, + { + "kind": "import-statement", + "original": "./mk.js", + "path": "node_modules/zod/v4/locales/mk.js" + }, + { + "kind": "import-statement", + "original": "./ms.js", + "path": "node_modules/zod/v4/locales/ms.js" + }, + { + "kind": "import-statement", + "original": "./nl.js", + "path": "node_modules/zod/v4/locales/nl.js" + }, + { + "kind": "import-statement", + "original": "./no.js", + "path": "node_modules/zod/v4/locales/no.js" + }, + { + "kind": "import-statement", + "original": "./ota.js", + "path": "node_modules/zod/v4/locales/ota.js" + }, + { + "kind": "import-statement", + "original": "./ps.js", + "path": "node_modules/zod/v4/locales/ps.js" + }, + { + "kind": "import-statement", + "original": "./pl.js", + "path": "node_modules/zod/v4/locales/pl.js" + }, + { + "kind": "import-statement", + "original": "./pt.js", + "path": "node_modules/zod/v4/locales/pt.js" + }, + { + "kind": "import-statement", + "original": "./ro.js", + "path": "node_modules/zod/v4/locales/ro.js" + }, + { + "kind": "import-statement", + "original": "./ru.js", + "path": "node_modules/zod/v4/locales/ru.js" + }, + { + "kind": "import-statement", + "original": "./sl.js", + "path": "node_modules/zod/v4/locales/sl.js" + }, + { + "kind": "import-statement", + "original": "./sv.js", + "path": "node_modules/zod/v4/locales/sv.js" + }, + { + "kind": "import-statement", + "original": "./ta.js", + "path": "node_modules/zod/v4/locales/ta.js" + }, + { + "kind": "import-statement", + "original": "./th.js", + "path": "node_modules/zod/v4/locales/th.js" + }, + { + "kind": "import-statement", + "original": "./tr.js", + "path": "node_modules/zod/v4/locales/tr.js" + }, + { + "kind": "import-statement", + "original": "./ua.js", + "path": "node_modules/zod/v4/locales/ua.js" + }, + { + "kind": "import-statement", + "original": "./uk.js", + "path": "node_modules/zod/v4/locales/uk.js" + }, + { + "kind": "import-statement", + "original": "./ur.js", + "path": "node_modules/zod/v4/locales/ur.js" + }, + { + "kind": "import-statement", + "original": "./uz.js", + "path": "node_modules/zod/v4/locales/uz.js" + }, + { + "kind": "import-statement", + "original": "./vi.js", + "path": "node_modules/zod/v4/locales/vi.js" + }, + { + "kind": "import-statement", + "original": "./zh-CN.js", + "path": "node_modules/zod/v4/locales/zh-CN.js" + }, + { + "kind": "import-statement", + "original": "./zh-TW.js", + "path": "node_modules/zod/v4/locales/zh-TW.js" + }, + { + "kind": "import-statement", + "original": "./yo.js", + "path": "node_modules/zod/v4/locales/yo.js" + } + ] + }, + "node_modules/zod/v4/locales/is.js": { + "bytes": 4635, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/it.js": { + "bytes": 4582, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ja.js": { + "bytes": 4851, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ka.js": { + "bytes": 6202, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/kh.js": { + "bytes": 111, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./km.js", + "path": "node_modules/zod/v4/locales/km.js" + } + ] + }, + "node_modules/zod/v4/locales/km.js": { + "bytes": 6242, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ko.js": { + "bytes": 4929, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/lt.js": { + "bytes": 8082, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/mk.js": { + "bytes": 5157, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ms.js": { + "bytes": 4491, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/nl.js": { + "bytes": 4762, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/no.js": { + "bytes": 4506, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ota.js": { + "bytes": 4525, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/pl.js": { + "bytes": 4966, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ps.js": { + "bytes": 4909, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/pt.js": { + "bytes": 4568, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ro.js": { + "bytes": 4774, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ru.js": { + "bytes": 6714, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/sl.js": { + "bytes": 4567, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/sv.js": { + "bytes": 4663, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ta.js": { + "bytes": 6369, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/th.js": { + "bytes": 6290, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/tr.js": { + "bytes": 4454, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ua.js": { + "bytes": 111, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "./uk.js", + "path": "node_modules/zod/v4/locales/uk.js" + } + ] + }, + "node_modules/zod/v4/locales/uk.js": { + "bytes": 5430, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/ur.js": { + "bytes": 5271, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/uz.js": { + "bytes": 4739, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/vi.js": { + "bytes": 4772, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/yo.js": { + "bytes": 4665, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/zh-CN.js": { + "bytes": 4452, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "node_modules/zod/v4/locales/zh-TW.js": { + "bytes": 4498, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../core/util.js", + "path": "node_modules/zod/v4/core/util.js" + } + ] + }, + "src/contracts/adjudication.ts": { + "bytes": 11437, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + }, + { + "kind": "import-statement", + "original": "./review.js", + "path": "src/contracts/review.ts" + } + ] + }, + "src/contracts/contexts.ts": { + "bytes": 4800, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./errors.js", + "path": "src/contracts/errors.ts" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + } + ] + }, + "src/contracts/errors.ts": { + "bytes": 20041, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:util" + }, + { + "kind": "import-statement", + "original": "./evidence.js", + "path": "src/contracts/evidence.ts" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + }, + { + "kind": "import-statement", + "original": "./phase-instance.js", + "path": "src/contracts/phase-instance.ts" + }, + { + "kind": "import-statement", + "original": "./path-claims.js", + "path": "src/contracts/path-claims.ts" + }, + { + "kind": "import-statement", + "original": "./gates.js", + "path": "src/contracts/gates.ts" + }, + { + "kind": "import-statement", + "original": "./tool-names.js", + "path": "src/contracts/tool-names.ts" + } + ] + }, + "src/contracts/evidence.ts": { + "bytes": 1993, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + } + ] + }, + "src/contracts/gates.ts": { + "bytes": 20832, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./evidence.js", + "path": "src/contracts/evidence.ts" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + }, + { + "kind": "import-statement", + "original": "./phase-instance.js", + "path": "src/contracts/phase-instance.ts" + }, + { + "kind": "import-statement", + "original": "./path-claims.js", + "path": "src/contracts/path-claims.ts" + }, + { + "kind": "import-statement", + "original": "./vocabulary.js", + "path": "src/contracts/vocabulary.ts" + } + ] + }, + "src/contracts/internal/trust-brands.ts": { + "bytes": 3476, + "format": "esm", + "imports": [] + }, + "src/contracts/mcp-tools.ts": { + "bytes": 18076, + "format": "esm", + "imports": [ + { + "external": true, + "kind": "import-statement", + "path": "node:util" + }, + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./adjudication.js", + "path": "src/contracts/adjudication.ts" + }, + { + "kind": "import-statement", + "original": "./errors.js", + "path": "src/contracts/errors.ts" + }, + { + "kind": "import-statement", + "original": "./gates.js", + "path": "src/contracts/gates.ts" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + }, + { + "kind": "import-statement", + "original": "./phase-instance.js", + "path": "src/contracts/phase-instance.ts" + }, + { + "kind": "import-statement", + "original": "./path-claims.js", + "path": "src/contracts/path-claims.ts" + }, + { + "kind": "import-statement", + "original": "./rubric.js", + "path": "src/contracts/rubric.ts" + }, + { + "kind": "import-statement", + "original": "./tool-names.js", + "path": "src/contracts/tool-names.ts" + }, + { + "kind": "import-statement", + "original": "./trust.js", + "path": "src/contracts/trust.ts" + } + ] + }, + "src/contracts/path-claims.ts": { + "bytes": 1595, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + } + ] + }, + "src/contracts/phase-instance.ts": { + "bytes": 1801, + "format": "esm", + "imports": [] + }, + "src/contracts/plain-json.ts": { + "bytes": 4540, + "format": "esm", + "imports": [] + }, + "src/contracts/review.ts": { + "bytes": 8734, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + } + ] + }, + "src/contracts/rubric.ts": { + "bytes": 1322, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + } + ] + }, + "src/contracts/schemas/v1/evidence-slots.schema.json": { + "bytes": 2790, + "format": "esm", + "imports": [], + "with": { + "type": "json" + } + }, + "src/contracts/schemas/v1/gate-contract.schema.json": { + "bytes": 16873, + "format": "esm", + "imports": [], + "with": { + "type": "json" + } + }, + "src/contracts/schemas/v1/gate-decision.schema.json": { + "bytes": 9402, + "format": "esm", + "imports": [], + "with": { + "type": "json" + } + }, + "src/contracts/schemas/v1/mcp-tools.schema.json": { + "bytes": 16657, + "format": "esm", + "imports": [], + "with": { + "type": "json" + } + }, + "src/contracts/schemas/v1/path-claim.schema.json": { + "bytes": 327, + "format": "esm", + "imports": [], + "with": { + "type": "json" + } + }, + "src/contracts/schemas/v1/primitives.schema.json": { + "bytes": 730, + "format": "esm", + "imports": [], + "with": { + "type": "json" + } + }, + "src/contracts/schemas/v1/project-error.schema.json": { + "bytes": 65252, + "format": "esm", + "imports": [], + "with": { + "type": "json" + } + }, + "src/contracts/schemas/v1/rubric.schema.json": { + "bytes": 781, + "format": "esm", + "imports": [], + "with": { + "type": "json" + } + }, + "src/contracts/tool-names.ts": { + "bytes": 377, + "format": "esm", + "imports": [] + }, + "src/contracts/trust.ts": { + "bytes": 25661, + "format": "esm", + "imports": [ + { + "external": true, + "kind": "import-statement", + "path": "node:crypto" + }, + { + "kind": "import-statement", + "original": "zod", + "path": "node_modules/zod/index.js" + }, + { + "kind": "import-statement", + "original": "./adjudication.js", + "path": "src/contracts/adjudication.ts" + }, + { + "kind": "import-statement", + "original": "./evidence.js", + "path": "src/contracts/evidence.ts" + }, + { + "kind": "import-statement", + "original": "./internal/trust-brands.js", + "path": "src/contracts/internal/trust-brands.ts" + }, + { + "kind": "import-statement", + "original": "./phase-instance.js", + "path": "src/contracts/phase-instance.ts" + }, + { + "kind": "import-statement", + "original": "./review.js", + "path": "src/contracts/review.ts" + }, + { + "kind": "import-statement", + "original": "./plain-json.js", + "path": "src/contracts/plain-json.ts" + } + ] + }, + "src/contracts/vocabulary.ts": { + "bytes": 569, + "format": "esm", + "imports": [] + }, + "src/main.ts": { + "bytes": 414, + "format": "esm", + "imports": [ + { + "external": true, + "kind": "import-statement", + "path": "node:process" + }, + { + "kind": "import-statement", + "original": "./mcp/process-runner.js", + "path": "src/mcp/process-runner.ts" + }, + { + "kind": "import-statement", + "original": "./mcp/sdk-adapter.js", + "path": "src/mcp/sdk-adapter.ts" + } + ] + }, + "src/mcp/framing.ts": { + "bytes": 3378, + "format": "esm", + "imports": [] + }, + "src/mcp/process-runner.ts": { + "bytes": 5511, + "format": "esm", + "imports": [] + }, + "src/mcp/sdk-adapter.ts": { + "bytes": 18189, + "format": "esm", + "imports": [ + { + "external": true, + "kind": "import-statement", + "path": "node:buffer" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:util" + }, + { + "kind": "import-statement", + "original": "@modelcontextprotocol/server", + "path": "node_modules/@modelcontextprotocol/server/dist/index.mjs" + }, + { + "kind": "import-statement", + "original": "../contracts/contexts.js", + "path": "src/contracts/contexts.ts" + }, + { + "kind": "import-statement", + "original": "./framing.js", + "path": "src/mcp/framing.ts" + }, + { + "kind": "import-statement", + "original": "./send-queue.js", + "path": "src/mcp/send-queue.ts" + }, + { + "kind": "import-statement", + "original": "./server.js", + "path": "src/mcp/server.ts" + }, + { + "kind": "import-statement", + "original": "./session.js", + "path": "src/mcp/session.ts" + }, + { + "kind": "import-statement", + "original": "./tools.js", + "path": "src/mcp/tools.ts" + } + ] + }, + "src/mcp/send-queue.ts": { + "bytes": 6425, + "format": "esm", + "imports": [] + }, + "src/mcp/server.ts": { + "bytes": 9506, + "format": "esm", + "imports": [ + { + "external": true, + "kind": "import-statement", + "path": "node:crypto" + }, + { + "kind": "import-statement", + "original": "../contracts/contexts.js", + "path": "src/contracts/contexts.ts" + }, + { + "kind": "import-statement", + "original": "../contracts/errors.js", + "path": "src/contracts/errors.ts" + }, + { + "kind": "import-statement", + "original": "../contracts/evidence.js", + "path": "src/contracts/evidence.ts" + }, + { + "kind": "import-statement", + "original": "../contracts/mcp-tools.js", + "path": "src/contracts/mcp-tools.ts" + }, + { + "kind": "import-statement", + "original": "../contracts/plain-json.js", + "path": "src/contracts/plain-json.ts" + }, + { + "kind": "import-statement", + "original": "../contracts/tool-names.js", + "path": "src/contracts/tool-names.ts" + } + ] + }, + "src/mcp/session.ts": { + "bytes": 21494, + "format": "esm", + "imports": [ + { + "external": true, + "kind": "import-statement", + "path": "node:buffer" + }, + { + "kind": "import-statement", + "original": "../contracts/errors.js", + "path": "src/contracts/errors.ts" + }, + { + "kind": "import-statement", + "original": "../contracts/plain-json.js", + "path": "src/contracts/plain-json.ts" + }, + { + "kind": "import-statement", + "original": "../contracts/tool-names.js", + "path": "src/contracts/tool-names.ts" + }, + { + "kind": "import-statement", + "original": "./server.js", + "path": "src/mcp/server.ts" + } + ] + }, + "src/mcp/tools.ts": { + "bytes": 4924, + "format": "esm", + "imports": [ + { + "kind": "import-statement", + "original": "../contracts/schemas/v1/evidence-slots.schema.json", + "path": "src/contracts/schemas/v1/evidence-slots.schema.json", + "with": { + "type": "json" + } + }, + { + "kind": "import-statement", + "original": "../contracts/schemas/v1/gate-contract.schema.json", + "path": "src/contracts/schemas/v1/gate-contract.schema.json", + "with": { + "type": "json" + } + }, + { + "kind": "import-statement", + "original": "../contracts/schemas/v1/gate-decision.schema.json", + "path": "src/contracts/schemas/v1/gate-decision.schema.json", + "with": { + "type": "json" + } + }, + { + "kind": "import-statement", + "original": "../contracts/schemas/v1/mcp-tools.schema.json", + "path": "src/contracts/schemas/v1/mcp-tools.schema.json", + "with": { + "type": "json" + } + }, + { + "kind": "import-statement", + "original": "../contracts/schemas/v1/path-claim.schema.json", + "path": "src/contracts/schemas/v1/path-claim.schema.json", + "with": { + "type": "json" + } + }, + { + "kind": "import-statement", + "original": "../contracts/schemas/v1/primitives.schema.json", + "path": "src/contracts/schemas/v1/primitives.schema.json", + "with": { + "type": "json" + } + }, + { + "kind": "import-statement", + "original": "../contracts/schemas/v1/project-error.schema.json", + "path": "src/contracts/schemas/v1/project-error.schema.json", + "with": { + "type": "json" + } + }, + { + "kind": "import-statement", + "original": "../contracts/schemas/v1/rubric.schema.json", + "path": "src/contracts/schemas/v1/rubric.schema.json", + "with": { + "type": "json" + } + }, + { + "kind": "import-statement", + "original": "../contracts/tool-names.js", + "path": "src/contracts/tool-names.ts" + } + ] + } + }, + "outputs": { + "archflow-mcp.mjs": { + "bytes": 1316957, + "entryPoint": "src/main.ts", + "exports": [], + "imports": [ + { + "external": true, + "kind": "import-statement", + "path": "node:process" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:buffer" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:util" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:util" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:crypto" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:util" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:crypto" + }, + { + "external": true, + "kind": "import-statement", + "path": "node:buffer" + } + ], + "inputs": { + "node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs": { + "bytesInOutput": 34870 + }, + "node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs": { + "bytesInOutput": 271819 + }, + "node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs": { + "bytesInOutput": 1382 + }, + "node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs": { + "bytesInOutput": 1284 + }, + "node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs": { + "bytesInOutput": 40127 + }, + "node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs": { + "bytesInOutput": 184676 + }, + "node_modules/zod/index.js": { + "bytesInOutput": 0 + }, + "node_modules/zod/v4/classic/checks.js": { + "bytesInOutput": 858 + }, + "node_modules/zod/v4/classic/coerce.js": { + "bytesInOutput": 540 + }, + "node_modules/zod/v4/classic/compat.js": { + "bytesInOutput": 641 + }, + "node_modules/zod/v4/classic/errors.js": { + "bytesInOutput": 1023 + }, + "node_modules/zod/v4/classic/external.js": { + "bytesInOutput": 6908 + }, + "node_modules/zod/v4/classic/from-json-schema.js": { + "bytesInOutput": 16474 + }, + "node_modules/zod/v4/classic/iso.js": { + "bytesInOutput": 1205 + }, + "node_modules/zod/v4/classic/parse.js": { + "bytesInOutput": 736 + }, + "node_modules/zod/v4/classic/schemas.js": { + "bytesInOutput": 45669 + }, + "node_modules/zod/v4/core/api.js": { + "bytesInOutput": 22885 + }, + "node_modules/zod/v4/core/checks.js": { + "bytesInOutput": 16479 + }, + "node_modules/zod/v4/core/core.js": { + "bytesInOutput": 2090 + }, + "node_modules/zod/v4/core/doc.js": { + "bytesInOutput": 924 + }, + "node_modules/zod/v4/core/errors.js": { + "bytesInOutput": 4672 + }, + "node_modules/zod/v4/core/index.js": { + "bytesInOutput": 8865 + }, + "node_modules/zod/v4/core/json-schema-generator.js": { + "bytesInOutput": 2118 + }, + "node_modules/zod/v4/core/json-schema-processors.js": { + "bytesInOutput": 16938 + }, + "node_modules/zod/v4/core/json-schema.js": { + "bytesInOutput": 30 + }, + "node_modules/zod/v4/core/parse.js": { + "bytesInOutput": 3794 + }, + "node_modules/zod/v4/core/regexes.js": { + "bytesInOutput": 7520 + }, + "node_modules/zod/v4/core/registries.js": { + "bytesInOutput": 1330 + }, + "node_modules/zod/v4/core/schemas.js": { + "bytesInOutput": 66155 + }, + "node_modules/zod/v4/core/to-json-schema.js": { + "bytesInOutput": 11413 + }, + "node_modules/zod/v4/core/util.js": { + "bytesInOutput": 19852 + }, + "node_modules/zod/v4/core/versions.js": { + "bytesInOutput": 54 + }, + "node_modules/zod/v4/locales/ar.js": { + "bytesInOutput": 7121 + }, + "node_modules/zod/v4/locales/az.js": { + "bytesInOutput": 4340 + }, + "node_modules/zod/v4/locales/be.js": { + "bytesInOutput": 8702 + }, + "node_modules/zod/v4/locales/bg.js": { + "bytesInOutput": 7825 + }, + "node_modules/zod/v4/locales/ca.js": { + "bytesInOutput": 4154 + }, + "node_modules/zod/v4/locales/cs.js": { + "bytesInOutput": 4466 + }, + "node_modules/zod/v4/locales/da.js": { + "bytesInOutput": 4171 + }, + "node_modules/zod/v4/locales/de.js": { + "bytesInOutput": 4003 + }, + "node_modules/zod/v4/locales/el.js": { + "bytesInOutput": 7983 + }, + "node_modules/zod/v4/locales/en.js": { + "bytesInOutput": 4077 + }, + "node_modules/zod/v4/locales/eo.js": { + "bytesInOutput": 4043 + }, + "node_modules/zod/v4/locales/es.js": { + "bytesInOutput": 4783 + }, + "node_modules/zod/v4/locales/fa.js": { + "bytesInOutput": 6726 + }, + "node_modules/zod/v4/locales/fi.js": { + "bytesInOutput": 4247 + }, + "node_modules/zod/v4/locales/fr-CA.js": { + "bytesInOutput": 3999 + }, + "node_modules/zod/v4/locales/fr.js": { + "bytesInOutput": 4525 + }, + "node_modules/zod/v4/locales/he.js": { + "bytesInOutput": 13032 + }, + "node_modules/zod/v4/locales/hr.js": { + "bytesInOutput": 4429 + }, + "node_modules/zod/v4/locales/hu.js": { + "bytesInOutput": 4279 + }, + "node_modules/zod/v4/locales/hy.js": { + "bytesInOutput": 8264 + }, + "node_modules/zod/v4/locales/id.js": { + "bytesInOutput": 3964 + }, + "node_modules/zod/v4/locales/index.js": { + "bytesInOutput": 1322 + }, + "node_modules/zod/v4/locales/is.js": { + "bytesInOutput": 4144 + }, + "node_modules/zod/v4/locales/it.js": { + "bytesInOutput": 3962 + }, + "node_modules/zod/v4/locales/ja.js": { + "bytesInOutput": 5348 + }, + "node_modules/zod/v4/locales/ka.js": { + "bytesInOutput": 7817 + }, + "node_modules/zod/v4/locales/kh.js": { + "bytesInOutput": 49 + }, + "node_modules/zod/v4/locales/km.js": { + "bytesInOutput": 8032 + }, + "node_modules/zod/v4/locales/ko.js": { + "bytesInOutput": 5145 + }, + "node_modules/zod/v4/locales/lt.js": { + "bytesInOutput": 7201 + }, + "node_modules/zod/v4/locales/mk.js": { + "bytesInOutput": 7000 + }, + "node_modules/zod/v4/locales/ms.js": { + "bytesInOutput": 3873 + }, + "node_modules/zod/v4/locales/nl.js": { + "bytesInOutput": 4129 + }, + "node_modules/zod/v4/locales/no.js": { + "bytesInOutput": 3925 + }, + "node_modules/zod/v4/locales/ota.js": { + "bytesInOutput": 4143 + }, + "node_modules/zod/v4/locales/pl.js": { + "bytesInOutput": 4655 + }, + "node_modules/zod/v4/locales/ps.js": { + "bytesInOutput": 6076 + }, + "node_modules/zod/v4/locales/pt.js": { + "bytesInOutput": 4004 + }, + "node_modules/zod/v4/locales/ro.js": { + "bytesInOutput": 4366 + }, + "node_modules/zod/v4/locales/ru.js": { + "bytesInOutput": 8988 + }, + "node_modules/zod/v4/locales/sl.js": { + "bytesInOutput": 4022 + }, + "node_modules/zod/v4/locales/sv.js": { + "bytesInOutput": 4120 + }, + "node_modules/zod/v4/locales/ta.js": { + "bytesInOutput": 8172 + }, + "node_modules/zod/v4/locales/th.js": { + "bytesInOutput": 8107 + }, + "node_modules/zod/v4/locales/tr.js": { + "bytesInOutput": 4081 + }, + "node_modules/zod/v4/locales/ua.js": { + "bytesInOutput": 49 + }, + "node_modules/zod/v4/locales/uk.js": { + "bytesInOutput": 7877 + }, + "node_modules/zod/v4/locales/ur.js": { + "bytesInOutput": 7394 + }, + "node_modules/zod/v4/locales/uz.js": { + "bytesInOutput": 4218 + }, + "node_modules/zod/v4/locales/vi.js": { + "bytesInOutput": 4665 + }, + "node_modules/zod/v4/locales/yo.js": { + "bytesInOutput": 4784 + }, + "node_modules/zod/v4/locales/zh-CN.js": { + "bytesInOutput": 4504 + }, + "node_modules/zod/v4/locales/zh-TW.js": { + "bytesInOutput": 4609 + }, + "src/contracts/adjudication.ts": { + "bytesInOutput": 7747 + }, + "src/contracts/contexts.ts": { + "bytesInOutput": 3278 + }, + "src/contracts/errors.ts": { + "bytesInOutput": 14954 + }, + "src/contracts/evidence.ts": { + "bytesInOutput": 566 + }, + "src/contracts/gates.ts": { + "bytesInOutput": 14100 + }, + "src/contracts/internal/trust-brands.ts": { + "bytesInOutput": 1368 + }, + "src/contracts/mcp-tools.ts": { + "bytesInOutput": 9327 + }, + "src/contracts/path-claims.ts": { + "bytesInOutput": 975 + }, + "src/contracts/phase-instance.ts": { + "bytesInOutput": 1112 + }, + "src/contracts/plain-json.ts": { + "bytesInOutput": 3767 + }, + "src/contracts/review.ts": { + "bytesInOutput": 5775 + }, + "src/contracts/rubric.ts": { + "bytesInOutput": 913 + }, + "src/contracts/schemas/v1/evidence-slots.schema.json": { + "bytesInOutput": 2613 + }, + "src/contracts/schemas/v1/gate-contract.schema.json": { + "bytesInOutput": 15993 + }, + "src/contracts/schemas/v1/gate-decision.schema.json": { + "bytesInOutput": 9098 + }, + "src/contracts/schemas/v1/mcp-tools.schema.json": { + "bytesInOutput": 15803 + }, + "src/contracts/schemas/v1/path-claim.schema.json": { + "bytesInOutput": 350 + }, + "src/contracts/schemas/v1/primitives.schema.json": { + "bytesInOutput": 717 + }, + "src/contracts/schemas/v1/project-error.schema.json": { + "bytesInOutput": 62400 + }, + "src/contracts/schemas/v1/rubric.schema.json": { + "bytesInOutput": 760 + }, + "src/contracts/tool-names.ts": { + "bytesInOutput": 247 + }, + "src/contracts/trust.ts": { + "bytesInOutput": 14468 + }, + "src/contracts/vocabulary.ts": { + "bytesInOutput": 91 + }, + "src/main.ts": { + "bytesInOutput": 304 + }, + "src/mcp/framing.ts": { + "bytesInOutput": 2632 + }, + "src/mcp/process-runner.ts": { + "bytesInOutput": 3855 + }, + "src/mcp/sdk-adapter.ts": { + "bytesInOutput": 15075 + }, + "src/mcp/send-queue.ts": { + "bytesInOutput": 4962 + }, + "src/mcp/server.ts": { + "bytesInOutput": 6292 + }, + "src/mcp/session.ts": { + "bytesInOutput": 15513 + }, + "src/mcp/tools.ts": { + "bytesInOutput": 3555 + } + } + } + } +} diff --git a/package.json b/package.json index 847134b9..74e66d0a 100644 --- a/package.json +++ b/package.json @@ -14,12 +14,19 @@ "test:mcp-runtime": "vitest run test/unit/mcp-*.test.ts test/integration/mcp-stdio.test.ts", "probe:phase4-mcp-compatibility": "node scripts/probe-phase-4-mcp-compatibility.mjs", "build:temp": "node scripts/build-temp.mjs", + "release:stage": "node scripts/build-release.mjs", + "release:check": "node scripts/check-release.mjs", + "release:reproduce": "node scripts/reproduce-release.mjs", + "release:write": "node scripts/write-tracked-release.mjs", + "release:smoke": "node scripts/smoke-release-bundle.mjs", + "release:mutations": "node scripts/test-release-integrity.mjs", + "check:release": "npm run release:check -- --payload dist && npm run release:smoke -- --payload dist && npm run release:mutations && npm run release:reproduce", "check:dependencies": "node scripts/check-dependency-policy.mjs", "check:notices": "node scripts/check-notices.mjs", "test:notices-policy": "node scripts/test-notices-policy.mjs", "check:phase4-mcp-boundary": "node scripts/check-phase-4-mcp-boundary.mjs", "test:phase4-mcp-boundary-policy": "node scripts/test-phase-4-mcp-boundary-policy.mjs", - "check": "npm run probe:phase4-mcp-compatibility && npm run typecheck && npm run test:mcp-runtime && npm test && npm run test:contracts && npm run build:temp && npm run check:dependencies && npm run check:notices && npm run test:notices-policy && npm run check:phase4-mcp-boundary && npm run test:phase4-mcp-boundary-policy" + "check": "npm run probe:phase4-mcp-compatibility && npm run typecheck && npm run test:mcp-runtime && npm test && npm run test:contracts && npm run build:temp && npm run check:dependencies && npm run check:notices && npm run test:notices-policy && npm run check:phase4-mcp-boundary && npm run test:phase4-mcp-boundary-policy && npm run check:release" }, "dependencies": { "@modelcontextprotocol/server": "2.0.0", diff --git a/release/evidence/advisory-snapshot.json b/release/evidence/advisory-snapshot.json new file mode 100644 index 00000000..2aaa36c0 --- /dev/null +++ b/release/evidence/advisory-snapshot.json @@ -0,0 +1,38 @@ +{ + "advisories": [ + { + "affected_version": "3.1.0", + "id": "GHSA-4c8g-83qw-93j6", + "safe_version": "3.1.3", + "severity": "high", + "source_url": "https://github.com/advisories/GHSA-4c8g-83qw-93j6" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-q3j6-qgpj-74h6", + "safe_version": "3.1.1", + "severity": "high", + "source_url": "https://github.com/advisories/GHSA-q3j6-qgpj-74h6" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-v2hh-gcrm-f6hx", + "safe_version": "3.1.4", + "severity": "high", + "source_url": "https://github.com/advisories/GHSA-v2hh-gcrm-f6hx" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-v39h-62p7-jpjc", + "safe_version": "3.1.2", + "severity": "high", + "source_url": "https://github.com/advisories/GHSA-v39h-62p7-jpjc" + } + ], + "observed_on": "2026-07-27", + "package_name": "fast-uri", + "package_version": "3.1.0", + "record_type": "advisory-snapshot", + "safe_version_floor": "3.1.4", + "schema_version": "1" +} diff --git a/release/evidence/focused-inert-reachability.json b/release/evidence/focused-inert-reachability.json new file mode 100644 index 00000000..e3cf3430 --- /dev/null +++ b/release/evidence/focused-inert-reachability.json @@ -0,0 +1,20 @@ +{ + "bundle_digest": "16faf6365bc502ec0c0e00f150b43c300e65dfa9dcace1cce3d98d850b8cbbd0", + "entry_bindings": [ + { + "handler_authority": "inert-no-handler", + "id": "mcp-stdio", + "role": "mcp-stdio" + } + ], + "finding": "Vulnerable URI routines are runtime-reachable during trusted SDK schema compilation, but the inert handler-free runtime exposes no identified route from untrusted JSON-RPC input to URI normalization.", + "limitations": [ + "This focused result does not remediate the vulnerable dependency.", + "This result is invalidated by any bundle, dependency, entry, or handler-authority change." + ], + "observed_on": "2026-07-27", + "record_type": "focused-inert-reachability", + "schema_version": "1", + "trusted_schema_compilation_reachable": true, + "untrusted_json_rpc_route_identified": false +} diff --git a/release/evidence/patched-artifact-availability.json b/release/evidence/patched-artifact-availability.json new file mode 100644 index 00000000..6321bf4f --- /dev/null +++ b/release/evidence/patched-artifact-availability.json @@ -0,0 +1,12 @@ +{ + "compatible_patched_artifact_available": false, + "embedded_package": "fast-uri", + "embedded_version": "3.1.0", + "observed_on": "2026-07-27", + "record_type": "patched-artifact-availability", + "registry_source": "https://registry.npmjs.org/@modelcontextprotocol/server/2.0.0", + "safe_version_floor": "3.1.4", + "schema_version": "1", + "server_package": "@modelcontextprotocol/server", + "server_version": "2.0.0" +} diff --git a/release/evidence/user-risk-acceptance.json b/release/evidence/user-risk-acceptance.json new file mode 100644 index 00000000..51f72bde --- /dev/null +++ b/release/evidence/user-risk-acceptance.json @@ -0,0 +1,26 @@ +{ + "acceptance_text": "go ahead and move forward. This isn't used in production/local only and only with my own agents", + "accepted_on": "2026-07-27", + "advisory_ids": [ + "GHSA-4c8g-83qw-93j6", + "GHSA-q3j6-qgpj-74h6", + "GHSA-v2hh-gcrm-f6hx", + "GHSA-v39h-62p7-jpjc" + ], + "package_name": "fast-uri", + "package_version": "3.1.0", + "record_type": "user-risk-acceptance", + "schema_version": "1", + "scope": { + "deployment": "local-only", + "handler_authority": "inert-no-handler", + "invalidated_by": [ + "bundle-change", + "dependency-change", + "entry-change", + "handler-authority-change" + ], + "operators": "user-owned-agents", + "production": false + } +} diff --git a/release/legal-review.json b/release/legal-review.json new file mode 100644 index 00000000..3741c936 --- /dev/null +++ b/release/legal-review.json @@ -0,0 +1,462 @@ +{ + "amendments": [], + "current_components": [ + { + "component_id": "ajv-embedded", + "legal_source": { + "digest": "a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3", + "payload_path": "legal/upstream/ajv-8.18.0/LICENSE", + "source_path": "release/legal/upstream/ajv-8.18.0/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "tarball_url": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz" + }, + "package_name": "ajv", + "package_version": "8.18.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "ajv/lib" + }, + { + "component_id": "ajv-formats-embedded", + "legal_source": { + "digest": "9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf", + "payload_path": "legal/upstream/ajv-formats-3.0.1/LICENSE", + "source_path": "release/legal/upstream/ajv-formats-3.0.1/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "tarball_url": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz" + }, + "package_name": "ajv-formats", + "package_version": "3.0.1", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "ajv-formats/src" + }, + { + "component_id": "content-type-embedded", + "legal_source": { + "digest": "257aed98914108e91a337912727b6a802eef218248507f74b76faffaff517a38", + "payload_path": "legal/upstream/content-type-1.0.5/LICENSE", + "source_path": "release/legal/upstream/content-type-1.0.5/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "tarball_url": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz" + }, + "package_name": "content-type", + "package_version": "1.0.5", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/src-CX2iR2pK.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "content-type" + }, + { + "component_id": "fast-deep-equal-embedded", + "legal_source": { + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "payload_path": "legal/upstream/fast-deep-equal-3.1.3/LICENSE", + "source_path": "release/legal/upstream/fast-deep-equal-3.1.3/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "tarball_url": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" + }, + "package_name": "fast-deep-equal", + "package_version": "3.1.3", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "fast-deep-equal" + }, + { + "component_id": "fast-uri-embedded", + "legal_source": { + "digest": "185ef4f377743572c2bf0931f741fae52401268cbe70c880b74063799814083e", + "payload_path": "legal/upstream/fast-uri-3.1.0/LICENSE", + "source_path": "release/legal/upstream/fast-uri-3.1.0/LICENSE" + }, + "license_expression": "BSD-3-Clause", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "tarball_url": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz" + }, + "package_name": "fast-uri", + "package_version": "3.1.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "fast-uri/lib" + }, + { + "component_id": "json-schema-traverse-embedded", + "legal_source": { + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "payload_path": "legal/upstream/json-schema-traverse-1.0.0/LICENSE", + "source_path": "release/legal/upstream/json-schema-traverse-1.0.0/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "tarball_url": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz" + }, + "package_name": "json-schema-traverse", + "package_version": "1.0.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + } + ], + "provenance_kind": "embedded", + "source_map_expected": true, + "source_root": "json-schema-traverse" + }, + { + "component_id": "modelcontextprotocol-core-installed", + "legal_source": { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "payload_path": "legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE", + "source_path": "release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE" + }, + "license_expression": "Apache-2.0 AND MIT", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", + "tarball_url": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz" + }, + "package_name": "@modelcontextprotocol/core", + "package_version": "2.0.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "LICENSE", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "dist/auth-CUe6YdwF.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/core", + "package_relative_path": "package.json", + "package_version": "2.0.0" + } + ], + "provenance_kind": "installed", + "source_map_expected": true, + "source_root": "dist" + }, + { + "component_id": "modelcontextprotocol-server-installed", + "legal_source": { + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "payload_path": "legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE", + "source_path": "release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE" + }, + "license_expression": "Apache-2.0 AND MIT", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==", + "tarball_url": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz" + }, + "package_name": "@modelcontextprotocol/server", + "package_version": "2.0.0", + "provenance_inputs": [ + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "LICENSE", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/ajvProvider-CEoC__sr.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/dialects-DoSzNhcb.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/mcp-DXXb3Vv3.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "dist/src-CX2iR2pK.mjs.map", + "package_version": "2.0.0" + }, + { + "package_name": "@modelcontextprotocol/server", + "package_relative_path": "package.json", + "package_version": "2.0.0" + } + ], + "provenance_kind": "installed", + "source_map_expected": true, + "source_root": "dist" + }, + { + "component_id": "zod-installed", + "legal_source": { + "digest": "3f1189b28e3866e0d979968d466b78f813f76827cfdca1fbb124cc0a5c8841f8", + "payload_path": "legal/upstream/zod-4.4.3/LICENSE", + "source_path": "release/legal/upstream/zod-4.4.3/LICENSE" + }, + "license_expression": "MIT", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "tarball_url": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz" + }, + "package_name": "zod", + "package_version": "4.4.3", + "provenance_inputs": [ + { + "package_name": "zod", + "package_relative_path": "LICENSE", + "package_version": "4.4.3" + }, + { + "package_name": "zod", + "package_relative_path": "package.json", + "package_version": "4.4.3" + } + ], + "provenance_kind": "installed", + "source_map_expected": false, + "source_root": "v4" + } + ], + "dependency_gate_decisions": [ + { + "advisories": [ + { + "affected_version": "3.1.0", + "id": "GHSA-4c8g-83qw-93j6", + "safe_version": "3.1.3", + "severity": "high" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-q3j6-qgpj-74h6", + "safe_version": "3.1.1", + "severity": "high" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-v2hh-gcrm-f6hx", + "safe_version": "3.1.4", + "severity": "high" + }, + { + "affected_version": "3.1.0", + "id": "GHSA-v39h-62p7-jpjc", + "safe_version": "3.1.2", + "severity": "high" + } + ], + "advisory_snapshot": { + "digest": "6282adc7c1d1304f245ff5877a2824b05b53f9842dc658282610c981505f0caf", + "path": "release/evidence/advisory-snapshot.json" + }, + "bundle_digest": "16faf6365bc502ec0c0e00f150b43c300e65dfa9dcace1cce3d98d850b8cbbd0", + "decision_digest": "37aa73ae5cd3da88860c0dad199308a103e9120699a2f52f47ee31d7f5a71358", + "dependency_inventory_digest": "1f93c687b91691f3afb99d657246504a9b369311333ecd4e8c77abab1a23c046", + "entry_bindings": [ + { + "handler_authority": "inert-no-handler", + "id": "mcp-stdio", + "role": "mcp-stdio" + } + ], + "id": "fast-uri-3-1-0-local-risk", + "package_name": "fast-uri", + "package_version": "3.1.0", + "patched_artifact_availability": { + "digest": "deb867f4b505da598ea0bf483ae6ecdb116460ebac573489d7763c720ad55ee1", + "path": "release/evidence/patched-artifact-availability.json" + }, + "reachability_evidence": { + "digest": "cac675f0183bfaa2e44707c4be9e93d156c9a695bef61177f305145995165007", + "path": "release/evidence/focused-inert-reachability.json" + }, + "scope": { + "deployment": "local-only", + "handler_authority": "inert-no-handler", + "invalidated_by": [ + "bundle-change", + "dependency-change", + "entry-change", + "handler-authority-change" + ], + "operators": "user-owned-agents", + "production": false + }, + "status": "accepted", + "user_acceptance": { + "digest": "d625ac9d722a8710bb8b0f18f69207df9434953584393a80e5f66d9e2fa0122f", + "path": "release/evidence/user-risk-acceptance.json" + } + } + ], + "distribution_status": "unresolved", + "inventory_method": "conservative-mapped-component-inventory", + "limitations": [ + "AJV JSON sources may be absent from source-map source content.", + "Embedded component inventory does not claim exact physical-byte attribution or composed source-map ranges.", + "This repository has no project license and this receipt makes no first-party license grant." + ], + "project_license_status": "missing", + "schema_version": "1", + "supersessions": [], + "upstream_legal_sources": [ + { + "component_id": "ajv-embedded", + "digest": "a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "tarball_url": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz" + }, + "payload_path": "legal/upstream/ajv-8.18.0/LICENSE", + "source_path": "release/legal/upstream/ajv-8.18.0/LICENSE" + }, + { + "component_id": "ajv-formats-embedded", + "digest": "9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "tarball_url": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz" + }, + "payload_path": "legal/upstream/ajv-formats-3.0.1/LICENSE", + "source_path": "release/legal/upstream/ajv-formats-3.0.1/LICENSE" + }, + { + "component_id": "content-type-embedded", + "digest": "257aed98914108e91a337912727b6a802eef218248507f74b76faffaff517a38", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "tarball_url": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz" + }, + "payload_path": "legal/upstream/content-type-1.0.5/LICENSE", + "source_path": "release/legal/upstream/content-type-1.0.5/LICENSE" + }, + { + "component_id": "fast-deep-equal-embedded", + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "tarball_url": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" + }, + "payload_path": "legal/upstream/fast-deep-equal-3.1.3/LICENSE", + "source_path": "release/legal/upstream/fast-deep-equal-3.1.3/LICENSE" + }, + { + "component_id": "fast-uri-embedded", + "digest": "185ef4f377743572c2bf0931f741fae52401268cbe70c880b74063799814083e", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "tarball_url": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz" + }, + "payload_path": "legal/upstream/fast-uri-3.1.0/LICENSE", + "source_path": "release/legal/upstream/fast-uri-3.1.0/LICENSE" + }, + { + "component_id": "json-schema-traverse-embedded", + "digest": "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a", + "package_identity": { + "authority": "npm-registry-artifact", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "tarball_url": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz" + }, + "payload_path": "legal/upstream/json-schema-traverse-1.0.0/LICENSE", + "source_path": "release/legal/upstream/json-schema-traverse-1.0.0/LICENSE" + }, + { + "component_id": "modelcontextprotocol-core-installed", + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", + "tarball_url": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz" + }, + "payload_path": "legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE", + "source_path": "release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE" + }, + { + "component_id": "modelcontextprotocol-server-installed", + "digest": "0382b0057770ca05e9c350a50aa3b1c1fea84da0bc81d723bf00b9aa841be58a", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==", + "tarball_url": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz" + }, + "payload_path": "legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE", + "source_path": "release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE" + }, + { + "component_id": "zod-installed", + "digest": "3f1189b28e3866e0d979968d466b78f813f76827cfdca1fbb124cc0a5c8841f8", + "package_identity": { + "authority": "package-lock", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "tarball_url": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz" + }, + "payload_path": "legal/upstream/zod-4.4.3/LICENSE", + "source_path": "release/legal/upstream/zod-4.4.3/LICENSE" + } + ] +} diff --git a/release/legal/upstream/ajv-8.18.0/LICENSE b/release/legal/upstream/ajv-8.18.0/LICENSE new file mode 100644 index 00000000..139162ad --- /dev/null +++ b/release/legal/upstream/ajv-8.18.0/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2021 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/release/legal/upstream/ajv-formats-3.0.1/LICENSE b/release/legal/upstream/ajv-formats-3.0.1/LICENSE new file mode 100644 index 00000000..a3f8ba02 --- /dev/null +++ b/release/legal/upstream/ajv-formats-3.0.1/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/release/legal/upstream/content-type-1.0.5/LICENSE b/release/legal/upstream/content-type-1.0.5/LICENSE new file mode 100644 index 00000000..34b1a2de --- /dev/null +++ b/release/legal/upstream/content-type-1.0.5/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/release/legal/upstream/fast-deep-equal-3.1.3/LICENSE b/release/legal/upstream/fast-deep-equal-3.1.3/LICENSE new file mode 100644 index 00000000..7f154356 --- /dev/null +++ b/release/legal/upstream/fast-deep-equal-3.1.3/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/release/legal/upstream/fast-uri-3.1.0/LICENSE b/release/legal/upstream/fast-uri-3.1.0/LICENSE new file mode 100644 index 00000000..a8fe7895 --- /dev/null +++ b/release/legal/upstream/fast-uri-3.1.0/LICENSE @@ -0,0 +1,32 @@ +Copyright (c) 2011-2021, Gary Court until https://github.com/garycourt/uri-js/commit/a1acf730b4bba3f1097c9f52e7d9d3aba8cdcaae +Copyright (c) 2021-present The Fastify team +All rights reserved. + +The Fastify team members are listed at https://github.com/fastify/fastify#team. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: +- https://github.com/garycourt/uri-js/graphs/contributors \ No newline at end of file diff --git a/release/legal/upstream/json-schema-traverse-1.0.0/LICENSE b/release/legal/upstream/json-schema-traverse-1.0.0/LICENSE new file mode 100644 index 00000000..7f154356 --- /dev/null +++ b/release/legal/upstream/json-schema-traverse-1.0.0/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE b/release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE new file mode 100644 index 00000000..4a939857 --- /dev/null +++ b/release/legal/upstream/modelcontextprotocol-core-2.0.0/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE b/release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE new file mode 100644 index 00000000..4a939857 --- /dev/null +++ b/release/legal/upstream/modelcontextprotocol-server-2.0.0/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/release/legal/upstream/zod-4.4.3/LICENSE b/release/legal/upstream/zod-4.4.3/LICENSE new file mode 100644 index 00000000..c0657962 --- /dev/null +++ b/release/legal/upstream/zod-4.4.3/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Colin McDonnell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/scripts/build-release.mjs b/scripts/build-release.mjs new file mode 100644 index 00000000..18e3cab1 --- /dev/null +++ b/scripts/build-release.mjs @@ -0,0 +1,20 @@ +import { fileURLToPath } from "node:url"; +import { resolve } from "node:path"; + +import { + buildReleasePayload, + parseCli, + runCli, + writeCanonicalSummary, +} from "./release-support.mjs"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); + +runCli(async () => { + const { stageRoot } = parseCli(process.argv.slice(2), { + "--output": "stageRoot", + required: ["stageRoot"], + usage: "npm run release:stage -- --output ", + }); + writeCanonicalSummary(await buildReleasePayload({ repositoryRoot, stageRoot })); +}); diff --git a/scripts/check-release.mjs b/scripts/check-release.mjs new file mode 100644 index 00000000..e606d849 --- /dev/null +++ b/scripts/check-release.mjs @@ -0,0 +1,21 @@ +import { fileURLToPath } from "node:url"; +import { resolve } from "node:path"; + +import { + checkReleasePayload, + parseCli, + runCli, + writeCanonicalSummary, +} from "./release-support.mjs"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); + +runCli(async () => { + const options = parseCli(process.argv.slice(2), { + "--payload": "payloadRoot", + "--compare": "comparisonRoot", + required: ["payloadRoot"], + usage: "npm run release:check -- --payload [--compare ]", + }); + writeCanonicalSummary(await checkReleasePayload({ repositoryRoot, ...options })); +}); diff --git a/scripts/release-support.mjs b/scripts/release-support.mjs new file mode 100644 index 00000000..f2f8719a --- /dev/null +++ b/scripts/release-support.mjs @@ -0,0 +1,1536 @@ +import { createHash } from "node:crypto"; +import { execFile } from "node:child_process"; +import { + access, + cp, + lstat, + mkdir, + mkdtemp, + open, + readFile, + readdir, + realpath, + rename, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { + dirname, + basename, + isAbsolute, + parse, + relative, + resolve, + sep, +} from "node:path"; +import { isDeepStrictEqual, promisify } from "node:util"; + +import Ajv2020 from "ajv/dist/2020.js"; +import addFormats from "ajv-formats"; +import { build } from "esbuild"; +import { LanguageVariant, SyntaxKind, createScanner } from "typescript/unstable/ast"; + +const execFileAsync = promisify(execFile); +const encoder = new TextEncoder(); +const decoder = new TextDecoder("utf-8", { fatal: true }); +const DIST_TRANSACTION = Object.freeze({ + marker: ".archflow-dist-transaction.json", + markerTemporary: ".archflow-dist-transaction.tmp", + promotion: ".archflow-dist-promotion", + backup: ".archflow-dist-backup", +}); + +export const RELEASE_FILES = Object.freeze([ + "archflow-mcp.mjs", + "legal/THIRD_PARTY_NOTICES.md", + "legal/review.json", + "manifest.json", + "metafile.json", +]); + +export const RELEASE_BUILD_PROFILE = Object.freeze({ + entry: "src/main.ts", + output: "archflow-mcp.mjs", + platform: "node", + format: "esm", + target: "node24", + bundle: true, + splitting: false, + minify: false, + sourcemap: false, + legalComments: "none", + banner: + 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);', + tsconfigRaw: Object.freeze({ compilerOptions: Object.freeze({}) }), + allowedImports: Object.freeze([ + "node:buffer", + "node:crypto", + "node:module", + "node:process", + "node:util", + ]), +}); + +const PROOF_INPUTS = Object.freeze([ + ".github/workflows/ci.yml", + "package.json", + "scripts/smoke-release-bundle.mjs", + "scripts/test-release-integrity.mjs", + "test/fixtures/mcp/runtime/adversarial-bytes.json", + "test/fixtures/mcp/runtime/calls.json", + "test/fixtures/mcp/runtime/initialize.json", + "test/fixtures/release/hostile-runtime-guard.cjs", + "test/integration/mcp-stdio.test.ts", + "test/integration/release-offline.test.ts", +]); +const LAUNCH_FIXTURES = Object.freeze([ + "test/fixtures/mcp/runtime/adversarial-bytes.json", + "test/fixtures/mcp/runtime/calls.json", + "test/fixtures/mcp/runtime/initialize.json", +]); + +const REQUIRED_CONTROLS = Object.freeze([ + ".gitattributes", + ".github/workflows/ci.yml", + "package-lock.json", + "package.json", + "scripts/build-release.mjs", + "scripts/check-release.mjs", + "scripts/release-support.mjs", + "scripts/reproduce-release.mjs", + "scripts/smoke-release-bundle.mjs", + "scripts/test-release-integrity.mjs", + "scripts/write-tracked-release.mjs", + "src/contracts/schemas/v1/release-legal-review.schema.json", + "src/contracts/schemas/v1/release-manifest.schema.json", + "src/contracts/versions.ts", + "test/contracts/release-contracts.test.ts", + "test/contracts/schema-registry.test.ts", + "test/fixtures/mcp/runtime/adversarial-bytes.json", + "test/fixtures/mcp/runtime/calls.json", + "test/fixtures/mcp/runtime/initialize.json", + "test/fixtures/release/hostile-runtime-guard.cjs", + "test/integration/mcp-stdio.test.ts", + "test/integration/release-offline.test.ts", +]); + +const DECLARED_ASSETS = Object.freeze([ + "assets/constitution/00-process.md", + "assets/constitution/10-architecture.md", + "assets/constitution/20-data.md", + "assets/constitution/30-product.md", + "assets/constitution/README.md", + "assets/workflow.yaml", +]); + +const KNOWN_EMBEDDED = new Map([ + ["ajv", "8.18.0"], + ["ajv-formats", "3.0.1"], + ["content-type", "1.0.5"], + ["fast-deep-equal", "3.1.3"], + ["fast-uri", "3.1.0"], + ["json-schema-traverse", "1.0.0"], +]); +const KNOWN_EMBEDDED_IDENTITIES = new Map([ + ["ajv@8.18.0", ["https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", "a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3"]], + ["ajv-formats@3.0.1", ["https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", "9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf"]], + ["content-type@1.0.5", ["https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", "257aed98914108e91a337912727b6a802eef218248507f74b76faffaff517a38"]], + ["fast-deep-equal@3.1.3", ["https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]], + ["fast-uri@3.1.0", ["https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", "185ef4f377743572c2bf0931f741fae52401268cbe70c880b74063799814083e"]], + ["json-schema-traverse@1.0.0", ["https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]], +]); + +function invariant(condition, message) { + if (!condition) throw new Error(message); +} + +export function assertReleaseLoaderPolicy(source) { + invariant(typeof source === "string", "release loader policy requires JavaScript source"); + invariant(source.startsWith(RELEASE_BUILD_PROFILE.banner), "release bundle is missing the exact createRequire banner"); + const remainder = source.slice(RELEASE_BUILD_PROFILE.banner.length); + const scanner = createScanner(true, LanguageVariant.Standard, remainder); + const forbidden = []; + let previous = SyntaxKind.Unknown; + let previousText = ""; + let previousEnd = -1; + const templateBraces = []; + for (let token = scanner.scan(); token !== SyntaxKind.EndOfFile; token = scanner.scan()) { + if (token === SyntaxKind.SlashToken && ( + previous === SyntaxKind.Unknown + || ["=", "(", "[", "{", ",", ":", ";", "return", "=>", "case", "throw", "else", "do", "typeof", "void", "delete", "in", "of", "!", "&&", "||", "??", "?"].includes(previousText) + )) token = scanner.reScanSlashToken(); + const tokenEnd = scanner.getTokenEnd(); + invariant(tokenEnd > previousEnd, `release loader scanner made no progress at byte ${scanner.getTokenStart()}`); + previousEnd = tokenEnd; + const text = scanner.getTokenText(); + if (token === SyntaxKind.OpenParenToken && previous === SyntaxKind.ImportKeyword) forbidden.push("dynamic import"); + if (text === "require" || text.startsWith("__require") || text === "createRequire" || text === "getBuiltinModule") { + forbidden.push(text); + } + if (token === SyntaxKind.TemplateHead) templateBraces.push(0); + else if (templateBraces.length > 0 && token === SyntaxKind.OpenBraceToken) { + templateBraces[templateBraces.length - 1] += 1; + } else if (templateBraces.length > 0 && token === SyntaxKind.CloseBraceToken) { + const index = templateBraces.length - 1; + if (templateBraces[index] > 0) templateBraces[index] -= 1; + else { + const templateToken = scanner.reScanTemplateToken(false); + invariant(scanner.getTokenEnd() > previousEnd, `release loader template scanner made no progress at byte ${scanner.getTokenStart()}`); + previousEnd = scanner.getTokenEnd(); + if (templateToken === SyntaxKind.TemplateTail) templateBraces.pop(); + previous = templateToken; + previousText = scanner.getTokenText(); + continue; + } + } + previous = token; + previousText = text; + } + invariant(forbidden.length === 0, `residual runtime loader is forbidden: ${[...new Set(forbidden)].join(", ")}`); +} + +function ordinal(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +export function sha256(bytes) { + return createHash("sha256").update(bytes).digest("hex"); +} + +function sortCanonical(value) { + if (Array.isArray(value)) return value.map(sortCanonical); + if (value && typeof value === "object") { + return Object.fromEntries( + Object.keys(value) + .sort(ordinal) + .map((key) => [key, sortCanonical(value[key])]), + ); + } + invariant(value !== undefined, "canonical JSON cannot contain undefined"); + invariant( + typeof value !== "number" || Number.isFinite(value), + "canonical JSON cannot contain a non-finite number", + ); + return value; +} + +export function canonicalJsonBytes(value) { + return encoder.encode(`${JSON.stringify(sortCanonical(value), null, 2)}\n`); +} + +export function canonicalDocument(value) { + const bytes = canonicalJsonBytes(value); + return Object.freeze({ bytes, value: Object.freeze(value), digest: sha256(bytes) }); +} + +export function parseCanonicalDocument(bytes, description = "JSON document") { + invariant(bytes instanceof Uint8Array, `${description} must be bytes`); + let value; + try { + value = JSON.parse(decoder.decode(bytes)); + } catch (error) { + throw new Error(`${description} is not valid UTF-8 JSON: ${error.message}`); + } + const expected = canonicalJsonBytes(value); + invariant( + Buffer.from(bytes).equals(Buffer.from(expected)), + `${description} is not canonical JSON`, + ); + return Object.freeze({ bytes, value: Object.freeze(value), digest: sha256(bytes) }); +} + +export function assertPortablePath(value, description = "path") { + invariant(typeof value === "string" && value.length > 0, `${description} must be non-empty`); + invariant(!value.includes("\\"), `${description} must use forward slashes`); + invariant(!value.startsWith("/") && !value.startsWith("//"), `${description} must be relative`); + invariant(!/^[A-Za-z]:/.test(value), `${description} must not be drive-qualified`); + const segments = value.split("/"); + invariant( + segments.every((segment) => segment !== "" && segment !== "." && segment !== ".."), + `${description} contains an unsafe segment`, + ); + return value; +} + +function isInside(root, candidate) { + const rel = relative(root, candidate); + return rel !== "" && !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel); +} + +async function assertNoSymlinkTraversal(path, { allowMissingLeaf = false } = {}) { + const absolute = resolve(path); + const root = parse(absolute).root; + invariant(absolute !== root, "filesystem roots are not valid release roots"); + const segments = relative(root, absolute).split(sep); + let cursor = root; + for (let index = 0; index < segments.length; index += 1) { + cursor = resolve(cursor, segments[index]); + let info; + try { + info = await lstat(cursor); + } catch (error) { + if (error.code === "ENOENT" && allowMissingLeaf && index === segments.length - 1) return; + throw error; + } + invariant(!info.isSymbolicLink(), `symlink traversal is forbidden: ${cursor}`); + if (index < segments.length - 1) invariant(info.isDirectory(), `non-directory ancestor: ${cursor}`); + } +} + +async function canonicalExistingDirectory(path, description) { + invariant(typeof path === "string" && isAbsolute(path), `${description} must be absolute`); + const absolute = resolve(path); + await assertNoSymlinkTraversal(absolute); + const info = await lstat(absolute); + invariant(info.isDirectory(), `${description} must be a directory`); + return realpath(absolute); +} + +async function prepareEmptyRoot(path, description, otherRoots) { + invariant(typeof path === "string" && isAbsolute(path), `${description} must be absolute`); + const absolute = resolve(path); + await assertNoSymlinkTraversal(dirname(absolute)); + let exists = true; + try { + const info = await lstat(absolute); + invariant(!info.isSymbolicLink() && info.isDirectory(), `${description} must be a directory`); + invariant((await readdir(absolute)).length === 0, `${description} must be empty`); + } catch (error) { + if (error.code !== "ENOENT") throw error; + exists = false; + } + if (!exists) await mkdir(absolute); + const canonical = await realpath(absolute); + invariant(canonical !== parse(canonical).root, `${description} cannot be a filesystem root`); + for (const [otherName, otherRoot] of otherRoots) { + invariant( + canonical !== otherRoot && !isInside(canonical, otherRoot) && !isInside(otherRoot, canonical), + `${description} overlaps ${otherName}`, + ); + } + return canonical; +} + +async function canonicalDedicatedRootCandidate(path, description) { + invariant(typeof path === "string" && isAbsolute(path), `${description} must be absolute`); + const absolute = resolve(path); + invariant(absolute !== parse(absolute).root, `${description} cannot be a filesystem root`); + await assertNoSymlinkTraversal(dirname(absolute)); + try { + const info = await lstat(absolute); + invariant(!info.isSymbolicLink() && info.isDirectory(), `${description} must be a directory`); + invariant((await readdir(absolute)).length === 0, `${description} must be empty`); + return realpath(absolute); + } catch (error) { + if (error.code !== "ENOENT") throw error; + return resolve(await realpath(dirname(absolute)), basename(absolute)); + } +} + +function assertRootsPairwiseNonOverlapping(roots) { + for (let left = 0; left < roots.length; left += 1) { + for (let right = left + 1; right < roots.length; right += 1) { + const [leftName, leftRoot] = roots[left]; + const [rightName, rightRoot] = roots[right]; + invariant( + leftRoot !== rightRoot && !isInside(leftRoot, rightRoot) && !isInside(rightRoot, leftRoot), + `${leftName} overlaps ${rightName}`, + ); + } + } +} + +async function readRegularFile(root, portablePath, description = portablePath) { + assertPortablePath(portablePath, description); + const absolute = resolve(root, ...portablePath.split("/")); + invariant(isInside(root, absolute), `${description} escapes its root`); + await assertNoSymlinkTraversal(absolute); + const info = await lstat(absolute); + invariant(info.isFile(), `${description} must be a regular file`); + return readFile(absolute); +} + +async function walkRegularFiles(root, prefix = "") { + const directory = prefix ? resolve(root, ...prefix.split("/")) : root; + const entries = await readdir(directory, { withFileTypes: true }); + const files = []; + for (const entry of entries.sort((a, b) => ordinal(a.name, b.name))) { + const path = prefix ? `${prefix}/${entry.name}` : entry.name; + invariant(!entry.isSymbolicLink(), `symlinks are forbidden in release trees: ${path}`); + if (entry.isDirectory()) files.push(...(await walkRegularFiles(root, path))); + else { + invariant(entry.isFile(), `non-regular file in release tree: ${path}`); + files.push(path); + } + } + return files; +} + +async function fileRecord(root, path) { + const bytes = await readRegularFile(root, path); + return Object.freeze({ path, size: bytes.byteLength, digest: sha256(bytes) }); +} + +async function collectDeclaredPaths(repositoryRoot) { + const schemas = (await readdir(resolve(repositoryRoot, "src/contracts/schemas/v1"))) + .filter((name) => name.endsWith(".schema.json")) + .map((name) => `src/contracts/schemas/v1/${name}`); + return [...schemas, ...DECLARED_ASSETS].sort(ordinal); +} + +async function collectLegalSourcePaths(repositoryRoot) { + const paths = ["release/legal-review.json"]; + const root = resolve(repositoryRoot, "release/legal/upstream"); + try { + for (const path of await walkRegularFiles(root)) paths.push(`release/legal/upstream/${path}`); + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + return paths; +} + +async function collectEvidencePaths(repositoryRoot) { + const root = resolve(repositoryRoot, "release/evidence"); + try { + return (await walkRegularFiles(root)).map((path) => `release/evidence/${path}`).sort(ordinal); + } catch (error) { + if (error.code === "ENOENT") return []; + throw error; + } +} + +async function deriveLaunchProfile(repositoryRoot) { + return { + node_major: 24, + executable: "process.execPath", + argv: ["--require", "hostile-runtime-guard.cjs", "archflow-mcp.mjs"], + environment_keys: ["HOME", "LANG", "LC_ALL", "NPM_CONFIG_CACHE", "PATH", "TMPDIR", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME"], + removed_environment_keys: ["NODE_OPTIONS", "NODE_PATH"], + cwd_class: "copied-payload", + stdio: { stdin: "pipe", stdout: "pipe", stderr: "pipe", guard_fd: 3 }, + guard_path: "test/fixtures/release/hostile-runtime-guard.cjs", + canary_paths: ["ambient/node_modules/archflow-release-canary/index.js", "repository-canary/SECRET"], + fixture_digests: await Promise.all(LAUNCH_FIXTURES.map(async (path) => ({ + path, + digest: sha256(await readRegularFile(repositoryRoot, path)), + }))), + allowed_imports: [...RELEASE_BUILD_PROFILE.allowedImports], + }; +} + +function packageIdentity(inputPath) { + const match = inputPath.match(/^node_modules\/((?:@[^/]+\/)?[^/]+)\/(.+)$/); + return match ? { packageName: match[1], packagePath: match[2] } : undefined; +} + +async function readPackageVersion(repositoryRoot, packageName) { + const bytes = await readRegularFile(repositoryRoot, `node_modules/${packageName}/package.json`); + const value = JSON.parse(decoder.decode(bytes)); + invariant(value.name === packageName && typeof value.version === "string", `invalid package identity: ${packageName}`); + return value.version; +} + +async function collectDependencyProvenance(repositoryRoot, metafile, contributing) { + const records = new Map(); + const embedded = new Map(); + const expectations = []; + const packageNames = new Set(); + for (const path of contributing) { + const identity = packageIdentity(path); + if (!identity) continue; + packageNames.add(identity.packageName); + if (!path.endsWith(".mjs")) continue; + const mapPath = `${path}.map`; + let mapBytes; + try { + mapBytes = await readRegularFile(repositoryRoot, mapPath); + } catch (error) { + if (error.code === "ENOENT") { + invariant( + path === "node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs", + `missing adjacent source map has no reviewed expected-absent disposition: ${path}`, + ); + expectations.push({ + input_key: path, + expectation: "expected-absent", + rationale: "The reviewed SDK bridge chunk has no published adjacent source map in @modelcontextprotocol/server@2.0.0.", + }); + continue; + } + throw error; + } + const mapIdentity = packageIdentity(mapPath); + const version = await readPackageVersion(repositoryRoot, mapIdentity.packageName); + records.set(`${mapIdentity.packageName}:${mapIdentity.packagePath}`, { + package_name: mapIdentity.packageName, + package_version: version, + package_relative_path: mapIdentity.packagePath, + size: mapBytes.byteLength, + digest: sha256(mapBytes), + purpose: "source-map", + }); + const sourceMap = JSON.parse(decoder.decode(mapBytes)); + const reviewedRoots = new Set(); + const recognizedComponents = new Set(); + for (const source of sourceMap.sources ?? []) { + const match = source.match(/\.pnpm\/((?:@[^/]+\/)?[^@/]+)@([^/]+)\/node_modules\/((?:@[^/]+\/)?[^/]+)/); + if (match) { + const name = match[3]; + const versionWithoutPeer = match[2].split("_")[0]; + invariant(KNOWN_EMBEDDED.get(name) === versionWithoutPeer, `unknown mapped component: ${name}@${versionWithoutPeer}`); + embedded.set(name, versionWithoutPeer); + recognizedComponents.add(`${name}@${versionWithoutPeer}`); + continue; + } + const firstParty = source.match(/^((?:\.\.\/)+(?:core-internal\/)?src)\//); + invariant(firstParty, `unreviewed source-map source path: ${source}`); + reviewedRoots.add(firstParty[1]); + } + expectations.push({ + input_key: path, + expectation: "present", + map: { + package_name: mapIdentity.packageName, + package_version: version, + package_relative_path: mapIdentity.packagePath, + digest: sha256(mapBytes), + }, + reviewed_first_party_roots: [...reviewedRoots].sort(ordinal), + recognized_third_party_components: [...recognizedComponents].sort(ordinal), + }); + } + for (const [name, version] of KNOWN_EMBEDDED) { + invariant(embedded.get(name) === version, `missing mapped component: ${name}@${version}`); + } + for (const packageName of packageNames) { + const packageRoot = `node_modules/${packageName}`; + const version = await readPackageVersion(repositoryRoot, packageName); + for (const packagePath of ["package.json", "LICENSE", "NOTICE"]) { + try { + const bytes = await readRegularFile(repositoryRoot, `${packageRoot}/${packagePath}`); + records.set(`${packageName}:${packagePath}`, { + package_name: packageName, + package_version: version, + package_relative_path: packagePath, + size: bytes.byteLength, + digest: sha256(bytes), + purpose: packagePath === "package.json" ? "package-manifest" : packagePath === "NOTICE" ? "notice" : "license", + }); + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + } + } + return { + records: [...records.values()].sort((a, b) => + ordinal(`${a.package_name}/${a.package_relative_path}`, `${b.package_name}/${b.package_relative_path}`), + ), + expectations: expectations.sort((a, b) => ordinal(a.input_key, b.input_key)), + embedded, + }; +} + +function legalProjection(review) { + const components = review.current_components ?? []; + const lines = [ + "# Third-Party Notices", + "", + "This generated inventory accompanies the offline ArchFlow MCP payload.", + "It does not grant a license to ArchFlow itself.", + "", + ]; + for (const component of components) { + const name = component.package_name; + const version = component.package_version; + const license = component.license_expression; + lines.push(`- ${name}@${version} — ${license}`); + } + lines.push("", "See legal/upstream/ for retained applicable upstream license and notice texts.", ""); + return encoder.encode(lines.join("\n")); +} + +async function loadSchemaValidators(repositoryRoot) { + const schemaDirectory = resolve(repositoryRoot, "src/contracts/schemas/v1"); + const ajv = new Ajv2020({ allErrors: true, strict: true }); + addFormats(ajv); + ajv.addKeyword({ + keyword: "x-archflow-sorted-unique", + schemaType: "boolean", + metaSchema: { const: true }, + type: "array", + errors: false, + validate: (_enabled, data) => data.every((value, index) => index === 0 || data[index - 1] < value), + }); + ajv.addKeyword({ + keyword: "x-archflow-unique-by", + schemaType: ["string", "array"], + metaSchema: { + oneOf: [ + { type: "string", minLength: 1 }, + { type: "array", minItems: 1, uniqueItems: true, items: { type: "string", minLength: 1 } }, + ], + }, + type: "array", + errors: false, + validate: (properties, data) => { + const names = typeof properties === "string" ? [properties] : properties; + const values = data.map((item) => names.map((name) => item?.[name])); + return values.every((value, index) => values.slice(0, index).every((prior) => !isDeepStrictEqual(prior, value))); + }, + }); + const manifestSchema = JSON.parse(await readFile(resolve(schemaDirectory, "release-manifest.schema.json"), "utf8")); + const legalSchema = JSON.parse(await readFile(resolve(schemaDirectory, "release-legal-review.schema.json"), "utf8")); + ajv.addSchema(manifestSchema); + ajv.addSchema(legalSchema); + return { + manifest: ajv.getSchema(manifestSchema.$id) ?? ajv.compile(manifestSchema), + legal: ajv.getSchema(legalSchema.$id) ?? ajv.compile(legalSchema), + evidence: { + "advisory-snapshot": ajv.getSchema(`${legalSchema.$id}#/$defs/advisory_snapshot_record`), + "patched-artifact-availability": ajv.getSchema(`${legalSchema.$id}#/$defs/artifact_availability_record`), + "focused-inert-reachability": ajv.getSchema(`${legalSchema.$id}#/$defs/reachability_record`), + "user-risk-acceptance": ajv.getSchema(`${legalSchema.$id}#/$defs/user_acceptance_record`), + }, + }; +} + +function schemaAssert(validator, value, description) { + invariant(validator(value), `${description} schema validation failed: ${JSON.stringify(validator.errors)}`); +} + +function recordPaths(records) { + return records.map((record) => record.path); +} + +function assertSortedUnique(values, description) { + const sorted = [...values].sort(ordinal); + invariant(new Set(values).size === values.length, `${description} contains duplicates`); + invariant(values.every((value, index) => value === sorted[index]), `${description} is not sorted`); +} + +async function assertRecords(repositoryRoot, records, description) { + assertSortedUnique(recordPaths(records), description); + for (const record of records) { + assertPortablePath(record.path, `${description} path`); + const bytes = await readRegularFile(repositoryRoot, record.path); + invariant(record.size === bytes.byteLength && record.digest === sha256(bytes), `${description} record is stale: ${record.path}`); + } +} + +async function verifyDependencyRecords(repositoryRoot, records) { + const keys = records.map((record) => `${record.package_name}@${record.package_version}/${record.package_relative_path}`); + assertSortedUnique(keys, "dependency provenance inputs"); + const versions = new Map(); + for (const record of records) { + assertPortablePath(record.package_relative_path, "dependency package path"); + invariant(typeof record.package_name === "string" && !record.package_name.includes(".."), "invalid package name"); + let version = versions.get(record.package_name); + if (!version) { + version = await readPackageVersion(repositoryRoot, record.package_name); + versions.set(record.package_name, version); + } + invariant(version === record.package_version, `dependency version mismatch: ${record.package_name}`); + const bytes = await readRegularFile( + repositoryRoot, + `node_modules/${record.package_name}/${record.package_relative_path}`, + "dependency provenance input", + ); + invariant(bytes.byteLength === record.size && sha256(bytes) === record.digest, `stale dependency input: ${record.package_name}/${record.package_relative_path}`); + } +} + +async function expectedControls(repositoryRoot, bundleInputs) { + return createControlRecords(repositoryRoot, bundleInputs); +} + +function assertEqualPathSet(actual, expected, description) { + assertSortedUnique(actual, description); + invariant( + actual.length === expected.length && actual.every((path, index) => path === expected[index]), + `${description} is not the exact required set`, + ); +} + +async function validateLegalCorrelation(repositoryRoot, manifestValue, legalValue, ownerPaths, validators) { + invariant(legalValue.project_license_status === "missing" && legalValue.distribution_status === "unresolved", "release must retain unresolved project licensing status"); + const limitationText = legalValue.limitations.join("\n").toLowerCase(); + invariant(limitationText.includes("exact") && limitationText.includes("ajv") && limitationText.includes("json"), "legal limitations must retain attribution and empty-AJV-JSON limitations"); + + const componentIds = legalValue.current_components.map((component) => component.component_id); + assertSortedUnique(componentIds, "current components"); + assertSortedUnique(legalValue.limitations, "legal limitations"); + const decisionIds = legalValue.dependency_gate_decisions.map((decision) => decision.id); + assertSortedUnique(decisionIds, "dependency gate decisions"); + const amendmentIds = legalValue.amendments.map((amendment) => amendment.id); + assertSortedUnique(amendmentIds, "decision amendments"); + const supersessionIds = legalValue.supersessions.map((supersession) => supersession.id); + assertSortedUnique(supersessionIds, "decision supersessions"); + const decisionsById = new Map(legalValue.dependency_gate_decisions.map((decision) => [decision.id, decision])); + for (const amendment of legalValue.amendments) { + invariant(decisionIds.includes(amendment.decision_id), `amendment references an unknown decision: ${amendment.id}`); + invariant(decisionsById.get(amendment.decision_id).decision_digest === amendment.prior_decision_digest, `amendment prior decision digest differs: ${amendment.id}`); + } + for (const supersession of legalValue.supersessions) { + invariant(decisionIds.includes(supersession.superseded_decision_id), `supersession references an unknown prior decision: ${supersession.id}`); + invariant(decisionIds.includes(supersession.replacement_decision_id), `supersession references an unknown replacement: ${supersession.id}`); + invariant(supersession.superseded_decision_id !== supersession.replacement_decision_id, `supersession is self-referential: ${supersession.id}`); + invariant(decisionsById.get(supersession.superseded_decision_id).decision_digest === supersession.superseded_decision_digest, `superseded decision digest differs: ${supersession.id}`); + invariant(decisionsById.get(supersession.replacement_decision_id).decision_digest === supersession.replacement_decision_digest, `replacement decision digest differs: ${supersession.id}`); + } + const replacementByPrior = new Map(); + for (const supersession of legalValue.supersessions) { + invariant(!replacementByPrior.has(supersession.superseded_decision_id), `conflicting supersessions for: ${supersession.superseded_decision_id}`); + replacementByPrior.set(supersession.superseded_decision_id, supersession.replacement_decision_id); + } + for (const start of replacementByPrior.keys()) { + const visited = new Set(); + let cursor = start; + while (replacementByPrior.has(cursor)) { + invariant(!visited.has(cursor), `cyclic supersession graph at: ${cursor}`); + visited.add(cursor); + cursor = replacementByPrior.get(cursor); + } + } + + const provenance = new Set(manifestValue.dependency_provenance_inputs.map((record) => + `${record.package_name}@${record.package_version}/${record.package_relative_path}`, + )); + const embedded = new Map(); + for (const component of legalValue.current_components) { + if (component.provenance_kind === "embedded") embedded.set(component.package_name, component.package_version); + for (const reference of component.provenance_inputs) { + invariant( + provenance.has(`${reference.package_name}@${reference.package_version}/${reference.package_relative_path}`), + `component has unresolved provenance: ${component.component_id}`, + ); + } + } + for (const [name, version] of KNOWN_EMBEDDED) invariant(embedded.get(name) === version, `legal inventory omits embedded ${name}@${version}`); + + const installedKeys = [...new Set(manifestValue.bundle_inputs + .filter((record) => record.origin.kind === "dependency" && record.bytes_in_output > 0) + .map((record) => `${record.origin.package_name}@${record.origin.package_version}`))].sort(ordinal); + const mappedKeys = [...new Set(manifestValue.adjacent_map_expectations.flatMap((expectation) => + expectation.expectation === "present" ? expectation.recognized_third_party_components : [], + ))].sort(ordinal); + const actualInstalled = legalValue.current_components.filter((component) => component.provenance_kind === "installed") + .map((component) => `${component.package_name}@${component.package_version}`).sort(ordinal); + const actualEmbedded = legalValue.current_components.filter((component) => component.provenance_kind === "embedded") + .map((component) => `${component.package_name}@${component.package_version}`).sort(ordinal); + invariant(isDeepStrictEqual(actualInstalled, installedKeys), "installed legal component closure differs from contributing packages"); + invariant(isDeepStrictEqual(actualEmbedded, mappedKeys), "embedded legal component closure differs from mapped packages"); + + const lock = JSON.parse(await readFile(resolve(repositoryRoot, "package-lock.json"), "utf8")); + const upstreamByComponent = new Map(legalValue.upstream_legal_sources.map((source) => [source.component_id, source])); + for (const component of legalValue.current_components) { + const key = `${component.package_name}@${component.package_version}`; + const upstream = upstreamByComponent.get(component.component_id); + invariant(upstream && isDeepStrictEqual(component.legal_source, { + source_path: upstream.source_path, + payload_path: upstream.payload_path, + digest: upstream.digest, + }), `component legal source is not the unique retained source: ${component.component_id}`); + invariant(isDeepStrictEqual(component.package_identity, upstream.package_identity), `component/upstream package identity differs: ${component.component_id}`); + let expectedIdentity; + if (component.provenance_kind === "installed") { + const locked = lock.packages?.[`node_modules/${component.package_name}`]; + invariant(locked?.version === component.package_version, `installed component is absent from package-lock: ${key}`); + expectedIdentity = { authority: "package-lock", tarball_url: locked.resolved, integrity: locked.integrity }; + const installedLicense = manifestValue.dependency_provenance_inputs.find((record) => + record.package_name === component.package_name + && record.package_version === component.package_version + && record.purpose === "license", + ); + invariant(installedLicense?.digest === component.legal_source.digest, `installed legal source differs from installed package bytes: ${key}`); + } else { + const identity = KNOWN_EMBEDDED_IDENTITIES.get(key); + invariant(identity, `embedded package has no immutable reviewed registry identity: ${key}`); + expectedIdentity = { authority: "npm-registry-artifact", tarball_url: identity[0], integrity: identity[1] }; + invariant(component.legal_source.digest === identity[2], `embedded legal source differs from reviewed registry artifact bytes: ${key}`); + } + invariant(isDeepStrictEqual(component.package_identity, expectedIdentity), `package identity differs from immutable authority: ${key}`); + const expectedProvenance = component.provenance_kind === "installed" + ? manifestValue.dependency_provenance_inputs.filter((record) => record.package_name === component.package_name && record.package_version === component.package_version) + .map(({ package_name, package_version, package_relative_path }) => ({ package_name, package_version, package_relative_path })) + : manifestValue.adjacent_map_expectations.filter((expectation) => expectation.expectation === "present" && expectation.recognized_third_party_components.includes(key)) + .map((expectation) => ({ + package_name: expectation.map.package_name, + package_version: expectation.map.package_version, + package_relative_path: expectation.map.package_relative_path, + })); + expectedProvenance.sort((a, b) => ordinal(`${a.package_name}/${a.package_relative_path}`, `${b.package_name}/${b.package_relative_path}`)); + invariant(isDeepStrictEqual(component.provenance_inputs, expectedProvenance), `component provenance is not the exact derived closure: ${component.component_id}`); + invariant(component.source_map_expected === (component.provenance_kind === "embedded" || expectedProvenance.some((record) => record.package_relative_path.endsWith(".map"))), `component source-map expectation differs: ${component.component_id}`); + } + invariant( + upstreamByComponent.size === legalValue.current_components.length + && legalValue.upstream_legal_sources.length === legalValue.current_components.length, + "component-to-upstream legal mapping is not one-to-one", + ); + + const upstreamSourcePaths = []; + const upstreamPayloadPaths = []; + for (const source of legalValue.upstream_legal_sources) { + invariant(componentIds.includes(source.component_id), `upstream legal source references an unknown component: ${source.source_path}`); + invariant(source.source_path.startsWith("release/legal/upstream/"), "upstream source is outside retained legal root"); + invariant(source.payload_path.startsWith("legal/upstream/"), "upstream payload is outside legal closure"); + invariant(source.payload_path === source.source_path.slice("release/".length), "upstream source/output mapping differs"); + const sourceBytes = await readRegularFile(repositoryRoot, source.source_path); + invariant(sha256(sourceBytes) === source.digest, `stale upstream legal source: ${source.source_path}`); + upstreamSourcePaths.push(source.source_path); + upstreamPayloadPaths.push(source.payload_path); + } + const actualUpstream = (await collectLegalSourcePaths(repositoryRoot)).filter((path) => path !== "release/legal-review.json"); + assertEqualPathSet(upstreamSourcePaths, actualUpstream, "upstream legal sources"); + assertSortedUnique(upstreamPayloadPaths, "upstream legal payloads"); + + const entryBindings = manifestValue.build_entries.map(({ id, role, handler_authority }) => ({ id, role, handler_authority })); + const resolveEvidence = async (binding, expectedPath, recordType) => { + invariant(binding.path === expectedPath, `risk evidence path differs: ${recordType}`); + invariant(ownerPaths.has(binding.path), `risk evidence is outside release controls: ${binding.path}`); + const document = parseCanonicalDocument(await readRegularFile(repositoryRoot, binding.path), `risk evidence ${recordType}`); + invariant(document.digest === binding.digest, `risk evidence digest differs: ${binding.path}`); + const validator = validators.evidence[recordType]; + invariant(validator, `missing evidence schema validator: ${recordType}`); + schemaAssert(validator, document.value, `risk evidence ${recordType}`); + return document.value; + }; + for (const decision of legalValue.dependency_gate_decisions) { + invariant(componentIds.some((id) => id.startsWith(`${decision.package_name.replace(/^@/, "").replaceAll("/", "-")}-`) || legalValue.current_components.some((component) => component.package_name === decision.package_name && component.package_version === decision.package_version)), `risk decision references an uninventoried component: ${decision.id}`); + assertSortedUnique(decision.advisories.map((advisory) => advisory.id), `risk decision advisories: ${decision.id}`); + invariant(decision.bundle_digest === manifestValue.bundle_digest, `risk decision bundle binding is stale: ${decision.id}`); + invariant(decision.dependency_inventory_digest === manifestValue.dependency_inventory_digest, `risk decision inventory binding is stale: ${decision.id}`); + invariant(Buffer.from(canonicalJsonBytes(decision.entry_bindings)).equals(Buffer.from(canonicalJsonBytes(entryBindings))), `risk decision entry binding is stale: ${decision.id}`); + invariant(decision.scope.handler_authority === "inert-no-handler", `risk decision handler scope expanded: ${decision.id}`); + const invalidators = ["bundle-change", "dependency-change", "entry-change", "handler-authority-change"]; + invariant(JSON.stringify(decision.scope.invalidated_by) === JSON.stringify(invalidators), `risk decision invalidators are incomplete: ${decision.id}`); + const withoutDigest = { ...decision }; + delete withoutDigest.decision_digest; + invariant(decision.decision_digest === sha256(canonicalJsonBytes(withoutDigest)), `risk decision digest is stale: ${decision.id}`); + const advisorySnapshot = await resolveEvidence(decision.advisory_snapshot, "release/evidence/advisory-snapshot.json", "advisory-snapshot"); + const availability = await resolveEvidence(decision.patched_artifact_availability, "release/evidence/patched-artifact-availability.json", "patched-artifact-availability"); + const reachability = await resolveEvidence(decision.reachability_evidence, "release/evidence/focused-inert-reachability.json", "focused-inert-reachability"); + const acceptance = await resolveEvidence(decision.user_acceptance, "release/evidence/user-risk-acceptance.json", "user-risk-acceptance"); + const snapshotAdvisories = advisorySnapshot.advisories.map(({ source_url: _sourceUrl, ...advisory }) => advisory); + invariant(isDeepStrictEqual(snapshotAdvisories, decision.advisories), `advisory snapshot differs from decision: ${decision.id}`); + invariant(advisorySnapshot.package_name === decision.package_name && advisorySnapshot.package_version === decision.package_version, `advisory snapshot package differs: ${decision.id}`); + invariant(availability.embedded_package === decision.package_name && availability.embedded_version === decision.package_version && availability.compatible_patched_artifact_available === false, `patched-artifact evidence differs: ${decision.id}`); + invariant(reachability.bundle_digest === decision.bundle_digest && isDeepStrictEqual(reachability.entry_bindings, decision.entry_bindings), `reachability evidence binding differs: ${decision.id}`); + invariant(acceptance.package_name === decision.package_name && acceptance.package_version === decision.package_version, `user acceptance package differs: ${decision.id}`); + invariant(isDeepStrictEqual(acceptance.advisory_ids, decision.advisories.map((advisory) => advisory.id)), `user acceptance advisories differ: ${decision.id}`); + invariant(isDeepStrictEqual(acceptance.scope, decision.scope), `user acceptance scope differs: ${decision.id}`); + } + for (const record of [...legalValue.amendments, ...legalValue.supersessions]) { + const binding = record.evidence; + invariant(ownerPaths.has(binding.path), `history evidence is outside release controls: ${binding.path}`); + const document = parseCanonicalDocument(await readRegularFile(repositoryRoot, binding.path), `history evidence ${record.id}`); + invariant(document.digest === binding.digest, `history evidence digest differs: ${record.id}`); + const digestField = "amendment_digest" in record ? "amendment_digest" : "supersession_digest"; + const withoutDigest = { ...record }; + delete withoutDigest[digestField]; + invariant(record[digestField] === sha256(canonicalJsonBytes(withoutDigest)), `history record digest differs: ${record.id}`); + } + const fastUri = legalValue.dependency_gate_decisions.find((decision) => decision.package_name === "fast-uri" && decision.package_version === "3.1.0"); + invariant(fastUri, "accepted fast-uri prototype risk decision is absent"); + const advisories = fastUri.advisories.map((advisory) => advisory.id).sort(); + invariant(JSON.stringify(advisories) === JSON.stringify([ + "GHSA-4c8g-83qw-93j6", + "GHSA-q3j6-qgpj-74h6", + "GHSA-v2hh-gcrm-f6hx", + "GHSA-v39h-62p7-jpjc", + ]), "fast-uri decision does not bind all four advisories"); + invariant(ownerPaths.has("release/legal-review.json"), "legal review source is outside release controls"); +} + +function manifestField(manifest, ...names) { + for (const name of names) if (manifest[name] !== undefined) return manifest[name]; + return undefined; +} + +export async function validateReleaseSemantics({ repositoryRoot, payloadRoot, manifest, legalReview }) { + const repository = await canonicalExistingDirectory(repositoryRoot, "repository root"); + const payload = await canonicalExistingDirectory(payloadRoot, "payload root"); + const trackedPayload = resolve(repository, "dist"); + invariant( + payload === trackedPayload + || (repository !== payload && !isInside(repository, payload) && !isInside(payload, repository)), + "payload root must be the fixed repository dist or outside the repository", + ); + const validators = await loadSchemaValidators(repository); + schemaAssert(validators.manifest, manifest.value, "release manifest"); + schemaAssert(validators.legal, legalReview.value, "release legal review"); + + const bundleInputs = manifestField(manifest.value, "bundle_inputs"); + const controls = manifestField(manifest.value, "release_control_inputs"); + const dependencyInputs = manifestField(manifest.value, "dependency_provenance_inputs"); + const contributing = manifestField(manifest.value, "contributing_inputs"); + const artifacts = manifestField(manifest.value, "artifacts", "generated_artifacts"); + invariant(Array.isArray(bundleInputs) && Array.isArray(controls) && Array.isArray(dependencyInputs), "manifest input collections are required"); + invariant(Array.isArray(contributing) && Array.isArray(artifacts), "manifest closure collections are required"); + assertSortedUnique(bundleInputs.map((record) => record.key), "bundle inputs"); + for (const record of bundleInputs) { + assertPortablePath(record.key, "bundle input key"); + const path = record.origin.kind === "repository" + ? record.origin.path + : `node_modules/${record.origin.package_name}/${record.origin.package_relative_path}`; + invariant(record.key === path, `bundle input key does not identify its physical origin: ${record.key}`); + const bytes = await readRegularFile(repository, path); + invariant(bytes.byteLength === record.size && sha256(bytes) === record.digest, `stale bundle input: ${record.key}`); + } + await assertRecords(repository, controls, "release controls"); + const exactControls = await expectedControls(repository, bundleInputs); + assertEqualPathSet(recordPaths(controls), recordPaths(exactControls), "release controls"); + await verifyDependencyRecords(repository, dependencyInputs); + const owners = [ + ...bundleInputs.filter((record) => record.origin.kind === "repository").map((record) => ({ path: record.origin.path })), + ...controls, + ]; + invariant(new Set(recordPaths(owners)).size === owners.length, "repository inputs have duplicate ownership"); + const ownerPaths = new Set(recordPaths(owners)); + assertEqualPathSet(manifest.value.proof_inputs, [...PROOF_INPUTS], "proof inputs"); + for (const path of manifest.value.proof_inputs) invariant(ownerPaths.has(path), `unresolved proof input: ${path}`); + const declared = manifest.value.declared_content; + const expectedDeclared = await collectDeclaredPaths(repository); + assertEqualPathSet(declared.schemas, expectedDeclared.filter((path) => path.startsWith("src/contracts/schemas/v1/")), "declared schemas"); + invariant(declared.workflow === "assets/workflow.yaml", "declared workflow differs"); + assertEqualPathSet(declared.constitution, expectedDeclared.filter((path) => path.startsWith("assets/constitution/")), "declared constitution"); + for (const path of [...declared.schemas, declared.workflow, ...declared.constitution]) invariant(ownerPaths.has(path), `unresolved declared content: ${path}`); + assertSortedUnique(contributing, "contributing inputs"); + invariant(contributing.every((path) => bundleInputs.some((record) => record.key === path)), "contributing input is not scanned"); + invariant( + contributing.length === bundleInputs.filter((record) => record.bytes_in_output > 0).length + && contributing.every((path) => bundleInputs.find((record) => record.key === path).bytes_in_output > 0), + "contributing inputs do not equal positive-byte bundle inputs", + ); + + const actualFiles = await walkRegularFiles(payload); + const artifactPaths = recordPaths(artifacts); + assertSortedUnique(artifactPaths, "artifacts"); + invariant(actualFiles.length === artifactPaths.length && actualFiles.every((path, index) => path === artifactPaths[index]), "payload closure does not match manifest artifacts"); + for (const artifact of artifacts) { + if (artifact.path === "manifest.json") { + invariant(artifact.role === "manifest" && artifact.size === undefined && artifact.digest === undefined, "manifest self-entry is invalid"); + continue; + } + const bytes = await readRegularFile(payload, artifact.path); + invariant(bytes.byteLength === artifact.size && sha256(bytes) === artifact.digest, `stale payload artifact: ${artifact.path}`); + } + const legalBytes = await readRegularFile(payload, "legal/review.json"); + invariant(Buffer.from(legalBytes).equals(Buffer.from(legalReview.bytes)), "payload legal review differs from canonical document"); + const sourceLegal = await readRegularFile(repository, "release/legal-review.json"); + invariant(Buffer.from(sourceLegal).equals(Buffer.from(legalReview.bytes)), "release legal source differs from payload"); + const bundleBytes = await readRegularFile(payload, "archflow-mcp.mjs"); + invariant(sha256(bundleBytes) === manifest.value.bundle_digest, "bundle digest mismatch"); + assertReleaseLoaderPolicy(decoder.decode(bundleBytes)); + const metafileDocument = parseCanonicalDocument(await readRegularFile(payload, "metafile.json"), "release metafile"); + const metafileInputs = metafileDocument.value.inputs; + const metafileOutputs = metafileDocument.value.outputs; + invariant(metafileInputs && metafileOutputs && Object.keys(metafileOutputs).length === 1, "release metafile must describe one output"); + const metafileOutput = metafileOutputs[RELEASE_BUILD_PROFILE.output]; + invariant(metafileOutput?.entryPoint === RELEASE_BUILD_PROFILE.entry, "release metafile entry/output differs"); + assertEqualPathSet(Object.keys(metafileInputs).sort(ordinal), bundleInputs.map((record) => record.key), "metafile inputs"); + for (const record of bundleInputs) { + invariant(metafileInputs[record.key]?.bytes === record.size, `metafile scanned size differs: ${record.key}`); + invariant((metafileOutput.inputs[record.key]?.bytesInOutput ?? 0) === record.bytes_in_output, `metafile byte contribution differs: ${record.key}`); + } + const actualImports = [...new Set(metafileOutput.imports.map((record) => record.path))].sort(ordinal); + invariant(actualImports.every((path) => RELEASE_BUILD_PROFILE.allowedImports.includes(path) && path !== "node:module"), "metafile contains a forbidden import"); + const derivedDependency = await collectDependencyProvenance(repository, metafileDocument.value, contributing); + invariant(isDeepStrictEqual(dependencyInputs, derivedDependency.records), "dependency provenance inputs are not the exact derived closure"); + invariant(isDeepStrictEqual(manifest.value.adjacent_map_expectations, derivedDependency.expectations), "adjacent source-map expectations differ from derived evidence"); + + const dependencyInventoryDigest = sha256(canonicalJsonBytes({ + adjacent_map_expectations: manifest.value.adjacent_map_expectations, + bundle_inputs: bundleInputs.filter((record) => record.origin.kind === "dependency"), + dependency_provenance_inputs: dependencyInputs, + current_components: legalReview.value.current_components, + })); + invariant(dependencyInventoryDigest === manifest.value.dependency_inventory_digest, "dependency inventory digest mismatch"); + invariant(legalReview.value.dependency_inventory_digest === undefined || legalReview.value.dependency_inventory_digest === dependencyInventoryDigest, "legal dependency inventory digest mismatch"); + const expectedEntry = { id: "mcp-stdio", role: "mcp-stdio", entry_point: "src/main.ts", output_path: "archflow-mcp.mjs", handler_authority: "inert-no-handler" }; + invariant(manifest.value.build_entries.length === 1 && Buffer.from(canonicalJsonBytes(manifest.value.build_entries[0])).equals(Buffer.from(canonicalJsonBytes(expectedEntry))), "release has an unexpected build entry"); + invariant(isDeepStrictEqual(manifest.value.launch_profile, await deriveLaunchProfile(repository)), "release launch profile differs from derived proof inputs"); + invariant(manifest.value.legal_review.digest === legalReview.digest, "manifest legal review binding is stale"); + await validateLegalCorrelation(repository, manifest.value, legalReview.value, ownerPaths, validators); + + const expectedLegalPayloads = new Set(legalReview.value.upstream_legal_sources.map((source) => source.payload_path)); + const actualLegalPayloads = actualFiles.filter((path) => path.startsWith("legal/upstream/")); + assertEqualPathSet(actualLegalPayloads, [...expectedLegalPayloads].sort(ordinal), "payload upstream legal closure"); + for (const source of legalReview.value.upstream_legal_sources) { + const sourceBytes = await readRegularFile(repository, source.source_path); + const payloadBytes = await readRegularFile(payload, source.payload_path); + invariant(Buffer.from(sourceBytes).equals(Buffer.from(payloadBytes)), `upstream legal source/output bytes differ: ${source.source_path}`); + } + const expectedNotice = legalProjection(legalReview.value); + const actualNotice = await readRegularFile(payload, "legal/THIRD_PARTY_NOTICES.md"); + invariant(Buffer.from(expectedNotice).equals(Buffer.from(actualNotice)), "generated third-party notice differs from canonical projection"); + + const summary = Object.freeze({ + payloadRoot: payload, + files: Object.freeze(await Promise.all(actualFiles.map((path) => fileRecord(payload, path)))), + bundleDigest: sha256(bundleBytes), + dependencyInventoryDigest, + manifest, + legalReview, + }); + return Object.freeze({ stageRoot: payload, summary }); +} + +async function readPayloadDocuments(payloadRoot) { + return { + manifest: parseCanonicalDocument(await readRegularFile(payloadRoot, "manifest.json"), "release manifest"), + legalReview: parseCanonicalDocument(await readRegularFile(payloadRoot, "legal/review.json"), "release legal review"), + }; +} + +function normalizedMetafile(metafile) { + return sortCanonical(metafile); +} + +async function buildRecords(repositoryRoot, metafile) { + const soleOutput = metafile.outputs[RELEASE_BUILD_PROFILE.output] ?? metafile.outputs[`dist/${RELEASE_BUILD_PROFILE.output}`]; + invariant(soleOutput, "esbuild metafile has no sole release output"); + invariant(Object.keys(metafile.outputs).length === 1, "release build must have exactly one output"); + const inputs = []; + for (const path of Object.keys(metafile.inputs).sort(ordinal)) { + assertPortablePath(path, "esbuild input path"); + const bytes = await readRegularFile(repositoryRoot, path); + const identity = packageIdentity(path); + const bytesInOutput = soleOutput.inputs[path]?.bytesInOutput ?? 0; + const origin = identity + ? { + kind: "dependency", + package_name: identity.packageName, + package_version: await readPackageVersion(repositoryRoot, identity.packageName), + package_relative_path: identity.packagePath, + } + : { kind: "repository", path }; + inputs.push({ + key: path, + origin, + size: bytes.byteLength, + digest: sha256(bytes), + bytes_in_output: bytesInOutput, + }); + } + const contributing = Object.entries(soleOutput.inputs) + .filter(([, record]) => record.bytesInOutput > 0) + .map(([path]) => path) + .sort(ordinal); + return { bundleInputs: inputs, contributing }; +} + +async function createControlRecords(repositoryRoot, bundleInputs) { + const bundled = new Set(bundleInputs.filter((record) => record.origin.kind === "repository").map((record) => record.origin.path)); + const candidates = new Set([ + ...REQUIRED_CONTROLS, + ...(await collectDeclaredPaths(repositoryRoot)), + ...(await collectLegalSourcePaths(repositoryRoot)), + ...(await collectEvidencePaths(repositoryRoot)), + ]); + const records = []; + for (const path of [...candidates].sort(ordinal)) { + if (bundled.has(path)) continue; + records.push(await fileRecord(repositoryRoot, path)); + } + return records; +} + +async function copyLegal(repositoryRoot, files) { + files.set("legal/review.json", await readRegularFile(repositoryRoot, "release/legal-review.json")); + const upstreamRoot = resolve(repositoryRoot, "release/legal/upstream"); + try { + for (const path of await walkRegularFiles(upstreamRoot)) { + files.set(`legal/upstream/${path}`, await readRegularFile(upstreamRoot, path)); + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } +} + +async function materializeFiles(stageRoot, files) { + for (const [path, bytes] of [...files].sort(([a], [b]) => ordinal(a, b))) { + assertPortablePath(path); + const target = resolve(stageRoot, ...path.split("/")); + await mkdir(dirname(target), { recursive: true }); + const handle = await open(target, "wx"); + try { + await handle.writeFile(bytes); + } finally { + await handle.close(); + } + } +} + +async function pathKind(path) { + try { + const info = await lstat(path); + invariant(!info.isSymbolicLink(), `release transaction path is a symlink: ${path}`); + return info.isDirectory() ? "directory" : info.isFile() ? "file" : "other"; + } catch (error) { + if (error.code === "ENOENT") return "missing"; + throw error; + } +} + +async function syncDirectory(path) { + const handle = await open(path, "r"); + try { await handle.sync(); } finally { await handle.close(); } +} + +async function removeTransactionPath(path, expectedKind) { + const kind = await pathKind(path); + if (kind === "missing") return; + invariant(kind === expectedKind, `release transaction path has unexpected kind: ${path}`); + await rm(path, expectedKind === "directory" ? { recursive: true } : undefined); +} + +export async function recoverTrackedRelease(repositoryRoot) { + const repository = await canonicalExistingDirectory(repositoryRoot, "repository root"); + const tracked = resolve(repository, "dist"); + const marker = resolve(repository, DIST_TRANSACTION.marker); + const markerTemporary = resolve(repository, DIST_TRANSACTION.markerTemporary); + const promotion = resolve(repository, DIST_TRANSACTION.promotion); + const backup = resolve(repository, DIST_TRANSACTION.backup); + const markerKind = await pathKind(marker); + if (markerKind === "missing") { + invariant(await pathKind(backup) === "missing", "orphan tracked-release backup requires manual recovery"); + await removeTransactionPath(promotion, "directory"); + await removeTransactionPath(markerTemporary, "file"); + await syncDirectory(repository); + return; + } + invariant(markerKind === "file", "tracked-release transaction marker must be a regular file"); + const transaction = parseCanonicalDocument(await readFile(marker), "tracked-release transaction marker").value; + invariant( + transaction.schema_version === "1" + && typeof transaction.had_dist === "boolean" + && /^[0-9a-f]{64}$/.test(transaction.candidate_manifest_digest) + && Object.keys(transaction).sort(ordinal).join(",") === "candidate_manifest_digest,had_dist,schema_version", + "tracked-release transaction marker is invalid", + ); + const trackedKind = await pathKind(tracked); + const backupKind = await pathKind(backup); + const promotionKind = await pathKind(promotion); + invariant(["missing", "directory"].includes(trackedKind), "tracked dist has an unsafe kind"); + invariant(["missing", "directory"].includes(backupKind), "tracked-release backup has an unsafe kind"); + invariant(["missing", "directory"].includes(promotionKind), "tracked-release promotion has an unsafe kind"); + + if (transaction.had_dist && trackedKind === "missing") { + invariant(backupKind === "directory", "tracked dist and recoverable backup are both absent"); + await rename(backup, tracked); + } else if (transaction.had_dist && backupKind === "directory") { + await removeTransactionPath(backup, "directory"); + } + await removeTransactionPath(promotion, "directory"); + await removeTransactionPath(markerTemporary, "file"); + await removeTransactionPath(marker, "file"); + await syncDirectory(repository); +} + +async function writeTransactionMarker(repository, value) { + const temporary = resolve(repository, DIST_TRANSACTION.markerTemporary); + const marker = resolve(repository, DIST_TRANSACTION.marker); + const handle = await open(temporary, "wx"); + try { + await handle.writeFile(canonicalJsonBytes(value)); + await handle.sync(); + } finally { + await handle.close(); + } + await rename(temporary, marker); + await syncDirectory(repository); +} + +function injectReleaseFault(step) { + if (process.env.ARCHFLOW_RELEASE_FAULT_AFTER !== step) return; + const error = new Error(`injected tracked-release crash after ${step}`); + error.releaseCrash = true; + throw error; +} + +export async function buildReleasePayload({ repositoryRoot, stageRoot }) { + const repository = await canonicalExistingDirectory(repositoryRoot, "repository root"); + await recoverTrackedRelease(repository); + const stage = await prepareEmptyRoot(stageRoot, "stage root", [["repository root", repository]]); + const result = await build({ + absWorkingDir: repository, + entryPoints: [RELEASE_BUILD_PROFILE.entry], + outfile: RELEASE_BUILD_PROFILE.output, + write: false, + metafile: true, + bundle: true, + platform: "node", + format: "esm", + target: "node24", + splitting: false, + minify: false, + sourcemap: false, + legalComments: "none", + plugins: [], + banner: { js: RELEASE_BUILD_PROFILE.banner }, + tsconfigRaw: RELEASE_BUILD_PROFILE.tsconfigRaw, + }); + invariant(result.outputFiles.length === 1, "release build emitted an unexpected file"); + const output = result.outputFiles[0].contents; + const outputMeta = result.metafile.outputs[RELEASE_BUILD_PROFILE.output]; + invariant(outputMeta, "release output has an unstable logical path"); + const imports = new Set(outputMeta.imports.map((record) => record.path)); + imports.add("node:module"); + for (const path of imports) invariant(RELEASE_BUILD_PROFILE.allowedImports.includes(path), `forbidden release import: ${path}`); + const source = decoder.decode(output); + assertReleaseLoaderPolicy(source); + + const { bundleInputs, contributing } = await buildRecords(repository, result.metafile); + const controls = await createControlRecords(repository, bundleInputs); + const dependency = await collectDependencyProvenance(repository, result.metafile, contributing); + const dependencyInputs = dependency.records; + const legalBytes = await readRegularFile(repository, "release/legal-review.json"); + const legalReview = parseCanonicalDocument(legalBytes, "release legal review source"); + const dependencyInventoryDigest = sha256(canonicalJsonBytes({ + adjacent_map_expectations: dependency.expectations, + bundle_inputs: bundleInputs.filter((record) => record.origin.kind === "dependency"), + dependency_provenance_inputs: dependencyInputs, + current_components: legalReview.value.current_components, + })); + const metafileBytes = canonicalJsonBytes(normalizedMetafile(result.metafile)); + const files = new Map([ + ["archflow-mcp.mjs", output], + ["metafile.json", metafileBytes], + ]); + await copyLegal(repository, files); + files.set("legal/THIRD_PARTY_NOTICES.md", legalProjection(legalReview.value)); + const artifactRole = (path) => path === "archflow-mcp.mjs" ? "executable" + : path === "metafile.json" ? "metafile" + : path === "legal/review.json" ? "legal-review" + : path === "legal/THIRD_PARTY_NOTICES.md" ? "legal-notice" + : "upstream-legal"; + const artifacts = [...files].map(([path, bytes]) => ({ path, role: artifactRole(path), size: bytes.byteLength, digest: sha256(bytes) })) + .sort((a, b) => ordinal(a.path, b.path)); + artifacts.push({ path: "manifest.json", role: "manifest" }); + artifacts.sort((a, b) => ordinal(a.path, b.path)); + const declaredPaths = await collectDeclaredPaths(repository); + const manifestValue = { + schema_version: "1", + bundle_digest: sha256(output), + dependency_inventory_digest: dependencyInventoryDigest, + bundle_inputs: bundleInputs, + contributing_inputs: contributing, + release_control_inputs: controls, + dependency_provenance_inputs: dependencyInputs, + adjacent_map_expectations: dependency.expectations, + declared_content: { + schemas: declaredPaths.filter((path) => path.startsWith("src/contracts/schemas/v1/")), + workflow: "assets/workflow.yaml", + constitution: declaredPaths.filter((path) => path.startsWith("assets/constitution/")), + }, + proof_inputs: [...PROOF_INPUTS], + build_entries: [{ id: "mcp-stdio", role: "mcp-stdio", entry_point: "src/main.ts", output_path: "archflow-mcp.mjs", handler_authority: "inert-no-handler" }], + launch_profile: await deriveLaunchProfile(repository), + legal_review: { source_path: "release/legal-review.json", payload_path: "legal/review.json", digest: legalReview.digest }, + artifacts, + }; + const manifest = canonicalDocument(manifestValue); + files.set("manifest.json", manifest.bytes); + await materializeFiles(stage, files); + const stageDocuments = await readPayloadDocuments(stage); + const validated = await validateReleaseSemantics({ repositoryRoot: repository, payloadRoot: stage, ...stageDocuments }); + return validated.summary; +} + +export async function checkReleasePayload({ repositoryRoot, payloadRoot, comparisonRoot }) { + const repository = await canonicalExistingDirectory(repositoryRoot, "repository root"); + await recoverTrackedRelease(repository); + const payload = await canonicalExistingDirectory(payloadRoot, "payload root"); + const stage = await validateReleaseSemantics({ repositoryRoot: repository, payloadRoot: payload, ...(await readPayloadDocuments(payload)) }); + if (comparisonRoot === undefined) return stage.summary; + const comparison = await canonicalExistingDirectory(comparisonRoot, "comparison root"); + invariant(comparison !== payload && !isInside(comparison, payload) && !isInside(payload, comparison), "payload roots overlap"); + const reproduced = await validateReleaseSemantics({ repositoryRoot: repository, payloadRoot: comparison, ...(await readPayloadDocuments(comparison)) }); + const comparedFiles = await comparePayloads(stage.summary, reproduced.summary); + return reproductionProof(stage.summary, reproduced.summary, comparedFiles); +} + +async function comparePayloads(candidate, reproduced) { + const left = new Map(candidate.files.map((record) => [record.path, record])); + const right = new Map(reproduced.files.map((record) => [record.path, record])); + invariant(left.size === right.size, "release payload file counts differ"); + const compared = [...left.keys()].sort(ordinal); + for (const path of compared) { + const a = left.get(path); + const b = right.get(path); + invariant(b && a.size === b.size && a.digest === b.digest, `release payload differs: ${path}`); + } + return Object.freeze(compared); +} + +function reproductionProof(candidate, reproduced, comparedFiles) { + const proofInputsDigest = sha256(canonicalJsonBytes(candidate.manifest.value.proof_inputs)); + const launchProfileDigest = sha256(canonicalJsonBytes(candidate.manifest.value.launch_profile ?? {})); + return Object.freeze({ candidate, reproduced, comparedFiles, proofInputsDigest, launchProfileDigest }); +} + +export async function materializeReleaseSourceRoot({ repositoryRoot, stage, materializationRoot }) { + const repository = await canonicalExistingDirectory(repositoryRoot, "repository root"); + invariant(stage?.summary?.manifest?.value, "a validated release stage is required"); + const root = await prepareEmptyRoot(materializationRoot, "materialization root", [ + ["repository root", repository], + ["candidate stage", stage.stageRoot], + ]); + const controls = stage.summary.manifest.value.release_control_inputs; + const repositoryInputs = stage.summary.manifest.value.bundle_inputs + .filter((record) => record.origin.kind === "repository") + .map((record) => ({ path: record.origin.path, size: record.size, digest: record.digest })); + const allowlist = [...repositoryInputs, ...controls]; + invariant(!allowlist.some((record) => record.path.startsWith("node_modules/")), "materialization cannot copy node_modules"); + for (const record of allowlist) { + const bytes = await readRegularFile(repository, record.path); + invariant(bytes.byteLength === record.size && sha256(bytes) === record.digest, `stale materialization input: ${record.path}`); + const target = resolve(root, ...record.path.split("/")); + await mkdir(dirname(target), { recursive: true }); + const handle = await open(target, "wx"); + try { await handle.writeFile(bytes); } finally { await handle.close(); } + } +} + +export async function reproduceReleasePayload({ repositoryRoot, stage, materializationRoot, comparisonRoot }) { + const repository = await canonicalExistingDirectory(repositoryRoot, "repository root"); + invariant(stage?.stageRoot && stage?.summary, "a validated release stage is required"); + const candidate = await canonicalExistingDirectory(stage.stageRoot, "candidate stage root"); + const materializationCandidate = await canonicalDedicatedRootCandidate(materializationRoot, "materialization root"); + const comparisonCandidate = await canonicalDedicatedRootCandidate(comparisonRoot, "comparison root"); + assertRootsPairwiseNonOverlapping([ + ["repository root", repository], + ["candidate stage root", candidate], + ["materialization root", materializationCandidate], + ["comparison root", comparisonCandidate], + ]); + await materializeReleaseSourceRoot({ repositoryRoot: repository, stage, materializationRoot }); + const materialization = await canonicalExistingDirectory(materializationRoot, "materialization root"); + await execFileAsync(process.platform === "win32" ? "npm.cmd" : "npm", ["ci", "--ignore-scripts", "--no-audit", "--no-fund"], { + cwd: materialization, + env: { PATH: process.env.PATH, HOME: resolve(materialization, ".home"), npm_config_cache: resolve(materialization, ".npm-cache") }, + maxBuffer: 16 * 1024 * 1024, + }); + await verifyDependencyRecords(materialization, stage.summary.manifest.value.dependency_provenance_inputs); + const reproduced = await buildReleasePayload({ repositoryRoot: materialization, stageRoot: comparisonCandidate }); + const refreshed = await validateReleaseSemantics({ + repositoryRoot: repository, + payloadRoot: candidate, + ...(await readPayloadDocuments(candidate)), + }); + await comparePayloads(stage.summary, refreshed.summary); + const comparedFiles = await comparePayloads(refreshed.summary, reproduced); + return reproductionProof(refreshed.summary, reproduced, comparedFiles); +} + +export async function reproduceCurrentRelease({ repositoryRoot }) { + const repository = await canonicalExistingDirectory(repositoryRoot, "repository root"); + const workRoot = await mkdtemp(resolve(tmpdir(), "archflow-release-reproduce-")); + try { + const candidateRoot = resolve(workRoot, "candidate"); + await buildReleasePayload({ repositoryRoot: repository, stageRoot: candidateRoot }); + const candidate = await validateReleaseSemantics({ + repositoryRoot: repository, + payloadRoot: candidateRoot, + ...(await readPayloadDocuments(candidateRoot)), + }); + return await reproduceReleasePayload({ + repositoryRoot: repository, + stage: candidate, + materializationRoot: resolve(workRoot, "source"), + comparisonRoot: resolve(workRoot, "comparison"), + }); + } finally { + await rm(workRoot, { recursive: true, force: true }); + } +} + +async function readHeadFile(repositoryRoot, path) { + try { + const { stdout } = await execFileAsync("git", ["show", `HEAD:${path}`], { cwd: repositoryRoot, encoding: "buffer", maxBuffer: 16 * 1024 * 1024 }); + return new Uint8Array(stdout); + } catch (error) { + if (error.code === 128 || error.stderr?.toString().includes("does not exist")) return undefined; + throw error; + } +} + +async function verifyHeadLegalBaseline(repositoryRoot, candidateLegal) { + const listed = (await execFileAsync("git", ["ls-tree", "-r", "--name-only", "HEAD", "release", "dist/legal"], { cwd: repositoryRoot })).stdout + .trim().split("\n").filter(Boolean).sort(ordinal); + const releasePaths = listed.filter((path) => path === "release/legal-review.json" || path.startsWith("release/legal/upstream/")); + const distPaths = listed.filter((path) => path.startsWith("dist/legal/")); + const source = releasePaths.includes("release/legal-review.json") ? await readHeadFile(repositoryRoot, "release/legal-review.json") : undefined; + const output = distPaths.includes("dist/legal/review.json") ? await readHeadFile(repositoryRoot, "dist/legal/review.json") : undefined; + if (!source && !output) { + invariant(releasePaths.length === 0 && distPaths.length === 0, "HEAD contains orphan legal artifacts without review baseline"); + return; + } + invariant(source && output, "HEAD legal source/output baseline is inconsistent"); + invariant(Buffer.from(source).equals(Buffer.from(output)), "HEAD legal source/output bytes differ"); + const prior = parseCanonicalDocument(source, "HEAD legal review").value; + for (const collection of ["dependency_gate_decisions", "amendments", "supersessions"]) { + const priorRecords = new Map((prior[collection] ?? []).map((record) => [record.id, canonicalJsonBytes(record)])); + const currentRecords = new Map((candidateLegal.value[collection] ?? []).map((record) => [record.id, canonicalJsonBytes(record)])); + for (const [id, bytes] of priorRecords) { + const current = currentRecords.get(id); + invariant(current && Buffer.from(current).equals(Buffer.from(bytes)), `HEAD ${collection} record changed or disappeared: ${id}`); + } + } + const sourceUpstream = releasePaths.filter((path) => path.startsWith("release/legal/upstream/")); + const distUpstream = distPaths.filter((path) => path.startsWith("dist/legal/upstream/")); + for (const path of sourceUpstream) { + const counterpart = `dist/${path.slice("release/".length)}`; + invariant(distUpstream.includes(counterpart), `HEAD upstream counterpart missing: ${counterpart}`); + invariant(Buffer.from(await readHeadFile(repositoryRoot, path)).equals(Buffer.from(await readHeadFile(repositoryRoot, counterpart))), `HEAD upstream counterpart differs: ${path}`); + } + invariant(sourceUpstream.length === distUpstream.length, "HEAD has orphan dist upstream legal artifacts"); + const exactDistLegal = [ + "dist/legal/THIRD_PARTY_NOTICES.md", + "dist/legal/review.json", + ...sourceUpstream.map((path) => `dist/${path.slice("release/".length)}`), + ].sort(ordinal); + invariant(isDeepStrictEqual(distPaths, exactDistLegal), "HEAD dist legal closure has missing or extra artifacts"); + const priorNotice = await readHeadFile(repositoryRoot, "dist/legal/THIRD_PARTY_NOTICES.md"); + invariant(Buffer.from(priorNotice).equals(Buffer.from(legalProjection(prior))), "HEAD generated notice differs from its review source"); +} + +export async function writeTrackedReleasePayload({ repositoryRoot, candidateStageRoot }) { + const repository = await canonicalExistingDirectory(repositoryRoot, "repository root"); + await recoverTrackedRelease(repository); + const candidateRoot = await canonicalExistingDirectory(candidateStageRoot, "candidate stage root"); + invariant( + candidateRoot !== repository + && !isInside(repository, candidateRoot) + && !isInside(candidateRoot, repository), + "candidate stage root must be outside the repository", + ); + const candidate = await validateReleaseSemantics({ repositoryRoot: repository, payloadRoot: candidateRoot, ...(await readPayloadDocuments(candidateRoot)) }); + await verifyHeadLegalBaseline(repository, candidate.summary.legalReview); + const workRoot = await mkdtemp(resolve(tmpdir(), "archflow-release-write-")); + try { + const proof = await reproduceReleasePayload({ + repositoryRoot: repository, + stage: candidate, + materializationRoot: resolve(workRoot, "source"), + comparisonRoot: resolve(workRoot, "comparison"), + }); + const tracked = resolve(repository, "dist"); + await assertNoSymlinkTraversal(dirname(tracked)); + const promotion = resolve(repository, DIST_TRANSACTION.promotion); + const backup = resolve(repository, DIST_TRANSACTION.backup); + let trackedExists = false; + try { + await assertNoSymlinkTraversal(tracked); + const trackedInfo = await lstat(tracked); + invariant(trackedInfo.isDirectory(), "tracked dist target must be a regular directory"); + await walkRegularFiles(tracked); + trackedExists = true; + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + for (const transient of [promotion, backup, resolve(repository, DIST_TRANSACTION.marker), resolve(repository, DIST_TRANSACTION.markerTemporary)]) { + try { await access(transient); throw new Error(`release promotion target already exists: ${transient}`); } + catch (error) { if (error.code !== "ENOENT") throw error; } + } + await mkdir(promotion); + try { + const candidateFiles = new Map(candidate.summary.files.map((file) => [file.path, file])); + for (const path of proof.comparedFiles) { + const source = resolve(candidateRoot, ...path.split("/")); + const target = resolve(promotion, ...path.split("/")); + await mkdir(dirname(target), { recursive: true }); + await cp(source, target, { errorOnExist: true, force: false, preserveTimestamps: false }); + const copied = await readFile(target); + const expected = candidateFiles.get(path); + invariant( + expected && copied.byteLength === expected.size && sha256(copied) === expected.digest, + `promotion copy differs from validated candidate: ${path}`, + ); + } + assertEqualPathSet(await walkRegularFiles(promotion), proof.comparedFiles, "promotion closure"); + await writeTransactionMarker(repository, { + schema_version: "1", + had_dist: trackedExists, + candidate_manifest_digest: candidate.summary.manifest.digest, + }); + injectReleaseFault("marker-written"); + if (trackedExists) { + await rename(tracked, backup); + await syncDirectory(repository); + injectReleaseFault("backup-renamed"); + } + await rename(promotion, tracked); + await syncDirectory(repository); + injectReleaseFault("promotion-renamed"); + } catch (error) { + if (!error.releaseCrash) await recoverTrackedRelease(repository); + throw error; + } + await recoverTrackedRelease(repository); + return proof; + } finally { + await rm(workRoot, { recursive: true, force: true }); + } +} + +export function jsonSummary(value) { + if (value?.manifest?.bytes) { + return { + payload_root: value.payloadRoot, + files: value.files, + bundle_digest: value.bundleDigest, + dependency_inventory_digest: value.dependencyInventoryDigest, + manifest_digest: value.manifest.digest, + legal_review_digest: value.legalReview.digest, + }; + } + if (value?.candidate && value?.reproduced) { + return { + candidate: jsonSummary(value.candidate), + reproduced: jsonSummary(value.reproduced), + compared_files: value.comparedFiles, + proof_inputs_digest: value.proofInputsDigest, + launch_profile_digest: value.launchProfileDigest, + }; + } + return value; +} + +export function writeCanonicalSummary(value) { + process.stdout.write(canonicalJsonBytes(jsonSummary(value))); +} + +export function runCli(main) { + Promise.resolve().then(main).catch((error) => { + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = error?.usage ? 2 : 1; + }); +} + +export function parseCli(arguments_, specification) { + const usageError = () => { + const error = new Error(`usage: ${specification.usage}`); + error.usage = true; + return error; + }; + const parsed = {}; + for (let index = 0; index < arguments_.length; index += 2) { + const flag = arguments_[index]; + const value = arguments_[index + 1]; + if (!Object.hasOwn(specification, flag) || value === undefined || value.startsWith("--")) { + throw usageError(); + } + if (parsed[specification[flag]] !== undefined) throw usageError(); + parsed[specification[flag]] = resolve(value); + } + for (const field of specification.required) { + if (!parsed[field]) { + throw usageError(); + } + } + return parsed; +} diff --git a/scripts/reproduce-release.mjs b/scripts/reproduce-release.mjs new file mode 100644 index 00000000..0db915bc --- /dev/null +++ b/scripts/reproduce-release.mjs @@ -0,0 +1,19 @@ +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { + reproduceCurrentRelease, + runCli, + writeCanonicalSummary, +} from "./release-support.mjs"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); + +runCli(async () => { + if (process.argv.length !== 2) { + const error = new Error("usage: npm run release:reproduce"); + error.usage = true; + throw error; + } + writeCanonicalSummary(await reproduceCurrentRelease({ repositoryRoot })); +}); diff --git a/scripts/smoke-release-bundle.mjs b/scripts/smoke-release-bundle.mjs new file mode 100644 index 00000000..d7b4a4f6 --- /dev/null +++ b/scripts/smoke-release-bundle.mjs @@ -0,0 +1,322 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { cp, mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const fixturesRoot = resolve(repositoryRoot, "test/fixtures/mcp/runtime"); +const guardSource = resolve(repositoryRoot, "test/fixtures/release/hostile-runtime-guard.cjs"); +const timeoutMs = 10_000; + +function usage(message) { + const error = new Error(message); + error.exitCode = 2; + return error; +} + +function parseArguments(argv) { + if (argv.length !== 2 || argv[0] !== "--payload" || argv[1] === "") { + throw usage("usage: smoke-release-bundle.mjs --payload "); + } + return resolve(argv[1]); +} + +function canonicalJson(value) { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; + if (value !== null && typeof value === "object") { + return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`; + } + return JSON.stringify(value); +} + +async function runChild({ argv, cwd, env, input }) { + const child = spawn(process.execPath, argv, { + cwd, + env, + stdio: ["pipe", "pipe", "pipe", "pipe"], + }); + const stdout = []; + const stderr = []; + const oracle = []; + child.stdout.on("data", (chunk) => stdout.push(Buffer.from(chunk))); + child.stderr.on("data", (chunk) => stderr.push(Buffer.from(chunk))); + child.stdio[3].on("data", (chunk) => oracle.push(Buffer.from(chunk))); + child.stdin.end(input); + let timer; + try { + const exit = await Promise.race([ + new Promise((resolveExit, rejectExit) => { + child.once("error", rejectExit); + child.once("exit", (code, signal) => resolveExit({ code, signal })); + }), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("release smoke child timed out")), timeoutMs); + }), + ]); + return { + ...exit, + oracle: Buffer.concat(oracle), + stderr: Buffer.concat(stderr), + stdout: Buffer.concat(stdout), + }; + } finally { + clearTimeout(timer); + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + } +} + +function minimalEnvironment(ambientRoot) { + return { + HOME: resolve(ambientRoot, "unusable-home"), + LANG: "C.UTF-8", + LC_ALL: "C.UTF-8", + NPM_CONFIG_CACHE: resolve(ambientRoot, "unusable-npm-cache"), + PATH: dirname(process.execPath), + TMPDIR: resolve(ambientRoot, "empty-tmp"), + XDG_CACHE_HOME: resolve(ambientRoot, "unusable-xdg-cache"), + XDG_CONFIG_HOME: resolve(ambientRoot, "unusable-xdg-config"), + XDG_DATA_HOME: resolve(ambientRoot, "unusable-xdg-data"), + }; +} + +async function assertGuardNegative({ cwd, env, guard }) { + const dns = await runChild({ + argv: ["--require", guard, "--eval", "require('node:dns').lookup('archflow.invalid',()=>{})"], + cwd, + env, + input: Buffer.alloc(0), + }); + assert.notEqual(dns.code, 0, "DNS negative control must be stopped by the guard"); + assert.match(dns.oracle.toString("utf8"), /"surface":"node:dns"/u); + + const websocket = await runChild({ + argv: ["--require", guard, "--eval", "new WebSocket('ws://archflow.invalid')"], + cwd, + env, + input: Buffer.alloc(0), + }); + assert.notEqual(websocket.code, 0, "WebSocket negative control must be stopped by the guard"); + assert.match(websocket.oracle.toString("utf8"), /"operation":"WebSocket"/u); + + const repositoryCanary = await runChild({ + argv: ["--require", guard, "--eval", "require('node:fs').readFileSync('../repository-canary/SECRET')"], + cwd, + env, + input: Buffer.alloc(0), + }); + assert.equal(repositoryCanary.code, 0, "repository canary observation control must complete normally"); + assert.match(repositoryCanary.oracle.toString("utf8"), /"type":"canary-attempt"/u); + assert.equal(repositoryCanary.stdout.toString("utf8"), "", "repository canary control must not print its contents"); +} + +function jsonLine(value) { + return `${JSON.stringify(value)}\n`; +} + +function assertCleanExit(result, label) { + assert.deepEqual(result.stderr, Buffer.alloc(0), `${label} emitted diagnostics`); + assert.deepEqual(result.oracle, Buffer.alloc(0), `${label} wrote to the guard oracle`); + assert.deepEqual({ code: result.code, signal: result.signal }, { code: 0, signal: null }, `${label} did not exit cleanly`); +} + +function assertCallTranscript(bytes, initialize, calls) { + const lines = bytes.toString("utf8").trimEnd().split("\n").map((line) => JSON.parse(line)); + assert.equal(lines.length, 7, "complete initialize/calls sequence must emit seven frames"); + assert.deepEqual(lines[0], initialize.malformed_response); + assert.deepEqual(lines[1], initialize.response); + assert.deepEqual(lines[2]?.jsonrpc, "2.0"); + assert.deepEqual(lines[2]?.id, calls.list.id); + assert.deepEqual(lines[2]?.result?.tools?.map((tool) => tool.name), [ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + "archflow_gate", + "archflow_waiver", + ]); + assert.deepEqual(lines[3], { + jsonrpc: "2.0", + id: calls.unknown.id, + error: { + code: -32001, + message: "TOOL_NOT_FOUND", + data: { + schema_version: "1", + code: "TOOL_NOT_FOUND", + owner: "protocol", + retryable: false, + diagnostic: { + template_id: "TOOL_NOT_FOUND", + parameters: { tool_name_digest: createHash("sha256").update(calls.unknown.params.name).digest("hex") }, + }, + next_action: "call-advertised-tool", + }, + }, + }); + for (const [index, request] of [[4, calls.missing_arguments], [5, calls.non_object_arguments]]) { + const frame = lines[index]; + assert.equal(frame.id, request.id); + assert.equal(frame.result?.isError, true); + assert.equal(frame.result?.structuredContent?.ok, false); + assert.equal(frame.result?.structuredContent?.error?.code, "CONTRACT_INVALID"); + assert.equal(frame.result?.structuredContent?.error?.diagnostic?.parameters?.issue_code, "input-not-object"); + assert.equal(frame.result?.content?.[0]?.text, JSON.stringify(frame.result.structuredContent)); + } + assert.deepEqual(lines[6], { + jsonrpc: "2.0", + id: calls.valid_disabled.id, + error: { + code: -32002, + message: "TOOL_DISABLED", + data: { + schema_version: "1", + code: "TOOL_DISABLED", + owner: "protocol", + retryable: false, + diagnostic: { + template_id: "TOOL_DISABLED", + parameters: { tool: "archflow_state", lifecycle_state: "inert-no-handler" }, + }, + next_action: "wait-for-tool-enable", + }, + }, + }); +} + +async function exerciseProtocolFixtures({ copiedBundle, copiedPayload, env, guard, initialize, calls, adversarial }) { + const callInput = Buffer.from([ + jsonLine(initialize.malformed_request), + jsonLine(initialize.request), + jsonLine(initialize.initialized), + ...Object.values(calls).map(jsonLine), + ].join("")); + const exact = await runChild({ argv: [copiedBundle], cwd: copiedPayload, env, input: callInput }); + assertCleanExit(exact, "exact copied payload call sequence"); + assertCallTranscript(exact.stdout, initialize, calls); + + const guarded = await runChild({ + argv: ["--require", guard, copiedBundle], + cwd: copiedPayload, + env, + input: callInput, + }); + assertCleanExit(guarded, "guarded copied payload call sequence"); + assert.deepEqual(guarded.stdout, exact.stdout, "guarded complete call transcript is not byte-exact"); + + const expectedParseError = Buffer.from(adversarial.parse_error_frame_utf8, "base64"); + let exactTranscriptBytes = exact.stdout.length; + let guardedTranscriptBytes = guarded.stdout.length; + for (const [fixture, expectedCode, expectedDiagnostic] of [ + ["malformed_json_utf8", 0, ""], + ["partial_json_utf8", 0, ""], + ["invalid_utf8", 1, "ARCHFLOW_MCP_TRANSPORT_ERROR\n"], + ]) { + const input = Buffer.from(adversarial[fixture], "base64"); + const unguardedResult = await runChild({ argv: [copiedBundle], cwd: copiedPayload, env, input }); + const guardedResult = await runChild({ argv: ["--require", guard, copiedBundle], cwd: copiedPayload, env, input }); + for (const [mode, result] of [["exact", unguardedResult], ["guarded", guardedResult]]) { + assert.deepEqual(result.stdout, expectedParseError, `${mode} ${fixture} stdout drifted`); + assert.deepEqual(result.stderr, Buffer.from(expectedDiagnostic), `${mode} ${fixture} diagnostics drifted`); + assert.deepEqual(result.oracle, Buffer.alloc(0), `${mode} ${fixture} wrote to fd 3`); + assert.deepEqual({ code: result.code, signal: result.signal }, { code: expectedCode, signal: null }); + } + exactTranscriptBytes += unguardedResult.stdout.length; + guardedTranscriptBytes += guardedResult.stdout.length; + assert.deepEqual(guardedResult.stdout, unguardedResult.stdout, `${fixture} modes were not byte-exact`); + } + assert.equal(guardedTranscriptBytes, exactTranscriptBytes, "protocol transcript byte counts differ between modes"); + return { guarded, guardedTranscriptBytes }; +} + +async function proveModuleCanaryIsolation({ copiedPayload, ambientRoot, env, guard }) { + const canaryModuleRoot = resolve(ambientRoot, "node_modules"); + const canaryEntry = resolve(canaryModuleRoot, "archflow-release-canary/index.js"); + const control = await runChild({ + argv: ["--eval", "process.stdout.write(require.resolve('archflow-release-canary')+'\\n'+require('archflow-release-canary'))"], + cwd: copiedPayload, + env: { ...env, NODE_PATH: canaryModuleRoot }, + input: Buffer.alloc(0), + }); + assert.deepEqual({ code: control.code, signal: control.signal }, { code: 0, signal: null }); + const [resolvedCanary, canaryContents] = control.stdout.toString("utf8").split("\n"); + assert.equal(resolve(resolvedCanary), canaryEntry, "module canary must resolve on the control lookup path"); + assert.equal(canaryContents, "ARCHFLOW_MODULE_CANARY", "control child must read the resolved module canary"); + assert.deepEqual(control.oracle, Buffer.alloc(0)); + + assert.equal(Object.hasOwn(env, "NODE_PATH"), false, "hostile environment must scrub NODE_PATH"); + const hostile = await runChild({ + argv: ["--require", guard, "--eval", "require('archflow-release-canary')"], + cwd: copiedPayload, + env, + input: Buffer.alloc(0), + }); + assert.notEqual(hostile.code, 0, "scrubbed hostile launch unexpectedly resolved the module canary"); + assert.match(hostile.stderr.toString("utf8"), /Cannot find module 'archflow-release-canary'/u); + assert.match(hostile.oracle.toString("utf8"), /"operation":"unresolved","surface":"module-canary"/u); + return "resolved-via-NODE_PATH"; +} + +export async function smokeReleasePayload(payloadRoot) { + const bundle = resolve(payloadRoot, "archflow-mcp.mjs"); + assert.equal((await stat(bundle)).isFile(), true, "payload must contain archflow-mcp.mjs"); + const temporaryRoot = await mkdtemp(resolve(tmpdir(), "archflow-release-hostile-")); + try { + const copiedPayload = resolve(temporaryRoot, "payload"); + const ambientRoot = resolve(temporaryRoot, "ambient"); + const guard = resolve(copiedPayload, "hostile-runtime-guard.cjs"); + await cp(payloadRoot, copiedPayload, { recursive: true, verbatimSymlinks: true }); + await cp(guardSource, guard); + await mkdir(resolve(ambientRoot, "empty-tmp"), { recursive: true }); + await mkdir(resolve(temporaryRoot, "repository-canary"), { recursive: true }); + await mkdir(resolve(ambientRoot, "node_modules/archflow-release-canary"), { recursive: true }); + await writeFile(resolve(temporaryRoot, "repository-canary/SECRET"), "ARCHFLOW_REPOSITORY_CANARY\n"); + await writeFile(resolve(ambientRoot, "node_modules/archflow-release-canary/index.js"), "module.exports = 'ARCHFLOW_MODULE_CANARY'\n"); + + const initialize = JSON.parse(await readFile(resolve(fixturesRoot, "initialize.json"), "utf8")); + const calls = JSON.parse(await readFile(resolve(fixturesRoot, "calls.json"), "utf8")); + const adversarial = JSON.parse(await readFile(resolve(fixturesRoot, "adversarial-bytes.json"), "utf8")); + const env = minimalEnvironment(ambientRoot); + const copiedBundle = resolve(copiedPayload, "archflow-mcp.mjs"); + const { guarded, guardedTranscriptBytes } = await exerciseProtocolFixtures({ + copiedBundle, + copiedPayload, + env, + guard, + initialize, + calls, + adversarial, + }); + for (const canary of ["ARCHFLOW_REPOSITORY_CANARY", "ARCHFLOW_MODULE_CANARY_READ"]) { + assert.equal(Buffer.concat([guarded.stdout, guarded.stderr]).includes(Buffer.from(canary)), false); + } + + const moduleCanary = await proveModuleCanaryIsolation({ copiedPayload, ambientRoot, env, guard }); + await assertGuardNegative({ cwd: copiedPayload, env, guard }); + return { + bundle: "archflow-mcp.mjs", + fixture_sequences: ["initialize-and-calls", "malformed-json", "partial-json", "invalid-utf8"], + guarded_transcript_bytes: guardedTranscriptBytes, + modes: ["exact-copy", "guarded-copy"], + module_canary_control: moduleCanary, + network_oracle_bytes: guarded.oracle.length, + payload_root: payloadRoot, + }; + } finally { + await rm(temporaryRoot, { force: true, recursive: true }); + } +} + +async function main() { + const payloadRoot = parseArguments(process.argv.slice(2)); + const result = await smokeReleasePayload(payloadRoot); + process.stdout.write(`${canonicalJson(result)}\n`); +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + main().catch((error) => { + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = Number.isInteger(error?.exitCode) ? error.exitCode : 1; + }); +} diff --git a/scripts/test-release-integrity.mjs b/scripts/test-release-integrity.mjs new file mode 100644 index 00000000..a87e0522 --- /dev/null +++ b/scripts/test-release-integrity.mjs @@ -0,0 +1,271 @@ +import assert from "node:assert/strict"; +import { cp, mkdtemp, mkdir, readFile, rename, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const trackedPayload = resolve(repositoryRoot, "dist"); + +function sortCanonical(value) { + if (Array.isArray(value)) return value.map(sortCanonical); + if (value !== null && typeof value === "object") { + return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortCanonical(value[key])])); + } + return value; +} + +function canonicalJson(value) { + return JSON.stringify(sortCanonical(value), null, 2); +} + +function findProperty(value, name) { + if (value === null || typeof value !== "object") return undefined; + if (Object.hasOwn(value, name)) return value[name]; + for (const child of Object.values(value)) { + const found = findProperty(child, name); + if (found !== undefined) return found; + } + return undefined; +} + +function findPathRecord(value) { + if (value === null || typeof value !== "object") return undefined; + if (!Array.isArray(value) && typeof value.path === "string") return value; + for (const child of Object.values(value)) { + const found = findPathRecord(child); + if (found !== undefined) return found; + } + return undefined; +} + +async function expectFailure(label, operation) { + let failed = false; + try { + await operation(); + } catch { + failed = true; + } + assert.equal(failed, true, `${label} mutation unexpectedly validated`); +} + +async function mutatePayload(temporaryRoot, label, mutation, checkReleasePayload) { + const root = resolve(temporaryRoot, label); + await cp(trackedPayload, root, { recursive: true, verbatimSymlinks: true }); + await mutation(root); + await expectFailure(label, () => checkReleasePayload({ repositoryRoot, payloadRoot: root })); +} + +async function main() { + const support = await import(pathToFileURL(resolve(repositoryRoot, "scripts/release-support.mjs"))); + assert.equal(typeof support.checkReleasePayload, "function", "release support must export checkReleasePayload"); + assert.equal(typeof support.buildReleasePayload, "function", "release support must export buildReleasePayload"); + await support.checkReleasePayload({ repositoryRoot, payloadRoot: trackedPayload }); + + const temporaryRoot = await mkdtemp(resolve(tmpdir(), "archflow-release-mutations-")); + const passed = []; + try { + await mutatePayload(temporaryRoot, "schema", async (root) => { + const path = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(path, "utf8")); + manifest.unrecognized_release_authority = true; + await writeFile(path, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("schema"); + + await mutatePayload(temporaryRoot, "graph", async (root) => { + const path = resolve(root, "metafile.json"); + const metafile = JSON.parse(await readFile(path, "utf8")); + metafile.inputs["src/forged-release-input.ts"] = { bytes: 1, imports: [] }; + await writeFile(path, `${canonicalJson(metafile)}\n`); + }, support.checkReleasePayload); + passed.push("graph"); + + await mutatePayload(temporaryRoot, "provenance", async (root) => { + const path = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(path, "utf8")); + const records = findProperty(manifest, "dependency_provenance_inputs"); + assert.ok(Array.isArray(records) && records.length > 0, "manifest has no dependency provenance records"); + records[0].digest = "0".repeat(64); + await writeFile(path, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("provenance"); + + await mutatePayload(temporaryRoot, "path", async (root) => { + const path = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(path, "utf8")); + const record = findPathRecord(manifest); + assert.ok(record, "manifest has no path-bearing record"); + record.path = "../release-escape"; + await writeFile(path, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("path"); + + await mutatePayload(temporaryRoot, "normalization", async (root) => { + const path = resolve(root, "manifest.json"); + const bytes = await readFile(path); + await writeFile(path, Buffer.from(bytes.toString("utf8").replace(/\n/gu, "\r\n"))); + }, support.checkReleasePayload); + passed.push("normalization"); + + await mutatePayload(temporaryRoot, "proof-input", async (root) => { + const path = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(path, "utf8")); + const inputs = findProperty(manifest, "proof_inputs"); + assert.ok(Array.isArray(inputs) && inputs.length > 0, "manifest has no proof inputs"); + inputs.pop(); + await writeFile(path, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("proof-input"); + + await mutatePayload(temporaryRoot, "bundle-origin-alias", async (root) => { + const path = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(path, "utf8")); + const repositoryInputs = manifest.bundle_inputs.filter((record) => record.origin.kind === "repository"); + assert.ok(repositoryInputs.length >= 2); + repositoryInputs[0].origin.path = repositoryInputs[1].origin.path; + repositoryInputs[0].size = repositoryInputs[1].size; + repositoryInputs[0].digest = repositoryInputs[1].digest; + await writeFile(path, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("bundle-origin-alias"); + + await mutatePayload(temporaryRoot, "metafile-size", async (root) => { + const manifestPath = resolve(root, "manifest.json"); + const metafilePath = resolve(root, "metafile.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + const metafile = JSON.parse(await readFile(metafilePath, "utf8")); + const key = Object.keys(metafile.inputs)[0]; + metafile.inputs[key].bytes += 1; + const metafileBytes = Buffer.from(`${canonicalJson(metafile)}\n`); + await writeFile(metafilePath, metafileBytes); + const artifact = manifest.artifacts.find((record) => record.path === "metafile.json"); + artifact.size = metafileBytes.length; + artifact.digest = support.sha256(metafileBytes); + await writeFile(manifestPath, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("metafile-size"); + + await mutatePayload(temporaryRoot, "adjacent-map-expectation", async (root) => { + const path = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(path, "utf8")); + manifest.adjacent_map_expectations.pop(); + await writeFile(path, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("adjacent-map-expectation"); + + await mutatePayload(temporaryRoot, "launch-profile", async (root) => { + const path = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(path, "utf8")); + manifest.launch_profile.fixture_digests[0].digest = "0".repeat(64); + await writeFile(path, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("launch-profile"); + + await mutatePayload(temporaryRoot, "legal-output", async (root) => { + const manifestPath = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + const legalArtifact = manifest.artifacts.find((record) => record.role === "upstream-legal"); + const outputPath = resolve(root, legalArtifact.path); + const bytes = Buffer.concat([await readFile(outputPath), Buffer.from("substitution")]); + await writeFile(outputPath, bytes); + legalArtifact.size = bytes.length; + legalArtifact.digest = support.sha256(bytes); + await writeFile(manifestPath, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("legal-output"); + + await mutatePayload(temporaryRoot, "generated-notice", async (root) => { + const manifestPath = resolve(root, "manifest.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + const noticeArtifact = manifest.artifacts.find((record) => record.role === "legal-notice"); + const outputPath = resolve(root, noticeArtifact.path); + const bytes = Buffer.from("forged notice\n"); + await writeFile(outputPath, bytes); + noticeArtifact.size = bytes.length; + noticeArtifact.digest = support.sha256(bytes); + await writeFile(manifestPath, `${canonicalJson(manifest)}\n`); + }, support.checkReleasePayload); + passed.push("generated-notice"); + + const nonEmptyStage = resolve(temporaryRoot, "non-empty-stage"); + await mkdir(nonEmptyStage); + await writeFile(resolve(nonEmptyStage, "external-target-canary"), "must remain unchanged\n"); + await expectFailure("pre-existing write target", () => support.buildReleasePayload({ + repositoryRoot, + stageRoot: nonEmptyStage, + })); + assert.equal(await readFile(resolve(nonEmptyStage, "external-target-canary"), "utf8"), "must remain unchanged\n"); + passed.push("write-target"); + + const realStage = resolve(temporaryRoot, "real-stage"); + const symlinkStage = resolve(temporaryRoot, "symlink-stage"); + await mkdir(realStage); + await symlink(realStage, symlinkStage, "dir"); + await expectFailure("symlink write root", () => support.buildReleasePayload({ + repositoryRoot, + stageRoot: symlinkStage, + })); + passed.push("symlink-root"); + + for (const source of [ + 'const specifier = "node:net"; require(specifier);', + 'const specifier = "node:net"; await import(specifier);', + 'process.getBuiltinModule("node:net");', + 'const load = require; load("node:net");', + 'import { createRequire as cr } from "node:module"; const load = cr(import.meta.url); load("node:net");', + 'const nested = `${`${require("node:net")}`}`;', + ]) { + await expectFailure("residual loader", () => support.assertReleaseLoaderPolicy(`${support.RELEASE_BUILD_PROFILE.banner}\n${source}`)); + } + support.assertReleaseLoaderPolicy(`${support.RELEASE_BUILD_PROFILE.banner}\n// require("node:net")\nconst inert = "getBuiltinModule require(node:net)";`); + passed.push("loader-policy"); + + const rootStagePath = resolve(temporaryRoot, "overlap-stage"); + const rootStageSummary = await support.buildReleasePayload({ repositoryRoot, stageRoot: rootStagePath }); + await expectFailure("nested comparison", () => support.reproduceReleasePayload({ + repositoryRoot, + stage: { stageRoot: rootStagePath, summary: rootStageSummary }, + materializationRoot: resolve(temporaryRoot, "overlap-source"), + comparisonRoot: resolve(rootStagePath, "nested-comparison"), + })); + passed.push("nested-comparison"); + + const recoveryRoot = resolve(temporaryRoot, "transaction-recovery"); + await mkdir(resolve(recoveryRoot, ".archflow-dist-backup"), { recursive: true }); + await mkdir(resolve(recoveryRoot, ".archflow-dist-promotion"), { recursive: true }); + await writeFile(resolve(recoveryRoot, ".archflow-dist-backup/old"), "old\n"); + await writeFile(resolve(recoveryRoot, ".archflow-dist-promotion/new"), "new\n"); + await writeFile(resolve(recoveryRoot, ".archflow-dist-transaction.json"), `${canonicalJson({ + candidate_manifest_digest: "a".repeat(64), + had_dist: true, + schema_version: "1", + })}\n`); + await support.recoverTrackedRelease(recoveryRoot); + assert.equal(await readFile(resolve(recoveryRoot, "dist/old"), "utf8"), "old\n"); + await mkdir(resolve(recoveryRoot, ".archflow-dist-backup")); + await writeFile(resolve(recoveryRoot, ".archflow-dist-backup/old"), "old\n"); + await mkdir(resolve(recoveryRoot, ".archflow-dist-promotion")); + await writeFile(resolve(recoveryRoot, ".archflow-dist-promotion/uninstalled"), "new\n"); + await rename(resolve(recoveryRoot, "dist"), resolve(recoveryRoot, "retained-old")); + await mkdir(resolve(recoveryRoot, "dist")); + await writeFile(resolve(recoveryRoot, "dist/new"), "new\n"); + await writeFile(resolve(recoveryRoot, ".archflow-dist-transaction.json"), `${canonicalJson({ + candidate_manifest_digest: "b".repeat(64), + had_dist: true, + schema_version: "1", + })}\n`); + await support.recoverTrackedRelease(recoveryRoot); + assert.equal(await readFile(resolve(recoveryRoot, "dist/new"), "utf8"), "new\n"); + passed.push("transaction-recovery"); + + process.stdout.write(`${canonicalJson({ mutations: passed, status: "passed" })}\n`); + } finally { + await rm(temporaryRoot, { force: true, recursive: true }); + } +} + +main().catch((error) => { + process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); + process.exitCode = 1; +}); diff --git a/scripts/write-tracked-release.mjs b/scripts/write-tracked-release.mjs new file mode 100644 index 00000000..cab71ab9 --- /dev/null +++ b/scripts/write-tracked-release.mjs @@ -0,0 +1,20 @@ +import { fileURLToPath } from "node:url"; +import { resolve } from "node:path"; + +import { + parseCli, + runCli, + writeCanonicalSummary, + writeTrackedReleasePayload, +} from "./release-support.mjs"; + +const repositoryRoot = resolve(fileURLToPath(new URL("..", import.meta.url))); + +runCli(async () => { + const { candidateStageRoot } = parseCli(process.argv.slice(2), { + "--stage": "candidateStageRoot", + required: ["candidateStageRoot"], + usage: "npm run release:write -- --stage ", + }); + writeCanonicalSummary(await writeTrackedReleasePayload({ repositoryRoot, candidateStageRoot })); +}); diff --git a/src/contracts/schemas/v1/release-legal-review.schema.json b/src/contracts/schemas/v1/release-legal-review.schema.json new file mode 100644 index 00000000..d192f90a --- /dev/null +++ b/src/contracts/schemas/v1/release-legal-review.schema.json @@ -0,0 +1,392 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:release-legal-review", + "title": "ArchFlow Release Legal Review v1", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "project_license_status", + "distribution_status", + "inventory_method", + "limitations", + "current_components", + "dependency_gate_decisions", + "amendments", + "supersessions", + "upstream_legal_sources" + ], + "properties": { + "schema_version": { "const": "1" }, + "project_license_status": { "const": "missing" }, + "distribution_status": { "const": "unresolved" }, + "inventory_method": { "const": "conservative-mapped-component-inventory" }, + "limitations": { + "type": "array", + "items": { "type": "string", "minLength": 1 }, + "x-archflow-sorted-unique": true + }, + "current_components": { + "type": "array", + "items": { "$ref": "#/$defs/current_component" }, + "x-archflow-unique-by": "component_id" + }, + "dependency_gate_decisions": { + "type": "array", + "items": { "$ref": "#/$defs/gate_decision" }, + "x-archflow-unique-by": "id" + }, + "amendments": { + "type": "array", + "items": { "$ref": "#/$defs/amendment" }, + "x-archflow-unique-by": "id" + }, + "supersessions": { + "type": "array", + "items": { "$ref": "#/$defs/supersession" }, + "uniqueItems": true, + "x-archflow-unique-by": "superseded_decision_id" + }, + "upstream_legal_sources": { + "type": "array", + "items": { "$ref": "#/$defs/upstream_legal_source" }, + "x-archflow-unique-by": "source_path" + } + }, + "$defs": { + "digest": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "portable_path": { + "type": "string", + "minLength": 1, + "pattern": "^(?![A-Za-z]:)(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//)[^/]+(?:/[^/]+)*$" + }, + "stable_id": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" }, + "package_name": { "type": "string", "minLength": 1, "pattern": "^(?:@[^/\\s]+/)?[^/\\s]+$" }, + "package_version": { "type": "string", "minLength": 1, "pattern": "^[^\\s]+$" }, + "current_component": { + "type": "object", + "additionalProperties": false, + "allOf": [ + { + "if": { "type": "object", "properties": { "provenance_kind": { "const": "embedded" } }, "required": ["provenance_kind"] }, + "then": { + "type": "object", + "properties": { + "package_identity": { + "type": "object", + "properties": { "authority": { "const": "npm-registry-artifact" } } + } + } + } + }, + { + "if": { "type": "object", "properties": { "provenance_kind": { "const": "installed" } }, "required": ["provenance_kind"] }, + "then": { + "type": "object", + "properties": { + "package_identity": { + "type": "object", + "properties": { "authority": { "const": "package-lock" } } + } + } + } + } + ], + "required": [ + "component_id", + "package_name", + "package_version", + "provenance_kind", + "source_root", + "license_expression", + "legal_source", + "package_identity", + "provenance_inputs", + "source_map_expected" + ], + "properties": { + "component_id": { "$ref": "#/$defs/stable_id" }, + "package_name": { "$ref": "#/$defs/package_name" }, + "package_version": { "$ref": "#/$defs/package_version" }, + "provenance_kind": { "enum": ["installed", "embedded"] }, + "source_root": { "$ref": "#/$defs/portable_path" }, + "license_expression": { "type": "string", "minLength": 1 }, + "legal_source": { "$ref": "#/$defs/legal_source_binding" }, + "package_identity": { "$ref": "#/$defs/package_identity" }, + "provenance_inputs": { + "type": "array", + "items": { "$ref": "#/$defs/dependency_reference" }, + "x-archflow-unique-by": ["package_name", "package_version", "package_relative_path"] + }, + "source_map_expected": { "type": "boolean" } + } + }, + "dependency_reference": { + "type": "object", + "additionalProperties": false, + "required": ["package_name", "package_version", "package_relative_path"], + "properties": { + "package_name": { "$ref": "#/$defs/package_name" }, + "package_version": { "$ref": "#/$defs/package_version" }, + "package_relative_path": { "$ref": "#/$defs/portable_path" } + } + }, + "legal_source_binding": { + "type": "object", + "additionalProperties": false, + "required": ["source_path", "payload_path", "digest"], + "properties": { + "source_path": { "$ref": "#/$defs/portable_path" }, + "payload_path": { "$ref": "#/$defs/portable_path" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "package_identity": { + "type": "object", + "additionalProperties": false, + "required": ["authority", "tarball_url", "integrity"], + "properties": { + "authority": { "enum": ["package-lock", "npm-registry-artifact"] }, + "tarball_url": { "type": "string", "format": "uri", "pattern": "^https://registry\\.npmjs\\.org/" }, + "integrity": { "type": "string", "pattern": "^sha512-[A-Za-z0-9+/]+={0,2}$" } + } + }, + "entry_binding": { + "type": "object", + "additionalProperties": false, + "required": ["id", "role", "handler_authority"], + "properties": { + "id": { "$ref": "#/$defs/stable_id" }, + "role": { "enum": ["mcp-stdio", "local-cli"] }, + "handler_authority": { "enum": ["inert-no-handler", "local-cli-handler"] } + } + }, + "advisory": { + "type": "object", + "additionalProperties": false, + "required": ["id", "severity", "affected_version", "safe_version"], + "properties": { + "id": { "type": "string", "pattern": "^GHSA-[23456789cfghjmpqrvwx]{4}-[23456789cfghjmpqrvwx]{4}-[23456789cfghjmpqrvwx]{4}$" }, + "severity": { "enum": ["low", "moderate", "high", "critical"] }, + "affected_version": { "$ref": "#/$defs/package_version" }, + "safe_version": { "$ref": "#/$defs/package_version" }, + "source_url": { "type": "string", "format": "uri", "pattern": "^https://github\\.com/advisories/GHSA-" } + } + }, + "gate_decision": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "decision_digest", + "status", + "scope", + "package_name", + "package_version", + "advisories", + "bundle_digest", + "entry_bindings", + "dependency_inventory_digest", + "advisory_snapshot", + "patched_artifact_availability", + "reachability_evidence", + "user_acceptance" + ], + "properties": { + "id": { "$ref": "#/$defs/stable_id" }, + "decision_digest": { "$ref": "#/$defs/digest" }, + "status": { "const": "accepted" }, + "scope": { "$ref": "#/$defs/risk_scope" }, + "package_name": { "$ref": "#/$defs/package_name" }, + "package_version": { "$ref": "#/$defs/package_version" }, + "advisories": { + "type": "array", + "minItems": 4, + "maxItems": 4, + "items": { "$ref": "#/$defs/advisory" }, + "x-archflow-unique-by": "id" + }, + "bundle_digest": { "$ref": "#/$defs/digest" }, + "entry_bindings": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/entry_binding" }, + "x-archflow-unique-by": "id" + }, + "dependency_inventory_digest": { "$ref": "#/$defs/digest" }, + "advisory_snapshot": { "$ref": "#/$defs/advisory_snapshot_binding" }, + "patched_artifact_availability": { "$ref": "#/$defs/artifact_availability_binding" }, + "reachability_evidence": { "$ref": "#/$defs/reachability_binding" }, + "user_acceptance": { "$ref": "#/$defs/user_acceptance_binding" } + } + }, + "evidence_binding": { + "type": "object", + "additionalProperties": false, + "required": ["path", "digest"], + "properties": { + "path": { "$ref": "#/$defs/portable_path" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "advisory_snapshot_binding": { + "allOf": [ + { "$ref": "#/$defs/evidence_binding" }, + { "type": "object", "properties": { "path": { "const": "release/evidence/advisory-snapshot.json" } } } + ] + }, + "artifact_availability_binding": { + "allOf": [ + { "$ref": "#/$defs/evidence_binding" }, + { "type": "object", "properties": { "path": { "const": "release/evidence/patched-artifact-availability.json" } } } + ] + }, + "reachability_binding": { + "allOf": [ + { "$ref": "#/$defs/evidence_binding" }, + { "type": "object", "properties": { "path": { "const": "release/evidence/focused-inert-reachability.json" } } } + ] + }, + "user_acceptance_binding": { + "allOf": [ + { "$ref": "#/$defs/evidence_binding" }, + { "type": "object", "properties": { "path": { "const": "release/evidence/user-risk-acceptance.json" } } } + ] + }, + "risk_scope": { + "type": "object", + "additionalProperties": false, + "required": ["deployment", "operators", "production", "handler_authority", "invalidated_by"], + "properties": { + "deployment": { "const": "local-only" }, + "operators": { "const": "user-owned-agents" }, + "production": { "const": false }, + "handler_authority": { "const": "inert-no-handler" }, + "invalidated_by": { + "type": "array", + "minItems": 4, + "uniqueItems": true, + "items": { "enum": ["bundle-change", "dependency-change", "entry-change", "handler-authority-change"] }, + "x-archflow-sorted-unique": true + } + } + }, + "amendment": { + "type": "object", + "additionalProperties": false, + "required": ["id", "amendment_digest", "decision_id", "prior_decision_digest", "reason", "evidence"], + "properties": { + "id": { "$ref": "#/$defs/stable_id" }, + "amendment_digest": { "$ref": "#/$defs/digest" }, + "decision_id": { "$ref": "#/$defs/stable_id" }, + "prior_decision_digest": { "$ref": "#/$defs/digest" }, + "reason": { "type": "string", "minLength": 1 }, + "evidence": { "$ref": "#/$defs/evidence_binding" } + } + }, + "supersession": { + "type": "object", + "additionalProperties": false, + "required": ["id", "supersession_digest", "superseded_decision_id", "superseded_decision_digest", "replacement_decision_id", "replacement_decision_digest", "reason", "evidence"], + "properties": { + "id": { "$ref": "#/$defs/stable_id" }, + "supersession_digest": { "$ref": "#/$defs/digest" }, + "superseded_decision_id": { "$ref": "#/$defs/stable_id" }, + "superseded_decision_digest": { "$ref": "#/$defs/digest" }, + "replacement_decision_id": { "$ref": "#/$defs/stable_id" }, + "replacement_decision_digest": { "$ref": "#/$defs/digest" }, + "reason": { "type": "string", "minLength": 1 }, + "evidence": { "$ref": "#/$defs/evidence_binding" } + } + }, + "upstream_legal_source": { + "type": "object", + "additionalProperties": false, + "required": ["component_id", "source_path", "payload_path", "digest", "package_identity"], + "properties": { + "component_id": { "$ref": "#/$defs/stable_id" }, + "source_path": { "$ref": "#/$defs/portable_path" }, + "payload_path": { "$ref": "#/$defs/portable_path" }, + "digest": { "$ref": "#/$defs/digest" }, + "package_identity": { "$ref": "#/$defs/package_identity" } + } + }, + "advisory_snapshot_record": { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "record_type", "observed_on", "package_name", "package_version", "safe_version_floor", "advisories"], + "properties": { + "schema_version": { "const": "1" }, + "record_type": { "const": "advisory-snapshot" }, + "observed_on": { "type": "string", "format": "date" }, + "package_name": { "$ref": "#/$defs/package_name" }, + "package_version": { "$ref": "#/$defs/package_version" }, + "safe_version_floor": { "$ref": "#/$defs/package_version" }, + "advisories": { + "type": "array", + "minItems": 4, + "maxItems": 4, + "items": { + "allOf": [ + { "$ref": "#/$defs/advisory" }, + { + "type": "object", + "required": ["source_url"], + "properties": { "source_url": { "type": "string", "format": "uri", "pattern": "^https://github\\.com/advisories/GHSA-" } } + } + ] + }, + "x-archflow-unique-by": "id" + } + } + }, + "artifact_availability_record": { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "record_type", "observed_on", "server_package", "server_version", "embedded_package", "embedded_version", "safe_version_floor", "compatible_patched_artifact_available", "registry_source"], + "properties": { + "schema_version": { "const": "1" }, + "record_type": { "const": "patched-artifact-availability" }, + "observed_on": { "type": "string", "format": "date" }, + "server_package": { "const": "@modelcontextprotocol/server" }, + "server_version": { "const": "2.0.0" }, + "embedded_package": { "const": "fast-uri" }, + "embedded_version": { "const": "3.1.0" }, + "safe_version_floor": { "const": "3.1.4" }, + "compatible_patched_artifact_available": { "const": false }, + "registry_source": { "type": "string", "format": "uri" } + } + }, + "reachability_record": { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "record_type", "observed_on", "bundle_digest", "entry_bindings", "trusted_schema_compilation_reachable", "untrusted_json_rpc_route_identified", "finding", "limitations"], + "properties": { + "schema_version": { "const": "1" }, + "record_type": { "const": "focused-inert-reachability" }, + "observed_on": { "type": "string", "format": "date" }, + "bundle_digest": { "$ref": "#/$defs/digest" }, + "entry_bindings": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/entry_binding" }, "x-archflow-unique-by": "id" }, + "trusted_schema_compilation_reachable": { "const": true }, + "untrusted_json_rpc_route_identified": { "const": false }, + "finding": { "type": "string", "minLength": 1 }, + "limitations": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 1 }, "uniqueItems": true, "x-archflow-sorted-unique": true } + } + }, + "user_acceptance_record": { + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "record_type", "accepted_on", "acceptance_text", "package_name", "package_version", "advisory_ids", "scope"], + "properties": { + "schema_version": { "const": "1" }, + "record_type": { "const": "user-risk-acceptance" }, + "accepted_on": { "type": "string", "format": "date" }, + "acceptance_text": { "type": "string", "minLength": 1 }, + "package_name": { "const": "fast-uri" }, + "package_version": { "const": "3.1.0" }, + "advisory_ids": { "const": ["GHSA-4c8g-83qw-93j6", "GHSA-q3j6-qgpj-74h6", "GHSA-v2hh-gcrm-f6hx", "GHSA-v39h-62p7-jpjc"] }, + "scope": { "$ref": "#/$defs/risk_scope" } + } + } + } +} diff --git a/src/contracts/schemas/v1/release-manifest.schema.json b/src/contracts/schemas/v1/release-manifest.schema.json new file mode 100644 index 00000000..1a9517f0 --- /dev/null +++ b/src/contracts/schemas/v1/release-manifest.schema.json @@ -0,0 +1,379 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:archflow:schema:v1:release-manifest", + "title": "ArchFlow Release Manifest v1", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "bundle_digest", + "dependency_inventory_digest", + "bundle_inputs", + "contributing_inputs", + "release_control_inputs", + "dependency_provenance_inputs", + "adjacent_map_expectations", + "proof_inputs", + "declared_content", + "build_entries", + "launch_profile", + "legal_review", + "artifacts" + ], + "properties": { + "schema_version": { "const": "1" }, + "bundle_digest": { "$ref": "#/$defs/digest" }, + "dependency_inventory_digest": { "$ref": "#/$defs/digest" }, + "bundle_inputs": { + "type": "array", + "items": { "$ref": "#/$defs/bundle_input" }, + "x-archflow-unique-by": "key" + }, + "contributing_inputs": { + "type": "array", + "items": { "$ref": "#/$defs/metafile_key" }, + "x-archflow-sorted-unique": true + }, + "release_control_inputs": { + "type": "array", + "items": { "$ref": "#/$defs/repository_file" }, + "x-archflow-unique-by": "path" + }, + "dependency_provenance_inputs": { + "type": "array", + "items": { "$ref": "#/$defs/dependency_file" }, + "x-archflow-unique-by": ["package_name", "package_version", "package_relative_path"] + }, + "adjacent_map_expectations": { + "type": "array", + "items": { "$ref": "#/$defs/adjacent_map_expectation" }, + "x-archflow-unique-by": "input_key" + }, + "proof_inputs": { + "type": "array", + "items": { "$ref": "#/$defs/portable_path" }, + "x-archflow-sorted-unique": true + }, + "declared_content": { "$ref": "#/$defs/declared_content" }, + "build_entries": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/build_entry" }, + "x-archflow-unique-by": "id" + }, + "launch_profile": { "$ref": "#/$defs/launch_profile" }, + "legal_review": { "$ref": "#/$defs/legal_review_binding" }, + "artifacts": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/artifact" }, + "x-archflow-unique-by": "path" + } + }, + "$defs": { + "digest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "portable_path": { + "type": "string", + "minLength": 1, + "pattern": "^(?![A-Za-z]:)(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//)[^/]+(?:/[^/]+)*$" + }, + "metafile_key": { + "type": "string", + "minLength": 1, + "pattern": "^(?![A-Za-z]:)(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//)[^/]+(?:/[^/]+)*$" + }, + "dependency_prebundle_key": { + "type": "string", + "pattern": "^node_modules/(?:@[^/]+/)?[^/]+/.+\\.mjs$" + }, + "byte_size": { + "type": "integer", + "minimum": 0 + }, + "package_name": { + "type": "string", + "minLength": 1, + "pattern": "^(?:@[^/\\s]+/)?[^/\\s]+$" + }, + "package_version": { + "type": "string", + "minLength": 1, + "pattern": "^[^\\s]+$" + }, + "repository_origin": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "path"], + "properties": { + "kind": { "const": "repository" }, + "path": { "$ref": "#/$defs/portable_path" } + } + }, + "dependency_origin": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "package_name", "package_version", "package_relative_path"], + "properties": { + "kind": { "const": "dependency" }, + "package_name": { "$ref": "#/$defs/package_name" }, + "package_version": { "$ref": "#/$defs/package_version" }, + "package_relative_path": { "$ref": "#/$defs/portable_path" } + } + }, + "bundle_input": { + "type": "object", + "additionalProperties": false, + "required": ["key", "origin", "size", "digest", "bytes_in_output"], + "properties": { + "key": { "$ref": "#/$defs/metafile_key" }, + "origin": { + "oneOf": [ + { "$ref": "#/$defs/repository_origin" }, + { "$ref": "#/$defs/dependency_origin" } + ] + }, + "size": { "$ref": "#/$defs/byte_size" }, + "digest": { "$ref": "#/$defs/digest" }, + "bytes_in_output": { "$ref": "#/$defs/byte_size" } + } + }, + "repository_file": { + "type": "object", + "additionalProperties": false, + "required": ["path", "size", "digest"], + "properties": { + "path": { "$ref": "#/$defs/portable_path" }, + "size": { "$ref": "#/$defs/byte_size" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "dependency_file": { + "type": "object", + "additionalProperties": false, + "required": ["package_name", "package_version", "package_relative_path", "purpose", "size", "digest"], + "properties": { + "package_name": { "$ref": "#/$defs/package_name" }, + "package_version": { "$ref": "#/$defs/package_version" }, + "package_relative_path": { "$ref": "#/$defs/portable_path" }, + "purpose": { + "enum": ["package-manifest", "source-map", "license", "notice", "provenance"] + }, + "size": { "$ref": "#/$defs/byte_size" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "dependency_reference": { + "type": "object", + "additionalProperties": false, + "required": ["package_name", "package_version", "package_relative_path", "digest"], + "properties": { + "package_name": { "$ref": "#/$defs/package_name" }, + "package_version": { "$ref": "#/$defs/package_version" }, + "package_relative_path": { "$ref": "#/$defs/portable_path" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "dependency_map_reference": { + "type": "object", + "additionalProperties": false, + "required": ["package_name", "package_version", "package_relative_path", "digest"], + "properties": { + "package_name": { "$ref": "#/$defs/package_name" }, + "package_version": { "$ref": "#/$defs/package_version" }, + "package_relative_path": { "type": "string", "pattern": "^[^\\\\]+\\.mjs\\.map$" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "adjacent_map_expectation": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "required": ["input_key", "expectation", "map", "reviewed_first_party_roots", "recognized_third_party_components"], + "properties": { + "input_key": { "$ref": "#/$defs/dependency_prebundle_key" }, + "expectation": { "const": "present" }, + "map": { "$ref": "#/$defs/dependency_map_reference" }, + "reviewed_first_party_roots": { + "type": "array", + "items": { "type": "string", "minLength": 1 }, + "uniqueItems": true, + "x-archflow-sorted-unique": true + }, + "recognized_third_party_components": { + "type": "array", + "items": { "type": "string", "pattern": "^(?:@[^/\\s]+/)?[^@/\\s]+@[^\\s]+$" }, + "uniqueItems": true, + "x-archflow-sorted-unique": true + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": ["input_key", "expectation", "rationale"], + "properties": { + "input_key": { "$ref": "#/$defs/dependency_prebundle_key" }, + "expectation": { "const": "expected-absent" }, + "rationale": { "type": "string", "minLength": 1 } + } + } + ] + }, + "declared_content": { + "type": "object", + "additionalProperties": false, + "required": ["schemas", "workflow", "constitution"], + "properties": { + "schemas": { + "type": "array", + "items": { "$ref": "#/$defs/portable_path" }, + "x-archflow-sorted-unique": true + }, + "workflow": { "const": "assets/workflow.yaml" }, + "constitution": { + "type": "array", + "items": { "$ref": "#/$defs/portable_path" }, + "x-archflow-sorted-unique": true + } + } + }, + "build_entry": { + "type": "object", + "additionalProperties": false, + "required": ["id", "role", "entry_point", "output_path", "handler_authority"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" }, + "role": { "enum": ["mcp-stdio", "local-cli"] }, + "entry_point": { "$ref": "#/$defs/portable_path" }, + "output_path": { "$ref": "#/$defs/portable_path" }, + "handler_authority": { "enum": ["inert-no-handler", "local-cli-handler"] } + } + }, + "launch_profile": { + "type": "object", + "additionalProperties": false, + "required": [ + "node_major", + "executable", + "argv", + "environment_keys", + "removed_environment_keys", + "cwd_class", + "stdio", + "guard_path", + "canary_paths", + "fixture_digests", + "allowed_imports" + ], + "properties": { + "node_major": { "const": 24 }, + "executable": { "const": "process.execPath" }, + "argv": { + "const": ["--require", "hostile-runtime-guard.cjs", "archflow-mcp.mjs"] + }, + "environment_keys": { + "const": ["HOME", "LANG", "LC_ALL", "NPM_CONFIG_CACHE", "PATH", "TMPDIR", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME"] + }, + "removed_environment_keys": { + "const": ["NODE_OPTIONS", "NODE_PATH"] + }, + "cwd_class": { "const": "copied-payload" }, + "stdio": { + "type": "object", + "additionalProperties": false, + "required": ["stdin", "stdout", "stderr", "guard_fd"], + "properties": { + "stdin": { "const": "pipe" }, + "stdout": { "const": "pipe" }, + "stderr": { "const": "pipe" }, + "guard_fd": { "const": 3 } + } + }, + "guard_path": { "const": "test/fixtures/release/hostile-runtime-guard.cjs" }, + "canary_paths": { + "const": ["ambient/node_modules/archflow-release-canary/index.js", "repository-canary/SECRET"] + }, + "fixture_digests": { + "type": "array", + "minItems": 3, + "maxItems": 3, + "prefixItems": [ + { "$ref": "#/$defs/adversarial_fixture" }, + { "$ref": "#/$defs/calls_fixture" }, + { "$ref": "#/$defs/initialize_fixture" } + ], + "items": false, + "x-archflow-unique-by": "path" + }, + "allowed_imports": { + "const": ["node:buffer", "node:crypto", "node:module", "node:process", "node:util"] + } + } + }, + "adversarial_fixture": { + "type": "object", + "additionalProperties": false, + "required": ["path", "digest"], + "properties": { + "path": { "const": "test/fixtures/mcp/runtime/adversarial-bytes.json" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "calls_fixture": { + "type": "object", + "additionalProperties": false, + "required": ["path", "digest"], + "properties": { + "path": { "const": "test/fixtures/mcp/runtime/calls.json" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "initialize_fixture": { + "type": "object", + "additionalProperties": false, + "required": ["path", "digest"], + "properties": { + "path": { "const": "test/fixtures/mcp/runtime/initialize.json" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "legal_review_binding": { + "type": "object", + "additionalProperties": false, + "required": ["source_path", "payload_path", "digest"], + "properties": { + "source_path": { "const": "release/legal-review.json" }, + "payload_path": { "const": "legal/review.json" }, + "digest": { "$ref": "#/$defs/digest" } + } + }, + "artifact": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "required": ["path", "role"], + "properties": { + "path": { "const": "manifest.json" }, + "role": { "const": "manifest" } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": ["path", "role", "size", "digest"], + "properties": { + "path": { "$ref": "#/$defs/portable_path" }, + "role": { "enum": ["executable", "metafile", "legal-review", "legal-notice", "upstream-legal"] }, + "size": { "$ref": "#/$defs/byte_size" }, + "digest": { "$ref": "#/$defs/digest" } + } + } + ] + } + } +} diff --git a/src/contracts/versions.ts b/src/contracts/versions.ts index 40c5c542..3214cdc7 100644 --- a/src/contracts/versions.ts +++ b/src/contracts/versions.ts @@ -22,5 +22,7 @@ export const SCHEMA_IDS = { protocolError: "urn:archflow:schema:v1:protocol-error", mcpTools: "https://archflow.dev/schemas/v1/mcp-tools", resultExpectation: "https://archflow.dev/schemas/v1/result-expectation", - pathClaim: "urn:archflow:schema:v1:path-claim" + pathClaim: "urn:archflow:schema:v1:path-claim", + releaseManifest: "urn:archflow:schema:v1:release-manifest", + releaseLegalReview: "urn:archflow:schema:v1:release-legal-review" } as const; diff --git a/test/contracts/release-contracts.test.ts b/test/contracts/release-contracts.test.ts new file mode 100644 index 00000000..ca6a13a9 --- /dev/null +++ b/test/contracts/release-contracts.test.ts @@ -0,0 +1,396 @@ +import { readFile } from "node:fs/promises"; + +import { describe, expect, it } from "vitest"; + +import { createJsonSchemaValidator } from "../../src/contracts/validators.js"; + +const digest = (character: string): string => character.repeat(64); + +const loadSchema = async (name: string): Promise> => + JSON.parse( + await readFile( + new URL(`../../src/contracts/schemas/v1/${name}.schema.json`, import.meta.url), + "utf8", + ), + ) as Record; + +const loadReleaseEvidence = async (name: string): Promise> => + JSON.parse( + await readFile(new URL(`../../release/evidence/${name}.json`, import.meta.url), "utf8"), + ) as Record; + +const evidenceValidator = async (definition: string) => { + const legalSchema = await loadSchema("release-legal-review"); + return createJsonSchemaValidator( + { + $schema: "https://json-schema.org/draft/2020-12/schema", + $id: `urn:archflow:test:${definition}`, + $ref: `urn:archflow:schema:v1:release-legal-review#/$defs/${definition}`, + }, + [legalSchema], + ); +}; + +const createManifest = (): Record => ({ + schema_version: "1", + bundle_digest: digest("a"), + dependency_inventory_digest: digest("b"), + bundle_inputs: [ + { + key: "node_modules/example/prebundle.mjs", + origin: { + kind: "dependency", + package_name: "example", + package_version: "1.2.3", + package_relative_path: "prebundle.mjs", + }, + size: 120, + digest: digest("c"), + bytes_in_output: 80, + }, + { + key: "src/main.ts", + origin: { kind: "repository", path: "src/main.ts" }, + size: 40, + digest: digest("d"), + bytes_in_output: 0, + }, + ], + contributing_inputs: ["node_modules/example/prebundle.mjs"], + release_control_inputs: [ + { path: "package-lock.json", size: 10, digest: digest("e") }, + { path: "package.json", size: 20, digest: digest("f") }, + ], + dependency_provenance_inputs: [ + { + package_name: "example", + package_version: "1.2.3", + package_relative_path: "package.json", + purpose: "package-manifest", + size: 30, + digest: digest("1"), + }, + { + package_name: "example", + package_version: "1.2.3", + package_relative_path: "prebundle.mjs.map", + purpose: "source-map", + size: 50, + digest: digest("2"), + }, + ], + adjacent_map_expectations: [ + { + input_key: "node_modules/example/prebundle.mjs", + expectation: "present", + map: { + package_name: "example", + package_version: "1.2.3", + package_relative_path: "prebundle.mjs.map", + digest: digest("2"), + }, + reviewed_first_party_roots: ["example/src"], + recognized_third_party_components: ["fast-uri@3.1.0"], + }, + ], + proof_inputs: ["package.json", "test/integration/release-offline.test.ts"], + declared_content: { + schemas: ["src/contracts/schemas/v1/release-manifest.schema.json"], + workflow: "assets/workflow.yaml", + constitution: [ + "assets/constitution/00-process.md", + "assets/constitution/README.md", + ], + }, + build_entries: [ + { + id: "mcp-stdio", + role: "mcp-stdio", + entry_point: "src/main.ts", + output_path: "archflow-mcp.mjs", + handler_authority: "inert-no-handler", + }, + ], + launch_profile: { + node_major: 24, + executable: "process.execPath", + argv: ["--require", "hostile-runtime-guard.cjs", "archflow-mcp.mjs"], + environment_keys: ["HOME", "LANG", "LC_ALL", "NPM_CONFIG_CACHE", "PATH", "TMPDIR", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME"], + removed_environment_keys: ["NODE_OPTIONS", "NODE_PATH"], + cwd_class: "copied-payload", + stdio: { stdin: "pipe", stdout: "pipe", stderr: "pipe", guard_fd: 3 }, + guard_path: "test/fixtures/release/hostile-runtime-guard.cjs", + canary_paths: ["ambient/node_modules/archflow-release-canary/index.js", "repository-canary/SECRET"], + fixture_digests: [ + { path: "test/fixtures/mcp/runtime/adversarial-bytes.json", digest: digest("1") }, + { path: "test/fixtures/mcp/runtime/calls.json", digest: digest("2") }, + { path: "test/fixtures/mcp/runtime/initialize.json", digest: digest("3") }, + ], + allowed_imports: ["node:buffer", "node:crypto", "node:module", "node:process", "node:util"], + }, + legal_review: { + source_path: "release/legal-review.json", + payload_path: "legal/review.json", + digest: digest("4"), + }, + artifacts: [ + { path: "archflow-mcp.mjs", role: "executable", size: 200, digest: digest("a") }, + { path: "legal/review.json", role: "legal-review", size: 60, digest: digest("4") }, + { path: "manifest.json", role: "manifest" }, + { path: "metafile.json", role: "metafile", size: 90, digest: digest("5") }, + ], +}); + +const createLegalReview = (): Record => ({ + schema_version: "1", + project_license_status: "missing", + distribution_status: "unresolved", + inventory_method: "conservative-mapped-component-inventory", + limitations: [ + "AJV JSON sources may be absent from source-map source content.", + "Mapped components do not prove exact physical-byte attribution.", + ], + current_components: [ + { + component_id: "fast-uri-embedded", + package_name: "fast-uri", + package_version: "3.1.0", + provenance_kind: "embedded", + source_root: "fast-uri/lib", + license_expression: "BSD-3-Clause", + legal_source: { + source_path: "release/legal/upstream/fast-uri-3.1.0/LICENSE", + payload_path: "legal/upstream/fast-uri-3.1.0/LICENSE", + digest: digest("9"), + }, + package_identity: { + authority: "npm-registry-artifact", + tarball_url: "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + integrity: "sha512-aGVsbG8=", + }, + provenance_inputs: [ + { + package_name: "@modelcontextprotocol/server", + package_version: "2.0.0", + package_relative_path: "dist/cjs/server/index.js.map", + }, + ], + source_map_expected: true, + }, + ], + dependency_gate_decisions: [ + { + id: "fast-uri-3-1-0-local-risk", + decision_digest: digest("6"), + status: "accepted", + scope: { + deployment: "local-only", + operators: "user-owned-agents", + production: false, + handler_authority: "inert-no-handler", + invalidated_by: [ + "bundle-change", + "dependency-change", + "entry-change", + "handler-authority-change", + ], + }, + package_name: "fast-uri", + package_version: "3.1.0", + advisories: [ + { id: "GHSA-4c8g-83qw-93j6", severity: "high", affected_version: "3.1.0", safe_version: "3.1.3" }, + { id: "GHSA-q3j6-qgpj-74h6", severity: "high", affected_version: "3.1.0", safe_version: "3.1.1" }, + { id: "GHSA-v2hh-gcrm-f6hx", severity: "high", affected_version: "3.1.0", safe_version: "3.1.4" }, + { id: "GHSA-v39h-62p7-jpjc", severity: "high", affected_version: "3.1.0", safe_version: "3.1.2" }, + ], + bundle_digest: digest("a"), + entry_bindings: [ + { id: "mcp-stdio", role: "mcp-stdio", handler_authority: "inert-no-handler" }, + ], + dependency_inventory_digest: digest("b"), + advisory_snapshot: { path: "release/evidence/advisory-snapshot.json", digest: digest("7") }, + patched_artifact_availability: { path: "release/evidence/patched-artifact-availability.json", digest: digest("8") }, + reachability_evidence: { path: "release/evidence/focused-inert-reachability.json", digest: digest("9") }, + user_acceptance: { path: "release/evidence/user-risk-acceptance.json", digest: digest("0") }, + }, + ], + amendments: [], + supersessions: [], + upstream_legal_sources: [ + { + component_id: "fast-uri-embedded", + source_path: "release/legal/upstream/fast-uri/LICENSE", + payload_path: "legal/upstream/fast-uri/LICENSE", + digest: digest("9"), + package_identity: { + authority: "npm-registry-artifact", + tarball_url: "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + integrity: "sha512-aGVsbG8=", + }, + }, + ], +}); + +describe("release manifest structural authority", () => { + it("accepts closed physical-input, proof, launch, and artifact records", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-manifest")); + expect(validator.assert(createManifest())).toEqual(expect.any(Object)); + }); + + it("retains scanned zero-byte inputs without treating them as contributors", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-manifest")); + const manifest = createManifest(); + expect(validator.assert(manifest)).toEqual(expect.any(Object)); + expect(manifest.contributing_inputs).toEqual(["node_modules/example/prebundle.mjs"]); + }); + + it("rejects unknown nested data, non-portable paths, malformed digests, and duplicate authorities", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-manifest")); + const unknown = structuredClone(createManifest()); + (unknown.launch_profile as Record).ambient_environment = true; + expect(() => validator.assert(unknown)).toThrow(/additional properties/iu); + + const escaped = structuredClone(createManifest()); + (escaped.release_control_inputs as Array>)[0]!.path = "../package-lock.json"; + expect(() => validator.assert(escaped)).toThrow(/pattern/iu); + + const badDigest = structuredClone(createManifest()); + badDigest.bundle_digest = "ABC"; + expect(() => validator.assert(badDigest)).toThrow(/pattern/iu); + + const duplicate = structuredClone(createManifest()); + (duplicate.release_control_inputs as unknown[]).push( + structuredClone((duplicate.release_control_inputs as unknown[])[0]), + ); + expect(() => validator.assert(duplicate)).toThrow(/x-archflow-unique-by/iu); + }); + + it("enumerates the manifest without requiring an impossible self-digest", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-manifest")); + const manifest = createManifest(); + const self = (manifest.artifacts as Array>).find( + (artifact) => artifact.role === "manifest", + ); + expect(self).toEqual({ path: "manifest.json", role: "manifest" }); + + const circular = structuredClone(manifest); + const circularSelf = (circular.artifacts as Array>).find( + (artifact) => artifact.role === "manifest", + )!; + circularSelf.digest = digest("0"); + expect(() => validator.assert(circular)).toThrow(/oneOf|additional properties/iu); + }); + + it("closes adjacent-map evidence and pins every structural launch identity", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-manifest")); + const absent = createManifest(); + absent.adjacent_map_expectations = [{ + input_key: "node_modules/example/prebundle.mjs", + expectation: "expected-absent", + rationale: "The reviewed package artifact ships no adjacent map for this prebundle.", + }]; + expect(validator.assert(absent)).toEqual(expect.any(Object)); + + const unreviewed = structuredClone(createManifest()); + delete ((unreviewed.adjacent_map_expectations as Array>)[0]!.map as Record).digest; + expect(() => validator.assert(unreviewed)).toThrow(/required/iu); + + const substitutedGuard = structuredClone(createManifest()); + (substitutedGuard.launch_profile as Record).guard_path = "test/fixtures/release/other.cjs"; + expect(() => validator.assert(substitutedGuard)).toThrow(/constant/iu); + + const duplicateFixture = structuredClone(createManifest()); + const fixtures = (duplicateFixture.launch_profile as Record).fixture_digests as Array>; + fixtures[1]!.path = fixtures[0]!.path; + expect(() => validator.assert(duplicateFixture)).toThrow(/constant|x-archflow-unique-by/iu); + }); +}); + +describe("release legal-review structural authority", () => { + it("records all four accepted advisories and digest-bound inert reachability scope", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-legal-review")); + const review = createLegalReview(); + expect(validator.assert(review)).toEqual(expect.any(Object)); + const [decision] = review.dependency_gate_decisions as Array>; + expect(decision!.advisories).toHaveLength(4); + expect(decision!.scope).toMatchObject({ + deployment: "local-only", + operators: "user-owned-agents", + production: false, + handler_authority: "inert-no-handler", + }); + }); + + it("requires the fields used by cross-document semantic correlation", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-legal-review")); + for (const field of [ + "bundle_digest", + "entry_bindings", + "dependency_inventory_digest", + "advisory_snapshot", + "patched_artifact_availability", + "reachability_evidence", + "user_acceptance", + ]) { + const review = createLegalReview(); + delete (review.dependency_gate_decisions as Array>)[0]![field]; + expect(() => validator.assert(review), field).toThrow(/required/iu); + } + }); + + it("fails closed on production scope, handler expansion, unknown fields, and unscoped provenance", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-legal-review")); + const production = createLegalReview(); + const productionScope = ((production.dependency_gate_decisions as Array>)[0]!.scope) as Record; + productionScope.production = true; + expect(() => validator.assert(production)).toThrow(/constant/iu); + + const expanded = createLegalReview(); + const expandedScope = ((expanded.dependency_gate_decisions as Array>)[0]!.scope) as Record; + expandedScope.handler_authority = "local-cli-handler"; + expect(() => validator.assert(expanded)).toThrow(/constant/iu); + + const unknown = createLegalReview(); + (unknown.current_components as Array>)[0]!.exact_physical_bytes = true; + expect(() => validator.assert(unknown)).toThrow(/additional properties/iu); + + const unscoped = createLegalReview(); + delete ((unscoped.current_components as Array>)[0]!.provenance_inputs as Array>)[0]!.package_version; + expect(() => validator.assert(unscoped)).toThrow(/required/iu); + }); + + it("requires immutable component identity, exact legal mapping, and append-only record evidence", async () => { + const validator = createJsonSchemaValidator(await loadSchema("release-legal-review")); + const missingIdentity = createLegalReview(); + delete (missingIdentity.current_components as Array>)[0]!.package_identity; + expect(() => validator.assert(missingIdentity)).toThrow(/required/iu); + + const missingMapping = createLegalReview(); + delete (missingMapping.upstream_legal_sources as Array>)[0]!.package_identity; + expect(() => validator.assert(missingMapping)).toThrow(/required/iu); + + const incompleteAmendment = createLegalReview(); + incompleteAmendment.amendments = [{ id: "amend-one", decision_id: "fast-uri-3-1-0-local-risk", reason: "Correction." }]; + expect(() => validator.assert(incompleteAmendment)).toThrow(/required/iu); + + const incompleteSupersession = createLegalReview(); + incompleteSupersession.supersessions = [{ id: "replace-one", superseded_decision_id: "fast-uri-3-1-0-local-risk", replacement_decision_id: "replacement", reason: "Replacement." }]; + expect(() => validator.assert(incompleteSupersession)).toThrow(/required/iu); + }); +}); + +describe("release risk evidence structural authority", () => { + for (const [filename, definition] of [ + ["advisory-snapshot", "advisory_snapshot_record"], + ["patched-artifact-availability", "artifact_availability_record"], + ["focused-inert-reachability", "reachability_record"], + ["user-risk-acceptance", "user_acceptance_record"], + ] as const) { + it(`validates the closed canonical ${filename} record`, async () => { + const validator = await evidenceValidator(definition); + const evidence = await loadReleaseEvidence(filename); + expect(validator.assert(evidence)).toEqual(expect.any(Object)); + expect(() => validator.assert({ ...evidence, unreviewed: true })).toThrow(/additional properties/iu); + }); + } +}); diff --git a/test/contracts/schema-registry.test.ts b/test/contracts/schema-registry.test.ts index 67611e41..d758cbfa 100644 --- a/test/contracts/schema-registry.test.ts +++ b/test/contracts/schema-registry.test.ts @@ -29,6 +29,8 @@ const SCHEMA_FILES = { mcpTools: "mcp-tools", resultExpectation: "result-expectation", pathClaim: "path-claim", + releaseManifest: "release-manifest", + releaseLegalReview: "release-legal-review", } as const satisfies Record; const loadSchema = async (name: string): Promise> => diff --git a/test/fixtures/release/hostile-runtime-guard.cjs b/test/fixtures/release/hostile-runtime-guard.cjs new file mode 100644 index 00000000..4d2031ab --- /dev/null +++ b/test/fixtures/release/hostile-runtime-guard.cjs @@ -0,0 +1,89 @@ +"use strict"; + +// This preload is intentionally dependency-free. It is copied beside the release +// payload and reports every guarded operation on the inherited fd-3 oracle. +const fs = require("node:fs"); +const moduleBuiltin = require("node:module"); +const path = require("node:path"); + +function report(type, surface, operation) { + observe(type, surface, operation); + throw new Error(`ARCHFLOW_HOSTILE_RUNTIME_GUARD:${surface}.${operation}`); +} + +function observe(type, surface, operation) { + const record = `${JSON.stringify({ operation, surface, type })}\n`; + try { + fs.writeSync(3, record); + } catch { + // A missing oracle must not turn a diagnostic guard into runtime authority. + } +} + +function replace(target, name, surface) { + if (target === undefined || typeof target[name] !== "function") return; + Object.defineProperty(target, name, { + configurable: true, + enumerable: Object.prototype.propertyIsEnumerable.call(target, name), + value: function guardedNetworkOperation() { + return report("network-attempt", surface, name); + }, + writable: true, + }); +} + +const guardedModules = [ + ["node:net", ["connect", "createConnection", "createServer"]], + ["node:tls", ["connect", "createServer"]], + ["node:dgram", ["createSocket"]], + ["node:http", ["request", "get", "createServer"]], + ["node:https", ["request", "get", "createServer"]], + ["node:http2", ["connect", "createServer", "createSecureServer"]], + ["node:dns", ["lookup", "resolve", "resolve4", "resolve6"]], + ["node:dns/promises", ["lookup", "resolve", "resolve4", "resolve6"]], +]; + +for (const [specifier, names] of guardedModules) { + const target = require(specifier); + for (const name of names) replace(target, name, specifier); +} + +for (const name of ["fetch", "WebSocket", "EventSource"]) { + if (!(name in globalThis)) continue; + Object.defineProperty(globalThis, name, { + configurable: true, + value: function guardedGlobalNetworkOperation() { + return report("network-attempt", "globalThis", name); + }, + writable: true, + }); +} + +const repositoryCanary = path.resolve(__dirname, "../repository-canary/SECRET"); +const guardedReadNames = ["open", "openSync", "readFile", "readFileSync", "stat", "statSync"]; +for (const name of guardedReadNames) { + const original = fs[name]; + if (typeof original !== "function") continue; + fs[name] = function guardedCanaryRead(candidate, ...args) { + if (typeof candidate === "string" && path.resolve(candidate) === repositoryCanary) { + observe("canary-attempt", "repository-canary", name); + } + return Reflect.apply(original, this, [candidate, ...args]); + }; +} + +const originalResolveFilename = moduleBuiltin._resolveFilename; +moduleBuiltin._resolveFilename = function guardedModuleCanary(request, ...args) { + if (request !== "archflow-release-canary") return Reflect.apply(originalResolveFilename, this, [request, ...args]); + try { + const result = Reflect.apply(originalResolveFilename, this, [request, ...args]); + observe("canary-attempt", "module-canary", "resolved"); + return result; + } catch (error) { + observe("canary-attempt", "module-canary", "unresolved"); + throw error; + } +}; + +// Make CommonJS patches visible to any ESM named imports loaded afterwards. +moduleBuiltin.syncBuiltinESMExports(); diff --git a/test/integration/mcp-stdio.test.ts b/test/integration/mcp-stdio.test.ts index e3ad5c3f..e5c74e09 100644 --- a/test/integration/mcp-stdio.test.ts +++ b/test/integration/mcp-stdio.test.ts @@ -164,7 +164,7 @@ beforeAll(async () => { runtimeBundle = built.stdout; expect(relative(repositoryRoot, runtimeBundle).startsWith("..")).toBe(true); - const trackedBuildOutput = spawnSync("git", ["ls-files", "--", ".tmp", "dist"], { + const trackedBuildOutput = spawnSync("git", ["ls-files", "--", ".tmp"], { cwd: repositoryRoot, encoding: "utf8", timeout: PROCESS_TIMEOUT_MS, diff --git a/test/integration/release-offline.test.ts b/test/integration/release-offline.test.ts new file mode 100644 index 00000000..33ebd435 --- /dev/null +++ b/test/integration/release-offline.test.ts @@ -0,0 +1,88 @@ +import { spawnSync } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +const TEST_TIMEOUT_MS = 120_000; +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); +const trackedPayload = resolve(repositoryRoot, "dist"); +let temporaryRoot = ""; +let firstStage = ""; +let secondStage = ""; + +function runScript(script: string, args: readonly string[]) { + return spawnSync(process.execPath, [resolve(repositoryRoot, script), ...args], { + cwd: repositoryRoot, + encoding: "utf8", + env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1" }, + timeout: TEST_TIMEOUT_MS, + }); +} + +function expectSuccess(result: ReturnType): Record { + expect(result.error).toBeUndefined(); + expect(result.status, result.stderr).toBe(0); + expect(result.stderr).toBe(""); + expect(result.stdout.endsWith("\n")).toBe(true); + return JSON.parse(result.stdout) as Record; +} + +beforeAll(async () => { + temporaryRoot = await mkdtemp(resolve(tmpdir(), "archflow-release-integration-")); + firstStage = resolve(temporaryRoot, "stage-a"); + secondStage = resolve(temporaryRoot, "stage-b"); +}, TEST_TIMEOUT_MS); + +afterAll(async () => { + if (temporaryRoot !== "") await rm(temporaryRoot, { force: true, recursive: true }); +}); + +describe("offline release payload", () => { + it("validates and starts the tracked payload from a guarded hostile copy", () => { + const checked = expectSuccess(runScript("scripts/check-release.mjs", ["--payload", trackedPayload])); + const smoked = expectSuccess(runScript("scripts/smoke-release-bundle.mjs", ["--payload", trackedPayload])); + + expect(checked).toHaveProperty("bundle_digest"); + expect(smoked).toMatchObject({ + bundle: "archflow-mcp.mjs", + fixture_sequences: ["initialize-and-calls", "malformed-json", "partial-json", "invalid-utf8"], + modes: ["exact-copy", "guarded-copy"], + module_canary_control: "resolved-via-NODE_PATH", + network_oracle_bytes: 0, + }); + expect(smoked.guarded_transcript_bytes).toEqual(expect.any(Number)); + expect(smoked.guarded_transcript_bytes).toBeGreaterThan(0); + }, TEST_TIMEOUT_MS); + + it("reproduces byte-identical payloads in independent roots", () => { + expectSuccess(runScript("scripts/build-release.mjs", ["--output", firstStage])); + expectSuccess(runScript("scripts/build-release.mjs", ["--output", secondStage])); + const proof = expectSuccess(runScript("scripts/check-release.mjs", [ + "--payload", firstStage, + "--compare", secondStage, + ])); + + expect(proof).toHaveProperty("compared_files"); + expect(proof).toHaveProperty("proof_inputs_digest"); + expect(proof).toHaveProperty("launch_profile_digest"); + }, TEST_TIMEOUT_MS); + + it("rejects unsafe roots and manifest-bound proof drift", () => { + const overlapping = runScript("scripts/build-release.mjs", ["--output", repositoryRoot]); + expect(overlapping.status).toBe(1); + expect(overlapping.stdout).toBe(""); + + const mutations = expectSuccess(runScript("scripts/test-release-integrity.mjs", [])); + expect(mutations).toMatchObject({ status: "passed" }); + expect(mutations.mutations).toEqual(expect.arrayContaining([ + "path", + "proof-input", + "provenance", + "symlink-root", + "write-target", + ])); + }, TEST_TIMEOUT_MS); +}); From 91a7c9576e730951e52a2014661e5a1860f48132 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Tue, 28 Jul 2026 11:02:16 -0500 Subject: [PATCH 016/124] MCP Integration: Design Phase 6 and Split Phase 7 The planned Phase 6 bundled two distinct bodies of work: the first filesystem and Git-subprocess layer in src/, and nine durable schemas. Three independent reviews found it did not fit one implementation session, so it is split at that seam. architecture.md now defines Phase 6 (Repository Identity, Paths, and Canonical Digests) and Phase 7 (Durable State and Artifact Schemas), with phases 7-19 renumbered to 8-20 and their dependencies rewired. REQ-33 is dropped from Phase 6, which no interface or chunk touched; it remains covered by phases 2, 3, 4, 5, 11, 12, 13, 18, 19. Phase 6 is DESIGNED at 10 chunks. Two sub-agent review rounds and one cross-client counter-review produced 18 findings, all accepted. The structural ones: the git runner is now root-bound at discovery, because an unrooted runner reports a missing attribute rather than an error when run from a subdirectory; every project error carries an operation context, because none was previously constructible from its own signature; raw Git paths get their own brand, because a conflicted file outside .archflow/ may legitimately carry a colon or non-NFC name; fingerprint collections are declared sets and sorted before hashing, because two callers could otherwise hash identical inputs differently; and the blanket "exit 128 means absent" rule is replaced by per-command declared absence, because git also returns 128 for dubious ownership and corrupt repositories. Phase 7 is DRAFT, not an approved design. It preserves the reviewed durable-schema material so it is not lost, but it has not passed a design gate, has not been counter-reviewed, and was written before Phase 6 exists, so every Phase 6 interface it references is provisional. Run archflow-phase-design mcp-integration 7 against Phase 6's implementation log before building it. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_011g9Dan3Gf3ztyovL2mXsu1 --- .../tasks/mcp-integration/architecture.md | 158 ++-- ...ry-identity-paths-and-canonical-digests.md | 711 ++++++++++++++++++ ...se-7-durable-state-and-artifact-schemas.md | 555 ++++++++++++++ .../reviews/phase-6-design-counter-review.md | 68 ++ 4 files changed, 1423 insertions(+), 69 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests.md create mode 100644 .archflow/tasks/mcp-integration/phases/phase-7-durable-state-and-artifact-schemas.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-6-design-counter-review.md diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index 3a548198..9eafdc12 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -18,7 +18,7 @@ | Packaging | esbuild `0.28.1`, exact npm lockfile, single host-neutral server/local-helper bundle | `install.sh` installs both `archflow-mcp` and `archflow-local` without an unpinned startup download. | | Verification | Vitest `4.1.10` with direct dev pin Vite `7.3.6`, fixture CLIs, fault injection, protocol fixtures, and black-box host/sandbox suites | The exact Vite 7 pin constrains Vitest to its supported permissive line; the lock must prove no `lightningcss` or other copyleft dependency before acceptance. Critical persistence, host, process, protocol, and manual-mode behavior is exercised at its real boundaries. | -All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. Direct pins are permissively licensed, and the complete lock must independently prove a permissive-only graph. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 10 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. +All runtime and development dependencies are exact lockfile pins. An update deliberately regenerates the lockfile, runs schema/protocol/CLI fixtures, verifies licenses, and records any format migration; beta, model, and CLI versions never float at startup. Direct pins are permissively licensed, and the complete lock must independently prove a permissive-only graph. The repository currently has no project license, which release packaging records alongside dependency notices. `@anthropic-ai/sandbox-runtime` is the preferred Phase 11 candidate behind the provider interface, not an adopted dependency: its package is Apache-2.0, while its Linux bubblewrap and socat paths introduce LGPL-2.0-or-later and GPL-2.0-only components. Those require later explicit user license approval; without it, affected environments remain unsupported. ## System Architecture @@ -305,7 +305,7 @@ Each dispatch creates a fresh, non-resumed child in a temporary directory outsid - use an OS containment primitive capable of terminating every descendant on abort, timeout, server shutdown, or output overflow even if a descendant creates a new process group/session—PID namespace/cgroup, Windows job object, or a proven equivalent, not Execa best effort alone; and - return a capability proof tied to the OS, provider, CLI/runtime versions, exact allowed-read manifest, and randomized denied canaries. -At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 10 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. +At install/startup and whenever that fingerprint changes, a black-box probe launches a real child that uses the selected CLI's measured runtime and own-auth paths, reads its envelope, and writes temp output while failing to read/write randomized repository, sibling-task, global agent config/instructions, the other family's credential store, and unrelated-secret canaries. ArchFlow never opens or copies the selected CLI's own credential files, and captured output/persisted diagnostics are scanned for unrelated-secret canaries and prohibited API-key/provider-routing material, not for the mere use of the supported CLI's own authentication. Managed Claude hooks/policy or Codex managed/global instructions make the environment unsupported unless real fixtures prove no injection. The proof is completed in Phase 11 for both producer directions. `@anthropic-ai/sandbox-runtime` remains a non-adopted preferred candidate subject to proof and license approval. The Claude adapter uses fresh `--safe-mode`, `--tools ""`, a strict empty MCP config, disabled slash commands, no persistence, and schema-constrained output. It preflights subscription authentication and managed hooks/policy. Host setup configures and validates the Claude server entry's persistent per-server `timeout` when supported; otherwise a newly started host must inherit `MCP_TOOL_TIMEOUT` as described below. Cancellation or host timeout always leaves a durable resumable gate; timeout-then-resume is supported normal behavior. The Codex adapter uses exact fixture-proven ephemeral, ignore-user-config, `--ignore-rules`, read-only, and output-schema behavior while preserving first-party auth; `--ignore-rules` is inherited-context isolation only, never security confinement. It configures/tests `project_doc_max_bytes=0` or a proven equivalent and rejects managed instruction injection. An ArchFlow deny-all Codex execpolicy remains an early feasibility candidate, and the design does not claim it works. Both adapters still require OS sandbox proof, are version-gated from real fixtures, and spawn with `shell: false`, scrubbed environment, no provider keys/routing or unrelated secrets, `killDescendants`, cancellation, timeout/output bounds, forced escalation, and provider-owned descendant containment. Stable failures cover missing CLI, auth, unsupported host/model, family mismatch, rate limit, timeout, cancellation, overflow, invalid output, nonzero exit, and I/O failure. @@ -375,22 +375,22 @@ Release is blocked unless all applicable tests pass and the supported matrix is | Coverage area | Requirements | Validation | Primary phases | Proof boundary | |---------------|--------------|------------|----------------|----------------| -| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 5, 13, 14, 19 | Strict assets/schemas, dependency-complete offline packaging, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | -| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 12, 14, 18, 19 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | -| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 2, 5, 6, 7, 8, 11, 14, 15, 17, 18 | Structured JSON/projections, manifest evidence, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | -| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 2, 11, 16, 17, 18 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | -| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 2, 9, 11, 16, 18 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | -| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 6, 7, 8, 9, 15, 17, 18 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | -| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 6, 7, 8, 9, 15, 16, 17 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | -| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 6, 7, 8, 10, 16, 17, 18 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | -| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 2, 3, 4, 5, 12, 13, 17, 18 | Correlated five-tool contracts, v2 fixtures, and the license-complete deterministic offline payload expose only the stdio boundary; the separate offline helper is not an MCP tool. | -| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 10, 12, 17, 18 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | -| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 2, 3, 4, 5, 10, 11, 12, 17, 18 | Hashed envelopes, portable manifest evidence, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | -| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 10, 13, 17, 18, 19 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | -| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 2, 9, 12, 15, 17, 18 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | -| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 12, 13, 15, 16, 18 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | -| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 2, 9, 14, 15, 18 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | -| Legacy migration | REQ-50 | VAL-17 | 6, 7, 8, 9, 16, 17, 18 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | +| Initialization and canonical repository contracts | REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06 | VAL-08, VAL-11, VAL-12 | 1, 5, 14, 15, 20 | Strict assets/schemas, dependency-complete offline packaging, preserving official registration, fixed graph, and documentation agreement establish one v1 authority. | +| Thin phase marshalling and production lifecycle | REQ-07, REQ-08, REQ-09, REQ-10 | VAL-01, VAL-02, VAL-05, VAL-06, VAL-16 | 1, 13, 15, 19, 20 | Normal skills drive persisted boundaries, implementation manifests, current-digest loops, approvals, parent updates, and commit authorization. | +| Review evidence and truthful status | REQ-11, REQ-12, REQ-13, REQ-14 | VAL-02, VAL-05, VAL-06, VAL-08, VAL-12, VAL-16 | 2, 5, 6, 7, 8, 9, 12, 15, 16, 18, 19 | Structured JSON/projections, manifest evidence, fixed-point fixtures, and reconciled normal/degraded status distinguish provenance. | +| Constitution and task policy | REQ-15, REQ-16, REQ-17 | VAL-03, VAL-15 | 1, 2, 12, 17, 18, 19 | Explicit approved policy base, trigger corpus, and unresolved-edit rejection fail closed. | +| Waivers, drift, and human authority | REQ-18, REQ-19, REQ-20 | VAL-01, VAL-03, VAL-04, VAL-09, VAL-15 | 2, 10, 12, 17, 19 | Digest-bound decisions, scoped expiry, migration audit, separate verdicts, and upstream reopening preserve authority. | +| Durable state and recovery | REQ-21, REQ-22 | VAL-05, VAL-06, VAL-09, VAL-12 | 6, 7, 8, 9, 10, 16, 18, 19 | Prepared-before-state semantics, fault injection, durable gates, helper reconciliation, and collision-safe restore never infer success. | +| Idempotency and concurrency | REQ-23, REQ-24, REQ-25 | VAL-05, VAL-06, VAL-08, VAL-10 | 6, 7, 8, 9, 10, 16, 17, 18 | Intent/state commitment, local lock/CAS, one-writer Git handoff, manifests, and exact restore cover retries/races without claiming distributed locks. | +| Repository and task isolation | REQ-26 | VAL-07, VAL-10, VAL-11, VAL-13 | 6, 7, 8, 9, 11, 17, 18, 19 | Path guards, narrow pre-init legacy read, and measured sandbox manifests block undeclared access. | +| Fixed MCP boundary and local service | REQ-27, REQ-28 | VAL-08, VAL-13 | 2, 3, 4, 5, 13, 14, 18, 19 | Correlated five-tool contracts, v2 fixtures, and the license-complete deterministic offline payload expose only the stdio boundary; the separate offline helper is not an MCP tool. | +| Host identity and routing | REQ-29, REQ-30, REQ-31 | VAL-07, VAL-08 | 11, 13, 18, 19 | Real handshakes and exact CLI fixtures bind immutable host/opposite family and reject injected managed context. | +| Fresh structured dispatch | REQ-32, REQ-33 | VAL-02, VAL-07, VAL-08, VAL-13 | 2, 3, 4, 5, 11, 12, 13, 18, 19 | Hashed envelopes, portable manifest evidence, measured runtime/selected-CLI own-auth reads, fresh PIDs, OS isolation, validation, and attestation prove the boundary. | +| Authentication and child lifecycle | REQ-34, REQ-35 | VAL-07, VAL-08, VAL-13, VAL-14 | 11, 14, 18, 19, 20 | Auth/version/policy preflights, environment sentinels, descendant escape tests, and the legal release gate prevent unsafe dispatch. | +| Durable gate semantics | REQ-36, REQ-37 | VAL-01, VAL-03, VAL-09, VAL-10 | 2, 10, 13, 16, 18, 19 | Deterministic IDs, pre-block publication, supplemental-review retry, cancellation, and CAS resolution prove exactly-once decisions. | +| Degraded/manual terminal completion | REQ-38, REQ-39, REQ-40 | VAL-06, VAL-09, VAL-12 | 13, 14, 16, 17, 19 | `archflow-local` and exact fallback templates advance only from validating evidence; loss of both paths stops for repair. | +| Optional cross-client gate review | REQ-41 | VAL-09, VAL-12, VAL-16 | 2, 10, 15, 16, 19 | Caller-known gate IDs avoid blocking deadlock; triage resumes or supersedes deterministically and decline fabricates nothing. | +| Legacy migration | REQ-50 | VAL-17 | 6, 7, 8, 9, 10, 17, 18, 19 | Staged import, no-state initialization union, existing phase mappings, implementation audits, and interruption fixtures prevent auto-promotion. | All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release validations `VAL-01` through `VAL-17`, appear above. `REQ-52` remains explicitly outside the v1 architecture. @@ -404,7 +404,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali **Requirements**: REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-10, REQ-15, REQ-17 -**Scope**: First add the visible lineage/supersession banner to `docs/mcp-integration-design.md`, preserving it as originating design and linking the normative PRD/architecture; Phase 19 later updates surrounding documentation. Establish a private ESM package, exact lockfile, scripts, Node matrix CI, dependency notices/policy, and only Phase-1 direct dependencies: Zod, Ajv, `ajv-formats`, YAML, TypeScript, Node typings, esbuild, Vitest, and direct Vite `7.3.6`. Implement recursive plain-JSON preflight, strict non-mutating Ajv2020, explicit Zod agreement infrastructure, branded canonical phase-instance codec, safe YAML parsing, fixed workflow/config/rubric/constitution rule contracts, shipped workflow/constitution assets, and append-only constitution evolution fixtures. This phase has no review/triage/adjudication contracts or renderers, error registry, tool schemas, MCP SDK/server, or tracked offline bundle. +**Scope**: First add the visible lineage/supersession banner to `docs/mcp-integration-design.md`, preserving it as originating design and linking the normative PRD/architecture; Phase 20 later updates surrounding documentation. Establish a private ESM package, exact lockfile, scripts, Node matrix CI, dependency notices/policy, and only Phase-1 direct dependencies: Zod, Ajv, `ajv-formats`, YAML, TypeScript, Node typings, esbuild, Vitest, and direct Vite `7.3.6`. Implement recursive plain-JSON preflight, strict non-mutating Ajv2020, explicit Zod agreement infrastructure, branded canonical phase-instance codec, safe YAML parsing, fixed workflow/config/rubric/constitution rule contracts, shipped workflow/constitution assets, and append-only constitution evolution fixtures. This phase has no review/triage/adjudication contracts or renderers, error registry, tool schemas, MCP SDK/server, or tracked offline bundle. **Success Criteria**: @@ -498,33 +498,52 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Node-core guards prove startup and protocol exercise open no network connection or listener, emit only MCP traffic on stdout, route diagnostics to stderr, and leave no background handle. - [ ] CI validates the manifest schema and all input/hash/license bindings, reproduces the payload, runs the hostile clean-copy smoke, and fails on bundle, lock, schema, asset, metafile, legal-inventory, attribution, or protocol-fixture drift. -### Phase 6: Repository Identity, Paths, Schemas, and Canonical Digests +### Phase 6: Repository Identity, Paths, and Canonical Digests -**Goal**: Establish the repository/task identity, path safety, durable schemas, immutable task configuration, and byte-stable digest contracts used by every mutation. +**Goal**: Establish the repository/task identity, path safety, immutable task configuration pinning, and byte-stable digest contracts used by every mutation. **Depends on**: Phases 1–5 -**Requirements**: REQ-04, REQ-05, REQ-11, REQ-13, REQ-14, REQ-21, REQ-26, REQ-33, REQ-39, REQ-50 +**Requirements**: REQ-04, REQ-05, REQ-13, REQ-26 -**Scope**: Implement Git/worktree and task identity; `.archflow/** -text merge=binary`; path allowlists; the durable `state.json` schema and task-initialization, document, implementation-output, legacy-import, manual-checkpoint, checkpoint-import, maintenance-record, and snapshot-accounting schemas; exact whole-file `config.yaml` pinning; canonical Git blob/tree-mode and request/input digests; divergence/conflict detection; and secret-scan result contracts. This phase does not implement state mutation or payload restore. +**Scope**: Implement Git/worktree and task identity; `.archflow/** -text merge=binary` with runtime attribute verification; task-relative and repository-relative path claims, path classes, and filesystem containment; canonical JSON, canonical Git blob/tree-mode identity, and request/declared-input digests; exact whole-file `config.yaml` digest pinning; divergence, conflict, and in-progress-operation detection; and the secret-scan result contract. This phase introduces the first filesystem and Git-subprocess code in `src/`. It implements no durable state or artifact schema, no state mutation, no payload restore, and no secret-scanning engine, and adds no runtime dependency. **Success Criteria**: -- [ ] Task initialization schemas bind the exact whole-file config digest. Any byte change is detected as `PINNED_CONFIG_MISMATCH` with expected/observed digests and no config content; no re-pin/amendment schema exists. -- [ ] Traversal, absolute paths, symlink escape, cross-task access, and identity mismatch fail before reads, while linked worktrees, relocation, spaces, and Unicode pass. +- [ ] Traversal, absolute paths, drive-relative and UNC inputs, symlink escape, cross-task access, pathspec metacharacters, and repository-identity mismatch fail before any read, while linked worktrees, relocation, spaces, and Unicode pass. - [ ] Committed inputs and tracked outputs have identical canonical Git blob/tree identities across LF/CRLF worktrees, `core.autocrlf`, `core.fileMode`, executable-bit support, and symlink-capable/incapable checkouts; unsupported materialization fails closed. -- [ ] Valid state/initialization/document/implementation/import/checkpoint/maintenance samples round-trip through normative schemas; predecessor gaps, unknown fields, digest mismatches, invalid phase IDs, and contradictory accounting fail with stable errors. +- [ ] The whole `config.yaml` file is pinned by exact digest, and any byte change is detected as `PINNED_CONFIG_MISMATCH` with expected/observed digests and no config content. +- [ ] The canonical request digest is computed from its closed field list only, and logically set-valued fingerprint collections hash identically under any input permutation. - [ ] Startup and pull/handoff detection identifies divergent histories and `.archflow/**` conflicts as non-authoritative without claiming it can detect independent-clone concurrency before divergence. +- [ ] Every Git invocation is bound to the discovered worktree root, so no command can silently report an absent path or attribute because of the caller's working directory. -### Phase 7: Transaction Kernel, Intent/CAS, and Crash Recovery +### Phase 7: Durable State and Artifact Schemas -**Goal**: Commit one task's transitions exactly once under races, crashes, retries, config drift, and bounded reconciliation. +**Goal**: Define every persisted shape as a versioned normative schema with one cross-document semantic authority. **Depends on**: Phase 6 +**Requirements**: REQ-04, REQ-11, REQ-13, REQ-14, REQ-21, REQ-26, REQ-39, REQ-50 + +**Scope**: Author the durable `state.json` schema and the task-initialization, document, implementation-output, legacy-import-initialization, manual-checkpoint, checkpoint-import, maintenance-record, and snapshot-accounting schemas, with Zod mirrors wherever a shape is reachable from the `archflow_state.artifact` union, plus one consolidated semantic validator for cross-document invariants. This phase consumes Phase 6's identity, path, and digest primitives. It implements no state mutation, transaction kernel, snapshot materialization, or payload restore. + +**Success Criteria**: + +- [ ] Task-initialization and legacy-import-initialization schemas bind the exact whole-file config digest; no re-pin or amendment schema exists. +- [ ] Valid state/initialization/document/implementation/import/checkpoint/maintenance samples round-trip through normative schemas; predecessor gaps, unknown fields, digest mismatches, invalid phase IDs, and contradictory accounting fail with stable errors. +- [ ] Every shape reachable from the `archflow_state.artifact` union passes Ajv/Zod agreement; purely server-internal shapes have exactly one shape model. +- [ ] Implementation-output manifests represent add/modify/delete/rename, tree modes, canonical Git blob identities, and bounded payload accounting without any structurally representable contradiction. +- [ ] Byte accounting is bound to the 25 MiB per-result and 250 MiB per-task caps and corresponds one-to-one with the declared outputs it measures. + +### Phase 8: Transaction Kernel, Intent/CAS, and Crash Recovery + +**Goal**: Commit one task's transitions exactly once under races, crashes, retries, config drift, and bounded reconciliation. + +**Depends on**: Phase 7 + **Requirements**: REQ-04, REQ-08, REQ-13, REQ-14, REQ-21, REQ-22, REQ-23, REQ-24, REQ-26, REQ-39, REQ-50 -**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 8. +**Scope**: Implement task locks, revision CAS on every invocation, closed request digests, prepared receipts/results, atomic projections, state-last commitment, direct and checkpoint-1-constrained revision-0→1 adoption, bounded ordinary reconciliation, explicit full audit/repair, config-pin enforcement before transition, and divergent-history repair/handoff. Payload snapshots and restore are Phase 9. **Success Criteria**: @@ -535,15 +554,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Mature-task step boundaries and status reconcile only current state projections, the relevant active/prepared intent, and active gate/checkpoint head; only explicit repair/import/audit walks history. - [ ] Divergent/conflicted clones remain non-authoritative until preserve-both-heads repair selects/replays one successor chain and records a clean one-writer handoff. -### Phase 8: Snapshots, Implementation Manifests, and Restore +### Phase 9: Snapshots, Implementation Manifests, and Restore **Goal**: Retain and restore deterministic declared outputs within explicit storage, retention, collision, and secret-safety bounds. -**Depends on**: Phase 7 +**Depends on**: Phase 8 **Requirements**: REQ-08, REQ-11, REQ-13, REQ-21, REQ-22, REQ-23, REQ-25, REQ-26, REQ-33, REQ-39, REQ-50 -**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 9 connects collision decisions to the gate service. +**Scope**: Implement content-addressed result manifests, tracked-output Git-object reuse, bounded untracked/generated/restore payload storage, implementation-output manifests, snapshot/checkpoint secret scanning, atomic projection/restore, collision classification, retention reachability, and explicit maintenance records. Phase 10 connects collision decisions to the gate service. **Success Criteria**: @@ -554,11 +573,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Secret fixtures in any candidate Git-tracked snapshot/checkpoint projection fail before projection with safe remediation warning that later `.archflow/` deletion cannot erase branch history; clean binary/text fixtures pass without logging secret values. - [ ] Snapshot/projection/restore fault injection preserves prior/next authority or exact repair, and the three `restore-collision` outcomes are representable without silent overwrite. -### Phase 9: Durable Gates, Waivers, and Manual Decisions +### Phase 10: Durable Gates, Waivers, and Manual Decisions **Goal**: Persist every human authority boundary independently of a live MCP request. -**Depends on**: Phase 8 +**Depends on**: Phase 9 **Requirements**: REQ-09, REQ-13, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -574,11 +593,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] `waiver-requested` is non-advancing and archives the current gate before the sole waiver gate opens; grant resumes only the recorded rule/scope, denial remains non-advancing, and no nested gate exists. `restore-collision` exposes only discard-and-restore, adopt-as-new-generation with changed inputs/fingerprint and rationale, or abort. - [ ] A real Claude host timeout leaves one pending gate, and a later invocation resumes and resolves that gate exactly once; timeout-then-resume is normal supported behavior. -### Phase 10: Host Identity, Sandbox, and CLI Dispatch +### Phase 11: Host Identity, Sandbox, and CLI Dispatch **Goal**: Prove fresh opposite-family reviewer processes receive only declared envelopes and are safe to dispatch on every claimed environment. -**Depends on**: Phases 1–9 +**Depends on**: Phases 1–10 **Requirements**: REQ-26, REQ-29, REQ-30, REQ-31, REQ-32, REQ-34, REQ-35 @@ -595,11 +614,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Any external sandbox dependency and license is presented for explicit acceptance before adoption; copyleft is never silently bundled. - [ ] The Anthropic subscription-authenticated dispatch path remains release-disabled until written clarification or a qualified legal determination satisfies `VAL-14`; implementation or fixture success is not legal approval. -### Phase 11: Constitution Adjudication, Drift, and Review Fixed Point +### Phase 12: Constitution Adjudication, Drift, and Review Fixed Point **Goal**: Turn validated reviewer output and pinned policy/upstream inputs into current-digest advancement evidence. -**Depends on**: Phases 1–10 +**Depends on**: Phases 1–11 **Requirements**: REQ-10, REQ-11, REQ-12, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-32, REQ-33 @@ -612,11 +631,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Positive, negative, and uncertain triggers plus current/missing/stale/failed mechanical evidence behave fail-closed against the approved policy-base constitution. - [ ] Aligned and incidental drift are recorded correctly; material drift gates and an accepted change reopens the affected upstream approval/evidence chain. -### Phase 12: Five-Tool MCP Assembly and Offline Local CLI +### Phase 13: Five-Tool MCP Assembly and Offline Local CLI **Goal**: Assemble persistence, dispatch, adjudication, and decisions behind the complete and only MCP workflow surface. -**Depends on**: Phases 1–11 +**Depends on**: Phases 1–12 **Requirements**: REQ-07, REQ-08, REQ-11, REQ-13, REQ-21, REQ-23, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40 @@ -632,15 +651,15 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] `archflow-local checkpoint` atomically extends only a valid reconciled chain, and server adoption imports only its greatest valid checkpoint via the closed union tag. - [ ] The updated tracked manifest binds the complete server/helper bundle to current package/lock/source/schema/assets digests and passes clean-checkout offline startup before installer work. -### Phase 13: Installer, Initialization, and Host Registration +### Phase 14: Installer, Initialization, and Host Registration **Goal**: Install the offline bundle and initialize supported repositories repeatedly without damaging host or project configuration. -**Depends on**: Phases 1, 10, and 12 +**Depends on**: Phases 1, 11, and 13 **Requirements**: REQ-01, REQ-02, REQ-28, REQ-29, REQ-34, REQ-37, REQ-40 -**Scope**: Verify the Phase 12 tracked bundle/manifest, then extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. +**Scope**: Verify the Phase 13 tracked bundle/manifest, then extend `install.sh` for both bundle launchers and skill targets, replacing hard-coded `STALE_SKILLS` deletion with an ArchFlow-owned install manifest that removes only obsolete owned files and preserves unrelated skills; create `archflow-init`; scaffold assets; require `claude mcp add --scope project` to create/update committed shared `.mcp.json` with the PATH command `archflow-mcp`, and use official Codex registration; narrowly patch unsupported persistent per-server timeout/required settings with parse-before/after preservation; otherwise emit exact shell-profile guidance and verify a newly started host inherits `MCP_TOOL_TIMEOUT`; detect collisions, untrusted or managed config, unsupported versions/auth, and missing sandbox capability; and add recovery guidance. **Success Criteria**: @@ -652,11 +671,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Initialized state is Git-trackable/shareable, contains no machine-specific executable path in portable task state, and works after repository relocation and in linked/space/Unicode worktrees. - [ ] `archflow-init` creates no task state and no commit. Fresh task creation refuses to start until workflow/constitution assets resolve from an explicitly approved immutable commit and then stages the normal initialization manifest. -### Phase 14: Normal-Mode Thin Phase Skills and Truthful Status +### Phase 15: Normal-Mode Thin Phase Skills and Truthful Status **Goal**: Drive the normal MCP workflow from host-neutral phase skills and report only reconciled durable truth. -**Depends on**: Phases 1–13 +**Depends on**: Phases 1–14 **Requirements**: REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-13, REQ-14, REQ-20, REQ-41 @@ -670,11 +689,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] The server sees only complete supplemental projections through filesystem notification plus bounded polling fallback. The gate-pending transition table admits only supplemental ingestion, triage, explicit decline/decision, cancellation, or supersession; `SUPPLEMENTAL_REVIEW_REQUIRED` rejection resumes the gate and accepted change supersedes it and re-enters the fixed point. - [ ] Status verifies the immutable whole-config digest before recommending work; `PINNED_CONFIG_MISMATCH` reports no config content and recommends only a distinct new task or explicit upgrade for intentional routing/model/effort changes. -### Phase 15: Manual and Degraded Recovery Workflow +### Phase 16: Manual and Degraded Recovery Workflow **Goal**: Complete and recover the workflow conservatively when individual MCP tools or the server are unavailable. -**Depends on**: Phases 1–14 +**Depends on**: Phases 1–15 **Requirements**: REQ-08, REQ-09, REQ-11, REQ-12, REQ-13, REQ-14, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41 @@ -688,11 +707,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Supplemental-review arrival, rejection/resume, accepted-change supersession, explicit decline, cancellation, and restart behave identically to normal-mode milestones. - [ ] Manual operation never auto-commits/pushes and documents clean human-approved checkpoint handoff between writers. -### Phase 16: Legacy Upgrade Workflow +### Phase 17: Legacy Upgrade Workflow **Goal**: Migrate selected legacy material into a distinct canonical task without changing or implicitly approving the source. -**Depends on**: Phases 6–9, 11, 12, 14, and 15 +**Depends on**: Phases 6–10, 12, 13, 15, and 16 **Requirements**: REQ-02, REQ-04, REQ-09, REQ-13, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -707,11 +726,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Pure manual upgrade begins with a validating legacy-initialization checkpoint and later server recovery adopts its chain without changing the source or replaying decisions. - [ ] The repository's current legacy task layout upgrades through the same fixture path, and release guidance tells users with in-flight tasks how to finish in legacy tooling or checkpoint/handoff into a distinct upgraded task without silent in-place conversion. -### Phase 17: Reliability and Security Matrices +### Phase 18: Reliability and Security Matrices **Goal**: Prove persistence, race, path, process, and isolation invariants under adversarial failures. -**Depends on**: Phases 1–16 +**Depends on**: Phases 1–17 **Requirements**: REQ-04, REQ-05, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-50 @@ -727,11 +746,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] Binary/mode/rename/delete restore, manual recovery, and legacy staging remain collision-safe under fault injection; tracked canonical blob/tree identities remain stable across attributes, LF/CRLF and `core.autocrlf`, `core.fileMode`, executable-bit, and symlink checkout cases. - [ ] Boundary and over-limit payload matrices prove 25 MiB/result and 250 MiB/task enforcement, no truncation/hidden authority, authoritative/evidence retention, maintenance reachability records, and pre-projection secret rejection under crashes and retries. -### Phase 18: Real-Host E2E and Review-Quality Validation +### Phase 19: Real-Host E2E and Review-Quality Validation **Goal**: Validate useful independent review and complete normal, manual, and migration journeys in both producer directions. -**Depends on**: Phases 1–17 +**Depends on**: Phases 1–18 **Requirements**: REQ-01, REQ-02, REQ-03, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -748,11 +767,11 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali - [ ] A real task reaches the snapshot boundaries, receives `SNAPSHOT_LIMIT` above either cap without partial authority, retains all current/evidence chains, records a safe maintenance prune, and rejects a secret-bearing checkpoint before Git projection. - [ ] The approved corpus thresholds demonstrate substantive defect detection and acceptable false blockers; failure of `VAL-02` reopens the automation premise. -### Phase 19: Release Packaging, Support Matrix, and Documentation Consistency +### Phase 20: Release Packaging, Support Matrix, and Documentation Consistency **Goal**: Produce a coherent beta release candidate and an explicit report of any remaining external release blockers. -**Depends on**: Phases 1–18 +**Depends on**: Phases 1–19 **Requirements**: REQ-01, REQ-02, REQ-03, REQ-04, REQ-05, REQ-06, REQ-07, REQ-08, REQ-09, REQ-10, REQ-11, REQ-12, REQ-13, REQ-14, REQ-15, REQ-16, REQ-17, REQ-18, REQ-19, REQ-20, REQ-21, REQ-22, REQ-23, REQ-24, REQ-25, REQ-26, REQ-27, REQ-28, REQ-29, REQ-30, REQ-31, REQ-32, REQ-33, REQ-34, REQ-35, REQ-36, REQ-37, REQ-38, REQ-39, REQ-40, REQ-41, REQ-50 @@ -776,20 +795,21 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali | 3 | MCP Contract Boundary and Dependency Admission | COMPLETE (2026-07-27) | | 4 | Guarded MCP Runtime and SDK Compatibility | COMPLETE (2026-07-27) | | 5 | Offline Bundle and Release Integrity | COMPLETE (2026-07-28) | -| 6 | Repository Identity, Paths, Schemas, and Canonical Digests | Not Started | -| 7 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | -| 8 | Snapshots, Implementation Manifests, and Restore | Not Started | -| 9 | Durable Gates, Waivers, and Manual Decisions | Not Started | -| 10 | Host Identity, Sandbox, and CLI Dispatch | Not Started | -| 11 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | -| 12 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | -| 13 | Installer, Initialization, and Host Registration | Not Started | -| 14 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | -| 15 | Manual and Degraded Recovery Workflow | Not Started | -| 16 | Legacy Upgrade Workflow | Not Started | -| 17 | Reliability and Security Matrices | Not Started | -| 18 | Real-Host E2E and Review-Quality Validation | Not Started | -| 19 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | +| 6 | Repository Identity, Paths, and Canonical Digests | Not Started | +| 7 | Durable State and Artifact Schemas | Not Started | +| 8 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | +| 9 | Snapshots, Implementation Manifests, and Restore | Not Started | +| 10 | Durable Gates, Waivers, and Manual Decisions | Not Started | +| 11 | Host Identity, Sandbox, and CLI Dispatch | Not Started | +| 12 | Constitution Adjudication, Drift, and Review Fixed Point | Not Started | +| 13 | Five-Tool MCP Assembly and Offline Local CLI | Not Started | +| 14 | Installer, Initialization, and Host Registration | Not Started | +| 15 | Normal-Mode Thin Phase Skills and Truthful Status | Not Started | +| 16 | Manual and Degraded Recovery Workflow | Not Started | +| 17 | Legacy Upgrade Workflow | Not Started | +| 18 | Reliability and Security Matrices | Not Started | +| 19 | Real-Host E2E and Review-Quality Validation | Not Started | +| 20 | Release Packaging, Support Matrix, and Documentation Consistency | Not Started | --- *Created: 2026-07-26* diff --git a/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests.md b/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests.md new file mode 100644 index 00000000..e7b96114 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests.md @@ -0,0 +1,711 @@ +# Phase 6: Repository Identity, Paths, and Canonical Digests + +**Status**: DESIGNED +**Task**: mcp-integration +**Goal**: Establish the repository/task identity, path safety, immutable task configuration pinning, and byte-stable digest contracts used by every mutation. +**Requirements completed**: none +**Requirements advanced**: REQ-04, REQ-05, REQ-13, REQ-26 + +**This phase completes no requirement, and says so deliberately.** REQ-04 requires that a task *records and enforces* immutable identity, base commit, workflow, constitution, and configuration inputs at task start — recording is durable-state work this phase excludes and Phase 7 owns. REQ-26 requires that *every tool* resolves the canonical root and rejects scope or identity violations before any read or child dispatch; this phase wires no production handler, so nothing is enforced end to end yet. What each requirement receives here is an exact contract slice: REQ-04 gets whole-file `config.yaml` digest pinning and the repository/task identity digests the manifest will bind; REQ-05 gets the pinning function and its mismatch producer, not workflow-graph validation, which Phase 1 already owns; REQ-13 gets the canonical request digest and declared-input fingerprint that later evidence-freshness comparisons depend on, not the fixed-point loop; REQ-26 gets the path claims, path classes, containment, and identity comparators the handlers will call. Completion is reserved for the phase that integrates and verifies the behaviour through all five tools. + +`architecture.md` has been updated to define this phase and Phase 7 separately; its earlier Phase 6 requirement list — which included REQ-33, untouched by any interface or chunk here — is corrected there. Phase 7 carries the durable state and artifact schemas. + +## Context + +Phases 1–5 produced a foundation with no persistence and no environment coupling. Phase 1 established the ESM package, exact lockfile, recursive plain-JSON preflight, strict Ajv2020, the Zod-agreement harness, and branded phase-instance codecs. Phase 2 froze evidence, gate, triage, adjudication, and error contracts, including the 52 project error codes this phase finally supplies producers for. Phase 3 froze the five-tool catalogue and the SDK-free boundary; Phase 4 made the runtime real but inert; Phase 5 tracked a reproducible `dist/` payload with `release-manifest` and `release-legal-review` under JSON Schema authority plus a single semantic validator. The stale `.archflow/context/*` snapshots predate Phases 3–5 and are wrong about both the MCP entry point and `dist/`; live code is authoritative. + +**This phase introduces the first filesystem and Git-subprocess code in `src/`.** Today `src/` contains zero `node:fs`, `node:path`, and `node:child_process` usage — all I/O is caller-supplied — and hashing appears at exactly three `createHash("sha256")` sites: two in `src/contracts/trust.ts` and one in `src/mcp/server.ts:196`, which digests an unknown tool name for `TOOL_NOT_FOUND`. There is no SHA-1 anywhere and no Git-OID computation anywhere. Three primitives this phase needs already exist only as plain JavaScript in `scripts/release-support.mjs`, which TypeScript cannot import: `canonicalJsonBytes`, `assertPortablePath` (lines 244–255), and the module-private `isInside` (lines 257–260) — the exact `path.relative` containment check re-derived here as containment step 6. + +Phase 6 supplies contracts, identity, path safety, digest functions, and the secret-scan *result* contract. It explicitly does **not** implement any durable state or artifact schema, state mutation, the transaction kernel, locking, CAS, intent receipts, atomic writes, payload snapshot materialisation or restore, gate lifecycle, dispatch, sandbox, or the secret-scanning *engine*. It adds **no runtime dependency**. + +## What We're Building + +One coherent layer with a single directional rule: **pure computation lives in `src/contracts/`; everything that shells out to `git` or touches `node:fs` lives in a new `src/repository/` tree.** `src/repository/**` is never re-exported from `src/contracts/index.ts`, and `src/contracts/**` never imports from `src/repository/**`, so the contract layer stays testable without a repository on disk. + +Four things make the layer safe rather than merely present, and each is a structural device rather than a convention: + +- **Branded values, not strings.** `TaskSlug`, `PathSafeId`, `TaskPathClaim`, `RepositoryPathClaim`, `RawGitPath`, `GitOid`, and `ResolvedTaskPath` are distinct brands whose parsers are the only mints. Every public interface that carries one of these values is retyped to the brand, so a frame or width mismatch is a compile error rather than a wrong digest. +- **A root-bound runner.** Worktree discovery does not return a location for callers to remember; it returns a `RootBoundGitRunner` that carries its location. Every reader below discovery accepts only that type, so it is structurally impossible to run a repository query from an arbitrary cwd. +- **Caller-declared absence.** `git` exits 128 for a dozen unrelated fatal conditions. Every command declares which exit codes are data for *that* command, with the diagnostic that must accompany them; everything else is a failure. +- **Explicit error context.** Every reader and classifier takes a pinned `RepositoryOperationContext`, because the project error codes they promise require parameters no Git command returns. + +Chunks are delegated to sub-agents with fresh context that never read each other's code, so the signatures below are the entire contract between them. Ordering is: **chunk 1 (canonical primitives) and chunk 2 (ID and path primitives) land first, in that order and alone**; chunk 3 (boundary retightening) consumes chunk 2's brands; chunk 5 consumes chunk 2's `TaskSlug` for `computeTaskIdentity` and chunk 4's runner; chunks 6–8 consume chunk 5's root-bound runner. + +## Interfaces and Contracts + +### Failure convention — stated once, applied everywhere + +`ProjectResult` is today purely a wire shape used at the tool boundary; nothing in `src/` returns it from an internal function, and internal failures use typed throws. This phase extends it inward under a three-way rule, and every signature below obeys it: + +> **Parsers and assertion helpers throw.** `parseGitOid`, `parseSecretScanResult`, `assertArchflowIndexEntry`, and every `parse*` in `src/contracts/` reject by throwing, matching the existing contract-layer convention exactly. +> **Orchestrating readers return `ProjectResult`** — the functions that run a Git command or touch the filesystem and must report to a caller. This is the rule `preflightGit` embodies: the runner throws, the reader translates. +> **Pure derivations return their value directly.** `computeTaskIdentity`, `computeRequestDigest`, `computeInputFingerprint`, `gitBlobOid`, and `canonicalJsonBytes` take already-parsed inputs and cannot fail meaningfully. + +**One declared exception.** `SecretScanResult`'s `outcome: "unavailable"` is a third channel, deliberately: the scanner's absence is a *result state* Phase 8 must persist as evidence that a projection was never scanned, not a call failure. A `ProjectResult` error would be surfaced and discarded. No other bespoke channel is permitted. + +### `src/contracts/canonical.ts` — chunk 1, lands first + +```ts +import { z } from "zod"; +import type { PlainJsonValue } from "./plain-json.js"; +import type { Sha256Digest } from "./evidence.js"; + +declare const gitOidBrand: unique symbol; + +/** Lowercase 40-character hexadecimal SHA-1 object name; blobs and commits share one brand. */ +export type GitOid = string & { readonly [gitOidBrand]: true }; + +export const GIT_TREE_MODES = ["040000", "100644", "100755", "120000", "160000"] as const; +export type GitTreeMode = (typeof GIT_TREE_MODES)[number]; +/** The only mode legal below `.archflow/**`. */ +export type ArchflowTreeMode = "100644"; + +export const gitOidV1Schema: z.ZodType; // /^[0-9a-f]{40}$/u +export const gitTreeModeV1Schema: z.ZodType; +export function parseGitOid(value: unknown): GitOid; +export function parseGitTreeMode(value: unknown): GitTreeMode; +/** Normalises the raw-tree 5-character `40000` form to the displayed `040000` form. */ +export function normalizeGitTreeMode(value: string): GitTreeMode; + +export function canonicalJsonBytes(value: PlainJsonValue): Uint8Array; +export function sha256Bytes(bytes: Uint8Array): Sha256Digest; +export function canonicalJsonDigest(value: PlainJsonValue): Sha256Digest; +/** OID = SHA1("blob " + ASCII_decimal(content.byteLength) + "\0" + content). */ +export function gitBlobOid(content: Uint8Array): GitOid; + +/** Shared digest helpers so independent chunks construct identical error parameters. */ +export function historyIdentityDigest(oid: GitOid): Sha256Digest; +export function repositoryCandidateDigest(absoluteCwd: string): Sha256Digest; + +export interface CanonicalDocument { + readonly bytes: Uint8Array; + readonly value: T; + readonly digest: Sha256Digest; +} +export function canonicalDocument(value: T): CanonicalDocument; +export function parseCanonicalDocument( + bytes: Uint8Array, + label?: string, +): CanonicalDocument; +``` + +**`parseCanonicalDocument` is a byte-authority, and its contract is pinned exactly**, mirroring Phase 5's live implementation rather than merely re-rendering. In order: decode with `new TextDecoder("utf-8", { fatal: true })`, so malformed UTF-8 throws rather than producing replacement characters; `JSON.parse`; `assertPlainJson`, which already rejects non-plain prototypes, symbol keys, accessor properties, non-finite numbers, and the dangerous own keys `__proto__`, `prototype`, `constructor`; re-render with `canonicalJsonBytes` and **byte-compare against the input**, rejecting any noncanonical form — wrong key order, non-two-space indent, a missing or extra trailing newline, or any other whitespace difference. `digest` is `sha256Bytes` over the **original** input bytes, which by that point are proven byte-identical to the re-rendered canonical form, so the two possible readings coincide by construction. Duplicate object keys need no special rule: `JSON.parse` keeps the last, so a duplicate-key input re-renders shorter and fails the byte comparison. Fixtures must cover malformed UTF-8, duplicate keys, permuted key order, two-versus-four-space indent, and missing/extra trailing newline. + +**The parity test needs a declaration file to typecheck.** `tsconfig.json` sets no `allowJs` and `skipLibCheck: false`, so importing `scripts/release-support.mjs` from a `.test.ts` fails with `TS7016: Could not find a declaration file`. Vitest would run it happily; `tsc --noEmit` would not, and `npm run check` runs typecheck first — so chunk 1 as written would break the aggregate at its first step. Chunk 1 therefore adds a hand-written `scripts/release-support.d.mts` declaring exactly the three exported symbols the test needs (`canonicalJsonBytes`, `sha256`, `assertPortablePath`). Note `sortCanonical` and `isInside` are **module-private and not exported**, so parity for the containment predicate is asserted behaviourally, not by direct call. The fallback is the subprocess pattern already used in `test/integration/release-offline.test.ts`. + +### `src/contracts/evidence.ts` and `src/contracts/path-claims.ts` — chunk 2 + +Chunk 2 publishes primitives and changes no consumer; chunk 3 does that. **Every schema below yields a branded value**, not `string`, using the `as unknown as z.ZodType` pattern `trust.ts:140-141` already establishes. Without this, a parsed `task_id` could not be passed to `computeTaskIdentity` or `toRepositoryPathClaim` without an undocumented cast at every call site. + +```ts +// src/contracts/evidence.ts — ADDED alongside the existing safeId, which is unchanged +declare const pathSafeIdBrand: unique symbol; +export type PathSafeId = string & { readonly [pathSafeIdBrand]: true }; +export const pathSafeIdV1Schema: z.ZodType; // /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u +export function parsePathSafeId(value: unknown): PathSafeId; + +declare const taskSlugBrand: unique symbol; +export type TaskSlug = string & { readonly [taskSlugBrand]: true }; +export const taskSlugV1Schema: z.ZodType; // /^[a-z0-9][a-z0-9._-]{0,63}$/u +export function parseTaskSlug(value: unknown): TaskSlug; + +// src/contracts/path-claims.ts +export type TaskPathClaim = string & { readonly [taskPathClaimBrand]: true }; // brand unchanged +export const taskPathClaimV1Schema: z.ZodType; +export function parseTaskPathClaim(value: unknown): TaskPathClaim; + +declare const repositoryPathClaimBrand: unique symbol; +/** Same lexical rules as TaskPathClaim; different frame — rooted at the worktree, not the task. */ +export type RepositoryPathClaim = string & { readonly [repositoryPathClaimBrand]: true }; +export const repositoryPathClaimV1Schema: z.ZodType; +export function parseRepositoryPathClaim(value: unknown): RepositoryPathClaim; +export function toRepositoryPathClaim(taskId: TaskSlug, claim: TaskPathClaim): RepositoryPathClaim; + +declare const rawGitPathBrand: unique symbol; +/** A path exactly as Git emitted it. Total constructor; carries no lexical guarantee at all. */ +export type RawGitPath = string & { readonly [rawGitPathBrand]: true }; +export function rawGitPath(value: string): RawGitPath; +/** The sole promotion path from untrusted Git output to a branded claim. */ +export function tryRepositoryPathClaim(value: RawGitPath): RepositoryPathClaim | undefined; + +export const TASK_PATH_CLASSES = [ + "task-config", "task-state", "gate-interface", "document", "review", + "decision", "result-manifest", "result-payload", "intent", "attempt", + "manual-checkpoint", "maintenance-record", "import", +] as const; +export const REPOSITORY_PATH_CLASSES = [ + "shared-workflow", "shared-constitution", "task-branch-constitution", "repository-source", +] as const; +export const PATH_CLASSES = [...TASK_PATH_CLASSES, ...REPOSITORY_PATH_CLASSES] as const; +export type TaskPathClass = (typeof TASK_PATH_CLASSES)[number]; +export type RepositoryPathClass = (typeof REPOSITORY_PATH_CLASSES)[number]; +export type PathClass = (typeof PATH_CLASSES)[number]; +export const READ_ONLY_PATH_CLASSES: readonly PathClass[]; // shared-workflow, shared-constitution +export function parsePathClass(value: unknown): PathClass; +``` + +**Three path representations, because one type cannot honestly carry three guarantees.** `TaskPathClaim` is rooted at the task directory; `RepositoryPathClaim` is rooted at the worktree; `RawGitPath` is whatever Git printed. The first two share one lexical schema — `path-claim.schema.json` remains the sole authority, and `primitives.schema.json` gains `repositoryPathClaim` as `{ "$ref": "urn:archflow:schema:v1:path-claim" }`, the same aliasing pattern `mcp-tools.schema.json:8` already uses for `"id"`. Only the frame differs, and since these paths feed digest-bound manifests, a frame mix-up produces a *wrong digest* rather than an error — exactly the failure class brands exist to catch. + +`RawGitPath` exists because **not every path a valid repository contains can be branded.** A user's repository may legitimately hold a conflicted file whose name has a colon, a trailing dot, non-NFC text, a reserved device name, or a newline; `git diff --diff-filter=U -z` emits it raw. Typing that list as `RepositoryPathClaim[]` would force either a throw while merely *checking* for unrelated conflicts, or an unsafe cast. `rawGitPath` is total and asserts nothing; `tryRepositoryPathClaim` is the sole promotion, and it returns `undefined` rather than throwing so a caller can count what it cannot represent. + +**Lexical rules, extended.** The existing `taskPathClaimV1Schema` rejects empty/`.`/`..` segments, leading `/`, drive and UNC prefixes, backslashes, control characters, and anything over 1024 UTF-8 bytes. Chunk 2 adds: reject `:` anywhere; reject Git pathspec metacharacters `*`, `?`, `[`, `]`; reject the remaining Windows-illegal characters `<`, `>`, `|`; reject segments matching `/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$/i`; reject segments with a trailing `.` or space; require every segment to be already NFC. The pathspec metacharacters are a correctness rule, not only a portability one: without them a single claimed path can select multiple files in any `git` invocation that takes a pathspec. + +**NFC needs a custom Ajv keyword**, because it is not expressible as a `pattern`. `path-claim.schema.json` is a pure `pattern` schema; an NFD sample would make Zod reject while Ajv accepts, failing `assertZodAgreement`. The repository already solved this class of problem — `x-archflow-max-utf8-bytes` at `src/contracts/validators.ts:178` is a custom keyword for the same reason. Chunk 2 adds a fifth keyword, `x-archflow-nfc`. + +**`PathSafeId` exists because `safeId` permits `:` and the repository's own corpus proves the collision.** `src/contracts/evidence.ts:23` is `/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u`, and `test/contracts/shared-primitives-schema-agreement.test.ts:20` uses `"task-1:phase"` as a canonical **valid** safeId sample. `src/contracts/mcp-tools.ts:30` validates `intent_id: safeId`, so a caller may legally send `intent_id: "retry:3"`; the `intent` path-class template then produces `intents/retry:3.json`, which chunk 2's own tightened claim schema rejects. + +**`TaskSlug` lives in `src/contracts/`, not `src/repository/`.** Its pattern is a pure lexical predicate with no Git or filesystem dependency, but `task_id` is validated at the MCP boundary in `mcp-tools.ts:30` as `safeId`, and contracts may not import repository. Left in the repository layer the rule could never be applied where it matters, and the two vocabularies disagree — `safeId` permits uppercase, `_`, `:`, and 128 characters, so a task named `My_Task` would pass `archflow_state` and then fail path resolution deep inside. + +`PATH_CLASSES` lives in `path-claims.ts` because `src/contracts/secret-scan.ts` references `PathClass` and contracts cannot import repository. + +### The boundary retightening — chunk 3, one atomic change + +Zod and JSON Schema are compared by `assertZodAgreement`, so **every Zod edit and its JSON Schema counterpart are a single indivisible change**. Retightening one side alone fails the agreement tests on the first colon or uppercase sample. + +**Read this before using the list below.** This inventory has been found incomplete three times across successive reviews. **It is a cross-check, not an authority.** The implementing chunk must **regenerate it mechanically** — grep every occurrence of each logical ID name across all Zod modules in `src/contracts/`, every exported TypeScript interface, all 24 normative JSON Schemas, the advertised-schema closure, and every fixture under `test/` — then reconcile the generated set against the prose list. **Any difference is a design defect to report back, not something to silently absorb**, in either direction: a site the list omits, and a site the list names that no longer exists. + +Retightening is **global per logical ID**. There are no per-site exceptions: + +| Logical ID | Becomes | Scope | +|---|---|---| +| `task_id` | `taskSlugV1Schema` → `TaskSlug` | **every** occurrence, everywhere | +| `intent_id` | `pathSafeIdV1Schema` → `PathSafeId` | **every** occurrence, everywhere | +| `gate_id`, `prior_gate_id`, `superseded_gate_id`, `origin_gate_id`, `waiver_gate_id` | `pathSafeIdV1Schema` → `PathSafeId` | **every** occurrence, everywhere | +| `rule_id`, `result_id`, `receipt_id`, `invocation_id`, `connection_id`, `decision_event_id`, `helper_invocation_id`, `detector_id`, `input_id` | unchanged `safeId` | **no** occurrence changes | + +Known sites, to be reconciled against the mechanical sweep: + +- `src/contracts/mcp-tools.ts` — `task_id`/`intent_id` at `:30` and `:128`; `superseded_gate_id` `:58`; `origin_gate_id` + `task_id` `:60`; `origin_gate_id`/`waiver_gate_id`/`task_id` `:80`. `rule_id` (`:27`, `:80`) and `result_id` (`:128`) stay `safeId`. +- `src/contracts/gates.ts` — `gate_id` and `task_id` on the decision envelope base at `:120`. `connection_id` and `decision_event_id` (`:117`) stay. +- `src/contracts/trust.ts` — `:157` parses `current_evidence.slots[*].gate_id` with the module-local `idSchema`; also the `gate_id` on `ObservationBindingByKind["review"]`. +- `src/contracts/supplemental.ts` — `:7` `SupplementalGateRef.prior_gate_id` and `task_id`; `:9` `GateSupersessionRef.superseded_gate_id`; `:21` `gateShape`; `:23` `gateCounterSlotSchema.gate_id`. +- `src/contracts/schemas/v1/mcp-tools.schema.json` — line 8 defines one local `"id": { "$ref": "…primitives#/$defs/safeId" }` that **every** id field points at: `task_id`/`intent_id` at 63–64, 98–99, 158–159, 208–209, 266–267, 371–372, plus `superseded_gate_id:283`, `origin_gate_id:390,421`, `waiver_gate_id:422`. Add `#/$defs/taskSlug` and `#/$defs/pathSafeId` and repoint each site individually — a global rename would be wrong, because `rule_id` and `result_id` must keep `safeId`. +- `src/contracts/schemas/v1/gate-decision.schema.json:107-112` — `gate_id` and `task_id`, currently `#/$defs/safeId`. +- `src/contracts/schemas/v1/result-expectation.schema.json:35-36` — `task_id` and `intent_id`, currently `#/$defs/id`, mirroring `mcp-tools.ts:128`. +- `src/contracts/schemas/v1/evidence-slots.schema.json:12` — `gateCounter.gate_id`, currently `#/$defs/id` (line 9, the colon-permitting pattern). +- `src/contracts/schemas/v1/supplemental-review.schema.json` and the authority-link contracts — the same logical gate and task IDs. +- `src/contracts/schemas/v1/project-error.schema.json:109,1434,1527` — `path_class`, only if chunk 3 takes the optional `z.enum(PATH_CLASSES)` narrowing; skipping the JSON side breaks `test/contracts/gate-error-schema-agreement.test.ts`. + +**Branded public interfaces.** Retyping the schemas is not enough — the exported interfaces must carry the brands too, or every downstream call needs a cast. `CommonToolInput`, `StateInput`/`CounterReviewInput`/`AdjudicateInput`/`GateInput`/`WaiverInput`, `ResultIdentityPayload`, `WaiverDecisionBinding`, `GateDecisionEnvelopeBase`, `GateSupersessionRef`, and `SupplementalGateRef` all change `task_id: string` to `task_id: TaskSlug` and the gate/intent fields to `PathSafeId`. A compile-time test asserts that a plain `string` is not assignable to any of them. + +**`SNAPSHOT_LIMIT.offending_paths` is retyped, not excepted.** The previous revision left it `taskPathClaimV1Schema` on the grounds that both brands erase to the same wire schema. That was wrong: the paths it reports are declared outputs, which are repository-relative, so leaving it task-branded forces a cast across frames at the one place a caller assembles the diagnostic. It becomes `z.array(repositoryPathClaimV1Schema)` in `errors.ts`, its `project-error.schema.json` `$ref` repoints to the `repositoryPathClaim` alias — the same lexical authority, so no wire change — and its fixtures update. + +**`task-branch-constitution` stays a literal, sourced from the enum.** `gates.ts:34` declares the field as the literal type and `gates.ts:93` parses `z.literal("task-branch-constitution")`; `gate-contract.schema.json:259` is `"const"`. Substituting `z.enum(PATH_CLASSES)` would let the `constitution-edit` gate accept `"repository-source"` or `"document"` when exactly one value is ever legal — and `parseGateContext` (`gates.ts:150`) ends in `contexts[kind].parse(value) as GateContext`, an unchecked cast, so a widened runtime result would be silently cast to a 1-value declared type with `tsc` never noticing. The fix removes only the duplication: `z.literal("task-branch-constitution" satisfies PathClass)`. The JSON Schema `const` is untouched. + +**Test corpus chunk 3 must update.** The fixtures are saturated with the exact strings being outlawed: `test/unit/mcp-tools.test.ts:124,139` (`task_id: "Task:1"`, `intent_id: "Intent:1"`) and `:244` (`task_id: "Task_1"` — the very string this design uses as its motivating counter-example is a live passing fixture); `test/contracts/mcp-advertised-schema.test.ts:118` (`COMMON`, feeding every advertised-schema case); `test/contracts/gate-error-schema-agreement.test.ts:38` (`task_id: "Task_1"`, `gate_id: "Gate:1"`); `test/contracts/mcp-contract-agreement.test.ts:50,85,97`; `test/unit/trust.test.ts` and `test/unit/supplemental.test.ts`, plus the gate/supplemental exhaustive fixtures, which currently accept `Gate:1` and `Task_1`. The JSON fixtures under `test/fixtures/` use `task-1`/`intent-1` and are safe. `test:mcp-runtime` is a **separate `npm run check` step** and also fails until `mcp-tools.test.ts` is updated. In `test/contracts/shared-primitives-schema-agreement.test.ts`, **append two rows to the `it.each` table at line 18** — one for `pathSafeId`, one for `taskSlug`; the existing `"task-1:phase"` row is unchanged, and that table is explicit rather than `$defs`-derived, so new `primitives.schema.json` entries neither break it nor gain coverage automatically. + +### `src/repository/git.ts` — chunk 4 + +```ts +export type GitFailureKind = + | "not-installed" | "not-executable" | "timeout" | "output-overflow" + | "spawn-failed" | "command-failed"; +export class GitInvocationError extends Error { + readonly kind: GitFailureKind; + readonly operation: SafeCode; + readonly argv: readonly string[]; + readonly code?: number; + readonly stderr?: string; +} + +/** Absence is command-specific and caller-declared; never inferred from exit 128 alone. */ +export interface ExpectedAbsence { + readonly code: number; + readonly stderrIncludes: string; +} +export interface GitCommandSpec { + readonly argv: readonly string[]; + readonly operation: SafeCode; // e.g. "git-ls-files", "git-check-attr", "git-status" + readonly expectedAbsence?: readonly ExpectedAbsence[]; + readonly maxBuffer?: number; // default 8 MiB + readonly timeoutMs?: number; // default 30_000 +} +export interface GitInvocationResult { + readonly code: number; + readonly stdout: Uint8Array; + readonly stderr: string; + readonly absent: boolean; // true only via a matched ExpectedAbsence +} +export interface GitRunner { + readonly cwd: string; + readonly run: (spec: GitCommandSpec) => Promise; + readonly runText: (spec: GitCommandSpec) => Promise; + readonly runNulFields: (spec: GitCommandSpec) => Promise; +} +export function createGitRunner(options: { + readonly cwd: string; + readonly gitPath?: string; + readonly maxBuffer?: number; + readonly timeoutMs?: number; +}): GitRunner; + +export interface GitEnvironment { + readonly version: SafeVersion; + readonly object_format: "sha1"; +} +export function preflightGit( + runner: GitRunner, + context: RepositoryOperationContext, +): Promise>; +``` + +**`exit 128 ⇒ absent` is withdrawn as unsafe.** Git returns 128 for dubious ownership, corrupt objects, a corrupt repository, invalid revision syntax, and many other fatal conditions — treating all of them as "the object is not there" turns a broken repository into a silent empty answer. Each command declares its own `expectedAbsence` entries, and a nonzero exit is classified as absence **only** when both the exact code and the accompanying diagnostic substring match. Everything else nonzero throws `GitInvocationError` with `kind: "command-failed"`. + +**The three methods behave identically on failure**, so chunks 5–8 cannot each invent a convention: + +| Outcome | `run` | `runText` | `runNulFields` | +|---|---|---|---| +| exit 0 | result, `absent: false` | UTF-8 decoded, single trailing LF stripped | NUL-split, trailing empty field dropped | +| nonzero matching an `expectedAbsence` | result, `absent: true` | `""` | `[]` | +| any other nonzero | throws `command-failed` | throws | throws | +| spawn `ENOENT` / `EACCES` | throws `not-installed` / `not-executable` | throws | throws | +| past `timeoutMs` | throws `timeout` | throws | throws | +| past `maxBuffer` | throws `output-overflow` | throws | throws | + +`runText` decodes with fatal UTF-8; `runNulFields` returns raw fields without decoding assumptions beyond fatal UTF-8, and never strips or interprets `\t`. + +### Error context and the complete failure map — chunk 4 publishes, all readers consume + +Every project error this phase promises requires parameters no Git command returns. The context is therefore an explicit argument, not something readers invent. + +```ts +export interface RepositoryOperationContext { + readonly task_id: TaskSlug; + readonly phase_instance: PhaseInstanceId; + readonly operation: SafeCode; // the logical operation, e.g. "startup-check", "handoff-check" + readonly attempt: SafeInteger; +} +``` + +Every failure branch in this phase maps to exactly one code with exactly these parameters: + +| Branch | Code | Parameters | +|---|---|---| +| `git` missing / not executable | `REPOSITORY_NOT_FOUND` | `{repository_candidate_digest: repositoryCandidateDigest(runner.cwd)}` | +| not inside a work tree; bare repo; inside `.git/` | `REPOSITORY_NOT_FOUND` | same | +| timeout, overflow, spawn failure, `command-failed` | `IO_ERROR` | `{operation: context.operation, attempt: context.attempt}` | +| Git below the ~2.25 floor | `RUNTIME_VERSION_UNSUPPORTED` | `{component: "git", version}` | +| `--show-object-format` is `sha256` | `RUNTIME_VERSION_UNSUPPORTED` | `{component: "git-object-format", version: "sha256"}` | +| shallow clone; unborn HEAD; submodule | `REPOSITORY_NOT_FOUND` | `{repository_candidate_digest}` | +| recorded identity ≠ observed | `REPOSITORY_MISMATCH` | `{expected_digest, observed_digest}` — both repository identity digests | +| claim fails the lexical schema | `PATH_INVALID` | `{task_id, path_class}` | +| containment rejects the resolved path | `PATH_ESCAPE` | `{task_id, path_class}` | +| claim resolves outside the active task | `TASK_SCOPE_VIOLATION` | `{task_id, path_class}` | +| `.archflow/**` index mode ≠ `100644`, or mode `160000` anywhere | `TASK_INVALID` | `{task_id, issue_code: "archflow-tree-mode-illegal"}` | +| `check-attr` reports anything but `text: unset` / `merge: binary` | `TASK_INVALID` | `{task_id, issue_code: "archflow-attributes-missing"}` | +| a returned path ≠ the requested claim | `TASK_INVALID` | `{task_id, issue_code: "git-path-mismatch"}` | +| conflicted `.archflow/` path present | `GIT_CONFLICT` | `{operation: context.operation}` | +| upstream tracked and ahead ≠ 0 and behind ≠ 0 | `GIT_DIVERGED` | `{expected_digest: historyIdentityDigest(upstreamOid), observed_digest: historyIdentityDigest(headOid)}` | +| any in-progress operation present | `HANDOFF_REQUIRED` | `{phase_instance: context.phase_instance}` | +| `config.yaml` bytes ≠ pinned digest | `PINNED_CONFIG_MISMATCH` | `{expected_digest, observed_digest}` | + +`historyIdentityDigest` and `repositoryCandidateDigest` are pinned in chunk 1 precisely so two chunks cannot construct the same error with different digests. `GIT_DIVERGED`'s parameters are `sha256` digests, not raw OIDs, because `PROJECT_PARAMETER_SCHEMAS` requires `/^[0-9a-f]{64}$/`; hashing the OID through the shared helper satisfies that without inventing a per-chunk encoding. + +### `src/repository/identity.ts` — chunk 5 + +```ts +export interface WorktreeLocation { + readonly worktreeRoot: string; // absolute realpath; where .archflow/ lives + readonly gitDir: string; // absolute, per-worktree + readonly gitCommonDir: string; // absolute, shared across linked worktrees + readonly linked: boolean; +} + +declare const rootBoundBrand: unique symbol; +/** A runner whose cwd is provably the worktree root. Only discovery can mint one. */ +export interface RootBoundGitRunner extends GitRunner { + readonly location: WorktreeLocation; + readonly [rootBoundBrand]: true; +} +/** Returns the runner, not just the location: there is no way to keep using the unbound one. */ +export function discoverWorktree( + runner: GitRunner, + context: RepositoryOperationContext, +): Promise>; + +export interface RepositoryIdentity { + readonly schema_version: "1"; + readonly object_format: "sha1"; + readonly root_commits: readonly GitOid[]; // ordinal-sorted, one entry per root + readonly digest: Sha256Digest; // sha256(canonicalJsonBytes({object_format, root_commits})) +} +export function resolveRepositoryIdentity( + runner: RootBoundGitRunner, + environment: GitEnvironment, + context: RepositoryOperationContext, +): Promise>; +export function verifyRepositoryIdentity( + expected: Sha256Digest, + observed: RepositoryIdentity, +): ProjectResult; + +export interface TaskIdentity { + readonly schema_version: "1"; + readonly task_id: TaskSlug; + readonly repository_identity_digest: Sha256Digest; + readonly digest: Sha256Digest; +} +/** Bare return: a pure derivation over already-parsed inputs, per the failure convention. */ +export function computeTaskIdentity(taskId: TaskSlug, repository: RepositoryIdentity): TaskIdentity; +``` + +**The root-bound runner closes a silent-wrong-answer hole, reproduced.** From a subdirectory `repo/sub`, `git ls-files -s -- .archflow/…` returns **nothing** and `git check-attr text merge -- .archflow/…` returns `text: auto` / `merge: unspecified` — no error in either case, just the wrong answer. Spelling it `../.archflow/…` finds the file but emits a path that can never be a valid `RepositoryPathClaim`. Making every reader below discovery accept only `RootBoundGitRunner` removes the possibility structurally rather than by convention. All pathspecs are top-anchored and literal — `:(top,literal)` with `--literal-pathspecs` — and every reader **asserts that each returned path is exactly equal to the requested claim**, producing `TASK_INVALID{issue_code:"git-path-mismatch"}` otherwise. + +### `src/repository/paths.ts` — chunk 6 + +```ts +import type { FileHandle } from "node:fs/promises"; + +declare const resolvedTaskPathBrand: unique symbol; +/** A path proven contained under the worktree root by realpath at resolution time. */ +export type ResolvedTaskPath = string & { readonly [resolvedTaskPathBrand]: true }; + +export interface ResolvedPath { + readonly path_class: PathClass; + readonly repositoryRelative: RepositoryPathClaim; + readonly absolute: ResolvedTaskPath; +} + +export function classifyTaskPath( + taskId: TaskSlug, claim: TaskPathClaim, +): ProjectResult; +export function classifyRepositoryPath( + claim: RepositoryPathClaim, +): ProjectResult; + +export function resolveTaskPath(options: { + readonly runner: RootBoundGitRunner; + readonly taskId: TaskSlug; + readonly claim: TaskPathClaim; // rooted at .archflow/tasks// + readonly expectedClass?: TaskPathClass; + readonly context: RepositoryOperationContext; +}): Promise>; + +export function resolveRepositoryPath(options: { + readonly runner: RootBoundGitRunner; + readonly claim: RepositoryPathClaim; // rooted at the worktree + readonly expectedClass?: RepositoryPathClass; + readonly context: RepositoryOperationContext; +}): Promise>; + +/** Throws; failure here is an environment fault with no caller-facing project code. */ +export function openResolved(path: ResolvedTaskPath, flags: number): Promise; +``` + +**Two resolvers, because one cannot represent all seventeen classes.** `toRepositoryPathClaim(taskId, claim)` necessarily places its result below `.archflow/tasks//`, yet `shared-workflow`, `shared-constitution`, `task-branch-constitution`, and `repository-source` are rooted at the worktree — `repository-source` is not under `.archflow/` at all. Splitting the API and partitioning the class enum makes the wrong call unrepresentable rather than merely discouraged. + +**Every class, its template, and its required identifiers.** Task-scoped classes resolve relative to `.archflow/tasks//`; repository-scoped classes relative to the worktree root. + +| Class | Scope | Template | Required identifiers | +|---|---|---|---| +| `task-config` | task | `config.yaml` | — | +| `task-state` | task | `state.json` | — | +| `gate-interface` | task | `gate.json` \| `gate.decision` | — | +| `document` | task | `prd.md` \| `design.md` \| `phases//design.md` \| `phases//impl-notes.md` | positive phase number | +| `review` | task | `reviews/.{self,counter,triage,adjudication}.md` \| `reviews/.gate-counter..md` | phase instance; gate ID for the last form | +| `decision` | task | `decisions//request.json` \| `decisions//decision.json` | gate ID | +| `result-manifest` | task | `results/sha256//manifest.json` | result digest | +| `result-payload` | task | `results/sha256//payload/` | result digest; declared output claim | +| `intent` | task | `intents/.json` | intent ID | +| `attempt` | task | `attempts//.json` | phase instance; attempt ID | +| `manual-checkpoint` | task | `manual/checkpoints/-.json` | revision; checkpoint digest | +| `maintenance-record` | task | `maintenance/.json` | maintenance ID | +| `import` | task | `imports//manifest.json` \| `imports//payload/` | import digest; legacy claim | +| `shared-workflow` | repository | `.archflow/workflow.yaml` | — (read-only) | +| `shared-constitution` | repository | `.archflow/constitution/.md` | name (read-only) | +| `task-branch-constitution` | repository | `.archflow/constitution/.md` | name | +| `repository-source` | repository | any repository claim **not** under `.archflow/` | — | + +Every identifier is a `PathSafeId` except phase instances (`PhaseInstanceId`), digests (`Sha256Digest`, already a strict subset of `PathSafeId`), phase numbers (`PositiveSafePhaseNumber`), and revisions (`SafeInteger`). `attempt-id` and `maintenance-id` have zero occurrences in `src/` today; they are template placeholders here and must be declared `PathSafeId` at birth in Phase 7 or later, never retrofitted. `shared-constitution` and `task-branch-constitution` share one template deliberately: they name the same file and are distinguished by *operation* — reading pinned policy versus detecting a task-branch edit — so `classifyRepositoryPath` returns `shared-constitution` and the caller narrows to `task-branch-constitution` when the operation is the constitution-edit check. That is stated rather than hidden because a path alone cannot decide it. + +**Containment is seven steps, in this exact order**: (1) reject NUL, `path.isAbsolute(input)`, or a win32 drive letter *before* resolving; (2) `candidate = path.resolve(root, input)`; (3) `realRoot = await realpath(root)`; (4) `realCand = await realpath(candidate)`, and on `ENOENT` realpath the nearest existing ancestor and re-append the missing tail; (5) `rel = path.relative(realRoot, realCand)`; (6) accept only if `rel === "" || (!rel.startsWith(".." + path.sep) && !path.isAbsolute(rel))`; (7) on the real open, OR in `(fs.constants.O_NOFOLLOW ?? 0)`. + +### `src/repository/attributes.ts` and `src/repository/index-entries.ts` — chunk 7 + +```ts +export const ARCHFLOW_GITATTRIBUTES_RULE = ".archflow/** -text merge=binary"; +export interface AttributeCheck { + readonly path: RepositoryPathClaim; + readonly text: string; // must be "unset" + readonly merge: string; // must be "binary" +} +export function checkArchflowAttributes( + runner: RootBoundGitRunner, + paths: readonly RepositoryPathClaim[], + context: RepositoryOperationContext, +): Promise>; + +export interface IndexEntry { + readonly path: RepositoryPathClaim; + readonly mode: GitTreeMode; + readonly oid: GitOid; + readonly stage: 0 | 1 | 2 | 3; +} +export function readIndexEntries( + runner: RootBoundGitRunner, + paths: readonly RepositoryPathClaim[], + context: RepositoryOperationContext, +): Promise>; +/** Throws; readIndexEntries translates to TASK_INVALID{issue_code:"archflow-tree-mode-illegal"}. */ +export function assertArchflowIndexEntry( + entry: IndexEntry, +): asserts entry is IndexEntry & { readonly mode: ArchflowTreeMode }; +``` + +**Both readers are `-z`, and the cardinality is pinned.** Without `-z`, both `git ls-files -s` and `git check-attr` C-quote non-ASCII filenames — reproduced with `.archflow/ü space.json` — so a caller would have to implement C-style unquoting to recover a name it already knows. With `-z`: + +- `git ls-files -s -z --literal-pathspecs -- :(top,literal)…` emits, per entry, one NUL-terminated field of the form ` \t`. Split on NUL first, then on the single `\t`; never split the path on whitespace. +- `git check-attr -z text merge --literal-pathspecs -- …` emits **NUL triplets, not lines**: `\0\0\0`, one triplet per (path, attribute) pair. For N paths and the two attributes requested, that is exactly **2N triplets, i.e. 6N NUL-terminated fields**. Any other count is `TASK_INVALID{issue_code:"git-path-mismatch"}` rather than a best-effort parse. + +Both readers assert every returned path is byte-equal to the requested claim, and both reject `160000` outright. + +### `src/repository/history.ts` and the barrel — chunk 8 + +```ts +export type UpstreamState = + | Readonly<{ kind: "no-upstream" }> + | Readonly<{ kind: "tracked"; upstream: string; ahead: number; behind: number; upstreamOid: GitOid }>; + +export const IN_PROGRESS_OPERATIONS = [ + "merge", "rebase-merge", "rebase-apply", "cherry-pick", "revert", +] as const; +export type InProgressOperation = (typeof IN_PROGRESS_OPERATIONS)[number]; + +export interface WorktreeHistoryStatus { + readonly head: GitOid | undefined; // undefined only for unborn HEAD + readonly branch: string | "(detached)"; + readonly upstream: UpstreamState; + readonly inProgress: readonly InProgressOperation[]; + /** Validated: an unrepresentable `.archflow/` name is a TASK_INVALID, since we own that tree. */ + readonly conflictedArchflowPaths: readonly RepositoryPathClaim[]; + /** Raw: a valid repository may legitimately contain names ArchFlow claims cannot express. */ + readonly conflictedOtherPaths: readonly RawGitPath[]; + readonly unrepresentableOtherConflicts: SafeInteger; +} +export function readHistoryStatus( + runner: RootBoundGitRunner, + context: RepositoryOperationContext, +): Promise>; +/** ProjectResult, not a third shape: success carries no value, failure carries the code. */ +export function classifyMutationReadiness( + status: WorktreeHistoryStatus, + context: RepositoryOperationContext, +): ProjectResult; +``` + +`classifyMutationReadiness` takes the context because none of `GIT_CONFLICT`, `GIT_DIVERGED`, or `HANDOFF_REQUIRED` can be constructed from `WorktreeHistoryStatus` alone: they need `operation`, a digest pair, and `phase_instance` respectively. `UpstreamState.tracked` carries `upstreamOid` for the same reason — the divergence digests are derived from it through `historyIdentityDigest`. + +Chunk 8 is the last repository chunk and therefore **owns `src/repository/index.ts`**, creating it once with the exports of chunks 4, 5, 6, 7, and 8. No earlier repository chunk touches the barrel. + +### `src/contracts/fingerprints.ts` — chunk 9 + +```ts +export interface DeclaredInputRef { + readonly input_id: SafeId; + readonly digest: Sha256Digest; +} +export interface GitIdentityRef { + readonly path: RepositoryPathClaim; + readonly mode: GitTreeMode; + readonly oid: GitOid; +} + +export interface InputFingerprintSubject { + readonly schema_version: "1"; + readonly workflow_digest: Sha256Digest; + readonly config_digest: Sha256Digest; + readonly constitution_digest: Sha256Digest; + readonly artifact_identities: readonly GitIdentityRef[]; // SET — sorted and deduped internally + readonly upstream_identities: readonly GitIdentityRef[]; // SET — sorted and deduped internally + readonly rubric_digest: Sha256Digest; + readonly phase_instance: PhaseInstanceId; + readonly declared_inputs: readonly DeclaredInputRef[]; // SET — sorted and deduped internally +} +export function computeInputFingerprint(subject: InputFingerprintSubject): Sha256Digest; + +export interface RequestDigestSubject { + readonly schema_version: "1"; + readonly tool: ToolName; + readonly repository_identity_digest: Sha256Digest; + readonly task_identity_digest: Sha256Digest; + readonly operation: SafeCode; + readonly operation_fields: PlainJsonObject; + readonly input_fingerprint: Sha256Digest; +} +export function computeRequestDigest(subject: RequestDigestSubject): Sha256Digest; + +/** Names that may never appear in `operation_fields`; asserted, not filtered. */ +export const EXCLUDED_REQUEST_DIGEST_FIELDS: readonly string[]; + +export function computePinnedConfigDigest(configBytes: Uint8Array): Sha256Digest; +export function verifyPinnedConfig( + expected: Sha256Digest, + observedBytes: Uint8Array, +): ProjectResult; +``` + +**All three collections are sets, and that is what makes the fingerprint deterministic.** `canonicalJsonBytes` sorts object keys but deliberately preserves array order, so an unsorted collection lets two callers hash identical logical inputs to different fingerprints — a silent divergence that would surface much later as a spurious `INPUT_FINGERPRINT_MISMATCH`. `InputFingerprintSubject` contains **no semantic sequences**. `computeInputFingerprint` therefore sorts before hashing: `artifact_identities` and `upstream_identities` by `path` ordinal, `declared_inputs` by `input_id` ordinal. A duplicate key in any of the three **throws** rather than being deduplicated, because two entries claiming the same path with different OIDs is a caller bug, not something to silently resolve. Permutation tests must prove that shuffling any collection yields an identical digest, and duplicate tests that a repeated key is rejected. `operation_fields` needs no rule — it is a plain object whose keys canonical JSON already sorts. + +### `src/contracts/secret-scan.ts` — chunk 9 + +```ts +export interface SecretScanCandidate { + readonly virtual_path: RepositoryPathClaim; // never a filesystem path, never raw Git output + readonly path_class: PathClass; + readonly content: string; +} +export interface SecretFinding { + readonly detector_id: SafeId; + readonly path_class: PathClass; + readonly virtual_path: RepositoryPathClaim; + readonly line: SafeInteger; // .min(1); 1-based, matching editor and secretlint convention + readonly column: SafeInteger; // .min(1) +} +export type SecretScanResult = + | Readonly<{ schema_version: "1"; outcome: "clean"; detector_set_id: SafeId; scanned_paths: readonly RepositoryPathClaim[] }> + | Readonly<{ schema_version: "1"; outcome: "detected"; detector_set_id: SafeId; findings: readonly SecretFinding[] }> + | Readonly<{ schema_version: "1"; outcome: "unavailable"; reason: SafeCode }>; + +export const secretScanResultV1Schema: z.ZodType; +export function parseSecretScanResult(value: unknown): SecretScanResult; // throws, per the convention +/** Interface Phase 8 implements. This phase ships the contract and no implementation. */ +export interface SecretScanner { + readonly scan: (candidates: readonly SecretScanCandidate[]) => Promise; +} +``` + +**The path fields are `RepositoryPathClaim` and that is provable, not assumed.** Secret-scan candidates are always *declared* paths — a candidate projection ArchFlow itself generates under `.archflow/`, or a declared implementation output the caller supplied and the claim schema already validated. They are never raw Git output, so no unrepresentable name can reach this contract. A compile-time test asserts a `RawGitPath` is not assignable to `virtual_path`, making the provenance invariant enforced rather than documented. + +`SecretFinding` carries no matched text, no surrounding context, and no redacted excerpt. The existing `SECRET_DETECTED` error takes exactly `{path_class, detector_id}`, which is the correct shape. `SafeInteger` permits `0`, so `line` and `column` carry `.min(1)` rather than leaving the base-index question to the implementing agent. + +**Safety note for whoever adapts an engine in Phase 8:** secretlint puts the **matched secret into `message`** — verified output reads `"found GitHub Token…: ghp_16C7e"`. The adapter must **explicitly drop `message`**, not merely omit it from the TypeScript type, or the value survives into logs through a stray object spread. `loc.start.line` and `loc.start.column` map cleanly onto this contract, and `ruleId` maps onto `detector_id`. + +## Files + +| Action | File | Chunk | Purpose | +|--------|------|-------|---------| +| Create | `src/contracts/canonical.ts`, `test/unit/canonical.test.ts` | 1 | Canonical JSON, SHA-256, Git blob OID, tree modes, shared error-digest helpers. | +| Create | `scripts/release-support.d.mts` | 1 | Hand-written declarations so the parity test passes `tsc --noEmit`. | +| Create | `test/contracts/canonical-parity.test.ts` | 1 | Prove the TypeScript and `.mjs` primitives agree over a shared corpus. | +| Modify | `.gitattributes` | 1 | Append `.archflow/** -text merge=binary` after the existing `* text=auto`. | +| Modify | `src/contracts/validators.ts` | 2 | Add the fifth custom Ajv keyword `x-archflow-nfc`. | +| Modify | `src/contracts/evidence.ts`, `src/contracts/schemas/v1/primitives.schema.json` | 2 | `PathSafeId`, `TaskSlug`, `repositoryPathClaim` `$defs`, all branded. | +| Modify | `src/contracts/path-claims.ts`, `src/contracts/schemas/v1/path-claim.schema.json` | 2 | Lexical hardening, `RepositoryPathClaim`, `RawGitPath`, the two class enums. | +| Modify | `src/contracts/mcp-tools.ts` + `mcp-tools.schema.json`; `gates.ts` + `gate-decision.schema.json`; `trust.ts`; `supplemental.ts` + `supplemental-review.schema.json`; `errors.ts` + `project-error.schema.json`; `result-expectation.schema.json`; `evidence-slots.schema.json` | 3 | The mechanically regenerated ID inventory, applied atomically across Zod and JSON Schema. | +| Modify | `test/unit/mcp-tools.test.ts`, `test/unit/trust.test.ts`, `test/unit/supplemental.test.ts`, `test/unit/path-claims.test.ts`, `test/contracts/mcp-advertised-schema.test.ts`, `test/contracts/mcp-contract-agreement.test.ts`, `test/contracts/gate-error-schema-agreement.test.ts`, `test/contracts/gate-error-supplemental-exhaustive.test.ts`, `test/contracts/shared-primitives-schema-agreement.test.ts` | 3 | Replace colon/underscore ID fixtures; append two `it.each` rows. | +| Create | `src/repository/git.ts`, `test/unit/repository-git.test.ts` | 4 | Runner, per-command absence, typed failure channel, `RepositoryOperationContext`. | +| Create | `src/repository/identity.ts`, `test/unit/repository-identity.test.ts` | 5 | Discovery, the root-bound runner, repository and task identity. | +| Create | `src/repository/paths.ts`, `test/unit/repository-paths.test.ts` | 6 | Two resolvers, the class table, containment, `ResolvedTaskPath`. | +| Create | `src/repository/attributes.ts`, `src/repository/index-entries.ts`, `test/unit/repository-index.test.ts` | 7 | `-z` `check-attr` triplets and `ls-files -s`, top-anchored literal pathspecs. | +| Create | `src/repository/history.ts`, `test/unit/repository-history.test.ts`, `src/repository/index.ts` | 8 | Porcelain v2 parsing, raw conflict paths, and the sole repository barrel. | +| Create | `src/contracts/fingerprints.ts`, `src/contracts/secret-scan.ts`, `src/contracts/schemas/v1/secret-scan-result.schema.json`, their tests and fixtures | 9 | Digests, set ordering, config pinning, secret-scan result contract. | +| Modify | `src/contracts/versions.ts`, `test/contracts/schema-registry.test.ts`, `src/contracts/index.ts` | 1–9 | Append-only registration, in strict chunk order. | +| Create | `test/integration/repository-git-matrix.test.ts` plus repository fixture helpers | 10 | Real temporary repositories covering the claims actually under test. | + +`package.json` and `.github/workflows/ci.yml` are deliberately **not** modified. `vitest.config.ts` already includes `test/**/*.test.ts`, so bare `npm test` — already the fourth step of `npm run check` and of CI — picks up the new integration suite automatically. Adding a `test:repository` script and wiring it into `check` would run the phase's most expensive suite twice. + +Registration files are shared and **append-only in strict numeric chunk order**. This is safe because `test/contracts/schema-registry.test.ts:31` is `as const satisfies Record`: appending to `SCHEMA_IDS` without the matching `SCHEMA_FILES` row fails `tsc --noEmit`, so each chunk's registry edits are necessarily atomic. New `$id` values use `urn:archflow:schema:v1:`, matching the 22-of-24 majority; the two `https://archflow.dev/...` IDs are legacy and are not a precedent. + +## Contract and Digest Rules + +- **Blob OID formula.** `OID = SHA1("blob " + ASCII_decimal(byteLength) + "\0" + contentBytes)`, where `byteLength` counts the content only. Verified: `printf 'hello\n' | git hash-object --stdin` and `printf 'blob 6\0hello\n' | sha1sum` both yield `ce013625030ba8dba906f756967f9e9ca394464a`. Computed in-process with `node:crypto`; no subprocess, no shell-escaping surface, trivially unit-testable. +- **`.archflow/** -text merge=binary`, at the repository root.** This is the highest-leverage line in the phase. With `-text` in force the attribute overrides `core.autocrlf` and `core.eol` entirely, so the blob OID becomes a pure function of the file's bytes, independent of every EOL-related config and of the platform. Measured: with no attribute, `autocrlf=false` hashes to `c30dea8a…` while `autocrlf=true` and `input` hash to `422c2b7a…`; with `-text` in force all three collapse to `c30dea8a…`. That collapse is what licenses in-process hashing. Use `merge=binary` — one of the three built-in low-level merge drivers (`text`, `binary`, `union`) — not the `binary` macro (`-diff -merge -text`), because the macro also kills diffs and readable `git diff` on state files is a real reviewer benefit. +- **Both attribute claims have now been independently reproduced by a second reviewer**, on a fresh repository: `git check-attr text merge` on an `.archflow/` path reports exactly `text: unset` and `merge: binary`, and a forced modify/modify conflict left the JSON **parseable with zero conflict markers** while `git status --porcelain=v2` and `git diff --name-only --diff-filter=U -z` both still reported the path unmerged. Conflict detection and file parseability are genuinely independent, which is the property the whole design leans on. +- **Ordering and renormalization.** `.gitattributes` already begins with `* text=auto`, and Git applies the **last** matching rule, so the new line is appended after it, never before. Because `.archflow/` is already tracked here with content, and changing attributes does not rewrite existing index blobs, a Windows checkout with `autocrlf=true` will show every `.archflow/` file as modified until someone runs `git add --renormalize .`. Invisible on Linux; a one-time cost, recorded rather than engineered around. +- **The attribute is verified at runtime, never assumed** — with the precedence stated correctly. Verified order: `$GIT_DIR/info/attributes` > in-tree `.gitattributes` > `core.attributesFile` > system. **Only `info/attributes` can override the repository file**; a global or system attributes file cannot. +- **Somebody has to create `.gitattributes` in the user's repository, and it is not this phase.** The `.gitattributes` change above modifies *this* repository; the server operates on the user's, and this phase implements no mutation. **Task initialization owns it** in Phase 7 or later, and until then `checkArchflowAttributes` is exercised entirely against temporary-repository fixtures. The `TASK_INVALID{issue_code:"archflow-attributes-missing"}` diagnostic must carry the remediation verbatim — *"add `.archflow/** -text merge=binary` to the repository root `.gitattributes`, commit it, then run `git add --renormalize .archflow`"* — because a bare failure is worthless to the user. +- **Legal tree modes** are `100644`, `100755`, `120000`, `160000`, `040000`. Raw tree objects store `40000` unpadded while `ls-tree`/`ls-files` display `040000`; normalise to the 6-character form. +- **Below `.archflow/**`, only mode `100644` is legal.** No executables, symlinks, or gitlinks. This single rule removes the entire `core.fileMode` / `core.symlinks` problem space for our own files. +- **For tracked repository outputs, mode and OID come from the index, never the filesystem** — `git ls-files -s`. `-s` is preferred over `--format`, which needs Git ≥2.38 and would raise the floor for no gain. `core.fileMode=false` makes Git ignore the filesystem executable bit and reuse the index mode; porcelain v2's three modes are ` ` and only `` may be trusted. Mode `160000` is rejected outright. +- Symlink-incapable checkouts need no special case. Git stores a symlink as a blob whose content is the target path with **no** trailing newline, and the index still records `120000`, so index-sourced mode plus content-derived OID is already stable across `core.symlinks=true/false`. +- **Object format fails closed on `sha256`.** `git rev-parse --show-object-format` is the detection command; reading `extensions.objectFormat` is wrong because that key is absent in a SHA-1 repository. SHA-1 remains the default in current Git — 2.55.0, released 2026-06-29 — and the SHA-256 flip is an unscheduled Git 3.0 item with no interoperability path. +- **One Git version floor: approximately 2.25**, from `--show-object-format`, absent in v2.24.0 and present in v2.25.0. The design avoids the two higher floors — `ls-files --format` (~2.38) and `rev-parse --path-format` (~2.31) — but does not reach zero. +- **Repository identity** = `sha256(canonicalJsonBytes({ object_format, root_commits }))`, where `root_commits` is the ordinal-sorted output of `git rev-list --max-parents=0 HEAD`. It contains no filesystem path, so it survives relocation and is shared by all linked worktrees. A generated UUID in a tracked `.archflow/repo-id` file was rejected: it survives more, but it introduces a tracked-file authority the architecture does not define and that repository initialization would have to create. +- **Canonical JSON** mirrors `scripts/release-support.mjs`: recursive key sort by ordinal comparison, 2-space indent, one trailing newline, UTF-8, arrays keep source order, `undefined` and non-finite numbers rejected. The script is `.mjs` and cannot import TypeScript, so the duplication is deliberate — and it is **three** primitives: `canonicalJsonBytes`, `assertPortablePath`, and the containment predicate. One divergence is recorded rather than removed: `release-support.mjs`'s private `isInside` requires `rel !== ""`, rejecting the root itself, because a release payload path is always a strict sub-path; containment step 6 here accepts `rel === ""` because a path class may legitimately resolve to the task root. +- **The request digest has one closed field list**: contract/schema version, logical tool name, canonical repository identity, canonical task identity, operation tag, that operation's request-specific semantic fields, and the recomputed declared-input fingerprint. Nothing else participates. The exclusions are the security property and are asserted, not filtered: `intent_id` identifies the receipt but is not self-hashed; `expected_revision`, connection/transport identifiers, timestamps, attempt counters, timeout/cancellation state, and retry metadata are all excluded. A retry after `SUPPLEMENTAL_REVIEW_REQUIRED` reuses the same digest with a refreshed `expected_revision`. +- **The declared-input fingerprint** hashes the versioned workflow digest, the immutable whole-config digest, the pinned constitution digest, canonical artifact and upstream Git identities, the rubric digest, the phase instance, and explicitly declared inputs — with the set-ordering rules above applied before hashing. The caller's `input_fingerprint` is an assertion, never authority; the server always recomputes. +- **Config pinning is `sha256` over the exact whole `config.yaml` bytes.** There is no in-task amendment and no re-pin schema: an intentional routing, model, or effort change requires a distinct task or the explicit upgrade flow, which is why whole-config binding can never cause partial in-task evidence invalidation. Any byte difference produces `PINNED_CONFIG_MISMATCH` with `{expected_digest, observed_digest}` and **no config content**. That code already exists with exactly that parameter pair and currently has zero producers; this phase gives it one. No `config.yaml` exists anywhere in the repository — only test fixtures — so this phase adds the pinning function and its fixtures, not a shipped config file. +- **Error catalogue: no new code.** Every code in the failure map already exists. If one were ever required it would be three coordinated edits in `src/contracts/errors.ts` — the `ProjectErrorCode` union, `PROJECT_PARAMETER_SCHEMAS` (typed `as const satisfies Record`, so a gap is a compile error), and `PROJECT_ERROR_DEFINITIONS` — plus two exhaustiveness assertions: `test/unit/errors.test.ts` asserts exactly 52 project codes and `test/contracts/gate-error-supplemental-exhaustive.test.ts` asserts exactly 56 total rows. +- **`SCHEMA_IDS` is `as const`, not `Object.freeze`** — immutability is a type-level guarantee only. The real enforcement is the registry bijection test plus the `satisfies` constraint on `SCHEMA_FILES`. + +## Path, Git, and Runtime Boundaries + +- The single `:` rejection neutralises Windows drive-relative escapes, alternate data streams (`file.txt:stream`), and UNC in one check. The live precedent is CVE-2026-31802 / GHSA-9ppj-qmqm-q256 (CVSS 8.2, `node-tar` ≤7.5.10, fixed 7.5.11, published 2026-03-09): node-tar validated `..` against a path still carrying the `C:` prefix, then stripped the drive letter afterward, yielding arbitrary file overwrite. The lesson this design encodes everywhere: **validate containment on the final normalised path, never on an intermediate form.** Reserved device names match with any extension (`CON.txt` is still `CON`), and Win32 silently strips trailing dots and spaces so `a.` and `a` alias the same file. +- **NFC is required, not applied.** On Linux/ext4 NFC and NFD are genuinely different files; APFS is normalisation-insensitive but preserving, so the same two names are one file on macOS. That mismatch is a real bypass class — see the setuptools `MANIFEST.in` exclusion bypass, GHSA-h35f-9h28-mq5c. Normalising naively would be worse than not normalising: on Linux the normalised string names a file that does not exist. Since `.archflow/` names are slugs we generate, requiring NFC costs nothing. Task slugs are constrained rather than case-folded, because naive `toLowerCase()` is locale-hazardous (`'İ'.toLowerCase()` has length 2). +- Every containment step is load-bearing. Step 1 is not optional: an absolute second argument makes `path.resolve` discard the root entirely — `resolve('/srv/root', '/etc/passwd')` is `/etc/passwd`. Steps 3–4 are the whole control; without them this is a string check, not a security boundary. Step 6 uses `path.relative` rather than `startsWith` because `startsWith(root)` accepts `/srv/root-evil/x` and `/srv/rootx`, while `startsWith(root + sep)` rejects the root itself. +- **Step 7's `?? 0` is defensive clarity, not a correctness fix.** Bitwise OR applies `ToInt32`, so `flags | undefined` evaluates to `flags`, not `NaN`; the flag would simply be dropped silently. The real point is platform-specific: `O_NOFOLLOW` does not exist on Windows, so on Windows step 7 is a **no-op** and the symlink defence there rests entirely on steps 3–6. Note also that `fsPromises.realpath.native` is `undefined` even though `fs.realpath.native` and `fs.realpathSync.native` exist. +- **Containment is a check-then-use control with an inherent TOCTOU window, and the design says so rather than implying atomicity.** Node 24 has no `openat`-style API: no `O_PATH`, no `O_RESOLVE_BENEATH`, no dir-relative `fs` variants, and `FileHandle` cannot serve as a directory base. There is no Node equivalent of Go's `os.Root`. `O_NOFOLLOW` is defence-in-depth, not a substitute. +- **No dependency, and the evaluation is recorded so the choice is auditable.** `is-path-inside` (64.2M weekly downloads) disqualifies itself in its own bundled type definitions — "You should not use this as a security mechanism" — and does not resolve symlinks; `path-is-inside`, `resolve-path`, and `contains-path` are likewise lexical-only. The one genuinely correct implementation is **`@openclaw/fs-safe@0.5.0`** (MIT, `O_NOFOLLOW`, post-open fd identity verification, kernel-atomic `openBeneath()` on Linux). Its **primary disqualifier is licensing, not size**: it carries an optional dependency on `jszip@3.10.1`, which declares `(MIT OR GPL-3.0-or-later)`. npm installs optional dependencies by default, and `scripts/check-dependency-policy.mjs` matches license strings **exactly**, so `npm run check:dependencies` would fail on the disjunction — and a disjunction is a human legal election, never an automatic pass. Secondary grounds: ~17 MB unpacked with prebuilt native binaries for seven platforms, 22 export subpaths far beyond the need, and pre-1.0 churn — 21 versions between 2026-05-06 and 2026-07-28, with `0.5.0` shipping on 2026-07-28 carrying a breaking migration that removed the Python worker earlier versions required. Roughly thirty lines of our own code is the right call. +- **Git runner discipline** follows the established `scripts/release-support.mjs` style, now in TypeScript: `execFile` with an argv array and no shell, explicit `cwd`, `encoding: "buffer"` where bytes matter, explicit `maxBuffer` and `timeoutMs`. Every call site names its own argv; there is no dynamic command construction, and `--literal-pathspecs` plus `:(top,literal)` prefixes are mandatory wherever a pathspec appears. +- **Worktree discovery.** `--show-toplevel` gives the current worktree root, which is where `.archflow/` lives. `--git-dir` is per-worktree; `--git-common-dir` is shared across linked worktrees. The trap: both return the **relative** path `.git` at the top of the main worktree but an **absolute** path from a linked worktree, so raw output is never concatenated. Rather than adopt `--path-format=absolute` and its ~2.31 floor, resolve the result against the worktree root. Detection matrix: `--is-inside-work-tree`, `--is-bare-repository`, `--is-inside-git-dir`. +- **Refusal conditions, each handled explicitly rather than assumed away.** Multiple root commits are normal in repositories formed with `--allow-unrelated-histories`, so the whole sorted set is hashed and the first line is never taken alone. Shallow clones return the grafted boundary commit, which is not the true root and differs by clone depth — `git rev-parse --is-shallow-repository` gates this. Unborn HEAD fails the root-commit query. Submodules are refused: `git rev-parse --show-superproject-working-tree` prints the parent worktree and is empty otherwise but exits 0 either way, so the test is for empty output, not exit code. +- **Orphan branches are a documented limitation, not a compensated one.** Checking out an orphan branch changes HEAD's root set. Computing over `--all` instead would only trade one instability for another. Identity is recorded at task initialization and compared thereafter, so a change surfaces as `REPOSITORY_MISMATCH` with expected and observed digests — which is the correct behaviour. +- **Porcelain parsing rules.** Use `git status --porcelain=v2 --branch -z`. `-z` matters: without it, unusual paths are backslash-quoted per `core.quotePath`. One wrinkle: in `-z` mode the rename/copy `2` lines put the original path in a separate NUL-terminated field, so field counts differ by entry type. Parse defensively — split on NUL, dispatch on the first token (`1`, `2`, `u`, `?`, `!`, `#`), and ignore unrecognised header lines, because v2 is documented as an extensible set of optional headers while v1 carries the backward-compatibility guarantee. Porcelain v2 has existed since Git 2.11 (2016) and adds no floor of its own. +- **The critical porcelain gotcha:** with no upstream configured, `# branch.upstream` and `# branch.ab` are silently absent. A missing `branch.ab` must never be read as "0 ahead, 0 behind"; "no upstream" is a distinct state and, for a task branch that has never been pushed, the normal one, so it is handled first. `git rev-list --left-right --count '@{upstream}...HEAD'` (three dots required; left is behind, right is ahead) *fails* without an upstream and is a secondary source only. +- **Conflicts and in-progress operations.** `git diff --name-only --diff-filter=U -z` is the cleanest conflicted-path primitive; porcelain `u` lines carry all three stage OIDs and modes when richer data is wanted. Unmerged XY codes are `DD`, `AU`, `UD`, `UA`, `DU`, `AA`, `UU`. In-progress markers live under the absolute git dir: `MERGE_HEAD`, `REBASE_HEAD`, `rebase-merge/`, `rebase-apply/`, `CHERRY_PICK_HEAD`, `REVERT_HEAD`. `rebase-merge/` and `rebase-apply/` are **directories**, so the existence check must accept directories. During a rebase `# branch.head` reads `(detached)`, so branch-name logic silently breaks mid-rebase — the rebase is detected first. +- **Honesty constraint, repeated from the architecture:** this detects divergent history and conflicts. It explicitly does **not** claim to detect independent-clone concurrency before divergence. Locking and revision CAS coordinate only processes sharing one filesystem; Git is transport and history, not a distributed lock. +- **Secret scanning is a contract only.** No dependency is added. The Phase 8 candidate and its evidence are recorded so the later decision is cheap: `@secretlint/core@13.0.4` plus `@secretlint/secretlint-rule-preset-recommend@13.0.4`, MIT, published 2026-07-22, pure ESM, `engines: node >=22`, scanning a fully virtual `filePath` with nothing touching disk. That install set is **8 packages / 1.5 MB — MIT ×6 and BSD-2-Clause ×2, zero copyleft**, measured identically by two independent reviewers. The `@secretlint/node` and CLI closures are larger, but their **disqualifier is licensing, not size**: they pull roughly 21 off-allowlist license strings — Artistic-2.0 ×5, WTFPL, Python-2.0, CC0-1.0, CC-BY-3.0, BlueOak-1.0.0, `(MIT OR CC0-1.0)`, plus 14 packages declaring no `license` field — every one of which hard-fails `scripts/check-dependency-policy.mjs`'s exact-string match. (Package *counts* for those larger closures were measured inconsistently and are deliberately not quoted.) Secretlint's known limitation is provider-pattern rules only, with no generic high-entropy rule. Ruled out: `trufflehog` is AGPL-3.0, a poor fit for a network-delivered server; `detect-secrets` needs Python or Docker; the npm `gitleaks` and `trufflehog` packages are unrelated abandoned squats. The gitleaks *scanner* and its `config/gitleaks.toml` are MIT and legally vendorable, but consuming them from Node means a TOML parser plus an RE2→JS regex translation layer plus reimplemented allowlist semantics, which would silently drift from upstream. +- **Not implemented in this phase**: any durable state or artifact schema, state mutation, the transaction kernel, locks, revision CAS, intent receipts, atomic writes, payload snapshot materialisation or restore, gate lifecycle, dispatch, sandbox, the secret-scanning engine, and any new runtime dependency. `package.json` `engines.node` is already `>=24.15.0`; no engine change is needed. + +## Work Breakdown + +1. **Canonical primitives**: Implement `src/contracts/canonical.ts` against the pinned signatures, including `parseCanonicalDocument`'s full byte-authority contract and the two shared error-digest helpers. Append the `.gitattributes` rule. Add `scripts/release-support.d.mts` and the three-primitive parity test, and confirm it passes `tsc --noEmit` as well as Vitest. Lands alone and first. +2. **ID and path primitives**: Add `PathSafeId` and `TaskSlug` to `evidence.ts` with `primitives.schema.json` `$defs`; add `x-archflow-nfc` to `validators.ts`; extend the lexical claim schema and `path-claim.schema.json` in lockstep; add `RepositoryPathClaim`, `RawGitPath`, `tryRepositoryPathClaim`, `toRepositoryPathClaim`, and the two class enums. Every schema yields a branded value. Change no consumer. +3. **Boundary retightening**: Regenerate the ID inventory mechanically, reconcile it against the prose list, report any difference, then apply the global per-ID retightening atomically across all Zod modules, all JSON Schemas, the branded public interfaces, `SNAPSHOT_LIMIT.offending_paths`, the `z.literal(… satisfies PathClass)` gate fix, and all nine test files. `test:mcp-runtime` and `test:contracts` must both pass before this chunk closes. +4. **Git runner, absence policy, and error context**: Implement `src/repository/git.ts` with `execFile`, argv arrays, no shell, explicit `cwd`/`maxBuffer`/`timeoutMs`, per-command `expectedAbsence`, the six-kind `GitInvocationError`, the three-method behaviour table, and `RepositoryOperationContext`. Preflight the ~2.25 floor and `--show-object-format`, failing closed on `sha256`. +5. **Discovery, root binding, and identity**: Implement `src/repository/identity.ts` — the detection matrix, relative-versus-absolute git-dir resolution, the `RootBoundGitRunner` mint, sorted multi-root identity digest, refusals for bare, inside-`.git/`, shallow, unborn-HEAD, and submodule cases, task identity, and the `REPOSITORY_MISMATCH` comparator. +6. **Path classes and the two resolvers**: Implement `src/repository/paths.ts` with the seven-step containment sequence, the complete class → template → identifier table, both resolvers restricted to their class subsets, `ResolvedTaskPath`, and `openResolved`. Make the existing `@ts-expect-error` brand assertion real. +7. **Attributes and index entries**: Implement `-z` `check-attr` triplet parsing with exact 6N cardinality and `-z` `ls-files -s` field parsing, both top-anchored and literal, both asserting returned paths equal requested claims, with `160000` and non-`100644` `.archflow/` modes rejected through the pinned codes. +8. **History, conflicts, and the barrel**: Implement `src/repository/history.ts` — defensive porcelain v2 `-z` parsing, the distinct no-upstream state carrying `upstreamOid`, validated `.archflow/` conflict claims versus raw other-conflict paths with an unrepresentable count, in-progress detection with rebase first, and `classifyMutationReadiness` constructing all three codes from the context. Create `src/repository/index.ts` once. +9. **Fingerprints, config pinning, and the secret-scan contract**: Implement `src/contracts/fingerprints.ts` with the closed-field request digest, asserted exclusions, set sorting and duplicate rejection before hashing, and whole-file `config.yaml` pinning. Implement `src/contracts/secret-scan.ts` and its schema with no engine and no secret value in any field. +10. **Integration verification**: Build the temporary-repository harness and run the five-repository matrix, the subdirectory-cwd reproduction, Unicode and pathspec-metacharacter filenames, the invalid-name conflict fixture, linked worktree, relocation, `check-attr`, and the forced-conflict proof. + +**Ten chunks, inside the 9–10 target.** The split from the previous fifteen-chunk single phase is what makes this fit: Phase 7 now carries every durable schema, and chunk 10 is a real integration chunk rather than verification borrowed from schema work. If it must shrink further, chunk 7 merges into chunk 6 — both are readers over the chunk-4 runner — for nine. Chunks 1 and 2 must stay isolated to be stable seams, and chunks 2 and 3 must **not** be re-merged: publishing primitives and retightening every consumer are separately reviewable, and merging them recreates a defect three successive reviews found. + +## Success Criteria + +- [ ] Every schema in `evidence.ts` and `path-claims.ts` yields a **branded** value, and `CommonToolInput`, the five tool inputs, `ResultIdentityPayload`, `WaiverDecisionBinding`, `GateDecisionEnvelopeBase`, `GateSupersessionRef`, and `SupplementalGateRef` all carry `TaskSlug`/`PathSafeId` fields. A compile-time test proves a plain `string` is not assignable to any of them. +- [ ] The ID inventory was regenerated mechanically before being applied, reconciled against the document's prose list, and any difference reported rather than absorbed. `task_id`, `intent_id`, and all five gate-ID names are retightened **globally**; `rule_id`, `result_id`, `receipt_id`, `invocation_id`, `connection_id`, `decision_event_id`, `helper_invocation_id`, `detector_id`, and `input_id` are unchanged **everywhere**. +- [ ] Every Zod retightening has its JSON Schema counterpart in the same chunk — `mcp-tools.schema.json`, `gate-decision.schema.json`, `result-expectation.schema.json`, `evidence-slots.schema.json`, `supplemental-review.schema.json`, and `project-error.schema.json` — and `assertZodAgreement` passes across the whole corpus with `test:mcp-runtime` and `test:contracts` green. +- [ ] `SNAPSHOT_LIMIT.offending_paths` is repository-relative in Zod, JSON Schema, and fixtures; no frame cast exists anywhere. +- [ ] `gate-contract.schema.json:259` remains `"const": "task-branch-constitution"` and `gates.ts` still parses a single literal sourced from the enum via `satisfies PathClass`. +- [ ] `TaskPathClaim`, `RepositoryPathClaim`, and `RawGitPath` are three distinct brands. `tryRepositoryPathClaim` is the only promotion from Git output to a claim, and a `RawGitPath` is not assignable to any claim field, including the secret-scan contract's. +- [ ] The lexical schema rejects `:`, `*`, `?`, `[`, `]`, `<`, `>`, `|`, reserved device names, trailing dot/space segments, and non-NFC segments; `x-archflow-nfc` makes Ajv and Zod agree on the NFD cases. +- [ ] Every reader below discovery accepts only a `RootBoundGitRunner`; holding an unrooted runner after discovery is a type error. All pathspecs are `:(top,literal)` under `--literal-pathspecs`, and every returned path is asserted byte-equal to the requested claim. +- [ ] Running any reader from a repository subdirectory produces the same answer as from the root — the reproduced `ls-files` empty result and `check-attr text: auto` wrong answer are both impossible to express. +- [ ] `git ls-files -s` and `git check-attr` are both `-z`; a filename containing spaces and non-ASCII text round-trips unquoted; `check-attr -z` output is validated at exactly 6N NUL fields for N paths and two attributes, and any other count fails rather than being best-effort parsed. +- [ ] Absence is command-specific: no code path treats a bare exit 128 as absence, and a dubious-ownership or corrupt-repository 128 produces `IO_ERROR`, not an empty result. The three-method behaviour table holds for every outcome. +- [ ] Every failure branch in the failure map constructs its exact code with its exact parameters from `RepositoryOperationContext` plus the two shared digest helpers; no reader invents a parameter and no promised error is unconstructible from its own signature. +- [ ] `resolveTaskPath` and `resolveRepositoryPath` are separate, each restricted to its class subset, and every one of the seventeen classes has a template and required identifiers that the resolver can actually produce. +- [ ] `conflictedOtherPaths` is `RawGitPath[]`; a repository containing a conflicted file whose name has a colon, trailing dot, non-NFC text, or newline is reported with an accurate `unrepresentableOtherConflicts` count and never throws while checking unrelated conflicts. +- [ ] `computeInputFingerprint` sorts all three collections before hashing and rejects duplicate keys; shuffling any collection yields an identical digest, and a repeated `path` or `input_id` throws. +- [ ] `parseCanonicalDocument` rejects malformed UTF-8, duplicate keys, permuted key order, wrong indent, and missing or extra trailing newline; `digest` covers the original bytes, proven byte-identical to the re-rendered canonical form. +- [ ] A single tracked file yields identical canonical blob OID and tree mode across the three `core.autocrlf` values, `core.fileMode` on and off, and symlink-capable and symlink-incapable checkouts; the in-process OID matches `git hash-object` in every case exercised. +- [ ] `git check-attr text merge` reports exactly `text: unset` / `merge: binary`; a removed rule and an overriding `$GIT_DIR/info/attributes` rule each produce `TASK_INVALID{issue_code:"archflow-attributes-missing"}` carrying the verbatim remediation. +- [ ] A forced conflict on a `.archflow/` JSON file leaves zero conflict markers and a parseable file while porcelain v2 and `--diff-filter=U -z` both report it unmerged. +- [ ] Multiple root commits, a shallow clone, an unborn HEAD, a submodule, a bare repository, and a cwd inside `.git/` each produce the exact intended outcome; a branch with no upstream is the distinct `no-upstream` state and never "0 ahead, 0 behind". +- [ ] `src/contracts/**` contains no import from `src/repository/**`, `src/contracts/index.ts` exports no repository module, `src/repository/index.ts` exists exactly once, no new error code is added, the 52/56 assertions hold, and `package.json` is unchanged in both `dependencies` and `scripts`. +- [ ] No durable state or artifact schema, no state mutation, no payload restore, no secret-scanning engine, and no runtime dependency is introduced; the full aggregate passes on Node `24.15.0` and `24.18.0`. + +## Verification Steps + +Steps 1–2 and 7–13 are platform-independent. **Steps 3–6 run on Linux only**, which is all CI provides — `.github/workflows/ci.yml` is `ubuntu-latest` only. `core.autocrlf`, `core.fileMode`, and `core.symlinks=false` are faithfully simulable there, but the Windows-specific rules this design spends the most prose on — trailing-dot and trailing-space stripping, reserved device names as real filesystem aliases, and `O_NOFOLLOW`'s absence — are **verified lexically only**, never against a real Win32 filesystem. That limitation is recorded rather than papered over, and "cross-platform" is not claimed for them. + +1. Run the canonical parity suite through both Vitest **and** `tsc --noEmit`: hash a corpus containing nested objects with keys requiring ordinal (not locale) sort, arrays whose order is semantic, empty objects and arrays, deep nesting, non-ASCII strings, and boundary numbers through both `canonicalJsonBytes` implementations, asserting byte equality. Do the same for `assertPortablePath`. Assert the containment predicate matches `isInside` except for `rel === ""`. Then exercise `parseCanonicalDocument` against malformed UTF-8, duplicate keys, permuted key order, four-space indent, a missing trailing newline, and an extra trailing newline, asserting each is rejected and that a valid document's `digest` equals `sha256Bytes` of the input bytes. +2. Verify the blob OID against `git hash-object` for empty content, content without a trailing newline, content with CRLF, binary content containing NUL, and content over 1 MiB. Confirm `printf 'hello\n'` yields `ce013625030ba8dba906f756967f9e9ca394464a`. +3. Build **five** temporary repositories — not a 24-cell cross-product, because this design's own central claim is that `-text` collapses the EOL configurations to one answer, so most cells are provably identical by that very argument and buy no confidence. The five that each test a distinct claim: one repository each at `core.autocrlf` `false`, `true`, and `input` over the same CRLF-containing file; one at `core.fileMode=false` with the executable bit toggled on disk; one at `core.symlinks=false` containing a symlink. In each, assert the in-process OID equals the index OID and that the mode is index-sourced. +4. **Run every reader from a subdirectory as well as the root**, asserting identical results. Construct the reproduced failure explicitly: confirm that an unbound runner in `repo/sub` would return nothing from `ls-files` and `text: auto` from `check-attr`, and that the `RootBoundGitRunner` type makes that call unwritable. +5. Create `.archflow/ü space.json` and a file whose name contains `*`, `?`, and `[`. Assert `-z` output round-trips both unquoted, that the metacharacter name is rejected by the claim schema before any Git call, and that `check-attr -z` yields exactly 6N fields for N paths. +6. Assert `git check-attr text merge` reports exactly `text: unset` / `merge: binary`. Then mutate **two** ways — delete the `.gitattributes` line, and add a conflicting rule in `$GIT_DIR/info/attributes` — and confirm each produces `TASK_INVALID{issue_code:"archflow-attributes-missing"}` with the verbatim remediation. A global or system attributes override is deliberately **not** tested: verified precedence is `info/attributes` > in-tree > `core.attributesFile` > system, so it could never produce the required error. +7. Force a conflict on a `.archflow/` JSON file, on a control file without the attribute, and on **a file outside `.archflow/` whose name is invalid under ArchFlow claims** (a colon, a trailing dot, and a non-NFC name). Assert the `.archflow/` file has zero markers and parses, the control file has markers, both appear unmerged in porcelain v2 and `--diff-filter=U -z`, and the invalid-named conflict appears in `conflictedOtherPaths` as a `RawGitPath` with `unrepresentableOtherConflicts` incremented and no throw. +8. Exercise a linked worktree created with `git worktree add` — asserting `--git-dir` and `--git-common-dir` return relative `.git` from the main worktree and absolute paths from the linked one — plus a relocated repository directory and paths containing spaces and Unicode. +9. Construct every identity failure mode: two roots merged with `--allow-unrelated-histories` (assert sorted multi-root hashing and that taking the first line alone would differ), a `--depth=1` clone, a fresh `git init` with unborn HEAD, a submodule checkout (assert refusal on empty-versus-non-empty `--show-superproject-working-tree` output, not exit code), a bare repository, and a cwd inside `.git/`. Separately, stub the runner to raise `ENOENT`, `EACCES`, a timeout, a `maxBuffer` overflow, an undeclared nonzero exit, a **128 with a dubious-ownership diagnostic**, and a 128 matching a declared `expectedAbsence`, asserting the exact code and parameters from the failure map in each case. +10. Exercise the path matrix through both resolvers: `../escape`, `a/../../etc/passwd`, `/etc/passwd`, `C:foo`, `D:..\x`, `\\?\C:\x`, `\\server\share\y`, `file.txt:stream`, `CON`, `CON.txt`, `a.`, `a ` (trailing space), an NFD segment, `a*b`, `a?b`, `a[b]`, `a=24.15.0` floor, and Phase 5's implementation log recorded the same trap. Note that `npm run check` and the CI step list are close but **not** a strict step-for-step mirror: CI adds `release:stage -- --output`, `release:check -- --compare`, and `test ! -e .tmp`. + +**Follow-up, outside this phase:** `docs/dependency-upgrades.md` still documents the MCP pin as `2.0.0-beta.5` while the project ships stable `2.0.0` (published 2026-07-27). Recorded here, not fixed here. + +--- +*Designed: 2026-07-28* diff --git a/.archflow/tasks/mcp-integration/phases/phase-7-durable-state-and-artifact-schemas.md b/.archflow/tasks/mcp-integration/phases/phase-7-durable-state-and-artifact-schemas.md new file mode 100644 index 00000000..a0040f09 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-7-durable-state-and-artifact-schemas.md @@ -0,0 +1,555 @@ +# Phase 7: Durable State and Artifact Schemas + +**Status**: DRAFT — not an approved design +**Task**: mcp-integration +**Goal**: Define every persisted shape as a versioned normative schema with one cross-document semantic authority. +**Depends on**: Phase 6 +**Requirements completed**: none +**Requirements advanced**: REQ-04, REQ-11, REQ-13, REQ-14, REQ-21, REQ-26, REQ-39, REQ-50 + +> **Read this before treating anything below as settled.** This document preserves the reviewed durable-schema material that was carved out of the original combined Phase 6 design, so that work is not lost. It has **not** passed a design gate, has **not** been counter-reviewed, and was written *before* Phase 6 was implemented. Every Phase 6 interface it references is therefore **provisional**: the names, shapes, and brands pinned here are what the combined design intended, not what Phase 6 actually exported. Before any of this is implemented, run `archflow-phase-design mcp-integration 7` properly, against Phase 6's implementation log and its real exported signatures, and reconcile every reference in the "Consumed from Phase 6" section. Treat a difference as a design defect to resolve at that gate, not something to patch around during implementation. + +**This phase completes no requirement.** It wires no handler, performs no mutation, and reads nothing at runtime; it defines file formats. What each requirement receives is an exact slice. REQ-04 gets the `task-initialization` and `legacy-import-initialization` shapes that *carry* the pinned identity, base commit, workflow, constitution, and config digests — but nothing records or enforces them until the transaction kernel lands. REQ-11 gets the evidence-chain and document shapes that hold review provenance; the review schemas, canonical rendering, and finding IDs are Phase 2's and the attestation is Phase 11's. REQ-13 gets the digest-bound fields that later freshness comparisons read, not the fixed-point loop. REQ-14 and REQ-21 get the `state.json` schema — the *format* of the truth `archflow-status` will one day read, with no reader and no writer here. REQ-26 gets the `path_class` constraints that bound what an implementation output may claim, enforced only when a handler calls them. REQ-39 gets the manual-checkpoint chain format. REQ-50 gets the legacy-import manifest. Completion for all eight belongs to the phases that integrate and verify the behaviour. + +## Context + +Phase 6 established the first filesystem and Git code in `src/`: canonical JSON, in-process Git blob OIDs, tree modes, three path brands, path classes and containment, repository and task identity, whole-file `config.yaml` pinning, the request digest and declared-input fingerprint, divergence and conflict detection, and the secret-scan *result* contract. Phase 5 set the precedent this phase follows for purely internal shapes: `release-manifest` and `release-legal-review` have JSON Schema authority, one consolidated semantic validator, and no Zod mirror. + +This phase authors nine durable shapes and one cross-document validator. It implements **no** state mutation, transaction kernel, lock, CAS, intent receipt, atomic write, snapshot materialisation, payload restore, gate lifecycle, dispatch, or secret-scanning engine, and adds **no runtime dependency**. + +## Consumed from Phase 6 — provisional + +Everything in this list is what the combined design pinned. **Verify each against Phase 6's implementation log before use**; a mismatch is a gate-time correction, not an implementation-time improvisation. + +| Symbol | Module | Used for | +|---|---|---| +| `Sha256Digest`, `SafeId`, `SafeInteger`, `SafeCode`, `SafeVersion` | `src/contracts/evidence.ts` | every digest, identifier, and count | +| `PathSafeId` | `src/contracts/evidence.ts` | `gate_id`, `intent_id`, `attempt_id`, `maintenance_id` — every ID that becomes a filename component | +| `TaskSlug` | `src/contracts/evidence.ts` | `task_id` | +| `RepositoryPathClaim`, `TaskPathClaim` | `src/contracts/path-claims.ts` | every persisted path, in its declared frame | +| `PathClass`, `PATH_CLASSES`, `TASK_PATH_CLASSES`, `REPOSITORY_PATH_CLASSES` | `src/contracts/path-claims.ts` | output classification and its constraints | +| `GitOid`, `GitTreeMode`, `ArchflowTreeMode` | `src/contracts/canonical.ts` | tracked-output identity | +| `CanonicalDocument`, `canonicalJsonBytes`, `canonicalJsonDigest`, `parseCanonicalDocument`, `gitBlobOid`, `sha256Bytes` | `src/contracts/canonical.ts` | document bytes, digests, and byte authority | +| `SecretScanResult` | `src/contracts/secret-scan.ts` | embedded in `implementation-output` | +| `PhaseInstanceId`, `PositiveSafePhaseNumber` | `src/contracts/phase-instance.ts` | phase instances (Phase 1) | +| `ReviewEvidenceSlot`, `Assurance` | `src/contracts/trust.ts` | evidence-chain provenance (Phase 2) | +| `ProjectResult`, `createProjectError` | `src/contracts/errors.ts` | the validator's return channel (Phase 2) | + +Phase 6's failure convention applies unchanged: **parsers and assertion helpers throw; orchestrating readers return `ProjectResult`; pure derivations return their value.** `validateDurableSemantics` is an orchestrating reader and returns `ProjectResult`. Every `parse*` in this phase throws. + +## What We're Building + +Nine versioned durable shapes, each with a JSON Schema authority in `src/contracts/schemas/v1/`, plus Zod mirrors where a shape crosses the MCP boundary, plus one consolidated semantic validator for everything the schemas structurally cannot express. + +Three structural devices carry the design, and each exists because chunks are delegated to fresh-context agents that never read each other's code: + +- **Every root document is pinned, not just the shared `$defs`.** The previous revision pinned `OutputEntry` and `PredecessorLink` and left `TaskStateV1` and all six artifact roots as prose noun-lists. That was the single largest defect: a fresh-context agent authoring `implementation-output` and another authoring `validateDurableSemantics` would have invented different field names for the same concept, and nothing would have caught it. Every root shape below has declared properties, required fields, discriminants, and cross-document keys. +- **`validateDurableSemantics` is typed against those roots**, not against `PlainJsonObject`. Its correlations are then compile-time checkable, so a renamed field breaks the build rather than silently disabling a check. +- **One integration chunk owns every shared file.** `SCHEMA_IDS`, `SCHEMA_FILES`, and `src/contracts/index.ts` are not append-only-by-convention; they are written once, by one agent, from a pinned table. + +## Interfaces and Contracts + +### Shared `$defs` — chunk 1, lands first + +Chunks 2–7 embed these by name and must not rename them. Chunk 1 owns `src/contracts/durable-primitives.ts` and `durable-primitives.schema.json`, and imports `DeclaredInputRef` and `GitIdentityRef` from Phase 6's `fingerprints.ts`. + +```ts +import type { Assurance, ReviewEvidenceSlot } from "./trust.js"; + +export const OUTPUT_OPERATIONS = ["add", "modify", "delete", "rename"] as const; +export type OutputOperation = (typeof OUTPUT_OPERATIONS)[number]; +export const OUTPUT_FILE_TYPES = ["regular", "symlink"] as const; +export type OutputFileType = (typeof OUTPUT_FILE_TYPES)[number]; +export const OUTPUT_STORAGE = ["git-object", "raw-payload"] as const; +export type OutputStorage = (typeof OUTPUT_STORAGE)[number]; + +export interface BlobIdentity { + readonly oid: GitOid; + readonly mode: GitTreeMode; // "160000" rejected + readonly size_bytes: SafeInteger; +} + +export interface OutputEntry { + readonly path: RepositoryPathClaim; + readonly path_class: PathClass; + readonly operation: OutputOperation; + readonly previous_path?: RepositoryPathClaim; + readonly file_type: OutputFileType; + readonly storage: OutputStorage; + readonly before?: BlobIdentity; + readonly after?: BlobIdentity; + readonly payload_bytes?: SafeInteger; + readonly payload_digest?: Sha256Digest; +} + +/** Composition, not modification: the slot is an unmodified evidence-slots member. */ +export type EvidenceChainEntry = + | Readonly<{ kind: "review"; slot: ReviewEvidenceSlot; authority_link_digest: Sha256Digest }> + | Readonly<{ + kind: "adjudication" | "triage"; + evidence_digest: Sha256Digest; + assurance: Assurance; + authority_link_digest: Sha256Digest; + }>; + +export interface PredecessorLink { + readonly revision: SafeInteger; // >= 1 + readonly predecessor_checkpoint_digest?: Sha256Digest; // absent iff revision === 1 + readonly predecessor_revision?: SafeInteger; // absent iff revision === 1; else < revision +} + +export interface SnapshotAccountingEntry { + readonly path: RepositoryPathClaim; + readonly storage: OutputStorage; + readonly stored_bytes: SafeInteger; // exactly 0 iff storage === "git-object" +} +export interface SnapshotAccountingV1 { + readonly schema_version: "1"; + readonly result_bytes: SafeInteger; // sum of counted_entries[].stored_bytes + readonly task_bytes: SafeInteger; // >= result_bytes + readonly result_byte_cap: 26214400; // 25 MiB, const + readonly task_byte_cap: 262144000; // 250 MiB, const + readonly counted_entries: readonly SnapshotAccountingEntry[]; + readonly measured_at_revision: SafeInteger; +} +export const snapshotAccountingV1Schema: z.ZodType; +export function parseSnapshotAccounting(value: unknown): SnapshotAccountingV1; +``` + +#### `EvidenceChainEntry` composes the slot — the earlier `$ref`-the-fields instruction is withdrawn + +An earlier revision said `EvidenceChainEntry` should `$ref` `evidence-slots.schema.json` for its role/assurance/`gate_id` correlations while carrying `role`, `assurance`, `evidence_digest`, `authority_link_digest`, and an optional `gate_id` as flat siblings. **Verified against live code, that is impossible.** `evidence-slots.schema.json`'s `self`, `counter`, and `gateCounter` each `require` `producer_family`, `reviewer_family`, and `independence`, are `additionalProperties: false`, and contain no `authority_link_digest`. A flat entry omits three required properties and adds a forbidden one, so no Ajv/Zod agreement is achievable under that reuse. The flat shape also silently dropped correlations those `$defs` already enforce: `self-review ⇒ agent-declared`, `counter-review | gate-counter-review ⇒ server-attested | degraded`, and the family-difference rules expressed as `oneOf` branches. + +The fix is **composition**: a review chain entry carries the slot object *unmodified* under a `slot` key and adds `authority_link_digest` as a sibling of `slot`, not of the slot's own properties. `additionalProperties: false` is respected because nothing is added inside the slot; every correlation survives untouched; and the two non-review roles get their own branch of a `kind`-discriminated union rather than being forced into a vocabulary that does not describe them. + +**Ownership is explicit**: `evidence-slots.schema.json` (Phase 2) remains the sole owner of the three slot `$defs` and is **not edited by this phase**. `durable-primitives.schema.json` (chunk 1) owns only the wrapper, whose review branch is `{"kind": {"const": "review"}, "slot": {"oneOf": [{"$ref": "urn:archflow:schema:v1:evidence-slots#/$defs/self"}, {"$ref": "…#/$defs/counter"}, {"$ref": "…#/$defs/gateCounter"}]}, "authority_link_digest": {"$ref": "…primitives#/$defs/sha256Digest"}}`. The Zod mirror reuses `trust.ts`'s exported `ReviewEvidenceSlot` union directly, so the two authorities cannot drift. `"triage"` is included as a chain role deliberately: a checkpoint's evidence chain must reference the triage record that dispositioned findings, and triage has its own `triage.schema.json`; it is a chain member, not a review role, which is why it lives in the non-review branch rather than being appended to `REVIEW_ROLES`. + +#### `OutputEntry`'s legal combinations + +Every cell is normative; anything not in the table is rejected. + +| `operation` | `before` | `after` | `storage` | `payload_bytes` / `payload_digest` | `previous_path` | +|---|---|---|---|---|---| +| `add` | absent | required | either | present iff `raw-payload` | absent | +| `modify` | required | required | either | present iff `raw-payload` | absent | +| `delete` | required | absent | **`git-object` forced** | absent | absent | +| `rename` | required | required | either | present iff `raw-payload` | required | + +`delete` forces `git-object` because there is no post-state content to store; a `raw-payload` delete would demand bytes for a file that no longer exists. One invariant closes the redundancy between `file_type` and the tree mode: **`file_type === "symlink"` if and only if the surviving `BlobIdentity`'s mode is `120000`** — `after.mode` for `add`/`modify`/`rename`, `before.mode` for `delete`. + +#### The table is structurally total but not integrity-total, and the gap is attributed + +Nothing above requires `payload_bytes` to equal the length of the bytes actually retained, `payload_digest` to equal SHA-256 of those bytes, or `after.oid` to equal `gitBlobOid(bytes)`. The snapshot-accounting invariants only equate `stored_bytes` with the *asserted* `payload_bytes`, so a manifest can be fully internally consistent and still describe bytes that do not exist anywhere. This is a real gap and it is **deliberate, bounded, and attributed** rather than left unowned: + +> **In Phase 7 these three fields are assertions. In Phase 9 they become verified facts.** Phase 9 (Snapshots, Implementation Manifests, and Restore) is the layer that retains the bytes, and it is the layer that must verify, at materialisation time, that the retained payload's length equals `payload_bytes`, that `sha256Bytes(payload)` equals `payload_digest`, and that `gitBlobOid(payload)` equals `after.oid` for a tracked output. Phase 7 cannot check any of this, because it never sees a byte. + +Phase 7's own contribution to closing the gap is to make the assertions *checkable later* — every field needed for the Phase 9 comparison is present, typed, and required — and to say plainly that a Phase 7 validation pass is not evidence that the bytes exist. + +#### `path_class` is constrained by path and operation + +An unconstrained `path_class` lets an implementation output claim `task-state` or a shared class and thereby assert authority over a file the server owns. The constraint has three parts, all enforced in `validateDurableSemantics`: + +| Rule | Detail | +|---|---| +| Frame agreement | `path_class ∈ REPOSITORY_PATH_CLASSES` iff `path` is not under `.archflow/`; a `.archflow/`-rooted path must carry a task class. | +| Claimable set | An `implementation-output` entry may claim only `repository-source`, `document`, `review`, `result-payload`, `manual-checkpoint`, `import`, or `task-branch-constitution`. | +| Server-owned set | `task-config`, `task-state`, `gate-interface`, `intent`, `attempt`, `decision`, `result-manifest`, `maintenance-record`, `shared-workflow`, and `shared-constitution` are **never** claimable by an implementation output; a manifest asserting one is rejected outright, not merely warned. | + +`task-branch-constitution` is claimable only when the manifest also carries the constitution-edit gate reference, because that is the one path on which a task-branch edit is a legitimate declared output rather than a policy violation. + +**The rename cross-class rule**: `previous_path` must classify to the **same** `path_class` as `path`. A cross-class rename — moving a `repository-source` file into `document`, or a `review` into `result-payload` — is rejected. Such a move is representable as a `delete` plus an `add`, which forces the manifest to state both classes explicitly instead of laundering an authority change through a rename. + +#### `SnapshotAccountingV1`'s invariants + +Five, all checked in `validateDurableSemantics` rather than in the schema: `result_bytes` equals the sum of `counted_entries[].stored_bytes`; `result_bytes <= result_byte_cap`; `task_bytes >= result_bytes`; `task_bytes <= task_byte_cap`; and the **cross-shape** invariant — `counted_entries` is in one-to-one correspondence with the owning `implementation-output`'s `outputs` by `path`, with matching `storage`, `stored_bytes === payload_bytes` for `raw-payload` entries, and `stored_bytes === 0` for `git-object` entries. The accounting block is never independent of the manifest it accompanies. `26214400 = 25 × 1048576` and `262144000 = 250 × 1048576`. + +### Root shapes — every field pinned + +These are the seams that a fresh-context agent cannot infer. Each is an exact interface; the JSON Schema is its mirror, and where a Zod mirror is required the three must agree. + +#### `TaskStateV1` — chunk 2, server-internal, no Zod mirror + +```ts +export const STEP_STATUSES = ["running", "succeeded", "failed"] as const; +export type StepStatus = (typeof STEP_STATUSES)[number]; + +export interface AuthoritativeResultRef { + readonly phase_instance: PhaseInstanceId; + readonly step: PipelineStep; // vocabulary.ts PIPELINE_STEPS + readonly result_digest: Sha256Digest; + readonly result_id: SafeId; + readonly input_fingerprint: Sha256Digest; + readonly manifest_path: RepositoryPathClaim; +} +export interface ApprovalRef { + readonly gate_id: PathSafeId; + readonly gate_kind: GateKind; // gates.ts GATE_KINDS + readonly subject_digest: Sha256Digest; + readonly decision_digest: Sha256Digest; + readonly resolved_at_revision: SafeInteger; +} +export interface OpenGateRef { + readonly gate_id: PathSafeId; + readonly gate_kind: GateKind; + readonly subject_digest: Sha256Digest; + readonly context_digest: Sha256Digest; + readonly opened_at_revision: SafeInteger; +} +export interface WaiverRef { + readonly gate_id: PathSafeId; + readonly rule_id: SafeId; + readonly rule_version: SafeInteger; + readonly subject_digest: Sha256Digest; + readonly granted: boolean; + readonly expires: "task-complete"; + readonly granted_at_revision: SafeInteger; +} +export interface PreparedIntentRef { + readonly intent_id: PathSafeId; + readonly request_digest: Sha256Digest; + readonly prior_revision: SafeInteger; +} + +export interface TaskStateV1 { + readonly schema_version: "1"; + readonly task_id: TaskSlug; + readonly repository_identity_digest: Sha256Digest; + readonly revision: SafeInteger; // strictly monotonic, >= 1 + readonly phase_instance: PhaseInstanceId; + readonly step: PipelineStep; + readonly status: StepStatus; + readonly attempt: SafeInteger; // >= 1 + readonly initialization_digest: Sha256Digest; // the adopted task- or legacy-import-initialization + readonly config_digest: Sha256Digest; + readonly workflow_digest: Sha256Digest; + readonly constitution_digest: Sha256Digest; + readonly policy_base_commit: GitOid; + readonly authoritative_results: readonly AuthoritativeResultRef[]; + readonly approvals: readonly ApprovalRef[]; + readonly open_gate?: OpenGateRef; // at most one; absent when no gate is pending + readonly waivers: readonly WaiverRef[]; + readonly prepared_intent?: PreparedIntentRef; + readonly terminal?: "complete" | "abandoned"; +} +``` + +**Cross-document keys** (what `validateDurableSemantics` correlates on): `initialization_digest` → the initialization artifact's canonical digest; `authoritative_results[*].result_digest` → a result manifest; `approvals[*].gate_id` and `open_gate.gate_id` → decision records; `waivers[*].gate_id` → an approval whose `gate_kind` is a waiver-bearing kind. **Discriminant**: none — `state.json` is not a union. **Sorted-set fields**: `authoritative_results` by `(phase_instance, step)`, `approvals` and `waivers` by `gate_id`, all ordinal, all duplicate-rejecting. + +#### `MaintenanceRecordV1` — chunk 2, server-internal, no Zod mirror + +```ts +export interface MaintenanceDeletion { + readonly digest: Sha256Digest; + readonly path: RepositoryPathClaim; + readonly byte_count: SafeInteger; + readonly category: "unreferenced-attempt" | "superseded-payload"; +} +export interface MaintenanceRecordV1 { + readonly schema_version: "1"; + readonly maintenance_id: PathSafeId; + readonly task_id: TaskSlug; + readonly performed_at_revision: SafeInteger; + readonly human_reason: string; // 1..4096 bytes, bounded like other prose fields + readonly reachability_proof_digest: Sha256Digest; + readonly deletions: readonly MaintenanceDeletion[]; // sorted by digest, non-empty, unique + readonly total_bytes_deleted: SafeInteger; // equals the sum of deletions[].byte_count +} +``` + +#### `TaskInitializationV1` — chunk 3, Zod mirror + +```ts +export interface TaskInitializationV1 { + readonly schema_version: "1"; + readonly artifact_kind: "task-initialization"; // discriminant of the archflow_state union + readonly task_id: TaskSlug; + readonly repository_identity_digest: Sha256Digest; + readonly code_baseline_commit: GitOid; + readonly policy_base_commit: GitOid; // explicitly approved, human-committed + readonly constitution_digest: Sha256Digest; + readonly workflow_digest: Sha256Digest; + readonly config_digest: Sha256Digest; // exact whole-file config.yaml bytes + readonly canonical_paths: CanonicalTaskPaths; +} +export interface CanonicalTaskPaths { + readonly task_root: RepositoryPathClaim; // .archflow/tasks/ + readonly config: RepositoryPathClaim; + readonly state: RepositoryPathClaim; + readonly workflow: RepositoryPathClaim; // .archflow/workflow.yaml + readonly constitution_root: RepositoryPathClaim; // .archflow/constitution +} +``` + +#### `LegacyImportInitializationV1` — chunk 3, Zod mirror + +```ts +export interface LegacyImportInitializationV1 { + readonly schema_version: "1"; + readonly artifact_kind: "legacy-import-initialization"; + readonly task_id: TaskSlug; // the destination task + readonly repository_identity_digest: Sha256Digest; + readonly source_identity_digest: Sha256Digest; // the selected legacy source, never mutated + readonly import_digest: Sha256Digest; // immutable staged import + readonly import_baseline_commit: GitOid; + readonly code_baseline_commit: GitOid; + readonly policy_base_commit: GitOid; + readonly constitution_digest: Sha256Digest; + readonly workflow_digest: Sha256Digest; + readonly config_digest: Sha256Digest; // the DESTINATION's config bytes + readonly canonical_paths: CanonicalTaskPaths; + readonly mapping: readonly LegacyMappingEntry[]; // sorted by destination_path, unique + readonly staged_payload_refs: readonly StagedPayloadRef[]; // sorted by legacy_path, unique +} +export interface LegacyMappingEntry { + readonly legacy_path: RepositoryPathClaim; + readonly destination_path: RepositoryPathClaim; + readonly phase_instance: PhaseInstanceId; + readonly disposition: "draft" | "historical"; // never "approved" +} +export interface StagedPayloadRef { + readonly legacy_path: RepositoryPathClaim; + readonly digest: Sha256Digest; + readonly byte_count: SafeInteger; +} +``` + +#### `DocumentArtifactV1` — chunk 4, Zod mirror + +```ts +export interface DocumentArtifactV1 { + readonly schema_version: "1"; + readonly artifact_kind: "document"; + readonly task_id: TaskSlug; + readonly phase_instance: PhaseInstanceId; + readonly document_path: TaskPathClaim; // task-relative, class `document` + readonly path_class: "document"; + readonly byte_count: SafeInteger; + readonly content_digest: Sha256Digest; + readonly declared_inputs: readonly DeclaredInputRef[]; // set: sorted by input_id, unique + readonly input_fingerprint: Sha256Digest; // recomputed; the caller's is an assertion + readonly snapshot_digest: Sha256Digest; // the retained result this projects + readonly projection_target: RepositoryPathClaim; +} +``` + +#### `ImplementationOutputV1` — chunk 5, Zod mirror, the largest shape + +```ts +export interface ImplementationOutputV1 { + readonly schema_version: "1"; + readonly artifact_kind: "implementation-output"; + readonly task_id: TaskSlug; + readonly phase_instance: PhaseInstanceId; // always phase-impl- + readonly base_commit: GitOid; // immutable; the tree the diff is against + readonly index_identity_digest: Sha256Digest; + readonly worktree_identity_digest: Sha256Digest; + readonly outputs: readonly OutputEntry[]; // set: sorted by path, unique, non-empty + readonly parent_documents: readonly ParentDocumentRef[]; // set: sorted by document_path, unique + readonly diff_digest: Sha256Digest; // the exact review/commit-authorization subject + readonly snapshot_digest: Sha256Digest; + readonly restore_targets: readonly RepositoryPathClaim[]; // subset of outputs[].path, sorted + readonly accounting: SnapshotAccountingV1; + readonly secret_scan: SecretScanResult; + readonly undeclared_changes: UndeclaredChangeReport; + readonly declared_inputs: readonly DeclaredInputRef[]; + readonly input_fingerprint: Sha256Digest; + readonly constitution_edit_gate_id?: PathSafeId; // required iff any output claims task-branch-constitution +} +export interface ParentDocumentRef { + readonly document_path: TaskPathClaim; + readonly content_digest: Sha256Digest; + readonly role: "prd" | "design" | "phase-design" | "impl-notes"; +} +export interface UndeclaredChangeReport { + readonly scanned: boolean; + readonly undeclared_paths: readonly RawGitPath[]; // raw: a repo may hold unrepresentable names + readonly unrepresentable_count: SafeInteger; +} +``` + +`undeclared_paths` is `RawGitPath[]`, not `RepositoryPathClaim[]`, for the reason Phase 6 established: a valid repository may contain a dirty file whose name has a colon, trailing dot, non-NFC text, or newline, and reporting undeclared changes must not throw when it meets one. + +#### `ManualCheckpointV1` — chunk 6, Zod mirror + +```ts +export interface ManualCheckpointV1 { + readonly schema_version: "1"; + readonly artifact_kind: "manual-checkpoint"; + readonly task_id: TaskSlug; + readonly link: PredecessorLink; + readonly checkpoint_digest: Sha256Digest; // self-digest over canonical bytes minus this field + readonly phase_instance: PhaseInstanceId; + readonly step: PipelineStep; + readonly status: StepStatus; + readonly input_fingerprint: Sha256Digest; + readonly authoritative_results: readonly AuthoritativeResultRef[]; + readonly projection_digests: readonly ProjectionDigestRef[]; // set: sorted by path, unique + readonly evidence_chain: readonly EvidenceChainEntry[]; // sequence: production order, not sorted + readonly approvals: readonly ApprovalRef[]; + readonly open_gate?: OpenGateRef; + readonly waivers: readonly WaiverRef[]; + readonly assurance: "degraded"; // always; manual mode is never attested + readonly initialization_digest?: Sha256Digest; // required iff link.revision === 1 +} +export interface ProjectionDigestRef { + readonly path: RepositoryPathClaim; + readonly content_digest: Sha256Digest; +} +``` + +`evidence_chain` is the one **sequence** in this phase, not a set: the order in which evidence was produced is semantic, since triage follows the reviews it dispositions. Every other collection is a set with a declared ordinal sort key and duplicate rejection, for the determinism reason Phase 6 pinned for the input fingerprint — `canonicalJsonBytes` preserves array order, so an unsorted set lets two callers digest identical logical content differently. + +#### `ManualCheckpointImportV1` — chunk 6, Zod mirror + +```ts +export interface ManualCheckpointImportV1 { + readonly schema_version: "1"; + readonly artifact_kind: "manual-checkpoint-import"; + readonly task_id: TaskSlug; + readonly repository_identity_digest: Sha256Digest; + readonly chain: readonly ManualCheckpointV1[]; // sequence: ascending link.revision, no gaps + readonly head_digest: Sha256Digest; // equals chain[chain.length - 1].checkpoint_digest + readonly head_revision: SafeInteger; + readonly expected_state_revision?: SafeInteger; // absent iff adopting from no-state +} +``` + +### `validateDurableSemantics` — chunk 7, typed against the roots + +```ts +export type DurableArtifact = + | TaskInitializationV1 + | LegacyImportInitializationV1 + | DocumentArtifactV1 + | ImplementationOutputV1 + | ManualCheckpointImportV1; + +export interface DurableSemanticSubject { + readonly state?: CanonicalDocument; + readonly artifact?: CanonicalDocument; + readonly checkpointChain?: readonly CanonicalDocument[]; + readonly maintenance?: CanonicalDocument; +} +export function validateDurableSemantics( + subject: DurableSemanticSubject, +): ProjectResult; +``` + +Typing the subject against the pinned roots rather than `PlainJsonObject` is what makes the validator's correlations checkable at compile time: renaming `initialization_digest` in chunk 2 breaks chunk 7's build instead of silently disabling the check that uses it. `DurableArtifact` is discriminated on `artifact_kind`, which is exactly the `archflow_state.artifact` tagged union — `manual-checkpoint` itself is not a union member, only its import wrapper is, which is why it appears in `checkpointChain` and not in `DurableArtifact`. + +The validator owns exactly these correlation classes and nothing else: predecessor-chain continuity and gaps; digest agreement between a reference and its target; phase-instance validity and `phase-impl-` restriction for implementation outputs; the five snapshot-accounting invariants; the `OutputEntry` table, `file_type`/mode equivalence, `path_class` constraints, and the rename cross-class rule; set sorting and duplicate rejection for every declared set; the one-active-gate rule; and `initialization_digest` presence exactly at revision 1. Structural rejection of unknown fields comes free from `.strict()` and `additionalProperties: false` and is not the validator's job. + +### The Zod-mirror rule, applied + +A durable shape gets a Zod mirror **if and only if it is reachable from an `archflow_state.artifact` union member**, because those shapes cross the MCP tool boundary where schemas are Zod-derived and Ajv/Zod agreement is required. Purely server-internal shapes get JSON Schema authority plus the semantic validator, exactly as Phase 5 did for `release-manifest` and `release-legal-review`. + +| Shape | Union-reachable | Mirror | Reason | +|---|---|---|---| +| `task-state` | no | no | server-internal; never an artifact | +| `maintenance-record` | no | no | server-internal | +| `task-initialization` | yes | yes | union member | +| `legacy-import-initialization` | yes | yes | union member | +| `document` | yes | yes | union member | +| `implementation-output` | yes | yes | union member | +| `manual-checkpoint-import` | yes | yes | union member | +| `manual-checkpoint` | yes | yes | reachable from `manual-checkpoint-import.chain` | +| `snapshot-accounting` | yes | yes | embedded in `implementation-output.accounting` | + +### Schema, module, and registry ownership — chunk 8 writes the shared files + +The previous revision made `SCHEMA_IDS`, `SCHEMA_FILES`, and `src/contracts/index.ts` append-only in numeric chunk order. **That is not safe for fresh-context delegation.** Seven independent agents editing the same object literal and the same export list produce patch conflicts, duplicate export lines, and — worst — one agent regenerating a file from its own view and silently dropping another's row. The `satisfies Record` constraint catches a *missing* pair, but not a dropped pair, a duplicated export, or a merge that loses one edit. + +**Chunk 8 has sole write access to all three files.** Leaf chunks 1–7 author only their own modules, schemas, and tests; none of them touches a registry or the barrel, and none of them can run the registry test until chunk 8 lands. Chunk 8's work is mechanical because every row is pinned here: + +| Leaf chunk | `SCHEMA_IDS` key | Schema filename | Barrel export | +|---|---|---|---| +| 1 | `durablePrimitives` | `durable-primitives.schema.json` | `export * from "./durable-primitives.js";` | +| 2 | `taskState` | `task-state.schema.json` | *(type-only; no runtime export)* | +| 2 | `maintenanceRecord` | `maintenance-record.schema.json` | *(type-only)* | +| 3 | `taskInitialization` | `task-initialization.schema.json` | `export * from "./artifacts/task-initialization.js";` | +| 3 | `legacyImportInitialization` | `legacy-import-initialization.schema.json` | `export * from "./artifacts/legacy-import-initialization.js";` | +| 4 | `documentArtifact` | `document-artifact.schema.json` | `export * from "./artifacts/document.js";` | +| 5 | `implementationOutput` | `implementation-output.schema.json` | `export * from "./artifacts/implementation-output.js";` | +| 6 | `manualCheckpoint` | `manual-checkpoint.schema.json` | `export * from "./artifacts/manual-checkpoint.js";` | +| 6 | `manualCheckpointImport` | `manual-checkpoint-import.schema.json` | `export * from "./artifacts/manual-checkpoint-import.js";` | +| 7 | — | — | `export * from "./durable.js";` | + +All `$id` values are `urn:archflow:schema:v1:`, matching the 22-of-24 majority; the two `https://archflow.dev/...` IDs are legacy and are not a precedent. Ten `SCHEMA_IDS` keys, nine schema files, and eight barrel lines — a mechanical transcription, not a judgement call. + +**Correction carried from the combined design**: it listed chunk 1 as a registry editor. Phase 6's chunk 1 added no schema, so it had no registry row; here, chunk 1 does add `durable-primitives.schema.json`, but it still does not edit the registry — chunk 8 does, for every row including chunk 1's. + +## Files + +| Action | File | Chunk | Purpose | +|--------|------|-------|---------| +| Create | `src/contracts/durable-primitives.ts`, `src/contracts/schemas/v1/durable-primitives.schema.json`, `test/unit/durable-primitives.test.ts` | 1 | Shared `$defs`, the composed evidence-chain entry, snapshot accounting. | +| Create | `src/contracts/schemas/v1/task-state.schema.json`, `maintenance-record.schema.json`, `src/contracts/state-types.ts` | 2 | Server-internal shapes: JSON Schema authority plus type-only declarations. | +| Create | `src/contracts/artifacts/task-initialization.ts`, `legacy-import-initialization.ts` and their two schemas | 3 | Both initialization authorities with Zod mirrors. | +| Create | `src/contracts/artifacts/document.ts`, `document-artifact.schema.json` | 4 | The document artifact with its Zod mirror. | +| Create | `src/contracts/artifacts/implementation-output.ts`, `implementation-output.schema.json` | 5 | The largest shape, entirely by `$ref`/import into chunk 1's files. | +| Create | `src/contracts/artifacts/manual-checkpoint.ts`, `manual-checkpoint-import.ts` and their two schemas | 6 | The predecessor-linked chain and its adoption wrapper. | +| Create | `src/contracts/durable.ts`, `test/contracts/durable-contracts.test.ts` | 7 | The sole semantic authority and its rejection matrix. | +| Create | `test/fixtures/contracts/durable/**` | 1–7 | Per-shape valid samples and rejection corpora, each owned by its authoring chunk. | +| Modify | `src/contracts/versions.ts`, `test/contracts/schema-registry.test.ts`, `src/contracts/index.ts` | **8 only** | Sole registry and barrel ownership, transcribed from the pinned table. | +| Create | `test/contracts/durable-agreement.test.ts` | 8 | Ajv/Zod agreement across every union-reachable shape, once all leaves exist. | + +`package.json` and `.github/workflows/ci.yml` are not modified: `vitest.config.ts` already includes `test/**/*.test.ts`, so `npm test` picks these up. No runtime dependency is added. + +## Contract and Semantic Rules + +- **JSON Schema is the structural authority for every shape.** Where a Zod mirror exists it is a mirror, never a second model, and `assertZodAgreement` proves it over a shared corpus. Where no mirror exists — `task-state`, `maintenance-record` — there is exactly one shape model and one semantic validator, following the Phase 5 precedent. +- **Unknown fields come free** from Zod `.strict()` and JSON Schema `additionalProperties: false`. The semantic validator never re-checks structure. +- **Every collection declares whether it is a set or a sequence.** Sets carry an ordinal sort key and reject duplicates before any digest is taken; the only sequences in this phase are `ManualCheckpointV1.evidence_chain` and `ManualCheckpointImportV1.chain`, both of which are semantic orderings. This mirrors the rule Phase 6 pinned for `computeInputFingerprint`, and for the same reason: `canonicalJsonBytes` preserves array order, so an unsorted set produces caller-dependent digests. +- **Digest fields are references, not authority.** A digest-shaped string never establishes that its target exists; the validator resolves what the subject supplies and reports what it cannot resolve. Phase 5 established this rule for release evidence and it holds unchanged. +- **`payload_bytes`, `payload_digest`, and `after.oid` are assertions in this phase and verified facts in Phase 9.** See the attribution above; a passing Phase 7 validation is never evidence that the described bytes exist. +- **`path_class` is constrained by path and operation**, with a closed claimable set and a closed server-owned set, and renames may not cross classes. +- **The one-active-gate rule** is structural: `open_gate` is a single optional object, not an array, in both `TaskStateV1` and `ManualCheckpointV1`. Nesting is unrepresentable rather than merely forbidden. +- **`initialization_digest` is present exactly at revision 1** in a checkpoint chain, and `predecessor_checkpoint_digest`/`predecessor_revision` are absent exactly at revision 1. Absence is expressed with `.optional()` and omission from `required`, never with `null`: across all schemas in `src/contracts/schemas/v1/` there are zero occurrences of `"null"`, and across `src/contracts/*.ts` zero `z.null`/`.nullable()` uses; the established convention is `gates.ts:95` and `mcp-tools.ts:59`. `SafeInteger` is branded and cannot be widened to admit `null` anyway. +- **No new error code.** Every failure this phase produces uses an existing code — `STATE_INVALID`, `SNAPSHOT_INVALID`, `TASK_INVALID`, `CONTRACT_INVALID`, `INPUT_FINGERPRINT_MISMATCH`. `test/unit/errors.test.ts` asserts exactly 52 project codes and `test/contracts/gate-error-supplemental-exhaustive.test.ts` asserts exactly 56 total rows; both must still pass unchanged. +- **`evidence-slots.schema.json` is not edited.** Phase 2 owns it; this phase composes with it. + +## Work Breakdown + +1. **Shared `$defs`**: Implement `durable-primitives.ts` and its schema — `BlobIdentity`, `OutputEntry` under its operation × storage table, the `kind`-discriminated `EvidenceChainEntry` composing unmodified `evidence-slots` members plus `authority_link_digest`, `PredecessorLink` under the absent convention, and `SnapshotAccountingV1` with its Zod mirror. Author no registry row. +2. **Server-internal shapes**: Author `task-state.schema.json` and `maintenance-record.schema.json` against the pinned `TaskStateV1` and `MaintenanceRecordV1` interfaces, with type-only TypeScript declarations and deliberately no Zod mirror. +3. **Initialization authorities**: Author `task-initialization` and `legacy-import-initialization` with Zod mirrors against the pinned interfaces, including `CanonicalTaskPaths`, the legacy mapping with its `draft`/`historical` disposition, and staged payload refs. +4. **Document artifact**: Author `document-artifact` with its Zod mirror, binding the task-relative path, byte count, content digest, declared inputs, recomputed fingerprint, snapshot, and projection target. +5. **Implementation-output artifact**: Author the largest shape and its mirror entirely by `$ref` and import into chunk 1's files, editing nothing chunk 1 owns. Include `ParentDocumentRef`, `UndeclaredChangeReport` with its raw paths, the embedded accounting and secret-scan results, and the conditional constitution-edit gate reference. +6. **Manual checkpoint chain**: Author `manual-checkpoint` and `manual-checkpoint-import` with their mirrors, using `PredecessorLink` and `EvidenceChainEntry`, the self-digest rule, and the ascending-no-gaps chain constraint. +7. **Cross-document semantics and corpus**: Implement `validateDurableSemantics` typed against the pinned roots, covering exactly the correlation classes listed above. Build the full rejection matrix over the per-chunk fixtures. +8. **Registry, barrel, and agreement integration**: Transcribe the ten `SCHEMA_IDS` keys, nine `SCHEMA_FILES` rows, and eight barrel exports from the pinned table; add the cross-shape Ajv/Zod agreement suite; run the aggregate. Sole writer of all three shared files. + +**Eight chunks, at the top of the 7–8 target.** The reduction path to seven, if needed, is merging chunk 4 into chunk 3 — `document-artifact` is the smallest artifact and shares no file with the initialization shapes. Chunks 1 and 8 must stay isolated: chunk 1 is the seam every other chunk builds on, and chunk 8's whole value is being the only writer of the shared files. + +## Success Criteria + +- [ ] Every root shape — `TaskStateV1`, `MaintenanceRecordV1`, and all six artifact roots — has declared properties, required fields, its `artifact_kind` discriminant where applicable, and named cross-document keys in both TypeScript and JSON Schema. No root document is specified only in prose. +- [ ] `validateDurableSemantics` is typed against those roots, not `PlainJsonObject`; renaming a correlated field in any leaf chunk fails `tsc --noEmit` in chunk 7. +- [ ] `EvidenceChainEntry` composes unmodified `evidence-slots` members under a `slot` key with `authority_link_digest` as a sibling. `evidence-slots.schema.json` is unedited, `additionalProperties: false` is never violated, and a `self-review` slot with `server-attested` assurance or matching families is rejected by the inherited `oneOf` correlations. +- [ ] All nine shapes round-trip valid samples through their normative JSON Schemas; every union-reachable shape — including `snapshot-accounting` and `manual-checkpoint` — passes Ajv/Zod agreement; `task-state` and `maintenance-record` have exactly one shape model each. +- [ ] Every `OutputEntry` combination outside the operation × storage table is rejected, and `file_type === "symlink"` holds iff the surviving `BlobIdentity` mode is `120000`. +- [ ] `path_class` is rejected when it disagrees with the path's frame, when an implementation output claims any server-owned class, when `task-branch-constitution` appears without `constitution_edit_gate_id`, and when a `rename` crosses classes. +- [ ] The document states plainly that `payload_bytes`, `payload_digest`, and `after.oid` are assertions here and names **Phase 9** as the layer that verifies them against retained bytes; no success criterion in this phase claims byte existence. +- [ ] All five snapshot-accounting invariants fail closed through `validateDurableSemantics`, including the one-to-one cross-shape correspondence with `outputs`. +- [ ] Every declared set is sorted by its declared ordinal key with duplicates rejected; the two sequences are not sorted; permutation fixtures prove a shuffled set is rejected rather than silently re-digested. +- [ ] Predecessor gaps, non-monotonic revisions, a predecessor field present at revision 1, a missing `initialization_digest` at revision 1, a `head_digest` disagreeing with the chain tail, and a second `open_gate` all fail with stable existing error codes. +- [ ] No schema contains `"null"` and no Zod module uses `.nullable()`; absence is `.optional()` plus omission from `required` throughout. +- [ ] Leaf chunks 1–7 modify no registry file and no barrel. Chunk 8 is the sole writer of `versions.ts`, `schema-registry.test.ts`, and `index.ts`, transcribing exactly ten keys, nine filenames, and eight exports; the bijection test and `satisfies Record` constraint both hold. +- [ ] No new error code is added; the 52-code and 56-row assertions still pass; `package.json` is unchanged in both `dependencies` and `scripts`. +- [ ] No state mutation, transaction kernel, snapshot materialisation, or payload restore is implemented; the full aggregate passes on Node `24.15.0` and `24.18.0`. + +## Verification Steps + +1. **Before anything else, reconcile the "Consumed from Phase 6" table against Phase 6's implementation log and its real exported signatures.** Report every difference as a design defect at the `archflow-phase-design mcp-integration 7` gate. Do not begin implementation from this document's provisional references. +2. Round-trip one valid sample per shape through its JSON Schema, and through `assertZodAgreement` for every union-reachable shape. Confirm `task-state` and `maintenance-record` have no second shape model by grepping for any Zod schema naming their fields. +3. Compose an `EvidenceChainEntry` review branch from each of the three `evidence-slots` `$defs` and assert Ajv accepts it. Then assert rejection of: a slot missing `producer_family`; a slot carrying `authority_link_digest` *inside* it; `self-review` with `server-attested`; `counter-review` with matching families; `gate-counter-review` without `gate_id`. Confirm `evidence-slots.schema.json` is byte-unchanged. +4. Run the `OutputEntry` rejection matrix: `delete` with `storage: "raw-payload"`; `git-object` with `payload_digest`; `raw-payload` without `payload_digest`; `delete` carrying `after`; `add` carrying `before`; `rename` without `previous_path`; `file_type: "regular"` with `after.mode: "120000"`; `after.mode: "160000"`. +5. Run the `path_class` matrix: an output under `.archflow/` claiming `repository-source`; an output outside `.archflow/` claiming `document`; an implementation output claiming each of the ten server-owned classes; `task-branch-constitution` without `constitution_edit_gate_id`; a `rename` from `repository-source` to `document`. +6. Run the accounting matrix: `result_bytes` disagreeing with the sum of `counted_entries`; `result_bytes` above 26214400; `task_bytes` above 262144000; `task_bytes` below `result_bytes`; a `git-object` entry with non-zero `stored_bytes`; a `counted_entries` path with no matching `OutputEntry`; an `OutputEntry` with no matching `counted_entries` row; `stored_bytes` disagreeing with `payload_bytes`. +7. Run the chain matrix: a missing predecessor at `revision > 1`; a predecessor field present at `revision === 1`; `predecessor_revision >= revision`; a digest mismatch against the named predecessor; a gap in `chain` revisions; `head_digest` disagreeing with the tail's `checkpoint_digest`; a missing `initialization_digest` at revision 1; two `open_gate` entries expressed as an array (assert the schema makes this unrepresentable rather than merely invalid). +8. Run the ordering matrix: shuffle each declared set and assert rejection; duplicate a key in each and assert rejection; shuffle `evidence_chain` and `chain` and assert **acceptance**, since those are sequences. +9. Assert the registry invariants after chunk 8: `SCHEMA_IDS` and `src/contracts/schemas/v1/` in exact bijection with `SCHEMA_FILES` satisfying its `Record` constraint; every new `$id` matching its file and compiling against all others; ten keys, nine files, eight exports, no duplicate export line; no leaf chunk's diff touching any of the three shared files. +10. Confirm the exclusions: no `"null"` in any schema, no `.nullable()` in any module, no new error code, 52/56 assertions green, `package.json` byte-identical, and no code in this phase that writes a file, acquires a lock, or materialises a payload. Run `npm run check` **invoking the exact `24.15.0` and `24.18.0` binaries explicitly** — the ambient developer Node is `24.11.1`, below the project's `>=24.15.0` floor, and Phase 5's implementation log recorded the same trap. + +--- +*Drafted: 2026-07-28 — preserved from the combined Phase 6 design; not gate-approved* diff --git a/.archflow/tasks/mcp-integration/reviews/phase-6-design-counter-review.md b/.archflow/tasks/mcp-integration/reviews/phase-6-design-counter-review.md new file mode 100644 index 00000000..a4265ba7 --- /dev/null +++ b/.archflow/tasks/mcp-integration/reviews/phase-6-design-counter-review.md @@ -0,0 +1,68 @@ +# Phase 6 Design Counter-Review + +Independent Git checks confirmed the narrow claims behind the proposed attribute rule: in a temporary repository, `.archflow/** -text merge=binary` produced `text: unset` and `merge: binary`; a forced modify/modify conflict left the selected JSON side parseable with zero conflict markers while both porcelain v2 and `git diff --name-only --diff-filter=U -z` still reported the path as unmerged. The live repository does not yet contain the rule, so its current output is `text: auto` / `merge: unspecified`, as expected before implementation. The findings below concern the surrounding contracts and phase fit. + +1. **blocker — The phase does not fit the implementation-session budget it cites.** The skill's current calibration is roughly 8–12 delegated chunks plus end-to-phase verification, while this design has 16 chunks, several of which are themselves large multi-file subsystems (notably chunks 10, 12, 13, 14, 15, and 16). The proposed fallback to 14 still exceeds that calibration and does not address integration/rework costs from multiple fresh-context authors. **Suggested resolution:** split Phase 6 at a coherent approved architecture boundary, most naturally repository/Git/path/digest primitives versus durable schemas/semantic validation, rather than merely merging chunk labels; preserve a dedicated integration and aggregate-verification allowance in each resulting phase. + +2. **blocker — Most durable chunk seams are prose, not pinned contracts.** `TaskStateV1`, `MaintenanceRecordV1`, all six artifact root shapes, and their exact properties/required fields/refs are not declared. Chunk 15 then accepts generic `PlainJsonObject` values and is expected to correlate fields whose names and shapes chunks 11–14 independently invent. The statement that shared `$defs` are pinned does not pin the root documents that consume them. **Suggested resolution:** add exact interfaces or exhaustive field/ref tables for every root shape, including discriminants and cross-document keys, and pin the semantic validator's typed inputs and correlations before delegating those chunks. + +3. **blocker — Chunk 5's “exact inventory” omits live mirrors and runtime validators, so agreement can break even if every listed file is changed.** `trust.ts:157` parses `current_evidence.slots[*].gate_id` with the old `idSchema`; `gate-decision.schema.json:107-112` mirrors the `GateDecisionEnvelopeBase.gate_id` and `task_id`; and `result-expectation.schema.json:35-36` mirrors `mcp-tools.ts:128`'s `task_id` and `intent_id`. None is in the file/test inventory. The same logical gate IDs also occur in `supplemental.ts`/`supplemental-review.schema.json` and authority-link contracts, while `test/unit/trust.test.ts`, `test/unit/supplemental.test.ts`, and gate/supplemental exhaustive fixtures currently accept values such as `Gate:1` and `Task_1`. **Suggested resolution:** inventory every logical task/intent/gate ID across Zod, exported types, all normative JSON Schemas, advertised schema closure, and fixtures; explicitly decide whether the retightening is global for each logical ID; update `trust.ts`, gate-decision, result-expectation, supplemental/authority-link mirrors, and their tests atomically. + +4. **major — The new ID brands stop at their parsers and cannot cross the MCP-to-repository seam.** The proposed schemas are declared as `z.ZodType`, while `CommonToolInput`, `ResultIdentityPayload`, `WaiverDecisionBinding`, `GateDecisionEnvelopeBase`, `GateSupersessionRef`, and related fields remain plain `string`. Consequently, a parsed `task_id` cannot be passed to `computeTaskIdentity` or `toRepositoryPathClaim`, and parsed gate/intent IDs cannot be passed to path templates without an undocumented cast or reparse. **Suggested resolution:** pin branded Zod outputs (`z.ZodType` / `z.ZodType`) and retype every affected public interface, or define one explicit conversion boundary with an owner and compile-time tests. + +5. **major — The chunk order does not typecheck as written.** Chunk 3 publishes `computeTaskIdentity(taskId: TaskSlug, ...)`, but `TaskSlug` is not created until chunk 4; the stated hard constraints mention chunk 4 before 5, not chunk 4 before 3. **Suggested resolution:** move `TaskSlug` into an earlier primitive chunk or reorder/depend chunk 3 on chunk 4, and update the advertised landing order. + +6. **blocker — The pinned ProjectResult signatures lack the data needed to construct the promised existing errors.** `readIndexEntries(runner, paths)` promises `TASK_INVALID`, which requires `{task_id, issue_code}` but receives no `task_id`. `classifyMutationReadiness(status)` promises `GIT_CONFLICT`, `GIT_DIVERGED`, and `HANDOFF_REQUIRED`, whose live parameters respectively require `operation`, `{expected_digest, observed_digest}`, and `phase_instance`; `WorktreeHistoryStatus` contains none of those. Git spawn mapping has the same gap: `REPOSITORY_NOT_FOUND` requires `repository_candidate_digest`, and `IO_ERROR` requires `{operation, attempt}`, but neither `preflightGit` nor the runner carries those values. **Suggested resolution:** add a pinned boundary/error context to the relevant reader/classifier signatures (or move translation to a layer that owns it) and specify exact code/parameter construction for every failure branch. + +7. **blocker — `EvidenceChainEntry` cannot `$ref` the existing evidence-slot definitions as prescribed.** `evidence-slots.schema.json`'s `self`, `counter`, and `gateCounter` objects require `producer_family`, `reviewer_family`, and `independence`, forbid extra properties, and do not contain `authority_link_digest`; the proposed `EvidenceChainEntry` omits those required fields and adds that forbidden field. Ajv/Zod agreement is therefore impossible under the stated reuse. **Suggested resolution:** either make the chain entry include/compose the full slot provenance shape plus its authority-link digest, or introduce one narrower shared correlation definition that both schemas can legally reference. + +8. **blocker — Repository-relative path claims are not guaranteed by the Git APIs.** `GitRunner.cwd` may be any caller cwd, while `readIndexEntries` and `checkArchflowAttributes` receive neither `WorktreeLocation` nor a root-bound runner. Reproduction from `repo/sub` showed `git ls-files -s -- .archflow/...` returned nothing and `git check-attr ... -- .archflow/...` returned `text: auto` / `merge: unspecified`; spelling the path as `../.archflow/...` found it but emitted a path that cannot be a `RepositoryPathClaim`. **Suggested resolution:** pin a root-bound runner created after discovery, or pass the worktree root into every repository-path command; use top-anchored literal pathspecs and assert that returned paths exactly equal requested repository claims. + +9. **major — The Git parsing contract is neither byte-safe nor literal.** Without `-z`, both `git ls-files -s` and `git check-attr` quote non-ASCII filenames (a reproduced `.archflow/ü space.json` became a C-quoted path), while `check-attr -z` emits NUL triplets rather than “lines.” In addition, the lexical claim schema permits Git pathspec metacharacters such as `*`, `?`, and `[]`, so one claimed path can select multiple files. **Suggested resolution:** pin `ls-files -s -z` and `check-attr -z`/`--stdin -z` parsers with exact cardinality, use `--literal-pathspecs` or `:(top,literal)`, and add Unicode-filename and metacharacter tests. Consider rejecting the remaining Windows-illegal `< > | ? *` characters as part of the claimed portability boundary. + +10. **major — Not every path emitted by Git can be branded `RepositoryPathClaim`.** An otherwise valid Git repository may contain conflicted paths with a colon, trailing dot, non-NFC text, reserved device name, newline, or another spelling deliberately rejected by ArchFlow's lexical schema. `git diff --diff-filter=U -z` emits those raw paths, so `conflictedOtherPaths: RepositoryPathClaim[]` either throws while checking unrelated conflicts or requires an unsafe cast. **Suggested resolution:** introduce an untrusted/raw Git path representation (or return valid claims plus an invalid-conflict presence/count) and only mint `RepositoryPathClaim` after validation; include a conflict outside `.archflow/` whose filename is invalid under ArchFlow claims. + +11. **major — The two-frame resolver cannot represent all declared path classes.** `resolveTaskPath` accepts a task-rooted `TaskPathClaim`, and `toRepositoryPathClaim(taskId, claim)` necessarily places it below `.archflow/tasks/`, but `PATH_CLASSES` also includes repository-rooted `shared-workflow`, `shared-constitution`, and `repository-source`. No repository-claim resolver or exact class-to-template/parameter table is pinned. **Suggested resolution:** split task-scoped and repository-scoped resolver APIs, restrict each to an explicit class subset, and write the exact template and required identifier inputs for every `PathClass`. + +12. **major — The documented `exit 128 => absent` rule is unsafe and under-specified.** Git uses 128 for dubious ownership, corrupt objects/repositories, invalid revision syntax, and other fatal conditions, not only absent refs/objects/config. The interaction of `allowExitCodes`, `absent`, `runText`, and `runNulLines` on nonzero exits is also unspecified, leaving chunks 3, 7, and 8 to invent incompatible behavior. **Suggested resolution:** make expected absence command-specific and caller-declared, classify only the exact expected exit/diagnostic for that command, and pin helper behavior for every nonzero/spawn/timeout/overflow case. + +13. **major — The OutputEntry table is structurally total but not integrity-total.** For `raw-payload`, nothing requires `payload_bytes` to equal retained byte length, `payload_digest` to equal SHA-256 of those bytes, or `after.oid` to equal `gitBlobOid(bytes)`; the five listed snapshot-accounting invariants only equate `stored_bytes` with the asserted `payload_bytes`. `path_class` is also unconstrained by path/operation, so an implementation output can claim a shared/task-state class, and rename has no cross-class rule for `previous_path`. **Suggested resolution:** pin the layer that validates payload bytes/digest/blob OID and add rejection fixtures; constrain implementation-output classes and rename transitions, or explicitly define every permitted class/path combination. + +14. **major — Input fingerprint canonicalization is not deterministic for logically set-valued collections.** `canonicalJsonBytes` preserves array order, but `artifact_identities`, `upstream_identities`, and `declared_inputs` have no canonical sort key, ordering precondition, or duplicate rule. Independent callers can hash the same logical inputs to different fingerprints. **Suggested resolution:** declare which collections are semantic sequences versus sets; for sets, pin ordinal sort keys and duplicate rejection before hashing, with permutation and duplicate tests. + +15. **major — `parseCanonicalDocument` does not pin the byte-authority security contract consumed by later chunks.** The design does not say whether it rejects noncanonical JSON bytes, malformed UTF-8, duplicate keys, dangerous object keys, or whether `digest` covers the original bytes or a re-rendered value. Phase 5's live precedent checks raw bytes against canonical rendering, but parity tests here cover only rendering. **Suggested resolution:** specify fatal UTF-8/JSON/plain-JSON validation, duplicate/dangerous-key policy, byte-for-byte canonical equality, and digest ownership; add malformed, duplicate-key, noncanonical-whitespace/order/newline fixtures. + +16. **major — The `SNAPSHOT_LIMIT.offending_paths` exception defeats the new path-frame distinction.** The design intentionally leaves it as `TaskPathClaim`, while `OutputEntry` and `SnapshotAccountingEntry` identify repository-relative declared outputs. A producer reporting those exact offending outputs must cast/reparse across frames. **Suggested resolution:** retype the diagnostic semantically as repository-relative (the wire schema may still share the same lexical authority) and update Zod/schema/tests, or explicitly redefine and prove that accounting paths are task-payload-relative instead. + +17. **major — The shared-file ownership plan is not safe for fresh-context delegation.** `SCHEMA_IDS`, `SCHEMA_FILES`, and `src/contracts/index.ts` are edited by many independent chunks at the same object/export-list boundaries; “append-only in numeric order” does not prevent patch conflicts, duplicate exports, or one agent omitting another's row. The document does not enumerate exact per-chunk keys/files/exports, and even lists chunk 1 as editing registries despite not adding a schema ID. **Suggested resolution:** pin every per-chunk registry key, filename, and barrel export, and give one final integration chunk sole ownership of the shared registries/barrel after leaf modules land. + +18. **major — REQ-04 and REQ-26 are advanced, not completed.** REQ-04 requires task-start recording and enforcement of immutable identity/base/workflow/constitution/config inputs; this phase defines schemas/digests but explicitly excludes state mutation, while Phase 7 still owns config-pin enforcement and also lists REQ-04. REQ-26 requires every tool to resolve the canonical root and reject scope/identity violations before reads or child dispatch; this phase supplies utilities but wires no production handlers, and later transaction/handler/dispatch/proof phases still own that behavior. **Suggested resolution:** mark both requirements as advanced and state the exact contract/mechanism slice delivered here; reserve completion for the phase that integrates and verifies the behavior through all five tools. The seven requirements already labeled advanced are honest partial contributions. + +## Triage + +**All 18 findings accepted; none rejected.** Findings 2–18 are verified defects with concrete resolutions. Finding 1 is accepted in principle but its resolution is a scope decision reserved for the human, and because that decision determines where the other 17 fixes land, the design revision is held until it is made. + +Spot-verified directly against live code before triage: `evidence-slots.schema.json`'s `self`/`counter`/`gateCounter` do require `producer_family`, `reviewer_family`, and `independence`, are `additionalProperties: false`, and carry no `authority_link_digest` (finding 7 confirmed); `gate-decision.schema.json:107-112`, `result-expectation.schema.json:35-36`, and `trust.ts:157` all mirror task/gate/intent IDs and are absent from the chunk 5 inventory (finding 3 confirmed). + +| # | Severity | Disposition | Resolution | +|---|---|---|---| +| 1 | blocker | **Accepted — escalated to the human** | Third independent finding that the phase does not fit one implementation session. The prior decision to keep a single Phase 6 was made against a 14-chunk estimate; the design is now 16 chunks and this review's own volume of structural blockers is further evidence. Escalated rather than resolved unilaterally: splitting changes where findings 2–18 land. | +| 2 | blocker | Accepted | Pin exact interfaces for `TaskStateV1`, `MaintenanceRecordV1`, and all six artifact root shapes, including discriminants and cross-document keys. Retype `validateDurableSemantics` from `PlainJsonObject` to the pinned types so its correlations are checkable. Round 2 pinned the shared `$defs` but not the roots that consume them. | +| 3 | blocker | Accepted | Add `trust.ts:157`, `gate-decision.schema.json:107-112`, `result-expectation.schema.json:35-36`, and the supplemental/authority-link mirrors to the chunk 5 inventory, with `test/unit/trust.test.ts` and `test/unit/supplemental.test.ts`. The ID inventory has now been found incomplete three times; the design will require it be regenerated mechanically by grep at implementation time and reconciled against the prose list, rather than trusted as enumerated. | +| 4 | major | Accepted | Change the pinned schemas from `z.ZodType` to `z.ZodType` / `z.ZodType` and retype `CommonToolInput`, `ResultIdentityPayload`, `WaiverDecisionBinding`, `GateDecisionEnvelopeBase`, and `GateSupersessionRef`. Without this a parsed `task_id` cannot reach `computeTaskIdentity` or `toRepositoryPathClaim` without an undocumented cast. | +| 5 | major | Accepted | Real ordering bug: chunk 3 consumes `TaskSlug`, which chunk 4 creates. Move the ID primitives ahead of chunk 3 and correct the advertised landing order. | +| 6 | blocker | Accepted | Every promised error is unconstructible from its pinned signature: `TASK_INVALID` needs `task_id`, `GIT_CONFLICT` needs `operation`, `GIT_DIVERGED` needs a digest pair, `HANDOFF_REQUIRED` needs `phase_instance`, `REPOSITORY_NOT_FOUND` needs `repository_candidate_digest`, `IO_ERROR` needs `{operation, attempt}`. Add a pinned error-context parameter to the reader and classifier signatures and specify exact code and parameter construction for every failure branch. | +| 7 | blocker | Accepted | The round-2 instruction to `$ref` the evidence slots was wrong and is withdrawn. Introduce one narrower shared correlation `$def` that both `evidence-slots.schema.json` and `EvidenceChainEntry` can legally reference, or compose the full slot provenance shape plus `authority_link_digest`. | +| 8 | blocker | Accepted | Pin a root-bound runner created after worktree discovery, so `GitRunner.cwd` cannot be an arbitrary subdirectory, and assert returned paths equal requested repository claims. The reproduction from `repo/sub` — `ls-files -s` returning nothing and `check-attr` reporting `text: auto` — is a silent-wrong-answer failure, not an error. | +| 9 | major | Accepted | Pin `ls-files -s -z` and `check-attr -z` parsers with exact cardinality (`check-attr -z` emits NUL triplets, not lines), use `--literal-pathspecs` or `:(top,literal)`, and reject pathspec metacharacters `*`, `?`, `[`, `]` plus the Windows-illegal `<`, `>`, `|` in the lexical schema. One claimed path selecting multiple files is a correctness and security defect. | +| 10 | major | Accepted | Introduce a raw/untrusted Git path representation; mint `RepositoryPathClaim` only after validation. A conflicted path outside `.archflow/` may legitimately carry a colon, newline, or non-NFC text, so `conflictedOtherPaths` currently either throws on unrelated conflicts or requires an unsafe cast. Add a fixture with an ArchFlow-invalid conflicted filename. | +| 11 | major | Accepted | Split the resolver into task-scoped and repository-scoped APIs restricted to explicit class subsets, and pin the exact template and required identifier inputs for every `PathClass`. `toRepositoryPathClaim(taskId, claim)` cannot express `shared-workflow`, `shared-constitution`, or `repository-source`. | +| 12 | major | Accepted | Replace the blanket `exit 128 ⇒ absent` rule with caller-declared, command-specific expected absence classified on the exact expected exit and diagnostic. Git also returns 128 for dubious ownership, corrupt repositories, and invalid revision syntax. Pin helper behaviour for every nonzero, spawn, timeout, and overflow case. | +| 13 | major | Accepted | Pin the layer that validates `payload_bytes` against retained length, `payload_digest` against SHA-256 of those bytes, and `after.oid` against `gitBlobOid(bytes)` — Phase 6 defines the contract, Phase 8 retains the bytes, so the design must name the owner rather than leave the integrity gap unattributed. Constrain `path_class` by path and operation, and pin the rename cross-class rule. | +| 14 | major | Accepted | Declare which fingerprint collections are sequences and which are sets; for sets pin an ordinal sort key and duplicate rejection before hashing, with permutation and duplicate tests. Independent callers currently hash identical logical inputs to different fingerprints — a correctness defect in a digest contract. | +| 15 | major | Accepted | Specify `parseCanonicalDocument`'s byte-authority contract: fatal UTF-8, JSON, and plain-JSON validation, duplicate and dangerous-key policy, byte-for-byte canonical equality, and whether `digest` covers original or re-rendered bytes. Phase 5's live `parseCanonicalDocument` already checks raw bytes against canonical rendering; the parity tests cover only rendering. | +| 16 | major | Accepted | The round-2 decision to leave `SNAPSHOT_LIMIT.offending_paths` as `TaskPathClaim` is withdrawn. Retype it semantically as repository-relative while keeping the shared lexical wire schema, and update Zod, JSON Schema, and tests. | +| 17 | major | Accepted | Give one final integration chunk sole ownership of `SCHEMA_IDS`, `SCHEMA_FILES`, and `src/contracts/index.ts` after the leaf modules land, and pin every per-chunk registry key, filename, and barrel export. "Append-only in numeric order" does not prevent patch conflicts or omitted rows across fresh-context agents. Also correct the table, which lists chunk 1 as editing registries despite adding no schema ID. | +| 18 | major | Accepted | Move REQ-04 and REQ-26 from "completed" to "advanced" and state the exact contract slice delivered. REQ-04 requires task-start recording and enforcement, which this phase excludes and Phase 7 owns; REQ-26 requires every tool to reject before reads, and this phase wires no handlers. No requirement is then claimed complete in Phase 6. | + +*Triaged: 2026-07-28* From 64982a31ae97c78cbc36a22c8ae8e74ff001abd8 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Tue, 28 Jul 2026 11:14:43 -0500 Subject: [PATCH 017/124] Archflow: Explore Codebase Context --- .archflow/context/architecture.md | 363 +++++++++++++++----- .archflow/context/dependencies.md | 48 ++- .archflow/context/patterns.md | 542 ++++++++++++++++++++++++++---- 3 files changed, 795 insertions(+), 158 deletions(-) diff --git a/.archflow/context/architecture.md b/.archflow/context/architecture.md index cf368b66..ce740489 100644 --- a/.archflow/context/architecture.md +++ b/.archflow/context/architecture.md @@ -1,113 +1,312 @@ -# Architecture Context +# ArchFlow MCP Server Architecture -**Explored:** 2026-07-27 -**Commit:** `8e3144c` +**Date**: 2026-07-28 +**Commit**: 91a7c95 -## Current shape +## Overview -This repository is the ArchFlow skills distribution plus an in-progress, contract-first TypeScript implementation of the planned local MCP integration. The implemented runtime code is currently a reusable contract library under `src/contracts/`; there is no MCP transport entry point, stdio server, persistent state engine, or tracked `dist/` bundle yet. The normative future design and phase plan live in `.archflow/tasks/mcp-integration/architecture.md`, while this document describes the code that exists at the stamped commit. +ArchFlow is a lightweight development workflow framework that runs as an MCP (Model Context Protocol) server. It provides six portable Agent Skills for Claude Code and Codex, guiding structured development from exploration through implementation with human review at every stage. The codebase consists of TypeScript/Node.js runtime logic and Markdown-based skill definitions. -The package is private, ESM-only, and targets Node 24 / ES2024. `src/contracts/index.ts` is its sole aggregate entry point. A temporary bundle is built from that file for compatibility smoke testing, but the package does not currently declare a public `exports`, `bin`, or production build artifact. +## Top-Level Directory Map -## Repository map +``` +. +├── src/ # TypeScript source +│ ├── main.ts # Entry point: process wiring +│ ├── contracts/ # Data structures & validation schemas +│ └── mcp/ # MCP protocol & runtime +├── skills/ # Six portable Agent Skills (Markdown) +│ ├── archflow-explore/ +│ ├── archflow-prd/ +│ ├── archflow-design/ +│ ├── archflow-phase-design/ +│ ├── archflow-phase-impl/ +│ └── archflow-status/ +├── test/ # Test suite (Vitest) +│ ├── unit/ +│ ├── integration/ +│ ├── contracts/ +│ └── fixtures/ +├── dist/ # Build output (bundled MCP runtime) +├── scripts/ # Build & release tooling +├── docs/ # Process documentation +├── release/ # Release artifacts +├── package.json # Node.js dependencies & scripts +├── tsconfig.json # TypeScript configuration +├── vitest.config.ts # Test runner configuration +└── THIRD_PARTY_NOTICES.md # License information +``` + +## Key Entry Points + +### Main Process Entry Point + +**File**: `src/main.ts` + +```typescript +import { runMcpProcess } from "./mcp/process-runner.js"; +import { startMcpRuntime } from "./mcp/sdk-adapter.js"; + +void runMcpProcess( + { + input: process.stdin, + output: process.stdout, + diagnostic: process.stderr, + workingDirectory: process.cwd(), + signals: process, + setExitCode: (code) => { process.exitCode = code; }, + }, + startMcpRuntime, +); +``` + +**Wiring**: The entry point binds Node.js process streams (stdin/stdout/stderr) and signals to the MCP runtime, allowing the server to receive JSON-RPC messages from clients and send responses via stdout with diagnostics on stderr. + +### MCP Runtime Initialization + +**Files**: +- `src/mcp/sdk-adapter.ts` — Starts the MCP runtime; adapts @modelcontextprotocol/server SDK +- `src/mcp/process-runner.ts` — Manages process lifecycle: startup, signal handling, graceful shutdown +- `src/mcp/session.ts` — Session state machine and JSON-RPC request routing +- `src/mcp/server.ts` — Tool invocation boundary with error handling and contract validation + +**Import Chain**: +1. `main.ts` calls `runMcpProcess()` +2. `runMcpProcess()` starts the MCP runtime via `startMcpRuntime()` +3. `startMcpRuntime()` creates an MCP `Server` instance, wires up tool handlers, and manages the JSON-RPC transport +4. Tool calls are routed through `createToolBoundary()` which validates inputs/outputs against contract schemas + +## Application Wiring & Dependency Flow + +### Protocol Stack (Bottom Up) + +1. **Framing** (`src/mcp/framing.ts`) + - JSON Line protocol encoding/decoding + - Ingress frame parsing + - Egress message serialization + +2. **Send Queue** (`src/mcp/send-queue.ts`) + - Serializes outgoing responses + - Coordinates queueing and backpressure + +3. **Session Controller** (`src/mcp/session.ts`) + - JSON-RPC request/response correlation + - Session state machine (PRE_INIT → INITIALIZING → INIT_RESPONSE_ACCEPTED → READY → CLOSING → CLOSED) + - Routes incoming requests to `initialize`, `ping`, `tools/list`, or `tools/call` + +4. **Tool Boundary** (`src/mcp/server.ts`) + - Validates tool names against contract (`isToolName()`) + - Parses structured inputs via `parseToolCall()` + - Enforces output schema via `validateProjectResultStructure()` / `validateProjectFailureStructure()` + - Returns either `project-result` or `protocol-error` + +5. **SDK Adapter** (`src/mcp/sdk-adapter.ts`) + - Wraps @modelcontextprotocol/server `Server` class + - Configures tool registry from `ADVERTISED_TOOL_CATALOGUE` + - Implements `MessageHandler` interface for MCP protocol events + +6. **Process Runner** (`src/mcp/process-runner.ts`) + - Orchestrates startup and graceful shutdown + - Handles SIGINT/SIGTERM + - Reports exit codes + +### Tool Definitions & Contracts + +**File**: `src/mcp/tools.ts` + +- **`ADVERTISED_TOOL_CATALOGUE`**: Array of `AdvertisedToolDescriptor` (name, inputSchema, outputSchema) +- **Tool schemas**: JSON Schema documents defining each tool's contract + - `mcp-tools.schema.json` — Main tool definitions + - `primitives.schema.json` — Common data types + - `path-claim.schema.json` — File path validation + - `evidence-slots.schema.json` — Evidence structures + - `rubric.schema.json` — Review criteria + - `gate-contract.schema.json` — Review gates + - `gate-decision.schema.json` — Gate outcomes + - `project-error.schema.json` — Error structures + +**Defined Tools** (sample): +- `analyze-code-structure` — Map codebase +- `perform-research` — Domain research +- `design-phase` — Phase design +- `review-document` — Cross-client review +- `gate-adjudication` — Human approval gates +- `execute-shell` — Shell commands +- etc. (full list in `src/contracts/tool-names.ts`) + +### Contract Layer -| Path | Responsibility | -|---|---| -| `src/contracts/` | TypeScript domain contracts, parsers, validators, trust/provenance rules, canonical renderers, MCP tool request/result shapes, and error catalogues. | -| `src/contracts/schemas/v1/` | Versioned JSON Schema counterparts for the TypeScript/Zod contracts. Contract-agreement tests keep both representations aligned. | -| `src/contracts/internal/` | Non-public capability/branding seams. Test capabilities can construct otherwise unforgeable trust objects without exporting those constructors from `index.ts`. | -| `assets/workflow.yaml` | Shipped fixed ArchFlow phase graph and gate policy. | -| `assets/constitution/` | Shipped repository-wide policy rule templates, one stable/versioned rule per numbered Markdown file. | -| `skills/` | Portable source of truth for the six Claude Code/Codex Agent Skills. This layer is installed by `install.sh` and is not wired to a server executable yet. | -| `test/unit/` | Behavioral tests for individual contract modules and cross-module invariants. | -| `test/contracts/` | Zod/JSON-Schema agreement, schema registry, MCP surface, and exhaustive catalogue tests. | -| `test/fixtures/` | Valid and invalid serialized contract examples used by both test layers. | -| `scripts/` | Temporary bundling/smoke checks and dependency/license/NOTICE policy enforcement. | -| `docs/` | User/process documentation and the preserved originating MCP integration design. | -| `.archflow/tasks/mcp-integration/` | Tracked workflow planning, phase designs/logs, and reviews for the MCP implementation itself. | -| `.github/workflows/ci.yml` | Node-version matrix verification pipeline. | -| `notices/`, `THIRD_PARTY_NOTICES.md` | Retained third-party notice material and the lockfile-derived license inventory. | +**Directory**: `src/contracts/` -Generated `.tmp/` bundles and installed `node_modules/` are local build products, not architecture sources. `dist/` is deliberately absent at this stage. +Exports re-exported from `src/contracts/index.ts`: -## Entry points and wiring +| Module | Purpose | +|--------|---------| +| `workflow.ts` | Workflow state (discovery, planning, implementation) | +| `mcp-tools.ts` | Tool contract parsing, validation, correlation | +| `tool-names.ts` | `ToolName` union type and validation | +| `yaml.ts` | YAML parsing for skill definitions | +| `contexts.ts` | Invocation context (user, client, phase, session) | +| `errors.ts` | Protocol and project errors | +| `evidence.ts` | Evidence slot structures | +| `gates.ts` | Review gate rules | +| `trust.ts` | Human trust boundaries | +| `triage.ts` | Counter-review triage | +| `plain-json.ts` | JSON value normalization | +| `validators.ts` | Input/output validation | +| `config.ts` | Configuration parsing | +| `renderers.ts` | Markdown rendering | -### Public contract surface +## Build System & Configuration -`src/contracts/index.ts` re-exports the supported library surface. Consumers are expected to enter through it rather than importing internal trust-brand machinery. Notably, connection contexts are type-exported and only invocation-context derivation is public; server-owned/test-only constructors remain internal. +### TypeScript Configuration -The temporary build demonstrates the intended library boundary: +**File**: `tsconfig.json` -```js -entryPoints: ["src/contracts/index.ts"], -outfile: ".tmp/archflow-contracts.mjs", -platform: "node", -format: "esm" +- **Target**: ES2024 +- **Module System**: ESM (NodeNext resolution) +- **Strict Mode**: Enabled (`strict: true`) +- **Root**: Current directory (monorepo-friendly) +- **No-Emit**: Type-checking only (compilation via esbuild) + +### NPM Scripts + +**Key scripts** (from `package.json`): + +| Script | Purpose | +|--------|---------| +| `typecheck` | TypeScript validation | +| `test` | Full vitest suite (unit + contracts + integration) | +| `test:unit` | Unit tests only | +| `test:mcp-runtime` | MCP protocol runtime tests | +| `build:temp` | Build temporary bundles for smoke testing | +| `release:stage` | Build release artifacts | +| `release:check` | Validate release bundle | +| `release:smoke` | Smoke test the bundle | +| `check:release` | Full release verification | +| `check` | Full CI suite: probe, typecheck, test, build, release, notices | + +### Test Configuration + +**File**: `vitest.config.ts` + +- **Environment**: Node.js +- **Test Patterns**: `test/**/*.test.ts` +- **Coverage**: Reported to `coverage/` directory + +### Build Artifacts + +**Output Directory**: `dist/` + +- `archflow-mcp.mjs` — Bundled MCP server (esbuild output, ~1.3MB) +- `manifest.json` — Tool metadata for distribution +- `metafile.json` — Build metadata +- `legal/` — Third-party notices + +**Build Tool**: esbuild (v0.28.1) + +## Skill System + +**Directory**: `skills/` + +Each skill is a self-contained Markdown document with YAML frontmatter: + +``` +skills/archflow-explore/SKILL.md + ├── name: archflow-explore + ├── description: Explore a codebase and produce persistent ArchFlow context references + └── [Full skill logic in Markdown format] ``` -`scripts/smoke-temp-bundle.mjs` dynamically imports that bundle and exercises YAML parsing, JSON Schema validation, review/adjudication derivation, render anti-spoofing, error creation, phase parsing, and the exact five-tool catalogue. +Skills define: +- Workflow steps (research, design, implementation) +- Sub-agent delegation strategy +- Approval gates +- File artifacts and state machines + +## Node.js Dependencies + +**Runtime** (`dependencies` in package.json): + +- `@modelcontextprotocol/server@2.0.0` — MCP SDK +- `ajv@8.20.0` — JSON Schema validation +- `ajv-formats@3.0.1` — Format validation (email, uri, etc.) +- `yaml@2.9.0` — YAML parsing for skill definitions +- `zod@4.4.3` — Data validation (complementary to JSON Schema) + +**Development** (`devDependencies`): -### Contract layering +- `typescript@7.0.2` — Type checking +- `vitest@4.1.10` — Test runner +- `esbuild@0.28.1` — Bundler +- `vite@7.3.6` — Build coordination +- `@types/node@24.13.3` — Node.js type definitions -The source dependency flow is mostly inward from generic serialization primitives toward workflow semantics: +**Node.js Engine**: >= 24.15.0 (ES2024 features required) -1. `plain-json.ts`, `versions.ts`, `vocabulary.ts`, and `phase-instance.ts` establish safe values, version constants, fixed vocabulary, and canonical phase identifiers. -2. `yaml.ts` and `validators.ts` provide strict YAML parsing and non-mutating Ajv 2020 validation; other parsers preflight input through the plain-JSON boundary. -3. `workflow.ts`, `config.ts`, `rubric.ts`, and `constitution.ts` validate repository configuration and shipped policy assets. -4. `evidence.ts`, `path-claims.ts`, `review.ts`, and `adjudication.ts` define digest-bound evidence, task-scoped paths, review findings, and policy/drift results. -5. `trust.ts` qualifies evidence using invocation/result/authority bindings. `internal/trust-brands.ts` guards authentic branded values; `internal/test-capabilities.ts` exposes controlled fixture seams only to tests. -6. `triage.ts`, `supplemental.ts`, and `renderers.ts` consume qualified evidence to validate exact review-set dispositions and produce canonical human-readable artifacts. -7. `gates.ts` defines gate contexts and decision effects. `errors.ts` composes the domain types into exhaustive project and protocol error catalogues. -8. `mcp-tools.ts` binds the five fixed tool names to versioned request/result schemas, validates calls, correlates results with expected identity, and exports immutable tool definitions. -9. `contexts.ts` creates immutable invocation-scoped context from connection data and maps invalid context to protocol errors; live MCP handshake/transport ownership is intentionally not implemented yet. +## Critical Boundaries & Trust -The five frozen tool names are `archflow_state`, `archflow_counter_review`, `archflow_adjudicate`, `archflow_gate`, and `archflow_waiver`. They are data contracts only at this commit—there are no handlers behind them. +### Protocol Guarantee -### Assets to contracts +The tool boundary (in `src/mcp/server.ts`) enforces a strict contract: + +1. **Input validation**: All tool arguments parsed and validated against contract schema before handler invocation +2. **Output validation**: All handler results validated against expected output schema +3. **Error coercion**: Failures are coerced into protocol-safe `ProtocolError` structures +4. **No handler bypass**: Direct tool access forbidden; all invocations go through boundary + +### Session State Machine + +The session controller enforces strict ordering: + +``` +PRE_INIT → INITIALIZING → INIT_RESPONSE_ACCEPTED → READY + ↓ ↓ + ├─────────────── (tool calls only in READY) ─────────→ + ↓ +CLOSING → CLOSED +``` -`assets/workflow.yaml` is parsed against a fixed workflow shape: explore is optional/ungated; PRD and design always gate; phase design and implementation gate on triggers. Constitution Markdown combines strict YAML frontmatter with normative prose. The contract tests load these assets directly, so shipped configuration and parser expectations are checked together. +Tool calls are rejected if session is not READY. -### Skills and installation +## Test Structure -`install.sh` copies the same `skills/` tree to `~/.claude/skills/` and/or `~/.agents/skills/`, optionally selected with `--claude` or `--codex`. It currently installs prompt/skill content only. MCP launchers, host registration, initialization, and offline helper installation remain planned later phases. +**Directory**: `test/` -## Build and verification +| Path | Purpose | +|------|---------| +| `unit/` | Individual module tests | +| `contracts/` | Contract validation tests | +| `integration/` | MCP protocol end-to-end tests (stdio simulation) | +| `fixtures/` | Test data and utilities | +| `types/` | Type-checking tests | -`package.json` provides no production build command yet. The principal commands are: +## Release & Integrity -| Command | Purpose | -|---|---| -| `npm run typecheck` | Strict TypeScript check with no emission. | -| `npm test` | Run all Vitest unit and contract-agreement tests. | -| `npm run test:unit` | Run module-level behavioral tests. | -| `npm run test:contracts` | Run schema and catalogue agreement tests. This is also run after the full suite in CI as an explicit gate. | -| `npm run build:temp` | Bundle `src/contracts/index.ts` with esbuild, then import and exercise the Node-targeted ESM bundle. | -| `npm run check:dependencies` | Enforce exact direct dependencies, exact lock metadata, approved licenses, and phase-boundary exclusions. | -| `npm run check:notices` | Verify the lockfile license inventory and retained notice digests. | -| `npm run test:notices-policy` | Mutation-test the NOTICE checks. | -| `npm run check` | Run the repository's complete local verification chain. | +**Release Process**: -GitHub Actions repeats these checks on Node `24.15.0` and `24.18.0`, using `npm ci`, and asserts that no tracked-release `dist/` bundle is produced prematurely. +1. **Stage**: Build temporary bundle, verify structure +2. **Check**: Run smoke tests on bundle +3. **Mutations**: Test integrity against bit-flip attacks +4. **Reproduce**: Verify deterministic rebuild +5. **Write**: Track release in git -## Configuration +**Release Artifacts** (in `release/`): +- Tracked bundles for reproducibility +- Checksums for integrity verification +- Legal notices for distribution -- `package.json`: private ESM package, exact runtime/development versions, and verification scripts. -- `package-lock.json`: npm lockfile v3; policy scripts treat exact resolution and license metadata as architectural constraints. -- `tsconfig.json`: `NodeNext` modules/resolution, ES2024 target, strict mode, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, and `noEmit`. -- `vitest.config.ts`: Node test environment, `test/**/*.test.ts`, coverage output under `coverage/`. -- `.github/workflows/ci.yml`: read-only CI permissions and supported Node matrix. -- `.gitattributes`: automatic text detection and LF normalization. -- `assets/workflow.yaml`: canonical application phase topology. -- `assets/constitution/*.md`: canonical initial policy rules. +## Configuration & Environment -There are currently no runtime environment variables, network endpoints, database settings, authentication provider settings, or MCP host configuration consumed by the implemented TypeScript code. Host CLI/auth/sandbox configuration belongs to future adapter and installer phases, not the present contract package. +- **Working Directory**: Current working directory (passed from caller) +- **Stdin/Stdout/Stderr**: Bound from process streams +- **Signals**: SIGINT (graceful close) and SIGTERM (immediate close) +- **Exit Codes**: + - `0` — Clean shutdown + - `1` — Protocol error or startup failure + - `130` — SIGINT (Ctrl+C) + - `143` — SIGTERM -## Architectural boundaries to preserve +--- -- Keep serialized inputs at a strict plain-JSON boundary before domain validation. -- Keep Zod behavior and shipped JSON Schemas demonstrably equivalent. -- Preserve digest-, task-, phase-, invocation-, and authority-bound evidence; schema-shaped objects alone must not acquire trust. -- Keep internal trust brands/capability constructors out of the aggregate public entry point. -- Preserve exactly five MCP tools; local maintenance/helper operations are designed for a separate CLI rather than expanding `tools/list`. -- Keep MCP SDK/transport concerns isolated from the contract layer when the server adapter arrives. -- Treat `.archflow/tasks/mcp-integration/architecture.md` as the implementation plan, but verify current code before assuming a planned subsystem exists. +**Key Architectural Principle**: ArchFlow separates *protocol and runtime* (MCP server in `src/mcp/`) from *domain logic* (workflow contracts and validation in `src/contracts/`), and *portable skills* (Markdown in `skills/`). This allows the same skill source to be distributed to both Claude Code and Codex without client-specific wiring. diff --git a/.archflow/context/dependencies.md b/.archflow/context/dependencies.md index b9ff093f..c4cc3d10 100644 --- a/.archflow/context/dependencies.md +++ b/.archflow/context/dependencies.md @@ -1,7 +1,7 @@ # Dependencies and Integrations -**Explored:** 2026-07-27 -**Commit:** `8e3144c` +**Explored:** 2026-07-28 +**Commit:** `91a7c95` ## Package and runtime baseline @@ -13,12 +13,13 @@ | Dependency | Pin | Use | | --- | --- | --- | +| `@modelcontextprotocol/server` | `2.0.0` | MCP server SDK (phase 4+) for stdio transport binding and tool dispatch. Used in `src/mcp/sdk-adapter.ts` to initialize the Server, handle `Transport`, and implement the `startMcpRuntime` entry point. Includes protocol types and error handling. | | `zod` | `4.4.3` | Primary TypeScript-side structural and semantic validation throughout `src/contracts/`, including configuration, workflow, gates, evidence, reviews, errors, MCP tool envelopes, and trust records. | | `ajv` | `8.20.0` | JSON Schema 2020-12 compilation and validation in `src/contracts/validators.ts`; loaded through `ajv/dist/2020.js`. | | `ajv-formats` | `3.0.1` | Adds standard JSON Schema formats to the Ajv validator in `src/contracts/validators.ts`. | | `yaml` | `2.9.0` | Strict YAML 1.2 parsing in `src/contracts/yaml.ts`, including rejection of multiple documents, warnings, duplicate keys, merges, aliases, and non-plain-JSON values. This parser feeds configuration, workflow, and rubric loading. | -The contract layer also uses only built-in Node modules: `node:crypto` for SHA-256 trust/evidence digests and `node:util` for deep equality. Scripts use built-in filesystem, path, process, OS, assertion, and child-process APIs. +The contract layer and MCP runtime also use only built-in Node modules: `node:crypto` for SHA-256 trust/evidence digests, `node:util` for deep equality, `node:buffer` for transport framing, and `node:stream` for Readable/Writable transport abstractions. Scripts use built-in filesystem, path, process, OS, assertion, and child-process APIs. ## Development and build dependencies @@ -40,11 +41,17 @@ No ESLint, Prettier, Biome, or separate coverage package/configuration is presen ## External integrations and persistence -At this commit, `src/` contains the shared contract and validation layer only. There is no executable MCP server entry point, transport binding, HTTP client, database driver, filesystem-backed state store, or cloud service integration. There are no calls to `fetch`, no database/auth-provider packages, and no application secrets or API-key requirements. +At this commit, `src/` contains the contract, validation, and MCP stdio transport layers. The MCP server implementation (`src/mcp/`) provides: -The future MCP integration is described in `docs/mcp-integration-design.md`: it is intended to dispatch short-lived `claude -p` and `codex exec` processes using the user's existing subscription authentication. The design explicitly avoids requiring or forwarding `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`, because those variables can switch child processes to metered API authentication. That behavior is design intent, not implemented runtime behavior in the current source tree. +- **Transport**: stdio-based message framing via `src/mcp/framing.ts` (JSON-line protocol), `src/mcp/send-queue.ts` (send buffering), and `src/mcp/process-runner.ts` (Node process integration). +- **Server**: `src/mcp/sdk-adapter.ts` binds the `@modelcontextprotocol/server` SDK, `src/mcp/server.ts` implements tool boundary enforcement and response verification, and `src/mcp/tools.ts` defines the advertised tool catalogue. +- **Session management**: `src/mcp/session.ts` handles JSON-RPC invocation context and argument projection. -`scripts/check-dependency-policy.mjs` additionally rejects packages reserved for later implementation phases: `@anthropic-ai/sandbox-runtime`, `@modelcontextprotocol/server`, `execa`, `proper-lockfile`, and `write-file-atomic`. Their absence is deliberate and confirms that MCP transport/dispatch, sandboxing, locking, and atomic state persistence have not yet landed. +There is no HTTP client, database driver, filesystem-backed state store, or cloud service integration. There are no calls to `fetch`, no database/auth-provider packages, and no application secrets or API-key requirements. + +The MCP integration dispatches short-lived `claude -p` and `codex exec` processes using the user's existing subscription authentication, as designed in `docs/mcp-integration-design.md`. The design explicitly avoids requiring or forwarding `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`, because those variables can switch child processes to metered API authentication. + +`scripts/check-dependency-policy.mjs` additionally rejects packages reserved for later implementation phases: `@anthropic-ai/sandbox-runtime`, `execa`, `proper-lockfile`, and `write-file-atomic`. Their absence is deliberate and confirms that sandboxing, locking, and atomic state persistence have not yet landed. Schema identifiers such as `https://archflow.dev/schemas/v1/mcp-tools` in `src/contracts/versions.ts` and `src/contracts/schemas/v1/*.json` are stable identifiers/references; the current validators register and resolve the bundled local schemas rather than fetching them over the network. @@ -57,16 +64,23 @@ Schema identifiers such as `https://archflow.dev/schemas/v1/mcp-tools` in `src/c ## CI/CD and verification -GitHub Actions is the only CI/CD integration (`.github/workflows/ci.yml`). On every push and pull request, an Ubuntu job runs for each supported Node version with read-only repository contents permission: +GitHub Actions is the only CI/CD integration (`.github/workflows/ci.yml`). On every push and pull request, an Ubuntu job runs for each supported Node version (`24.15.0`, `24.18.0`) with read-only repository contents permission: 1. `npm ci` -2. `npm run typecheck` -3. `npm test` -4. `npm run test:contracts` -5. `npm run build:temp` -6. `npm run check:dependencies` -7. `npm run check:notices` -8. `npm run test:notices-policy` -9. Assert that no tracked/release `dist` directory was produced - -`npm run check` provides the corresponding local aggregate, though it invokes the broad `npm test` and then the contract subset again. There is no deployment, package publication, container build, release workflow, or external CI service configured. +2. `npm run probe:phase4-mcp-compatibility` — MCP SDK compatibility checks +3. `npm run typecheck` +4. `npm run test:mcp-runtime` — Unit and integration tests for MCP transport and process binding +5. `npm test` — Full test suite +6. `npm run test:contracts` — Contract-specific tests +7. `npm run build:temp` — Temporary bundle artifact for smoke testing +8. `npm run check:dependencies` — Dependency policy verification +9. `npm run check:notices` — Third-party notice inventory validation +10. `npm run test:notices-policy` — Notice mutation tests +11. `npm run check:phase4-mcp-boundary` — Phase 4 MCP module boundary checks +12. `npm run test:phase4-mcp-boundary-policy` — Phase 4 boundary mutation tests +13. `npm run release:check` — Release payload verification +14. `npm run release:smoke` — Release bundle smoke tests +15. `npm run release:mutations` — Release integrity mutation tests +16. `npm run release:reproduce` — Release reproducibility verification + +`npm run check` provides the corresponding local aggregate that runs all verification steps in sequence. There is no deployment, package publication, container build, or external CI service configured; releases are staged to a tracked `dist/` directory for reproducibility validation. diff --git a/.archflow/context/patterns.md b/.archflow/context/patterns.md index c5726f65..c6bf8ada 100644 --- a/.archflow/context/patterns.md +++ b/.archflow/context/patterns.md @@ -1,59 +1,483 @@ -# Patterns and Conventions - -**Explored:** 2026-07-27 -**Commit:** `8e3144c` - -## Package and module conventions - -- The package is strict TypeScript and native ESM (`package.json` has `"type": "module"`; `tsconfig.json` uses `NodeNext`). Relative imports therefore include the emitted `.js` extension even in `.ts` sources, for example `import { assertPlainJson } from "./plain-json.js"` in `src/contracts/config.ts`. -- Source code currently lives under `src/contracts/`; each file owns one contract area such as configuration, evidence, gates, review, or trust. Public consumers use the curated barrel at `src/contracts/index.ts`. -- Internal trust-minting helpers live below `src/contracts/internal/` and are deliberately excluded from the public barrel. `test/contracts/schema-registry.test.ts` asserts that test authority factories are not exported. -- Names expose version and role explicitly: runtime schemas use names such as `configV1Schema`, parsers use `parseConfigV1` / `parseConfigYaml`, fixed vocabularies use uppercase constants such as `ROUTING_ROLES`, and public data types use PascalCase names such as `ConfigV1` and `ProjectResult`. -- JSON keys and serialized vocabulary use `snake_case` and lowercase hyphenated literals (`schema_version`, `input_fingerprint`, `counter-reviewer`). TypeScript-only identifiers use `camelCase` / `PascalCase`. -- Constants commonly combine literal preservation with compile-time completeness checks: `as const satisfies ...`. Read-only data is favored in public types (`readonly` properties and arrays), while branded string/number types prevent raw values from acquiring validated authority. -- Imports are generally grouped as external or Node built-ins, a blank line, then local imports. Type-only dependencies use `import type` or inline `type` specifiers because `verbatimModuleSyntax` is enabled. There is no configured ESLint or Prettier command; formatting is maintained by source convention and the TypeScript compiler. - -## Boundary validation and data handling - -- Untrusted values are checked as plain JSON before domain parsing. Typical entry points call `assertPlainJson(value, "config")` and then a strict Zod schema (`src/contracts/config.ts`). `src/contracts/plain-json.ts` rejects cycles, accessors, inherited/symbol/dangerous properties, sparse arrays, non-finite numbers, and mutation during inspection. -- Zod object schemas are closed with `.strict()`. Cross-field semantics are expressed through `.refine()` / `.superRefine()` and, where useful, an additional explicit validation function. This makes unknown fields and inconsistent derived fields fail instead of being silently stripped. -- Normative JSON Schemas under `src/contracts/schemas/v1/` are mirrored by TypeScript/Zod contracts. `src/contracts/validators.ts` configures AJV in strict, non-coercing, non-defaulting mode and provides `assertZodAgreement` so the two representations cannot silently diverge. -- Parsers return the original value when validation does not require derivation, preserving identity and avoiding mutation. Tests commonly clone input first and assert it remains equal afterward, for example `test/contracts/foundational-schema-agreement.test.ts` and `test/unit/plain-json.test.ts`. -- Canonical order and exact-set invariants are common: arrays are required to be sorted and unique, review slots have a fixed role order, and count/verdict fields must match their contents. Helpers in `src/contracts/validators.ts` and domain modules enforce these rules. -- Rendering is deterministic and byte-oriented. `src/contracts/renderers.ts` escapes invisible or markup-sensitive characters, emits fields in fixed order, and returns UTF-8 `Uint8Array` values rather than loosely formatted objects. -- There is no database or general data-access layer in the current repository. Runtime code is predominantly pure contract parsing, validation, derivation, and rendering. Filesystem reads appear mainly in tests and asset-loading paths, using `node:fs/promises` and `new URL(..., import.meta.url)` rather than process-relative paths. - -## State, identity, and immutability - -- State is represented as explicit validated values, not mutable application stores. Discriminated unions and correlated generic maps encode legal result, error, gate, evidence, and workflow variants at compile time. -- Security- or trust-sensitive values require unforgeable identity in addition to matching structure. Unique-symbol brands and internal `WeakSet`/capability machinery in `src/contracts/internal/trust-brands.ts` distinguish authentic values from spread copies; tests in `test/unit/trust.test.ts` and `test/unit/mcp-tools.test.ts` verify copied objects lose authority. -- Registries and capabilities are frozen with `Object.freeze`, including nested parser/definition objects where relevant. `src/contracts/errors.ts` is representative: definitions are immutable, parameter schemas are correlated by error code, and construction emits frozen, serializable envelopes. -- Functions generally avoid ambient state. When stateful behavior is necessary, it is scoped to an invocation/capability and authenticated before use rather than exposed as a global mutable singleton. - -## Error handling - -- Boundary failures throw typed built-in subclasses with useful labels and paths: `PlainJsonError extends TypeError` (`src/contracts/plain-json.ts`) and `ContractValidationError extends TypeError` (`src/contracts/validators.ts`). YAML syntax failures use `SyntaxError` with source label, line, and column (`src/contracts/yaml.ts`). -- Domain validation usually throws `TypeError` for structurally or semantically invalid values. Errors are fail-fast; parsing does not coerce or repair caller data. -- Operational/project failures intended for transport are values rather than exceptions. `src/contracts/errors.ts` defines exhaustive `PROJECT_ERROR_DEFINITIONS` and `PROTOCOL_ERROR_DEFINITIONS`, with each code correlated to an owner, retryability, a strict parameter parser, a next action, and a projection. -- Serialized diagnostics intentionally contain bounded, validated parameters instead of raw exceptions or sensitive names. `test/unit/errors.test.ts` verifies extra diagnostic fields are rejected and project/protocol error spaces remain distinct. -- Narrow `try`/`catch` blocks are used only when converting a predicate or preserving a validation boundary; broad swallowing is not a convention. For example, `isPlainJsonValue` converts `assertPlainJson` failure into `false`, while most public parsers allow actionable validation errors to propagate. - -## Testing conventions - -- Vitest is the sole test framework, configured for Node in `vitest.config.ts`; files match `test/**/*.test.ts`. Commands split fast domain tests (`npm run test:unit`) from schema/representation agreement tests (`npm run test:contracts`). -- Tests mirror the source boundary: - - `test/unit/` exercises individual TypeScript contract modules and semantic invariants. - - `test/contracts/` checks JSON Schema compilation, registry completeness, exhaustive vocabulary, and agreement with Zod/runtime behavior. - - `test/fixtures/` contains small valid and deliberately invalid JSON, YAML, and Markdown examples grouped by `foundation/` or `contracts/` and domain. -- Tests use `describe` / `it` with behavioral sentences, direct `expect` assertions, and `it.each` or compact loops for rejection matrices. Compile-time guarantees use Vitest's `expectTypeOf` and `// @ts-expect-error`, as shown in `test/unit/path-claims.test.ts`. -- Fixture helpers are local to the test file and load through `readFile(new URL(..., import.meta.url), "utf8")`; JSON fixtures are explicitly parsed and cast from `unknown`. There is no shared global setup or mock-heavy fixture framework. -- Negative and adversarial coverage is a first-class pattern: unknown keys, prototype/accessor attacks, malformed Unicode, duplicate IDs, stale/foreign evidence, copied branded values, and Zod/JSON Schema disagreement all receive explicit tests. -- Tests frequently verify non-mutation and identity semantics, not only value equality. `structuredClone` captures before-state; authentic-object tests also assert that a spread copy is rejected. - -## Practical checklist for new code - -1. Put the contract in the domain-specific `src/contracts/.ts` module and export only the intended surface through `src/contracts/index.ts`. -2. Treat every `unknown` input as hostile: plain-JSON preflight it, apply a strict schema, then enforce semantic/cross-field invariants without mutation. -3. Keep serialized names in the established `snake_case` vocabulary, TypeScript names idiomatic, and version public schemas/types explicitly when they are wire contracts. -4. Add unit tests for happy paths, rejection matrices, non-mutation, and type/brand boundaries. Add or update contract-agreement tests whenever normative JSON Schema is involved. -5. Use `.js` suffixes for relative imports, type-only imports where applicable, immutable public types, and deterministic ordering for serialized collections and output. +# Codebase Patterns and Conventions + +**Date:** 2026-07-28 +**Commit:** 91a7c95 + +--- + +## Naming Conventions + +### TypeScript/JavaScript + +- **Variables, functions, methods:** camelCase + ```typescript + const sessionState = "READY"; + function parsePhaseInstance(value: unknown): PhaseInstance { } + ``` + +- **Type names and interfaces:** PascalCase + ```typescript + interface ConnectionContext { } + type ToolName = string & { readonly [toolNameBrand]: true }; + type ProjectError = { /* ... */ }; + ``` + +- **Constants and enums:** UPPER_CASE or PascalCase for enum values + ```typescript + const TOOL_NAMES = Object.freeze(["archflow_state", "archflow_counter_review"]); + const MAX_ENTRIES = 1_024; + export type ErrorOwner = "contracts" | "config" | "repository" | "paths" | "policy" | "state"; + ``` + +- **Branded type symbols:** Unique symbols with descriptive names + ```typescript + declare const positiveSafePhaseBrand: unique symbol; + declare const phaseInstanceIdBrand: unique symbol; + export type PositiveSafePhaseNumber = number & { readonly [positiveSafePhaseBrand]: true }; + ``` + +- **Unique Symbol declarations:** Descriptive names prefixed with the concept + ```typescript + const connectionContextBrand: unique symbol = Symbol("ConnectionContext"); + const invocationContextBrand: unique symbol = Symbol("InvocationContext"); + ``` + +### JSON/Configuration Fields + +- **JSON serialized data:** snake_case + ```typescript + const digestPair = { expected_digest: sha256DigestV1Schema, observed_digest: sha256DigestV1Schema }; + ``` + +- **Tool names:** snake_case with prefix + ```typescript + const TOOL_NAMES = Object.freeze([ + "archflow_state", + "archflow_counter_review", + "archflow_adjudicate", + ] as const); + ``` + +--- + +## Error Handling Approach + +### Structured Error Definitions + +Errors are defined with comprehensive metadata using Zod schemas for validation: + +```typescript +export type ErrorOwner = "contracts" | "config" | "repository" | "paths" | "policy" | "state" | "intent" | "snapshot" | "gate" | "routing" | "dispatch" | "sandbox" | "protocol" | "integrity"; + +export interface ErrorDefinition

>, O extends ErrorOwner, R extends boolean, A extends string, X extends ErrorProjection> { + readonly owner: O; + readonly retryable: R; + readonly parameter_parser: StrictParameterParser

; + readonly action: A; + readonly projection: X; +} +``` + +### Error Creation and Parsing + +```typescript +export function createProjectError( + code: K, + parameters: z.input<(typeof PROJECT_PARAMETER_SCHEMAS)[K]> +): ErrorValue { + return constructError(PROJECT_ERROR_DEFINITIONS, code, parameters); +} + +export function parseProjectError(value: unknown): ProjectError { + return parseSerializedError(PROJECT_ERROR_DEFINITIONS, value, "project error") as ProjectError; +} +``` + +### Custom Error Classes + +```typescript +export class ProtocolContextError extends Error { + public constructor(public readonly protocol_error: ProtocolError) { + super(protocol_error.code); + this.name = "ProtocolContextError"; + } +} + +export class ContractValidationError extends TypeError { + public constructor(message: string, public readonly details?: unknown) { + super(message); + this.name = "ContractValidationError"; + } +} +``` + +### Error Parameter Schemas + +- Errors use discriminated union types with Zod validation +- Parameters are validated on construction and deserialization +- Deep strict equality checking ensures round-trip integrity +- Each error has an associated action string for recovery guidance + +--- + +## State Management Patterns + +### Immutable State Design + +All state is frozen using `Object.freeze()` to prevent mutations: + +```typescript +function deepFreeze(value: T): T { + if (value !== null && typeof value === "object") { + for (const nested of Object.values(value)) deepFreeze(nested); + Object.freeze(value); + } + return value; +} +``` + +### State Machines + +State is represented as discriminated unions with exhaustive handling: + +```typescript +export type SessionState = "PRE_INIT" | "INITIALIZING" | "INIT_RESPONSE_ACCEPTED" | "READY" | "CLOSING" | "CLOSED"; + +export type SessionAction = + | Readonly<{ kind: "send"; source: "direct" | "sdk" | "fallback"; message: Readonly>; }> + | Readonly<{ kind: "forward-sdk"; route: "initialize" | "ping" | "tools-list" | "tools-call"; }> + | Readonly<{ kind: "validate-cancellation"; /* ... */ }>; +``` + +### Branded Type Authentication + +WeakSet tracks authentic instances to prevent spoofing: + +```typescript +const authenticConnections = new WeakSet(); +const authenticInvocations = new WeakSet(); + +export function createInvocationContext( + connection: ConnectionContext, + seed: unknown, + signal: AbortSignal +): InvocationContext { + if (!authenticConnections.has(connection)) { + throw new TypeError("a branded connection context is required"); + } + // ... validation ... + authenticInvocations.add(context); + return context; +} + +export function assertAuthenticInvocationContext(value: unknown): asserts value is InvocationContext { + if (value === null || typeof value !== "object" || !authenticInvocations.has(value)) { + throw new TypeError("an authentic invocation context is required"); + } +} +``` + +### Deferred Pattern for Async Operations + +```typescript +interface Deferred { + readonly promise: Promise; + readonly resolve: () => void; + readonly reject: (reason: unknown) => void; +} + +function deferred(): Deferred { + let resolvePromise!: () => void; + let rejectPromise!: (reason: unknown) => void; + const promise = new Promise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + return { promise, resolve: resolvePromise, reject: rejectPromise }; +} +``` + +--- + +## Data Access Patterns + +### Zod Schema Validation + +Input validation using Zod with strict object shapes: + +```typescript +const object = (shape: T) => z.object(shape).strict(); + +const PROJECT_PARAMETER_SCHEMAS = { + CONTRACT_INVALID: object({ + tool: tool.optional(), + issue_code: safeCodeV1Schema, + schema_version: safeVersionV1Schema.optional() + }), + RESULT_INVALID: object({ + tool, + result_id: safeIdV1Schema + }), +} as const; +``` + +### AJV JSON Schema Validation + +AJV used alongside Zod for additional schema validation with custom keywords: + +```typescript +import { Ajv2020, type ValidateFunction } from "ajv/dist/2020.js"; +import * as formatsModule from "ajv-formats"; + +export interface JsonSchemaValidator { + readonly validate: ValidateFunction; + readonly assert: (value: unknown, label?: string) => T; +} +``` + +### Plain JSON Assertion + +Helper function to ensure data is plain JSON serializable: + +```typescript +export function assertPlainJson(value: unknown, label: string): void { + if (typeof value === "object" && value !== null) { + const proto = Object.getPrototypeOf(value); + if (proto !== null && proto !== Object.prototype && !Array.isArray(value)) { + throw new TypeError(`${label} must be plain JSON`); + } + } +} +``` + +### Structured Cloning for Data Copies + +```typescript +function copy(value: T): T { + return structuredClone(value as PlainJsonValue) as T; +} + +// Usage: defensive copy of validated input +const startup = deepFreeze(copy(startupSchema.parse(seed))); +``` + +### Type-Only Exports for Contract Boundaries + +```typescript +// Type-only exports make the exact table primitives discoverable without granting authority. +export type ErrorParameterPrimitives = { + readonly digest: Sha256Digest; + readonly tool: ToolName; + readonly phase: PhaseInstanceId; + readonly path: TaskPathClaim; + readonly gate: GateKind; + readonly adapter: AdapterId; + readonly family: ModelFamily; +}; +``` + +--- + +## Testing Framework and Conventions + +### Test Runner: Vitest + +Configuration in `vitest.config.ts`: + +```typescript +export default defineConfig({ + test: { + environment: "node", + include: ["test/**/*.test.ts"], + coverage: { + reportsDirectory: "coverage" + } + } +}); +``` + +### Test Structure + +- Tests co-located in `test/` directory matching source structure +- Test files named with `.test.ts` extension +- Organized by category: `contracts/`, `unit/`, `integration/` +- Fixtures in `test/fixtures/` organized by feature + +### Test Patterns + +```typescript +import { describe, expect, it } from "vitest"; + +describe("transport-neutral contexts", () => { + it("defensively copies, deeply freezes, and initializes once", () => { + const startupSeed = { + connection_id: "connection-1", + startup_repository_candidate: { working_directory: "/work/repo" } + }; + const captured = connectionContextFactory.captureStartup(startupSeed); + startupSeed.startup_repository_candidate.working_directory = "/changed"; + const connection = captured.initialize(candidates); + + expect(connection.startup_repository_candidate.working_directory).toBe("/work/repo"); + expect(Object.isFrozen(connection.initialization_candidates.client)).toBe(true); + expect(() => captured.initialize(candidates)).toThrow(ProtocolContextError); + }); +}); +``` + +### Test Fixtures + +Fixtures stored as JSON files for contract validation: + +``` +test/fixtures/ + contracts/ + mcp-tools/ + state-valid.json + state-invalid-artifact.json + path-claims/ + valid.json + mcp/ + runtime/ + initialize.json + calls.json +``` + +--- + +## Code Formatting and Imports + +### TypeScript Configuration + +Strict compiler settings in `tsconfig.json`: + +```json +{ + "compilerOptions": { + "target": "ES2024", + "lib": ["ES2024"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noEmit": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "verbatimModuleSyntax": true, + "resolveJsonModule": true, + "types": ["node"], + "skipLibCheck": false + } +} +``` + +Key settings: +- **noUncheckedIndexedAccess:** Requires explicit type narrowing for array/object access +- **exactOptionalPropertyTypes:** Distinguishes between optional (`?:`) and `| undefined` +- **verbatimModuleSyntax:** Enforces consistent module syntax (ESM) +- **strict:** Enables strict null checking and implicit any detection + +### Import Organization + +Imports grouped and alphabetized: + +```typescript +// 1. Node built-in imports +import process from "node:process"; +import { Buffer } from "node:buffer"; +import { readFile } from "node:fs/promises"; +import type { Writable } from "node:stream"; + +// 2. Third-party imports +import { z } from "zod"; +import { isDeepStrictEqual } from "node:util"; +import { Ajv2020 } from "ajv/dist/2020.js"; +import * as formatsModule from "ajv-formats"; + +// 3. Local imports with .js extensions (ESM) +import { runMcpProcess } from "./mcp/process-runner.js"; +import { startMcpRuntime } from "./mcp/sdk-adapter.js"; +import type { ConnectionContext } from "./contracts/contexts.js"; +``` + +### ES Modules + +- **Module type:** "module" in package.json +- **File extensions:** Explicit `.js` extensions in imports (ESM requirement) +- **Node version:** >=24.15.0 + +--- + +## Module Conventions + +### Feature-Based Organization + +``` +src/ + contracts/ # Data contract definitions and validation + index.ts # Public API + errors.ts # Error definitions + validators.ts # Validation utilities + contexts.ts # Context types and factories + schemas/ + v1/ # JSON schemas for contracts + mcp/ # MCP protocol implementation + server.ts + session.ts + tools.ts + process-runner.ts + send-queue.ts +``` + +### Public API Pattern + +Index files expose only what clients need: + +```typescript +// src/contracts/index.ts +export { + createInvocationContext, + parseTransportRequestId, + parseClientImplementation, + assertAuthenticInvocationContext, + // NOT exported: connectionContextFactory (internal factory) +} from "./contexts.js"; +``` + +### Private Internal Modules + +Internal implementations use `internal/` subdirectory: + +``` +src/contracts/ + internal/ + test-capabilities.ts # Testing utilities + trust-brands.ts # Branding implementation +``` + +### Type-Safe Exports + +Exports carefully separated into types and implementations: + +```typescript +// Some exports are type-only to control authority +export type ErrorParameterPrimitives = { /* ... */ }; + +// Functions and classes provide the actual capability +export function createProjectError( + code: K, + parameters: z.input<(typeof PROJECT_PARAMETER_SCHEMAS)[K]> +): ErrorValue { } +``` + +--- + +## Key Patterns Summary + +1. **Strict Type Safety:** Branded types with unique symbols prevent invalid states at compile time +2. **Immutable State:** Deep freezing prevents accidental mutations +3. **Explicit Error Handling:** Structured error definitions with Zod schemas ensure consistency +4. **Defensive Copying:** Structured cloning isolates internal state from external changes +5. **Authentication via WeakSet:** Prevents spoofing of critical objects like contexts +6. **Discriminated Unions:** State machines use union types for exhaustive handling +7. **Plain JSON Validation:** Ensures serialization/deserialization safety +8. **Dual Validation:** Both Zod and AJV used for comprehensive schema validation From cd6143415d0910d02888e134d609b50b5583b3e0 Mon Sep 17 00:00:00 2001 From: Jeremy Bird Date: Tue, 28 Jul 2026 13:01:56 -0500 Subject: [PATCH 018/124] MCP Integration Phase 6: Repository Identity, Paths, and Canonical Digests Adds the first filesystem and Git-subprocess layer in src/: canonical JSON, SHA-256 and Git blob-OID primitives, branded ID and path-claim types with hardened lexical rules, a global retightening of task_id/intent_id/gate IDs across every Zod module and JSON Schema, a root-bound Git runner with caller-declared absence, worktree discovery and repository/task identity digests, two path resolvers over a seven-step containment sequence, -z attribute and index readers, porcelain-v2 history and conflict classification, and the fingerprint, config-pinning, and secret-scan contracts. No durable state, no mutation, no new dependency, no new error code. Implementation corrected three design errors: containment step 6 omitted a `rel !== ".."` guard and so accepted the root's own parent; --literal-pathspecs and :(top,literal) are mutually exclusive on git 2.43, so the flag is now prohibited rather than mandated; and --git-common-dir is relative to the process cwd, not the worktree toplevel. The mandated mechanical ID sweep found a fourth round of unlisted sites, where retightening review/triage/adjudication task_id is a vocabulary swap rather than a pure narrowing. Counter-review fixed a blocker where a getter could return one value to the exclusion walk and another to canonicalization, letting an excluded field reach a request digest, and closed a gap where path-unsafe IDs passed the ID schemas but failed path composition. check:release remains blocked: the tracked dist/ payload cannot be re-promoted after any bundle change, because committed decision records are byte-immutable against HEAD, every decision must bind the current bundle digest, and a supersession must retain the superseded decision carrying the old digest. The user re-accepted the fast-uri risk and release:stage passed; only promotion fails. Fixing Phase 5's integrity model is tracked as a follow-up. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01UvSQLKZFe1zaSgWHCQ9zKP --- .../tasks/mcp-integration/architecture.md | 16 +- ...dentity-paths-and-canonical-digests-log.md | 100 +++ ...ry-identity-paths-and-canonical-digests.md | 22 +- .../reviews/phase-6-impl-counter-review.md | 33 + .gitattributes | 5 + CLAUDE.md | 7 + scripts/release-support.d.mts | 12 + src/contracts/adjudication.ts | 7 +- src/contracts/canonical.ts | 142 +++ src/contracts/errors.ts | 19 +- src/contracts/evidence.ts | 45 + src/contracts/fingerprints.ts | 225 +++++ src/contracts/gates.ts | 13 +- src/contracts/index.ts | 3 + src/contracts/mcp-tools.ts | 18 +- src/contracts/path-claims.ts | 84 +- src/contracts/review.ts | 7 +- .../v1/adjudication-evidence.schema.json | 4 +- .../schemas/v1/adjudication.schema.json | 4 +- .../schemas/v1/authority-link.schema.json | 6 +- .../schemas/v1/evidence-slots.schema.json | 4 +- .../schemas/v1/gate-decision.schema.json | 6 +- .../schemas/v1/mcp-tools.schema.json | 38 +- .../schemas/v1/path-claim.schema.json | 3 +- .../schemas/v1/primitives.schema.json | 9 + .../schemas/v1/project-error.schema.json | 54 +- .../schemas/v1/result-expectation.schema.json | 6 +- .../schemas/v1/review-evidence.schema.json | 4 +- src/contracts/schemas/v1/review.schema.json | 4 +- .../schemas/v1/secret-scan-result.schema.json | 84 ++ .../v1/supplemental-review.schema.json | 13 +- src/contracts/schemas/v1/triage.schema.json | 4 +- src/contracts/secret-scan.ts | 96 ++ src/contracts/supplemental.ts | 11 +- src/contracts/triage.ts | 7 +- src/contracts/trust.ts | 20 +- src/contracts/validators.ts | 16 + src/contracts/versions.ts | 3 +- src/repository/attributes.ts | 133 +++ src/repository/git.ts | 333 +++++++ src/repository/history.ts | 413 +++++++++ src/repository/identity.ts | 328 +++++++ src/repository/index-entries.ts | 170 ++++ src/repository/index.ts | 15 + src/repository/paths.ts | 484 ++++++++++ test/contracts/canonical-parity.test.ts | 130 +++ .../gate-error-schema-agreement.test.ts | 4 +- ...gate-error-supplemental-exhaustive.test.ts | 8 +- test/contracts/mcp-advertised-schema.test.ts | 19 +- test/contracts/mcp-contract-agreement.test.ts | 12 +- test/contracts/repository-boundary.test.ts | 107 +++ test/contracts/schema-registry.test.ts | 1 + ...shared-primitives-schema-agreement.test.ts | 37 +- .../fingerprints/config-reordered.yaml | 8 + .../contracts/fingerprints/config.yaml | 8 + .../mcp/catalogue/classified-corpus.json | 1 + test/helpers/temp-repository.ts | 201 +++++ .../integration/repository-git-matrix.test.ts | 581 ++++++++++++ test/unit/canonical.test.ts | 294 ++++++ test/unit/errors.test.ts | 18 + test/unit/evidence.test.ts | 122 ++- test/unit/fingerprints.test.ts | 246 +++++ test/unit/gates.test.ts | 9 + test/unit/mcp-tools.test.ts | 110 ++- test/unit/path-claims.test.ts | 158 +++- test/unit/renderers.test.ts | 13 +- test/unit/repository-git.test.ts | 367 ++++++++ test/unit/repository-history.test.ts | 494 +++++++++++ test/unit/repository-identity.test.ts | 424 +++++++++ test/unit/repository-index.test.ts | 586 ++++++++++++ test/unit/repository-paths.test.ts | 838 ++++++++++++++++++ test/unit/secret-scan.test.ts | 94 ++ test/unit/supplemental.test.ts | 15 +- test/unit/triage.test.ts | 11 +- test/unit/trust.test.ts | 45 +- 75 files changed, 7776 insertions(+), 215 deletions(-) create mode 100644 .archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests-log.md create mode 100644 .archflow/tasks/mcp-integration/reviews/phase-6-impl-counter-review.md create mode 100644 scripts/release-support.d.mts create mode 100644 src/contracts/canonical.ts create mode 100644 src/contracts/fingerprints.ts create mode 100644 src/contracts/schemas/v1/secret-scan-result.schema.json create mode 100644 src/contracts/secret-scan.ts create mode 100644 src/repository/attributes.ts create mode 100644 src/repository/git.ts create mode 100644 src/repository/history.ts create mode 100644 src/repository/identity.ts create mode 100644 src/repository/index-entries.ts create mode 100644 src/repository/index.ts create mode 100644 src/repository/paths.ts create mode 100644 test/contracts/canonical-parity.test.ts create mode 100644 test/contracts/repository-boundary.test.ts create mode 100644 test/fixtures/contracts/fingerprints/config-reordered.yaml create mode 100644 test/fixtures/contracts/fingerprints/config.yaml create mode 100644 test/helpers/temp-repository.ts create mode 100644 test/integration/repository-git-matrix.test.ts create mode 100644 test/unit/canonical.test.ts create mode 100644 test/unit/fingerprints.test.ts create mode 100644 test/unit/repository-git.test.ts create mode 100644 test/unit/repository-history.test.ts create mode 100644 test/unit/repository-identity.test.ts create mode 100644 test/unit/repository-index.test.ts create mode 100644 test/unit/repository-paths.test.ts create mode 100644 test/unit/secret-scan.test.ts diff --git a/.archflow/tasks/mcp-integration/architecture.md b/.archflow/tasks/mcp-integration/architecture.md index 9eafdc12..c01332b7 100644 --- a/.archflow/tasks/mcp-integration/architecture.md +++ b/.archflow/tasks/mcp-integration/architecture.md @@ -508,14 +508,16 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali **Scope**: Implement Git/worktree and task identity; `.archflow/** -text merge=binary` with runtime attribute verification; task-relative and repository-relative path claims, path classes, and filesystem containment; canonical JSON, canonical Git blob/tree-mode identity, and request/declared-input digests; exact whole-file `config.yaml` digest pinning; divergence, conflict, and in-progress-operation detection; and the secret-scan result contract. This phase introduces the first filesystem and Git-subprocess code in `src/`. It implements no durable state or artifact schema, no state mutation, no payload restore, and no secret-scanning engine, and adds no runtime dependency. +**Implemented 2026-07-28.** Three design errors were corrected during implementation and are recorded in the phase log: containment step 6 omitted a `rel !== ".."` guard and therefore accepted the root's own parent; `--literal-pathspecs` and `:(top,literal)` are mutually exclusive on git 2.43, so the flag is now prohibited rather than mandated; and `--git-common-dir` is relative to the process cwd, not the worktree toplevel. The global ID retightening reached a fourth round of previously unlisted sites (`review.ts`, `triage.ts`, `adjudication.ts`, `errors.ts`, `authority-link.schema.json`), where it is a vocabulary swap rather than a pure narrowing. `npm run check:release` remains blocked, but **not** on the risk re-acceptance, which the user granted and which `release:stage` accepted. Promotion fails because three invariants in `scripts/release-support.mjs` cannot co-exist across a bundle change: committed decision records are byte-immutable against HEAD (`:1380`), every decision must bind the current bundle digest (`:803`), and a supersession must retain the superseded decision (`:676-677`) — which necessarily carries the old digest. The tracked `dist/` payload therefore cannot be re-promoted after any bundle change; Phase 5 created the initial release, so this path was never exercised. Fixing Phase 5's integrity model is tracked as a follow-up. + **Success Criteria**: -- [ ] Traversal, absolute paths, drive-relative and UNC inputs, symlink escape, cross-task access, pathspec metacharacters, and repository-identity mismatch fail before any read, while linked worktrees, relocation, spaces, and Unicode pass. -- [ ] Committed inputs and tracked outputs have identical canonical Git blob/tree identities across LF/CRLF worktrees, `core.autocrlf`, `core.fileMode`, executable-bit support, and symlink-capable/incapable checkouts; unsupported materialization fails closed. -- [ ] The whole `config.yaml` file is pinned by exact digest, and any byte change is detected as `PINNED_CONFIG_MISMATCH` with expected/observed digests and no config content. -- [ ] The canonical request digest is computed from its closed field list only, and logically set-valued fingerprint collections hash identically under any input permutation. -- [ ] Startup and pull/handoff detection identifies divergent histories and `.archflow/**` conflicts as non-authoritative without claiming it can detect independent-clone concurrency before divergence. -- [ ] Every Git invocation is bound to the discovered worktree root, so no command can silently report an absent path or attribute because of the caller's working directory. +- [x] Traversal, absolute paths, drive-relative and UNC inputs, symlink escape, cross-task access, pathspec metacharacters, and repository-identity mismatch fail before any read, while linked worktrees, relocation, spaces, and Unicode pass. +- [x] Committed inputs and tracked outputs have identical canonical Git blob/tree identities across LF/CRLF worktrees, `core.autocrlf`, `core.fileMode`, executable-bit support, and symlink-capable/incapable checkouts; unsupported materialization fails closed. +- [x] The whole `config.yaml` file is pinned by exact digest, and any byte change is detected as `PINNED_CONFIG_MISMATCH` with expected/observed digests and no config content. +- [x] The canonical request digest is computed from its closed field list only, and logically set-valued fingerprint collections hash identically under any input permutation. **Limitation recorded**: the closed list is enforced by an exact-name denylist over an open `operation_fields`, so alternate spellings of volatile state are not caught; a closed per-operation allowlist is owned by the phase that defines operation field sets. +- [x] Startup and pull/handoff detection identifies divergent histories and `.archflow/**` conflicts as non-authoritative without claiming it can detect independent-clone concurrency before divergence. +- [x] Every Git invocation is bound to the discovered worktree root, so no command can silently report an absent path or attribute because of the caller's working directory. ### Phase 7: Durable State and Artifact Schemas @@ -795,7 +797,7 @@ All v1 requirements `REQ-01` through `REQ-41` and `REQ-50`, and all release vali | 3 | MCP Contract Boundary and Dependency Admission | COMPLETE (2026-07-27) | | 4 | Guarded MCP Runtime and SDK Compatibility | COMPLETE (2026-07-27) | | 5 | Offline Bundle and Release Integrity | COMPLETE (2026-07-28) | -| 6 | Repository Identity, Paths, and Canonical Digests | Not Started | +| 6 | Repository Identity, Paths, and Canonical Digests | COMPLETE (2026-07-28) | | 7 | Durable State and Artifact Schemas | Not Started | | 8 | Transaction Kernel, Intent/CAS, and Crash Recovery | Not Started | | 9 | Snapshots, Implementation Manifests, and Restore | Not Started | diff --git a/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests-log.md b/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests-log.md new file mode 100644 index 00000000..4c7b5970 --- /dev/null +++ b/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests-log.md @@ -0,0 +1,100 @@ +## Implementation Log: Phase 6 - Repository Identity, Paths, and Canonical Digests + +**Implemented**: 2026-07-28 +**Status**: COMPLETE +**Requirements advanced**: REQ-04, REQ-05, REQ-13, REQ-26 (none completed — see the design's opening note) + +### Decisions Made + +- Kept the directional rule absolute: pure computation in `src/contracts/`, all `git`/`node:fs` in the new `src/repository/` tree. `src/contracts/**` never imports `src/repository/**`, and the repository barrel is never re-exported from the contracts barrel. `test/contracts/repository-boundary.test.ts` asserts this structurally rather than by convention, scanning import specifiers rather than raw text. +- Made every unsafe state unrepresentable with brands instead of documenting it: `TaskSlug`, `PathSafeId`, `TaskPathClaim`, `RepositoryPathClaim`, `RawGitPath`, `GitOid`, `ResolvedTaskPath`, and `RootBoundGitRunner`. Discovery returns the *runner*, not a location, so there is no way to keep using an unbound one; `tryRepositoryPathClaim` is the sole promotion from Git output to a claim and returns `undefined` rather than throwing so callers can count what they cannot represent. +- Withdrew `exit 128 ⇒ absent` as unsafe. Every command declares its own `ExpectedAbsence{code, stderrIncludes}`, and a nonzero exit is absence only when both the code and the diagnostic substring match. A dubious-ownership or corrupt-repository 128 now produces `IO_ERROR`, not a silent empty answer. +- Centralised the failure translation in one exported `projectErrorForGitFailure` rather than letting each of chunks 5–8 re-derive it. The design pinned the failure map but no function for it; five independent authors would have produced five encodings of the same error. +- Recorded the `--literal-pathspecs` finding as a permanent prohibition rather than a one-off workaround, because the natural instinct is to "harden" the call by adding the flag back. +- Chose the denylist limitation over a speculative subsystem for request-digest exclusions (counter-review finding 3). See Gotchas. + +### Deviations from Plan + +- **Containment step 6 was wrong in the design and is now corrected.** The pinned condition omitted `rel !== ".."`, and `"..".startsWith("../")` is `false`, so it *accepted the root's own parent* — the exact escape the check exists to prevent. `release-support.mjs`'s private `isInside` carries the guard; this design had dropped it. Added with a regression test; the design document is updated. +- **`--literal-pathspecs` and `:(top,literal)` are mutually exclusive.** The flag disables pathspec magic, so the magic prefix is then matched as a literal filename and selects nothing (reproduced on git 2.43: empty output). Placed after the subcommand, `ls-files` and `check-attr` reject it outright. `check-attr` takes pathnames, not pathspecs, so it needs neither. Kept `:(top,literal)` alone, which supplies both literal matching and root anchoring. The design's success criterion was unsatisfiable as written and is corrected. +- **`--git-common-dir` is relative to the process cwd, not the worktree toplevel.** From `repo/nested/deeper` it returns `../../.git`; resolving that against the toplevel lands two levels above the repository and produced a real `IO_ERROR`. Both values are now queried through one `git -C rev-parse --git-dir --git-common-dir`, which makes the design's stated resolution rule true in every case. `--path-format=absolute` was still rejected — it would raise the version floor to ~2.31. +- **The ID inventory was incomplete for a fourth time**, which is why the mechanical sweep is mandated. Additional sites retightened: `review.ts`, `triage.ts`, `adjudication.ts` and their five schemas; `errors.ts` (`task_id` on `taskPathClass`/`TASK_INVALID`, `gate_id` at five further codes); `authority-link.schema.json`; four more `trust.ts` `task_id` interface fields; two more `mcp-tools.schema.json` `task_id` sites. Named but non-existent: `input_id` (zero occurrences repository-wide) and `prior_gate_id` in `mcp-tools.ts`. +- **At `review.ts`/`triage.ts`/`adjudication.ts` the retightening is a vocabulary swap, not a narrowing.** Those `task_id` fields used a local kebab-only pattern (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`), not `safeId`. `TaskSlug` caps length at 64 but newly admits `.`, `_`, and a leading digit. Applied for consistency with "global per logical ID, no exceptions"; flagged at the human gate. +- **`.gitattributes` is a tracked release control**, so chunk 1's rule forced a `dist/manifest.json` regeneration the Files table never anticipated. See Gotchas for the larger consequence. +- **`step 3` also uses the nearest-existing-ancestor walk.** The task root `.archflow/tasks//` legitimately does not exist before task initialization, and a bare `realpath(root)` turned every pre-init resolution into `IO_ERROR`. +- **`TaskSlug`/`PathSafeId` gained the reserved-device and trailing-dot rules** after counter-review finding 2. The pinned regexes accepted `con`, `task.`, `CON`, `gate.`, `PRN.txt` — all rejected at path composition, recreating the exact mismatch these types were introduced to prevent. The two predicates now live in `evidence.ts` and are imported by `path-claims.ts`, so the two authorities cannot drift. +- Added one exported symbol beyond the pinned lists per module where the design pinned behaviour but no function: `projectErrorForGitFailure` (chunk 4), `ARCHFLOW_ATTRIBUTES_REMEDIATION` (chunk 7), `secretFindingV1Schema` (chunk 9). + +### Patterns Established + +- **Brands are minted by exactly one function and the brand symbol is module-private.** `RootBoundGitRunner` is the strongest instance: only `discoverWorktree` can mint one, so "run a repository query from an arbitrary cwd" is a compile error, not a review comment. +- **Errors carry an explicit `RepositoryOperationContext`, never one the reader invents.** Every project error these readers promise needs parameters no Git command returns (`task_id`, `phase_instance`, `operation`, `attempt`). Any new reader takes the context as an argument. +- **Shared digest helpers are pinned so two chunks cannot construct the same error differently** — `historyIdentityDigest` and `repositoryCandidateDigest`. Never re-derive a digest inline; `GIT_DIVERGED` hashes OIDs through the shared helper because `PROJECT_PARAMETER_SCHEMAS` requires 64 hex characters. +- **Digest inputs are validated and materialized once, then never re-read.** `computeInputFingerprint` and `computeRequestDigest` call `assertPlainJson` then `structuredClone` on the whole subject as their first statement; every later step reads the detached clone. Any future digest function must do the same — see Gotchas. +- **Three-way failure convention, applied without exception**: parsers and assertion helpers throw; orchestrating readers (anything that runs a git command or touches the filesystem) return `ProjectResult`; pure derivations return their value directly. +- **Zod and JSON Schema edits are one indivisible change**, because `assertZodAgreement` compares them. This now includes the *inline mirrors*: eight schemas duplicate the ID patterns literally, and updating only `primitives.schema.json` reintroduces the drift. +- **Set-valued collections are sorted and duplicate-checked before hashing.** `canonicalJsonBytes` sorts object keys but preserves array order, so an unsorted collection lets two callers hash identical logical inputs to different fingerprints. + +### Gotchas + +- **`--literal-pathspecs` silently returns nothing when combined with `:(top,literal)`.** No error, empty output. Anyone "hardening" a git call by adding the flag will break the readers invisibly. +- **`check-attr -z` emits NUL triplets, not lines**: exactly 6N NUL-terminated fields for N paths and two attributes. Any other count is treated as a mismatch rather than best-effort parsed. +- **`ls-files -s -z` fields are ` \t`** — split on NUL first, then on the single tab. Never split the path on whitespace. +- **Running a reader from a subdirectory is a silent wrong answer, not an error.** From `repo/sub`, `ls-files` returns nothing and `check-attr` reports `text: auto`. This is why the root-bound runner exists. +- **`git rev-parse --show-superproject-working-tree` exits 0 whether or not there is a superproject** — the submodule test is for empty output, not exit code. +- **`fsPromises.realpath.native` is `undefined`** even though `fs.realpath.native` and `fs.realpathSync.native` exist. +- **`O_NOFOLLOW` does not exist on Windows**, so containment step 7 is a no-op there and the symlink defence rests entirely on steps 3–6. Containment is check-then-use with an inherent TOCTOU window: Node 24 has no `openat`-style API, no `O_PATH`, no `O_RESOLVE_BENEATH`, and no equivalent of Go's `os.Root`. +- **`assertPlainJson` already rejects accessor properties**, which is what made the counter-review blocker cheap to fix. Before the fix, a getter could return a safe object to the exclusion walk and an excluded field to canonicalization, so `computeRequestDigest` returned a digest containing `intent_id` instead of throwing. Any function that inspects a caller-owned object more than once has this bug. +- **KNOWN LIMITATION — the request-digest denylist is not category-complete.** `operation_fields` is an open `PlainJsonObject`, so exact-name exclusion cannot catch `started_at`, `attempt_number`, `retry_reason`, `timed_out`, and similar spellings; two callers can encode the same volatile state under different names and disagree. The correct fix is a closed per-operation allowlist, which Phase 6 cannot build because it defines no operations. **Owner: the phase that defines per-operation request field sets** must replace the denylist and delete the note in `fingerprints.ts`. +- **The Windows-specific rules are verified lexically only.** CI is `ubuntu-latest`; trailing-dot/space stripping, reserved device names as real filesystem aliases, and `O_NOFOLLOW`'s absence are never exercised against a real Win32 filesystem. +- **Orphan branches remain a documented limitation.** Checking out an orphan branch changes HEAD's root set and surfaces as `REPOSITORY_MISMATCH`, which is the intended behaviour. +- **`.gitattributes` is in `REQUIRED_CONTROLS`**, so touching it invalidates the tracked release payload — and regenerating that payload is gated on a risk-decision re-binding, not a mechanical rebuild. Any phase that edits a release control input inherits that gate. Node `24.15.0`/`24.18.0` were absent again and had to be installed; the ambient `24.11.1` is below the `>=24.15.0` engines floor. +- **Beware abandoned `build-release.mjs` processes.** Four orphaned runs (PPID 1) from a prior session were found pinning four cores for 4h17m. The script does not die with its parent and has no wall-clock timeout, so an interrupted agent leaves a full release build spinning. Recorded as a follow-up, not fixed here. + +### Key Interfaces + +- `src/contracts/canonical.ts`: `GitOid`/`parseGitOid`/`gitOidV1Schema`, `GIT_TREE_MODES`/`GitTreeMode`/`ArchflowTreeMode`/`parseGitTreeMode`/`normalizeGitTreeMode`, `canonicalJsonBytes`, `sha256Bytes`, `canonicalJsonDigest`, `gitBlobOid`, `historyIdentityDigest`, `repositoryCandidateDigest`, `CanonicalDocument`, `canonicalDocument`, `parseCanonicalDocument`. +- `src/contracts/evidence.ts`: adds `PathSafeId`/`pathSafeIdV1Schema`/`parsePathSafeId` and `TaskSlug`/`taskSlugV1Schema`/`parseTaskSlug`, plus the shared `isReservedDeviceName` and `endsWithDotOrSpace` predicates that `path-claims.ts` imports. The pre-existing `safeId` is unchanged. +- `src/contracts/path-claims.ts`: `TaskPathClaim`, `RepositoryPathClaim`, `RawGitPath`, `rawGitPath`, `tryRepositoryPathClaim`, `toRepositoryPathClaim`, `TASK_PATH_CLASSES` (13), `REPOSITORY_PATH_CLASSES` (4), `PATH_CLASSES` (17), `READ_ONLY_PATH_CLASSES`, `parsePathClass`. +- `src/contracts/fingerprints.ts`: `computeInputFingerprint(InputFingerprintSubject)`, `computeRequestDigest(RequestDigestSubject)`, `EXCLUDED_REQUEST_DIGEST_FIELDS`, `computePinnedConfigDigest(bytes)`, `verifyPinnedConfig(expected, observedBytes)`, `DeclaredInputRef`, `GitIdentityRef`. +- `src/contracts/secret-scan.ts`: `SecretScanCandidate`, `SecretFinding`, `SecretScanResult` (clean/detected/unavailable), `secretScanResultV1Schema`, `parseSecretScanResult`, `SecretScanner` — contract only, no engine. Schema `urn:archflow:schema:v1:secret-scan-result`. +- `src/repository/git.ts`: `createGitRunner({cwd, gitPath?, maxBuffer?, timeoutMs?})`, `GitRunner{cwd, run, runText, runNulFields}`, `GitCommandSpec`, `ExpectedAbsence`, `GitInvocationError`, `GitFailureKind`, `preflightGit(runner, context)`, `GitEnvironment`, `RepositoryOperationContext`, `projectErrorForGitFailure(error, runner, context)`. +- `src/repository/identity.ts`: `discoverWorktree(runner, context) → ProjectResult`, `WorktreeLocation`, `RootBoundGitRunner`, `resolveRepositoryIdentity(runner, environment, context)`, `verifyRepositoryIdentity(expected, observed)`, `computeTaskIdentity(taskId, repository)`, `RepositoryIdentity`, `TaskIdentity`. +- `src/repository/paths.ts`: `classifyTaskPath`, `classifyRepositoryPath`, `resolveTaskPath`, `resolveRepositoryPath`, `openResolved(path, flags)`, `ResolvedTaskPath`, `ResolvedPath`. +- `src/repository/attributes.ts`: `ARCHFLOW_GITATTRIBUTES_RULE`, `ARCHFLOW_ATTRIBUTES_REMEDIATION`, `AttributeCheck`, `checkArchflowAttributes(runner, paths, context)`. +- `src/repository/index-entries.ts`: `IndexEntry`, `readIndexEntries(runner, paths, context)`, `assertArchflowIndexEntry(entry)`. +- `src/repository/history.ts`: `readHistoryStatus(runner, context)`, `classifyMutationReadiness(status, context) → ProjectResult`, `WorktreeHistoryStatus`, `UpstreamState`, `IN_PROGRESS_OPERATIONS`, `InProgressOperation`. +- `src/repository/index.ts`: the sole repository barrel, 39 symbols, created once by chunk 8. +- `test/helpers/temp-repository.ts`: `createTempRepository({label, directoryName, attributes, config})` with `write`/`chmod`/`commitAll`/`hashObject`/`git`/`addWorktree`/`relocate`/`forceConflict`, plus `cleanupTemporaryRepositories` and `gitAvailable`. + +### Verification + +- Full aggregate green under exact Node `24.15.0` and `24.18.0` except the one blocked step below: `probe:phase4-mcp-compatibility`, `typecheck`, `test:mcp-runtime` (99), `test:contracts` (102), `build:temp`, `check:dependencies`, `check:notices`, `test:notices-policy`, `check:phase4-mcp-boundary`, `test:phase4-mcp-boundary-policy` all pass. +- 635 of 638 tests pass, up from 383 before the phase. The 3 failures are `test/integration/release-offline.test.ts` "stale bundle input". +- Counter-review findings 1 and 2 were reproduced independently before triage and re-verified after fixing. Finding 1's secondary claim (same subject hashing differently across consecutive calls) did **not** reproduce; the split-observation defect it points at is real and was fixed regardless. +- Integration suite runtime is ~0.7 s of test time and leaves no `/tmp` residue. + +### Blocked at Phase Close — a contradiction in the release integrity model + +`npm run check:release` cannot pass, and **the blocker is not the risk re-acceptance.** The user explicitly re-accepted the `fast-uri-3-1-0-local-risk` decision for this bundle. The re-binding was then attempted end to end and **`release:stage` passed** with the rebound records. Promotion is what fails: `release:write` aborts with `HEAD dependency_gate_decisions record changed or disappeared: fast-uri-3-1-0-local-risk`. + +Three invariants in `scripts/release-support.mjs` cannot all hold across a bundle change: + +1. `:1380` — every decision record committed at HEAD must remain **byte-identical** in the candidate. So a decision cannot be edited in place. +2. `:803` — **every** decision in `dependency_gate_decisions` must satisfy `decision.bundle_digest === manifestValue.bundle_digest`, i.e. bind the *current* bundle. +3. `:676-677` — a supersession requires **both** the superseded and the replacement decision to remain in `dependency_gate_decisions`. + +In-place re-binding violates (1). The supersession mechanism, which exists precisely for this, violates (2) — the retained superseded record necessarily carries the *old* bundle digest, so it can never satisfy the every-decision check. An amendment does not help either: `:673` binds it to an unchanged decision digest, leaving the stale `bundle_digest` in place to fail (2). `write-tracked-release.mjs` has no override flag. + +**Consequence: the tracked `dist/` payload cannot be re-promoted after any bundle change.** This is the first time that has been attempted — Phase 5 *created* the initial tracked release, so the re-promotion path was never exercised. The measured values are recorded for whoever fixes it: old bundle `16faf636…`, new bundle `dec8044b…`, and `dependency_inventory_digest` **unchanged** at `1f93c687…`, confirming no dependency change. + +All attempted edits to `release/` and `dist/` were reverted; both are at HEAD. Fixing this means changing Phase 5's integrity model — most plausibly by scoping (2) to non-superseded decisions — which is a deliberate design decision about legal-record semantics, not an expedient patch to land mid-commit. **Recorded as the top follow-up, out of Phase 6 scope.** The three failing `test/integration/release-offline.test.ts` cases are this one issue. + +### Durable Convention Proposal + +Two rules outlive this task and belong in the project's `CLAUDE.md`, since `.archflow/` is deleted before PR: + +1. **Never pass `--literal-pathspecs` to a Git invocation that uses a `:(top,literal)` pathspec.** The flag disables pathspec magic, so the prefix is matched as a literal filename and the command silently selects nothing. +2. **Validate and materialize a caller-owned object once before inspecting it more than once.** Use `assertPlainJson` then `structuredClone`; an enumerable getter can otherwise return different values to a validation pass and a hashing pass. + +Everything else recorded here is specific to this task and stays in this log. diff --git a/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests.md b/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests.md index e7b96114..375496c0 100644 --- a/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests.md +++ b/.archflow/tasks/mcp-integration/phases/phase-6-repository-identity-paths-and-canonical-digests.md @@ -1,6 +1,6 @@ # Phase 6: Repository Identity, Paths, and Canonical Digests -**Status**: DESIGNED +**Status**: IN PROGRESS **Task**: mcp-integration **Goal**: Establish the repository/task identity, path safety, immutable task configuration pinning, and byte-stable digest contracts used by every mutation. **Requirements completed**: none @@ -162,7 +162,9 @@ export function parsePathClass(value: unknown): PathClass; Zod and JSON Schema are compared by `assertZodAgreement`, so **every Zod edit and its JSON Schema counterpart are a single indivisible change**. Retightening one side alone fails the agreement tests on the first colon or uppercase sample. -**Read this before using the list below.** This inventory has been found incomplete three times across successive reviews. **It is a cross-check, not an authority.** The implementing chunk must **regenerate it mechanically** — grep every occurrence of each logical ID name across all Zod modules in `src/contracts/`, every exported TypeScript interface, all 24 normative JSON Schemas, the advertised-schema closure, and every fixture under `test/` — then reconcile the generated set against the prose list. **Any difference is a design defect to report back, not something to silently absorb**, in either direction: a site the list omits, and a site the list names that no longer exists. +**Read this before using the list below.** This inventory has been found incomplete three times across successive reviews — and a **fourth** time by the mandated mechanical sweep at implementation time, which is exactly why the sweep is mandated. **It is a cross-check, not an authority.** + +**The fourth-round delta, recorded so it is durable.** Sites the prose list omitted, all real and all retightened: `review.ts`, `triage.ts`, and `adjudication.ts` plus their five schemas; `errors.ts` `task_id` (`taskPathClass`, `TASK_INVALID`) and `gate_id` at five further codes; `authority-link.schema.json`; four more `trust.ts` `task_id` interface fields; and two `mcp-tools.schema.json` `task_id` sites beyond the six enumerated (`waiverOrigin.task_id` and the waiver-success `task_id`). Sites the prose list named that **do not exist**: `input_id` has zero occurrences anywhere in the repository, and `prior_gate_id` does not appear in `mcp-tools.ts`. **One consequence needs a human's eye:** at `review.ts`/`triage.ts`/`adjudication.ts` the pre-existing `task_id` used a *local kebab-only* pattern (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`), not `safeId`, so retightening there is a **vocabulary swap rather than a pure narrowing** — it caps length at 64 but newly admits `.`, `_`, and a leading digit. The implementing chunk must **regenerate it mechanically** — grep every occurrence of each logical ID name across all Zod modules in `src/contracts/`, every exported TypeScript interface, all 24 normative JSON Schemas, the advertised-schema closure, and every fixture under `test/` — then reconcile the generated set against the prose list. **Any difference is a design defect to report back, not something to silently absorb**, in either direction: a site the list omits, and a site the list names that no longer exists. Retightening is **global per logical ID**. There are no per-site exceptions: @@ -349,7 +351,7 @@ export interface TaskIdentity { export function computeTaskIdentity(taskId: TaskSlug, repository: RepositoryIdentity): TaskIdentity; ``` -**The root-bound runner closes a silent-wrong-answer hole, reproduced.** From a subdirectory `repo/sub`, `git ls-files -s -- .archflow/…` returns **nothing** and `git check-attr text merge -- .archflow/…` returns `text: auto` / `merge: unspecified` — no error in either case, just the wrong answer. Spelling it `../.archflow/…` finds the file but emits a path that can never be a valid `RepositoryPathClaim`. Making every reader below discovery accept only `RootBoundGitRunner` removes the possibility structurally rather than by convention. All pathspecs are top-anchored and literal — `:(top,literal)` with `--literal-pathspecs` — and every reader **asserts that each returned path is exactly equal to the requested claim**, producing `TASK_INVALID{issue_code:"git-path-mismatch"}` otherwise. +**The root-bound runner closes a silent-wrong-answer hole, reproduced.** From a subdirectory `repo/sub`, `git ls-files -s -- .archflow/…` returns **nothing** and `git check-attr text merge -- .archflow/…` returns `text: auto` / `merge: unspecified` — no error in either case, just the wrong answer. Spelling it `../.archflow/…` finds the file but emits a path that can never be a valid `RepositoryPathClaim`. Making every reader below discovery accept only `RootBoundGitRunner` removes the possibility structurally rather than by convention. All pathspecs are top-anchored and literal via the `:(top,literal)` magic prefix — **not** `--literal-pathspecs`, which is mutually exclusive with it (see chunk 7) — and every reader **asserts that each returned path is exactly equal to the requested claim**, producing `TASK_INVALID{issue_code:"git-path-mismatch"}` otherwise. ### `src/repository/paths.ts` — chunk 6 @@ -418,7 +420,9 @@ export function openResolved(path: ResolvedTaskPath, flags: number): Promise