diff --git a/AGENTS.md b/AGENTS.md index 80a008c..defeccf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,9 +27,12 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. 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. + All four `0.1.4` packages completed verified trusted publication for governed + authoring contexts, report queries and bounded resumable repair; retain the + [public release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). + Synchronized `0.1.5` is the unpublished answering read-batching candidate and + requires its own review, current-head gates, trusted publication and strict + verification. Grouped reads establish no universal query or CPU budget. 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 @@ -140,7 +143,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.4` candidate's own review, trusted publication, and strict registry +`0.1.5` 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 6b85d31..5a032b0 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-09: KB-01 through KB-03 provide contracts, pure domain +> Development status as of 2026-11-10: 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. @@ -21,9 +21,12 @@ and exact publication approval. It requires no GitHub connection or AI provider. > 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. +> All four `0.1.4` packages completed +> [verified trusted publication](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4) +> for governed authoring-context reads, report queries and bounded resumable repair. +> Synchronized `0.1.5` is the **unpublished patch candidate** for answering read +> batching; its own 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. @@ -47,7 +50,7 @@ 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 +The `0.1.4` release provides `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 @@ -159,11 +162,14 @@ 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.3` release are complete; -their exact receipts remain in the ledger. All four KB packages have -`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. +`0.1.1` release and the four-package KB trusted +[`0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4) +are complete; prior exact receipts remain historical evidence. All four KB +packages currently have `latest: 0.1.4`; Agent Access has `latest: 0.1.1`; all +retain historical `bootstrap: 0.1.0`. Synchronized source `0.1.5` remains +unpublished and needs its own review, current-head CI, trusted release and strict +consumer verification. Read batching establishes no universal backend query or +CPU budget. Neither registry publication nor synthetic proof satisfies real +host acceptance or approves activation. Built in the open by RetireGolden, LLC. diff --git a/docs/AGENT_API.md b/docs/AGENT_API.md index 646de96..807ae9c 100644 --- a/docs/AGENT_API.md +++ b/docs/AGENT_API.md @@ -5,11 +5,13 @@ 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. 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. +have since completed verified trusted publication. Optional human-reviewed +report mode shipped in [`0.1.3`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3). +All four KB packages are now verified published at +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4), including +the governed authoring-context pair and optional aggregate report query. The +synchronized `0.1.5` internal read-batching candidate remains unpublished; 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 @@ -110,7 +112,7 @@ 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`, +The verified `0.1.4` release 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, @@ -223,7 +225,7 @@ The [public types](../packages/mcp/src/types.ts) and 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. +neither the release nor the `0.1.5` candidate makes a universal Free-tier acceptance claim. ## HTTP composition diff --git a/docs/AGENT_WORKFLOW.md b/docs/AGENT_WORKFLOW.md index 86d820f..5995ab2 100644 --- a/docs/AGENT_WORKFLOW.md +++ b/docs/AGENT_WORKFLOW.md @@ -5,11 +5,13 @@ 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. 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 +since completed verified trusted publication. Optional human-report mode shipped +in [`0.1.3`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3). All four +packages are now verified published at +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4), including +governed context reads and an optional aggregate report query. The synchronized +`0.1.5` internal read-batching candidate remains unpublished, with its own review, +gates, publication and strict verification 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). @@ -110,7 +112,7 @@ 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 +The verified `0.1.4` release 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 @@ -212,8 +214,9 @@ 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.4` context/query candidate retains its own gates, PR, and verified -trusted release pending. Both verified trusted dependencies precede production host +KB `0.1.4` has since completed verified trusted publication. The `0.1.5` internal +read-batching candidate retains its own gates, PR, and verified trusted release +pending. Both verified trusted dependencies precede production host assembly. Branches, copied source, local paths, and unpublished production tarballs cannot substitute for them. diff --git a/docs/BOOTSTRAP.md b/docs/BOOTSTRAP.md index f0cf37a..6546592 100644 --- a/docs/BOOTSTRAP.md +++ b/docs/BOOTSTRAP.md @@ -6,12 +6,14 @@ 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.3`; Agent Access remains verified -at `0.1.1`. Their receipts close public producer release prerequisites only. -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. +KB's current verified trusted release is +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4); Agent Access +remains verified at `0.1.1`. Their receipts close public producer release +prerequisites only. The dated trusted KB `0.1.1`, `0.1.2` and `0.1.3` receipts +remain below as history. Synchronized KB `0.1.5` is the unpublished internal +answering read-batching candidate; its own review, current-head CI, trusted +publication and strict consumer verification remain pending. Host acceptance +remains separate. The five KB/Agent Access trusted-publisher entries have been configured through the CLI. An actual trusted release still requires the reviewed source and @@ -84,7 +86,19 @@ the approved dependency set or establishes real-host acceptance. ## Verified Knowledge Base release -### Current verified `0.1.3` release +### Current verified `0.1.4` release + +All four synchronized KB packages completed qualified trusted publication at +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). This release +provides governed operation-local authoring contexts, optional body-free report +queries, prepared read waves and bounded resumable repair. Its public release +retains the original artifact and verification summary, including qualification +limits. Publication does not establish durable-host or actual-client acceptance. +The earlier receipt below remains as history under its preserved anchor. + + + +### Historical 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 @@ -134,11 +148,12 @@ 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. +This release provides optional human-reviewed evidence reports. The later +verified `0.1.4` release adds governed authoring contexts and optional report +queries. Synchronized `0.1.5` is an unpublished internal read-batching candidate +with its own review, current-head gates, trusted publication and strict +verification still required. Producer releases do not close Workers Free +call/CPU acceptance, host activation or pilot gates. @@ -211,8 +226,8 @@ 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` 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. +host/client, privacy, activation or pilot acceptance or verifies later changed +source. The verified `0.1.4` release has its separate public release record above. ## Verified Agent Access prerequisite @@ -257,8 +272,9 @@ verification; no package version or artifact was replaced. This closes the verified public Agent Access `0.1.1` prerequisite. The KB protocol proof now composes that exact registry producer with four packed KB candidate artifacts in a fresh consumer. KB `0.1.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 +receipt above; the later `0.1.4` release is also verified. Source `0.1.5` retains +its own current-head gates, PR, trusted release, and strict verification. +Existing-login, current-Admin consent, every requested client/mode, and both real hosts remain separately unproven. ## Historical initial preparation procedure (`0.1.0`) @@ -336,10 +352,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.4` with exact internal dependency +The synchronized KB source candidate is `0.1.5` 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.3`, recorded separately above. +historical first advertised trusted release is `0.1.1`; the `0.1.3` receipt +remains above, followed by the current verified `0.1.4` release record. 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 @@ -354,7 +370,8 @@ 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.3` and Agent -Access `0.1.1` public producer release prerequisites are closed. This candidate +[source preparation](SOURCE_PREPARATION.md). The verified KB `0.1.3` receipt +remains historical; KB `0.1.4` 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 f64a3b8..9165d18 100644 --- a/docs/COLLECTIONS.md +++ b/docs/COLLECTIONS.md @@ -12,9 +12,10 @@ 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.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 +[verified `0.1.3` release](BOOTSTRAP.md#current-verified-013-release) is complete, +as is the later [`0.1.4` trusted release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). +The synchronized `0.1.5` internal read-batching candidate is unpublished; its own +release, real-host acceptance, and production readiness retain their gates. The earlier `0.1.1` release has a separate [historical receipt](BOOTSTRAP.md#historical-verified-011-release), as does [`0.1.2`](BOOTSTRAP.md#historical-verified-012-release). diff --git a/docs/EVIDENCE_REPORTS.md b/docs/EVIDENCE_REPORTS.md index 562c270..d72c017 100644 --- a/docs/EVIDENCE_REPORTS.md +++ b/docs/EVIDENCE_REPORTS.md @@ -2,10 +2,11 @@ `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; +The optional governed context pair and body-free `query` described below shipped +in the qualified [`0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). +Synchronized `0.1.5` is an **unpublished internal read-batching candidate** with +its own review, current-head CI, trusted publication and strict consumer +verification 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. @@ -21,23 +22,23 @@ 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. | -| `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. | +| 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` release) | 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. The candidate optional pair uses the +only when authorized, `getEvidence` reads. The 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. @@ -63,9 +64,9 @@ 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) +## Optional governed context and query (`0.1.4` release) -The candidate application's +The 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 @@ -113,7 +114,7 @@ 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 +The 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 @@ -152,15 +153,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`. | -| `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. | +| Method | Purpose and authority | +| ------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `ledger` | Body-free current epoch/capacity state; requires current `evidenceSubmit`. | +| `query` (`0.1.4` release) | 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 3b2efb1..c4b82a5 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -16,9 +16,13 @@ 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. +The governed authoring-context/report-query features shipped in the qualified +[`0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). +Synchronized `0.1.5` is an unpublished internal answering read-batching candidate; +its own review, current-head gates, trusted release and strict registry/provenance +verification remain open. Internal read-wave changes preserve the public ports +and do not establish a universal Workers Free call/CPU allowance or live-host +acceptance. Supported invocation profiles require their own measurements. Host acceptance remains separate. No package becomes an identity system or an operational hosted endpoint. See [declared collections](COLLECTIONS.md) for the required @@ -27,9 +31,9 @@ layout, CAS, admission, and replay design. The earlier merged [partial KB-05 source](https://github.com/pegma-dev/knowledge-base/pull/4), documented in [source preparation](SOURCE_PREPARATION.md), adds shared memory/Azurite/local-D1 conformance and a -[public synthetic composition](../examples/composition/README.md). The D1 +[public synthetic composition](../examples/composition/README.md). The current D1 fixture passes a real Miniflare binding directly to the released -`@pegma/storage-cloudflare-d1@0.4.1` adapter with isolated per-factory cleanup. +`@pegma/storage-cloudflare-d1@0.4.6` adapter with isolated per-factory cleanup. It is local consumer evidence, not a deployed Workers binding or production acceptance. The example's resolved contexts and receipt registry stand in for trusted host facts; they authenticate no real browser, agent, or staging run. @@ -121,19 +125,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` | -| 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 | +| 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` release) | `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 @@ -176,7 +180,7 @@ 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) +### Governed authoring context (`0.1.4` release) `getAuthoringContext(access, { articleId, includeEvidence?: boolean })` returns `{ context, observation }`. The context combines current `draft` and narrow @@ -204,7 +208,7 @@ 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, +The released `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 diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 9e54a3e..bce079d 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -24,19 +24,28 @@ at **2026-11-08T03:39:55Z**; the [historical receipt](BOOTSTRAP.md#historical-verified-012-release) retains its source/tag and original prepared artifact bindings. -The current verified release is [`0.1.3`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3) +The historical 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) distinguishes the released `0.1.3` factory -from the `0.1.4` candidate additions. No `v0.1.4` publication is claimed here. +The current verified release is +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). All four +packages were qualified against their signed-source preparation, with registry +signatures, source provenance and public-consumer verification. The public +release retains the original preparation archive and verification summary, +including the original writer attempts and final recovery. It ships governed +authoring-context reads, report queries and bounded resumable repair. + +Source `0.1.5` is the synchronized **unpublished** patch candidate for answering +read batching. Its own review, current-head CI, signed tag, trusted publication +and strict consumer verification remain pending. Existing links to `v0.1.2` +and the released `0.1.3` report factory remain historical contracts; do not +relabel their source or artifact receipts as the new candidate. Grouped reads +establish no universal backend query or CPU budget, and host acceptance remains +separate. [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) @@ -49,7 +58,7 @@ Changed source still needs all current-head gates before release preparation. No source merge configures publishers, creates a tag/release, or publishes npm packages. The [maintainer bootstrap ledger](BOOTSTRAP.md) retains the actual manual commands/stdout, exact identities, preparation runs/artifacts, and -independently retained digests. The qualified release versions are KB `0.1.3` +independently retained digests. The qualified release versions are KB `0.1.4` 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. @@ -62,7 +71,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.4` candidate still needs its own current-head gates, review, PR, publication, +The KB `0.1.5` 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 33d02c2..dafa26e 100644 --- a/docs/RETRIEVAL.md +++ b/docs/RETRIEVAL.md @@ -10,16 +10,15 @@ 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 [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 +and [verified `0.1.3` release](BOOTSTRAP.md#current-verified-013-release). The later +qualified [`0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4) +includes governed authoring contexts, optional report queries and the bounded +repair mode described below. Synchronized `0.1.5` is an unpublished internal +answering read-batching candidate. Source tests and repository gates, not this +document, determine changed-source 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. +their own gates. 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, diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md index 11810f7..b828495 100644 --- a/docs/SOURCE_PREPARATION.md +++ b/docs/SOURCE_PREPARATION.md @@ -54,16 +54,18 @@ at **2026-11-07T23:35:31Z**; see its separate 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`/`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 | +[verified](BOOTSTRAP.md#current-verified-013-release). The governed context/query +features subsequently shipped in the qualified +[`0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). +Synchronized `0.1.5` is the unpublished internal read-batching candidate with its +own review, current-head gates, trusted publication and strict verification 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`/`0.1.3` receipts remain separate; `0.1.4` is qualified and `0.1.5` still needs its own verified release | +| Task readiness | Current-head repository gates establish source readiness | Verified trusted releases and two-host/client acceptance remain separately recorded | The merged-source results above do not certify this working tree. Record verified current-head gate results before treating changed source as validated. @@ -300,12 +302,12 @@ trusted-publisher entries have been configured through the CLI. Recheck the full ownership, protected tag/main, approved signer, approval environment, per-package publisher binding, direct-publishing, and 2FA/token-policy checklist in [release operations](RELEASING.md) for the actual trusted release. -The current KB `0.1.3` trusted release has completed complete-set registry +The KB `0.1.3` trusted release completed complete-set registry integrity/signature/provenance verification and released-consumer proof; its [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. +historical source records. The later `0.1.4` release is also qualified. The +unpublished `0.1.5` internal read-batching candidate retains its own review, +current-head gates, trusted publication, strict verification and released-consumer proof. Manual bootstrap is not OIDC provenance. Agent Access has its own publication history: [Agent Access release preparation](https://github.com/pegma-dev/agent-access/pull/2) @@ -326,9 +328,9 @@ closed the public producer prerequisite; see the [exact receipt](BOOTSTRAP.md#verified-agent-access-prerequisite). The original source-producer proof remains historical evidence, while the changed registry composition requires its own current-head gates. -The verified KB `0.1.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 +The verified KB `0.1.3` receipt remains historical; KB `0.1.4` and Agent Access +`0.1.1` producer release prerequisites are closed. The new `0.1.5` internal +read-batching candidate needs its own verified release before host adoption. Both hosts still require exact verified trusted dependencies and their retained acceptance before activation. Hosts must wait for exact released artifacts rather than adopting branches, copied source, local paths, or unpublished production tarballs. diff --git a/examples/agent/README.md b/examples/agent/README.md index 81484b8..e5d3a6a 100644 --- a/examples/agent/README.md +++ b/examples/agent/README.md @@ -20,10 +20,14 @@ 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. +The four packed KB artifacts in this working tree are unpublished `0.1.5` +answering read-batching candidates. The separate +[qualified `0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4) +shipped the governed context/query features; its verification does not validate +changed `0.1.5` source. The candidate requires its own review, current-head gates, +trusted publication and strict consumer verification. The +[verified `0.1.3` receipt](../../docs/BOOTSTRAP.md#current-verified-013-release) +remains historical. ## Artifact boundary diff --git a/examples/composition/README.md b/examples/composition/README.md index aadf5c6..b7975f9 100644 --- a/examples/composition/README.md +++ b/examples/composition/README.md @@ -25,10 +25,13 @@ four-package `0.1.1` trusted release has a [historical receipt](../../docs/BOOTSTRAP.md#historical-verified-011-release). 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. +The four-package `0.1.3` release has a +[historical verified receipt](../../docs/BOOTSTRAP.md#current-verified-013-release). +All four packages subsequently completed qualified trusted publication at +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4) for the +governed context/query features. Source `0.1.5` is the unpublished internal +answering read-batching candidate requiring its own reviewed, verified trusted +release. Production hosts retain their separate acceptance gates. The flow creates a fictional workshop collection with portal use disabled and a diff --git a/package.json b/package.json index e83e1d2..444b8a0 100644 --- a/package.json +++ b/package.json @@ -34,14 +34,14 @@ "@cloudflare/workers-types": "5.20260730.1", "@modelcontextprotocol/sdk": "1.32.2", "@pegma/authorization-core": "0.4.0", - "@pegma/knowledge-base-application": "0.1.4", + "@pegma/knowledge-base-application": "0.1.5", "@pegma/knowledge-base-application-previous": "npm:@pegma/knowledge-base-application@0.1.1", - "@pegma/knowledge-base-contracts": "0.1.4", - "@pegma/knowledge-base-core": "0.1.4", - "@pegma/knowledge-base-mcp": "0.1.4", + "@pegma/knowledge-base-contracts": "0.1.5", + "@pegma/knowledge-base-core": "0.1.5", + "@pegma/knowledge-base-mcp": "0.1.5", "@pegma/spine": "0.1.2", "@pegma/storage-azure-tables": "0.4.0", - "@pegma/storage-cloudflare-d1": "0.4.1", + "@pegma/storage-cloudflare-d1": "0.4.6", "@pegma/storage-core": "0.4.0", "@types/node": "26.6.6", "azurite": "3.37.0", diff --git a/packages/application/README.md b/packages/application/README.md index 902cecc..7f20e90 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -17,9 +17,13 @@ production activation remain separately gated. 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. +Governed authoring contexts, report queries and bounded resumable repair shipped +in the verified +[`v0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). +Source here prepares the synchronized **unpublished `0.1.5` candidate** for +answering read batching. Its own review, current-head gates, trusted publication +and strict registry verification remain required. Backend query and CPU budgets +require actual host measurements. 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; @@ -172,13 +176,13 @@ 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, +The application exports `createKnowledgeEvidenceReports` and its public option, 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) +`0.1.3`; governed authoring-context and report-query support shipped in verified +`0.1.4`. The new `0.1.5` performance candidate requires its own review, +current-head CI, trusted publication and strict consumer verification. Host +acceptance remains separate. The +[versioned evidence-report guide](https://github.com/pegma-dev/knowledge-base/blob/v0.1.4/docs/EVIDENCE_REPORTS.md) describes explicit Store namespace/current-authority ports, human confirmation before actual KB qualification, bounded epochs/retention, and the separate report-ledger-to-article commit window. @@ -223,7 +227,7 @@ 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 +The verified `0.1.4` release 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 @@ -248,8 +252,8 @@ 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. +Workers Free quota acceptance. The `0.1.5` candidate's own gates, trusted +release and whole-host measurements remain separate. ## Storage and limits diff --git a/packages/application/package.json b/packages/application/package.json index df77539..fbd4bb5 100644 --- a/packages/application/package.json +++ b/packages/application/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-application", - "version": "0.1.4", + "version": "0.1.5", "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.4", - "@pegma/knowledge-base-core": "0.1.4", + "@pegma/knowledge-base-contracts": "0.1.5", + "@pegma/knowledge-base-core": "0.1.5", "@pegma/spine": "0.1.2", "@pegma/storage-core": "0.4.0" }, diff --git a/packages/application/src/governance.ts b/packages/application/src/governance.ts index 1e9cca2..a527935 100644 --- a/packages/application/src/governance.ts +++ b/packages/application/src/governance.ts @@ -20,7 +20,12 @@ import { KnowledgeBasePrerequisiteError, requirePermission, } from "./errors.js"; -import type { KnowledgeRepository, RepositoryCommand } from "./repository.js"; +import type { + KnowledgeRepository, + RepositoryCommand, + VersionedState, +} from "./repository.js"; +import type { StoredCollection, StoredValidationPolicy } from "./records.js"; import { canonicalJson, commandFingerprint, @@ -188,23 +193,26 @@ export interface GovernanceObservation extends CurrentGovernanceContext { readonly configuration: GovernanceConfiguration; } -/** Initial authoritative facts; the caller must subsequently fence the heads. */ -export async function readGovernanceObservation( - repository: KnowledgeRepository, - collectionId: string, - at: IsoTimestamp, -): Promise { - requireIdentifier(collectionId, "collectionId"); - const collection = await repository.readCollectionVersioned(collectionId); +/** Validate the captured C before preparing any dependent resource read. */ +export function governanceConfigurationFrom( + collection: VersionedState | null, +): GovernanceConfiguration { if (collection === null) throw new KnowledgeBaseNotFoundError("collection"); const configuration = collection.value.configuration; if (configuration === undefined) { throw new KnowledgeBasePrerequisiteError("collection_configuration"); } validateConfiguration(configuration); - const validation = await repository.readValidationPolicyVersioned( - configuration.validationPolicy.id, - ); + return configuration; +} + +/** The same validation for ordinary and internally prepared observations. */ +export function governanceObservationFrom( + collection: VersionedState, + validation: VersionedState | null, + at: IsoTimestamp, +): GovernanceObservation { + const configuration = governanceConfigurationFrom(collection); if ( validation === null || validation.value.policy.id !== configuration.validationPolicy.id || @@ -229,6 +237,23 @@ export async function readGovernanceObservation( }); } +/** Initial authoritative facts; the caller must subsequently fence the heads. */ +export async function readGovernanceObservation( + repository: KnowledgeRepository, + collectionId: string, + at: IsoTimestamp, +): Promise { + requireIdentifier(collectionId, "collectionId"); + const collection = await repository.readCollectionVersioned(collectionId); + if (collection === null) throw new KnowledgeBaseNotFoundError("collection"); + const configuration = governanceConfigurationFrom(collection); + // Preserve configuration refusal before dispatching the dependent V read. + const validation = await repository.readValidationPolicyVersioned( + configuration.validationPolicy.id, + ); + return governanceObservationFrom(collection, validation, at); +} + /** Recheck current authority heads after all verifier/fact awaits. */ export async function confirmGovernanceObservation( repository: KnowledgeRepository, diff --git a/packages/application/src/publication.ts b/packages/application/src/publication.ts index 0f97337..4fa69aa 100644 --- a/packages/application/src/publication.ts +++ b/packages/application/src/publication.ts @@ -20,11 +20,18 @@ import { KnowledgeBaseNotFoundError, KnowledgeBasePrerequisiteError, } from "./errors.js"; -import { readGovernanceObservation } from "./governance.js"; +import { + governanceConfigurationFrom, + governanceObservationFrom, + readGovernanceObservation, +} from "./governance.js"; +import type { StoredCollection } from "./records.js"; import type { ArticlePublicationState, + GovernedPublicationRead, KnowledgeRepository, ResourceVersion, + VersionedState, } from "./repository.js"; import { canonicalJson, @@ -76,6 +83,12 @@ export interface CheckedPublication { readonly enabledUses: readonly ("portal" | "bot")[]; } +/** A single confirmation's already authorized collection, never a credential. */ +interface AuthorizedPublicationRead { + readonly collection: VersionedState; + readonly expectedGeneration: number; +} + interface ConfirmationState { readonly access: AccessContext; readonly purpose: PublicationPurpose; @@ -169,6 +182,7 @@ export function createPublicationChecker( ): { readonly check: ( request: PublicationCheckRequest, + observed?: AuthorizedPublicationRead, ) => Promise; readonly recheck: (checked: CheckedPublication) => Promise; } { @@ -213,7 +227,7 @@ export function createPublicationChecker( } return { - async check(request) { + async check(request, observed) { const access = immutable(snapshotData(request.access)); const articleId = request.articleId; requireIdentifier(articleId, "articleId"); @@ -226,8 +240,21 @@ export function createPublicationChecker( : snapshotData(request.applicability); authorize(access, purpose); try { + let prepared: GovernedPublicationRead | undefined; + if (observed !== undefined) { + // Preserve configuration validation before any dependent A/V read. + governanceConfigurationFrom(observed.collection); + const read = await repository.readGovernedPublicationVersioned( + articleId, + observed.collection, + observed.expectedGeneration, + ); + if (read === null) throw unavailable(); + prepared = read; + } const loaded = - await repository.readArticlePublicationVersioned(articleId); + prepared?.article ?? + (await repository.readArticlePublicationVersioned(articleId)); const current = loaded?.value; const publication = current?.published; const review = current?.publicationReview; @@ -248,11 +275,18 @@ export function createPublicationChecker( ) throw unavailable(); const at = clockTime(options); - const governance = await readGovernanceObservation( - repository, - revision.collectionId, - at, - ); + const governance = + observed === undefined || prepared === undefined + ? await readGovernanceObservation( + repository, + revision.collectionId, + at, + ) + : governanceObservationFrom( + observed.collection, + prepared.validation, + at, + ); const policy = governance.context.collection.policy; const enabledUses: ("portal" | "bot")[] = []; if (policy.portal.enabled) enabledUses.push("portal"); diff --git a/packages/application/src/repository.ts b/packages/application/src/repository.ts index 6a6e358..6ca5cfd 100644 --- a/packages/application/src/repository.ts +++ b/packages/application/src/repository.ts @@ -105,6 +105,11 @@ export interface ArticlePublicationState { readonly publishedProvenance?: SourceSnapshot; readonly publicationReview?: ReviewSnapshot; } +/** One operation's exact authorized C, current A/V heads and published rows. */ +export interface GovernedPublicationRead { + readonly article: VersionedState; + readonly validation: VersionedState; +} /** Current authoring material only; excludes publication and provenance rows. */ export interface ArticleAuthoringState { readonly articleId: string; @@ -130,6 +135,11 @@ export interface KnowledgeRepository { readArticlePublicationVersioned( id: string, ): Promise | null>; + readGovernedPublicationVersioned( + id: string, + collection: VersionedState, + expectedGeneration: number, + ): Promise; /** Complete approved proof rows and revocation markers in one prepared wave. */ readPublicationEvidence( id: string, @@ -408,6 +418,7 @@ export function createKnowledgeRepository( kind: ResourceKind, id: string, keys: readonly string[], + preparedScope?: string, ): Promise> { const unique = [...new Set(keys)]; for (const key of unique) { @@ -419,7 +430,7 @@ export function createKnowledgeRepository( ) throw new RepositoryIntegrityError(); } - const scope = await partition(kind, id); + const scope = preparedScope ?? (await partition(kind, id)); const rows = await Promise.all( unique.map((key) => records.get({ partition: scope, id: key })), ); @@ -852,27 +863,29 @@ export function createKnowledgeRepository( version: row.version, }; } - async function readPublication( + function publicationKeys(pointer: ArticlePointer): readonly string[] { + if (pointer.published === undefined) return []; + return [ + "revision:" + pointer.published.revision, + pointer.published.approval, + "provenance:" + pointer.publishedProvenance, + pointer.publicationReview!, + ]; + } + function publicationFromRows( id: string, - ): Promise | null> { - const row = await getHead("article", id); - if (row === null) return null; - const pointer = (row.value.data as Head).pointer as ArticlePointer; + pointer: ArticlePointer, + rows: ReadonlyMap, + ): ArticlePublicationState { const value: ArticlePublicationState = { articleId: id, generation: pointer.generation, state: pointer.state, publicationHeld: pointer.publicationHeld, }; - if (pointer.published === undefined) return { value, version: row.version }; + if (pointer.published === undefined) return value; 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, @@ -899,15 +912,101 @@ export function createKnowledgeRepository( throw new RepositoryIntegrityError(); } return { - value: { - ...value, - published: { revision, approval }, - publishedProvenance, - publicationReview, - }, + ...value, + published: { revision, approval }, + publishedProvenance, + publicationReview, + }; + } + async function readPublication( + id: string, + ): Promise | null> { + const row = await getHead("article", id); + if (row === null) return null; + const pointer = (row.value.data as Head).pointer as ArticlePointer; + const rows = + pointer.published === undefined + ? new Map() + : await preparedRows("article", id, publicationKeys(pointer)); + return { + value: publicationFromRows(id, pointer, rows), version: row.version, }; } + async function readGovernedPublication( + id: string, + collection: VersionedState, + expectedGeneration: number, + ): Promise { + requireGeneration(expectedGeneration, 1); + const configured = collection.value.configuration?.validationPolicy; + if (configured === undefined) throw new RepositoryIntegrityError(); + requireIdentifier(configured.id); + requireGeneration(configured.version, 1); + // The caller has already authorized this exact C. Finish both hashes + // before dispatching any A/V head read; no A probe precedes C authority. + const [articleScope, validationScope] = await Promise.all([ + partition("article", id), + partition("validation", configured.id), + ]); + const [articleHead, validationHead] = await Promise.all([ + records + .getVersioned({ partition: articleScope, id: "head" }) + .then((row) => checkedHead("article", id, articleScope, row)), + records + .getVersioned({ partition: validationScope, id: "head" }) + .then((row) => + checkedHead("validation", configured.id, validationScope, row), + ), + ]); + if (articleHead === null || validationHead === null) return null; + const articlePointer = (articleHead.value.data as Head).pointer; + const validationPointer = (validationHead.value.data as Head).pointer; + if ( + articlePointer.resourceKind !== "article" || + validationPointer.resourceKind !== "validation" + ) + throw new RepositoryIntegrityError(); + if ( + articlePointer.generation !== expectedGeneration || + articlePointer.state === "retired" || + articlePointer.publicationHeld || + articlePointer.published === undefined + ) + return null; + const policyKey = "policy:" + validationPointer.version; + // Scopes and every immutable key are ready. Both groups synchronously + // enqueue their public Store reads before the first group is awaited. + const [articleRows, validationRows] = await Promise.all([ + preparedRows( + "article", + id, + publicationKeys(articlePointer), + articleScope, + ), + preparedRows("validation", configured.id, [policyKey], validationScope), + ]); + const article = publicationFromRows(id, articlePointer, articleRows); + const policy = planned( + validationRows, + policyKey, + "policy", + ); + if ( + article.published?.revision.collectionId !== + collection.value.collection.id || + policy.id !== configured.id || + policy.version !== validationPointer.version + ) + throw new RepositoryIntegrityError(); + return { + article: { value: article, version: articleHead.version }, + validation: { + value: { generation: validationPointer.generation, policy }, + version: validationHead.version, + }, + }; + } async function readPublicationEvidence( id: string, publication: PublishedArticle, @@ -1447,6 +1546,7 @@ export function createKnowledgeRepository( limits, readArticleVersioned: (id) => read("article", id), readArticlePublicationVersioned: readPublication, + readGovernedPublicationVersioned: readGovernedPublication, readPublicationEvidence, readArticleAuthoringVersioned: readAuthoring, confirmResourceVersions, diff --git a/packages/application/src/retrieval-repository.ts b/packages/application/src/retrieval-repository.ts index 78c0ffe..caab8ba 100644 --- a/packages/application/src/retrieval-repository.ts +++ b/packages/application/src/retrieval-repository.ts @@ -68,8 +68,13 @@ export interface RetrievalRepository { /** Every returned page/entry must be charged before query filtering/deduplication. */ readPostingPages( scope: RetrievalScope, - term: string, - ): Promise; + terms: readonly string[], + ): Promise< + readonly { + readonly term: string; + readonly pages: readonly RetrievalPostingPage[]; + }[] + >; readArticleProjection( articleId: string, ): Promise; @@ -926,17 +931,32 @@ export function createRetrievalRepository( scopes: scopesUnion(active.flatMap((entry) => entry.scopes)), }; }, - async readPostingPages(scope, term) { + async readPostingPages(scope, terms) { requireRetrievalScope(scope); - const termHash = await retrievalTermHash(term); - 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), - ), - })); + if (!Array.isArray(terms) || terms.length > limits.maxQueryTerms) + throw new TypeError("Expected bounded normalized lexical terms"); + const selected = [...terms]; + // Reject duplicate normalized terms rather than silently deduplicating. + unique(selected); + // No Store read starts until the complete scope and term-key set is ready. + // loadPostings validates all heads before issuing its complete page wave. + const [partition, hashes] = await Promise.all([ + scopePartition(scope), + Promise.all(selected.map(retrievalTermHash)), + ]); + const loaded = await loadPostings(partition, scope, hashes); + return selected.map((term, index) => { + const posting = loaded.get(hashes[index]!); + if (posting === undefined) throw new RepositoryIntegrityError(); + return { + term, + pages: posting.pages.map((page) => ({ + entries: (page.value.data as PostingPage).entries.map((entry) => + snapshotData(entry.hint), + ), + })), + }; + }); }, async readArticleProjection(articleId) { return (await readState(articleId))?.state ?? null; diff --git a/packages/application/src/retrieval.ts b/packages/application/src/retrieval.ts index 86e23ff..feb09a1 100644 --- a/packages/application/src/retrieval.ts +++ b/packages/application/src/retrieval.ts @@ -12,7 +12,11 @@ import { createPublicationChecker, type CheckedPublication, } from "./publication.js"; -import { createKnowledgeRepository } from "./repository.js"; +import { + createKnowledgeRepository, + type VersionedState, +} from "./repository.js"; +import type { StoredCollection } from "./records.js"; import { createRetrievalReadBudget, RetrievalBudgetError, @@ -57,6 +61,8 @@ interface AuthorizedScope { readonly scope: RetrievalScope; readonly governanceGeneration: number; readonly label: string; + /** Exact request-local C observation for prepared citation confirmation. */ + readonly collection: VersionedState; } interface Candidate { @@ -277,6 +283,7 @@ export function createRetrievalServices(input: { }, governanceGeneration: loaded.value.generation, label: collection.name, + collection: loaded, }; } @@ -311,12 +318,33 @@ export function createRetrievalServices(input: { for (const authorized of scopes) { const scope = authorized.scope; if (candidateAdapter === undefined) { - for (const term of terms) { - const pages = await index.readPostingPages(scope, term); - for (const page of pages) { - budget.indexEntries(page.entries.length); - for (const hint of page.entries) add(hint, scope, term); + const maxEntriesPerTerm = + limits.postingPageEntries * limits.maxPostingPagesPerTerm; + for (let offset = 0; offset < terms.length;) { + const remainingEntries = + budget.remainingCandidateWork().postingEntries; + // Only group an ordered prefix whose worst-case entries fit. One + // term still has to reveal its actual pages, as in the prior path. + const termCount = Math.min( + terms.length - offset, + Math.max(1, Math.floor(remainingEntries / maxEntriesPerTerm)), + ); + const postings = await index.readPostingPages( + scope, + terms.slice(offset, offset + termCount), + ); + let entries = 0; + for (const { pages } of postings) + for (const page of pages) entries += page.entries.length; + // Charge every fetched entry, including duplicates across terms, + // before filtering, deduplicating or starting another read wave. + budget.indexEntries(entries); + for (const { term, pages } of postings) { + for (const page of pages) { + for (const hint of page.entries) add(hint, scope, term); + } } + offset += termCount; } continue; } @@ -682,32 +710,37 @@ export function createRetrievalServices(input: { return noSources(); try { const scope = requestScope(); + const collections = new Map(); for (const collectionId of new Set( query.references.map((reference) => reference.collectionId), )) { - if ( - (await scope.authorizeCollection(caller, collectionId, "bot")) === - null - ) - return noSources(); + const authorized = await scope.authorizeCollection( + caller, + collectionId, + "bot", + ); + if (authorized === null) return noSources(); + collections.set(collectionId, authorized); } const checked: CheckedPublication[] = []; for (const reference of query.references) { scope.budget.candidateHead(); - if ( - (await scope.repository.readResourceGeneration( - "article", - reference.articleId, - )) !== reference.applicationGeneration - ) - return noSources(); + const authorized = collections.get(reference.collectionId); + // Every reference was authorized above; retain a fail-closed map guard. + if (authorized === undefined) return noSources(); scope.budget.confirmation(); - const confirmed = await scope.checker.check({ - articleId: reference.articleId, - purpose: "bot", - access: caller, - applicability, - }); + const confirmed = await scope.checker.check( + { + articleId: reference.articleId, + purpose: "bot", + access: caller, + applicability, + }, + { + collection: authorized.collection, + expectedGeneration: reference.applicationGeneration, + }, + ); if ( canonicalJson(referenceOf(confirmed)) !== canonicalJson(reference) ) diff --git a/packages/contracts/README.md b/packages/contracts/README.md index 0308fc0..7edbd38 100644 --- a/packages/contracts/README.md +++ b/packages/contracts/README.md @@ -6,6 +6,12 @@ permission names; the application enforces current permission/resource checks using host-resolved Authorization Core contexts. Identity and time types come from `@pegma/spine`. +The current verified synchronized release is +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). Source +here prepares the unpublished `0.1.5` patch candidate alongside the application +answering read-batching work. Its own review, current-head gates, trusted +publication and strict registry verification remain required. + Collections independently enable portal and bot use for an explicit audience. Every article inherits its collection policy; there are no article-level access overrides. An enabled permission audience names a permission the host resolves. diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 66b3583..e802c2f 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-contracts", - "version": "0.1.4", + "version": "0.1.5", "description": "Provider-neutral knowledge collections, revisions, validation, and approval contracts.", "license": "MIT", "type": "module", diff --git a/packages/core/README.md b/packages/core/README.md index 28c350e..2ff3286 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -4,6 +4,12 @@ Pure collection, draft, verification, review, publication, and retirement transitions. It requires no Support Desk, GitHub, model, framework, database, or provider SDK. +The current verified synchronized release is +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). Source +here prepares the unpublished `0.1.5` patch candidate alongside the application +answering read-batching work. Its own review, current-head gates, trusted +publication and strict registry verification remain required. + Core owns domain invariants. The application service checks current named permissions, loads authoritative records, uses host-verified evidence facts, and commits state with Audit through Storage Core. The host authenticates diff --git a/packages/core/package.json b/packages/core/package.json index b673bf8..e45f6c4 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-core", - "version": "0.1.4", + "version": "0.1.5", "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.4" + "@pegma/knowledge-base-contracts": "0.1.5" }, "scripts": { "build": "tsc -p tsconfig.json", diff --git a/packages/mcp/README.md b/packages/mcp/README.md index b3558dc..5cf319f 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -6,10 +6,11 @@ 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. +[`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4), including +the optional aggregate query over the existing report workflow. Source here +prepares the synchronized **unpublished `0.1.5` patch candidate** for answering +read batching; 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 @@ -70,8 +71,8 @@ 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 +The verified `0.1.3` release provides that report trio. The verified `0.1.4` +release 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, @@ -120,8 +121,10 @@ Read the verified `0.1.3` [wire contract](https://github.com/pegma-dev/knowledge [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. +shipped in verified `0.1.4`; see its +[versioned guide](https://github.com/pegma-dev/knowledge-base/blob/v0.1.4/docs/EVIDENCE_REPORTS.md). +The new `0.1.5` candidate still requires its own verified publication. Actual +client/host acceptance remains open. ## Local verification and release @@ -152,8 +155,9 @@ compiled-test exclusion. All four package versions remain synchronized with exact internal dependency pins. Publishing, release tags, trusted-publisher configuration, and host activation are separate maintainer operations in the [release procedure](https://github.com/pegma-dev/knowledge-base/blob/v0.1.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. +The report-trio contract links above retain verified `v0.1.3`; aggregate query +and context-pair support shipped in verified `v0.1.4`. The `0.1.5` candidate +retains its separate 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 a83929a..24aa545 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-mcp", - "version": "0.1.4", + "version": "0.1.5", "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.4", - "@pegma/knowledge-base-contracts": "0.1.4", - "@pegma/knowledge-base-core": "0.1.4", + "@pegma/knowledge-base-application": "0.1.5", + "@pegma/knowledge-base-contracts": "0.1.5", + "@pegma/knowledge-base-core": "0.1.5", "zod": "4.6.7" }, "scripts": { diff --git a/packages/mcp/src/mcp.ts b/packages/mcp/src/mcp.ts index f5e3452..c54b338 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.4" }, + { name: "@pegma/knowledge-base-mcp", version: "0.1.5" }, { capabilities: { tools: {} }, // Workers prohibit the runtime code generation used by SDK-default AJV. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d73a610..7030a2c 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.4 + specifier: 0.1.5 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.4 + specifier: 0.1.5 version: link:packages/contracts '@pegma/knowledge-base-core': - specifier: 0.1.4 + specifier: 0.1.5 version: link:packages/core '@pegma/knowledge-base-mcp': - specifier: 0.1.4 + specifier: 0.1.5 version: link:packages/mcp '@pegma/spine': specifier: 0.1.2 @@ -45,8 +45,8 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/storage-cloudflare-d1': - specifier: 0.4.1 - version: 0.4.1 + specifier: 0.4.6 + version: 0.4.6 '@pegma/storage-core': specifier: 0.4.0 version: 0.4.0 @@ -81,10 +81,10 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/knowledge-base-contracts': - specifier: 0.1.4 + specifier: 0.1.5 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.4 + specifier: 0.1.5 version: link:../core '@pegma/spine': specifier: 0.1.2 @@ -102,7 +102,7 @@ importers: packages/core: dependencies: '@pegma/knowledge-base-contracts': - specifier: 0.1.4 + specifier: 0.1.5 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.4 + specifier: 0.1.5 version: link:../application '@pegma/knowledge-base-contracts': - specifier: 0.1.4 + specifier: 0.1.5 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.4 + specifier: 0.1.5 version: link:../core zod: specifier: 4.6.7 @@ -846,8 +846,8 @@ packages: resolution: {integrity: sha512-cHVrLyQRf8qu2d83fgO7spPxKxAZlOOfvEi/t38S6l3SD2678khJvUMcvAHm/rAQ8BlReDWd6WSnIZuQiI3A1Q==} engines: {node: '>=22'} - '@pegma/storage-cloudflare-d1@0.4.1': - resolution: {integrity: sha512-nVH+ppAWi3QwyEX8QVkPOLXNjtblO0jDnnGqCHpbZZzPvFQAVyd/1Bhxg8JdsuOD/UWGktJ26asAKzpNjRol0w==} + '@pegma/storage-cloudflare-d1@0.4.6': + resolution: {integrity: sha512-DjBRoRq5C6sWgL2KWdWOcW0F3N7HHuRu1i7Gr8SM4Aeh4FpEh1hQwIdMvkXpPHCd48CMqLJz8M5HYYR+/sRUgw==} engines: {node: '>=22'} '@pegma/storage-core@0.4.0': @@ -3428,7 +3428,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@pegma/storage-cloudflare-d1@0.4.1': + '@pegma/storage-cloudflare-d1@0.4.6': dependencies: '@pegma/storage-core': 0.4.0 diff --git a/test/README.md b/test/README.md index c0bd0b3..557bb4b 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.4`, and the Agent Access +The four unpublished candidate runtime packages are `0.1.5`, and the Agent Access protocol-proof pin remains `0.1.1`. `trace-store.ts` delegates every record operation to the supplied real store. @@ -54,8 +54,13 @@ between tests or omit awaiting a factory/disposal. The isolation suite uses the same article IDs in independently created stores and verifies public publication/retrieval/retirement behavior without inspecting storage. -Vitest is bounded to four workers, 180-second tests, and 30-second hooks; D1's -disposal hook also has a 30-second limit. CI jobs on Node 22/24 each have a +Vitest is bounded to four workers, a default 180-second test watchdog, and +30-second hooks; D1's disposal hook also has a 30-second limit. The complete-history +Miniflare D1 case in `retrieval-confirm-read-plan.test.ts` uses a 300-second total +fixture watchdog for local construction, transport and readback. That exception +preserves its measured hard limits of 50 D1 calls and 100 parameters per statement, +and its at-most-seven-call confirmation target. It is not a production latency or +whole-host budget qualification. CI jobs on Node 22/24 each have a 30-minute timeout. The workspace allows only the pinned `workerd` install script. These controls bound local native tooling, not production capacity. Windows local elapsed time includes Node-to-workerd RPC and setup overhead; @@ -92,6 +97,8 @@ 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 [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. +and [verified `0.1.3` release](../docs/BOOTSTRAP.md#current-verified-013-release). +The later [`0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4) +is qualified. Synchronized `0.1.5` is an unpublished internal read-batching +candidate with its own gates and verified trusted release required; host +activation gates remain open. diff --git a/tests/native-history-preparation.ts b/tests/native-history-preparation.ts new file mode 100644 index 0000000..3c10bf2 --- /dev/null +++ b/tests/native-history-preparation.ts @@ -0,0 +1,67 @@ +import { + knowledgeRecords, + retrievalRecords, +} from "@pegma/knowledge-base-application"; +import type { + CollectionDefinition, + Store, + TransactionAction, +} from "@pegma/storage-core"; +import { expect } from "vitest"; +import { allKnowledgeRows } from "../test/application-stores.js"; +import { allRetrievalRows } from "../test/retrieval-fixtures.js"; + +/** + * Prepare a read-conformance fixture from complete public-application history. + * Only declared values cross Stores; source version tokens and application + * observations are never transferred. This is not a migration implementation + * or evidence that the destination executed the donor's authoring workflow. + */ +export async function prepareNativeHistory(source: Store, target: Store) { + const knowledge = await allKnowledgeRows(source); + const retrieval = await allRetrievalRows(source); + const counts = { transactions: 0, maximumActions: 0 }; + + async function insertDeclared( + definition: CollectionDefinition, + values: readonly T[], + ) { + const destination = target.collection(definition); + const empty = await destination.scan({ limit: 1 }); + expect(empty.records).toEqual([]); + expect(empty.nextCursor).toBeNull(); + const partitions = new Map(); + for (const value of values) { + const key = definition.key(value); + const rows = partitions.get(key.partition); + if (rows === undefined) partitions.set(key.partition, [value]); + else rows.push(value); + } + // Public transact requires one partition and at most 100 actions. The + // actual destination adapter applies its own codec and SQL parameters. + for (const [partition, rows] of partitions) { + for (let offset = 0; offset < rows.length; offset += 100) { + const actions: TransactionAction[] = rows + .slice(offset, offset + 100) + .map((value): TransactionAction => ({ action: "insert", value })); + counts.maximumActions = Math.max(counts.maximumActions, actions.length); + expect(actions.length).toBeLessThanOrEqual(100); + const outcome = await destination.transact(partition, actions); + expect(outcome.committed).toBe(true); + counts.transactions += 1; + } + } + } + + await insertDeclared(knowledgeRecords, knowledge); + await insertDeclared(retrievalRecords, retrieval); + // Include every immutable receipt/Audit/job and exact quota/projection row, + // rather than reconstructing only the records needed by the positive read. + expect(await allKnowledgeRows(target)).toEqual(knowledge); + expect(await allRetrievalRows(target)).toEqual(retrieval); + return { + knowledgeRows: knowledge.length, + retrievalRows: retrieval.length, + ...counts, + }; +} diff --git a/tests/retrieval-confirm-read-plan.test.ts b/tests/retrieval-confirm-read-plan.test.ts new file mode 100644 index 0000000..34f2a0f --- /dev/null +++ b/tests/retrieval-confirm-read-plan.test.ts @@ -0,0 +1,850 @@ +import { + createKnowledgeBaseApplication, + knowledgeRecords, + type AnswerSourcesResult, + type PrivateSourceReference, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { + createCloudflareD1Store, + type CloudflareD1Database, + type CloudflareD1PreparedStatement, +} from "@pegma/storage-cloudflare-d1"; +import { createMemoryStore, type Store } from "@pegma/storage-core"; +import { Miniflare } from "miniflare"; +import { AsyncLocalStorage } from "node:async_hooks"; +import { randomUUID } from "node:crypto"; +import { describe, expect, it, onTestFinished } from "vitest"; +import { + access, + admin, + author, + at, + evidence, + validationPolicy, +} from "../test/application-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { D1_COMPATIBILITY_DATE } from "../test/d1.js"; +import { + botCustomer, + countSyntheticTokens, + retrievalApplicability, + retrievalFixture, + retrievalGuides, +} from "../test/retrieval-fixtures.js"; +import type { ReadTrace } from "../test/trace-store.js"; +import { prepareNativeHistory } from "./native-history-preparation.js"; + +type Fixture = ReturnType; +const articleId = "article/export"; +const collectionId = "collection/workshop"; +const source: PrivateSourceReference = { + id: "source/fictional", + system: "synthetic-support", + resourceId: "PRIVATE_SOURCE_CANARY", + version: "1", +}; + +function confirm(f: Fixture, answer: AnswerSourcesResult) { + return f.app.confirmAnswerSources(botCustomer, { + references: answer.sources.map((entry) => entry.reference), + applicability: retrievalApplicability, + }); +} + +function noSources(result: AnswerSourcesResult) { + expect(result).toEqual({ + outcome: "no_result", + sources: [], + serializedSources: "", + sourceTokens: 0, + }); +} + +async function sourcedGuide(f: Fixture) { + await f.setupCollection(); + let current = await f.createDraft( + articleId, + collectionId, + retrievalGuides[0]!.draft, + ); + current = await f.setSources(current, [source]); + current = (await f.submitEvidence(current)).current; + await f.publish(current); + await f.repair(articleId); + const answer = await f.app.retrieveAnswerSources(botCustomer, f.botInput()); + expect(answer.sources).toHaveLength(1); + f.privateSources.canPublish.mockClear(); + f.privateSources.isCurrent.mockClear(); + return answer; +} + +async function rewriteHead( + backing: Store, + kind: "article" | "collection" | "validation", +) { + const row = (await allKnowledgeRows(backing)).find( + (item) => item.kind === "head" && item.resourceKind === kind, + ); + if (row === undefined) throw new Error("Expected an actual governed head"); + const records = 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 opaque version"); + expect(await records.putIfUnchanged(saved.value, saved.version)).toBe(true); + const rewritten = await records.getVersioned(key); + expect(rewritten?.value).toEqual(saved.value); + expect(rewritten?.version).not.toBe(saved.version); +} + +function evidenceRead(trace: ReadTrace) { + return ( + trace.collection === knowledgeRecords.name && + trace.method === "get" && + (trace.key.id.startsWith("evidence:") || + trace.key.id.startsWith("revoked:")) + ); +} + +function readIdentity(trace: ReadTrace) { + return JSON.stringify([trace.key.partition, trace.key.id]); +} + +/** A release latch only; the Store and every stored row remain real. */ +function latch() { + let release = () => {}; + const waiting = new Promise((resolve) => { + release = resolve; + }); + return { waiting, release }; +} + +type HistoryMark = (stage: string, completed?: number, total?: number) => void; + +async function completeHistory(f: Fixture, mark: HistoryMark = () => {}) { + mark("history.collection.before"); + await f.setupCollection(); + mark("history.collection.after"); + const extraChecks = Array.from({ length: 27 }, (_, index) => ({ + ...validationPolicy.requirements[0]!, + id: `explanation-extra-${index}`, + })); + // Four other-kind/workflow requirements remain. The 32-check policy thus + // admits 28 distinct explanation proofs, not an impossible 32-proof review. + const policy = { + ...validationPolicy, + version: 2, + requirements: [...validationPolicy.requirements, ...extraChecks], + }; + expect(policy.requirements).toHaveLength(32); + mark("history.policy.before"); + const previousPolicy = await f.authoringApp.getValidationPolicy(admin, { + policyId: policy.id, + }); + await f.authoringApp.putValidationPolicy(admin, { + ...f.command("complete-policy", previousPolicy.generation), + policy, + }); + const configured = await f.authoringApp.getGovernanceConfiguration(admin, { + collectionId, + }); + await f.authoringApp.putGovernanceConfiguration(admin, { + ...f.command("complete-configuration", configured.generation), + collectionId, + configuration: { + ...configured.configuration, + validationPolicy: { id: policy.id, version: policy.version }, + }, + }); + mark("history.policy.after"); + mark("history.draft.before"); + let current = await f.createDraft( + articleId, + collectionId, + retrievalGuides[0]!.draft, + ); + mark("history.draft.after"); + mark("history.approved.before"); + let approvedCount = 0; + for (const check of policy.requirements.filter( + (item) => item.kind === "explanation", + )) { + current = ( + await f.submitEvidence(current, undefined, { + ...evidence(current.revision), + id: `proof/${check.id}`, + checkId: check.id, + }) + ).current; + approvedCount += 1; + if (approvedCount % 8 === 0 || approvedCount === 28) + mark("history.approved.progress", approvedCount, 28); + } + const approved = await f.authoringApp.getEvidence(admin, { articleId }); + expect(approved.evidence).toHaveLength(28); + mark("history.approved.after", approvedCount, 28); + mark("history.publish.before"); + const published = await f.publish(current); + expect(published.input.review.binding.evidence).toHaveLength(28); + mark("history.publish.after"); + mark("history.repair.before"); + await f.repair(articleId); + mark("history.repair.after"); + mark("history.draft2.before"); + await f.authoringApp.updateDraft(author, { + ...f.command("unapproved-private-draft", published.current.generation), + articleId, + collectionId, + draft: { + ...retrievalGuides[0]!.draft, + content: { format: "plain_text", text: "UNAPPROVED_DRAFT_CANARY" }, + }, + }); + current = await f.authoringApp.getDraft(author, { articleId }); + mark("history.draft2.after"); + mark("history.current.before"); + // Same-check evidence is legal draft data, but deliberately not a qualifying + // publication. None may replace or shorten the retained approved proof set. + for (let index = 0; index < 32; index += 1) { + current = ( + await f.submitEvidence(current, undefined, { + ...evidence(current.revision), + id: `current-proof/${index}`, + }) + ).current; + if ((index + 1) % 8 === 0) mark("history.current.progress", index + 1, 32); + } + mark("history.current.after", 32, 32); + mark("history.revocations.before"); + for (let index = 0; index < 64; index += 1) { + const facts = await f.authoringApp.getEvidence(admin, { articleId }); + const proof = facts.evidence.find((item) => item.id === "current-proof/0"); + if (proof === undefined) throw new Error("Expected real current proof"); + await f.authoringApp.revokeEvidence(admin, { + ...f.command("retain-revocation", facts.generation), + articleId, + articleRevision: proof.articleRevision, + evidenceId: proof.id, + evidenceVersion: proof.version, + evidenceHash: proof.hash, + reason: "Synthetic retained-history replacement", + }); + current = await f.authoringApp.getDraft(author, { articleId }); + current = ( + await f.submitEvidence(current, undefined, { + ...evidence(current.revision), + id: "current-proof/0", + }) + ).current; + if ((index + 1) % 8 === 0) + mark("history.revocations.progress", index + 1, 64); + } + mark("history.revocations.after", 64, 64); + mark("history.summary.before"); + const retained = await f.authoringApp.getEvidence(admin, { articleId }); + expect(retained.evidence).toHaveLength(32); + expect(retained.revokedEvidence).toHaveLength(64); + expect(current.revision.number).toBe(2); + mark("history.summary.after"); + return { approved, retained }; +} + +for (const [name, createStore] of storeFactories) { + describe(`conservative publication read plan (${name})`, () => { + it("authorizes C before any A probe and never borrows another collection's authority", async () => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + await f.publishGuide(); + await f.setupCollection("collection/second"); + await f.publishGuide( + { ...retrievalGuides[0]!, id: "article/second" }, + "collection/second", + ); + const answer = await f.app.retrieveAnswerSources(botCustomer, { + ...f.botInput(), + collectionIds: [collectionId, "collection/second"], + }); + expect(answer.sources).toHaveLength(2); + expect(await confirm(f, answer)).toEqual(answer); + const articlePartitions = new Set( + (await allKnowledgeRows(backing)) + .filter((row) => row.resourceKind === "article") + .map((row) => row.partition), + ); + f.clearObservations(); + const denied = access("customer/unapproved", [ + knowledgePermissions.articleRead, + knowledgePermissions.botRead, + ]); + noSources( + await f.app.confirmAnswerSources(denied, { + references: answer.sources.map((entry) => entry.reference), + applicability: retrievalApplicability, + }), + ); + expect( + f.traced.reads.some((read) => + articlePartitions.has(read.key.partition), + ), + ).toBe(false); + const first = answer.sources.find( + (entry) => entry.reference.articleId === articleId, + ); + if (first === undefined) throw new Error("Expected a returned source"); + noSources( + await f.app.confirmAnswerSources(botCustomer, { + references: [ + { ...first.reference, collectionId: "collection/second" }, + ], + applicability: retrievalApplicability, + }), + ); + expect(f.traced.enumerations).toEqual([]); + expect(f.traced.transactions).toEqual([]); + }); + + it("keeps both raw A/C/V fences even when numeric generations and payloads do not change", async () => { + const backing = await createStore(); + const f = retrievalFixture(backing); + const answer = await sourcedGuide(f); + for (const kind of ["article", "collection", "validation"] as const) { + for (const round of [1, 2]) { + let calls = 0; + f.privateSources.canPublish.mockClear(); + f.privateSources.isCurrent.mockImplementation(async () => { + calls += 1; + if (calls === round) await rewriteHead(backing, kind); + return true; + }); + f.clearObservations(); + noSources(await confirm(f, answer)); + expect(calls).toBe(round); + expect(f.privateSources.canPublish).toHaveBeenCalledTimes(round); + expect(f.traced.transactions).toEqual([]); + } + } + }); + + it("retains both live source callback pairs and excludes every private source or evidence field", async () => { + const f = retrievalFixture(await createStore()); + const answer = await sourcedGuide(f); + expect(await confirm(f, answer)).toEqual(answer); + expect(f.privateSources.canPublish).toHaveBeenCalledTimes(2); + expect(f.privateSources.isCurrent).toHaveBeenCalledTimes(2); + for (const callback of ["canPublish", "isCurrent"] as const) { + for (const round of [1, 2]) { + let calls = 0; + f.privateSources[callback].mockImplementation(async () => { + calls += 1; + return calls !== round; + }); + noSources(await confirm(f, answer)); + expect(calls).toBe(round); + f.privateSources[callback].mockImplementation(async () => true); + } + } + for (const privateValue of [ + source.resourceId, + source.system, + "PRIVATE_STAFF_EVIDENCE", + "staff/verifier", + "runner/staging", + "attestation", + "provenance", + ]) + expect(answer.serializedSources).not.toContain(privateValue); + }); + + it.each(["audience", "validation", "evidence", "retirement"] as const)( + "withholds an already serialized answer after current %s changes in the second source fence", + async (change) => { + const f = retrievalFixture(await createStore()); + const answer = await sourcedGuide(f); + let calls = 0; + f.privateSources.isCurrent.mockImplementation(async () => { + calls += 1; + if (calls !== 2) return true; + if (change === "audience") { + const preview = await f.authoringApp.previewCollectionPolicy( + admin, + { + collectionId, + uses: { portal: { enabled: false }, bot: { enabled: false } }, + }, + ); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("withdraw-audience", preview.generation), + collectionId, + preview: preview.preview, + }); + } else if (change === "validation") { + const current = await f.authoringApp.getValidationPolicy(admin, { + policyId: validationPolicy.id, + }); + await f.authoringApp.putValidationPolicy(admin, { + ...f.command("withdraw-validation", current.generation), + policy: { + ...current.policy, + version: current.policy.version + 1, + }, + }); + } else if (change === "evidence") { + const facts = await f.authoringApp.getEvidence(admin, { + articleId, + }); + const proof = facts.evidence[0]; + if (proof === undefined) throw new Error("Expected accepted proof"); + await f.authoringApp.revokeEvidence(admin, { + ...f.command("withdraw-proof", facts.generation), + articleId, + articleRevision: proof.articleRevision, + evidenceId: proof.id, + evidenceVersion: proof.version, + evidenceHash: proof.hash, + reason: "Synthetic current proof withdrawal", + }); + } else { + const current = await f.authoringApp.getDraft(admin, { articleId }); + await f.authoringApp.retireArticle(admin, { + ...f.command("retire-after-serialization", current.generation), + articleId, + }); + } + return true; + }); + noSources(await confirm(f, answer)); + expect(calls).toBe(2); + }, + ); + + it.each(["missing", "corrupt"] as const)( + "refuses a %s approved proof without appending any rows", + async (fault) => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + await f.publishGuide(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + expect(answer.sources).toHaveLength(1); + const row = (await allKnowledgeRows(backing)).find( + (item) => item.kind === "evidence" && item.resourceId === articleId, + ); + if (row === undefined) + throw new Error("Expected actual approved evidence"); + const records = backing.collection(knowledgeRecords); + const key = { partition: row.partition, id: row.id }; + const saved = await records.getVersioned(key); + if (saved === null) throw new Error("Expected actual proof version"); + if (fault === "missing") { + expect(await records.deleteIfUnchanged(key, saved.version)).toBe( + true, + ); + } else { + const data = saved.value.data; + if (data === null || typeof data !== "object" || Array.isArray(data)) + throw new Error("Expected an actual structured proof"); + expect( + await records.putIfUnchanged( + { ...saved.value, data: { ...data, hash: "0".repeat(64) } }, + saved.version, + ), + ).toBe(true); + } + const before = await allKnowledgeRows(backing); + f.clearObservations(); + noSources(await confirm(f, answer)); + expect(f.traced.transactions).toEqual([]); + expect(await allKnowledgeRows(backing)).toEqual(before); + }, + ); + + // Memory/Azurite retain vitest.config.ts's global 180-second watchdog. + // The Native Node/workerd fixture retains its 300-second exception; + // measured query/parameter and SDK limits stay fixed. + it( + "keeps complete approved proofs independent of legal E32/R64 draft history and starts the whole E/R wave", + async ({ task }) => { + const started = performance.now(); + let observed: Fixture | undefined; + const timings: { + stage: string; + elapsedMilliseconds: number; + readObservations: number; + enumerationObservations: number; + transactionObservations: number; + completed?: number; + total?: number; + }[] = []; + const mark: HistoryMark = (stage, completed, total) => { + // Fixed stage names and numeric work only: no keys, IDs, content or SQL. + if (timings.length >= 64) return; + const sample = { + stage, + elapsedMilliseconds: Math.round(performance.now() - started), + readObservations: observed?.traced.reads.length ?? 0, + enumerationObservations: observed?.traced.enumerations.length ?? 0, + transactionObservations: observed?.traced.transactions.length ?? 0, + ...(completed === undefined ? {} : { completed }), + ...(total === undefined ? {} : { total }), + }; + timings.push(sample); + Object.assign(task.meta, { + knowledgeHistoryTimings: structuredClone(timings), + }); + console.info( + "knowledge-history-timing", + JSON.stringify({ backend: name, ...sample }), + ); + }; + // Emits the last known stage even when the test watchdog triggers first. + onTestFinished(() => mark("test.finished")); + mark("case.before"); + try { + mark("store.before"); + // This large-history case uses the public opt-in already exercised by + // physicalD1; all other generic Native cases retain direct reads. + const native = + name === "Miniflare D1" ? await physicalD1() : undefined; + const backing = + native === undefined ? await createStore() : native.setup; + mark("store.after"); + // The large Native case checks publication READ conformance. Build + // its full legal history through the actual public Memory app, then + // transfer all declared values through the real Native Store. Other + // Native cases still execute their own real authoring workflows. + const construction = retrievalFixture( + native === undefined ? backing : createMemoryStore(), + ); + observed = construction; + Object.assign(task.meta, { + knowledgeHistoryPreparation: + native === undefined + ? "same-backend-public-application" + : "memory-public-application-to-native-read-fixture", + }); + const facts = await completeHistory(construction, mark); + const f = + native === undefined ? construction : retrievalFixture(backing); + if (native !== undefined) { + mark("native.copy.before"); + const copied = await prepareNativeHistory( + construction.store, + backing, + ); + Object.assign(task.meta, { knowledgeHistoryCopiedRows: copied }); + mark("native.copy.after"); + // Match the retrieval clock and follow all donor authoring actions. + // No donor receipts, raw versions or confirmation WeakMaps are reused. + f.setTime(600_000); + observed = f; + mark("native.readback.before"); + expect( + await f.authoringApp.getDraft(author, { articleId }), + ).toEqual( + await construction.authoringApp.getDraft(author, { articleId }), + ); + expect( + await f.authoringApp.getEvidence(admin, { articleId }), + ).toEqual(facts.retained); + mark("native.readback.after"); + } + mark("retrieve.before"); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput(), + ); + mark("retrieve.after"); + expect(answer.sources).toHaveLength(1); + expect(answer.sources[0]?.reference.articleRevision).toBe(1); + expect(answer.sources[0]?.content).toEqual( + retrievalGuides[0]!.draft.content, + ); + expect(answer.serializedSources).not.toContain( + "UNAPPROVED_DRAFT_CANARY", + ); + if (native !== undefined) { + mark("native.qualification.before"); + expect(await confirm(f, answer)).toEqual(answer); + mark("native.qualification.after"); + } + f.clearObservations(); + mark("confirm.baseline.before"); + const profile: PhysicalProfile = { + calls: 0, + statements: 0, + batches: 0, + maximumParameters: 0, + blocked: 0, + }; + try { + const result = + native === undefined + ? await confirm(f, answer) + : await native.measure(profile, () => confirm(f, answer)); + expect(result).toEqual(answer); + } finally { + if (native !== undefined) { + Object.assign(task.meta, { + knowledgeHistoryConfirmationProfile: structuredClone(profile), + }); + console.info( + "knowledge-history-confirmation-profile", + JSON.stringify(profile), + ); + expect(profile.blocked).toBe(0); + expect(profile.maximumParameters).toBeLessThanOrEqual(100); + expect(profile.calls).toBeGreaterThan(0); + expect(profile.calls).toBeLessThanOrEqual(7); + } + } + mark("confirm.baseline.after"); + const expected = f.traced.reads + .filter(evidenceRead) + .map(readIdentity); + expect(expected).toHaveLength(facts.approved.evidence.length * 2); + expect(expected).toHaveLength(56); + expect(new Set(expected).size).toBe(expected.length); + mark("barrier.create"); + const release = latch(); + const reached = latch(); + const seen: ReadTrace[] = []; + f.clearObservations(); + f.traced.beforeRead(async (trace) => { + if (!evidenceRead(trace)) return; + seen.push(trace); + if (seen.length === 1) + mark("barrier.firstEvidence", seen.length, expected.length); + reached.release(); + await release.waiting; + }); + const pending = confirm(f, answer); + mark("barrier.await"); + try { + await Promise.race([ + reached.waiting, + pending.then(() => { + throw new Error( + "Confirmation completed without the required proof wave", + ); + }), + ]); + mark("barrier.entered", seen.length, expected.length); + expect(seen.map(readIdentity).sort()).toEqual([...expected].sort()); + mark("barrier.release", seen.length, expected.length); + release.release(); + expect(await pending).toEqual(answer); + mark("barrier.confirm.after"); + } finally { + mark("barrier.finally", seen.length, expected.length); + release.release(); + f.traced.beforeRead(undefined); + await pending; + } + expect(f.traced.transactions).toEqual([]); + const accepted = facts.approved.evidence.at(-1); + if (accepted === undefined) + throw new Error("Expected last approved proof"); + mark("withdraw.before"); + const current = await f.authoringApp.getDraft(author, { articleId }); + await f.authoringApp.revokeEvidence(admin, { + ...f.command( + native === undefined + ? "revoke-last-approved" + : "native-read-revoke-last-approved", + current.generation, + ), + articleId, + articleRevision: accepted.articleRevision, + evidenceId: accepted.id, + evidenceVersion: accepted.version, + evidenceHash: accepted.hash, + reason: "Synthetic exact retained-publication withdrawal", + }); + mark("withdraw.after"); + mark("confirm.final.before"); + noSources(await confirm(f, answer)); + mark("confirm.final.after"); + } finally { + mark("case.finally"); + } + }, + name === "Miniflare D1" ? 300_000 : 180_000, + ); + }); +} + +interface PhysicalProfile { + calls: number; + statements: number; + batches: number; + maximumParameters: number; + blocked: number; +} + +/** Count real D1 binding executions, not Store calls or statements in a batch. */ +async function physicalD1() { + let runtime: Miniflare | undefined; + let disposal: Promise | undefined; + const dispose = () => { + const current = runtime; + if (current === undefined) return Promise.resolve(); + disposal ??= current.dispose(); + return disposal; + }; + onTestFinished(dispose, 30_000); + try { + runtime = new Miniflare({ + modules: true, + script: + "export default { fetch() { return new Response(null, { status: 204 }); } };", + compatibilityDate: D1_COMPATIBILITY_DATE, + host: "127.0.0.1", + port: 0, + cf: false, + d1Persist: false, + d1Databases: { DB: randomUUID() }, + }); + const actual: CloudflareD1Database = await runtime.getD1Database("DB"); + const active = new AsyncLocalStorage(); + const originals = new WeakMap< + CloudflareD1PreparedStatement, + CloudflareD1PreparedStatement + >(); + function execution(statements: number, batch = false) { + const profile = active.getStore(); + if (profile === undefined) return; + if (profile.calls >= 50) { + profile.blocked += 1; + throw new Error("Synthetic D1 physical-call ceiling exceeded"); + } + profile.calls += 1; + profile.statements += statements; + if (batch) profile.batches += 1; + } + function observed( + statement: CloudflareD1PreparedStatement, + ): CloudflareD1PreparedStatement { + const wrapped = new Proxy(statement, { + get(target, property) { + if (property === "bind") + return (...values: unknown[]) => { + const profile = active.getStore(); + if (profile !== undefined) { + profile.maximumParameters = Math.max( + profile.maximumParameters, + values.length, + ); + if (values.length > 100) { + profile.blocked += 1; + throw new Error("Synthetic D1 parameter ceiling exceeded"); + } + } + return observed(target.bind(...values)); + }; + const value: unknown = Reflect.get(target, property, target); + if (typeof value !== "function") return value; + if (["first", "all", "run", "raw"].includes(String(property))) + return (...args: unknown[]) => { + execution(1); + return Reflect.apply(value, target, args); + }; + return value.bind(target); + }, + }); + originals.set(wrapped, statement); + return wrapped; + } + const database = new Proxy(actual, { + get(target, property) { + if (property === "prepare") + return (query: string) => observed(target.prepare(query)); + if (property === "batch") + return (statements: CloudflareD1PreparedStatement[]) => { + const native = statements.map((statement) => { + const original = originals.get(statement); + if (original === undefined) + throw new Error("Expected a genuine observed D1 statement"); + return original; + }); + execution(native.length, true); + return target.batch(native); + }; + const value: unknown = Reflect.get(target, property, target); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + return { + setup: createCloudflareD1Store({ database, readBatchSize: 512 }), + fresh: () => + createCloudflareD1Store({ + database, + createSchemaIfMissing: false, + readBatchSize: 512, + }), + measure: (profile: PhysicalProfile, work: () => Promise) => + active.run(profile, work), + }; + } catch (error) { + try { + await dispose(); + } catch (cleanupError) { + throw new AggregateError( + [error, cleanupError], + "Real D1 initialization and disposal failed", + ); + } + throw error; + } +} + +it("confirms one real approved source with at most seven physical D1 calls and no query or parameter waiver", async ({ + task, +}) => { + const d1 = await physicalD1(); + const seeded = retrievalFixture(d1.setup); + await seeded.setupCollection(); + await seeded.publishGuide(); + const answer = await seeded.app.retrieveAnswerSources( + botCustomer, + seeded.botInput(), + ); + expect(answer.sources).toHaveLength(1); + const profile: PhysicalProfile = { + calls: 0, + statements: 0, + batches: 0, + maximumParameters: 0, + blocked: 0, + }; + try { + const result = await d1.measure(profile, async () => { + // A fresh adapter and application enter the measured scope. Only schema + // creation and genuine public SDK setup above are unmeasured. + const app = createKnowledgeBaseApplication({ + store: d1.fresh(), + clock: { now: () => at(600_000) }, + retrieval: { tokenCounter: { count: countSyntheticTokens } }, + }); + return app.confirmAnswerSources(botCustomer, { + references: answer.sources.map((entry) => entry.reference), + applicability: retrievalApplicability, + }); + }); + expect(result).toEqual(answer); + } finally { + Object.assign(task.meta, { + knowledgeConfirmationProfile: structuredClone(profile), + }); + expect(profile.blocked).toBe(0); + expect(profile.maximumParameters).toBeLessThanOrEqual(100); + expect(profile.calls).toBeGreaterThan(0); + expect(profile.calls).toBeLessThanOrEqual(7); + } +}); diff --git a/tests/retrieval-posting-read-batching.test.ts b/tests/retrieval-posting-read-batching.test.ts new file mode 100644 index 0000000..4d6c48b --- /dev/null +++ b/tests/retrieval-posting-read-batching.test.ts @@ -0,0 +1,413 @@ +import { + knowledgeRecords, + retrievalRecords, +} from "@pegma/knowledge-base-application"; +import { createMemoryStore } from "@pegma/storage-core"; +import { describe, expect, it } from "vitest"; +import { admin } from "../test/application-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { + botCustomer, + retrievalFixture, + retrievalGuides, +} from "../test/retrieval-fixtures.js"; +import type { ReadTrace } from "../test/trace-store.js"; + +function barrier() { + let release = () => {}; + const reached = new Promise((resolve) => { + release = resolve; + }); + return { reached, release }; +} + +function posting(trace: ReadTrace) { + return ( + trace.collection === retrievalRecords.name && + trace.key.id.startsWith("posting:") + ); +} +function page(trace: ReadTrace) { + return ( + trace.collection === retrievalRecords.name && + trace.key.id.startsWith("page:") + ); +} + +for (const [name, createStore] of storeFactories) { + describe(`prepared multi-term posting reads (${name})`, () => { + it("prepares every term head before reading any declared page, then starts every page together", async () => { + // A lower legal page size creates two genuinely maintained pages per term + // with two public-API-published guides; no fabricated posting rows. + const f = retrievalFixture(await createStore(), { + limits: { postingPageEntries: 1 }, + }); + await f.setupCollection(); + await f.publishGuide(); + await f.publishGuide({ + ...retrievalGuides[0]!, + id: "article/export-second", + }); + f.clearObservations(); + const firstHead = barrier(); + const releaseHeads = barrier(); + const firstPage = barrier(); + const releasePages = barrier(); + const heads: ReadTrace[] = []; + const pages: ReadTrace[] = []; + f.traced.beforeRead(async (trace) => { + if (posting(trace)) { + heads.push(trace); + firstHead.release(); + await releaseHeads.reached; + } else if (page(trace)) { + pages.push(trace); + firstPage.release(); + await releasePages.reached; + } + }); + const pending = f.app.retrieveAnswerSources( + botCustomer, + f.botInput("workspace export csv"), + ); + try { + await firstHead.reached; + expect(heads).toHaveLength(3); + expect(pages).toEqual([]); + releaseHeads.release(); + await firstPage.reached; + expect(pages).toHaveLength(6); + releasePages.release(); + const answer = await pending; + expect( + answer.sources.map((source) => source.reference.articleId), + ).toEqual(["article/export", "article/export-second"]); + expect(new Set(heads.map((read) => read.key.id)).size).toBe(3); + expect(new Set(pages.map((read) => read.key.id)).size).toBe(6); + expect(f.traced.enumerations).toEqual([]); + expect(f.traced.transactions).toEqual([]); + } finally { + releaseHeads.release(); + releasePages.release(); + f.traced.beforeRead(undefined); + await pending; + } + }); + + it("preserves multi-term ranking, deduplication and complete source results for reversed term order", async () => { + const f = retrievalFixture(await createStore()); + await f.corpus(); + const forward = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("csv export invite"), + ); + const reversed = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("invite export csv"), + ); + expect( + forward.sources.map((source) => source.reference.articleId), + ).toEqual(["article/export", "article/invite"]); + expect(reversed).toEqual(forward); + expect(JSON.parse(forward.serializedSources)).toEqual(forward.sources); + }); + + it.each([{ maxIndexKeyReads: 5 }, { maxPostingEntries: 2 }])( + "preserves request accounting without partial results at %j", + async (limits) => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + await f.publishGuide(); + const limited = retrievalFixture(backing, { limits }); + limited.clearObservations(); + const answer = await limited.app.retrieveAnswerSources( + botCustomer, + limited.botInput("workspace export csv"), + ); + expect(answer.outcome).toBe("no_result"); + expect(answer.sources).toEqual([]); + const indexReads = limited.traced.reads.filter( + (read) => read.collection === retrievalRecords.name, + ); + if ("maxIndexKeyReads" in limits) + expect(indexReads.length).toBeLessThanOrEqual( + limits.maxIndexKeyReads, + ); + expect(limited.traced.enumerations).toEqual([]); + expect(limited.traced.transactions).toEqual([]); + }, + ); + + it("refuses a missing actually declared page instead of returning other matching terms", async () => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + await f.publishGuide(); + f.clearObservations(); + expect( + ( + await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("workspace"), + ) + ).sources, + ).toHaveLength(1); + const observed = f.traced.reads.find(page); + if (observed === undefined) + throw new Error("Expected an actual maintained page read"); + const rows = backing.collection(retrievalRecords); + const original = await rows.getVersioned(observed.key); + if (original === null) throw new Error("Expected the actual page"); + expect(await rows.deleteIfUnchanged(observed.key, original.version)).toBe( + true, + ); + f.clearObservations(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("workspace export csv"), + ); + expect(answer.sources).toEqual([]); + expect(answer.outcome).toBe("no_result"); + expect(f.traced.transactions).toEqual([]); + }); + + it("validates all prepared heads and refuses an excessive declared page count before reading pages", async () => { + const backing = await createStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + await f.publishGuide(); + f.clearObservations(); + await f.app.retrieveAnswerSources(botCustomer, f.botInput("workspace")); + const observed = f.traced.reads.find(posting); + if (observed === undefined) + throw new Error("Expected an actual maintained head read"); + const rows = backing.collection(retrievalRecords); + const original = await rows.getVersioned(observed.key); + if ( + original === null || + original.value.kind !== "posting" || + typeof original.value.data !== "object" || + original.value.data === null || + Array.isArray(original.value.data) + ) + throw new Error("Expected the actual posting-head data"); + const changed = await rows.putIfUnchanged( + { + ...original.value, + data: { ...original.value.data, pages: Number.MAX_SAFE_INTEGER }, + }, + original.version, + ); + expect(changed).toBe(true); + f.clearObservations(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("workspace export csv"), + ); + expect(answer.sources).toEqual([]); + expect(f.traced.reads.filter(posting)).toHaveLength(3); + expect(f.traced.reads.filter(page)).toEqual([]); + expect(f.traced.transactions).toEqual([]); + }); + + it("retains authoritative evidence revocation after a real posting-page await", async () => { + const f = retrievalFixture(await createStore()); + await f.setupCollection(); + const published = await f.publishGuide(); + const reached = barrier(); + const resume = barrier(); + let held = false; + f.traced.beforeRead(async (trace) => { + if (page(trace) && !held) { + held = true; + reached.release(); + await resume.reached; + } + }); + const pending = f.app.retrieveAnswerSources( + botCustomer, + f.botInput("workspace export csv"), + ); + try { + await reached.reached; + const proof = ( + await f.app.getEvidence(admin, { + articleId: published.current.articleId, + }) + ).evidence[0]; + if (proof === undefined) + throw new Error("Expected genuinely accepted evidence"); + await f.app.revokeEvidence(admin, { + ...f.command( + "withdraw-during-posting-wave", + published.current.generation, + ), + articleId: published.current.articleId, + articleRevision: proof.articleRevision, + evidenceId: proof.id, + evidenceVersion: proof.version, + evidenceHash: proof.hash, + reason: "Synthetic withdrawal", + }); + const writes = f.traced.transactions.length; + resume.release(); + expect((await pending).sources).toEqual([]); + expect(f.traced.transactions).toHaveLength(writes); + } finally { + resume.release(); + f.traced.beforeRead(undefined); + await pending; + } + }); + + it("counts missing term heads without reading pages or inventing a source", async () => { + const f = retrievalFixture(await createStore()); + await f.setupCollection(); + await f.publishGuide(); + f.clearObservations(); + const answer = await f.app.retrieveAnswerSources( + botCustomer, + f.botInput("quasar nebula"), + ); + expect(answer.sources).toEqual([]); + expect(f.traced.reads.filter(posting)).toHaveLength(2); + expect(f.traced.reads.filter(page)).toEqual([]); + expect(f.traced.enumerations).toEqual([]); + expect(f.traced.transactions).toEqual([]); + }); + }); +} + +describe("posting-entry early exit (memory)", () => { + it("stops later term reads at a lowered posting-entry cap while retaining the default eight-term wave", async () => { + const terms = [ + "amber", + "birch", + "cedar", + "delta", + "ember", + "fable", + "grove", + "harbor", + ]; + const query = terms.join(" "); + const backing = createMemoryStore(); + const f = retrievalFixture(backing); + await f.setupCollection(); + const guide = { + ...retrievalGuides[0]!, + id: "article/eight-term-cap", + draft: { + ...retrievalGuides[0]!.draft, + title: query, + tags: terms, + }, + }; + await f.publishGuide(guide); + // Inspect the real maintained head outside the measured request. No copied + // key codec or invented projection supplies the expected article identity. + const articleHead = (await allKnowledgeRows(backing)).find( + (row) => + row.kind === "head" && + row.resourceKind === "article" && + row.resourceId === guide.id, + ); + if (articleHead === undefined) + throw new Error( + "Public publication did not retain its actual article head", + ); + + f.clearObservations(); + const firstHead = barrier(); + const releaseHeads = barrier(); + const firstPage = barrier(); + const releasePages = barrier(); + const heads: ReadTrace[] = []; + const pages: ReadTrace[] = []; + f.traced.beforeRead(async (trace) => { + if (posting(trace)) { + heads.push(trace); + firstHead.release(); + await releaseHeads.reached; + } else if (page(trace)) { + pages.push(trace); + firstPage.release(); + await releasePages.reached; + } + }); + const pending = f.app.retrieveAnswerSources(botCustomer, f.botInput(query)); + try { + await firstHead.reached; + expect(heads).toHaveLength(8); + expect(pages).toEqual([]); + releaseHeads.release(); + await firstPage.reached; + expect(pages).toHaveLength(8); + releasePages.release(); + const answer = await pending; + expect( + answer.sources.map((source) => source.reference.articleId), + ).toEqual([guide.id]); + expect( + await f.app.retrieveAnswerSources( + botCustomer, + f.botInput([...terms].reverse().join(" ")), + ), + ).toEqual(answer); + } finally { + releaseHeads.release(); + releasePages.release(); + f.traced.beforeRead(undefined); + await pending; + } + // Both queries above observed all terms; retain only the first query's + // ordered keys as the real public-Store oracle for the restricted request. + const firstHeads = heads.slice(0, 8); + const firstPages = pages.slice(0, 8); + expect(new Set(firstHeads.map((read) => read.key.id)).size).toBe(8); + expect(new Set(firstPages.map((read) => read.key.id)).size).toBe(8); + for (const read of firstPages) { + const row = await backing.collection(retrievalRecords).get(read.key); + const data = row?.data; + if ( + row?.kind !== "page" || + typeof data !== "object" || + data === null || + !("entries" in data) || + !Array.isArray(data.entries) + ) + throw new Error("Expected the actual maintained posting page"); + expect(data.entries).toHaveLength(1); + } + + const limited = retrievalFixture(backing, { + limits: { maxPostingEntries: 1 }, + }); + limited.clearObservations(); + const result = await limited.app.retrieveAnswerSources( + botCustomer, + limited.botInput(query), + ); + expect(result.outcome).toBe("no_result"); + expect(result.sources).toEqual([]); + // The second real one-entry term reveals exhaustion. No later term may + // start after that checkpoint; duplicates still count as fetched entries. + expect(limited.traced.reads.filter(posting)).toEqual( + firstHeads.slice(0, 2), + ); + expect(limited.traced.reads.filter(page)).toEqual(firstPages.slice(0, 2)); + expect( + limited.traced.reads.filter( + (read) => + read.collection === knowledgeRecords.name && + read.key.partition === articleHead.partition, + ), + ).toEqual([]); + expect(limited.traced.enumerations).toEqual([]); + expect(limited.traced.transactions).toEqual([]); + }); +});