diff --git a/AGENTS.md b/AGENTS.md index 5c03741..f505933 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,9 @@ tests. The approved scope is the [Support Desk enhancement plan](https://github. read batching; retain the [historical release receipt](docs/BOOTSTRAP.md#current-verified-015-release). All four `0.1.6` packages completed verified trusted publication for MCP metadata compatibility. Retain the [current release receipt](docs/BOOTSTRAP.md#current-verified-016-release). - The synchronized `0.1.7` source candidate remains unpublished. + All four `0.1.7` packages completed verified trusted publication for the staff + report-view canonical receipt. Retain the [verified release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). + The synchronized `0.1.8` source candidate remains unpublished. Grouped reads establish no universal query or CPU budget. Host dependency adoption and real-host acceptance remain separate. - Never implement a database, authorization role model, identity/session/token diff --git a/README.md b/README.md index 598238a..94151cc 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,9 @@ and exact publication approval. It requires no GitHub connection or AI provider. > for answering read batching, including strict registry/provenance and public-consumer > verification. All four `0.1.6` packages completed > [verified trusted publication](docs/BOOTSTRAP.md#current-verified-016-release) -> for MCP extension metadata compatibility. The `0.1.7` candidate remains unpublished. +> for MCP extension metadata compatibility. All four `0.1.7` packages completed +> [verified trusted publication](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7) +> for the staff report-view canonical receipt. The `0.1.8` candidate remains unpublished. > Host dependency adoption remains separate. > Actual two-host existing-login/client acceptance remains open. > Host activation remains separately gated; this repository supplies no hosted KB. @@ -173,7 +175,7 @@ release checkpoint, all four KB packages had `latest: 0.1.5`; Agent Access remained at `latest: 0.1.1`; all retained `bootstrap: 0.1.0`. Dist-tags are mutable observations. The [retained `0.1.5` receipt](docs/BOOTSTRAP.md#current-verified-015-release) binds the original artifact, exact manifest, authenticated original writers and -strict verification. The [current `0.1.6` receipt](docs/BOOTSTRAP.md#current-verified-016-release) +strict verification. The [historical `0.1.6` receipt](docs/BOOTSTRAP.md#current-verified-016-release) records the later verified metadata compatibility release. Read batching establishes no universal backend query or CPU budget. Neither registry publication nor synthetic proof satisfies real host acceptance or approves activation. diff --git a/docs/AGENT_API.md b/docs/AGENT_API.md index 0339aab..40fee25 100644 --- a/docs/AGENT_API.md +++ b/docs/AGENT_API.md @@ -12,7 +12,7 @@ in [`0.1.4`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4). All four synchronized `0.1.5` packages have completed verified trusted publication for answering read batching; see the [retained receipt](BOOTSTRAP.md#current-verified-015-release). The current verified -release is [`0.1.6`](BOOTSTRAP.md#current-verified-016-release). The `0.1.7` candidate +release is [`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). The `0.1.8` candidate remains unpublished. Changed source requires its own review and current-head gates. Agent Access's verified public `0.1.1` producer prerequisite is closed; see the diff --git a/docs/AGENT_WORKFLOW.md b/docs/AGENT_WORKFLOW.md index d1da881..92c1e7a 100644 --- a/docs/AGENT_WORKFLOW.md +++ b/docs/AGENT_WORKFLOW.md @@ -1,8 +1,8 @@ # Agent authoring and test-evidence workflow The current verified Knowledge Base release is -[`0.1.6`](BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. The [merged KB-04 source](https://github.com/pegma-dev/knowledge-base/pull/5) adds optional authoring transports over the existing Knowledge Base diff --git a/docs/BOOTSTRAP.md b/docs/BOOTSTRAP.md index 88c883a..d619428 100644 --- a/docs/BOOTSTRAP.md +++ b/docs/BOOTSTRAP.md @@ -7,13 +7,13 @@ The maintainer owns npm publication and external configuration. All four KB 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.6`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6); Agent Access +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7); 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`, `0.1.3`, `0.1.4` and `0.1.5` receipts remain below as history. The answering read-batching `0.1.5` release completed its own review, current-head gates, trusted publication and strict -registry/consumer qualification. The [current `0.1.6` receipt](#current-verified-016-release) -records the later MCP metadata compatibility release. The `0.1.7` source candidate +registry/consumer qualification. The [retained `0.1.6` receipt](#current-verified-016-release) +records the MCP metadata compatibility release. The `0.1.8` source candidate remains unpublished and requires its own current-head gates and release. Host dependency adoption and acceptance remain separate. @@ -88,7 +88,25 @@ the approved dependency set or establishes real-host acceptance. ## Verified Knowledge Base release -### Current verified `0.1.6` release +### Verified `0.1.7` release + +All four synchronized [`0.1.7` packages](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7) +completed exact-registry-byte, native signature, source-provenance and clean +consumer verification. Signed source is `27074b8bba76817ea6960606cf29d8fc239943b0`, +with annotated tag object `8cd14438d9dbff78eb0e1db288cfa09741e12e99`. The +[successful attempt 5](https://github.com/pegma-dev/knowledge-base/actions/runs/43271542639/attempts/5) +verified four identical existing packages and uploaded zero versions. Original +physical writers were attempts 1 through 4. The original preparation artifact +`13969137667` has ZIP SHA-256 +`c683fb87be0351ce75d6a99921b5e4428c501f39e22cf6ce04aeba6ad962b75c`; +its manifest SHA-256 is +`514cbf58b297dd73939dc37d833254edfc39de561cd40f525717947d06491116`. +The release adds the canonical receipt to the staff report view. Its original +package bytes and prior release receipts retain their identities. + + + +### Historical verified `0.1.6` release All four synchronized KB `0.1.6` packages completed exact-registry-byte, native signature, authenticated source-provenance and clean-consumer verification at @@ -508,11 +526,11 @@ 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 current KB release is `0.1.6` with exact internal dependency +The synchronized current verified KB release is `0.1.7` with exact internal dependency pins. Any changed source needs its own review and current-head gates before a new release. The historical first advertised trusted release is `0.1.1`; its receipt and those for `0.1.2` through `0.1.5` remain above alongside the -current verified `0.1.6` receipt. +retained verified `0.1.6` receipt and the `0.1.7` release. 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 @@ -528,6 +546,6 @@ 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` receipt -remains historical; KB `0.1.6` and Agent Access `0.1.1` public producer release +remains historical; KB `0.1.7` and Agent Access `0.1.1` public producer release prerequisites are closed. Both hosts still require their retained actual login/Admin-consent/client/staging acceptance. diff --git a/docs/COLLECTIONS.md b/docs/COLLECTIONS.md index a4bd011..8af2479 100644 --- a/docs/COLLECTIONS.md +++ b/docs/COLLECTIONS.md @@ -1,8 +1,8 @@ # Declared collections and durable layout The current verified Knowledge Base release is -[`0.1.6`](BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. ## Design status diff --git a/docs/EVIDENCE_REPORTS.md b/docs/EVIDENCE_REPORTS.md index 485d6be..a0c83fd 100644 --- a/docs/EVIDENCE_REPORTS.md +++ b/docs/EVIDENCE_REPORTS.md @@ -1,8 +1,8 @@ # Human-reviewed evidence reports The current verified Knowledge Base release is -[`0.1.6`](BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. `createKnowledgeEvidenceReports` shipped in the four synchronized, verified [`0.1.3` packages](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3). @@ -131,6 +131,52 @@ intact. This source change establishes no universal Workers Free 50-query, CPU or wall-clock guarantee. Complete host invocations, real authorities, supported histories, retries and cold composition require their own measured acceptance. +## Optional report observations (`0.1.8` candidate) + +The unpublished `0.1.8` candidate adds `reports.observations` when the factory +receives the actual `authoringContext` pair. Legacy factories keep this property +absent. Existing `read`, owner-only `status`, decisions and the verifier retain +their contracts. + +`observe(access, { articleId, ledgerEpoch, reportId })` returns +`{ view, context, observation }` for a confirmed report. The view has the existing +`KnowledgeReportView` shape. The context contains the actual governed draft, +narrow requirements and complete current accepted evidence/revocation history. +The configured human confirmation permission, draft/evidence reading and either +evidence-submit or draft-write authority remain required. Current staff authority +is checked again after all private reads before disclosure. + +Treat the returned data as provisional until +`confirm(access, observation, verification?)` finishes. Its opaque handle belongs +to that report instance, exact effective actor and one operation. A clone or +another instance is invalid. A wrong actor cannot consume the original handle. +An actual confirmation consumes it before awaited work, including failed probes; +start a fresh observation after failure. Returned data is detached from the +retained observation, so changing a view cannot change its binding. Keep handles +out of wire DTOs, storage, command fingerprints and retained receipts. + +The confirmation checks the real KB authoring resource versions before its +closing report read. Fresh actor and reviewer authority are checked in a settled +read-only wave with the exact report row. The observed reviewer authority and +report version must still match. The ledger head is the final data await, fencing +reset, resetting state and changed raw head versions. These separate observations +establish bounded freshness across collections; they hold no atomic lock. + +The result is `{ receipt, attestation }`. Without `verification`, attestation is +`null`. A trusted host may supply the existing `EvidenceVerificationRequest` for +the actual original submitter. The method reuses the legacy verifier's receipt, +whole submission, article, configuration, revocation and freshness predicates +against the already-observed real context. Current original-owner evidence-submit +authority remains required. Another staff reader can confirm a private read while +owner-only status and attestation remain bound to the submitter. Hosts continue +to obtain privileged current governance through their existing intrinsic port; +the new context exposes the existing narrow requirements DTO only. + +The pair adds no durable row, scope, tool, credential or host session check. Hosts +retain their current credential, Support/source/product and precommit/ACK fences. +Query count and CPU acceptance require complete physical host measurements with +the actual read scheduling and authority callbacks. + ## Submit, review, then qualify evidence `report(access, input)` accepts `SubmitKnowledgeReportInput`: `commandId`, diff --git a/docs/HOST_COMPOSITION.md b/docs/HOST_COMPOSITION.md index b5450e5..116f503 100644 --- a/docs/HOST_COMPOSITION.md +++ b/docs/HOST_COMPOSITION.md @@ -1,8 +1,8 @@ # Application and retrieval host composition The current verified Knowledge Base release is -[`0.1.6`](BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. ## Status and ownership @@ -220,6 +220,17 @@ requirements operation; legacy report trios retain their fallback. It returns no draft body, private evidence, report details, reviewer or provenance. See [evidence reports](EVIDENCE_REPORTS.md) for composition and exact privacy rules. +The unpublished `0.1.8` report observation capability reuses the real +evidence-bearing authoring context within one operation. Its private view remains +provisional until the paired confirmation checks resource versions, current +actor/reviewer authority, the exact report and final ledger head. Keep the +original effective caller and the host's current credential, governance, +Support/source/product and commit/ACK guards. A different staff reader receives +no submitter-bound verifier authority. The +[report contract](EVIDENCE_REPORTS.md#optional-report-observations-018-candidate) +defines the instance-bound, single-use handle and legacy fallback. Real host +query and CPU profiles remain pending acceptance work. + These are finite current observations across separate partitions, not a global snapshot or policy lock. Evidence qualification, exact review/publication and host credential freshness remain independent checks. Private record keys are diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 11bca9f..e3748fe 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -66,7 +66,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.6` +independently retained digests. The qualified release versions are KB `0.1.7` 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. @@ -103,24 +103,35 @@ signature, source-provenance and clean-consumer verification. Existing release receipts, tag links and tarballs retain their original identities. Host and native-client acceptance remain separately gated. -## Unpublished 0.1.7 candidate +## Verified 0.1.7 release -All four source package versions and exact internal pins are synchronized at -`0.1.7`. The candidate adds the required `receipt: string` to the existing staff +All four released package versions and exact internal pins were synchronized at +`0.1.7`. The release added the required `receipt: string` to the existing staff `KnowledgeReportView` for its authenticated canonical report receipt. The read refuses observed concurrent report or ledger changes before returning the view. A host can associate the receipt with Support test results after refreshing the governed KB context and checking exact accepted evidence and revocation DTOs through authorized public reads. Actual receipt verification and owner-only status remain bound to the original submitter. These host association checks -leave existing KB evidence acceptance unchanged. The candidate adds no tool, +leave existing KB evidence acceptance unchanged. The release adds no tool, scope, role or durable state. -The current qualified release remains `0.1.6`. Combined candidate source requires -current-head Node 22 and 24 gates, review, signed-tag preparation, trusted -publication and strict complete-set registry verification before adoption. -Host and native-client acceptance remain separately gated. Read the -[application upgrade note](../packages/application/README.md#unpublished-017-candidate) for the receipt boundary and synchronized graph. +The [qualified `0.1.7` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7) completed trusted +publication and strict complete-set registry and consumer verification. Host and +native-client acceptance remain separate. Read the +[application upgrade note](../packages/application/README.md#verified-017-release) +for the receipt boundary and synchronized graph. + +## Unpublished 0.1.8 candidate + +All four source versions and internal pins are synchronized at `0.1.8`. The +optional operation-local [report observation pair](EVIDENCE_REPORTS.md#optional-report-observations-018-candidate) +reuses the real governed context and confirms its resources, report, ledger and +current authorities. It adds no wire operation, scope, durable row or migration. +The candidate requires current-head Node 22 and 24 gates, configured review, +signed-tag preparation, trusted publication and complete-set registry verification +before public adoption. Host query and CPU profiles remain measured acceptance +work. ## Repository and development artifact gates diff --git a/docs/RETRIEVAL.md b/docs/RETRIEVAL.md index acbf499..d2fc022 100644 --- a/docs/RETRIEVAL.md +++ b/docs/RETRIEVAL.md @@ -1,8 +1,8 @@ # KB-03 bounded retrieval The current verified Knowledge Base release is -[`0.1.6`](BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. ## Design status diff --git a/docs/SOURCE_PREPARATION.md b/docs/SOURCE_PREPARATION.md index c91ecd6..4711fc5 100644 --- a/docs/SOURCE_PREPARATION.md +++ b/docs/SOURCE_PREPARATION.md @@ -1,8 +1,8 @@ # KB-05 source preparation The current verified Knowledge Base release is -[`0.1.6`](BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. ## Scope and readiness diff --git a/examples/agent/README.md b/examples/agent/README.md index b98d018..32d2eb8 100644 --- a/examples/agent/README.md +++ b/examples/agent/README.md @@ -1,8 +1,8 @@ # Packed local agent protocol proof The current verified Knowledge Base release is -[`0.1.6`](../../docs/BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. Run `pnpm run agent:proof` from the repository after `pnpm install --frozen-lockfile`, on Node 22.6+ or Node 24. npm must be diff --git a/examples/composition/README.md b/examples/composition/README.md index 61da573..ea17dd0 100644 --- a/examples/composition/README.md +++ b/examples/composition/README.md @@ -1,8 +1,8 @@ # Fictional Knowledge Base composition The current verified Knowledge Base release is -[`0.1.6`](../../docs/BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. This runnable Node example uses public package entry points and Storage Core's real memory Store. It demonstrates authoring, bound synthetic verification diff --git a/package.json b/package.json index a9a87ec..0379b50 100644 --- a/package.json +++ b/package.json @@ -34,11 +34,11 @@ "@cloudflare/workers-types": "5.20260730.1", "@modelcontextprotocol/sdk": "1.32.2", "@pegma/authorization-core": "0.4.0", - "@pegma/knowledge-base-application": "0.1.7", + "@pegma/knowledge-base-application": "0.1.8", "@pegma/knowledge-base-application-previous": "npm:@pegma/knowledge-base-application@0.1.1", - "@pegma/knowledge-base-contracts": "0.1.7", - "@pegma/knowledge-base-core": "0.1.7", - "@pegma/knowledge-base-mcp": "0.1.7", + "@pegma/knowledge-base-contracts": "0.1.8", + "@pegma/knowledge-base-core": "0.1.8", + "@pegma/knowledge-base-mcp": "0.1.8", "@pegma/spine": "0.1.2", "@pegma/storage-azure-tables": "0.4.0", "@pegma/storage-cloudflare-d1": "0.4.6", diff --git a/packages/application/README.md b/packages/application/README.md index 90f9eae..0ba5252 100644 --- a/packages/application/README.md +++ b/packages/application/README.md @@ -24,7 +24,7 @@ The synchronized answering read-batching `0.1.5` release has completed verified trusted publication; see its [release receipt](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.5). The current verified synchronized release is -[`0.1.6`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6). +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). Changed source still requires its own review and current-head gates. Backend query and CPU budgets require actual host measurements. These source README corrections apply to a future release. Published `0.1.5` tarballs, including @@ -197,9 +197,9 @@ no populated-namespace detection, layout switch or migration is automatic. The factory adds no agent scope, MCP tool, role, login, scheduler or provenance bridge. Hosts retain exact-publication and activation prerequisites. -### Unpublished 0.1.7 candidate +### Verified 0.1.7 release -The candidate adds required `readonly receipt: string` to the existing staff +The `0.1.7` release adds required `readonly receipt: string` to the existing staff `KnowledgeReportView` for pending, confirmed and rejected reads. It returns the authenticated canonical receipt from the same current report snapshot as its generation, hash and confirmation. Confirmation preserves the receipt, @@ -215,14 +215,31 @@ and owner-only status remain bound to the original submitter. Staff and resource read guards, the five agent operations, scopes, roles and durable report state remain unchanged. -The verified [`0.1.6` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6) -remains the released graph. Combined `0.1.7` source requires its current-head -Node 22 and 24 gates, review and complete release verification before adoption. -Then align all four exact package versions together. Existing external pins and +The verified [`0.1.7` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7) +is the released graph. Align all four exact package versions together. Existing external pins and the previous application writer at `0.1.1` remain unchanged. The extension requires no data migration. Host acceptance and activation remain separately gated, and existing release receipts and artifact bytes retain their identities. +### Unpublished 0.1.8 report observation candidate + +With a real `authoringContext` pair, the report factory exposes optional +`observations.observe(access, key)` and `observations.confirm(access, handle, +verification?)`. The first returns the existing private report view, complete +current evidence-bearing context and an instance-bound, single-use handle. It +checks current staff authority after its private reads. Treat the data as +provisional until confirmation finishes. The confirmation rechecks real KB +resource versions, fresh actor/reviewer authority, the exact report row and the +final ledger head. Its optional original-owner verification request reuses the +legacy verifier predicates and returns the same attestation without reloading +the context. Other staff readers receive no owner-verifier authority. + +Keep this pair inside one operation and application/report instance. Handles +cannot be cloned, serialized, persisted or reused after an attempted confirmation. +The [source contract](https://github.com/pegma-dev/knowledge-base/blob/main/docs/EVIDENCE_REPORTS.md#optional-report-observations-018-candidate) +describes failure and host ownership. This unpublished candidate adds no durable +state, MCP tool or scope. Actual host query/CPU acceptance is pending. + ## Bounded retrieval and repair `listPortalCollections` and `searchPublishedArticles` require current portal @@ -285,6 +302,106 @@ authorization cache and do not establish Workers Free quota acceptance. The `0.1.5` trusted release is complete; changed-source gates and whole-host measurements remain separate. +## Background published comparisons + +`publishedSearchObservations` is a bounded staff-authoring capability for a host +queue, timer, or deferred checker. Do not invoke its catalogue work in portal +search, answering, or another inline request path. It requires current +`draftRead` **and** `articleRead`, the permissions already held by the intrinsic +learning-draft service. It needs no customer audience permission, ambient role, +`collectionRead`, `botRead`, `indexManage`, or administrative grant. At least one +collection channel must be enabled. Private permission audiences and bot-only +collections remain valid staff comparison targets. + +This is a separate use from customer browsing and answering. Existing +`searchPublishedArticles` and `getPublishedArticle` retain their portal checks; +bot retrieval retains its independent bot permission and audience. The shared +publication checker uses an internal authoring purpose with the same exact +approval, policy, retained evidence, source eligibility, and current-resource +fences. A staff read never creates a portal browse permission. No route, MCP +tool, credential scope, permission name, publication capability, or schema is +added. + +`observe(access, { collectionId, query, applicability, limit })` returns a +`complete` result containing matching approved `PublishedArticleDto` values, an +opaque observation, and the actual `scopeState`. An authorized scope with no +matches may have an empty array. Matching uses the exact collection and +applicability tuple and normalized lexical terms from approved titles, +summaries, and tags; it is not a semantic or global duplicate search. Instance +query character/term limits are checked before I/O. Explicit `null` limits and +other invalid input throw rather than becoming defaults. A result limit that +would omit a match yields `partial` with no articles. + +The authoritative layout has no per-collection membership index. This background +fallback therefore scans **all physical KB records**, using actual backend +continuations in pages of at most eight records. The page count is also bounded; +every history, private, duplicate, and nonmatching row is charged before +filtering, and an empty page still costs read work. The existing per-record +native estimate and fixed 7.2 MB page allowance bound materialized native payload +independently from the total row count. Only bounded keys, opaque versions, and +head IDs survive between pages; full page payloads are released before advancing. +This is not a measured heap, CPU, or backend allocation guarantee. + +Each scan pass has a hard 256-physical-row limit and shares the original request +read allowance with all publication checks and the second pass. Reaching the +row/work/page bound with a continuation yields `partial`; no possible 257th row +is fetched as a probe. Consequently an adapter that emits a speculative cursor +at exactly 256 rows can conservatively hold, even when its next page would be +empty. A terminal `null` cursor is required for completion. A full page alone +never proves that no rows remain. There is no new collection, projection index, +query filter, or adapter API. + +After current publication/source and collection-version checks, a second +completed bounded pass must return the same physical key/version membership. +Observed changes, including unrelated writes, invalidate the comparison. +These completed scan cycles and resource checks provide bounded observations +and change detection, not an atomic cross-partition snapshot or a guarantee +against concurrent/future membership changes. Large or actively changing stores +can remain held and need a later host-owned background strategy. No universal +query/CPU or Workers Free acceptance is claimed. + +`readScope(access, { collectionId })` performs only bounded keyed collection +reads under the same authoring permissions. It returns +`{ collectionId, generation, scopeHash }`, derived from the actual collection +generation, opaque backend head version, and current policy digest. A second +versioned collection read fences asynchronous hashing/public-approval validation. +It returns no policy, audience, approval actor, or staff metadata. Complete +`observe` results compute the same `PublishedSearchScopeState` from their already +read collection. Bind it into the private comparison receipt and recheck it for +later policy/authority checks, including an empty result, without another scan. +Keep it outside model payloads. This state is collection authority, not a fresh +catalogue search; a new article alone need not change it, and it proves no current +or future absence of additional matches. + +`readArticle(access, { articleId })` returns only the current approved +`PublishedArticleDto` through the same authoring publication checker. It uses +keyed reads and no enumeration, including for a bot-only or private-audience +collection. Current private draft text, proof history, and provenance are not +projected. Missing, retired, held, source-ineligible, or policy-invalid +publications cannot produce an article. This method supports later checks of +retained comparison resources without switching to a customer portal read. + +Keep the opaque observation in RAM for one bounded background operation on the +same application instance. `confirm(access, observation)` consumes it before its +first await, rechecks the same actor's current authoring permissions, repeats +current scope/publication/source checks and the bounded membership comparison, +and rejects changed observations. A clone, another instance/actor, reuse, +partial recheck, or dependency failure cannot confirm it. The host owns operation +deadlines and fresh access resolution. Neither method grants review/publication +authority or locks articles. + +Known capacity/work limits return content-free `partial`; ordinary authority or +storage availability failures return content-free `unavailable` from `observe`. +Keyed reads and confirmation throw on refusal. Integrity and unexpected +programming faults remain visible to background operators instead of becoming +normal unavailability. No article subset or private diagnostic fields are added +to failure DTOs; hosts must keep operational logs safe. + +The current factory always constructs this capability. Its type stays optional +for structural legacy applications and wrappers; it is not a configurable +factory opt-out. A missing legacy port cannot be replaced by caller-supplied +empty comparison results. + ## Storage and limits All accepted head changes, immutable rows, generic Audit actions, receipts, and diff --git a/packages/application/package.json b/packages/application/package.json index 0c2bb56..e873592 100644 --- a/packages/application/package.json +++ b/packages/application/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-application", - "version": "0.1.7", + "version": "0.1.8", "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.7", - "@pegma/knowledge-base-core": "0.1.7", + "@pegma/knowledge-base-contracts": "0.1.8", + "@pegma/knowledge-base-core": "0.1.8", "@pegma/spine": "0.1.2", "@pegma/storage-core": "0.4.0" }, diff --git a/packages/application/src/evidence-reports-types.ts b/packages/application/src/evidence-reports-types.ts index 2b5c2f7..ff7306e 100644 --- a/packages/application/src/evidence-reports-types.ts +++ b/packages/application/src/evidence-reports-types.ts @@ -5,6 +5,7 @@ import type { IsoTimestamp, Logger, PrincipalId, + VerificationEvidence, } from "@pegma/knowledge-base-contracts"; import type { EvidenceSubmission } from "@pegma/knowledge-base-core"; import type { Store } from "@pegma/storage-core"; @@ -13,6 +14,7 @@ import type { KnowledgeBaseApplication, EvidenceDto, EvidenceVerifier, + EvidenceVerificationRequest, ValidationRequirementsDto, } from "./types.js"; @@ -110,6 +112,41 @@ export interface KnowledgeReportKey extends KnowledgeReportArticleInput { readonly reportId: string; } +declare const reportObservationBrand: unique symbol; +/** Single-use, instance-bound read observation. Keep it inside one operation. */ +export interface KnowledgeReportObservation { + readonly [reportObservationBrand]: true; +} + +export interface KnowledgeReportObservationRead { + /** Provisional private data; await confirm before using it as a current binding. */ + readonly view: KnowledgeReportView; + readonly context: KnowledgeEvidenceContext; + readonly observation: KnowledgeReportObservation; +} + +export interface KnowledgeReportObservationConfirmation { + readonly receipt: string; + /** Present only when the optional original-owner verification request succeeds. */ + readonly attestation: VerificationEvidence["attestation"] | null; +} + +/** Optional paired reads, available only with the real authoringContext pair. */ +export interface KnowledgeReportObservations { + observe( + access: AccessContext, + input: KnowledgeReportKey, + ): Promise; + /** Confirms exact KB resources/report/head and current actor/reviewer authority. + * The handle is consumed before awaited work, including a failed confirmation. + * An optional verification request retains the legacy verifier's owner binding. */ + confirm( + access: AccessContext, + observation: KnowledgeReportObservation, + verification?: EvidenceVerificationRequest, + ): Promise; +} + export interface SubmitKnowledgeReportInput extends KnowledgeReportArticleInput { readonly commandId: string; readonly ledgerEpoch: number; @@ -171,6 +208,7 @@ export interface KnowledgeEvidenceReportsOptions { export interface KnowledgeEvidenceReports { readonly verifier: EvidenceVerifier; + readonly observations?: KnowledgeReportObservations; query( access: AccessContext, input: KnowledgeReportQueryInput, diff --git a/packages/application/src/evidence-reports.ts b/packages/application/src/evidence-reports.ts index e50889a..22f5c18 100644 --- a/packages/application/src/evidence-reports.ts +++ b/packages/application/src/evidence-reports.ts @@ -16,6 +16,7 @@ import { import { defineCollection, type EntityKey } from "@pegma/storage-core"; import type { EvidenceVerifier, + EvidenceVerificationRequest, KnowledgeAuthoringContextObservation, } from "./types.js"; import type { @@ -28,6 +29,10 @@ import type { KnowledgeEvidenceReportStorageLayout, KnowledgeEvidenceReportsOptions, KnowledgeEvidenceReports, + KnowledgeReportView, + KnowledgeReportObservation, + KnowledgeReportObservationConfirmation, + KnowledgeReportObservations, } from "./evidence-reports-types.js"; import { KnowledgeEvidenceReportsError, @@ -728,18 +733,17 @@ export function createKnowledgeEvidenceReports( function now(): string { return stored("clock_read", () => timestamp(options.clock.now())); } - async function current( - access: AccessContext, - permission: string, - ): Promise { - const caller = callerContext(access); + async function resolvePrincipal(id: string): Promise { const resolved = await ledgerIo("principal_resolve", () => - options.resolvePrincipal(caller.principalId), + options.resolvePrincipal(id), ); - const authority = - resolved === null - ? null - : stored("principal_resolve", () => callerContext(resolved)); + return resolved === null + ? null + : stored("principal_resolve", () => callerContext(resolved)); + } + async function currentAuthority(access: AccessContext, permission: string) { + const caller = callerContext(access); + const authority = await resolvePrincipal(caller.principalId); if ( authority === null || authority.principalId !== caller.principalId || @@ -750,11 +754,14 @@ export function createKnowledgeEvidenceReports( throw new KnowledgeEvidenceReportsError("forbidden"); // A current owner/Admin context establishes continued authority; it never // replaces the original credential's restricted effective permissions. - return caller; + return { caller, authority }; } - async function staff(access: AccessContext): Promise { - access = await current(access, confirmationPermission); + async function current(access: AccessContext, permission: string) { + return (await currentAuthority(access, permission)).caller; + } + function staffPermissions(access: AccessContext): void { for (const permission of [ + confirmationPermission, knowledgePermissions.draftRead, knowledgePermissions.evidenceRead, ]) @@ -767,8 +774,24 @@ export function createKnowledgeEvidenceReports( !hasPermission(access, knowledgePermissions.draftWrite) ) throw new KnowledgeEvidenceReportsError("forbidden"); + } + async function staff(access: AccessContext): Promise { + access = await current(access, confirmationPermission); + staffPermissions(access); return access; } + async function staffAuthority(access: AccessContext) { + const resolved = await currentAuthority(access, confirmationPermission); + staffPermissions(resolved.caller); + return resolved; + } + async function reviewerAuthority(id: string): Promise { + const reviewer = await resolvePrincipal(id); + if (reviewer === null || reviewer.principalId !== id) + throw new KnowledgeEvidenceReportsError("forbidden"); + staffPermissions(reviewer); + return reviewer; + } async function headVersion(articleId: string) { const saved = await ledgerIo("head_read", () => records.getVersioned(storageKey(articleId, "head")), @@ -1041,6 +1064,219 @@ export function createKnowledgeEvidenceReports( Date.parse(report.confirmation.confirmedAt) <= now)) ); } + async function verificationIdentityMatches( + report: ReportRecord, + request: EvidenceVerificationRequest, + ): Promise { + return ( + acknowledgement(report).receipt === request.receipt && + report.status === "confirmed" && + report.confirmation !== null && + request.access.principalId === report.submittedBy && + (await knowledgeDigest(request.submission)) === report.submissionHash && + request.configuration.trustedAttesterIds.includes( + report.confirmation.reviewerId, + ) + ); + } + async function verificationContextMatches( + report: ReportRecord, + request: EvidenceVerificationRequest, + value: KnowledgeEvidenceContext, + ): Promise { + return ( + (await valid(report, request.article, value, now())) && + request.configuration.expectedStagingBuildId === + value.requirements.expectedStagingBuildId && + (await knowledgeDigest(request.configuration.validationPolicy)) === + (await knowledgeDigest(value.requirements.validationPolicy)) + ); + } + function fulfilled(result: PromiseSettledResult): T { + if (result.status === "rejected") throw result.reason; + return result.value; + } + interface ReportObservationState { + readonly access: AccessContext; + readonly reviewer: AccessContext; + readonly head: Awaited>; + readonly report: Awaited>; + readonly context: KnowledgeEvidenceContext; + readonly contextObservation: KnowledgeAuthoringContextObservation; + } + const reportObservations = new WeakMap(); + const observations = Object.freeze({ + async observe(access, value) { + const input = exactObject(requestData(value), [ + "articleId", + "ledgerEpoch", + "reportId", + ]); + const articleId = scalar(input.articleId); + const epoch = positive(input.ledgerEpoch); + const reportId = scalar(input.reportId); + const initial = await staffAuthority(access); + access = initial.caller; + // Start only independent read observations together. Every result settles + // before a refusal; error precedence is head, report, context. + const reportRead = observedReport(articleId, epoch, reportId); + const results = await Promise.allSettled([ + headVersion(articleId), + reportRead, + observeContext(access, articleId, true), + ]); + const head = fulfilled(results[0]); + if (head.value.ledgerEpoch !== epoch) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (head.value.status !== "active") + throw new KnowledgeEvidenceReportsError("ledger_resetting"); + const observed = fulfilled(results[1]); + const context = fulfilled(results[2]); + const report = observed.value; + if ( + report.status !== "confirmed" || + report.confirmation === null || + context.observation === undefined || + !(await valid( + report, + context.value.draft.revision, + context.value, + now(), + )) + ) + throw new KnowledgeEvidenceReportsError("report_not_verifiable"); + const reviewBindingHash = await knowledgeDigest({ + report, + context: context.value, + }); + const view: KnowledgeReportView = { + ...summary(report), + receipt: acknowledgement(report).receipt, + evidence: report.evidence, + report: report.report, + draft: context.value.draft, + reportHash: report.reportHash, + submissionHash: report.submissionHash, + governanceHash: report.governanceHash, + requirements: context.value.requirements, + reviewBindingHash, + expectedReportGeneration: report.reportGeneration, + confirmation: report.confirmation, + }; + // Private data is disclosed only after another current staff observation. + // Report/context currency is provisional until this handle is confirmed. + // Resolve the initial reviewer here, alongside the closing actor, after + // the private reads/hashes. The later confirm still resolves both afresh. + const actorRead = staffAuthority(access); + const reviewerRead = + report.confirmation.reviewerId === access.principalId + ? actorRead.then((value) => value.authority) + : reviewerAuthority(report.confirmation.reviewerId); + const authorities = await Promise.allSettled([actorRead, reviewerRead]); + fulfilled(authorities[0]); + const reviewer = fulfilled(authorities[1]); + staffPermissions(reviewer); + const observation = Object.freeze({}) as KnowledgeReportObservation; + reportObservations.set(observation, { + access, + reviewer, + head, + report: observed, + context: context.value, + contextObservation: context.observation, + }); + return { ...snapshotData({ view, context: context.value }), observation }; + }, + async confirm(access, observation, verification) { + access = callerContext(access); + const captured = + observation !== null && typeof observation === "object" + ? reportObservations.get(observation) + : undefined; + if (captured === undefined) + throw new KnowledgeEvidenceReportsError("invalid_request"); + if ( + serializeAccessContext(access) !== + serializeAccessContext(captured.access) + ) + throw new KnowledgeEvidenceReportsError("forbidden"); + // No await precedes consumption. Cloned/foreign handles and a different + // actor cannot consume the original handle; every actual attempt does. + reportObservations.delete(observation); + verification = + verification === undefined ? undefined : requestData(verification); + const report = captured.report.value; + let attestation: KnowledgeReportObservationConfirmation["attestation"] = + null; + if ( + !(await valid( + report, + captured.context.draft.revision, + captured.context, + now(), + )) + ) + throw new KnowledgeEvidenceReportsError("report_not_verifiable"); + if (verification !== undefined) { + let matches = false; + try { + const owner = callerContext(verification.access); + matches = + owner.principalId === access.principalId && + hasPermission(owner, knowledgePermissions.evidenceSubmit) && + owner.permissions.every((grant) => hasPermission(access, grant)) && + (await verificationIdentityMatches(report, verification)) && + (await verificationContextMatches( + report, + verification, + captured.context, + )); + } catch (error) { + if (error instanceof KnowledgeEvidenceReportsUnavailableError) + throw error; + } + if (!matches || report.confirmation === null) + throw new KnowledgeEvidenceReportsError("report_not_verifiable"); + attestation = { + id: acknowledgement(report).receipt, + verifiedBy: report.confirmation.reviewerId, + verifiedAt: report.confirmation.confirmedAt, + }; + } + // This exact KB resource check must complete before the closing report + // read. Fresh actor/reviewer observations then share one read-only wave. + await confirmContext(access, captured.contextObservation); + const actorRead = staffAuthority(access); + const reviewerRead = + captured.reviewer.principalId === access.principalId + ? actorRead.then((value) => value.authority) + : reviewerAuthority(captured.reviewer.principalId); + const results = await Promise.allSettled([ + actorRead, + reviewerRead, + observedReport(report.articleId, report.ledgerEpoch, report.reportId), + ]); + fulfilled(results[0]); + const reviewer = fulfilled(results[1]); + staffPermissions(reviewer); + if ( + serializeAccessContext(reviewer) !== + serializeAccessContext(captured.reviewer) + ) + throw new KnowledgeEvidenceReportsError("forbidden"); + if (fulfilled(results[2]).version !== captured.report.version) + throw new KnowledgeEvidenceReportsError("report_changed"); + // The head is the final data await. No cross-collection lock is promised. + const head = await headVersion(report.articleId); + if (head.value.ledgerEpoch !== report.ledgerEpoch) + throw new KnowledgeEvidenceReportsError("ledger_epoch_changed"); + if (head.value.status !== "active") + throw new KnowledgeEvidenceReportsError("ledger_resetting"); + if (head.version !== captured.head.version) + throw new KnowledgeEvidenceReportsError("ledger_changed"); + return { receipt: acknowledgement(report).receipt, attestation }; + }, + }); async function replay( articleId: string, epoch: number, @@ -1191,15 +1427,8 @@ export function createKnowledgeEvidenceReports( load(request.article.articleId, epoch, reportId), ]); if ( - report.receiptGeneration !== cycle || - report.status !== "confirmed" || report.confirmation === null || - request.access.principalId !== report.submittedBy || - (await knowledgeDigest(request.submission)) !== - report.submissionHash || - !request.configuration.trustedAttesterIds.includes( - report.confirmation.reviewerId, - ) + !(await verificationIdentityMatches(report, request)) ) return null; const confirmation = report.confirmation; @@ -1219,13 +1448,7 @@ export function createKnowledgeEvidenceReports( ) return null; const value = await context(reviewer, report.articleId); - if ( - !(await valid(report, request.article, value, now())) || - request.configuration.expectedStagingBuildId !== - value.requirements.expectedStagingBuildId || - (await knowledgeDigest(request.configuration.validationPolicy)) !== - (await knowledgeDigest(value.requirements.validationPolicy)) - ) + if (!(await verificationContextMatches(report, request, value))) return null; await current(request.access, knowledgePermissions.evidenceSubmit); await staff(reviewer); @@ -1267,6 +1490,7 @@ export function createKnowledgeEvidenceReports( }; return Object.freeze({ verifier, + ...(authoringContext === undefined ? {} : { observations }), async query(access, input) { input = requestData(input); access = await current(access, knowledgePermissions.evidenceSubmit); diff --git a/packages/application/src/index.ts b/packages/application/src/index.ts index 3b01556..c3cdaf3 100644 --- a/packages/application/src/index.ts +++ b/packages/application/src/index.ts @@ -3,6 +3,7 @@ import { createGovernanceServices } from "./governance.js"; import { createReadServices } from "./reads.js"; import { createKnowledgeRepository } from "./repository.js"; import { createPublicationChecker } from "./publication.js"; +import { createPublishedSearchObservations } from "./published-search-observations.js"; import { resolveRetrievalLimits } from "./retrieval-limits.js"; import { createRetrievalMaintenanceServices } from "./retrieval-maintenance.js"; import { createRetrievalRepository } from "./retrieval-repository.js"; @@ -35,6 +36,11 @@ export function createKnowledgeBaseApplication( ); const publications = createPublicationChecker(repository, services); return Object.freeze({ + publishedSearchObservations: createPublishedSearchObservations( + options.store, + services, + retrievalLimits, + ), ...createArticleServices(repository, services), ...createGovernanceServices(repository, services), ...createReadServices(repository, services), @@ -68,6 +74,7 @@ export { } from "./storage-helpers.js"; export type * from "./types.js"; export type * from "./retrieval-types.js"; +export type * from "./published-search-observations-types.js"; export { defaultKnowledgeRetrievalLimits } from "./retrieval-types.js"; export { retrievalRecords, type RetrievalRecord } from "./retrieval-records.js"; export { knowledgePermissions } from "@pegma/knowledge-base-contracts"; diff --git a/packages/application/src/publication.ts b/packages/application/src/publication.ts index 4fa69aa..0ea103b 100644 --- a/packages/application/src/publication.ts +++ b/packages/application/src/publication.ts @@ -47,7 +47,7 @@ import type { SourceSnapshot, } from "./types.js"; -export type PublicationPurpose = "portal" | "bot" | "index"; +export type PublicationPurpose = "portal" | "bot" | "index" | "authoring"; export interface PublicationCheckRequest { readonly articleId: string; @@ -131,7 +131,10 @@ function authorize(access: AccessContext, purpose: PublicationPurpose): void { } if ( !hasPermission(access, knowledgePermissions.articleRead) || - (purpose === "bot" && !hasPermission(access, knowledgePermissions.botRead)) + (purpose === "bot" && + !hasPermission(access, knowledgePermissions.botRead)) || + (purpose === "authoring" && + !hasPermission(access, knowledgePermissions.draftRead)) ) throw unavailable(); } @@ -175,7 +178,7 @@ async function publishedEvidence( return evidence; } -/** One authority path for portal reads, customer bot retrieval, and private indexing. */ +/** One proof path for portal, bot, private indexing, and staff authoring reads. */ export function createPublicationChecker( repository: KnowledgeRepository, options: KnowledgeBaseServiceOptions, @@ -231,7 +234,7 @@ export function createPublicationChecker( const access = immutable(snapshotData(request.access)); const articleId = request.articleId; requireIdentifier(articleId, "articleId"); - if (!["portal", "bot", "index"].includes(request.purpose)) + if (!["portal", "bot", "index", "authoring"].includes(request.purpose)) throw new TypeError("Unknown publication purpose"); const purpose = request.purpose; const applicability = @@ -291,7 +294,10 @@ export function createPublicationChecker( const enabledUses: ("portal" | "bot")[] = []; if (policy.portal.enabled) enabledUses.push("portal"); if (policy.bot.enabled) enabledUses.push("bot"); - const use = purpose === "index" ? undefined : policy[purpose]; + const use = + purpose === "index" || purpose === "authoring" + ? undefined + : policy[purpose]; if (use === undefined ? enabledUses.length === 0 : !allows(use, access)) throw unavailable(); if ( @@ -404,6 +410,11 @@ export function createPublicationChecker( confirmations.set(checked, state); return checked; } catch (error) { + if ( + purpose === "authoring" && + error instanceof RepositoryIntegrityError + ) + throw error; if (purpose === "index" && error instanceof RepositoryCapacityError) throw error; if (isUnavailable(error)) throw unavailable(); @@ -416,6 +427,11 @@ export function createPublicationChecker( try { await confirm(state); } catch (error) { + if ( + state.purpose === "authoring" && + error instanceof RepositoryIntegrityError + ) + throw error; if ( state.purpose === "index" && error instanceof RepositoryCapacityError diff --git a/packages/application/src/published-search-observations-types.ts b/packages/application/src/published-search-observations-types.ts new file mode 100644 index 0000000..e0d49ea --- /dev/null +++ b/packages/application/src/published-search-observations-types.ts @@ -0,0 +1,58 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import type { SearchPublishedArticlesInput } from "./retrieval-types.js"; +import type { PublishedArticleDto } from "./types.js"; + +declare const publishedSearchObservationBrand: unique symbol; + +/** Same-instance, actor-bound, single-use background observation; never persist it. */ +export interface PublishedSearchObservation { + readonly [publishedSearchObservationBrand]: true; +} + +/** Current authorized collection identity; no policy, audience, or staff metadata. */ +export interface PublishedSearchScopeState { + readonly collectionId: string; + readonly generation: number; + readonly scopeHash: string; +} + +export type PublishedSearchObservationResult = + | { + readonly outcome: "complete"; + readonly articles: readonly PublishedArticleDto[]; + readonly scopeState: PublishedSearchScopeState; + readonly observation: PublishedSearchObservation; + } + | { + readonly outcome: "partial" | "unavailable"; + readonly articles: readonly []; + }; + +/** + * Bounded background comparison work, never portal/request-path retrieval. + * Requires current draftRead and articleRead. Staff authoring does not inherit + * customer portal/bot audiences; at least one collection channel must be enabled. + * Complete covers the exact collection, applicability and approved-metadata + * lexical query only. It establishes no global duplicate absence or lock. + */ +export interface PublishedSearchObservations { + /** Keyed scope/authority recheck only; no corpus enumeration or collectionRead. */ + readScope( + access: AccessContext, + input: { readonly collectionId: string }, + ): Promise; + /** Keyed current approved publication under the same staff authoring authority. */ + readArticle( + access: AccessContext, + input: { readonly articleId: string }, + ): Promise; + observe( + access: AccessContext, + input: SearchPublishedArticlesInput, + ): Promise; + /** Rechecks scope membership, versions, source eligibility and current authority. */ + confirm( + access: AccessContext, + observation: PublishedSearchObservation, + ): Promise; +} diff --git a/packages/application/src/published-search-observations.ts b/packages/application/src/published-search-observations.ts new file mode 100644 index 0000000..100eb30 --- /dev/null +++ b/packages/application/src/published-search-observations.ts @@ -0,0 +1,509 @@ +import type { AccessContext } from "@pegma/authorization-core"; +import { + knowledgePermissions, + type Applicability, +} from "@pegma/knowledge-base-contracts"; +import { StorageError, type ScanPage, type Store } from "@pegma/storage-core"; +import { + KnowledgeBaseAuthorizationError, + KnowledgeBaseNotFoundError, + KnowledgeBasePrerequisiteError, + requirePermission, +} from "./errors.js"; +import { normalizeQuery, scoreConfirmedArticle } from "./lexical.js"; +import { + createPublicationChecker, + type CheckedPublication, +} from "./publication.js"; +import type { + PublishedSearchObservation, + PublishedSearchObservations, + PublishedSearchScopeState, +} from "./published-search-observations-types.js"; +import { + knowledgeRecords, + maximumRecordNativeBytes, + type KnowledgeRecord, + type StoredCollection, +} from "./records.js"; +import { + createKnowledgeRepository, + type VersionedState, +} from "./repository.js"; +import { + createRetrievalReadBudget, + RetrievalBudgetError, + type RetrievalReadBudget, +} from "./retrieval-budget.js"; +import type { + KnowledgeRetrievalLimits, + SearchPublishedArticlesInput, +} from "./retrieval-types.js"; +import { + canonicalJson, + fingerprint, + RepositoryCapacityError, + RepositoryConflictError, + RepositoryIntegrityError, + requireIdentifier, + snapshotData, +} from "./storage-helpers.js"; +import type { + KnowledgeBaseServiceOptions, + PublishedArticleDto, +} from "./types.js"; + +// The authoritative layout has no per-collection membership index. This +// background-only fallback charges every physical KB record, not just matches. +const maximumPhysicalRows = 256; +// Bound native payload materialization independently from total physical work. +// Decoder/backend allocation overhead still needs actual host measurement. +const maximumPageNativeBytes = 7_200_000; +const maximumPageRows = Math.min( + 8, + Math.floor(maximumPageNativeBytes / maximumRecordNativeBytes), +); + +class PartialObservationError extends Error {} + +interface CapturedSearch { + readonly input: SearchPublishedArticlesInput; + readonly actorId: string; + readonly membership: string; + readonly articles: string; +} + +function inputSnapshot(input: T, fields: readonly string[]): T { + const value = snapshotData(input); + if ( + value === null || + typeof value !== "object" || + Array.isArray(value) || + Object.keys(value).some((key) => !fields.includes(key)) + ) + throw new TypeError( + "Published comparison input contains unsupported fields", + ); + return value; +} + +function searchInput( + request: SearchPublishedArticlesInput, + limits: KnowledgeRetrievalLimits, +) { + const input = inputSnapshot(request, [ + "collectionId", + "query", + "applicability", + "limit", + ]); + requireIdentifier(input.collectionId, "collectionId"); + if ( + typeof input.query !== "string" || + input.query.length > limits.maxQueryCharacters + ) + throw new TypeError( + "Published comparison exceeds its query character limit", + ); + const terms = normalizeQuery(input.query); + if (terms.length > limits.maxQueryTerms) + throw new TypeError("Published comparison exceeds its query term limit"); + if (terms.length === 0) + throw new TypeError("Published comparison requires a lexical search term"); + const applicability: Applicability = inputSnapshot(input.applicability, [ + "productId", + "productVersion", + "buildId", + "locale", + ]); + requireIdentifier(applicability.productId, "applicability.productId"); + requireIdentifier( + applicability.productVersion, + "applicability.productVersion", + ); + if (Object.hasOwn(applicability, "buildId")) + requireIdentifier(applicability.buildId!, "applicability.buildId"); + if (Object.hasOwn(applicability, "locale")) + requireIdentifier(applicability.locale!, "applicability.locale"); + const limit = input.limit === undefined ? limits.maxResults : input.limit; + if (!Number.isSafeInteger(limit) || limit < 1 || limit > limits.maxResults) + throw new TypeError( + "Published comparison result limit exceeds its ceiling", + ); + return { input, terms, limit }; +} + +function authorize(access: AccessContext): void { + requireIdentifier(access.principalId, "principalId"); + requirePermission(access, knowledgePermissions.articleRead); + requirePermission(access, knowledgePermissions.draftRead); +} + +function unavailable(): KnowledgeBasePrerequisiteError { + return new KnowledgeBasePrerequisiteError("published_search_observation"); +} + +function isUnavailable(error: unknown): boolean { + return ( + error instanceof KnowledgeBaseAuthorizationError || + error instanceof KnowledgeBaseNotFoundError || + error instanceof KnowledgeBasePrerequisiteError || + error instanceof RepositoryConflictError || + error instanceof StorageError + ); +} + +function isPartial(error: unknown): boolean { + return ( + error instanceof PartialObservationError || + error instanceof RetrievalBudgetError || + error instanceof RepositoryCapacityError + ); +} + +/** Reuse current publication authority; never trust a search-provider empty list. */ +export function createPublishedSearchObservations( + store: Store, + services: KnowledgeBaseServiceOptions, + limits: KnowledgeRetrievalLimits, +): PublishedSearchObservations { + const records = store.collection(knowledgeRecords); + const observations = new WeakMap< + PublishedSearchObservation, + CapturedSearch + >(); + + function readBudget() { + return createRetrievalReadBudget(store, { + maxPhysicalReads: limits.maxRequestPhysicalGets, + maxIndexReads: limits.maxRequestPhysicalGets, + maxPostingEntries: limits.maxPostingEntries, + maxCandidateHeads: limits.maxHeadProbes, + maxConfirmations: limits.maxConfirmations, + indexCollectionName: knowledgeRecords.name, + }); + } + + async function scopeState( + access: AccessContext, + collection: VersionedState, + ): Promise { + const current = collection.value.collection; + const policy = current.policy; + authorize(access); + if (!policy.portal.enabled && !policy.bot.enabled) + throw new KnowledgeBaseNotFoundError("collection"); + const policyHash = await fingerprint(policy); + if ( + [policy.portal, policy.bot].some( + (use) => use.enabled && use.audience.kind === "anonymous", + ) + ) { + const approval = current.publicApproval; + if ( + approval === undefined || + approval.collectionId !== current.id || + approval.policyVersion !== policy.version || + approval.policyHash !== policyHash + ) + throw new KnowledgeBaseNotFoundError("collection"); + } + return { + collectionId: current.id, + generation: collection.value.generation, + scopeHash: await fingerprint({ + collectionId: current.id, + generation: collection.value.generation, + version: collection.version, + policyHash, + }), + }; + } + + async function catalogue(budget: RetrievalReadBudget) { + const membership: string[] = []; + const keys = new Set(); + const articleIds: string[] = []; + const cursors = new Set(); + let cursor: string | undefined; + let physicalRows = 0; + let pages = 0; + for (;;) { + const limit = Math.min( + maximumPageRows, + maximumPhysicalRows - physicalRows, + budget.remainingCandidateWork().physicalRows, + ); + // Empty continuation pages consume work too. Never make an unbounded + // series of empty probes or fetch a possible 257th physical record. + if (limit < 1 || pages >= maximumPhysicalRows) + throw new PartialObservationError(); + let page: ScanPage | undefined = await records.scan({ + limit, + ...(cursor === undefined ? {} : { cursor }), + }); + if (!Array.isArray(page.records) || page.records.length > limit) + throw new RepositoryIntegrityError(); + // Charge all physical records before filtering/deduplication, including + // every private/history/nonmatching row. An empty page costs one read. + budget.accountExternal({ + keyedReads: 0, + physicalRows: Math.max(1, page.records.length), + pagesRead: 1, + postingEntries: 0, + }); + physicalRows += page.records.length; + pages += 1; + for (const row of page.records) { + if ( + row.key.partition !== row.value.partition || + row.key.id !== row.value.id || + typeof row.version !== "string" || + row.version.length === 0 + ) + throw new RepositoryIntegrityError(); + const key = canonicalJson(row.key); + if (keys.has(key)) throw new RepositoryIntegrityError(); + keys.add(key); + membership.push(canonicalJson([row.key, row.version])); + if (row.value.resourceKind !== "article" || row.value.kind !== "head") + continue; + if (row.value.id !== "head") throw new RepositoryIntegrityError(); + requireIdentifier(row.value.resourceId, "articleId"); + articleIds.push(row.value.resourceId); + } + const next = page.nextCursor; + // Retain only bounded keys/versions/head IDs, never prior page payloads. + page = undefined; + if (next === null) break; + if ( + typeof next !== "string" || + next.length === 0 || + next.length > 16_384 || + cursors.has(next) + ) + throw new RepositoryIntegrityError(); + cursors.add(next); + cursor = next; + } + if (new Set(articleIds).size !== articleIds.length) + throw new RepositoryIntegrityError(); + return { + membership: canonicalJson(membership.sort()), + articleIds: articleIds.sort(), + }; + } + + async function read( + access: AccessContext, + request: SearchPublishedArticlesInput, + ) { + const { input, terms, limit } = searchInput(request, limits); + authorize(access); + const budget = readBudget(); + const repository = createKnowledgeRepository(budget.store, services.limits); + const publications = createPublicationChecker(repository, services); + const collection = await repository.readCollectionVersioned( + input.collectionId, + ); + if (collection === null) throw new KnowledgeBaseNotFoundError("collection"); + const observedScope = await scopeState(access, collection); + const initial = await catalogue(budget); + const matches: { + readonly checked: CheckedPublication; + readonly score: number; + }[] = []; + for (const articleId of initial.articleIds) { + budget.candidateHead(); + const current = + await repository.readArticlePublicationVersioned(articleId); + if (current === null) throw new RepositoryConflictError(); + const state = current.value; + const revision = state.published?.revision; + if ( + state.state === "retired" || + state.publicationHeld || + revision === undefined || + revision.collectionId !== input.collectionId || + canonicalJson(revision.applicability) !== + canonicalJson(input.applicability) + ) + continue; + // Metadata is only a local match predicate. No unconfirmed text escapes. + const score = scoreConfirmedArticle(revision, terms); + if (score === 0) continue; + budget.confirmation(); + const checked = await publications.check({ + access, + articleId, + purpose: "authoring", + applicability: input.applicability, + }); + if (checked.article.collectionId !== input.collectionId) + throw new RepositoryConflictError(); + matches.push({ checked, score }); + if (matches.length > limit) throw new PartialObservationError(); + } + matches.sort( + (left, right) => + right.score - left.score || + (left.checked.article.articleId < right.checked.article.articleId + ? -1 + : 1), + ); + const articles = snapshotData( + matches.map(({ checked }) => checked.article), + ); + const serialized = canonicalJson(articles); + if ( + new TextEncoder().encode(serialized).byteLength > limits.maxContentBytes + ) + throw new PartialObservationError(); + for (const { checked } of matches) await publications.recheck(checked); + const latestCollection = await repository.readCollectionVersioned( + input.collectionId, + ); + if (latestCollection?.version !== collection.version) + throw new RepositoryConflictError(); + // Compare a second completed bounded scan cycle after source/head checks. + // These observations are not an atomic cross-partition snapshot or lock. + const final = await catalogue(budget); + if (initial.membership !== final.membership) + throw new RepositoryConflictError(); + authorize(access); + return { + input, + articles, + serialized, + membership: final.membership, + scopeState: observedScope, + }; + } + + return Object.freeze({ + async readScope(access, request) { + access = snapshotData(access); + const input = inputSnapshot(request, ["collectionId"]); + requireIdentifier(input.collectionId, "collectionId"); + authorize(access); + try { + const repository = createKnowledgeRepository( + readBudget().store, + services.limits, + ); + const collection = await repository.readCollectionVersioned( + input.collectionId, + ); + if (collection === null) + throw new KnowledgeBaseNotFoundError("collection"); + const state = await scopeState(access, collection); + // Hashing and public-approval validation await trusted facts. Recheck + // the actual opaque C version afterwards, including empty scopes. + const latest = await repository.readCollectionVersioned( + input.collectionId, + ); + if (latest?.version !== collection.version) + throw new RepositoryConflictError(); + authorize(access); + return state; + } catch (error) { + if ( + error instanceof KnowledgeBaseAuthorizationError || + error instanceof KnowledgeBaseNotFoundError + ) + throw error; + if (isUnavailable(error) || isPartial(error)) + throw new KnowledgeBasePrerequisiteError("published_search_scope"); + throw error; + } + }, + + async readArticle(access, request) { + access = snapshotData(access); + const input = inputSnapshot(request, ["articleId"]); + requireIdentifier(input.articleId, "articleId"); + authorize(access); + try { + const repository = createKnowledgeRepository( + readBudget().store, + services.limits, + ); + const publications = createPublicationChecker(repository, services); + const checked = await publications.check({ + access, + articleId: input.articleId, + purpose: "authoring", + }); + return checked.article; + } catch (error) { + if ( + error instanceof KnowledgeBaseAuthorizationError || + error instanceof KnowledgeBaseNotFoundError + ) + throw error; + if (isUnavailable(error) || isPartial(error)) + throw new KnowledgeBasePrerequisiteError("published_search_article"); + throw error; + } + }, + + async observe(access, request) { + access = snapshotData(access); + // Invalid requests throw; dependency, authority and capacity outcomes do + // not disclose any confirmed subset, candidate count or private material. + const { input } = searchInput(request, limits); + try { + const result = await read(access, input); + const observation = Object.freeze({}) as PublishedSearchObservation; + observations.set(observation, { + input: result.input, + actorId: access.principalId, + membership: result.membership, + articles: result.serialized, + }); + return { + outcome: "complete", + articles: result.articles, + scopeState: result.scopeState, + observation, + }; + } catch (error) { + if (isPartial(error)) return { outcome: "partial", articles: [] }; + if (isUnavailable(error)) + return { outcome: "unavailable", articles: [] }; + // Background operators must see integrity/programming faults. No + // article subset or private diagnostic fields are returned in DTOs. + throw error; + } + }, + async confirm(access, observation) { + access = snapshotData(access); + const captured = + observation !== null && typeof observation === "object" + ? observations.get(observation) + : undefined; + if (captured === undefined) + throw new TypeError( + "Published search observation is invalid or consumed", + ); + authorize(access); + if (access.principalId !== captured.actorId) + throw new KnowledgeBaseAuthorizationError( + knowledgePermissions.articleRead, + ); + // Consume before the first await, including failed or concurrent rechecks. + observations.delete(observation); + try { + const current = await read(access, captured.input); + if ( + captured.membership !== current.membership || + captured.articles !== current.serialized + ) + throw unavailable(); + } catch (error) { + if (isUnavailable(error) || isPartial(error)) throw unavailable(); + throw error; + } + }, + }); +} diff --git a/packages/application/src/types.ts b/packages/application/src/types.ts index e621e26..4d35c21 100644 --- a/packages/application/src/types.ts +++ b/packages/application/src/types.ts @@ -22,6 +22,7 @@ import type { } from "@pegma/knowledge-base-core"; import type { Store } from "@pegma/storage-core"; import type { KnowledgeEvidenceContext } from "./evidence-reports-types.js"; +import type { PublishedSearchObservations } from "./published-search-observations-types.js"; import type { KnowledgeRepositoryLimits } from "./repository.js"; import type { @@ -348,6 +349,8 @@ export interface KnowledgeAuthoringContextRead { } export interface KnowledgeBaseApplication extends KnowledgeRetrievalApplication { + /** Optional bounded background comparison observations; never inline portal search. */ + readonly publishedSearchObservations?: PublishedSearchObservations; createCollection( access: AccessContext, input: CreateCollectionInput, diff --git a/packages/contracts/README.md b/packages/contracts/README.md index 43c5d2e..fb81a84 100644 --- a/packages/contracts/README.md +++ b/packages/contracts/README.md @@ -7,7 +7,7 @@ using host-resolved Authorization Core contexts. Identity and time types come from `@pegma/spine`. The current verified synchronized release is -[`0.1.6`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6), including +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7), including MCP extension metadata compatibility. The historical [`0.1.5` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.5) provided application answering read batching. Changed source still requires diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 6658092..10fb0ca 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-contracts", - "version": "0.1.7", + "version": "0.1.8", "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 aaa0af2..bb5f448 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -5,7 +5,7 @@ transitions. It requires no Support Desk, GitHub, model, framework, database, or provider SDK. The current verified synchronized release is -[`0.1.6`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.6), including +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7), including MCP extension metadata compatibility. The historical [`0.1.5` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.5) provided application answering read batching. Changed source still requires diff --git a/packages/core/package.json b/packages/core/package.json index 2fd797a..4935cde 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-core", - "version": "0.1.7", + "version": "0.1.8", "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.7" + "@pegma/knowledge-base-contracts": "0.1.8" }, "scripts": { "build": "tsc -p tsconfig.json", diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 746be45..d51d83c 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -8,7 +8,7 @@ endpoints; the package does not supply a hosted service. The historical synchronized [`0.1.5` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.5) includes answering read batching and the aggregate report query introduced in -`0.1.4`. The current verified synchronized release is `0.1.6`, described below. +`0.1.4`. The current verified synchronized release is `0.1.7`, described below. Changed source requires its own review and current-head gates. Host and actual client acceptance remain separate. These source README corrections apply to a future release. Published `0.1.5` tarballs, including their bundled README bytes, @@ -24,10 +24,10 @@ ceilings, strict tool arguments and fresh host authentication remain unchanged. The official-SDK regression and packed protocol proof exercise fictional extension values; actual requested-client and host acceptance remain separate. -The unpublished `0.1.7` candidate synchronizes all four packages for the staff -report receipt extension. Its combined source requires current-head gates and -release verification before adoption. See the -[application upgrade note](https://github.com/pegma-dev/knowledge-base/blob/61dcaaf19f7a0db644709aef8f52a826f3c1b34d/packages/application/README.md#unpublished-017-candidate). +The verified [`0.1.7` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7) +synchronizes all four packages for the staff report receipt extension. The +unpublished `0.1.8` candidate adds an application-only report observation pair; +the five MCP tools and three scopes remain unchanged. The contracts, core, and application packages remain independent of MCP, HTTP, provider SDKs, and login flows. Hosts choose this adapter when exposing agent diff --git a/packages/mcp/package.json b/packages/mcp/package.json index d4d3c26..e46456a 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/knowledge-base-mcp", - "version": "0.1.7", + "version": "0.1.8", "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.7", - "@pegma/knowledge-base-contracts": "0.1.7", - "@pegma/knowledge-base-core": "0.1.7", + "@pegma/knowledge-base-application": "0.1.8", + "@pegma/knowledge-base-contracts": "0.1.8", + "@pegma/knowledge-base-core": "0.1.8", "zod": "4.6.7" }, "scripts": { diff --git a/packages/mcp/src/mcp.ts b/packages/mcp/src/mcp.ts index 92f1e70..01befff 100644 --- a/packages/mcp/src/mcp.ts +++ b/packages/mcp/src/mcp.ts @@ -353,7 +353,7 @@ export function createKnowledgeAgentMcp( maxRequestBodySize: dispatcher.limits.maxRequestBytes, }); const server = new Server( - { name: "@pegma/knowledge-base-mcp", version: "0.1.7" }, + { name: "@pegma/knowledge-base-mcp", version: "0.1.8" }, { capabilities: { tools: {} }, // Workers prohibit the runtime code generation used by SDK-default AJV. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cf815fa..6da10c5 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.7 + specifier: 0.1.8 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.7 + specifier: 0.1.8 version: link:packages/contracts '@pegma/knowledge-base-core': - specifier: 0.1.7 + specifier: 0.1.8 version: link:packages/core '@pegma/knowledge-base-mcp': - specifier: 0.1.7 + specifier: 0.1.8 version: link:packages/mcp '@pegma/spine': specifier: 0.1.2 @@ -81,10 +81,10 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/knowledge-base-contracts': - specifier: 0.1.7 + specifier: 0.1.8 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.7 + specifier: 0.1.8 version: link:../core '@pegma/spine': specifier: 0.1.2 @@ -102,7 +102,7 @@ importers: packages/core: dependencies: '@pegma/knowledge-base-contracts': - specifier: 0.1.7 + specifier: 0.1.8 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.7 + specifier: 0.1.8 version: link:../application '@pegma/knowledge-base-contracts': - specifier: 0.1.7 + specifier: 0.1.8 version: link:../contracts '@pegma/knowledge-base-core': - specifier: 0.1.7 + specifier: 0.1.8 version: link:../core zod: specifier: 4.6.7 diff --git a/test/README.md b/test/README.md index 78d213b..1f417b1 100644 --- a/test/README.md +++ b/test/README.md @@ -1,8 +1,8 @@ # Public KB conformance fixtures The current verified Knowledge Base release is -[`0.1.6`](../docs/BOOTSTRAP.md#current-verified-016-release). -The `0.1.7` source candidate remains unpublished. +[`0.1.7`](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.7). +The `0.1.8` source candidate remains unpublished. The application/storage/review and retrieval/bounds/maintenance/regression suites under `tests/` share `application-stores.ts`. They target Storage Core's @@ -26,7 +26,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 current four-package verified KB release is `0.1.6`, and the Agent Access +The current four-package verified KB release is `0.1.7`, and the Agent Access protocol-proof pin remains `0.1.1`. Tests exercise the current working tree; changed-source gates are separate from immutable published-release evidence. diff --git a/tests/published-search-observations.test.ts b/tests/published-search-observations.test.ts new file mode 100644 index 0000000..0857a94 --- /dev/null +++ b/tests/published-search-observations.test.ts @@ -0,0 +1,1277 @@ +import { + createKnowledgeBaseApplication, + knowledgeRecords, + KnowledgeBaseAuthorizationError, + KnowledgeBaseNotFoundError, + KnowledgeBasePrerequisiteError, + RepositoryIntegrityError, + type KnowledgeRetrievalOptions, + type PublishedSearchObservationResult, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import { resolveAccess } from "@pegma/authorization-core"; +import { StorageError } from "@pegma/storage-core"; +import type { + CollectionDefinition, + EntityKey, + ScanOptions, + Store, +} from "@pegma/storage-core"; +import { describe, expect, it } from "vitest"; +import { + access, + admin, + applicationFixture, + at, + author, + customer, + draft, + outsider, +} from "../test/application-fixtures.js"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { barrier } from "../test/trace-store.js"; +import { + botCustomer, + retrievalFixture, + retrievalGuides, +} from "../test/retrieval-fixtures.js"; + +// Exact resolved defaults from PG support-background-service-access.ts. +// No customer audience, collectionRead, role assignment, or ambient entitlement. +const authoringReader = resolveAccess( + { principalId: "pegma/support-learning-draft" }, + { + version: "pg-background-learning-draft-v1", + defaults: [ + "support.queue.read", + "support.learning.read", + "support.learning.process", + knowledgePermissions.articleRead, + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.provenanceRead, + knowledgePermissions.provenanceWrite, + ], + }, +); + +interface KeyedRead { + readonly method: "get" | "getVersioned"; + readonly key: EntityKey; +} + +function fixture(backing: Store, retrieval: KnowledgeRetrievalOptions = {}) { + const f = applicationFixture(backing); + let scans = 0; + let scanPasses = 0; + const scanPages: { + pass: number; + requested: number; + physicalRows: number; + hasCursor: boolean; + }[] = []; + let beforeScan: + | ((ordinal: number, pass: number, input: ScanOptions) => Promise) + | undefined; + const keyedReads: KeyedRead[] = []; + let beforeRead: ((read: KeyedRead) => Promise) | undefined; + const observed: Store = { + collection(definition: CollectionDefinition) { + const target = backing.collection(definition); + return new Proxy(target, { + get(object, property) { + if (property === "get" || property === "getVersioned") + return async (key: EntityKey) => { + const read: KeyedRead = { + method: property, + key: structuredClone(key), + }; + keyedReads.push(read); + if (beforeRead !== undefined) await beforeRead(read); + return property === "get" + ? object.get(key) + : object.getVersioned(key); + }; + if (property === "scan") + return async (input: ScanOptions) => { + scans += 1; + if (input.cursor === undefined) scanPasses += 1; + await beforeScan?.(scans, scanPasses, input); + const page = await object.scan(input); + scanPages.push({ + pass: scanPasses, + requested: input.limit, + physicalRows: page.records.length, + hasCursor: page.nextCursor !== null, + }); + return page; + }; + const value: unknown = Reflect.get(object, property, object); + return typeof value === "function" ? value.bind(object) : value; + }, + }); + }, + }; + const app = createKnowledgeBaseApplication({ + store: observed, + clock: { now: () => at(600_000) }, + evidenceVerifier: { verify: f.verify }, + privateSources: f.privateSources, + retrieval, + }); + return { + ...f, + app, + authoringApp: f.app, + backing, + observers: app.publishedSearchObservations!, + scans: () => scans, + scanPasses: () => scanPasses, + scanPages, + keyedReads, + beforeRead(handler: typeof beforeRead) { + beforeRead = handler; + }, + beforeScan(handler: typeof beforeScan) { + beforeScan = handler; + }, + input(query = "export") { + return { + collectionId: "collection/workshop", + query, + applicability: draft().applicability, + }; + }, + }; +} + +function complete(result: PublishedSearchObservationResult) { + expect(result.outcome).toBe("complete"); + if (result.outcome !== "complete") throw new Error("Expected complete scope"); + return result; +} + +async function change( + f: ReturnType, + kind: "publish" | "withdraw" | "draft" | "policy", +) { + if (kind === "publish") { + await f.publishedArticle("article/late"); + return; + } + if (kind === "policy") { + const preview = await f.authoringApp.previewCollectionPolicy(admin, { + collectionId: "collection/workshop", + uses: { portal: { enabled: false }, bot: { enabled: false } }, + }); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("withdraw-portal", preview.generation), + collectionId: "collection/workshop", + preview: preview.preview, + }); + return; + } + const current = await f.authoringApp.getDraft(author, { + articleId: "article/export", + }); + if (kind === "withdraw") + await f.authoringApp.retireArticle(admin, { + ...f.command("retire", current.generation), + articleId: current.articleId, + }); + else + await f.authoringApp.updateDraft(author, { + ...f.command("edit", current.generation), + articleId: current.articleId, + collectionId: "collection/workshop", + draft: { ...draft(), title: "UNAPPROVED_DRAFT_CANARY" }, + }); +} + +async function seedHistory( + f: ReturnType, + count: number, + prefix: string, + payload = "", +) { + const sample = (await allKnowledgeRows(f.backing)).find( + (row) => row.resourceKind === "collection" && row.kind === "head", + ); + if (sample === undefined) + throw new Error("Expected the real collection head"); + const records = f.backing.collection(knowledgeRecords); + for (let offset = 0; offset < count; offset += 4) + await Promise.all( + Array.from({ length: Math.min(4, count - offset) }, (_, index) => + records.put({ + ...sample, + id: `job:${prefix}:${offset + index}`, + kind: "job", + data: { task: "collection_changed", fixturePayload: payload }, + }), + ), + ); +} + +for (const [backend, createStore] of storeFactories) { + describe(`background published search observations (${backend})`, () => { + it("completes and confirms a genuinely empty authorized scope without the index", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + expect(result.articles).toEqual([]); + expect(f.scanPasses()).toBe(2); + await expect( + f.observers.confirm(authoringReader, result.observation), + ).resolves.toBeUndefined(); + expect(f.scanPasses()).toBe(4); + }); + + it("finds a newly published unindexed guide even when legacy provider search fails", async () => { + const f = fixture(await createStore(), { + candidateAdapter: { + search: async () => { + throw new Error("Synthetic search provider unavailable"); + }, + }, + }); + await f.setupCollection(); + await f.publishedArticle(); + expect(await f.app.searchPublishedArticles(customer, f.input())).toEqual({ + outcome: "no_result", + articles: [], + }); + expect(f.scans()).toBe(0); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + expect(result.articles.map(({ articleId }) => articleId)).toEqual([ + "article/export", + ]); + expect(result.articles[0]?.content).toEqual(draft().content); + await f.observers.confirm(authoringReader, result.observation); + }); + + it("covers only the exact authorized collection, applicability, and metadata query", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.setupCollection("collection/other"); + await f.publishedArticle(); + await f.publishedArticle("article/elsewhere", "collection/other"); + await f.publishedArticle("article/other-version", undefined, { + ...draft(), + applicability: { ...draft().applicability, productVersion: "1.1" }, + }); + await f.publishedArticle("article/other-query", undefined, { + ...draft(), + title: "Restore a password", + summary: "Recover sign-in access.", + tags: ["password"], + }); + await f.createDraft("article/unpublished"); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + expect(result.articles.map(({ articleId }) => articleId)).toEqual([ + "article/export", + ]); + const absent = complete( + await f.observers.observe(authoringReader, f.input("quasar")), + ); + expect(absent.articles).toEqual([]); + }); + + it("projects approved content only, excludes private provenance and draft edits, and detaches data", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + let current = await f.createDraft(); + current = await f.setSources(current, [ + { + id: "private/guide", + system: "synthetic", + resourceId: "PRIVATE_SOURCE_CANARY", + version: "1", + }, + ]); + current = (await f.submitEvidence(current)).current; + await f.publish(current); + await change(f, "draft"); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + expect(result.articles[0]?.title).toBe(draft().title); + const serialized = JSON.stringify(result); + for (const canary of [ + "PRIVATE_STAFF_EVIDENCE", + "PRIVATE_SOURCE_CANARY", + "UNAPPROVED_DRAFT_CANARY", + "sourceSnapshotHash", + "publishedProvenance", + "reviewerId", + ]) + expect(serialized).not.toContain(canary); + expect(f.privateSources.canPublish).toHaveBeenCalled(); + expect(f.privateSources.isCurrent).toHaveBeenCalled(); + Reflect.set(result.articles[0]!, "title", "Mutated projection"); + await f.observers.confirm(authoringReader, result.observation); + expect( + ( + await f.app.getPublishedArticle(customer, { + articleId: "article/export", + }) + ).title, + ).toBe(draft().title); + }); + + it("holds instead of slicing a larger matching set to the requested limit", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + await f.publishedArticle("article/second"); + expect( + await f.observers.observe(authoringReader, { ...f.input(), limit: 1 }), + ).toEqual({ outcome: "partial", articles: [] }); + }); + + it("holds whole approved content when the content bound cannot fit it", async () => { + const f = fixture(await createStore(), { + limits: { maxContentBytes: 1 }, + }); + await f.setupCollection(); + await f.publishedArticle(); + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "partial", + articles: [], + }); + }); + + it("counts every physical history/nonmatching row before filtering and holds at the total row cap", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const sample = (await allKnowledgeRows(f.backing)).find( + (row) => row.resourceKind === "collection" && row.kind === "head", + ); + if (sample === undefined) + throw new Error("Expected a real collection head"); + const records = f.backing.collection(knowledgeRecords); + for (let offset = 0; offset < 260; offset += 16) + await Promise.all( + Array.from({ length: Math.min(16, 260 - offset) }, (_, index) => + records.put({ + ...sample, + id: `job:physical:${offset + index}`, + kind: "job", + data: { task: "collection_changed" }, + }), + ), + ); + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "partial", + articles: [], + }); + expect(f.scanPasses()).toBe(1); + expect( + f.scanPages.reduce((total, page) => total + page.physicalRows, 0), + ).toBeLessThanOrEqual(256); + expect(f.scanPages.every((page) => page.requested <= 8)).toBe(true); + }); + + it("reports scan dependency failure as unavailable, never as complete empty", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + f.beforeScan(async () => { + throw new StorageError("Synthetic backing scan unavailable"); + }); + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "unavailable", + articles: [], + }); + }); + + it("rejects portal-only readers and missing authoring permission before enumerating", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + for (const denied of [ + customer, + outsider, + access(customer.principalId, ["workshop.customer"]), + ]) + expect(await f.observers.observe(denied, f.input())).toEqual({ + outcome: "unavailable", + articles: [], + }); + expect(f.scans()).toBe(0); + }); + + it.each(["publish", "withdraw", "draft", "policy"] as const)( + "refuses a late %s before the final membership/version fence", + async (kind) => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + f.beforeScan(async (_ordinal, pass, input) => { + if (pass === 2 && input.cursor === undefined) await change(f, kind); + }); + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "unavailable", + articles: [], + }); + }, + ); + + it.each(["publish", "withdraw", "draft", "policy"] as const)( + "rejects and consumes a captured scope after a %s", + async (kind) => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + await change(f, kind); + await expect( + f.observers.confirm(authoringReader, result.observation), + ).rejects.toBeInstanceOf(KnowledgeBasePrerequisiteError); + await expect( + f.observers.confirm(authoringReader, result.observation), + ).rejects.toBeInstanceOf(TypeError); + }, + ); + + it("rejects a new publication during confirmation's final async fence", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + f.beforeScan(async (_ordinal, pass, input) => { + if (pass === 4 && input.cursor === undefined) + await change(f, "publish"); + }); + await expect( + f.observers.confirm(authoringReader, result.observation), + ).rejects.toBeInstanceOf(KnowledgeBasePrerequisiteError); + }); + + it("rejects an opaque head-version change even when its generation and payload are unchanged", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + const head = (await allKnowledgeRows(f.backing)).find( + (row) => row.resourceId === "article/export" && row.kind === "head", + ); + if (head === undefined) throw new Error("Expected the real article head"); + const records = f.backing.collection(knowledgeRecords); + const saved = await records.getVersioned({ + partition: head.partition, + id: head.id, + }); + if (saved === null) + throw new Error("Expected its opaque backend version"); + expect(await records.putIfUnchanged(saved.value, saved.version)).toBe( + true, + ); + await expect( + f.observers.confirm(authoringReader, result.observation), + ).rejects.toBeInstanceOf(KnowledgeBasePrerequisiteError); + }); + + it("rechecks current private-source eligibility instead of reusing an earlier publication check", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + let current = await f.createDraft(); + current = await f.setSources(current, [ + { + id: "source/one", + system: "synthetic", + resourceId: "row/one", + version: "1", + }, + ]); + current = (await f.submitEvidence(current)).current; + await f.publish(current); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + f.trust.sourceCurrent = false; + await expect( + f.observers.confirm(authoringReader, result.observation), + ).rejects.toBeInstanceOf(KnowledgeBasePrerequisiteError); + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "unavailable", + articles: [], + }); + }); + + it("binds the opaque single-use token to the instance and actor, and rechecks current permission", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + const foreign = createKnowledgeBaseApplication({ + store: f.backing, + clock: { now: () => at(600_000) }, + }).publishedSearchObservations!; + for (const [observer, token] of [ + [f.observers, structuredClone(result.observation)], + [foreign, result.observation], + ] as const) + await expect( + observer.confirm(authoringReader, token), + ).rejects.toBeInstanceOf(TypeError); + await expect( + f.observers.confirm( + access("customer/different", authoringReader.permissions), + result.observation, + ), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.observers.confirm( + access(authoringReader.principalId, []), + result.observation, + ), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await f.observers.confirm(authoringReader, result.observation); + await expect( + f.observers.confirm(authoringReader, result.observation), + ).rejects.toBeInstanceOf(TypeError); + }); + + it("consumes the token before the first awaited re-observation", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const result = complete( + await f.observers.observe(authoringReader, f.input()), + ); + const pause = barrier(); + f.beforeScan(async (_ordinal, pass, input) => { + if (pass === 3 && input.cursor === undefined) await pause.wait(); + }); + const pending = f.observers.confirm(authoringReader, result.observation); + await pause.reached; + await expect( + f.observers.confirm(authoringReader, result.observation), + ).rejects.toBeInstanceOf(TypeError); + pause.release(); + await expect(pending).resolves.toBeUndefined(); + }); + + it("never allows budget exhaustion or invalid scope input to become complete empty", async () => { + const f = fixture(await createStore(), { + limits: { maxRequestPhysicalGets: 2 }, + }); + await f.setupCollection(); + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "partial", + articles: [], + }); + await expect( + f.observers.observe(authoringReader, { ...f.input(), limit: 6 }), + ).rejects.toBeInstanceOf(TypeError); + await expect( + f.observers.observe(authoringReader, { ...f.input(), query: "the" }), + ).rejects.toBeInstanceOf(TypeError); + await expect( + f.observers.observe(authoringReader, { + ...f.input(), + applicability: { ...draft().applicability, productVersion: "" }, + }), + ).rejects.toBeInstanceOf(TypeError); + }); + }); + + describe(`comparison query and catalogue limits (${backend})`, () => { + it("rejects configured query ceilings and explicit null limit before any I/O", async () => { + const store = await createStore(); + const characters = fixture(store, { limits: { maxQueryCharacters: 3 } }); + const terms = fixture(store, { limits: { maxQueryTerms: 1 } }); + const normal = fixture(store); + await expect( + characters.observers.observe( + authoringReader, + characters.input("export"), + ), + ).rejects.toBeInstanceOf(TypeError); + await expect( + terms.observers.observe( + authoringReader, + terms.input("export workspace"), + ), + ).rejects.toBeInstanceOf(TypeError); + await expect( + normal.observers.observe( + authoringReader, + JSON.parse( + JSON.stringify({ + ...normal.input(), + limit: null, + }), + ), + ), + ).rejects.toBeInstanceOf(TypeError); + for (const f of [characters, terms, normal]) { + expect(f.keyedReads).toEqual([]); + expect(f.scanPages).toEqual([]); + expect(f.scans()).toBe(0); + } + }); + + it("bounds each large private/history payload page while completing the observed cycles", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await seedHistory( + f, + 16, + "large-private", + "PRIVATE_LARGE_HISTORY_CANARY" + "x".repeat(399_000), + ); + const observed = complete( + await f.observers.observe(authoringReader, f.input()), + ); + expect(observed.articles).toEqual([]); + expect(JSON.stringify(observed)).not.toContain( + "PRIVATE_LARGE_HISTORY_CANARY", + ); + expect(f.scanPasses()).toBe(2); + expect(f.scanPages.length).toBeGreaterThan(2); + expect( + f.scanPages.every( + (page) => page.requested <= 8 && page.physicalRows <= 8, + ), + ).toBe(true); + for (const pass of [1, 2]) + expect( + f.scanPages.filter((page) => page.pass === pass).at(-1)?.hasCursor, + ).toBe(false); + }); + + it("honors the exact 256-row terminal contract and never probes a possible 257th row", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const initialRows = (await allKnowledgeRows(f.backing)).length; + await seedHistory(f, 256 - initialRows, "boundary"); + expect((await allKnowledgeRows(f.backing)).length).toBe(256); + const result = await f.observers.observe(authoringReader, f.input()); + const firstPass = f.scanPages.filter((page) => page.pass === 1); + expect(firstPass.reduce((sum, page) => sum + page.physicalRows, 0)).toBe( + 256, + ); + if (result.outcome === "complete") { + expect(result.articles).toEqual([]); + expect(firstPass.at(-1)?.hasCursor).toBe(false); + expect( + f.scanPages.filter((page) => page.pass === 2).at(-1)?.hasCursor, + ).toBe(false); + } else { + // A backend's speculative full-page cursor cannot establish that an + // additional physical record is absent within the hard row allowance. + expect(result).toEqual({ outcome: "partial", articles: [] }); + expect(firstPass.at(-1)?.hasCursor).toBe(true); + } + await seedHistory(f, 1, "overflow"); + const before = f.scanPages.length; + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "partial", + articles: [], + }); + const overflow = f.scanPages.slice(before); + expect(overflow.reduce((sum, page) => sum + page.physicalRows, 0)).toBe( + 256, + ); + expect(overflow.every((page) => page.requested <= 8)).toBe(true); + expect(overflow.at(-1)?.hasCursor).toBe(true); + }); + + it("shares the original physical-work budget across every scan page and early overflow", async () => { + const f = fixture(await createStore(), { + limits: { maxRequestPhysicalGets: 12 }, + }); + await f.setupCollection(); + await seedHistory(f, 32, "work-budget"); + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "partial", + articles: [], + }); + const actualWork = + f.keyedReads.length + + f.scanPages.reduce( + (sum, page) => sum + Math.max(1, page.physicalRows), + 0, + ); + expect(actualWork).toBeLessThanOrEqual(12); + expect(f.scanPages.every((page) => page.requested <= 8)).toBe(true); + expect(f.scanPasses()).toBe(1); + }); + + it("keeps dependency holds content-free but exposes integrity and programming faults to background operators", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + f.beforeScan(async () => { + throw new StorageError("Synthetic dependency unavailable"); + }); + expect(await f.observers.observe(authoringReader, f.input())).toEqual({ + outcome: "unavailable", + articles: [], + }); + f.beforeScan(async () => { + throw new RepositoryIntegrityError(); + }); + await expect( + f.observers.observe(authoringReader, f.input()), + ).rejects.toBeInstanceOf(RepositoryIntegrityError); + f.beforeScan(async () => { + throw new TypeError("Synthetic background programming fault"); + }); + await expect( + f.observers.observe(authoringReader, f.input()), + ).rejects.toBeInstanceOf(TypeError); + f.beforeScan(undefined); + const observed = complete( + await f.observers.observe(authoringReader, f.input()), + ); + f.beforeScan(async () => { + throw new RepositoryIntegrityError(); + }); + await expect( + f.observers.confirm(authoringReader, observed.observation), + ).rejects.toBeInstanceOf(RepositoryIntegrityError); + await expect( + f.observers.confirm(authoringReader, observed.observation), + ).rejects.toBeInstanceOf(TypeError); + f.beforeScan(undefined); + await f.publishedArticle(); + f.beforeRead(async () => { + throw new RepositoryIntegrityError(); + }); + await expect( + f.observers.readArticle(authoringReader, { + articleId: "article/export", + }), + ).rejects.toBeInstanceOf(RepositoryIntegrityError); + await expect( + f.app.getPublishedArticle(customer, { articleId: "article/export" }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + await expect( + f.observers.readScope(authoringReader, { + collectionId: "collection/workshop", + }), + ).rejects.toBeInstanceOf(RepositoryIntegrityError); + }); + }); + + describe(`authoring published reads (${backend})`, () => { + it("compares private audience publications with exact intrinsic permissions and no audience grant", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + expect(authoringReader.permissions).not.toContain("workshop.customer"); + expect(authoringReader.permissions).not.toContain( + knowledgePermissions.botRead, + ); + expect(authoringReader.permissions).not.toContain( + knowledgePermissions.collectionRead, + ); + expect(authoringReader.roles).toEqual([]); + expect(authoringReader.entitlements).toEqual([]); + const current = await f.observers.readArticle(authoringReader, { + articleId: "article/export", + }); + expect(current.title).toBe(draft().title); + expect(current.content).toEqual(draft().content); + expect(f.scans()).toBe(0); + await expect( + f.app.getPublishedArticle(authoringReader, { + articleId: current.articleId, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + await expect( + f.app.getPublishedArticle(customer, { articleId: current.articleId }), + ).resolves.toEqual(current); + const compared = complete( + await f.observers.observe(authoringReader, f.input()), + ); + expect(compared.articles).toEqual([current]); + await f.observers.confirm(authoringReader, compared.observation); + }); + + it("admits bot-only authoring comparisons while preserving independent portal and bot readers", async () => { + const f = retrievalFixture(await createStore()); + const collectionId = "collection/bot-only"; + await f.setupCollection(collectionId, false); + await f.publishGuide(retrievalGuides[0], collectionId); + const observers = f.app.publishedSearchObservations!; + const scope = await observers.readScope(authoringReader, { + collectionId, + }); + const current = await observers.readArticle(authoringReader, { + articleId: retrievalGuides[0]!.id, + }); + expect(current.collectionId).toBe(scope.collectionId); + const compared = complete( + await observers.observe(authoringReader, { + ...f.portalInput(), + collectionId, + }), + ); + expect(compared.articles).toEqual([current]); + await observers.confirm(authoringReader, compared.observation); + await expect( + f.app.getPublishedArticle(customer, { articleId: current.articleId }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + expect( + await f.app.searchPublishedArticles(customer, { + ...f.portalInput(), + collectionId, + }), + ).toEqual({ outcome: "no_result", articles: [] }); + const answer = await f.app.retrieveAnswerSources(botCustomer, { + ...f.botInput(), + collectionIds: [collectionId], + }); + expect(answer.sources).toHaveLength(1); + expect(answer.sources[0]?.citation).not.toHaveProperty("portalArticle"); + expect( + ( + await f.app.retrieveAnswerSources(authoringReader, { + ...f.botInput(), + collectionIds: [collectionId], + }) + ).sources, + ).toEqual([]); + }); + + it("refuses portal-only and draft-only callers without changing their ordinary reads", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + await expect( + f.app.getPublishedArticle(customer, { articleId: "article/export" }), + ).resolves.toEqual( + expect.objectContaining({ articleId: "article/export" }), + ); + const draftOnly = access("staff/draft-only", [ + knowledgePermissions.draftRead, + ]); + await expect( + f.app.getDraft(draftOnly, { articleId: "article/export" }), + ).resolves.toEqual( + expect.objectContaining({ articleId: "article/export" }), + ); + for (const caller of [customer, draftOnly]) { + await expect( + f.observers.readScope(caller, { + collectionId: "collection/workshop", + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.observers.readArticle(caller, { + articleId: "article/export", + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + expect(await f.observers.observe(caller, f.input())).toEqual({ + outcome: "unavailable", + articles: [], + }); + } + expect(f.scans()).toBe(0); + }); + + it("rechecks revoked articleRead and draftRead without treating an observation as authority", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + const observed = complete( + await f.observers.observe(authoringReader, f.input()), + ); + for (const permission of [ + knowledgePermissions.articleRead, + knowledgePermissions.draftRead, + ]) { + const revoked = resolveAccess( + { principalId: authoringReader.principalId }, + { + version: "pg-background-learning-draft-revoked", + defaults: authoringReader.permissions.filter( + (value) => value !== permission, + ), + }, + ); + await expect( + f.observers.readScope(revoked, { + collectionId: "collection/workshop", + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.observers.readArticle(revoked, { + articleId: "article/export", + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.observers.confirm(revoked, observed.observation), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + } + await f.observers.confirm(authoringReader, observed.observation); + }); + + it("returns the approved publication while a new private draft exists, then refuses retirement", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + await change(f, "draft"); + const current = await f.observers.readArticle(authoringReader, { + articleId: "article/export", + }); + expect(current.title).toBe(draft().title); + expect(JSON.stringify(current)).not.toContain("UNAPPROVED_DRAFT_CANARY"); + await f.createDraft("article/draft-only"); + for (const articleId of ["article/missing", "article/draft-only"]) + await expect( + f.observers.readArticle(authoringReader, { articleId }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + await change(f, "withdraw"); + await expect( + f.observers.readArticle(authoringReader, { + articleId: "article/export", + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + expect(f.scans()).toBe(0); + }); + + it("refuses a publication held by actual evidence revocation", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + await f.publishedArticle(); + const current = await f.app.getDraft(author, { + articleId: "article/export", + }); + const proof = ( + await f.app.getEvidence(admin, { + articleId: current.articleId, + }) + ).evidence[0]!; + await f.app.revokeEvidence(admin, { + ...f.command("authoring-proof-withdrawal", current.generation), + articleId: current.articleId, + articleRevision: proof.articleRevision, + evidenceId: proof.id, + evidenceVersion: proof.version, + evidenceHash: proof.hash, + reason: "Synthetic exact proof withdrawal", + }); + await expect( + f.observers.readArticle(authoringReader, { + articleId: current.articleId, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + expect(f.scans()).toBe(0); + }); + + it("keeps current private-source eligibility as a publication read gate", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + let current = await f.createDraft(); + current = await f.setSources(current, [ + { + id: "source/authoring", + system: "synthetic", + resourceId: "row/private", + version: "1", + }, + ]); + current = (await f.submitEvidence(current)).current; + await f.publish(current); + await f.observers.readArticle(authoringReader, { + articleId: current.articleId, + }); + f.trust.sourceCurrent = false; + await expect( + f.observers.readArticle(authoringReader, { + articleId: current.articleId, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + expect(f.scans()).toBe(0); + }); + }); + + describe(`keyed published scope (${backend})`, () => { + const intrinsic = authoringReader; + + it("reads the actual scope with intrinsic authority and no collectionRead or enumeration", async () => { + const f = fixture(await createStore()); + const actual = await f.setupCollection(); + expect(intrinsic.permissions).not.toContain( + knowledgePermissions.collectionRead, + ); + expect(intrinsic.permissions).not.toContain("workshop.customer"); + expect(intrinsic.roles).toEqual([]); + expect(intrinsic.entitlements).toEqual([]); + const state = await f.observers.readScope(intrinsic, { + collectionId: "collection/workshop", + }); + expect(Object.keys(state).sort()).toEqual([ + "collectionId", + "generation", + "scopeHash", + ]); + expect(state.collectionId).toBe(actual.collection.id); + expect(state.generation).toBe(actual.generation); + expect(state.scopeHash).toMatch(/^[a-f0-9]{64}$/u); + expect(f.scans()).toBe(0); + expect(f.keyedReads.length).toBeGreaterThan(0); + expect(new Set(f.keyedReads.map(({ key }) => key.partition)).size).toBe( + 1, + ); + expect( + await f.observers.readScope(intrinsic, { + collectionId: "collection/workshop", + }), + ).toEqual(state); + expect(f.scans()).toBe(0); + }); + + it("returns the same actual scopeState with a complete empty observation", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const observed = complete( + await f.observers.observe(intrinsic, f.input()), + ); + expect(observed.articles).toEqual([]); + const scans = f.scans(); + const keyed = await f.observers.readScope(intrinsic, { + collectionId: "collection/workshop", + }); + expect(observed.scopeState).toEqual(keyed); + expect(f.scans()).toBe(scans); + await f.observers.confirm(intrinsic, observed.observation); + }); + + it("refuses a missing or closed scope without fabricating fresh state", async () => { + const f = fixture(await createStore()); + await expect( + f.observers.readScope(intrinsic, { + collectionId: "collection/missing", + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + await f.setupCollection("collection/closed", false); + const preview = await f.authoringApp.previewCollectionPolicy(admin, { + collectionId: "collection/closed", + uses: { portal: { enabled: false }, bot: { enabled: false } }, + }); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("close-all-scope-channels", preview.generation), + collectionId: "collection/closed", + preview: preview.preview, + }); + await expect( + f.observers.readScope(intrinsic, { collectionId: "collection/closed" }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + expect(f.scans()).toBe(0); + }); + + it("rechecks current authoring permission without an ambient audience role", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const request = { collectionId: "collection/workshop" }; + await f.observers.readScope(intrinsic, request); + const withdrawnRole = { + ...access(intrinsic.principalId, [knowledgePermissions.articleRead]), + roles: ["former-learning-role"], + }; + await expect( + f.observers.readScope(withdrawnRole, request), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.observers.readScope( + access(intrinsic.principalId, ["workshop.customer"]), + request, + ), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.observers.readScope( + access(intrinsic.principalId, [knowledgePermissions.collectionRead]), + request, + ), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect(f.observers.readScope(intrinsic, request)).resolves.toEqual( + expect.objectContaining(request), + ); + expect(f.scans()).toBe(0); + }); + + it("binds customer audience changes without requiring that audience for staff authoring", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const request = { collectionId: "collection/workshop" }; + const before = await f.observers.readScope(intrinsic, request); + const preview = await f.authoringApp.previewCollectionPolicy(admin, { + ...request, + uses: { + portal: { + enabled: true, + audience: { kind: "permission", permission: "workshop.next" }, + }, + bot: { enabled: false }, + }, + }); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("replace-scope-audience", preview.generation), + ...request, + preview: preview.preview, + }); + const after = await f.observers.readScope(intrinsic, request); + expect(intrinsic.permissions).not.toContain("workshop.next"); + expect(after.generation).toBeGreaterThan(before.generation); + expect(after.scopeHash).not.toBe(before.scopeHash); + expect(f.scans()).toBe(0); + }); + + it("binds collection generation changes even when portal policy is unchanged", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const request = { collectionId: "collection/workshop" }; + const before = await f.observers.readScope(intrinsic, request); + const actual = await f.authoringApp.getGovernanceConfiguration( + admin, + request, + ); + await f.authoringApp.putGovernanceConfiguration(admin, { + ...f.command("replace-scope-generation", actual.generation), + ...request, + configuration: { + ...actual.configuration, + expectedStagingBuildId: "staging-43", + }, + }); + const after = await f.observers.readScope(intrinsic, request); + expect(after.generation).toBeGreaterThan(before.generation); + expect(after.scopeHash).not.toBe(before.scopeHash); + expect(f.scans()).toBe(0); + }); + + it("binds an actual opaque collection version change without exposing the version", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const request = { collectionId: "collection/workshop" }; + const before = await f.observers.readScope(intrinsic, request); + const head = (await allKnowledgeRows(f.backing)).find( + (row) => row.resourceId === request.collectionId && row.kind === "head", + ); + if (head === undefined) + throw new Error("Expected the real collection head"); + const records = f.backing.collection(knowledgeRecords); + const current = await records.getVersioned(head); + if (current === null) throw new Error("Expected its opaque version"); + expect(await records.putIfUnchanged(current.value, current.version)).toBe( + true, + ); + const after = await f.observers.readScope(intrinsic, request); + expect(after.generation).toBe(before.generation); + expect(after.scopeHash).not.toBe(before.scopeHash); + expect(after).not.toHaveProperty("version"); + expect(f.scans()).toBe(0); + }); + + it("rejects a late policy change after hashing and before the final keyed head read", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const head = (await allKnowledgeRows(f.backing)).find( + (row) => + row.resourceId === "collection/workshop" && row.kind === "head", + ); + if (head === undefined) + throw new Error("Expected the real collection head"); + let heads = 0; + f.beforeRead(async ({ method, key }) => { + if ( + method !== "getVersioned" || + key.partition !== head.partition || + key.id !== "head" + ) + return; + heads += 1; + if (heads === 2) await change(f, "policy"); + }); + await expect( + f.observers.readScope(intrinsic, { + collectionId: "collection/workshop", + }), + ).rejects.toBeInstanceOf(KnowledgeBasePrerequisiteError); + expect(f.scans()).toBe(0); + }); + + it("validates public policy approval while exposing no policy or staff metadata", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const request = { collectionId: "collection/workshop" }; + const preview = await f.authoringApp.previewCollectionPolicy(admin, { + ...request, + uses: { + portal: { enabled: true, audience: { kind: "anonymous" } }, + bot: { enabled: false }, + }, + }); + await f.authoringApp.updateCollectionPolicy(admin, { + ...f.command("approve-public-scope", preview.generation), + ...request, + preview: preview.preview, + approvePublic: true, + }); + const state = await f.observers.readScope(intrinsic, request); + expect(Object.keys(state).sort()).toEqual([ + "collectionId", + "generation", + "scopeHash", + ]); + const serialized = JSON.stringify(state); + for (const hidden of [ + "portal", + "audience", + "publicApproval", + "trustedAttesterIds", + "staff/workshop", + "configuration", + ]) + expect(serialized).not.toContain(hidden); + expect(f.scans()).toBe(0); + }); + + it("does not turn a keyed authority state into a fresh catalogue membership claim", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + const request = { collectionId: "collection/workshop" }; + const before = await f.observers.readScope(intrinsic, request); + await f.publishedArticle(); + const after = await f.observers.readScope(intrinsic, request); + expect(after).toEqual(before); + expect(f.scans()).toBe(0); + }); + + it("throws on dependency or input failure instead of returning invented state", async () => { + const f = fixture(await createStore()); + await f.setupCollection(); + f.beforeRead(async () => { + throw new StorageError( + "Synthetic current scope dependency unavailable", + ); + }); + await expect( + f.observers.readScope(intrinsic, { + collectionId: "collection/workshop", + }), + ).rejects.toBeInstanceOf(KnowledgeBasePrerequisiteError); + await expect( + f.observers.readScope(intrinsic, { collectionId: "" }), + ).rejects.toBeInstanceOf(TypeError); + expect(f.scans()).toBe(0); + }); + }); +} diff --git a/tests/report-observations.test.ts b/tests/report-observations.test.ts new file mode 100644 index 0000000..1ab15fa --- /dev/null +++ b/tests/report-observations.test.ts @@ -0,0 +1,500 @@ +import { + createKnowledgeEvidenceReports, + type KnowledgeReportObservation, +} from "@pegma/knowledge-base-application"; +import { knowledgePermissions } from "@pegma/knowledge-base-contracts"; +import type { + CollectionDefinition, + EntityKey, + Store, +} from "@pegma/storage-core"; +import { describe, expect, it } from "vitest"; +import { + allKnowledgeRows, + storeFactories, +} from "../test/application-stores.js"; +import { + confirmationPermission, + evidenceReportsFixture, + reportBarrier, +} from "../test/evidence-reports-fixtures.js"; + +type Fixture = Awaited>; + +function afterReadStore( + backing: Store, + afterRead: (collection: string, key: EntityKey) => Promise, +): Store { + return { + collection(definition: CollectionDefinition) { + const target = backing.collection(definition); + return new Proxy(target, { + get(object, property) { + if (property === "getVersioned") + return async (key: EntityKey) => { + const result = await object.getVersioned(key); + await afterRead(definition.name, key); + return result; + }; + const value: unknown = Reflect.get(object, property, object); + return typeof value === "function" ? value.bind(object) : value; + }, + }); + }, + }; +} + +async function prepared(createStore: () => Store | Promise) { + const f = await evidenceReportsFixture(await createStore()); + const packet = await f.report(); + const confirmed = await f.decide(packet.ack); + const hooks: { + afterContext?: () => Promise; + afterConfirm?: () => Promise; + afterRead?: (collection: string, key: EntityKey) => Promise; + } = {}; + let contextReads = 0; + const options = { + ...f.baseOptions, + store: afterReadStore(f.baseOptions.store, async (collection, key) => { + await hooks.afterRead?.(collection, key); + }), + authoringContext: { + async getAuthoringContext( + ...args: Parameters + ) { + contextReads++; + const value = await f.app.getAuthoringContext(...args); + await hooks.afterContext?.(); + return value; + }, + async confirmAuthoringContext( + ...args: Parameters + ) { + await f.app.confirmAuthoringContext(...args); + await hooks.afterConfirm?.(); + }, + }, + }; + const reports = createKnowledgeEvidenceReports(options); + const observations = reports.observations; + expect(observations).toBeDefined(); + if (observations === undefined) throw new Error("Observation port missing"); + return { + ...f, + packet, + confirmed, + reports, + observations, + hooks, + contextReads: () => contextReads, + fresh: () => createKnowledgeEvidenceReports(options), + }; +} + +for (const [backend, createStore] of storeFactories) { + describe(`operation-local report observations over ${backend}`, () => { + it("keeps the capability absent without the actual governed context pair", async () => { + const f = await evidenceReportsFixture(await createStore()); + expect(f.reports.observations).toBeUndefined(); + const packet = await f.report(); + expect(await f.reports.read(f.reviewer, f.key(packet.ack))).toMatchObject( + { + status: "pending", + receipt: packet.ack.receipt, + }, + ); + }); + + it("returns the real report and complete private context without writing, then confirms once", async () => { + const f = await prepared(createStore); + const before = await allKnowledgeRows(f.backing); + const rows = await f.rawRows(); + const legacy = await f.reports.read(f.owner, f.key(f.confirmed.ack)); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + expect(observed.view).toEqual(legacy); + expect(observed.context).toEqual( + ( + await f.app.getAuthoringContext(f.owner, { + articleId: f.articleId, + includeEvidence: true, + }) + ).context, + ); + expect(JSON.stringify(observed.observation)).toBe("{}"); + expect( + await f.observations.confirm(f.owner, observed.observation), + ).toEqual({ + receipt: f.confirmed.ack.receipt, + attestation: null, + }); + await expect( + f.observations.confirm(f.owner, observed.observation), + ).rejects.toMatchObject({ code: "invalid_request" }); + expect(await f.rawRows()).toEqual(rows); + expect(await allKnowledgeRows(f.backing)).toEqual(before); + }); + + it("reuses the actual owner verifier predicates and its already-observed context", async () => { + const f = await prepared(createStore); + const request = await f.verificationRequest( + f.confirmed.ack, + f.packet.input.evidence, + ); + const expected = await f.reports.verifier.verify(request); + expect(expected).not.toBeNull(); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + const count = f.contextReads(); + expect( + await f.observations.confirm(f.owner, observed.observation, request), + ).toEqual({ receipt: f.confirmed.ack.receipt, attestation: expected }); + expect(f.contextReads()).toBe(count); + expect( + await f.reports.status(f.agent, f.key(f.confirmed.ack)), + ).toMatchObject({ + receipt: f.confirmed.ack.receipt, + status: "confirmed", + }); + }); + + it.each(["pending", "rejected", "missing confirmation"] as const)( + "refuses observe-time %s reports without writes or a synthesized handle", + async (state) => { + const f = await prepared(createStore); + if (state === "missing confirmation") { + const saved = (await f.physicalRows()).find( + (row) => + row.value.id === + `report:${f.confirmed.ack.ledgerEpoch}:${f.confirmed.ack.reportId}`, + )!; + const report = JSON.parse(saved.value.payload); + expect(report.status).toBe("confirmed"); + expect(report.confirmation).not.toBeNull(); + // No public transition can create this invalid confirmed state. + // Corrupt a real encoded row through the existing fault fixture. + expect( + await f.replaceRow(saved, { + ...saved.value, + payload: JSON.stringify({ ...report, confirmation: null }), + }), + ).toBe(true); + } else { + const pending = await f.decide(f.confirmed.ack, "pending"); + if (state === "rejected") await f.decide(pending.ack, "rejected"); + } + const rows = await f.rawRows(); + const writes = f.observed.transactions.length; + await expect( + f.observations.observe(f.owner, f.key(f.confirmed.ack)), + ).rejects.toMatchObject( + state === "missing confirmation" + ? { code: "report_ledger_unavailable", stage: "report_decode" } + : { code: "report_not_verifiable" }, + ); + expect(await f.rawRows()).toEqual(rows); + expect(f.observed.transactions).toHaveLength(writes); + }, + ); + + it("allows a different current staff reader without impersonating the report submitter", async () => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.reviewer, + f.key(f.confirmed.ack), + ); + expect( + await f.observations.confirm(f.reviewer, observed.observation), + ).toEqual({ + receipt: f.confirmed.ack.receipt, + attestation: null, + }); + const request = await f.verificationRequest( + f.confirmed.ack, + f.packet.input.evidence, + ); + const second = await f.observations.observe( + f.reviewer, + f.key(f.confirmed.ack), + ); + await expect( + f.observations.confirm(f.reviewer, second.observation, request), + ).rejects.toMatchObject({ code: "report_not_verifiable" }); + await expect( + f.reports.status(f.reviewer, f.key(f.confirmed.ack)), + ).rejects.toMatchObject({ + code: "report_not_found", + }); + }); + + it.each(["clone", "foreign instance", "wrong actor"] as const)( + "refuses a %s handle without consuming the original actor's observation", + async (kind) => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + const before = f.observed.reads.length; + const promise = + kind === "clone" + ? f.observations.confirm( + f.owner, + structuredClone(observed.observation), + ) + : kind === "foreign instance" + ? f.fresh().observations!.confirm(f.owner, observed.observation) + : f.observations.confirm(f.reviewer, observed.observation); + await expect(promise).rejects.toMatchObject({ + code: kind === "wrong actor" ? "forbidden" : "invalid_request", + }); + expect(f.observed.reads).toHaveLength(before); + await expect( + f.observations.confirm(f.owner, observed.observation), + ).resolves.toMatchObject({ + receipt: f.confirmed.ack.receipt, + }); + }, + ); + + it("consumes before awaited confirmation so concurrent calls cannot reuse it", async () => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + const results = await Promise.allSettled([ + f.observations.confirm(f.owner, observed.observation), + f.observations.confirm(f.owner, observed.observation), + ]); + expect(results.map((value) => value.status).sort()).toEqual([ + "fulfilled", + "rejected", + ]); + expect( + results.find((value) => value.status === "rejected"), + ).toMatchObject({ + reason: { code: "invalid_request" }, + }); + }); + + it("checks current staff again after private context reads before disclosure", async () => { + const f = await prepared(createStore); + f.hooks.afterContext = async () => { + f.principals.delete(f.owner.principalId); + }; + await expect( + f.observations.observe(f.owner, f.key(f.confirmed.ack)), + ).rejects.toMatchObject({ + code: "forbidden", + }); + }); + + it("refreshes a distinct reviewer after the private context observation", async () => { + const f = await prepared(createStore); + f.hooks.afterContext = async () => { + f.principals.delete(f.reviewer.principalId); + }; + await expect( + f.observations.observe(f.owner, f.key(f.confirmed.ack)), + ).rejects.toMatchObject({ code: "forbidden" }); + }); + + it.each(["actor", "reviewer"] as const)( + "checks fresh %s authority after the actual resource confirmation", + async (who) => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + f.hooks.afterConfirm = async () => { + const subject = who === "actor" ? f.owner : f.reviewer; + f.principals.set(subject.principalId, { + ...subject, + permissions: subject.permissions.filter( + (value) => value !== confirmationPermission, + ), + }); + }; + await expect( + f.observations.confirm(f.owner, observed.observation), + ).rejects.toMatchObject({ + code: "forbidden", + }); + await expect( + f.observations.confirm(f.owner, observed.observation), + ).rejects.toMatchObject({ + code: "invalid_request", + }); + }, + ); + + it.each(["draft", "governance", "source", "accepted evidence"] as const)( + "refuses changed %s heads with no synthesized confirmation", + async (change) => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + if (change === "draft") await f.updateDraft(); + else if (change === "governance") + await f.configure({ expectedStagingBuildId: "changed-build" }); + else if (change === "source") + await f.app.setProvenance(f.owner, { + ...f.command( + "change-observed-source", + (await f.current()).generation, + ), + articleId: f.articleId, + references: [], + }); + else await f.submit(f.confirmed.ack, f.packet.input.evidence); + await expect( + f.observations.confirm(f.owner, observed.observation), + ).rejects.toMatchObject({ + code: "report_changed", + }); + }, + ); + + it("retains complete revocation history and refuses a revoked accepted proof", async () => { + const f = await prepared(createStore); + await f.submit(f.confirmed.ack, f.packet.input.evidence); + const accepted = ( + await f.app.getEvidence(f.owner, { articleId: f.articleId }) + ).evidence[0]!; + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + await f.app.revokeEvidence(f.owner, { + ...f.command( + "revoke-observed-evidence", + (await f.current()).generation, + ), + articleId: f.articleId, + articleRevision: accepted.articleRevision, + evidenceId: accepted.id, + evidenceVersion: accepted.version, + evidenceHash: accepted.hash, + reason: "Synthetic current execution revoked", + }); + await expect( + f.observations.confirm(f.owner, observed.observation), + ).rejects.toMatchObject({ code: "report_changed" }); + await expect( + f.observations.observe(f.owner, f.key(f.confirmed.ack)), + ).rejects.toMatchObject({ code: "report_not_verifiable" }); + }); + + it("refuses report reassessment after observing the confirmed cycle", async () => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + await f.decide(f.confirmed.ack, "pending"); + await expect( + f.observations.confirm(f.owner, observed.observation), + ).rejects.toMatchObject({ code: "report_changed" }); + }); + + it("anchors the ledger after the closing report read, including concurrent reset", async () => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + const reportKey = (await f.physicalRows()).find((value) => + value.value.id.startsWith("report:"), + )!.key; + const gate = reportBarrier(); + f.hooks.afterRead = async (collection, key) => { + if (collection === f.namespace && key.id === reportKey.id) { + delete f.hooks.afterRead; + await gate.wait(); + } + }; + const pending = f.observations + .confirm(f.owner, observed.observation) + .then( + (value) => ({ value }), + (error: unknown) => ({ error }), + ); + try { + await gate.reached(pending); + await f.reports.reset(f.reviewer, { + articleId: f.articleId, + commandId: "reset-before-final-observed-head", + expectedLedgerEpoch: f.confirmed.ack.ledgerEpoch, + }); + } finally { + gate.release(); + } + expect(await pending).toMatchObject({ + error: { code: "ledger_epoch_changed" }, + }); + }); + + it("keeps a mutated returned view from rewriting the captured verifier binding", async () => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + const request = await f.verificationRequest( + f.confirmed.ack, + f.packet.input.evidence, + ); + Object.assign(observed.view, { receipt: "fabricated" }); + Object.assign(observed.context.requirements, { + expectedStagingBuildId: "fabricated", + }); + expect( + await f.observations.confirm(f.owner, observed.observation, request), + ).toMatchObject({ + receipt: f.confirmed.ack.receipt, + attestation: { id: f.confirmed.ack.receipt }, + }); + }); + + it("fails closed for an expired proof and retains the legacy verifier's owner ceiling", async () => { + const f = await prepared(createStore); + const observed = await f.observations.observe( + f.owner, + f.key(f.confirmed.ack), + ); + await expect( + f.observations.observe(f.agent, f.key(f.confirmed.ack)), + ).rejects.toMatchObject({ code: "forbidden" }); + f.advance(1_000_000_000); + await expect( + f.observations.confirm(f.owner, observed.observation), + ).rejects.toMatchObject({ code: "report_not_verifiable" }); + const request = await f.verificationRequest( + f.confirmed.ack, + f.packet.input.evidence, + ); + expect(await f.reports.verifier.verify(request)).toBeNull(); + const noEvidence = { + ...f.owner, + permissions: f.owner.permissions.filter( + (value) => value !== knowledgePermissions.evidenceRead, + ), + }; + await expect( + f.observations.observe(noEvidence, f.key(f.confirmed.ack)), + ).rejects.toMatchObject({ code: "forbidden" }); + await expect( + f.observations.confirm(f.owner, {} as KnowledgeReportObservation), + ).rejects.toMatchObject({ code: "invalid_request" }); + }); + }); +}