From 54073e4db13a1cd5c13696f79b4616ee4c89fc76 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sat, 7 Nov 2026 20:16:12 -0500 Subject: [PATCH 1/2] feat: commit draft content and private sources atomically --- AGENTS.md | 24 +- README.md | 34 +- docs/AGENT_API.md | 12 +- docs/AGENT_WORKFLOW.md | 16 +- docs/BOOTSTRAP.md | 73 ++- docs/COLLECTIONS.md | 23 +- docs/HOST_COMPOSITION.md | 34 +- docs/RELEASING.md | 32 +- docs/RETRIEVAL.md | 11 +- docs/SOURCE_PREPARATION.md | 40 +- examples/agent/README.md | 2 +- examples/composition/README.md | 8 +- package.json | 8 +- packages/application/README.md | 32 +- packages/application/package.json | 6 +- packages/application/src/articles.ts | 40 +- packages/application/src/types.ts | 4 + packages/contracts/package.json | 2 +- packages/core/package.json | 4 +- packages/mcp/README.md | 10 +- packages/mcp/package.json | 8 +- packages/mcp/src/mcp.ts | 2 +- packages/mcp/src/types.ts | 5 +- pnpm-lock.yaml | 20 +- test/README.md | 6 +- test/atomic-draft-sources-fixtures.ts | 63 +++ tests/agent-source-boundary.test.ts | 130 +++++ tests/atomic-draft-sources.test.ts | 689 ++++++++++++++++++++++++++ 28 files changed, 1198 insertions(+), 140 deletions(-) create mode 100644 test/atomic-draft-sources-fixtures.ts create mode 100644 tests/agent-source-boundary.test.ts create mode 100644 tests/atomic-draft-sources.test.ts diff --git a/AGENTS.md b/AGENTS.md index 98dcdc7..f9b19c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,9 +20,12 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. slices are merged. The partial slice adds local D1 conformance and a public synthetic composition; the release slice adds exact-artifact tooling. All four `0.1.0` packages completed manual maintainer bootstrap with exact-byte - postflight on 2026-11-07, without OIDC provenance. Source `0.1.1` is a candidate - for the first advertised trusted release; its review, publication, strict - registry/provenance verification, and host acceptance remain gates. + postflight on 2026-11-07, without OIDC provenance. All four `0.1.1` packages + subsequently completed verified trusted publication; retain the + [release receipt](docs/BOOTSTRAP.md#verified-knowledge-base-release). + Source `0.1.2` is the SD-03 atomic draft/source candidate and still requires + its own review, current-head gates, trusted publication, and strict verification. + Real-host acceptance remains separate. - Never implement a database, authorization role model, identity/session/token system, audit log, request limiter, or durable scheduler here. Compose the corresponding Pegma package in the owning later task. @@ -39,6 +42,13 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. enforces named permissions and current KB resources; the host authenticates access contexts and evidence/source facts. Caller-supplied proof fields do not establish that trust. +- Direct host `createDraft`/`updateDraft` may supply complete `sourceReferences` + atomically with content. Presence, including `[]`, requires `draftWrite` and + `provenanceWrite`; every reference needs current source-read authority on + conflict retry and replay. Initial HTTP/MCP schemas reject the field and + expose no new scope or tool. SD-03 hosts must always supply a complete + nonempty set; omission retains legacy behavior and does not close its source + window. Readability does not establish publication eligibility/currentness. - KB-02 article heads are normalized; content/evidence/publication history is immutable and bounded. Application generation fences every state change, independently of content revision. Same-partition CAS, Audit, receipts, and @@ -99,8 +109,8 @@ tarballs. Independently retain its SHA-256 digest; never trust a digest taken only from the downloaded artifact. Preflight all four registry versions before any publish, and recover only by accepting byte-identical existing artifacts. See [release operations](docs/RELEASING.md) and the -[first-publication handoff](docs/BOOTSTRAP.md) for the completed manual bootstrap -receipt and pending trusted release. All five KB/Agent Access trusted publishers +[publication ledger](docs/BOOTSTRAP.md) for the completed manual bootstrap +and verified trusted `0.1.1` receipts. All five KB/Agent Access trusted publishers have been configured through the CLI; that configuration does not prove a trusted publish. Recheck ownership, signer, tag, approval environment, direct publishing, and 2FA/token restrictions for the release. OIDC publishing receives only verified prepared @@ -116,8 +126,8 @@ packed KB candidate artifacts and the official SDK in a fresh temporary consumer with lifecycle scripts disabled. It accepts no source-producer fallback. Historical source-fixture evidence is not evidence for changed proof code; current-head Node 22/24 gates must execute the registry composition. The KB -`0.1.1` candidate's own review, publication, strict registry verification, and -host acceptance remain open before real host assembly. +`0.1.2` candidate's own review, trusted publication, and strict registry +verification remain open. Host acceptance remains open before activation. Keep actual existing-login/Admin-consent and every requested client/mode proof open in P-00 and PG-01/RG-01 until both hosts record them before activation. diff --git a/README.md b/README.md index 64329dc..5feefad 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,12 @@ and exact publication approval. It requires no GitHub connection or AI provider. > [release-preparation source](https://github.com/pegma-dev/knowledge-base/pull/6) > supplies exact-artifact tooling. Both are merged. All four `0.1.0` packages > completed manual bootstrap with exact-byte postflight on 2026-11-07, without -> OIDC provenance. Source `0.1.1` is a candidate for the first advertised trusted -> release. Its review, publication, strict registry/provenance verification, -> and actual two-host existing-login/client acceptance remain separate gates. -> This repository is not an operational hosted KB or a production dependency. +> OIDC provenance. All four `0.1.1` packages subsequently completed +> [verified trusted publication](docs/BOOTSTRAP.md#verified-knowledge-base-release). +> Source `0.1.2` is the SD-03 atomic draft/source candidate; its own review, +> current-head gates, trusted release, and strict registry/provenance verification +> remain required. Actual two-host existing-login/client acceptance remains open. +> Host activation remains separately gated; this repository supplies no hosted KB. | Package | Scope | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | @@ -68,6 +70,17 @@ Read [declared collections](docs/COLLECTIONS.md) and [host composition](docs/HOST_COMPOSITION.md) for the layout, limits, verifier contract, and safe read boundaries. +Privileged direct application callers can supply complete `sourceReferences` +with `createDraft`/`updateDraft` to commit content and current provenance in +one article transaction. Presence requires both draft-write and provenance-write +authority, including an explicit empty set. SD-03 host workflows must always +supply the complete nonempty set to close the empty/stale source window; +source readability alone does not establish publication eligibility/currentness. +Omission retains legacy behavior. The five-operation HTTP/MCP schemas continue +to reject this field and add no scope or tool. The +[approved source progression](https://github.com/pegma-dev/support-desk/pull/38) +does not close release or host acceptance gates. + KB-03 adds deterministic lexical retrieval over a bounded, repairable projection. Hints are confirmed against current authoritative publication, audience, applicability, and source eligibility before disclosure. Portal and @@ -130,13 +143,10 @@ Merging source does not publish a package. The [maintainer bootstrap ledger](docs/BOOTSTRAP.md) records the completed manual `0.1.0` uploads and exact-byte postflight. All five KB/Agent Access trusted publishers are configured through the CLI. Agent Access's verified trusted -`0.1.1` release is complete, while the KB trusted release remains gated. The -four KB packages' `latest` tags still resolve to `0.1.0`. A verified KB `0.1.1` -release is intended to advance them. An earlier attempt to delete Agent Access's -`latest` tag returned HTTP 400 before its `0.1.1` release. Agent Access now has -`latest: 0.1.1` and `bootstrap: 0.1.0`. -This does not advertise the KB bootstrap set or approve host use. SD-02 and host installation wait -for the verified trusted dependencies; source and synthetic proof cannot satisfy -real host acceptance. +`0.1.1` release and the four-package KB trusted `0.1.1` release are complete; +their exact receipts remain in the ledger. All four KB packages and Agent Access +have `latest: 0.1.1` and `bootstrap: 0.1.0`. Source `0.1.2` remains a candidate +for a separately reviewed trusted release. Neither registry publication nor +synthetic proof satisfies real host acceptance or approves activation. Built in the open by RetireGolden, LLC. diff --git a/docs/AGENT_API.md b/docs/AGENT_API.md index 97688ae..fca5a7b 100644 --- a/docs/AGENT_API.md +++ b/docs/AGENT_API.md @@ -4,8 +4,10 @@ an MCP adapter, and a Web Request/Response adapter. Both transports invoke the existing `KnowledgeBaseApplication`; neither introduces an authorization engine or another article lifecycle. The KB `0.1.0` packages -completed manual bootstrap without OIDC provenance; source `0.1.1` remains an -unpublished candidate with its own gates and verified trusted release pending. +completed manual bootstrap without OIDC provenance. All four `0.1.1` packages +have since completed [verified trusted publication](BOOTSTRAP.md#verified-knowledge-base-release). +Source `0.1.2` remains a candidate with its own review, gates, and verified +trusted release pending. Agent Access's verified public `0.1.1` producer prerequisite is closed; see the [release receipt](BOOTSTRAP.md#verified-agent-access-prerequisite). Passing synthetic transport tests does not establish live host login, protected staging @@ -66,7 +68,7 @@ validation requirements. There are no collection, private-evidence read, provenance, review, publication, retirement, retrieval, or administration tools in this initial transport surface. -Inputs mirror the public application contracts: +Inputs use the following bounded subset of the public application contracts: - `getDraft`: `{ articleId }`. - `getValidationRequirements`: `{ collectionId, kind }`. @@ -82,6 +84,10 @@ articleId, evidence, receipt }`. Evidence contains `id`, `articleId`, `executedAt`, `runnerId`, and `artifacts: [{ id, hash }]`. The opaque receipt is nonempty and at most 8,192 UTF-8 bytes. +`sourceReferences` is rejected by the strict `createDraft`/`updateDraft` schemas +over both HTTP and MCP. The optional atomic draft/source input belongs only to +privileged direct host application calls; no scope or tool is added here. + Caller-supplied context, scopes, principal, proof, evidence version/hash, or attestation fields are rejected. Evidence's revision/content hash, policy reference, artifact hashes, runner, execution time, and claimed result are diff --git a/docs/AGENT_WORKFLOW.md b/docs/AGENT_WORKFLOW.md index 63fbf16..5cc7aef 100644 --- a/docs/AGENT_WORKFLOW.md +++ b/docs/AGENT_WORKFLOW.md @@ -4,8 +4,9 @@ The [merged KB-04 source](https://github.com/pegma-dev/knowledge-base/pull/5) adds optional authoring transports over the existing Knowledge Base application. [KB-05 release-preparation source](https://github.com/pegma-dev/knowledge-base/pull/6) is also merged. All four KB `0.1.0` packages completed manual bootstrap and -exact-byte postflight without OIDC provenance. Source `0.1.1` is a candidate -for the first advertised trusted release, which remains gated; this document +exact-byte postflight without OIDC provenance. All four `0.1.1` packages have +since completed [verified trusted publication](BOOTSTRAP.md#verified-knowledge-base-release). +Source `0.1.2` remains a candidate for a separately reviewed trusted release; this document describes the composition and retained acceptance contract, not a live service or a client-compatibility claim. The exact wire contract is in [AGENT_API.md](AGENT_API.md). @@ -67,6 +68,10 @@ or grant-management tool. Agents cannot act as staff or Admin through this surface. Hosts use their separately authorized staff services for review and publication. +Both transports reject `sourceReferences` on draft create/update. Atomic +draft/source authoring remains a privileged direct host application operation; +the five tools and three consent scopes remain unchanged. + ## Prepare, test, and submit 1. Obtain the target collection and article identity through the host's @@ -117,15 +122,16 @@ Historical source-proof evidence retains the original reviewed AUTH-01 accepts no source fallback and requires its own current-head gate results. The merged KB-04 source exit closes only its source slice. KB-05 release-preparation -source is merged; full KB-05 publication remains open. Agent Access's +source is merged, and the separate KB `0.1.1` trusted release is verified. +Agent Access's [release-preparation source](https://github.com/pegma-dev/agent-access/pull/2) is also merged; its manual `0.1.0` bootstrap is complete and its verified trusted `0.1.1` release closed the public producer prerequisite at **2026-11-07T22:32:42Z**. The [release ledger](BOOTSTRAP.md#verified-agent-access-prerequisite) records exact identities, the successful attempt-2 workflow, and strict verification stdout. -The KB `0.1.1` candidate remains unpublished with its own gates, PR, and trusted -release pending. Both verified trusted releases precede production host +The KB `0.1.2` candidate retains its own gates, PR, and verified trusted release +pending. Both verified trusted dependencies precede production host assembly. Branches, copied source, local paths, and unpublished production tarballs cannot substitute for them. diff --git a/docs/BOOTSTRAP.md b/docs/BOOTSTRAP.md index c774654..2189571 100644 --- a/docs/BOOTSTRAP.md +++ b/docs/BOOTSTRAP.md @@ -1,4 +1,4 @@ -# First-publication handoff +# Publication ledger ## Current state and owner @@ -6,10 +6,11 @@ The maintainer owns npm publication and external configuration. All four KB `0.1.0` uploads were accepted through manual bootstrap, and their exact-byte postflight passed at **2026-11-07T21:56:24Z**. Agent Access `0.1.0` also completed manual bootstrap and postflight. Neither bootstrap has OIDC provenance. -Source `0.1.1` is the KB candidate for a separately reviewed first advertised -trusted release; it is not published or verified by this document. -Agent Access has since completed its verified trusted `0.1.1` release, recorded -below; that closes the public producer prerequisite only. +KB and Agent Access have since completed their verified trusted `0.1.1` +releases, recorded below. Those receipts close the public producer release +prerequisites only. Source `0.1.2` is the synchronized KB SD-03 atomic draft/source +candidate; its own review, current-head gates, trusted release, and strict +verification remain open. The five KB/Agent Access trusted-publisher entries have been configured through the CLI. An actual trusted release still requires the reviewed source and @@ -75,11 +76,43 @@ it is not the trusted-release `verify` result or OIDC provenance. At the manual-bootstrap checkpoint, the observed npm `latest` dist-tags resolved to `0.1.0` despite the publishes using `--tag bootstrap`. An earlier attempt to delete Agent Access's `latest` tag returned HTTP 400 before its `0.1.1` release. -The four KB packages' `latest` tags still resolve to `0.1.0`; their intended -correction is a verified forward `0.1.1` release. -Agent Access's current `latest` is `0.1.1` and its `bootstrap` remains `0.1.0`. +Following their trusted releases, all four KB packages and Agent Access have +`latest: 0.1.1` and `bootstrap: 0.1.0`. Neither tag behavior nor package availability advertises the KB bootstrap as -the approved dependency set or authorizes host installation. +the approved dependency set or establishes real-host acceptance. + +## Verified Knowledge Base release + +At **2026-11-07T23:35:31Z**, all four KB `0.1.1` packages completed strict registry +and clean-consumer verification. [Release PR #8](https://github.com/pegma-dev/knowledge-base/pull/8) +was reviewed at +[`a3354ec39c5cc0401f4a19b92e08f8aa95c946b3`](https://github.com/pegma-dev/knowledge-base/commit/a3354ec39c5cc0401f4a19b92e08f8aa95c946b3) +and merged at +[`32086e4374f2ef45044cd09c371e506d10b88d64`](https://github.com/pegma-dev/knowledge-base/commit/32086e4374f2ef45044cd09c371e506d10b88d64). +The approved signed annotated [`v0.1.1` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.1) +targets that merged source. The +[trusted workflow run, attempt 5](https://github.com/pegma-dev/knowledge-base/actions/runs/42424148244/attempts/5) +succeeded. Its separate unprivileged +[strict verification job](https://github.com/pegma-dev/knowledge-base/actions/runs/42424148244/job/128564059833) +verified all four exact registry artifacts/dependencies, cryptographic signatures, +source/workflow/tag/commit provenance, and isolated clean-consumer imports. + +| Field | Value | +| --------------------------------------- | ------------------------------------------------------------------ | +| Artifact ID | `13595485168` | +| Artifact name | `knowledge-base-release-42424148244-1` | +| Downloaded artifact archive SHA-256 | `6274a14ba2780e384fb00d414a7e7f5b2f897aa201104286aece13f732cf54e4` | +| Independently retained manifest SHA-256 | `75cb63984706b964edd073932a8f14e3b53701620320d86a367ec29b5198ba4b` | + +The original prepared artifact and independent digest were preserved across +failed-only reruns while registry visibility was delayed. Recovery accepted +only identical existing package bytes; no version, tag, or artifact was replaced. +All four packages now have `latest: 0.1.1` and `bootstrap: 0.1.0`. Manual `0.1.0` +bootstrap receipts remain distinct and have no OIDC provenance. + +This closes the verified KB `0.1.1` producer release prerequisite. It does not +verify the `0.1.2` candidate or complete host/client, privacy, activation, or +pilot acceptance. ## Verified Agent Access prerequisite @@ -123,9 +156,9 @@ verification; no package version or artifact was replaced. This closes the verified public Agent Access `0.1.1` prerequisite. The KB protocol proof now composes that exact registry producer with four packed KB -candidate artifacts in a fresh consumer. KB `0.1.1` remains an unpublished -candidate with its own current-head gates, PR, trusted release, and strict -verification pending. Existing-login, current-Admin consent, every requested +candidate artifacts in a fresh consumer. KB `0.1.1` has its separate verified +receipt above; source `0.1.2` retains its own current-head gates, PR, trusted +release, and strict verification. Existing-login, current-Admin consent, every requested client/mode, and both real hosts remain separately unproven. ## Historical initial preparation procedure (`0.1.0`) @@ -193,7 +226,7 @@ Retain the manual publication receipts and bootstrap integrity record, with provenance explicitly recorded as absent. Do not advertise this bootstrap as the released dependency set or authorize host installation from it. -## First advertised trusted release +## Subsequent trusted releases The names now exist and all five KB/Agent Access trusted-publisher entries have been configured through the CLI. Recheck the protected `npm-publish` environment, @@ -203,9 +236,10 @@ must name this repository's exact `publish.yml` workflow and environment and explicitly permit direct publishing. Time new configurations to the prepared trusted release so their first-use expiry does not strand the release. -The first advertised KB release candidate is synchronized version `0.1.1` with -exact internal dependency pins. It still needs review and all current-head -gates before release. A previously manually published version cannot be +The synchronized KB source candidate is `0.1.2` with exact internal dependency +pins. It still needs review and all current-head gates before release. The +verified first advertised trusted release remains `0.1.1`, recorded above. +A previously manually published version cannot be republished through OIDC to add provenance. Run the full review/Node 22/24 gate for the newly reviewed commit, create its approved signed annotated version tag on `origin/main`, then create its GitHub release with `--verify-tag` to trigger @@ -219,6 +253,7 @@ signatures, and matching source/workflow/tag/commit provenance. Preserve those results with the release identity and independent manifest digest. The active KB protocol proof uses the verified registry producer `@pegma/agent-access@0.1.1`; historical source-producer evidence remains in -[source preparation](SOURCE_PREPARATION.md). SD-02 still waits for the verified -trusted KB set. The Agent Access release prerequisite is closed; both hosts -still require their retained actual login/Admin-consent/client/staging acceptance. +[source preparation](SOURCE_PREPARATION.md). The verified KB `0.1.1` and Agent +Access `0.1.1` public producer release prerequisites are closed. This candidate +requires its own verified release, and both hosts still require their retained +actual login/Admin-consent/client/staging acceptance. diff --git a/docs/COLLECTIONS.md b/docs/COLLECTIONS.md index 218c9b7..4b09aba 100644 --- a/docs/COLLECTIONS.md +++ b/docs/COLLECTIONS.md @@ -11,9 +11,10 @@ document alone does not mark a task complete. The authoritative collection is The approved scope is the [implementation plan](https://github.com/pegma-dev/support-desk/blob/main/docs/KNOWLEDGE_AI_PLAN.md) and its P-00 capacity/privacy requirements. KB-04's optional HTTP/MCP adapter -source is [merged](https://github.com/pegma-dev/knowledge-base/pull/5). Package -publication, real-host acceptance, and production readiness remain separate -gates. +source is [merged](https://github.com/pegma-dev/knowledge-base/pull/5). The +[verified `0.1.1` release](BOOTSTRAP.md#verified-knowledge-base-release) is +complete; the `0.1.2` source candidate, real-host acceptance, and production +readiness retain their own gates. ## Partition and authority rules @@ -165,6 +166,22 @@ Audit, receipt, and causal work. A conflict reloads/redecides within a bound and repeats resource checks under the call's trusted access-context freshness boundary; it does not append an unbounded attempt log. +Direct host `createDraft`/`updateDraft` inputs may include complete +`sourceReferences`. Presence, including `[]`, requires both `draftWrite` and +`provenanceWrite`. Every supplied reference must pass current `canRead` checks, +repeated on CAS retry and exact replay. Content and the current private +provenance snapshot commit in the existing article transaction with its head, +immutable rows, Audit, receipt, and causal jobs; there is no second provenance +write. An update preserves the older publication's separate +`publishedProvenance`. Omission retains the legacy draft-only behavior. + +This closes SD-03's empty/stale source window only when the owning host always +supplies its complete nonempty reference set. A readable source may still be +ineligible or stale: review/publication and current published reads retain +their independent source eligibility/currentness gates. This operation adds no +cross-partition fence over external source policy. The initial HTTP/MCP +authoring schemas reject `sourceReferences` and add no scope or tool. + A command ID is scoped to its actor, operation, target, and exact input semantic fingerprint. Identical replay returns a bounded historical acknowledgement without duplicating history/Audit/jobs; a changed fingerprint diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index f5583e6..47d25b7 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -10,9 +10,11 @@ application composes contracts/core with host-supplied Storage Core and Authorization Core. The optional `@pegma/knowledge-base-mcp` package supplies bounded HTTP/MCP adapters over that application. All four `0.1.0` packages completed manual bootstrap -and exact-byte postflight without OIDC provenance. Source `0.1.1` is a candidate -for the first advertised trusted release; review, publication, strict registry/ -provenance verification, and host acceptance remain gates. +and exact-byte postflight without OIDC provenance. The four-package `0.1.1` +trusted release is now [verified](BOOTSTRAP.md#verified-knowledge-base-release). +Source `0.1.2` is the atomic draft/source candidate; its own review, current-head +gates, trusted release, and strict registry/provenance verification remain open. +Host acceptance remains separate. No package becomes an identity system or an operational hosted endpoint. See [declared collections](COLLECTIONS.md) for the required layout, CAS, admission, and replay design. @@ -36,7 +38,7 @@ draft/evidence transport loop. Agent Access's is also merged, and its manual `0.1.0` bootstrap is complete without OIDC provenance. Its trusted `0.1.1` release and strict registry verification have since closed the public producer prerequisite. Actual existing-login/client -acceptance on both hosts and full KB-05 publication remain open. See the +acceptance on both hosts remains open. See the [release ledger](BOOTSTRAP.md#verified-agent-access-prerequisite) for the exact Agent Access receipt. The changed registry proof still needs current-head execution; historical source-producer evidence does not validate it. @@ -133,6 +135,25 @@ and proof checks remain additional requirements. `getPublishedArticle` is a portal read, not bot-only retrieval. The separate retrieval methods below enforce their own effective-customer use and audience. +Privileged hosts calling `createDraft` or `updateDraft` directly may pass optional +`sourceReferences` as the complete current private source set. Supplying the +field requires both `draftWrite` and `provenanceWrite`, even for `[]`; every +reference must pass `PrivateSourcesVerifier.canRead`. The application repeats +these current operation/resource and per-reference checks after a CAS conflict +and before acknowledging exact replay. Content and current provenance commit +atomically in the existing article transaction, including Audit, receipt, and +causal jobs. Updating a draft preserves the older publication's separate +`publishedProvenance`. Omitting the field retains legacy draft-only behavior. + +SD-03 closes its empty/stale source window only if the owning host always +supplies a complete nonempty reference set for each generated draft create or +update. The [approved source progression](https://github.com/pegma-dev/support-desk/pull/38) +does not establish release, host/client, privacy, or pilot acceptance. Source +readability may coexist with publication ineligibility or staleness; +`canPublish`/`isCurrent` and exact review/publication checks remain required. +The initial local-agent HTTP/MCP schemas reject `sourceReferences`. This direct +host extension adds no tool or consent scope. + `getValidationRequirements` returns the current article-kind checks, validation-policy reference, governance generation, and expected staging build for authorized authors. It omits trusted attester IDs; full governance @@ -204,8 +225,9 @@ source metadata or resolving the reference; unavailable source authorization must not be treated as an allow. Keep raw customer conversations in the owning support system rather than copying them into KB history. -`PrivateSourcesVerifier.canRead` checks each private reference returned by -`getProvenance`. The separate `canPublish` and `isCurrent` callbacks attest +`PrivateSourcesVerifier.canRead` checks each private reference supplied through +atomic draft authoring or returned by `getProvenance`. The separate `canPublish` +and `isCurrent` callbacks attest source eligibility/currentness without returning source bodies. Nonempty source snapshots fail closed when those required gates are unavailable. A portal customer does not need permission to read private source tickets in diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 26c5f32..b16f392 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -9,30 +9,32 @@ The release set is exactly these packages, in dependency order: 3. `@pegma/knowledge-base-application` 4. `@pegma/knowledge-base-mcp` -As of **2026-11-07T21:56:24Z**, all four `0.1.0` packages completed manual -bootstrap with exact-byte postflight and no OIDC provenance. Source `0.1.1` is -the candidate for the first advertised trusted release; it remains subject to -review, current-head gates, publication, and strict registry/provenance -verification. Package README source links target the expected `v0.1.1` release -tag; that candidate tag and trusted release remain pending. +All four `0.1.0` packages completed manual bootstrap with exact-byte postflight +at **2026-11-07T21:56:24Z**, without OIDC provenance. The first advertised trusted +KB release, `0.1.1`, completed strict complete-set registry/signature/provenance +and clean-consumer verification at **2026-11-07T23:35:31Z**. The +[release receipt](BOOTSTRAP.md#verified-knowledge-base-release) retains its +reviewed head, merged source, signed tag, immutable artifact/digests, successful +attempt-5 workflow, and separate unprivileged verification job. +Source `0.1.2` is the synchronized SD-03 atomic draft/source candidate. It still +requires its own review, current-head gates, signed tag, trusted publication, +and strict verification. Package README links target its expected `v0.1.2` +release tag, which remains pending. [KB-04 source](https://github.com/pegma-dev/knowledge-base/pull/5) and [KB-05 release preparation](https://github.com/pegma-dev/knowledge-base/pull/6) are merged. The separate earlier [partial KB-05 source slice](https://github.com/pegma-dev/knowledge-base/pull/4) supplied local D1 conformance and public synthetic composition; PR #6 added release tooling. The canonical [historical source-gate record](SOURCE_PREPARATION.md#historical-source-gates) identifies reviewed heads separately from merge commits and retains exact -CI links, counts, review, and security receipts. Full KB-05 publication remains -open. +CI links, counts, review, and security receipts. The verified `0.1.1` publication +is a separate receipt, not a claim about changed candidate source. Changed source still needs all current-head gates before release preparation. No source merge configures publishers, creates a tag/release, or publishes npm packages. The [maintainer bootstrap ledger](BOOTSTRAP.md) retains the actual manual commands/stdout, exact identities, preparation runs/artifacts, and -independently retained digests. The four KB packages' `latest` tags still -resolve to `0.1.0` despite bootstrap tagging. A verified KB `0.1.1` release is -intended to advance them. An earlier attempt to delete Agent Access's `latest` -tag returned HTTP 400 before its `0.1.1` release. Agent Access -now has `latest: 0.1.1` and `bootstrap: 0.1.0`. This is not approval to consume -the KB bootstrap. +independently retained digests. All four KB packages and Agent Access now have +`latest: 0.1.1` and `bootstrap: 0.1.0`. The manual bootstraps remain historical +integrity receipts without OIDC provenance. [Agent Access](https://github.com/pegma-dev/agent-access) is a separate release. Its `0.1.1` trusted publication and strict registry verification completed at @@ -43,7 +45,7 @@ retains its exact artifact/digest, successful attempt-2 workflow, and unprivileg verification job. That public producer prerequisite is closed. The active `agent:proof` installs exact registry `@pegma/agent-access@0.1.1` with four packed KB artifacts and official MCP SDK `1.32.2` in a fresh consumer. -The KB candidate still needs its own current-head gates, review, PR, publication, +The KB `0.1.2` candidate still needs its own current-head gates, review, PR, publication, and strict verification; historical source-proof results do not validate this changed composition. Production hosts require verified trusted versions of both components and their separately retained acceptance. diff --git a/docs/RETRIEVAL.md b/docs/RETRIEVAL.md index 27dc05a..b9a8ae2 100644 --- a/docs/RETRIEVAL.md +++ b/docs/RETRIEVAL.md @@ -7,12 +7,13 @@ with the agreed public types and projection layout. Implementation tests and repository gates remain required. KB-03 extends the existing application package; it creates no new package, database, model integration, or authentication system. The KB `0.1.0` packages -completed manual bootstrap without OIDC provenance; source `0.1.1` remains an -unpublished candidate. Source tests and repository gates, not +completed manual bootstrap without OIDC provenance. All four `0.1.1` packages +have since completed [verified trusted publication](BOOTSTRAP.md#verified-knowledge-base-release). +Source `0.1.2` remains a candidate. Source tests and repository gates, not this document, determine completion. KB-04's optional HTTP/MCP adapter source -is [merged](https://github.com/pegma-dev/knowledge-base/pull/5). Verified trusted -KB publication, real-host acceptance, and production activation remain separate -tasks. +is [merged](https://github.com/pegma-dev/knowledge-base/pull/5). The candidate's +verified trusted release, real-host acceptance, and production activation retain +their own gates. Read [declared collections](COLLECTIONS.md) for the authoritative record layout and [host composition](HOST_COMPOSITION.md) for trusted access, diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md index bea6fa6..971560a 100644 --- a/docs/SOURCE_PREPARATION.md +++ b/docs/SOURCE_PREPARATION.md @@ -6,8 +6,9 @@ KB-05 source preparation has two separately reviewed source slices. The earlier [partial source slice](https://github.com/pegma-dev/knowledge-base/pull/4) supplied the real local D1 consumer fixture and public synthetic composition. The later [release-preparation slice](https://github.com/pegma-dev/knowledge-base/pull/6) -added exact-artifact release tooling. Neither source slice completes full -KB-05 publication or host acceptance. +added exact-artifact release tooling. Those source slices established source +readiness only; later verified publication is separately recorded below. +Neither source slice establishes host acceptance. ### Historical source gates @@ -47,16 +48,18 @@ current-head gates. The historical `0.1.0` absence snapshot below predates the completed manual bootstrap. All four exact `0.1.0` artifacts passed manual postflight at **2026-11-07T21:56:24Z**, without OIDC provenance; see the [operator-recorded bootstrap receipt](BOOTSTRAP.md#recorded-manual-bootstrap-receipt). -Source `0.1.1` is a candidate for the first advertised trusted release, with -its own review, current-head gates, publication, and strict registry/provenance -verification pending. - -| Evidence area | This source slice | Separate remaining proof | -| ---------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -| Storage consumer | Shared public KB suites on memory, local Azurite, and local Miniflare D1 | Production Azure/Workers configuration, operations, and host acceptance | -| Composition | Runnable fictional author/evidence/review/publication/retrieval flow | Real host identity, staging verification, existing-login/client acceptance, and UI | -| Artifacts | Four-package checks, schema-2 preparation, and manual `0.1.0` exact-byte postflight | First advertised trusted release with its own registry/provenance verification and released consumers | -| Task readiness | Current-head repository gates establish source readiness | Verified trusted releases and two-host/client acceptance remain separately recorded | +The subsequent four-package `0.1.1` trusted release completed strict verification +at **2026-11-07T23:35:31Z**; see its separate +[release receipt](BOOTSTRAP.md#verified-knowledge-base-release). Source `0.1.2` +is now the SD-03 atomic draft/source candidate with its own review, current-head +gates, trusted publication, and strict verification still required. + +| Evidence area | This source slice | Separate remaining proof | +| ---------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| Storage consumer | Shared public KB suites on memory, local Azurite, and local Miniflare D1 | Production Azure/Workers configuration, operations, and host acceptance | +| Composition | Runnable fictional author/evidence/review/publication/retrieval flow | Real host identity, staging verification, existing-login/client acceptance, and UI | +| Artifacts | Four-package checks, schema-2 preparation, and manual `0.1.0` exact-byte postflight | The separate `0.1.1` trusted-release receipt; each candidate still needs its own verified release | +| Task readiness | Current-head repository gates establish source readiness | Verified trusted releases and two-host/client acceptance remain separately recorded | The merged-source results above do not certify this working tree. Record verified current-head gate results before treating changed source as validated. @@ -293,9 +296,11 @@ trusted-publisher entries have been configured through the CLI. Recheck the full ownership, protected tag/main, approved signer, approval environment, per-package publisher binding, direct-publishing, and 2FA/token-policy checklist in [release operations](RELEASING.md) for the actual trusted release. -Full KB-05 still requires the `0.1.1` candidate's review and current-head gates, -then its own trusted publication, complete-set registry -integrity/signature/provenance verification, and released-consumer proof. +The KB `0.1.1` trusted release has completed complete-set registry +integrity/signature/provenance verification and released-consumer proof; its +[receipt](BOOTSTRAP.md#verified-knowledge-base-release) is separate from these +historical source records. Source `0.1.2` retains its own review, current-head +gates, trusted publication, strict verification, and released-consumer proof. Manual bootstrap is not OIDC provenance. Agent Access has its own publication history: [Agent Access release preparation](https://github.com/pegma-dev/agent-access/pull/2) @@ -316,7 +321,8 @@ closed the public producer prerequisite; see the [exact receipt](BOOTSTRAP.md#verified-agent-access-prerequisite). The original source-producer proof remains historical evidence, while the changed registry composition requires its own current-head gates. -SD-02 waits for the verified trusted KB release, and both hosts wait for exact -verified trusted KB and Agent Access dependencies before their retained acceptance. +The verified KB `0.1.1` and Agent Access `0.1.1` producer release prerequisites +are closed. Both hosts still require exact verified trusted dependencies and +their retained acceptance before activation. Hosts must wait for exact released artifacts rather than adopting branches, copied source, local paths, or unpublished production tarballs. diff --git a/examples/agent/README.md b/examples/agent/README.md index 9466f9d..b38c850 100644 --- a/examples/agent/README.md +++ b/examples/agent/README.md @@ -18,7 +18,7 @@ Core `0.4.0`, Storage Core `0.4.0`, exact registry `@pegma/agent-access@0.1.1`, and all four packed KB candidate artifacts. It does not establish any of the four target client applications, a deployed host, real browser login, real staging execution, verified KB publication, or host activation. -Those acceptance tasks remain open. +Real host/client acceptance and activation remain open. ## Artifact boundary diff --git a/examples/composition/README.md b/examples/composition/README.md index 0db941b..0071b13 100644 --- a/examples/composition/README.md +++ b/examples/composition/README.md @@ -20,9 +20,11 @@ pnpm run example and `runCompleteExampleFlow(composition)`. The optional Store defaults to `createMemoryStore()`; the example imports no test helpers. [`run.ts`](run.ts) prints a safe completion summary. These are workspace source examples. The KB -`0.1.0` packages completed manual bootstrap without OIDC provenance; the -`0.1.1` candidate remains unpublished and requires its own verified trusted -release before production installation. +`0.1.0` packages completed manual bootstrap without OIDC provenance, and the +four-package `0.1.1` trusted release is now +[verified](../../docs/BOOTSTRAP.md#verified-knowledge-base-release). Source `0.1.2` +remains a candidate requiring its own reviewed, verified trusted release. +Production hosts retain their separate acceptance gates. The flow creates a fictional workshop collection with portal use disabled and a separate bot audience. A synthetic author creates a walkthrough, submits its diff --git a/package.json b/package.json index 3e482b6..91ec2a5 100644 --- a/package.json +++ b/package.json @@ -34,10 +34,10 @@ "@cloudflare/workers-types": "5.20260730.1", "@modelcontextprotocol/sdk": "1.32.2", "@pegma/authorization-core": "0.4.0", - "@pegma/knowledge-base-application": "0.1.1", - "@pegma/knowledge-base-contracts": "0.1.1", - "@pegma/knowledge-base-core": "0.1.1", - "@pegma/knowledge-base-mcp": "0.1.1", + "@pegma/knowledge-base-application": "0.1.2", + "@pegma/knowledge-base-contracts": "0.1.2", + "@pegma/knowledge-base-core": "0.1.2", + "@pegma/knowledge-base-mcp": "0.1.2", "@pegma/spine": "0.1.2", "@pegma/storage-azure-tables": "0.4.0", "@pegma/storage-cloudflare-d1": "0.4.1", diff --git a/packages/application/README.md b/packages/application/README.md index aecf18b..ee0e88b 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -5,10 +5,10 @@ host-supplied Storage Core, Authorization Core, Audit, and a clock. Source implementation and repository gates determine task completion; neither this package nor local tests establish a live host or production readiness. -The [declared layout](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/COLLECTIONS.md) records the agreement made -before durable operations. [Host composition](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/HOST_COMPOSITION.md) describes the host +The [declared layout](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/COLLECTIONS.md) records the agreement made +before durable operations. [Host composition](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/HOST_COMPOSITION.md) describes the host authentication, current-resource authorization, verified-evidence, and privacy -boundaries. [Retrieval](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/RETRIEVAL.md) +boundaries. [Retrieval](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RETRIEVAL.md) documents bounded lexical lookup, authoritative confirmation, citations, and repair. The optional `@pegma/knowledge-base-mcp` package adds HTTP/MCP adapters over this API; it supplies no login or token issuer. Real-host acceptance and @@ -43,7 +43,7 @@ or a support model. `limits`, `evidenceVerifier`, `privateSources`, and nested `retrieval` settings. Hosts authenticate callers and resolve current scoped `AccessContext` values. The -[public types](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/packages/application/src/types.ts) define commands and purpose-specific results; +[public types](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/packages/application/src/types.ts) define commands and purpose-specific results; the package owns no HTTP routes or credentials. Creates use `expectedGeneration: 0`; later mutations use exact application @@ -59,6 +59,21 @@ exact `ReviewSnapshot`, reject, retire, set private provenance, or revoke an exact historical proof. The snapshot includes the core approval binding plus article/source/governance generations. +Privileged direct host calls to `createDraft`/`updateDraft` may supply optional +`sourceReferences` as the complete current private source set. Presence, +including `[]`, requires both `draftWrite` and `provenanceWrite`; every reference +must pass current `PrivateSourcesVerifier.canRead` checks on the initial +attempt, CAS retry, and exact replay. Content and current provenance commit in +one existing article transaction with Audit, receipt, and causal jobs. An update +preserves the older publication's `publishedProvenance`. Omission retains +legacy draft-only behavior. + +SD-03 hosts must always supply a complete nonempty set to close the empty/stale +source window. A readable reference may still be ineligible or stale; +review/publication and published reads retain their eligibility/currentness +checks. The initial HTTP/MCP schemas reject `sourceReferences`; this extension +adds no agent scope or tool. + `CommandResult` returns `{ value, replayed }`, where `value` is a bounded historical acknowledgement. It contains no body/evidence/provenance. Replay rechecks current operation/resource authority, conflicts on changed semantic @@ -77,7 +92,8 @@ approved content/safe metadata. It is not KB-03 search or bot-only retrieval. `EvidenceVerifier.verify` authenticates an opaque receipt against the entire submission, authenticated actor, exact article, and governance configuration. It returns trusted attestation facts or null. A missing verifier fails closed. -`PrivateSourcesVerifier.canRead` controls private reference disclosure; +`PrivateSourcesVerifier.canRead` controls atomic draft source input and private +reference disclosure; `canPublish` and `isCurrent` independently attest source eligibility without making source tickets readable to customers. Missing required gates fail closed for nonempty source snapshots. @@ -116,7 +132,7 @@ provider data controls; current publication checks remain mandatory. ranked prefix of whole articles within aggregate byte/token budgets with a positive local count; reconfirmation is exact and all-or-nothing. `retrieval.limits` can only lower fixed component ceilings. -See [retrieval](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/RETRIEVAL.md) +See [retrieval](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RETRIEVAL.md) for the exact API, limits, authority/reference fences, and evaluation boundary. `repairArticleIndex`, `repairRetrievalPage`, and `getArticleIndexStatus` require @@ -133,13 +149,13 @@ causal jobs share one resource partition in `knowledge-base.records.v1`. Native flat chunk properties keep bounded rows compatible with the host's store adapter. The application separately bounds physical rows, encoded bytes, history, transaction work, retries, and control reserve. Read the -[layout limits](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/COLLECTIONS.md#physical-representation-and-hard-bounds) +[layout limits](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/COLLECTIONS.md#physical-representation-and-hard-bounds) before changing admission or retention; these are component safety bounds, not measured host throughput. No private persistence or parallel audit log is implemented here. Merging source does not publish a package. Hosts verify exact registry artifacts and provenance and complete their release/host activation gates. See -[release operations](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/RELEASING.md). +[release operations](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RELEASING.md). Built in the open by RetireGolden, LLC. diff --git a/packages/application/package.json b/packages/application/package.json index ff6b5b2..c507257 100644 --- a/packages/application/package.json +++ b/packages/application/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-application", - "version": "0.1.1", + "version": "0.1.2", "description": "Authorized knowledge authoring, evidence, review, and publication over Pegma storage.", "license": "MIT", "type": "module", @@ -31,8 +31,8 @@ "dependencies": { "@pegma/audit": "0.2.0", "@pegma/authorization-core": "0.4.0", - "@pegma/knowledge-base-contracts": "0.1.1", - "@pegma/knowledge-base-core": "0.1.1", + "@pegma/knowledge-base-contracts": "0.1.2", + "@pegma/knowledge-base-core": "0.1.2", "@pegma/spine": "0.1.2", "@pegma/storage-core": "0.4.0" }, diff --git a/packages/application/src/articles.ts b/packages/application/src/articles.ts index d281c20..97b3f99 100644 --- a/packages/application/src/articles.ts +++ b/packages/application/src/articles.ts @@ -42,6 +42,7 @@ import type { ArticleAcknowledgement, ArticleCommandInput, CommandResult, + CreateDraftInput, KnowledgeBaseApplication, KnowledgeBaseServiceOptions, PrivateSourceReference, @@ -303,6 +304,19 @@ export function createArticleServices( } } + async function recheckDraftSources( + command: Pick, + caller: AccessContext, + ): Promise { + if (command.sourceReferences === undefined) return; + requirePermission(caller, knowledgePermissions.provenanceWrite); + await requireSourceAccess( + caller, + command.articleId, + command.sourceReferences, + ); + } + async function execute( access: AccessContext, input: T, @@ -317,6 +331,7 @@ export function createArticleServices( ) => Promise, control = false, create = false, + recheckCommand?: (command: T, caller: AccessContext) => Promise, ): Promise> { const request = commandSnapshot(access, input, permission, extraFields); if ( @@ -360,6 +375,7 @@ export function createArticleServices( if (collection === null) throw new KnowledgeBaseNotFoundError("collection"); } + await recheckCommand?.(request.input, request.access); }, decide: async (current, generation) => decide(current, generation, request.input, request.access), @@ -374,7 +390,7 @@ export function createArticleServices( input, knowledgePermissions.draftWrite, "article.create", - ["collectionId", "draft"], + ["collectionId", "draft", "sourceReferences"], async (current, _generation, command, caller) => { if (current !== null) throw new RepositoryConflictError(); requireIdentifier(command.collectionId, "collectionId"); @@ -391,7 +407,10 @@ export function createArticleServices( return { next: { article, - provenance: await sourceSnapshot(1, []), + provenance: await sourceSnapshot( + 1, + command.sourceReferences ?? [], + ), publicationHeld: false, revokedEvidence: [], }, @@ -399,6 +418,7 @@ export function createArticleServices( }, false, true, + recheckDraftSources, ); }, @@ -408,7 +428,7 @@ export function createArticleServices( input, knowledgePermissions.draftWrite, "article.update", - ["collectionId", "draft"], + ["collectionId", "draft", "sourceReferences"], async (current, _generation, command, caller) => { const stored = requireArticle(current); requireIdentifier(command.collectionId, "collectionId"); @@ -422,8 +442,20 @@ export function createArticleServices( draft: command.draft, context: { ...governance.context, actorId: caller.principalId }, }); - return { next: { ...withoutPendingReview(stored), article } }; + const provenance = + command.sourceReferences === undefined + ? stored.provenance + : await sourceSnapshot( + stored.provenance.generation + 1, + command.sourceReferences, + ); + return { + next: { ...withoutPendingReview(stored), article, provenance }, + }; }, + false, + false, + recheckDraftSources, ); }, diff --git a/packages/application/src/types.ts b/packages/application/src/types.ts index ff2009f..7b959a1 100644 --- a/packages/application/src/types.ts +++ b/packages/application/src/types.ts @@ -271,12 +271,16 @@ export interface CreateDraftInput extends CommandInput { readonly articleId: string; readonly collectionId: string; readonly draft: ArticleDraft; + /** Supplied references are committed with content and require provenanceWrite. */ + readonly sourceReferences?: readonly PrivateSourceReference[]; } export interface UpdateDraftInput extends CommandInput { readonly articleId: string; readonly collectionId: string; readonly draft: ArticleDraft; + /** Omission preserves current provenance; supplied references replace it atomically. */ + readonly sourceReferences?: readonly PrivateSourceReference[]; } export interface SubmitEvidenceInput extends CommandInput { diff --git a/packages/contracts/package.json b/packages/contracts/package.json index a0e02e2..7c3b3ee 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-contracts", - "version": "0.1.1", + "version": "0.1.2", "description": "Provider-neutral knowledge collections, revisions, validation, and approval contracts.", "license": "MIT", "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index bba2079..4a3fe7e 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-core", - "version": "0.1.1", + "version": "0.1.2", "description": "Pure knowledge article, validation, and publication transitions.", "license": "MIT", "type": "module", @@ -29,7 +29,7 @@ "directory": "packages/core" }, "dependencies": { - "@pegma/knowledge-base-contracts": "0.1.1" + "@pegma/knowledge-base-contracts": "0.1.2" }, "scripts": { "build": "tsc -p tsconfig.json", diff --git a/packages/mcp/README.md b/packages/mcp/README.md index d22881f..a93e44b 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -40,13 +40,17 @@ against shared internal schemas and fixed component ceilings before dispatch. Errors use bounded public responses rather than exposing internal exceptions or private evidence and provenance. +The initial `createDraft`/`updateDraft` HTTP/MCP schemas reject +`sourceReferences`. Atomic draft/source authoring is a privileged direct-host +application extension; it adds no agent scope or tool. + `createKnowledgeAgentHttp` and `createKnowledgeAgentMcp` expose that dispatcher through host-configured protected endpoints. Both require fresh host authentication and admission control on every request; neither issues tokens. -The [host composition contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/HOST_COMPOSITION.md) +The [host composition contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/HOST_COMPOSITION.md) describes authenticated contexts, trusted evidence, replay, and safe DTOs. The -[retrieval contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/RETRIEVAL.md) +[retrieval contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RETRIEVAL.md) describes authoritative current-publication confirmation and audience boundaries. ## Local verification and release @@ -77,7 +81,7 @@ Each package has its own README, MIT LICENSE, build-on-prepack hook, and compiled-test exclusion. All four package versions remain synchronized with exact internal dependency pins. Publishing, release tags, trusted-publisher configuration, and host activation are separate maintainer operations in the -[release procedure](https://github.com/pegma-dev/knowledge-base/blob/v0.1.1/docs/RELEASING.md). +[release procedure](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RELEASING.md). Documentation links target this package's release tag rather than development `main`. During release preparation that tag may still be pending; it is created after the reviewed merge and before publishing. Source readers can use the diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 0037050..3ed8525 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-mcp", - "version": "0.1.1", + "version": "0.1.2", "description": "Optional MCP transport for authorized Pegma knowledge authoring and validation.", "license": "MIT", "type": "module", @@ -32,9 +32,9 @@ "@cfworker/json-schema": "4.1.6", "@modelcontextprotocol/sdk": "1.32.2", "@pegma/authorization-core": "0.4.0", - "@pegma/knowledge-base-application": "0.1.1", - "@pegma/knowledge-base-contracts": "0.1.1", - "@pegma/knowledge-base-core": "0.1.1", + "@pegma/knowledge-base-application": "0.1.2", + "@pegma/knowledge-base-contracts": "0.1.2", + "@pegma/knowledge-base-core": "0.1.2", "zod": "4.6.7" }, "scripts": { diff --git a/packages/mcp/src/mcp.ts b/packages/mcp/src/mcp.ts index 7d8a4a7..6deda9a 100644 --- a/packages/mcp/src/mcp.ts +++ b/packages/mcp/src/mcp.ts @@ -332,7 +332,7 @@ export function createKnowledgeAgentMcp( maxRequestBodySize: dispatcher.limits.maxRequestBytes, }); const server = new Server( - { name: "@pegma/knowledge-base-mcp", version: "0.1.1" }, + { name: "@pegma/knowledge-base-mcp", version: "0.1.2" }, { capabilities: { tools: {} }, // Workers prohibit the runtime code generation used by SDK-default AJV. diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts index 880bcbc..c8b51e7 100644 --- a/packages/mcp/src/types.ts +++ b/packages/mcp/src/types.ts @@ -49,8 +49,9 @@ export interface KnowledgeAgentIdentity { export interface KnowledgeAgentInputMap { readonly getDraft: ArticleReadInput; - readonly createDraft: CreateDraftInput; - readonly updateDraft: UpdateDraftInput; + /** Privileged host provenance delivery is outside initial agent consent. */ + readonly createDraft: Omit; + readonly updateDraft: Omit; readonly getValidationRequirements: ValidationRequirementsReadInput; readonly submitEvidence: SubmitEvidenceInput; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 287f19b..3f741da 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,16 +24,16 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/knowledge-base-application': - specifier: 0.1.1 + specifier: 0.1.2 version: link:packages/application '@pegma/knowledge-base-contracts': - specifier: 0.1.1 + specifier: 0.1.2 version: link:packages/contracts '@pegma/knowledge-base-core': - specifier: 0.1.1 + specifier: 0.1.2 version: link:packages/core '@pegma/knowledge-base-mcp': - specifier: 0.1.1 + specifier: 0.1.2 version: link:packages/mcp '@pegma/spine': specifier: 0.1.2 @@ -78,10 +78,10 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/knowledge-base-contracts': - specifier: 0.1.1 + specifier: 0.1.2 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.1 + specifier: 0.1.2 version: link:../core '@pegma/spine': specifier: 0.1.2 @@ -99,7 +99,7 @@ importers: packages/core: dependencies: '@pegma/knowledge-base-contracts': - specifier: 0.1.1 + specifier: 0.1.2 version: link:../contracts packages/mcp: @@ -114,13 +114,13 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/knowledge-base-application': - specifier: 0.1.1 + specifier: 0.1.2 version: link:../application '@pegma/knowledge-base-contracts': - specifier: 0.1.1 + specifier: 0.1.2 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.1 + specifier: 0.1.2 version: link:../core zod: specifier: 4.6.7 diff --git a/test/README.md b/test/README.md index 6b04e55..55dfdef 100644 --- a/test/README.md +++ b/test/README.md @@ -81,5 +81,7 @@ establish actual site logins or target-client application acceptance. Local storage tests establish no browser UI, live Workers/host acceptance, model-provider settings, production throughput, or retention operations. All four KB `0.1.0` packages completed manual bootstrap -without OIDC provenance. KB `0.1.1` remains an unpublished candidate; its full -verified trusted release and the host activation gates remain required. +without OIDC provenance. The four-package KB `0.1.1` trusted release is now +[verified](../docs/BOOTSTRAP.md#verified-knowledge-base-release). Source `0.1.2` +remains a candidate with its own gates and verified trusted release required; +host activation gates remain open. diff --git a/test/atomic-draft-sources-fixtures.ts b/test/atomic-draft-sources-fixtures.ts new file mode 100644 index 0000000..609acb6 --- /dev/null +++ b/test/atomic-draft-sources-fixtures.ts @@ -0,0 +1,63 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import type { + CreateDraftInput, + PrivateSourceReference, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { + access, + applicationFixture, + author, + draft, +} from "./application-fixtures.js"; + +export type DraftOperation = "create" | "update"; +export type ApplicationFixture = ReturnType; + +export const sourceAuthor = access(author.principalId, [ + ...author.permissions, + knowledgePermissions.provenanceWrite, +]); + +export const firstSource: PrivateSourceReference = { + id: "source/first", + system: "fictional-support", + resourceId: "ticket/first", + version: "resolved/1", +}; + +export const secondSource: PrivateSourceReference = { + ...firstSource, + id: "source/second", + resourceId: "ticket/second", + version: "resolved/2", +}; + +/** Seeds updates through the public API; it owns no persistence or trust port. */ +export async function prepareDraftCommand( + fixture: ApplicationFixture, + operation: DraftOperation, + articleId = "article/atomic-sources", +): Promise { + const expectedGeneration = + operation === "create" + ? 0 + : (await fixture.createDraft(articleId)).generation; + return { + ...fixture.command(`atomic-${operation}`, expectedGeneration), + articleId, + collectionId: "collection/workshop", + draft: { ...draft(), title: `Atomic ${operation} with private sources` }, + }; +} + +export function invokeDraftCommand( + fixture: ApplicationFixture, + operation: DraftOperation, + input: CreateDraftInput, + caller: AccessContext = sourceAuthor, +) { + return operation === "create" + ? fixture.app.createDraft(caller, input) + : fixture.app.updateDraft(caller, input); +} diff --git a/tests/agent-source-boundary.test.ts b/tests/agent-source-boundary.test.ts new file mode 100644 index 0000000..621ec96 --- /dev/null +++ b/tests/agent-source-boundary.test.ts @@ -0,0 +1,130 @@ +import type { PrivateSourceReference } from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { + knowledgeAgentScopes, + type KnowledgeAgentInputMap, + type KnowledgeAgentOperation, +} from "@pegma/knowledge-base-mcp"; +import { createMemoryStore } from "@pegma/storage-core"; +import { describe, expect, expectTypeOf, it } from "vitest"; +import { admin, author, draft } from "../test/application-fixtures.js"; +import { + agentChannels, + agentFixture, + agentIdentity, + agentResult, + expectPrivateAgentError, +} from "../test/agent-fixtures.js"; +import { allKnowledgeRows } from "../test/application-stores.js"; +import { traceStore } from "../test/trace-store.js"; + +const source: PrivateSourceReference = { + id: "source/private", + system: "synthetic-support", + resourceId: "PRIVATE_SOURCE_TICKET_7", + version: "resolution-2", +}; + +describe("initial agent provenance boundary", () => { + it("keeps host-only source delivery out of agent authoring input types", () => { + expectTypeOf() + .extract<"sourceReferences">() + .toBeNever(); + expectTypeOf() + .extract<"sourceReferences">() + .toBeNever(); + }); + + for (const channel of ["dispatcher", ...agentChannels] as const) { + it(`${channel} rejects source delivery before mutation while ordinary draft authoring preserves provenance`, async () => { + const traced = traceStore(createMemoryStore()); + const f = agentFixture(traced.store); + await f.setupCollection(); + // A broader host context and an unregistered requested scope still cannot + // widen the five initial operations into provenance authoring. + f.authority.current = { + ...agentIdentity(), + access: admin, + scopes: [ + ...Object.values(knowledgeAgentScopes), + knowledgePermissions.provenanceWrite, + ], + }; + const call = (operation: KnowledgeAgentOperation, input: unknown) => + channel === "dispatcher" + ? f.dispatcher.dispatch(f.authority.current, { + apiVersion: "1", + operation, + input, + }) + : f.call(channel, operation, input); + const create = { + ...f.command("agent-create", 0), + articleId: "article/agent-export", + collectionId: "collection/workshop", + draft: draft(), + }; + const beforeCreate = await allKnowledgeRows(f.store); + const createTransactions = traced.transactions.length; + for (const sourceReferences of [[source], []]) { + expectPrivateAgentError( + await call("createDraft", { ...create, sourceReferences }), + "invalid_request", + ); + expect(traced.transactions).toHaveLength(createTransactions); + expect(await allKnowledgeRows(f.store)).toEqual(beforeCreate); + } + expect( + agentResult(await call("createDraft", create), "createDraft"), + ).toMatchObject({ + replayed: false, + value: { generation: 1, articleRevision: 1 }, + }); + let current = await f.app.getDraft(author, { + articleId: create.articleId, + }); + current = await f.setSources(current, [source]); + const provenance = await f.app.getProvenance(admin, { + articleId: current.articleId, + }); + const update = { + ...f.command("agent-update", current.generation), + articleId: current.articleId, + collectionId: current.revision.collectionId, + draft: { ...draft(), title: "Export a fictional workspace safely" }, + }; + const beforeUpdate = await allKnowledgeRows(f.store); + const updateTransactions = traced.transactions.length; + for (const sourceReferences of [[{ ...source, version: "3" }], []]) { + expectPrivateAgentError( + await call("updateDraft", { ...update, sourceReferences }), + "invalid_request", + ); + expect(traced.transactions).toHaveLength(updateTransactions); + expect(await allKnowledgeRows(f.store)).toEqual(beforeUpdate); + } + expect( + agentResult(await call("updateDraft", update), "updateDraft"), + ).toMatchObject({ + replayed: false, + value: { + generation: current.generation + 1, + articleRevision: 2, + }, + }); + const visible = agentResult( + await call("getDraft", { articleId: current.articleId }), + "getDraft", + ); + expect(visible.revision.title).toBe(update.draft.title); + expect(JSON.stringify(visible)).not.toContain(source.resourceId); + expect( + ( + await f.app.getProvenance(admin, { + articleId: current.articleId, + }) + ).snapshot, + ).toEqual(provenance.snapshot); + }); + } +}); diff --git a/tests/atomic-draft-sources.test.ts b/tests/atomic-draft-sources.test.ts new file mode 100644 index 0000000..1f03d82 --- /dev/null +++ b/tests/atomic-draft-sources.test.ts @@ -0,0 +1,689 @@ +import type { + CreateDraftInput, + KnowledgeRecord, + PrivateSourceReference, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { describe, expect, it } from "vitest"; +import { + access, + admin, + applicationFixture, + author, + customer, +} from "../test/application-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { + firstSource, + invokeDraftCommand, + prepareDraftCommand, + secondSource, + sourceAuthor, +} from "../test/atomic-draft-sources-fixtures.js"; +import { barrier, traceStore } from "../test/trace-store.js"; + +const operations = ["create", "update"] as const; +const prerequisite = { name: "KnowledgeBasePrerequisiteError" }; +const conflict = { name: "RepositoryConflictError" }; + +function articleRows(rows: readonly KnowledgeRecord[], articleId: string) { + return rows.filter( + (row) => row.resourceKind === "article" && row.resourceId === articleId, + ); +} + +for (const [name, createStore] of storeFactories) { + describe(`Atomic draft content and private sources (${name})`, () => { + it.each(operations)( + "makes %s content and its new source snapshot observable in one transaction", + async (operation) => { + const backing = await createStore(); + const traced = traceStore(backing); + const f = applicationFixture(traced.store); + await f.setupCollection(); + const input = { + ...(await prepareDraftCommand(f, operation)), + sourceReferences: [firstSource, secondSource], + }; + const before = await allKnowledgeRows(backing); + const observations: KnowledgeRecord[][] = []; + traced.transactions.length = 0; + f.privateSources.canRead.mockClear(); + traced.intercept(async (_trace, commit) => { + observations.push(await allKnowledgeRows(backing)); + if (operation === "create") { + expect(articleRows(observations[0]!, input.articleId)).toHaveLength( + 0, + ); + for (const reference of input.sourceReferences) + expect(f.privateSources.canRead).toHaveBeenCalledWith({ + access: sourceAuthor, + articleId: input.articleId, + reference, + }); + } + const outcome = await commit(); + observations.push(await allKnowledgeRows(backing)); + return outcome; + }); + const accepted = await invokeDraftCommand(f, operation, input); + traced.intercept(undefined); + expect(traced.transactions).toHaveLength(1); + expect(traced.transactions[0]).toMatchObject({ + collection: "knowledge-base.records.v1", + partition: expect.stringMatching(/^article:[a-f0-9]{64}$/u), + }); + expect(observations[0]).toEqual(before); + const after = await allKnowledgeRows(backing); + expect(observations[1]).toEqual(after); + const priorIds = new Set( + articleRows(before, input.articleId).map((row) => row.id), + ); + const additions = articleRows(after, input.articleId).filter( + (row) => !priorIds.has(row.id), + ); + expect(additions.map((row) => row.kind).sort()).toEqual( + operation === "create" + ? ["audit", "command", "head", "job", "provenance", "revision"] + : ["audit", "command", "job", "provenance", "revision"], + ); + const current = await f.app.getDraft(admin, { + articleId: input.articleId, + }); + const provenance = await f.app.getProvenance(admin, { + articleId: input.articleId, + }); + expect(current).toMatchObject({ + generation: input.expectedGeneration + 1, + revision: { title: input.draft.title }, + }); + expect(provenance).toMatchObject({ + generation: current.generation, + snapshot: { + generation: operation === "create" ? 1 : 2, + references: input.sourceReferences, + hash: expect.stringMatching(/^[a-f0-9]{64}$/u), + }, + }); + expect(accepted.value).toMatchObject({ + generation: current.generation, + contentHash: current.revision.contentHash, + }); + for (const reference of input.sourceReferences) + expect(f.privateSources.canRead).toHaveBeenCalledWith({ + access: sourceAuthor, + articleId: input.articleId, + reference, + }); + expect(f.privateSources.isCurrent).not.toHaveBeenCalled(); + expect(f.privateSources.canPublish).not.toHaveBeenCalled(); + }, + ); + + it.each(operations)( + "leaves no losing %s revision or provenance after a real competing transaction wins", + async (operation) => { + const backing = await createStore(); + const winner = applicationFixture(backing); + await winner.setupCollection(); + const original = await prepareDraftCommand(winner, operation); + const traced = traceStore(backing); + const loser = applicationFixture(traced.store); + const losingInput = { + ...original, + sourceReferences: [firstSource], + }; + const gate = barrier(); + let refusedTransactions = 0; + traced.intercept(async (_trace, commit) => { + await gate.wait(); + const outcome = await commit(); + if (!outcome.committed) refusedTransactions += 1; + return outcome; + }); + const pending = invokeDraftCommand(loser, operation, losingInput).then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); + let committedRows: KnowledgeRecord[] | undefined; + try { + await Promise.race([ + gate.reached, + pending.then(() => { + throw new Error("Draft did not reach its transaction barrier"); + }), + ]); + await invokeDraftCommand(winner, operation, { + ...original, + ...winner.command("winning-draft", original.expectedGeneration), + draft: { ...original.draft, title: "Winning content and sources" }, + sourceReferences: [secondSource], + }); + committedRows = await allKnowledgeRows(backing); + } finally { + gate.release(); + } + expect(await pending).toMatchObject({ error: conflict }); + traced.intercept(undefined); + expect(refusedTransactions).toBe(1); + expect(await allKnowledgeRows(backing)).toEqual(committedRows); + expect( + await winner.app.getProvenance(admin, { + articleId: original.articleId, + }), + ).toMatchObject({ snapshot: { references: [secondSource] } }); + expect( + await winner.app.getDraft(admin, { articleId: original.articleId }), + ).toMatchObject({ revision: { title: "Winning content and sources" } }); + }, + ); + + it("keeps omitted sources compatible with legacy authority and exact replay fingerprints", async () => { + const backing = await createStore(); + const f = applicationFixture(backing); + await f.setupCollection(); + const withoutSources = applicationFixture(backing, { + missingPrivateSources: true, + }); + const create = await prepareDraftCommand(withoutSources, "create"); + const created = await invokeDraftCommand( + withoutSources, + "create", + create, + author, + ); + let current = await f.app.getDraft(author, { + articleId: create.articleId, + }); + expect( + await withoutSources.app.getProvenance(admin, { + articleId: create.articleId, + }), + ).toMatchObject({ snapshot: { generation: 1, references: [] } }); + current = await f.setSources(current, [firstSource]); + const originalSources = await f.app.getProvenance(admin, { + articleId: create.articleId, + }); + const update = { + ...create, + ...f.command("legacy-update", current.generation), + draft: { ...create.draft, title: "Legacy source-preserving edit" }, + }; + const updated = await invokeDraftCommand( + withoutSources, + "update", + update, + author, + ); + expect( + (await f.app.getProvenance(admin, { articleId: create.articleId })) + .snapshot, + ).toEqual(originalSources.snapshot); + f.trust.canReadSource = false; + const beforeReplay = await allKnowledgeRows(backing); + for (const [operation, input, accepted] of [ + ["create", create, created], + ["update", update, updated], + ] as const) { + expect( + await invokeDraftCommand(withoutSources, operation, input, author), + ).toEqual({ value: accepted.value, replayed: true }); + await expect( + invokeDraftCommand(f, operation, { + ...input, + sourceReferences: [], + }), + ).rejects.toMatchObject(conflict); + } + expect(await allKnowledgeRows(backing)).toEqual(beforeReplay); + // Empty supplied snapshots still require both permissions, but need no + // external source verifier even when replacing a nonempty snapshot. + current = await withoutSources.app.getDraft(author, { + articleId: create.articleId, + }); + await withoutSources.app.updateDraft(sourceAuthor, { + ...update, + ...f.command("clear-without-verifier", current.generation), + sourceReferences: [], + }); + expect( + await withoutSources.app.getProvenance(admin, { + articleId: create.articleId, + }), + ).toMatchObject({ + snapshot: { + generation: originalSources.snapshot.generation + 1, + references: [], + }, + }); + }); + + it.each(operations)( + "requires draft-write and provenance-write together for supplied %s sources, including an empty list", + async (operation) => { + const f = applicationFixture(await createStore()); + await f.setupCollection(); + for (const references of [[], [firstSource]]) { + for (const permissions of [ + [], + [knowledgePermissions.draftWrite], + [knowledgePermissions.provenanceWrite], + [ + knowledgePermissions.draftWrite, + knowledgePermissions.provenanceWrite, + ], + ]) { + const input = { + ...(await prepareDraftCommand( + f, + operation, + `article/permissions-${references.length}-${permissions.join("-") || "none"}`, + )), + sourceReferences: references, + }; + const caller = access(author.principalId, permissions); + const before = await allKnowledgeRows(f.store); + if (permissions.length === 2) { + await invokeDraftCommand(f, operation, input, caller); + expect( + await f.app.getProvenance(admin, { + articleId: input.articleId, + }), + ).toMatchObject({ snapshot: { references } }); + } else { + await expect( + invokeDraftCommand(f, operation, input, caller), + ).rejects.toMatchObject({ + name: "KnowledgeBaseAuthorizationError", + permission: permissions.includes( + knowledgePermissions.draftWrite, + ) + ? knowledgePermissions.provenanceWrite + : knowledgePermissions.draftWrite, + }); + expect(await allKnowledgeRows(f.store)).toEqual(before); + } + } + } + }, + ); + + it.each(["missing", "throwing", "denied"] as const)( + "fails closed before either draft write when source authorization is %s", + async (defect) => { + const backing = await createStore(); + const traced = traceStore(backing); + const f = applicationFixture(traced.store); + await f.setupCollection(); + for (const operation of operations) { + const input = { + ...(await prepareDraftCommand( + f, + operation, + `article/${defect}-${operation}`, + )), + sourceReferences: [firstSource], + }; + const writer = + defect === "missing" + ? applicationFixture(traced.store, { + missingPrivateSources: true, + }) + : f; + if (defect === "throwing") + f.privateSources.canRead.mockRejectedValue( + new Error("Source port unavailable"), + ); + if (defect === "denied") f.trust.canReadSource = false; + traced.transactions.length = 0; + const before = await allKnowledgeRows(backing); + await expect( + invokeDraftCommand(writer, operation, input), + ).rejects.toMatchObject({ + ...prerequisite, + prerequisite: + defect === "missing" + ? "private-source-verifier" + : "source-access", + }); + expect(traced.transactions).toHaveLength(0); + expect(await allKnowledgeRows(backing)).toEqual(before); + } + }, + ); + + it.each(operations)( + "rechecks current permissions and source access before replaying an accepted %s", + async (operation) => { + const backing = await createStore(); + const f = applicationFixture(backing); + await f.setupCollection(); + for (const sourceReferences of [[], [firstSource]]) { + const input = { + ...(await prepareDraftCommand( + f, + operation, + `article/replay-${sourceReferences.length}`, + )), + sourceReferences, + }; + const accepted = await invokeDraftCommand(f, operation, input); + const before = await allKnowledgeRows(backing); + for (const permission of [ + knowledgePermissions.draftWrite, + knowledgePermissions.provenanceWrite, + ]) { + const revoked = access( + sourceAuthor.principalId, + sourceAuthor.permissions.filter((value) => value !== permission), + ); + await expect( + invokeDraftCommand(f, operation, input, revoked), + ).rejects.toMatchObject({ + name: "KnowledgeBaseAuthorizationError", + permission, + }); + } + if (sourceReferences.length > 0) { + f.trust.canReadSource = false; + await expect( + invokeDraftCommand(f, operation, input), + ).rejects.toMatchObject({ + ...prerequisite, + prerequisite: "source-access", + }); + f.trust.canReadSource = true; + f.privateSources.canRead.mockImplementationOnce(async () => { + f.trust.canReadSource = false; + return true; + }); + await expect( + invokeDraftCommand(f, operation, input), + ).rejects.toMatchObject({ + ...prerequisite, + prerequisite: "source-access", + }); + f.trust.canReadSource = true; + await expect( + invokeDraftCommand(f, operation, { + ...input, + sourceReferences: [secondSource], + }), + ).rejects.toMatchObject(conflict); + } + expect(await invokeDraftCommand(f, operation, input)).toEqual({ + value: accepted.value, + replayed: true, + }); + expect(await allKnowledgeRows(backing)).toEqual(before); + } + }, + ); + + it.each(operations)( + "withdraws source access between a refused %s CAS and its retry without writing", + async (operation) => { + const backing = await createStore(); + const traced = traceStore(backing); + const f = applicationFixture(traced.store); + await f.setupCollection(); + const input = { + ...(await prepareDraftCommand(f, operation)), + sourceReferences: [firstSource], + }; + const before = await allKnowledgeRows(backing); + f.privateSources.canRead.mockClear(); + traced.transactions.length = 0; + traced.intercept(async () => { + f.trust.canReadSource = false; + return { committed: false, reason: "changed" }; + }); + await expect( + invokeDraftCommand(f, operation, input), + ).rejects.toMatchObject({ + ...prerequisite, + prerequisite: "source-access", + }); + traced.intercept(undefined); + expect(traced.transactions).toHaveLength(1); + expect(f.privateSources.canRead).toHaveBeenCalledTimes(2); + expect(await allKnowledgeRows(backing)).toEqual(before); + }, + ); + + it.each(["unknown outcome", "postcommit source withdrawal"] as const)( + "recovers an atomic accepted command after %s without duplicating retained work", + async (failure) => { + const backing = await createStore(); + const traced = traceStore(backing); + const f = applicationFixture(traced.store); + await f.setupCollection(); + for (const operation of operations) { + const input = { + ...(await prepareDraftCommand( + f, + operation, + `article/recovery-${operation}`, + )), + sourceReferences: [firstSource], + }; + traced.transactions.length = 0; + traced.intercept(async (_trace, commit) => { + const outcome = await commit(); + if (!outcome.committed) + throw new Error("Expected the real transaction to commit"); + if (failure === "unknown outcome") + throw new Error( + "Synthetic transport lost the accepted acknowledgement", + ); + f.trust.canReadSource = false; + return outcome; + }); + await expect( + invokeDraftCommand(f, operation, input), + ).rejects.toMatchObject( + failure === "unknown outcome" + ? { + message: + "Synthetic transport lost the accepted acknowledgement", + } + : { ...prerequisite, prerequisite: "source-access" }, + ); + traced.intercept(undefined); + f.trust.canReadSource = true; + const committed = await allKnowledgeRows(backing); + expect( + await f.app.getDraft(admin, { articleId: input.articleId }), + ).toMatchObject({ revision: { title: input.draft.title } }); + expect( + await f.app.getProvenance(admin, { articleId: input.articleId }), + ).toMatchObject({ snapshot: { references: [firstSource] } }); + const replayed = await invokeDraftCommand(f, operation, input); + expect(replayed.replayed).toBe(true); + expect(replayed.value.generation).toBe(input.expectedGeneration + 1); + expect(Object.keys(replayed.value).sort()).toEqual([ + "articleRevision", + "contentHash", + "generation", + "id", + "state", + ]); + expect(await allKnowledgeRows(backing)).toEqual(committed); + expect(traced.transactions).toHaveLength(1); + const rows = articleRows(committed, input.articleId); + for (const kind of [ + "audit", + "command", + "job", + "provenance", + "revision", + ]) + expect(rows.filter((row) => row.kind === kind)).toHaveLength( + operation === "create" ? 1 : 2, + ); + } + }, + ); + + it("rejects malformed, excessive, duplicate, and URL source references before either draft can mutate", async () => { + const backing = await createStore(); + const traced = traceStore(backing); + const f = applicationFixture(traced.store); + await f.setupCollection(); + const { version: _version, ...missingVersion } = firstSource; + const invalidReferences: readonly (readonly [unknown, string])[] = [ + [null, "RepositoryCapacityError"], + [[null], "TypeError"], + [[missingVersion], "TypeError"], + [ + [{ ...firstSource, body: "Source content is forbidden" }], + "TypeError", + ], + [[{ ...firstSource, version: "v".repeat(201) }], "TypeError"], + [[{ ...firstSource, resourceId: "ticket/\u0000" }], "TypeError"], + [[{ ...firstSource, id: "source/\ud800" }], "TypeError"], + [ + [firstSource, { ...firstSource, resourceId: "ticket/duplicate-id" }], + "TypeError", + ], + [ + Array.from({ length: 33 }, (_, ordinal) => ({ + ...firstSource, + id: `source/${ordinal}`, + })), + "RepositoryCapacityError", + ], + ...["id", "system", "resourceId", "version"].map( + (field) => + [ + [ + { + ...firstSource, + [field]: "https://fictional.invalid/private", + }, + ], + "TypeError", + ] as const, + ), + ]; + for (const operation of operations) { + const input = await prepareDraftCommand( + f, + operation, + `article/invalid-${operation}`, + ); + const before = await allKnowledgeRows(backing); + traced.transactions.length = 0; + for (const [references, errorName] of invalidReferences) { + // Real host JSON can reach this boundary despite the static type. + const malformed = { + ...input, + sourceReferences: references as readonly PrivateSourceReference[], + } satisfies CreateDraftInput; + await expect( + invokeDraftCommand(f, operation, malformed), + ).rejects.toMatchObject({ name: errorName }); + } + expect(traced.transactions).toHaveLength(0); + expect(await allKnowledgeRows(backing)).toEqual(before); + } + }); + + it("accepts readable draft sources independently of publication eligibility and preserves the old publication snapshot", async () => { + const f = applicationFixture(await createStore()); + await f.setupCollection(); + f.trust.sourceCurrent = false; + f.trust.canPublishSource = false; + const input = { + ...(await prepareDraftCommand(f, "create")), + sourceReferences: [firstSource], + }; + await invokeDraftCommand(f, "create", input); + expect(f.privateSources.isCurrent).not.toHaveBeenCalled(); + expect(f.privateSources.canPublish).not.toHaveBeenCalled(); + let current = await f.app.getDraft(author, { + articleId: input.articleId, + }); + current = (await f.submitEvidence(current)).current; + const beforeReview = await allKnowledgeRows(f.store); + await expect(f.review(current)).rejects.toMatchObject(prerequisite); + expect(await allKnowledgeRows(f.store)).toEqual(beforeReview); + f.trust.sourceCurrent = true; + f.trust.canPublishSource = true; + const reviewed = await f.review(current); + const publish = { + ...f.command("publish-after-source-approval", reviewed.generation), + articleId: input.articleId, + review: reviewed.review, + }; + f.trust.canPublishSource = false; + const beforePublish = await allKnowledgeRows(f.store); + await expect(f.app.publishArticle(admin, publish)).rejects.toMatchObject( + prerequisite, + ); + expect(await allKnowledgeRows(f.store)).toEqual(beforePublish); + f.trust.canPublishSource = true; + await f.app.publishArticle(admin, publish); + const published = await f.app.getPublishedArticle(customer, { + articleId: input.articleId, + }); + const oldSources = await f.app.getProvenance(admin, { + articleId: input.articleId, + }); + expect(oldSources.publishedSnapshot).toEqual(oldSources.snapshot); + current = await f.app.getDraft(author, { articleId: input.articleId }); + f.trust.sourceCurrent = false; + f.trust.canPublishSource = false; + f.privateSources.isCurrent.mockClear(); + f.privateSources.canPublish.mockClear(); + await f.app.updateDraft(sourceAuthor, { + ...f.command("new-draft-with-new-source", current.generation), + articleId: input.articleId, + collectionId: input.collectionId, + draft: { ...input.draft, title: "Unapproved second-source draft" }, + sourceReferences: [secondSource], + }); + expect(f.privateSources.isCurrent).not.toHaveBeenCalled(); + expect(f.privateSources.canPublish).not.toHaveBeenCalled(); + const updatedSources = await f.app.getProvenance(admin, { + articleId: input.articleId, + }); + expect(updatedSources.snapshot).toMatchObject({ + generation: oldSources.snapshot.generation + 1, + references: [secondSource], + }); + expect(updatedSources.publishedSnapshot).toEqual( + oldSources.publishedSnapshot, + ); + f.privateSources.isCurrent.mockImplementation(async ({ snapshot }) => + snapshot.references.every( + (reference) => reference.id === firstSource.id, + ), + ); + f.privateSources.canPublish.mockImplementation(async ({ snapshot }) => + snapshot.references.every( + (reference) => reference.id === firstSource.id, + ), + ); + expect( + await f.app.getPublishedArticle(customer, { + articleId: input.articleId, + }), + ).toEqual(published); + expect(f.privateSources.isCurrent).toHaveBeenLastCalledWith( + expect.objectContaining({ snapshot: oldSources.publishedSnapshot }), + ); + current = await f.app.getDraft(author, { articleId: input.articleId }); + current = (await f.submitEvidence(current)).current; + await expect(f.review(current)).rejects.toMatchObject(prerequisite); + expect( + await f.app.getPublishedArticle(customer, { + articleId: input.articleId, + }), + ).toEqual(published); + }); + }); +} From 639da5edec3fcae50911c40bac55b4764b0b330c Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sat, 7 Nov 2026 20:39:45 -0500 Subject: [PATCH 2/2] fix: validate source writes without rejecting legacy snapshots --- docs/COLLECTIONS.md | 21 ++- docs/HOST_COMPOSITION.md | 27 +++- package.json | 1 + packages/application/README.md | 29 +++- packages/application/src/articles.ts | 26 ++- pnpm-lock.yaml | 32 ++++ test/README.md | 8 + test/atomic-draft-sources-fixtures.ts | 26 +++ tests/atomic-draft-sources.test.ts | 218 +++++++++++++++++++++++++- 9 files changed, 365 insertions(+), 23 deletions(-) diff --git a/docs/COLLECTIONS.md b/docs/COLLECTIONS.md index 4b09aba..3f09294 100644 --- a/docs/COLLECTIONS.md +++ b/docs/COLLECTIONS.md @@ -169,11 +169,20 @@ boundary; it does not append an unbounded attempt log. Direct host `createDraft`/`updateDraft` inputs may include complete `sourceReferences`. Presence, including `[]`, requires both `draftWrite` and `provenanceWrite`. Every supplied reference must pass current `canRead` checks, -repeated on CAS retry and exact replay. Content and the current private -provenance snapshot commit in the existing article transaction with its head, +repeated on CAS retry, after a successful commit, and on exact replay. Content +and current private provenance commit in the existing article transaction with its head, immutable rows, Audit, receipt, and causal jobs; there is no second provenance write. An update preserves the older publication's separate -`publishedProvenance`. Omission retains the legacy draft-only behavior. +`publishedProvenance`. Each accepted command supplying the field creates a fresh +current source-snapshot generation even when the references are unchanged, as +with `setProvenance`; bounded history admission still applies. Exact replay adds +no rows. An absent property retains legacy draft-only behavior and preserves an +existing current source snapshot; `sourceReferences: undefined` is rejected by +the strict JSON-data boundary. + +The exact ordered array participates in both command and source-snapshot +identity. Persist and retry its original order; a same-command-ID permutation +conflicts without writes. This closes SD-03's empty/stale source window only when the owning host always supplies its complete nonempty reference set. A readable source may still be @@ -195,6 +204,12 @@ that the acknowledged content is still published or usable. A separate current read establishes current availability. Published-history hydration uses its exact retained immutable versions, not the new mutable draft's material. +A post-commit source-read denial or unavailable dependency can return an error +after the mutation was accepted. Do not assume rollback or issue a new command +ID. Under refreshed authority, retry the same command ID, exact payload and +source order, and original `expectedGeneration` to resolve its bounded historical +acknowledgement without duplicate writes. + Invalid rows or an unavailable dependency produce a visible failure. There is no best-effort acceptance through Spine's event bus. Projection/search repair cannot authorize a read or hide a failed authoritative diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index 47d25b7..f3eb5f1 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -139,11 +139,22 @@ Privileged hosts calling `createDraft` or `updateDraft` directly may pass option `sourceReferences` as the complete current private source set. Supplying the field requires both `draftWrite` and `provenanceWrite`, even for `[]`; every reference must pass `PrivateSourcesVerifier.canRead`. The application repeats -these current operation/resource and per-reference checks after a CAS conflict -and before acknowledging exact replay. Content and current provenance commit +per-reference checks after a CAS conflict, after a successful commit, and before +acknowledging exact replay; current operation/resource authority also remains +required. Content and current provenance commit atomically in the existing article transaction, including Audit, receipt, and causal jobs. Updating a draft preserves the older publication's separate -`publishedProvenance`. Omitting the field retains legacy draft-only behavior. +`publishedProvenance`. Omission means the property is absent and retains legacy +draft-only behavior, preserving an existing current source snapshot. Explicit +`undefined` is rejected by the strict JSON-data boundary rather than normalized +away. + +The exact ordered `sourceReferences` array participates in command and +source-snapshot identity. Persist and retry its original order; a same-command-ID +permutation conflicts without writes. Each accepted command supplying the field +creates a fresh current source-snapshot generation even for unchanged references, +as with `setProvenance`, subject to bounded history admission. Exact replay adds +no rows. SD-03 closes its empty/stale source window only if the owning host always supplies a complete nonempty reference set for each generated draft create or @@ -334,10 +345,12 @@ replay, while a new command must match current generation. A retained receipt cannot restore access after revocation. A storage or transport failure can leave the caller uncertain whether the -transaction committed. Retry the same command ID and exact semantic input, -including its original expected generation, under freshly resolved access. -The committed receipt resolves an accepted command without duplicating its -effects; an unknown outcome is not a reason to issue a new command ID. +transaction committed. A post-commit source-read denial or dependency error can +also follow an accepted mutation. Do not assume rollback or issue a new command +ID. Retry the same command ID and exact payload, including the source-reference +order and original `expectedGeneration`, under freshly resolved authority. +The committed receipt resolves the bounded historical acknowledgement without +duplicating effects once the current authorization checks pass. Resource generation, content revision, and opaque store version are distinct: the first is the application command fence, the second identifies immutable diff --git a/package.json b/package.json index 91ec2a5..081f7f1 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "@modelcontextprotocol/sdk": "1.32.2", "@pegma/authorization-core": "0.4.0", "@pegma/knowledge-base-application": "0.1.2", + "@pegma/knowledge-base-application-previous": "npm:@pegma/knowledge-base-application@0.1.1", "@pegma/knowledge-base-contracts": "0.1.2", "@pegma/knowledge-base-core": "0.1.2", "@pegma/knowledge-base-mcp": "0.1.2", diff --git a/packages/application/README.md b/packages/application/README.md index ee0e88b..092166f 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -63,10 +63,25 @@ Privileged direct host calls to `createDraft`/`updateDraft` may supply optional `sourceReferences` as the complete current private source set. Presence, including `[]`, requires both `draftWrite` and `provenanceWrite`; every reference must pass current `PrivateSourcesVerifier.canRead` checks on the initial -attempt, CAS retry, and exact replay. Content and current provenance commit in -one existing article transaction with Audit, receipt, and causal jobs. An update -preserves the older publication's `publishedProvenance`. Omission retains -legacy draft-only behavior. +attempt, CAS retry, after a successful commit, and on exact replay. Content and +current provenance commit in one existing article transaction with Audit, +receipt, and causal jobs. An update preserves the older publication's +`publishedProvenance`. Omission means the +property is absent and retains legacy draft-only behavior, preserving an existing +current source snapshot. Explicit `undefined` is rejected by the strict JSON-data +boundary. + +The exact ordered array participates in command and source-snapshot identity. +Persist and retry that order: a same-command-ID permutation conflicts without +writes. Each accepted command supplying the field creates a fresh current +source-snapshot generation even when references are unchanged, as with +`setProvenance`, subject to bounded history admission. Exact replay adds no rows. + +Historical source snapshots retain the `0.1.1` structural and hash rules; +stricter URL-prefix hygiene applies only to newly supplied write inputs. +Existing opaque keys such as `git:issue/1` or `data:row42` remain reviewable and +publishable subject to the same current source eligibility and exact approval +gates. Draft edits that omit `sourceReferences` preserve those snapshots. SD-03 hosts must always supply a complete nonempty set to close the empty/stale source window. A readable reference may still be ineligible or stale; @@ -79,6 +94,12 @@ historical acknowledgement. It contains no body/evidence/provenance. Replay rechecks current operation/resource authority, conflicts on changed semantic input, and does not claim the historical result is currently servable. +A source-read denial or dependency error after commit may follow an accepted +mutation. Do not assume rollback or use a new command ID. Under refreshed +authority, retry the same command ID and exact payload, including source order +and the original `expectedGeneration`, to resolve the bounded historical +acknowledgement without duplicate writes. + ## Reads and trust `getDraft`, `getEvidence`, `getProvenance`, and `getReview` have distinct diff --git a/packages/application/src/articles.ts b/packages/application/src/articles.ts index 97b3f99..c6b1747 100644 --- a/packages/application/src/articles.ts +++ b/packages/application/src/articles.ts @@ -48,6 +48,7 @@ import type { PrivateSourceReference, ReviewSnapshot, SourceSnapshot, + UpdateDraftInput, } from "./types.js"; type ArticleMethods = Pick< @@ -169,11 +170,11 @@ function acknowledgement( function validateReferences( references: readonly PrivateSourceReference[], + mode: "write" | "historical" = "write", ): void { - if ( - !Array.isArray(references) || - references.length > maximumSourceReferences - ) { + if (!Array.isArray(references)) + throw new TypeError("Source references must be an array"); + if (references.length > maximumSourceReferences) { throw new RepositoryCapacityError("source_references"); } const ids = new Set(); @@ -185,7 +186,14 @@ function validateReferences( ); for (const [field, value] of Object.entries(reference)) { boundedText(value, "source." + field, 200); - if (value.includes("://")) + if ( + value.includes("://") || + (mode === "write" && + (value.startsWith("//") || + /^(?:https?|wss?|ftps?|file|data|javascript|vbscript|blob|mailto|tel|sms|ssh|git):/iu.test( + value, + ))) + ) throw new TypeError("Source references must use opaque identifiers"); } for (const field of ["id", "system", "resourceId", "version"] as const) { @@ -209,7 +217,8 @@ async function sourceSnapshot( async function verifySourceSnapshot(snapshot: SourceSnapshot): Promise { requireGeneration(snapshot.generation, 1); - validateReferences(snapshot.references); + // Preserve the lexical rules under which an existing snapshot was accepted. + validateReferences(snapshot.references, "historical"); if ( snapshot.hash !== (await fingerprint({ @@ -305,7 +314,10 @@ export function createArticleServices( } async function recheckDraftSources( - command: Pick, + command: Pick< + CreateDraftInput | UpdateDraftInput, + "articleId" | "sourceReferences" + >, caller: AccessContext, ): Promise { if (command.sourceReferences === undefined) return; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3f741da..5b894f9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -26,6 +26,9 @@ importers: '@pegma/knowledge-base-application': specifier: 0.1.2 version: link:packages/application + '@pegma/knowledge-base-application-previous': + specifier: npm:@pegma/knowledge-base-application@0.1.1 + version: '@pegma/knowledge-base-application@0.1.1' '@pegma/knowledge-base-contracts': specifier: 0.1.2 version: link:packages/contracts @@ -819,6 +822,18 @@ packages: resolution: {integrity: sha512-GkagQwyDfKokB2Nm9EAo6cvKB8c90VN6Or6IdaWeMwCeuseOxDZ8ccxKqccW9YorByE6rHhr2nbxjsNWorZTHQ==} engines: {node: '>=22'} + '@pegma/knowledge-base-application@0.1.1': + resolution: {integrity: sha512-9aFTznz8mbFrkBFNZTwoT9P5geu0y2wHdMCGgXGnaBSHPsVoSqfoMjkGK3o1tPO8KFF+bY2epPaAc8+a1Uc0PQ==} + engines: {node: '>=22'} + + '@pegma/knowledge-base-contracts@0.1.1': + resolution: {integrity: sha512-gtoOLSnKfnmbTyLZqm77O2XVrcgVsDu53HHReY5vtIRrPFscsis2LI4+xea7wLZkp3xMjrByQIs93JxhNRR9fw==} + engines: {node: '>=22'} + + '@pegma/knowledge-base-core@0.1.1': + resolution: {integrity: sha512-iDL70YAYe0ZRFhVsCxnBuu/3Y1iVsJSd5bhkazNob/iGY5dJNTMWfUJBZQI3UU1Pst2YzFict84pGPxw5147Qw==} + engines: {node: '>=22'} + '@pegma/spine@0.1.1': resolution: {integrity: sha512-EV0Zq8KJX7r7ybI+eIHUCAhnd261bveZykMQVmmZibSDRJVcd2bOuYCPvPg4wax7GmrUrdtVFJYEJqHl4PkhwQ==} engines: {node: '>=22'} @@ -3385,6 +3400,23 @@ snapshots: dependencies: '@pegma/authorization-contracts': 0.4.0 + '@pegma/knowledge-base-application@0.1.1': + dependencies: + '@pegma/audit': 0.2.0 + '@pegma/authorization-core': 0.4.0 + '@pegma/knowledge-base-contracts': 0.1.1 + '@pegma/knowledge-base-core': 0.1.1 + '@pegma/spine': 0.1.2 + '@pegma/storage-core': 0.4.0 + + '@pegma/knowledge-base-contracts@0.1.1': + dependencies: + '@pegma/spine': 0.1.2 + + '@pegma/knowledge-base-core@0.1.1': + dependencies: + '@pegma/knowledge-base-contracts': 0.1.1 + '@pegma/spine@0.1.1': {} '@pegma/spine@0.1.2': {} diff --git a/test/README.md b/test/README.md index 55dfdef..4c1e30d 100644 --- a/test/README.md +++ b/test/README.md @@ -17,6 +17,14 @@ boundary, not a production attestation or credential implementation. Evidence times follow the draft being tested; malformed-time cases call the public service directly instead of using the successful-staging helper. +Upgrade tests use the dev-only exact registry alias +`@pegma/knowledge-base-application-previous` to +`npm:@pegma/knowledge-base-application@0.1.1` to write real legacy records before +the candidate reads them. The lockfile integrity pin matches the previously +verified `0.1.1` artifact; no copied source or branch supplies this writer. +The four candidate runtime packages remain `0.1.2`, and the Agent Access +protocol-proof pin remains `0.1.1`. + `trace-store.ts` delegates every record operation to the supplied real store. Its transaction interception adds refusals or a manual race barrier; captured traces are observations, not another persistence implementation. The race diff --git a/test/atomic-draft-sources-fixtures.ts b/test/atomic-draft-sources-fixtures.ts index 609acb6..62dee91 100644 --- a/test/atomic-draft-sources-fixtures.ts +++ b/test/atomic-draft-sources-fixtures.ts @@ -3,10 +3,14 @@ import type { CreateDraftInput, PrivateSourceReference, } from "@pegma/knowledge-base-application"; +import { createKnowledgeBaseApplication as createPreviousApplication } from "@pegma/knowledge-base-application-previous"; import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; import { access, applicationFixture, + at, author, draft, } from "./application-fixtures.js"; @@ -33,6 +37,28 @@ export const secondSource: PrivateSourceReference = { version: "resolved/2", }; +/** Uses the exact published previous writer, never reconstructed storage rows. */ +export async function publishedPreviousApplication( + fixture: ApplicationFixture, +) { + const manifest: { name?: unknown; version?: unknown } = JSON.parse( + await readFile( + new URL( + "../package.json", + import.meta.resolve("@pegma/knowledge-base-application-previous"), + ), + "utf8", + ), + ); + assert.equal(manifest.name, "@pegma/knowledge-base-application"); + assert.equal(manifest.version, "0.1.1"); + return createPreviousApplication({ + store: fixture.store, + clock: { now: () => at() }, + privateSources: fixture.privateSources, + }); +} + /** Seeds updates through the public API; it owns no persistence or trust port. */ export async function prepareDraftCommand( fixture: ApplicationFixture, diff --git a/tests/atomic-draft-sources.test.ts b/tests/atomic-draft-sources.test.ts index 1f03d82..ede5766 100644 --- a/tests/atomic-draft-sources.test.ts +++ b/tests/atomic-draft-sources.test.ts @@ -20,6 +20,7 @@ import { firstSource, invokeDraftCommand, prepareDraftCommand, + publishedPreviousApplication, secondSource, sourceAuthor, } from "../test/atomic-draft-sources-fixtures.js"; @@ -454,6 +455,97 @@ for (const [name, createStore] of storeFactories) { }, ); + it.each(operations)( + "retains ordered opaque namespace sources for exact %s replay and snapshots supplied new mutations", + async (operation) => { + const backing = await createStore(); + const f = applicationFixture(backing); + await f.setupCollection(); + const references: readonly PrivateSourceReference[] = [ + { + ...firstSource, + id: "source:first", + system: "support:desk", + resourceId: "ticket:123", + version: "resolved:1", + }, + { + ...secondSource, + id: "source:second", + system: "pegma:support", + resourceId: "urn:pegma:ticket:456", + version: "version:2", + }, + ]; + const input = { + ...(await prepareDraftCommand(f, operation)), + sourceReferences: references, + }; + const accepted = await invokeDraftCommand(f, operation, input); + const original = await f.app.getProvenance(admin, { + articleId: input.articleId, + }); + expect(original.snapshot.references).toEqual(references); + for (const reference of references) + expect(f.privateSources.canRead).toHaveBeenCalledWith({ + access: sourceAuthor, + articleId: input.articleId, + reference, + }); + const committedRows = await allKnowledgeRows(backing); + await expect( + invokeDraftCommand(f, operation, { + ...input, + sourceReferences: [...references].reverse(), + }), + ).rejects.toMatchObject(conflict); + expect(await allKnowledgeRows(backing)).toEqual(committedRows); + expect(await invokeDraftCommand(f, operation, input)).toEqual({ + value: accepted.value, + replayed: true, + }); + expect(await allKnowledgeRows(backing)).toEqual(committedRows); + expect( + (await f.app.getProvenance(admin, { articleId: input.articleId })) + .snapshot, + ).toEqual(original.snapshot); + + const next = { + ...input, + ...f.command("same-sources-new-content", accepted.value.generation), + draft: { + ...input.draft, + title: "New draft retaining ordered sources", + }, + }; + const updated = await f.app.updateDraft(sourceAuthor, next); + const supplied = await f.app.getProvenance(admin, { + articleId: input.articleId, + }); + expect(supplied.snapshot).toMatchObject({ + generation: original.snapshot.generation + 1, + references, + }); + expect(supplied.snapshot.hash).not.toBe(original.snapshot.hash); + const beforeReplay = await allKnowledgeRows(backing); + expect(await f.app.updateDraft(sourceAuthor, next)).toEqual({ + value: updated.value, + replayed: true, + }); + expect(await allKnowledgeRows(backing)).toEqual(beforeReplay); + + const { sourceReferences: _references, ...omitted } = next; + await f.app.updateDraft(author, { + ...omitted, + ...f.command("same-sources-omitted", updated.value.generation), + }); + expect( + (await f.app.getProvenance(admin, { articleId: input.articleId })) + .snapshot, + ).toEqual(supplied.snapshot); + }, + ); + it.each(["unknown outcome", "postcommit source withdrawal"] as const)( "recovers an atomic accepted command after %s without duplicating retained work", async (failure) => { @@ -535,7 +627,10 @@ for (const [name, createStore] of storeFactories) { await f.setupCollection(); const { version: _version, ...missingVersion } = firstSource; const invalidReferences: readonly (readonly [unknown, string])[] = [ - [null, "RepositoryCapacityError"], + [null, "TypeError"], + ["ticket:123", "TypeError"], + [{ reference: firstSource }, "TypeError"], + [undefined, "TypeError"], [[null], "TypeError"], [[missingVersion], "TypeError"], [ @@ -568,6 +663,15 @@ for (const [name, createStore] of storeFactories) { "TypeError", ] as const, ), + ...[ + "//fictional.invalid/private", + "https:/fictional.invalid/private", + "data:text/plain,private", + "HtTpS:fictional.invalid/private", + ].map( + (resourceId) => + [[{ ...firstSource, resourceId }], "TypeError"] as const, + ), ]; for (const operation of operations) { const input = await prepareDraftCommand( @@ -578,7 +682,7 @@ for (const [name, createStore] of storeFactories) { const before = await allKnowledgeRows(backing); traced.transactions.length = 0; for (const [references, errorName] of invalidReferences) { - // Real host JSON can reach this boundary despite the static type. + // Exercise malformed runtime inputs beyond the static declarations. const malformed = { ...input, sourceReferences: references as readonly PrivateSourceReference[], @@ -592,6 +696,116 @@ for (const [name, createStore] of storeFactories) { } }); + it("reviews and publishes actual 0.1.1 source snapshots under current source gates without admitting new URL-like writes", async () => { + const backing = await createStore(); + const f = applicationFixture(backing); + await f.setupCollection(); + const previous = await publishedPreviousApplication(f); + const input = await prepareDraftCommand(f, "create"); + const created = await previous.createDraft(author, input); + const historicalReferences = [ + { ...firstSource, resourceId: "git:issue/1" }, + { ...secondSource, resourceId: "data:row42" }, + ]; + await previous.setProvenance(admin, { + ...f.command("previous-release-sources", created.value.generation), + articleId: input.articleId, + references: historicalReferences, + }); + const historical = await previous.getProvenance(admin, { + articleId: input.articleId, + }); + expect(historical.snapshot.references).toEqual(historicalReferences); + expect( + await f.app.getProvenance(admin, { articleId: input.articleId }), + ).toEqual(historical); + let current = await f.app.getDraft(author, { + articleId: input.articleId, + }); + current = (await f.submitEvidence(current)).current; + const beforeReview = await allKnowledgeRows(backing); + for (const gate of ["sourceCurrent", "canPublishSource"] as const) { + f.trust[gate] = false; + await expect(f.review(current)).rejects.toMatchObject(prerequisite); + f.trust[gate] = true; + expect(await allKnowledgeRows(backing)).toEqual(beforeReview); + } + const reviewed = await f.review(current); + expect(reviewed.review).toMatchObject({ + sourceGeneration: historical.snapshot.generation, + sourceSnapshotHash: historical.snapshot.hash, + }); + const publish = { + ...f.command("publish-previous-release-sources", reviewed.generation), + articleId: input.articleId, + review: reviewed.review, + }; + const beforePublish = await allKnowledgeRows(backing); + for (const gate of ["sourceCurrent", "canPublishSource"] as const) { + f.trust[gate] = false; + await expect( + f.app.publishArticle(admin, publish), + ).rejects.toMatchObject(prerequisite); + f.trust[gate] = true; + expect(await allKnowledgeRows(backing)).toEqual(beforePublish); + } + const published = await f.app.publishArticle(admin, publish); + const publishedSources = await f.app.getProvenance(admin, { + articleId: input.articleId, + }); + expect(publishedSources.snapshot).toEqual(historical.snapshot); + expect(publishedSources.publishedSnapshot).toEqual(historical.snapshot); + const approved = await f.app.getPublishedArticle(customer, { + articleId: input.articleId, + }); + for (const gate of ["sourceCurrent", "canPublishSource"] as const) { + f.trust[gate] = false; + await expect( + f.app.getPublishedArticle(customer, { articleId: input.articleId }), + ).rejects.toMatchObject({ name: "KnowledgeBaseNotFoundError" }); + f.trust[gate] = true; + } + expect( + await f.app.getPublishedArticle(customer, { + articleId: input.articleId, + }), + ).toEqual(approved); + + const beforeRejectedWrites = await allKnowledgeRows(backing); + for (const reference of historicalReferences) { + const sourceReferences = [reference]; + await expect( + f.app.createDraft(sourceAuthor, { + ...input, + ...f.command("reject-new-url-source-create", 0), + articleId: "article/rejected-new-url-source", + sourceReferences, + }), + ).rejects.toMatchObject({ name: "TypeError" }); + await expect( + f.app.updateDraft(sourceAuthor, { + ...input, + ...f.command( + "reject-new-url-source-update", + published.value.generation, + ), + sourceReferences, + }), + ).rejects.toMatchObject({ name: "TypeError" }); + await expect( + f.app.setProvenance(admin, { + ...f.command( + "reject-new-url-source-provenance", + published.value.generation, + ), + articleId: input.articleId, + references: sourceReferences, + }), + ).rejects.toMatchObject({ name: "TypeError" }); + } + expect(await allKnowledgeRows(backing)).toEqual(beforeRejectedWrites); + }); + it("accepts readable draft sources independently of publication eligibility and preserves the old publication snapshot", async () => { const f = applicationFixture(await createStore()); await f.setupCollection();