diff --git a/AGENTS.md b/AGENTS.md index fd55136..80a008c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,9 +24,12 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. subsequently completed verified trusted publication; retain the [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. + for SD-03 atomic draft/source authoring. All four `0.1.3` packages completed + verified trusted publication for optional human-reviewed evidence reports; + retain the [public release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3). + Synchronized `0.1.4` is the unpublished governed authoring-context/report-query + candidate and 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 @@ -58,6 +61,13 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. not provide a global policy fence; current reads must reject stale authority. - Replay rechecks current operation/resource permission and returns a bounded historical acknowledgement, not raw content or restored publication authority. +- Governed authoring reads require `draftRead` and either `draftWrite` or + `evidenceSubmit`; explicit private evidence additionally requires `evidenceRead`. + Keep opaque authoring observations within one operation and application + instance. They are single-use head observations, never serialized credentials, + evidence, review or publication authority. Preserve complete admitted proof + history and the legacy report context path. Provider batching and fewer public + calls do not establish universal Workers Free query/CPU acceptance. - Retrieval projections are derived hints. Count physical work before filtering; request paths use keyed reads, never a corpus scan. Confirm current publication, applicability, and effective portal/bot audience before exposing any title, @@ -112,7 +122,9 @@ 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 KB `0.1.2` and Agent Access `0.1.1` receipts. All five KB/Agent Access trusted publishers +and historical KB `0.1.2` and Agent Access `0.1.1` receipts. The +[KB `0.1.3` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3) +is also verified. 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 @@ -128,7 +140,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.3` candidate's own review, trusted publication, and strict registry +`0.1.4` 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 32d6250..6b85d31 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-08: KB-01 through KB-03 provide contracts, pure domain +> Development status as of 2026-11-09: 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. @@ -17,10 +17,12 @@ and exact publication approval. It requires no GitHub connection or AI provider. > OIDC provenance. All four `0.1.1` packages subsequently completed > [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, +> [verified trusted publication](docs/BOOTSTRAP.md#historical-verified-012-release) +> for SD-03 atomic draft/source authoring. All four `0.1.3` packages completed +> [verified trusted publication](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3) +> for optional human-reviewed [evidence reports](docs/EVIDENCE_REPORTS.md). +> Synchronized `0.1.4` is the **unpublished source candidate** for governed +> authoring-context reads and report queries; 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. @@ -45,6 +47,16 @@ and review reads have separate DTOs. The keyed published read returns portal-safe content only. The three base packages remain independent of HTTP, MCP, and provider SDKs. +The `0.1.4` candidate adds `getAuthoringContext` to read current draft and narrow +requirements together. It requires draft-read plus draft-write or evidence-submit; +requesting complete private evidence also requires evidence-read. Its opaque, +single-use `confirmAuthoringContext` observation is local to the same operation +and application instance, never a credential or publication authority. An +optional report-factory context pair and body-free `query` reduce repeated reads +while preserving legacy ports, full proof history and exact authority fences. +These source changes do not prove a universal 50-query or CPU budget for Workers +Free; real host profiles still require measured acceptance. + The optional adapter exposes exactly `getDraft`, `createDraft`, `updateDraft`, `getValidationRequirements`, and `submitEvidence` over the same application. Its scopes reuse `knowledgePermissions.draftRead`, `draftWrite`, and @@ -147,10 +159,10 @@ Merging source does not publish a package. The [maintainer bootstrap ledger](docs/BOOTSTRAP.md) records the completed manual `0.1.0` uploads and exact-byte postflight. All five KB/Agent Access trusted publishers are configured through the CLI. Agent Access's verified trusted -`0.1.1` release and the four-package KB trusted `0.1.2` release are complete; +`0.1.1` release and the four-package KB trusted `0.1.3` 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, +`latest: 0.1.3`; Agent Access has `latest: 0.1.1`; all retain historical +`bootstrap: 0.1.0`. Synchronized source `0.1.4` 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. diff --git a/docs/AGENT_API.md b/docs/AGENT_API.md index d8ab4db..646de96 100644 --- a/docs/AGENT_API.md +++ b/docs/AGENT_API.md @@ -5,10 +5,11 @@ 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. The current verified KB -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. +have since completed verified trusted publication. All four KB packages are now +verified published at [`0.1.3`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3), +including optional human-reviewed report mode. The synchronized `0.1.4` source +candidate adds the governed authoring-context pair and optional aggregate report +query. Its own review, gates, publication and strict verification remain open. 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 @@ -100,7 +101,7 @@ artifact URL and executes no guide step. ## Optional native-client report mode -The unpublished `0.1.3` source adds an optional `reports` port: +The verified `0.1.3` release includes 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 @@ -109,6 +110,24 @@ 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 unpublished `0.1.4` candidate additionally accepts optional `reports.query`, +extending that trio with `Partial>`. +The trusted method is `query(access, { articleId, status?: { ledgerEpoch, +reportId } })`. Its body-free result contains `target: { articleId, generation, +collectionId, kind }`, `requirements`, `ledger`, and optional owner-only `status`. +The dispatcher makes one query call for report-aware requirements and projects +only the existing requirements/reportLedger/reportStatus fields. Internal target +metadata and ledger capacity are not new wire fields. This is a producer port, +not an additional tool, scope, client flag or client-supplied authority. + +Supplying only the original trio retains its existing observation sequence. +Legacy requirements without `articleId` do not invoke query. A configured query's +failure or malformed output never falls back to a potentially different read; +missing or unsolicited status and inconsistent target/status identities refuse. +Collection/kind and epoch conflicts retain their existing safe errors. The +native query owns its current target, governance, ledger and final owner-status +observations; these do not form a cross-collection transaction. + The public types are `KnowledgeAgentReportRequirementsInput`, `KnowledgeAgentReportRequirementsResult`, `KnowledgeAgentReportSubmissionInput`, `KnowledgeAgentPendingReport`, `KnowledgeAgentReportEnvelope`, and @@ -161,13 +180,24 @@ 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. +all report/query work to the same original authenticated request, credential, +principal, grant, client and resource. Authenticate the initial transport request. +For pure reads, a host may retain per-port checks or use a request-local read +group: refresh full credential authority before its first read, enforce every +required permission clause on its restricted context, then refresh full current +authority after the completed actual `dispatcher.dispatch` invocation and before +any result is disclosed. Recheck the original header and all used scope and +permission requirements; never reuse the group across dispatches. MCP's actual +awaited tool callback is the boundary, not an outer Response that might precede +asynchronous tool work. Preserve fresh before/after guards on every write. + +Preserve the dispatcher-supplied restricted context; a freshly resolved +owner/Admin context must not replace it. The shared ledger's current-principal +checks do not independently authenticate a host grant. The `0.1.4` application +context/confirmation pair can reduce repeated governed reads, but its opaque, +single-use observation is instance- and caller-bound read bookkeeping, not a +credential, evidence attestation or permission. It is never serialized, stored +or supplied by the agent. See [report composition](EVIDENCE_REPORTS.md). Report writes and article reads/commits are separate. A later fence failure can withhold a response after a report was queued; conflict or unavailability @@ -191,6 +221,9 @@ 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. +Reducing public-port calls does not establish a D1 query, CPU, physical-row or +wall-clock allowance. Actual supported host profiles still require measurement; +this candidate makes no universal Free-tier acceptance claim. ## HTTP composition diff --git a/docs/AGENT_WORKFLOW.md b/docs/AGENT_WORKFLOW.md index 033d245..86d820f 100644 --- a/docs/AGENT_WORKFLOW.md +++ b/docs/AGENT_WORKFLOW.md @@ -5,10 +5,11 @@ 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, followed by the current verified -[`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 +since completed verified trusted publication. All four packages are now verified +published at [`0.1.3`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3), +including optional human-report mode. The synchronized unpublished `0.1.4` +candidate adds governed context reads and an optional aggregate report query; +its own review, gates, publication and strict verification remain open. 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). @@ -109,6 +110,15 @@ 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`. +The `0.1.4` source candidate can compose optional `reports.query` behind that +same requirements tool. It consolidates the current target/requirements, +ledger and optional owner-status observations without changing the client +request, result schema, five tools or three scopes. The original three report +methods remain a compatible fallback; omitting reports retains legacy mode. +Query target metadata, private report data and opaque context observations are +never added to the wire. A failed configured query refuses rather than silently +switching read paths. Clients do not request or authorize this optimization. + 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 @@ -140,10 +150,18 @@ reportGeneration }` and exact command input. This acknowledges a private 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 +The host must bind optional report/query calls to the original authenticated +request, credential, principal, grant, client and resource. Keep initial request +authentication. Pure reads may use a request-local full-credential check before +the first read and another after the complete actual dispatcher invocation, +checking every required scope/permission clause before disclosing its result. +That final check belongs inside the awaited MCP tool callback; guarding only an +outer Response is insufficient. Per-port read checks remain valid, and writes +retain fresh before/after guards. Never cache a read group across invocations. +Current owner/Admin authority never substitutes for the restricted delegated +context. An opaque application context observation only rechecks the producing +instance's exact read; it supplies no credential, human review or proof authority. +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. @@ -185,7 +203,8 @@ 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 current separate KB `0.1.2` trusted release is verified. +source is merged, and all four KB `0.1.3` packages have completed verified +publication. The earlier `0.1.2` release remains historical evidence. 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 @@ -193,8 +212,8 @@ 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.3` report-mode candidate retains its own gates, PR, and verified trusted release -pending. Both verified trusted dependencies precede production host +The KB `0.1.4` context/query 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. @@ -229,3 +248,6 @@ content, and operational evidence in their owning private systems. Actual client runs, staff review/publication, privacy, isolation, bounded work, and full human-workflow acceptance remain prerequisites before activation, A-01, and either supervised pilot. Synthetic SDK success waives none of them. +Fewer repeated reads do not prove a Free-tier D1 budget, CPU allowance or bounded +physical-row cost. Measure the actual supported host invocation profiles before +claiming readiness; this candidate closes no such acceptance gate. diff --git a/docs/BOOTSTRAP.md b/docs/BOOTSTRAP.md index 11e7b4b..f0cf37a 100644 --- a/docs/BOOTSTRAP.md +++ b/docs/BOOTSTRAP.md @@ -6,10 +6,10 @@ 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's current verified trusted release is `0.1.2`; Agent Access remains verified +KB's current verified trusted release is `0.1.3`; 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; +The dated trusted KB `0.1.1` and `0.1.2` receipts remain below as history. Synchronized +KB `0.1.4` is the unpublished governed authoring-context/report-query candidate; its own review, current-head CI, trusted publication, strict consumer verification and host acceptance remain pending. @@ -84,7 +84,65 @@ the approved dependency set or establishes real-host acceptance. ## Verified Knowledge Base release -### Current verified `0.1.2` release +### Current verified `0.1.3` release + +All four KB `0.1.3` packages completed exact-registry-byte, cryptographic +signature/Sigstore, authenticated source-provenance and public-consumer +qualification at **2026-11-09T00:05:01.700778Z**. The +[`v0.1.3` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3) +binds signed source +[`8b4c25aa6a40f0c56be97f07e3b7b5ac6136a99b`](https://github.com/pegma-dev/knowledge-base/commit/8b4c25aa6a40f0c56be97f07e3b7b5ac6136a99b) +and signed annotated tag object `07326885d0074075738b27d555790eda2802ffd2`. +The [release run's final attempt 5](https://github.com/pegma-dev/knowledge-base/actions/runs/42533473529/attempts/5) +has six successful job records, including the separate +[strict registry/consumer verification job](https://github.com/pegma-dev/knowledge-base/actions/runs/42533473529/job/128906942012). + +The actual original [Node 22](https://github.com/pegma-dev/knowledge-base/actions/runs/42533473529/job/128892580576) +and [Node 24](https://github.com/pegma-dev/knowledge-base/actions/runs/42533473529/job/128892580550) +release gates executed in attempt 1. Each passed 675 runtime tests across 16 +files and 128 release regressions, with zero skips, plus the required +format/type/example/package/protocol steps. Their successful records and the +original preparation were reused in the final attempt; they were not newly +executed gates in attempt 5. + +| Field | Value | +| --------------------------------------- | ------------------------------------------------------------------ | +| Original prepared attempt | `1` | +| Original prepared artifact ID | `13638542884` | +| Original ZIP SHA-256 | `25a4f95e7d5f9722f3b8ece3e20cf6bd35c5d6618abfa52d218319236b449464` | +| Independently retained manifest SHA-256 | `8a384bf5972eee0cd9796367a632d01b4b57832f33bac073665281dfd7b9ed8a` | +| Successful final attempt | `5` | + +The original [prepared ZIP is a public release asset](https://github.com/pegma-dev/knowledge-base/releases/download/v0.1.3/knowledge-base-v0.1.3-artifact-13638542884.zip). +Recovery retained that artifact and exact manifest/tarballs without repacking, +moving the signed tag or replacing any version. The authenticated original +per-package publication invocations are distinct from the final successful +idempotent publisher. An earlier writer job could fail after an accepted +upload; recovery did not treat that failure as rollback or republish its bytes: + +| Package | Original writer attempt | Original writer job | +| ----------- | ----------------------- | ----------------------------------------------------------------------------------------------------- | +| Contracts | `1` | [128894569185](https://github.com/pegma-dev/knowledge-base/actions/runs/42533473529/job/128894569185) | +| Core | `2` | [128897903802](https://github.com/pegma-dev/knowledge-base/actions/runs/42533473529/job/128897903802) | +| Application | `3` | [128900136498](https://github.com/pegma-dev/knowledge-base/actions/runs/42533473529/job/128900136498) | +| MCP | `4` | [128903298046](https://github.com/pegma-dev/knowledge-base/actions/runs/42533473529/job/128903298046) | + +The [public verification summary](https://github.com/pegma-dev/knowledge-base/releases/download/v0.1.3/knowledge-base-v0.1.3-verification.json) +records these bindings and qualified checks. It is a summary, not a substitute +for actual cryptographic verification. The clean synthetic registry consumer +imported all four public package roots and constructed the report factory with +both storage layouts and legacy optional modes. It did not perform report +admission or establish a durable host or actual client/staging acceptance. + +This release provides optional human-reviewed evidence reports. Synchronized +`0.1.4` source adds governed authoring contexts and optional report queries and +still requires its own review, current-head gates, trusted publication and +strict verification. Neither producer release closes Workers Free call/CPU +acceptance, host activation or pilot gates. + + + +### Historical 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 @@ -114,14 +172,13 @@ 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`. +replaced. At that release checkpoint, KB dist-tags were `latest: 0.1.2` and +`bootstrap: 0.1.0`; Agent Access was `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. +no shared human-reviewed report factory; that API subsequently shipped in +`0.1.3`, whose separate receipt is above. This historical release establishes +no actual host/client, privacy, activation or pilot acceptance. ### Historical verified `0.1.1` release @@ -153,8 +210,9 @@ At that historical checkpoint, all four packages had `latest: 0.1.1` and `bootst bootstrap receipts remain distinct and have no OIDC provenance. 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. +later `0.1.2` and `0.1.3` releases have their own receipts above; none completes +host/client, privacy, activation or pilot acceptance or verifies changed +`0.1.4` source. ## Verified Agent Access prerequisite @@ -198,8 +256,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.2` has its separate verified -receipt above; source `0.1.3` retains its own current-head gates, PR, trusted +candidate artifacts in a fresh consumer. KB `0.1.3` has its separate verified +receipt above; source `0.1.4` 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. @@ -278,10 +336,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.3` with exact internal dependency +The synchronized KB source candidate is `0.1.4` with exact internal dependency pins. It still needs review and all current-head gates before release. The historical first advertised trusted release is `0.1.1`; the current verified -release is `0.1.2`, recorded separately above. +release is `0.1.3`, 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 @@ -296,7 +354,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.2` and Agent +[source preparation](SOURCE_PREPARATION.md). The verified KB `0.1.3` and Agent Access `0.1.1` public producer release prerequisites are closed. This candidate requires its own verified release, and both hosts still require their retained actual login/Admin-consent/client/staging acceptance. diff --git a/docs/COLLECTIONS.md b/docs/COLLECTIONS.md index 3535654..f64a3b8 100644 --- a/docs/COLLECTIONS.md +++ b/docs/COLLECTIONS.md @@ -12,11 +12,12 @@ 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 -[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 +[current verified `0.1.3` release](BOOTSTRAP.md#current-verified-013-release) is +complete; the unpublished `0.1.4` governed authoring-context/report-query 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). +[historical receipt](BOOTSTRAP.md#historical-verified-011-release), as does +[`0.1.2`](BOOTSTRAP.md#historical-verified-012-release). ## Partition and authority rules diff --git a/docs/EVIDENCE_REPORTS.md b/docs/EVIDENCE_REPORTS.md index 607d791..562c270 100644 --- a/docs/EVIDENCE_REPORTS.md +++ b/docs/EVIDENCE_REPORTS.md @@ -1,10 +1,11 @@ # 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; +`createKnowledgeEvidenceReports` shipped in the four synchronized, verified +[`0.1.3` packages](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3). +Synchronized `0.1.4` is an **unpublished source candidate** adding the optional +governed context pair and body-free `query` described below. Its own review, +current-head CI, trusted publication and strict consumer verification remain +pending. Hosts must wait for exact verified publication before adopting new APIs; source tests and local adapter fixtures do not establish host activation, actual client acceptance, or a real staging test. @@ -20,22 +21,24 @@ 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. | +| 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. | +| `authoringContext` (`0.1.4` candidate) | Optionally forward both public `getAuthoringContext` and `confirmAuthoringContext` methods for an operation-local governed read/recheck. The legacy `readContext` option remains required and supported. | +| `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 +only when authorized, `getEvidence` reads. The candidate optional pair uses the +same restricted context through the new governed read instead. A report-supplied article, permission array, runner name, or `passed` value does not supply authority. The initial delegated scopes remain only `knowledgePermissions.draftRead`, @@ -48,10 +51,80 @@ 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. +those shapes; omitted-port legacy schemas stay unchanged. Keep initial request +authentication and bind all work to the same original request, credential, +principal, grant, client and resource. For pure report-port reads, hosts may +revalidate before and after each awaited call or use the +[request-local read-group boundary](AGENT_API.md#optional-native-client-report-mode): +refresh full credential authority before the first read and after the completed +actual dispatcher invocation, enforcing every required scope/permission clause +before disclosure. The final MCP check belongs inside its awaited tool callback. +Every write retains fresh before/after guards. Never reuse a read group across +invocations or replace the restricted effective context with owner/Admin authority. +The ledger's current-principal resolver is not a host credential/grant verifier. + +## Optional governed context and query (`0.1.4` candidate) + +The candidate application's +`getAuthoringContext(access, { articleId, includeEvidence?: boolean })` returns +`{ context, observation }`. It requires `draftRead` and either `draftWrite` or +`evidenceSubmit`, deriving the collection/kind from the current article. The +context contains the existing draft and narrow requirements DTOs. Explicit +`includeEvidence: true` additionally requires `evidenceRead` and includes the +complete current evidence and retained revocation DTO at that same generation. +Otherwise evidence is omitted, never substituted with empty history. Trusted +attester lists, full configuration, provenance and publication proofs remain out +of this projection. + +Forward the paired methods through `authoringContext`, using deferred closures +when the application receives this factory's verifier. Keep `readContext` for +legacy compatibility. The factory requests no private evidence for pending +agent admission/query and complete evidence for human qualification. With no +pair it retains the legacy full-context observation path. + +Keep the opaque observation only in the current operation and owning application +instance. `confirmAuthoringContext(access, observation)` requires the same actor +and projection permissions and checks exact article, collection and validation +head versions. It consumes the handle before storage, so a failed storage probe +needs a fresh observation. Copying, serializing or recreating the object does not +make a valid handle. It belongs in no database, wire response, command fingerprint, +report hash or retained receipt. It grants no permission, human confirmation, +evidence qualification or publication authority. + +Optimized report decisions retain fresh same-principal staff checks at entry, +after the metadata probe/preparation immediately before the write, and after +commit before releasing an ACK. Only the extra probe-adjacent resolution is +omitted; no content or side effect escapes before the fresh prewrite check. +Revoked authority can withhold an ACK after commit. Retry the exact command under +refreshed authority rather than assuming rollback or issuing a new command ID. + +`query(access, { articleId, status?: { ledgerEpoch, reportId } })` requires current +`draftRead` plus `evidenceSubmit`. It returns +`{ target, requirements, ledger, status? }`, where target contains only +`articleId`, application `generation`, `collectionId` and `kind`. Status contains +only the existing acknowledgement plus pending/confirmed/rejected state and is +available only to the submitting principal. It is not a report download or staff +listing. A lookup from another epoch, resetting ledger, changed report or changed +observed context refuses rather than presenting a synthesized current receipt. + +The query observes ledger/report state, confirms the governed context and reads +selected owner status again after the other awaited fences. These separate +collections still provide no atomic snapshot or receipt consumption. Its target +metadata is for the trusted dispatcher to match the requested collection/kind; +the existing wire projection excludes it, the full draft and all private fields. + +The candidate dispatcher's report port may optionally include `query`. It uses +that aggregate once for the article-specific requirements mode, retaining the +old `report`/`ledger`/`status` trio fallback and exactly the same five tools, +three scopes and wire DTOs. The host must preserve its reviewed current-credential +and same-principal disclosure fences; one SDK port call is not one database call +and does not replace Agent Access authentication. + +Prepared keyed-read waves can use optional provider batching without a new Store +API, SQL or collection layout. All admitted evidence/revocation history remains +intact. This source change establishes no universal Workers Free 50-query, CPU +or wall-clock guarantee. Complete host invocations, real authorities, supported +histories, retries and cold composition require their own measured acceptance. ## Submit, review, then qualify evidence @@ -79,14 +152,15 @@ 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`. | -| `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. | +| Method | Purpose and authority | +| --------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `ledger` | Body-free current epoch/capacity state; requires current `evidenceSubmit`. | +| `query` (`0.1.4` candidate) | Governed body-free requirements/ledger/optional owner status; requires current `draftRead` plus `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`, `evidenceRead`, and either `evidenceSubmit` or `draftWrite`, under diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index 828ab1f..3b2efb1 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -12,10 +12,13 @@ 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 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. +The four-package `0.1.2` atomic draft/source release is +[verified](BOOTSTRAP.md#current-verified-012-release). All four `0.1.3` +human-reviewed report packages subsequently completed +[verified trusted publication](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3). +Synchronized `0.1.4` is the unpublished governed authoring-context/report-query +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 @@ -118,18 +121,19 @@ clock, current scoped access, and verified external facts. The application does not take an actor, role list, timestamp, or permission grant from an untrusted command body as proof of authority. -| Operation family | Service methods | Required named permission | -| ---------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| Collection policy | `createCollection`, `previewCollectionPolicy`, `updateCollectionPolicy` | `collectionManage`; anonymous portal or bot use additionally needs `publicCollectionApprove` and explicit `approvePublic` | -| Validation/governance | `putValidationPolicy`, `putGovernanceConfiguration`, `getValidationPolicy`, `getGovernanceConfiguration` | `validationManage` | -| Collection staff view | `getCollection` | `collectionRead` | -| Author requirements | `getValidationRequirements` | `draftWrite` or `evidenceSubmit` | -| Drafts | `createDraft`, `updateDraft`; `getDraft` | `draftWrite`; `draftRead` respectively | -| Evidence | `submitEvidence`; `getEvidence`; `revokeEvidence` | `evidenceSubmit`; `evidenceRead`; `evidenceRevoke` respectively | -| Private provenance | `setProvenance`; `getProvenance` | `provenanceWrite`; `provenanceRead`, plus source-resource checks | -| Review | `submitForReview`; `getReview`, `rejectReview` | `reviewSubmit`; `review` respectively | -| Publication | `publishArticle`; `retireArticle` | `publish`; `retire` respectively | -| Portal-safe keyed read | `getPublishedArticle` | `articleRead` and the published collection's current portal audience | +| Operation family | Service methods | Required named permission | +| -------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| Collection policy | `createCollection`, `previewCollectionPolicy`, `updateCollectionPolicy` | `collectionManage`; anonymous portal or bot use additionally needs `publicCollectionApprove` and explicit `approvePublic` | +| Validation/governance | `putValidationPolicy`, `putGovernanceConfiguration`, `getValidationPolicy`, `getGovernanceConfiguration` | `validationManage` | +| Collection staff view | `getCollection` | `collectionRead` | +| Author requirements | `getValidationRequirements` | `draftWrite` or `evidenceSubmit` | +| Governed authoring (`0.1.4` candidate) | `getAuthoringContext`, `confirmAuthoringContext` | `draftRead` and (`draftWrite` or `evidenceSubmit`); private evidence additionally needs `evidenceRead` | +| Drafts | `createDraft`, `updateDraft`; `getDraft` | `draftWrite`; `draftRead` respectively | +| Evidence | `submitEvidence`; `getEvidence`; `revokeEvidence` | `evidenceSubmit`; `evidenceRead`; `evidenceRevoke` respectively | +| Private provenance | `setProvenance`; `getProvenance` | `provenanceWrite`; `provenanceRead`, plus source-resource checks | +| Review | `submitForReview`; `getReview`, `rejectReview` | `reviewSubmit`; `review` respectively | +| Publication | `publishArticle`; `retireArticle` | `publish`; `retire` respectively | +| Portal-safe keyed read | `getPublishedArticle` | `articleRead` and the published collection's current portal audience | Names in this table are members of the contracts package's `knowledgePermissions`; they are permission identifiers, not roles. Resource @@ -172,6 +176,50 @@ validation-policy reference, governance generation, and expected staging build for authorized authors. It omits trusted attester IDs; full governance configuration remains an administrative read. +### Governed authoring context (`0.1.4` candidate) + +`getAuthoringContext(access, { articleId, includeEvidence?: boolean })` returns +`{ context, observation }`. The context combines current `draft` and narrow +`requirements`. It derives collection/kind from the actual article and checks +exact article, collection and validation-policy head versions before returning. +It does not hydrate unrelated publication or provenance material. Explicit +`includeEvidence: true` requires `evidenceRead` and adds the complete current +evidence and retained revocation DTO at the draft's generation. Omission excludes +that DTO; it is never a claim that accepted or revoked evidence is empty. + +`confirmAuthoringContext(access, observation)` rechecks those heads for the same +actor and required projection permissions. The opaque handle belongs to one +application instance and current operation. Confirmation consumes it before +storage reads; retrying after a storage failure needs a new observation. Never +clone, serialize, persist, send or hash the handle into report/replay identity. +It exposes no Store version and supplies no permission, verified proof, review +or publication authority. A confirmation cannot turn a restricted context into +the resolver's broader human authority. + +The report factory's optional paired `authoringContext` port uses this operation- +local recheck instead of a second full context hydration. Its required legacy +`readContext` port remains supported. Optimized decisions retain live entry, +post-probe prewrite and postcommit staff checks; they omit only the redundant +metadata-probe-adjacent resolution. No DTO or side effect is released before the +fresh prewrite check. A postcommit denial can withhold an accepted ACK, so preserve +the exact original command for recovery. + +The candidate `reports.query` returns body-free target metadata, requirements, +ledger state and optional owner-only status under `draftRead` plus +`evidenceSubmit`. The optional agent report port can use it through the existing +requirements operation; legacy report trios retain their fallback. It returns +no draft body, private evidence, report details, reviewer or provenance. See +[evidence reports](EVIDENCE_REPORTS.md) for composition and exact privacy rules. + +These are finite current observations across separate partitions, not a global +snapshot or policy lock. Evidence qualification, exact review/publication and +host credential freshness remain independent checks. Private record keys are +prepared before parallel keyed reads so a provider may batch them through its +existing Store implementation. Full history remains subject to the existing +bounds, without truncation or a new lifetime cap. Fewer calls do not prove a +universal Workers Free 50-query or CPU budget; measure complete real host +invocations, supported histories, cold composition and contention separately. + Use application generation for optimistic mutation commands. Content revision is only the version of the article text and metadata: diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 192416e..9e54a3e 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -16,35 +16,42 @@ and clean-consumer verification at **2026-11-07T23:35:31Z**. The [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. -The current verified KB release is `0.1.2`, at signed source +The historical SD-03 KB `0.1.2` release, 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 +[historical receipt](BOOTSTRAP.md#historical-verified-012-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, +The current verified release is [`0.1.3`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3) +at signed source `8b4c25aa6a40f0c56be97f07e3b7b5ac6136a99b`. All four exact +registry packages passed signature/provenance and public-consumer qualification; +the [receipt](BOOTSTRAP.md#current-verified-013-release) distinguishes original +writer attempts 1–4 from the final successful attempt 5 and binds the unchanged +original prepared artifact. + +Source `0.1.4` is the synchronized **unpublished** candidate for governed +authoring-context reads and optional report queries. 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. +[report guide](EVIDENCE_REPORTS.md) distinguishes the released `0.1.3` factory +from the `0.1.4` candidate additions. No `v0.1.4` publication 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.2` publication +CI links, counts, review, and security receipts. The verified `0.1.3` 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 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. +independently retained digests. The qualified release versions are KB `0.1.3` +and Agent Access `0.1.1`. The manual `0.1.0` bootstraps and their dated dist-tag +observations remain historical integrity receipts without OIDC provenance. [Agent Access](https://github.com/pegma-dev/agent-access) is a separate release. Its `0.1.1` trusted publication and strict registry verification completed at @@ -55,7 +62,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.3` candidate still needs its own current-head gates, review, PR, publication, +The KB `0.1.4` candidate still needs its own current-head gates, review, PR, publication, and strict verification; historical source-proof results do not validate this changed composition. Production hosts require verified trusted versions of both components and their separately retained acceptance. diff --git a/docs/RETRIEVAL.md b/docs/RETRIEVAL.md index 00489d5..33d02c2 100644 --- a/docs/RETRIEVAL.md +++ b/docs/RETRIEVAL.md @@ -9,14 +9,18 @@ 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 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 +followed by the [historical `0.1.2` release](BOOTSTRAP.md#historical-verified-012-release) +and current [verified `0.1.3` release](BOOTSTRAP.md#current-verified-013-release). +Source `0.1.4` is the unpublished governed authoring-context/report-query 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. +The optional bounded repair mode described below is also unpublished `0.1.4` +candidate behavior. It requires the candidate's own validation and release; +this guide does not establish a passing host quota or CPU profile. + Read [declared collections](COLLECTIONS.md) for the authoritative record layout and [host composition](HOST_COMPOSITION.md) for trusted access, evidence, source eligibility, and safe DTO boundaries. @@ -110,22 +114,22 @@ These are component work/admission ceilings, not measured production capacity or retrieval-quality certification. Hosts may configure lower values only. Each independent bound still applies when another bound has remaining space. -| Scope | Ceiling | -| --------------------- | ------------------------------------------------------------------------------------------------ | -| Directory | 64 collections per instance | -| Catalog | 256 articles per collection | -| Terms | 256 indexed terms per article | -| Posting | 16 entries per page; 16 pages per term | -| Projection partition | 8,192 physical rows and 16 MiB encoded-record estimate | -| Query | 256 UTF-16 code units and 8 distinct normalized terms | -| Bot query scope | 4 collections | -| Request index work | 128 keyed index reads and 2,048 posting entries | -| Request article work | 64 head probes and 8 full authoritative confirmations | -| Returned sources | 5 whole articles and 64 KiB of content | -| Model source budget | 8,192 tokens in the complete serialized source set | -| Request physical work | 768 total physical keyed reads | -| Maintenance scan | Configured row ceiling 100; actual page also bounded by requested limit and shared batch ceiling | -| Maintenance batches | 32 shared per maintenance call; at most 32 physical scan rows with defaults | +| Scope | Ceiling | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| Directory | 64 collections per instance | +| Catalog | 256 articles per collection | +| Terms | 256 indexed terms per article | +| Posting | 16 entries per page; 16 pages per term | +| Projection partition | 8,192 physical rows and 16 MiB encoded-record estimate | +| Query | 256 UTF-16 code units and 8 distinct normalized terms | +| Bot query scope | 4 collections | +| Request index work | 128 keyed index reads and 2,048 posting entries | +| Request article work | 64 head probes and 8 full authoritative confirmations | +| Returned sources | 5 whole articles and 64 KiB of content | +| Model source budget | 8,192 tokens in the complete serialized source set | +| Request physical work | 768 total physical keyed reads | +| Maintenance scan | Configured row ceiling 100; actual page also bounded by requested limit and shared batch ceiling | +| Maintenance batches | Legacy advancement allowance 32; optional transaction-attempt budget at most 32 per resource; default physical scan at most 32 rows | Count physical work before filtering and deduplication. A query cannot bypass work limits by retrieving many unauthorized, duplicate, or stale entries. @@ -184,15 +188,61 @@ confirms collection labels and portal access. `repairRetrievalPage` scans at most the minimum of its requested limit, `maxRepairScanRows`, and `maxMaintenanceBatches`. Defaults therefore scan at most 32 physical rows, even though the configurable scan ceiling is 100. -Each unique resource gets at most one collection registration or article -advancement batch on that page; -`repairArticleIndex` can use the full shared batch allowance for its one -article. A completed scan page or cycle is not proof all pending projections +When `maxBatches` is omitted, each unique resource gets at most one collection +registration or article advancement batch on that page; +`repairArticleIndex` can use the full instance advancement allowance for its one +article, default 32. These legacy allowances include internal prerequisite work +and bounded conflict retries; they are not a count of physical Store transactions. +A completed scan page or cycle is not proof all pending projections are finished. Hosts persist the actual backend `nextCursor` and repeat full cycles to revisit pending heads/jobs without starving later resources. Repair does not mutate or acknowledge authoritative causal jobs; they remain replay-safe hints. +Both repair methods accept optional `maxBatches`, a positive integer no greater +than the instance's `maxMaintenanceBatches`. Explicit presence selects a shared +physical Store transaction-attempt budget: `repairArticleIndex` shares it across +that article's projection setup, directory/catalog registration, posting rewrites, +completion and blocked-state writes. A failed CAS consumes an attempt too; +nested retries cannot reset the budget. Already-current prerequisites consume +no attempt, so repeated one-attempt calls can reach later phases rather than +repeating the first completed write. `repairRetrievalPage` gives each unique +resource its own budget, including collection-directory work. The page's +physical scan limit remains independent; `maxBatches: 1` does not mean one +transaction across a multi-resource page. + +A host can call `repairArticleIndex(access, { articleId, maxBatches: 1 })` in a +dedicated worker invocation. For one-resource scan recovery, use +`repairRetrievalPage(access, { limit: 1, maxBatches: 1, cursor })`, omitting +`cursor` at a cycle's start. Publication and withdrawal commands already persist +their causal `article_changed` jobs atomically with the article change, Audit +and replay receipt. Hosts may schedule derived work separately from the mutation +response; a second enqueue is not required to establish that durable recovery +source. Jobs remain hints: every repair plans from current authoritative facts. + +Per-article manifests and pending scopes retain committed progress. After a +lost write acknowledgement, the next invocation re-reads actual state and +resumes the same plan without resetting completed terms or generation floors. +Budget exhaustion or a bounded CAS conflict returns conservative `pending` with +`indexed: false`. Storage or current-source confirmation can still throw after +a partial derived write. Keep the work pending and retry the original scan +cursor on an exception. After a successful bounded page, save its actual +`nextCursor` even if an article remains pending, then revisit it on later full +cycles; pinning the global cursor to one unfinished article can starve others. +Capacity holds remain visible and need available capacity or changed inputs +before convergence. + +The attempt budget bounds derived transaction attempts, not all keyed reads, +backend statements, schema initialization, host checkpoint/OCC work, external +source-verifier I/O, CPU or elapsed time. A Store adapter may issue several +queries per operation. Hosts must measure the entire invocation on their actual +composition; neither page size one nor a transaction budget of one certifies a +Workers Free quota or a latency/capacity SLA. No retained proof or revocation +history is discarded. Prepared keyed-read waves preserve every required approved +proof and its current revocation marker, and final current +article/collection/validation-head and source +confirmation; they introduce no authorization cache or provider-specific SQL. + Derived writes and cleanup must be generation-fenced and idempotent so a delayed job cannot restore obsolete content. Persist bounded per-article pending/blocked progress and capacity reasons. Do not mark an article indexed @@ -221,6 +271,11 @@ withdrawal is `ready` with `indexed: false`; ready does not necessarily mean there is a usable indexed publication. Terms, postings, hashes, and private sources are absent. Repair-page diagnostic counts and `nextCursor` are staff-only and never become customer search totals. +Only a current call returning `ready` establishes completion of that repair +plan. A host's ready-key hint may be acknowledged only against its unchanged +version after that result; `pending`, `blocked`, exceptions and an older ready +observation are not completion acknowledgements. This does not turn the result +into publication or customer-read authority. Staff maintenance is not a customer no-result path: unexpected configuration, adapter, or storage errors remain visible exceptions. Supported admission and source-hold conditions retain their named status/withdrawal behavior. diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md index cd18820..11810f7 100644 --- a/docs/SOURCE_PREPARATION.md +++ b/docs/SOURCE_PREPARATION.md @@ -51,16 +51,18 @@ postflight at **2026-11-07T21:56:24Z**, without OIDC provenance; see the The subsequent four-package `0.1.1` trusted release completed strict verification at **2026-11-07T23:35:31Z**; see its separate [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, +The subsequent SD-03 atomic draft/source `0.1.2` release has a +[historical verified receipt](BOOTSTRAP.md#historical-verified-012-release). +The optional human-report `0.1.3` release is now +[verified](BOOTSTRAP.md#current-verified-013-release). Source `0.1.4` is the +unpublished governed authoring-context/report-query 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 | +| Artifacts | Four-package checks, schema-2 preparation, and manual `0.1.0` exact-byte postflight | Verified `0.1.1`/`0.1.2`/`0.1.3` receipts are separate; `0.1.4` 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 @@ -298,10 +300,10 @@ 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 current KB `0.1.2` trusted release has completed complete-set registry +The current KB `0.1.3` trusted release has completed complete-set registry integrity/signature/provenance verification and released-consumer proof; its -[receipt](BOOTSTRAP.md#current-verified-012-release) is separate from these -historical source records. The unpublished `0.1.3` human-report source candidate +[receipt](BOOTSTRAP.md#current-verified-013-release) is separate from these +historical source records. The unpublished `0.1.4` governed context/query source candidate retains its own review, current-head gates, trusted publication, strict verification, and released-consumer proof. Manual bootstrap is not OIDC provenance. @@ -324,8 +326,8 @@ closed the public producer prerequisite; see the [exact receipt](BOOTSTRAP.md#verified-agent-access-prerequisite). The original source-producer proof remains historical evidence, while the changed registry composition requires its own current-head gates. -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 +The verified KB `0.1.3` and Agent Access `0.1.1` producer release prerequisites +are closed. The new `0.1.4` context/query 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, diff --git a/examples/agent/README.md b/examples/agent/README.md index b38c850..81484b8 100644 --- a/examples/agent/README.md +++ b/examples/agent/README.md @@ -20,6 +20,11 @@ not establish any of the four target client applications, a deployed host, real browser login, real staging execution, verified KB publication, or host activation. Real host/client acceptance and activation remain open. +The four packed KB artifacts in this working tree are unpublished `0.1.4` +candidates. The separate [verified `0.1.3` release](../../docs/BOOTSTRAP.md#current-verified-013-release) +does not validate changed context/query source; `0.1.4` retains its own review, +current-head gates, trusted publication and strict consumer verification. + ## Artifact boundary The [orchestrator](../../scripts/agent-protocol-proof.mjs): diff --git a/examples/composition/README.md b/examples/composition/README.md index 0e82731..aadf5c6 100644 --- a/examples/composition/README.md +++ b/examples/composition/README.md @@ -23,9 +23,11 @@ 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 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 +The four-package `0.1.2` release has a +[historical verified receipt](../../docs/BOOTSTRAP.md#historical-verified-012-release). +The current four-package `0.1.3` release is +[verified](../../docs/BOOTSTRAP.md#current-verified-013-release). Source `0.1.4` +is the unpublished governed context/query candidate requiring its own reviewed, verified trusted release. Production hosts retain their separate acceptance gates. diff --git a/package.json b/package.json index 4a4d4f4..e83e1d2 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.3", + "@pegma/knowledge-base-application": "0.1.4", "@pegma/knowledge-base-application-previous": "npm:@pegma/knowledge-base-application@0.1.1", - "@pegma/knowledge-base-contracts": "0.1.3", - "@pegma/knowledge-base-core": "0.1.3", - "@pegma/knowledge-base-mcp": "0.1.3", + "@pegma/knowledge-base-contracts": "0.1.4", + "@pegma/knowledge-base-core": "0.1.4", + "@pegma/knowledge-base-mcp": "0.1.4", "@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 9a87875..902cecc 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -14,9 +14,12 @@ 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. -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. +Links pinned to `v0.1.2` below retain that historical verified release contract. +The optional report service shipped in the verified +[`v0.1.3` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3). +Governed authoring-context and report-query additions are unpublished `0.1.4` +candidate source; their guide uses DEVELOPMENT `main` until their 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; @@ -130,11 +133,49 @@ 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) +## Governed authoring reads (new source) + +`getAuthoringContext(access, { articleId, includeEvidence?: boolean })` +returns `{ context, observation }`. The context contains the current draft and +narrow validation requirements, without hydrating private provenance or an +unrelated retained publication. It requires `draftRead` and either `draftWrite` +or `evidenceSubmit`. Explicit `includeEvidence: true` additionally requires +`evidenceRead` and returns the complete current evidence and revocation DTO at +the same article generation. Omission excludes that material; it does not mean +empty accepted evidence or revocation history. + +The read confirms exact article, collection and validation-policy head versions. +`confirmAuthoringContext(access, observation)` checks those heads again under +the original actor and required permissions. It consumes the instance-bound +handle before storage, including on failure. Keep it only within the current +operation: never clone, serialize, persist or send it to a client. It grants +no permission or evidence/publication authority, and supplies no cross-partition +lock. Resolve host authority freshly at its existing operation boundaries. + +Reports can opt into these methods through the optional paired +`authoringContext` factory port. Deferred forwarding closures preserve the +application/verifier construction cycle. The required legacy `readContext` +port and its two-context behavior remain supported. A report decision using +the optional pair retains live entry, post-probe prewrite and postcommit staff +checks; exact replay fingerprints contain no observation. + +`reports.query(access, { articleId, status?: { ledgerEpoch, reportId } })` +combines safe requirements, ledger state and optional owner-only status. It +requires `draftRead` plus `evidenceSubmit` and returns a body-free target binding, +never a draft body, report, evidence or provenance. The optional MCP query port +uses the existing requirements tool and response shape; it adds no scope/tool. + +Evidence/revocation keys are prepared before a parallel keyed-read wave, allowing +a provider's optional batching without a new Store method or private SQL. This +does not establish a host query/CPU budget: legitimate histories remain bounded +by the existing component limits, and real host profiles need measured proof. + +## Human-reviewed evidence reports (`0.1.3` release) 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. +input, view, acknowledgement and error types. The factory shipped in verified +`0.1.3`; the governed context/report-query additions are the unpublished +synchronized `0.1.4` candidate. 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) @@ -171,8 +212,9 @@ provider data controls; current publication checks remain mandatory. ranked prefix of whole articles within aggregate byte/token budgets with a positive local count; reconfirmation is exact and all-or-nothing. `retrieval.limits` can only lower fixed component ceilings. -See [retrieval](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RETRIEVAL.md) -for the exact API, limits, authority/reference fences, and evaluation boundary. +See the verified `v0.1.3` +[retrieval contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.3/docs/RETRIEVAL.md) +for its exact API, limits, authority/reference fences, and evaluation boundary. `repairArticleIndex`, `repairRetrievalPage`, and `getArticleIndexStatus` require `indexManage`. Only maintenance performs bounded physical scans with opaque @@ -181,6 +223,34 @@ cursors. Pending/blocked status remains visible until repair converges; may lag retirement/revocation, but current authority checks still reject ineligible publications. The host owns scheduling and recovery. +The unpublished `0.1.4` candidate accepts optional `maxBatches` on keyed and +paged repair. It must be a positive integer within the instance's +`maxMaintenanceBatches`. Explicit `maxBatches: 1` shares one physical Store +transaction attempt across the article's prerequisites, posting work and +completion; failed CAS attempts count, while already-current prerequisites do +not. Page repair applies the allowance separately to each resource, including +collection-directory work. Use `limit: 1` as well when scheduling one resource +per invocation. Omission retains legacy behavior: keyed repair can perform up +to the instance's advancement allowance (default 32), and page repair gives +each candidate one advancement with internal prerequisite/retry work. + +Committed manifests and pending scopes let later calls resume after partial +failure or a lost acknowledgement. Budget exhaustion returns conservative +`pending`; storage or current-source confirmation may still throw. Retain work +on pending, blocked or error; acknowledge a host ready-key hint only after a +current `ready` result and an unchanged hint version. Save actual successful +scan continuations and repeat full cycles, including when individual articles +remain pending. Existing atomic `article_changed` jobs remain recovery hints. +No article mutation, Audit, receipt or proof history is discarded or reset. + +This bounds derived transaction attempts, not total backend queries, verifier +I/O, host checkpoints, CPU or elapsed time. Prepared read waves preserve all +required approved proofs and revocation markers, and final current publication, +audience, source and head checks. Retained history is unchanged. They add no +authorization cache and do not establish +Workers Free quota acceptance. The candidate's own gates, trusted release and +whole-host measurements remain separate. + ## Storage and limits All accepted head changes, immutable rows, generic Audit actions, receipts, and diff --git a/packages/application/package.json b/packages/application/package.json index 125f9f6..df77539 100644 --- a/packages/application/package.json +++ b/packages/application/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-application", - "version": "0.1.3", + "version": "0.1.4", "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.3", - "@pegma/knowledge-base-core": "0.1.3", + "@pegma/knowledge-base-contracts": "0.1.4", + "@pegma/knowledge-base-core": "0.1.4", "@pegma/spine": "0.1.2", "@pegma/storage-core": "0.4.0" }, diff --git a/packages/application/src/articles.ts b/packages/application/src/articles.ts index c6b1747..b892b6f 100644 --- a/packages/application/src/articles.ts +++ b/packages/application/src/articles.ts @@ -21,7 +21,11 @@ import { KnowledgeBasePrerequisiteError, requirePermission, } from "./errors.js"; -import { loadGovernanceContext } from "./governance.js"; +import { + confirmGovernanceObservation, + loadGovernanceContext, + readGovernanceObservation, +} from "./governance.js"; import { maximumRecordNativeBytes, type StoredArticle } from "./records.js"; import type { KnowledgeRepository, @@ -505,19 +509,11 @@ export function createArticleServices( if (typeof verifier?.verify !== "function") { throw new KnowledgeBasePrerequisiteError("evidence-verifier"); } - const before = await loadGovernanceContext( + const before = await readGovernanceObservation( repository, stored.article.current.collectionId, options.clock.now(), ); - const collection = await repository.readCollectionVersioned( - stored.article.current.collectionId, - ); - if (collection?.value.configuration === undefined) { - throw new KnowledgeBasePrerequisiteError( - "governance-configuration", - ); - } let attestation: VerificationEvidence["attestation"] | null; try { const verified = await verifier.verify({ @@ -525,7 +521,7 @@ export function createArticleServices( article: snapshotData(stored.article.current), submission: snapshotData(command.evidence), receipt: command.receipt, - configuration: snapshotData(collection.value.configuration), + configuration: snapshotData(before.configuration), }); attestation = verified === null || verified === undefined @@ -537,21 +533,11 @@ export function createArticleServices( if (attestation === null || attestation === undefined) { throw new KnowledgeBasePrerequisiteError("evidence-verifier"); } - const after = await loadGovernanceContext( - repository, - stored.article.current.collectionId, - options.clock.now(), - ); - if ( - before.governanceGeneration !== after.governanceGeneration || - before.validationGeneration !== after.validationGeneration || - collection.value.generation !== before.governanceGeneration - ) - throw new RepositoryConflictError(); + await confirmGovernanceObservation(repository, before); const article = await recordEvidence(stored.article, { evidence: command.evidence, attestation, - context: after.context, + context: { ...before.context, at: options.clock.now() }, }); return { next: { ...withoutPendingReview(stored), article } }; }, diff --git a/packages/application/src/evidence-reports-types.ts b/packages/application/src/evidence-reports-types.ts index 1a3463a..5fcd41c 100644 --- a/packages/application/src/evidence-reports-types.ts +++ b/packages/application/src/evidence-reports-types.ts @@ -1,6 +1,7 @@ import type { AccessContext } from "@pegma/authorization-core"; import type { Clock, + ArticleKind, IsoTimestamp, Logger, PrincipalId, @@ -9,6 +10,7 @@ import type { EvidenceSubmission } from "@pegma/knowledge-base-core"; import type { Store } from "@pegma/storage-core"; import type { DraftArticleDto, + KnowledgeBaseApplication, EvidenceDto, EvidenceVerifier, ValidationRequirementsDto, @@ -80,6 +82,28 @@ export interface KnowledgeReportArticleInput { readonly articleId: string; } +export interface KnowledgeReportQueryInput extends KnowledgeReportArticleInput { + readonly status?: { + readonly ledgerEpoch: number; + readonly reportId: string; + }; +} + +/** Body-free governed authoring target and owner-only report status. */ +export interface KnowledgeReportQueryResult { + readonly target: { + readonly articleId: string; + readonly generation: number; + readonly collectionId: string; + readonly kind: ArticleKind; + }; + readonly requirements: ValidationRequirementsDto; + readonly ledger: KnowledgeReportLedgerState; + readonly status?: KnowledgeReportAcknowledgement & { + readonly status: KnowledgeReportStatus; + }; +} + export interface KnowledgeReportKey extends KnowledgeReportArticleInput { readonly ledgerEpoch: number; readonly reportId: string; @@ -136,11 +160,20 @@ export interface KnowledgeEvidenceReportsOptions { access: AccessContext, articleId: string, ) => Promise; + /** Optional operation-local observation/recheck; legacy readContext remains valid. */ + readonly authoringContext?: Pick< + KnowledgeBaseApplication, + "getAuthoringContext" | "confirmAuthoringContext" + >; readonly logger?: Logger; } export interface KnowledgeEvidenceReports { readonly verifier: EvidenceVerifier; + query( + access: AccessContext, + input: KnowledgeReportQueryInput, + ): Promise; report( access: AccessContext, input: SubmitKnowledgeReportInput, diff --git a/packages/application/src/evidence-reports.ts b/packages/application/src/evidence-reports.ts index 32a1a2b..9880494 100644 --- a/packages/application/src/evidence-reports.ts +++ b/packages/application/src/evidence-reports.ts @@ -14,7 +14,10 @@ import { type ArticleRevision, } from "@pegma/knowledge-base-contracts"; import { defineCollection, type EntityKey } from "@pegma/storage-core"; -import type { EvidenceVerifier } from "./types.js"; +import type { + EvidenceVerifier, + KnowledgeAuthoringContextObservation, +} from "./types.js"; import type { KnowledgeTestReport, KnowledgeReportAcknowledgement, @@ -35,7 +38,7 @@ import { KnowledgeBaseAuthorizationError, KnowledgeBaseNotFoundError, } from "./errors.js"; -import { snapshotData } from "./storage-helpers.js"; +import { RepositoryConflictError, snapshotData } from "./storage-helpers.js"; const MAX_REPORTS = 16; const MAX_ROWS = 160; @@ -679,10 +682,28 @@ export function createKnowledgeEvidenceReports( ].some((permission) => permission === confirmationPermission) || typeof options.resolvePrincipal !== "function" || typeof options.readContext !== "function" || + (options.authoringContext !== undefined && + (options.authoringContext === null || + typeof options.authoringContext.getAuthoringContext !== "function" || + typeof options.authoringContext.confirmAuthoringContext !== + "function")) || typeof options.store?.collection !== "function" || typeof options.clock?.now !== "function" ) throw new KnowledgeEvidenceReportsError("invalid_configuration"); + const authoringContext = + options.authoringContext === undefined + ? undefined + : { + getAuthoringContext: + options.authoringContext.getAuthoringContext.bind( + options.authoringContext, + ), + confirmAuthoringContext: + options.authoringContext.confirmAuthoringContext.bind( + options.authoringContext, + ), + }; function storageKey(articleId: string, id: string): EntityKey { if (storageLayout === "legacy-raw-v1") return { partition: articleId, id }; const partition = encodedKey("a-", articleId); @@ -810,13 +831,56 @@ export function createKnowledgeEvidenceReports( throw new KnowledgeEvidenceReportsUnavailableError("report_identity"); return report; } - async function context( + async function observedReport( + articleId: string, + epoch: number, + reportId: string, + ) { + 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 ( + saved.value.articleId !== articleId || + saved.value.id !== reportKey(epoch, reportId) || + report.articleId !== articleId || + report.reportId !== reportId || + report.ledgerEpoch !== epoch + ) + throw new KnowledgeEvidenceReportsUnavailableError("report_identity"); + return { value: report, version: saved.version }; + } + async function observeContext( access: AccessContext, articleId: string, - ): Promise { + includeEvidence: boolean, + ): Promise<{ + readonly value: KnowledgeEvidenceContext; + readonly observation?: KnowledgeAuthoringContextObservation; + }> { try { + const observed = + authoringContext === undefined + ? undefined + : await authoringContext.getAuthoringContext(callerContext(access), { + articleId, + includeEvidence, + }); + if ( + authoringContext !== undefined && + (observed === undefined || + observed.observation === null || + typeof observed.observation !== "object") + ) + throw new KnowledgeEvidenceReportsUnavailableError("context_read"); + // Only detach JSON context. The instance-bound observation must never be + // cloned, persisted, hashed into report identity, or exposed in a DTO. const value = snapshotData( - await options.readContext(callerContext(access), articleId), + observed === undefined + ? await options.readContext(callerContext(access), articleId) + : observed.context, ); if ( value.draft.articleId !== articleId || @@ -853,7 +917,18 @@ export function createKnowledgeEvidenceReports( } }); } - return value; + if ( + authoringContext !== undefined && + includeEvidence && + value.evidence === undefined + ) + throw new KnowledgeEvidenceReportsUnavailableError("context_read"); + return { + value, + ...(observed === undefined + ? {} + : { observation: observed.observation }), + }; } catch (error) { if (error instanceof KnowledgeEvidenceReportsError) throw error; if (error instanceof KnowledgeBaseAuthorizationError) @@ -863,6 +938,34 @@ export function createKnowledgeEvidenceReports( throw new KnowledgeEvidenceReportsUnavailableError("context_read"); } } + async function context( + access: AccessContext, + articleId: string, + includeEvidence = hasPermission(access, knowledgePermissions.evidenceRead), + ): Promise { + return (await observeContext(access, articleId, includeEvidence)).value; + } + async function confirmContext( + access: AccessContext, + observation: KnowledgeAuthoringContextObservation, + ): Promise { + try { + if (authoringContext === undefined) + throw new KnowledgeEvidenceReportsUnavailableError("context_read"); + await authoringContext.confirmAuthoringContext( + callerContext(access), + observation, + ); + } catch (error) { + if (error instanceof KnowledgeEvidenceReportsUnavailableError) + throw error; + if (error instanceof RepositoryConflictError) + throw new KnowledgeEvidenceReportsError("report_changed"); + if (error instanceof KnowledgeBaseAuthorizationError) + throw new KnowledgeEvidenceReportsError("forbidden"); + throw new KnowledgeEvidenceReportsUnavailableError("context_read"); + } + } async function contextHashes(value: KnowledgeEvidenceContext) { return { articleHash: await knowledgeDigest(value.draft.revision), @@ -1011,12 +1114,9 @@ export function createKnowledgeEvidenceReports( receiptGeneration: report.receiptGeneration, }, }); - await current( - access, - previousVersion === undefined - ? knowledgePermissions.evidenceSubmit - : confirmationPermission, - ); + if (previousVersion === undefined) + await current(access, knowledgePermissions.evidenceSubmit); + else await staff(access); const headRow = row(report.articleId, "head", { ...head.value, reports, @@ -1086,8 +1186,10 @@ export function createKnowledgeEvidenceReports( 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); + const [, report] = await Promise.all([ + active(request.article.articleId, epoch), + load(request.article.articleId, epoch, reportId), + ]); if ( report.receiptGeneration !== cycle || report.status !== "confirmed" || @@ -1165,6 +1267,110 @@ export function createKnowledgeEvidenceReports( }; return Object.freeze({ verifier, + async query(access, input) { + input = requestData(input); + access = await current(access, knowledgePermissions.evidenceSubmit); + if (!hasPermission(access, knowledgePermissions.draftRead)) + throw new KnowledgeEvidenceReportsError("forbidden"); + const request = optionalKeysObject(input, ["articleId"], ["status"]); + const articleId = scalar(request.articleId); + const statusInput = Object.hasOwn(request, "status") + ? exactObject(request.status, ["ledgerEpoch", "reportId"]) + : undefined; + const lookup = + statusInput === undefined + ? undefined + : { + ledgerEpoch: positive(statusInput.ledgerEpoch), + reportId: scalar(statusInput.reportId), + }; + const observed = await observeContext(access, articleId, false); + const first = observed.value; + const head = await headVersion(articleId); + if (lookup !== undefined) { + if (head.value.ledgerEpoch !== lookup.ledgerEpoch) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (head.value.status !== "active") + throw new KnowledgeEvidenceReportsError("ledger_resetting"); + } + const report = + lookup === undefined + ? undefined + : await observedReport( + articleId, + lookup.ledgerEpoch, + lookup.reportId, + ); + if ( + report !== undefined && + report.value.submittedBy !== access.principalId + ) + throw new KnowledgeEvidenceReportsError("report_not_found"); + if (observed.observation !== undefined) { + await confirmContext(access, observed.observation); + } else { + const latest = await context(access, articleId, false); + if ( + latest.draft.generation !== first.draft.generation || + latest.draft.revision.collectionId !== + first.draft.revision.collectionId || + latest.draft.revision.kind !== first.draft.revision.kind || + (await knowledgeDigest(latest.requirements)) !== + (await knowledgeDigest(first.requirements)) + ) + throw new KnowledgeEvidenceReportsError("report_changed"); + } + // Context confirmation can await a ledger reset without changing the old + // report row. Observe both ledger and owner status after that work in one + // keyed-read wave; these separate authorities still provide no lock. + const [latestHead, latestReport] = await Promise.all([ + headVersion(articleId), + lookup === undefined + ? undefined + : observedReport(articleId, lookup.ledgerEpoch, lookup.reportId), + ]); + if ( + latestHead.value.ledgerEpoch !== head.value.ledgerEpoch || + latestHead.value.status !== head.value.status + ) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (latestHead.version !== head.version) + throw new KnowledgeEvidenceReportsError("ledger_changed"); + if ( + report !== undefined && + (latestReport === undefined || + latestReport.version !== report.version || + latestReport.value.submittedBy !== access.principalId || + latestReport.value.reportGeneration !== + report.value.reportGeneration || + latestReport.value.receiptGeneration !== + report.value.receiptGeneration || + latestReport.value.status !== report.value.status || + latestReport.value.reportHash !== report.value.reportHash) + ) + throw new KnowledgeEvidenceReportsError("report_changed"); + // Re-resolve only after the awaited resource observations, preserving the + // original credential's restricted permissions through final disclosure. + await current(access, knowledgePermissions.evidenceSubmit); + return { + target: { + articleId, + generation: first.draft.generation, + collectionId: first.draft.revision.collectionId, + kind: first.draft.revision.kind, + }, + requirements: first.requirements, + ledger: state(articleId, latestHead.value), + ...(latestReport === undefined + ? {} + : { + status: { + ...acknowledgement(latestReport.value), + status: latestReport.value.status, + }, + }), + }; + }, async ledger(access, input) { input = requestData(input); access = await current(access, knowledgePermissions.evidenceSubmit); @@ -1221,7 +1427,7 @@ export function createKnowledgeEvidenceReports( } if (!validSubmissionSyntax(evidence)) throw new KnowledgeEvidenceReportsError("invalid_request"); - const valueContext = await context(access, articleId); + const valueContext = await context(access, articleId, false); if ( expectedArticleGeneration !== undefined && valueContext.draft.generation !== expectedArticleGeneration @@ -1331,7 +1537,7 @@ export function createKnowledgeEvidenceReports( 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 valueContext = await context(access, articleId, true); const reviewBindingHash = await knowledgeDigest({ report, context: valueContext, @@ -1411,7 +1617,8 @@ export function createKnowledgeEvidenceReports( : report.status !== "pending") ) throw new KnowledgeEvidenceReportsError("report_changed"); - const valueContext = await context(access, articleId); + const observed = await observeContext(access, articleId, true); + const valueContext = observed.value; if ( (await knowledgeDigest({ report, context: valueContext })) !== binding ) @@ -1442,12 +1649,19 @@ export function createKnowledgeEvidenceReports( !(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"); + if (observed.observation !== undefined) { + // This probe releases no DTO or side effect. write() resolves the + // original caller's complete live staff authority after the probe and + // its head read, immediately before CAS, then again after commit. + await confirmContext(access, observed.observation); + } else { + 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) { diff --git a/packages/application/src/governance.ts b/packages/application/src/governance.ts index 92f62a4..1e9cca2 100644 --- a/packages/application/src/governance.ts +++ b/packages/application/src/governance.ts @@ -182,13 +182,18 @@ export interface CurrentGovernanceContext { readonly governanceGeneration: number; readonly validationGeneration: number; } +export interface GovernanceObservation extends CurrentGovernanceContext { + readonly collectionVersion: string; + readonly validationVersion: string; + readonly configuration: GovernanceConfiguration; +} -/** Load authoritative application facts; author input cannot supply this context. */ -export async function loadGovernanceContext( +/** Initial authoritative facts; the caller must subsequently fence the heads. */ +export async function readGovernanceObservation( repository: KnowledgeRepository, collectionId: string, at: IsoTimestamp, -): Promise { +): Promise { requireIdentifier(collectionId, "collectionId"); const collection = await repository.readCollectionVersioned(collectionId); if (collection === null) throw new KnowledgeBaseNotFoundError("collection"); @@ -208,18 +213,6 @@ export async function loadGovernanceContext( throw new KnowledgeBasePrerequisiteError("current_validation_policy"); } validateValidationPolicy(validation.value.policy); - const [current, currentValidation] = await Promise.all([ - repository.readCollectionVersioned(collectionId), - repository.readValidationPolicyVersioned(configuration.validationPolicy.id), - ]); - if ( - current === null || - current.value.generation !== collection.value.generation || - currentValidation === null || - currentValidation.value.generation !== validation.value.generation - ) { - throw new RepositoryConflictError(); - } return snapshotData({ context: { collection: collection.value.collection, @@ -230,9 +223,62 @@ export async function loadGovernanceContext( }, governanceGeneration: collection.value.generation, validationGeneration: validation.value.generation, + collectionVersion: collection.version, + validationVersion: validation.version, + configuration, }); } +/** Recheck current authority heads after all verifier/fact awaits. */ +export async function confirmGovernanceObservation( + repository: KnowledgeRepository, + observed: GovernanceObservation, +): Promise { + await repository.confirmGovernanceVersions([ + { + kind: "collection", + id: observed.context.collection.id, + version: observed.collectionVersion, + }, + { + kind: "validation", + id: observed.context.validationPolicy.id, + version: observed.validationVersion, + }, + ]); +} + +/** Load authoritative application facts; author input cannot supply this context. */ +export async function loadGovernanceContext( + repository: KnowledgeRepository, + collectionId: string, + at: IsoTimestamp, +): Promise { + const observed = await readGovernanceObservation( + repository, + collectionId, + at, + ); + const [current, currentValidation] = await Promise.all([ + repository.readCollectionVersioned(collectionId), + repository.readValidationPolicyVersioned( + observed.context.validationPolicy.id, + ), + ]); + if ( + current === null || + current.value.generation !== observed.governanceGeneration || + currentValidation === null || + currentValidation.value.generation !== observed.validationGeneration + ) + throw new RepositoryConflictError(); + return { + context: observed.context, + governanceGeneration: observed.governanceGeneration, + validationGeneration: observed.validationGeneration, + }; +} + export function createGovernanceServices( repository: KnowledgeRepository, options: KnowledgeBaseServiceOptions, diff --git a/packages/application/src/publication.ts b/packages/application/src/publication.ts index d4d9ccf..0f97337 100644 --- a/packages/application/src/publication.ts +++ b/packages/application/src/publication.ts @@ -20,10 +20,11 @@ import { KnowledgeBaseNotFoundError, KnowledgeBasePrerequisiteError, } from "./errors.js"; -import { loadGovernanceContext } from "./governance.js"; +import { readGovernanceObservation } from "./governance.js"; import type { ArticlePublicationState, KnowledgeRepository, + ResourceVersion, } from "./repository.js"; import { canonicalJson, @@ -82,6 +83,7 @@ interface ConfirmationState { readonly revision: ArticleRevision; readonly source: SourceSnapshot; readonly use?: CollectionUse; + readonly versions: readonly ResourceVersion[]; } function unavailable(): KnowledgeBaseNotFoundError { @@ -152,22 +154,12 @@ async function publishedEvidence( references.length > knowledgeLimits.evidence ) throw new RepositoryIntegrityError(); - return Promise.all( - references.map(async (reference) => { - const [evidence, revoked] = await Promise.all([ - repository.getEvidenceVersion( - current.articleId, - published.revision.number, - reference.id, - reference.version, - ), - repository.isEvidenceRevoked(current.articleId, reference.hash), - ]); - if (evidence === null || revoked || evidence.hash !== reference.hash) - throw unavailable(); - return evidence; - }), + const evidence = await repository.readPublicationEvidence( + current.articleId, + published, ); + if (evidence === null) throw unavailable(); + return evidence; } /** One authority path for portal reads, customer bot retrieval, and private indexing. */ @@ -215,23 +207,8 @@ export function createPublicationChecker( } if (eligible.some((value) => value !== true)) throw unavailable(); } - const [article, collection, validation] = await Promise.all([ - repository.readResourceGeneration("article", state.binding.articleId), - repository.readResourceGeneration( - "collection", - state.binding.collectionId, - ), - repository.readResourceGeneration( - "validation", - state.binding.validationPolicy.id, - ), - ]); - if ( - article !== state.binding.articleGeneration || - collection !== state.binding.governanceGeneration || - validation !== state.binding.validationGeneration - ) - throw unavailable(); + await repository.confirmResourceVersions(state.versions); + clockTime(options); authorize(state.access, state.purpose); } @@ -271,7 +248,7 @@ export function createPublicationChecker( ) throw unavailable(); const at = clockTime(options); - const governance = await loadGovernanceContext( + const governance = await readGovernanceObservation( repository, revision.collectionId, at, @@ -345,13 +322,26 @@ export function createPublicationChecker( sourceGeneration: source.generation, sourceSnapshotHash: source.hash, }; - const state = immutable( + const state: ConfirmationState = immutable( snapshotData({ access, purpose, binding, revision, source, + versions: [ + { kind: "article", id: articleId, version: loaded!.version }, + { + kind: "collection", + id: revision.collectionId, + version: governance.collectionVersion, + }, + { + kind: "validation", + id: revision.validationPolicy.id, + version: governance.validationVersion, + }, + ] satisfies readonly ResourceVersion[], ...(use === undefined ? {} : { use }), }), ); diff --git a/packages/application/src/reads.ts b/packages/application/src/reads.ts index 56b969c..c52cde2 100644 --- a/packages/application/src/reads.ts +++ b/packages/application/src/reads.ts @@ -6,14 +6,18 @@ import { } from "@pegma/knowledge-base-contracts"; import { + KnowledgeBaseAuthorizationError, KnowledgeBaseNotFoundError, KnowledgeBasePrerequisiteError, requirePermission, } from "./errors.js"; -import { loadGovernanceContext } from "./governance.js"; +import { + loadGovernanceContext, + readGovernanceObservation, +} from "./governance.js"; import { createPublicationChecker } from "./publication.js"; import type { StoredArticle } from "./records.js"; -import type { KnowledgeRepository } from "./repository.js"; +import type { KnowledgeRepository, ResourceVersion } from "./repository.js"; import { canonicalJson, RepositoryConflictError, @@ -24,6 +28,7 @@ import { import type { KnowledgeBaseApplication, KnowledgeBaseServiceOptions, + KnowledgeAuthoringContextObservation, PrivateSourceReference, SourceSnapshot, } from "./types.js"; @@ -86,6 +91,8 @@ export function createReadServices( | "getValidationPolicy" | "getGovernanceConfiguration" | "getValidationRequirements" + | "getAuthoringContext" + | "confirmAuthoringContext" | "getDraft" | "getEvidence" | "getProvenance" @@ -93,7 +100,131 @@ export function createReadServices( | "getPublishedArticle" > { const publications = createPublicationChecker(repository, options); + const observations = new WeakMap< + KnowledgeAuthoringContextObservation, + { + readonly actorId: string; + readonly includeEvidence: boolean; + readonly resources: readonly ResourceVersion[]; + } + >(); + function authoringPermission( + access: Parameters[0], + includeEvidence: boolean, + ): void { + requireIdentifier(access.principalId, "principalId"); + requirePermission(access, knowledgePermissions.draftRead); + if (!hasPermission(access, knowledgePermissions.evidenceSubmit)) + requirePermission(access, knowledgePermissions.draftWrite); + if (includeEvidence) + requirePermission(access, knowledgePermissions.evidenceRead); + } return { + async getAuthoringContext(access, request) { + access = snapshotData(access); + const input = readInput(request, "articleId", ["includeEvidence"]); + if ( + Object.hasOwn(input, "includeEvidence") && + typeof input.includeEvidence !== "boolean" + ) + throw new TypeError("includeEvidence must be a boolean"); + const includeEvidence = input.includeEvidence === true; + authoringPermission(access, includeEvidence); + const article = await repository.readArticleAuthoringVersioned( + input.articleId, + includeEvidence, + ); + if (article === null) throw new KnowledgeBaseNotFoundError("article"); + const current = article.value; + const governance = await readGovernanceObservation( + repository, + current.current.collectionId, + clockTime(options), + ); + const resources: readonly ResourceVersion[] = [ + { kind: "article", id: input.articleId, version: article.version }, + { + kind: "collection", + id: current.current.collectionId, + version: governance.collectionVersion, + }, + { + kind: "validation", + id: governance.context.validationPolicy.id, + version: governance.validationVersion, + }, + ]; + await repository.confirmResourceVersions(resources); + authoringPermission(access, includeEvidence); + const context = snapshotData({ + draft: { + articleId: current.articleId, + generation: current.generation, + state: current.state, + revision: current.current, + hasPendingReview: current.hasPendingReview, + hasPublication: current.hasPublication, + publicationHeld: current.publicationHeld, + }, + requirements: { + collectionId: current.current.collectionId, + governanceGeneration: governance.governanceGeneration, + validationPolicy: { + id: governance.context.validationPolicy.id, + version: governance.context.validationPolicy.version, + }, + expectedStagingBuildId: governance.context.expectedStagingBuildId, + checks: governance.context.validationPolicy.requirements + .filter((check) => check.kind === current.current.kind) + .map((check) => ({ + id: check.id, + testKind: check.testKind, + maxAgeMilliseconds: check.maxAgeMilliseconds, + })), + }, + ...(includeEvidence + ? { + evidence: { + articleId: current.articleId, + generation: current.generation, + evidence: current.evidence!, + revokedEvidence: current.revokedEvidence!, + }, + } + : {}), + }); + const observation = Object.freeze( + {}, + ) as KnowledgeAuthoringContextObservation; + observations.set(observation, { + actorId: access.principalId, + includeEvidence, + resources, + }); + return { context, observation }; + }, + + async confirmAuthoringContext(access, observation) { + access = snapshotData(access); + const captured = + observation !== null && typeof observation === "object" + ? observations.get(observation) + : undefined; + if (captured === undefined) + throw new TypeError( + "Authoring observation is invalid or already consumed", + ); + authoringPermission(access, captured.includeEvidence); + if (access.principalId !== captured.actorId) + throw new KnowledgeBaseAuthorizationError( + knowledgePermissions.draftRead, + ); + // Consume before storage so concurrent callers cannot reuse the handle. + observations.delete(observation); + await repository.confirmResourceVersions(captured.resources); + authoringPermission(access, captured.includeEvidence); + }, + async getCollection(access, request) { access = snapshotData(access); requirePermission(access, knowledgePermissions.collectionRead); diff --git a/packages/application/src/repository.ts b/packages/application/src/repository.ts index 0b8aeb3..6a6e358 100644 --- a/packages/application/src/repository.ts +++ b/packages/application/src/repository.ts @@ -105,6 +105,23 @@ export interface ArticlePublicationState { readonly publishedProvenance?: SourceSnapshot; readonly publicationReview?: ReviewSnapshot; } +/** Current authoring material only; excludes publication and provenance rows. */ +export interface ArticleAuthoringState { + readonly articleId: string; + readonly generation: number; + readonly state: Article["state"]; + readonly current: ArticleRevision; + readonly hasPendingReview: boolean; + readonly hasPublication: boolean; + readonly publicationHeld: boolean; + readonly evidence?: readonly VerificationEvidence[]; + readonly revokedEvidence?: readonly EvidenceRevocation[]; +} +export interface ResourceVersion { + readonly kind: ResourceKind; + readonly id: string; + readonly version: string; +} export interface KnowledgeRepository { readonly limits: KnowledgeRepositoryLimits; readArticleVersioned( @@ -113,6 +130,19 @@ export interface KnowledgeRepository { readArticlePublicationVersioned( id: string, ): Promise | null>; + /** Complete approved proof rows and revocation markers in one prepared wave. */ + readPublicationEvidence( + id: string, + publication: PublishedArticle, + ): Promise; + readArticleAuthoringVersioned( + id: string, + includeEvidence: boolean, + ): Promise | null>; + confirmResourceVersions(resources: readonly ResourceVersion[]): Promise; + confirmGovernanceVersions( + resources: readonly ResourceVersion[], + ): Promise; /** One keyed head read; never hydrates draft, evidence, or private source rows. */ readResourceGeneration( kind: ResourceKind, @@ -374,12 +404,52 @@ export function createKnowledgeRepository( throw new RepositoryIntegrityError(); return row.data as T; } - async function getHead( + async function preparedRows( kind: ResourceKind, id: string, - ): Promise | null> { + keys: readonly string[], + ): Promise> { + const unique = [...new Set(keys)]; + for (const key of unique) { + if ( + typeof key !== "string" || + key.length === 0 || + key.length > 300 || + /[^A-Za-z0-9|:._-]/u.test(key) + ) + throw new RepositoryIntegrityError(); + } const scope = await partition(kind, id); - const row = await records.getVersioned({ partition: scope, id: "head" }); + const rows = await Promise.all( + unique.map((key) => records.get({ partition: scope, id: key })), + ); + return new Map( + unique.map((key, index) => { + const row = rows[index]; + if (row === undefined) throw new RepositoryIntegrityError(); + if (row !== null) checkIdentity(row, kind, id, scope, key); + return [key, row] as const; + }), + ); + } + function planned( + rows: ReadonlyMap, + key: string, + expectedKind: KnowledgeRecord["kind"], + ): T { + const row = rows.get(key); + if (row === undefined || row === null || row.kind !== expectedKind) + throw new RepositoryIntegrityError(); + // Separate logical references retain detached values even when they share + // one immutable physical row in this operation's plan. + return snapshotData(row.data) as T; + } + function checkedHead( + kind: ResourceKind, + id: string, + scope: string, + row: VersionedRecord | null, + ): VersionedRecord | null { if (row === null) return null; checkIdentity(row.value, kind, id, scope, "head"); try { @@ -438,6 +508,135 @@ export function createKnowledgeRepository( throw new RepositoryIntegrityError(); } } + async function getHead( + kind: ResourceKind, + id: string, + ): Promise | null> { + const scope = await partition(kind, id); + return checkedHead( + kind, + id, + scope, + await records.getVersioned({ partition: scope, id: "head" }), + ); + } + async function confirmVersions( + resources: readonly ResourceVersion[], + ): Promise { + // Finish every async key calculation before issuing a synchronous read + // wave, allowing a provider's optional keyed-read batching to coalesce it. + const scopes = await Promise.all( + resources.map(({ kind, id }) => partition(kind, id)), + ); + const heads = await Promise.all( + resources.map(({ kind, id }, index) => + records + .getVersioned({ partition: scopes[index]!, id: "head" }) + .then((row) => checkedHead(kind, id, scopes[index]!, row)), + ), + ); + if ( + heads.some( + (head, index) => + head === null || head.version !== resources[index]!.version, + ) + ) + throw new RepositoryConflictError(); + } + async function confirmResourceVersions( + resources: readonly ResourceVersion[], + ): Promise { + if (resources.length !== 3) throw new RepositoryIntegrityError(); + await confirmVersions(resources); + } + async function confirmGovernanceVersions( + resources: readonly ResourceVersion[], + ): Promise { + if ( + resources.length !== 2 || + resources[0]?.kind !== "collection" || + resources[1]?.kind !== "validation" + ) + throw new RepositoryIntegrityError(); + await confirmVersions(resources); + } + async function readAuthoring( + id: string, + includeEvidence: boolean, + ): Promise | null> { + const head = await getHead("article", id); + if (head === null) return null; + const pointer = (head.value.data as Head).pointer; + if (pointer.resourceKind !== "article") + throw new RepositoryIntegrityError(); + const scope = await partition("article", id); + const references = includeEvidence ? pointer.evidence : []; + const revocations = includeEvidence ? pointer.revocations : []; + const evidenceKeys = await Promise.all( + references.map((reference) => + evidenceId(reference.articleRevision, reference.id, reference.version), + ), + ); + const keys = [ + "revision:" + pointer.current, + ...evidenceKeys, + ...revocations.map((hash) => "revoked:" + hash), + ]; + // All partitions and evidence hashes are ready. Do not call getRow here: + // its per-row async hashing would split the provider's keyed-read wave. + const rows = await Promise.all( + keys.map((key) => records.get({ partition: scope, id: key })), + ); + for (let index = 0; index < rows.length; index += 1) { + const row = rows[index]; + if (row === null || row === undefined) + throw new RepositoryIntegrityError(); + checkIdentity(row, "article", id, scope, keys[index]!); + } + const currentRow = rows[0]!; + const current = currentRow.data as ArticleRevision; + if ( + currentRow.kind !== "revision" || + current.articleId !== id || + current.number !== pointer.current + ) + throw new RepositoryIntegrityError(); + const evidence = references.map((reference, index) => { + const row = rows[index + 1]!; + const value = row.data as VerificationEvidence; + if ( + row.kind !== "evidence" || + value.articleId !== id || + value.articleRevision !== pointer.current || + value.articleRevision !== reference.articleRevision || + value.id !== reference.id || + value.version !== reference.version || + value.hash !== reference.hash + ) + throw new RepositoryIntegrityError(); + return value; + }); + const revokedEvidence = revocations.map((hash, index) => { + const row = rows[1 + references.length + index]!; + const value = row.data as EvidenceRevocation; + if (row.kind !== "revocation" || value.hash !== hash) + throw new RepositoryIntegrityError(); + return value; + }); + return { + version: head.version, + value: { + articleId: id, + generation: pointer.generation, + state: pointer.state, + current, + hasPendingReview: pointer.review !== undefined, + hasPublication: pointer.published !== undefined, + publicationHeld: pointer.publicationHeld, + ...(includeEvidence ? { evidence, revokedEvidence } : {}), + }, + }; + } async function getRevision( id: string, number: number, @@ -485,10 +684,14 @@ export function createKnowledgeRepository( if (pointer.resourceKind !== kind) throw new RepositoryIntegrityError(); validatePointer(pointer); if (pointer.resourceKind === "collection") { - const collection = await required( - kind, - id, - "collection-policy:" + pointer.revision, + const policyKey = "collection-policy:" + pointer.revision; + const rows = await preparedRows(kind, id, [ + policyKey, + ...(pointer.configuration === undefined ? [] : [pointer.configuration]), + ]); + const collection = planned( + rows, + policyKey, "collection-policy", ); if (collection.id !== id || collection.revision !== pointer.revision) @@ -496,9 +699,8 @@ export function createKnowledgeRepository( const configuration = pointer.configuration === undefined ? undefined - : await required( - kind, - id, + : planned( + rows, pointer.configuration, "configuration", ); @@ -528,44 +730,79 @@ export function createKnowledgeRepository( typeof pointer.publicationHeld !== "boolean" ) throw new RepositoryIntegrityError(); - const current = await getRevision(id, pointer.current); - if (current === null) throw new RepositoryIntegrityError(); - const evidence = await Promise.all( - pointer.evidence.map(async (reference) => { - if (reference.articleRevision !== pointer.current) - throw new RepositoryIntegrityError(); - const value = await getEvidence( - id, - reference.articleRevision, - reference.id, - reference.version, - ); - if (value === null || value.hash !== reference.hash) - throw new RepositoryIntegrityError(); - return value; - }), + const evidenceKeys = await Promise.all( + pointer.evidence.map((reference) => + evidenceId(reference.articleRevision, reference.id, reference.version), + ), ); - const provenance = await required( - kind, - id, - "provenance:" + pointer.provenance, + const currentKey = "revision:" + pointer.current; + const provenanceKey = "provenance:" + pointer.provenance; + const publishedRevisionKey = + pointer.published === undefined + ? undefined + : "revision:" + pointer.published.revision; + const publishedProvenanceKey = + pointer.publishedProvenance === undefined + ? undefined + : "provenance:" + pointer.publishedProvenance; + const rows = await preparedRows(kind, id, [ + currentKey, + ...evidenceKeys, + provenanceKey, + ...(pointer.review === undefined ? [] : [pointer.review]), + ...(pointer.published === undefined + ? [] + : [publishedRevisionKey!, pointer.published.approval]), + ...(publishedProvenanceKey === undefined ? [] : [publishedProvenanceKey]), + ...(pointer.publicationReview === undefined + ? [] + : [pointer.publicationReview]), + ...pointer.revocations.map((hash) => "revoked:" + hash), + ]); + const current = planned(rows, currentKey, "revision"); + if (current.articleId !== id || current.number !== pointer.current) + throw new RepositoryIntegrityError(); + const evidence = pointer.evidence.map((reference, index) => { + const value = planned( + rows, + evidenceKeys[index]!, + "evidence", + ); + if ( + reference.articleRevision !== pointer.current || + value.articleId !== id || + value.articleRevision !== reference.articleRevision || + value.id !== reference.id || + value.version !== reference.version || + value.hash !== reference.hash + ) + throw new RepositoryIntegrityError(); + return value; + }); + const provenance = planned( + rows, + provenanceKey, "provenance", ); const review = pointer.review === undefined ? undefined - : await required(kind, id, pointer.review, "review"); + : planned(rows, pointer.review, "review"); let published: Article["published"]; if (pointer.published !== undefined) { - const revision = await getRevision(id, pointer.published.revision); - const approval = await required( - kind, - id, + const revision = planned( + rows, + publishedRevisionKey!, + "revision", + ); + const approval = planned( + rows, pointer.published.approval, "publication", ); if ( - revision === null || + revision.articleId !== id || + revision.number !== pointer.published.revision || approval.binding.articleId !== id || approval.binding.articleRevision !== revision.number || approval.binding.contentHash !== revision.contentHash @@ -576,25 +813,13 @@ export function createKnowledgeRepository( const publishedProvenance = pointer.publishedProvenance === undefined ? undefined - : await required( - kind, - id, - "provenance:" + pointer.publishedProvenance, - "provenance", - ); + : planned(rows, publishedProvenanceKey!, "provenance"); const publicationReview = pointer.publicationReview === undefined ? undefined - : await required( - kind, - id, - pointer.publicationReview, - "review", - ); - const revokedEvidence = await Promise.all( - pointer.revocations.map((hash) => - required(kind, id, "revoked:" + hash, "revocation"), - ), + : planned(rows, pointer.publicationReview, "review"); + const revokedEvidence = pointer.revocations.map((hash) => + planned(rows, "revoked:" + hash, "revocation"), ); const article: Article = { id, @@ -640,30 +865,33 @@ export function createKnowledgeRepository( publicationHeld: pointer.publicationHeld, }; if (pointer.published === undefined) return { value, version: row.version }; - const [revision, approval, publishedProvenance, publicationReview] = - await Promise.all([ - getRevision(id, pointer.published.revision), - required( - "article", - id, - pointer.published.approval, - "publication", - ), - required( - "article", - id, - "provenance:" + pointer.publishedProvenance, - "provenance", - ), - required( - "article", - id, - pointer.publicationReview!, - "review", - ), - ]); + const revisionKey = "revision:" + pointer.published.revision; + const provenanceKey = "provenance:" + pointer.publishedProvenance; + const rows = await preparedRows("article", id, [ + revisionKey, + pointer.published.approval, + provenanceKey, + pointer.publicationReview!, + ]); + const revision = planned(rows, revisionKey, "revision"); + const approval = planned( + rows, + pointer.published.approval, + "publication", + ); + const publishedProvenance = planned( + rows, + provenanceKey, + "provenance", + ); + const publicationReview = planned( + rows, + pointer.publicationReview!, + "review", + ); if ( - revision === null || + revision.articleId !== id || + revision.number !== pointer.published.revision || approval.binding.articleId !== id || approval.binding.articleRevision !== revision.number || approval.binding.contentHash !== revision.contentHash @@ -680,6 +908,55 @@ export function createKnowledgeRepository( version: row.version, }; } + async function readPublicationEvidence( + id: string, + publication: PublishedArticle, + ): Promise { + const references = publication.approval.binding.evidence; + if (!Array.isArray(references) || references.length > 32) + throw new RepositoryIntegrityError(); + const keys = await Promise.all( + references.map((reference) => + evidenceId( + publication.revision.number, + reference.id, + reference.version, + ), + ), + ); + const revokedKeys = references.map((reference) => { + if (!/^[a-f0-9]{64}$/u.test(reference.hash)) + throw new RepositoryIntegrityError(); + return "revoked:" + reference.hash; + }); + const rows = await preparedRows("article", id, [...keys, ...revokedKeys]); + const result: VerificationEvidence[] = []; + for (const [index, reference] of references.entries()) { + const proof = rows.get(keys[index]!); + const revoked = rows.get(revokedKeys[index]!); + if (proof === undefined || revoked === undefined) + throw new RepositoryIntegrityError(); + if ( + revoked !== null && + (revoked.kind !== "revocation" || + (revoked.data as EvidenceRevocation).hash !== reference.hash) + ) + throw new RepositoryIntegrityError(); + if (proof === null || revoked !== null) return null; + const value = proof.data as VerificationEvidence; + if ( + proof.kind !== "evidence" || + value.articleId !== id || + value.articleRevision !== publication.revision.number || + value.id !== reference.id || + value.version !== reference.version || + value.hash !== reference.hash + ) + throw new RepositoryIntegrityError(); + result.push(snapshotData(value)); + } + return result; + } async function execute( kind: ResourceKind, input: MutationInput, @@ -766,7 +1043,7 @@ export function createKnowledgeRepository( ); const next = snapshotData({ ...decision.next, generation }) as T; const additions: KnowledgeRecord[] = []; - const queued = new Map(); + const proposals = new Map(); let immutablePlanningCollision = false; const buildRow = ( id: string, @@ -786,27 +1063,13 @@ export function createKnowledgeRepository( rowKind: KnowledgeRecord["kind"], data: unknown, ): Promise => { - if (immutablePlanningCollision) return; const record = buildRow(key, rowKind, data); - const pending = queued.get(key); + const pending = proposals.get(key); if (pending !== undefined) { - if (canonicalJson(pending) !== canonicalJson(record)) - throw new RepositoryIntegrityError(); + pending.push(record); return; } - const previous = await getRow(kind, request.id, key); - if (previous !== null) { - if (canonicalJson(previous) !== canonicalJson(record)) { - // A matching command may have committed after this attempt read - // its receipt. Re-enter the receipt-first, authorized retry path; - // server timestamps are not part of semantic command identity. - immutablePlanningCollision = true; - } - return; - } - encodeKnowledgeRecord(record); - queued.set(key, record); - additions.push(record); + proposals.set(key, [record]); }; let pointer: Pointer; if (kind === "article") { @@ -991,6 +1254,36 @@ export function createKnowledgeRepository( version: value.policy.version, }; } + // Finish every immutable proposal/hash before issuing keyed I/O. This + // map is attempt-local, including absent rows; no admission is cached + // across a conflict or authorized receipt-first retry. + const previousRows = await preparedRows(kind, request.id, [ + ...proposals.keys(), + ]); + for (const [key, candidates] of proposals) { + const previous = previousRows.get(key); + if (previous === undefined) throw new RepositoryIntegrityError(); + if (previous !== null) { + if ( + candidates.some( + (record) => canonicalJson(previous) !== canonicalJson(record), + ) + ) + immutablePlanningCollision = true; + continue; + } + const record = candidates[0]!; + if ( + candidates.some( + (candidate) => canonicalJson(candidate) !== canonicalJson(record), + ) + ) + throw new RepositoryIntegrityError(); + encodeKnowledgeRecord(record); + additions.push(record); + } + // A matching command may have committed after the earlier receipt read. + // Retry that original authorized path rather than overwrite history. if (immutablePlanningCollision) continue; const audit = defineAudit({ collection: knowledgeRecords, @@ -1154,6 +1447,10 @@ export function createKnowledgeRepository( limits, readArticleVersioned: (id) => read("article", id), readArticlePublicationVersioned: readPublication, + readPublicationEvidence, + readArticleAuthoringVersioned: readAuthoring, + confirmResourceVersions, + confirmGovernanceVersions, readResourceGeneration: async (kind, id) => { const row = await getHead(kind, id); return row === null ? null : (row.value.data as Head).pointer.generation; diff --git a/packages/application/src/retrieval-maintenance.ts b/packages/application/src/retrieval-maintenance.ts index 1d7a1d5..e90aa39 100644 --- a/packages/application/src/retrieval-maintenance.ts +++ b/packages/application/src/retrieval-maintenance.ts @@ -15,12 +15,17 @@ import type { RetrievalProjectionState, RetrievalProjectionTarget, } from "./retrieval-records.js"; -import type { createRetrievalRepository } from "./retrieval-repository.js"; +import { + RetrievalStepBudgetError, + type RetrievalStepBudget, + type createRetrievalRepository, +} from "./retrieval-repository.js"; import type { ArticleIndexInput, ArticleIndexStatusDto, KnowledgeRetrievalApplication, KnowledgeRetrievalLimits, + RepairArticleIndexInput, RepairRetrievalPageInput, } from "./retrieval-types.js"; import { @@ -48,6 +53,7 @@ interface MaintenanceOptions { interface BatchBudget { remaining: number; + readonly step?: RetrievalStepBudget; } interface DesiredProjection { @@ -97,6 +103,32 @@ export function createRetrievalMaintenanceServices( } const records = options.store.collection(knowledgeRecords); + function maxBatches(value: number | undefined): number | undefined { + if ( + value !== undefined && + (!Number.isSafeInteger(value) || + value < 1 || + value > limits.maxMaintenanceBatches) + ) + throw new TypeError("Repair attempts exceed the maintenance bound"); + return value; + } + + async function pendingStep(articleId: string, plan?: DesiredProjection) { + // Exhausting a write allowance never skips the original post-write source + // and A/C/V confirmation. Its failure stays visible to the host worker. + if (plan !== undefined) await recheckDesired(articleId, plan); + const current = await retrieval.readArticleProjection(articleId); + return status( + articleId, + plan?.articleGeneration ?? null, + current, + "pending", + false, + "conflict", + ); + } + function caller(access: AccessContext): AccessContext { const current = snapshotData(access); requirePermission(current, knowledgePermissions.indexManage); @@ -317,6 +349,7 @@ export function createRetrievalMaintenanceServices( state: RetrievalProjectionState | null, reason: RetrievalBlockedReason, sourceGeneration?: number, + budget?: RetrievalStepBudget, ): Promise { if (state === null && sourceGeneration === undefined) return null; try { @@ -325,6 +358,7 @@ export function createRetrievalMaintenanceServices( state?.generation ?? 1, reason, state === null ? sourceGeneration : undefined, + budget, ); } catch (error) { if (!(error instanceof RepositoryConflictError)) throw error; @@ -343,6 +377,7 @@ export function createRetrievalMaintenanceServices( attempt < repository.limits.maxConflictAttempts; attempt += 1 ) { + if (budget.step?.remaining === 0) return pendingStep(articleId); if (budget.remaining === 0) return currentStatus(access, articleId); let state = await retrieval.readArticleProjection(articleId); let plan: DesiredProjection | undefined; @@ -353,26 +388,38 @@ export function createRetrievalMaintenanceServices( await recheckDesired(articleId, plan); const generation = (state?.generation ?? 0) + 1; requireGeneration(generation, 1); - state = await retrieval.beginArticleProjection({ - articleId, - generation, - sourceGeneration: plan.articleGeneration ?? state!.sourceGeneration, - targets: plan.targets, - }); + state = await retrieval.beginArticleProjection( + { + articleId, + generation, + sourceGeneration: plan.articleGeneration ?? state!.sourceGeneration, + targets: plan.targets, + }, + budget.step, + ); await recheckDesired(articleId, plan); + if (budget.step?.remaining === 0) return pendingStep(articleId, plan); while (state.status === "pending" && budget.remaining > 0) { await recheckDesired(articleId, plan); budget.remaining -= 1; const advanced = await retrieval.advanceArticleProjection( articleId, state.generation, + budget.step, ); state = advanced.state; await recheckDesired(articleId, plan); if (advanced.complete) break; + if (budget.step?.remaining === 0) return pendingStep(articleId, plan); } if (plan.capacity) { - state = await markBlocked(articleId, state, "capacity"); + state = await markBlocked( + articleId, + state, + "capacity", + undefined, + budget.step, + ); return status( articleId, plan.articleGeneration, @@ -391,13 +438,22 @@ export function createRetrievalMaintenanceServices( state.status === "blocked" ? state.reason : undefined, ); } catch (error) { + if (error instanceof RetrievalStepBudgetError) + return pendingStep(articleId, plan); if (error instanceof RepositoryCapacityError) { - state = await markBlocked( - articleId, - state, - "capacity", - plan?.articleGeneration ?? undefined, - ); + try { + state = await markBlocked( + articleId, + state, + "capacity", + plan?.articleGeneration ?? undefined, + budget.step, + ); + } catch (failure) { + if (failure instanceof RetrievalStepBudgetError) + return pendingStep(articleId, plan); + throw failure; + } return status( articleId, plan?.articleGeneration ?? null, @@ -408,12 +464,25 @@ export function createRetrievalMaintenanceServices( ); } if (error instanceof RepositoryConflictError) { + if (budget.step !== undefined) return pendingStep(articleId, plan); // Contention is not a durable hold. A same-plan winner may still be // advancing this exact generation; blocking it would stall recovery. continue; } if (error instanceof KnowledgeBaseNotFoundError) { - await markBlocked(articleId, state, "source-unavailable"); + try { + await markBlocked( + articleId, + state, + "source-unavailable", + undefined, + budget.step, + ); + } catch (failure) { + if (failure instanceof RetrievalStepBudgetError) + return pendingStep(articleId, plan); + throw failure; + } continue; } throw error; @@ -424,23 +493,26 @@ export function createRetrievalMaintenanceServices( async function repairCollectionDirectory( collectionId: string, + budget?: RetrievalStepBudget, ): Promise { for ( let attempt = 0; attempt < repository.limits.maxConflictAttempts; attempt += 1 ) { + if (budget?.remaining === 0) return "pending"; try { const current = await repository.readCollectionVersioned(collectionId); if (current === null) return "ready"; // Only the opaque ID is derived. Request readers re-authorize policy. - await retrieval.registerCollection(collectionId); + await retrieval.registerCollection(collectionId, budget); const latest = await repository.readResourceGeneration( "collection", collectionId, ); if (latest === current.value.generation) return "ready"; } catch (error) { + if (error instanceof RetrievalStepBudgetError) return "pending"; if (error instanceof RepositoryCapacityError) return "blocked"; if (!(error instanceof RepositoryConflictError)) throw error; } @@ -451,9 +523,15 @@ export function createRetrievalMaintenanceServices( return { async repairArticleIndex(access, request) { access = caller(access); - const input = articleInput(request); + const input: RepairArticleIndexInput = objectInput(request, [ + "articleId", + "maxBatches", + ]); + requireIdentifier(input.articleId, "articleId"); + const attempts = maxBatches(input.maxBatches); const result = await repair(access, input.articleId, { - remaining: limits.maxMaintenanceBatches, + remaining: attempts ?? limits.maxMaintenanceBatches, + ...(attempts === undefined ? {} : { step: { remaining: attempts } }), }); requirePermission(access, knowledgePermissions.indexManage); return result; @@ -472,7 +550,9 @@ export function createRetrievalMaintenanceServices( const input: RepairRetrievalPageInput = objectInput(request, [ "cursor", "limit", + "maxBatches", ]); + const attempts = maxBatches(input.maxBatches); const requestedLimit = input.limit ?? limits.maxRepairScanRows; if ( !Number.isSafeInteger(requestedLimit) || @@ -546,8 +626,18 @@ export function createRetrievalMaintenanceServices( for (const candidate of candidates.values()) { const state = candidate.kind === "article" - ? (await repair(access, candidate.id, { remaining: 1 })).status - : await repairCollectionDirectory(candidate.id); + ? ( + await repair(access, candidate.id, { + remaining: 1, + ...(attempts === undefined + ? {} + : { step: { remaining: attempts } }), + }) + ).status + : await repairCollectionDirectory( + candidate.id, + attempts === undefined ? undefined : { remaining: attempts }, + ); if (state === "ready") repaired += 1; else if (state === "blocked") blocked += 1; else pending += 1; diff --git a/packages/application/src/retrieval-repository.ts b/packages/application/src/retrieval-repository.ts index 523520c..78c0ffe 100644 --- a/packages/application/src/retrieval-repository.ts +++ b/packages/application/src/retrieval-repository.ts @@ -44,8 +44,25 @@ export interface RetrievalCatalog { readonly scopes: readonly RetrievalScope[]; } +/** Invocation-local write-attempt allowance; never persisted or reused. */ +export interface RetrievalStepBudget { + remaining: number; +} + +export class RetrievalStepBudgetError extends Error { + override readonly name = "RetrievalStepBudgetError"; +} + +function available(budget: RetrievalStepBudget | undefined): void { + if (budget !== undefined && budget.remaining === 0) + throw new RetrievalStepBudgetError(); +} + export interface RetrievalRepository { - registerCollection(collectionId: string): Promise; + registerCollection( + collectionId: string, + budget?: RetrievalStepBudget, + ): Promise; readDirectory(): Promise; readCatalog(collectionId: string): Promise; /** Every returned page/entry must be charged before query filtering/deduplication. */ @@ -58,10 +75,12 @@ export interface RetrievalRepository { ): Promise; beginArticleProjection( input: BeginArticleProjectionInput, + budget?: RetrievalStepBudget, ): Promise; advanceArticleProjection( articleId: string, expectedGeneration: number, + budget?: RetrievalStepBudget, ): Promise<{ readonly state: RetrievalProjectionState; readonly complete: boolean; @@ -72,6 +91,7 @@ export interface RetrievalRepository { generation: number, reason: RetrievalBlockedReason, sourceGeneration?: number, + budget?: RetrievalStepBudget, ): Promise; } @@ -115,6 +135,12 @@ interface PostingPage { readonly entries: readonly StoredPostingEntry[]; } +interface LoadedPosting { + readonly head: VersionedRecord | null; + readonly pages: VersionedRecord[]; + readonly entries: StoredPostingEntry[]; +} + const maximumEpochs = 32; const maximumKnownScopes = 32; const maximumAttempts = 3; @@ -373,6 +399,7 @@ export function createRetrievalRepository( async function transact( partition: string, actions: readonly TransactionAction[], + budget?: RetrievalStepBudget, ): Promise { if (actions.length > maximumActions) throw new RepositoryCapacityError("index_transaction_actions"); @@ -384,6 +411,8 @@ export function createRetrievalRepository( : encodedBytes(encodeRetrievalRecord(action.value)) + 256; if (bytes > maximumTransactionBytes) throw new RepositoryCapacityError("index_transaction_bytes"); + available(budget); + if (budget !== undefined) budget.remaining -= 1; return (await records.transact(partition, actions)).committed; } const write = ( @@ -394,13 +423,16 @@ export function createRetrievalRepository( ? { action: "insert", value } : { action: "putIfUnchanged", value, version: before.version }; - async function readState(articleId: string): Promise<{ + async function readState( + articleId: string, + preparedPartition?: string, + ): Promise<{ state: RetrievalProjectionState; row: VersionedRecord; } | null> { requireIdentifier(articleId); const before = await get( - await articlePartition(articleId), + preparedPartition ?? (await articlePartition(articleId)), "head", "article", ); @@ -433,9 +465,13 @@ export function createRetrievalRepository( throw new RepositoryIntegrityError(); } } - async function registerDirectory(collectionId: string): Promise { + async function registerDirectory( + collectionId: string, + budget?: RetrievalStepBudget, + ): Promise { requireIdentifier(collectionId, "collectionId"); for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + available(budget); const before = await get("directory", "head", "directory"); let ids: readonly string[] = []; if (before !== null) { @@ -449,14 +485,18 @@ export function createRetrievalRepository( if (ids.length >= limits.maxDirectoryCollections) throw new RepositoryCapacityError("index_directory"); if ( - await transact("directory", [ - write( - row("directory", "head", "directory", { - collectionIds: [...ids, collectionId].sort(), - }), - before, - ), - ]) + await transact( + "directory", + [ + write( + row("directory", "head", "directory", { + collectionIds: [...ids, collectionId].sort(), + }), + before, + ), + ], + budget, + ) ) return; } @@ -484,9 +524,11 @@ export function createRetrievalRepository( async function registerCatalog( state: RetrievalProjectionState, collectionId: string, + budget?: RetrievalStepBudget, ): Promise { - await registerDirectory(collectionId); + await registerDirectory(collectionId, budget); for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + available(budget); const loaded = await loadCatalog(collectionId); const existing = loaded.data.entries.find( (entry) => entry.articleId === state.articleId, @@ -524,41 +566,59 @@ export function createRetrievalRepository( entries, epochs, } satisfies CatalogData); - if (await transact(loaded.partition, [write(value, loaded.row)])) return; + if (await transact(loaded.partition, [write(value, loaded.row)], budget)) + return; } throw new RepositoryConflictError(); } - async function loadPosting( + async function loadPostings( partition: string, scope: RetrievalScope, - termHash: string, - ): Promise<{ - head: VersionedRecord | null; - pages: readonly VersionedRecord[]; - entries: readonly StoredPostingEntry[]; - }> { - const head = await get(partition, "posting:" + termHash, "posting"); - if (head === null) return { head, pages: [], entries: [] }; - const data = head.value.data as PostingHead; - try { - exactObject(data, ["termHash", "pages"]); - if (data.termHash !== termHash) throw new RepositoryIntegrityError(); - requireGeneration(data.pages, 1); - if (data.pages > limits.maxPostingPagesPerTerm) - throw new RepositoryCapacityError("index_posting_pages"); - } catch (error) { - if (error instanceof RepositoryCapacityError) throw error; - throw new RepositoryIntegrityError(); + termHashes: readonly string[], + ): Promise> { + // Every key is ready before either Store wave. Head-declared page bounds + // remain authoritative; no page is dropped to fit a provider budget. + const heads = await Promise.all( + termHashes.map((termHash) => + get(partition, "posting:" + termHash, "posting"), + ), + ); + const requests: { termHash: string; page: number }[] = []; + for (const [index, termHash] of termHashes.entries()) { + const head = heads[index]; + if (head === undefined) throw new RepositoryIntegrityError(); + if (head === null) continue; + const data = head.value.data as PostingHead; + try { + exactObject(data, ["termHash", "pages"]); + if (data.termHash !== termHash) throw new RepositoryIntegrityError(); + requireGeneration(data.pages, 1); + if (data.pages > limits.maxPostingPagesPerTerm) + throw new RepositoryCapacityError("index_posting_pages"); + } catch (error) { + if (error instanceof RepositoryCapacityError) throw error; + throw new RepositoryIntegrityError(); + } + for (let page = 0; page < data.pages; page += 1) + requests.push({ termHash, page }); } - const pages: VersionedRecord[] = []; - const entries: StoredPostingEntry[] = []; - for (let page = 0; page < data.pages; page += 1) { - const loaded = await get( - partition, - "page:" + termHash + ":" + page, - "page", - ); + const loadedPages = await Promise.all( + requests.map(({ termHash, page }) => + get(partition, "page:" + termHash + ":" + page, "page"), + ), + ); + const result = new Map(); + for (const [index, termHash] of termHashes.entries()) + result.set(termHash, { + head: heads[index] ?? null, + pages: [], + entries: [], + }); + for (const [index, request] of requests.entries()) { + const { termHash, page } = request; + const loaded = loadedPages[index]; + if (loaded === undefined) throw new RepositoryIntegrityError(); if (loaded === null) throw new RepositoryConflictError(); try { const value = loaded.value.data as PostingPage; @@ -584,29 +644,38 @@ export function createRetrievalRepository( ); if (members.length > limits.postingPageEntries) throw new RepositoryCapacityError("index_posting_entries"); - entries.push(...members); + result.get(termHash)!.entries.push(...members); } catch (error) { if (error instanceof RepositoryCapacityError) throw error; throw new RepositoryIntegrityError(); } - pages.push(loaded); + result.get(termHash)!.pages.push(loaded); } - return { head, pages, entries }; + return result; } async function applyScopeBatch( state: RetrievalProjectionState, scope: RetrievalScope, + budget?: RetrievalStepBudget, ): Promise { - const partition = await scopePartition(scope); - const manifestId = "manifest:" + (await fingerprint(state.articleId)); + const [partition, articleScope, articleHash] = await Promise.all([ + scopePartition(scope), + articlePartition(state.articleId), + fingerprint(state.articleId), + ]); + const manifestId = "manifest:" + articleHash; const desired = state.targets.find((target) => sameScope(target.scope, scope)) ?? null; for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { - const global = await readState(state.articleId); + available(budget); + const [global, headRow, manifestRow] = await Promise.all([ + readState(state.articleId, articleScope), + get(partition, "head", "scope"), + get(partition, manifestId, "manifest"), + ]); if (global === null || global.state.generation !== state.generation) throw new RepositoryConflictError(); - const headRow = await get(partition, "head", "scope"); let head: ScopeHead | null = null; if (headRow !== null) { try { @@ -621,7 +690,6 @@ export function createRetrievalRepository( ) throw new RepositoryCapacityError("index_partition"); } - const manifestRow = await get(partition, manifestId, "manifest"); let previous: Manifest | null = null; if (manifestRow !== null) { try { @@ -681,8 +749,9 @@ export function createRetrievalRepository( after: RetrievalRecord | null; }[] = []; let planningConflict = false; + const postings = await loadPostings(partition, scope, work); for (const termHash of work) { - const loaded = await loadPosting(partition, scope, termHash); + const loaded = postings.get(termHash)!; const old = actual.get(termHash); const found = loaded.entries.filter( (entry) => entry.hint.articleId === state.articleId, @@ -834,7 +903,7 @@ export function createRetrievalRepository( throw new RepositoryCapacityError("index_partition_bytes"); actions.unshift(write(nextHeadRow, headRow)); // Every posting/manifest mutation changes this head. Its CAS also fences deletes. - if (!(await transact(partition, actions))) continue; + if (!(await transact(partition, actions, budget))) continue; return [...new Set([...actual.keys(), ...desiredTerms])].every( (term) => !differs(term), ); @@ -860,11 +929,9 @@ export function createRetrievalRepository( async readPostingPages(scope, term) { requireRetrievalScope(scope); const termHash = await retrievalTermHash(term); - const loaded = await loadPosting( - await scopePartition(scope), - scope, - termHash, - ); + const loaded = ( + await loadPostings(await scopePartition(scope), scope, [termHash]) + ).get(termHash)!; return loaded.pages.map((page) => ({ entries: (page.value.data as PostingPage).entries.map((entry) => snapshotData(entry.hint), @@ -874,7 +941,7 @@ export function createRetrievalRepository( async readArticleProjection(articleId) { return (await readState(articleId))?.state ?? null; }, - async beginArticleProjection(input) { + async beginArticleProjection(input, budget) { const request = snapshotData(input); if ( Object.keys(request).some( @@ -920,6 +987,7 @@ export function createRetrievalRepository( ); unique(targets.map((target) => scopeIdentity(target.scope))); for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + available(budget); const before = await readState(request.articleId); const current = before?.state; if ( @@ -954,18 +1022,23 @@ export function createRetrievalRepository( const { reason: _reason, ...clean } = state; const partition = await articlePartition(request.articleId); if ( - await transact(partition, [ - write( - row(partition, "head", "article", clean), - before?.row ?? null, - ), - ]) + await transact( + partition, + [ + write( + row(partition, "head", "article", clean), + before?.row ?? null, + ), + ], + budget, + ) ) return clean; } throw new RepositoryConflictError(); }, - async advanceArticleProjection(articleId, expectedGeneration) { + async advanceArticleProjection(articleId, expectedGeneration, budget) { + available(budget); requireGeneration(expectedGeneration, 1); const before = await readState(articleId); if (before === null || before.state.generation !== expectedGeneration) @@ -977,11 +1050,13 @@ export function createRetrievalRepository( return { state, complete: false, changed: false }; const scope = state.pendingScopes[0]; if (scope !== undefined) { - await registerCatalog(state, scope.collectionId); - if (!(await applyScopeBatch(state, scope))) + await registerCatalog(state, scope.collectionId, budget); + available(budget); + if (!(await applyScopeBatch(state, scope, budget))) return { state, complete: false, changed: true }; } for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + available(budget); const latest = await readState(articleId); if (latest === null || latest.state.generation !== expectedGeneration) throw new RepositoryConflictError(); @@ -1004,9 +1079,11 @@ export function createRetrievalRepository( }; const partition = latest.row.value.partition; if ( - await transact(partition, [ - write(row(partition, "head", "article", next), latest.row), - ]) + await transact( + partition, + [write(row(partition, "head", "article", next), latest.row)], + budget, + ) ) return { state: next, complete, changed: true }; } @@ -1017,6 +1094,7 @@ export function createRetrievalRepository( generation, reason, sourceGeneration, + budget, ) { requireGeneration(generation, 1); if (sourceGeneration !== undefined) @@ -1024,6 +1102,7 @@ export function createRetrievalRepository( if (!["capacity", "source-unavailable", "conflict"].includes(reason)) throw new TypeError("Expected a projection block reason"); for (let attempt = 0; attempt < maximumAttempts; attempt += 1) { + available(budget); const before = await readState(articleId); if ( before === null && @@ -1048,12 +1127,16 @@ export function createRetrievalRepository( const partition = before?.row.value.partition ?? (await articlePartition(articleId)); if ( - await transact(partition, [ - write( - row(partition, "head", "article", state), - before?.row ?? null, - ), - ]) + await transact( + partition, + [ + write( + row(partition, "head", "article", state), + before?.row ?? null, + ), + ], + budget, + ) ) return state; } diff --git a/packages/application/src/retrieval-types.ts b/packages/application/src/retrieval-types.ts index 4d3af53..b7e68c8 100644 --- a/packages/application/src/retrieval-types.ts +++ b/packages/application/src/retrieval-types.ts @@ -174,6 +174,15 @@ export interface ArticleIndexInput { readonly articleId: string; } +export interface RepairArticleIndexInput extends ArticleIndexInput { + /** + * Optional bounded mode: at most this many derived transaction attempts, + * including conflicts. Already-current prerequisites consume no attempt. + * Omission retains the instance's legacy advancement allowance. + */ + readonly maxBatches?: number; +} + export type ArticleIndexState = "pending" | "ready" | "blocked"; export type ArticleIndexBlockReason = @@ -194,6 +203,8 @@ export interface RepairRetrievalPageInput { readonly cursor?: string; /** Physical scan rows, counted before filtering or candidate deduplication. */ readonly limit?: number; + /** Optional transaction-attempt allowance for each resource on this page. */ + readonly maxBatches?: number; } /** Staff maintenance diagnostics; these counts never enter search/customer DTOs. */ @@ -225,7 +236,7 @@ export interface KnowledgeRetrievalApplication { ): Promise; repairArticleIndex( staffAccess: AccessContext, - input: ArticleIndexInput, + input: RepairArticleIndexInput, ): Promise; repairRetrievalPage( staffAccess: AccessContext, diff --git a/packages/application/src/types.ts b/packages/application/src/types.ts index 7b959a1..e621e26 100644 --- a/packages/application/src/types.ts +++ b/packages/application/src/types.ts @@ -21,6 +21,7 @@ import type { EvidenceSubmission, } from "@pegma/knowledge-base-core"; import type { Store } from "@pegma/storage-core"; +import type { KnowledgeEvidenceContext } from "./evidence-reports-types.js"; import type { KnowledgeRepositoryLimits } from "./repository.js"; import type { @@ -330,6 +331,22 @@ export interface ArticleReadInput { readonly articleId: string; } +export interface AuthoringContextReadInput extends ArticleReadInput { + /** Omission excludes private accepted evidence and revocation history. */ + readonly includeEvidence?: boolean; +} + +declare const authoringObservationBrand: unique symbol; +/** Instance-bound, single-use observation; never serialize or persist it. */ +export interface KnowledgeAuthoringContextObservation { + readonly [authoringObservationBrand]: true; +} + +export interface KnowledgeAuthoringContextRead { + readonly context: KnowledgeEvidenceContext; + readonly observation: KnowledgeAuthoringContextObservation; +} + export interface KnowledgeBaseApplication extends KnowledgeRetrievalApplication { createCollection( access: AccessContext, @@ -403,6 +420,15 @@ export interface KnowledgeBaseApplication extends KnowledgeRetrievalApplication access: AccessContext, input: ValidationRequirementsReadInput, ): Promise; + getAuthoringContext( + access: AccessContext, + input: AuthoringContextReadInput, + ): Promise; + /** Rechecks current heads and permissions, consuming this instance's handle. */ + confirmAuthoringContext( + access: AccessContext, + observation: KnowledgeAuthoringContextObservation, + ): Promise; getDraft( access: AccessContext, input: ArticleReadInput, diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 2db5324..66b3583 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-contracts", - "version": "0.1.3", + "version": "0.1.4", "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 4336010..b673bf8 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-core", - "version": "0.1.3", + "version": "0.1.4", "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.3" + "@pegma/knowledge-base-contracts": "0.1.4" }, "scripts": { "build": "tsc -p tsconfig.json", diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 698bec0..b3558dc 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -5,6 +5,12 @@ adapts the authorized application API to bounded agent commands and the Model Context Protocol. Hosts compose it with their protected Knowledge Base endpoints; the package does not supply a hosted service. +All four Knowledge Base packages are verified published at +[`0.1.3`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3). +This synchronized `0.1.4` source candidate adds an optional aggregate query over +the existing report workflow; its own review, gates, trusted publication and +strict verification remain open. Host and actual client acceptance are separate. + The contracts, core, and application packages remain independent of MCP, HTTP, provider SDKs, and login flows. Hosts choose this adapter when exposing agent access. The adapter pins `@modelcontextprotocol/sdk` at `1.32.2` and `zod` at @@ -48,12 +54,12 @@ application extension; it adds no agent scope or tool. through host-configured protected endpoints. Both require fresh host authentication and admission control on every request; neither issues tokens. -The [host composition contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/HOST_COMPOSITION.md) +The [host composition contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.3/docs/HOST_COMPOSITION.md) describes authenticated contexts, trusted evidence, replay, and safe DTOs. The -[retrieval contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RETRIEVAL.md) +[retrieval contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.3/docs/RETRIEVAL.md) describes authoritative current-publication confirmation and audience boundaries. -## Optional native-client report mode (unpublished `0.1.3` source) +## Optional native-client report mode `createKnowledgeAgentDispatcher` optionally accepts `reports: Pick`. @@ -64,6 +70,18 @@ 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. +The verified `0.1.3` release provides that report trio. The unpublished `0.1.4` +candidate additionally accepts `reports.query`, typed as the optional +`Partial>` extension. The dispatcher +calls it once for report-aware requirements, passing only the article ID and +optional owner-status key. It projects the returned governed requirements, +ledger and status into the same wire result. Internal target metadata and +capacity, report bodies, evidence and opaque context observations never appear +as added fields. No tool, scope, schema or client option changes. Supplying only +the original trio retains its existing read sequence; legacy requirements do +not invoke query. A configured query's failure or malformed output refuses +without falling back. + Both report variants need effective `draftRead` and `evidenceSubmit`. Requirements input adds `articleId` and optional `reportLookup: { ledgerEpoch, reportId }`, returning `reportLedger` and optional @@ -81,17 +99,29 @@ 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. +Hosts bind all report/query work to the original request, credential, principal, +grant, client and resource. Keep initial request authentication. For pure reads, +hosts may revalidate per port or use one request-local full-credential check +before the first read and another after the completed actual dispatcher call, +checking all required scopes/permissions before disclosure. MCP needs that fence +inside its awaited tool callback, not only around an outer Response. Writes +retain fresh before/after guards; no read group is reused across invocations. +Preserve the restricted context rather than substituting current owner/Admin +authority. Ledger principal resolution is not a host credential verifier. + +The optional application context/read-confirm pair is trusted composition only. +Its opaque observation is instance- and caller-bound, single-use read +bookkeeping; it is neither authority nor an attestation and never reaches the +agent or durable records. Fewer repeated reads do not prove that a complete host +invocation fits the Workers Free limit of 50 D1 queries per invocation, or establish +a CPU, physical-row or latency guarantee; actual host profiles remain unproven. + +Read the verified `0.1.3` [wire contract](https://github.com/pegma-dev/knowledge-base/blob/v0.1.3/docs/AGENT_API.md#optional-native-client-report-mode), +[native-client workflow](https://github.com/pegma-dev/knowledge-base/blob/v0.1.3/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/v0.1.3/docs/EVIDENCE_REPORTS.md) +for the published report trio. The aggregate query and context/read-confirm pair +are DEVELOPMENT `0.1.4` additions and require their own verified publication +before host adoption. Actual client/host acceptance remains open. ## Local verification and release @@ -121,9 +151,9 @@ Each package has its own README, MIT LICENSE, build-on-prepack hook, and compiled-test exclusion. All four package versions remain synchronized with exact internal dependency pins. Publishing, release tags, trusted-publisher configuration, and host activation are separate maintainer operations in the -[release procedure](https://github.com/pegma-dev/knowledge-base/blob/v0.1.2/docs/RELEASING.md). -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. +[release procedure](https://github.com/pegma-dev/knowledge-base/blob/v0.1.3/docs/RELEASING.md). +The published-contract links above target verified `v0.1.3`; new aggregate and +context-pair source retains its separate `0.1.4` release gates. Source readers can use the explicitly moving [DEVELOPMENT documentation on main](https://github.com/pegma-dev/knowledge-base/blob/main/docs/HOST_COMPOSITION.md) diff --git a/packages/mcp/package.json b/packages/mcp/package.json index e58bc52..a83929a 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-mcp", - "version": "0.1.3", + "version": "0.1.4", "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.3", - "@pegma/knowledge-base-contracts": "0.1.3", - "@pegma/knowledge-base-core": "0.1.3", + "@pegma/knowledge-base-application": "0.1.4", + "@pegma/knowledge-base-contracts": "0.1.4", + "@pegma/knowledge-base-core": "0.1.4", "zod": "4.6.7" }, "scripts": { diff --git a/packages/mcp/src/dispatcher.ts b/packages/mcp/src/dispatcher.ts index cb3e7bf..f73bd4a 100644 --- a/packages/mcp/src/dispatcher.ts +++ b/packages/mcp/src/dispatcher.ts @@ -1,5 +1,7 @@ import type { AccessContext } from "@pegma/authorization-core"; import { KnowledgeEvidenceReportsError } from "@pegma/knowledge-base-application"; +import { articleKinds } from "@pegma/knowledge-base-contracts"; +import { z } from "zod"; import { createKnowledgeAgentErrorResponse, @@ -191,7 +193,9 @@ export function createKnowledgeAgentDispatcher( (!suppliedReports || typeof suppliedReports.report !== "function" || typeof suppliedReports.ledger !== "function" || - typeof suppliedReports.status !== "function") + typeof suppliedReports.status !== "function" || + (suppliedReports.query !== undefined && + typeof suppliedReports.query !== "function")) ) { throw new TypeError("Invalid knowledge agent report service"); } @@ -202,6 +206,9 @@ export function createKnowledgeAgentDispatcher( report: suppliedReports.report.bind(suppliedReports), ledger: suppliedReports.ledger.bind(suppliedReports), status: suppliedReports.status.bind(suppliedReports), + ...(suppliedReports.query === undefined + ? {} + : { query: suppliedReports.query.bind(suppliedReports) }), }); const envelopeSchema = reports === undefined @@ -221,6 +228,25 @@ export function createKnowledgeAgentDispatcher( } const reportResult = knowledgeAgentReportResultSchemas.getValidationRequirements.shape; + // Trusted aggregate data is still bounded and projected; none of its internal + // target binding or private implementation fields become new wire fields. + const aggregateResult = z + .object({ + target: z + .object({ + articleId: z.unknown().transform((value) => trustedText(value, 200)), + generation: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), + collectionId: z + .unknown() + .transform((value) => trustedText(value, 200)), + kind: z.enum(articleKinds), + }) + .strip(), + requirements: knowledgeAgentResultSchemas.getValidationRequirements, + ledger: reportResult.reportLedger, + status: reportResult.reportStatus, + }) + .strip(); return Object.freeze({ limits, ...(reports === undefined ? {} : { reportWorkflow: true as const }), @@ -264,6 +290,47 @@ export function createKnowledgeAgentDispatcher( throw new KnowledgeAgentBoundaryError("invalid_request"); { const input = envelope.input; + if (reports.query !== undefined) { + const lookup = input.reportLookup; + const queried = reportOutput( + aggregateResult, + await reports.query(access, { + articleId: input.articleId, + ...(lookup === undefined ? {} : { status: lookup }), + }), + ); + if ( + queried.target.articleId !== input.articleId || + queried.requirements.collectionId !== + queried.target.collectionId + ) + throw new KnowledgeAgentBoundaryError("unavailable"); + if ( + queried.target.collectionId !== input.collectionId || + queried.target.kind !== input.kind + ) + throw new KnowledgeAgentBoundaryError("conflict"); + if ( + lookup !== undefined && + queried.ledger.ledgerEpoch !== lookup.ledgerEpoch + ) + throw new KnowledgeAgentBoundaryError("conflict"); + if ( + (lookup === undefined) !== (queried.status === undefined) || + (queried.status !== undefined && + (queried.status.ledgerEpoch !== lookup?.ledgerEpoch || + queried.status.reportId !== lookup?.reportId)) + ) + throw new KnowledgeAgentBoundaryError("unavailable"); + result = { + ...queried.requirements, + reportLedger: queried.ledger, + ...(queried.status === undefined + ? {} + : { reportStatus: queried.status }), + }; + break; + } const target = await application.getDraft(access, { articleId: input.articleId, }); diff --git a/packages/mcp/src/mcp.ts b/packages/mcp/src/mcp.ts index 8b104f6..f5e3452 100644 --- a/packages/mcp/src/mcp.ts +++ b/packages/mcp/src/mcp.ts @@ -349,7 +349,7 @@ export function createKnowledgeAgentMcp( maxRequestBodySize: dispatcher.limits.maxRequestBytes, }); const server = new Server( - { name: "@pegma/knowledge-base-mcp", version: "0.1.3" }, + { name: "@pegma/knowledge-base-mcp", version: "0.1.4" }, { capabilities: { tools: {} }, // Workers prohibit the runtime code generation used by SDK-default AJV. diff --git a/packages/mcp/src/types.ts b/packages/mcp/src/types.ts index 5798d0e..26549f3 100644 --- a/packages/mcp/src/types.ts +++ b/packages/mcp/src/types.ts @@ -212,12 +212,13 @@ export interface KnowledgeAgentDispatcherOptions { 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. */ + * fence the same authenticated request/grant around the completed actual + * read dispatch, and retain fresh before/after guards on writes. */ readonly reports?: Pick< KnowledgeEvidenceReports, "report" | "ledger" | "status" - >; + > & + Partial>; /** * Positive safe integers may only reduce the fixed component ceilings. * maxResponseBytes must reserve at least 2,048 bytes for acknowledgements. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3194d1f..d73a610 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.3 + specifier: 0.1.4 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.3 + specifier: 0.1.4 version: link:packages/contracts '@pegma/knowledge-base-core': - specifier: 0.1.3 + specifier: 0.1.4 version: link:packages/core '@pegma/knowledge-base-mcp': - specifier: 0.1.3 + specifier: 0.1.4 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.3 + specifier: 0.1.4 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.3 + specifier: 0.1.4 version: link:../core '@pegma/spine': specifier: 0.1.2 @@ -102,7 +102,7 @@ importers: packages/core: dependencies: '@pegma/knowledge-base-contracts': - specifier: 0.1.3 + specifier: 0.1.4 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.3 + specifier: 0.1.4 version: link:../application '@pegma/knowledge-base-contracts': - specifier: 0.1.3 + specifier: 0.1.4 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.3 + specifier: 0.1.4 version: link:../core zod: specifier: 4.6.7 diff --git a/test/README.md b/test/README.md index a08cd95..c0bd0b3 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 unpublished candidate runtime packages are `0.1.3`, and the Agent Access +The four unpublished candidate runtime packages are `0.1.4`, and the Agent Access protocol-proof pin remains `0.1.1`. `trace-store.ts` delegates every record operation to the supplied real store. @@ -91,6 +91,7 @@ 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 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 +by the [historical verified `0.1.2` release](../docs/BOOTSTRAP.md#historical-verified-012-release) +and current [verified `0.1.3` release](../docs/BOOTSTRAP.md#current-verified-013-release). +Source `0.1.4` is an unpublished governed context/query candidate with its own gates and verified trusted release required; host activation gates remain open. diff --git a/tests/agent-reports.test.ts b/tests/agent-reports.test.ts index 5bbdcee..7081eeb 100644 --- a/tests/agent-reports.test.ts +++ b/tests/agent-reports.test.ts @@ -1,6 +1,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; import type { + KnowledgeBaseApplication, KnowledgeEvidenceReports, KnowledgeReportAcknowledgement, } from "@pegma/knowledge-base-application"; @@ -29,12 +30,17 @@ import { import { evidenceReportsFixture } from "../test/evidence-reports-fixtures.js"; type Channel = "HTTP" | "MCP"; -type Reports = Pick; +type Reports = Pick & + Partial>; async function fixture( options: { legacy?: boolean; + aggregate?: boolean; limits?: Partial; + wrapApplication?: ( + application: KnowledgeBaseApplication, + ) => KnowledgeBaseApplication; wrapReports?: ( reports: Reports, f: Awaited>, @@ -52,12 +58,22 @@ async function fixture( resource: agentResource, }, }; + // Keep the original trio explicit so its compatibility/fence cases continue + // exercising the legacy path even after the actual factory gains query(). + const suppliedReports: Reports = { + report: f.reports.report, + ledger: f.reports.ledger, + status: f.reports.status, + ...(options.aggregate ? { query: f.reports.query } : {}), + }; const dispatcher = createKnowledgeAgentDispatcher({ - application: f.app, + application: options.wrapApplication?.(f.app) ?? f.app, resource: agentResource, ...(options.legacy ? {} - : { reports: options.wrapReports?.(f.reports, f) ?? f.reports }), + : { + reports: options.wrapReports?.(suppliedReports, f) ?? suppliedReports, + }), ...(options.limits === undefined ? {} : { limits: options.limits }), }); const common = { @@ -220,104 +236,107 @@ describe.each(["HTTP", "MCP"] as const)( (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 }>( + it.each([false, true])( + "queues privately, requires human confirmation, polls its own receipt, accepts every real check and leaves publication to staff (aggregate=%s)", + async (aggregate) => { + const f = await fixture({ aggregate }); + 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), - ).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), + "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, - 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, + }); + 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, - }), - ).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); - }); + }); + 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 }); @@ -885,3 +904,529 @@ describe("optional native report bounds and observational fences", () => { ); }); }); + +describe.each(["HTTP", "MCP"] as const)( + "aggregate report query over %s", + (channel) => { + it("uses one real aggregate query for discovery/polling and no redundant dispatcher subreads", async () => { + const calls = { + query: 0, + ledger: 0, + status: 0, + draft: 0, + requirements: 0, + }; + const f = await fixture({ + aggregate: true, + wrapApplication: (app) => ({ + ...app, + async getDraft(...args) { + calls.draft++; + return app.getDraft(...args); + }, + async getValidationRequirements(...args) { + calls.requirements++; + return app.getValidationRequirements(...args); + }, + }), + wrapReports: (reports) => { + const query = reports.query; + if (query === undefined) + throw new Error("Expected actual aggregate query"); + return { + ...reports, + async query(access, input) { + calls.query++; + expect(access.roles).toEqual([]); + expect(access.entitlements).toEqual([]); + expect(access.permissions).toEqual( + Object.values(knowledgeAgentScopes), + ); + expect(Object.keys(input).sort()).toEqual( + input.status === undefined + ? ["articleId"] + : ["articleId", "status"], + ); + return query(access, input); + }, + async ledger(...args) { + calls.ledger++; + return reports.ledger(...args); + }, + async status(...args) { + calls.status++; + return reports.status(...args); + }, + }; + }, + }); + f.authority.current = { + ...f.authority.current, + access: { + ...f.owner, + roles: ["synthetic-admin"], + entitlements: ["PRIVATE_ENTITLEMENT"], + }, + }; + const before = await f.physicalRows(); + const discovery = success( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput(), + ), + ); + expect(discovery).toHaveProperty("reportLedger", { + ledgerEpoch: 1, + status: "active", + }); + expect(discovery).not.toHaveProperty("reportStatus"); + expect(calls).toEqual({ + query: 1, + ledger: 0, + status: 0, + draft: 0, + requirements: 0, + }); + expect(await f.physicalRows()).toEqual(before); + const recorded = await f.report(); + await f.decide(recorded.ack); + const saved = await f.physicalRows(); + const polled = success( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput({ + ...recorded.ack, + kind: "pending-human-review", + }), + ), + ); + expect(polled.reportStatus).toEqual( + await f.reports.status(f.agent, f.key(recorded.ack)), + ); + expect(calls).toEqual({ + query: 2, + ledger: 0, + status: 0, + draft: 0, + requirements: 0, + }); + expect(await f.physicalRows()).toEqual(saved); + bodyFree(polled); + expect(polled).not.toHaveProperty("target"); + }); + + it("retains the same advertised schemas and legacy requirements without invoking query", async () => { + let calls = 0; + const f = await fixture({ + aggregate: true, + wrapReports: (reports) => ({ + ...reports, + async query() { + calls++; + throw new Error("PRIVATE_UNUSED_QUERY"); + }, + }), + }); + const input = { + collectionId: f.collectionId, + kind: "walkthrough" as const, + }; + expect( + success(await f.call(channel, "getValidationRequirements", input)), + ).toEqual(await f.app.getValidationRequirements(f.agent, input)); + expect(calls).toBe(0); + const legacy = await fixture(); + expect((await (await f.sdk()).listTools()).tools).toEqual( + (await (await legacy.sdk()).listTools()).tools, + ); + expect(Object.values(knowledgeAgentScopes)).toHaveLength(3); + }); + + it("projects away internal target, ledger capacity and private fields from trusted aggregate output", async () => { + const f = await fixture({ + aggregate: true, + wrapReports: (reports) => { + const query = reports.query; + if (query === undefined) + throw new Error("Expected actual aggregate query"); + return { + ...reports, + async query(...args) { + const actual = structuredClone(await query(...args)); + Reflect.set( + actual, + "PRIVATE_REPORT_BODY_CANARY", + "private/artifact", + ); + Reflect.set( + actual.target, + "privateSource", + "PRIVATE_SOURCE_BODY", + ); + Reflect.set(actual.requirements, "trustedAttesterIds", [ + "staff/verifier", + ]); + Reflect.set( + actual.ledger, + "privateDetails", + "PRIVATE_LEDGER_BODY", + ); + if (actual.status !== undefined) + Reflect.set( + actual.status, + "confirmation", + "PRIVATE_CONFIRMATION", + ); + return actual; + }, + }; + }, + }); + const recorded = await f.report(); + const result = success( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput({ + ...recorded.ack, + kind: "pending-human-review", + }), + ), + ); + expect(Object.keys(result.reportLedger).sort()).toEqual([ + "ledgerEpoch", + "status", + ]); + expect(Object.keys(result.reportStatus ?? {}).sort()).toEqual([ + "ledgerEpoch", + "receipt", + "reportGeneration", + "reportId", + "status", + ]); + expect(result).not.toHaveProperty("target"); + bodyFree(result); + }); + + it.each([ + ["target article", "target", "articleId", "article/foreign"], + ["target generation", "target", "generation", -1], + ["target kind", "target", "kind", "private-kind"], + [ + "requirements collection", + "requirements", + "collectionId", + "collection/foreign", + ], + ["ledger status", "ledger", "status", "invalid"], + ["status receipt", "status", "receipt", 19], + ["status identity", "status", "reportId", "foreign-report"], + ] as const)( + "refuses malformed or mismatched trusted %s without fallback", + async (_name, part, field, invalid) => { + let fallback = 0; + const f = await fixture({ + aggregate: true, + wrapReports: (reports) => { + const query = reports.query; + if (query === undefined) + throw new Error("Expected actual aggregate query"); + return { + ...reports, + async query(...args) { + const actual = structuredClone(await query(...args)); + const selected = actual[part]; + if (selected === undefined) + throw new Error("Expected owner status"); + Reflect.set(selected, field, invalid); + return actual; + }, + async ledger(...args) { + fallback++; + return reports.ledger(...args); + }, + async status(...args) { + fallback++; + return reports.status(...args); + }, + }; + }, + }); + const recorded = await f.report(); + const before = await f.physicalRows(); + privateError( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput({ + ...recorded.ack, + kind: "pending-human-review", + }), + ), + "unavailable", + ); + expect(fallback).toBe(0); + expect(await f.physicalRows()).toEqual(before); + }, + ); + + it("keeps target, epoch, owner and effective scope refusals on the real aggregate", async () => { + const f = await fixture({ aggregate: true }); + const recorded = await f.report(); + const input = f.requirementsInput({ + ...recorded.ack, + kind: "pending-human-review", + }); + const before = await f.physicalRows(); + privateError( + await f.call(channel, "getValidationRequirements", { + ...input, + collectionId: "collection/foreign", + }), + "conflict", + ); + privateError( + await f.call(channel, "getValidationRequirements", { + ...input, + kind: "explanation", + }), + "conflict", + ); + privateError( + await f.call(channel, "getValidationRequirements", { + ...input, + reportLookup: { + ledgerEpoch: recorded.ack.ledgerEpoch + 1, + reportId: recorded.ack.reportId, + }, + }), + "conflict", + ); + f.authority.current = { ...f.authority.current, access: f.otherAgent }; + privateError( + await f.call(channel, "getValidationRequirements", input), + "not_found", + ); + for (const scope of Object.values(knowledgeAgentScopes)) { + f.authority.current = { + ...f.authority.current, + access: f.agent, + scopes: [scope], + }; + privateError( + await f.call(channel, "getValidationRequirements", input), + "forbidden", + ); + } + expect(await f.physicalRows()).toEqual(before); + }); + + it.each(["missing", "unsolicited"] as const)( + "refuses %s aggregate status instead of leaking or downgrading it", + async (mode) => { + let recorded: KnowledgeReportAcknowledgement | undefined; + const f = await fixture({ + aggregate: true, + wrapReports: (reports) => { + const query = reports.query; + if (query === undefined) + throw new Error("Expected actual aggregate query"); + return { + ...reports, + async query(access, input) { + const actual = structuredClone(await query(access, input)); + if (mode === "missing") + Reflect.deleteProperty(actual, "status"); + else { + if (recorded === undefined) + throw new Error("Expected actual owner report"); + Reflect.set( + actual, + "status", + await reports.status(access, { + articleId: input.articleId, + ledgerEpoch: recorded.ledgerEpoch, + reportId: recorded.reportId, + }), + ); + } + return actual; + }, + }; + }, + }); + recorded = (await f.report()).ack; + const before = await f.physicalRows(); + privateError( + await f.call( + channel, + "getValidationRequirements", + mode === "missing" + ? f.requirementsInput({ + ...recorded, + kind: "pending-human-review", + }) + : f.requirementsInput(), + ), + "unavailable", + ); + expect(await f.physicalRows()).toEqual(before); + }, + ); + + it("fails closed on unavailable aggregate work without falling back or exposing its exception", async () => { + let fallback = 0; + const f = await fixture({ + aggregate: true, + wrapReports: (reports) => ({ + ...reports, + async query() { + throw new Error("PRIVATE_REPORT_BODY_CANARY private/artifact"); + }, + async ledger(...args) { + fallback++; + return reports.ledger(...args); + }, + async status(...args) { + fallback++; + return reports.status(...args); + }, + }), + }); + const before = await f.physicalRows(); + privateError( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput(), + ), + "unavailable", + ); + expect(fallback).toBe(0); + expect(await f.physicalRows()).toEqual(before); + }); + + it("propagates an actual aggregate target-change conflict without exposing stale report status", async () => { + const f = await fixture({ aggregate: true }); + const recorded = await f.report(); + const before = await f.physicalRows(); + let edit = true; + f.hooks.afterContext = async () => { + if (!edit) return; + edit = false; + await f.updateDraft(); + }; + privateError( + await f.call( + channel, + "getValidationRequirements", + f.requirementsInput({ + ...recorded.ack, + kind: "pending-human-review", + }), + ), + "conflict", + ); + expect((await f.current()).revision.number).toBe(2); + expect(await f.physicalRows()).toEqual(before); + }); + + it("never makes query a prerequisite for historical report ACK recovery after a real draft edit", async () => { + let queries = 0; + const f = await fixture({ + aggregate: true, + wrapReports: (reports) => ({ + ...reports, + async query() { + queries++; + throw new Error("PRIVATE_QUERY_UNAVAILABLE"); + }, + }), + }); + const current = await f.current(); + const input = { + ...f.command("aggregate-history", current.generation), + ...(await f.reportInput()), + }; + const ack = success( + await f.call(channel, "submitEvidence", input), + ); + await f.updateDraft(); + const before = await f.physicalRows(); + const next: Channel = channel === "HTTP" ? "MCP" : "HTTP"; + expect(success(await f.call(next, "submitEvidence", input))).toEqual(ack); + privateError( + await f.call(channel, "submitEvidence", { + ...input, + expectedGeneration: (await f.current()).generation, + }), + "conflict", + ); + expect(queries).toBe(0); + expect(await f.physicalRows()).toEqual(before); + }); + }, +); + +describe("aggregate report configuration", () => { + it.each([null, false, "query"])( + "rejects a supplied non-callable query %s", + async (invalid) => { + const f = await fixture(); + const reports = { + report: f.reports.report, + ledger: f.reports.ledger, + status: f.reports.status, + query: f.reports.query, + }; + Reflect.set(reports, "query", invalid); + expect(() => + createKnowledgeAgentDispatcher({ + application: f.app, + resource: agentResource, + reports, + }), + ).toThrow(TypeError); + }, + ); + + it("captures the trusted query method and receiver before caller mutation", async () => { + let supplied: Reports | undefined; + let calls = 0; + const f = await fixture({ + aggregate: true, + wrapReports: (reports) => { + const query = reports.query; + if (query === undefined) + throw new Error("Expected actual aggregate query"); + const ports: Reports = { + ...reports, + async query(...args) { + expect(this).toBe(ports); + calls++; + return query(...args); + }, + }; + supplied = ports; + return ports; + }, + }); + if (supplied === undefined) + throw new Error("Expected supplied report methods"); + Reflect.set(supplied, "query", async () => { + throw new Error("PRIVATE_REPLACEMENT_QUERY"); + }); + expect( + success( + await f.call( + "HTTP", + "getValidationRequirements", + f.requirementsInput(), + ), + ).reportLedger.status, + ).toBe("active"); + expect(calls).toBe(1); + }); +}); diff --git a/tests/free-evidence-read-plan.test.ts b/tests/free-evidence-read-plan.test.ts new file mode 100644 index 0000000..9672ac4 --- /dev/null +++ b/tests/free-evidence-read-plan.test.ts @@ -0,0 +1,352 @@ +import { + createKnowledgeBaseApplication, + knowledgeRecords, + RepositoryConflictError, + RepositoryIntegrityError, + type EvidenceVerificationRequest, + type KnowledgeBaseApplication, +} from "@pegma/knowledge-base-application"; +import { describe, expect, it } from "vitest"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { + evidenceReportsFixture, + reportBarrier, +} from "../test/evidence-reports-fixtures.js"; +import type { Store } from "@pegma/storage-core"; + +async function fixture(backing: Store) { + const f = await evidenceReportsFixture(backing); + let app: KnowledgeBaseApplication; + const hooks: { afterVerifier?: () => Promise } = {}; + const requests: EvidenceVerificationRequest[] = []; + const reports = f.freshReports({ + authoringContext: { + getAuthoringContext: (...args) => app.getAuthoringContext(...args), + confirmAuthoringContext: (...args) => + app.confirmAuthoringContext(...args), + }, + }); + app = createKnowledgeBaseApplication({ + store: f.observed.store, + clock: f.clock, + evidenceVerifier: { + async verify(request) { + requests.push(request); + const result = await reports.verifier.verify(request); + if (result !== null) await hooks.afterVerifier?.(); + return result; + }, + }, + }); + async function packet() { + const input = await f.reportInput(); + const ack = await reports.report(f.agent, input); + const view = await reports.read(f.reviewer, f.key(ack)); + await reports.decide( + f.reviewer, + { + ...f.key(ack), + commandId: f.command("confirm-free-plan", 0).commandId, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }, + "confirmed", + ); + const current = await app.getDraft(f.agent, { articleId: f.articleId }); + return { + report: input, + input: { + ...f.command("accept-free-plan", current.generation), + articleId: f.articleId, + evidence: input.evidence, + receipt: ack.receipt, + }, + }; + } + return { ...f, app, reports, hooks, requests, packet }; +} + +for (const [backend, createStore] of storeFactories) { + describe(`complete free evidence read plan over ${backend}`, () => { + it("accepts a real human-confirmed receipt and replays its historical ACK without another verifier call", async () => { + const f = await fixture(await createStore()); + const packet = await f.packet(); + const result = await f.app.submitEvidence(f.agent, packet.input); + expect(result.replayed).toBe(false); + const accepted = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + expect(accepted.evidence).toHaveLength(1); + expect(accepted.evidence[0]?.attestation.id).toBe(packet.input.receipt); + expect(f.requests).toHaveLength(1); + const configuration = await f.app.getGovernanceConfiguration(f.owner, { + collectionId: f.collectionId, + }); + expect(f.requests[0]?.configuration).toEqual(configuration.configuration); + await f.updateDraft(); + const before = await allKnowledgeRows(f.backing); + expect(await f.app.submitEvidence(f.agent, packet.input)).toEqual({ + ...result, + replayed: true, + }); + expect(f.requests).toHaveLength(1); + expect(await allKnowledgeRows(f.backing)).toEqual(before); + }); + + it.each([ + "collection", + "validation", + "collection-version", + "validation-version", + ] as const)( + "refuses a changed %s after the actual verifier returns, without an article transaction", + async (change) => { + const f = await fixture(await createStore()); + const packet = await f.packet(); + f.hooks.afterVerifier = async () => { + if (change === "collection") { + await f.configure({ + expectedStagingBuildId: "changed-after-verification", + }); + } else if (change === "validation") { + const current = await f.app.getValidationPolicy(f.owner, { + policyId: packet.input.evidence.validationPolicy.id, + }); + await f.app.putValidationPolicy(f.owner, { + ...f.command("change-after-verifier", current.generation), + policy: { + ...current.policy, + version: current.policy.version + 1, + }, + }); + } else { + const kind = + change === "collection-version" ? "collection" : "validation"; + const id = + kind === "collection" + ? f.collectionId + : packet.input.evidence.validationPolicy.id; + const row = (await allKnowledgeRows(f.backing)).find( + (item) => + item.kind === "head" && + item.resourceKind === kind && + item.resourceId === id, + ); + if (row === undefined) + throw new Error("Expected the real governed head."); + const records = f.backing.collection(knowledgeRecords); + const key = { partition: row.partition, id: row.id }; + const saved = await records.getVersioned(key); + if (saved === null) + throw new Error("Expected a real head version."); + expect( + await records.putIfUnchanged(saved.value, saved.version), + ).toBe(true); + } + }; + const generation = (await f.current()).generation; + const transactions = f.observed.transactions.length; + await expect( + f.app.submitEvidence(f.agent, packet.input), + ).rejects.toBeInstanceOf(RepositoryConflictError); + expect(f.requests).toHaveLength(1); + expect((await f.current()).generation).toBe(generation); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toEqual([]); + // Real governance commands may commit, but the article may not. + expect( + f.observed.transactions + .slice(transactions) + .filter((trace) => + trace.actions.some( + (action) => + "value" in action && + typeof action.value === "object" && + action.value !== null && + "resourceId" in action.value && + action.value.resourceId === f.articleId, + ), + ), + ).toEqual([]); + }, + ); + + it("uses a fresh age-check clock after verifier and head awaits", async () => { + const f = await fixture(await createStore()); + const packet = await f.packet(); + const requirements = await f.app.getValidationRequirements(f.agent, { + collectionId: f.collectionId, + kind: "walkthrough", + }); + const check = requirements.checks.find( + (item) => item.id === packet.input.evidence.checkId, + ); + if (check === undefined) + throw new Error("Expected the actual configured check."); + f.hooks.afterVerifier = async () => { + f.advance(check.maxAgeMilliseconds + 1); + }; + const before = await allKnowledgeRows(f.backing); + await expect( + f.app.submitEvidence(f.agent, packet.input), + ).rejects.toThrow(); + expect(f.requests).toHaveLength(1); + expect(await allKnowledgeRows(f.backing)).toEqual(before); + }); + + it("issues every required current/published/provenance/evidence/revocation read while the first immutable row is paused", async () => { + const f = await fixture(await createStore()); + await f.completeChecks(); + await f.publish(); + const accepted = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + const proof = accepted.evidence[0]; + if (proof === undefined) + throw new Error("Expected actual accepted proof."); + await f.app.revokeEvidence(f.reviewer, { + ...f.command("retain-complete-history", accepted.generation), + articleId: f.articleId, + articleRevision: proof.articleRevision, + evidenceId: proof.id, + evidenceVersion: proof.version, + evidenceHash: proof.hash, + reason: "Synthetic complete-history race", + }); + const rows = (await allKnowledgeRows(f.backing)).filter( + (row) => row.resourceId === f.articleId, + ); + const revision = rows.find((row) => row.kind === "revision"); + if (revision === undefined) + throw new Error("Expected the actual current revision."); + const gate = reportBarrier(); + const start = f.observed.reads.length; + f.observed.beforeRead(async ({ collection, key }) => { + if ( + collection === knowledgeRecords.name && + key.partition === revision.partition && + key.id === revision.id + ) + await gate.wait(); + }); + const pending = f.app.getDraft(f.agent, { articleId: f.articleId }); + try { + await gate.reached(pending); + const reads = f.observed.reads.slice(start); + for (const kind of [ + "revision", + "evidence", + "provenance", + "publication", + "review", + "revocation", + ]) { + const required = rows.filter((row) => row.kind === kind); + expect(required.length).toBeGreaterThan(0); + for (const row of required) + expect(reads).toContainEqual({ + collection: knowledgeRecords.name, + method: "get", + key: { partition: row.partition, id: row.id }, + }); + } + } finally { + gate.release(); + await pending; + } + expect(await pending).toMatchObject({ + hasPublication: true, + publicationHeld: true, + }); + f.observed.beforeRead(undefined); + const current = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + expect(current.evidence).toHaveLength(2); + expect(current.revokedEvidence).toHaveLength(1); + }); + + it.each(["revision", "provenance", "review", "publication"] as const)( + "retains the refusal when a referenced published %s row is missing", + async (kind) => { + const f = await fixture(await createStore()); + await f.completeChecks(); + await f.publish(); + await f.updateDraft(); + const rows = await allKnowledgeRows(f.backing); + const row = rows.find( + (item) => + item.resourceId === f.articleId && + item.kind === kind && + (kind !== "revision" || item.id === "revision:1"), + ); + if (row === undefined) + throw new Error("Expected the real referenced published row."); + const records = f.backing.collection(knowledgeRecords); + const key = { partition: row.partition, id: row.id }; + const saved = await records.getVersioned(key); + if (saved === null) + throw new Error("Expected an actual immutable version."); + expect(await records.deleteIfUnchanged(key, saved.version)).toBe(true); + const before = f.observed.transactions.length; + await expect( + f.app.getDraft(f.agent, { articleId: f.articleId }), + ).rejects.toBeInstanceOf(RepositoryIntegrityError); + expect(f.observed.transactions).toHaveLength(before); + }, + ); + + it.each([true, false])( + "rechecks admission after another real writer commits (same command=%s)", + async (sameCommand) => { + const f = await fixture(await createStore()); + const first = await f.packet(); + const second = sameCommand ? first : await f.packet(); + const gate = reportBarrier(); + f.observed.beforeRead(async ({ collection, key }) => { + if ( + collection !== knowledgeRecords.name || + !key.id.startsWith("evidence:") + ) + return; + f.observed.beforeRead(undefined); + await gate.wait(); + }); + const pending = f.app.submitEvidence(f.agent, first.input); + // Attach a rejection observer before deliberately racing the real writers. + const settled = pending.then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); + let committedRows; + try { + await gate.reached(pending); + const winner = await f.app.submitEvidence(f.agent, second.input); + expect(winner.replayed).toBe(false); + committedRows = await allKnowledgeRows(f.backing); + } finally { + gate.release(); + await settled; + } + const result = await settled; + if (sameCommand) { + expect(result).toHaveProperty("value.replayed", true); + } else { + expect(result).toHaveProperty("error"); + if ("error" in result) + expect(result.error).toBeInstanceOf(RepositoryConflictError); + } + expect(await allKnowledgeRows(f.backing)).toEqual(committedRows); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toHaveLength(1); + }, + ); + }); +} diff --git a/tests/free-retrieval-step.test.ts b/tests/free-retrieval-step.test.ts new file mode 100644 index 0000000..bc17eaa --- /dev/null +++ b/tests/free-retrieval-step.test.ts @@ -0,0 +1,608 @@ +import { + knowledgeRecords, + type ArticleIndexStatusDto, + type RetrievalRecord, +} from "@pegma/knowledge-base-application"; +import { describe, expect, it } from "vitest"; +import { admin, customer, evidence } from "../test/application-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { + allRetrievalRows, + indexAdministrator, + retrievalFixture, + retrievalGuides, +} from "../test/retrieval-fixtures.js"; +import { barrier, type TransactionTrace } from "../test/trace-store.js"; + +const articleId = "article/export"; +const indexCollection = "knowledge-base.retrieval.v1"; +type Fixture = ReturnType; + +function values(trace: TransactionTrace): RetrievalRecord[] { + if (trace.collection !== indexCollection) return []; + return trace.actions.flatMap((action) => + "value" in action ? [action.value as RetrievalRecord] : [], + ); +} + +function phase(trace: TransactionTrace): string | undefined { + const rows = values(trace); + if ( + rows.some( + (row) => + row.kind === "article" && + (row.data as { status?: string }).status === "ready", + ) + ) + return "finish"; + return rows.find((row) => + ["article", "directory", "catalog", "scope"].includes(row.kind), + )?.kind; +} + +async function publish(f: Fixture) { + await f.setupCollection(); + return f.publishedArticle( + articleId, + "collection/workshop", + retrievalGuides[0]!.draft, + ); +} + +async function step(f: Fixture) { + f.clearObservations(); + const result = await f.app.repairArticleIndex(indexAdministrator, { + articleId, + maxBatches: 1, + }); + expect( + f.traced.transactions.filter( + (trace) => trace.collection === indexCollection, + ).length, + ).toBeLessThanOrEqual(1); + expect(f.traced.enumerations).toEqual([]); + expect(result.articleId).toBe(articleId); + if (result.status !== "ready") expect(result.indexed).toBe(false); + return result; +} + +async function converge( + f: Fixture, + onStep?: (status: ArticleIndexStatusDto) => void, +) { + for (let attempt = 0; attempt < 48; attempt += 1) { + const result = await step(f); + onStep?.(result); + if (result.status !== "pending") return result; + } + throw new Error( + "Bounded synthetic article repair made no convergence within 48 steps", + ); +} + +async function reached( + gate: ReturnType, + pending: Promise, +) { + let timer: ReturnType | undefined; + try { + await Promise.race([ + gate.reached, + pending.then(() => { + throw new Error("Repair completed before its intended barrier"); + }), + new Promise((_resolve, reject) => { + timer = setTimeout( + () => reject(new Error("Repair barrier exceeded 10 seconds")), + 10_000, + ); + }), + ]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } +} + +for (const [backend, createStore] of storeFactories) { + describe(`resumable one-attempt retrieval over ${backend}`, () => { + it("validates explicit keyed/page attempt bounds before any physical I/O", async () => { + const f = retrievalFixture(await createStore(), { + limits: { maxMaintenanceBatches: 2 }, + }); + for (const maxBatches of [ + 0, + -1, + 1.5, + 3, + Number.NaN, + Number.POSITIVE_INFINITY, + ]) { + await expect( + f.app.repairArticleIndex(indexAdministrator, { + articleId, + maxBatches, + }), + ).rejects.toBeInstanceOf(TypeError); + await expect( + f.app.repairRetrievalPage(indexAdministrator, { + limit: 1, + maxBatches, + }), + ).rejects.toBeInstanceOf(TypeError); + } + expect(f.traced.reads).toEqual([]); + expect(f.traced.enumerations).toEqual([]); + expect(f.traced.transactions).toEqual([]); + }); + + it("advances durable prerequisites and both scopes one attempt at a time, then performs an idempotent current no-op", async () => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await publish(f); + const authoritative = await allKnowledgeRows(backing); + const phases: string[] = []; + const generations = new Set(); + const result = await converge(f, (status) => { + if (status.projectionGeneration !== null) + generations.add(status.projectionGeneration); + phases.push( + ...f.traced.transactions + .map(phase) + .filter((value): value is string => value !== undefined), + ); + }); + expect(result).toMatchObject({ status: "ready", indexed: true }); + expect(phases).toContain("directory"); + expect(phases).toContain("catalog"); + expect( + phases.filter((value) => value === "scope").length, + ).toBeGreaterThan(2); + expect(phases).toContain("finish"); + expect([...generations]).toEqual([1]); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles[0]?.articleId, + ).toBe(articleId); + const before = await allRetrievalRows(backing); + expect(await step(f)).toEqual(result); + expect(f.traced.transactions).toEqual([]); + expect(await allRetrievalRows(backing)).toEqual(before); + expect(await allKnowledgeRows(backing)).toEqual(authoritative); + }); + + it.each(["article", "directory", "catalog", "scope"])( + "charges a genuine concurrent %s CAS failure once and resumes without resetting progress", + async (targetPhase) => { + const backing = await createStore(); + const f = retrievalFixture(backing); + const winner = retrievalFixture(backing); + await publish(f); + let collided = false; + f.traced.intercept(async (trace, commit) => { + if (!collided && phase(trace) === targetPhase) { + collided = true; + expect( + ( + await winner.app.repairArticleIndex(indexAdministrator, { + articleId, + maxBatches: 1, + }) + ).status, + ).toBe("pending"); + const outcome = await commit(); + expect(outcome).toMatchObject({ committed: false }); + return outcome; + } + return commit(); + }); + try { + for (let attempt = 0; attempt < 32 && !collided; attempt += 1) + expect((await step(f)).status).toBe("pending"); + expect(collided).toBe(true); + expect(f.traced.transactions).toHaveLength(1); + } finally { + f.traced.intercept(undefined); + } + expect(await converge(f)).toMatchObject({ + status: "ready", + indexed: true, + projectionGeneration: 1, + }); + }, + ); + + it.each(["article", "scope", "finish"])( + "recovers a lost %s transaction acknowledgement without reapplying completed terms or authoritative mutations", + async (targetPhase) => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await publish(f); + const authoritative = await allKnowledgeRows(backing); + let lost = false; + f.traced.intercept(async (trace, commit) => { + const outcome = await commit(); + if (!lost && outcome.committed && phase(trace) === targetPhase) { + lost = true; + throw new Error("Synthetic accepted-write acknowledgement loss"); + } + return outcome; + }); + try { + for (let attempt = 0; attempt < 40 && !lost; attempt += 1) { + f.clearObservations(); + try { + const result = await f.app.repairArticleIndex( + indexAdministrator, + { articleId, maxBatches: 1 }, + ); + expect(result.status).toBe("pending"); + } catch (error) { + expect(lost).toBe(true); + expect(error).toMatchObject({ + message: "Synthetic accepted-write acknowledgement loss", + }); + } + expect( + f.traced.transactions.filter( + (trace) => trace.collection === indexCollection, + ), + ).toHaveLength(1); + } + expect(lost).toBe(true); + } finally { + f.traced.intercept(undefined); + } + const result = await converge(f); + expect(result).toMatchObject({ + status: "ready", + indexed: true, + projectionGeneration: 1, + }); + const rows = await allRetrievalRows(backing); + for (const row of rows.filter((value) => value.kind === "page")) { + const entries = ( + row.data as { entries: { hint: { articleId: string } }[] } + ).entries; + expect( + entries.filter((entry) => entry.hint.articleId === articleId), + ).toHaveLength(1); + } + expect(await step(f)).toEqual(result); + expect(await allRetrievalRows(backing)).toEqual(rows); + expect(await allKnowledgeRows(backing)).toEqual(authoritative); + }, + ); + + it("retains legacy omitted-input convergence and returns a confirmed withdrawal after retirement", async () => { + const f = retrievalFixture(await createStore()); + const published = await publish(f); + f.clearObservations(); + expect( + await f.app.repairArticleIndex(indexAdministrator, { articleId }), + ).toMatchObject({ status: "ready", indexed: true }); + expect(f.traced.transactions.length).toBeGreaterThan(1); + await f.authoringApp.retireArticle(admin, { + ...f.command("retire-step", published.current.generation), + articleId, + }); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + expect(await converge(f)).toMatchObject({ + status: "ready", + indexed: false, + }); + }); + + it("keeps a genuine capacity hold distinct from successful withdrawal", async () => { + const f = retrievalFixture(await createStore(), { + limits: { maxTermsPerArticle: 1 }, + }); + await publish(f); + expect(await converge(f)).toMatchObject({ + status: "blocked", + indexed: false, + reason: "capacity", + }); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + }); + + it("replays an actual opaque physical page with one article attempt and eventually completes without moving the authoritative source", async () => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await publish(f); + const authoritative = await allKnowledgeRows(backing); + let cursor: string | undefined; + let found = false; + for (let page = 0; page < 128; page += 1) { + f.clearObservations(); + const result = await f.app.repairRetrievalPage(indexAdministrator, { + limit: 1, + maxBatches: 1, + ...(cursor === undefined ? {} : { cursor }), + }); + expect(result.physicalRows).toBeLessThanOrEqual(1); + expect(f.traced.transactions.length).toBeLessThanOrEqual(1); + if (f.traced.transactions.some((trace) => phase(trace) === "article")) { + found = true; + break; + } + if (result.nextCursor === null) + throw new Error("No actual article hint in bounded source scan"); + cursor = result.nextCursor; + } + expect(found).toBe(true); + let ready = false; + for (let replay = 0; replay < 40; replay += 1) { + f.clearObservations(); + const result = await f.app.repairRetrievalPage(indexAdministrator, { + limit: 1, + maxBatches: 1, + ...(cursor === undefined ? {} : { cursor }), + }); + expect(result.physicalRows).toBe(1); + expect(f.traced.transactions.length).toBeLessThanOrEqual(1); + if (result.repaired === 1) { + ready = true; + break; + } + } + expect(ready).toBe(true); + expect( + await f.app.getArticleIndexStatus(indexAdministrator, { articleId }), + ).toMatchObject({ status: "ready", indexed: true }); + expect(await allKnowledgeRows(backing)).toEqual(authoritative); + }); + + it("also bounds a real collection-directory conflict on an explicit one-row recovery page", async () => { + const backing = await createStore(); + const f = retrievalFixture(backing); + const winner = retrievalFixture(backing); + await f.setupCollection(); + const records = backing.collection(knowledgeRecords); + let cursor: string | undefined; + let found = false; + for (let page = 0; page < 128; page += 1) { + const result = await records.scan({ + limit: 1, + ...(cursor === undefined ? {} : { cursor }), + }); + if ( + result.records.some( + ({ value }) => + value.resourceKind === "collection" && + (value.kind === "head" || value.kind === "job"), + ) + ) { + found = true; + break; + } + if (result.nextCursor === null) break; + cursor = result.nextCursor; + } + expect(found).toBe(true); + let collided = false; + f.traced.intercept(async (trace, commit) => { + if (!collided && phase(trace) === "directory") { + collided = true; + await winner.app.repairRetrievalPage(indexAdministrator, { + limit: 1, + maxBatches: 1, + ...(cursor === undefined ? {} : { cursor }), + }); + const outcome = await commit(); + expect(outcome.committed).toBe(false); + return outcome; + } + return commit(); + }); + try { + f.clearObservations(); + expect( + await f.app.repairRetrievalPage(indexAdministrator, { + limit: 1, + maxBatches: 1, + ...(cursor === undefined ? {} : { cursor }), + }), + ).toMatchObject({ pending: 1, repaired: 0 }); + expect(collided).toBe(true); + expect(f.traced.transactions).toHaveLength(1); + } finally { + f.traced.intercept(undefined); + } + expect( + await f.app.repairRetrievalPage(indexAdministrator, { + limit: 1, + maxBatches: 1, + ...(cursor === undefined ? {} : { cursor }), + }), + ).toMatchObject({ repaired: 1 }); + }); + + // 32 real public submissions over released D1/default single reads make + // setup substantial. This case-only timeout is not a latency assertion. + it("reads all 28 retained approved proofs and revocation markers while preserving 32 legitimate current proofs", async () => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + const configuration = await f.authoringApp.getGovernanceConfiguration( + admin, + { + collectionId: "collection/workshop", + }, + ); + const policy = await f.authoringApp.getValidationPolicy(admin, { + policyId: configuration.configuration.validationPolicy.id, + }); + const template = policy.policy.requirements.find( + (check) => check.kind === "explanation", + )!; + // The 32-check policy must also retain content checks for the other three + // kinds and the walkthrough workflow check. Exactly 28 explanation checks + // can therefore qualify this publication; 32 approved checks are illegal. + const required = Array.from({ length: 28 }, (_unused, ordinal) => ({ + ...template, + id: `full/content/${ordinal}`, + })); + const requirements = [ + ...policy.policy.requirements.filter( + (check) => check.kind !== "explanation", + ), + ...required, + ]; + expect(requirements).toHaveLength(32); + const policyVersion = policy.policy.version + 1; + await f.authoringApp.putValidationPolicy(admin, { + ...f.command("full-proof-policy", policy.generation), + policy: { ...policy.policy, version: policyVersion, requirements }, + }); + await f.authoringApp.putGovernanceConfiguration(admin, { + ...f.command("full-proof-configuration", configuration.generation), + collectionId: "collection/workshop", + configuration: { + ...configuration.configuration, + validationPolicy: { id: policy.policy.id, version: policyVersion }, + }, + }); + let current = await f.createDraft(); + for (const [proof, check] of required.entries()) + current = ( + await f.submitEvidence(current, undefined, { + ...evidence(current.revision), + id: `proof/full/${proof}`, + checkId: check.id, + testKind: check.testKind, + }) + ).current; + current = (await f.publish(current)).current; + // Four later, genuinely verified draft proofs retain the same content and + // policy. They cannot silently join or rewrite the retained approval. + for (let proof = 0; proof < 4; proof += 1) + current = ( + await f.submitEvidence(current, undefined, { + ...evidence(current.revision), + id: `proof/later/${proof}`, + checkId: required[proof]!.id, + testKind: required[proof]!.testKind, + }) + ).current; + expect(current).toMatchObject({ state: "draft", hasPublication: true }); + expect( + (await f.authoringApp.getEvidence(admin, { articleId })).evidence, + ).toHaveLength(32); + f.clearObservations(); + expect( + await f.app.getPublishedArticle(customer, { articleId }), + ).toMatchObject({ articleId, contentHash: current.revision.contentHash }); + const rows = f.traced.reads.filter( + (trace) => trace.collection === "knowledge-base.records.v1", + ); + const proofs = rows.filter((trace) => + trace.key.id.startsWith("evidence:"), + ); + const revocations = rows.filter((trace) => + trace.key.id.startsWith("revoked:"), + ); + expect(proofs).toHaveLength(28); + expect(revocations).toHaveLength(28); + const lastProof = Math.max( + ...rows.map((trace, index) => + trace.key.id.startsWith("evidence:") || + trace.key.id.startsWith("revoked:") + ? index + : -1, + ), + ); + expect( + rows.slice(lastProof + 1).filter((trace) => trace.key.id === "head"), + ).toHaveLength(3); + expect(f.traced.transactions).toEqual([]); + const retained = (await allKnowledgeRows(backing)).filter( + (row) => row.kind === "evidence", + ); + expect(retained).toHaveLength(32); + const selected = proofs.at(-1)!; + const last = retained.find( + (row) => + row.partition === selected.key.partition && + row.id === selected.key.id, + )!; + await backing + .collection(knowledgeRecords) + .delete({ partition: last.partition, id: last.id }); + await expect( + f.app.getPublishedArticle(customer, { articleId }), + ).rejects.toMatchObject({ name: "KnowledgeBaseNotFoundError" }); + }, 480_000); + + it.each(["retire", "policy"])( + "refuses %s after the last immutable publication proof await", + async (change) => { + const f = retrievalFixture(await createStore()); + const published = await publish(f); + const gate = barrier(); + let armed = true; + f.traced.beforeRead(async (trace) => { + if ( + armed && + trace.collection === "knowledge-base.records.v1" && + trace.key.id.startsWith("evidence:") + ) { + armed = false; + await gate.wait(); + } + }); + f.clearObservations(); + const pending = f.app.repairArticleIndex(indexAdministrator, { + articleId, + maxBatches: 1, + }); + try { + await reached(gate, pending); + if (change === "retire") + await f.authoringApp.retireArticle(admin, { + ...f.command("retire-proof-await", published.current.generation), + articleId, + }); + else { + const preview = await f.authoringApp.previewCollectionPolicy( + admin, + { + collectionId: "collection/workshop", + uses: { portal: { enabled: false }, bot: { enabled: false } }, + }, + ); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("withdraw-proof-await", preview.generation), + collectionId: "collection/workshop", + preview: preview.preview, + }); + } + } finally { + gate.release(); + f.traced.beforeRead(undefined); + } + expect(await pending).toMatchObject({ + status: "pending", + indexed: false, + }); + expect( + f.traced.transactions + .flatMap(values) + .filter((row) => row.kind === "scope" || row.kind === "page"), + ).toEqual([]); + expect( + (await f.app.searchPublishedArticles(customer, f.portalInput())) + .articles, + ).toEqual([]); + }, + ); + }); +} diff --git a/tests/read-context.test.ts b/tests/read-context.test.ts new file mode 100644 index 0000000..5a82b16 --- /dev/null +++ b/tests/read-context.test.ts @@ -0,0 +1,357 @@ +import { + createKnowledgeBaseApplication, + knowledgeRecords, + KnowledgeBaseAuthorizationError, + RepositoryConflictError, + RepositoryIntegrityError, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { describe, expect, it } from "vitest"; +import { access } from "../test/application-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { + evidenceReportsFixture, + reportBarrier, +} from "../test/evidence-reports-fixtures.js"; + +for (const [backend, createStore] of storeFactories) { + describe(`governed authoring observations over ${backend}`, () => { + it("projects author-only material without private history, and detaches it from persistence", async () => { + const f = await evidenceReportsFixture(await createStore()); + await f.completeChecks(); + await f.publish(); + const before = f.observed.reads.length; + const enumerations = f.observed.enumerations.length; + const result = await f.app.getAuthoringContext(f.agent, { + articleId: f.articleId, + }); + expect(result.context.evidence).toBeUndefined(); + expect(result.context.draft.hasPublication).toBe(true); + expect( + result.context.requirements.checks.map((check) => check.id).sort(), + ).toEqual(["walkthrough-content", "walkthrough-workflow"]); + const reads = f.observed.reads.slice(before); + expect(reads).not.toHaveLength(0); + expect( + reads.some(({ key }) => + /^(evidence:|revoked:|provenance:|review:|publication:)/u.test( + key.id, + ), + ), + ).toBe(false); + expect(JSON.stringify(result.context)).not.toContain( + "PRIVATE_STAFF_EVIDENCE", + ); + expect(JSON.stringify(result.context)).not.toContain( + "trustedAttesterIds", + ); + const title = result.context.draft.revision.title; + Reflect.set( + result.context.draft.revision, + "title", + "Mutated returned projection", + ); + expect((await f.current()).revision.title).toBe(title); + await expect( + f.app.confirmAuthoringContext(f.agent, result.observation), + ).resolves.toBeUndefined(); + expect(f.observed.enumerations).toHaveLength(enumerations); + }); + + it("requires the exact named projection clauses without upgrading an agent to its owner", async () => { + const f = await evidenceReportsFixture(await createStore()); + for (const permissions of [ + [knowledgePermissions.draftRead], + [knowledgePermissions.draftWrite], + [knowledgePermissions.evidenceSubmit], + ]) { + const before = f.observed.reads.length; + await expect( + f.app.getAuthoringContext(access(f.agent.principalId, permissions), { + articleId: f.articleId, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + expect(f.observed.reads).toHaveLength(before); + } + for (const alternative of [ + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, + ]) { + const caller = access(f.agent.principalId, [ + knowledgePermissions.draftRead, + alternative, + ]); + const result = await f.app.getAuthoringContext(caller, { + articleId: f.articleId, + }); + await expect( + f.app.confirmAuthoringContext(caller, result.observation), + ).resolves.toBeUndefined(); + } + await expect( + f.app.getAuthoringContext(f.agent, { + articleId: f.articleId, + includeEvidence: true, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + expect(f.agent.permissions).toHaveLength(3); + }); + + it("rejects unknown fields and explicit undefined instead of silently selecting a projection", async () => { + const f = await evidenceReportsFixture(await createStore()); + for (const input of [ + { articleId: f.articleId, includeEvidence: undefined }, + { articleId: f.articleId, includeEvidence: "false" }, + { articleId: f.articleId, trustedAttesterIds: [] }, + ]) { + const before = f.observed.reads.length; + await expect( + Reflect.apply(f.app.getAuthoringContext, f.app, [f.agent, input]), + ).rejects.toBeInstanceOf(TypeError); + expect(f.observed.reads).toHaveLength(before); + } + }); + + it("returns the complete accepted evidence and retained revocations only with evidenceRead", async () => { + const f = await evidenceReportsFixture(await createStore()); + await f.completeChecks(); + const accepted = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + const first = accepted.evidence[0]; + if (first === undefined) + throw new Error("Expected actual accepted evidence."); + await f.app.revokeEvidence(f.reviewer, { + ...f.command("revoke-for-projection", accepted.generation), + articleId: f.articleId, + articleRevision: first.articleRevision, + evidenceId: first.id, + evidenceVersion: first.version, + evidenceHash: first.hash, + reason: "Synthetic independent revocation", + }); + const expected = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + const projected = await f.app.getAuthoringContext(f.reviewer, { + articleId: f.articleId, + includeEvidence: true, + }); + expect(projected.context.evidence).toEqual(expected); + expect(projected.context.evidence?.evidence).toHaveLength(2); + expect(projected.context.evidence?.revokedEvidence).toHaveLength(1); + const restricted = access( + f.reviewer.principalId, + f.reviewer.permissions.filter( + (permission) => permission !== knowledgePermissions.evidenceRead, + ), + ); + const before = f.observed.reads.length; + await expect( + f.app.confirmAuthoringContext(restricted, projected.observation), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + expect(f.observed.reads).toHaveLength(before); + }); + + it("rejects forged, serialized, foreign-instance and wrong-actor handles before storage", async () => { + const f = await evidenceReportsFixture(await createStore()); + const result = await f.app.getAuthoringContext(f.agent, { + articleId: f.articleId, + }); + const foreign = createKnowledgeBaseApplication({ + store: f.observed.store, + clock: f.clock, + }); + const before = f.observed.reads.length; + await expect( + Reflect.apply(f.app.confirmAuthoringContext, f.app, [f.agent, {}]), + ).rejects.toBeInstanceOf(TypeError); + await expect( + f.app.confirmAuthoringContext( + f.agent, + structuredClone(result.observation), + ), + ).rejects.toBeInstanceOf(TypeError); + await expect( + foreign.confirmAuthoringContext(f.agent, result.observation), + ).rejects.toBeInstanceOf(TypeError); + await expect( + f.app.confirmAuthoringContext(f.otherAgent, result.observation), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + expect(f.observed.reads).toHaveLength(before); + }); + + it("consumes an observation before its first awaited read, including overlapping confirmation", async () => { + const f = await evidenceReportsFixture(await createStore()); + const { observation } = await f.app.getAuthoringContext(f.agent, { + articleId: f.articleId, + }); + const gate = reportBarrier(); + f.observed.beforeRead(async () => { + f.observed.beforeRead(undefined); + await gate.wait(); + }); + const pending = f.app.confirmAuthoringContext(f.agent, observation); + await gate.reached(pending); + try { + const before = f.observed.reads.length; + await expect( + f.app.confirmAuthoringContext(f.agent, observation), + ).rejects.toBeInstanceOf(TypeError); + expect(f.observed.reads).toHaveLength(before); + } finally { + gate.release(); + } + await pending; + await expect( + f.app.confirmAuthoringContext(f.agent, observation), + ).rejects.toBeInstanceOf(TypeError); + }); + + it.each(["article", "collection", "validation"] as const)( + "refuses a changed %s head and never retries an ambiguous observation", + async (kind) => { + const f = await evidenceReportsFixture(await createStore()); + const result = await f.app.getAuthoringContext(f.agent, { + articleId: f.articleId, + }); + if (kind === "article") await f.updateDraft(); + else if (kind === "collection") + await f.configure({ expectedStagingBuildId: "changed-build" }); + else { + const policyId = result.context.requirements.validationPolicy.id; + const current = await f.app.getValidationPolicy(f.owner, { + policyId, + }); + await f.app.putValidationPolicy(f.owner, { + ...f.command("replace-validation-head", current.generation), + policy: { ...current.policy, version: current.policy.version + 1 }, + }); + } + await expect( + f.app.confirmAuthoringContext(f.agent, result.observation), + ).rejects.toBeInstanceOf(RepositoryConflictError); + await expect( + f.app.confirmAuthoringContext(f.agent, result.observation), + ).rejects.toBeInstanceOf(TypeError); + }, + ); + + it("detects an opaque head-version change even when numeric generation and payload are unchanged", async () => { + const f = await evidenceReportsFixture(await createStore()); + const result = await f.app.getAuthoringContext(f.agent, { + articleId: f.articleId, + }); + const row = (await allKnowledgeRows(f.backing)).find( + (value) => value.resourceId === f.articleId && value.kind === "head", + ); + if (row === undefined) throw new Error("Expected the real article head."); + const records = f.backing.collection(knowledgeRecords); + const saved = await records.getVersioned({ + partition: row.partition, + id: row.id, + }); + if (saved === null) throw new Error("Expected a versioned real head."); + expect(await records.putIfUnchanged(saved.value, saved.version)).toBe( + true, + ); + await expect( + f.app.confirmAuthoringContext(f.agent, result.observation), + ).rejects.toBeInstanceOf(RepositoryConflictError); + }); + + it("rejects an edit during the initial governed read instead of returning mixed current facts", async () => { + const f = await evidenceReportsFixture(await createStore()); + const row = (await allKnowledgeRows(f.backing)).find( + (value) => value.resourceId === f.articleId && value.kind === "head", + ); + if (row === undefined) throw new Error("Expected the real article head."); + let observations = 0; + f.observed.beforeRead(async ({ key }) => { + if (key.partition !== row.partition || key.id !== "head") return; + observations += 1; + if (observations !== 2) return; + f.observed.beforeRead(undefined); + await f.updateDraft(); + }); + await expect( + f.app.getAuthoringContext(f.agent, { articleId: f.articleId }), + ).rejects.toBeInstanceOf(RepositoryConflictError); + expect(observations).toBe(2); + }); + + it("rejects a missing referenced immutable revision without changing any records", async () => { + const f = await evidenceReportsFixture(await createStore()); + const row = (await allKnowledgeRows(f.backing)).find( + (value) => + value.resourceId === f.articleId && value.kind === "revision", + ); + if (row === undefined) + throw new Error("Expected the real immutable revision."); + const records = f.backing.collection(knowledgeRecords); + const saved = await records.getVersioned({ + partition: row.partition, + id: row.id, + }); + if (saved === null) throw new Error("Expected actual immutable storage."); + expect( + await records.deleteIfUnchanged( + { partition: row.partition, id: row.id }, + saved.version, + ), + ).toBe(true); + const before = f.observed.transactions.length; + await expect( + f.app.getAuthoringContext(f.agent, { articleId: f.articleId }), + ).rejects.toBeInstanceOf(RepositoryIntegrityError); + expect(f.observed.transactions).toHaveLength(before); + }); + + it.each(["evidence", "revocation"] as const)( + "refuses missing referenced %s facts instead of returning an incomplete EvidenceDto", + async (kind) => { + const f = await evidenceReportsFixture(await createStore()); + await f.completeChecks(); + if (kind === "revocation") { + const accepted = await f.app.getEvidence(f.reviewer, { + articleId: f.articleId, + }); + const first = accepted.evidence[0]; + if (first === undefined) + throw new Error("Expected actual accepted evidence."); + await f.app.revokeEvidence(f.reviewer, { + ...f.command("revoke-missing-fact", accepted.generation), + articleId: f.articleId, + articleRevision: first.articleRevision, + evidenceId: first.id, + evidenceVersion: first.version, + evidenceHash: first.hash, + reason: "Synthetic missing-marker test", + }); + } + const row = (await allKnowledgeRows(f.backing)).find( + (value) => value.resourceId === f.articleId && value.kind === kind, + ); + if (row === undefined) + throw new Error("Expected the real referenced immutable fact."); + const records = f.backing.collection(knowledgeRecords); + const key = { partition: row.partition, id: row.id }; + const saved = await records.getVersioned(key); + if (saved === null) + throw new Error("Expected the referenced fact in real storage."); + expect(await records.deleteIfUnchanged(key, saved.version)).toBe(true); + const before = f.observed.transactions.length; + await expect( + f.app.getAuthoringContext(f.reviewer, { + articleId: f.articleId, + includeEvidence: true, + }), + ).rejects.toBeInstanceOf(RepositoryIntegrityError); + expect(f.observed.transactions).toHaveLength(before); + }, + ); + }); +} diff --git a/tests/report-query.test.ts b/tests/report-query.test.ts new file mode 100644 index 0000000..1cfa4d1 --- /dev/null +++ b/tests/report-query.test.ts @@ -0,0 +1,727 @@ +import { + type KnowledgeAuthoringContextObservation, + type KnowledgeReportAcknowledgement, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import type { AccessContext } from "@pegma/authorization-core"; +import type { Store } from "@pegma/storage-core"; +import { describe, expect, it, vi } from "vitest"; +import { access } from "../test/application-fixtures.js"; +import { storeFactories } from "../test/application-stores.js"; +import { + confirmationPermission, + evidenceReportsFixture, + reportBarrier, +} from "../test/evidence-reports-fixtures.js"; + +async function queryFixture(backing: Store, optimized = true) { + const f = await evidenceReportsFixture(backing); + const hooks: { + beforeConfirm?: () => Promise; + beforeLegacyContext?: () => Promise; + } = {}; + const authoringContext = { + getAuthoringContext: vi.fn(f.app.getAuthoringContext), + confirmAuthoringContext: vi.fn( + async ( + caller: AccessContext, + observation: KnowledgeAuthoringContextObservation, + ) => { + await hooks.beforeConfirm?.(); + return f.app.confirmAuthoringContext(caller, observation); + }, + ), + }; + const reports = f.freshReports( + optimized + ? { authoringContext } + : { + readContext: async (caller, articleId) => { + await hooks.beforeLegacyContext?.(); + return f.readContext(caller, articleId); + }, + }, + ); + async function packet() { + const current = await f.current(); + const input = { + ...(await f.reportInput()), + expectedArticleGeneration: current.generation, + }; + return { input, ack: await reports.report(f.agent, input) }; + } + async function decision( + ack: KnowledgeReportAcknowledgement, + status: "confirmed" | "pending" = "confirmed", + ) { + const view = await reports.read(f.reviewer, f.key(ack)); + return { + ...f.key(ack), + commandId: f.command("query-" + status, 0).commandId, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }; + } + return { + ...f, + reports, + authoringContext, + queryHooks: hooks, + packet, + decision, + }; +} + +/** Pause the real optimized confirmation, or the second real legacy context. + * Captured pauses occur after the legacy context's authoritative reads; the + * before-read variant lets article changes be observed by those actual reads. + * Every hook is one-shot so the concurrent public operation cannot deadlock. */ +function pauseFinalContext( + f: Awaited>, + optimized: boolean, + beforeLegacyRead = false, +) { + const gate = reportBarrier(); + if (optimized) { + f.queryHooks.beforeConfirm = async () => { + delete f.queryHooks.beforeConfirm; + await gate.wait(); + }; + } else { + let contexts = 0; + if (beforeLegacyRead) { + f.queryHooks.beforeLegacyContext = async () => { + if (++contexts !== 2) return; + delete f.queryHooks.beforeLegacyContext; + await gate.wait(); + }; + } else { + f.hooks.afterContext = async () => { + if (++contexts !== 2) return; + delete f.hooks.afterContext; + await gate.wait(); + }; + } + } + return gate; +} + +function captureQuery(pending: Promise) { + return pending.then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); +} + +for (const [backend, createStore] of storeFactories) { + describe(`body-free governed report query over ${backend}`, () => { + it("discovers the current target and polls pending/confirmed status without private data or writes", async () => { + const f = await queryFixture(await createStore()); + const packet = await f.packet(); + const before = f.observed.transactions.length; + const query = { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }; + const pending = await f.reports.query(f.agent, query); + expect(pending.target).toEqual({ + articleId: f.articleId, + generation: (await f.current()).generation, + collectionId: f.collectionId, + kind: "walkthrough", + }); + expect(pending.status).toEqual({ ...packet.ack, status: "pending" }); + expect(f.observed.transactions).toHaveLength(before); + for (const privateValue of [ + packet.input.report.details, + "PRIVATE_STAFF_EVIDENCE", + f.reviewer.principalId, + "trustedAttesterIds", + "reportHash", + "reviewBindingHash", + ]) { + expect(JSON.stringify(pending)).not.toContain(privateValue); + } + expect(f.readContext).not.toHaveBeenCalled(); + await f.reports.decide( + f.reviewer, + await f.decision(packet.ack), + "confirmed", + ); + const confirmed = await f.reports.query(f.agent, query); + expect(confirmed.status).toEqual({ + ...packet.ack, + reportGeneration: 2, + status: "confirmed", + }); + expect( + (await f.app.getEvidence(f.reviewer, { articleId: f.articleId })) + .evidence, + ).toEqual([]); + const discovery = await f.reports.query(f.agent, { + articleId: f.articleId, + }); + expect(discovery.status).toBeUndefined(); + expect(discovery.ledger.status).toBe("active"); + }); + + it("requires draftRead AND evidenceSubmit and never promotes a restricted caller to its owner", async () => { + const f = await queryFixture(await createStore()); + for (const permissions of [ + [knowledgePermissions.draftRead], + [knowledgePermissions.evidenceSubmit], + [knowledgePermissions.draftRead, knowledgePermissions.draftWrite], + ]) { + const before = f.observed.reads.length; + await expect( + f.reports.query(access(f.agent.principalId, permissions), { + articleId: f.articleId, + }), + ).rejects.toMatchObject({ code: "forbidden" }); + expect(f.observed.reads).toHaveLength(before); + } + const result = await f.reports.query(f.agent, { articleId: f.articleId }); + expect(result.status).toBeUndefined(); + expect( + f.authoringContext.getAuthoringContext.mock.calls.at(-1)?.[0] + .permissions, + ).toEqual(f.agent.permissions); + expect(f.agent.permissions).toHaveLength(3); + }); + + it("hides another submitter's status while allowing the same public ledger discovery", async () => { + const f = await queryFixture(await createStore()); + const packet = await f.packet(); + const before = await f.rows(); + await expect( + f.reports.query(f.otherAgent, { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }), + ).rejects.toMatchObject({ code: "report_not_found" }); + expect( + (await f.reports.query(f.otherAgent, { articleId: f.articleId })).ledger + .ledgerEpoch, + ).toBe(packet.ack.ledgerEpoch); + expect(await f.rows()).toEqual(before); + }); + + it.each([false, true])( + "keeps old context fallback and historical exact report replay (optimized=%s)", + async (optimized) => { + const f = await queryFixture(await createStore(), optimized); + const packet = await f.packet(); + const original = await f.decision(packet.ack); + const confirmed = await f.reports.decide( + f.reviewer, + original, + "confirmed", + ); + await f.updateDraft(); + const before = await f.rows(); + const contextCalls = + f.authoringContext.getAuthoringContext.mock.calls.length; + await expect(f.reports.report(f.agent, packet.input)).resolves.toEqual( + packet.ack, + ); + await expect( + f.reports.decide(f.reviewer, original, "confirmed"), + ).resolves.toEqual(confirmed); + expect(await f.rows()).toEqual(before); + expect(f.authoringContext.getAuthoringContext).toHaveBeenCalledTimes( + contextCalls, + ); + const fresh = await f.reports.query(f.agent, { + articleId: f.articleId, + }); + expect(fresh.target.generation).toBe((await f.current()).generation); + if (!optimized) + expect(f.readContext.mock.calls.length).toBeGreaterThanOrEqual(2); + }, + ); + + it("returns resetting ledger metadata but refuses old-epoch status and never rearms a report", async () => { + const f = await queryFixture(await createStore()); + const packet = await f.packet(); + await f.reports.reset(f.reviewer, { + articleId: f.articleId, + commandId: "query-reset", + expectedLedgerEpoch: packet.ack.ledgerEpoch, + }); + const before = await f.rows(); + const result = await f.reports.query(f.agent, { articleId: f.articleId }); + expect(result.ledger).toMatchObject({ + ledgerEpoch: packet.ack.ledgerEpoch + 1, + status: "resetting", + }); + await expect( + f.reports.query(f.agent, { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }), + ).rejects.toMatchObject({ code: "ledger_epoch_changed" }); + expect(await f.rows()).toEqual(before); + }); + + it.each([ + { optimized: false, drain: false }, + { optimized: true, drain: false }, + { optimized: false, drain: true }, + { optimized: true, drain: true }, + ])( + "withholds the old epoch/receipt after reset during final context (optimized=$optimized, drain=$drain)", + async ({ optimized, drain }) => { + const f = await queryFixture(await createStore(), optimized); + const packet = await f.packet(); + await f.reports.decide( + f.reviewer, + await f.decision(packet.ack), + "confirmed", + ); + const before = await f.physicalRows(); + const oldReport = before.find(({ value }) => + value.id.startsWith("report:"), + ); + const oldHead = before.find(({ value }) => value.id === "head"); + if (oldReport === undefined || oldHead === undefined) + throw new Error("Expected real report and ledger head rows."); + const gate = pauseFinalContext(f, optimized); + const pending = f.reports.query(f.agent, { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }); + const outcome = captureQuery(pending); + try { + await gate.reached(pending); + let ledger = await f.reports.reset(f.reviewer, { + articleId: f.articleId, + commandId: "reset-during-final-query-context", + expectedLedgerEpoch: packet.ack.ledgerEpoch, + }); + const resetRows = await f.physicalRows(); + expect( + resetRows.find(({ value }) => value.id === oldReport.value.id), + ).toEqual(oldReport); + expect( + resetRows.find(({ value }) => value.id === "head")?.version, + ).not.toBe(oldHead.version); + if (drain) { + for ( + let page = 0; + ledger.status === "resetting" && page < 4; + page++ + ) + ledger = await f.reports.drain(f.reviewer, { + articleId: f.articleId, + ledgerEpoch: ledger.ledgerEpoch, + }); + expect(ledger.status).toBe("active"); + expect( + (await f.physicalRows()).some( + ({ value }) => value.id === oldReport.value.id, + ), + ).toBe(false); + } + const settled = await f.rows(); + const writes = f.observed.transactions.length; + gate.release(); + await expect(outcome).resolves.toMatchObject({ + error: { + code: drain + ? expect.stringMatching( + /^(ledger_epoch_changed|report_not_found)$/u, + ) + : "ledger_epoch_changed", + }, + }); + expect(await f.rows()).toEqual(settled); + expect(f.observed.transactions).toHaveLength(writes); + } finally { + gate.release(); + await outcome; + } + }, + ); + + it.each([ + { optimized: false, change: "suspend" }, + { optimized: true, change: "suspend" }, + { optimized: false, change: "revoke" }, + { optimized: true, change: "revoke" }, + ] as const)( + "re-resolves restricted authority after final context (optimized=$optimized, change=$change)", + async ({ optimized, change }) => { + const f = await queryFixture(await createStore(), optimized); + await f.packet(); + const before = await f.rows(); + const resolutions = f.resolvePrincipal.mock.calls.filter( + ([id]) => id === f.agent.principalId, + ).length; + const gate = pauseFinalContext(f, optimized); + const pending = f.reports.query(f.agent, { articleId: f.articleId }); + const outcome = captureQuery(pending); + try { + await gate.reached(pending); + if (change === "suspend") f.principals.delete(f.agent.principalId); + else + f.principals.set( + f.agent.principalId, + access( + f.agent.principalId, + f.owner.permissions.filter( + (permission) => + permission !== knowledgePermissions.evidenceSubmit, + ), + ), + ); + gate.release(); + await expect(outcome).resolves.toMatchObject({ + error: { code: "forbidden" }, + }); + expect( + f.resolvePrincipal.mock.calls.filter( + ([id]) => id === f.agent.principalId, + ), + ).toHaveLength(resolutions + 2); + expect(await f.rows()).toEqual(before); + const projected = optimized + ? f.authoringContext.getAuthoringContext.mock.calls.at(-1)?.[0] + : f.readContext.mock.calls.at(-1)?.[0]; + expect(projected?.permissions).toEqual(f.agent.permissions); + expect(f.agent.permissions).toHaveLength(3); + } finally { + gate.release(); + await outcome; + } + }, + ); + + it.each([false, true])( + "refuses a head-only report claim during final context (optimized=%s)", + async (optimized) => { + const f = await queryFixture(await createStore(), optimized); + const packet = await f.packet(); + const before = await f.physicalRows(); + const report = before.find(({ value }) => + value.id.startsWith("report:"), + ); + const head = before.find(({ value }) => value.id === "head"); + if (report === undefined || head === undefined) + throw new Error("Expected real query rows."); + const gate = pauseFinalContext(f, optimized); + const pending = f.reports.query(f.agent, { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }); + const outcome = captureQuery(pending); + try { + await gate.reached(pending); + const next = await f.packet(); + expect(next.ack.reportId).not.toBe(packet.ack.reportId); + expect(next.ack.ledgerEpoch).toBe(packet.ack.ledgerEpoch); + const settled = await f.physicalRows(); + expect( + settled.find(({ value }) => value.id === report.value.id), + ).toEqual(report); + expect( + settled.find(({ value }) => value.id === "head")?.version, + ).not.toBe(head.version); + const writes = f.observed.transactions.length; + gate.release(); + await expect(outcome).resolves.toMatchObject({ + error: { code: "ledger_changed" }, + }); + expect(await f.physicalRows()).toEqual(settled); + expect(f.observed.transactions).toHaveLength(writes); + } finally { + gate.release(); + await outcome; + } + }, + ); + + it.each([false, true])( + "retains the exact report mutation fence after final context (optimized=%s)", + async (optimized) => { + const f = await queryFixture(await createStore(), optimized); + const packet = await f.packet(); + const command = await f.decision(packet.ack); + const old = (await f.physicalRows()).find(({ value }) => + value.id.startsWith("report:"), + ); + if (old === undefined) throw new Error("Expected the real report row."); + const gate = pauseFinalContext(f, optimized); + const pending = f.reports.query(f.agent, { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }); + const outcome = captureQuery(pending); + try { + await gate.reached(pending); + await f.reports.decide(f.reviewer, command, "confirmed"); + const settled = await f.physicalRows(); + expect( + settled.find(({ value }) => value.id === old.value.id)?.version, + ).not.toBe(old.version); + const writes = f.observed.transactions.length; + gate.release(); + await expect(outcome).resolves.toMatchObject({ + error: { + code: expect.stringMatching(/^(ledger_changed|report_changed)$/u), + }, + }); + expect(await f.physicalRows()).toEqual(settled); + expect(f.observed.transactions).toHaveLength(writes); + } finally { + gate.release(); + await outcome; + } + }, + ); + + it.each([ + { optimized: false, change: "edit" }, + { optimized: true, change: "edit" }, + { optimized: false, change: "retire" }, + { optimized: true, change: "retire" }, + ] as const)( + "retains real article mutation/retirement fences after initial reads (optimized=$optimized, change=$change)", + async ({ optimized, change }) => { + const f = await queryFixture(await createStore(), optimized); + const packet = await f.packet(); + const current = await f.current(); + const before = await f.rows(); + const gate = pauseFinalContext(f, optimized, true); + const pending = f.reports.query(f.agent, { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }); + const outcome = captureQuery(pending); + try { + await gate.reached(pending); + if (change === "edit") await f.updateDraft(); + else + await f.app.retireArticle(f.reviewer, { + ...f.command("retire-during-query-context", current.generation), + articleId: f.articleId, + }); + const changed = await f.current(); + expect(changed.generation).toBeGreaterThan(current.generation); + if (change === "retire") expect(changed.state).toBe("retired"); + const writes = f.observed.transactions.length; + gate.release(); + await expect(outcome).resolves.toMatchObject({ + error: { code: "report_changed" }, + }); + expect(await f.rows()).toEqual(before); + expect(f.observed.transactions).toHaveLength(writes); + } finally { + gate.release(); + await outcome; + } + }, + ); + + it.each(["confirmed", "pending"] as const)( + "refuses a %s decision/reassessment between the first and final report observations", + async (transition) => { + const f = await queryFixture(await createStore()); + const packet = await f.packet(); + if (transition === "pending") + await f.reports.decide( + f.reviewer, + await f.decision(packet.ack), + "confirmed", + ); + const command = await f.decision(packet.ack, transition); + const row = (await f.physicalRows()).find((item) => + item.value.id.startsWith("report:"), + ); + if (row === undefined) + throw new Error("Expected the factory's actual report key."); + let reads = 0; + f.observed.beforeRead(async ({ collection, key }) => { + if ( + collection !== f.namespace || + key.partition !== row.key.partition || + key.id !== row.key.id + ) + return; + reads += 1; + if (reads !== 2) return; + f.observed.beforeRead(undefined); + await f.reports.decide(f.reviewer, command, transition); + }); + await expect( + f.reports.query(f.agent, { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }), + ).rejects.toMatchObject({ code: "report_changed" }); + expect(reads).toBe(2); + }, + ); + + it("refuses a reset observed at the second ledger read", async () => { + const f = await queryFixture(await createStore()); + const packet = await f.packet(); + const row = (await f.physicalRows()).find( + (item) => item.value.id === "head", + ); + if (row === undefined) + throw new Error("Expected the factory's actual head key."); + let heads = 0; + f.observed.beforeRead(async ({ collection, key }) => { + if ( + collection !== f.namespace || + key.partition !== row.key.partition || + key.id !== row.key.id + ) + return; + heads += 1; + if (heads !== 2) return; + f.observed.beforeRead(undefined); + await f.reports.reset(f.reviewer, { + articleId: f.articleId, + commandId: "reset-query-race", + expectedLedgerEpoch: packet.ack.ledgerEpoch, + }); + }); + await expect( + f.reports.query(f.agent, { + articleId: f.articleId, + status: { + ledgerEpoch: packet.ack.ledgerEpoch, + reportId: packet.ack.reportId, + }, + }), + ).rejects.toMatchObject({ code: "ledger_epoch_changed" }); + expect(heads).toBe(2); + }); + + it("conflicts on changed governed facts during the query without a new context fallback", async () => { + const f = await queryFixture(await createStore()); + f.queryHooks.beforeConfirm = async () => { + await f.updateDraft(); + }; + const before = f.authoringContext.getAuthoringContext.mock.calls.length; + await expect( + f.reports.query(f.agent, { articleId: f.articleId }), + ).rejects.toMatchObject({ code: "report_changed" }); + expect(f.authoringContext.getAuthoringContext).toHaveBeenCalledTimes( + before + 1, + ); + expect(f.readContext).not.toHaveBeenCalled(); + }); + + it("withholds query output when current principal resolution loses the required grant", async () => { + const f = await queryFixture(await createStore()); + let resolutions = 0; + f.hooks.beforeResolve = async (id) => { + if (id !== f.agent.principalId) return; + resolutions += 1; + if (resolutions === 2) + f.principals.set( + id, + access( + id, + f.owner.permissions.filter( + (permission) => + permission !== knowledgePermissions.evidenceSubmit, + ), + ), + ); + }; + const before = await f.rows(); + await expect( + f.reports.query(f.agent, { articleId: f.articleId }), + ).rejects.toMatchObject({ code: "forbidden" }); + expect(await f.rows()).toEqual(before); + }); + + it.each([ + confirmationPermission, + knowledgePermissions.draftRead, + knowledgePermissions.evidenceRead, + ])( + "refuses a decision when %s is revoked during metadata-only confirmation", + async (permission) => { + const f = await queryFixture(await createStore()); + const packet = await f.packet(); + const command = await f.decision(packet.ack); + const before = await f.rows(); + f.queryHooks.beforeConfirm = async () => { + f.principals.set( + f.reviewer.principalId, + access( + f.reviewer.principalId, + f.reviewer.permissions.filter((value) => value !== permission), + ), + ); + }; + await expect( + f.reports.decide(f.reviewer, command, "confirmed"), + ).rejects.toMatchObject({ code: "forbidden" }); + expect(await f.rows()).toEqual(before); + }, + ); + + it("withholds a committed decision ACK on revocation and recovers its exact historical result without new reads or rows", async () => { + const f = await queryFixture(await createStore()); + const packet = await f.packet(); + const command = await f.decision(packet.ack); + f.observed.intercept(async (trace, commit) => { + const result = await commit(); + if (trace.collection === f.namespace && result.committed) { + f.observed.intercept(undefined); + f.principals.delete(f.reviewer.principalId); + } + return result; + }); + await expect( + f.reports.decide(f.reviewer, command, "confirmed"), + ).rejects.toMatchObject({ code: "forbidden" }); + const stored = await f.rows(); + expect( + stored.some( + (row) => + row.id.startsWith("report:") && + JSON.parse(row.payload).status === "confirmed", + ), + ).toBe(true); + f.principals.set(f.reviewer.principalId, structuredClone(f.reviewer)); + const before = f.authoringContext.getAuthoringContext.mock.calls.length; + await expect( + f.reports.decide(f.reviewer, command, "confirmed"), + ).resolves.toEqual({ ...packet.ack, reportGeneration: 2 }); + expect(await f.rows()).toEqual(stored); + expect(f.authoringContext.getAuthoringContext).toHaveBeenCalledTimes( + before, + ); + }); + }); +}