From 0645aa364457e58eb4006bdd637228e7556ce841 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sun, 8 Nov 2026 15:22:31 -0500 Subject: [PATCH 1/5] [KB-04] Add human-reviewed evidence reports and native client workflow --- AGENTS.md | 12 +- README.md | 23 +- docs/AGENT_API.md | 89 +- docs/AGENT_WORKFLOW.md | 62 +- docs/BOOTSTRAP.md | 73 +- docs/EVIDENCE_REPORTS.md | 220 +++ docs/RELEASING.md | 28 +- package.json | 8 +- packages/application/README.md | 26 +- packages/application/package.json | 6 +- .../src/evidence-reports-errors.ts | 58 + .../application/src/evidence-reports-types.ts | 176 ++ packages/application/src/evidence-reports.ts | 1457 +++++++++++++++++ packages/application/src/index.ts | 8 + packages/contracts/package.json | 2 +- packages/core/package.json | 4 +- packages/mcp/README.md | 46 +- packages/mcp/package.json | 8 +- packages/mcp/src/dispatcher.ts | 201 ++- packages/mcp/src/mcp.ts | 51 +- packages/mcp/src/schemas.ts | 106 ++ packages/mcp/src/types.ts | 99 +- pnpm-lock.yaml | 20 +- scripts/agent-protocol-fixture.mjs | 372 ++++- scripts/agent-protocol-proof.mjs | 1 + scripts/release-packages.mjs | 112 +- test/evidence-reports-fixtures.ts | 491 ++++++ tests/agent-reports.test.ts | 646 ++++++++ tests/evidence-reports.test.ts | 1342 +++++++++++++++ 29 files changed, 5610 insertions(+), 137 deletions(-) create mode 100644 docs/EVIDENCE_REPORTS.md create mode 100644 packages/application/src/evidence-reports-errors.ts create mode 100644 packages/application/src/evidence-reports-types.ts create mode 100644 packages/application/src/evidence-reports.ts create mode 100644 test/evidence-reports-fixtures.ts create mode 100644 tests/agent-reports.test.ts create mode 100644 tests/evidence-reports.test.ts diff --git a/AGENTS.md b/AGENTS.md index f9b19c8..fd55136 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,9 +22,11 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. `0.1.0` packages completed manual maintainer bootstrap with exact-byte 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. + [historical release receipt](docs/BOOTSTRAP.md#historical-verified-011-release). + All four `0.1.2` packages have since completed verified trusted publication + for SD-03 atomic draft/source authoring. Source `0.1.3` is the synchronized, + unpublished optional human-reviewed evidence-report 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 @@ -110,7 +112,7 @@ 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 [publication ledger](docs/BOOTSTRAP.md) for the completed manual bootstrap -and verified trusted `0.1.1` receipts. All five KB/Agent Access trusted publishers +and verified KB `0.1.2` and Agent Access `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 @@ -126,7 +128,7 @@ 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.2` candidate's own review, trusted publication, and strict registry +`0.1.3` 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 5feefad..32d6250 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Hosts own their users, storage, authorization policy, interfaces, and deployment Knowledge Base owns collection policy, immutable article revisions, validation, and exact publication approval. It requires no GitHub connection or AI provider. -> Development status as of 2026-11-07: KB-01 through KB-03 provide contracts, pure domain +> Development status as of 2026-11-08: KB-01 through KB-03 provide contracts, pure domain > transitions, authorized application/persistence, and bounded retrieval/repair. > [Merged KB-04 source](https://github.com/pegma-dev/knowledge-base/pull/5) adds > the optional five-operation HTTP/MCP adapter and authenticated protocol proof. @@ -15,10 +15,14 @@ and exact publication approval. It requires no GitHub connection or AI provider. > 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. 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. +> [verified trusted publication](docs/BOOTSTRAP.md#historical-verified-011-release). +> All four `0.1.2` packages have since completed +> [verified trusted publication](docs/BOOTSTRAP.md#verified-knowledge-base-release) +> for SD-03 atomic draft/source authoring. Synchronized `0.1.3` is the +> **unpublished source candidate** for optional human-reviewed +> [evidence reports](docs/EVIDENCE_REPORTS.md); its review, current-head CI, +> trusted publication and strict consumer verification remain pending. +> Actual two-host existing-login/client acceptance remains open. > Host activation remains separately gated; this repository supplies no hosted KB. | Package | Scope | @@ -143,10 +147,11 @@ 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 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 +`0.1.1` release and the four-package KB trusted `0.1.2` release are complete; +their exact receipts remain in the ledger. All four KB packages have +`latest: 0.1.2`; Agent Access has `latest: 0.1.1`; all retain historical +`bootstrap: 0.1.0`. Source `0.1.3` remains unpublished and needs its own review, +current-head CI, trusted release and strict consumer verification. 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 fca5a7b..ac5172f 100644 --- a/docs/AGENT_API.md +++ b/docs/AGENT_API.md @@ -5,9 +5,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. 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. +have since completed verified trusted publication. The current verified KB +release is [`0.1.2`](BOOTSTRAP.md#verified-knowledge-base-release). +Optional report mode is new unpublished `0.1.3` candidate source, 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 @@ -15,7 +16,7 @@ execution, KB trusted publication, or host readiness. ## Trusted host composition -Create `createKnowledgeAgentDispatcher({ application, resource, limits? })` once. +Create `createKnowledgeAgentDispatcher({ application, resource, reports?, limits? })`. For every call and retry the host must authenticate the credential, validate its exact audience/resource and client, and resolve current authorization. Supply `{ access, scopes, clientId, resource }` as a trusted `KnowledgeAgentIdentity`, @@ -68,7 +69,8 @@ validation requirements. There are no collection, private-evidence read, provenance, review, publication, retirement, retrieval, or administration tools in this initial transport surface. -Inputs use the following bounded subset of the public application contracts: +Legacy inputs use the following bounded subset of the public application +contracts; configured report-mode variants are described below: - `getDraft`: `{ articleId }`. - `getValidationRequirements`: `{ collectionId, kind }`. @@ -96,6 +98,78 @@ anything. The existing trusted evidence verifier must authenticate and bind the opaque receipt; missing verification fails closed. The transport fetches no artifact URL and executes no guide step. +## Optional native-client report mode + +The unpublished `0.1.3` source adds an optional `reports` port: +`Pick`. A host can +compose the shared [human-report factory](EVIDENCE_REPORTS.md) behind this port. +It adds no tool or scope. The same MCP connection advertises extended strict +input schemas/descriptions for the existing requirements and evidence tools; +HTTP accepts the same versioned envelopes. Clients cannot enable the mode +through a request flag. When `reports` is omitted, legacy tool schemas, +accepted inputs and result shapes remain unchanged; extension fields reject. + +The public types are `KnowledgeAgentReportRequirementsInput`, +`KnowledgeAgentReportRequirementsResult`, `KnowledgeAgentReportSubmissionInput`, +`KnowledgeAgentPendingReport`, `KnowledgeAgentReportEnvelope`, and +`KnowledgeAgentReportSuccess`. Both report variants require the effective +`draftRead` **and** `evidenceSubmit` permissions. This does not change the +legacy requirements variant's `draftWrite`-or-`evidenceSubmit` rule. + +For report-aware `getValidationRequirements`, input is strictly +`{ collectionId, kind, articleId, reportLookup?: { ledgerEpoch, reportId } }`. +The current draft must match the supplied collection/kind. The result adds +`reportLedger: { ledgerEpoch, status: "active" | "resetting" }` to the normal +requirements. Supplying `reportLookup` also returns the submitting owner's +body-free `reportStatus: { ledgerEpoch, reportId, receipt, reportGeneration, +status: "pending" | "confirmed" | "rejected" }`. No report body, reviewer, +private accepted evidence or trusted-attester registry is exposed. An epoch +mismatch conflicts; another submitter's report is not found. + +For report submission, the existing `submitEvidence` tool accepts strictly +`{ commandId, correlationId, expectedGeneration, articleId, evidence, +ledgerEpoch, report: { summary, details } }`, with **no `receipt` field**. +`evidence` remains the whole original `EvidenceSubmission`; `summary` is at +most 1,000 characters and `details` at most 16,000, within the existing complete +request bounds. Admission checks the exact current article generation and +ledger epoch. The result is +`{ kind: "pending-human-review", ledgerEpoch, reportId, receipt, +reportGeneration }`, with a receipt bounded to 512 UTF-8 bytes. This records a +private report only: it is not `{ value, replayed }`, does not accept KB evidence, +and does not change the article generation. Keep that distinction in clients. + +A human uses separately authorized staff services to inspect the private +report and record a decision. A current authorized Admin may review their own +agent's report; no two-person rule is enforced. The agent polls through the +report-aware requirements input. After first confirmation, it uses the same +original opaque report receipt and exact evidence in the legacy `submitEvidence` +input, with the current article generation. Only that call performs actual KB +qualification. Current runner/result/build/governance, reviewer trust, exact +revision and freshness checks still apply; `confirmed` is not accepted evidence. +Explicit reassessment rotates the receipt cycle; poll for its current receipt +and obtain a new human confirmation before submitting it. + +The optional port is trusted host composition, not a credential verifier. Bind +each `report`, `ledger` and `status` call to the same authenticated request/grant +and recheck that grant's identity, scope/resource restrictions and revocation +before and after awaited work. Preserve the dispatcher-supplied restricted +context; a freshly resolved owner/Admin context must not replace it. The host +must fence current grant changes during these awaits as well as authenticate +the initial transport request. The shared ledger's current-principal checks +do not independently authenticate a host grant. + +Report writes and article reads/commits are separate. A later fence failure +can withhold a response after a report was queued; conflict or unavailability +does not prove rollback. Retry an uncertain report command with the same ID +and exact input under fresh authority. Report epoch/generation conflicts and +resetting ledgers map to `conflict`; report bounds/capacity to `capacity`; +missing grants to `forbidden`; unconfirmed or altered receipts fail actual +evidence qualification with `prerequisite`. No agent report-listing, human +decision, reset/drain, private-evidence read or publication tool is added. +The [public types](../packages/mcp/src/types.ts) and +[source protocol cases](../tests/agent-reports.test.ts) cover this optional mode; +actual native-client/host acceptance remains separate. + ## HTTP composition `createKnowledgeAgentHttp({ dispatcher, apiUrl, resource, @@ -165,9 +239,10 @@ and `createdAt`, plus bounded state flags. They exclude evidence, provenance, review records, and attestation artifacts. Validation requirements expose only collection/governance generation, policy reference, expected staging build, and current checks; trusted runner/attester registries remain private. -Mutations return the existing `{ value, replayed }` acknowledgement with +Article mutations return the existing `{ value, replayed }` acknowledgement with ID/generation, content revision, state, and content hash. Output schemas -explicitly whitelist these DTO fields. +explicitly whitelist these DTO fields. Configured report queuing instead +returns the distinct `pending-human-review` result described above. Failures are `{ apiVersion: "1", operation, error: { code, status, message } }`. Invalid envelopes use `operation: null` rather than reflecting an arbitrary diff --git a/docs/AGENT_WORKFLOW.md b/docs/AGENT_WORKFLOW.md index 5cc7aef..1ffe27a 100644 --- a/docs/AGENT_WORKFLOW.md +++ b/docs/AGENT_WORKFLOW.md @@ -5,8 +5,10 @@ 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. 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 +since completed verified trusted publication, followed by the current verified +[`0.1.2` release](BOOTSTRAP.md#verified-knowledge-base-release). +Optional human-report mode is unpublished `0.1.3` candidate source with its own +review/release gates. 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). @@ -86,7 +88,8 @@ the five tools and three consent scopes remain unchanged. revision/content hash and product/build. Protect test artifacts through the host's evidence channel. The KB transport executes no steps and fetches no submitted artifact URL. -4. Submit evidence and the host's opaque receipt using the current generation. +4. Submit evidence and the host's opaque receipt using the current generation, + or use the configured human-report flow below to obtain confirmation first. The host attester must verify the authenticated actor and runner, exact revision/content hash, check, staging build, result, and receipt before returning trusted verification facts. An authenticated agent's own `passed` @@ -97,6 +100,52 @@ the five tools and three consent scopes remain unchanged. review and publication separately bind the exact current revision, audience, policy, applicability, and verified evidence. +## Submit a report and poll through the same MCP connection + +When the host composes the optional `reports` port, native clients use the same +five tools and three consent scopes. The requirements and evidence tools +advertise their additional input variants; there is no report-management or +staff tool. Without that port, their legacy schemas and behavior remain exact. +The [wire contract](AGENT_API.md#optional-native-client-report-mode) defines +the public DTOs. Both variants need effective `draftRead` and `evidenceSubmit`. + +1. Read the exact draft and call `getValidationRequirements` with its + `collectionId`, `kind` and `articleId`. Keep the returned + `reportLedger.ledgerEpoch`; a resetting ledger needs authorized staff + recovery before new report work. +2. Run the actual required checks against authorized staging. Call the existing + `submitEvidence` tool with the whole exact evidence submission, original + command/correlation fields, current `expectedGeneration`, `ledgerEpoch`, + and `report: { summary, details }`, omitting `receipt`. Preserve the returned + `{ kind: "pending-human-review", ledgerEpoch, reportId, receipt, +reportGeneration }` and exact command input. This acknowledges a private + report, not verified evidence or an article mutation. +3. A currently authorized human reviews the full report, exact revision/build, + hashes, execution and current requirements through the host's staff surface. + Staff may explicitly review their own agent's report; there is no two-person + rule. The agent's same-principal bearer still cannot perform that decision. +4. Poll `getValidationRequirements` with `articleId` and + `reportLookup: { ledgerEpoch, reportId }`. `reportStatus` contains only the + owner's opaque receipt/generation/status. Pending means wait; rejected or + changed/expired context requires a fresh authorized workflow. Polling never + exposes private report bodies, reviewers, accepted evidence or registries. +5. After confirmation, read the current draft generation and use the original + receipt-bearing `submitEvidence` input with the same exact evidence and + report receipt. First confirmation preserves that receipt. Explicit staff + reassessment rotates its cycle, so obtain the current receipt and a new + confirmation if reassessment occurred. Actual KB qualification can still + refuse runner, result, staging/build, governance, applicability, revision or + freshness mismatches. Complete every required check, then let staff perform + separate exact review/publication. + +The host must bind optional report-port calls to the same authenticated +request/grant, rechecking its current scope/resource/identity and revocation +before and after awaited report work. Current owner/Admin authority never +substitutes for the restricted delegated context. Report/KB transactions remain +separate; a final conflict or lost response can follow a queued report without +rolling it back. See [report retention and replay](EVIDENCE_REPORTS.md#capacity-retention-and-replay) +for epoch reset, receipt cycles and bounded recovery. + For an uncertain mutation result, authenticate again and retry the same `commandId` and exact semantic input, including the original `expectedGeneration`. An accepted replay returns its historical bounded @@ -122,7 +171,7 @@ 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, and the separate KB `0.1.1` trusted release is verified. +source is merged, and the current separate KB `0.1.2` 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 @@ -130,7 +179,7 @@ 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.2` candidate retains its own gates, PR, and verified trusted release +The KB `0.1.3` report-mode 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. @@ -148,7 +197,8 @@ targets all remain unproven until actual results are recorded on both hosts: For every target client/mode on each host, record discovery, existing human login/current-Admin consent, draft read/create/update, requirements, verified -evidence submission, and matching HTTP/MCP outcomes using exact released +evidence submission, configured report submission/own-status polling/human +confirmation where used, and matching HTTP/MCP outcomes using exact released dependencies. Record unsupported or unavailable flows as open gaps. Retain explicit expiry, wrong-audience, revocation, excess-scope, current diff --git a/docs/BOOTSTRAP.md b/docs/BOOTSTRAP.md index 2189571..11e7b4b 100644 --- a/docs/BOOTSTRAP.md +++ b/docs/BOOTSTRAP.md @@ -6,11 +6,12 @@ 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. -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. +KB's current verified trusted release is `0.1.2`; Agent Access remains verified +at `0.1.1`. Their receipts close public producer release prerequisites only. +The dated first trusted KB `0.1.1` receipt remains below as history. Synchronized +KB `0.1.3` is the unpublished optional human-reviewed evidence-report candidate; +its own review, current-head CI, trusted publication, strict consumer +verification and host acceptance remain pending. The five KB/Agent Access trusted-publisher entries have been configured through the CLI. An actual trusted release still requires the reviewed source and @@ -76,13 +77,54 @@ 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. -Following their trusted releases, all four KB packages and Agent Access have +At the subsequent `0.1.1` trusted-release checkpoint, all four KB packages and Agent Access had `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 establishes real-host acceptance. ## Verified Knowledge Base release +### Current verified `0.1.2` release + +At **2026-11-08T03:39:55Z**, all four KB `0.1.2` packages completed strict +registry/signature/provenance and clean-consumer verification. The +[`v0.1.2` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.2) +identifies reviewed [PR #9](https://github.com/pegma-dev/knowledge-base/pull/9) +source at +[`004044bfa836b74a61fb5defa49d5ebab1fe37dd`](https://github.com/pegma-dev/knowledge-base/commit/004044bfa836b74a61fb5defa49d5ebab1fe37dd). +The annotated tag object is `85ec72f153be541e8cc551600b16bfd224f06d2d`, with a +valid verified signature. The +[trusted workflow, attempt 5](https://github.com/pegma-dev/knowledge-base/actions/runs/42436081951/attempts/5) +completed successfully at that source. Its separate unprivileged +[strict verification job](https://github.com/pegma-dev/knowledge-base/actions/runs/42436081951/job/128617897564) +recorded: + +```text +Verified registry release and clean consumer for 4 packages. +``` + +| Field | Value | +| --------------------------------------- | ------------------------------------------------------------------ | +| Original prepared artifact ID | `13599399407` | +| Artifact name | `knowledge-base-release-42436081951-1` | +| Downloaded artifact archive SHA-256 | `c5ad819773292ef100a97a8f30e9c639b4ce5fca96c901a5873f8da6364f8609` | +| Independently retained manifest SHA-256 | `a7369297302182645c5157cd997c2ded0c3698c3e142efcff23866337cb51b33` | + +The verifier bound the source/tag/commit, original artifact and independent +manifest digest to all four registry artifacts/dependencies, cryptographic +signatures, source-bound provenance, and clean-consumer imports. Recovery kept +the original prepared artifact; no package version, signed tag or tarball was +replaced. Current KB dist-tags are `latest: 0.1.2` and historical +`bootstrap: 0.1.0`; Agent Access remains `latest: 0.1.1`, `bootstrap: 0.1.0`. + +This release provides SD-03 atomic draft/private-source authoring. It contains +no shared human-reviewed report factory. That optional API is new `0.1.3` +candidate source with its own pending review/CI/release/verification gates. +Neither release establishes actual host/client, privacy, activation or pilot +acceptance. + +### Historical verified `0.1.1` 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 @@ -107,12 +149,12 @@ source/workflow/tag/commit provenance, and isolated clean-consumer imports. 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` +At that historical checkpoint, all four packages had `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. +This dated receipt closed the KB `0.1.1` producer release prerequisite. The +later `0.1.2` release has its own receipt above; neither completes host/client, +privacy, activation or pilot acceptance, nor verifies changed `0.1.3` source. ## Verified Agent Access prerequisite @@ -156,8 +198,8 @@ 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` has its separate verified -receipt above; source `0.1.2` retains its own current-head gates, PR, trusted +candidate artifacts in a fresh consumer. KB `0.1.2` has its separate verified +receipt above; source `0.1.3` 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. @@ -236,9 +278,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 synchronized KB source candidate is `0.1.2` with exact internal dependency +The synchronized KB source candidate is `0.1.3` 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. +historical first advertised trusted release is `0.1.1`; the current verified +release is `0.1.2`, recorded separately 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 @@ -253,7 +296,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). The verified KB `0.1.1` and Agent +[source preparation](SOURCE_PREPARATION.md). The verified KB `0.1.2` 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/EVIDENCE_REPORTS.md b/docs/EVIDENCE_REPORTS.md new file mode 100644 index 0000000..806cf4a --- /dev/null +++ b/docs/EVIDENCE_REPORTS.md @@ -0,0 +1,220 @@ +# Human-reviewed evidence reports + +`createKnowledgeEvidenceReports` is a new **unpublished API in the synchronized +`0.1.3` source candidate** for `@pegma/knowledge-base-application`. It is not part +of the currently verified `0.1.2` release. Its own review, current-head CI, +trusted publication and strict consumer verification remain pending. +Hosts must wait for exact verified publication before production adoption; +source tests and local adapter fixtures do not establish host activation, +actual client acceptance, or a real staging test. + +The factory stores bounded test reports for authorized human review and supplies +an `EvidenceVerifier` to the existing KB application. It adds no login, roles, +credential issuer, HTTP routes, MCP tools, scheduler, or test runner. It never +fetches report/artifact URLs, executes submitted steps, or creates a private +provenance/source-verification bridge. + +## Compose the trusted host ports + +The [public types](../packages/application/src/evidence-reports-types.ts) and +[implementation](../packages/application/src/evidence-reports.ts) define the +current source contract: + +| Factory option | Host responsibility | +| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `store`, `clock` | Supply the real Storage Core Store and trusted clock. | +| `collectionName` | Choose an explicit, exclusive report namespace, separate from KB article/retrieval collections. Preserve it for retained reports and receipts. | +| `storageLayout` | Choose the physical-key layout deliberately; the default is `portable-v1`. | +| `confirmationPermission` | Supply a human-only permission distinct from all three initial agent scopes. The factory creates no assignment or role. | +| `resolvePrincipal` | Resolve the same principal's current authority on every call and verification; return null for known absence and let dependency failures remain unavailable. | +| `readContext` | Read the current authorized `draft`, narrow `requirements`, and optional accepted `evidence` through the public KB application. | +| `logger` | Optionally receive coarse verifier-unavailable categories, without report bodies or raw dependency errors. | + +Authenticate before calling the service. Pass the effective credential's scoped +`AccessContext`, including for replay. Current principal resolution confirms +that its retained named permissions remain valid; it never replaces a restricted agent context +with the owner's broader Admin context. Preserve that same effective context +inside `readContext` and use actual `getDraft`, `getValidationRequirements`, and, +only when authorized, `getEvidence` reads. A report-supplied article, permission +array, runner name, or `passed` value does not supply authority. + +The initial delegated scopes remain only `knowledgePermissions.draftRead`, +`draftWrite`, and `evidenceSubmit`. Report submission/status can be exposed by +an authenticated host boundary using existing evidence-submit authority; this +factory registers no additional scope or transport operation. Keep human +confirmation, private report reads, review and publication outside agent grants. + +The optional agent dispatcher's `reports` port can expose `report`, `ledger` +and owner-only `status` through modes of its existing requirements/evidence +tools, letting native clients submit and poll through the same MCP connection. +The [agent wire contract](AGENT_API.md#optional-native-client-report-mode) defines +those shapes; omitted-port legacy schemas stay unchanged. Host wrappers must +revalidate the same authenticated request/grant before and after every awaited +report-port call, preserving the restricted effective context. The ledger's +current-principal resolver is not a host credential/grant verifier. + +## Submit, review, then qualify evidence + +`report(access, input)` accepts `SubmitKnowledgeReportInput`: `commandId`, +`articleId`, current `ledgerEpoch`, a whole `EvidenceSubmission`, and a +`KnowledgeTestReport` containing `summary` and `details`. Preserve the complete +submission: article revision/content hash, validation policy, check/test kind, +applicability/build, steps, result, original execution time, runner, and artifact +IDs/hashes. The authenticated context supplies the submitting principal. + +| Method | Purpose and authority | +| ---------------- | ------------------------------------------------------------------------------------------------------------- | +| `ledger` | Body-free current epoch/capacity state; requires current `evidenceSubmit`. | +| `report` | Save a pending report and return a bounded acknowledgement/opaque receipt; requires current `evidenceSubmit`. | +| `status` | Return acknowledgement plus status only to the original submitting principal under current `evidenceSubmit`. | +| `list`, `read` | Staff summaries or the complete private `KnowledgeReportView`. | +| `decide` | Explicitly confirm, reject, or reassess a report using its exact reviewed binding. | +| `reset`, `drain` | Authorized bounded ledger retention/recovery. | + +Every staff method requires the configured `confirmationPermission` plus +`draftRead` and `evidenceRead`, under current same-principal authority. The full +view includes the report/submission, hashes, exact current draft/requirements, +`reviewBindingHash`, `expectedReportGeneration`, and any confirmation. Keep +these private; the agent's body-free `status` is not a staff listing or report +download. Render untrusted report text safely and do not fetch submitted links. + +Call `decide` with `DecideKnowledgeReportInput`: `commandId`, `articleId`, +`ledgerEpoch`, `reportId`, `expectedReportGeneration`, and the exact +`reviewBindingHash` returned by `read`. Use `"confirmed"` or `"rejected"` for +a pending report. Changed report or KB context requires a fresh read/review. +A host-authorized Admin may human-confirm their own agent's report; the factory +enforces no reviewer-different-from-submitter or two-person rule. A restricted +agent with that same principal ID still lacks the human permission. + +Confirmation records human review. The agent then supplies its current opaque +receipt and exact submission to the existing KB `submitEvidence` command. +The verifier rechecks the submitting identity, receipt cycle, whole submission, +current exact revision/context and reviewer authority, including current +trusted-attester membership. Actual KB qualification still enforces runner, +result, staging build, governance, applicability, policy and freshness. +A confirmed receipt can therefore be refused. Every required check must qualify +before the separate exact SDK review/publication workflow can proceed. + +To reassess a confirmed or rejected report, freshly `read` it and call `decide` +with `"pending"`. This clears confirmation, advances report generation and +rotates the receipt cycle. The original execution must still match the current +revision and be fresh; reassessment neither refreshes its timestamp nor turns +it into a test of an edited revision. The owner retrieves the new receipt with +`status`, then obtains a new explicit human decision before submission. + +## Choose physical keys before writing + +`portable-v1`, the default, uses `a-` partition and `r-` row-key prefixes followed +by fixed-width hexadecimal UTF-16 code units. It preserves opaque logical IDs +while keeping physical keys backend-safe and bounded. The logical envelope, +payload bindings and opaque receipt semantics are separate from that encoding. +The portable codec stores that logical JSON in a strict versioned envelope +with at most six flat string parts, each bounded to 12,000 UTF-16 code units. +It preserves surrogate pairs and enforces the original 60,000-byte UTF-8 bound +after joining. This keeps permitted reports within Azure's native per-property +limit without changing their logical payload, hashes or receipts. + +`legacy-raw-v1` must be selected explicitly for a compatible existing raw-key +**epoch ledger**, such as PG's retained R1 D1 report ledger. With its exact +existing `collectionName`, it preserves physical article partition/row keys, +logical JSON, hashes and receipt layout. It does not migrate the earlier +pre-epoch PG ledger's unversioned rows. It does not make raw keys portable to +Azure Tables; unsupported raw identities fail rather than being escaped or +retried under another layout. + +There is no detection, fallback, copying or migration. A portable read against +a raw populated namespace can look empty because the physical keys differ. +Never switch layouts on a populated namespace or use a changed collection name +as an implicit upgrade. Any data/adapter transition needs a separate deliberate +migration and proof; compatibility fixtures are not evidence of a live migration. + +In either layout, an absent head permits initialization only when the selected +physical article partition is empty. Existing readable rows without a head +produce unavailable stage `head_partition_orphaned` before any write; malformed +or oversized partitions can instead fail earlier integrity checks. Pre-epoch +rows are refused rather than silently assigned a new epoch. The guard checks +the selected physical partition, not an alternate layout's keys. + +Before activation, quiesce old writers and inspect the actual namespace and +layout. Any pre-epoch data requires a separate verified migration before this +factory can use it. Do not automatically copy or delete rows, synthesize a head, +or retry under another layout to bypass the refusal. + +## Capacity, retention and replay + +Each article ledger's admitted state is bounded to 16 reports, 160 physical rows +including its head/Audit/command records, and 60,000 UTF-8 bytes per record's JSON +payload. Report and decision writes commit their head/report changes, Audit and +command receipt in one report partition. Admission refuses further work at +capacity; it does not silently evict retained reports or accepted proof. + +These admission limits do not bound physical reads against uncontrolled legacy +or corrupt data. Storage Core `0.4` has no bounded partition probe: the +missing-head guard uses a full `list(partition)` before initialization. An +existing head skips that extra probe, but staff listing and reset/drain integrity +reads also read the full partition before checking its size and contents. There +is no constant physical-work or wall-clock guarantee for these reads. + +Execution-age limits govern new human confirmation, reassessment and evidence +qualification. There is no automatic report TTL eviction. Hosts own authorized +retention/export procedures and decide when to reset the ledger. + +`reset` takes `ResetKnowledgeReportsInput` with `commandId`, `articleId`, and +`expectedLedgerEpoch`. It advances the epoch and enters `resetting`, immediately +fencing old report receipts and commands. `drain` takes `articleId` and the new +`ledgerEpoch`, deleting at most 48 old ledger rows per call. At most four calls +cover an admitted finite old ledger; this deletion bound does not limit each +call's full-partition integrity read. Resume after interruption until it is +`active`. New report work remains held while resetting. `rowsRemaining` means +admission capacity while active and rows left to delete while resetting. + +Exact accepted report/decision retries under current authority return historical +acknowledgements within the active epoch, without repeating transitions. An old +acknowledgement does not prove that its receipt cycle is still current after +reassessment. Reset ends that epoch's replay horizon. The head retains a bounded +history seal and only the latest reset intent: its exact retry returns current +metadata without another reset; after a subsequent reset, the older intent +conflicts. It is not an indefinite archive of drained reports or Audit receipts. + +Reset/reassessment does not revoke evidence already accepted by KB or withdraw +an approved publication. Retained publication uses its reviewed proof snapshot; +a later draft or elapsed original execution TTL alone does not expire it. +Current SDK policy/source authority, proof availability, explicit evidence +revocation and retirement still apply. + +The report ledger and KB article commit are separate transactions. Reset fences +subsequent verification; it cannot cancel an article commit already independently +verified before reset. Do not describe a receipt as atomically consumed across +both collections, or promise globally atomic revocation. + +## Fictional source example and failures + +The [synthetic fixture](../test/evidence-reports-fixtures.ts) uses +`workshop.knowledge-reports.v1`, human permission +`workshop.knowledge.report.confirm`, and a fictional export walkthrough. Its +`baseOptions` has the public `KnowledgeEvidenceReportsOptions` type; this +composition excerpt is taken from that fixture: + +```ts +const reports: KnowledgeEvidenceReports = + createKnowledgeEvidenceReports(baseOptions); +const app: KnowledgeBaseApplication = createKnowledgeBaseApplication({ + store: observed.store, + clock, + evidenceVerifier: reports.verifier, +}); +``` + +The fixture's current-principal map and report data are synthetic trust inputs, +not a login or staging verifier to copy into a host. Its +[public-API cases](../tests/evidence-reports.test.ts) exercise report/review, +actual evidence submission/publication, same-human confirmation, layout choice, +retention and failure boundaries. Current-head gates establish execution. + +Hosts map `KnowledgeEvidenceReportsError.code` to their refusal/conflict/input +responses. `KnowledgeEvidenceReportsUnavailableError` has safe code +`report_ledger_unavailable` and a coarse stage for dependency or stored-integrity +failure; do not return stored bodies or raw exceptions. The `verifier` fails +closed with null on unavailable or invalid proof. Retry uncertain accepted +commands using the same command ID and exact input under refreshed authority. +These APIs establish no host credential, production deployment, or client proof. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index b16f392..192416e 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -13,27 +13,37 @@ 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 +[historical release receipt](BOOTSTRAP.md#historical-verified-011-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. +The current verified KB release is `0.1.2`, at signed source +`004044bfa836b74a61fb5defa49d5ebab1fe37dd`. Its separate +[strict verification job](https://github.com/pegma-dev/knowledge-base/actions/runs/42436081951/job/128617897564) +completed complete-set registry/signature/provenance and clean-consumer checks +at **2026-11-08T03:39:55Z**; the +[current receipt](BOOTSTRAP.md#verified-knowledge-base-release) retains its +source/tag and original prepared artifact bindings. + +Source `0.1.3` is the synchronized **unpublished** candidate for the optional +shared human-reviewed evidence-report service. Its own review, current-head CI, +signed tag, trusted publication and strict consumer verification remain pending. +Existing package links to `v0.1.2` describe that verified release; the new +[report guide](EVIDENCE_REPORTS.md) remains DEVELOPMENT documentation until its +own reviewed release tag exists. No `v0.1.3` release is claimed here. [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. The verified `0.1.1` publication +CI links, counts, review, and security receipts. The verified `0.1.2` 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. All four KB packages and Agent Access now have -`latest: 0.1.1` and `bootstrap: 0.1.0`. The manual bootstraps remain historical +independently retained digests. All four KB packages have `latest: 0.1.2`; +Agent Access has `latest: 0.1.1`; all retain `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. @@ -45,7 +55,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 `0.1.2` candidate still needs its own current-head gates, review, PR, publication, +The KB `0.1.3` 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/package.json b/package.json index 081f7f1..4a4d4f4 100644 --- a/package.json +++ b/package.json @@ -34,11 +34,11 @@ "@cloudflare/workers-types": "5.20260730.1", "@modelcontextprotocol/sdk": "1.32.2", "@pegma/authorization-core": "0.4.0", - "@pegma/knowledge-base-application": "0.1.2", + "@pegma/knowledge-base-application": "0.1.3", "@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", + "@pegma/knowledge-base-contracts": "0.1.3", + "@pegma/knowledge-base-core": "0.1.3", + "@pegma/knowledge-base-mcp": "0.1.3", "@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 092166f..9a87875 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -14,10 +14,10 @@ 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 production activation remain separately gated. -GitHub 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 explicitly moving +Existing versioned documentation links below describe the verified `v0.1.2` +release. The optional report service is new unpublished `0.1.3` candidate source; +the new guide uses DEVELOPMENT `main` until its own reviewed release tag exists. +Source readers can use the explicitly moving [DEVELOPMENT documentation on main](https://github.com/pegma-dev/knowledge-base/blob/main/docs/HOST_COMPOSITION.md) while preparing a release. The versioned contract references remain tag-pinned; the DEVELOPMENT link is a source-reader fallback. @@ -130,6 +130,24 @@ proof availability, and revocation remain live checks. Article CAS cannot globally fence separate collection/ validation-policy partitions. +## Human-reviewed evidence reports (`0.1.3` source candidate) + +New source exports `createKnowledgeEvidenceReports` and its public option, +input, view, acknowledgement and error types. This API is unpublished in the +synchronized `0.1.3` candidate and is absent from the verified `0.1.2` release. +Its own review, current-head CI, trusted publication, strict consumer +verification and host acceptance remain pending. The +[DEVELOPMENT evidence-report guide](https://github.com/pegma-dev/knowledge-base/blob/main/docs/EVIDENCE_REPORTS.md) +describes explicit Store namespace/current-authority ports, human confirmation +before actual KB qualification, bounded epochs/retention, and the separate +report-ledger-to-article commit window. + +Choose default `portable-v1` encoded physical keys for a new ledger. Select +`legacy-raw-v1` explicitly only to retain a compatible existing raw-key ledger; +no populated-namespace detection, layout switch or migration is automatic. +The factory adds no agent scope, MCP tool, role, login, scheduler or provenance +bridge. Hosts retain exact-publication and activation prerequisites. + ## Bounded retrieval and repair `listPortalCollections` and `searchPublishedArticles` require current portal diff --git a/packages/application/package.json b/packages/application/package.json index c507257..125f9f6 100644 --- a/packages/application/package.json +++ b/packages/application/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-application", - "version": "0.1.2", + "version": "0.1.3", "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.2", - "@pegma/knowledge-base-core": "0.1.2", + "@pegma/knowledge-base-contracts": "0.1.3", + "@pegma/knowledge-base-core": "0.1.3", "@pegma/spine": "0.1.2", "@pegma/storage-core": "0.4.0" }, diff --git a/packages/application/src/evidence-reports-errors.ts b/packages/application/src/evidence-reports-errors.ts new file mode 100644 index 0000000..ec1cddd --- /dev/null +++ b/packages/application/src/evidence-reports-errors.ts @@ -0,0 +1,58 @@ +export type KnowledgeEvidenceReportsErrorCode = + | "invalid_configuration" + | "invalid_request" + | "report_too_large" + | "forbidden" + | "report_not_found" + | "report_target_unavailable" + | "command_conflict" + | "report_capacity" + | "report_changed" + | "report_not_verifiable" + | "ledger_epoch_changed" + | "ledger_resetting" + | "ledger_changed" + | "ledger_epoch_exhausted"; + +/** Component refusal; hosts choose their HTTP/status/UI mapping. */ +export class KnowledgeEvidenceReportsError extends Error { + override readonly name = "KnowledgeEvidenceReportsError"; + constructor(readonly code: KnowledgeEvidenceReportsErrorCode) { + super("Knowledge evidence report operation refused: " + code); + } +} + +export type KnowledgeEvidenceReportsStage = + | "record_decode" + | "report_decode" + | "head_decode" + | "principal_resolve" + | "head_read" + | "head_identity" + | "head_partition_orphaned" + | "partition_read" + | "partition_integrity" + | "report_read" + | "report_identity" + | "context_read" + | "receipt_read" + | "receipt_decode" + | "report_write" + | "report_count" + | "reset_count" + | "reset_head" + | "reset_begin" + | "reset_drain" + | "drain_count" + | "clock_read" + | "collection_open" + | "hashing"; + +/** Safe dependency/integrity category, without stored bodies or raw exceptions. */ +export class KnowledgeEvidenceReportsUnavailableError extends Error { + override readonly name = "KnowledgeEvidenceReportsUnavailableError"; + readonly code = "report_ledger_unavailable"; + constructor(readonly stage: KnowledgeEvidenceReportsStage) { + super("Knowledge evidence report ledger is unavailable."); + } +} diff --git a/packages/application/src/evidence-reports-types.ts b/packages/application/src/evidence-reports-types.ts new file mode 100644 index 0000000..744b4a6 --- /dev/null +++ b/packages/application/src/evidence-reports-types.ts @@ -0,0 +1,176 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import type { + Clock, + IsoTimestamp, + Logger, + PrincipalId, +} from "@pegma/knowledge-base-contracts"; +import type { EvidenceSubmission } from "@pegma/knowledge-base-core"; +import type { Store } from "@pegma/storage-core"; +import type { + DraftArticleDto, + EvidenceDto, + EvidenceVerifier, + ValidationRequirementsDto, +} from "./types.js"; + +export interface KnowledgeTestReport { + readonly summary: string; + readonly details: string; +} + +export type KnowledgeReportStatus = "pending" | "confirmed" | "rejected"; + +export interface KnowledgeReportAcknowledgement { + readonly ledgerEpoch: number; + readonly reportId: string; + readonly receipt: string; + readonly reportGeneration: number; +} + +export interface KnowledgeReportSummary { + readonly ledgerEpoch: number; + readonly reportId: string; + readonly articleId: string; + readonly reportGeneration: number; + readonly status: KnowledgeReportStatus; + readonly submittedBy: PrincipalId; + readonly submittedAt: IsoTimestamp; + readonly summary: string; +} + +export interface KnowledgeReportConfirmation { + readonly reviewerId: PrincipalId; + readonly confirmedAt: IsoTimestamp; +} + +export interface KnowledgeReportLedgerState { + readonly articleId: string; + readonly ledgerEpoch: number; + readonly status: "active" | "resetting"; + readonly reportsRemaining: number; + /** Available admission rows while active; rows left to drain while resetting. */ + readonly rowsRemaining: number; +} + +/** Trusted current KB DTOs, obtained through authorized public application reads. */ +export interface KnowledgeEvidenceContext { + readonly draft: DraftArticleDto; + readonly requirements: ValidationRequirementsDto; + readonly evidence?: EvidenceDto; +} + +export interface KnowledgeReportView extends KnowledgeReportSummary { + readonly evidence: EvidenceSubmission; + readonly report: KnowledgeTestReport; + readonly reportHash: string; + readonly submissionHash: string; + readonly governanceHash: string; + readonly draft: DraftArticleDto; + readonly requirements: ValidationRequirementsDto; + readonly reviewBindingHash: string; + readonly expectedReportGeneration: number; + readonly confirmation: KnowledgeReportConfirmation | null; +} + +export interface KnowledgeReportArticleInput { + readonly articleId: string; +} + +export interface KnowledgeReportKey extends KnowledgeReportArticleInput { + readonly ledgerEpoch: number; + readonly reportId: string; +} + +export interface SubmitKnowledgeReportInput extends KnowledgeReportArticleInput { + readonly commandId: string; + readonly ledgerEpoch: number; + readonly evidence: EvidenceSubmission; + readonly report: KnowledgeTestReport; +} + +export interface DecideKnowledgeReportInput extends KnowledgeReportKey { + readonly commandId: string; + readonly expectedReportGeneration: number; + readonly reviewBindingHash: string; +} + +export interface ResetKnowledgeReportsInput extends KnowledgeReportArticleInput { + readonly commandId: string; + readonly expectedLedgerEpoch: number; +} + +export interface DrainKnowledgeReportsInput extends KnowledgeReportArticleInput { + readonly ledgerEpoch: number; +} + +export type KnowledgeEvidenceReportStorageLayout = + "portable-v1" | "legacy-raw-v1"; + +export interface KnowledgeEvidenceReportsOptions { + readonly store: Store; + readonly clock: Clock; + /** Explicit, exclusive report namespace; may preserve an existing host ledger. */ + readonly collectionName: string; + /** + * Defaults to portable-v1, with backend-safe encoded physical keys and + * bounded string chunks for the serialized payload. + * Select legacy-raw-v1 explicitly only for an existing compatible raw-key + * ledger (such as the original D1 host). It preserves that ledger's raw keys + * and original single-payload record, not Azure portability. No data/layout + * detection or migration is performed. + * Never switch layouts on a populated namespace without an explicit migration. + */ + readonly storageLayout?: KnowledgeEvidenceReportStorageLayout; + /** Human-only host permission, additional to KB draft/evidence reading. */ + readonly confirmationPermission: string; + readonly resolvePrincipal: (id: PrincipalId) => Promise; + readonly readContext: ( + access: AccessContext, + articleId: string, + ) => Promise; + readonly logger?: Logger; +} + +export interface KnowledgeEvidenceReports { + readonly verifier: EvidenceVerifier; + report( + access: AccessContext, + input: SubmitKnowledgeReportInput, + ): Promise; + status( + access: AccessContext, + input: KnowledgeReportKey, + ): Promise< + KnowledgeReportAcknowledgement & { readonly status: KnowledgeReportStatus } + >; + read( + access: AccessContext, + input: KnowledgeReportKey, + ): Promise; + list( + access: AccessContext, + input: KnowledgeReportArticleInput, + ): Promise<{ + readonly ledger: KnowledgeReportLedgerState; + readonly reports: readonly KnowledgeReportSummary[]; + }>; + ledger( + access: AccessContext, + input: KnowledgeReportArticleInput, + ): Promise; + decide( + access: AccessContext, + input: DecideKnowledgeReportInput, + decision: KnowledgeReportStatus, + ): Promise; + /** Retires report receipts; does not revoke already accepted KB evidence. */ + reset( + access: AccessContext, + input: ResetKnowledgeReportsInput, + ): Promise; + drain( + access: AccessContext, + input: DrainKnowledgeReportsInput, + ): Promise; +} diff --git a/packages/application/src/evidence-reports.ts b/packages/application/src/evidence-reports.ts new file mode 100644 index 0000000..a854f68 --- /dev/null +++ b/packages/application/src/evidence-reports.ts @@ -0,0 +1,1457 @@ +import { + hasPermission, + serializeAccessContext, + type AccessContext, +} from "@pegma/authorization-core"; +import { auditEvent } from "@pegma/audit"; +import type { EvidenceSubmission } from "@pegma/knowledge-base-core"; +import { + knowledgePermissions, + type Applicability, + type ArticleRevision, +} from "@pegma/knowledge-base-contracts"; +import { defineCollection, type EntityKey } from "@pegma/storage-core"; +import type { EvidenceVerifier } from "./types.js"; +import type { + KnowledgeTestReport, + KnowledgeReportAcknowledgement, + KnowledgeReportSummary, + KnowledgeReportConfirmation as Confirmation, + KnowledgeReportLedgerState, + KnowledgeEvidenceContext, + KnowledgeEvidenceReportStorageLayout, + KnowledgeEvidenceReportsOptions, + KnowledgeEvidenceReports, +} from "./evidence-reports-types.js"; +import { + KnowledgeEvidenceReportsError, + KnowledgeEvidenceReportsUnavailableError, + type KnowledgeEvidenceReportsStage, +} from "./evidence-reports-errors.js"; +import { + KnowledgeBaseAuthorizationError, + KnowledgeBaseNotFoundError, +} from "./errors.js"; +import { snapshotData } from "./storage-helpers.js"; + +const MAX_REPORTS = 16; +const MAX_ROWS = 160; +const MAX_RECORD_BYTES = 60_000; +const DRAIN_ROWS = 48; +const CHUNK_CHARACTERS = 12_000; +// Even when each nonfinal chunk loses one code unit to preserve a pair, +// six parts cover every payload within the existing 60,000 UTF-8 byte cap. +const MAX_CHUNKS = 6; + +function stored(stage: KnowledgeEvidenceReportsStage, read: () => T): T { + try { + return read(); + } catch { + throw new KnowledgeEvidenceReportsUnavailableError(stage); + } +} +async function ledgerIo( + stage: KnowledgeEvidenceReportsStage, + operation: () => Promise, +): Promise { + try { + return await operation(); + } catch { + throw new KnowledgeEvidenceReportsUnavailableError(stage); + } +} + +interface LedgerRow { + readonly articleId: string; + readonly id: string; + readonly payload: string; +} +function evidenceRecords( + collectionName: string, + storageLayout: KnowledgeEvidenceReportStorageLayout, + storageKey: (articleId: string, id: string) => EntityKey, +) { + return defineCollection({ + name: collectionName, + key: (row) => storageKey(row.articleId, row.id), + codec: { + encode: (row) => { + if (storageLayout === "legacy-raw-v1") + return { + articleId: row.articleId, + id: row.id, + payload: row.payload, + }; + const payload = boundedString(row.payload, 1, MAX_RECORD_BYTES, { + allowMultiline: true, + }); + if (new TextEncoder().encode(payload).byteLength > MAX_RECORD_BYTES) + throw new KnowledgeEvidenceReportsError("report_too_large"); + const parts: string[] = []; + for (let offset = 0; offset < payload.length;) { + let end = Math.min(payload.length, offset + CHUNK_CHARACTERS); + const last = payload.charCodeAt(end - 1); + if (end < payload.length && last >= 0xd800 && last <= 0xdbff) + end -= 1; + const part = payload.slice(offset, end); + if (/[\uD800-\uDFFF]/u.test(part)) + throw new KnowledgeEvidenceReportsError("invalid_request"); + parts.push(part); + offset = end; + } + if (parts.length === 0 || parts.length > MAX_CHUNKS) + throw new KnowledgeEvidenceReportsError("report_too_large"); + const encoded: Record = { + schemaVersion: 1, + articleId: scalar(row.articleId), + id: scalar(row.id), + partCount: parts.length, + }; + for (const [index, part] of parts.entries()) + encoded["part" + index] = part; + return encoded; + }, + decode: (row) => + stored("record_decode", () => { + let value: unknown = row.payload; + if (storageLayout === "portable-v1") { + if ( + row.schemaVersion !== 1 || + typeof row.partCount !== "number" || + !Number.isSafeInteger(row.partCount) || + row.partCount < 1 || + row.partCount > MAX_CHUNKS + ) + throw new TypeError("Invalid report chunk schema."); + const expected = new Set([ + "schemaVersion", + "articleId", + "id", + "partCount", + ...Array.from( + { length: row.partCount }, + (_, index) => "part" + index, + ), + ]); + if ( + Object.keys(row).length !== expected.size || + Object.keys(row).some((key) => !expected.has(key)) + ) + throw new TypeError("Invalid report chunk fields."); + const parts: string[] = []; + for (let index = 0; index < row.partCount; index += 1) { + const part = row["part" + index]; + // Canonical JSON escapes lone code units. An unpaired unit here + // is malformed data or a surrogate pair split across properties. + if ( + typeof part !== "string" || + part.length === 0 || + part.length > CHUNK_CHARACTERS || + /[\uD800-\uDFFF]/u.test(part) + ) + throw new TypeError("Invalid report chunk."); + parts.push(part); + } + value = parts.join(""); + } + const payload = boundedString(value, 1, MAX_RECORD_BYTES, { + allowMultiline: true, + }); + if (new TextEncoder().encode(payload).byteLength > MAX_RECORD_BYTES) + throw new TypeError("Stored report record exceeds its byte bound."); + return { + articleId: scalar(row.articleId), + id: scalar(row.id), + payload, + }; + }), + }, + }); +} + +interface ReportRecord extends Omit { + readonly receiptGeneration: number; + readonly evidence: EvidenceSubmission; + readonly report: KnowledgeTestReport; + readonly submissionHash: string; + readonly reportHash: string; + readonly articleHash: string; + readonly governanceHash: string; + readonly confirmation: Confirmation | null; +} +interface ResetRecord { + readonly fingerprint: string; + readonly actorId: string; + readonly fromEpoch: number; + readonly startedAt: string; + readonly completedAt: string | null; + readonly retiredRows: number; + readonly retiredReports: number; + readonly contentHash: string; +} +interface LedgerHead { + readonly ledgerEpoch: number; + readonly status: "active" | "resetting"; + readonly reports: number; + readonly rows: number; + readonly drainRemaining: number; + readonly historyHash: string; + readonly lastReset: ResetRecord | null; +} + +function isPlainObject(value: unknown): value is Record { + return ( + typeof value === "object" && + value !== null && + !Array.isArray(value) && + Object.getPrototypeOf(value) === Object.prototype + ); +} +function exactObject( + value: unknown, + keys: readonly string[], +): Record { + if ( + !isPlainObject(value) || + Object.keys(value).length !== keys.length || + keys.some((key) => !Object.hasOwn(value, key)) + ) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return value; +} +function optionalKeysObject( + value: unknown, + required: readonly string[], + optional: readonly string[], +): Record { + if (!isPlainObject(value)) + throw new KnowledgeEvidenceReportsError("invalid_request"); + const allowed = new Set([...required, ...optional]); + if ( + Object.keys(value).some((key) => !allowed.has(key)) || + required.some((key) => !Object.hasOwn(value, key)) + ) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return value; +} +function boundedString( + value: unknown, + minimum: number, + maximum: number, + options: { readonly allowMultiline?: boolean } = {}, +): string { + if ( + typeof value !== "string" || + value.length < minimum || + value.length > maximum + ) + throw new KnowledgeEvidenceReportsError("invalid_request"); + const controls = options.allowMultiline + ? /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/u + : /[\u0000-\u001F\u007F-\u009F]/u; + if (controls.test(value)) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return value; +} +/** Capture bounded JSON data, without invoking caller accessors or coercion. */ +function requestData(value: T): T { + try { + return snapshotData(value); + } catch { + throw new KnowledgeEvidenceReportsError("invalid_request"); + } +} +function callerContext(value: AccessContext): AccessContext { + try { + serializeAccessContext(value); + return requestData(value); + } catch { + throw new KnowledgeEvidenceReportsError("invalid_request"); + } +} + +function scalar(value: unknown, maximum = 200): string { + return boundedString(value, 1, maximum); +} +function positive(value: unknown, minimum = 1): number { + if ( + typeof value !== "number" || + !Number.isSafeInteger(value) || + value < minimum + ) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return value; +} +function timestamp(value: unknown): string { + const text = scalar(value, 32); + if ( + !Number.isFinite(Date.parse(text)) || + new Date(text).toISOString() !== text + ) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return text; +} +function hash(value: unknown): string { + const text = scalar(value, 64); + if (!/^[a-f0-9]{64}$/u.test(text)) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return text; +} +function array(value: unknown, maximum: number): readonly unknown[] { + if (!Array.isArray(value) || value.length > maximum) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return value; +} +function applicability(value: unknown): Applicability { + const object = optionalKeysObject( + value, + ["productId", "productVersion"], + ["buildId", "locale"], + ); + return { + productId: scalar(object.productId), + productVersion: scalar(object.productVersion), + ...(object.buildId === undefined + ? {} + : { buildId: scalar(object.buildId) }), + ...(object.locale === undefined ? {} : { locale: scalar(object.locale) }), + }; +} +function parseKnowledgeEvidence(value: unknown): EvidenceSubmission { + const input = exactObject(value, [ + "id", + "articleId", + "articleRevision", + "contentHash", + "validationPolicy", + "checkId", + "testKind", + "applicability", + "stagingBuildId", + "steps", + "result", + "executedAt", + "runnerId", + "artifacts", + ]); + const policy = exactObject(input.validationPolicy, ["id", "version"]); + if ( + input.result !== "passed" && + input.result !== "failed" && + input.result !== "inconclusive" + ) + throw new KnowledgeEvidenceReportsError("invalid_request"); + const steps = array(input.steps, 16).map((step) => scalar(step, 1000)); + if (steps.length === 0) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return { + id: scalar(input.id), + articleId: scalar(input.articleId), + articleRevision: positive(input.articleRevision), + contentHash: hash(input.contentHash), + validationPolicy: { + id: scalar(policy.id), + version: positive(policy.version), + }, + checkId: scalar(input.checkId), + testKind: scalar(input.testKind, 64), + applicability: applicability(input.applicability), + stagingBuildId: scalar(input.stagingBuildId), + steps, + result: input.result, + executedAt: timestamp(input.executedAt), + runnerId: scalar(input.runnerId), + artifacts: array(input.artifacts, 8).map((item) => { + const artifact = exactObject(item, ["id", "hash"]); + return { id: scalar(artifact.id), hash: hash(artifact.hash) }; + }), + }; +} +function parseReport(value: unknown): KnowledgeTestReport { + const report = exactObject(value, ["summary", "details"]); + return { + summary: scalar(report.summary, 1000), + details: boundedString(report.details, 1, 16_000, { allowMultiline: true }), + }; +} +function canonical(value: unknown): string { + if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]"; + if (isPlainObject(value)) + return ( + "{" + + Object.keys(value) + .sort() + .map((key) => JSON.stringify(key) + ":" + canonical(value[key])) + .join(",") + + "}" + ); + if ( + value === null || + typeof value === "string" || + typeof value === "boolean" || + (typeof value === "number" && Number.isFinite(value)) + ) + return JSON.stringify(value); + throw new TypeError("Unsupported knowledge evidence value."); +} +async function knowledgeDigest(value: unknown): Promise { + try { + const bytes = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(canonical(value)), + ); + return [...new Uint8Array(bytes)] + .map((byte) => byte.toString(16).padStart(2, "0")) + .join(""); + } catch { + throw new KnowledgeEvidenceReportsUnavailableError("hashing"); + } +} +function row(articleId: string, id: string, value: unknown): LedgerRow { + const payload = canonical(value); + if (new TextEncoder().encode(payload).byteLength > MAX_RECORD_BYTES) + throw new KnowledgeEvidenceReportsError("report_too_large"); + return { articleId, id, payload }; +} +function decodeReport(payload: string): ReportRecord { + return stored("report_decode", () => { + const item = exactObject(JSON.parse(payload), [ + "ledgerEpoch", + "receiptGeneration", + "reportId", + "articleId", + "reportGeneration", + "status", + "submittedBy", + "submittedAt", + "evidence", + "report", + "submissionHash", + "reportHash", + "articleHash", + "governanceHash", + "confirmation", + ]); + if ( + item.status !== "pending" && + item.status !== "confirmed" && + item.status !== "rejected" + ) + throw new TypeError("Invalid report status."); + let confirmation: Confirmation | null = null; + if (item.confirmation !== null) { + const proof = exactObject(item.confirmation, [ + "reviewerId", + "confirmedAt", + ]); + confirmation = { + reviewerId: scalar(proof.reviewerId), + confirmedAt: timestamp(proof.confirmedAt), + }; + } + if ((item.status === "confirmed") !== (confirmation !== null)) + throw new TypeError("Invalid confirmation."); + return { + ledgerEpoch: positive(item.ledgerEpoch), + receiptGeneration: positive(item.receiptGeneration), + reportId: scalar(item.reportId), + articleId: scalar(item.articleId), + reportGeneration: positive(item.reportGeneration), + status: item.status, + submittedBy: scalar(item.submittedBy), + submittedAt: timestamp(item.submittedAt), + evidence: parseKnowledgeEvidence(item.evidence), + report: parseReport(item.report), + submissionHash: hash(item.submissionHash), + reportHash: hash(item.reportHash), + articleHash: hash(item.articleHash), + governanceHash: hash(item.governanceHash), + confirmation, + }; + }); +} +function decodeHead(payload: string): LedgerHead { + return stored("head_decode", () => { + const item = exactObject(JSON.parse(payload), [ + "ledgerEpoch", + "status", + "reports", + "rows", + "drainRemaining", + "historyHash", + "lastReset", + ]); + if (item.status !== "active" && item.status !== "resetting") + throw new TypeError("Invalid ledger status."); + const ledgerEpoch = positive(item.ledgerEpoch); + const reports = positive(item.reports, 0); + const rows = positive(item.rows); + const drainRemaining = positive(item.drainRemaining, 0); + if ( + reports > MAX_REPORTS || + rows > MAX_ROWS || + drainRemaining >= MAX_ROWS || + (item.status === "active" && drainRemaining !== 0) || + (item.status === "resetting" && (reports !== 0 || rows !== 1)) + ) + throw new TypeError("Invalid ledger counts."); + let lastReset: ResetRecord | null = null; + if (item.lastReset !== null) { + const reset = exactObject(item.lastReset, [ + "fingerprint", + "actorId", + "fromEpoch", + "startedAt", + "completedAt", + "retiredRows", + "retiredReports", + "contentHash", + ]); + lastReset = { + fingerprint: hash(reset.fingerprint), + actorId: scalar(reset.actorId), + fromEpoch: positive(reset.fromEpoch), + startedAt: timestamp(reset.startedAt), + completedAt: + reset.completedAt === null ? null : timestamp(reset.completedAt), + retiredRows: positive(reset.retiredRows, 0), + retiredReports: positive(reset.retiredReports, 0), + contentHash: hash(reset.contentHash), + }; + if ( + lastReset.fromEpoch + 1 !== ledgerEpoch || + lastReset.retiredRows >= MAX_ROWS || + lastReset.retiredReports > MAX_REPORTS || + (item.status === "active") !== (lastReset.completedAt !== null) + ) + throw new TypeError("Invalid reset seal."); + } else if (ledgerEpoch !== 1 || item.status !== "active") + throw new TypeError("Missing reset seal."); + return { + ledgerEpoch, + status: item.status, + reports, + rows, + drainRemaining, + historyHash: hash(item.historyHash), + lastReset, + }; + }); +} +const INITIAL_HEAD: LedgerHead = { + ledgerEpoch: 1, + status: "active", + reports: 0, + rows: 1, + drainRemaining: 0, + historyHash: "0".repeat(64), + lastReset: null, +}; +function summary(report: ReportRecord): KnowledgeReportSummary { + return { + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + articleId: report.articleId, + reportGeneration: report.reportGeneration, + status: report.status, + submittedBy: report.submittedBy, + submittedAt: report.submittedAt, + summary: report.report.summary, + }; +} +function acknowledgement(report: ReportRecord): KnowledgeReportAcknowledgement { + return { + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + receipt: + "e" + + report.ledgerEpoch + + "." + + report.receiptGeneration + + "." + + report.reportId, + reportGeneration: report.reportGeneration, + }; +} +function reportBinding(report: ReportRecord): unknown { + return { + ledgerEpoch: report.ledgerEpoch, + receiptGeneration: report.receiptGeneration, + reportId: report.reportId, + articleId: report.articleId, + evidence: report.evidence, + report: report.report, + submittedBy: report.submittedBy, + articleHash: report.articleHash, + governanceHash: report.governanceHash, + }; +} +function state( + articleId: string, + head: LedgerHead, +): KnowledgeReportLedgerState { + return { + articleId, + ledgerEpoch: head.ledgerEpoch, + status: head.status, + reportsRemaining: head.status === "active" ? MAX_REPORTS - head.reports : 0, + rowsRemaining: + head.status === "active" ? MAX_ROWS - head.rows : head.drainRemaining, + }; +} +function reportKey(epoch: number, id: string): string { + return "report:" + epoch + ":" + id; +} +function commandKey(epoch: number, idHash: string): string { + return "command:" + epoch + ":" + idHash; +} + +/** Fixed-width code units preserve opaque strings injectively, including astral pairs. */ +function encodedKey(prefix: string, value: string): string { + let result = prefix; + for (let index = 0; index < value.length; index += 1) + result += value.charCodeAt(index).toString(16).padStart(4, "0"); + return result; +} + +/** + * Human review is explicit. It is not a promise that KB will accept the receipt. + * A missing head triggers an unbounded underlying Store partition list for + * integrity/refusal, not a bounded scan or an automatic migration. Quiesce old + * writers and inspect the namespace before activation; this observation is not + * an atomic fence against an old writer inserting after the empty-partition read. + */ +export function createKnowledgeEvidenceReports( + options: KnowledgeEvidenceReportsOptions, +): KnowledgeEvidenceReports { + if (options === null || typeof options !== "object") + throw new KnowledgeEvidenceReportsError("invalid_configuration"); + const { collectionName, confirmationPermission } = options; + const storageLayout = + options.storageLayout === undefined ? "portable-v1" : options.storageLayout; + if ( + typeof collectionName !== "string" || + !/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/u.test(collectionName) || + collectionName === "knowledge-base.records.v1" || + collectionName === "knowledge-base.retrieval.v1" || + (storageLayout !== "portable-v1" && storageLayout !== "legacy-raw-v1") || + typeof confirmationPermission !== "string" || + confirmationPermission.length > 255 || + !/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)*$/u.test( + confirmationPermission, + ) || + [ + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, + ].some((permission) => permission === confirmationPermission) || + typeof options.resolvePrincipal !== "function" || + typeof options.readContext !== "function" || + typeof options.store?.collection !== "function" || + typeof options.clock?.now !== "function" + ) + throw new KnowledgeEvidenceReportsError("invalid_configuration"); + function storageKey(articleId: string, id: string): EntityKey { + if (storageLayout === "legacy-raw-v1") return { partition: articleId, id }; + const partition = encodedKey("a-", articleId); + const physicalId = encodedKey("r-", id); + // Both encoded keys and collectionName are ASCII. Azure prefixes the + // physical partition with collectionName + ":"; include it in the bound. + if ( + collectionName.length + 1 + partition.length > 1_024 || + physicalId.length > 1_024 + ) + throw new KnowledgeEvidenceReportsError("invalid_request"); + return { partition, id: physicalId }; + } + function storagePartition(articleId: string): string { + return storageKey(articleId, "head").partition; + } + const records = stored("collection_open", () => + options.store.collection( + evidenceRecords(collectionName, storageLayout, storageKey), + ), + ); + function now(): string { + return stored("clock_read", () => timestamp(options.clock.now())); + } + async function current( + access: AccessContext, + permission: string, + ): Promise { + const caller = callerContext(access); + const resolved = await ledgerIo("principal_resolve", () => + options.resolvePrincipal(caller.principalId), + ); + const authority = + resolved === null + ? null + : stored("principal_resolve", () => callerContext(resolved)); + if ( + authority === null || + authority.principalId !== caller.principalId || + !hasPermission(caller, permission) || + !hasPermission(authority, permission) || + caller.permissions.some((grant) => !hasPermission(authority, grant)) + ) + throw new KnowledgeEvidenceReportsError("forbidden"); + // A current owner/Admin context establishes continued authority; it never + // replaces the original credential's restricted effective permissions. + return caller; + } + async function staff(access: AccessContext): Promise { + access = await current(access, confirmationPermission); + for (const permission of [ + knowledgePermissions.draftRead, + knowledgePermissions.evidenceRead, + ]) + if (!hasPermission(access, permission)) + throw new KnowledgeEvidenceReportsError("forbidden"); + return access; + } + async function headVersion(articleId: string) { + const saved = await ledgerIo("head_read", () => + records.getVersioned(storageKey(articleId, "head")), + ); + // Missing metadata is fresh only when its actual partition is empty. Never + // silently initialize an epoch over pre-epoch records or orphaned history. + // Storage Core 0.4 has no bounded partition probe: partitionRows uses the + // existing unbounded list port, with integrity checks after that read. + if (saved === null && (await partitionRows(articleId)).length !== 0) + throw new KnowledgeEvidenceReportsUnavailableError( + "head_partition_orphaned", + ); + if ( + saved !== null && + (saved.value.articleId !== articleId || saved.value.id !== "head") + ) + throw new KnowledgeEvidenceReportsUnavailableError("head_identity"); + return { + value: saved === null ? INITIAL_HEAD : decodeHead(saved.value.payload), + version: saved?.version, + }; + } + async function active(articleId: string, epoch: number): Promise { + const head = (await headVersion(articleId)).value; + if (head.ledgerEpoch !== epoch) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (head.status !== "active") + throw new KnowledgeEvidenceReportsError("ledger_resetting"); + return head; + } + async function partitionRows(articleId: string): Promise { + const rows = await ledgerIo("partition_read", () => + records.list(storagePartition(articleId)), + ); + if ( + rows.length > MAX_ROWS || + rows.some((item) => item.articleId !== articleId) || + new Set(rows.map((item) => item.id)).size !== rows.length + ) + throw new KnowledgeEvidenceReportsUnavailableError("partition_integrity"); + return rows; + } + async function load( + articleId: string, + epoch: number, + reportId: string, + ): Promise { + const saved = await ledgerIo("report_read", () => + records.get(storageKey(articleId, reportKey(epoch, reportId))), + ); + if (saved === null) + throw new KnowledgeEvidenceReportsError("report_not_found"); + const report = decodeReport(saved.payload); + if ( + saved.id !== reportKey(epoch, reportId) || + report.articleId !== articleId || + report.reportId !== reportId || + report.ledgerEpoch !== epoch + ) + throw new KnowledgeEvidenceReportsUnavailableError("report_identity"); + return report; + } + async function context( + access: AccessContext, + articleId: string, + ): Promise { + try { + const value = snapshotData( + await options.readContext(callerContext(access), articleId), + ); + if ( + value.draft.articleId !== articleId || + value.draft.revision.articleId !== articleId || + value.requirements.collectionId !== value.draft.revision.collectionId || + (value.evidence !== undefined && value.evidence.articleId !== articleId) + ) + throw new KnowledgeEvidenceReportsUnavailableError("context_read"); + return value; + } catch (error) { + if (error instanceof KnowledgeEvidenceReportsError) throw error; + if (error instanceof KnowledgeBaseAuthorizationError) + throw new KnowledgeEvidenceReportsError("forbidden"); + if (error instanceof KnowledgeBaseNotFoundError) + throw new KnowledgeEvidenceReportsError("report_target_unavailable"); + throw new KnowledgeEvidenceReportsUnavailableError("context_read"); + } + } + async function contextHashes(value: KnowledgeEvidenceContext) { + return { + articleHash: await knowledgeDigest(value.draft.revision), + governanceHash: await knowledgeDigest(value.requirements), + }; + } + async function valid( + report: ReportRecord, + article: ArticleRevision, + value: KnowledgeEvidenceContext, + at: string, + ): Promise { + if ( + report.reportHash !== (await knowledgeDigest(reportBinding(report))) || + report.articleHash !== (await knowledgeDigest(article)) || + report.governanceHash !== (await knowledgeDigest(value.requirements)) || + report.submissionHash !== (await knowledgeDigest(report.evidence)) || + value.evidence?.revokedEvidence.some( + (item) => + item.id === report.evidence.id && + item.articleRevision === report.evidence.articleRevision, + ) + ) + return false; + const submission = report.evidence; + const requirement = value.requirements.checks.find( + (item) => + item.id === submission.checkId && item.testKind === submission.testKind, + ); + const executed = Date.parse(submission.executedAt); + const now = Date.parse(at); + return ( + submission.articleId === article.articleId && + submission.articleRevision === article.number && + submission.contentHash === article.contentHash && + (await knowledgeDigest(submission.applicability)) === + (await knowledgeDigest(article.applicability)) && + (await knowledgeDigest(submission.validationPolicy)) === + (await knowledgeDigest(value.requirements.validationPolicy)) && + (await knowledgeDigest(article.validationPolicy)) === + (await knowledgeDigest(value.requirements.validationPolicy)) && + submission.stagingBuildId === value.requirements.expectedStagingBuildId && + (article.applicability.buildId === undefined || + submission.stagingBuildId === article.applicability.buildId) && + requirement !== undefined && + executed >= Date.parse(article.createdAt) && + executed <= now && + now - executed <= requirement.maxAgeMilliseconds && + (report.confirmation === null || + (Date.parse(report.confirmation.confirmedAt) >= executed && + Date.parse(report.confirmation.confirmedAt) <= now)) + ); + } + async function replay( + articleId: string, + epoch: number, + commandId: string, + fingerprint: string, + ): Promise { + const saved = await ledgerIo("receipt_read", () => + records.get(storageKey(articleId, commandKey(epoch, commandId))), + ); + if (saved === null) return null; + const decoded = stored("receipt_decode", () => { + const receipt = exactObject(JSON.parse(saved.payload), [ + "fingerprint", + "result", + ]); + if ( + typeof receipt.fingerprint !== "string" || + !/^[a-f0-9]{64}$/u.test(receipt.fingerprint) + ) + throw new TypeError("Invalid receipt."); + const result = exactObject(receipt.result, [ + "ledgerEpoch", + "reportId", + "receipt", + "reportGeneration", + ]); + const decoded = { + ledgerEpoch: positive(result.ledgerEpoch), + reportId: scalar(result.reportId), + receipt: scalar(result.receipt), + reportGeneration: positive(result.reportGeneration), + }; + if (decoded.ledgerEpoch !== epoch) + throw new TypeError("Receipt epoch changed."); + return { fingerprint: receipt.fingerprint, result: decoded }; + }); + if (decoded.fingerprint !== fingerprint) + throw new KnowledgeEvidenceReportsError("command_conflict"); + return decoded.result; + } + async function write( + access: AccessContext, + commandId: string, + fingerprint: string, + report: ReportRecord, + previousVersion?: string, + ): Promise { + const head = await headVersion(report.articleId); + if (head.value.ledgerEpoch !== report.ledgerEpoch) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (head.value.status !== "active") + throw new KnowledgeEvidenceReportsError("ledger_resetting"); + const reports = + head.value.reports + (previousVersion === undefined ? 1 : 0); + const rows = head.value.rows + (previousVersion === undefined ? 3 : 2); + if (reports > MAX_REPORTS || rows > MAX_ROWS) + throw new KnowledgeEvidenceReportsError("report_capacity"); + const result = acknowledgement(report); + const key = commandKey(report.ledgerEpoch, commandId); + const event = auditEvent({ + id: key, + occurredAt: now(), + actor: { kind: "principal", principalId: access.principalId }, + action: "knowledge.report." + report.status, + subject: report.articleId, + details: { + reportId: report.reportId, + reportHash: report.reportHash, + generation: report.reportGeneration, + ledgerEpoch: report.ledgerEpoch, + receiptGeneration: report.receiptGeneration, + }, + }); + await current( + access, + previousVersion === undefined + ? knowledgePermissions.evidenceSubmit + : confirmationPermission, + ); + const headRow = row(report.articleId, "head", { + ...head.value, + reports, + rows, + }); + const reportRow = row( + report.articleId, + reportKey(report.ledgerEpoch, report.reportId), + report, + ); + const outcome = await ledgerIo("report_write", () => + records.transact(storagePartition(report.articleId), [ + head.version === undefined + ? { action: "insert", value: headRow } + : { action: "putIfUnchanged", value: headRow, version: head.version }, + previousVersion === undefined + ? { action: "insert", value: reportRow } + : { + action: "putIfUnchanged", + value: reportRow, + version: previousVersion, + }, + { + action: "insert", + value: row(report.articleId, key, { fingerprint, result }), + }, + { + action: "insert", + value: row(report.articleId, "audit:" + key, event), + }, + ]), + ); + if (!outcome.committed) { + await active(report.articleId, report.ledgerEpoch); + const accepted = await replay( + report.articleId, + report.ledgerEpoch, + commandId, + fingerprint, + ); + if (accepted !== null) return accepted; + throw new KnowledgeEvidenceReportsError("report_changed"); + } + await active(report.articleId, report.ledgerEpoch); + return result; + } + const verifier: EvidenceVerifier = { + async verify(request) { + try { + request = requestData(request); + const receipt = + /^e([1-9][0-9]*)\.([1-9][0-9]*)\.([A-Za-z0-9-]{1,100})$/u.exec( + scalar(request.receipt), + ); + if (receipt === null) return null; + const epoch = positive(Number(receipt[1])); + const cycle = positive(Number(receipt[2])); + const reportId = scalar(receipt[3]); + await active(request.article.articleId, epoch); + const report = await load(request.article.articleId, epoch, reportId); + if ( + report.receiptGeneration !== cycle || + report.status !== "confirmed" || + report.confirmation === null || + request.access.principalId !== report.submittedBy || + (await knowledgeDigest(request.submission)) !== + report.submissionHash || + !request.configuration.trustedAttesterIds.includes( + report.confirmation.reviewerId, + ) + ) + return null; + const confirmation = report.confirmation; + const resolvedReviewer = await ledgerIo("principal_resolve", () => + options.resolvePrincipal(confirmation.reviewerId), + ); + const reviewer = + resolvedReviewer === null + ? null + : stored("principal_resolve", () => + callerContext(resolvedReviewer), + ); + if ( + reviewer === null || + reviewer.principalId !== confirmation.reviewerId || + !hasPermission(reviewer, confirmationPermission) + ) + return null; + const value = await context(reviewer, report.articleId); + if ( + !(await valid(report, request.article, value, now())) || + request.configuration.expectedStagingBuildId !== + value.requirements.expectedStagingBuildId || + (await knowledgeDigest(request.configuration.validationPolicy)) !== + (await knowledgeDigest(value.requirements.validationPolicy)) + ) + return null; + await current(request.access, knowledgePermissions.evidenceSubmit); + await staff(reviewer); + const latest = await load(report.articleId, epoch, reportId); + if ( + latest.reportGeneration !== report.reportGeneration || + latest.receiptGeneration !== cycle || + latest.status !== "confirmed" + ) + return null; + // A reset fences subsequent verification. The SDK's already verified + // article commit is outside this separate report-ledger transaction. + await active(report.articleId, epoch); + return { + id: request.receipt, + verifiedBy: report.confirmation.reviewerId, + verifiedAt: report.confirmation.confirmedAt, + }; + } catch (error) { + if (!(error instanceof KnowledgeEvidenceReportsError)) { + try { + options.logger?.log( + "error", + "knowledge.evidence_reports.verifier_unavailable", + { + stage: + error instanceof KnowledgeEvidenceReportsUnavailableError + ? error.stage + : "verification", + }, + ); + } catch { + /* Logging must not turn refusal into a verifier exception. */ + } + } + return null; + } + }, + }; + return Object.freeze({ + verifier, + async ledger(access, input) { + input = requestData(input); + access = await current(access, knowledgePermissions.evidenceSubmit); + const value = exactObject(input, ["articleId"]); + const articleId = scalar(value.articleId); + const head = await headVersion(articleId); + await current(access, knowledgePermissions.evidenceSubmit); + return state(articleId, head.value); + }, + async report(access, value) { + value = requestData(value); + access = await current(access, knowledgePermissions.evidenceSubmit); + const input = exactObject(value, [ + "commandId", + "articleId", + "ledgerEpoch", + "evidence", + "report", + ]); + const commandId = await knowledgeDigest(scalar(input.commandId)); + const articleId = scalar(input.articleId); + const ledgerEpoch = positive(input.ledgerEpoch); + const evidence = parseKnowledgeEvidence(input.evidence); + const report = parseReport(input.report); + if (evidence.articleId !== articleId) + throw new KnowledgeEvidenceReportsError("invalid_request"); + await active(articleId, ledgerEpoch); + const fingerprint = await knowledgeDigest({ + actor: access.principalId, + operation: "report", + commandId, + articleId, + ledgerEpoch, + evidence, + report, + }); + const accepted = await replay( + articleId, + ledgerEpoch, + commandId, + fingerprint, + ); + if (accepted !== null) { + await current(access, knowledgePermissions.evidenceSubmit); + await active(articleId, ledgerEpoch); + return accepted; + } + const hashes = await contextHashes(await context(access, articleId)); + const initial: ReportRecord = { + ledgerEpoch, + receiptGeneration: 1, + reportId: crypto.randomUUID(), + articleId, + reportGeneration: 1, + status: "pending", + submittedBy: access.principalId, + submittedAt: now(), + evidence, + report, + submissionHash: await knowledgeDigest(evidence), + reportHash: "0".repeat(64), + ...hashes, + confirmation: null, + }; + return write(access, commandId, fingerprint, { + ...initial, + reportHash: await knowledgeDigest(reportBinding(initial)), + }); + }, + async status(access, value) { + value = requestData(value); + access = await current(access, knowledgePermissions.evidenceSubmit); + const input = exactObject(value, [ + "articleId", + "ledgerEpoch", + "reportId", + ]); + const articleId = scalar(input.articleId); + const epoch = positive(input.ledgerEpoch); + await active(articleId, epoch); + const report = await load(articleId, epoch, scalar(input.reportId)); + if (report.submittedBy !== access.principalId) + throw new KnowledgeEvidenceReportsError("report_not_found"); + await current(access, knowledgePermissions.evidenceSubmit); + await active(articleId, epoch); + return { ...acknowledgement(report), status: report.status }; + }, + async list(access, value) { + value = requestData(value); + access = await staff(access); + const input = exactObject(value, ["articleId"]); + const articleId = scalar(input.articleId); + const head = await headVersion(articleId); + const rows = await partitionRows(articleId); + const reports = + head.value.status === "active" + ? rows + .filter((item) => + item.id.startsWith("report:" + head.value.ledgerEpoch + ":"), + ) + .map((item) => { + const report = decodeReport(item.payload); + if ( + report.articleId !== articleId || + report.ledgerEpoch !== head.value.ledgerEpoch || + item.id !== reportKey(head.value.ledgerEpoch, report.reportId) + ) + throw new KnowledgeEvidenceReportsUnavailableError( + "report_identity", + ); + return summary(report); + }) + : []; + await staff(access); + const latest = await headVersion(articleId); + if ( + latest.value.ledgerEpoch !== head.value.ledgerEpoch || + latest.value.status !== head.value.status + ) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (latest.version !== head.version) + throw new KnowledgeEvidenceReportsError("ledger_changed"); + if ( + head.value.status === "active" && + reports.length !== head.value.reports + ) + throw new KnowledgeEvidenceReportsUnavailableError("report_count"); + return { ledger: state(articleId, latest.value), reports }; + }, + async read(access, value) { + value = requestData(value); + access = await staff(access); + const input = exactObject(value, [ + "articleId", + "ledgerEpoch", + "reportId", + ]); + const articleId = scalar(input.articleId); + const epoch = positive(input.ledgerEpoch); + await active(articleId, epoch); + const report = await load(articleId, epoch, scalar(input.reportId)); + const valueContext = await context(access, articleId); + const reviewBindingHash = await knowledgeDigest({ + report, + context: valueContext, + }); + await staff(access); + await active(articleId, epoch); + return { + ...summary(report), + evidence: report.evidence, + report: report.report, + draft: valueContext.draft, + reportHash: report.reportHash, + submissionHash: report.submissionHash, + governanceHash: report.governanceHash, + requirements: valueContext.requirements, + reviewBindingHash, + expectedReportGeneration: report.reportGeneration, + confirmation: report.confirmation, + }; + }, + async decide(access, value, decision) { + value = requestData(value); + if ( + decision !== "confirmed" && + decision !== "rejected" && + decision !== "pending" + ) + throw new KnowledgeEvidenceReportsError("invalid_request"); + access = await staff(access); + const input = exactObject(value, [ + "commandId", + "articleId", + "ledgerEpoch", + "reportId", + "expectedReportGeneration", + "reviewBindingHash", + ]); + const commandId = await knowledgeDigest(scalar(input.commandId)); + const articleId = scalar(input.articleId); + const epoch = positive(input.ledgerEpoch); + const reportId = scalar(input.reportId); + const expected = positive(input.expectedReportGeneration); + const binding = hash(input.reviewBindingHash); + await active(articleId, epoch); + const fingerprint = await knowledgeDigest({ + actor: access.principalId, + operation: decision, + commandId, + articleId, + ledgerEpoch: epoch, + reportId, + expected, + binding, + }); + const accepted = await replay(articleId, epoch, commandId, fingerprint); + if (accepted !== null) { + await staff(access); + await active(articleId, epoch); + return accepted; + } + const saved = await ledgerIo("report_read", () => + records.getVersioned(storageKey(articleId, reportKey(epoch, reportId))), + ); + if (saved === null) + throw new KnowledgeEvidenceReportsError("report_not_found"); + const report = decodeReport(saved.value.payload); + if ( + report.ledgerEpoch !== epoch || + report.reportId !== reportId || + report.articleId !== articleId + ) + throw new KnowledgeEvidenceReportsUnavailableError("report_identity"); + if ( + report.reportGeneration !== expected || + (decision === "pending" + ? report.status === "pending" + : report.status !== "pending") + ) + throw new KnowledgeEvidenceReportsError("report_changed"); + const valueContext = await context(access, articleId); + if ( + (await knowledgeDigest({ report, context: valueContext })) !== binding + ) + throw new KnowledgeEvidenceReportsError("report_changed"); + const at = now(); + let next: ReportRecord = { + ...report, + reportGeneration: positive(report.reportGeneration + 1), + status: decision, + confirmation: + decision === "confirmed" + ? { reviewerId: access.principalId, confirmedAt: at } + : null, + }; + if (decision === "pending") { + next = { + ...next, + receiptGeneration: positive(report.receiptGeneration + 1), + ...(await contextHashes(valueContext)), + }; + next = { + ...next, + reportHash: await knowledgeDigest(reportBinding(next)), + }; + } + if ( + decision !== "rejected" && + !(await valid(next, valueContext.draft.revision, valueContext, at)) + ) + throw new KnowledgeEvidenceReportsError("report_not_verifiable"); + const latestContext = await context(await staff(access), articleId); + if ( + (await knowledgeDigest(valueContext)) !== + (await knowledgeDigest(latestContext)) + ) + throw new KnowledgeEvidenceReportsError("report_changed"); + return write(access, commandId, fingerprint, next, saved.version); + }, + async reset(access, value) { + value = requestData(value); + access = await staff(access); + const input = exactObject(value, [ + "commandId", + "articleId", + "expectedLedgerEpoch", + ]); + const articleId = scalar(input.articleId); + const expected = positive(input.expectedLedgerEpoch); + const fingerprint = await knowledgeDigest({ + actorId: access.principalId, + articleId, + expectedLedgerEpoch: expected, + commandId: scalar(input.commandId), + }); + const head = await headVersion(articleId); + if ( + head.value.lastReset?.fingerprint === fingerprint && + head.value.lastReset.actorId === access.principalId && + head.value.lastReset.fromEpoch === expected + ) { + await staff(access); + return state(articleId, head.value); + } + if (head.value.ledgerEpoch !== expected) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (head.value.status !== "active") + throw new KnowledgeEvidenceReportsError("ledger_resetting"); + if (expected === Number.MAX_SAFE_INTEGER) + throw new KnowledgeEvidenceReportsError("ledger_epoch_exhausted"); + const oldRows = (await partitionRows(articleId)) + .filter((item) => item.id !== "head") + .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + if ((await headVersion(articleId)).version !== head.version) + throw new KnowledgeEvidenceReportsError("ledger_changed"); + if (oldRows.length !== head.value.rows - 1) + throw new KnowledgeEvidenceReportsUnavailableError("reset_count"); + const reset: ResetRecord = { + fingerprint, + actorId: access.principalId, + fromEpoch: expected, + startedAt: now(), + completedAt: null, + retiredRows: oldRows.length, + retiredReports: head.value.reports, + contentHash: await knowledgeDigest(oldRows), + }; + const next: LedgerHead = { + ledgerEpoch: expected + 1, + status: "resetting", + reports: 0, + rows: 1, + drainRemaining: oldRows.length, + historyHash: await knowledgeDigest({ + previous: head.value.historyHash, + reset, + }), + lastReset: reset, + }; + await staff(access); + const outcome = await ledgerIo("reset_begin", () => + records.transact(storagePartition(articleId), [ + head.version === undefined + ? { action: "insert", value: row(articleId, "head", next) } + : { + action: "putIfUnchanged", + value: row(articleId, "head", next), + version: head.version, + }, + ]), + ); + if (!outcome.committed) + throw new KnowledgeEvidenceReportsError("ledger_changed"); + return state(articleId, next); + }, + async drain(access, value) { + value = requestData(value); + access = await staff(access); + const input = exactObject(value, ["articleId", "ledgerEpoch"]); + const articleId = scalar(input.articleId); + const epoch = positive(input.ledgerEpoch); + const head = await headVersion(articleId); + if (head.value.ledgerEpoch !== epoch) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (head.value.status === "active") { + await staff(access); + return state(articleId, head.value); + } + if (head.version === undefined || head.value.lastReset === null) + throw new KnowledgeEvidenceReportsUnavailableError("reset_head"); + const version = head.version; + const oldRows = (await partitionRows(articleId)) + .filter((item) => item.id !== "head") + .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + if ((await headVersion(articleId)).version !== version) + throw new KnowledgeEvidenceReportsError("ledger_changed"); + if (oldRows.length !== head.value.drainRemaining) + throw new KnowledgeEvidenceReportsUnavailableError("drain_count"); + const selected = oldRows.slice(0, DRAIN_ROWS); + const remaining = oldRows.length - selected.length; + const next: LedgerHead = { + ...head.value, + status: remaining === 0 ? "active" : "resetting", + drainRemaining: remaining, + lastReset: { + ...head.value.lastReset, + completedAt: remaining === 0 ? now() : null, + }, + }; + await staff(access); + const outcome = await ledgerIo("reset_drain", () => + records.transact(storagePartition(articleId), [ + { + action: "putIfUnchanged", + value: row(articleId, "head", next), + version, + }, + ...selected.map((item) => ({ + action: "delete" as const, + key: storageKey(articleId, item.id), + })), + ]), + ); + if (!outcome.committed) + throw new KnowledgeEvidenceReportsError("ledger_changed"); + return state(articleId, next); + }, + } satisfies KnowledgeEvidenceReports); +} diff --git a/packages/application/src/index.ts b/packages/application/src/index.ts index 66d4c2d..3b01556 100644 --- a/packages/application/src/index.ts +++ b/packages/application/src/index.ts @@ -71,3 +71,11 @@ export type * from "./retrieval-types.js"; export { defaultKnowledgeRetrievalLimits } from "./retrieval-types.js"; export { retrievalRecords, type RetrievalRecord } from "./retrieval-records.js"; export { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +export { createKnowledgeEvidenceReports } from "./evidence-reports.js"; +export { + KnowledgeEvidenceReportsError, + KnowledgeEvidenceReportsUnavailableError, + type KnowledgeEvidenceReportsErrorCode, + type KnowledgeEvidenceReportsStage, +} from "./evidence-reports-errors.js"; +export type * from "./evidence-reports-types.js"; diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 7c3b3ee..2db5324 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-contracts", - "version": "0.1.2", + "version": "0.1.3", "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 4a3fe7e..4336010 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-core", - "version": "0.1.2", + "version": "0.1.3", "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.2" + "@pegma/knowledge-base-contracts": "0.1.3" }, "scripts": { "build": "tsc -p tsconfig.json", diff --git a/packages/mcp/README.md b/packages/mcp/README.md index a93e44b..698bec0 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -53,6 +53,46 @@ describes authenticated contexts, trusted evidence, replay, and safe DTOs. The [retrieval contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RETRIEVAL.md) describes authoritative current-publication confirmation and audience boundaries. +## Optional native-client report mode (unpublished `0.1.3` source) + +`createKnowledgeAgentDispatcher` optionally accepts +`reports: Pick`. +This composes the shared human-report service without adding tools or scopes. +The existing five operations remain `getDraft`, `createDraft`, `updateDraft`, +`getValidationRequirements` and `submitEvidence`. Configured MCP tool schemas +advertise report discovery/polling and submission variants on the latter two; +HTTP uses the same envelopes. Omitting `reports` preserves the exact legacy +schemas and results, rejecting extension fields. + +Both report variants need effective `draftRead` and `evidenceSubmit`. +Requirements input adds `articleId` and optional +`reportLookup: { ledgerEpoch, reportId }`, returning `reportLedger` and optional +owner-only, body-free `reportStatus`. Receipt-free `submitEvidence` adds the +current `ledgerEpoch` and `report: { summary, details }` to the original command +and exact evidence fields. Its `kind: "pending-human-review"` result acknowledges +only a report; it is not an article mutation or verified evidence. + +The native client polls through that same requirements tool. A separately +authorized human reviews the private report and records a decision; staff may +review their own agent and no two-person rule is enforced. After confirmation, +the original receipt-bearing `submitEvidence` form performs actual KB +qualification with the exact evidence and current article generation. First +confirmation preserves the report receipt; reassessment rotates its cycle. +Current runner/result/build/governance and freshness checks still apply. +Report bodies, reviewer details and private accepted evidence remain staff-only. + +Hosts must bind optional report methods to the same authenticated request/grant +and revalidate it before and after every awaited `report`, `ledger` or `status` +call. Preserve the dispatcher-supplied restricted context rather than replacing +it with current owner/Admin authority. Principal resolution inside a report +ledger does not replace host credential/grant freshness checks. + +Read the DEVELOPMENT [wire contract](https://github.com/pegma-dev/knowledge-base/blob/main/docs/AGENT_API.md#optional-native-client-report-mode), +[native-client workflow](https://github.com/pegma-dev/knowledge-base/blob/main/docs/AGENT_WORKFLOW.md#submit-a-report-and-poll-through-the-same-mcp-connection) +and [report lifecycle](https://github.com/pegma-dev/knowledge-base/blob/main/docs/EVIDENCE_REPORTS.md) +before composing this unpublished mode. The verified `0.1.2` release does not +contain it; its own reviewed publication and host/client acceptance remain open. + ## Local verification and release Repository development uses Node 22.6.0+ or 24 with pnpm 10.34.5: @@ -82,9 +122,9 @@ 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.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 +The base-contract links above target verified `v0.1.2`; new report-mode links +explicitly target DEVELOPMENT `main` until their own reviewed release tag exists. +Source readers can use the explicitly moving [DEVELOPMENT documentation on main](https://github.com/pegma-dev/knowledge-base/blob/main/docs/HOST_COMPOSITION.md) while preparing a release. The versioned contract references remain tag-pinned; diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 3ed8525..e58bc52 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-mcp", - "version": "0.1.2", + "version": "0.1.3", "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.2", - "@pegma/knowledge-base-contracts": "0.1.2", - "@pegma/knowledge-base-core": "0.1.2", + "@pegma/knowledge-base-application": "0.1.3", + "@pegma/knowledge-base-contracts": "0.1.3", + "@pegma/knowledge-base-core": "0.1.3", "zod": "4.6.7" }, "scripts": { diff --git a/packages/mcp/src/dispatcher.ts b/packages/mcp/src/dispatcher.ts index d8952e5..bce17bc 100644 --- a/packages/mcp/src/dispatcher.ts +++ b/packages/mcp/src/dispatcher.ts @@ -1,4 +1,5 @@ import type { AccessContext } from "@pegma/authorization-core"; +import { KnowledgeEvidenceReportsError } from "@pegma/knowledge-base-application"; import { createKnowledgeAgentErrorResponse, @@ -7,6 +8,8 @@ import { } from "./errors.js"; import { knowledgeAgentEnvelopeSchema, + knowledgeAgentReportEnvelopeSchema, + knowledgeAgentReportResultSchemas, knowledgeAgentResultSchemas, resolveKnowledgeAgentLimits, snapshotKnowledgeAgentJson, @@ -140,6 +143,38 @@ function requireOperation( if (!allowed) throw new KnowledgeAgentBoundaryError("forbidden"); } +function requireReportAccess(access: AccessContext): void { + if ( + !access.permissions.includes(knowledgeAgentScopes.draftRead) || + !access.permissions.includes(knowledgeAgentScopes.evidenceSubmit) + ) { + throw new KnowledgeAgentBoundaryError("forbidden"); + } +} + +function reportError( + error: KnowledgeEvidenceReportsError, +): KnowledgeAgentBoundaryError { + switch (error.code) { + case "invalid_request": + return new KnowledgeAgentBoundaryError("invalid_request"); + case "report_too_large": + case "report_capacity": + return new KnowledgeAgentBoundaryError("capacity"); + case "forbidden": + return new KnowledgeAgentBoundaryError("forbidden"); + case "report_not_found": + return new KnowledgeAgentBoundaryError("not_found"); + case "invalid_configuration": + return new KnowledgeAgentBoundaryError("unavailable"); + case "report_target_unavailable": + case "report_not_verifiable": + return new KnowledgeAgentBoundaryError("prerequisite"); + default: + return new KnowledgeAgentBoundaryError("conflict"); + } +} + /** * One versioned least-authority boundary shared by HTTP and MCP. Authentication, * credential issuance, current access resolution, and rate limits are host work. @@ -150,8 +185,35 @@ export function createKnowledgeAgentDispatcher( const limits = resolveKnowledgeAgentLimits(options.limits); const resource = trustedText(options.resource, 2_048); const application = options.application; + const suppliedReports = options.reports; + if ( + suppliedReports !== undefined && + (!suppliedReports || + typeof suppliedReports.report !== "function" || + typeof suppliedReports.ledger !== "function" || + typeof suppliedReports.status !== "function") + ) { + throw new TypeError("Invalid knowledge agent report service"); + } + const reports = + suppliedReports === undefined + ? undefined + : Object.freeze({ + report: suppliedReports.report.bind(suppliedReports), + ledger: suppliedReports.ledger.bind(suppliedReports), + status: suppliedReports.status.bind(suppliedReports), + }); + const envelopeSchema = + reports === undefined + ? knowledgeAgentEnvelopeSchema + : knowledgeAgentReportEnvelopeSchema; + const resultSchemas = + reports === undefined + ? knowledgeAgentResultSchemas + : knowledgeAgentReportResultSchemas; return Object.freeze({ limits, + ...(reports === undefined ? {} : { reportWorkflow: true as const }), async dispatch(identity: KnowledgeAgentIdentity, request: unknown) { let operation: KnowledgeAgentOperation | null = null; try { @@ -159,7 +221,7 @@ export function createKnowledgeAgentDispatcher( // await. The application still performs current resource/replay checks. const access = effectiveAccess(identity, resource); const snapshot = snapshotKnowledgeAgentJson(request, limits); - const parsed = knowledgeAgentEnvelopeSchema.safeParse(snapshot); + const parsed = envelopeSchema.safeParse(snapshot); if (!parsed.success) throw new KnowledgeAgentBoundaryError("invalid_request"); const envelope = snapshotKnowledgeAgentJson( @@ -180,13 +242,132 @@ export function createKnowledgeAgentDispatcher( result = await application.updateDraft(access, envelope.input); break; case "getValidationRequirements": - result = await application.getValidationRequirements( - access, - envelope.input, - ); + if (!("articleId" in envelope.input)) { + result = await application.getValidationRequirements( + access, + envelope.input, + ); + break; + } + requireReportAccess(access); + if (reports === undefined) + throw new KnowledgeAgentBoundaryError("invalid_request"); + { + const input = envelope.input; + const target = await application.getDraft(access, { + articleId: input.articleId, + }); + if ( + target.revision.collectionId !== input.collectionId || + target.revision.kind !== input.kind + ) + throw new KnowledgeAgentBoundaryError("conflict"); + // Closed application DTOs receive only their actual public fields. + const query = { + collectionId: input.collectionId, + kind: input.kind, + }; + const requirements = await application.getValidationRequirements( + access, + query, + ); + const ledger = await reports.ledger(access, { + articleId: input.articleId, + }); + const lookup = input.reportLookup; + if ( + lookup !== undefined && + ledger.ledgerEpoch !== lookup.ledgerEpoch + ) + throw new KnowledgeAgentBoundaryError("conflict"); + const status = + lookup === undefined + ? undefined + : await reports.status(access, { + articleId: input.articleId, + ...lookup, + }); + const latestRequirements = + await application.getValidationRequirements(access, query); + const latestLedger = await reports.ledger(access, { + articleId: input.articleId, + }); + const latest = await application.getDraft(access, { + articleId: input.articleId, + }); + if ( + latest.generation !== target.generation || + latest.revision.collectionId !== input.collectionId || + latest.revision.kind !== input.kind || + JSON.stringify(latestRequirements) !== + JSON.stringify(requirements) || + latestLedger.ledgerEpoch !== ledger.ledgerEpoch || + latestLedger.status !== ledger.status + ) + throw new KnowledgeAgentBoundaryError("conflict"); + if ( + status !== undefined && + (status.ledgerEpoch !== lookup?.ledgerEpoch || + status.reportId !== lookup?.reportId) + ) + throw new KnowledgeAgentBoundaryError("unavailable"); + result = { + ...latestRequirements, + reportLedger: { + ledgerEpoch: latestLedger.ledgerEpoch, + status: latestLedger.status, + }, + ...(status === undefined + ? {} + : { + reportStatus: { + ledgerEpoch: status.ledgerEpoch, + reportId: status.reportId, + receipt: status.receipt, + reportGeneration: status.reportGeneration, + status: status.status, + }, + }), + }; + } break; case "submitEvidence": - result = await application.submitEvidence(access, envelope.input); + if ("receipt" in envelope.input) { + result = await application.submitEvidence(access, envelope.input); + break; + } + requireReportAccess(access); + if (reports === undefined) + throw new KnowledgeAgentBoundaryError("invalid_request"); + { + const input = envelope.input; + const target = await application.getDraft(access, { + articleId: input.articleId, + }); + if (target.generation !== input.expectedGeneration) + throw new KnowledgeAgentBoundaryError("conflict"); + const ack = await reports.report(access, { + commandId: input.commandId, + articleId: input.articleId, + ledgerEpoch: input.ledgerEpoch, + evidence: input.evidence, + report: input.report, + }); + // The report and article live in separate partitions. A changed + // article withholds this ACK; it does not roll back a queued report. + const latest = await application.getDraft(access, { + articleId: input.articleId, + }); + if (latest.generation !== target.generation) + throw new KnowledgeAgentBoundaryError("conflict"); + result = { + kind: "pending-human-review", + ledgerEpoch: ack.ledgerEpoch, + reportId: ack.reportId, + receipt: ack.receipt, + reportGeneration: ack.reportGeneration, + }; + } break; } let detached: unknown; @@ -205,7 +386,7 @@ export function createKnowledgeAgentDispatcher( } throw new KnowledgeAgentBoundaryError("unavailable"); } - const safe = knowledgeAgentResultSchemas[operation].safeParse(detached); + const safe = resultSchemas[operation].safeParse(detached); if (!safe.success) throw new KnowledgeAgentBoundaryError("unavailable"); return snapshotKnowledgeAgentJson( { apiVersion: "1", operation, result: safe.data }, @@ -214,7 +395,11 @@ export function createKnowledgeAgentDispatcher( ) as KnowledgeAgentSuccess; } catch (error) { return createKnowledgeAgentErrorResponse( - mapKnowledgeAgentError(error).code, + mapKnowledgeAgentError( + error instanceof KnowledgeEvidenceReportsError + ? reportError(error) + : error, + ).code, operation, ); } diff --git a/packages/mcp/src/mcp.ts b/packages/mcp/src/mcp.ts index 6deda9a..8b104f6 100644 --- a/packages/mcp/src/mcp.ts +++ b/packages/mcp/src/mcp.ts @@ -15,6 +15,7 @@ import { } from "./errors.js"; import { knowledgeAgentInputSchemas, + knowledgeAgentReportInputSchemas, snapshotKnowledgeAgentJson, } from "./schemas.js"; import { @@ -214,21 +215,35 @@ const descriptions: Readonly> = { submitEvidence: "Submit evidence with a host-verifiable receipt for an exact revision.", }; -const tools = knowledgeAgentOperations.map((operation) => - ToolSchema.parse({ - name: knowledgeAgentToolNames[operation], - description: descriptions[operation], - inputSchema: z.toJSONSchema(knowledgeAgentInputSchemas[operation], { - unrepresentable: "any", +function toolsFor(reportWorkflow = false) { + const schemas = reportWorkflow + ? knowledgeAgentReportInputSchemas + : knowledgeAgentInputSchemas; + return knowledgeAgentOperations.map((operation) => + ToolSchema.parse({ + name: knowledgeAgentToolNames[operation], + description: + reportWorkflow && operation === "getValidationRequirements" + ? "Read requirements; with articleId, discover its report epoch and optionally poll your own report status." + : reportWorkflow && operation === "submitEvidence" + ? "Queue an exact-revision test report for human review, or submit evidence with its confirmed opaque receipt. Pending review is not verified evidence." + : descriptions[operation], + inputSchema: { + ...z.toJSONSchema(schemas[operation], { unrepresentable: "any" }), + // MCP requires an object root even when strict object alternatives are + // advertised through anyOf. Each branch retains its closed field set. + type: "object", + }, + annotations: { + readOnlyHint: + operation === "getDraft" || operation === "getValidationRequirements", + destructiveHint: false, + openWorldHint: false, + }, }), - annotations: { - readOnlyHint: - operation === "getDraft" || operation === "getValidationRequirements", - destructiveHint: false, - openWorldHint: false, - }, - }), -); + ); +} +const tools = toolsFor(); function operationForTool(name: string): KnowledgeAgentOperation | null { return ( @@ -274,6 +289,8 @@ export function createKnowledgeAgentMcp( "mcp", ); const dispatcher = options.dispatcher; + const configuredTools = + dispatcher.reportWorkflow === true ? toolsFor(true) : tools; // The logical response is identical to HTTP. JSON text inside JSON-RPC can // double its escaping; bounded framing must not reject a complete valid guide. const wireBudget = dispatcher.limits.maxResponseBytes * 2 + 4_096; @@ -332,14 +349,16 @@ export function createKnowledgeAgentMcp( maxRequestBodySize: dispatcher.limits.maxRequestBytes, }); const server = new Server( - { name: "@pegma/knowledge-base-mcp", version: "0.1.2" }, + { name: "@pegma/knowledge-base-mcp", version: "0.1.3" }, { capabilities: { tools: {} }, // Workers prohibit the runtime code generation used by SDK-default AJV. jsonSchemaValidator: new CfWorkerJsonSchemaValidator(), }, ); - server.setRequestHandler(ListToolsRequestSchema, () => ({ tools })); + server.setRequestHandler(ListToolsRequestSchema, () => ({ + tools: configuredTools, + })); server.setRequestHandler(CallToolRequestSchema, async (call) => { const operation = operationForTool(call.params.name); if (operation === null) diff --git a/packages/mcp/src/schemas.ts b/packages/mcp/src/schemas.ts index 43d6ce8..851bf03 100644 --- a/packages/mcp/src/schemas.ts +++ b/packages/mcp/src/schemas.ts @@ -158,6 +158,69 @@ export const knowledgeAgentEnvelopeSchema = z.discriminatedUnion("operation", [ .strict(), ]); +const reportLookup = z + .object({ ledgerEpoch: positiveInteger, reportId: identifier }) + .strict(); +const reportRequirementsInput = z + .object({ + collectionId: identifier, + kind, + articleId: identifier, + reportLookup: reportLookup.optional(), + }) + .strict(); +const reportSubmissionInput = z + .object({ + ...command, + articleId: identifier, + evidence: evidenceSubmission, + ledgerEpoch: positiveInteger, + report: z + .object({ + summary: boundedText(1000).regex(/^[^\u007f-\u009f]*$/u), + details: z + .string() + .min(1) + .max(16_000) + .regex( + /^[^\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\ud800-\udfff]*$/u, + ), + }) + .strict(), + }) + .strict(); + +/** Enabled only by the host's explicit report-service composition. The legacy + * schemas above remain exact when that optional service is omitted. */ +export const knowledgeAgentReportInputSchemas = Object.freeze({ + ...knowledgeAgentInputSchemas, + getValidationRequirements: z.union([ + knowledgeAgentInputSchemas.getValidationRequirements, + reportRequirementsInput, + ]), + submitEvidence: z.union([ + knowledgeAgentInputSchemas.submitEvidence, + reportSubmissionInput, + ]), +}); +export const knowledgeAgentReportEnvelopeSchema = z.union([ + knowledgeAgentEnvelopeSchema, + z + .object({ + apiVersion: z.literal("1"), + operation: z.literal("getValidationRequirements"), + input: reportRequirementsInput, + }) + .strict(), + z + .object({ + apiVersion: z.literal("1"), + operation: z.literal("submitEvidence"), + input: reportSubmissionInput, + }) + .strict(), +]); + // Output schemas deliberately construct purpose-specific DTOs. Extra private // fields from an application wrapper never become transport response fields. const articleState = z.enum(["draft", "in-review", "published", "retired"]); @@ -225,6 +288,49 @@ export const knowledgeAgentResultSchemas = Object.freeze({ submitEvidence: acknowledgement, }); +// A report acknowledgement fits the existing prepaid 2048-byte minimum: one +// 200-character identifier, a <=512-byte JSON-encoded receipt, safe integers and fixed +// framing. Current report receipts are compact epoch/generation/opaque-ID data. +const reportAcknowledgement = z + .object({ + ledgerEpoch: positiveInteger, + reportId: identifier, + receipt: boundedText(512).refine( + (value) => + new TextEncoder().encode(JSON.stringify(value)).byteLength <= 512, + ), + reportGeneration: positiveInteger, + }) + .strip(); +const reportRequirementsResult = + knowledgeAgentResultSchemas.getValidationRequirements + .extend({ + reportLedger: z + .object({ + ledgerEpoch: positiveInteger, + status: z.enum(["active", "resetting"]), + }) + .strip(), + reportStatus: reportAcknowledgement + .extend({ status: z.enum(["pending", "confirmed", "rejected"]) }) + .strip() + .optional(), + }) + .strip(); +export const knowledgeAgentReportResultSchemas = Object.freeze({ + ...knowledgeAgentResultSchemas, + getValidationRequirements: z.union([ + reportRequirementsResult, + knowledgeAgentResultSchemas.getValidationRequirements, + ]), + submitEvidence: z.union([ + reportAcknowledgement + .extend({ kind: z.literal("pending-human-review") }) + .strip(), + acknowledgement, + ]), +}); + export function resolveKnowledgeAgentLimits( requested: Partial = {}, ): KnowledgeAgentLimits { diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts index c8b51e7..5798d0e 100644 --- a/packages/mcp/src/types.ts +++ b/packages/mcp/src/types.ts @@ -6,6 +6,11 @@ import type { CreateDraftInput, DraftArticleDto, KnowledgeBaseApplication, + KnowledgeEvidenceReports, + KnowledgeReportAcknowledgement, + KnowledgeReportLedgerState, + KnowledgeReportStatus, + KnowledgeTestReport, SubmitEvidenceInput, UpdateDraftInput, ValidationRequirementsDto, @@ -64,21 +69,81 @@ export interface KnowledgeAgentResultMap { readonly submitEvidence: CommandResult; } -export type KnowledgeAgentEnvelope = { - [Operation in KnowledgeAgentOperation]: { - readonly apiVersion: "1"; - readonly operation: Operation; - readonly input: KnowledgeAgentInputMap[Operation]; +/** Optional author-only human-review workflow; it adds no operation or scope. */ +export interface KnowledgeAgentReportRequirementsInput extends ValidationRequirementsReadInput { + readonly articleId: string; + readonly reportLookup?: { + readonly ledgerEpoch: number; + readonly reportId: string; }; -}[KnowledgeAgentOperation]; +} + +export interface KnowledgeAgentReportSubmissionInput extends Omit< + SubmitEvidenceInput, + "receipt" +> { + readonly ledgerEpoch: number; + readonly report: KnowledgeTestReport; +} -export type KnowledgeAgentSuccess = { - [Operation in KnowledgeAgentOperation]: { - readonly apiVersion: "1"; - readonly operation: Operation; - readonly result: KnowledgeAgentResultMap[Operation]; +export interface KnowledgeAgentReportRequirementsResult extends ValidationRequirementsDto { + readonly reportLedger: Pick< + KnowledgeReportLedgerState, + "ledgerEpoch" | "status" + >; + readonly reportStatus?: KnowledgeReportAcknowledgement & { + readonly status: KnowledgeReportStatus; }; -}[KnowledgeAgentOperation]; +} + +/** This acknowledges only a private report, never an article/evidence update. */ +export interface KnowledgeAgentPendingReport extends KnowledgeReportAcknowledgement { + readonly kind: "pending-human-review"; +} + +export type KnowledgeAgentReportEnvelope = + | { + readonly apiVersion: "1"; + readonly operation: "getValidationRequirements"; + readonly input: KnowledgeAgentReportRequirementsInput; + } + | { + readonly apiVersion: "1"; + readonly operation: "submitEvidence"; + readonly input: KnowledgeAgentReportSubmissionInput; + }; + +export type KnowledgeAgentReportSuccess = + | { + readonly apiVersion: "1"; + readonly operation: "getValidationRequirements"; + readonly result: KnowledgeAgentReportRequirementsResult; + } + | { + readonly apiVersion: "1"; + readonly operation: "submitEvidence"; + readonly result: KnowledgeAgentPendingReport; + }; + +export type KnowledgeAgentEnvelope = + | { + [Operation in KnowledgeAgentOperation]: { + readonly apiVersion: "1"; + readonly operation: Operation; + readonly input: KnowledgeAgentInputMap[Operation]; + }; + }[KnowledgeAgentOperation] + | KnowledgeAgentReportEnvelope; + +export type KnowledgeAgentSuccess = + | { + [Operation in KnowledgeAgentOperation]: { + readonly apiVersion: "1"; + readonly operation: Operation; + readonly result: KnowledgeAgentResultMap[Operation]; + }; + }[KnowledgeAgentOperation] + | KnowledgeAgentReportSuccess; export type KnowledgeAgentErrorCode = | "invalid_request" @@ -145,6 +210,14 @@ export interface KnowledgeAgentDispatcherOptions { readonly application: KnowledgeBaseApplication; /** Exact protected-resource identifier configured by this host. */ readonly resource: string; + /** Trusted optional human-report service. Always receives the restricted + * delegated context, never a substituted current human/Admin context. Hosts + * revalidate the same authenticated request/grant before and after awaited + * report/ledger/status calls, just as for the five application operations. */ + readonly reports?: Pick< + KnowledgeEvidenceReports, + "report" | "ledger" | "status" + >; /** * Positive safe integers may only reduce the fixed component ceilings. * maxResponseBytes must reserve at least 2,048 bytes for acknowledgements. @@ -154,6 +227,8 @@ export interface KnowledgeAgentDispatcherOptions { export interface KnowledgeAgentDispatcher { readonly limits: KnowledgeAgentLimits; + /** Trusted configuration metadata for optional MCP schema advertisement. */ + readonly reportWorkflow?: true; dispatch( identity: KnowledgeAgentIdentity, envelope: unknown, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5b894f9..3194d1f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,19 +24,19 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/knowledge-base-application': - specifier: 0.1.2 + specifier: 0.1.3 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 + specifier: 0.1.3 version: link:packages/contracts '@pegma/knowledge-base-core': - specifier: 0.1.2 + specifier: 0.1.3 version: link:packages/core '@pegma/knowledge-base-mcp': - specifier: 0.1.2 + specifier: 0.1.3 version: link:packages/mcp '@pegma/spine': specifier: 0.1.2 @@ -81,10 +81,10 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/knowledge-base-contracts': - specifier: 0.1.2 + specifier: 0.1.3 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.2 + specifier: 0.1.3 version: link:../core '@pegma/spine': specifier: 0.1.2 @@ -102,7 +102,7 @@ importers: packages/core: dependencies: '@pegma/knowledge-base-contracts': - specifier: 0.1.2 + specifier: 0.1.3 version: link:../contracts packages/mcp: @@ -117,13 +117,13 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/knowledge-base-application': - specifier: 0.1.2 + specifier: 0.1.3 version: link:../application '@pegma/knowledge-base-contracts': - specifier: 0.1.2 + specifier: 0.1.3 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.2 + specifier: 0.1.3 version: link:../core zod: specifier: 4.6.7 diff --git a/scripts/agent-protocol-fixture.mjs b/scripts/agent-protocol-fixture.mjs index 7c99494..1fe6114 100644 --- a/scripts/agent-protocol-fixture.mjs +++ b/scripts/agent-protocol-fixture.mjs @@ -19,7 +19,10 @@ import { createProtectedResourceAuthenticator, } from "@pegma/agent-access"; import { hasPermission, resolveAccess } from "@pegma/authorization-core"; -import { createKnowledgeBaseApplication } from "@pegma/knowledge-base-application"; +import { + createKnowledgeBaseApplication, + createKnowledgeEvidenceReports, +} from "@pegma/knowledge-base-application"; import { articleKinds, knowledgePermissions, @@ -39,6 +42,7 @@ const PRINCIPAL = "fictional/staff/admin"; const RUNNER = "fictional/runner/loopback"; const ATTESTER = "fictional/verifier/registry"; const LINK = "agent.access.link"; +const CONFIRM = "fictional.knowledge.evidence.confirm"; const COLLECTION = "fictional/collection/workshop"; const ARTICLE = "fictional/article/export"; const BUILD = "fictional-loopback-build-42"; @@ -98,7 +102,7 @@ async function formPost(url, values, headers = {}) { }); } -async function createHost() { +async function createHost({ reportsEnabled = false } = {}) { const store = createMemoryStore(); let milliseconds = Date.now(); let administrator = true; @@ -109,11 +113,31 @@ async function createHost() { { version: "fictional-kb-protocol-1", roles: { - Admin: [LINK, ...Object.values(knowledgePermissions)], + Admin: [ + LINK, + ...Object.values(knowledgePermissions), + ...(reportsEnabled ? [CONFIRM] : []), + ], Viewer: [], }, }, ); + const reviewerAccess = () => + resolveAccess( + { principalId: ATTESTER, roles: ["EvidenceReviewer"] }, + { + version: "fictional-kb-protocol-1", + roles: { + EvidenceReviewer: [ + CONFIRM, + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceRead, + knowledgePermissions.evidenceSubmit, + ], + }, + }, + ); const policy = { id: "fictional/validation/workshop", version: 1, @@ -147,10 +171,49 @@ async function createHost() { callbacks: 0, }; stage = 11; - const application = createKnowledgeBaseApplication({ + let application; + const reports = reportsEnabled + ? createKnowledgeEvidenceReports({ + store, + clock, + collectionName: "fictional-protocol.evidence-reports.v1", + confirmationPermission: CONFIRM, + async resolvePrincipal(principalId) { + return principalId === PRINCIPAL + ? currentAccess() + : principalId === ATTESTER + ? reviewerAccess() + : null; + }, + async readContext(access, articleId) { + const draft = await application.getDraft(access, { articleId }); + const requirements = await application.getValidationRequirements( + access, + { + collectionId: draft.revision.collectionId, + kind: draft.revision.kind, + }, + ); + const accepted = hasPermission( + access, + knowledgePermissions.evidenceRead, + ) + ? await application.getEvidence(access, { articleId }) + : undefined; + const latest = await application.getDraft(access, { articleId }); + assert.equal(latest.generation, draft.generation); + return { + draft: latest, + requirements, + ...(accepted === undefined ? {} : { evidence: accepted }), + }; + }, + }) + : undefined; + application = createKnowledgeBaseApplication({ store, clock, - evidenceVerifier: { + evidenceVerifier: reports?.verifier ?? { async verify(proof) { const execution = executions.get(proof.receipt); if ( @@ -371,6 +434,7 @@ async function createHost() { const dispatcher = createKnowledgeAgentDispatcher({ application: trackedApplication, resource, + ...(reports === undefined ? {} : { reports }), }); const common = { resource, @@ -501,6 +565,30 @@ async function createHost() { demote: () => { administrator = false; }, + async acceptedEvidence() { + return application.getEvidence(currentAccess(), { articleId: ARTICLE }); + }, + async confirmReport(queued) { + assert.ok(reports); + const access = reviewerAccess(); + const view = await reports.read(access, { + articleId: ARTICLE, + ledgerEpoch: queued.ledgerEpoch, + reportId: queued.reportId, + }); + return reports.decide( + access, + { + commandId: "fictional/report/confirm/" + queued.reportId, + articleId: ARTICLE, + ledgerEpoch: queued.ledgerEpoch, + reportId: queued.reportId, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }, + "confirmed", + ); + }, async wrongResourceCredential() { const issued = await otherService.beginDeviceAuthorization({ clientId: CLIENT_ID, @@ -584,7 +672,7 @@ async function createHost() { } } -function createProvider(host) { +function createProvider(host, requestedScopes = scopes) { let savedTokens; let verifier; let authorizationUrl; @@ -598,7 +686,7 @@ function createProvider(host) { grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none", - scope: scopes.join(" "), + scope: requestedScopes.join(" "), }, clientInformation: () => ({ client_id: CLIENT_ID, @@ -656,7 +744,12 @@ function createProvider(host) { }; } -async function approve(host, authorizationUrl, checkProtections = false) { +async function approve( + host, + authorizationUrl, + checkProtections = false, + requestedScopes = scopes, +) { assert.equal(authorizationUrl.origin, host.origin); assert.equal(authorizationUrl.pathname, "/authorize"); assert.equal( @@ -686,7 +779,7 @@ async function approve(host, authorizationUrl, checkProtections = false) { assert.equal(view.resource, host.resource); assert.deepEqual( view.requestedScopes.map(({ name }) => name).sort(), - [...scopes].sort(), + [...requestedScopes].sort(), ); const values = { request_id: consent.searchParams.get("request_id"), @@ -777,8 +870,13 @@ async function rejectedCredential(host, token, replay) { assert.equal(host.counts.applicationCalls, before); } -async function authorization(host, owned, checkProtections = false) { - const provider = createProvider(host); +async function authorization( + host, + owned, + checkProtections = false, + requestedScopes = scopes, +) { + const provider = createProvider(host, requestedScopes); const initial = new StreamableHTTPClientTransport(new URL(host.resource), { authProvider: provider.provider, fetch: request, @@ -801,6 +899,7 @@ async function authorization(host, owned, checkProtections = false) { host, provider.authorizationUrl(), checkProtections, + requestedScopes, ); const code = provider.callbackCode(callback); await initial.finishAuth(code); @@ -952,6 +1051,15 @@ async function runProof() { assert.deepEqual(await httpRequirements.json(), requirements); assert.equal("trustedAttesterIds" in requirements.result, false); assert.equal("trustedRunnerIds" in requirements.result.checks[0], false); + const omittedReports = await mcpCall( + session.client, + "getValidationRequirements", + { + ...requirementsInput, + articleId: ARTICLE, + }, + ); + assert.equal(omittedReports.error.code, "invalid_request"); const execution = host.executeFixtureCheck(current); const submission = { ...command("evidence-submit", current.generation), @@ -1087,6 +1195,7 @@ async function runProof() { httpMcpParity: true, replayAcknowledgements: true, privateEvidenceExcluded: true, + optionalReportsOmitted: true, wrongResourceRejected: true, wrongPkceRejected: true, expiredRejected: true, @@ -1114,8 +1223,247 @@ async function runProof() { } } +function privateReportFree(value) { + const serialized = JSON.stringify(value); + for (const marker of [ + "SYNTHETIC_PRIVATE_REPORT", + "SYNTHETIC_PRIVATE_EVIDENCE", + ]) + assert.equal(serialized.includes(marker), false); + for (const key of [ + "report", + "evidence", + "reportHash", + "submissionHash", + "governanceHash", + "confirmation", + "reviewerId", + "submittedBy", + "trustedAttesterIds", + "trustedRunnerIds", + ]) + assert.equal(serialized.includes(JSON.stringify(key) + ":"), false); +} + +async function runReportProof() { + stage = 90; + const host = await createHost({ reportsEnabled: true }); + const owned = []; + try { + stage = 91; + const session = await authorization(host, owned); + const tools = await session.client.listTools(); + assert.deepEqual( + tools.tools.map(({ name }) => name).sort(), + Object.values(knowledgeAgentToolNames).sort(), + ); + assert.equal(tools.tools.length, 5); + assert.equal(host.configuration.scopes.length, 3); + const created = await mcpCall(session.client, "createDraft", { + ...command("report-draft-create", 0), + articleId: ARTICLE, + collectionId: COLLECTION, + draft: guide, + }); + const updated = await mcpCall(session.client, "updateDraft", { + ...command("report-draft-update", created.result.value.generation), + articleId: ARTICLE, + collectionId: COLLECTION, + draft: { + ...guide, + summary: "Save the exact fictional workspace as a CSV spreadsheet.", + }, + }); + assert.equal(updated.result.value.articleRevision, 2); + const current = ( + await mcpCall(session.client, "getDraft", { articleId: ARTICLE }) + ).result; + const requirementsInput = { + collectionId: COLLECTION, + kind: "walkthrough", + articleId: ARTICLE, + }; + stage = 92; + const requirements = await mcpCall( + session.client, + "getValidationRequirements", + requirementsInput, + ); + assert.deepEqual(requirements.result.reportLedger, { + ledgerEpoch: 1, + status: "active", + }); + assert.equal("reportStatus" in requirements.result, false); + privateReportFree(requirements); + const execution = host.executeFixtureCheck(current); + const reportInput = { + ...command("queue-human-report", current.generation), + articleId: ARTICLE, + evidence: execution.evidence, + ledgerEpoch: requirements.result.reportLedger.ledgerEpoch, + report: { + summary: "SYNTHETIC_PRIVATE_REPORT: locally checked fictional CSV.", + details: + "SYNTHETIC_PRIVATE_REPORT: the independent fictional CSV check completed exactly.", + }, + }; + const queued = await mcpCall(session.client, "submitEvidence", reportInput); + assert.equal(queued.result.kind, "pending-human-review"); + assert.deepEqual(Object.keys(queued.result).sort(), [ + "kind", + "ledgerEpoch", + "receipt", + "reportGeneration", + "reportId", + ]); + assert.equal(queued.result.reportGeneration, 1); + privateReportFree(queued); + assert.equal((await host.acceptedEvidence()).evidence.length, 0); + const lookup = { + ...requirementsInput, + reportLookup: { + ledgerEpoch: queued.result.ledgerEpoch, + reportId: queued.result.reportId, + }, + }; + const pending = await mcpCall( + session.client, + "getValidationRequirements", + lookup, + ); + assert.deepEqual(pending.result.reportLedger, { + ledgerEpoch: 1, + status: "active", + }); + assert.deepEqual(Object.keys(pending.result.reportStatus).sort(), [ + "ledgerEpoch", + "receipt", + "reportGeneration", + "reportId", + "status", + ]); + assert.equal(pending.result.reportStatus.status, "pending"); + assert.equal(pending.result.reportStatus.receipt, queued.result.receipt); + privateReportFree(pending); + const commitInput = { + ...command("reported-evidence-commit", current.generation), + articleId: ARTICLE, + evidence: execution.evidence, + receipt: queued.result.receipt, + }; + const premature = await mcpCall(session.client, "submitEvidence", { + ...commitInput, + ...command("unconfirmed-report-receipt", current.generation), + }); + assert.equal(premature.error.code, "prerequisite"); + assert.equal((await host.acceptedEvidence()).evidence.length, 0); + + stage = 93; + const readOnly = await authorization(host, owned, false, [ + knowledgeAgentScopes.draftRead, + ]); + const forbidden = await mcpCall( + readOnly.client, + "getValidationRequirements", + lookup, + ); + assert.equal(forbidden.error.code, "forbidden"); + privateReportFree(forbidden); + const privateLookup = await mcpCall( + session.client, + "getValidationRequirements", + { + ...lookup, + reportLookup: { ...lookup.reportLookup, reviewerId: ATTESTER }, + }, + ); + assert.equal(privateLookup.error.code, "invalid_request"); + privateReportFree(privateLookup); + + stage = 94; + const confirmation = await host.confirmReport(queued.result); + assert.equal(confirmation.receipt, queued.result.receipt); + assert.equal((await host.acceptedEvidence()).evidence.length, 0); + const confirmed = await mcpCall( + session.client, + "getValidationRequirements", + lookup, + ); + assert.equal(confirmed.result.reportStatus.status, "confirmed"); + assert.equal(confirmed.result.reportStatus.receipt, queued.result.receipt); + assert.equal(confirmed.result.reportStatus.reportGeneration, 2); + privateReportFree(confirmed); + const tampered = await mcpCall(session.client, "submitEvidence", { + ...commitInput, + ...command("tampered-reported-evidence", current.generation), + evidence: { + ...execution.evidence, + artifacts: [{ id: "forged", hash: "f".repeat(64) }], + }, + }); + assert.equal(tampered.error.code, "prerequisite"); + assert.equal((await host.acceptedEvidence()).evidence.length, 0); + + stage = 95; + const committed = await mcpCall( + session.client, + "submitEvidence", + commitInput, + ); + assert.equal(committed.result.replayed, false); + assert.equal(committed.result.value.generation, current.generation + 1); + const accepted = await host.acceptedEvidence(); + assert.equal(accepted.evidence.length, 1); + assert.equal(accepted.evidence[0].attestation.id, queued.result.receipt); + assert.equal(accepted.evidence[0].attestation.verifiedBy, ATTESTER); + const replay = await mcpCall(session.client, "submitEvidence", commitInput); + assert.equal(replay.result.replayed, true); + assert.deepEqual(replay.result.value, committed.result.value); + assert.equal((await host.acceptedEvidence()).evidence.length, 1); + const safeDraft = await mcpCall(session.client, "getDraft", { + articleId: ARTICLE, + }); + assert.equal(safeDraft.result.hasPublication, false); + privateReportFree(safeDraft); + return { + passed: true, + tools: tools.tools.length, + scopes: host.configuration.scopes.length, + reportQueued: true, + bodyFreePolling: true, + humanConfirmed: true, + originalReceiptCommitted: true, + evidenceAccepted: true, + acceptedEvidenceCount: 1, + acknowledgementWasNotAcceptance: true, + publicationProven: false, + readOnlyReportDenied: true, + privateLookupRejected: true, + unconfirmedReceiptRejected: true, + tamperedEvidenceRejected: true, + exactReplay: true, + }; + } finally { + let cleanupFailed = false; + try { + for (const resource of owned.reverse()) { + try { + await resource.close(); + } catch { + cleanupFailed = true; + } + } + } finally { + await host.close(); + } + assert.equal(cleanupFailed, false, "Report client cleanup failed."); + } +} + try { - console.log(JSON.stringify(await runProof())); + const legacy = await runProof(); + const reportWorkflow = await runReportProof(); + console.log(JSON.stringify({ ...legacy, reportWorkflow })); } catch { console.error(JSON.stringify({ passed: false, stage })); process.exitCode = 1; diff --git a/scripts/agent-protocol-proof.mjs b/scripts/agent-protocol-proof.mjs index 73977b3..a8cd165 100644 --- a/scripts/agent-protocol-proof.mjs +++ b/scripts/agent-protocol-proof.mjs @@ -261,6 +261,7 @@ async function proof() { JSON.parse(run(process.execPath, ["proof.mjs"], consumer, env)), ); assert.equal(receipt.passed, true); + assert.equal(receipt.reportWorkflow?.passed, true); return { ...receipt, packedPackages: dependencies.length, diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index c160d0b..fd571ab 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -364,8 +364,9 @@ async function prepareArtifacts(mode, options = {}) { 'import assert from "node:assert/strict";', 'import { readFile } from "node:fs/promises";', 'import { createMemoryStore } from "@pegma/storage-core";', - 'import { createKnowledgeBaseApplication } from "@pegma/knowledge-base-application";', - 'import { createKnowledgeAgentDispatcher, createKnowledgeAgentMcp } from "@pegma/knowledge-base-mcp";', + 'import { createKnowledgeBaseApplication, createKnowledgeEvidenceReports } from "@pegma/knowledge-base-application";', + 'import { knowledgePermissions } from "@pegma/knowledge-base-contracts";', + 'import { createKnowledgeAgentDispatcher, createKnowledgeAgentMcp, knowledgeAgentOperations, knowledgeAgentScopes, knowledgeAgentToolNames } from "@pegma/knowledge-base-mcp";', ...packages.map( ({ name, runtimeExport, runtimeExportType }, index) => `const package${index} = await import(${JSON.stringify(name)});\nassert.equal(typeof package${index}[${JSON.stringify(runtimeExport)}], ${JSON.stringify(runtimeExportType)});`, @@ -376,10 +377,25 @@ const mcpManifest = JSON.parse(await readFile( "utf8", )); const resource = "https://knowledge-artifact.example/mcp"; +const store = createMemoryStore(); +const clock = { now: () => "2026-11-07T12:00:00.000Z" }; const application = createKnowledgeBaseApplication({ - store: createMemoryStore(), - clock: { now: () => "2026-11-07T12:00:00.000Z" }, + store, + clock, }); +assert.equal(typeof createKnowledgeEvidenceReports, "function"); +const reports = createKnowledgeEvidenceReports({ + store, + clock, + collectionName: "artifact.knowledge-reports.v1", + confirmationPermission: "artifact.knowledge.report.confirm", + resolvePrincipal: async () => null, + async readContext() { + throw new Error("Artifact metadata smoke does not read report content"); + }, +}); +assert.equal(typeof reports.report, "function"); +assert.equal(typeof reports.verifier.verify, "function"); const dispatcher = createKnowledgeAgentDispatcher({ application, resource }); const identity = { clientId: "synthetic-artifact-client", @@ -393,8 +409,7 @@ const identity = { permissions: [], }, }; -const mcp = createKnowledgeAgentMcp({ - dispatcher, +const transportOptions = { resource, mcpUrl: resource, protectedResourceMetadataUrl: @@ -405,7 +420,8 @@ const mcp = createKnowledgeAgentMcp({ assert.equal(request.headers.get("Authorization"), "Bearer synthetic-artifact-smoke"); return identity; }, -}); +}; +const mcp = createKnowledgeAgentMcp({ ...transportOptions, dispatcher }); const initialized = await mcp.handle(new Request(resource, { method: "POST", headers: { @@ -432,6 +448,88 @@ assert.equal(initializedBody.id, 1); assert.equal(initializedBody.error, undefined); assert.equal(initializedBody.result.serverInfo.name, mcpManifest.name); assert.equal(initializedBody.result.serverInfo.version, mcpManifest.version); +async function listTools(adapter, id) { + const response = await adapter.handle(new Request(resource, { + method: "POST", + headers: { + Authorization: "Bearer synthetic-artifact-smoke", + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + }, + body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/list" }), + })); + assert.ok(response instanceof Response); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.id, id); + assert.equal(body.error, undefined); + assert.ok(Array.isArray(body.result.tools)); + return body.result.tools; +} +assert.deepEqual(knowledgeAgentOperations, [ + "getDraft", "createDraft", "updateDraft", "getValidationRequirements", "submitEvidence", +]); +assert.deepEqual(Object.values(knowledgeAgentScopes).sort(), [ + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, +].sort()); +const legacyTools = await listTools(mcp, 2); +const expectedNames = [ + "knowledge_v1_get_draft", "knowledge_v1_create_draft", "knowledge_v1_update_draft", + "knowledge_v1_get_validation_requirements", "knowledge_v1_submit_evidence", +].sort(); +assert.deepEqual(Object.values(knowledgeAgentToolNames).sort(), expectedNames); +assert.deepEqual(legacyTools.map((tool) => tool.name).sort(), expectedNames); +const inputSchema = (tools, operation) => { + const tool = tools.find((entry) => entry.name === knowledgeAgentToolNames[operation]); + assert.ok(tool); + return tool.inputSchema; +}; +const legacySubmission = inputSchema(legacyTools, "submitEvidence"); +assert.ok(legacySubmission.required.includes("receipt")); +assert.equal(legacySubmission.properties.report, undefined); +assert.equal(legacySubmission.properties.ledgerEpoch, undefined); +assert.equal(inputSchema(legacyTools, "getValidationRequirements").properties.reportLookup, undefined); +const reportDispatcher = createKnowledgeAgentDispatcher({ application, resource, reports }); +assert.equal(dispatcher.reportWorkflow, undefined); +assert.equal(reportDispatcher.reportWorkflow, true); +const reportTools = await listTools(createKnowledgeAgentMcp({ + ...transportOptions, dispatcher: reportDispatcher, +}), 3); +assert.deepEqual(reportTools.map((tool) => tool.name).sort(), expectedNames); +for (const operation of ["getDraft", "createDraft", "updateDraft"]) + assert.deepEqual(inputSchema(reportTools, operation), inputSchema(legacyTools, operation)); +const reportSubmissionBranches = inputSchema(reportTools, "submitEvidence").anyOf; +assert.ok(Array.isArray(reportSubmissionBranches)); +const retainedLegacySubmission = reportSubmissionBranches.find((schema) => schema.required.includes("receipt")); +assert.ok(retainedLegacySubmission); +assert.deepEqual(retainedLegacySubmission.properties, legacySubmission.properties); +assert.deepEqual(retainedLegacySubmission.required, legacySubmission.required); +assert.equal(retainedLegacySubmission.additionalProperties, false); +const reportSubmission = reportSubmissionBranches.find((schema) => schema.required.includes("report")); +assert.ok(reportSubmission); +assert.ok(reportSubmission.required.includes("ledgerEpoch")); +assert.equal(reportSubmission.properties.receipt, undefined); +assert.equal(reportSubmission.additionalProperties, false); +assert.equal(reportSubmission.properties.report.additionalProperties, false); +assert.deepEqual(reportSubmission.properties.report.required, ["summary", "details"]); +assert.equal(reportSubmission.properties.report.properties.summary.maxLength, 1000); +assert.equal(reportSubmission.properties.report.properties.details.maxLength, 16000); +const requirementsBranches = inputSchema(reportTools, "getValidationRequirements").anyOf; +assert.ok(Array.isArray(requirementsBranches)); +const retainedLegacyRequirements = requirementsBranches.find((schema) => !schema.required.includes("articleId")); +assert.ok(retainedLegacyRequirements); +assert.deepEqual(retainedLegacyRequirements.properties, + inputSchema(legacyTools, "getValidationRequirements").properties); +assert.deepEqual(retainedLegacyRequirements.required, + inputSchema(legacyTools, "getValidationRequirements").required); +assert.equal(retainedLegacyRequirements.additionalProperties, false); +const reportRequirements = requirementsBranches.find((schema) => schema.required.includes("articleId")); +assert.ok(reportRequirements); +assert.equal(reportRequirements.additionalProperties, false); +assert.equal(reportRequirements.properties.reportLookup.additionalProperties, false); +assert.deepEqual(reportRequirements.properties.reportLookup.required, ["ledgerEpoch", "reportId"]); `, ].join("\n"), ], diff --git a/test/evidence-reports-fixtures.ts b/test/evidence-reports-fixtures.ts new file mode 100644 index 0000000..3bace27 --- /dev/null +++ b/test/evidence-reports-fixtures.ts @@ -0,0 +1,491 @@ +import { hasPermission, type AccessContext } from "@pegma/authorization-core"; +import { + createKnowledgeBaseApplication, + createKnowledgeEvidenceReports, + type DecideKnowledgeReportInput, + type EvidenceVerificationRequest, + type GovernanceConfiguration, + type KnowledgeBaseApplication, + type KnowledgeEvidenceContext, + type KnowledgeEvidenceReports, + type KnowledgeEvidenceReportsOptions, + type KnowledgeReportAcknowledgement, + type KnowledgeReportKey, + type KnowledgeReportStatus, + type SubmitKnowledgeReportInput, +} from "@pegma/knowledge-base-application"; +import { + knowledgePermissions, + type PrincipalId, +} from "@pegma/knowledge-base-contracts"; +import type { EvidenceSubmission } from "@pegma/knowledge-base-core"; +import { + createMemoryStore, + defineCollection, + type CollectionDefinition, + type EntityKey, + type ScanRecord, + type Store, + type StoredRecord, +} from "@pegma/storage-core"; +import { vi } from "vitest"; +import { + access, + admin, + applicationFixture, + at, + author, + customer, + draft, + evidence, +} from "./application-fixtures.js"; +import { barrier, traceStore } from "./trace-store.js"; + +export const reportNamespace = "workshop.knowledge-reports.v1"; +export const confirmationPermission = "workshop.knowledge.report.confirm"; +const humanPermissions = [ + ...Object.values(knowledgePermissions), + confirmationPermission, + "workshop.customer", +]; + +/** Synthetic effective contexts; no identity, role, or credential implementation. */ +export const reportAgent = access(author.principalId, [ + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, +]); +export const reportOwner = access(author.principalId, humanPermissions); +export const reportReviewer = access("staff/verifier", humanPermissions); +export const otherReportAgent = access("runner/other", reportAgent.permissions); + +export interface ReportLedgerRow { + readonly articleId: string; + readonly id: string; + readonly payload: string; +} + +/** Read flat backend data without interpreting the component-owned codec. */ +function rawReportRowsDefinition( + name = reportNamespace, + physicalKey?: EntityKey, +) { + return defineCollection({ + name, + key: () => { + if (physicalKey === undefined) + throw new Error("Test fault writes require an observed physical key"); + return physicalKey; + }, + codec: { + encode: (value) => ({ ...value }), + decode: (value) => ({ ...value }), + }, + }); +} + +function logicalReportRow(value: unknown): ReportLedgerRow { + if ( + typeof value !== "object" || + value === null || + !("articleId" in value) || + !("id" in value) || + !("payload" in value) || + typeof value.articleId !== "string" || + typeof value.id !== "string" || + typeof value.payload !== "string" + ) + throw new TypeError("Factory codec returned an invalid ledger envelope"); + return { articleId: value.articleId, id: value.id, payload: value.payload }; +} + +export function reportBarrier() { + const gate = barrier(); + return { + wait: gate.wait, + release: gate.release, + async reached(pending: Promise) { + let timeout: ReturnType | undefined; + try { + await Promise.race([ + gate.reached, + pending.then(() => { + throw new Error("Operation ended before test barrier"); + }), + new Promise((_, reject) => { + timeout = setTimeout( + () => reject(new Error("Test barrier timed out")), + 10_000, + ); + }), + ]); + } finally { + if (timeout !== undefined) clearTimeout(timeout); + } + }, + }; +} + +export async function evidenceReportsFixture( + backing: Store, + options: { + readonly collectionName?: string; + readonly articleId?: string; + readonly storageLayout?: KnowledgeEvidenceReportsOptions["storageLayout"]; + readonly commandPrefix?: string; + } = {}, +) { + const namespace = options.collectionName ?? reportNamespace; + const articleId = options.articleId ?? "article/export"; + const collectionId = "collection/workshop"; + const observed = traceStore(backing); + let reportDefinition: CollectionDefinition | undefined; + const reportStore: Store = { + collection(definition: CollectionDefinition) { + // Retain the original factory's codec even when a later test probes a + // different layout in this same namespace. All storage still delegates. + if (definition.name === namespace && reportDefinition === undefined) + reportDefinition = definition; + return observed.store.collection(definition); + }, + }; + const base = applicationFixture(observed.store, { + missingEvidenceVerifier: true, + }); + let offset = 0; + const clock = { now: () => at(offset) }; + const principals = new Map([ + [reportOwner.principalId, structuredClone(reportOwner)], + [reportReviewer.principalId, structuredClone(reportReviewer)], + [otherReportAgent.principalId, structuredClone(otherReportAgent)], + ]); + const hooks: { + afterContext?: (access: AccessContext, id: string) => Promise; + beforeResolve?: (id: PrincipalId) => Promise; + } = {}; + const logger = { log: vi.fn() }; + const resolvePrincipal = vi.fn(async (id: PrincipalId) => { + await hooks.beforeResolve?.(id); + const current = principals.get(id); + return current === undefined ? null : structuredClone(current); + }); + const readContext = vi.fn( + async ( + caller: AccessContext, + id: string, + ): Promise => { + const current = await app.getDraft(caller, { articleId: id }); + const [requirements, accepted] = await Promise.all([ + app.getValidationRequirements(caller, { + collectionId: current.revision.collectionId, + kind: current.revision.kind, + }), + hasPermission(caller, knowledgePermissions.evidenceRead) + ? app.getEvidence(caller, { articleId: id }) + : Promise.resolve(undefined), + ]); + const latest = await app.getDraft(caller, { articleId: id }); + if (latest.generation !== current.generation) + throw new Error("Synthetic context changed during its public reads"); + await hooks.afterContext?.(caller, id); + return { + draft: latest, + requirements, + ...(accepted === undefined ? {} : { evidence: accepted }), + }; + }, + ); + const baseOptions: KnowledgeEvidenceReportsOptions = { + store: reportStore, + clock, + collectionName: namespace, + confirmationPermission, + ...(options.storageLayout === undefined + ? {} + : { storageLayout: options.storageLayout }), + resolvePrincipal, + readContext, + logger, + }; + const reports: KnowledgeEvidenceReports = + createKnowledgeEvidenceReports(baseOptions); + const app: KnowledgeBaseApplication = createKnowledgeBaseApplication({ + store: observed.store, + clock, + evidenceVerifier: reports.verifier, + }); + const setTime = (milliseconds: number) => { + offset = milliseconds; + base.setTime(milliseconds); + }; + const command: typeof base.command = (prefix, expectedGeneration) => + base.command((options.commandPrefix ?? "") + prefix, expectedGeneration); + await base.setupCollection(collectionId); + await base.createDraft(articleId, collectionId, draft("walkthrough")); + setTime(3_000); + + const current = () => app.getDraft(reportAgent, { articleId }); + async function submission(checkId = "walkthrough-content") { + return evidence((await current()).revision, checkId); + } + function key(ack: KnowledgeReportAcknowledgement): KnowledgeReportKey { + return { articleId, ledgerEpoch: ack.ledgerEpoch, reportId: ack.reportId }; + } + async function reportInput( + proof?: EvidenceSubmission, + ): Promise { + return { + commandId: command("report", 0).commandId, + articleId, + ledgerEpoch: (await reports.ledger(reportAgent, { articleId })) + .ledgerEpoch, + evidence: proof ?? (await submission()), + report: { + summary: "Synthetic workspace export check", + details: "Reviewed staging output. PRIVATE_REPORT_BODY_CANARY", + }, + }; + } + async function report(proof?: EvidenceSubmission, caller = reportAgent) { + const input = await reportInput(proof); + return { input, ack: await reports.report(caller, input) }; + } + async function decide( + ack: KnowledgeReportAcknowledgement, + status: KnowledgeReportStatus = "confirmed", + caller = reportReviewer, + ) { + const view = await reports.read(caller, key(ack)); + const input: DecideKnowledgeReportInput = { + ...key(ack), + commandId: command("report-" + status, 0).commandId, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }; + return { view, input, ack: await reports.decide(caller, input, status) }; + } + async function submit( + ack: KnowledgeReportAcknowledgement, + proof: EvidenceSubmission, + caller = reportAgent, + ) { + const value = await app.getDraft(caller, { articleId }); + const input = { + ...command("accept-report", value.generation), + articleId, + evidence: proof, + receipt: ack.receipt, + }; + return { input, result: await app.submitEvidence(caller, input) }; + } + async function verificationRequest( + ack: KnowledgeReportAcknowledgement, + proof: EvidenceSubmission, + ): Promise { + const [value, configuration] = await Promise.all([ + current(), + app.getGovernanceConfiguration(admin, { collectionId }), + ]); + return { + access: reportAgent, + article: value.revision, + configuration: configuration.configuration, + submission: proof, + receipt: ack.receipt, + }; + } + async function completeChecks() { + const value = await current(); + const requirements = await app.getValidationRequirements(reportAgent, { + collectionId, + kind: value.revision.kind, + }); + const accepted = []; + for (const check of requirements.checks) { + const packet = await report(await submission(check.id)); + const confirmed = await decide(packet.ack); + const submitted = await submit(confirmed.ack, packet.input.evidence); + accepted.push({ ...packet, confirmed, submitted }); + } + return accepted; + } + async function publish() { + const value = await current(); + await app.submitForReview(reportReviewer, { + ...command("review-reports", value.generation), + articleId, + }); + const reviewed = await app.getReview(reportReviewer, { articleId }); + const input = { + ...command("publish-reports", reviewed.generation), + articleId, + review: reviewed.review, + }; + return { input, result: await app.publishArticle(reportReviewer, input) }; + } + async function updateDraft() { + const value = await current(); + await app.updateDraft(reportAgent, { + ...command("edit-report-target", value.generation), + articleId, + collectionId, + draft: draft( + "walkthrough", + "Choose Export, then save the updated download.", + ), + }); + return current(); + } + async function configure(patch: Partial) { + const value = await app.getGovernanceConfiguration(admin, { collectionId }); + return app.putGovernanceConfiguration(admin, { + ...command("change-report-governance", value.generation), + collectionId, + configuration: { ...value.configuration, ...patch }, + }); + } + function factoryDefinition(): CollectionDefinition { + if (reportDefinition === undefined) + throw new Error("Report factory did not declare its collection"); + return reportDefinition; + } + async function rawRows(): Promise[]> { + const collection = backing.collection(rawReportRowsDefinition(namespace)); + const found: ScanRecord[] = []; + let cursor: string | undefined; + for (let page = 0; page < 4; page++) { + const scanned = await collection.scan({ + limit: 160, + ...(cursor === undefined ? {} : { cursor }), + }); + found.push(...scanned.records); + if (scanned.nextCursor === null) + return found + .filter((item) => item.value.articleId === articleId) + .sort( + (left, right) => + left.key.partition.localeCompare(right.key.partition) || + left.key.id.localeCompare(right.key.id), + ); + cursor = scanned.nextCursor; + } + throw new Error( + "Synthetic report inspection exceeded its physical scan bound", + ); + } + async function physicalRows(): Promise[]> { + const definition = factoryDefinition(); + return (await rawRows()).map((item) => ({ + ...item, + value: logicalReportRow(definition.codec.decode(item.value)), + })); + } + async function installPreparedHistory(rows: readonly ReportLedgerRow[]) { + if (rows.length !== 160 || (await rawRows()).length !== 0) + throw new Error("Prepared history requires an empty 160-row target"); + const definition = factoryDefinition(); + const partition = definition.key(rows[0]!).partition; + if ( + rows.some( + (row) => + row.articleId !== articleId || + definition.key(row).partition !== partition, + ) + ) + throw new Error("Prepared history must retain its one article partition"); + const target = reportStore.collection(definition); + for (let offset = 0; offset < rows.length; offset += 100) { + const result = await target.transact( + partition, + rows.slice(offset, offset + 100).map((value) => ({ + action: "insert" as const, + value, + })), + ); + if (!result.committed) + throw new Error("Prepared history insertion did not commit"); + } + } + return { + app, + reports, + backing, + observed, + baseOptions, + clock, + logger, + hooks, + resolvePrincipal, + readContext, + principals, + articleId, + collectionId, + namespace, + agent: reportAgent, + owner: reportOwner, + reviewer: reportReviewer, + otherAgent: otherReportAgent, + customer, + command, + key, + current, + submission, + reportInput, + report, + decide, + submit, + verificationRequest, + completeChecks, + publish, + updateDraft, + configure, + setTime, + advance: (milliseconds: number) => setTime(offset + milliseconds), + rawRows, + physicalRows, + installPreparedHistory, + insertOpaqueRow: (value: ReportLedgerRow) => { + if (value.articleId !== articleId || value.id === "head") + throw new Error("Opaque fixture rows cannot create or cross a head"); + return reportStore.collection(factoryDefinition()).insertIfAbsent(value); + }, + rows: async () => + (await physicalRows()) + .map((item) => item.value) + .sort((left, right) => left.id.localeCompare(right.id)), + replaceRow: (saved: ScanRecord, value: ReportLedgerRow) => + backing + .collection({ ...factoryDefinition(), key: () => saved.key }) + .putIfUnchanged(value, saved.version), + replaceRaw: (saved: ScanRecord, value: StoredRecord) => + backing + .collection(rawReportRowsDefinition(namespace, saved.key)) + .putIfUnchanged(value, saved.version), + freshReports: (overrides: Partial = {}) => + createKnowledgeEvidenceReports({ ...baseOptions, ...overrides }), + }; +} + +/** + * Prepare the expensive history through real public operations on MemoryStore, + * then install its exact logical rows using the target factory's actual codec. + * This prepares a capacity fixture; it is not a migration or target history-write + * proof. All capacity refusals, reset, drains and new admission run on the target. + */ +export async function evidenceReportsHistoryFixture(backing: Store) { + const donor = await evidenceReportsFixture(createMemoryStore(), { + commandPrefix: "prepared-history-", + }); + const proof = await donor.submission(); + const packets = []; + for (let count = 0; count < 15; count++) + packets.push(await donor.report(proof)); + let ack = packets[0]!.ack; + for (let count = 0; count < 57; count++) + ack = (await donor.decide(ack, count % 2 === 0 ? "confirmed" : "pending")) + .ack; + const rows = await donor.rows(); + const target = await evidenceReportsFixture(backing); + await target.installPreparedHistory(rows); + return { ...target, preparedHistory: { ack, proof, rows } }; +} diff --git a/tests/agent-reports.test.ts b/tests/agent-reports.test.ts new file mode 100644 index 0000000..2d62dfe --- /dev/null +++ b/tests/agent-reports.test.ts @@ -0,0 +1,646 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import type { KnowledgeEvidenceReports } from "@pegma/knowledge-base-application"; +import { + createKnowledgeAgentDispatcher, + createKnowledgeAgentHttp, + createKnowledgeAgentMcp, + knowledgeAgentScopes, + knowledgeAgentToolNames, + type KnowledgeAgentIdentity, + type KnowledgeAgentLimits, + type KnowledgeAgentOperation, + type KnowledgeAgentPendingReport, + type KnowledgeAgentReportRequirementsResult, + type KnowledgeAgentReportSubmissionInput, + type KnowledgeAgentResponse, +} from "@pegma/knowledge-base-mcp"; +import { createMemoryStore } from "@pegma/storage-core"; +import { describe, expect, it, onTestFinished } from "vitest"; +import { + agentApiUrl, + agentMetadataUrl, + agentOrigin, + agentResource, +} from "../test/agent-fixtures.js"; +import { evidenceReportsFixture } from "../test/evidence-reports-fixtures.js"; + +type Channel = "HTTP" | "MCP"; +type Reports = Pick; + +async function fixture( + options: { + legacy?: boolean; + limits?: Partial; + wrapReports?: ( + reports: Reports, + f: Awaited>, + ) => Reports; + } = {}, +) { + const f = await evidenceReportsFixture(createMemoryStore()); + // Scripted trusted contexts are fictional host inputs, not an OAuth/login or + // live staging proof. All KB, report persistence and evidence checks are real. + const authority: { current: KnowledgeAgentIdentity } = { + current: { + access: f.agent, + scopes: Object.values(knowledgeAgentScopes), + clientId: "synthetic-report-agent", + resource: agentResource, + }, + }; + const dispatcher = createKnowledgeAgentDispatcher({ + application: f.app, + resource: agentResource, + ...(options.legacy + ? {} + : { reports: options.wrapReports?.(f.reports, f) ?? f.reports }), + ...(options.limits === undefined ? {} : { limits: options.limits }), + }); + const common = { + dispatcher, + resource: agentResource, + protectedResourceMetadataUrl: agentMetadataUrl, + allowedOrigins: [agentOrigin], + authenticate: async () => structuredClone(authority.current), + limit: async () => true, + }; + const http = createKnowledgeAgentHttp({ ...common, apiUrl: agentApiUrl }); + const mcp = createKnowledgeAgentMcp({ ...common, mcpUrl: agentResource }); + let client: Client | undefined; + async function sdk() { + if (client !== undefined) return client; + const next = new Client({ name: "synthetic-report-client", version: "1" }); + onTestFinished(() => next.close()); + await next.connect( + new StreamableHTTPClientTransport(new URL(agentResource), { + requestInit: { + headers: { Authorization: "Bearer synthetic-credential" }, + }, + fetch: async (input, init) => { + const response = await mcp.handle(new Request(input, init)); + if (response === null) + throw new Error("Official MCP request was not routed"); + return response; + }, + }), + ); + client = next; + return next; + } + async function call( + channel: Channel, + operation: KnowledgeAgentOperation, + input: unknown, + ): Promise { + if (channel === "HTTP") { + const response = await http.handle( + new Request(agentApiUrl, { + method: "POST", + headers: { + Authorization: "Bearer synthetic-credential", + "Content-Type": "application/json", + }, + body: JSON.stringify({ apiVersion: "1", operation, input }), + }), + ); + if (response === null) + throw new Error("Actual HTTP request was not routed"); + const result = (await response.json()) as KnowledgeAgentResponse; + expect(response.status).toBe( + "error" in result ? result.error.status : 200, + ); + return result; + } + const result = await ( + await sdk() + ).callTool({ + name: knowledgeAgentToolNames[operation], + arguments: input as Record, + }); + if (!Array.isArray(result.content) || result.content.length !== 1) + throw new Error("Expected one exact SDK text result"); + const content = result.content[0]; + if (content?.type !== "text" || typeof content.text !== "string") + throw new Error("Expected complete JSON text"); + const response = JSON.parse(content.text) as KnowledgeAgentResponse; + expect(result.isError === true).toBe("error" in response); + return response; + } + function requirementsInput(report?: KnowledgeAgentPendingReport) { + return { + collectionId: f.collectionId, + kind: "walkthrough", + articleId: f.articleId, + ...(report === undefined + ? {} + : { + reportLookup: { + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + }, + }), + }; + } + async function packet(channel: Channel, check = "walkthrough-content") { + const requirements = success( + await call(channel, "getValidationRequirements", requirementsInput()), + ); + const current = await f.current(); + const input: KnowledgeAgentReportSubmissionInput = { + ...f.command("native-report", current.generation), + articleId: f.articleId, + evidence: await f.submission(check), + ledgerEpoch: requirements.reportLedger.ledgerEpoch, + report: { + summary: "Synthetic staging execution", + details: + "Actual reviewed fixture output. PRIVATE_REPORT_BODY_CANARY\nSecond report line.", + }, + }; + return { + input, + ack: success( + await call(channel, "submitEvidence", input), + ), + }; + } + return { + ...f, + authority, + dispatcher, + http, + mcp, + sdk, + call, + packet, + requirementsInput, + }; +} + +function success(response: KnowledgeAgentResponse): T { + if ("error" in response) throw new Error(JSON.stringify(response)); + return response.result as T; +} + +function privateError(response: KnowledgeAgentResponse, code: string) { + expect(response).toMatchObject({ apiVersion: "1", error: { code } }); + const value = JSON.stringify(response); + for (const secret of [ + "PRIVATE_", + "trustedAttesterIds", + "trustedRunnerIds", + "staff/verifier", + "private/artifact", + ]) + expect(value).not.toContain(secret); +} + +function bodyFree(value: unknown) { + const encoded = JSON.stringify(value); + for (const privateValue of [ + "PRIVATE_REPORT_BODY_CANARY", + "PRIVATE_STAFF_EVIDENCE", + "private/artifact", + "staff/verifier", + "trustedAttesterIds", + "trustedRunnerIds", + "reportHash", + "submissionHash", + "confirmation", + ]) + expect(encoded).not.toContain(privateValue); +} + +describe.each(["HTTP", "MCP"] as const)( + "optional native human-report workflow over %s", + (channel) => { + const other: Channel = channel === "HTTP" ? "MCP" : "HTTP"; + + it("queues privately, requires human confirmation, polls its own receipt, accepts every real check and leaves publication to staff", async () => { + const f = await fixture(); + const before = await f.current(); + const first = await f.packet(channel); + expect(first.ack).toMatchObject({ + kind: "pending-human-review", + ledgerEpoch: 1, + reportGeneration: 1, + }); + bodyFree(first.ack); + expect((await f.current()).generation).toBe(before.generation); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toHaveLength(0); + const pending = success( + await f.call( + other, + "getValidationRequirements", + f.requirementsInput(first.ack), + ), + ); + expect(pending.reportStatus).toMatchObject({ + status: "pending", + receipt: first.ack.receipt, + }); + bodyFree(pending); + const trusted = { + ...f.command("submit-native-evidence", before.generation), + articleId: f.articleId, + evidence: first.input.evidence, + receipt: first.ack.receipt, + }; + privateError( + await f.call(channel, "submitEvidence", trusted), + "prerequisite", + ); + const confirmation = await f.decide(first.ack); + expect(confirmation.ack.receipt).toBe(first.ack.receipt); + const checked = success( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput(first.ack), + ), + ); + expect(checked.reportStatus).toMatchObject({ + status: "confirmed", + receipt: first.ack.receipt, + }); + bodyFree(checked); + expect( + success<{ replayed: boolean }>( + await f.call(channel, "submitEvidence", trusted), + ).replayed, + ).toBe(false); + expect( + success<{ replayed: boolean }>( + await f.call(other, "submitEvidence", trusted), + ).replayed, + ).toBe(true); + const second = await f.packet(other, "walkthrough-workflow"); + await f.decide(second.ack); + const current = await f.current(); + success( + await f.call(channel, "submitEvidence", { + ...f.command("submit-native-workflow", current.generation), + articleId: f.articleId, + evidence: second.input.evidence, + receipt: second.ack.receipt, + }), + ); + const accepted = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + expect(accepted.evidence).toHaveLength(2); + expect( + accepted.evidence.every( + (value) => value.attestation.verifiedBy === f.reviewer.principalId, + ), + ).toBe(true); + expect((await f.current()).hasPublication).toBe(false); + await expect( + f.app.submitForReview(f.agent, { + ...f.command( + "forbidden-agent-review", + (await f.current()).generation, + ), + articleId: f.articleId, + }), + ).rejects.toMatchObject({ name: "KnowledgeBaseAuthorizationError" }); + await f.publish(); + const published = await f.app.getPublishedArticle(f.customer, { + articleId: f.articleId, + }); + expect(published.revision).toBe(1); + bodyFree(published); + }); + + it("keeps exact default legacy schemas, tool count and receipt submission behavior", async () => { + const f = await fixture({ legacy: true }); + expect(f.dispatcher.reportWorkflow).toBeUndefined(); + privateError( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput(), + ), + "invalid_request", + ); + const current = await f.current(); + const raw = await f.reportInput(); + privateError( + await f.call(channel, "submitEvidence", { + ...f.command("disabled-report", current.generation), + ...raw, + }), + "invalid_request", + ); + const legacyRequirements = success>( + await f.call(channel, "getValidationRequirements", { + collectionId: f.collectionId, + kind: "walkthrough", + }), + ); + expect(legacyRequirements).not.toHaveProperty("reportLedger"); + expect(legacyRequirements).not.toHaveProperty("reportStatus"); + const reported = await f.report(); + await f.decide(reported.ack); + const result = success>( + await f.call(channel, "submitEvidence", { + ...f.command("legacy-accepted", current.generation), + articleId: f.articleId, + evidence: reported.input.evidence, + receipt: reported.ack.receipt, + }), + ); + expect(result).toHaveProperty("value"); + expect(result).not.toHaveProperty("kind"); + const listed = await (await f.sdk()).listTools(); + expect(listed.tools).toHaveLength(5); + expect(JSON.stringify(listed.tools)).not.toContain("ledgerEpoch"); + }); + + it("requires both existing effective permissions for the optional extension and never grants staff capabilities", async () => { + const f = await fixture(); + const current = await f.current(); + const raw = await f.reportInput(); + const input = { + ...f.command("missing-report-scope", current.generation), + ...raw, + }; + const initial = f.authority.current; + for (const scopes of [ + [knowledgeAgentScopes.draftWrite], + [knowledgeAgentScopes.evidenceSubmit], + [knowledgeAgentScopes.draftRead], + ]) { + f.authority.current = { ...initial, scopes }; + privateError( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput(), + ), + "forbidden", + ); + privateError( + await f.call(channel, "submitEvidence", input), + "forbidden", + ); + } + f.authority.current = initial; + await expect( + f.reports.read(f.agent, { + articleId: f.articleId, + ledgerEpoch: 1, + reportId: "unknown", + }), + ).rejects.toMatchObject({ code: "forbidden" }); + for (const operation of [ + "publishArticle", + "getProvenance", + "getEvidence", + "submitForReview", + "confirmReport", + ]) { + const response = await f.dispatcher.dispatch(initial, { + apiVersion: "1", + operation, + input: {}, + }); + privateError(response, "invalid_request"); + } + expect(await f.rows()).toHaveLength(0); + }); + + it("strictly rejects unknown fields, mixed receipt/report variants and excess report bounds before a write", async () => { + const f = await fixture(); + const current = await f.current(); + const raw = await f.reportInput(); + const input = { + ...f.command("strict-report", current.generation), + ...raw, + }; + for (const invalid of [ + { ...input, receipt: "untrusted" }, + { ...input, principalId: f.agent.principalId }, + { ...input, report: { ...input.report, attestation: "fake" } }, + { + ...input, + evidence: { + ...input.evidence, + attestation: { verifiedBy: f.reviewer.principalId }, + }, + }, + { ...input, report: { summary: "S".repeat(1001), details: "bounded" } }, + { + ...input, + report: { summary: "bounded", details: "D".repeat(16_001) }, + }, + ]) + privateError( + await f.call(channel, "submitEvidence", invalid), + "invalid_request", + ); + privateError( + await f.call(channel, "getValidationRequirements", { + ...f.requirementsInput(), + reportLookup: { + ledgerEpoch: 1, + reportId: "fake", + reviewerId: "fake", + }, + }), + "invalid_request", + ); + privateError( + await f.call(channel, "getValidationRequirements", { + collectionId: f.collectionId, + kind: "walkthrough", + reportLookup: { ledgerEpoch: 1, reportId: "fake" }, + }), + "invalid_request", + ); + expect(await f.rows()).toHaveLength(0); + }); + + it("binds article collection/kind, current generation and report epoch without exposing other authors' status", async () => { + const f = await fixture(); + const current = await f.current(); + const raw = await f.reportInput(); + privateError( + await f.call(channel, "getValidationRequirements", { + ...f.requirementsInput(), + collectionId: "foreign-collection", + }), + "conflict", + ); + privateError( + await f.call(channel, "getValidationRequirements", { + ...f.requirementsInput(), + kind: "explanation", + }), + "conflict", + ); + privateError( + await f.call(channel, "submitEvidence", { + ...f.command("stale-report", current.generation + 1), + ...raw, + }), + "conflict", + ); + privateError( + await f.call(channel, "submitEvidence", { + ...f.command("wrong-epoch-report", current.generation), + ...raw, + ledgerEpoch: raw.ledgerEpoch + 1, + }), + "conflict", + ); + const own = await f.packet(channel); + privateError( + await f.call(channel, "getValidationRequirements", { + ...f.requirementsInput(), + reportLookup: { + ledgerEpoch: own.ack.ledgerEpoch + 1, + reportId: own.ack.reportId, + }, + }), + "conflict", + ); + f.authority.current = { ...f.authority.current, access: f.otherAgent }; + privateError( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput(own.ack), + ), + "not_found", + ); + f.authority.current = { ...f.authority.current, access: f.agent }; + await f.decide(own.ack); + const invalidReceipt = { + ...f.command("tampered-native-receipt", current.generation), + articleId: f.articleId, + evidence: own.input.evidence, + receipt: own.ack.receipt + "tampered", + }; + privateError( + await f.call(channel, "submitEvidence", invalidReceipt), + "prerequisite", + ); + privateError( + await f.call(channel, "submitEvidence", { + ...invalidReceipt, + receipt: own.ack.receipt, + evidence: { ...own.input.evidence, stagingBuildId: "wrong-build" }, + }), + "prerequisite", + ); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toHaveLength(0); + }); + }, +); + +describe("optional native report bounds and observational fences", () => { + it("advertises the optional variants on exactly the same five official MCP tools", async () => { + const f = await fixture(); + expect(f.dispatcher.reportWorkflow).toBe(true); + const listed = await (await f.sdk()).listTools(); + expect(listed.tools).toHaveLength(5); + const requirements = listed.tools.find( + (tool) => tool.name === knowledgeAgentToolNames.getValidationRequirements, + ); + const submission = listed.tools.find( + (tool) => tool.name === knowledgeAgentToolNames.submitEvidence, + ); + expect(requirements?.inputSchema.type).toBe("object"); + expect(submission?.inputSchema.type).toBe("object"); + expect(JSON.stringify(requirements?.inputSchema)).toContain("reportLookup"); + expect(JSON.stringify(submission?.inputSchema)).toContain("ledgerEpoch"); + expect(JSON.stringify(submission?.inputSchema)).toContain("receipt"); + expect(Object.values(knowledgeAgentScopes)).toHaveLength(3); + }); + + it("retains the complete pending acknowledgement at the existing minimum response budget", async () => { + const f = await fixture({ limits: { maxResponseBytes: 2048 } }); + const queued = await f.packet("MCP"); + expect(queued.ack.kind).toBe("pending-human-review"); + expect( + new TextEncoder().encode(JSON.stringify(queued.ack)).byteLength, + ).toBeLessThan(2048); + expect((await f.current()).generation).toBe(1); + }); + + it("withholds a queued-report ACK after an actual draft edit without claiming report rollback", async () => { + const f = await fixture({ + wrapReports: (reports, app) => ({ + ...reports, + async report(access, input) { + expect(access.roles).toEqual([]); + expect(access.entitlements).toEqual([]); + expect(access.permissions).toEqual( + Object.values(knowledgeAgentScopes), + ); + const ack = await reports.report(access, input); + await app.updateDraft(); + return ack; + }, + }), + }); + f.authority.current = { + ...f.authority.current, + access: { + ...f.owner, + roles: ["synthetic-admin"], + entitlements: ["synthetic-entitlement"], + }, + }; + const current = await f.current(); + const raw = await f.reportInput(); + privateError( + await f.call("HTTP", "submitEvidence", { + ...f.command("changed-after-report", current.generation), + ...raw, + }), + "conflict", + ); + expect((await f.rows()).length).toBeGreaterThan(0); + expect((await f.current()).revision.number).toBe(2); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toHaveLength(0); + }); + + it("withholds old report status after an actual draft edit during the status await", async () => { + let edit = false; + const f = await fixture({ + wrapReports: (reports, app) => ({ + ...reports, + async status(access, input) { + const status = await reports.status(access, input); + if (edit) { + edit = false; + await app.updateDraft(); + } + return status; + }, + }), + }); + const queued = await f.packet("HTTP"); + edit = true; + privateError( + await f.call( + "MCP", + "getValidationRequirements", + f.requirementsInput(queued.ack), + ), + "conflict", + ); + }); +}); diff --git a/tests/evidence-reports.test.ts b/tests/evidence-reports.test.ts new file mode 100644 index 0000000..bb66965 --- /dev/null +++ b/tests/evidence-reports.test.ts @@ -0,0 +1,1342 @@ +import { + createKnowledgeEvidenceReports, + KnowledgeEvidenceReportsError, + type EvidenceVerificationRequest, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import type { EvidenceSubmission } from "@pegma/knowledge-base-core"; +import { describe, expect, it } from "vitest"; +import { access, at, draft, evidence } from "../test/application-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { + confirmationPermission, + evidenceReportsFixture, + evidenceReportsHistoryFixture, + reportBarrier, +} from "../test/evidence-reports-fixtures.js"; + +const unavailable = { code: "report_ledger_unavailable" }; +const kbEvidenceRefusal = { + name: expect.stringMatching( + /^(KnowledgeBaseError|KnowledgeBasePrerequisiteError)$/u, + ), +}; +const capture = (promise: Promise) => + promise.then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); + +async function maximumAsciiReport( + f: Awaited>, +) { + const original = await f.reportInput({ + ...(await f.submission()), + steps: Array.from({ length: 16 }, () => "S".repeat(1_000)), + }); + const input = { + ...original, + report: { summary: "R".repeat(1_000), details: "D".repeat(16_000) }, + }; + return { input, ack: await f.reports.report(f.agent, input) }; +} + +for (const [backend, createStore] of storeFactories) { + describe(`shared evidence reports over ${backend}`, () => { + it("accepts only independently confirmed reports, completes every required check, then publishes through the actual KB", async () => { + const f = await evidenceReportsFixture(await createStore()); + const first = await f.report(); + await expect( + f.submit(first.ack, first.input.evidence), + ).rejects.toMatchObject(kbEvidenceRefusal); + const confirmed = await f.decide(first.ack); + const accepted = await f.submit(confirmed.ack, first.input.evidence); + const current = await f.current(); + await expect( + f.app.submitForReview(f.reviewer, { + ...f.command("missing-workflow-check", current.generation), + articleId: f.articleId, + }), + ).rejects.toMatchObject({ code: "evidence" }); + const required = await f.app.getValidationRequirements(f.agent, { + collectionId: f.collectionId, + kind: current.revision.kind, + }); + expect(required.checks.map((check) => check.id).sort()).toEqual([ + "walkthrough-content", + "walkthrough-workflow", + ]); + const second = await f.report(await f.submission("walkthrough-workflow")); + const checked = await f.decide(second.ack); + await f.submit(checked.ack, second.input.evidence); + await f.publish(); + const visible = await f.app.getPublishedArticle(f.customer, { + articleId: f.articleId, + }); + expect(visible.revision).toBe(1); + const stored = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + expect(stored.evidence).toHaveLength(2); + expect( + stored.evidence.map((item) => item.attestation.verifiedBy), + ).toEqual([f.reviewer.principalId, f.reviewer.principalId]); + expect(stored.evidence[0]?.attestation.id).toBe(confirmed.ack.receipt); + expect(stored.evidence[0]?.attestation.id).not.toBe(first.ack.reportId); + expect(accepted.result.replayed).toBe(false); + for (const secret of [ + "PRIVATE_REPORT_BODY_CANARY", + "PRIVATE_STAFF_EVIDENCE", + "private/artifact/export", + f.reviewer.principalId, + first.ack.reportId, + confirmed.ack.receipt, + ]) + expect(JSON.stringify(visible)).not.toContain(secret); + }); + + it("preserves restricted caller grants despite current owner/Admin authority, while the same human principal may explicitly confirm", async () => { + const f = await evidenceReportsFixture(await createStore()); + await f.configure({ + trustedAttesterIds: [f.reviewer.principalId, f.owner.principalId], + }); + const packet = await f.report(); + expect(f.readContext.mock.calls[0]?.[0].permissions).toEqual( + f.agent.permissions, + ); + expect(f.agent.principalId).toBe(f.owner.principalId); + expect(f.agent.permissions).toHaveLength(3); + const view = await f.reports.read(f.owner, f.key(packet.ack)); + const decision = { + ...f.key(packet.ack), + commandId: "same-principal-human-review", + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }; + const before = await f.rows(); + for (const operation of [ + () => f.reports.read(f.agent, f.key(packet.ack)), + () => f.reports.list(f.agent, { articleId: f.articleId }), + () => f.reports.decide(f.agent, decision, "confirmed"), + () => + f.reports.reset(f.agent, { + articleId: f.articleId, + commandId: "agent-reset", + expectedLedgerEpoch: 1, + }), + ]) + await expect(operation()).rejects.toMatchObject({ code: "forbidden" }); + expect(await f.rows()).toEqual(before); + const confirmed = await f.reports.decide(f.owner, decision, "confirmed"); + await f.submit(confirmed, packet.input.evidence); + expect( + (await f.app.getEvidence(f.owner, { articleId: f.articleId })) + .evidence[0]?.attestation.verifiedBy, + ).toBe(f.owner.principalId); + }); + + it("exposes only an opaque body-free status to the submitting owner and denies other owners", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const status = await f.reports.status(f.agent, f.key(packet.ack)); + expect(status).toEqual({ ...packet.ack, status: "pending" }); + expect(Object.keys(status).sort()).toEqual([ + "ledgerEpoch", + "receipt", + "reportGeneration", + "reportId", + "status", + ]); + expect(JSON.stringify(status)).not.toContain( + "PRIVATE_REPORT_BODY_CANARY", + ); + await expect( + f.reports.status(f.otherAgent, f.key(packet.ack)), + ).rejects.toMatchObject({ code: "report_not_found" }); + const reviewed = await f.reports.list(f.reviewer, { + articleId: f.articleId, + }); + expect(reviewed.reports[0]?.summary).toBe(packet.input.report.summary); + expect(JSON.stringify(reviewed.reports)).not.toContain( + "PRIVATE_REPORT_BODY_CANARY", + ); + expect( + (await f.reports.read(f.reviewer, f.key(packet.ack))).report.details, + ).toBe(packet.input.report.details); + }); + + it("replays exact commands without appending rows and rejects changed report or decision bindings", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const before = await f.rows(); + expect(await f.reports.report(f.agent, packet.input)).toEqual(packet.ack); + expect(await f.rows()).toEqual(before); + await expect( + f.reports.report(f.agent, { + ...packet.input, + report: { + ...packet.input.report, + details: "Different submitted artifact", + }, + }), + ).rejects.toMatchObject({ code: "command_conflict" }); + const decision = await f.decide(packet.ack); + const afterDecision = await f.rows(); + expect( + await f.reports.decide(f.reviewer, decision.input, "confirmed"), + ).toEqual(decision.ack); + await expect( + f.reports.decide(f.reviewer, decision.input, "rejected"), + ).rejects.toMatchObject({ code: "command_conflict" }); + expect(await f.rows()).toEqual(afterDecision); + expect( + (await f.reports.list(f.reviewer, { articleId: f.articleId })).reports, + ).toHaveLength(1); + }); + + it("recovers the exact accepted report after a real transaction commits and loses its acknowledgement", async () => { + const f = await evidenceReportsFixture(await createStore()); + const input = await f.reportInput(); + let lost = false; + f.observed.intercept(async (trace, commit) => { + const result = await commit(); + if (!lost && trace.collection === f.namespace) { + lost = true; + throw new Error("PRIVATE_STORAGE_ACK_CANARY"); + } + return result; + }); + await expect(f.reports.report(f.agent, input)).rejects.toMatchObject({ + ...unavailable, + stage: "report_write", + message: "Knowledge evidence report ledger is unavailable.", + }); + f.observed.intercept(undefined); + const committed = await f.rows(); + expect(committed).toHaveLength(4); + const recovered = await f.reports.report(f.agent, input); + expect(await f.reports.status(f.agent, f.key(recovered))).toEqual({ + ...recovered, + status: "pending", + }); + expect(await f.rows()).toEqual(committed); + }); + + it("fences an actual competing report transaction without half-written report, Audit or receipt rows", async () => { + const f = await evidenceReportsFixture(await createStore()); + const gate = reportBarrier(); + let paused = false; + f.observed.intercept(async (trace, commit) => { + if (!paused && trace.collection === f.namespace) { + paused = true; + await gate.wait(); + } + return commit(); + }); + const input = await f.reportInput(); + const pending = capture(f.reports.report(f.agent, input)); + try { + await gate.reached(pending); + await f.report(); + } finally { + gate.release(); + } + expect(await pending).toMatchObject({ + error: { code: "report_changed" }, + }); + f.observed.intercept(undefined); + expect(await f.rows()).toHaveLength(4); + await f.reports.report(f.agent, input); + expect(await f.rows()).toHaveLength(7); + expect( + (await f.reports.list(f.reviewer, { articleId: f.articleId })).reports, + ).toHaveLength(2); + }); + + it("binds every submitted evidence field and artifact to the independently confirmed report", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + const proof = packet.input.evidence; + const tampered: EvidenceSubmission[] = [ + { ...proof, id: "evidence/other-id" }, + { ...proof, articleRevision: 2 }, + { ...proof, contentHash: "b".repeat(64) }, + { + ...proof, + validationPolicy: { ...proof.validationPolicy, version: 2 }, + }, + { ...proof, checkId: "walkthrough-workflow" }, + { ...proof, testKind: "workflow" }, + { + ...proof, + applicability: { ...proof.applicability, productId: "other-product" }, + }, + { ...proof, stagingBuildId: "staging-other" }, + { ...proof, steps: ["Unreviewed procedure"] }, + { ...proof, result: "failed" }, + { ...proof, executedAt: at(2_000) }, + { ...proof, runnerId: "unreviewed/runner" }, + { + ...proof, + artifacts: [{ id: "other/artifact", hash: "c".repeat(64) }], + }, + ]; + const request = await f.verificationRequest(confirmed.ack, proof); + const before = await allKnowledgeRows(f.backing); + for (const submission of tampered) { + expect( + await f.reports.verifier.verify({ ...request, submission }), + ).toBeNull(); + await expect(f.submit(confirmed.ack, submission)).rejects.toMatchObject( + kbEvidenceRefusal, + ); + expect(await allKnowledgeRows(f.backing)).toEqual(before); + } + expect( + await f.reports.verifier.verify({ ...request, access: f.otherAgent }), + ).toBeNull(); + await expect( + f.submit(confirmed.ack, proof, f.otherAgent), + ).rejects.toMatchObject(kbEvidenceRefusal); + await f.submit(confirmed.ack, proof); + }); + + it("rejects a confirmed report from an untrusted runner under actual KB evidence policy", async () => { + const f = await evidenceReportsFixture(await createStore()); + const proof = await f.submission(); + const input = { ...proof, runnerId: "untrusted/runner" }; + const packet = await f.report(input); + const confirmed = await f.decide(packet.ack); + await expect(f.submit(confirmed.ack, input)).rejects.toMatchObject( + kbEvidenceRefusal, + ); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toEqual([]); + }); + + it("records a reviewed failed result but requires a genuinely passing replacement before publication", async () => { + const f = await evidenceReportsFixture(await createStore()); + const failedProof: EvidenceSubmission = { + ...(await f.submission()), + result: "failed", + }; + const failed = await f.report(failedProof); + const confirmedFailure = await f.decide(failed.ack); + expect( + (await f.submit(confirmedFailure.ack, failedProof)).result.replayed, + ).toBe(false); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toMatchObject([{ id: failedProof.id, result: "failed", version: 1 }]); + const workflow = await f.report( + await f.submission("walkthrough-workflow"), + ); + await f.submit( + (await f.decide(workflow.ack)).ack, + workflow.input.evidence, + ); + await expect(f.publish()).rejects.toMatchObject({ code: "evidence" }); + const passing = await f.report(await f.submission()); + await f.submit((await f.decide(passing.ack)).ack, passing.input.evidence); + const qualified = ( + await f.app.getEvidence(f.reviewer, { articleId: f.articleId }) + ).evidence; + expect( + qualified.find((item) => item.id === failedProof.id), + ).toMatchObject({ result: "passed", version: 2 }); + await f.publish(); + expect( + ( + await f.app.getPublishedArticle(f.customer, { + articleId: f.articleId, + }) + ).revision, + ).toBe(1); + }); + + it.each(["build", "check", "revision", "future", "expired"] as const)( + "refuses human confirmation against a %s mismatch or stale execution", + async (defect) => { + const f = await evidenceReportsFixture(await createStore()); + const original = await f.submission(); + const proof: EvidenceSubmission = { + ...original, + ...(defect === "build" ? { stagingBuildId: "wrong-build" } : {}), + ...(defect === "check" ? { checkId: "absent-check" } : {}), + ...(defect === "revision" ? { articleRevision: 2 } : {}), + ...(defect === "future" ? { executedAt: at(4_000) } : {}), + }; + const packet = await f.report(proof); + if (defect === "expired") f.advance(61_000); + const before = await f.rows(); + await expect(f.decide(packet.ack)).rejects.toMatchObject({ + code: "report_not_verifiable", + }); + expect(await f.rows()).toEqual(before); + }, + ); + + it("invalidates an old review binding after an actual draft edit or governance change", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const view = await f.reports.read(f.reviewer, f.key(packet.ack)); + const input = { + ...f.key(packet.ack), + commandId: "stale-human-decision", + expectedReportGeneration: view.reportGeneration, + reviewBindingHash: view.reviewBindingHash, + }; + await f.configure({ + trustedAttesterIds: [f.owner.principalId, f.reviewer.principalId], + }); + await expect( + f.reports.decide(f.reviewer, input, "confirmed"), + ).rejects.toMatchObject({ code: "report_changed" }); + await expect(f.decide(packet.ack)).rejects.toMatchObject({ + code: "report_not_verifiable", + }); + await f.updateDraft(); + await expect(f.decide(packet.ack)).rejects.toMatchObject({ + code: "report_not_verifiable", + }); + expect((await f.reports.status(f.agent, f.key(packet.ack))).status).toBe( + "pending", + ); + }); + + it("reassessment rotates the receipt cycle and requires a fresh exact human confirmation", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const old = await f.decide(packet.ack); + await f.configure({ + trustedAttesterIds: [f.owner.principalId, f.reviewer.principalId], + }); + const stale = await f.verificationRequest(old.ack, packet.input.evidence); + expect(await f.reports.verifier.verify(stale)).toBeNull(); + const reassessed = await f.decide(old.ack, "pending"); + expect(reassessed.ack.reportId).toBe(old.ack.reportId); + expect(reassessed.ack.receipt).not.toBe(old.ack.receipt); + expect(await f.reports.verifier.verify(stale)).toBeNull(); + const beforeReplay = await f.rows(); + expect( + await f.reports.decide(f.reviewer, old.input, "confirmed"), + ).toEqual(old.ack); + expect(await f.rows()).toEqual(beforeReplay); + expect((await f.reports.status(f.agent, f.key(old.ack))).status).toBe( + "pending", + ); + await expect( + f.submit(reassessed.ack, packet.input.evidence), + ).rejects.toMatchObject(kbEvidenceRefusal); + const confirmed = await f.decide(reassessed.ack); + await f.submit(confirmed.ack, packet.input.evidence); + expect(await f.reports.verifier.verify(stale)).toBeNull(); + }); + + it.each(["principal", "governance"] as const)( + "rechecks %s attester revocation after awaited public KB reads", + async (revocation) => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + const gate = reportBarrier(); + let paused = false; + f.hooks.afterContext = async (caller) => { + if (!paused && caller.principalId === f.reviewer.principalId) { + paused = true; + await gate.wait(); + } + }; + const pending = capture(f.submit(confirmed.ack, packet.input.evidence)); + try { + await gate.reached(pending); + if (revocation === "principal") + f.principals.delete(f.reviewer.principalId); + else await f.configure({ trustedAttesterIds: [f.owner.principalId] }); + } finally { + gate.release(); + } + expect(await pending).toMatchObject({ + error: + revocation === "governance" + ? { name: "RepositoryConflictError" } + : { + name: "KnowledgeBasePrerequisiteError", + prerequisite: "evidence-verifier", + }, + }); + await expect( + f.submit(confirmed.ack, packet.input.evidence), + ).rejects.toMatchObject({ + name: "KnowledgeBasePrerequisiteError", + prerequisite: "evidence-verifier", + }); + expect( + (await f.app.getEvidence(f.owner, { articleId: f.articleId })) + .evidence, + ).toEqual([]); + expect( + (await f.reports.status(f.agent, f.key(packet.ack))).status, + ).toBe("confirmed"); + }, + ); + + it("denies a private view when human confirmation authority is revoked while its body loads", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const gate = reportBarrier(); + f.hooks.afterContext = () => gate.wait(); + const pending = capture(f.reports.read(f.reviewer, f.key(packet.ack))); + try { + await gate.reached(pending); + f.principals.set( + f.reviewer.principalId, + access( + f.reviewer.principalId, + f.reviewer.permissions.filter( + (permission) => permission !== confirmationPermission, + ), + ), + ); + } finally { + gate.release(); + } + expect(await pending).toMatchObject({ error: { code: "forbidden" } }); + expect(await f.rows()).toHaveLength(4); + }); + + it("denies report acceptance and exact replay after the submitting principal loses current scope", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const before = await f.rows(); + f.principals.set( + f.owner.principalId, + access( + f.owner.principalId, + f.owner.permissions.filter( + (permission) => permission !== knowledgePermissions.evidenceSubmit, + ), + ), + ); + await expect( + f.reports.report(f.agent, packet.input), + ).rejects.toMatchObject({ code: "forbidden" }); + await expect( + f.reports.status(f.agent, f.key(packet.ack)), + ).rejects.toMatchObject({ code: "forbidden" }); + expect(await f.rows()).toEqual(before); + }); + + it("requires the exact original reviewer identity rather than a substituted current principal", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + f.principals.set( + f.reviewer.principalId, + access("staff/replacement", f.reviewer.permissions), + ); + expect( + await f.reports.verifier.verify( + await f.verificationRequest(confirmed.ack, packet.input.evidence), + ), + ).toBeNull(); + await expect( + f.submit(confirmed.ack, packet.input.evidence), + ).rejects.toMatchObject(kbEvidenceRefusal); + }); + + it("snapshots the complete report and restricted caller before an awaited context port", async () => { + const f = await evidenceReportsFixture(await createStore()); + const original = await f.reportInput(); + const input = { + ...original, + report: { ...original.report }, + evidence: { + ...original.evidence, + steps: [...original.evidence.steps], + }, + }; + const grants = [...f.agent.permissions]; + const caller = access(f.agent.principalId, grants); + const gate = reportBarrier(); + f.hooks.afterContext = () => gate.wait(); + const pending = capture(f.reports.report(caller, input)); + try { + await gate.reached(pending); + input.report.details = "LATE_UNREVIEWED_REPORT_BODY"; + input.evidence.steps.push("LATE_UNREVIEWED_STEP"); + grants.push(confirmationPermission); + } finally { + gate.release(); + } + const result = await pending; + if (!("value" in result)) + throw new Error("Expected snapshotted report acceptance"); + delete f.hooks.afterContext; + const view = await f.reports.read(f.reviewer, f.key(result.value)); + expect(view.report).toEqual(original.report); + expect(view.evidence).toEqual(original.evidence); + expect(f.readContext.mock.calls[0]?.[0].permissions).toEqual( + f.agent.permissions, + ); + }); + + it("retains accepted SDK ACKs and immutable published evidence while a newer draft starts without current proof", async () => { + const f = await evidenceReportsFixture(await createStore()); + const accepted = await f.completeChecks(); + await f.publish(); + const published = await f.app.getPublishedArticle(f.customer, { + articleId: f.articleId, + }); + const acceptedEvidence = ( + await f.app.getEvidence(f.owner, { articleId: f.articleId }) + ).evidence; + const immutableEvidence = (await allKnowledgeRows(f.backing)).filter( + (row) => row.resourceId === f.articleId && row.kind === "evidence", + ); + expect(immutableEvidence).toHaveLength(2); + const old = accepted[0]!; + const oldRequest = await f.verificationRequest( + old.confirmed.ack, + old.input.evidence, + ); + const resetInput = { + articleId: f.articleId, + commandId: "retire-host-ledger", + expectedLedgerEpoch: 1, + }; + let state = await f.reports.reset(f.reviewer, resetInput); + expect(state).toMatchObject({ ledgerEpoch: 2, status: "resetting" }); + expect(await f.reports.reset(f.reviewer, resetInput)).toEqual(state); + expect(await f.reports.verifier.verify(oldRequest)).toBeNull(); + await expect(f.reports.report(f.agent, old.input)).rejects.toMatchObject({ + code: "ledger_epoch_changed", + }); + await expect( + f.reports.decide(f.reviewer, old.confirmed.input, "confirmed"), + ).rejects.toMatchObject({ code: "ledger_epoch_changed" }); + await expect( + f.reports.drain(f.reviewer, { articleId: f.articleId, ledgerEpoch: 1 }), + ).rejects.toMatchObject({ code: "ledger_epoch_changed" }); + await expect( + f.submit(old.confirmed.ack, old.input.evidence), + ).rejects.toMatchObject(kbEvidenceRefusal); + for (let page = 0; state.status === "resetting" && page < 4; page++) + state = await f.reports.drain(f.reviewer, { + articleId: f.articleId, + ledgerEpoch: 2, + }); + expect(state).toMatchObject({ + status: "active", + reportsRemaining: 16, + rowsRemaining: 159, + }); + expect(await f.rows()).toHaveLength(1); + expect( + (await f.app.getEvidence(f.owner, { articleId: f.articleId })).evidence, + ).toEqual(acceptedEvidence); + f.advance(70_000); + expect( + (await f.app.getEvidence(f.owner, { articleId: f.articleId })).evidence, + ).toEqual(acceptedEvidence); + expect( + await f.app.getPublishedArticle(f.customer, { articleId: f.articleId }), + ).toEqual(published); + await f.updateDraft(); + expect((await f.current()).revision.number).toBe(2); + const replay = await f.app.submitEvidence(f.agent, old.submitted.input); + expect(replay.replayed).toBe(true); + expect(replay.value).toEqual(old.submitted.result.value); + expect( + (await f.app.getEvidence(f.owner, { articleId: f.articleId })).evidence, + ).toEqual([]); + expect( + (await allKnowledgeRows(f.backing)).filter( + (row) => row.resourceId === f.articleId && row.kind === "evidence", + ), + ).toEqual(immutableEvidence); + expect( + await f.app.getPublishedArticle(f.customer, { articleId: f.articleId }), + ).toEqual(published); + expect(await f.reports.verifier.verify(oldRequest)).toBeNull(); + }); + + it("admits at most sixteen reports, then resets and drains only the real old ledger rows", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packets = []; + const proof = await f.submission(); + for (let count = 0; count < 16; count++) + packets.push(await f.report(proof)); + const full = await f.reports.ledger(f.agent, { articleId: f.articleId }); + expect(full.reportsRemaining).toBe(0); + expect(await f.rows()).toHaveLength(49); + const before = await f.rows(); + await expect(f.report()).rejects.toMatchObject({ + code: "report_capacity", + }); + expect(await f.rows()).toEqual(before); + const reset = await f.reports.reset(f.reviewer, { + articleId: f.articleId, + commandId: "reset-full-reports", + expectedLedgerEpoch: 1, + }); + expect(reset.rowsRemaining).toBe(48); + await expect( + f.reports.status(f.agent, f.key(packets[0]!.ack)), + ).rejects.toMatchObject({ code: "ledger_epoch_changed" }); + const drained = await f.reports.drain(f.reviewer, { + articleId: f.articleId, + ledgerEpoch: 2, + }); + expect(drained).toMatchObject({ + status: "active", + reportsRemaining: 16, + rowsRemaining: 159, + }); + const drain = f.observed.transactions + .filter((tx) => tx.collection === f.namespace) + .at(-1)!; + expect( + drain.actions.filter((action) => action.action === "delete"), + ).toHaveLength(48); + expect(await f.rows()).toHaveLength(1); + expect((await f.report()).ack.ledgerEpoch).toBe(2); + }); + + it("preserves reset capacity at the 160-row history ceiling and drains in no more than four 48-row batches", async () => { + const f = await evidenceReportsHistoryFixture(await createStore()); + const { ack, proof, rows } = f.preparedHistory; + const installed = f.observed.transactions.filter( + (transaction) => transaction.collection === f.namespace, + ); + expect( + installed.map((transaction) => transaction.actions.length), + ).toEqual([100, 60]); + expect( + new Set(installed.map((transaction) => transaction.partition)).size, + ).toBe(1); + expect( + installed.every((transaction) => + transaction.actions.every((action) => action.action === "insert"), + ), + ).toBe(true); + expect(await f.rows()).toEqual(rows); + expect(rows).toHaveLength(160); + const confirmed = await f.reports.read(f.reviewer, f.key(ack)); + expect(confirmed).toMatchObject({ + status: "confirmed", + submittedBy: f.agent.principalId, + evidence: proof, + confirmation: { reviewerId: f.reviewer.principalId }, + }); + expect( + await f.reports.verifier.verify( + await f.verificationRequest(ack, proof), + ), + ).toMatchObject({ id: ack.receipt, verifiedBy: f.reviewer.principalId }); + expect( + (await f.reports.ledger(f.agent, { articleId: f.articleId })) + .rowsRemaining, + ).toBe(0); + const before = await f.rows(); + await expect(f.decide(ack, "pending")).rejects.toMatchObject({ + code: "report_capacity", + }); + await expect(f.report(proof)).rejects.toMatchObject({ + code: "report_capacity", + }); + expect(await f.rows()).toEqual(before); + let state = await f.reports.reset(f.reviewer, { + articleId: f.articleId, + commandId: "reset-full-history", + expectedLedgerEpoch: 1, + }); + let batches = 0; + while (state.status === "resetting" && batches < 4) { + const beforeRows = (await f.rows()).length; + state = await f.reports.drain(f.reviewer, { + articleId: f.articleId, + ledgerEpoch: 2, + }); + expect(beforeRows - (await f.rows()).length).toBeLessThanOrEqual(48); + batches++; + } + expect(batches).toBe(4); + expect(state.status).toBe("active"); + expect(await f.rows()).toHaveLength(1); + expect((await f.report()).ack.ledgerEpoch).toBe(2); + }); + + it("supports the existing explicit host namespace and fresh factory replacement without reinterpreting receipts", async () => { + const f = await evidenceReportsFixture(await createStore(), { + collectionName: "pegma-dev.knowledge-evidence.v1", + }); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + const replacement = f.freshReports(); + expect(await replacement.status(f.agent, f.key(confirmed.ack))).toEqual({ + ...confirmed.ack, + status: "confirmed", + }); + expect( + await replacement.verifier.verify( + await f.verificationRequest(confirmed.ack, packet.input.evidence), + ), + ).toMatchObject({ + id: confirmed.ack.receipt, + verifiedBy: f.reviewer.principalId, + }); + await f.submit(confirmed.ack, packet.input.evidence); + }); + + it("round-trips slash, reserved-key and Unicode article identities through the default portable layout", async () => { + const articleId = "article/export#?\\folder-雪-🧪"; + const f = await evidenceReportsFixture(await createStore(), { + articleId, + }); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + await f.submit(confirmed.ack, packet.input.evidence); + expect( + (await f.reports.read(f.reviewer, f.key(confirmed.ack))).articleId, + ).toBe(articleId); + const physical = await f.physicalRows(); + expect(physical).toHaveLength(6); + expect(physical.every((item) => item.value.articleId === articleId)).toBe( + true, + ); + for (const item of physical) { + expect(item.key.partition).not.toBe(articleId); + expect(item.key.partition).not.toMatch(/[\/\\#?\u0000-\u001f\u007f]/u); + expect(item.key.id).not.toMatch(/[\/\\#?\u0000-\u001f\u007f]/u); + } + }); + + it("round-trips a maximum ASCII report beyond one native string property and qualifies its actual KB evidence", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await maximumAsciiReport(f); + const view = await f.reports.read(f.reviewer, f.key(packet.ack)); + expect(view.report).toEqual(packet.input.report); + expect(view.evidence).toEqual(packet.input.evidence); + const confirmed = await f.decide(packet.ack); + const retained = (await f.physicalRows()).find((row) => + row.value.id.startsWith("report:"), + )!; + const bytes = new TextEncoder().encode(retained.value.payload).byteLength; + expect(bytes).toBe(retained.value.payload.length); + expect(retained.value.payload.length).toBeGreaterThan(32_768); + expect(bytes).toBeLessThanOrEqual(60_000); + const raw = await f.rawRows(); + expect(raw).toHaveLength((await f.physicalRows()).length); + for (const row of raw) { + expect(row.value).not.toHaveProperty("payload"); + for (const value of Object.values(row.value)) { + expect( + value === null || + ["string", "number", "boolean"].includes(typeof value), + ).toBe(true); + if (typeof value === "string") + expect(value.length).toBeLessThanOrEqual(32_768); + } + } + await f.submit(confirmed.ack, packet.input.evidence); + const accepted = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + expect(accepted.evidence[0]?.steps).toEqual(packet.input.evidence.steps); + expect(accepted.evidence[0]?.attestation.id).toBe(confirmed.ack.receipt); + const workflow = await f.report( + await f.submission("walkthrough-workflow"), + ); + await f.submit( + (await f.decide(workflow.ack)).ack, + workflow.input.evidence, + ); + await f.publish(); + expect( + ( + await f.app.getPublishedArticle(f.customer, { + articleId: f.articleId, + }) + ).revision, + ).toBe(1); + }); + + it.each(["missing", "extra", "count", "UTF8 bound"] as const)( + "refuses %s corruption in actual portable chunks without accepting a previously valid receipt or writing rows", + async (defect) => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await maximumAsciiReport(f); + const confirmed = await f.decide(packet.ack); + const request = await f.verificationRequest( + confirmed.ack, + packet.input.evidence, + ); + expect(await f.reports.verifier.verify(request)).toMatchObject({ + id: confirmed.ack.receipt, + verifiedBy: f.reviewer.principalId, + }); + const saved = (await f.rawRows()).find( + (row) => + typeof row.value.id === "string" && + row.value.id.startsWith("report:"), + )!; + if (typeof saved.value.partCount !== "number") + throw new Error("Expected the actual portable chunk format"); + expect(saved.value.partCount).toBeGreaterThanOrEqual(3); + const corrupted = { ...saved.value }; + if (defect === "missing") delete corrupted.part1; + else if (defect === "extra") corrupted.part99 = "UNEXPECTED_PART"; + else if (defect === "count") corrupted.partCount = 7; + else { + // Every individual property remains portable; the joined UTF-8 + // payload exceeds the independent logical-record byte ceiling. + for (let index = 0; index < 3; index++) + corrupted["part" + index] = "雪".repeat(12_000); + } + expect(await f.replaceRaw(saved, corrupted)).toBe(true); + const before = await f.rawRows(); + const writes = f.observed.transactions.length; + await expect( + f.reports.read(f.reviewer, f.key(confirmed.ack)), + ).rejects.toMatchObject({ + ...unavailable, + stage: "report_read", + message: "Knowledge evidence report ledger is unavailable.", + }); + expect(await f.reports.verifier.verify(request)).toBeNull(); + await expect( + f.submit(confirmed.ack, packet.input.evidence), + ).rejects.toMatchObject(kbEvidenceRefusal); + expect(await f.rawRows()).toEqual(before); + expect(f.observed.transactions).toHaveLength(writes); + expect(JSON.stringify(f.logger.log.mock.calls)).not.toContain( + packet.input.report.details, + ); + }, + ); + + it("preserves an explicitly selected compatible raw ledger and does not automatically detect it as portable", async () => { + const f = await evidenceReportsFixture(await createStore(), { + articleId: "historical-article", + collectionName: "pegma-dev.knowledge-evidence.v1", + storageLayout: "legacy-raw-v1", + }); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + const before = await f.rows(); + const physical = await f.physicalRows(); + expect( + physical.every( + (item) => + item.key.partition === f.articleId && item.key.id === item.value.id, + ), + ).toBe(true); + const retained = f.freshReports({ storageLayout: "legacy-raw-v1" }); + expect(await retained.status(f.agent, f.key(confirmed.ack))).toEqual({ + ...confirmed.ack, + status: "confirmed", + }); + expect(await retained.report(f.agent, packet.input)).toEqual(packet.ack); + const request = await f.verificationRequest( + confirmed.ack, + packet.input.evidence, + ); + expect(await retained.verifier.verify(request)).toMatchObject({ + id: confirmed.ack.receipt, + verifiedBy: f.reviewer.principalId, + }); + const portableProbe = f.freshReports({ storageLayout: "portable-v1" }); + expect( + await portableProbe.ledger(f.agent, { articleId: f.articleId }), + ).toMatchObject({ reportsRemaining: 16, ledgerEpoch: 1 }); + await expect( + portableProbe.status(f.agent, f.key(packet.ack)), + ).rejects.toMatchObject({ code: "report_not_found" }); + expect(await portableProbe.verifier.verify(request)).toBeNull(); + expect(await f.rows()).toEqual(before); + await f.submit(confirmed.ack, packet.input.evidence); + }); + + it("keeps explicit raw-layout slash identities on compatible stores and refuses them on Azure without escaping or falling back", async () => { + const f = await evidenceReportsFixture(await createStore(), { + storageLayout: "legacy-raw-v1", + }); + expect(f.articleId).toBe("article/export"); + if (backend === "Azurite") { + await expect(f.report()).rejects.toMatchObject({ + ...unavailable, + stage: "head_read", + }); + expect(await f.rows()).toEqual([]); + } else { + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + await f.submit(confirmed.ack, packet.input.evidence); + expect( + (await f.physicalRows()).every( + (item) => item.key.partition === f.articleId, + ), + ).toBe(true); + expect( + await f + .freshReports({ storageLayout: "legacy-raw-v1" }) + .status(f.agent, f.key(confirmed.ack)), + ).toEqual({ ...confirmed.ack, status: "confirmed" }); + } + }); + + it.each(["legacy-raw-v1", "portable-v1"] as const)( + "refuses a nonempty headless %s partition without changing opaque unversioned history", + async (storageLayout) => { + const f = await evidenceReportsFixture(await createStore(), { + articleId: "historical-article", + storageLayout, + }); + const input = await f.reportInput(); + const reportId = "00000000-0000-4000-8000-000000000001"; + const commandId = "a".repeat(64); + // These are opaque pre-epoch logical envelopes, not output from an old + // producer invocation and not a migration or valid report attestation. + const rows = [ + "report:" + reportId, + "command:" + commandId, + "audit:command:" + commandId, + ].map((id) => ({ + articleId: f.articleId, + id, + payload: JSON.stringify({ + articleId: f.articleId, + reportId, + opaque: "PRE_EPOCH_PRIVATE_HISTORY", + }), + })); + for (const row of rows) + expect((await f.insertOpaqueRow(row)).inserted).toBe(true); + const before = await f.rawRows(); + expect(before).toHaveLength(3); + expect(before.some((row) => row.value.id === "head")).toBe(false); + if (storageLayout === "legacy-raw-v1") { + for (const row of before) { + expect(Object.keys(row.value).sort()).toEqual([ + "articleId", + "id", + "payload", + ]); + expect(row.key).toEqual({ + partition: f.articleId, + id: row.value.id, + }); + } + } + const writes = f.observed.transactions.length; + for (const operation of [ + () => f.reports.ledger(f.agent, { articleId: f.articleId }), + () => f.reports.report(f.agent, input), + () => + f.reports.reset(f.reviewer, { + articleId: f.articleId, + commandId: "refuse-headless-reset", + expectedLedgerEpoch: 1, + }), + () => + f.reports.drain(f.reviewer, { + articleId: f.articleId, + ledgerEpoch: 1, + }), + ]) { + await expect(operation()).rejects.toMatchObject({ + ...unavailable, + stage: "head_partition_orphaned", + message: "Knowledge evidence report ledger is unavailable.", + }); + expect(await f.rawRows()).toEqual(before); + expect(f.observed.transactions).toHaveLength(writes); + } + }, + ); + + it("admits a genuinely empty article partition while another article already has report history", async () => { + const f = await evidenceReportsFixture(await createStore()); + await f.report(); + const existing = await f.rawRows(); + const articleId = "article/second-export"; + await f.app.createDraft(f.agent, { + ...f.command("second-report-article", 0), + articleId, + collectionId: f.collectionId, + draft: draft("walkthrough"), + }); + f.advance(2_000); + const current = await f.app.getDraft(f.agent, { articleId }); + const ledger = await f.reports.ledger(f.agent, { articleId }); + expect(ledger).toMatchObject({ + articleId, + ledgerEpoch: 1, + reportsRemaining: 16, + rowsRemaining: 159, + }); + const accepted = await f.reports.report(f.agent, { + commandId: "first-report-for-second-article", + articleId, + ledgerEpoch: ledger.ledgerEpoch, + evidence: evidence(current.revision), + report: { + summary: "Second synthetic export report", + details: "Independent empty article partition admission", + }, + }); + expect( + await f.reports.status(f.agent, { + articleId, + ledgerEpoch: accepted.ledgerEpoch, + reportId: accepted.reportId, + }), + ).toEqual({ ...accepted, status: "pending" }); + expect(await f.rawRows()).toEqual(existing); + }); + + it("isolates identical article inputs in independently declared report namespaces", async () => { + const f = await evidenceReportsFixture(await createStore()); + const first = await f.report(); + const other = f.freshReports({ + collectionName: "observatory.knowledge-reports.v1", + }); + const second = await other.report(f.agent, first.input); + expect(second.reportId).not.toBe(first.ack.reportId); + await expect( + other.status(f.agent, f.key(first.ack)), + ).rejects.toMatchObject({ code: "report_not_found" }); + await expect( + f.reports.status(f.agent, f.key(second)), + ).rejects.toMatchObject({ code: "report_not_found" }); + expect(await f.rows()).toHaveLength(4); + }); + + it("validates required configuration, reserved KB namespaces and human-only permission names", async () => { + const f = await evidenceReportsFixture(await createStore()); + for (const collectionName of [ + "", + "../reports", + "reports/name", + "a".repeat(129), + "knowledge-base.records.v1", + "knowledge-base.retrieval.v1", + ]) + expect(() => f.freshReports({ collectionName })).toThrowError( + KnowledgeEvidenceReportsError, + ); + for (const permission of [ + "", + "human permission", + "Human.confirm", + "a".repeat(256), + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, + ]) + expect(() => + f.freshReports({ confirmationPermission: permission }), + ).toThrowError(KnowledgeEvidenceReportsError); + for (const storageLayout of [null, "automatic", "legacy"]) + expect(() => + Reflect.apply(createKnowledgeEvidenceReports, undefined, [ + { + ...f.baseOptions, + storageLayout, + }, + ]), + ).toThrowError(KnowledgeEvidenceReportsError); + for (const field of ["clock", "store", "resolvePrincipal", "readContext"]) + expect(() => + Reflect.apply(createKnowledgeEvidenceReports, undefined, [ + { + ...f.baseOptions, + [field]: undefined, + }, + ]), + ).toThrowError(KnowledgeEvidenceReportsError); + expect(await f.rows()).toEqual([]); + }); + + it("rejects unknown runtime command fields and oversized reports without appending ledger rows", async () => { + const f = await evidenceReportsFixture(await createStore()); + const input = await f.reportInput(); + await expect( + Reflect.apply(f.reports.report, f.reports, [ + f.agent, + { + ...input, + passed: true, + }, + ]), + ).rejects.toMatchObject({ code: "invalid_request" }); + await expect( + f.reports.report(f.agent, { + ...input, + report: { ...input.report, details: "x".repeat(16_001) }, + }), + ).rejects.toMatchObject({ code: "invalid_request" }); + await expect( + f.reports.report(f.agent, { + ...input, + evidence: { + ...input.evidence, + steps: Array.from({ length: 16 }, () => '"'.repeat(1_000)), + }, + report: { ...input.report, details: '"'.repeat(16_000) }, + }), + ).rejects.toMatchObject({ code: "report_too_large" }); + expect(await f.rows()).toEqual([]); + }); + + it.each(["principal", "context"] as const)( + "sanitizes a failed %s port without trusting its exception or losing confirmation history", + async (port) => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + const request = await f.verificationRequest( + confirmed.ack, + packet.input.evidence, + ); + const before = await f.rows(); + const canary = "PRIVATE_EXTERNAL_PORT_EXCEPTION"; + if (port === "principal") + f.hooks.beforeResolve = async () => { + throw new Error(canary); + }; + else + f.hooks.afterContext = async () => { + throw new Error(canary); + }; + await expect( + f.reports.read(f.reviewer, f.key(packet.ack)), + ).rejects.toMatchObject({ + ...unavailable, + stage: port === "principal" ? "principal_resolve" : "context_read", + message: "Knowledge evidence report ledger is unavailable.", + }); + expect(await f.reports.verifier.verify(request)).toBeNull(); + expect(await f.rows()).toEqual(before); + expect(JSON.stringify(f.logger.log.mock.calls)).not.toContain(canary); + }, + ); + + it.each(["articleId", "ledgerEpoch", "reportId"] as const)( + "refuses a payload-only %s mismatch during list without returning hints or writing rows", + async (field) => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const rows = await f.physicalRows(); + const saved = rows.find((item) => item.value.id.startsWith("report:"))!; + const head = rows.find((item) => item.value.id === "head")!; + const payload = JSON.parse(saved.value.payload); + payload[field] = + field === "ledgerEpoch" + ? packet.ack.ledgerEpoch + 1 + : field === "articleId" + ? "article/other" + : "different-report-id"; + expect( + await f.replaceRow(saved, { + ...saved.value, + payload: JSON.stringify(payload), + }), + ).toBe(true); + const before = await f.physicalRows(); + expect(before.find((item) => item.value.id === "head")).toEqual(head); + expect(before).toHaveLength(rows.length); + expect( + before.find((item) => item.value.id === saved.value.id)?.key, + ).toEqual(saved.key); + const writes = f.observed.transactions.length; + await expect( + f.reports.list(f.reviewer, { articleId: f.articleId }), + ).rejects.toMatchObject({ + ...unavailable, + stage: "report_identity", + message: "Knowledge evidence report ledger is unavailable.", + }); + expect(await f.physicalRows()).toEqual(before); + expect(f.observed.transactions).toHaveLength(writes); + }, + ); + + it("detects a changed stored report body rather than treating a previously issued receipt as authority", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + const stored = (await f.physicalRows()).find((row) => + row.value.id.startsWith("report:"), + )!; + const value = JSON.parse(stored.value.payload); + value.report.details = "CORRUPTED_UNREVIEWED_ARTIFACT"; + expect( + await f.replaceRow(stored, { + ...stored.value, + payload: JSON.stringify(value), + }), + ).toBe(true); + expect( + await f.reports.verifier.verify( + await f.verificationRequest(confirmed.ack, packet.input.evidence), + ), + ).toBeNull(); + await expect( + f.submit(confirmed.ack, packet.input.evidence), + ).rejects.toMatchObject(kbEvidenceRefusal); + }); + + it("maps corrupt real stored heads and dependency failures to safe domain stages", async () => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + const request: EvidenceVerificationRequest = await f.verificationRequest( + confirmed.ack, + packet.input.evidence, + ); + const canary = "PRIVATE_DEPENDENCY_OR_ROW_BODY"; + f.observed.beforeRead(async (trace) => { + if (trace.collection === f.namespace) throw new Error(canary); + }); + await expect( + f.reports.ledger(f.agent, { articleId: f.articleId }), + ).rejects.toMatchObject({ + ...unavailable, + stage: "head_read", + message: "Knowledge evidence report ledger is unavailable.", + }); + f.logger.log.mockImplementation(() => { + throw new Error("PRIVATE_LOGGER_FAILURE"); + }); + expect(await f.reports.verifier.verify(request)).toBeNull(); + f.observed.beforeRead(undefined); + const head = (await f.physicalRows()).find( + (row) => row.value.id === "head", + )!; + expect( + await f.replaceRow(head, { + ...head.value, + payload: JSON.stringify({ body: canary }), + }), + ).toBe(true); + await expect( + f.reports.ledger(f.agent, { articleId: f.articleId }), + ).rejects.toMatchObject({ + ...unavailable, + stage: "head_decode", + message: "Knowledge evidence report ledger is unavailable.", + }); + expect(await f.reports.verifier.verify(request)).toBeNull(); + expect(JSON.stringify(f.logger.log.mock.calls)).not.toContain(canary); + }); + }); +} From e77d791848054095aca5f76f6a0faba1dcfe1099 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sun, 8 Nov 2026 15:35:55 -0500 Subject: [PATCH 2/5] [KB-04] Request the restricted scope explicitly in packed proof --- scripts/agent-protocol-fixture.mjs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/scripts/agent-protocol-fixture.mjs b/scripts/agent-protocol-fixture.mjs index 1fe6114..0ce2e42 100644 --- a/scripts/agent-protocol-fixture.mjs +++ b/scripts/agent-protocol-fixture.mjs @@ -888,10 +888,25 @@ async function authorization( bootstrap.onerror = () => {}; owned.push(initial, bootstrap); let redirected = false; - try { - await bootstrap.connect(initial); - } catch (error) { - assert.ok(error instanceof UnauthorizedError); + if (isDeepStrictEqual(requestedScopes, scopes)) { + try { + await bootstrap.connect(initial); + } catch (error) { + assert.ok(error instanceof UnauthorizedError); + redirected = true; + } + } else { + // The SDK prefers discovered scopes_supported over clientMetadata.scope. + // Its public explicit-scope option selects this deliberately narrower grant + // without altering the real resource metadata, token or consent boundary. + assert.equal( + await auth(provider.provider, { + serverUrl: host.resource, + scope: requestedScopes.join(" "), + fetchFn: request, + }), + "REDIRECT", + ); redirected = true; } assert.equal(redirected, true); @@ -1362,6 +1377,7 @@ async function runReportProof() { const readOnly = await authorization(host, owned, false, [ knowledgeAgentScopes.draftRead, ]); + assert.equal(readOnly.tokens().scope, knowledgeAgentScopes.draftRead); const forbidden = await mcpCall( readOnly.client, "getValidationRequirements", From 58aefc21770b6af976bce5cb15f32f8c10fc4dfc Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sun, 8 Nov 2026 16:50:54 -0500 Subject: [PATCH 3/5] Fix reviewed evidence authority, replay and MCP boundaries --- docs/AGENT_API.md | 32 +- docs/AGENT_WORKFLOW.md | 16 +- docs/COLLECTIONS.md | 8 +- docs/EVIDENCE_REPORTS.md | 29 +- docs/HOST_COMPOSITION.md | 8 +- docs/RETRIEVAL.md | 8 +- docs/SOURCE_PREPARATION.md | 38 +- examples/composition/README.md | 9 +- .../application/src/evidence-reports-types.ts | 7 + packages/application/src/evidence-reports.ts | 135 +++++- packages/core/src/index.ts | 1 + packages/mcp/src/dispatcher.ts | 88 +++- packages/mcp/src/schemas.ts | 14 +- scripts/agent-protocol-fixture.mjs | 14 + test/README.md | 11 +- test/evidence-reports-fixtures.ts | 13 +- tests/agent-reports.test.ts | 317 +++++++++++-- tests/evidence-reports.test.ts | 438 ++++++++++++++++++ 18 files changed, 1049 insertions(+), 137 deletions(-) diff --git a/docs/AGENT_API.md b/docs/AGENT_API.md index ac5172f..d8ab4db 100644 --- a/docs/AGENT_API.md +++ b/docs/AGENT_API.md @@ -6,7 +6,7 @@ existing `KnowledgeBaseApplication`; neither introduces an authorization engine or another article lifecycle. The KB `0.1.0` packages completed manual bootstrap without OIDC provenance. All four `0.1.1` packages have since completed verified trusted publication. The current verified KB -release is [`0.1.2`](BOOTSTRAP.md#verified-knowledge-base-release). +release is [`0.1.2`](BOOTSTRAP.md#current-verified-012-release). Optional report mode is new unpublished `0.1.3` candidate source, with its own review, gates and verified trusted release pending. Agent Access's verified public `0.1.1` producer prerequisite is closed; see the @@ -125,16 +125,27 @@ body-free `reportStatus: { ledgerEpoch, reportId, receipt, reportGeneration, status: "pending" | "confirmed" | "rejected" }`. No report body, reviewer, private accepted evidence or trusted-attester registry is exposed. An epoch mismatch conflicts; another submitter's report is not found. +The input variant selects the output schema: a report-aware result must contain +valid bounded report metadata. Malformed extended port results are unavailable, +not silently reduced to legacy requirements. Configured legacy inputs still +receive the legacy result. Polling rechecks the report DTO after its other +awaited reads; observed receipt, generation or status drift conflicts, and a +fresh poll obtains a new point-in-time view. It is not a global atomic snapshot. For report submission, the existing `submitEvidence` tool accepts strictly `{ commandId, correlationId, expectedGeneration, articleId, evidence, ledgerEpoch, report: { summary, details } }`, with **no `receipt` field**. `evidence` remains the whole original `EvidenceSubmission`; `summary` is at most 1,000 characters and `details` at most 16,000, within the existing complete -request bounds. Admission checks the exact current article generation and +request bounds. New admission checks the exact current article generation and ledger epoch. The result is `{ kind: "pending-human-review", ledgerEpoch, reportId, receipt, -reportGeneration }`, with a receipt bounded to 512 UTF-8 bytes. This records a +reportGeneration }`, with the receipt's **JSON-encoded string** bounded to 512 +UTF-8 bytes, including its surrounding quotes and any escapes. This also applies +to custom host report ports: a receipt of 512 ASCII letters encodes to 514 +bytes and is rejected; quotes and backslashes require further escaping. The +complete acknowledgement still fits the existing +2,048-byte minimum response budget; that budget is unchanged. This records a private report only: it is not `{ value, replayed }`, does not accept KB evidence, and does not change the article generation. Keep that distinction in clients. @@ -161,8 +172,19 @@ do not independently authenticate a host grant. Report writes and article reads/commits are separate. A later fence failure can withhold a response after a report was queued; conflict or unavailability does not prove rollback. Retry an uncertain report command with the same ID -and exact input under fresh authority. Report epoch/generation conflicts and -resetting ledgers map to `conflict`; report bounds/capacity to `capacity`; +and exact input under fresh authority, including the original +`expectedGeneration`. The dispatcher forwards it as the shared service's +optional `expectedArticleGeneration`, bound into the command fingerprint when +present. Exact replay lookup precedes the new-admission generation check: a +retry can recover its historical acknowledgement at a stable newer article +generation, while changing the expected generation on the same command +conflicts. New commands with a wrong generation are not admitted. Custom report +ports must preserve this generation-binding/replay contract as well as the DTO +shape. The observed before/after draft fence still applies, so a change during +recovery can withhold that response again. A recovered acknowledgement does not +establish current review status or receipt validity; poll owner-only status +before using it. Report epoch/generation conflicts and resetting ledgers map to +`conflict`; report bounds/capacity to `capacity`; missing grants to `forbidden`; unconfirmed or altered receipts fail actual evidence qualification with `prerequisite`. No agent report-listing, human decision, reset/drain, private-evidence read or publication tool is added. diff --git a/docs/AGENT_WORKFLOW.md b/docs/AGENT_WORKFLOW.md index 1ffe27a..033d245 100644 --- a/docs/AGENT_WORKFLOW.md +++ b/docs/AGENT_WORKFLOW.md @@ -6,7 +6,7 @@ application. [KB-05 release-preparation source](https://github.com/pegma-dev/kno is also merged. All four KB `0.1.0` packages completed manual bootstrap and exact-byte postflight without OIDC provenance. All four `0.1.1` packages have since completed verified trusted publication, followed by the current verified -[`0.1.2` release](BOOTSTRAP.md#verified-knowledge-base-release). +[`0.1.2` release](BOOTSTRAP.md#current-verified-012-release). Optional human-report mode is unpublished `0.1.3` candidate source with its own review/release gates. This document describes the composition and retained acceptance contract, not a live service @@ -129,6 +129,8 @@ reportGeneration }` and exact command input. This acknowledges a private owner's opaque receipt/generation/status. Pending means wait; rejected or changed/expired context requires a fresh authorized workflow. Polling never exposes private report bodies, reviewers, accepted evidence or registries. + Observed report receipt/generation/status drift conflicts; retry the poll + for a fresh point-in-time view, not an atomic cross-system snapshot. 5. After confirmation, read the current draft generation and use the original receipt-bearing `submitEvidence` input with the same exact evidence and report receipt. First confirmation preserves that receipt. Explicit staff @@ -146,6 +148,18 @@ separate; a final conflict or lost response can follow a queued report without rolling it back. See [report retention and replay](EVIDENCE_REPORTS.md#capacity-retention-and-replay) for epoch reset, receipt cycles and bounded recovery. +If a report acknowledgement is lost, retry that exact report command under +fresh authority with its **original** `expectedGeneration`, even if the article +has since advanced. The dispatcher forwards this generation as the shared +report service's optional `expectedArticleGeneration`; exact replay precedes +new-admission checks. At a stable newer generation the accepted command returns +its historical acknowledgement without another report write. Changing the +expected generation on that same command conflicts, and a new command with a +stale generation is refused. The observed draft fence can still withhold a +response if the article changes during recovery. After recovering the report +key, poll its status: the acknowledgement does not establish the current human +decision, receipt cycle or eligibility for actual KB evidence acceptance. + For an uncertain mutation result, authenticate again and retry the same `commandId` and exact semantic input, including the original `expectedGeneration`. An accepted replay returns its historical bounded diff --git a/docs/COLLECTIONS.md b/docs/COLLECTIONS.md index 3f09294..3535654 100644 --- a/docs/COLLECTIONS.md +++ b/docs/COLLECTIONS.md @@ -12,9 +12,11 @@ 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). 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. +[current verified `0.1.2` release](BOOTSTRAP.md#current-verified-012-release) is +complete; the unpublished `0.1.3` human-report source candidate, real-host +acceptance, and production readiness retain their own gates. The earlier +`0.1.1` release has a separate +[historical receipt](BOOTSTRAP.md#historical-verified-011-release). ## Partition and authority rules diff --git a/docs/EVIDENCE_REPORTS.md b/docs/EVIDENCE_REPORTS.md index 806cf4a..fc4dc43 100644 --- a/docs/EVIDENCE_REPORTS.md +++ b/docs/EVIDENCE_REPORTS.md @@ -62,6 +62,15 @@ submission: article revision/content hash, validation policy, check/test kind, applicability/build, steps, result, original execution time, runner, and artifact IDs/hashes. The authenticated context supplies the submitting principal. +The optional `expectedArticleGeneration` is a nonnegative safe integer. When +supplied, it is part of the exact command fingerprint and must match the current +draft generation for **new** admission. An exact accepted replay is looked up +before that admission check, so retry the original value even after another +article mutation. Changing, adding or removing the bound field on the same +command conflicts. Omitting it preserves the existing legacy fingerprints; +the service does not invent a default generation. The agent dispatcher passes +its wire `expectedGeneration` through this field. + | Method | Purpose and authority | | ---------------- | ------------------------------------------------------------------------------------------------------------- | | `ledger` | Body-free current epoch/capacity state; requires current `evidenceSubmit`. | @@ -72,8 +81,13 @@ IDs/hashes. The authenticated context supplies the submitting principal. | `reset`, `drain` | Authorized bounded ledger retention/recovery. | Every staff method requires the configured `confirmationPermission` plus -`draftRead` and `evidenceRead`, under current same-principal authority. The full -view includes the report/submission, hashes, exact current draft/requirements, +`draftRead`, `evidenceRead`, and either `evidenceSubmit` or `draftWrite`, under +current same-principal authority. The recommended minimum human reviewer has +exactly the confirmation permission, `draftRead`, `evidenceRead` and +`evidenceSubmit`: neither an Admin role nor `draftWrite` is required. The +either/or requirement supplies the public `getValidationRequirements` read +prerequisite. Choose `evidenceSubmit` to review without draft-editing authority. +The full view includes the report/submission, hashes, exact current draft/requirements, `reviewBindingHash`, `expectedReportGeneration`, and any confirmation. Keep these private; the agent's body-free `status` is not a staff listing or report download. Render untrusted report text safely and do not fetch submitted links. @@ -169,9 +183,14 @@ call's full-partition integrity read. Resume after interruption until it is admission capacity while active and rows left to delete while resetting. Exact accepted report/decision retries under current authority return historical -acknowledgements within the active epoch, without repeating transitions. An old -acknowledgement does not prove that its receipt cycle is still current after -reassessment. Reset ends that epoch's replay horizon. The head retains a bounded +acknowledgements within the active epoch, without repeating transitions. An +exact report retry can recover its lost acknowledgement at a stable newer +article generation; the original bound generation is not updated on retry. +Current principal authority and epoch fences still apply. Transport target +reads and observed draft fences can withhold the response again if the article +changes during recovery. Poll owner-only `status` after recovery: an old +acknowledgement does not prove that its receipt cycle or review status is still +current after reassessment. Reset ends that epoch's replay horizon. The head retains a bounded history seal and only the latest reset intent: its exact retry returns current metadata without another reset; after a subsequent reset, the older intent conflicts. It is not an indefinite archive of drained reports or Audit receipts. diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index f3eb5f1..828ab1f 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -11,9 +11,11 @@ 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. 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. +trusted release has a [historical receipt](BOOTSTRAP.md#historical-verified-011-release). +The current four-package `0.1.2` atomic draft/source release is +[verified](BOOTSTRAP.md#current-verified-012-release). Source `0.1.3` is the +unpublished human-reviewed report 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 diff --git a/docs/RETRIEVAL.md b/docs/RETRIEVAL.md index b9a8ae2..00489d5 100644 --- a/docs/RETRIEVAL.md +++ b/docs/RETRIEVAL.md @@ -8,9 +8,11 @@ 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. 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 +completed [historical verified trusted publication](BOOTSTRAP.md#historical-verified-011-release), +followed by the current +[verified `0.1.2` release](BOOTSTRAP.md#current-verified-012-release). +Source `0.1.3` is the unpublished human-report 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). The candidate's verified trusted release, real-host acceptance, and production activation retain their own gates. diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md index 971560a..cd18820 100644 --- a/docs/SOURCE_PREPARATION.md +++ b/docs/SOURCE_PREPARATION.md @@ -50,16 +50,18 @@ postflight at **2026-11-07T21:56:24Z**, without OIDC provenance; see the [operator-recorded bootstrap receipt](BOOTSTRAP.md#recorded-manual-bootstrap-receipt). 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 | +[historical release receipt](BOOTSTRAP.md#historical-verified-011-release). +The subsequent SD-03 atomic draft/source `0.1.2` release is now +[verified](BOOTSTRAP.md#current-verified-012-release). Source `0.1.3` is the +unpublished human-report 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 | Verified `0.1.1`/`0.1.2` release receipts are separate; `0.1.3` 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. @@ -296,11 +298,12 @@ 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. -The KB `0.1.1` trusted release has completed complete-set registry +The current KB `0.1.2` 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. +[receipt](BOOTSTRAP.md#current-verified-012-release) is separate from these +historical source records. The unpublished `0.1.3` human-report source candidate +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) @@ -321,8 +324,9 @@ 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. -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. +The verified KB `0.1.2` and Agent Access `0.1.1` producer release prerequisites +are closed. The new `0.1.3` report candidate needs its own verified release +before host adoption. 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/composition/README.md b/examples/composition/README.md index 0071b13..0e82731 100644 --- a/examples/composition/README.md +++ b/examples/composition/README.md @@ -21,9 +21,12 @@ 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, 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. +four-package `0.1.1` trusted release has a +[historical receipt](../../docs/BOOTSTRAP.md#historical-verified-011-release). +The current four-package `0.1.2` release is +[verified](../../docs/BOOTSTRAP.md#current-verified-012-release). Source `0.1.3` +is the unpublished human-report 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 diff --git a/packages/application/src/evidence-reports-types.ts b/packages/application/src/evidence-reports-types.ts index 744b4a6..1a3463a 100644 --- a/packages/application/src/evidence-reports-types.ts +++ b/packages/application/src/evidence-reports-types.ts @@ -57,6 +57,9 @@ export interface KnowledgeReportLedgerState { export interface KnowledgeEvidenceContext { readonly draft: DraftArticleDto; readonly requirements: ValidationRequirementsDto; + /** Complete current getEvidence DTO at the draft's exact generation is + * required for human qualification and verification. Pending agent report + * admission may omit private evidence; omission is never empty history. */ readonly evidence?: EvidenceDto; } @@ -85,6 +88,10 @@ export interface KnowledgeReportKey extends KnowledgeReportArticleInput { export interface SubmitKnowledgeReportInput extends KnowledgeReportArticleInput { readonly commandId: string; readonly ledgerEpoch: number; + /** Admission fence for a new command, bound into its exact replay identity + * only when present. Retry the original value; omission preserves legacy + * fingerprints and does not introduce a default generation. */ + readonly expectedArticleGeneration?: number; readonly evidence: EvidenceSubmission; readonly report: KnowledgeTestReport; } diff --git a/packages/application/src/evidence-reports.ts b/packages/application/src/evidence-reports.ts index a854f68..131fd37 100644 --- a/packages/application/src/evidence-reports.ts +++ b/packages/application/src/evidence-reports.ts @@ -4,7 +4,10 @@ import { type AccessContext, } from "@pegma/authorization-core"; import { auditEvent } from "@pegma/audit"; -import type { EvidenceSubmission } from "@pegma/knowledge-base-core"; +import { + knowledgeDigest as coreKnowledgeDigest, + type EvidenceSubmission, +} from "@pegma/knowledge-base-core"; import { knowledgePermissions, type Applicability, @@ -707,6 +710,13 @@ export function createKnowledgeEvidenceReports( ]) if (!hasPermission(access, permission)) throw new KnowledgeEvidenceReportsError("forbidden"); + // The prescribed public readContext uses getValidationRequirements, whose + // existing author-facing permission is evidenceSubmit OR draftWrite. + if ( + !hasPermission(access, knowledgePermissions.evidenceSubmit) && + !hasPermission(access, knowledgePermissions.draftWrite) + ) + throw new KnowledgeEvidenceReportsError("forbidden"); return access; } async function headVersion(articleId: string) { @@ -783,9 +793,37 @@ export function createKnowledgeEvidenceReports( value.draft.articleId !== articleId || value.draft.revision.articleId !== articleId || value.requirements.collectionId !== value.draft.revision.collectionId || - (value.evidence !== undefined && value.evidence.articleId !== articleId) + (value.evidence !== undefined && + (!isPlainObject(value.evidence) || + value.evidence.articleId !== articleId || + value.evidence.generation !== value.draft.generation || + !Array.isArray(value.evidence.evidence) || + !Array.isArray(value.evidence.revokedEvidence))) ) throw new KnowledgeEvidenceReportsUnavailableError("context_read"); + if (value.evidence !== undefined) { + const evidence = value.evidence; + stored("context_read", () => { + for (const item of evidence.revokedEvidence) { + const revoked = exactObject(item, [ + "articleRevision", + "id", + "version", + "hash", + "reason", + "revokedBy", + "revokedAt", + ]); + positive(revoked.articleRevision); + scalar(revoked.id); + positive(revoked.version); + hash(revoked.hash); + scalar(revoked.reason, 1000); + scalar(revoked.revokedBy); + timestamp(revoked.revokedAt); + } + }); + } return value; } catch (error) { if (error instanceof KnowledgeEvidenceReportsError) throw error; @@ -813,13 +851,34 @@ export function createKnowledgeEvidenceReports( report.articleHash !== (await knowledgeDigest(article)) || report.governanceHash !== (await knowledgeDigest(value.requirements)) || report.submissionHash !== (await knowledgeDigest(report.evidence)) || - value.evidence?.revokedEvidence.some( - (item) => - item.id === report.evidence.id && - item.articleRevision === report.evidence.articleRevision, - ) + value.evidence === undefined ) return false; + if (report.confirmation !== null) { + // Core revokes one exact accepted fact, including its version and human + // attestation. Reconstruct it even when current evidence was replaced; + // a separately reviewed replacement is not an identifier-wide ban. + const attestation = { + id: acknowledgement(report).receipt, + verifiedBy: report.confirmation.reviewerId, + verifiedAt: report.confirmation.confirmedAt, + }; + for (const revoked of value.evidence.revokedEvidence) { + if ( + revoked.id === report.evidence.id && + revoked.articleRevision === report.evidence.articleRevision && + revoked.hash === + (await ledgerIo("hashing", () => + coreKnowledgeDigest({ + ...report.evidence, + version: revoked.version, + attestation, + }), + )) + ) + return false; + } + } const submission = report.evidence; const requirement = value.requirements.checks.find( (item) => @@ -968,10 +1027,21 @@ export function createKnowledgeEvidenceReports( commandId, fingerprint, ); - if (accepted !== null) return accepted; + if (accepted !== null) { + await active(report.articleId, report.ledgerEpoch); + if (previousVersion === undefined) + await current(access, knowledgePermissions.evidenceSubmit); + else await staff(access); + return accepted; + } throw new KnowledgeEvidenceReportsError("report_changed"); } await active(report.articleId, report.ledgerEpoch); + // Withhold an ACK if authority changed during storage; a committed report + // or decision remains committed and is not rolled back by this refusal. + if (previousVersion === undefined) + await current(access, knowledgePermissions.evidenceSubmit); + else await staff(access); return result; } const verifier: EvidenceVerifier = { @@ -1077,16 +1147,20 @@ export function createKnowledgeEvidenceReports( async report(access, value) { value = requestData(value); access = await current(access, knowledgePermissions.evidenceSubmit); - const input = exactObject(value, [ - "commandId", - "articleId", - "ledgerEpoch", - "evidence", - "report", - ]); + const input = optionalKeysObject( + value, + ["commandId", "articleId", "ledgerEpoch", "evidence", "report"], + ["expectedArticleGeneration"], + ); const commandId = await knowledgeDigest(scalar(input.commandId)); const articleId = scalar(input.articleId); const ledgerEpoch = positive(input.ledgerEpoch); + const expectedArticleGeneration = Object.hasOwn( + input, + "expectedArticleGeneration", + ) + ? positive(input.expectedArticleGeneration, 0) + : undefined; const evidence = parseKnowledgeEvidence(input.evidence); const report = parseReport(input.report); if (evidence.articleId !== articleId) @@ -1098,6 +1172,9 @@ export function createKnowledgeEvidenceReports( commandId, articleId, ledgerEpoch, + ...(expectedArticleGeneration === undefined + ? {} + : { expectedArticleGeneration }), evidence, report, }); @@ -1108,11 +1185,17 @@ export function createKnowledgeEvidenceReports( fingerprint, ); if (accepted !== null) { - await current(access, knowledgePermissions.evidenceSubmit); await active(articleId, ledgerEpoch); + await current(access, knowledgePermissions.evidenceSubmit); return accepted; } - const hashes = await contextHashes(await context(access, articleId)); + const valueContext = await context(access, articleId); + if ( + expectedArticleGeneration !== undefined && + valueContext.draft.generation !== expectedArticleGeneration + ) + throw new KnowledgeEvidenceReportsError("report_changed"); + const hashes = await contextHashes(valueContext); const initial: ReportRecord = { ledgerEpoch, receiptGeneration: 1, @@ -1150,7 +1233,17 @@ export function createKnowledgeEvidenceReports( throw new KnowledgeEvidenceReportsError("report_not_found"); await current(access, knowledgePermissions.evidenceSubmit); await active(articleId, epoch); - return { ...acknowledgement(report), status: report.status }; + // Finite final observation after authority/head awaits. A concurrent + // human decision rotates this generation/cycle; do not return old status. + const latest = await load(articleId, epoch, report.reportId); + if ( + latest.reportGeneration !== report.reportGeneration || + latest.receiptGeneration !== report.receiptGeneration || + latest.status !== report.status || + latest.reportHash !== report.reportHash + ) + throw new KnowledgeEvidenceReportsError("report_changed"); + return { ...acknowledgement(latest), status: latest.status }; }, async list(access, value) { value = requestData(value); @@ -1263,8 +1356,8 @@ export function createKnowledgeEvidenceReports( }); const accepted = await replay(articleId, epoch, commandId, fingerprint); if (accepted !== null) { - await staff(access); await active(articleId, epoch); + await staff(access); return accepted; } const saved = await ledgerIo("report_read", () => @@ -1399,6 +1492,8 @@ export function createKnowledgeEvidenceReports( ); if (!outcome.committed) throw new KnowledgeEvidenceReportsError("ledger_changed"); + // The reset may already be durable. Refusal here withholds only its ACK. + await staff(access); return state(articleId, next); }, async drain(access, value) { @@ -1451,6 +1546,8 @@ export function createKnowledgeEvidenceReports( ); if (!outcome.committed) throw new KnowledgeEvidenceReportsError("ledger_changed"); + // Deleted rows are not restored if staff authority changed during IO. + await staff(access); return state(articleId, next); }, } satisfies KnowledgeEvidenceReports); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 2883ec4..acf56f9 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -19,6 +19,7 @@ export { type ReviewContext, } from "./articles.js"; export { + digest as knowledgeDigest, KnowledgeBaseError, knowledgeLimits, validatePolicy as validateValidationPolicy, diff --git a/packages/mcp/src/dispatcher.ts b/packages/mcp/src/dispatcher.ts index bce17bc..cb3e7bf 100644 --- a/packages/mcp/src/dispatcher.ts +++ b/packages/mcp/src/dispatcher.ts @@ -207,10 +207,20 @@ export function createKnowledgeAgentDispatcher( reports === undefined ? knowledgeAgentEnvelopeSchema : knowledgeAgentReportEnvelopeSchema; - const resultSchemas = - reports === undefined - ? knowledgeAgentResultSchemas - : knowledgeAgentReportResultSchemas; + function reportOutput( + schema: { parse(value: unknown): T }, + value: unknown, + ): T { + try { + return schema.parse( + snapshotKnowledgeAgentJson(value, limits, limits.maxResponseBytes), + ); + } catch { + throw new KnowledgeAgentBoundaryError("unavailable"); + } + } + const reportResult = + knowledgeAgentReportResultSchemas.getValidationRequirements.shape; return Object.freeze({ limits, ...(reports === undefined ? {} : { reportWorkflow: true as const }), @@ -271,9 +281,10 @@ export function createKnowledgeAgentDispatcher( access, query, ); - const ledger = await reports.ledger(access, { - articleId: input.articleId, - }); + const ledger = reportOutput( + reportResult.reportLedger, + await reports.ledger(access, { articleId: input.articleId }), + ); const lookup = input.reportLookup; if ( lookup !== undefined && @@ -283,15 +294,19 @@ export function createKnowledgeAgentDispatcher( const status = lookup === undefined ? undefined - : await reports.status(access, { - articleId: input.articleId, - ...lookup, - }); + : reportOutput( + reportResult.reportStatus.unwrap(), + await reports.status(access, { + articleId: input.articleId, + ...lookup, + }), + ); const latestRequirements = await application.getValidationRequirements(access, query); - const latestLedger = await reports.ledger(access, { - articleId: input.articleId, - }); + const latestLedger = reportOutput( + reportResult.reportLedger, + await reports.ledger(access, { articleId: input.articleId }), + ); const latest = await application.getDraft(access, { articleId: input.articleId, }); @@ -311,21 +326,41 @@ export function createKnowledgeAgentDispatcher( status.reportId !== lookup?.reportId) ) throw new KnowledgeAgentBoundaryError("unavailable"); + // Observe the bounded report DTO again after all other awaited + // fences. This does not lock a decision atomically with a response. + const latestStatus = + lookup === undefined + ? undefined + : reportOutput( + reportResult.reportStatus.unwrap(), + await reports.status(access, { + articleId: input.articleId, + ...lookup, + }), + ); + if ( + latestStatus !== undefined && + (latestStatus.ledgerEpoch !== lookup?.ledgerEpoch || + latestStatus.reportId !== lookup?.reportId) + ) + throw new KnowledgeAgentBoundaryError("unavailable"); + if (JSON.stringify(latestStatus) !== JSON.stringify(status)) + throw new KnowledgeAgentBoundaryError("conflict"); result = { ...latestRequirements, reportLedger: { ledgerEpoch: latestLedger.ledgerEpoch, status: latestLedger.status, }, - ...(status === undefined + ...(latestStatus === undefined ? {} : { reportStatus: { - ledgerEpoch: status.ledgerEpoch, - reportId: status.reportId, - receipt: status.receipt, - reportGeneration: status.reportGeneration, - status: status.status, + ledgerEpoch: latestStatus.ledgerEpoch, + reportId: latestStatus.reportId, + receipt: latestStatus.receipt, + reportGeneration: latestStatus.reportGeneration, + status: latestStatus.status, }, }), }; @@ -344,12 +379,11 @@ export function createKnowledgeAgentDispatcher( const target = await application.getDraft(access, { articleId: input.articleId, }); - if (target.generation !== input.expectedGeneration) - throw new KnowledgeAgentBoundaryError("conflict"); const ack = await reports.report(access, { commandId: input.commandId, articleId: input.articleId, ledgerEpoch: input.ledgerEpoch, + expectedArticleGeneration: input.expectedGeneration, evidence: input.evidence, report: input.report, }); @@ -386,7 +420,15 @@ export function createKnowledgeAgentDispatcher( } throw new KnowledgeAgentBoundaryError("unavailable"); } - const safe = resultSchemas[operation].safeParse(detached); + const resultSchema = + envelope.operation === "getValidationRequirements" && + "articleId" in envelope.input + ? knowledgeAgentReportResultSchemas.getValidationRequirements + : envelope.operation === "submitEvidence" && + !("receipt" in envelope.input) + ? knowledgeAgentReportResultSchemas.submitEvidence + : knowledgeAgentResultSchemas[operation]; + const safe = resultSchema.safeParse(detached); if (!safe.success) throw new KnowledgeAgentBoundaryError("unavailable"); return snapshotKnowledgeAgentJson( { apiVersion: "1", operation, result: safe.data }, diff --git a/packages/mcp/src/schemas.ts b/packages/mcp/src/schemas.ts index 851bf03..9753d31 100644 --- a/packages/mcp/src/schemas.ts +++ b/packages/mcp/src/schemas.ts @@ -319,16 +319,10 @@ const reportRequirementsResult = .strip(); export const knowledgeAgentReportResultSchemas = Object.freeze({ ...knowledgeAgentResultSchemas, - getValidationRequirements: z.union([ - reportRequirementsResult, - knowledgeAgentResultSchemas.getValidationRequirements, - ]), - submitEvidence: z.union([ - reportAcknowledgement - .extend({ kind: z.literal("pending-human-review") }) - .strip(), - acknowledgement, - ]), + getValidationRequirements: reportRequirementsResult, + submitEvidence: reportAcknowledgement + .extend({ kind: z.literal("pending-human-review") }) + .strip(), }); export function resolveKnowledgeAgentLimits( diff --git a/scripts/agent-protocol-fixture.mjs b/scripts/agent-protocol-fixture.mjs index 0ce2e42..30a25be 100644 --- a/scripts/agent-protocol-fixture.mjs +++ b/scripts/agent-protocol-fixture.mjs @@ -1436,6 +1436,18 @@ async function runReportProof() { assert.equal(replay.result.replayed, true); assert.deepEqual(replay.result.value, committed.result.value); assert.equal((await host.acceptedEvidence()).evidence.length, 1); + const reportReplay = await mcpCall( + session.client, + "submitEvidence", + reportInput, + ); + assert.deepEqual(reportReplay.result, queued.result); + const reboundReport = await mcpCall(session.client, "submitEvidence", { + ...reportInput, + expectedGeneration: committed.result.value.generation, + }); + assert.equal(reboundReport.error.code, "conflict"); + assert.equal((await host.acceptedEvidence()).evidence.length, 1); const safeDraft = await mcpCall(session.client, "getDraft", { articleId: ARTICLE, }); @@ -1458,6 +1470,8 @@ async function runReportProof() { unconfirmedReceiptRejected: true, tamperedEvidenceRejected: true, exactReplay: true, + historicalReportAckRecovered: true, + reportGenerationRebindingRejected: true, }; } finally { let cleanupFailed = false; diff --git a/test/README.md b/test/README.md index 4c1e30d..a08cd95 100644 --- a/test/README.md +++ b/test/README.md @@ -22,7 +22,7 @@ Upgrade tests use the dev-only exact registry alias `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 +The four unpublished candidate runtime packages are `0.1.3`, and the Agent Access protocol-proof pin remains `0.1.1`. `trace-store.ts` delegates every record operation to the supplied real store. @@ -89,7 +89,8 @@ 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. 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. +without OIDC provenance. The four-package KB `0.1.1` trusted release has a +[historical receipt](../docs/BOOTSTRAP.md#historical-verified-011-release), followed +by the current [verified `0.1.2` release](../docs/BOOTSTRAP.md#current-verified-012-release). +Source `0.1.3` is an unpublished human-report candidate with its own gates and +verified trusted release required; host activation gates remain open. diff --git a/test/evidence-reports-fixtures.ts b/test/evidence-reports-fixtures.ts index 3bace27..d7078a3 100644 --- a/test/evidence-reports-fixtures.ts +++ b/test/evidence-reports-fixtures.ts @@ -250,10 +250,10 @@ export async function evidenceReportsFixture( const input = await reportInput(proof); return { input, ack: await reports.report(caller, input) }; } - async function decide( + async function decisionInput( ack: KnowledgeReportAcknowledgement, - status: KnowledgeReportStatus = "confirmed", caller = reportReviewer, + status: KnowledgeReportStatus = "confirmed", ) { const view = await reports.read(caller, key(ack)); const input: DecideKnowledgeReportInput = { @@ -262,6 +262,14 @@ export async function evidenceReportsFixture( expectedReportGeneration: view.expectedReportGeneration, reviewBindingHash: view.reviewBindingHash, }; + return { view, input }; + } + async function decide( + ack: KnowledgeReportAcknowledgement, + status: KnowledgeReportStatus = "confirmed", + caller = reportReviewer, + ) { + const { view, input } = await decisionInput(ack, caller, status); return { view, input, ack: await reports.decide(caller, input, status) }; } async function submit( @@ -432,6 +440,7 @@ export async function evidenceReportsFixture( submission, reportInput, report, + decisionInput, decide, submit, verificationRequest, diff --git a/tests/agent-reports.test.ts b/tests/agent-reports.test.ts index 2d62dfe..5bbdcee 100644 --- a/tests/agent-reports.test.ts +++ b/tests/agent-reports.test.ts @@ -1,6 +1,9 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import type { KnowledgeEvidenceReports } from "@pegma/knowledge-base-application"; +import type { + KnowledgeEvidenceReports, + KnowledgeReportAcknowledgement, +} from "@pegma/knowledge-base-application"; import { createKnowledgeAgentDispatcher, createKnowledgeAgentHttp, @@ -361,6 +364,222 @@ describe.each(["HTTP", "MCP"] as const)( expect(JSON.stringify(listed.tools)).not.toContain("ledgerEpoch"); }); + it("keeps legacy requirements exact even when the report port is configured", async () => { + let calls = 0; + const f = await fixture({ + wrapReports: (reports) => ({ + ...reports, + async ledger(...args) { + calls++; + return reports.ledger(...args); + }, + async status(...args) { + calls++; + return reports.status(...args); + }, + }), + }); + const input = { + collectionId: f.collectionId, + kind: "walkthrough" as const, + }; + const actual = success( + await f.call(channel, "getValidationRequirements", input), + ); + expect(actual).toEqual( + await f.app.getValidationRequirements(f.agent, input), + ); + expect(actual).not.toHaveProperty("reportLedger"); + expect(actual).not.toHaveProperty("reportStatus"); + expect(calls).toBe(0); + }); + + it.each([ + ["ledger status", "ledger", "status", "malformed"], + ["ledger epoch", "ledger", "ledgerEpoch", 0], + ["report status", "status", "status", "malformed"], + ["report generation", "status", "reportGeneration", 0], + ["report receipt", "status", "receipt", 17], + ] as const)( + "refuses malformed trusted %s instead of stripping into legacy success", + async (_name, port, field, invalid) => { + const f = await fixture({ + wrapReports: (reports) => ({ + ...reports, + async ledger(...args) { + const value = { ...(await reports.ledger(...args)) }; + if (port === "ledger") Reflect.set(value, field, invalid); + return value; + }, + async status(...args) { + const value = { ...(await reports.status(...args)) }; + if (port === "status") Reflect.set(value, field, invalid); + return value; + }, + }), + }); + const actual = await f.report(); + const response = await f.call( + channel, + "getValidationRequirements", + f.requirementsInput({ ...actual.ack, kind: "pending-human-review" }), + ); + privateError(response, "unavailable"); + expect(response).not.toHaveProperty("result"); + }, + ); + + it.each([ + ["ASCII exact", "r".repeat(510), 512, true], + ["ASCII one over", "r".repeat(511), 513, false], + ["512 raw ASCII", "r".repeat(512), 514, false], + ["escaped quotes exact", '"'.repeat(255), 512, true], + ["escaped quotes one over", '"'.repeat(255) + "r", 513, false], + ["escaped backslashes exact", "\\".repeat(255), 512, true], + ["escaped backslashes one over", "\\".repeat(255) + "r", 513, false], + ] as const)( + "enforces the existing JSON-encoded receipt bound for %s at the minimum budget", + async (_name, receipt, bytes, accepted) => { + expect( + new TextEncoder().encode(JSON.stringify(receipt)).byteLength, + ).toBe(bytes); + const f = await fixture({ + limits: { maxResponseBytes: 2048 }, + wrapReports: (reports) => ({ + ...reports, + async report(...args) { + return { ...(await reports.report(...args)), receipt }; + }, + async status(...args) { + return { ...(await reports.status(...args)), receipt }; + }, + }), + }); + const existing = await f.report(); + const current = await f.current(); + const input = { + ...f.command("receipt-bound", current.generation), + ...(await f.reportInput()), + }; + const queued = await f.call(channel, "submitEvidence", input); + const polled = await f.call( + channel, + "getValidationRequirements", + f.requirementsInput({ + ...existing.ack, + kind: "pending-human-review", + }), + ); + if (accepted) { + expect(success(queued).receipt).toBe( + receipt, + ); + expect( + success(polled).reportStatus + ?.receipt, + ).toBe(receipt); + expect( + new TextEncoder().encode(JSON.stringify(polled)).byteLength, + ).toBeLessThanOrEqual(2048); + } else { + privateError(queued, "unavailable"); + privateError(polled, "unavailable"); + } + }, + ); + + it("recovers an exact report ACK after evidence-only generation changes and rejects generation rebinding", async () => { + const f = await fixture(); + const queued = await f.packet(channel); + await f.decide(queued.ack); + await f.submit(queued.ack, queued.input.evidence); + const current = await f.current(); + expect(current.generation).toBe(queued.input.expectedGeneration + 1); + expect(current.revision.number).toBe( + queued.input.evidence.articleRevision, + ); + const before = await f.physicalRows(); + expect( + success( + await f.call(other, "submitEvidence", queued.input), + ), + ).toEqual(queued.ack); + privateError( + await f.call(channel, "submitEvidence", { + ...queued.input, + expectedGeneration: current.generation, + }), + "conflict", + ); + privateError( + await f.call(channel, "submitEvidence", { + ...queued.input, + ...f.command("new-stale-generation", queued.input.expectedGeneration), + }), + "conflict", + ); + expect(await f.physicalRows()).toEqual(before); + expect(await f.current()).toEqual(current); + }); + + it.each(["confirmed", "pending"] as const)( + "withholds a status invalidated by a real %s decision between awaited fences", + async (decision) => { + let apply: (() => Promise) | undefined; + let observedStatus = false; + const f = await fixture({ + wrapReports: (reports) => ({ + ...reports, + async status(...args) { + const value = await reports.status(...args); + if (apply !== undefined) observedStatus = true; + return value; + }, + async ledger(...args) { + const value = await reports.ledger(...args); + if (observedStatus && apply !== undefined) { + const decide = apply; + apply = undefined; + observedStatus = false; + await decide(); + } + return value; + }, + }), + }); + const queued = await f.packet(channel); + if (decision === "pending") await f.decide(queued.ack); + const initial = await f.reports.status(f.agent, f.key(queued.ack)); + const target = await f.current(); + apply = async () => { + await f.decide(queued.ack, decision); + }; + privateError( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput(queued.ack), + ), + "conflict", + ); + const latest = await f.reports.status(f.agent, f.key(queued.ack)); + expect(latest.reportGeneration).toBe(initial.reportGeneration + 1); + expect(latest.status).toBe(decision); + if (decision === "pending") + expect(latest.receipt).not.toBe(initial.receipt); + expect(await f.current()).toEqual(target); + const fresh = success( + await f.call( + other, + "getValidationRequirements", + f.requirementsInput(queued.ack), + ), + ); + expect(fresh.reportStatus).toEqual(latest); + bodyFree(fresh); + }, + ); + it("requires both existing effective permissions for the optional extension and never grants staff capabilities", async () => { const f = await fixture(); const current = await f.current(); @@ -576,46 +795,68 @@ describe("optional native report bounds and observational fences", () => { expect((await f.current()).generation).toBe(1); }); - it("withholds a queued-report ACK after an actual draft edit without claiming report rollback", async () => { - const f = await fixture({ - wrapReports: (reports, app) => ({ - ...reports, - async report(access, input) { - expect(access.roles).toEqual([]); - expect(access.entitlements).toEqual([]); - expect(access.permissions).toEqual( - Object.values(knowledgeAgentScopes), - ); - const ack = await reports.report(access, input); - await app.updateDraft(); - return ack; + it.each(["HTTP", "MCP"] as const)( + "recovers a withheld queued-report ACK after an actual draft edit over %s without claiming rollback", + async (channel) => { + let edit = true; + let historical: KnowledgeReportAcknowledgement | undefined; + const f = await fixture({ + wrapReports: (reports, app) => ({ + ...reports, + async report(access, input) { + expect(access.roles).toEqual([]); + expect(access.entitlements).toEqual([]); + expect(access.permissions).toEqual( + Object.values(knowledgeAgentScopes), + ); + const ack = await reports.report(access, input); + if (edit) { + edit = false; + historical = ack; + await app.updateDraft(); + } + return ack; + }, + }), + }); + f.authority.current = { + ...f.authority.current, + access: { + ...f.owner, + roles: ["synthetic-admin"], + entitlements: ["synthetic-entitlement"], }, - }), - }); - f.authority.current = { - ...f.authority.current, - access: { - ...f.owner, - roles: ["synthetic-admin"], - entitlements: ["synthetic-entitlement"], - }, - }; - const current = await f.current(); - const raw = await f.reportInput(); - privateError( - await f.call("HTTP", "submitEvidence", { + }; + const current = await f.current(); + const raw = await f.reportInput(); + const input = { ...f.command("changed-after-report", current.generation), ...raw, - }), - "conflict", - ); - expect((await f.rows()).length).toBeGreaterThan(0); - expect((await f.current()).revision.number).toBe(2); - expect( - (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) - .evidence, - ).toHaveLength(0); - }); + }; + privateError(await f.call(channel, "submitEvidence", input), "conflict"); + if (historical === undefined) + throw new Error("Expected the real report write before the ACK fence"); + expect((await f.rows()).length).toBeGreaterThan(0); + const latest = await f.current(); + expect(latest.revision.number).toBe(2); + const before = await f.physicalRows(); + expect( + success( + await f.call( + channel === "HTTP" ? "MCP" : "HTTP", + "submitEvidence", + input, + ), + ), + ).toEqual({ kind: "pending-human-review", ...historical }); + expect(await f.physicalRows()).toEqual(before); + expect(await f.current()).toEqual(latest); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toHaveLength(0); + }, + ); it("withholds old report status after an actual draft edit during the status await", async () => { let edit = false; diff --git a/tests/evidence-reports.test.ts b/tests/evidence-reports.test.ts index bb66965..fb2e42e 100644 --- a/tests/evidence-reports.test.ts +++ b/tests/evidence-reports.test.ts @@ -1,4 +1,5 @@ import { + createKnowledgeBaseApplication, createKnowledgeEvidenceReports, KnowledgeEvidenceReportsError, type EvidenceVerificationRequest, @@ -44,6 +45,52 @@ async function maximumAsciiReport( return { input, ack: await f.reports.report(f.agent, input) }; } +type ReportsFixture = Awaited>; +type ReportMutation = "report" | "decide" | "reset" | "drain"; + +/** Build real public commands once so uncertain mutations can retry exactly. */ +async function reportMutation(f: ReportsFixture, operation: ReportMutation) { + if (operation === "report") { + const input = await f.reportInput(); + return { + caller: f.agent, + rowsAfterCommit: 4, + run: (): Promise => f.reports.report(f.agent, input), + }; + } + const packet = await f.report(); + if (operation === "decide") { + const { input } = await f.decisionInput(packet.ack); + return { + caller: f.reviewer, + rowsAfterCommit: 6, + run: (): Promise => + f.reports.decide(f.reviewer, input, "confirmed"), + }; + } + const input = { + articleId: f.articleId, + commandId: "postcommit-reset", + expectedLedgerEpoch: 1, + }; + if (operation === "reset") + return { + caller: f.reviewer, + rowsAfterCommit: 4, + run: (): Promise => f.reports.reset(f.reviewer, input), + }; + await f.reports.reset(f.reviewer, input); + return { + caller: f.reviewer, + rowsAfterCommit: 1, + run: (): Promise => + f.reports.drain(f.reviewer, { + articleId: f.articleId, + ledgerEpoch: 2, + }), + }; +} + for (const [backend, createStore] of storeFactories) { describe(`shared evidence reports over ${backend}`, () => { it("accepts only independently confirmed reports, completes every required check, then publishes through the actual KB", async () => { @@ -138,6 +185,70 @@ for (const [backend, createStore] of storeFactories) { ).toBe(f.owner.principalId); }); + it("qualifies every required check with exactly the four minimum reviewer permissions and a separate publisher", async () => { + const f = await evidenceReportsFixture(await createStore()); + const reviewer = access(f.reviewer.principalId, [ + confirmationPermission, + knowledgePermissions.draftRead, + knowledgePermissions.evidenceRead, + knowledgePermissions.evidenceSubmit, + ]); + f.principals.set(reviewer.principalId, reviewer); + expect(reviewer.permissions).toHaveLength(4); + expect(reviewer.permissions).not.toContain( + knowledgePermissions.draftWrite, + ); + expect(reviewer.permissions).not.toContain(knowledgePermissions.publish); + const requirements = await f.app.getValidationRequirements(f.agent, { + collectionId: f.collectionId, + kind: (await f.current()).revision.kind, + }); + for (const check of requirements.checks) { + const packet = await f.report(await f.submission(check.id)); + await expect( + f.reports.read( + access(reviewer.principalId, reviewer.permissions.slice(0, 3)), + f.key(packet.ack), + ), + ).rejects.toMatchObject({ code: "forbidden" }); + const confirmed = await f.decide(packet.ack, "confirmed", reviewer); + await f.submit(confirmed.ack, packet.input.evidence); + } + const accepted = await f.app.getEvidence(reviewer, { + articleId: f.articleId, + }); + expect(accepted.evidence).toHaveLength(requirements.checks.length); + expect( + accepted.evidence.every( + (item) => item.attestation.verifiedBy === reviewer.principalId, + ), + ).toBe(true); + const current = await f.current(); + await f.app.submitForReview(f.owner, { + ...f.command("minimum-reviewer-qualified", current.generation), + articleId: f.articleId, + }); + const reviewed = await f.app.getReview(f.owner, { + articleId: f.articleId, + }); + const publication = { + ...f.command("separate-human-publisher", reviewed.generation), + articleId: f.articleId, + review: reviewed.review, + }; + await expect( + f.app.publishArticle(reviewer, publication), + ).rejects.toMatchObject({ name: "KnowledgeBaseAuthorizationError" }); + await f.app.publishArticle(f.owner, publication); + expect( + ( + await f.app.getPublishedArticle(f.customer, { + articleId: f.articleId, + }) + ).revision, + ).toBe(1); + }); + it("exposes only an opaque body-free status to the submitting owner and denies other owners", async () => { const f = await evidenceReportsFixture(await createStore()); const packet = await f.report(); @@ -168,6 +279,61 @@ for (const [backend, createStore] of storeFactories) { ).toBe(packet.input.report.details); }); + it.each(["confirm", "reassess"] as const)( + "refuses a stale owner status when a concurrent %s changes the report after its first load", + async (transition) => { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const original = + transition === "reassess" + ? (await f.decide(packet.ack)).ack + : packet.ack; + const physical = await f.physicalRows(); + const report = physical.find((row) => + row.value.id.startsWith("report:"), + )!; + const head = physical.find((row) => row.value.id === "head")!; + const gate = reportBarrier(); + let loaded = false; + let paused = false; + f.observed.beforeRead(async (trace) => { + if (trace.collection !== f.namespace) return; + if (trace.method === "get" && trace.key.id === report.key.id) + loaded = true; + if (!paused && loaded && trace.key.id === head.key.id) { + paused = true; + await gate.wait(); + } + }); + const pending = capture(f.reports.status(f.agent, f.key(original))); + let latest = original; + let changedRows = await f.rawRows(); + try { + await gate.reached(pending); + latest = ( + await f.decide( + original, + transition === "reassess" ? "pending" : "confirmed", + ) + ).ack; + changedRows = await f.rawRows(); + } finally { + gate.release(); + f.observed.beforeRead(undefined); + } + expect(await pending).toMatchObject({ + error: { code: "report_changed" }, + }); + expect(await f.rawRows()).toEqual(changedRows); + expect(await f.reports.status(f.agent, f.key(original))).toEqual({ + ...latest, + status: transition === "reassess" ? "pending" : "confirmed", + }); + if (transition === "reassess") + expect(latest.receipt).not.toBe(original.receipt); + }, + ); + it("replays exact commands without appending rows and rejects changed report or decision bindings", async () => { const f = await evidenceReportsFixture(await createStore()); const packet = await f.report(); @@ -225,6 +391,135 @@ for (const [backend, createStore] of storeFactories) { expect(await f.rows()).toEqual(committed); }); + it("recovers a generation-bound lost acknowledgement after a real article edit while fencing changed and new stale commands", async () => { + const f = await evidenceReportsFixture(await createStore()); + const input = { + ...(await f.reportInput()), + expectedArticleGeneration: (await f.current()).generation, + }; + let lost = false; + f.observed.intercept(async (trace, commit) => { + const result = await commit(); + if (!lost && trace.collection === f.namespace && result.committed) { + lost = true; + throw new Error("PRIVATE_GENERATION_BOUND_ACK_LOSS"); + } + return result; + }); + await expect(f.reports.report(f.agent, input)).rejects.toMatchObject({ + ...unavailable, + stage: "report_write", + }); + f.observed.intercept(undefined); + const committed = await f.rawRows(); + const changed = await f.updateDraft(); + expect(changed.generation).toBeGreaterThan( + input.expectedArticleGeneration, + ); + const recovered = await f.reports.report(f.agent, input); + expect(await f.reports.status(f.agent, f.key(recovered))).toEqual({ + ...recovered, + status: "pending", + }); + await expect( + f.reports.report(f.agent, { + ...input, + expectedArticleGeneration: changed.generation, + }), + ).rejects.toMatchObject({ code: "command_conflict" }); + await expect( + f.reports.report(f.agent, { + ...input, + commandId: "new-command-with-stale-article-generation", + }), + ).rejects.toMatchObject({ code: "report_changed" }); + await expect(f.decide(recovered)).rejects.toMatchObject({ + code: "report_not_verifiable", + }); + expect(await f.rawRows()).toEqual(committed); + }); + + it.each(["report", "decide", "reset", "drain"] as const)( + "withholds the %s acknowledgement after committed storage loses current principal authority, while retaining its effect", + async (operation) => { + const f = await evidenceReportsFixture(await createStore()); + const mutation = await reportMutation(f, operation); + const authority = f.principals.get(mutation.caller.principalId)!; + const gate = reportBarrier(); + let paused = false; + let committedRows = await f.rawRows(); + f.observed.intercept(async (trace, commit) => { + const result = await commit(); + if (!paused && trace.collection === f.namespace && result.committed) { + paused = true; + await gate.wait(); + } + return result; + }); + const pending = capture(mutation.run()); + try { + await gate.reached(pending); + committedRows = await f.rawRows(); + expect(committedRows).toHaveLength(mutation.rowsAfterCommit); + f.principals.delete(mutation.caller.principalId); + } finally { + gate.release(); + f.observed.intercept(undefined); + } + expect(await pending).toMatchObject({ error: { code: "forbidden" } }); + expect(await f.rawRows()).toEqual(committedRows); + f.principals.set(mutation.caller.principalId, authority); + await mutation.run(); + expect(await f.rawRows()).toEqual(committedRows); + }, + ); + + it.each(["report", "decide"] as const)( + "withholds the competing %s command's retained receipt when authority is revoked after its failed CAS", + async (operation) => { + const f = await evidenceReportsFixture(await createStore()); + const mutation = await reportMutation(f, operation); + const authority = f.principals.get(mutation.caller.principalId)!; + const beforeCommit = reportBarrier(); + const afterRefusal = reportBarrier(); + let first = true; + let refused = false; + f.observed.intercept(async (trace, commit) => { + if (first && trace.collection === f.namespace) { + first = false; + await beforeCommit.wait(); + const result = await commit(); + refused = !result.committed; + await afterRefusal.wait(); + return result; + } + return commit(); + }); + const pending = capture(mutation.run()); + let accepted: unknown; + let committedRows = await f.rawRows(); + try { + await beforeCommit.reached(pending); + accepted = await mutation.run(); + beforeCommit.release(); + await afterRefusal.reached(pending); + expect(refused).toBe(true); + committedRows = await f.rawRows(); + expect(committedRows).toHaveLength(mutation.rowsAfterCommit); + f.principals.delete(mutation.caller.principalId); + } finally { + beforeCommit.release(); + afterRefusal.release(); + f.observed.intercept(undefined); + } + expect(await pending).toMatchObject({ error: { code: "forbidden" } }); + expect(await f.rawRows()).toEqual(committedRows); + f.principals.set(mutation.caller.principalId, authority); + expect(await mutation.run()).toEqual(accepted); + expect(await f.rawRows()).toEqual(committedRows); + }, + ); + it("fences an actual competing report transaction without half-written report, Audit or receipt rows", async () => { const f = await evidenceReportsFixture(await createStore()); const gate = reportBarrier(); @@ -361,6 +656,149 @@ for (const [backend, createStore] of storeFactories) { ).toBe(1); }); + it("keeps revoked proof and its old receipt refused while a freshly reviewed execution replaces the same evidence identity", async () => { + const f = await evidenceReportsFixture(await createStore()); + const original = await f.report(); + const confirmed = await f.decide(original.ack); + await f.submit(confirmed.ack, original.input.evidence); + const old = ( + await f.app.getEvidence(f.reviewer, { articleId: f.articleId }) + ).evidence[0]!; + await f.app.revokeEvidence(f.owner, { + ...f.command( + "revoke-reviewed-old-version", + (await f.current()).generation, + ), + articleId: f.articleId, + articleRevision: old.articleRevision, + evidenceId: old.id, + evidenceVersion: old.version, + evidenceHash: old.hash, + reason: "Synthetic independent execution requires replacement", + }); + const oldRequest = await f.verificationRequest( + confirmed.ack, + original.input.evidence, + ); + expect(await f.reports.verifier.verify(oldRequest)).toBeNull(); + await expect( + f.submit(confirmed.ack, original.input.evidence), + ).rejects.toMatchObject(kbEvidenceRefusal); + f.advance(1_000); + const freshProof: EvidenceSubmission = { + ...original.input.evidence, + executedAt: at(3_500), + steps: ["Run a fresh independent workspace export check"], + artifacts: [ + { id: "private/artifact/fresh-export", hash: "b".repeat(64) }, + ], + }; + const fresh = await f.report(freshProof); + const reviewed = await f.decide(fresh.ack); + expect(reviewed.ack.receipt).not.toBe(confirmed.ack.receipt); + await f.submit(reviewed.ack, freshProof); + const current = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + expect(current.evidence).toMatchObject([ + { + id: old.id, + articleRevision: old.articleRevision, + version: old.version + 1, + executedAt: freshProof.executedAt, + artifacts: freshProof.artifacts, + attestation: { id: reviewed.ack.receipt }, + }, + ]); + expect(current.evidence[0]?.hash).not.toBe(old.hash); + expect(current.revokedEvidence).toMatchObject([ + { id: old.id, version: old.version, hash: old.hash }, + ]); + expect( + await f.reports.verifier.verify( + await f.verificationRequest(confirmed.ack, original.input.evidence), + ), + ).toBeNull(); + await expect( + f.submit(confirmed.ack, original.input.evidence), + ).rejects.toMatchObject(kbEvidenceRefusal); + expect( + await f.app.getEvidence(f.reviewer, { articleId: f.articleId }), + ).toEqual(current); + const workflow = await f.report( + await f.submission("walkthrough-workflow"), + ); + await f.submit( + (await f.decide(workflow.ack)).ack, + workflow.input.evidence, + ); + await f.publish(); + expect( + ( + await f.app.getPublishedArticle(f.customer, { + articleId: f.articleId, + }) + ).revision, + ).toBe(old.articleRevision); + }); + + it("allows pending agent reports without evidence-read scope but refuses qualification when the host omits authoritative evidence state", async () => { + const f = await evidenceReportsFixture(await createStore()); + const missing = f.freshReports({ + readContext: async (caller, articleId) => { + const value = await f.readContext(caller, articleId); + return { draft: value.draft, requirements: value.requirements }; + }, + }); + const input = await f.reportInput(); + const pending = await missing.report(f.agent, input); + expect( + (await f.readContext(f.agent, f.articleId)).evidence, + ).toBeUndefined(); + const view = await missing.read(f.reviewer, f.key(pending)); + const before = await f.rawRows(); + await expect( + missing.decide( + f.reviewer, + { + ...f.key(pending), + commandId: "missing-authoritative-evidence-confirmation", + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }, + "confirmed", + ), + ).rejects.toMatchObject({ code: "report_not_verifiable" }); + expect(await f.rawRows()).toEqual(before); + const confirmed = await f.decide(pending); + const request = await f.verificationRequest( + confirmed.ack, + input.evidence, + ); + expect(await f.reports.verifier.verify(request)).not.toBeNull(); + expect(await missing.verifier.verify(request)).toBeNull(); + const app = createKnowledgeBaseApplication({ + store: f.baseOptions.store, + clock: f.clock, + evidenceVerifier: missing.verifier, + }); + await expect( + app.submitEvidence(f.agent, { + ...f.command( + "missing-authoritative-evidence-acceptance", + (await f.current()).generation, + ), + articleId: f.articleId, + evidence: input.evidence, + receipt: confirmed.ack.receipt, + }), + ).rejects.toMatchObject(kbEvidenceRefusal); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toEqual([]); + }); + it.each(["build", "check", "revision", "future", "expired"] as const)( "refuses human confirmation against a %s mismatch or stale execution", async (defect) => { From 81c2d925e2b3a4d36ced99dddf24ef6f693b260d Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sun, 8 Nov 2026 17:24:46 -0500 Subject: [PATCH 4/5] Reject unqualifiable reports while preserving historical receipts --- docs/EVIDENCE_REPORTS.md | 16 + packages/application/src/evidence-reports.ts | 32 ++ test/evidence-reports-fixtures.ts | 16 +- test/evidence-reports-retained-whitespace.ts | 331 +++++++++++++++++++ tests/evidence-reports.test.ts | 188 +++++++++++ 5 files changed, 580 insertions(+), 3 deletions(-) create mode 100644 test/evidence-reports-retained-whitespace.ts diff --git a/docs/EVIDENCE_REPORTS.md b/docs/EVIDENCE_REPORTS.md index fc4dc43..3e21c51 100644 --- a/docs/EVIDENCE_REPORTS.md +++ b/docs/EVIDENCE_REPORTS.md @@ -71,6 +71,14 @@ command conflicts. Omitting it preserves the existing legacy fingerprints; the service does not invent a default generation. The agent dispatcher passes its wire `expectedGeneration` through this field. +After an exact replay lookup misses, new report admission rejects evidence text +fields and steps that Core would trim, a supplied locale outside Core's +language-tag syntax or longer than 64 characters, and duplicate artifact IDs. +These are rejection checks: no evidence, opaque ID or receipt is normalized. +The report boundary also retains its existing C1-control rejection, which is +intentionally stricter than Core's legacy syntax. The legacy MCP schemas are +unchanged. + | Method | Purpose and authority | | ---------------- | ------------------------------------------------------------------------------------------------------------- | | `ledger` | Body-free current epoch/capacity state; requires current `evidenceSubmit`. | @@ -109,6 +117,14 @@ result, staging build, governance, applicability, policy and freshness. A confirmed receipt can therefore be refused. Every required check must qualify before the separate exact SDK review/publication workflow can proceed. +The stored decoder, scalar rules and fingerprints are unchanged. Evidence +previously admitted but failing the added syntax checks can still recover an +exact retained command's historical acknowledgement. That replay does not +qualify the evidence: confirmation, reassessment and the verifier refuse its +malformed syntax, even if the retained report was already confirmed. Such a +confirmed report uses the existing authorized ledger reset/drain recovery; +there is no new repair or reactivation transition. + To reassess a confirmed or rejected report, freshly `read` it and call `decide` with `"pending"`. This clears confirmation, advances report generation and rotates the receipt cycle. The original execution must still match the current diff --git a/packages/application/src/evidence-reports.ts b/packages/application/src/evidence-reports.ts index 131fd37..32a1a2b 100644 --- a/packages/application/src/evidence-reports.ts +++ b/packages/application/src/evidence-reports.ts @@ -370,6 +370,35 @@ function parseKnowledgeEvidence(value: unknown): EvidenceSubmission { }), }; } +function validSubmissionSyntax(evidence: EvidenceSubmission): boolean { + // Keep the report parser's intentionally stricter C1-control rejection. + // Check Core's additional syntax without trimming or rewriting stored data. + const text = [ + evidence.id, + evidence.articleId, + evidence.validationPolicy.id, + evidence.checkId, + evidence.testKind, + evidence.stagingBuildId, + evidence.runnerId, + evidence.applicability.productId, + evidence.applicability.productVersion, + ...(evidence.applicability.buildId === undefined + ? [] + : [evidence.applicability.buildId]), + ...evidence.steps, + ...evidence.artifacts.map((artifact) => artifact.id), + ]; + const locale = evidence.applicability.locale; + return ( + text.every((value) => value.trim() === value) && + (locale === undefined || + (locale.length <= 64 && + /^[a-zA-Z]{2,8}(?:-[a-zA-Z0-9]{1,8})*$/u.test(locale))) && + new Set(evidence.artifacts.map((artifact) => artifact.id)).size === + evidence.artifacts.length + ); +} function parseReport(value: unknown): KnowledgeTestReport { const report = exactObject(value, ["summary", "details"]); return { @@ -847,6 +876,7 @@ export function createKnowledgeEvidenceReports( at: string, ): Promise { if ( + !validSubmissionSyntax(report.evidence) || report.reportHash !== (await knowledgeDigest(reportBinding(report))) || report.articleHash !== (await knowledgeDigest(article)) || report.governanceHash !== (await knowledgeDigest(value.requirements)) || @@ -1189,6 +1219,8 @@ export function createKnowledgeEvidenceReports( await current(access, knowledgePermissions.evidenceSubmit); return accepted; } + if (!validSubmissionSyntax(evidence)) + throw new KnowledgeEvidenceReportsError("invalid_request"); const valueContext = await context(access, articleId); if ( expectedArticleGeneration !== undefined && diff --git a/test/evidence-reports-fixtures.ts b/test/evidence-reports-fixtures.ts index d7078a3..7eae1c1 100644 --- a/test/evidence-reports-fixtures.ts +++ b/test/evidence-reports-fixtures.ts @@ -388,9 +388,13 @@ export async function evidenceReportsFixture( value: logicalReportRow(definition.codec.decode(item.value)), })); } - async function installPreparedHistory(rows: readonly ReportLedgerRow[]) { - if (rows.length !== 160 || (await rawRows()).length !== 0) - throw new Error("Prepared history requires an empty 160-row target"); + async function installCapturedRows(rows: readonly ReportLedgerRow[]) { + if ( + rows.length === 0 || + rows.length > 160 || + (await rawRows()).length !== 0 + ) + throw new Error("Captured rows require an empty bounded target"); const definition = factoryDefinition(); const partition = definition.key(rows[0]!).partition; if ( @@ -414,6 +418,11 @@ export async function evidenceReportsFixture( throw new Error("Prepared history insertion did not commit"); } } + async function installPreparedHistory(rows: readonly ReportLedgerRow[]) { + if (rows.length !== 160) + throw new Error("Prepared history requires exactly 160 rows"); + await installCapturedRows(rows); + } return { app, reports, @@ -452,6 +461,7 @@ export async function evidenceReportsFixture( advance: (milliseconds: number) => setTime(offset + milliseconds), rawRows, physicalRows, + installCapturedRows, installPreparedHistory, insertOpaqueRow: (value: ReportLedgerRow) => { if (value.articleId !== articleId || value.id === "head") diff --git a/test/evidence-reports-retained-whitespace.ts b/test/evidence-reports-retained-whitespace.ts new file mode 100644 index 0000000..bd63ec4 --- /dev/null +++ b/test/evidence-reports-retained-whitespace.ts @@ -0,0 +1,331 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import type { + DecideKnowledgeReportInput, + KnowledgeEvidenceContext, + KnowledgeReportAcknowledgement, + SubmitKnowledgeReportInput, +} from "@pegma/knowledge-base-application"; +import type { ReportLedgerRow } from "./evidence-reports-fixtures.js"; + +/** + * Actual synthetic public-factory capture from pre-guard source 58aefc2. + * Commands, acknowledgements and logical row payloads are retained unchanged. + * Core refused this evidence; this is not published-producer, accepted-KB-proof, + * target history-writing, or migration evidence. No current factory re-creates + * the retained hashes or confirms malformed submissions for this fixture. + */ +export const retainedWhitespaceReport = { + sourceCommit: "58aefc21770b6af976bce5cb15f32f8c10fc4dfc", + captureSha256: + "6a362198cfc836beb1400570cfa930b45d989df6077440186f25d1f59ba288df", + capturedAt: "2026-11-08T22:13:22.659Z", + sources: [ + { + path: "packages/application/src/evidence-reports.ts", + bytes: 55744, + sha256: + "fbddfaa9ae9c5b94727add385885794e2a04743a96fdb925a3121e9eee9e0477", + }, + { + path: "packages/application/src/evidence-reports-types.ts", + bytes: 6150, + sha256: + "2c24b51bcb7b2505282b81ac52ab9235f951569a6a74f0daa3c9b50abdc1284a", + }, + { + path: "packages/application/src/evidence-reports-errors.ts", + bytes: 1640, + sha256: + "1bcaab74f3dfaa510d811615487ce71e93efdaba2451b377c4463adf8760a726", + }, + { + path: "packages/core/src/articles.ts", + bytes: 19340, + sha256: + "03ce81d34d64be26bd91cd9745ca2de86a6212f0a459afc066e4aa6d7e673217", + }, + { + path: "packages/core/src/validation.ts", + bytes: 11021, + sha256: + "6f3f76adba3a58c0421e81c6baa4118c5692e8916d994f84781066412400ee30", + }, + { + path: "test/evidence-reports-fixtures.ts", + bytes: 16959, + sha256: + "b95eb9e0ad1e0720e6e68d0de44ddbd5adc0d4675d696991454fa8ce6abe09bb", + }, + ], + articleId: "article/export", + collectionId: "collection/workshop", + namespace: "workshop.knowledge-reports.v1", + clock: "2026-11-06T20:00:03.000Z", + agent: { + principalId: "runner/staging", + policyVersion: "synthetic-1", + roles: [], + entitlements: [], + permissions: [ + "knowledge.article.draft.read", + "knowledge.article.draft.write", + "knowledge.article.evidence.submit", + ], + }, + reviewer: { + principalId: "staff/verifier", + policyVersion: "synthetic-1", + roles: [], + entitlements: [], + permissions: [ + "knowledge.collection.read", + "knowledge.collection.manage", + "knowledge.collection.approve-public", + "knowledge.article.read", + "knowledge.article.bot.read", + "knowledge.index.manage", + "knowledge.article.draft.read", + "knowledge.article.draft.write", + "knowledge.article.evidence.read", + "knowledge.article.evidence.submit", + "knowledge.article.evidence.revoke", + "knowledge.article.provenance.read", + "knowledge.article.provenance.write", + "knowledge.article.review.submit", + "knowledge.article.review", + "knowledge.article.publish", + "knowledge.article.retire", + "knowledge.validation.manage", + "workshop.knowledge.report.confirm", + "workshop.customer", + ], + }, + context: { + draft: { + articleId: "article/export", + generation: 1, + hasPendingReview: false, + hasPublication: false, + publicationHeld: false, + revision: { + applicability: { + buildId: "staging-42", + locale: "en-US", + productId: "fictional-workshop", + productVersion: "1.0", + }, + articleId: "article/export", + collectionId: "collection/workshop", + content: { + format: "markdown", + text: "Choose [Export](/workspace/export). ", + }, + contentHash: + "11fff3f38bf9f66d3bf40785d412250dcb6eff495b7ae61e3f1bbaf23366bdc6", + createdAt: "2026-11-06T20:00:00.000Z", + createdBy: "runner/staging", + kind: "walkthrough", + number: 1, + summary: "Download a synthetic workspace export.", + tags: ["export"], + title: "Export your workspace", + validationPolicy: { + id: "policy/workshop", + version: 1, + }, + }, + state: "draft", + }, + requirements: { + checks: [ + { + id: "walkthrough-content", + maxAgeMilliseconds: 60000, + testKind: "content", + }, + { + id: "walkthrough-workflow", + maxAgeMilliseconds: 60000, + testKind: "workflow", + }, + ], + collectionId: "collection/workshop", + expectedStagingBuildId: "staging-42", + governanceGeneration: 3, + validationPolicy: { + id: "policy/workshop", + version: 1, + }, + }, + evidence: { + articleId: "article/export", + evidence: [], + generation: 1, + revokedEvidence: [], + }, + }, + report: { + input: { + commandId: "report/6", + articleId: "article/export", + ledgerEpoch: 1, + evidence: { + id: "evidence/walkthrough-content", + articleId: "article/export", + articleRevision: 1, + contentHash: + "11fff3f38bf9f66d3bf40785d412250dcb6eff495b7ae61e3f1bbaf23366bdc6", + validationPolicy: { + id: "policy/workshop", + version: 1, + }, + checkId: "walkthrough-content", + testKind: "content", + applicability: { + buildId: "staging-42", + locale: "en-US", + productId: "fictional-workshop", + productVersion: "1.0", + }, + stagingBuildId: "staging-42", + steps: [" Retained synthetic workspace export step "], + result: "passed", + executedAt: "2026-11-06T20:00:01.000Z", + runnerId: "runner/staging", + artifacts: [ + { + id: "private/artifact/export", + hash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + }, + ], + }, + report: { + summary: "Synthetic workspace export check", + details: "Reviewed staging output. PRIVATE_REPORT_BODY_CANARY", + }, + }, + ack: { + ledgerEpoch: 1, + reportId: "67dba5ab-2d6d-4e10-9a54-2103c4012a15", + receipt: "e1.1.67dba5ab-2d6d-4e10-9a54-2103c4012a15", + reportGeneration: 1, + }, + }, + confirmation: { + input: { + articleId: "article/export", + ledgerEpoch: 1, + reportId: "67dba5ab-2d6d-4e10-9a54-2103c4012a15", + commandId: "report-confirmed/7", + expectedReportGeneration: 1, + reviewBindingHash: + "5b013bc7e40cfb274afc152294a47741cfbc6b57070863d9f7e391e224a51dbb", + }, + ack: { + ledgerEpoch: 1, + reportId: "67dba5ab-2d6d-4e10-9a54-2103c4012a15", + receipt: "e1.1.67dba5ab-2d6d-4e10-9a54-2103c4012a15", + reportGeneration: 2, + }, + }, + pendingRows: [ + { + articleId: "article/export", + id: "audit:command:1:f894407af154f1e207068b414cbdd943707b667b521c81ab7141ca18711e6395", + payload: + '{"action":"knowledge.report.pending","actor":{"kind":"principal","principalId":"runner/staging"},"details":{"generation":1,"ledgerEpoch":1,"receiptGeneration":1,"reportHash":"8e555b4e254a8a4dc4d75dcee4927cf81762d2d805ef6a393642c432f54f461c","reportId":"67dba5ab-2d6d-4e10-9a54-2103c4012a15"},"id":"command:1:f894407af154f1e207068b414cbdd943707b667b521c81ab7141ca18711e6395","occurredAt":"2026-11-06T20:00:03.000Z","subject":"article/export"}', + }, + { + articleId: "article/export", + id: "command:1:f894407af154f1e207068b414cbdd943707b667b521c81ab7141ca18711e6395", + payload: + '{"fingerprint":"c5f1cf4251a0ef8b751bf90be3b5c36bfd13d864cbdc530f9503e8af2d5d2e4a","result":{"ledgerEpoch":1,"receipt":"e1.1.67dba5ab-2d6d-4e10-9a54-2103c4012a15","reportGeneration":1,"reportId":"67dba5ab-2d6d-4e10-9a54-2103c4012a15"}}', + }, + { + articleId: "article/export", + id: "head", + payload: + '{"drainRemaining":0,"historyHash":"0000000000000000000000000000000000000000000000000000000000000000","lastReset":null,"ledgerEpoch":1,"reports":1,"rows":4,"status":"active"}', + }, + { + articleId: "article/export", + id: "report:1:67dba5ab-2d6d-4e10-9a54-2103c4012a15", + payload: + '{"articleHash":"9eb8fe1bf46de2abda3a94693cc3535c65fbc49efc5996951f972459fb8265a7","articleId":"article/export","confirmation":null,"evidence":{"applicability":{"buildId":"staging-42","locale":"en-US","productId":"fictional-workshop","productVersion":"1.0"},"articleId":"article/export","articleRevision":1,"artifacts":[{"hash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","id":"private/artifact/export"}],"checkId":"walkthrough-content","contentHash":"11fff3f38bf9f66d3bf40785d412250dcb6eff495b7ae61e3f1bbaf23366bdc6","executedAt":"2026-11-06T20:00:01.000Z","id":"evidence/walkthrough-content","result":"passed","runnerId":"runner/staging","stagingBuildId":"staging-42","steps":[" Retained synthetic workspace export step "],"testKind":"content","validationPolicy":{"id":"policy/workshop","version":1}},"governanceHash":"b28c799e61de634ac7a37533da9cb5a90f069e5710e84cb5d6b11eb947c35c0b","ledgerEpoch":1,"receiptGeneration":1,"report":{"details":"Reviewed staging output. PRIVATE_REPORT_BODY_CANARY","summary":"Synthetic workspace export check"},"reportGeneration":1,"reportHash":"8e555b4e254a8a4dc4d75dcee4927cf81762d2d805ef6a393642c432f54f461c","reportId":"67dba5ab-2d6d-4e10-9a54-2103c4012a15","status":"pending","submissionHash":"81d6f111e8d91cdefaedeeb546dde036308140f0d2459e3c0f1074d97bf0a5d1","submittedAt":"2026-11-06T20:00:03.000Z","submittedBy":"runner/staging"}', + }, + ], + confirmedRows: [ + { + articleId: "article/export", + id: "audit:command:1:dd215bda968707d391c82623f71a2771ede659cd1626f19c43c0f3e0ea40e32e", + payload: + '{"action":"knowledge.report.confirmed","actor":{"kind":"principal","principalId":"staff/verifier"},"details":{"generation":2,"ledgerEpoch":1,"receiptGeneration":1,"reportHash":"8e555b4e254a8a4dc4d75dcee4927cf81762d2d805ef6a393642c432f54f461c","reportId":"67dba5ab-2d6d-4e10-9a54-2103c4012a15"},"id":"command:1:dd215bda968707d391c82623f71a2771ede659cd1626f19c43c0f3e0ea40e32e","occurredAt":"2026-11-06T20:00:03.000Z","subject":"article/export"}', + }, + { + articleId: "article/export", + id: "audit:command:1:f894407af154f1e207068b414cbdd943707b667b521c81ab7141ca18711e6395", + payload: + '{"action":"knowledge.report.pending","actor":{"kind":"principal","principalId":"runner/staging"},"details":{"generation":1,"ledgerEpoch":1,"receiptGeneration":1,"reportHash":"8e555b4e254a8a4dc4d75dcee4927cf81762d2d805ef6a393642c432f54f461c","reportId":"67dba5ab-2d6d-4e10-9a54-2103c4012a15"},"id":"command:1:f894407af154f1e207068b414cbdd943707b667b521c81ab7141ca18711e6395","occurredAt":"2026-11-06T20:00:03.000Z","subject":"article/export"}', + }, + { + articleId: "article/export", + id: "command:1:dd215bda968707d391c82623f71a2771ede659cd1626f19c43c0f3e0ea40e32e", + payload: + '{"fingerprint":"3e1b825ad54a52900147c69db8abe5e9bc73a8b5f166a41838aa21c5a028c038","result":{"ledgerEpoch":1,"receipt":"e1.1.67dba5ab-2d6d-4e10-9a54-2103c4012a15","reportGeneration":2,"reportId":"67dba5ab-2d6d-4e10-9a54-2103c4012a15"}}', + }, + { + articleId: "article/export", + id: "command:1:f894407af154f1e207068b414cbdd943707b667b521c81ab7141ca18711e6395", + payload: + '{"fingerprint":"c5f1cf4251a0ef8b751bf90be3b5c36bfd13d864cbdc530f9503e8af2d5d2e4a","result":{"ledgerEpoch":1,"receipt":"e1.1.67dba5ab-2d6d-4e10-9a54-2103c4012a15","reportGeneration":1,"reportId":"67dba5ab-2d6d-4e10-9a54-2103c4012a15"}}', + }, + { + articleId: "article/export", + id: "head", + payload: + '{"drainRemaining":0,"historyHash":"0000000000000000000000000000000000000000000000000000000000000000","lastReset":null,"ledgerEpoch":1,"reports":1,"rows":6,"status":"active"}', + }, + { + articleId: "article/export", + id: "report:1:67dba5ab-2d6d-4e10-9a54-2103c4012a15", + payload: + '{"articleHash":"9eb8fe1bf46de2abda3a94693cc3535c65fbc49efc5996951f972459fb8265a7","articleId":"article/export","confirmation":{"confirmedAt":"2026-11-06T20:00:03.000Z","reviewerId":"staff/verifier"},"evidence":{"applicability":{"buildId":"staging-42","locale":"en-US","productId":"fictional-workshop","productVersion":"1.0"},"articleId":"article/export","articleRevision":1,"artifacts":[{"hash":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","id":"private/artifact/export"}],"checkId":"walkthrough-content","contentHash":"11fff3f38bf9f66d3bf40785d412250dcb6eff495b7ae61e3f1bbaf23366bdc6","executedAt":"2026-11-06T20:00:01.000Z","id":"evidence/walkthrough-content","result":"passed","runnerId":"runner/staging","stagingBuildId":"staging-42","steps":[" Retained synthetic workspace export step "],"testKind":"content","validationPolicy":{"id":"policy/workshop","version":1}},"governanceHash":"b28c799e61de634ac7a37533da9cb5a90f069e5710e84cb5d6b11eb947c35c0b","ledgerEpoch":1,"receiptGeneration":1,"report":{"details":"Reviewed staging output. PRIVATE_REPORT_BODY_CANARY","summary":"Synthetic workspace export check"},"reportGeneration":2,"reportHash":"8e555b4e254a8a4dc4d75dcee4927cf81762d2d805ef6a393642c432f54f461c","reportId":"67dba5ab-2d6d-4e10-9a54-2103c4012a15","status":"confirmed","submissionHash":"81d6f111e8d91cdefaedeeb546dde036308140f0d2459e3c0f1074d97bf0a5d1","submittedAt":"2026-11-06T20:00:03.000Z","submittedBy":"runner/staging"}', + }, + ], + preGuardAttestation: { + id: "e1.1.67dba5ab-2d6d-4e10-9a54-2103c4012a15", + verifiedBy: "staff/verifier", + verifiedAt: "2026-11-06T20:00:03.000Z", + }, +} satisfies { + readonly sourceCommit: string; + readonly captureSha256: string; + readonly capturedAt: string; + readonly sources: readonly { + readonly path: string; + readonly bytes: number; + readonly sha256: string; + }[]; + readonly articleId: string; + readonly collectionId: string; + readonly namespace: string; + readonly clock: string; + readonly agent: AccessContext; + readonly reviewer: AccessContext; + readonly context: KnowledgeEvidenceContext; + readonly report: { + readonly input: SubmitKnowledgeReportInput; + readonly ack: KnowledgeReportAcknowledgement; + }; + readonly confirmation: { + readonly input: DecideKnowledgeReportInput; + readonly ack: KnowledgeReportAcknowledgement; + }; + readonly pendingRows: readonly ReportLedgerRow[]; + readonly confirmedRows: readonly ReportLedgerRow[]; + readonly preGuardAttestation: { + readonly id: string; + readonly verifiedBy: string; + readonly verifiedAt: string; + }; +}; diff --git a/tests/evidence-reports.test.ts b/tests/evidence-reports.test.ts index fb2e42e..2784f0f 100644 --- a/tests/evidence-reports.test.ts +++ b/tests/evidence-reports.test.ts @@ -18,6 +18,7 @@ import { evidenceReportsHistoryFixture, reportBarrier, } from "../test/evidence-reports-fixtures.js"; +import { retainedWhitespaceReport } from "../test/evidence-reports-retained-whitespace.js"; const unavailable = { code: "report_ledger_unavailable" }; const kbEvidenceRefusal = { @@ -1635,6 +1636,193 @@ for (const [backend, createStore] of storeFactories) { expect(await f.rows()).toEqual([]); }); + it("rejects malformed submission syntax before new admission without changing ledger rows", async () => { + const f = await evidenceReportsFixture(await createStore()); + const input = await f.reportInput(); + const proof = input.evidence; + const artifact = proof.artifacts[0]!; + const malformed: readonly [string, EvidenceSubmission][] = [ + ["leading step whitespace", { ...proof, steps: [" Run export"] }], + ["trailing step whitespace", { ...proof, steps: ["Run export "] }], + ["whitespace-only step", { ...proof, steps: [" "] }], + ["C1 control step", { ...proof, steps: ["Run\u0085export"] }], + ["leading evidence ID whitespace", { ...proof, id: " " + proof.id }], + ["trailing evidence ID whitespace", { ...proof, id: proof.id + " " }], + [ + "leading runner ID whitespace", + { ...proof, runnerId: " " + proof.runnerId }, + ], + [ + "trailing runner ID whitespace", + { ...proof, runnerId: proof.runnerId + " " }, + ], + [ + "leading artifact ID whitespace", + { ...proof, artifacts: [{ ...artifact, id: " " + artifact.id }] }, + ], + [ + "trailing artifact ID whitespace", + { ...proof, artifacts: [{ ...artifact, id: artifact.id + " " }] }, + ], + [ + "duplicate artifact IDs with different hashes", + { + ...proof, + artifacts: [artifact, { ...artifact, hash: "b".repeat(64) }], + }, + ], + ...["en_US", " en-US", "en-US ", "en" + "-abcdefgh".repeat(7)].map( + (locale): [string, EvidenceSubmission] => [ + "invalid locale " + JSON.stringify(locale), + { ...proof, applicability: { ...proof.applicability, locale } }, + ], + ), + ]; + const before = await f.rawRows(); + const writes = f.observed.transactions.length; + for (const [label, evidence] of malformed) { + await expect( + f.reports.report(f.agent, { ...input, evidence }), + label, + ).rejects.toMatchObject({ code: "invalid_request" }); + expect(await f.rawRows(), label).toEqual(before); + expect(f.observed.transactions, label).toHaveLength(writes); + } + }); + + it("accepts clean submission syntax with internal spaces and valid bounded language tags through actual KB qualification", async () => { + const f = await evidenceReportsFixture(await createStore()); + const longestLocale = "en" + "-abcdefgh".repeat(6) + "-abcdefg"; + expect(longestLocale).toHaveLength(64); + for (const locale of ["en-US", "zh-Hant-TW", longestLocale]) { + const current = await f.current(); + if (current.revision.applicability.locale !== locale) { + const value = draft("walkthrough"); + await f.app.updateDraft(f.agent, { + ...f.command("valid-submission-locale", current.generation), + articleId: f.articleId, + collectionId: f.collectionId, + draft: { + ...value, + applicability: { ...value.applicability, locale }, + }, + }); + f.advance(2_000); + } + const proof: EvidenceSubmission = { + ...(await f.submission()), + id: "evidence/export content check", + steps: ["Run the export check, then inspect its output"], + artifacts: [ + { id: "private/artifact/export report", hash: "c".repeat(64) }, + ], + }; + const packet = await f.report(proof); + const reviewed = await f.decide(packet.ack); + expect(reviewed.view.evidence).toEqual(proof); + await f.submit(reviewed.ack, proof); + const accepted = ( + await f.app.getEvidence(f.reviewer, { articleId: f.articleId }) + ).evidence; + expect(accepted).toMatchObject([ + { + id: proof.id, + steps: proof.steps, + artifacts: proof.artifacts, + applicability: { locale }, + attestation: { id: reviewed.ack.receipt }, + }, + ]); + } + }); + + it.each(["pending", "confirmed"] as const)( + "preserves retained pre-guard %s report reads and exact ACKs while refusing new qualification and retaining recovery", + async (status) => { + const retained = retainedWhitespaceReport; + const f = await evidenceReportsFixture(await createStore(), { + commandPrefix: "after-syntax-guard-", + }); + expect(f.clock.now()).toBe(retained.clock); + expect(f.agent).toEqual(retained.agent); + expect(f.reviewer).toEqual(retained.reviewer); + expect(await f.readContext(f.reviewer, f.articleId)).toEqual( + retained.context, + ); + const rows = + status === "pending" ? retained.pendingRows : retained.confirmedRows; + await f.installCapturedRows(rows); + expect(await f.rows()).toEqual(rows); + const before = await f.rawRows(); + expect(await f.reports.report(f.agent, retained.report.input)).toEqual( + retained.report.ack, + ); + if (status === "confirmed") + expect( + await f.reports.decide( + f.reviewer, + retained.confirmation.input, + "confirmed", + ), + ).toEqual(retained.confirmation.ack); + const ack = + status === "pending" + ? retained.report.ack + : retained.confirmation.ack; + const view = await f.reports.read(f.reviewer, f.key(ack)); + expect(view).toMatchObject({ + status, + reportGeneration: ack.reportGeneration, + evidence: retained.report.input.evidence, + report: retained.report.input.report, + }); + await expect( + f.reports.report(f.agent, { + ...retained.report.input, + commandId: "new-copy-of-retained-malformed-report", + }), + ).rejects.toMatchObject({ code: "invalid_request" }); + await expect( + f.decide(ack, status === "pending" ? "confirmed" : "pending"), + ).rejects.toMatchObject({ code: "report_not_verifiable" }); + expect( + await f.reports.verifier.verify( + await f.verificationRequest(ack, retained.report.input.evidence), + ), + ).toBeNull(); + if (status === "confirmed") + await expect( + f.submit(ack, retained.report.input.evidence), + ).rejects.toMatchObject({ + name: "KnowledgeBasePrerequisiteError", + prerequisite: "evidence-verifier", + }); + expect(await f.rawRows()).toEqual(before); + if (status === "pending") { + const rejected = await f.decide(ack, "rejected"); + expect(await f.reports.status(f.agent, f.key(ack))).toEqual({ + ...rejected.ack, + status: "rejected", + }); + } + let state = await f.reports.reset(f.reviewer, { + articleId: f.articleId, + commandId: "reset-retained-malformed-report", + expectedLedgerEpoch: ack.ledgerEpoch, + }); + for (let page = 0; state.status === "resetting" && page < 4; page++) + state = await f.reports.drain(f.reviewer, { + articleId: f.articleId, + ledgerEpoch: state.ledgerEpoch, + }); + expect(state).toMatchObject({ status: "active", ledgerEpoch: 2 }); + expect(await f.rows()).toHaveLength(1); + await expect( + f.reports.report(f.agent, retained.report.input), + ).rejects.toMatchObject({ code: "ledger_epoch_changed" }); + }, + ); + it.each(["principal", "context"] as const)( "sanitizes a failed %s port without trusting its exception or losing confirmation history", async (port) => { From 487cab327bc9d239dfd0ccdbc1150e7277e356db Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Sun, 8 Nov 2026 17:31:33 -0500 Subject: [PATCH 5/5] Clarify that Core rejects padded evidence --- docs/EVIDENCE_REPORTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/EVIDENCE_REPORTS.md b/docs/EVIDENCE_REPORTS.md index 3e21c51..607d791 100644 --- a/docs/EVIDENCE_REPORTS.md +++ b/docs/EVIDENCE_REPORTS.md @@ -72,7 +72,7 @@ the service does not invent a default generation. The agent dispatcher passes its wire `expectedGeneration` through this field. After an exact replay lookup misses, new report admission rejects evidence text -fields and steps that Core would trim, a supplied locale outside Core's +fields and steps that Core rejects for surrounding whitespace, a supplied locale outside Core's language-tag syntax or longer than 64 characters, and duplicate artifact IDs. These are rejection checks: no evidence, opaque ID or receipt is normalized. The report boundary also retains its existing C1-control rejection, which is