diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md new file mode 100644 index 0000000..d5a60e7 --- /dev/null +++ b/docs/KNOWLEDGE_COMPOSITION.md @@ -0,0 +1,391 @@ +# Knowledge Base host composition + +This is a **source candidate**, with public activation disabled. The host uses +exact published `@pegma/agent-access@0.1.1` and all four +`@pegma/knowledge-base-*` packages at `0.1.4`, over its existing Identity, +Sessions, stored roles and D1 Store. The public catalog at `/api/mcp` remains +separate from protected article authoring. + +The bounded-maintenance dependency is now installed through the exact alias +`@pegma/rate-limit-paged: npm:@pegma/rate-limit@0.3.3` in +[`package.json`](../package.json) and [`pnpm-lock.yaml`](../pnpm-lock.yaml). +The [published `0.3.3` release](https://github.com/pegma-dev/rate-limit/releases/tag/v0.3.3) +at signed source +[`72358940203e1d398087f2fbe49d33ee95b6fb71`](https://github.com/pegma-dev/rate-limit/commit/72358940203e1d398087f2fbe49d33ee95b6fb71) +passed independent exact-byte, signature/provenance and registry-consumer +verification. Existing Identity and Support Desk keep their +`@pegma/rate-limit@0.2.0` dependency; Support Desk remains at `0.1.1`. + +All four exact KB `0.1.4` packages, including the shared report factory and +governed authoring-context/report-query APIs, are installed in the manifest and +lockfile. The +[verified `0.1.4` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.4) +at signed source +[`541e8c93fe1b15bee9345e59b36325f422f97c50`](https://github.com/pegma-dev/knowledge-base/commit/541e8c93fe1b15bee9345e59b36325f422f97c50) +passed full-set original-byte, signature/provenance and registry-consumer +verification. Recovery retained the original prepared artifact without +repacking; the [release run completed at attempt 5](https://github.com/pegma-dev/knowledge-base/actions/runs/42576167664/attempts/5). +Activation remains disabled; producer verification and installation are not host +or actual-client acceptance. +Do not substitute a source +checkout, local tarball, dependency override, or forced SDK/schema deduplication +for the released producer graph. The catalog transport and protected KB +transport retain their respective released dependencies. + +The current manifest and lockfile pin released KB `0.1.4`, +`@pegma/storage-cloudflare-d1@0.4.6` and genuine `@pegma/storage-core@0.4.0`. +The D1 adapter itself retains that exact Core `0.4.0` dependency; no source alias, +local archive, override or forced Core deduplication supplies the canonical +graph. The frozen registry installation is complete. + +The [qualified D1 `0.4.6` release](https://github.com/pegma-dev/storage-core/releases/tag/v0.4.6) +uses signed source +[`35daa5e679d353fffc9fbf5afe73fe73198d8abf`](https://github.com/pegma-dev/storage-core/commit/35daa5e679d353fffc9fbf5afe73fe73198d8abf) +and annotated tag object `52049598b9088f18cd8fae2a68f243b55cf80815`. +[Release attempt 3 completed successfully](https://github.com/pegma-dev/storage-core/actions/runs/42705318277/attempts/3), +with only D1 newly published and the other package versions reusing their genuine +original archives. Exact registry bytes, source/provenance and public-consumer +verification qualify the producer; they do not qualify this host. + +Installed D1 and Core files match the original release archives byte for byte; +actual public ESM imports resolve the same Core module and error classes. +On Node `22.18.0`, the ordinary checked-in configurations pass type checks and +all 554 tests: 505 Node tests across 45 files, 47 real D1 tests across five files, +and two Bench Ticket Worker/D1/R2 tests. The static build emits 21 pages, and +Wrangler's explicit dry run packages the Worker without uploading it. These +checks use the published registry graph, without source aliases. Earlier +source-alias runs remain historical diagnostics. + +Current-head CI and full reviews remain pending. Actual-client acceptances +remain at zero and no pilot has run. Keep activation disabled through the +remaining deployed-host, staging/privacy and actual-client acceptance gates. + +## Configuration and activation + +`worker/wrangler.jsonc` starts with `PEGMA_KNOWLEDGE_ENABLED=false` and +`PEGMA_AGENT_CLIENTS_JSON=[]`. Disabled requests return before constructing +Identity or opening D1. Scheduled storage maintenance is a separate path and +must continue independently of this request switch. + +Missing or empty client configuration disables the OAuth issuer and delegated +transports. Invalid optional agent configuration also leaves those paths +unavailable without disabling browser guides and human review, provided the +browser's own configuration is valid. No alternate client or authority is +invented as a fallback. + +Client configuration is an explicit JSON array of the released `PublicClient` +shape: `clientId`, `name`, `redirectUris`, `allowedScopes`, and `grantTypes`. +The host bounds it to 16 clients and 16 KiB, rejects unknown fields/scopes, +and delegates redirect and OAuth validation to Agent Access. Never infer a +registration or callback from a synthetic test. Record the actual requested +client, installed version, provider mode, callback and observed flow. There is +no dynamic registration endpoint or client secret. + +Wrangler owns plain variables; deployment replaces dashboard-added plain +variables. Change configuration through review and regenerate Worker types. +The two exact discovery routes belong to Worker ingress. Logical collections +use the existing generic Storage Core schema with +`createSchemaIfMissing:false`; no new SQL migration is added by this slice. + +Keep test collections closed during controlled staff acceptance. The disabled +candidate is not advertised through new global navigation or Account links. +Expose those entry points only after activation requirements pass. Actual +existing-login/Admin consent, device/PKCE flows, scoped API/MCP operations, +revocation, and failure cases must be observed through the requested clients. +Source and full D1 tests do not establish any of the four actual client +acceptances, provider/staging controls, production readiness, or pilot results. + +## Current roles and browser boundaries + +The [host policy](../worker/src/support-access.ts) keeps authority explicit: + +- `Support` retains exactly its original six Support Desk permissions: queue + read, staff reply, notes, assignment, management and Audit read. Existing + assignments are not migrated or silently granted KB powers. +- `Knowledge` is a separately assigned role for collection reads, draft and + evidence work, human report review, publication and withdrawal. Admin-only + collection/governance mutation controls remain separate. +- `Admin` keeps role administration, full intended KB administration and the + exclusive permission to link agents. An Admin explicitly assigns/revokes + `Knowledge` through the existing audited role surface. + +Authenticated accounts receive the named article-read permission; collection +audience policy and the released KB's current publication checks still decide +which guides they can read. Role names do not bypass those checks. +Portal article, search and collection results are withheld if the session or +principal changes, or any captured permission is lost during the read. Added +grants do not invalidate an otherwise authorized result. + +`/account/agents/device` accepts a human-entered/confirmed code of at most 128 +characters. `/account/agents/authorize` displays the exact request and requires +an explicit decision. Existing login resumes only allowlisted same-origin +agent paths; it never auto-approves. Consent pages/data are no-store and +no-referrer. Untrusted text is rendered as text, using external CSP-compatible +scripts; tokens are not placed in URLs or browser storage. + +Consent POSTs reauthenticate after validating the complete request body and +immediately before approval. The fresh context must match the original session, +principal and credential headers. A final check also withholds stale responses +after the service returns; it does not roll back an approval already committed. + +Host-owned JSON POST bodies for portal reads, staff commands, agent test +reports and consent approvals have a ten-second total read deadline, in +addition to the byte limit. Trickle input does not restart that deadline. +An expired body read returns `408 request_timeout`, cancels the reader and +starts no KB read or consent/report command. This bounds body reading; +authentication, storage work and SDK-owned protocol parsing keep their own +boundaries. + +`/api/agent-access/*` composes the released protocol plus browser-only consent +and known-grant controls. Discovery is at +`/.well-known/oauth-authorization-server` and +`/.well-known/oauth-protected-resource/api/knowledge/mcp`. +The canonical audience is `https://pegma.dev/api/knowledge/mcp`; +`/api/knowledge/v1` shares that audience and the same dispatcher. + +Every bearer use and refresh rechecks the active account and current role +permissions. Initial delegated scopes are only draft read, draft write and +evidence submission. They carry no Admin, Support or Knowledge role, linking, +publication, review, collection/governance control, or private provenance +authority. Future scopes require explicit configuration and fresh consent. + +Browser commands use current session, same-origin and CSRF checks; a cookie +alone cannot authenticate protected authoring transports, which require header +bearer authentication. Grant controls are owner-only. After device approval, +the UI reads the actual `GrantView` and displays its returned grant ID/status +and revocation controls; a failed management lookup does not undo accepted +consent. Logout revokes the browser session, not every agent family. + +`/staff/knowledge` exposes capability-gated collection reads, management, +draft/report review, exact publication, article retirement and exact evidence +revocation. `/knowledge` uses only the three signed-in portal operations and +their safe published DTOs, never private evidence/provenance/reviewer data. + +## Human-reviewed test reports and KB acceptance + +An agent with evidence-submission scope submits a bounded report through +`/api/knowledge/reports`, using the current ledger epoch. It can retrieve only +its own safe acknowledgement/status and opaque receipt. Staff inspect full +report text, artifact hashes, execution time/result, and the exact draft, +revision/hash, policy/check/applicability/build and validation requirements. + +Confirmation is a human browser review, not accepted KB evidence or an +automatic test execution. A currently authorized Knowledge reviewer or Admin +may confirm the report, including an Admin who owns its submitting agent. +There is **no reviewer-different-from-submitter or two-person rule**. Agent +scope or a model's assertion alone cannot perform that human confirmation. + +The decision binds the exact submitting principal, ledger epoch, report +generation and complete current review hash. The released requirements DTO +includes governance generation, policy, expected build and check freshness; +raw governance mutation authority is not required to review it. A changed +view requires fresh review. Confirmation never refreshes execution time. + +The agent subsequently calls actual released `submitEvidence` with its +current receipt and exact submission. The host rechecks the confirmation, +receipt generation, submitting identity and current reviewer authority. The +KB independently checks trusted attester/runner, revision/hash/policy, +applicability/build, result and freshness. A human confirmation can still fail +those acceptance prerequisites. A currently trusted reviewer can explicitly +reassess an unchanged, still-fresh report; reassessment clears confirmation, +advances its generation, rotates the opaque receipt and returns it to pending. +The agent retrieves its current status/receipt before resubmission. Reassessment +does not relabel an old execution as a test of a different article revision. + +Article publication still requires the complete current SDK review snapshot. +Report rejection/reset is not KB evidence revocation. Staff use actual +`revokeEvidence` with the exact accepted revision/id/version/hash and generation, +or `retireArticle` with its current generation, for those separate changes. + +## Report retention and replay horizon + +The host ledger permits at most 16 reports and 160 physical rows per article, +with bounded report/Audit/command data. Expired, failed or rejected reports are +not automatically removed merely because execution-age validity has elapsed. +The host has no automatic report TTL eviction; operators own retention and +approved export/deletion procedures. + +Authorized staff can inspect ledger capacity and explicitly reset its current +epoch with an expected-epoch fence. Reset immediately marks the next epoch +`resetting`, permanently invalidating earlier report receipts and command +replays. Cleanup removes at most 48 old rows per drain call; at most four +calls cover the finite ledger. The UI bounds each cleanup pass to four calls +and offers explicit continuation after interruption. New report work resumes +only when the ledger is active. The head retains a bounded reset/history seal, +not an unlimited archive of drained reports, Audit events or receipts. + +Within an active epoch, exact command replay returns its historical bounded +acknowledgement, not a new confirmation or proof that an old receipt generation +is current. Reassessment invalidates earlier receipt generations. Reset ends +that epoch's replay horizon; only the head's latest exact reset operation has +its bounded retry acknowledgement. Preserve required operational evidence +before choosing a reset rather than treating receipts as permanent history. + +There is no report-backed private-source bridge in this integration. Browser +and agent draft inputs cannot attach arbitrary `sourceReferences`; PG01 +provenance remains empty/read-only. A later Support-source integration must +compose the real authorization/withdrawal verifier separately. + +Once the actual KB accepts evidence and publishes revision 1, a later draft +or elapsed report/check TTL alone does not withdraw that approved publication. +Ledger reset/draining also does not erase accepted KB evidence or publication. +The SDK retains its immutable approved revision and own current access/policy, +revocation and retirement gates. Do not convert report retention or a newer +draft into an invented publication-eligibility check. + +## Admission and maintenance + +KB browser admission defaults to 120 requests per five minutes per IP through +`PEGMA_KNOWLEDGE_BROWSER_LIMIT`. Protected resource admission defaults to 300 +through `PEGMA_AGENT_RESOURCE_LIMIT`, shared across HTTP, MCP and report +operations for that IP. These are shared abuse budgets, not per-user quotas; +reviewers behind one egress can share capacity. Both settings accept integers +from 1 through 10,000. UI refusals surface HTTP 429 and `Retry-After`. + +The new source imports the installed separate `@pegma/rate-limit-paged` alias +for verified Rate Limit `0.3.3`. Policy names include +`.v1.limit-` instead of rewriting an immutable descriptor under the old +name. Old Identity/Support policies stay on their existing `0.2.0` import. +New names have independent counters; coordinate configuration changes rather +than assuming old/new budgets combine. The producer dependency is installed; +validating the resulting current head and host acceptance remain activation +prerequisites. + +### Limiter window cleanup and the shared cron + +The [scheduler](../worker/src/index.ts) keeps five distinct cron expressions. +`RATE_LIMIT_CRON` remains `0-57 * * * *`. Its 58 eligible minutes allocate +two isolated rate invocations followed by one ready-hint invocation: + +- UTC minutes with remainder 0 or 1 when divided by three run one + [global limiter cleanup](../worker/src/knowledge-maintenance.ts) page of at + most 20 physical rows: 39 pages per hour. This runs independently of the + Knowledge flag and optional agent registrations. +- Minutes with remainder 2 run one + [ready-hint page](../worker/src/knowledge-retrieval-ready.ts) when Knowledge + is enabled: 19 pages per hour. They do not also run limiter cleanup or + physical KB recovery. An empty ready queue does not trigger another heavy + task. This reduces the previous 29 ready opportunities to 19; ready hints + remain a latency aid, with atomic SDK jobs and physical recovery preserved. + +The original four other expressions and all 15 rotating cleanup lanes remain +in place. Minutes 58 and 59 have no `RATE_LIMIT_CRON` invocation. Before +merging, inventory every Worker's current cron triggers in the deployment +account: pushes to `main` deploy these schedules even while Knowledge is +disabled. Deployment replaces this Worker's existing expressions with these +five. The [Workers Free allowance is five triggers per account](https://developers.cloudflare.com/workers/platform/limits/#account-plan-limits), +so this configuration leaves no capacity for another Worker's triggers. +Require the account total after replacement to fit its effective allowance; +if it does not, hold the merge and revise the scheduling design. Repeat this +check before later deployments that change schedules. Retrieval shares the +fifth expression and does not register a sixth. + +The limiter bookmark advances only after success, retaining the prior +continuation on failure. Follow no-deletion pages and repeat complete cycles; +pages are not snapshots. Descriptors, malformed/legacy `0.2.0` rows and +unknown layouts remain retained. This does not silently migrate old limiter +storage; existing Identity/Support maintenance remains in place. + +The scheduled limiter ceiling is 780 physical rows per hour if all 39 pages +succeed and fill. Live windows, descriptors, retained rows and cursor-cycle +overhead consume slots, so this is not a deletion or expiry guarantee. The +synthetic capacity regression creates 50 browser IP subjects plus one subject +in each of six Agent Access policy shapes per five-minute cohort: 672 counters +per hour for four continuing hours, then two hours without new arrivals. +Seven persistent descriptors, live windows and the minute-58/59 gaps remain +in the actual Store. It checks backlog and oldest-expiry age at the same +workload phase after warmup, cursor-cycle progress and eventual drainage. +This finite workload is not a production benchmark, universal arrival-rate +bound or passed-gate claim in this guide. + +Descriptor reads, conditional deletes and checkpoint work add storage +operations beyond the scan-row limit. Validate the complete scheduled handler +against the Free 50-call D1 budget. The real-D1 fixture counts actual binding +executions, including batches and checkpoints, and has a calibration that +throws before backend execution 51. That does not prove the Free 10 ms CPU +budget, daily row quotas or live capacity. Activation also requires measured +runtime budgets, full cursor-cycle progress and sustained deletion throughput +under actual load. + +### Retrieval projection repair + +Publication and indexing are separate durable work. After an accepted +`publishArticle`, `retireArticle` or `revokeEvidence`, the +[request hook](../worker/src/knowledge-runtime.ts) attempts one nonthrowing, +body-free ready-hint overwrite for that article. It no longer awaits inline +`repairArticleIndex`. The record contains only a hash key, article identity, +format and trusted request time in `pegma-dev.knowledge-retrieval-ready.v1`; +it contains no report, evidence or article body. Duplicate acknowledgements +can overwrite the same hint. Enqueue or diagnostic failures do not undo the +committed command. The existing final browser-authority check still runs and +can withhold its acknowledgement if authority changed. + +The ready worker scans one physical hint and calls the actual SDK +`repairArticleIndex` with `maxBatches:1`. This bounds attempted derived +transactions, including contention, rather than allowing an unbounded retry +loop. It deletes only the exact scanned Store key/version after that call +returns `status:'ready'`; `indexed:false` is a converged withdrawal. Pending, +blocked and failed work retain their hints. A newer enqueue changes the opaque +Store version and wins over an older worker's conditional deletion. + +The ready cursor rotates past a failed item so other hints can progress, then +revisits retained work on later cycles. It uses the separate +`pegma-dev-maintenance` key `{ partition:'knowledge', id:'retrieval-ready' }`. +The physical recovery worker retains `{ partition:'knowledge', id:'retrieval' }`. +Both checkpoints use a bounded opaque cursor and safe-integer monotonic +generation, with one OCC attempt and a generation increment even for +`null` to `null`. Scan/checkpoint failures preserve saved progress; delayed +completions cannot overwrite a newer generation. Already committed projection +writes are not rolled back after acknowledgement uncertainty. + +The existing Knowledge turn in the +[15-lane cleanup schedule](../worker/src/maintenance-schedule.ts) independently +calls `repairRetrievalPage` with `limit:1` and `maxBatches:1`. Complete physical +cycles and the SDK's existing atomic article-change jobs remain the recovery +path for a lost hint, collection/policy changes and unfinished work. The ready +queue is a latency aid, not the authority or sole delivery guarantee. +Physical recovery still includes no-match pages and repeated cycles; a large +corpus or persistent failures can delay convergence. No indexing latency or +live SLA is claimed. + +Both projection paths use the existing AuthCore-resolved, server-owned +principal with only `knowledge.index.manage`, without an Admin role or new +human/agent permission. Scheduled composition opens a separate Store with +`createSchemaIfMissing:false` and explicit `readBatchSize:512`, then constructs +the actual application from that Store and clock. It does not initialize +Identity, mail, sessions, reports or agent registrations. Projection work +checks the current `PEGMA_KNOWLEDGE_ENABLED=true` flag before Store access and +after awaits; disabled ticks do no projection work. Limiter cleanup remains +independent of that flag and projection failures. + +This phase has no private-source eligibility verifier. Retained nonempty +`privateSources` references remain blocked/unavailable. A future source-enabled +composition must provide its real authorization/withdrawal ports in both +request and repair paths; there is no allow-all fallback. HTTP handlers do not +scan the corpus or expose maintenance DTOs. Coarse diagnostics contain counts +and fixed stages, not article IDs, cursors, queries, private bodies or exception +text. + +Projection-dependent portal discovery/search stays empty or unavailable until +current repair qualifies it. Known-ID publication reads retain their existing +SDK authority checks. Retirement, evidence revocation and audience withdrawal +are filtered immediately, before a worker removes stale hints; an index entry +cannot grant access, restore approval or serve as customer confirmation of an +unqualified publication. + +Earlier local candidate measurements of the awaited inline path reached 118 +D1 calls for publication and 104 for evidence revocation, above the 50-call +limit despite successful logical responses. The real-D1 +profiling fixture now passes on the canonical published graph. It exercises whole HTTP/MCP and scheduled +invocations, including genuine 32-proof/96-revocation history, pending work, +transport failure, newer enqueue races and lost-hint recovery, with a hard +50-call guard on the bounded Free-plan cases. This local result does not +establish deployed CPU limits, daily quotas or sustained production throughput. +Preserve all authority and history checks, keep activation disabled and complete +the live-platform gates before use. + +Disable the feature if acceptance fails. Identity, role administration, human +Support Desk and the public catalog retain their original composition. No +model/provider, automatic publication, GitHub export or customer notification +is enabled by this slice. Production settings, installed-client results, +staging/privacy controls and supervised pilots remain host-owned proof. diff --git a/docs/catalog/RECIPE_BACKLOG.md b/docs/catalog/RECIPE_BACKLOG.md index 62894b6..2208bbe 100644 --- a/docs/catalog/RECIPE_BACKLOG.md +++ b/docs/catalog/RECIPE_BACKLOG.md @@ -90,7 +90,7 @@ deferred). | --- | --- | | **Intent** | A fictional makerspace helpdesk (“Bench Ticket”) runs a small support-desk site with first-party email-code login, sessions, mail to a catcher, and ticket create/list/reply. | | **Packages (published)** | `@pegma/identity`, `@pegma/sessions`, `@pegma/mail`, `@pegma/rate-limit`, `@pegma/health`, `@pegma/support-desk-*`, `@pegma/storage-core`, `@pegma/spine` | -| **Adapters** | memory (local Docker); `storage-cloudflare-d1`; `storage-azure-tables`; forthcoming `storage-dynamodb` | +| **Adapters** | memory (local Docker); `storage-cloudflare-d1`; `storage-azure-tables`; published `storage-dynamodb@0.4.5` | | **Host must provide** | HTTP, cookies, injected Store, mail catcher, email-code secret | | **Non-goals** | Auth0/Entra/Cognito, Stripe, production email, passkeys-required login | | **Anti-patterns** | Treating Support Desk as hosted SaaS; giving Audit/Mail their own store | diff --git a/evals/assembly-eval.test.ts b/evals/assembly-eval.test.ts index bc3a2d7..0e7b7db 100644 --- a/evals/assembly-eval.test.ts +++ b/evals/assembly-eval.test.ts @@ -21,7 +21,8 @@ const EVAL_NPM: Record = { '@pegma/spine': '0.1.1', '@pegma/storage-core': '0.4.0', '@pegma/storage-azure-tables': '0.4.0', - '@pegma/storage-cloudflare-d1': '0.4.1', + '@pegma/storage-cloudflare-d1': '0.4.6', + '@pegma/storage-dynamodb': '0.4.5', '@pegma/storage-blobs': '0.1.0', '@pegma/storage-azure-blob': '0.1.0', '@pegma/storage-cloudflare-r2': '0.1.0', @@ -102,7 +103,9 @@ describe('assembly eval harness (Phase 5)', () => { it('compiles the real catalog artifact (not a hand-built twin)', () => { expect(catalog.schemaVersion).toBe('0.1.0'); expect(catalog.components.length).toBe(components.length); - const scaffold = catalog.recipes.find((r) => r.id === 'static-brochure-minimal'); + const scaffold = catalog.recipes.find( + (r) => r.id === 'static-brochure-minimal', + ); expect(scaffold?.fixture.status).toBe('green'); expect(scaffold?.fixture.citation).toContain('scaffold-cf-minimal'); expect(scaffold?.capabilityTags).toEqual(['static_host']); @@ -132,13 +135,17 @@ describe('assembly eval harness (Phase 5)', () => { } expect(withCatalog.passRate).toBe(1); - const staticCase = withCatalog.cases.find((c) => c.id === 'static-brochure')!; + const staticCase = withCatalog.cases.find( + (c) => c.id === 'static-brochure', + )!; expect(staticCase.primaryRecipeId).toBe('static-brochure-minimal'); - const healthCase = withCatalog.cases.find((c) => c.id === 'health-endpoint-only')!; + const healthCase = withCatalog.cases.find( + (c) => c.id === 'health-endpoint-only', + )!; expect(healthCase.primaryRecipeId).not.toBe('static-brochure-minimal'); - expect(healthCase.packageNames.some((p) => p.includes('@pegma/health'))).toBe( - true, - ); + expect( + healthCase.packageNames.some((p) => p.includes('@pegma/health')), + ).toBe(true); }); }); diff --git a/package.json b/package.json index 2a186c0..c53713d 100644 --- a/package.json +++ b/package.json @@ -17,10 +17,11 @@ "worker:dev": "wrangler dev -c worker/wrangler.jsonc", "worker:deploy": "wrangler deploy -c worker/wrangler.jsonc", "worker:tail": "wrangler tail pegma-dev-api", - "worker:types": "wrangler types worker/worker-configuration.d.ts -c worker/wrangler.jsonc" + "worker:types": "wrangler types worker/worker-configuration.d.ts -c worker/wrangler.jsonc && node scripts/normalize-worker-types.mjs" }, "dependencies": { "@modelcontextprotocol/server": "^2.0.0", + "@pegma/agent-access": "0.1.1", "@pegma/audit": "0.2.0", "@pegma/authorization-admin": "0.4.0", "@pegma/authorization-core": "0.4.0", @@ -29,14 +30,19 @@ "@pegma/authorization-storage": "0.4.0", "@pegma/health": "^0.2.0", "@pegma/identity": "0.1.2", + "@pegma/knowledge-base-application": "0.1.4", + "@pegma/knowledge-base-contracts": "0.1.4", + "@pegma/knowledge-base-core": "0.1.4", + "@pegma/knowledge-base-mcp": "0.1.4", "@pegma/logger-cloudflare": "^0.1.1", "@pegma/logger-datadog": "^0.1.1", "@pegma/logger-tee": "^0.1.1", "@pegma/mail": "0.1.1", "@pegma/rate-limit": "0.2.0", + "@pegma/rate-limit-paged": "npm:@pegma/rate-limit@0.3.3", "@pegma/sessions": "0.2.0", "@pegma/spine": "^0.1.1", - "@pegma/storage-cloudflare-d1": "0.4.1", + "@pegma/storage-cloudflare-d1": "0.4.6", "@pegma/storage-core": "0.4.0", "@pegma/support-desk-application": "0.1.1", "@pegma/support-desk-contracts": "0.1.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 310204f..ba6c290 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -11,6 +11,9 @@ importers: '@modelcontextprotocol/server': specifier: ^2.0.0 version: 2.0.0 + '@pegma/agent-access': + specifier: 0.1.1 + version: 0.1.1 '@pegma/audit': specifier: 0.2.0 version: 0.2.0 @@ -35,6 +38,18 @@ importers: '@pegma/identity': specifier: 0.1.2 version: 0.1.2 + '@pegma/knowledge-base-application': + specifier: 0.1.4 + version: 0.1.4 + '@pegma/knowledge-base-contracts': + specifier: 0.1.4 + version: 0.1.4 + '@pegma/knowledge-base-core': + specifier: 0.1.4 + version: 0.1.4 + '@pegma/knowledge-base-mcp': + specifier: 0.1.4 + version: 0.1.4 '@pegma/logger-cloudflare': specifier: ^0.1.1 version: 0.1.1 @@ -50,6 +65,9 @@ importers: '@pegma/rate-limit': specifier: 0.2.0 version: 0.2.0 + '@pegma/rate-limit-paged': + specifier: npm:@pegma/rate-limit@0.3.3 + version: '@pegma/rate-limit@0.3.3' '@pegma/sessions': specifier: 0.2.0 version: 0.2.0 @@ -57,8 +75,8 @@ importers: specifier: ^0.1.1 version: 0.1.1 '@pegma/storage-cloudflare-d1': - specifier: 0.4.1 - version: 0.4.1 + specifier: 0.4.6 + version: 0.4.6 '@pegma/storage-core': specifier: 0.4.0 version: 0.4.0 @@ -79,7 +97,7 @@ importers: version: 0.1.1 agents: specifier: ^0.20.1 - version: 0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.4.3) + version: 0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.6)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.4.3) zod: specifier: ^4.4.3 version: 4.4.3 @@ -398,6 +416,9 @@ packages: '@cfworker/json-schema@4.1.1': resolution: {integrity: sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==} + '@cfworker/json-schema@4.1.6': + resolution: {integrity: sha512-YzVGTHXf4bzlyAL5KAvHYCdNbbt6zM5cYkAgxqxQPDQM6aZ4ShIIN5yJ+6q7YeonnevxT8k/LmD2tJi/jOiKkg==} + '@clack/core@1.4.3': resolution: {integrity: sha512-/kr3UWNtdJfxZtPgDqUOmG2pvwlmcLGheex5yiZKdwbzZJxhV+HMNR9QNmyY5cGwTNV6LrR7Jtp+KjhUAP1qBQ==} engines: {node: '>= 20.12.0'} @@ -1018,6 +1039,16 @@ packages: '@cfworker/json-schema': optional: true + '@modelcontextprotocol/sdk@1.32.2': + resolution: {integrity: sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==} + engines: {node: '>=18'} + peerDependencies: + '@cfworker/json-schema': ^4.1.1 + zod: ^3.25 || ^4.0 + peerDependenciesMeta: + '@cfworker/json-schema': + optional: true + '@modelcontextprotocol/server@2.0.0': resolution: {integrity: sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==} engines: {node: '>=20'} @@ -1075,6 +1106,10 @@ packages: resolution: {integrity: sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==} engines: {node: '>=20.0.0'} + '@pegma/agent-access@0.1.1': + resolution: {integrity: sha512-C8t2kkv2piE9Jxt48hrRj+dYDoBd4BMgyO9JpgBQT5ycr8xZx4hq43DSG9I/KjjPQhEvRhp7obYnZ/IiBme/Jw==} + engines: {node: '>=22'} + '@pegma/audit@0.2.0': resolution: {integrity: sha512-gUcfdp1QrLJtaMImA9NzZWfDEIuqBkALepceDIl1NPyCt0ZcdMs2ud8GuppQY5wXCB1/rgCYWYzep2OkDCrMBA==} engines: {node: '>=22'} @@ -1119,6 +1154,22 @@ packages: resolution: {integrity: sha512-r8AsVTnwCSBU2LZZjieW5FgIJ2TUWi5DlU9kp+4tuaWDFfl85EezkD6F5omAFjTnaFqCRN1T2d/KsHoESarB2A==} engines: {node: '>=22'} + '@pegma/knowledge-base-application@0.1.4': + resolution: {integrity: sha512-j27QtdalETp3VW/bn92dmrGhzcorCuXeh79O1+2C0eY9QgRYP1eThN07op8DsQqjZJeyrwezU+I+mCvwkzV+Hg==} + engines: {node: '>=22'} + + '@pegma/knowledge-base-contracts@0.1.4': + resolution: {integrity: sha512-en4R5pLgKhMnnJqtA4A2A/5hUdQZWsUV+XbzlLdQCYqIABnJnLehL+MhwTvwZJfYdaddrhfBwPPJk/EL/DYajg==} + engines: {node: '>=22'} + + '@pegma/knowledge-base-core@0.1.4': + resolution: {integrity: sha512-eztpYFfXyTgvJTgx9PxitXkwLrFP+h03yJYxhQnM8mbNZNjulXF1j//eH8FjmQZzLRDGU1vW9Ec35T9xL43G1A==} + engines: {node: '>=22'} + + '@pegma/knowledge-base-mcp@0.1.4': + resolution: {integrity: sha512-Lk9Ig88bIWsxVEzutPJLLwv6yfK+e7QjdmnWPArDCe+NahmNtAWrLK7fomslmJ+PCEHMh3EeXzi85xxPuJHGow==} + engines: {node: '>=22'} + '@pegma/logger-cloudflare@0.1.1': resolution: {integrity: sha512-ZAcj5ekxWvpBtx3yzNeNBiydYlYsUMPyKcQEbsbuyGktdlTObKrnUYnyZn/8KL5cvKSoLO5GnsFW2pxIeXaMZA==} engines: {node: '>=22'} @@ -1139,6 +1190,10 @@ packages: resolution: {integrity: sha512-gzaXefDW4Rg9Yla5qQOEeDChIm8hoYS6Eed1a4UNZb4BIJAcIkePwz5aZL6Ld5xCk3g8oTWdii78PLplwrzN9A==} engines: {node: '>=22'} + '@pegma/rate-limit@0.3.3': + resolution: {integrity: sha512-Bu2t3WjD4VsQj5lWnz+XZ0KQ/F2rbs1CkDmH6aSl9kCg1cYNZHviL9o5XJhbsA7siFo9G+FOJXK2REnnzWtk9Q==} + engines: {node: '>=22'} + '@pegma/sessions@0.2.0': resolution: {integrity: sha512-dHGmFzQjHe9O+arGEQUcwutLuZ9+cA409hetiqxzQUXIOHOulOsA4/ywlDDRGiskMijyXLVlxvmGryjxV8NxZQ==} engines: {node: '>=22'} @@ -1147,8 +1202,12 @@ packages: resolution: {integrity: sha512-EV0Zq8KJX7r7ybI+eIHUCAhnd261bveZykMQVmmZibSDRJVcd2bOuYCPvPg4wax7GmrUrdtVFJYEJqHl4PkhwQ==} engines: {node: '>=22'} - '@pegma/storage-cloudflare-d1@0.4.1': - resolution: {integrity: sha512-nVH+ppAWi3QwyEX8QVkPOLXNjtblO0jDnnGqCHpbZZzPvFQAVyd/1Bhxg8JdsuOD/UWGktJ26asAKzpNjRol0w==} + '@pegma/spine@0.1.2': + resolution: {integrity: sha512-jueFYJ3oJUacKdiERkEZ7R34xDMiEWXqn4MSA5bpTXzsXhWSap4EJUzKXtXnXuLPPjwJWLn5uoQe98kWQ6NS8A==} + engines: {node: '>=22'} + + '@pegma/storage-cloudflare-d1@0.4.6': + resolution: {integrity: sha512-DjBRoRq5C6sWgL2KWdWOcW0F3N7HHuRu1i7Gr8SM4Aeh4FpEh1hQwIdMvkXpPHCd48CMqLJz8M5HYYR+/sRUgw==} engines: {node: '>=22'} '@pegma/storage-core@0.4.0': @@ -3079,6 +3138,9 @@ packages: zod@4.4.3: resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + zwitch@2.0.4: resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} @@ -3399,6 +3461,8 @@ snapshots: '@cfworker/json-schema@4.1.1': {} + '@cfworker/json-schema@4.1.6': {} + '@clack/core@1.4.3': dependencies: fast-wrap-ansi: 0.2.2 @@ -3822,13 +3886,13 @@ snapshots: eventsource-parser: 3.1.0 jose: 6.2.4 pkce-challenge: 5.0.1 - zod: 4.4.3 + zod: 4.6.7 '@modelcontextprotocol/core@2.0.0': dependencies: - zod: 4.4.3 + zod: 4.6.7 - '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)': + '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.6)(zod@4.4.3)': dependencies: '@hono/node-server': 2.0.12(hono@4.12.32) ajv: 8.20.0 @@ -3848,7 +3912,31 @@ snapshots: zod: 4.4.3 zod-to-json-schema: 3.25.2(zod@4.4.3) optionalDependencies: - '@cfworker/json-schema': 4.1.1 + '@cfworker/json-schema': 4.1.6 + transitivePeerDependencies: + - supports-color + + '@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)': + dependencies: + '@hono/node-server': 2.0.12(hono@4.12.32) + ajv: 8.20.0 + ajv-formats: 3.0.1(ajv@8.20.0) + content-type: 1.0.5 + cors: 2.8.6 + cross-spawn: 7.0.6 + eventsource: 3.0.7 + eventsource-parser: 3.1.0 + express: 5.2.1 + express-rate-limit: 8.6.1(express@5.2.1) + hono: 4.12.32 + jose: 6.2.4 + json-schema-typed: 8.0.2 + pkce-challenge: 5.0.1 + raw-body: 3.0.2 + zod: 4.6.7 + zod-to-json-schema: 3.25.2(zod@4.6.7) + optionalDependencies: + '@cfworker/json-schema': 4.1.6 transitivePeerDependencies: - supports-color @@ -3975,6 +4063,13 @@ snapshots: tslib: 2.8.1 tsyringe: 4.10.0 + '@pegma/agent-access@0.1.1': + dependencies: + '@pegma/audit': 0.2.0 + '@pegma/authorization-core': 0.4.0 + '@pegma/spine': 0.1.2 + '@pegma/storage-core': 0.4.0 + '@pegma/audit@0.2.0': dependencies: '@pegma/spine': 0.1.1 @@ -4027,6 +4122,35 @@ snapshots: unicode-case-folding: 1.1.1 unorm: 1.6.0 + '@pegma/knowledge-base-application@0.1.4': + dependencies: + '@pegma/audit': 0.2.0 + '@pegma/authorization-core': 0.4.0 + '@pegma/knowledge-base-contracts': 0.1.4 + '@pegma/knowledge-base-core': 0.1.4 + '@pegma/spine': 0.1.2 + '@pegma/storage-core': 0.4.0 + + '@pegma/knowledge-base-contracts@0.1.4': + dependencies: + '@pegma/spine': 0.1.2 + + '@pegma/knowledge-base-core@0.1.4': + dependencies: + '@pegma/knowledge-base-contracts': 0.1.4 + + '@pegma/knowledge-base-mcp@0.1.4': + dependencies: + '@cfworker/json-schema': 4.1.6 + '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7) + '@pegma/authorization-core': 0.4.0 + '@pegma/knowledge-base-application': 0.1.4 + '@pegma/knowledge-base-contracts': 0.1.4 + '@pegma/knowledge-base-core': 0.1.4 + zod: 4.6.7 + transitivePeerDependencies: + - supports-color + '@pegma/logger-cloudflare@0.1.1': dependencies: '@pegma/spine': 0.1.1 @@ -4049,6 +4173,11 @@ snapshots: '@pegma/spine': 0.1.1 '@pegma/storage-core': 0.4.0 + '@pegma/rate-limit@0.3.3': + dependencies: + '@pegma/spine': 0.1.1 + '@pegma/storage-core': 0.4.0 + '@pegma/sessions@0.2.0': dependencies: '@pegma/spine': 0.1.1 @@ -4056,7 +4185,9 @@ snapshots: '@pegma/spine@0.1.1': {} - '@pegma/storage-cloudflare-d1@0.4.1': + '@pegma/spine@0.1.2': {} + + '@pegma/storage-cloudflare-d1@0.4.6': dependencies: '@pegma/storage-core': 0.4.0 @@ -4360,12 +4491,12 @@ snapshots: mime-types: 3.0.2 negotiator: 1.0.0 - agents@0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.4.3): + agents@0.20.1(@babel/core@8.0.1)(@babel/runtime@7.29.7)(@cloudflare/workers-types@5.20260729.1)(@modelcontextprotocol/client@2.0.0)(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.6)(zod@4.4.3))(@modelcontextprotocol/server@2.0.0)(react@19.2.8)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0))(zod@4.4.3): dependencies: '@babel/plugin-proposal-decorators': 8.0.2(@babel/core@8.0.1) '@cfworker/json-schema': 4.1.1 '@modelcontextprotocol/client': 2.0.0 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3) + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.6)(zod@4.4.3) '@modelcontextprotocol/server': 2.0.0 '@rolldown/plugin-babel': 0.2.3(@babel/core@8.0.1)(@babel/runtime@7.29.7)(rolldown@1.1.5)(vite@8.1.5(@types/node@26.1.1)(esbuild@0.28.1)(tsx@4.23.13)(yaml@2.9.0)) cron-schedule: 6.0.0 @@ -6005,8 +6136,14 @@ snapshots: dependencies: zod: 4.4.3 + zod-to-json-schema@3.25.2(zod@4.6.7): + dependencies: + zod: 4.6.7 + zod@3.25.76: {} zod@4.4.3: {} + zod@4.6.7: {} + zwitch@2.0.4: {} diff --git a/public/_headers b/public/_headers index 748736c..2f4fa11 100644 --- a/public/_headers +++ b/public/_headers @@ -8,3 +8,19 @@ Content-Security-Policy: default-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none' Permissions-Policy: camera=(), microphone=(), geolocation=(), publickey-credentials-create=(self), publickey-credentials-get=(self) Cross-Origin-Opener-Policy: same-origin + +/account/agents/* + Cache-Control: no-store + Referrer-Policy: no-referrer + X-Robots-Tag: noindex, nofollow + +/staff/knowledge + Cache-Control: no-store + Referrer-Policy: no-referrer + X-Robots-Tag: noindex, nofollow + +/knowledge + Cache-Control: no-store + +/knowledge/* + Cache-Control: no-store diff --git a/public/account.js b/public/account.js index f8ae53f..8e00769 100644 --- a/public/account.js +++ b/public/account.js @@ -16,6 +16,41 @@ let emailCodeHandle = ''; let emailChallengeFlow = 'sign-in'; let passkeyRemovalAvailable = false; +function agentReturnPath() { + const candidates = new URLSearchParams(window.location.search).getAll( + 'returnTo', + ); + if (candidates.length !== 1) return null; + const value = candidates[0]; + if ( + value.length > 16_384 || + !value.startsWith('/') || + value.startsWith('//') || + /[\\\u0000-\u001f\u007f]/u.test(value) + ) + return null; + try { + const destination = new URL(value, window.location.origin); + const path = destination.pathname.replace(/\/$/u, ''); + const allowed = [ + '/account/agents/authorize', + '/account/agents/device', + '/api/agent-access/authorize', + ]; + if ( + destination.origin !== window.location.origin || + destination.hash || + !allowed.includes(path) + ) + return null; + return `${path}${destination.search}`; + } catch { + return null; + } +} + +const agentContinuation = agentReturnPath(); + function showStatus(message, isError = false) { statusNode.textContent = message; statusNode.dataset.tone = isError ? 'error' : 'neutral'; @@ -184,6 +219,7 @@ async function refreshAccount() { signedOut.hidden = true; signedIn.hidden = false; showStatus('Your account is ready.'); + if (agentContinuation !== null) window.location.replace(agentContinuation); return true; } catch (error) { if (error.status !== 401) { diff --git a/public/agent-access.js b/public/agent-access.js new file mode 100644 index 0000000..ee85bb0 --- /dev/null +++ b/public/agent-access.js @@ -0,0 +1,374 @@ +const flow = document.querySelector('[data-agent-flow]').dataset.agentFlow; +const statusNode = document.querySelector('#agent-status'); +const signedOut = document.querySelector('#agent-signed-out'); +const panel = document.querySelector('#agent-panel'); +const requestPanel = document.querySelector('#agent-request'); +const consentForm = document.querySelector('#agent-consent'); +const deviceForm = document.querySelector('#agent-device-code'); +const userCodeInput = document.querySelector('#agent-user-code'); +const grantInput = document.querySelector('#agent-grant-id'); +const grantPanel = document.querySelector('#agent-grant'); +const revokeButton = document.querySelector('#agent-revoke'); +let csrfToken = ''; +let approval = null; +let approvalUserCode = ''; +let currentGrant = null; +let loadGeneration = 0; +let grantGeneration = 0; +let mutationPending = false; +let approvedLookupSelector = ''; + +const messages = { + forbidden: 'Your current account does not have Admin access.', + not_found: 'That request or grant is unavailable.', + expired: 'That request has expired. Start a new connection in your agent.', + invalid_request: 'Check the request or device code and try again.', + unavailable: 'Agent access is not available right now.', + rate_limited: 'Please wait before trying again.', +}; + +function status(message, error = false) { + statusNode.textContent = message; + statusNode.dataset.tone = error ? 'error' : 'neutral'; +} + +function retryMessage(error) { + return Number.isFinite(error.retryAfterSeconds) + ? `Too many requests. Try again in ${error.retryAfterSeconds} second(s).` + : 'Too many requests. Wait before trying again.'; +} + +function retryAfter(response) { + const value = response.headers.get('Retry-After'); + if (value === null) return undefined; + const seconds = /^\d+$/u.test(value) + ? Number(value) + : Math.ceil((Date.parse(value) - Date.now()) / 1000); + return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined; +} + +async function failure( + error, + isCurrent = () => true, + resource = false, + acceptedConsent = false, +) { + if (!isCurrent()) return; + const prefix = acceptedConsent + ? 'Consent was accepted, but grant controls could not be loaded. ' + : ''; + if (error.status === 403 && resource) { + try { + const state = await api('/api/agent-access/state'); + if (!isCurrent()) return; + csrfToken = state.csrfToken; + status( + `${prefix}That request or grant is not available to this account. Other Admin controls remain available.`, + true, + ); + return; + } catch (authorityError) { + if (!isCurrent()) return; + if (authorityError.status !== 401 && authorityError.status !== 403) { + status( + `${prefix}${authorityError.status === 429 ? retryMessage(authorityError) : 'Current Admin access could not be checked. Retry the lookup.'}`, + true, + ); + return; + } + error = authorityError; + } + } + if (!isCurrent()) return; + if (error.status === 401) { + ++loadGeneration; + ++grantGeneration; + csrfToken = ''; + approval = null; + currentGrant = null; + panel.hidden = true; + signedOut.hidden = false; + status(`${prefix}Sign in to continue.`); + return; + } + if (error.status === 403) { + ++loadGeneration; + ++grantGeneration; + approval = null; + currentGrant = null; + csrfToken = ''; + panel.hidden = true; + } + status( + prefix + + (error.status === 429 + ? retryMessage(error) + : (messages[error.message] ?? + (error.status === 403 + ? messages.forbidden + : 'The request could not be completed. Refresh and try again.'))), + true, + ); +} + +async function api(path, init = {}) { + const headers = new Headers(init.headers); + if (init.body !== undefined) headers.set('Content-Type', 'application/json'); + if (csrfToken) headers.set('X-Pegma-CSRF', csrfToken); + const response = await fetch(path, { + ...init, + headers, + credentials: 'same-origin', + cache: 'no-store', + referrerPolicy: 'no-referrer', + }); + const body = response.status === 204 ? null : await response.json(); + if (!response.ok) { + const error = new Error( + typeof body?.error === 'string' ? body.error : 'unavailable', + ); + error.status = response.status; + error.retryAfterSeconds = retryAfter(response); + throw error; + } + return body; +} + +function details(node, entries) { + node.replaceChildren(); + for (const [label, value] of entries) { + const term = document.createElement('dt'); + const description = document.createElement('dd'); + term.textContent = label; + description.textContent = String(value); + node.append(term, description); + } +} + +function parameter(name) { + const values = new URLSearchParams(window.location.search).getAll(name); + return values.length === 1 && values[0].length <= 128 ? values[0] : ''; +} + +function setMutationPending(pending) { + mutationPending = pending; + for (const button of consentForm.querySelectorAll('button')) + button.disabled = pending || approval?.status !== 'pending'; + revokeButton.disabled = + pending || currentGrant === null || currentGrant.status === 'revoked'; +} + +async function loadApproval(selector, userCode = '') { + const generation = ++loadGeneration; + const isCurrent = () => generation === loadGeneration; + approval = null; + requestPanel.hidden = true; + status('Loading the request...'); + try { + const result = await api(`/api/agent-access/approval?${selector}`); + if (!isCurrent()) return; + if (result.flow !== flow) throw new Error('invalid_request'); + approval = result; + approvalUserCode = userCode; + document.querySelector('#agent-client').textContent = result.clientName; + details(document.querySelector('#agent-details'), [ + ['Client ID', result.clientId], + ['Resource', result.resource], + ['Request ID', result.requestId], + ['Status', result.status], + ['Expires', result.expiresAt], + ]); + const scopes = document.querySelector('#agent-scopes'); + scopes.replaceChildren(); + for (const [index, scope] of result.requestedScopes.entries()) { + const row = document.createElement('p'); + const checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + checkbox.name = 'scope'; + checkbox.value = scope.name; + checkbox.id = `agent-scope-${index}`; + checkbox.checked = true; + const label = document.createElement('label'); + label.htmlFor = checkbox.id; + label.textContent = `${scope.description} (${scope.name})`; + row.append(checkbox, label); + scopes.append(row); + } + requestPanel.hidden = false; + setMutationPending(mutationPending); + status( + result.status === 'pending' + ? 'Review the request and choose approve or deny.' + : `This request is ${result.status}.`, + ); + } catch (error) { + await failure(error, isCurrent, true); + } +} + +consentForm.addEventListener('submit', async (event) => { + event.preventDefault(); + if (mutationPending || approval?.status !== 'pending') return; + const decision = event.submitter?.value; + if (decision !== 'approve' && decision !== 'deny') return; + const selected = [ + ...consentForm.querySelectorAll('input[name="scope"]:checked'), + ].map((input) => input.value); + if (decision === 'approve' && selected.length === 0) { + status('Select at least one permission, or deny this request.', true); + return; + } + const request = { requestId: approval.requestId, decision }; + if (decision === 'approve') request.approvedScopes = selected; + if (flow === 'device_code') request.userCode = approvalUserCode; + ++loadGeneration; + ++grantGeneration; + setMutationPending(true); + try { + const result = await api('/api/agent-access/approval', { + method: 'POST', + body: JSON.stringify(request), + }); + approval = null; + requestPanel.hidden = true; + if (result.flow === 'authorization_code') { + // Only the server's registered-client callback is used; never a query-string return URL. + const callback = new URL(result.redirectUri); + const loopback = ['localhost', '127.0.0.1', '[::1]'].includes( + callback.hostname, + ); + if ( + callback.protocol !== 'https:' && + !(callback.protocol === 'http:' && loopback) + ) + throw new Error('invalid_request'); + window.location.assign(callback.href); + return; + } + if (result.flow !== 'device_code') throw new Error('invalid_request'); + window.history.replaceState(null, '', window.location.pathname); + if (userCodeInput) userCodeInput.value = ''; + if (result.approved) { + approvedLookupSelector = request.requestId; + document.querySelector('#agent-approved-grant').hidden = false; + await loadGrant(approvedLookupSelector, true); + } else status('Request denied.'); + } catch (error) { + await failure(error, () => true, true); + } finally { + setMutationPending(false); + } +}); + +deviceForm?.addEventListener('submit', async (event) => { + event.preventDefault(); + if (mutationPending) return; + const code = userCodeInput.value.trim(); + if (!code || code.length > 128) return; + await loadApproval(new URLSearchParams({ user_code: code }), code); +}); + +async function loadGrant(id, acceptedConsent = false) { + const generation = ++grantGeneration; + const isCurrent = () => generation === grantGeneration; + currentGrant = null; + grantPanel.hidden = true; + try { + const grant = await api( + `/api/agent-access/grants/${encodeURIComponent(id)}`, + ); + if (!isCurrent()) return; + currentGrant = grant; + grantInput.value = grant.grantId; + details(document.querySelector('#agent-grant-details'), [ + ['Grant ID', grant.grantId], + ['Client ID', grant.clientId], + ['Resource', grant.resource], + ['Permissions', grant.scopes.map((scope) => scope.name).join(', ')], + ['Status', grant.status], + ['Created', grant.createdAt], + ['Expires', grant.expiresAt], + ]); + grantPanel.hidden = false; + document.querySelector('#agent-grant-instructions').textContent = + `Grant ID: ${grant.grantId}. Use this ID in the lookup form or choose Revoke this grant below. Status: ${grant.status}.`; + setMutationPending(mutationPending); + if (acceptedConsent) + document.querySelector('#agent-approved-grant').hidden = true; + status( + acceptedConsent + ? 'Consent accepted and grant controls loaded. Return to your agent to finish connecting. The exact grant ID and revocation controls are below.' + : 'Grant loaded.', + ); + } catch (error) { + await failure(error, isCurrent, true, acceptedConsent); + } +} + +document + .querySelector('#agent-approved-grant') + .addEventListener('click', async () => { + if (!approvedLookupSelector || mutationPending) return; + await loadGrant(approvedLookupSelector, true); + }); + +document + .querySelector('#agent-grant-lookup') + .addEventListener('submit', async (event) => { + event.preventDefault(); + const id = grantInput.value.trim(); + if (!id || id.length > 128 || mutationPending) return; + await loadGrant(id); + }); + +revokeButton.addEventListener('click', async () => { + if (mutationPending || currentGrant === null) return; + const id = currentGrant.grantId; + if (!window.confirm('Revoke this agent grant and its credentials?')) return; + ++loadGeneration; + const generation = ++grantGeneration; + const isCurrent = () => generation === grantGeneration; + setMutationPending(true); + try { + await api(`/api/agent-access/grants/${encodeURIComponent(id)}`, { + method: 'DELETE', + }); + if (!isCurrent()) return; + currentGrant = null; + grantPanel.hidden = true; + status('Grant revoked.'); + } catch (error) { + await failure(error, isCurrent, true); + } finally { + setMutationPending(false); + } +}); + +async function start() { + const returnTo = `${window.location.pathname}${window.location.search}`; + document.querySelector('#agent-sign-in').href = + `/account?${new URLSearchParams({ returnTo })}`; + try { + const state = await api('/api/agent-access/state'); + csrfToken = state.csrfToken; + document.querySelector('#agent-resource').textContent = + `Protected resource: ${state.resource}`; + panel.hidden = false; + if (flow === 'device_code') { + userCodeInput.value = parameter('user_code'); + status('Enter or confirm the code shown by your agent.'); + } else { + const requestId = parameter('request_id'); + if (requestId) + await loadApproval(new URLSearchParams({ request_id: requestId })); + else + status( + 'Open the approval link from your registered client, or enter a known grant ID below.', + ); + } + } catch (error) { + await failure(error); + } +} + +await start(); diff --git a/public/knowledge.js b/public/knowledge.js new file mode 100644 index 0000000..b54c7f4 --- /dev/null +++ b/public/knowledge.js @@ -0,0 +1,186 @@ +const statusNode = document.querySelector('#knowledge-status'); +const panel = document.querySelector('#knowledge-panel'); +const signedOut = document.querySelector('#knowledge-signed-out'); +const collectionSelect = document.querySelector('#knowledge-collection'); +const resultsNode = document.querySelector('#knowledge-results'); +const articleNode = document.querySelector('#knowledge-article'); +let csrfToken = ''; +let readGeneration = 0; + +function status(message, error = false) { + statusNode.textContent = message; + statusNode.dataset.tone = error ? 'error' : 'neutral'; +} + +function failure(error) { + if (error.status === 401 || error.status === 403) { + ++readGeneration; + resultsNode.replaceChildren(); + articleNode.hidden = true; + document.querySelector('#knowledge-content').textContent = ''; + panel.hidden = true; + signedOut.hidden = error.status !== 401; + } + status( + error.status === 429 + ? Number.isFinite(error.retryAfterSeconds) + ? `Too many requests. Try again in ${error.retryAfterSeconds} second(s).` + : 'Too many requests. Wait before trying again.' + : error.status === 401 + ? 'Sign in to read your available guides.' + : error.status === 403 + ? 'These guides are not available to your account.' + : error.status === 404 + ? 'That guide is unavailable.' + : 'Guides are temporarily unavailable. Try again later.', + error.status !== 401, + ); +} + +async function json(path, init = {}) { + const response = await fetch(path, { + ...init, + credentials: 'same-origin', + cache: 'no-store', + referrerPolicy: 'no-referrer', + }); + const body = await response.json(); + if (!response.ok) { + const error = new Error( + typeof body.error === 'string' ? body.error : 'unavailable', + ); + error.status = response.status; + const retry = response.headers.get('Retry-After'); + const seconds = + retry === null + ? NaN + : /^\d+$/u.test(retry) + ? Number(retry) + : Math.ceil((Date.parse(retry) - Date.now()) / 1000); + if (Number.isFinite(seconds) && seconds >= 0) + error.retryAfterSeconds = seconds; + throw error; + } + return body; +} + +function portal(operation, input) { + return json('/api/knowledge/portal', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Pegma-CSRF': csrfToken }, + body: JSON.stringify({ operation, input }), + }); +} + +async function showArticle(articleId, updateUrl = true) { + const generation = ++readGeneration; + articleNode.hidden = true; + status('Loading guide...'); + try { + const article = await portal('getPublishedArticle', { articleId }); + if (generation !== readGeneration) return; + document.querySelector('#knowledge-title').textContent = article.title; + document.querySelector('#knowledge-summary').textContent = article.summary; + const applicability = article.applicability; + document.querySelector('#knowledge-applicability').textContent = [ + applicability.productId, + applicability.productVersion, + applicability.buildId, + applicability.locale, + ] + .filter(Boolean) + .join(' · '); + // Published Markdown is still untrusted content; display it as text. + document.querySelector('#knowledge-content').textContent = + article.content.text; + articleNode.hidden = false; + if (updateUrl) + window.history.replaceState( + null, + '', + `/knowledge?${new URLSearchParams({ article: article.articleId })}`, + ); + status('Approved guide loaded.'); + } catch (error) { + if (generation === readGeneration) failure(error); + } +} + +document + .querySelector('#knowledge-search') + .addEventListener('submit', async (event) => { + event.preventDefault(); + const generation = ++readGeneration; + articleNode.hidden = true; + resultsNode.replaceChildren(); + const fields = new FormData(event.currentTarget); + const applicability = { + productId: String(fields.get('productId')).trim(), + productVersion: String(fields.get('productVersion')).trim(), + }; + for (const key of ['buildId', 'locale']) { + const value = String(fields.get(key)).trim(); + if (value) applicability[key] = value; + } + status('Searching approved guides...'); + try { + const result = await portal('searchPublishedArticles', { + collectionId: fields.get('collectionId'), + query: String(fields.get('query')).trim(), + applicability, + }); + if (generation !== readGeneration) return; + for (const article of result.articles) { + const item = document.createElement('li'); + const title = document.createElement('button'); + title.type = 'button'; + title.className = 'text-button'; + title.textContent = article.title; + title.addEventListener('click', () => { + showArticle(article.articleId); + }); + const snippet = document.createElement('p'); + snippet.textContent = article.snippet; + item.append(title, snippet); + resultsNode.append(item); + } + status( + result.articles.length + ? `${result.articles.length} approved guide(s) found.` + : 'No approved guides match that search and version.', + ); + } catch (error) { + if (generation === readGeneration) failure(error); + } + }); + +async function start() { + try { + const account = await json('/api/identity/account'); + csrfToken = account.csrfToken; + const result = await portal('listPortalCollections', {}); + for (const collection of result.collections) { + const option = document.createElement('option'); + option.value = collection.collectionId; + option.textContent = collection.label; + collectionSelect.append(option); + } + panel.hidden = false; + document.querySelector('#knowledge-search button').disabled = + result.collections.length === 0; + status( + result.collections.length + ? 'Choose a collection and search.' + : 'No approved guide collections are available to your account.', + ); + const requested = new URLSearchParams(window.location.search).getAll( + 'article', + ); + if (requested.length === 1 && requested[0] && requested[0].length <= 512) + await showArticle(requested[0], false); + } catch (error) { + failure(error); + } +} + +await start(); diff --git a/public/llms.txt b/public/llms.txt index 5e6cb73..59eb09b 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -126,7 +126,7 @@ mail catcher, storage, health). No Stripe, Auth0, Entra, or production email. - Local Docker (template): https://pegma.dev/runbooks/local-docker - Cloudflare (D1 + R2): https://pegma.dev/runbooks/cloudflare - Azure (Tables + Blob): https://pegma.dev/runbooks/azure -- AWS (DynamoDB via forthcoming `@pegma/storage-dynamodb`): https://pegma.dev/runbooks/aws +- AWS (DynamoDB via published `@pegma/storage-dynamodb@0.4.5`): https://pegma.dev/runbooks/aws - Fixture: https://github.com/pegma-dev/pegma.dev/tree/main/recipes/bench-ticket ## Scaffold (agents) diff --git a/public/staff-knowledge.js b/public/staff-knowledge.js new file mode 100644 index 0000000..5bb2cc0 --- /dev/null +++ b/public/staff-knowledge.js @@ -0,0 +1,766 @@ +const select = (selector) => document.querySelector(selector); +const panel = select('#kb-panel'); +const statusNode = select('#kb-status'); +let csrfToken = ''; +let attesterId = ''; +let permissions = {}; +let collection = null; +let governanceGeneration = null; +let validationGeneration = 0; +let validationId = ''; +let draft = null; +let review = null; +let report = null; +let evidenceSnapshot = null; +let reportLedger = null; +let busy = false; +let requirementCounter = 0; +const commandIds = new Map(); + +function status(message, error = false) { + statusNode.textContent = message; + statusNode.dataset.tone = error ? 'error' : 'neutral'; +} + +function text(selector, value) { + select(selector).textContent = JSON.stringify(value, null, 2); +} + +function required(selector) { + const value = select(selector).value.trim(); + if (!value) + throw Object.assign(new Error('missing_field'), { + clientMessage: 'Complete the required fields first.', + }); + return value; +} + +function lines(value) { + return value + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean); +} + +async function request(path, init = {}) { + const response = await fetch(path, { + ...init, + credentials: 'same-origin', + cache: 'no-store', + referrerPolicy: 'no-referrer', + }); + const body = await response.json(); + if (!response.ok) { + const error = new Error( + typeof body.error === 'string' ? body.error : 'unavailable', + ); + error.status = response.status; + const retry = response.headers.get('Retry-After'); + const seconds = + retry === null + ? NaN + : /^\d+$/u.test(retry) + ? Number(retry) + : Math.ceil((Date.parse(retry) - Date.now()) / 1000); + if (Number.isFinite(seconds) && seconds >= 0) + error.retryAfterSeconds = seconds; + throw error; + } + return body; +} + +function call(operation, input) { + return request('/api/staff/knowledge/command', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Pegma-CSRF': csrfToken }, + body: JSON.stringify({ operation, input }), + }); +} + +function mutate(operation, input, sdk = true) { + const intent = JSON.stringify({ operation, input }); + if (!commandIds.has(intent)) commandIds.set(intent, crypto.randomUUID()); + const commandId = commandIds.get(intent); + return call(operation, { + ...input, + commandId, + ...(sdk ? { correlationId: commandId } : {}), + }); +} + +async function run(action) { + if (busy) return; + busy = true; + for (const field of panel.querySelectorAll('button,input,select,textarea')) + field.disabled = true; + try { + await action(); + } catch (error) { + if (error.status === 401 || error.status === 403) { + collection = null; + draft = null; + review = null; + report = null; + csrfToken = ''; + for (const node of panel.querySelectorAll('pre')) node.textContent = ''; + panel.hidden = true; + select('#kb-signed-out').hidden = error.status !== 401; + } + status( + (error.status === 429 + ? Number.isFinite(error.retryAfterSeconds) + ? `Too many requests. Try again in ${error.retryAfterSeconds} second(s).` + : 'Too many requests. Wait before trying again.' + : error.clientMessage) ?? + (error.status === 401 + ? 'Sign in to continue.' + : error.status === 403 + ? 'Your current account does not have permission for this operation.' + : error.status === 409 + ? 'The record changed or its checks are not current. Reload and review before trying again.' + : error.status === 404 + ? 'That record is unavailable.' + : 'The operation could not be completed. Reload current state or retry the same request.'), + true, + ); + } finally { + busy = false; + for (const field of panel.querySelectorAll('button,input,select,textarea')) + field.disabled = false; + } +} + +function requireCollection() { + if (!collection) + throw Object.assign(new Error('collection_required'), { + clientMessage: 'Load a collection first.', + }); + return collection.collection.id; +} + +function requireArticle() { + if (!draft) + throw Object.assign(new Error('article_required'), { + clientMessage: 'Load the current draft first.', + }); + return draft.articleId; +} + +async function loadGovernance() { + const collectionId = requireCollection(); + try { + const result = await call('getGovernanceConfiguration', { collectionId }); + governanceGeneration = result.generation; + select('#kb-governance-policy').value = + result.configuration.validationPolicy.id; + select('#kb-governance-version').value = String( + result.configuration.validationPolicy.version, + ); + select('#kb-staging-build').value = + result.configuration.expectedStagingBuildId; + select('#kb-attesters').value = + result.configuration.trustedAttesterIds.join('\n'); + text('#kb-governance-detail', result); + } catch (error) { + if (error.status !== 404) throw error; + governanceGeneration = collection.generation; + select('#kb-governance-policy').value = ''; + select('#kb-governance-version').value = '1'; + select('#kb-staging-build').value = ''; + select('#kb-attesters').value = attesterId; + select('#kb-governance-detail').textContent = + 'No governance is configured yet.'; + } +} + +async function loadCollection(collectionId) { + collection = null; + governanceGeneration = null; + policyPreview = null; + select('#kb-collection-detail').textContent = ''; + select('#kb-governance-detail').textContent = ''; + select('#kb-portal-form').hidden = true; + select('#kb-policy-preview').hidden = true; + select('#kb-policy-apply').hidden = true; + collection = await call('getCollection', { collectionId }); + text('#kb-collection-detail', collection); + select('#kb-portal-form').hidden = permissions.collectionManage !== true; + const portal = collection.collection.policy.portal; + select('#kb-portal-enabled').checked = portal.enabled; + select('#kb-portal-permission').value = + portal.enabled && portal.audience.kind === 'permission' + ? portal.audience.permission + : 'knowledge.article.read'; + select('#kb-policy-preview').hidden = true; + select('#kb-policy-apply').hidden = true; + if (permissions.validationManage) await loadGovernance(); + status('Collection loaded.'); +} + +select('#kb-collection-form').addEventListener('submit', (event) => { + event.preventDefault(); + const action = event.submitter?.value; + run(async () => { + const collectionId = required('#kb-collection-id'); + if (action === 'create') + await mutate('createCollection', { + collectionId, + name: required('#kb-collection-name'), + expectedGeneration: 0, + }); + await loadCollection(collectionId); + }); +}); + +let policyPreview = null; +select('#kb-portal-form').addEventListener('submit', (event) => { + event.preventDefault(); + run(async () => { + const collectionId = requireCollection(); + const portal = select('#kb-portal-enabled').checked + ? { + enabled: true, + audience: { + kind: 'permission', + permission: required('#kb-portal-permission'), + }, + } + : { enabled: false }; + policyPreview = await call('previewCollectionPolicy', { + collectionId, + uses: { portal, bot: collection.collection.policy.bot }, + }); + text('#kb-policy-preview', policyPreview); + select('#kb-policy-preview').hidden = false; + select('#kb-policy-apply').hidden = permissions.collectionManage !== true; + status('Review the exact audience policy preview before applying it.'); + }); +}); + +select('#kb-policy-apply').addEventListener('click', () => + run(async () => { + if ( + !policyPreview || + !window.confirm('Apply this exact reviewed audience policy?') + ) + return; + const collectionId = requireCollection(); + await mutate('updateCollectionPolicy', { + collectionId, + expectedGeneration: policyPreview.generation, + preview: policyPreview.preview, + }); + policyPreview = null; + await loadCollection(collectionId); + }), +); + +select('#kb-governance-read').addEventListener('click', () => + run(async () => { + await loadGovernance(); + status('Current governance loaded.'); + }), +); +select('#kb-governance-form').addEventListener('submit', (event) => { + event.preventDefault(); + run(async () => { + const collectionId = requireCollection(); + if (governanceGeneration === null) + throw Object.assign(new Error('load_governance'), { + clientMessage: 'Load current governance first.', + }); + await mutate('putGovernanceConfiguration', { + collectionId, + expectedGeneration: governanceGeneration, + configuration: { + validationPolicy: { + id: required('#kb-governance-policy'), + version: Number(required('#kb-governance-version')), + }, + expectedStagingBuildId: required('#kb-staging-build'), + trustedAttesterIds: lines(required('#kb-attesters')), + }, + }); + await loadCollection(collectionId); + status( + 'Governance saved. Existing reviews must pass the current configuration.', + ); + }); +}); + +function addRequirement(value = {}) { + const row = document.createElement('fieldset'); + row.dataset.requirement = 'true'; + const legend = document.createElement('legend'); + legend.textContent = 'Validation check'; + row.append(legend); + const fields = [ + ['id', 'Check ID'], + ['kind', 'Article kind'], + ['testKind', 'Test kind'], + ['maxAgeMilliseconds', 'Maximum evidence age (milliseconds)'], + ['trustedRunnerIds', 'Trusted runner IDs (one per line)'], + ]; + for (const [key, title] of fields) { + const label = document.createElement('label'); + const input = + key === 'kind' + ? document.createElement('select') + : key === 'trustedRunnerIds' + ? document.createElement('textarea') + : document.createElement('input'); + input.id = `kb-check-${++requirementCounter}`; + input.dataset.field = key; + input.required = true; + if (key === 'kind') { + for (const kind of [ + 'explanation', + 'walkthrough', + 'troubleshooting', + 'developer-reference', + ]) { + const option = document.createElement('option'); + option.value = kind; + option.textContent = kind; + input.append(option); + } + } else if (key === 'maxAgeMilliseconds') { + input.type = 'number'; + input.min = '1'; + input.step = '1'; + } else if (key !== 'trustedRunnerIds') input.maxLength = 200; + label.htmlFor = input.id; + label.textContent = title; + input.value = + key === 'trustedRunnerIds' + ? (value[key] ?? []).join('\n') + : String(value[key] ?? ''); + if (key === 'kind' && !value.kind) input.value = 'explanation'; + row.append(label, input); + } + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'secondary-button'; + remove.textContent = 'Remove check'; + remove.addEventListener('click', () => row.remove()); + row.append(remove); + select('#kb-requirements').append(row); +} + +select('#kb-add-requirement').addEventListener('click', () => addRequirement()); +select('#kb-validation-read').addEventListener('submit', (event) => { + event.preventDefault(); + run(async () => { + const policyId = required('#kb-validation-id'); + validationId = ''; + validationGeneration = 0; + select('#kb-requirements').replaceChildren(); + try { + const result = await call('getValidationPolicy', { policyId }); + validationId = result.policy.id; + validationGeneration = result.generation; + select('#kb-validation-version').value = String(result.policy.version); + select('#kb-requirements').replaceChildren(); + for (const check of result.policy.requirements) addRequirement(check); + status('Validation policy loaded.'); + } catch (error) { + if (error.status !== 404) throw error; + validationId = policyId; + validationGeneration = 0; + select('#kb-requirements').replaceChildren(); + addRequirement(); + status( + 'No policy exists at that ID. Define its first version and checks.', + ); + } + }); +}); + +select('#kb-validation-form').addEventListener('submit', (event) => { + event.preventDefault(); + run(async () => { + const id = required('#kb-validation-id'); + const requirements = [...select('#kb-requirements').children].map((row) => { + const field = (key) => + row.querySelector(`[data-field="${key}"]`).value.trim(); + return { + id: field('id'), + kind: field('kind'), + testKind: field('testKind'), + maxAgeMilliseconds: Number(field('maxAgeMilliseconds')), + trustedRunnerIds: lines(field('trustedRunnerIds')), + }; + }); + if (!requirements.length) + throw Object.assign(new Error('missing_checks'), { + clientMessage: 'Add the required validation checks first.', + }); + const result = await mutate('putValidationPolicy', { + expectedGeneration: id === validationId ? validationGeneration : 0, + policy: { + id, + version: Number(required('#kb-validation-version')), + requirements, + }, + }); + validationId = id; + validationGeneration = result.value.generation; + status('Validation policy saved.'); + }); +}); + +async function loadDraft(articleId) { + draft = null; + review = null; + report = null; + evidenceSnapshot = null; + reportLedger = null; + select('#kb-draft-detail').textContent = ''; + select('#kb-article-actions').hidden = true; + select('#kb-review-panel').hidden = true; + select('#kb-report-panel').hidden = true; + select('#kb-ledger-panel').hidden = true; + select('#kb-evidence-panel').hidden = true; + select('#kb-evidence-select').replaceChildren(); + select('#kb-evidence-selected').textContent = ''; + select('#kb-article-detail').textContent = ''; + select('#kb-report-list').replaceChildren(); + draft = await call('getDraft', { articleId }); + text('#kb-draft-detail', draft); + select('#kb-article-actions').hidden = false; + status('Current draft loaded.'); +} + +select('#kb-article-form').addEventListener('submit', (event) => { + event.preventDefault(); + run(() => loadDraft(required('#kb-article-id'))); +}); +for (const [button, operation] of [['#kb-provenance-read', 'getProvenance']]) { + select(button).addEventListener('click', () => + run(async () => { + text( + '#kb-article-detail', + await call(operation, { articleId: requireArticle() }), + ); + status('Current private staff detail loaded.'); + }), + ); +} + +async function loadEvidence() { + evidenceSnapshot = null; + select('#kb-evidence-panel').hidden = true; + select('#kb-evidence-selected').textContent = ''; + const result = await call('getEvidence', { articleId: requireArticle() }); + evidenceSnapshot = result; + text('#kb-article-detail', result); + const choices = select('#kb-evidence-select'); + choices.replaceChildren(); + const prompt = document.createElement('option'); + prompt.value = ''; + prompt.textContent = 'Select the exact evidence version to revoke'; + choices.append(prompt); + for (const [index, item] of result.evidence.entries()) { + const revoked = result.revokedEvidence.some( + (entry) => + entry.articleRevision === item.articleRevision && + entry.id === item.id && + entry.version === item.version && + entry.hash === item.hash, + ); + if (revoked) continue; + const option = document.createElement('option'); + option.value = String(index); + option.textContent = `${item.id} · article revision ${item.articleRevision} · evidence version ${item.version} · ${item.hash}`; + choices.append(option); + } + select('#kb-evidence-panel').hidden = permissions.evidenceRevoke !== true; + status('Current evidence and exact revocation choices loaded.'); +} + +select('#kb-evidence-read').addEventListener('click', () => run(loadEvidence)); +select('#kb-evidence-select').addEventListener('change', () => { + const value = select('#kb-evidence-select').value; + const item = value === '' ? null : evidenceSnapshot?.evidence[Number(value)]; + if (item) text('#kb-evidence-selected', item); + else select('#kb-evidence-selected').textContent = ''; +}); +select('#kb-evidence-revoke').addEventListener('submit', (event) => { + event.preventDefault(); + run(async () => { + const value = select('#kb-evidence-select').value; + const snapshot = evidenceSnapshot; + const item = value === '' ? null : snapshot?.evidence[Number(value)]; + if (!snapshot || !item || permissions.evidenceRevoke !== true) return; + const reason = required('#kb-evidence-reason'); + if ( + !window.confirm( + `Revoke evidence ${item.id}, version ${item.version}, hash ${item.hash}, for article ${snapshot.articleId} revision ${item.articleRevision}?`, + ) + ) + return; + await mutate('revokeEvidence', { + articleId: snapshot.articleId, + expectedGeneration: snapshot.generation, + articleRevision: item.articleRevision, + evidenceId: item.id, + evidenceVersion: item.version, + evidenceHash: item.hash, + reason, + }); + await loadDraft(snapshot.articleId); + await loadEvidence(); + status('The exact evidence version was revoked.'); + }); +}); + +select('#kb-retire').addEventListener('click', () => + run(async () => { + requireArticle(); + const snapshot = draft; + if ( + permissions.retire !== true || + !window.confirm( + `Retire article ${snapshot.articleId} at generation ${snapshot.generation}, revision ${snapshot.revision.number}, content hash ${snapshot.revision.contentHash}? Any publication will be withdrawn.`, + ) + ) + return; + await mutate('retireArticle', { + articleId: snapshot.articleId, + expectedGeneration: snapshot.generation, + }); + await loadDraft(snapshot.articleId); + status( + draft.state === 'retired' + ? 'Article retired.' + : 'Retirement acknowledged. The current article state is shown above.', + ); + }), +); + +select('#kb-submit-review').addEventListener('click', () => + run(async () => { + const articleId = requireArticle(); + await mutate('submitForReview', { + articleId, + expectedGeneration: draft.generation, + }); + await loadDraft(articleId); + status('Draft submitted. Load the exact review before publishing.'); + }), +); +select('#kb-review-read').addEventListener('click', () => + run(async () => { + review = null; + select('#kb-review-panel').hidden = true; + review = await call('getReview', { articleId: requireArticle() }); + text('#kb-review-detail', review); + select('#kb-review-panel').hidden = false; + status('Review the complete snapshot before publication.'); + }), +); +select('#kb-publish').addEventListener('click', () => + run(async () => { + if ( + !review || + !window.confirm( + 'Approve and publish exactly this reviewed article revision?', + ) + ) + return; + const articleId = requireArticle(); + await mutate('publishArticle', { + articleId, + expectedGeneration: review.generation, + review: review.review, + }); + await loadDraft(articleId); + status('Reviewed revision published.'); + }), +); +select('#kb-reject-review').addEventListener('submit', (event) => { + event.preventDefault(); + run(async () => { + if (!review) return; + const articleId = requireArticle(); + await mutate('rejectReview', { + articleId, + expectedGeneration: review.generation, + reason: required('#kb-review-reason'), + }); + await loadDraft(articleId); + status('Review rejected.'); + }); +}); + +function showLedger(ledger) { + reportLedger = ledger; + text('#kb-ledger-detail', ledger); + select('#kb-ledger-panel').hidden = false; + select('#kb-ledger-reset').hidden = + permissions.evidenceConfirm !== true || ledger.status !== 'active'; + select('#kb-ledger-drain').hidden = + permissions.evidenceConfirm !== true || ledger.status !== 'resetting'; +} + +async function loadLedger() { + const ledger = await call('reportLedger', { articleId: requireArticle() }); + showLedger(ledger); + return ledger; +} + +async function drainLedger(ledger) { + for (let page = 0; page < 4 && ledger.status === 'resetting'; page += 1) { + ledger = await call('drainReports', { + articleId: ledger.articleId, + ledgerEpoch: ledger.ledgerEpoch, + }); + showLedger(ledger); + } + status( + ledger.status === 'active' + ? 'Report cleanup completed. Earlier report receipts remain invalid.' + : 'This bounded cleanup pass finished. Continue cleanup to inspect the remaining rows.', + ); +} + +select('#kb-ledger-read').addEventListener('click', () => + run(async () => { + await loadLedger(); + status('Current report ledger loaded.'); + }), +); +select('#kb-ledger-reset').addEventListener('click', () => + run(async () => { + if (!reportLedger || permissions.evidenceConfirm !== true) return; + const snapshot = reportLedger; + if ( + !window.confirm( + `Reset report ledger ${snapshot.articleId} at epoch ${snapshot.ledgerEpoch}? Earlier report receipts and commands become permanently invalid. Accepted KB evidence and publication are unchanged.`, + ) + ) + return; + const result = await mutate( + 'resetReports', + { + articleId: snapshot.articleId, + expectedLedgerEpoch: snapshot.ledgerEpoch, + }, + false, + ); + report = null; + select('#kb-report-panel').hidden = true; + select('#kb-report-list').replaceChildren(); + showLedger(result); + await drainLedger(result); + }), +); +select('#kb-ledger-drain').addEventListener('click', () => + run(async () => { + if (permissions.evidenceConfirm !== true) return; + await drainLedger(await loadLedger()); + }), +); + +async function readReport(reportId, ledgerEpoch) { + report = null; + select('#kb-report-panel').hidden = true; + select('#kb-report-detail').textContent = ''; + if (ledgerEpoch === undefined) ledgerEpoch = (await loadLedger()).ledgerEpoch; + report = await call('reportRead', { + articleId: requireArticle(), + reportId, + ledgerEpoch, + }); + select('#kb-report-id').value = report.reportId; + text('#kb-report-detail', report); + const elapsed = Date.now() - Date.parse(report.evidence.executedAt); + select('#kb-report-age').textContent = Number.isFinite(elapsed) + ? `Execution age by this browser's clock: ${Math.floor(elapsed / 60_000)} minute(s). Current acceptance and maximum-age checks are performed by the service.` + : 'Execution time is shown in the report above.'; + select('#kb-report-panel').hidden = false; + status('Review this report and its current exact bindings before deciding.'); +} + +select('#kb-reports-read').addEventListener('click', () => + run(async () => { + const result = await call('reportList', { articleId: requireArticle() }); + showLedger(result.ledger); + select('#kb-report-list').replaceChildren(); + for (const item of result.reports) { + const row = document.createElement('li'); + const button = document.createElement('button'); + button.type = 'button'; + button.textContent = item.reportId; + button.addEventListener('click', () => + run(() => readReport(item.reportId, result.ledger.ledgerEpoch)), + ); + const summary = document.createElement('p'); + summary.textContent = `${item.status} · ${item.submittedAt} · ${typeof item.summary === 'string' ? item.summary : JSON.stringify(item.summary)}`; + row.append(button, summary); + select('#kb-report-list').append(row); + } + status( + result.reports.length + ? 'Select a report to inspect.' + : 'No reports are available for this article.', + ); + }), +); +select('#kb-report-read').addEventListener('submit', (event) => { + event.preventDefault(); + run(() => readReport(required('#kb-report-id'))); +}); +for (const [button, operation, decision] of [ + ['#kb-report-confirm', 'confirmReport', 'confirm'], + ['#kb-report-reject', 'rejectReport', 'reject'], + ['#kb-report-reassess', 'reassessReport', 'reassess'], +]) { + select(button).addEventListener('click', () => + run(async () => { + if ( + !report || + !window.confirm( + `Record your decision to ${decision} this exact report and current revision/build binding?`, + ) + ) + return; + const result = await mutate( + operation, + { + articleId: report.articleId, + reportId: report.reportId, + ledgerEpoch: report.ledgerEpoch, + expectedReportGeneration: report.expectedReportGeneration, + reviewBindingHash: report.reviewBindingHash, + }, + false, + ); + report = null; + select('#kb-report-panel').hidden = true; + text('#kb-article-detail', result); + status( + decision === 'confirm' + ? 'Human review recorded. The agent can submit the exact evidence with its existing report receipt; Knowledge Base acceptance is a separate step.' + : decision === 'reassess' + ? 'Report returned to pending human review. The earlier confirmation no longer applies; the agent must poll the current report status and use its current receipt.' + : 'Report rejected.', + ); + }), + ); +} + +await run(async () => { + const state = await request('/api/staff/knowledge/state'); + csrfToken = state.csrfToken; + attesterId = state.attesterId; + permissions = state.permissions; + for (const node of panel.querySelectorAll('[data-kb-permission]')) + node.hidden = permissions[node.dataset.kbPermission] !== true; + select('#kb-attester-note').textContent = + `This browser review uses current attester ID: ${attesterId}`; + select('#kb-attesters').value = attesterId; + panel.hidden = false; + addRequirement(); + status('Ready. Load a collection or draft, or configure a new collection.'); +}); diff --git a/public/staff-roles.js b/public/staff-roles.js index 1cb5a16..0b8d8e8 100644 --- a/public/staff-roles.js +++ b/public/staff-roles.js @@ -236,6 +236,14 @@ assignForm.addEventListener('submit', async (event) => { ) { return; } + if ( + role === 'Knowledge' && + !window.confirm( + 'Grant the Knowledge role? It permits draft editing, test-report review, evidence and provenance management, guide publication, and retirement.', + ) + ) { + return; + } try { await api( `/api/admin/principals/${encodeURIComponent(currentPrincipal)}/roles`, diff --git a/recipes/bench-ticket/composition.ts b/recipes/bench-ticket/composition.ts index cb68cad..c2ffa33 100644 --- a/recipes/bench-ticket/composition.ts +++ b/recipes/bench-ticket/composition.ts @@ -5,8 +5,8 @@ * support-desk site with first-party Identity **email-code** login (not * Auth0, Entra, or passkeys-required), Sessions, Mail to a catcher, * Support Desk create/list/reply, and Health. Tests inject - * `createMemoryStore()`. Cloud runbooks inject D1, Azure Tables, or the - * forthcoming `@pegma/storage-dynamodb` adapter — same composition shape. + * `createMemoryStore()`. Cloud runbooks describe wiring D1, Azure Tables, or + * the published `@pegma/storage-dynamodb` adapter — same composition shape. * * Not pegma.dev’s production feedback API. Do not copy commercial route * maps, cookie names, or CSRF tokens from any live product. @@ -72,7 +72,7 @@ export interface BenchTicketCompositionOptions { /** * Required injected store. Local Docker tests and compose use * `createMemoryStore()`. Production-shaped hosts pass a durable adapter - * (D1, Azure Tables, or `@pegma/storage-dynamodb` once published). + * (D1, Azure Tables, or the published `@pegma/storage-dynamodb`). * Memory is never the silent default. */ readonly store: Store; diff --git a/scripts/normalize-worker-types.mjs b/scripts/normalize-worker-types.mjs new file mode 100644 index 0000000..d3045da --- /dev/null +++ b/scripts/normalize-worker-types.mjs @@ -0,0 +1,10 @@ +import { readFileSync, writeFileSync } from 'node:fs'; + +const file = new URL('../worker/worker-configuration.d.ts', import.meta.url); +const bytes = readFileSync(file); +const original = new TextDecoder('utf-8', { fatal: true }).decode(bytes); +const normalized = original.replace(/\t/gu, ' '); +if (/[\u0000-\u0009\u000B\u000C\u000E-\u001F\u007F]/u.test(normalized)) { + throw new Error('Generated Worker types contain unsafe control characters.'); +} +if (normalized !== original) writeFileSync(file, normalized, 'utf8'); diff --git a/src/data/catalog-enrichment.ts b/src/data/catalog-enrichment.ts index 8938774..ac3eff5 100644 --- a/src/data/catalog-enrichment.ts +++ b/src/data/catalog-enrichment.ts @@ -20,7 +20,9 @@ export interface ComponentEnrichment { } /** Keyed by component id (= registry `repo`). */ -export const COMPONENT_ENRICHMENT: Readonly> = { +export const COMPONENT_ENRICHMENT: Readonly< + Record +> = { spine: { dependencies: [], adapters: [], @@ -31,7 +33,11 @@ export const COMPONENT_ENRICHMENT: Readonly> }, 'storage-core': { dependencies: [ - { componentId: 'spine', kind: 'requires', note: 'Shared contracts and Logger' }, + { + componentId: 'spine', + kind: 'requires', + note: 'Shared contracts and Logger', + }, ], adapters: [ { @@ -56,8 +62,7 @@ export const COMPONENT_ENRICHMENT: Readonly> id: 'dynamodb', packageName: '@pegma/storage-dynamodb', host: 'other', - when: - 'AWS-hosted apps using DynamoDB. Requires pegma-dev/storage-core#7 to be merged; factory is createDynamoDbStore. Not yet on npm.', + when: 'AWS-hosted apps using DynamoDB; hosts provide the AWS SDK client and table name to createDynamoDbStore.', }, ], hostMustProvide: [ @@ -99,7 +104,11 @@ export const COMPONENT_ENRICHMENT: Readonly> }, 'cache-core': { dependencies: [ - { componentId: 'spine', kind: 'requires', note: 'Injected Clock and Logger' }, + { + componentId: 'spine', + kind: 'requires', + note: 'Injected Clock and Logger', + }, ], adapters: [ { @@ -310,7 +319,11 @@ export const COMPONENT_ENRICHMENT: Readonly> }, 'flags-core': { dependencies: [ - { componentId: 'spine', kind: 'requires', note: 'Injected Clock and Logger' }, + { + componentId: 'spine', + kind: 'requires', + note: 'Injected Clock and Logger', + }, ], adapters: [ { @@ -359,7 +372,11 @@ export const COMPONENT_ENRICHMENT: Readonly> }, 'logger-adapters': { dependencies: [ - { componentId: 'spine', kind: 'requires', note: 'Implements Spine Logger' }, + { + componentId: 'spine', + kind: 'requires', + note: 'Implements Spine Logger', + }, ], adapters: [], hostMustProvide: [ diff --git a/src/data/components.ts b/src/data/components.ts index e5bb27b..d00b5f3 100644 --- a/src/data/components.ts +++ b/src/data/components.ts @@ -55,6 +55,7 @@ export const components: readonly PegmaComponent[] = [ '@pegma/storage-core', '@pegma/storage-azure-tables', '@pegma/storage-cloudflare-d1', + '@pegma/storage-dynamodb', ], status: 'published', summary: 'Persistence without the component knowing what the database is.', @@ -70,7 +71,7 @@ export const components: readonly PegmaComponent[] = [ 'Cross-partition anything', 'Compatibility layers for pre-existing data layouts — Pegma targets net-new projects', ], - now: '0.4.0 on npm with the Azure Tables (0.4.0) and Cloudflare D1 (0.4.1) adapters; both adapters pass the same conformance suite.', + now: 'Fallback snapshot (2026-08-15): 0.4.0 on npm with the Azure Tables (0.4.0) and Cloudflare D1 (0.4.1) adapters; both adapters pass the same conformance suite.', }, { repo: 'storage-blobs', diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index dd320d1..ddd3038 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -21,7 +21,7 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ '@pegma/rate-limit@0.2.0', '@pegma/authorization-identity@0.4.0', '@pegma/storage-core@0.4.0', - '@pegma/storage-cloudflare-d1@0.4.1', + '@pegma/storage-cloudflare-d1@0.4.6', '@pegma/spine@0.1.1', ], adapters: [{ componentId: 'storage-core', adapterId: 'cloudflare-d1' }], @@ -161,13 +161,12 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ id: 'logger-tee-composition', intent: 'A fictional batch importer (Ledger Drop) wires Spine Logger once at the composition root through @pegma/logger-tee into Cloudflare Workers Logs.', - packages: [ - '@pegma/spine', - '@pegma/logger-tee', - '@pegma/logger-cloudflare', - ], + packages: ['@pegma/spine', '@pegma/logger-tee', '@pegma/logger-cloudflare'], adapters: [], - hostResponsibilities: ['Composition-root Logger wiring', 'Sink configuration'], + hostResponsibilities: [ + 'Composition-root Logger wiring', + 'Sink configuration', + ], nonGoals: ['Pegma-owned traces, metrics, or APM'], antiPatterns: [ 'Putting sink SDKs into Spine', @@ -221,15 +220,17 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ 'Provider signature verification', 'Storage for the receipt ledger', ], - nonGoals: ['Exactly-once delivery', 'Payload archival in the receipt ledger'], + nonGoals: [ + 'Exactly-once delivery', + 'Payload archival in the receipt ledger', + ], antiPatterns: [ 'Claiming exactly-once processing', 'Storing full webhook bodies in receipts', ], fixture: { kind: 'pending', - citation: - 'docs/catalog/RECIPE_BACKLOG.md#d1--inbound-webhook-receipts', + citation: 'docs/catalog/RECIPE_BACKLOG.md#d1--inbound-webhook-receipts', status: 'none', }, capabilityTags: ['webhooks_inbound'], diff --git a/src/pages/account/agents/authorize.astro b/src/pages/account/agents/authorize.astro new file mode 100644 index 0000000..4fe48d8 --- /dev/null +++ b/src/pages/account/agents/authorize.astro @@ -0,0 +1,53 @@ +--- +import Base from '../../../layouts/Base.astro'; +--- + + + +

Checking your account access...

+ + + + + diff --git a/src/pages/account/agents/device.astro b/src/pages/account/agents/device.astro new file mode 100644 index 0000000..8fce5f2 --- /dev/null +++ b/src/pages/account/agents/device.astro @@ -0,0 +1,59 @@ +--- +import Base from '../../../layouts/Base.astro'; +--- + + + +

Checking your account access...

+ + + + + diff --git a/src/pages/examples.astro b/src/pages/examples.astro index 8be8551..9ba89de 100644 --- a/src/pages/examples.astro +++ b/src/pages/examples.astro @@ -245,8 +245,8 @@ const pendingRecipes = RECIPE_BACKLOG.filter( Bench Ticket (synthetic): first-party Identity email-code (not Auth0/Entra/passkeys-required), Sessions, Support Desk create/list/reply, Health, and mail to a catcher. Tests inject memory; environment runbooks - inject D1, Azure Tables, or @pegma/storage-dynamodb (requires - the storage-core adapter PR to be merged). + describe wiring D1, Azure Tables, or the published + @pegma/storage-dynamodb@0.4.5 adapter. See environment runbooks.

{benchTicketExcerpt}
diff --git a/src/pages/knowledge.astro b/src/pages/knowledge.astro new file mode 100644 index 0000000..13487c6 --- /dev/null +++ b/src/pages/knowledge.astro @@ -0,0 +1,48 @@ +--- +import Base from '../layouts/Base.astro'; +--- + + + +

Checking your account...

+ + +

Account · Ask for help

+ + + + + diff --git a/src/pages/runbooks.md b/src/pages/runbooks.md index da1fc24..6d33e33 100644 --- a/src/pages/runbooks.md +++ b/src/pages/runbooks.md @@ -17,7 +17,7 @@ Logged-out: sign in with a first-party **email code**. Logged-in: file a ticket, | Azure | `@pegma/storage-azure-tables` | Blob container (provisioned) | console / container logs | [Azure](/runbooks/azure) | | AWS | `@pegma/storage-dynamodb` | S3 (`@pegma/storage-s3`) | console / CloudWatch | [AWS](/runbooks/aws) | -The AWS record adapter is `@pegma/storage-dynamodb` (`createDynamoDbStore`) from [storage-core#7](https://github.com/pegma-dev/storage-core/pull/7). The AWS runbook uses the same one-shot shape as Azure and D1; it requires that adapter PR to be merged before `pnpm add` succeeds. +The AWS record adapter is the published `@pegma/storage-dynamodb@0.4.5` (`createDynamoDbStore`); see the [qualified release](https://github.com/pegma-dev/storage-core/releases/tag/v0.4.5). The AWS runbook describes the same composition shape as Azure and D1. The committed host and CI fixture use MemoryStore; package publication does not establish an AWS deployment of that fixture. **Fixture (CI-tested):** [`recipes/bench-ticket`](https://github.com/pegma-dev/pegma.dev/tree/main/recipes/bench-ticket) — catalog recipe `support-queue-slice`. Pin versions from [`catalog.json`](/catalog.json). Do not invent Auth0, Entra, or Stripe steps. diff --git a/src/pages/runbooks/aws.md b/src/pages/runbooks/aws.md index 7b9c856..17985cc 100644 --- a/src/pages/runbooks/aws.md +++ b/src/pages/runbooks/aws.md @@ -8,9 +8,9 @@ description: One-shot AWS runbook for the Bench Ticket Pegma demo. DynamoDB reco Same one-shot as [Local Docker](/runbooks/local-docker), [Cloudflare](/runbooks/cloudflare), and [Azure](/runbooks/azure): Bench Ticket with first-party email-code login, Sessions, Support Desk create/list/reply, Health. Mail is a **console catcher** (CloudWatch logs) — do not sign up for SES, SendGrid, ACS, or Resend. Do not add Stripe, Auth0, Entra, or Cognito. -## Requires the storage-core DynamoDB adapter PR +## Published DynamoDB adapter -Record persistence on AWS uses the Storage Core adapter that passes `packages/storage-core/src/conformance.ts`. That package is being added in [pegma-dev/storage-core#7](https://github.com/pegma-dev/storage-core/pull/7) as **DynamoDB**, named to match siblings: +Record persistence on AWS uses the published `@pegma/storage-dynamodb@0.4.5` adapter from the [qualified Storage Core release](https://github.com/pegma-dev/storage-core/releases/tag/v0.4.5), named to match siblings: | Sibling | Package | Factory | | --- | --- | --- | @@ -18,9 +18,9 @@ Record persistence on AWS uses the Storage Core adapter that passes `packages/st | Cloudflare D1 | `@pegma/storage-cloudflare-d1` | `createCloudflareD1Store` | | AWS DynamoDB | `@pegma/storage-dynamodb` | `createDynamoDbStore` | -**Do not implement that adapter in pegma.dev.** If `pnpm add @pegma/storage-dynamodb` fails because the package is not on npm yet, stop and merge/publish [storage-core#7](https://github.com/pegma-dev/storage-core/pull/7) first, then resume at step 4. Blobs are already published (`@pegma/storage-s3` / `createS3BlobStore`). +**Use the published adapter rather than implementing it in pegma.dev.** Blobs are also published (`@pegma/storage-s3` / `createS3BlobStore`). -Until that package is on npm, Local Docker, Cloudflare, and Azure still one-shot from this same fixture. +The committed host and CI fixture use `createMemoryStore()`. This runbook describes AWS wiring; the adapter's qualified publication does not establish an AWS deployment or production validation of Bench Ticket. ## Prerequisites @@ -77,13 +77,13 @@ aws s3api create-bucket --bucket "$BUCKET" --region "$REGION" The adapter can create the table on first use (`createTableIfMissing` defaults to true). This runbook provisions it in infrastructure instead, then passes `createTableIfMissing: false` so the task role does not need `CreateTable`. Do not invent a second table “for audit”. -## 4. Point the host at DynamoDB (after the adapter is on npm) +## 4. Point the host at DynamoDB ```sh pnpm add @pegma/storage-dynamodb @aws-sdk/client-dynamodb @pegma/storage-s3 @aws-sdk/client-s3 ``` -Pin `@pegma/storage-dynamodb` to the exact version in [catalog.json](/catalog.json) once the compiler lists it. Until then, use the version the storage-core release publishes (do not invent a caret range). +Pin `@pegma/storage-dynamodb` to the exact version in [catalog.json](/catalog.json); the qualified release cited here is `0.4.5`. Do not invent a caret range. In `recipes/bench-ticket/host.ts`, replace `createMemoryStore()` with the sibling-shaped factory: @@ -98,7 +98,7 @@ const store = createDynamoDbStore({ }); ``` -If the published factory options differ, copy them from that package’s README — keep the call site a single `createDynamoDbStore({ … })` returning a Storage Core `Store`, then pass it to `createBenchTicketComposition` unchanged. +Check factory options against the [versioned package README](https://github.com/pegma-dev/storage-core/blob/v0.4.5/packages/storage-dynamodb/README.md). Pass the returned Storage Core `Store` to `createBenchTicketComposition` unchanged. Optional blobs (provisioned above; not required for the ticket round-trip): @@ -168,8 +168,8 @@ Follow logs with the platform’s tail (`aws logs tail … --follow` or App Runn | Sign | Next command | | --- | --- | | `aws sts get-caller-identity` fails | `aws login` / `aws configure sso` | -| `pnpm add @pegma/storage-dynamodb` 404 | Adapter PR not merged/published. Do **not** implement DynamoDB here. Finish Local Docker / Cloudflare / Azure instead. See [storage-core#7](https://github.com/pegma-dev/storage-core/pull/7). | -| `Cannot find module '@pegma/storage-dynamodb'` | Same — wait for the storage-core AWS package; name it `@pegma/storage-dynamodb` / `createDynamoDbStore`. | +| `pnpm add @pegma/storage-dynamodb` 404 | Version `0.4.5` is published. Check the exact package/version spelling, registry configuration and connectivity; do not implement a local replacement. | +| `Cannot find module '@pegma/storage-dynamodb'` | Install the exact published package in this host and check dependency resolution; its public factory is `createDynamoDbStore`. | | `ResourceNotFoundException` | `aws dynamodb describe-table --table-name bench-ticket`. Recreate using `pk` HASH + `sk` RANGE. | | Health 503 / storage fail | IAM: the task role needs DynamoDB on that table. `aws dynamodb scan --table-name bench-ticket --max-items 1`. | | Origin invalid / finish 400 | `BENCH_TICKET_ORIGIN` must be the public HTTPS origin with no path. | @@ -193,7 +193,7 @@ rm -f /tmp/bench-ticket.cookies ## Store wiring (same composition) -After the adapter exists, the host is the Azure/D1 shape: +The published adapter uses the same injected-Store composition shape as Azure/D1: ```ts import { createDynamoDbStore } from "@pegma/storage-dynamodb"; diff --git a/src/pages/staff/knowledge.astro b/src/pages/staff/knowledge.astro new file mode 100644 index 0000000..5c8138f --- /dev/null +++ b/src/pages/staff/knowledge.astro @@ -0,0 +1,119 @@ +--- +import Base from '../../layouts/Base.astro'; +--- + + + +

Checking staff access...

+ + +

Customer guides · Agent grants · Roles

+ + + + + diff --git a/src/pages/staff/roles.astro b/src/pages/staff/roles.astro index e0e91d7..09c6cce 100644 --- a/src/pages/staff/roles.astro +++ b/src/pages/staff/roles.astro @@ -78,7 +78,14 @@ import Base from '../../layouts/Base.astro'; +

+ Support grants Support Desk access. Knowledge separately grants draft + editing, test-report review, evidence and provenance management, guide + publication, and retirement. Knowledge does not grant agent linking + or account and role administration. +

diff --git a/worker/src/admin-api.test.ts b/worker/src/admin-api.test.ts index 19b43b9..da977e5 100644 --- a/worker/src/admin-api.test.ts +++ b/worker/src/admin-api.test.ts @@ -11,7 +11,15 @@ import type { VerifiedIdentityClaims, } from './identity-contracts'; import { createRoleHolderIndex } from './role-holder-index'; -import { ADMIN_ROLE, SUPPORT_ROLE } from './support-access'; +import { + ADMIN_ROLE, + SUPPORT_ROLE, + KNOWLEDGE_ROLE, + APPLICATION_SCOPE, + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + AGENT_LINK_PERMISSION, +} from './support-access'; +import { createAgentPrincipalResolver } from './agent-authority'; import { createAdminLookupLimiter, createAdminMutationLimiter, @@ -114,7 +122,9 @@ function mutate( }); } -function fixture(options: { bootstrapPrincipals?: readonly PrincipalId[] } = {}) { +function fixture( + options: { bootstrapPrincipals?: readonly PrincipalId[] } = {}, +) { const store = createMemoryStore(); const sessions = createSessionStore(store, { logger }); const users = new Map([ @@ -131,33 +141,32 @@ function fixture(options: { bootstrapPrincipals?: readonly PrincipalId[] } = {}) logger, clock, }); + const holderIndex = createRoleHolderIndex(store); const api = createAdminApi({ sessions, identity, identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, logger, roleStore: runtime.roleStore, - holderIndex: createRoleHolderIndex(store), + holderIndex, mutationLimiter: createAdminMutationLimiter(store, clock), lookupLimiter: createAdminLookupLimiter(store, clock), bootstrapPrincipals: new Set(options.bootstrapPrincipals ?? []), }); - return { api, sessions, identity, roleStore: runtime.roleStore }; + return { api, sessions, identity, roleStore: runtime.roleStore, holderIndex }; } /** Seed the first administrator the way the bootstrap touch would. */ -async function bootstrappedAdmin( - options: { bootstrapArmed?: boolean } = {}, -) { +async function bootstrappedAdmin(options: { bootstrapArmed?: boolean } = {}) { const world = fixture({ bootstrapPrincipals: [admin] }); const auth = await sessionCookie(world.sessions, admin, 'b'.repeat(43)); // The first authenticated admin-surface touch seeds Admin, then passes // the permission check on the same request. const state = await world.api(get('/api/admin/state', auth.cookie)); expect(state.status).toBe(200); - expect(((await state.json()) as { bootstrapArmed: boolean }).bootstrapArmed).toBe( - options.bootstrapArmed ?? true, - ); + expect( + ((await state.json()) as { bootstrapArmed: boolean }).bootstrapArmed, + ).toBe(options.bootstrapArmed ?? true); return { ...world, auth }; } @@ -208,7 +217,9 @@ describe('one search box', () => { // Exactly one email normalization function exists and it lives in // Identity: the host trims the text-box value and passes it through // untouched — no host-side lowercasing. - expect(identity.findUserByEmail).toHaveBeenCalledWith('Member@Example.TEST'); + expect(identity.findUserByEmail).toHaveBeenCalledWith( + 'Member@Example.TEST', + ); }); it('answers 404 for an unknown principal and 400 for unusable input', async () => { @@ -312,11 +323,7 @@ describe('admin API access', () => { ); expect(assign.status).toBe(201); const revoke = await api( - mutate( - 'DELETE', - `/api/admin/assignments/${held[0]!.id}`, - auth, - ), + mutate('DELETE', `/api/admin/assignments/${held[0]!.id}`, auth), ); expect(revoke.status).toBe(200); const after = await api(get('/api/admin/state', auth.cookie)); @@ -372,14 +379,200 @@ describe('principal views', () => { const history = await api( get(`/api/admin/principals/${member}/history`, auth.cookie), ); - const events = ((await history.json()) as { - events: readonly { kind: string; role: string }[]; - }).events; + const events = ( + (await history.json()) as { + events: readonly { kind: string; role: string }[]; + } + ).events; expect(events.map((event) => event.kind)).toEqual(['granted', 'revoked']); }); }); describe('role mutations', () => { + it('assigns and revokes explicit Knowledge through the audited surface without changing existing grants', async () => { + const world = await bootstrappedAdmin(); + const resolver = createAgentPrincipalResolver({ + identity: world.identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + roleStore: world.roleStore, + }); + expect( + ( + await world.api( + mutate('POST', `/api/admin/principals/${member}/roles`, world.auth, { + role: SUPPORT_ROLE, + }), + ) + ).status, + ).toBe(201); + expect( + ( + await world.api( + mutate( + 'POST', + `/api/admin/principals/${secondAdmin}/roles`, + world.auth, + { role: SUPPORT_ROLE }, + ), + ) + ).status, + ).toBe(201); + const historical = ( + await world.roleStore.listActiveRoleAssignments( + secondAdmin, + APPLICATION_SCOPE, + ) + ).find((assignment) => assignment.role === SUPPORT_ROLE); + if (historical === undefined) + throw new Error('Expected historical Support assignment.'); + expect( + ( + await world.api( + mutate( + 'DELETE', + `/api/admin/assignments/${historical.id}`, + world.auth, + ), + ) + ).status, + ).toBe(200); + const supportBefore = await world.roleStore.listRoleAssignments( + member, + APPLICATION_SCOPE, + ); + const revokedBefore = await world.roleStore.getRoleAssignment( + historical.id, + ); + const adminBefore = await world.roleStore.listRoleAssignments( + admin, + APPLICATION_SCOPE, + ); + expect(revokedBefore?.assignment.status).toBe('revoked'); + expect((await resolver(member))?.permissions).not.toContain( + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + ); + expect( + ( + await world.api( + mutate('POST', `/api/admin/principals/${member}/roles`, world.auth, { + role: KNOWLEDGE_ROLE, + }), + ) + ).status, + ).toBe(201); + const knowledge = ( + await world.roleStore.listActiveRoleAssignments(member, APPLICATION_SCOPE) + ).find((assignment) => assignment.role === KNOWLEDGE_ROLE); + if (knowledge === undefined) + throw new Error('Expected explicitly assigned Knowledge role.'); + expect(knowledge.grantedBy).toEqual({ + kind: 'principal', + principalId: admin, + }); + expect(await world.holderIndex.listByRole(KNOWLEDGE_ROLE)).toContainEqual({ + role: KNOWLEDGE_ROLE, + principalId: member, + assignmentId: knowledge.id, + }); + const approved = await resolver(member); + expect(approved?.permissions).toContain( + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + ); + expect(approved?.permissions).toContain('knowledge.article.publish'); + expect(approved?.permissions).not.toContain(AGENT_LINK_PERMISSION); + expect(approved?.permissions).not.toContain('admin.role.assign'); + expect(approved?.permissions).not.toContain('knowledge.collection.manage'); + const knowledgeSession = await sessionCookie(world.sessions, member); + expect( + ( + await world.api( + mutate( + 'POST', + `/api/admin/principals/${member}/roles`, + knowledgeSession, + { role: ADMIN_ROLE }, + ), + ) + ).status, + ).toBe(403); + expect( + ( + await world.api( + mutate('POST', `/api/admin/principals/${member}/roles`, world.auth, { + role: KNOWLEDGE_ROLE, + }), + ) + ).status, + ).toBe(409); + expect( + ( + await world.api( + mutate( + 'DELETE', + `/api/admin/assignments/${knowledge.id}`, + world.auth, + ), + ) + ).status, + ).toBe(200); + expect((await resolver(member))?.permissions).not.toContain( + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + ); + expect((await resolver(member))?.permissions).not.toContain( + 'knowledge.article.publish', + ); + expect( + ( + await world.roleStore.listRoleAssignments(member, APPLICATION_SCOPE) + ).filter((assignment) => assignment.role === SUPPORT_ROLE), + ).toEqual(supportBefore); + expect(await world.roleStore.getRoleAssignment(historical.id)).toEqual( + revokedBefore, + ); + expect( + await world.roleStore.listRoleAssignments(admin, APPLICATION_SCOPE), + ).toEqual(adminBefore); + expect( + (await world.roleStore.listRoleAssignmentAuditEvents(knowledge.id)).map( + (record) => record.event.kind, + ), + ).toEqual(['granted', 'revoked']); + // The holder index is deliberately an append-only superset after revocation. + expect(await world.holderIndex.listByRole(KNOWLEDGE_ROLE)).toContainEqual({ + role: KNOWLEDGE_ROLE, + principalId: member, + assignmentId: knowledge.id, + }); + }); + + it('requires actual Admin authority and CSRF for Knowledge assignments', async () => { + const world = await bootstrappedAdmin(); + const memberSession = await sessionCookie(world.sessions, member); + expect( + ( + await world.api( + mutate( + 'POST', + `/api/admin/principals/${member}/roles`, + memberSession, + { role: KNOWLEDGE_ROLE }, + ), + ) + ).status, + ).toBe(403); + const noCsrf = mutate( + 'POST', + `/api/admin/principals/${member}/roles`, + world.auth, + { role: KNOWLEDGE_ROLE }, + ); + noCsrf.headers.delete('X-Pegma-CSRF'); + expect((await world.api(noCsrf)).status).toBe(403); + expect( + await world.roleStore.listRoleAssignments(member, APPLICATION_SCOPE), + ).toEqual([]); + }); + it('assigns allowlisted roles only, to real principals only, once', async () => { const { api, auth } = await bootstrappedAdmin(); expect( @@ -394,9 +587,14 @@ describe('role mutations', () => { expect( ( await api( - mutate('POST', '/api/admin/principals/unknown-principal/roles', auth, { - role: SUPPORT_ROLE, - }), + mutate( + 'POST', + '/api/admin/principals/unknown-principal/roles', + auth, + { + role: SUPPORT_ROLE, + }, + ), ) ).status, ).toBe(404); diff --git a/worker/src/admin-api.ts b/worker/src/admin-api.ts index fa32a75..73cf5ef 100644 --- a/worker/src/admin-api.ts +++ b/worker/src/admin-api.ts @@ -20,12 +20,10 @@ import { requireSameOriginMutation, type Authenticated, } from './api-auth'; -import type { - IdentityLinkProjector, - IdentityPort, -} from './identity-contracts'; +import type { IdentityLinkProjector, IdentityPort } from './identity-contracts'; import { ADMIN_ROLE, + KNOWLEDGE_ROLE, APPLICATION_SCOPE, PEGMA_ACCESS_POLICY, SUPPORT_ROLE, @@ -41,7 +39,8 @@ import { const PRINCIPAL_PATH = /^\/api\/admin\/principals\/([A-Za-z0-9._~-]{1,200})(?:\/(roles|history))?$/u; -const ASSIGNMENT_PATH = /^\/api\/admin\/assignments\/([A-Za-z0-9._~-]{1,200})$/u; +const ASSIGNMENT_PATH = + /^\/api\/admin\/assignments\/([A-Za-z0-9._~-]{1,200})$/u; /** How a lookup query was interpreted. */ export type LookupKind = 'email' | 'principalId'; @@ -61,7 +60,7 @@ export function classifyLookup(query: string): LookupKind { /** The only roles the surface may assign; entitlements are not roles. */ const ASSIGNABLE_ROLES: ReadonlySet = Object.freeze( - new Set([SUPPORT_ROLE, ADMIN_ROLE]), + new Set([SUPPORT_ROLE, KNOWLEDGE_ROLE, ADMIN_ROLE]), ); export interface AdminApiOptions { @@ -218,8 +217,7 @@ export function createAdminApi( authenticated.link.subject, ); const body = exactObject(await readJson(request), ['query']); - const query = - typeof body.query === 'string' ? body.query.trim() : ''; + const query = typeof body.query === 'string' ? body.query.trim() : ''; if (query === '' || query.length > 320) { throw new ApiError(400, 'invalid_query'); } diff --git a/worker/src/agent-access-api.ts b/worker/src/agent-access-api.ts new file mode 100644 index 0000000..deb94f1 --- /dev/null +++ b/worker/src/agent-access-api.ts @@ -0,0 +1,211 @@ +import { + OAuthError, + type AgentAccessConfiguration, + type AgentAccessServicePort, + type ApproveInput, +} from '@pegma/agent-access'; +import { + ApiError, + boundedString, + json, + optionalKeysObject, + readJson, +} from './api-auth'; +import { + requireAgentBrowserContext, + type AgentBrowserOptions, +} from './agent-authority'; + +export interface AgentAccessApiOptions extends AgentBrowserOptions { + readonly service: AgentAccessServicePort; + readonly configuration: AgentAccessConfiguration; + readonly limit: (request: Request) => Promise; +} + +/** Existing-login consent and owner-only views. Public OAuth routes live in AA. */ +export function createAgentAccessApi( + options: AgentAccessApiOptions, +): (request: Request) => Promise { + return async (request) => { + const url = new URL(request.url); + const path = url.pathname; + const grant = /^\/api\/agent-access\/grants\/([A-Za-z0-9_-]{1,128})$/u.exec( + path, + ); + if ( + path !== '/api/agent-access/state' && + path !== '/api/agent-access/approval' && + grant === null + ) + return null; + let response: Response; + try { + const allowed = + path === '/api/agent-access/state' + ? ['GET'] + : grant === null + ? ['GET', 'POST'] + : ['GET', 'DELETE']; + if (!allowed.includes(request.method)) + return json( + { error: 'method_not_allowed' }, + { + status: 405, + headers: { + Allow: allowed.join(', '), + 'Referrer-Policy': 'no-referrer', + }, + }, + ); + const credentialHeaders = [ + 'Cookie', + 'Origin', + 'X-Pegma-CSRF', + 'Sec-Fetch-Site', + 'Authorization', + ].map((name) => ({ name, value: request.headers.get(name) })); + function sameBrowserHeaders() { + if ( + credentialHeaders.some( + ({ name, value }) => request.headers.get(name) !== value, + ) + ) + throw new ApiError(403, 'browser_credential_changed'); + } + await options.limit(request); + sameBrowserHeaders(); + const { authenticated, context } = await requireAgentBrowserContext( + request, + options, + request.method !== 'GET', + ); + sameBrowserHeaders(); + const principalId = context.access.principalId; + const sessionId = authenticated.rawSessionId; + if (path === '/api/agent-access/state') { + if (url.search !== '') throw new ApiError(400, 'invalid_request'); + response = json({ + csrfToken: authenticated.csrfToken, + resource: options.configuration.resource, + scopes: options.configuration.scopes, + }); + } else if (grant !== null) { + if ( + url.search !== '' || + (request.method === 'DELETE' && request.body !== null) + ) + throw new ApiError(400, 'invalid_request'); + const grantId = boundedString(grant[1], 1, 128); + if (request.method === 'GET') + response = json(await options.service.getGrant(context, grantId)); + else { + await options.service.revokeGrant(context, grantId); + response = new Response(null, { + status: 204, + headers: { + 'Cache-Control': 'no-store', + Pragma: 'no-cache', + Vary: 'Cookie', + }, + }); + } + } else if (request.method === 'GET') { + const keys = [...url.searchParams.keys()]; + if ( + keys.length !== 1 || + (keys[0] !== 'request_id' && keys[0] !== 'user_code') + ) + throw new ApiError(400, 'invalid_request'); + const selector = boundedString(url.searchParams.get(keys[0]), 1, 128); + response = json( + keys[0] === 'user_code' + ? await options.service.getDeviceApproval(context, selector) + : await options.service.getAuthorizationApproval(context, selector), + ); + } else { + if (url.search !== '') throw new ApiError(400, 'invalid_request'); + const body = optionalKeysObject( + await readJson(request, { timeoutMs: 10_000 }), + ['requestId', 'decision'], + ['approvedScopes', 'userCode'], + ); + if (body.decision !== 'approve' && body.decision !== 'deny') + throw new ApiError(400, 'invalid_request'); + let approvedScopes: string[] | undefined; + if (body.approvedScopes !== undefined) { + if ( + !Array.isArray(body.approvedScopes) || + body.approvedScopes.length > 3 + ) + throw new ApiError(400, 'invalid_request'); + approvedScopes = body.approvedScopes.map((value: unknown) => + boundedString(value, 1, 128), + ); + } + const command: ApproveInput = { + requestId: boundedString(body.requestId, 1, 128), + decision: body.decision, + ...(approvedScopes === undefined ? {} : { approvedScopes }), + ...(body.userCode === undefined + ? {} + : { userCode: boundedString(body.userCode, 1, 128) }), + }; + // Body input is an awaited browser boundary. Account/role authority in + // AA cannot establish that the original host session is still live. + sameBrowserHeaders(); + const current = await requireAgentBrowserContext( + request, + options, + true, + ); + sameBrowserHeaders(); + if ( + current.authenticated.rawSessionId !== sessionId || + current.context.access.principalId !== principalId + ) + throw new ApiError(403, 'browser_credential_changed'); + response = json( + await options.service.approve(current.context, command), + ); + } + // The service may have awaited private reads or a committed mutation. + // Withhold its response if the original browser no longer has authority; + // this does not undo an approval or revocation that already committed. + const final = await requireAgentBrowserContext( + request, + options, + request.method !== 'GET', + ); + sameBrowserHeaders(); + if ( + final.authenticated.rawSessionId !== sessionId || + final.context.access.principalId !== principalId + ) + throw new ApiError(403, 'forbidden'); + } catch (error) { + if (error instanceof ApiError) + response = json( + { error: error.code }, + { + status: error.status, + ...(error.retryAfterSeconds === undefined + ? {} + : { + headers: { 'Retry-After': String(error.retryAfterSeconds) }, + }), + }, + ); + else if (error instanceof OAuthError) + response = json(error.toJSON(), { status: error.status }); + else { + options.logger.log('error', 'agent_access.browser_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + response = json({ error: 'service_unavailable' }, { status: 503 }); + } + } + response.headers.set('Referrer-Policy', 'no-referrer'); + response.headers.set('X-Content-Type-Options', 'nosniff'); + return response; + }; +} diff --git a/worker/src/agent-access-runtime.test.ts b/worker/src/agent-access-runtime.test.ts new file mode 100644 index 0000000..6224ed2 --- /dev/null +++ b/worker/src/agent-access-runtime.test.ts @@ -0,0 +1,544 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createMemoryStore } from '@pegma/storage-core'; +import { createSessionStore } from '@pegma/sessions'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { hasPermission } from '@pegma/authorization-core'; +import type { PublicClient } from '@pegma/agent-access'; +import type { + IdentityPort, + IdentityUser, + VerifiedIdentityClaims, +} from './identity-contracts'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { isPlainObject } from './api-auth'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { + ADMIN_ROLE, + AGENT_KNOWLEDGE_PERMISSIONS, + AGENT_LINK_PERMISSION, + APPLICATION_SCOPE, + AUTHORIZATION_APPLICATION_ID, + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + KNOWLEDGE_ROLE, + PEGMA_ACCESS_POLICY, + SUPPORT_ROLE, + SUPPORT_STAFF_PERMISSIONS, +} from './support-access'; +import { + AGENT_RESOURCE, + createAgentAccessRuntime, + readAgentClients, +} from './agent-access-runtime'; + +const client: PublicClient = { + clientId: 'synthetic-unit-client', + name: 'Synthetic protocol client', + redirectUris: ['https://client.example.test/callback'], + allowedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS], + grantTypes: ['device_code', 'authorization_code'], +}; + +async function body( + response: Response | null, +): Promise> { + if (response === null) throw new Error('Expected a routed response.'); + const result: unknown = await response.json(); + if (!isPlainObject(result)) throw new Error('Expected an object response.'); + return result; +} +function text(value: Record, key: string): string { + const field = value[key]; + if (typeof field !== 'string') throw new Error('Expected a response string.'); + return field; +} + +async function fixture() { + const store = createMemoryStore(); + const logger = { log: vi.fn() }; + const sessions = createSessionStore(store, { logger }); + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + const users = new Map(); + for (const id of ['admin', 'other-admin', 'staff', 'knowledge', 'member']) + users.set(id, { + principalId: id, + email: `${id}@example.test`, + emailVerified: true, + status: 'active', + createdAt: '2026-07-31T00:00:00.000Z', + updatedAt: '2026-07-31T00:00:00.000Z', + }); + const identity: IdentityPort = { + claimsFor: vi.fn(async (principalId: string) => { + const current = users.get(principalId); + if (current === undefined) + throw Object.assign(new Error('not found'), { code: 'not_found' }); + if (current.status !== 'active' || !current.emailVerified) + throw Object.assign(new Error('not active and verified'), { + code: 'invalid_state', + }); + return { + issuer: IDENTITY_ISSUER, + subject: principalId, + emailVerified: true, + } satisfies VerifiedIdentityClaims; + }), + getUser: vi.fn( + async (principalId: string) => users.get(principalId) ?? null, + ), + findUserByEmail: vi.fn(async () => null), + beginPasskeyRegistration: vi.fn(), + finishPasskeyRegistration: vi.fn(), + beginPasskeyAuthentication: vi.fn(), + finishPasskeyAuthentication: vi.fn(), + listPasskeys: vi.fn(async () => []), + removePasskey: vi.fn(async () => true), + }; + async function grant(principalId: string, role: string) { + return roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: `${principalId}-${role}`, + principalId, + role, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'principal', principalId: 'test-operator' }, + grantedAtEpochMs: 1000, + status: 'active', + }, + auditEventId: `grant-${principalId}-${role}`, + }); + } + await grant('admin', ADMIN_ROLE); + await grant('other-admin', ADMIN_ROLE); + await grant('staff', SUPPORT_ROLE); + await grant('knowledge', KNOWLEDGE_ROLE); + const cookies = new Map(); + const rawSessions = new Map(); + for (const [index, id] of [ + 'admin', + 'other-admin', + 'staff', + 'knowledge', + 'member', + ].entries()) { + const raw = String(index).padStart(2, '0') + 's'.repeat(41); + await sessions.create(raw, { + principalId: id, + data: JSON.stringify({ + version: 1, + csrfToken: 'c'.repeat(43), + issuer: IDENTITY_ISSUER, + subject: id, + }), + }); + cookies.set(id, `${SESSION_COOKIE}=${raw}`); + rawSessions.set(id, raw); + } + const options = { + store, + sessions, + identity, + roleStore, + logger, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + clients: [client], + }; + const candidateRuntime = createAgentAccessRuntime(options); + if (candidateRuntime === null) + throw new Error('Expected a configured runtime.'); + const runtime = candidateRuntime; + function request(path: string, actor = 'admin', init: RequestInit = {}) { + const headers = new Headers(init.headers); + const cookie = cookies.get(actor); + if (cookie !== undefined) headers.set('Cookie', cookie); + if (init.method === 'POST' || init.method === 'DELETE') { + headers.set('Origin', IDENTITY_ISSUER); + headers.set('Sec-Fetch-Site', 'same-origin'); + headers.set('X-Pegma-CSRF', 'c'.repeat(43)); + if (init.body !== undefined) + headers.set('Content-Type', 'application/json'); + } + return new Request(`${IDENTITY_ISSUER}${path}`, { ...init, headers }); + } + async function prepared() { + const device = await runtime.service.beginDeviceAuthorization({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + scopes: [...AGENT_KNOWLEDGE_PERMISSIONS], + }); + const view = await body( + await runtime.api( + request(`/api/agent-access/approval?user_code=${device.user_code}`), + ), + ); + return { device, requestId: text(view, 'requestId') }; + } + async function approved() { + const pending = await prepared(); + const result = await runtime.api( + request('/api/agent-access/approval', 'admin', { + method: 'POST', + body: JSON.stringify({ + requestId: pending.requestId, + decision: 'approve', + userCode: pending.device.user_code, + approvedScopes: [AGENT_KNOWLEDGE_PERMISSIONS[0]], + }), + }), + ); + expect(result?.status).toBe(200); + const tokens = await runtime.service.pollDeviceToken({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + deviceCode: pending.device.device_code, + }); + return { ...pending, tokens }; + } + return { + store, + logger, + sessions, + rawSessions, + roleStore, + users, + identity, + options, + runtime, + request, + prepared, + approved, + }; +} + +describe('Agent Access host composition', () => { + it('applies an explicit resource budget using the existing durable limiter', async () => { + const f = await fixture(); + const runtime = createAgentAccessRuntime({ + ...f.options, + resourceLimitCount: 1, + }); + if (runtime === null) throw new Error('Expected a configured runtime.'); + const request = new Request(AGENT_RESOURCE, { + headers: { 'CF-Connecting-IP': '192.0.2.17' }, + }); + expect(await runtime.resourceLimit(request)).toMatchObject({ + allowed: true, + }); + expect(await runtime.resourceLimit(request)).toMatchObject({ + allowed: false, + }); + expect(runtime.limiters).toHaveLength(6); + }); + + it('requires explicit bounded public client registration', async () => { + const f = await fixture(); + expect(readAgentClients(undefined)).toBeNull(); + expect(readAgentClients('[]')).toBeNull(); + expect( + createAgentAccessRuntime({ ...f.options, clients: null }), + ).toBeNull(); + expect(readAgentClients(JSON.stringify([client]))).toEqual([client]); + expect(() => readAgentClients('x'.repeat(16385))).toThrow(); + expect(() => + readAgentClients( + JSON.stringify([{ ...client, clientSecret: 'not-supported' }]), + ), + ).toThrow(); + expect(() => + readAgentClients( + JSON.stringify([{ ...client, allowedScopes: [AGENT_LINK_PERMISSION] }]), + ), + ).toThrow(); + expect(() => + createAgentAccessRuntime({ + ...f.options, + clients: [ + { ...client, redirectUris: ['https://client.example.test/*'] }, + ], + }), + ).toThrow(); + }); + + it('preserves existing role lifecycle while only current Admin can link', async () => { + const f = await fixture(); + const history = await f.roleStore.listRoleAssignments( + 'admin', + APPLICATION_SCOPE, + ); + expect( + (await f.runtime.api(f.request('/api/agent-access/state')))?.status, + ).toBe(200); + expect( + (await f.runtime.api(f.request('/api/agent-access/state', 'staff'))) + ?.status, + ).toBe(403); + expect( + (await f.runtime.api(f.request('/api/agent-access/state', 'knowledge'))) + ?.status, + ).toBe(403); + expect( + (await f.runtime.api(f.request('/api/agent-access/state', 'member'))) + ?.status, + ).toBe(403); + expect( + (await f.runtime.api(f.request('/api/agent-access/state', 'absent'))) + ?.status, + ).toBe(401); + expect( + await f.roleStore.listRoleAssignments('admin', APPLICATION_SCOPE), + ).toEqual(history); + const staff = await createAgentPrincipalResolver(f.options)('staff'); + expect(PEGMA_ACCESS_POLICY.roles?.[SUPPORT_ROLE]).toEqual( + SUPPORT_STAFF_PERMISSIONS, + ); + expect(staff?.permissions).not.toContain( + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + ); + expect(staff?.permissions).not.toContain('knowledge.article.draft.write'); + expect(staff?.permissions).not.toContain('knowledge.article.publish'); + expect(staff?.permissions).not.toContain(AGENT_LINK_PERMISSION); + expect(staff?.permissions).not.toContain('knowledge.collection.manage'); + expect( + (await f.roleStore.listRoleAssignments('staff', APPLICATION_SCOPE)).map( + (assignment) => assignment.role, + ), + ).toEqual([SUPPORT_ROLE]); + const knowledge = await createAgentPrincipalResolver(f.options)( + 'knowledge', + ); + expect(knowledge?.permissions).toContain( + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + ); + expect(knowledge?.permissions).toContain('knowledge.article.publish'); + expect(knowledge?.permissions).not.toContain(AGENT_LINK_PERMISSION); + expect(knowledge?.permissions).not.toContain('admin.role.assign'); + expect(knowledge?.permissions).not.toContain('knowledge.collection.manage'); + }); + + it('rejects bearer substitution, missing CSRF, cross-origin consent and caller actors', async () => { + const f = await fixture(); + const pending = await f.prepared(); + const command = { + requestId: pending.requestId, + decision: 'approve', + userCode: pending.device.user_code, + }; + const bearer = f.request('/api/agent-access/state'); + bearer.headers.set('Authorization', 'Bearer not-a-browser-session'); + expect((await f.runtime.api(bearer))?.status).toBe(403); + const noCsrf = f.request('/api/agent-access/approval', 'admin', { + method: 'POST', + body: JSON.stringify(command), + }); + noCsrf.headers.delete('X-Pegma-CSRF'); + expect((await f.runtime.api(noCsrf))?.status).toBe(403); + const cross = f.request('/api/agent-access/approval', 'admin', { + method: 'POST', + body: JSON.stringify(command), + }); + cross.headers.set('Origin', 'https://attacker.example.test'); + expect((await f.runtime.api(cross))?.status).toBe(403); + expect( + ( + await f.runtime.api( + f.request('/api/agent-access/approval', 'admin', { + method: 'POST', + body: JSON.stringify({ ...command, actorId: 'other-admin' }), + }), + ) + )?.status, + ).toBe(400); + const view = await body( + await f.runtime.api( + f.request( + `/api/agent-access/approval?user_code=${pending.device.user_code}`, + ), + ), + ); + expect(view.status).toBe('pending'); + }); + + it('uses current consent subset and never delegates staff, governance or linking authority', async () => { + const f = await fixture(); + const { tokens } = await f.approved(); + const access = await f.runtime.protectedResource.authenticate( + new Request(`${IDENTITY_ISSUER}/api/knowledge/v1`, { + headers: { Authorization: `Bearer ${tokens.access_token}` }, + }), + ); + if (access instanceof Response) + throw new Error('Expected delegated access.'); + expect(access.access.permissions).toEqual([AGENT_KNOWLEDGE_PERMISSIONS[0]]); + expect(access.access.roles).toEqual([]); + expect(access.access.entitlements).toEqual([]); + expect(hasPermission(access.access, AGENT_LINK_PERMISSION)).toBe(false); + expect( + hasPermission(access.access, KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION), + ).toBe(false); + }); + + it('enforces owner-only grant reads and revocation, then rejects access and refresh', async () => { + const f = await fixture(); + const { tokens, requestId } = await f.approved(); + expect( + ( + await f.runtime.api( + f.request(`/api/agent-access/grants/${requestId}`, 'other-admin'), + ) + )?.status, + ).toBe(403); + expect( + ( + await f.runtime.api( + f.request(`/api/agent-access/grants/${requestId}`, 'other-admin', { + method: 'DELETE', + }), + ) + )?.status, + ).toBe(403); + expect( + (await f.runtime.api(f.request(`/api/agent-access/grants/${requestId}`))) + ?.status, + ).toBe(200); + expect( + ( + await f.runtime.api( + f.request(`/api/agent-access/grants/${requestId}`, 'admin', { + method: 'DELETE', + }), + ) + )?.status, + ).toBe(204); + await expect( + f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).rejects.toThrow(); + await expect( + f.runtime.service.refresh({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + refreshToken: tokens.refresh_token, + }), + ).rejects.toThrow(); + }); + + it('honors real stored Admin revocation without caching or reseeding', async () => { + const f = await fixture(); + const { tokens } = await f.approved(); + const record = await f.roleStore.getRoleAssignment('admin-Admin'); + if (record === null) throw new Error('Expected stored Admin assignment.'); + await f.roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: 'admin-Admin', + expectedConcurrencyToken: record.concurrencyToken, + revokedBy: { kind: 'principal', principalId: 'other-admin' }, + revokedAtEpochMs: 2000, + auditEventId: 'revoke-admin', + }); + await expect( + f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).rejects.toThrow(); + await expect( + f.runtime.service.refresh({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + refreshToken: tokens.refresh_token, + }), + ).rejects.toThrow(); + expect( + (await f.runtime.api(f.request('/api/agent-access/state')))?.status, + ).toBe(403); + expect( + (await f.roleStore.getRoleAssignment('admin-Admin'))?.assignment.status, + ).toBe('revoked'); + }); + + it('rechecks active account and browser session independently', async () => { + const f = await fixture(); + const { tokens } = await f.approved(); + const raw = f.rawSessions.get('admin'); + if (raw === undefined) throw new Error('Expected browser session.'); + await f.sessions.destroy(raw); + expect( + (await f.runtime.api(f.request('/api/agent-access/state')))?.status, + ).toBe(401); + await expect( + f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).resolves.toMatchObject({ clientId: client.clientId }); + const prior = f.users.get('admin'); + if (prior === undefined) throw new Error('Expected account.'); + f.users.set('admin', { ...prior, status: 'pending' }); + await expect( + f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).rejects.toThrow(); + await expect( + f.runtime.service.refresh({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + refreshToken: tokens.refresh_token, + }), + ).rejects.toThrow(); + }); + + it('fails closed on authority infrastructure outage without logging submitted credentials', async () => { + const f = await fixture(); + const runtime = createAgentAccessRuntime({ + ...f.options, + roleStore: { + listActiveRoleAssignments: async (id, scope) => { + await f.roleStore.listActiveRoleAssignments(id, scope); + throw new Error('private-backend-detail'); + }, + }, + }); + if (runtime === null) throw new Error('Expected configured runtime.'); + expect( + (await runtime.api(f.request('/api/agent-access/state')))?.status, + ).toBe(503); + expect(JSON.stringify(f.logger.log.mock.calls)).not.toContain( + 'private-backend-detail', + ); + }); + + it('preserves the validated PKCE request through existing-login redirect', async () => { + const f = await fixture(); + const values = new URLSearchParams({ + response_type: 'code', + client_id: client.clientId, + redirect_uri: client.redirectUris[0] ?? '', + resource: AGENT_RESOURCE, + scope: AGENT_KNOWLEDGE_PERMISSIONS.join(' '), + code_challenge: 'A'.repeat(43), + code_challenge_method: 'S256', + state: 'synthetic-state', + }); + const request = new Request( + `${IDENTITY_ISSUER}/api/agent-access/authorize?${values}`, + ); + const response = await f.runtime.protocol.handle(request); + expect(response?.status).toBe(303); + const location = response?.headers.get('Location'); + if (location === null || location === undefined) + throw new Error('Expected login redirect.'); + const login = new URL(location); + expect(login.origin + login.pathname).toBe(`${IDENTITY_ISSUER}/account`); + expect(login.searchParams.get('returnTo')).toBe( + new URL(request.url).pathname + new URL(request.url).search, + ); + expect( + await f.runtime.protocol.handle( + new Request(`${IDENTITY_ISSUER}/api/mcp`), + ), + ).toBeNull(); + }); +}); diff --git a/worker/src/agent-access-runtime.ts b/worker/src/agent-access-runtime.ts new file mode 100644 index 0000000..ebe149a --- /dev/null +++ b/worker/src/agent-access-runtime.ts @@ -0,0 +1,276 @@ +import { + createAgentAccess, + createAgentAccessHttp, + createProtectedResourceAuthenticator, + type AgentAccessConfiguration, + type AgentAccessHttp, + type AgentAccessLimitResult, + type AgentAccessServicePort, + type GrantType, + type ProtectedResourceAuthenticator, + type PublicClient, + type ScopeDefinition, +} from '@pegma/agent-access'; +import { + createDurableLimiter, + defineRateLimitPolicy, + type DurableRateLimiter, +} from '@pegma/rate-limit-paged'; +import { systemClock, type Clock } from '@pegma/spine'; +import { knowledgeAdmissionPolicyName } from './knowledge-admission'; +import type { Store } from '@pegma/storage-core'; +import { + ApiError, + exactObject, + isPlainObject, + json, + boundedString, +} from './api-auth'; +import { + createAgentPrincipalResolver, + requireAgentBrowserContext, + type AgentBrowserOptions, +} from './agent-authority'; +import { createAgentAccessApi } from './agent-access-api'; +import { IDENTITY_ISSUER } from './identity-api'; +import { + AGENT_KNOWLEDGE_PERMISSIONS, + AGENT_LINK_PERMISSION, +} from './support-access'; + +export const AGENT_RESOURCE = 'https://pegma.dev/api/knowledge/mcp'; +export const AGENT_API_URL = 'https://pegma.dev/api/knowledge/v1'; +export const AGENT_RESOURCE_METADATA_URL = + 'https://pegma.dev/.well-known/oauth-protected-resource/api/knowledge/mcp'; +export const AGENT_ENDPOINTS = Object.freeze({ + authorize: `${IDENTITY_ISSUER}/api/agent-access/authorize`, + deviceAuthorization: `${IDENTITY_ISSUER}/api/agent-access/device-authorizations`, + token: `${IDENTITY_ISSUER}/api/agent-access/token`, + revocation: `${IDENTITY_ISSUER}/api/agent-access/revoke`, + verification: `${IDENTITY_ISSUER}/account/agents/device`, + approval: `${IDENTITY_ISSUER}/account/agents/authorize`, + resourceMetadata: AGENT_RESOURCE_METADATA_URL, +}); +export const AGENT_SCOPES: readonly ScopeDefinition[] = Object.freeze( + AGENT_KNOWLEDGE_PERMISSIONS.map((permission, index) => + Object.freeze({ + name: permission, + version: '1', + description: + [ + 'Read Knowledge Base drafts.', + 'Create and update Knowledge Base drafts.', + 'Submit test evidence for independent staff confirmation.', + ][index] ?? 'Knowledge Base authoring.', + permissions: Object.freeze([permission]), + }), + ), +); + +function strings( + value: unknown, + maximum: number, + itemMaximum: number, +): string[] { + if (!Array.isArray(value) || value.length > maximum) + throw new TypeError('Invalid agent client configuration.'); + const result = value.map((item: unknown) => + boundedString(item, 1, itemMaximum), + ); + if (new Set(result).size !== result.length) + throw new TypeError('Invalid agent client configuration.'); + return result; +} + +/** Optional explicit public registrations. Missing/empty input disables linking. */ +export function readAgentClients( + raw: string | undefined, +): readonly PublicClient[] | null { + if (raw === undefined || raw.trim() === '') return null; + if (raw.length > 16384 || new TextEncoder().encode(raw).byteLength > 16384) + throw new TypeError('Agent client configuration exceeds its bound.'); + const parsed: unknown = JSON.parse(raw); + if (!Array.isArray(parsed) || parsed.length > 16) + throw new TypeError('Invalid agent client configuration.'); + if (parsed.length === 0) return null; + return Object.freeze( + parsed.map((value: unknown): PublicClient => { + if (!isPlainObject(value)) + throw new TypeError('Invalid agent client configuration.'); + const client = exactObject(value, [ + 'clientId', + 'name', + 'redirectUris', + 'allowedScopes', + 'grantTypes', + ]); + const allowedScopes = strings(client.allowedScopes, 3, 128); + if ( + allowedScopes.some( + (scope) => + !AGENT_KNOWLEDGE_PERMISSIONS.some((known) => known === scope), + ) + ) + throw new TypeError('Invalid agent client scopes.'); + const grantTypes = strings(client.grantTypes, 2, 32).map( + (type): GrantType => { + if (type !== 'device_code' && type !== 'authorization_code') + throw new TypeError('Invalid agent grant type.'); + return type; + }, + ); + return Object.freeze({ + clientId: boundedString(client.clientId, 1, 128), + name: boundedString(client.name, 1, 200), + redirectUris: Object.freeze(strings(client.redirectUris, 8, 2048)), + allowedScopes: Object.freeze(allowedScopes), + grantTypes: Object.freeze(grantTypes), + }); + }), + ); +} + +export interface AgentAccessRuntimeOptions extends AgentBrowserOptions { + readonly store: Store; + readonly clock?: Clock; + readonly clients?: readonly PublicClient[] | null; + readonly resourceLimitCount?: number; +} +export interface AgentAccessRuntime { + readonly configuration: AgentAccessConfiguration; + readonly service: AgentAccessServicePort; + readonly protocol: AgentAccessHttp; + readonly api: (request: Request) => Promise; + readonly protectedResource: ProtectedResourceAuthenticator; + readonly resourceLimit: (request: Request) => Promise; + readonly limiters: readonly DurableRateLimiter[]; +} + +async function requestKey(request: Request): Promise { + const address = ( + request.headers.get('CF-Connecting-IP') ?? 'unavailable' + ).slice(0, 128); + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(address), + ); + return [...new Uint8Array(digest)] + .map((byte) => byte.toString(16).padStart(2, '0')) + .join(''); +} + +/** Compose the released OAuth service; no configured client means no issuer. */ +export function createAgentAccessRuntime( + options: AgentAccessRuntimeOptions, +): AgentAccessRuntime | null { + if ( + options.clients === undefined || + options.clients === null || + options.clients.length === 0 + ) + return null; + if (options.clients.length > 16) + throw new TypeError('Agent client configuration exceeds its bound.'); + const clock = options.clock ?? systemClock; + const configuration: AgentAccessConfiguration = Object.freeze({ + issuer: IDENTITY_ISSUER, + resource: AGENT_RESOURCE, + endpoints: AGENT_ENDPOINTS, + approvalPermission: AGENT_LINK_PERMISSION, + clients: options.clients, + scopes: AGENT_SCOPES, + }); + const service = createAgentAccess({ + configuration, + store: options.store, + clock, + resolvePrincipal: createAgentPrincipalResolver(options), + }); + const limiters: DurableRateLimiter[] = []; + function admission(name: string, limit: number) { + const limiter = createDurableLimiter( + defineRateLimitPolicy({ + name: knowledgeAdmissionPolicyName(name, limit), + limit, + windowMs: 5 * 60_000, + }), + options.store, + { clock }, + ); + limiters.push(limiter); + return async (request: Request): Promise => { + const decision = await limiter.allow(await requestKey(request)); + return { + allowed: decision.allowed, + ...(decision.retryAfter === undefined + ? {} + : { + retryAfterSeconds: Math.max( + 1, + Math.ceil(decision.retryAfter / 1000), + ), + }), + }; + }; + } + const protocolLimiters = { + authorize: admission('pegma.agent.authorize', 60), + device_authorization: admission('pegma.agent.device', 60), + token: admission('pegma.agent.token', 300), + revocation: admission('pegma.agent.revoke', 120), + }; + const browserLimit = admission('pegma.agent.browser', 120); + const resourceLimit = admission( + 'pegma.agent.resource', + options.resourceLimitCount ?? 300, + ); + const protocol = createAgentAccessHttp({ + service, + configuration, + limit: (request, { endpoint }) => protocolLimiters[endpoint](request), + authenticateBrowser: async (request) => { + try { + return (await requireAgentBrowserContext(request, options)).context; + } catch (error) { + if (error instanceof ApiError && error.status === 401) { + const original = new URL(request.url); + const login = new URL('/account', IDENTITY_ISSUER); + login.searchParams.set( + 'returnTo', + original.pathname + original.search, + ); + return new Response(null, { + status: 303, + headers: { Location: login.href }, + }); + } + if (error instanceof ApiError) + return json({ error: error.code }, { status: error.status }); + options.logger.log('error', 'agent_access.authority_unavailable'); + return json({ error: 'service_unavailable' }, { status: 503 }); + } + }, + }); + const api = createAgentAccessApi({ + ...options, + service, + configuration, + limit: async (request) => { + const decision = await browserLimit(request); + if (!decision.allowed) + throw new ApiError(429, 'rate_limited', decision.retryAfterSeconds); + }, + }); + return Object.freeze({ + configuration, + service, + protocol, + api, + protectedResource: createProtectedResourceAuthenticator({ + service, + configuration, + }), + resourceLimit, + limiters: Object.freeze(limiters), + }); +} diff --git a/worker/src/agent-authority.ts b/worker/src/agent-authority.ts new file mode 100644 index 0000000..0dd8aa4 --- /dev/null +++ b/worker/src/agent-authority.ts @@ -0,0 +1,121 @@ +import { + hasPermission, + resolveAccess, + type AccessContext, +} from '@pegma/authorization-core'; +import type { BrowserApprovalContext } from '@pegma/agent-access'; +import type { PrincipalId } from '@pegma/spine'; +import { + ApiError, + authenticate, + requireCsrf, + requireSameOriginMutation, + type Authenticated, + type AuthenticationOptions, +} from './api-auth'; +import { IDENTITY_ISSUER } from './identity-api'; +import type { IdentityLinkProjector, IdentityPort } from './identity-contracts'; +import { + AGENT_LINK_PERMISSION, + APPLICATION_SCOPE, + PEGMA_ACCESS_POLICY, + type SupportRoleReader, +} from './support-access'; + +export interface AgentAuthorityOptions { + readonly identity: IdentityPort; + readonly identityLinkFromClaims: IdentityLinkProjector; + readonly roleStore: SupportRoleReader; +} +export interface AgentBrowserOptions + extends AuthenticationOptions, AgentAuthorityOptions {} + +/** Current account and stored roles, with no session-era grants or bootstrap writes. */ +export function createAgentPrincipalResolver( + options: AgentAuthorityOptions, +): (principalId: PrincipalId) => Promise { + return async (principalId) => { + const assignments = await options.roleStore.listActiveRoleAssignments( + principalId, + APPLICATION_SCOPE, + ); + // Published Identity claimsFor requires an active, verified current user. + // Keep that account observation after the awaited stored-role lookup. + let claims; + try { + claims = await options.identity.claimsFor(principalId); + } catch (error) { + const code = + typeof error === 'object' && error !== null && 'code' in error + ? error.code + : undefined; + if (code === 'not_found' || code === 'invalid_state') return null; + throw error; + } + let link; + try { + link = options.identityLinkFromClaims(claims); + } catch { + return null; + } + if ( + claims.issuer !== IDENTITY_ISSUER || + claims.subject !== principalId || + claims.emailVerified !== true || + link.issuer !== IDENTITY_ISSUER || + link.subject !== principalId + ) + return null; + return resolveAccess( + { principalId, roles: assignments.map((assignment) => assignment.role) }, + PEGMA_ACCESS_POLICY, + ); + }; +} + +/** Browser-only host authority; never accepts an agent credential as staff consent. */ +export async function requireCurrentBrowserAccess( + request: Request, + options: AgentBrowserOptions, + permission: string, + mutation = false, +): Promise<{ + readonly authenticated: Authenticated; + readonly access: AccessContext; +}> { + if (new URL(request.url).origin !== IDENTITY_ISSUER) + throw new ApiError(403, 'cross_origin_denied'); + if (request.headers.has('Authorization')) + throw new ApiError(403, 'browser_session_required'); + if (mutation) requireSameOriginMutation(request); + const authenticated = await authenticate(request, options); + if (authenticated === null) + throw new ApiError(401, 'authentication_required'); + if (mutation) await requireCsrf(request, authenticated); + const access = await createAgentPrincipalResolver(options)( + authenticated.link.subject, + ); + if (access === null) throw new ApiError(401, 'authentication_required'); + if (!hasPermission(access, permission)) throw new ApiError(403, 'forbidden'); + return { authenticated, access }; +} + +export async function requireAgentBrowserContext( + request: Request, + options: AgentBrowserOptions, + mutation = false, +): Promise<{ + readonly authenticated: Authenticated; + readonly context: BrowserApprovalContext; +}> { + const { authenticated, access } = await requireCurrentBrowserAccess( + request, + options, + AGENT_LINK_PERMISSION, + mutation, + ); + return { + authenticated, + context: { authentication: 'browser-session', access }, + }; +} diff --git a/worker/src/agent-browser-freshness.test.ts b/worker/src/agent-browser-freshness.test.ts new file mode 100644 index 0000000..cbc73c8 --- /dev/null +++ b/worker/src/agent-browser-freshness.test.ts @@ -0,0 +1,1208 @@ +import type { + ApproveInput, + GrantType, + PublicClient, +} from '@pegma/agent-access'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { KnowledgeBaseNotFoundError } from '@pegma/knowledge-base-application'; +import { createSessionStore } from '@pegma/sessions'; +import { + createMemoryStore, + type CollectionDefinition, + type CollectionStore, + type Store, +} from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import { + createAgentAccessRuntime, + AGENT_RESOURCE, +} from './agent-access-runtime'; +import { isPlainObject } from './api-auth'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { createKnowledgeRuntime } from './knowledge-runtime'; +import { + ADMIN_ROLE, + AGENT_KNOWLEDGE_PERMISSIONS, + APPLICATION_SCOPE, + AUTHORIZATION_APPLICATION_ID, +} from './support-access'; + +const owner = 'synthetic-browser-owner'; +const other = 'synthetic-browser-other-admin'; +const client: PublicClient = { + clientId: 'synthetic-browser-freshness-client', + name: 'Synthetic browser freshness client', + redirectUris: ['https://client.example.test/callback'], + allowedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS], + grantTypes: ['device_code', 'authorization_code'], +}; + +function barrier() { + let release = () => {}; + const ready = new Promise((resolve) => { + release = resolve; + }); + return { ready, release }; +} + +interface StoreHooks { + afterGrantRead: (() => Promise) | undefined; + afterGrantCommit: (() => Promise) | undefined; + afterKbRead: (() => Promise) | undefined; + afterKbCommit: (() => Promise) | undefined; + beforeSessionRead: (() => Promise) | undefined; +} + +/** Only delay real adapter operations; all records and authority are real. */ +function observedStore(backing: Store, hooks: StoreHooks): Store { + return { + collection(definition: CollectionDefinition): CollectionStore { + const target = backing.collection(definition); + const grant = definition.name === 'agent-access.records.v1'; + const kb = definition.name === 'knowledge-base.records.v1'; + const session = definition.name === 'sessions'; + if (!grant && !kb && !session) return target; + return { + ...target, + async get(key) { + if (session) await hooks.beforeSessionRead?.(); + const result = await target.get(key); + if (kb) await hooks.afterKbRead?.(); + return result; + }, + async getVersioned(key) { + if (session) await hooks.beforeSessionRead?.(); + const value = await target.getVersioned(key); + if (grant) await hooks.afterGrantRead?.(); + if (kb) await hooks.afterKbRead?.(); + return value; + }, + async transact(partition, actions) { + const result = await target.transact(partition, actions); + if (result.committed) { + if (grant) await hooks.afterGrantCommit?.(); + if (kb) await hooks.afterKbCommit?.(); + } + return result; + }, + }; + }, + }; +} + +async function value( + response: Response | null, +): Promise> { + if (response === null) throw new Error('Expected the actual browser route.'); + const result: unknown = await response.json(); + if (!isPlainObject(result)) throw new Error('Expected a JSON object.'); + return result; +} + +async function fixture() { + const backing = createMemoryStore(); + const hooks: StoreHooks = { + afterGrantRead: undefined, + afterGrantCommit: undefined, + afterKbRead: undefined, + afterKbCommit: undefined, + beforeSessionRead: undefined, + }; + const store = observedStore(backing, hooks); + const logger = { log() {} }; + const clock = { now: () => new Date().toISOString() }; + const identity = createIdentityRuntime( + { + store, + emailCodeSecretBase64: btoa('s'.repeat(32)), + emailFrom: 'Pegma ', + emailEnabled: false, + }, + logger, + ).identity; + const sessions = createSessionStore(store, { logger, clock }); + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + const cookies = new Map(); + const sessionIds = new Map(); + for (const [index, principalId] of [owner, other].entries()) { + await identity.provisionVerifiedUser({ + principalId, + email: principalId + '@example.test', + }); + await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: 'admin-' + principalId, + principalId, + role: ADMIN_ROLE, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-browser-setup' }, + grantedAtEpochMs: Date.now(), + status: 'active', + }, + auditEventId: 'grant-' + principalId, + }); + const sessionId = String(index) + 's'.repeat(42); + await sessions.create(sessionId, { + principalId, + data: JSON.stringify({ + version: 1, + csrfToken: 'c'.repeat(43), + issuer: IDENTITY_ISSUER, + subject: principalId, + }), + }); + cookies.set(principalId, SESSION_COOKIE + '=' + sessionId); + sessionIds.set(principalId, sessionId); + } + const options = { + store, + clock, + logger, + identity, + sessions, + roleStore, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }; + const candidateRuntime = createAgentAccessRuntime({ + ...options, + clients: [client], + }); + if (candidateRuntime === null) + throw new Error('Expected the explicitly registered synthetic client.'); + const runtime = candidateRuntime; + const knowledge = createKnowledgeRuntime({ + ...options, + agentAccess: runtime, + }); + const resolve = createAgentPrincipalResolver(options); + async function access(principalId = other) { + const current = await resolve(principalId); + if (current === null) throw new Error('Expected a current real principal.'); + return current; + } + function cookie(principalId: string) { + const found = cookies.get(principalId); + if (found === undefined) + throw new Error('Expected an actual session cookie.'); + return found; + } + function browser( + path: string, + method = 'GET', + input?: unknown, + principalId = owner, + ) { + return new Request(IDENTITY_ISSUER + path, { + method, + headers: { + Cookie: cookie(principalId), + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + 'X-Pegma-CSRF': 'c'.repeat(43), + ...(input === undefined ? {} : { 'Content-Type': 'application/json' }), + }, + ...(input === undefined ? {} : { body: JSON.stringify(input) }), + }); + } + async function prepared() { + const device = await runtime.service.beginDeviceAuthorization({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + scopes: [...AGENT_KNOWLEDGE_PERMISSIONS], + }); + const viewed = await runtime.api( + browser( + '/api/agent-access/approval?user_code=' + + encodeURIComponent(device.user_code), + ), + ); + expect(viewed?.status).toBe(200); + const view = await value(viewed); + if (typeof view.requestId !== 'string') + throw new Error('Expected the real approval request ID.'); + return { + device, + requestId: view.requestId, + input: { + requestId: view.requestId, + decision: 'approve', + userCode: device.user_code, + approvedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS], + } satisfies ApproveInput, + }; + } + async function approved() { + const pending = await prepared(); + expect( + ( + await runtime.api( + browser('/api/agent-access/approval', 'POST', pending.input), + ) + )?.status, + ).toBe(200); + const loaded = await runtime.api( + browser('/api/agent-access/grants/' + pending.requestId), + ); + expect(loaded?.status).toBe(200); + const grant = await value(loaded); + if (typeof grant.grantId !== 'string') + throw new Error('Expected the actual returned GrantView identity.'); + return { ...pending, grantId: grant.grantId }; + } + async function pendingApproval(flow: GrantType) { + if (flow === 'device_code') { + const pending = await prepared(); + return { + requestId: pending.requestId, + input: pending.input, + viewPath: + '/api/agent-access/approval?user_code=' + + encodeURIComponent(pending.device.user_code), + async issue(result: Record) { + expect(result).toMatchObject({ flow, approved: true }); + return runtime.service.pollDeviceToken({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + deviceCode: pending.device.device_code, + }); + }, + }; + } + const codeVerifier = 'v'.repeat(43); + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(codeVerifier), + ); + const codeChallenge = btoa(String.fromCharCode(...new Uint8Array(digest))) + .replace(/\+/gu, '-') + .replace(/\//gu, '_') + .replace(/=+$/gu, ''); + const request = await runtime.service.beginAuthorization( + { authentication: 'browser-session', access: await access(owner) }, + { + clientId: client.clientId, + resource: AGENT_RESOURCE, + scopes: [...AGENT_KNOWLEDGE_PERMISSIONS], + redirectUri: client.redirectUris[0]!, + codeChallenge, + codeChallengeMethod: 'S256', + state: 'synthetic-delayed-consent', + }, + ); + expect(request.status).toBe('pending'); + return { + requestId: request.requestId, + input: { + requestId: request.requestId, + decision: 'approve', + approvedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS], + } satisfies ApproveInput, + viewPath: + '/api/agent-access/approval?request_id=' + + encodeURIComponent(request.requestId), + async issue(result: Record) { + expect(result.flow).toBe(flow); + if (typeof result.redirectUri !== 'string') + throw new Error('Expected the actual PKCE approval redirect.'); + const redirect = new URL(result.redirectUri); + expect(redirect.origin + redirect.pathname).toBe( + client.redirectUris[0], + ); + expect(redirect.searchParams.get('state')).toBe( + 'synthetic-delayed-consent', + ); + const code = redirect.searchParams.get('code'); + if (code === null) + throw new Error('Expected an actual authorization code.'); + return runtime.service.exchangeAuthorizationCode({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + code, + redirectUri: client.redirectUris[0]!, + codeVerifier, + }); + }, + }; + } + async function revokeAdmin() { + const assignment = await roleStore.getRoleAssignment('admin-' + owner); + if (assignment === null) + throw new Error('Expected the actual active assignment.'); + expect( + ( + await roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: assignment.assignment.id, + expectedConcurrencyToken: assignment.concurrencyToken, + revokedBy: { kind: 'principal', principalId: other }, + revokedAtEpochMs: Date.now(), + auditEventId: 'revoke-browser-admin', + }) + ).status, + ).toBe('revoked'); + } + async function restoreAdmin() { + await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: 'restored-admin-' + owner, + principalId: owner, + role: ADMIN_ROLE, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'principal', principalId: other }, + grantedAtEpochMs: Date.now(), + status: 'active', + }, + auditEventId: 'restore-browser-admin', + }); + } + async function revokeSession() { + const sessionId = sessionIds.get(owner); + if (sessionId === undefined) + throw new Error('Expected the actual owner session.'); + await sessions.destroy(sessionId); + } + async function restoreSession() { + const sessionId = 'r'.repeat(43); + await sessions.create(sessionId, { + principalId: owner, + data: JSON.stringify({ + version: 1, + csrfToken: 'c'.repeat(43), + issuer: IDENTITY_ISSUER, + subject: owner, + }), + }); + cookies.set(owner, SESSION_COOKIE + '=' + sessionId); + sessionIds.set(owner, sessionId); + } + function block(hook: keyof StoreHooks) { + const entered = barrier(); + const resume = barrier(); + hooks[hook] = async () => { + hooks[hook] = undefined; + entered.release(); + await resume.ready; + }; + return { + waitFor: (operation: Promise) => + Promise.race([ + entered.ready, + operation.then(() => { + throw new Error('The operation ended before its storage barrier.'); + }), + ]), + release: resume.release, + }; + } + return { + runtime, + knowledge, + access, + hooks, + browser, + cookie, + prepared, + pendingApproval, + approved, + revokeAdmin, + restoreAdmin, + revokeSession, + restoreSession, + block, + }; +} + +describe('actual current browser authority after AA service awaits', () => { + it('keeps the original owner-only grant view and browser protections', async () => { + const f = await fixture(); + const grant = await f.approved(); + const own = await f.runtime.api( + f.browser('/api/agent-access/grants/' + grant.grantId), + ); + expect(own?.status).toBe(200); + expect(await value(own)).toMatchObject({ + grantId: grant.grantId, + ownerId: owner, + }); + expect( + ( + await f.runtime.api( + f.browser( + '/api/agent-access/grants/' + grant.grantId, + 'GET', + undefined, + other, + ), + ) + )?.status, + ).toBe(403); + const csrf = f.browser( + '/api/agent-access/grants/' + grant.grantId, + 'DELETE', + ); + csrf.headers.delete('X-Pegma-CSRF'); + expect((await f.runtime.api(csrf))?.status).toBe(403); + const foreign = f.browser( + '/api/agent-access/grants/' + grant.grantId, + 'DELETE', + ); + foreign.headers.set('Origin', 'https://foreign.example.test'); + expect((await f.runtime.api(foreign))?.status).toBe(403); + expect( + ( + await f.runtime.api( + f.browser('/api/agent-access/grants/' + grant.grantId), + ) + )?.status, + ).toBe(200); + }); + + it.each(['role', 'session'] as const)( + 'withholds the private owned-grant DTO after %s revocation during its real AA read', + async (kind) => { + const f = await fixture(); + const grant = await f.approved(); + const blocked = f.block('afterGrantRead'); + const pending = f.runtime.api( + f.browser('/api/agent-access/grants/' + grant.grantId), + ); + await blocked.waitFor(pending); + try { + if (kind === 'role') await f.revokeAdmin(); + else await f.revokeSession(); + } finally { + blocked.release(); + } + const result = await pending; + expect(result?.status).toBe(kind === 'role' ? 403 : 401); + const denied = await value(result); + expect(denied).not.toHaveProperty('grantId'); + expect(denied).not.toHaveProperty('scopes'); + expect(denied).not.toHaveProperty('ownerId'); + }, + ); + + it('withholds a private approval view after stored Admin revocation during its real head read', async () => { + const f = await fixture(); + const request = await f.prepared(); + const blocked = f.block('afterGrantRead'); + const pending = f.runtime.api( + f.browser( + '/api/agent-access/approval?user_code=' + + encodeURIComponent(request.device.user_code), + ), + ); + await blocked.waitFor(pending); + try { + await f.revokeAdmin(); + } finally { + blocked.release(); + } + const result = await pending; + expect(result?.status).toBe(403); + expect(await value(result)).not.toHaveProperty('requestedScopes'); + }); + + it('binds the response to the original browser principal even if a different current Admin session replaces it', async () => { + const f = await fixture(); + const grant = await f.approved(); + const request = f.browser('/api/agent-access/grants/' + grant.grantId); + const blocked = f.block('afterGrantRead'); + const pending = f.runtime.api(request); + await blocked.waitFor(pending); + request.headers.set('Cookie', f.cookie(other)); + blocked.release(); + const result = await pending; + expect(result?.status).toBe(403); + expect(await value(result)).not.toHaveProperty('grantId'); + }); + + it('withholds a committed approval ACK after Admin removal and retains the actual approval', async () => { + const f = await fixture(); + const request = await f.prepared(); + const blocked = f.block('afterGrantCommit'); + const pending = f.runtime.api( + f.browser('/api/agent-access/approval', 'POST', request.input), + ); + await blocked.waitFor(pending); + try { + await f.revokeAdmin(); + } finally { + blocked.release(); + } + const result = await pending; + expect(result?.status).toBe(403); + expect(await value(result)).not.toHaveProperty('approved'); + await f.restoreAdmin(); + const retained = await f.runtime.api( + f.browser( + '/api/agent-access/approval?user_code=' + + encodeURIComponent(request.device.user_code), + ), + ); + expect(retained?.status).toBe(200); + expect(await value(retained)).toMatchObject({ + requestId: request.requestId, + status: 'approved', + }); + }); + + it('withholds a committed revoke ACK after Admin removal and retains the actual revocation', async () => { + const f = await fixture(); + const grant = await f.approved(); + const blocked = f.block('afterGrantCommit'); + const pending = f.runtime.api( + f.browser('/api/agent-access/grants/' + grant.grantId, 'DELETE'), + ); + await blocked.waitFor(pending); + try { + await f.revokeAdmin(); + } finally { + blocked.release(); + } + const result = await pending; + expect(result?.status).toBe(403); + expect(await value(result)).toMatchObject({ error: 'forbidden' }); + await f.restoreAdmin(); + const retained = await f.runtime.api( + f.browser('/api/agent-access/grants/' + grant.grantId), + ); + expect(retained?.status).toBe(200); + expect(await value(retained)).toMatchObject({ + grantId: grant.grantId, + status: 'revoked', + }); + }); +}); + +function staffInput(collectionId: string) { + return { + operation: 'createCollection', + input: { + commandId: 'create-' + collectionId, + correlationId: 'synthetic-browser-command', + expectedGeneration: 0, + collectionId, + name: 'Private synthetic collection', + }, + }; +} + +function delayedCommand(base: Request, input: unknown) { + const reading = barrier(); + const resume = barrier(); + let pulled = false; + const body = new ReadableStream( + { + async pull(controller) { + pulled = true; + reading.release(); + await resume.ready; + controller.enqueue(new TextEncoder().encode(JSON.stringify(input))); + controller.close(); + }, + }, + { highWaterMark: 0 }, + ); + const options = { + method: 'POST', + headers: base.headers, + body, + duplex: 'half', + }; + return { + request: new Request(base.url, options), + get pulled() { + return pulled; + }, + waitFor: (operation: Promise) => + Promise.race([ + reading.ready, + operation.then(() => { + throw new Error('Expected the bounded body read.'); + }), + ]), + release: resume.release, + }; +} + +function controlledApprovalBody(base: Request, input: ApproveInput) { + const encoded = new TextEncoder().encode(JSON.stringify(input)); + const reading = barrier(); + const releasePull = barrier(); + let source: ReadableStreamDefaultController | undefined; + let closed = false; + let sent = 0; + const cancel = vi.fn(() => { + closed = true; + }); + const stream = new ReadableStream( + { + start(controller) { + source = controller; + }, + pull() { + reading.release(); + return releasePull.ready; + }, + cancel, + }, + { highWaterMark: 0 }, + ); + const options: RequestInit & { duplex: 'half' } = { + method: 'POST', + headers: base.headers, + body: stream, + duplex: 'half', + }; + return { + request: new Request(base.url, options), + reading: reading.ready, + cancel, + trickle() { + if (closed || source === undefined) + throw new Error('The actual consent body is no longer open.'); + const end = Math.min(encoded.length, sent + 8); + source.enqueue(encoded.slice(sent, end)); + sent = end; + }, + complete() { + if (!closed && source !== undefined) { + source.enqueue(encoded.slice(sent)); + sent = encoded.length; + source.close(); + closed = true; + } + releasePull.release(); + }, + }; +} + +describe.each(['device_code', 'authorization_code'] as const)( + 'authenticated %s consent body deadline', + (flow) => { + it.each(['stalled', 'trickled'] as const)( + 'rejects a %s body at the total deadline without persisting approval', + async (kind) => { + const f = await fixture(); + const approval = await f.pendingApproval(flow); + let commits = 0; + f.hooks.afterGrantCommit = async () => { + commits += 1; + }; + const body = controlledApprovalBody( + f.browser('/api/agent-access/approval', 'POST', approval.input), + approval.input, + ); + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }); + let settled = false; + const pending = f.runtime.api(body.request).finally(() => { + settled = true; + }); + try { + await body.reading; + expect(commits).toBe(0); + await vi.advanceTimersByTimeAsync(9_000); + if (kind === 'trickled') body.trickle(); + await vi.advanceTimersByTimeAsync(999); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + // The old unbounded route fails here; finally releases its actual + // body so ROOT's RED run cannot leave the consent operation parked. + expect(settled).toBe(true); + const result = await pending; + expect(result?.status).toBe(408); + expect(await value(result)).toEqual({ error: 'request_timeout' }); + expect(body.cancel).toHaveBeenCalledTimes(1); + expect(body.request.body?.locked).toBe(false); + expect(commits).toBe(0); + const retained = await f.runtime.api(f.browser(approval.viewPath)); + expect(retained?.status).toBe(200); + expect(await value(retained)).toMatchObject({ + requestId: approval.requestId, + flow, + status: 'pending', + }); + expect(commits).toBe(0); + expect(vi.getTimerCount()).toBe(0); + } finally { + body.complete(); + try { + await pending; + } finally { + vi.useRealTimers(); + } + } + }, + ); + + it('approves the real request and issues tokens when its body completes before expiry', async () => { + const f = await fixture(); + const approval = await f.pendingApproval(flow); + let commits = 0; + f.hooks.afterGrantCommit = async () => { + commits += 1; + }; + const body = controlledApprovalBody( + f.browser('/api/agent-access/approval', 'POST', approval.input), + approval.input, + ); + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }); + let settled = false; + const pending = f.runtime.api(body.request).finally(() => { + settled = true; + }); + try { + await body.reading; + await vi.advanceTimersByTimeAsync(9_999); + expect(settled).toBe(false); + expect(commits).toBe(0); + body.complete(); + const result = await pending; + expect(result?.status).toBe(200); + expect(commits).toBe(1); + const tokens = await approval.issue(await value(result)); + expect(tokens.token_type).toBe('Bearer'); + expect(tokens.refresh_token).toEqual(expect.any(String)); + expect( + await f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).toMatchObject({ + clientId: client.clientId, + access: { principalId: owner }, + }); + expect(body.cancel).not.toHaveBeenCalled(); + expect(body.request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + } finally { + body.complete(); + try { + await pending; + } finally { + vi.useRealTimers(); + } + } + }); + }, +); + +describe('actual AA approval authority after delayed browser input', () => { + it.each(['device_code', 'authorization_code'] as const)( + 'approves a pending %s request for the same current Admin after delayed input', + async (flow) => { + const f = await fixture(); + const approval = await f.pendingApproval(flow); + let commits = 0; + f.hooks.afterGrantCommit = async () => { + commits += 1; + }; + const delayed = delayedCommand( + f.browser('/api/agent-access/approval', 'POST', approval.input), + approval.input, + ); + const pending = f.runtime.api(delayed.request); + try { + await delayed.waitFor(pending); + expect(commits).toBe(0); + } finally { + delayed.release(); + } + const result = await pending; + expect(result?.status).toBe(200); + expect(commits).toBe(1); + const tokens = await approval.issue(await value(result)); + expect(tokens.token_type).toBe('Bearer'); + expect(tokens.access_token).toEqual(expect.any(String)); + expect(tokens.refresh_token).toEqual(expect.any(String)); + expect( + await f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).toMatchObject({ + clientId: client.clientId, + access: { principalId: owner }, + }); + }, + ); + + it.each([ + ['device_code', 'session'], + ['device_code', 'role'], + ['authorization_code', 'session'], + ['authorization_code', 'role'], + ] as const)( + 'leaves the actual %s request pending when %s is revoked while reading its body', + async (flow, revoked) => { + const f = await fixture(); + const approval = await f.pendingApproval(flow); + let commits = 0; + f.hooks.afterGrantCommit = async () => { + commits += 1; + }; + const delayed = delayedCommand( + f.browser('/api/agent-access/approval', 'POST', approval.input), + approval.input, + ); + const pending = f.runtime.api(delayed.request); + try { + await delayed.waitFor(pending); + expect(commits).toBe(0); + if (revoked === 'session') await f.revokeSession(); + else await f.revokeAdmin(); + } finally { + delayed.release(); + } + const result = await pending; + expect(result?.status).toBe(revoked === 'session' ? 401 : 403); + const denied = await value(result); + expect(denied).not.toHaveProperty('approved'); + expect(denied).not.toHaveProperty('redirectUri'); + expect(denied).not.toHaveProperty('access_token'); + expect(denied).not.toHaveProperty('refresh_token'); + // Observe real AA commits, not just the final withheld HTTP response. + expect(commits).toBe(0); + if (revoked === 'session') await f.restoreSession(); + else await f.restoreAdmin(); + const retained = await f.runtime.api(f.browser(approval.viewPath)); + expect(retained?.status).toBe(200); + expect(await value(retained)).toMatchObject({ + requestId: approval.requestId, + flow, + status: 'pending', + }); + expect(commits).toBe(0); + }, + ); + + it.each([ + ['device_code', 'same-owner'], + ['device_code', 'other-admin'], + ['authorization_code', 'same-owner'], + ['authorization_code', 'other-admin'], + ] as const)( + 'refuses delayed %s consent after a %s browser-session replacement', + async (flow, replacement) => { + const f = await fixture(); + const approval = await f.pendingApproval(flow); + let commits = 0; + f.hooks.afterGrantCommit = async () => { + commits += 1; + }; + const delayed = delayedCommand( + f.browser('/api/agent-access/approval', 'POST', approval.input), + approval.input, + ); + const pending = f.runtime.api(delayed.request); + try { + await delayed.waitFor(pending); + if (replacement === 'same-owner') await f.restoreSession(); + delayed.request.headers.set( + 'Cookie', + f.cookie(replacement === 'same-owner' ? owner : other), + ); + } finally { + delayed.release(); + } + expect((await pending)?.status).toBe(403); + expect(commits).toBe(0); + const retained = await f.runtime.api(f.browser(approval.viewPath)); + expect(retained?.status).toBe(200); + expect(await value(retained)).toMatchObject({ + requestId: approval.requestId, + status: 'pending', + }); + }, + ); + + it.each(['device_code', 'authorization_code'] as const)( + 'refuses a header swap during awaited post-body session authentication for %s', + async (flow) => { + const f = await fixture(); + const approval = await f.pendingApproval(flow); + let commits = 0; + f.hooks.afterGrantCommit = async () => { + commits += 1; + }; + const delayed = delayedCommand( + f.browser('/api/agent-access/approval', 'POST', approval.input), + approval.input, + ); + const pending = f.runtime.api(delayed.request); + let blocked: ReturnType | undefined; + try { + await delayed.waitFor(pending); + blocked = f.block('beforeSessionRead'); + delayed.release(); + await blocked.waitFor(pending); + delayed.request.headers.set('Cookie', f.cookie(other)); + } finally { + delayed.release(); + blocked?.release(); + } + expect((await pending)?.status).toBe(403); + expect(commits).toBe(0); + const retained = await f.runtime.api(f.browser(approval.viewPath)); + expect(retained?.status).toBe(200); + expect(await value(retained)).toMatchObject({ + requestId: approval.requestId, + status: 'pending', + }); + }, + ); +}); + +describe('staff KB command browser authority around bounded input and real SDK work', () => { + it('executes a current authorized browser command through the actual KB service', async () => { + const f = await fixture(); + const input = staffInput('browser-allowed'); + const result = await f.knowledge.handle( + f.browser('/api/staff/knowledge/command', 'POST', input), + ); + expect(result?.status).toBe(200); + expect(await value(result)).toMatchObject({ replayed: false }); + expect( + await f.knowledge.application.getCollection(await f.access(), { + collectionId: input.input.collectionId, + }), + ).toMatchObject({ collection: { name: input.input.name } }); + }); + + it.each(['session', 'role'] as const)( + 'refuses %s revocation during delayed input before any protected read or write', + async (kind) => { + const f = await fixture(); + const input = staffInput('browser-body-' + kind); + const delayed = delayedCommand( + f.browser('/api/staff/knowledge/command', 'POST', input), + input, + ); + let kbReads = 0; + f.hooks.afterKbRead = async () => { + kbReads += 1; + }; + const pending = f.knowledge.handle(delayed.request); + await delayed.waitFor(pending); + expect(kbReads).toBe(0); + try { + if (kind === 'session') await f.revokeSession(); + else await f.revokeAdmin(); + } finally { + delayed.release(); + } + const result = await pending; + expect(result?.status).toBe(kind === 'session' ? 401 : 403); + expect(kbReads).toBe(0); + await expect( + f.knowledge.application.getCollection(await f.access(), { + collectionId: input.input.collectionId, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + }, + ); + + it.each(['Cookie', 'Origin', 'X-Pegma-CSRF', 'Authorization'] as const)( + 'refuses original %s changes during input even when another current session is valid', + async (header) => { + const f = await fixture(); + const input = staffInput('browser-header-' + header); + const delayed = delayedCommand( + f.browser('/api/staff/knowledge/command', 'POST', input), + input, + ); + const pending = f.knowledge.handle(delayed.request); + await delayed.waitFor(pending); + try { + delayed.request.headers.set( + header, + header === 'Cookie' + ? f.cookie(other) + : header === 'Origin' + ? 'https://foreign.example.test' + : header === 'X-Pegma-CSRF' + ? 'd'.repeat(43) + : 'Bearer synthetic-forbidden', + ); + } finally { + delayed.release(); + } + expect((await pending)?.status).toBe(403); + await expect( + f.knowledge.application.getCollection(await f.access(), { + collectionId: input.input.collectionId, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + }, + ); + + it('refuses a current session swap while full post-body authentication awaits real session storage', async () => { + const f = await fixture(); + const input = staffInput('browser-auth-swap'); + const blocked = f.block('beforeSessionRead'); + const request = f.browser('/api/staff/knowledge/command', 'POST', input); + const pending = f.knowledge.handle(request); + await blocked.waitFor(pending); + try { + request.headers.set('Cookie', f.cookie(other)); + } finally { + blocked.release(); + } + expect((await pending)?.status).toBe(403); + await expect( + f.knowledge.application.getCollection(await f.access(), { + collectionId: input.input.collectionId, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + }); + + it.each(['missing_cookie', 'bearer', 'origin', 'csrf', 'oversize'] as const)( + 'rejects %s before consuming command bytes or reading KB facts', + async (kind) => { + const f = await fixture(); + const input = staffInput('browser-static-' + kind); + const delayed = delayedCommand( + f.browser('/api/staff/knowledge/command', 'POST', input), + input, + ); + if (kind === 'missing_cookie') delayed.request.headers.delete('Cookie'); + if (kind === 'bearer') + delayed.request.headers.set( + 'Authorization', + 'Bearer synthetic-forbidden', + ); + if (kind === 'origin') + delayed.request.headers.set('Origin', 'https://foreign.example.test'); + if (kind === 'csrf') delayed.request.headers.delete('X-Pegma-CSRF'); + if (kind === 'oversize') + delayed.request.headers.set('Content-Length', String(64 * 1024 + 1)); + let kbReads = 0; + f.hooks.afterKbRead = async () => { + kbReads += 1; + }; + try { + const result = await f.knowledge.handle(delayed.request); + expect(result?.status).toBe( + kind === 'missing_cookie' ? 401 : kind === 'oversize' ? 413 : 403, + ); + expect(delayed.pulled).toBe(false); + expect(kbReads).toBe(0); + } finally { + delayed.release(); + } + }, + ); + + it('bounds actual input bytes and exposes the explicit malformed-cookie JSON-error precedence', async () => { + const f = await fixture(); + const base = f.browser('/api/staff/knowledge/command', 'POST', {}); + base.headers.set('Cookie', 'malformed-but-bounded'); + const invalid = await f.knowledge.handle( + new Request(base.url, { + method: 'POST', + headers: base.headers, + body: '{', + }), + ); + expect(invalid?.status).toBe(400); + expect(await value(invalid)).toEqual({ error: 'invalid_json' }); + const oversized = await f.knowledge.handle( + new Request(base.url, { + method: 'POST', + headers: base.headers, + body: JSON.stringify({ + operation: 'createCollection', + input: 'x'.repeat(64 * 1024), + }), + }), + ); + expect(oversized?.status).toBe(413); + }); + + it.each(['session', 'role'] as const)( + 'withholds private collection content after %s revocation during actual KB reads', + async (kind) => { + const f = await fixture(); + const input = staffInput('browser-read-' + kind); + await f.knowledge.application.createCollection( + await f.access(), + input.input, + ); + const blocked = f.block('afterKbRead'); + const pending = f.knowledge.handle( + f.browser('/api/staff/knowledge/command', 'POST', { + operation: 'getCollection', + input: { collectionId: input.input.collectionId }, + }), + ); + await blocked.waitFor(pending); + try { + if (kind === 'session') await f.revokeSession(); + else await f.revokeAdmin(); + } finally { + blocked.release(); + } + const result = await pending; + expect(result?.status).toBe(kind === 'session' ? 401 : 403); + expect(JSON.stringify(await value(result))).not.toContain( + input.input.name, + ); + }, + ); + + it.each(['session', 'role'] as const)( + 'withholds a committed command ACK after %s revocation and preserves the actual collection', + async (kind) => { + const f = await fixture(); + const input = staffInput('browser-commit-' + kind); + const blocked = f.block('afterKbCommit'); + const pending = f.knowledge.handle( + f.browser('/api/staff/knowledge/command', 'POST', input), + ); + await blocked.waitFor(pending); + try { + if (kind === 'session') await f.revokeSession(); + else await f.revokeAdmin(); + } finally { + blocked.release(); + } + const result = await pending; + expect(result?.status).toBe(kind === 'session' ? 401 : 403); + expect(await value(result)).not.toHaveProperty('value'); + expect( + await f.knowledge.application.getCollection(await f.access(), { + collectionId: input.input.collectionId, + }), + ).toMatchObject({ collection: { name: input.input.name } }); + }, + ); + + it('withholds a committed command ACK when another valid browser session replaces the original', async () => { + const f = await fixture(); + const input = staffInput('browser-commit-cookie-swap'); + const request = f.browser('/api/staff/knowledge/command', 'POST', input); + const blocked = f.block('afterKbCommit'); + const pending = f.knowledge.handle(request); + await blocked.waitFor(pending); + try { + request.headers.set('Cookie', f.cookie(other)); + } finally { + blocked.release(); + } + const result = await pending; + expect(result?.status).toBe(403); + expect(await value(result)).not.toHaveProperty('value'); + expect( + await f.knowledge.application.getCollection(await f.access(), { + collectionId: input.input.collectionId, + }), + ).toMatchObject({ collection: { name: input.input.name } }); + }); +}); diff --git a/worker/src/api-auth.ts b/worker/src/api-auth.ts index 2c8dd4e..be4250e 100644 --- a/worker/src/api-auth.ts +++ b/worker/src/api-auth.ts @@ -168,7 +168,10 @@ export function boundedString( return value; } -export async function readJson(request: Request): Promise { +export async function readJson( + request: Request, + options?: { timeoutMs: number }, +): Promise { const contentType = request.headers.get('Content-Type')?.split(';', 1)[0]; if (contentType?.trim().toLowerCase() !== 'application/json') { throw new ApiError(415, 'json_required'); @@ -183,24 +186,77 @@ export async function readJson(request: Request): Promise { if (request.body === null) { throw new ApiError(400, 'invalid_json'); } + const timeoutMs = options?.timeoutMs; + if ( + timeoutMs !== undefined && + (!Number.isSafeInteger(timeoutMs) || + timeoutMs <= 0 || + timeoutMs > 2_147_483_647) + ) { + throw new RangeError('Invalid JSON body timeout'); + } const reader = request.body.getReader(); const chunks: Uint8Array[] = []; let length = 0; + let timer: ReturnType | undefined; + let cancellationRequested = false; + let timedOut = false; + const timeoutError = new ApiError(408, 'request_timeout'); + function cancelWithoutWaiting(reason: unknown): void { + if (cancellationRequested) return; + cancellationRequested = true; + // A source's cancellation promise can hang or reject. Neither may hold + // the timed request open or replace the original failure. + try { + void reader.cancel(reason).catch(() => {}); + } catch { + // Cancellation is best effort; the reader lock is released below. + } + } + const expiresAt = + timeoutMs === undefined ? undefined : performance.now() + timeoutMs; + const deadline = + timeoutMs === undefined + ? undefined + : new Promise((_resolve, reject) => { + timer = setTimeout(() => { + timedOut = true; + // Reject before cancellation settles any pending read. + reject(timeoutError); + cancelWithoutWaiting(timeoutError); + }, timeoutMs); + }); try { while (true) { - const chunk = await reader.read(); + if (expiresAt !== undefined && performance.now() >= expiresAt) { + throw timeoutError; + } + const chunk = + deadline === undefined + ? await reader.read() + : await Promise.race([reader.read(), deadline]); + if ( + timedOut || + (expiresAt !== undefined && performance.now() >= expiresAt) + ) { + throw timeoutError; + } if (chunk.done) { break; } length += chunk.value.byteLength; if (length > JSON_LIMIT) { - await reader.cancel(); + if (deadline === undefined) await reader.cancel(); throw new ApiError(413, 'request_too_large'); } chunks.push(chunk.value); } + } catch (error) { + if (deadline !== undefined) cancelWithoutWaiting(error); + throw error; } finally { + if (timer !== undefined) clearTimeout(timer); reader.releaseLock(); } diff --git a/worker/src/identity-runtime.ts b/worker/src/identity-runtime.ts index b88c151..68baf6a 100644 --- a/worker/src/identity-runtime.ts +++ b/worker/src/identity-runtime.ts @@ -115,10 +115,12 @@ function deferredEmailCodeProtector(secret: Uint8Array): EmailCodeProtector { export function createProductionIdentityRuntime( env: IdentityRuntimeEnv, logger: Logger, + readBatchSize?: number, ): IdentityRuntime { const store = createCloudflareD1Store({ database: env.IDENTITY_DB, createSchemaIfMissing: false, + ...(readBatchSize === undefined ? {} : { readBatchSize }), }); return createIdentityRuntime( { diff --git a/worker/src/index.ts b/worker/src/index.ts index cc59964..a3ec163 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -40,14 +40,22 @@ import { type SupportRuntimeEnv, } from './support-desk'; import { runSupportMaintenance } from './support-maintenance'; +import { runKnowledgeMaintenance } from './knowledge-maintenance'; +import { createKnowledgeRetrievalMaintenance } from './knowledge-retrieval-maintenance'; +import { createKnowledgeRetrievalReady } from './knowledge-retrieval-ready'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { systemClock } from '@pegma/spine'; import { MAIL_CRON, MAIL_RECONCILE_CRON, CLEANUP_CRON, + RATE_LIMIT_CRON, cleanupLaneAt, + rateKnowledgeLaneAt, } from './maintenance-schedule'; import { createPegmaMcpHandler } from './mcp-server'; import type { CatalogFetchEnv } from './mcp-catalog-fetch'; +import { handleKnowledgeRequest, isKnowledgeRequest } from './knowledge-host'; type AppEnv = Env & LoggerEnv & @@ -56,6 +64,23 @@ type AppEnv = Env & SupportRuntimeEnv & CatalogFetchEnv; +function knowledgeRetrievalEnabled(environment: { + readonly PEGMA_KNOWLEDGE_ENABLED?: string; +}): boolean { + return environment.PEGMA_KNOWLEDGE_ENABLED === 'true'; +} + +// No Identity, sessions, mail, or AgentAccess initialization in projection ticks. +function createKnowledgeProjectionStore(environment: { + readonly IDENTITY_DB: D1Database; +}) { + return createCloudflareD1Store({ + database: environment.IDENTITY_DB, + createSchemaIfMissing: false, + readBatchSize: 512, + }); +} + function createSupportHandler( env: AppEnv, logger: ReturnType, @@ -139,6 +164,10 @@ export default { } } + if (isKnowledgeRequest(path)) { + return handleKnowledgeRequest(request, env, logger); + } + if ( request.method === 'GET' && (path === '/' || path === '/health' || path === '/api/health') @@ -380,6 +409,36 @@ export default { const logger = createAppLogger(env, (promise) => ctx.waitUntil(promise)); // Each cron has its own invocation CPU budget. Never combine all cleanup // with the time-sensitive mail path on Workers Free. + if (controller.cron === RATE_LIMIT_CRON) { + ctx.waitUntil( + (async () => { + try { + if ( + rateKnowledgeLaneAt(controller.scheduledTime) === 'rate_limits' + ) { + await runKnowledgeMaintenance( + { store: createProductionStore(env), clock: systemClock }, + logger, + { tasks: ['rate_limits'] }, + ); + } else if (knowledgeRetrievalEnabled(env)) { + await createKnowledgeRetrievalReady({ + store: createKnowledgeProjectionStore(env), + clock: systemClock, + logger, + isEnabled: () => knowledgeRetrievalEnabled(env), + }).runPage(); + } + } catch (error) { + logger.log('error', 'knowledge.maintenance_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + })(), + ); + return; + } + if (controller.cron === RELEASE_RECONCILIATION_CRON) { ctx.waitUntil( (async () => { @@ -448,6 +507,27 @@ export default { })(), ); + // Retrieval keeps its existing knowledge lane and activation gate, + // independently of the isolated global limiter cron. + if (cleanup?.kind === 'knowledge' && knowledgeRetrievalEnabled(env)) + ctx.waitUntil( + (async () => { + try { + if (!knowledgeRetrievalEnabled(env)) return; + await createKnowledgeRetrievalMaintenance({ + store: createKnowledgeProjectionStore(env), + clock: systemClock, + logger, + isEnabled: () => knowledgeRetrievalEnabled(env), + }).runPage(); + } catch { + logger.log('error', 'knowledge.retrieval_maintenance.failed', { + stage: 'composition', + }); + } + })(), + ); + if (cleanup?.kind === 'support') ctx.waitUntil( (async () => { diff --git a/worker/src/knowledge-admission.test.ts b/worker/src/knowledge-admission.test.ts new file mode 100644 index 0000000..305ce49 --- /dev/null +++ b/worker/src/knowledge-admission.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest'; +import { + knowledgeAdmissionCount, + knowledgeAdmissionPolicyName, +} from './knowledge-admission'; + +describe('trusted knowledge admission configuration', () => { + it('bounds explicit budgets while retaining the chosen default for absent configuration', () => { + expect(knowledgeAdmissionCount(undefined, 120)).toBe(120); + expect(knowledgeAdmissionCount('1', 120)).toBe(1); + expect(knowledgeAdmissionCount(' 10000 ', 120)).toBe(10_000); + for (const value of [ + '', + '0', + '-1', + '1.5', + '1e3', + '01', + '10001', + 'Infinity', + '9'.repeat(17), + ]) { + expect(() => knowledgeAdmissionCount(value, 120)).toThrow(TypeError); + } + }); + + it('uses a distinct immutable policy for a changed budget and reuses the original on rollback', () => { + const initial = knowledgeAdmissionPolicyName('pegma.agent.resource', 300); + expect(knowledgeAdmissionPolicyName('pegma.agent.resource', 600)).not.toBe( + initial, + ); + expect(knowledgeAdmissionPolicyName('pegma.agent.resource', 300)).toBe( + initial, + ); + for (const invalid of [0, -1, 1.5, 10_001, NaN, Infinity]) { + expect(() => + knowledgeAdmissionPolicyName('pegma.agent.resource', invalid), + ).toThrow(TypeError); + } + }); +}); diff --git a/worker/src/knowledge-admission.ts b/worker/src/knowledge-admission.ts new file mode 100644 index 0000000..b6ecc4f --- /dev/null +++ b/worker/src/knowledge-admission.ts @@ -0,0 +1,26 @@ +/** Trusted host configuration; these are shared IP budgets, not user quotas. */ +export function knowledgeAdmissionCount( + value: string | undefined, + fallback: number, +): number { + if (value === undefined) return fallback; + if (value.length > 16 || !/^[1-9][0-9]{0,4}$/u.test(value.trim())) { + throw new TypeError('Invalid knowledge admission configuration.'); + } + const limit = Number(value.trim()); + if (!Number.isSafeInteger(limit) || limit > 10_000) { + throw new TypeError('Invalid knowledge admission configuration.'); + } + return limit; +} + +/** A changed immutable policy budget gets its own bounded, deterministic name. */ +export function knowledgeAdmissionPolicyName( + name: string, + limit: number, +): string { + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 10_000) { + throw new TypeError('Invalid knowledge admission configuration.'); + } + return `${name}.v1.limit-${limit}`; +} diff --git a/worker/src/knowledge-agent-freshness.test.ts b/worker/src/knowledge-agent-freshness.test.ts new file mode 100644 index 0000000..7fec922 --- /dev/null +++ b/worker/src/knowledge-agent-freshness.test.ts @@ -0,0 +1,1336 @@ +import type { PublicClient } from '@pegma/agent-access'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { KnowledgeBaseNotFoundError } from '@pegma/knowledge-base-application'; +import { articleKinds } from '@pegma/knowledge-base-contracts'; +import type { + ArticleDraft, + EvidenceSubmission, +} from '@pegma/knowledge-base-core'; +import { + knowledgeAgentToolNames, + knowledgeAgentScopes, + type KnowledgeAgentOperation, +} from '@pegma/knowledge-base-mcp'; +import { createSessionStore } from '@pegma/sessions'; +import type { Logger } from '@pegma/spine'; +import { + createMemoryStore, + type CollectionDefinition, + type CollectionStore, + type Store, +} from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { + AGENT_API_URL, + AGENT_RESOURCE, + createAgentAccessRuntime, +} from './agent-access-runtime'; +import { isPlainObject } from './api-auth'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { createKnowledgeRuntime } from './knowledge-runtime'; +import { + ADMIN_ROLE, + AGENT_KNOWLEDGE_PERMISSIONS, + APPLICATION_SCOPE, + AUTHORIZATION_APPLICATION_ID, +} from './support-access'; + +type Transport = 'http' | 'mcp'; +type Revocation = 'grant' | 'role'; +const ownerId = 'freshness-owner'; +const inspectorId = 'freshness-inspector'; +const collectionId = 'freshness-guides'; +const client: PublicClient = { + clientId: 'synthetic-freshness-client', + name: 'Synthetic freshness client', + redirectUris: ['https://client.example.test/callback'], + allowedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS], + grantTypes: ['device_code'], +}; +const draft: ArticleDraft = { + kind: 'explanation', + title: 'Current-authority guide', + summary: 'A complete example guide.', + content: { + format: 'plain_text', + text: 'Private guide content for the synthetic example.', + }, + tags: [], + applicability: { + productId: 'example', + productVersion: '1', + buildId: 'staging-1', + }, +}; + +function barrier() { + let release = () => {}; + const ready = new Promise((resolve) => { + release = resolve; + }); + return { ready, release }; +} + +interface StoreHooks { + afterKbRead: ((rowId?: string) => Promise) | undefined; + afterKbCommit: ((rowId?: string) => Promise) | undefined; + afterReportRead: ((rowId?: string) => Promise) | undefined; + afterReportCommit: ((rowId?: string) => Promise) | undefined; +} + +/** Pause actual adapter operations, without replacing authentication or persistence. */ +function observedStore(backing: Store, hooks: StoreHooks): Store { + return { + collection(definition: CollectionDefinition): CollectionStore { + const target = backing.collection(definition); + const reportRecords = + definition.name === 'pegma-dev.knowledge-evidence.v1'; + if (definition.name !== 'knowledge-base.records.v1' && !reportRecords) + return target; + return { + ...target, + async get(key) { + const value = await target.get(key); + await (reportRecords ? hooks.afterReportRead : hooks.afterKbRead)?.( + key.id, + ); + return value; + }, + async getVersioned(key) { + const value = await target.getVersioned(key); + await (reportRecords ? hooks.afterReportRead : hooks.afterKbRead)?.( + key.id, + ); + return value; + }, + async transact(partition, actions) { + const result = await target.transact(partition, actions); + if (result.committed) + await ( + reportRecords ? hooks.afterReportCommit : hooks.afterKbCommit + )?.(); + return result; + }, + }; + }, + }; +} + +function wire( + transport: Transport, + operation: KnowledgeAgentOperation, + input: unknown, +) { + return transport === 'http' + ? { apiVersion: '1', operation, input } + : { + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: knowledgeAgentToolNames[operation], arguments: input }, + }; +} + +function agentRequest( + transport: Transport, + token: string, + body: string | ReadableStream, +) { + const options = { + method: 'POST', + duplex: 'half', + body, + headers: { + Authorization: 'Bearer ' + token, + 'Content-Type': 'application/json', + ...(transport === 'mcp' + ? { + Accept: 'application/json, text/event-stream', + 'MCP-Protocol-Version': '2025-06-18', + } + : {}), + }, + }; + return new Request( + transport === 'http' ? AGENT_API_URL : AGENT_RESOURCE, + options, + ); +} + +function delayedBody(value: unknown) { + const reading = barrier(); + const finish = barrier(); + const stream = new ReadableStream( + { + async pull(controller) { + reading.release(); + await finish.ready; + controller.enqueue(new TextEncoder().encode(JSON.stringify(value))); + controller.close(); + }, + }, + { highWaterMark: 0 }, + ); + return { stream, reading: reading.ready, finish: finish.release }; +} + +async function logicalResponse( + response: Response | null, + transport: Transport, +): Promise> { + if (response === null) + throw new Error('Expected a matching real agent route.'); + const value: unknown = await response.json(); + if (!isPlainObject(value)) + throw new Error('Expected an object agent response.'); + if (transport === 'http') return value; + const result = value.result; + if (!isPlainObject(result) || !Array.isArray(result.content)) + throw new Error('Expected an actual MCP tool result.'); + const content: unknown = result.content[0]; + if (!isPlainObject(content) || typeof content.text !== 'string') + throw new Error('Expected an MCP JSON text result.'); + const logical: unknown = JSON.parse(content.text); + if (!isPlainObject(logical)) throw new Error('Expected an object KB result.'); + return logical; +} + +async function fixture() { + const backing = createMemoryStore(); + const hooks: StoreHooks = { + afterKbRead: undefined, + afterKbCommit: undefined, + afterReportRead: undefined, + afterReportCommit: undefined, + }; + const store = observedStore(backing, hooks); + const logger: Logger = { log() {} }; + let instant = Date.now(); + const clock = { now: () => new Date(instant).toISOString() }; + const identity = createIdentityRuntime( + { + store, + emailCodeSecretBase64: btoa('s'.repeat(32)), + emailFrom: 'Pegma ', + emailEnabled: false, + }, + logger, + ).identity; + // Public trusted provisioning creates real verified Identity records; there + // is no fake claimsFor/getUser or authentication implementation in this suite. + for (const id of [ownerId, inspectorId]) { + await identity.provisionVerifiedUser({ + principalId: id, + email: id + '@example.test', + }); + } + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + for (const id of [ownerId, inspectorId]) { + await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: 'admin-' + id, + principalId: id, + role: ADMIN_ROLE, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-freshness-setup' }, + grantedAtEpochMs: instant, + status: 'active', + }, + auditEventId: 'grant-' + id, + }); + } + const sessions = createSessionStore(store, { logger, clock }); + const sessionId = 's'.repeat(43); + const csrfToken = 'c'.repeat(43); + await sessions.create(sessionId, { + principalId: ownerId, + data: JSON.stringify({ + version: 1, + csrfToken, + issuer: IDENTITY_ISSUER, + subject: ownerId, + }), + }); + const options = { + store, + clock, + logger, + identity, + sessions, + roleStore, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }; + const candidateAgents = createAgentAccessRuntime({ + ...options, + clients: [client], + }); + if (candidateAgents === null) + throw new Error('Expected the explicit synthetic client.'); + const agents = candidateAgents; + const knowledge = createKnowledgeRuntime({ ...options, agentAccess: agents }); + const resolve = createAgentPrincipalResolver(options); + async function access(id = inspectorId) { + const current = await resolve(id); + if (current === null) + throw new Error('Expected a current actual Identity principal.'); + return current; + } + function browser(path: string, method = 'GET', body?: unknown) { + return new Request(IDENTITY_ISSUER + path, { + method, + headers: { + Cookie: SESSION_COOKIE + '=' + sessionId, + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + 'X-Pegma-CSRF': csrfToken, + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + } + async function device( + scopes: readonly string[] = AGENT_KNOWLEDGE_PERMISSIONS, + ) { + const pending = await agents.service.beginDeviceAuthorization({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + scopes: [...scopes], + }); + const viewed = await agents.api( + browser( + '/api/agent-access/approval?user_code=' + + encodeURIComponent(pending.user_code), + ), + ); + if (viewed === null) + throw new Error('Expected the real browser approval API.'); + expect(viewed.status).toBe(200); + const approval: unknown = await viewed.json(); + if (!isPlainObject(approval) || typeof approval.requestId !== 'string') + throw new Error('Expected a credential-free real approval view.'); + const approved = await agents.api( + browser('/api/agent-access/approval', 'POST', { + requestId: approval.requestId, + userCode: pending.user_code, + decision: 'approve', + approvedScopes: [...scopes], + }), + ); + expect(approved?.status).toBe(200); + instant += pending.interval * 1_000 + 1; + const tokens = await agents.service.pollDeviceToken({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + deviceCode: pending.device_code, + }); + const delegated = await agents.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }); + expect(delegated.access.roles).toEqual([]); + expect(delegated.access.entitlements).toEqual([]); + expect(delegated.access.permissions.slice().sort()).toEqual( + [...scopes].sort(), + ); + return { + token: tokens.access_token, + grantId: delegated.grantId, + access: delegated.access, + }; + } + const admin = await access(); + const collection = await knowledge.application.createCollection(admin, { + commandId: 'collection', + correlationId: 'freshness', + expectedGeneration: 0, + collectionId, + name: 'Freshness guides', + }); + await knowledge.application.putValidationPolicy(admin, { + commandId: 'policy', + correlationId: 'freshness', + expectedGeneration: 0, + policy: { + id: 'freshness-policy', + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: kind + '-content', + kind, + testKind: 'content', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: [ownerId], + })), + { + id: 'walkthrough-workflow', + kind: 'walkthrough', + testKind: 'workflow', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: [ownerId], + }, + ], + }, + }); + await knowledge.application.putGovernanceConfiguration(admin, { + commandId: 'governance', + correlationId: 'freshness', + expectedGeneration: collection.value.generation, + collectionId, + configuration: { + validationPolicy: { id: 'freshness-policy', version: 1 }, + expectedStagingBuildId: 'staging-1', + trustedAttesterIds: [ownerId], + }, + }); + const credential = await device(); + function createInput(articleId: string) { + return { + commandId: 'create-' + articleId, + correlationId: 'freshness', + expectedGeneration: 0, + articleId, + collectionId, + draft, + }; + } + async function reportInput(articleId: string) { + await knowledge.application.createDraft( + await access(), + createInput(articleId), + ); + const target = await knowledge.application.getDraft(await access(), { + articleId, + }); + const ledger = await knowledge.evidence.ledger(credential.access, { + articleId, + }); + const evidence: EvidenceSubmission = { + id: 'run-' + articleId, + articleId, + articleRevision: target.revision.number, + contentHash: target.revision.contentHash, + validationPolicy: target.revision.validationPolicy, + checkId: 'explanation-content', + testKind: 'content', + applicability: target.revision.applicability, + stagingBuildId: 'staging-1', + steps: ['Read the complete synthetic guide.'], + result: 'passed', + executedAt: clock.now(), + runnerId: ownerId, + artifacts: [{ id: 'synthetic-report', hash: 'a'.repeat(64) }], + }; + return { + commandId: 'report-' + articleId, + correlationId: 'freshness', + expectedGeneration: target.generation, + articleId, + ledgerEpoch: ledger.ledgerEpoch, + evidence, + report: { + summary: 'Synthetic check passed.', + details: 'Private synthetic execution details.', + }, + }; + } + async function queueReport(articleId: string) { + const input = await reportInput(articleId); + const acknowledgement = await knowledge.evidence.report(credential.access, { + commandId: input.commandId, + articleId, + ledgerEpoch: input.ledgerEpoch, + evidence: input.evidence, + report: input.report, + }); + return { input, acknowledgement }; + } + async function revoke(kind: Revocation, grantId = credential.grantId) { + if (kind === 'grant') { + const response = await agents.api( + browser('/api/agent-access/grants/' + grantId, 'DELETE'), + ); + expect(response?.status).toBe(204); + } else { + const assignment = await roleStore.getRoleAssignment('admin-' + ownerId); + if (assignment === null) + throw new Error('Expected the real Admin assignment.'); + expect( + ( + await roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: 'admin-' + ownerId, + expectedConcurrencyToken: assignment.concurrencyToken, + revokedBy: { kind: 'principal', principalId: inspectorId }, + revokedAtEpochMs: instant, + auditEventId: 'revoke-owner', + }) + ).status, + ).toBe('revoked'); + } + } + function block( + hook: keyof StoreHooks, + rowIdContains?: string, + failAfterRead = false, + ) { + const entered = barrier(); + const finish = barrier(); + hooks[hook] = async (rowId) => { + if (rowIdContains !== undefined && !rowId?.includes(rowIdContains)) + return; + hooks[hook] = undefined; + entered.release(); + await finish.ready; + if (failAfterRead) + throw new Error('Synthetic private final-read failure canary.'); + }; + return { entered: entered.ready, finish: finish.release }; + } + return { + knowledge, + agents, + access, + credential, + device, + createInput, + reportInput, + queueReport, + revoke, + block, + identity, + roleStore, + resolve, + hooks, + }; +} + +/** A real request body whose bytes remain controlled after bearer auth. */ +function controlledReportBody(token: string, input: unknown) { + const reading = barrier(); + const releasePull = barrier(); + let source: ReadableStreamDefaultController | undefined; + let closed = false; + const encoded = new TextEncoder().encode(JSON.stringify(input)); + let sent = 0; + const cancel = vi.fn(() => { + closed = true; + }); + const stream = new ReadableStream( + { + start(controller) { + source = controller; + }, + pull() { + reading.release(); + return releasePull.ready; + }, + cancel, + }, + { highWaterMark: 0 }, + ); + function complete() { + if (!closed && source !== undefined) { + source.enqueue(encoded.slice(sent)); + sent = encoded.length; + source.close(); + closed = true; + } + releasePull.release(); + } + const options: RequestInit & { duplex: 'half' } = { + method: 'POST', + headers: { + Authorization: 'Bearer ' + token, + 'Content-Type': 'application/json', + }, + body: stream, + duplex: 'half', + }; + return { + request: new Request(IDENTITY_ISSUER + '/api/knowledge/reports', options), + reading: reading.ready, + cancel, + trickle() { + if (closed || source === undefined) + throw new Error('The actual request stream is no longer open.'); + const next = Math.min(encoded.length, sent + 8); + source.enqueue(encoded.slice(sent, next)); + sent = next; + }, + complete, + }; +} + +describe('authenticated local-agent report body deadline', () => { + async function submission(articleId: string) { + const f = await fixture(); + const input = await f.reportInput(articleId); + let commits = 0; + f.hooks.afterReportCommit = async () => { + commits += 1; + }; + const body = controlledReportBody(f.credential.token, { + commandId: input.commandId, + articleId: input.articleId, + ledgerEpoch: input.ledgerEpoch, + evidence: input.evidence, + report: input.report, + }); + return { f, input, body, commits: () => commits }; + } + + it.each(['stalled', 'trickled'] as const)( + 'rejects an actual %s bearer report body at the total deadline without a report commit', + async (kind) => { + const { f, input, body, commits } = await submission('deadline-' + kind); + // Keep the actual Identity/AA/KB setup and its clocks real. Only the + // established readJson timer/performance boundary is advanced here. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }); + let settled = false; + const pending = f.knowledge.handle(body.request).finally(() => { + settled = true; + }); + try { + await body.reading; + expect(commits()).toBe(0); + await vi.advanceTimersByTimeAsync(9_000); + if (kind === 'trickled') body.trickle(); + await vi.advanceTimersByTimeAsync(999); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + // This assertion fails promptly on the old unbounded route, while + // finally completes its real body so a RED run never parks forever. + expect(settled).toBe(true); + const result = await pending; + expect(result?.status).toBe(408); + expect(await result?.json()).toEqual({ error: 'request_timeout' }); + expect(body.cancel).toHaveBeenCalledTimes(1); + expect(body.request.body?.locked).toBe(false); + expect(commits()).toBe(0); + expect( + await f.knowledge.evidence.list(await f.access(), { + articleId: input.articleId, + }), + ).toMatchObject({ reports: [] }); + expect( + await f.agents.service.authenticate({ + token: f.credential.token, + resource: AGENT_RESOURCE, + }), + ).toMatchObject({ grantId: f.credential.grantId }); + expect(vi.getTimerCount()).toBe(0); + } finally { + body.complete(); + try { + await pending; + } finally { + vi.useRealTimers(); + } + } + }, + ); + + it('queues an actual report when its complete bearer body arrives before the deadline', async () => { + const { f, input, body, commits } = await submission('deadline-positive'); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); + let settled = false; + const pending = f.knowledge.handle(body.request).finally(() => { + settled = true; + }); + try { + await body.reading; + await vi.advanceTimersByTimeAsync(9_999); + expect(settled).toBe(false); + expect(commits()).toBe(0); + body.complete(); + const result = await pending; + expect(result?.status).toBe(200); + expect(await result?.json()).toMatchObject({ + reportId: expect.any(String), + }); + expect(commits()).toBe(1); + const retained = await f.knowledge.evidence.list(await f.access(), { + articleId: input.articleId, + }); + expect(retained.reports).toHaveLength(1); + expect(retained.reports[0]).toMatchObject({ + status: 'pending', + submittedBy: ownerId, + }); + expect( + ( + await f.knowledge.application.getEvidence(await f.access(), { + articleId: input.articleId, + }) + ).evidence, + ).toEqual([]); + expect(body.cancel).not.toHaveBeenCalled(); + expect(body.request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + } finally { + body.complete(); + try { + await pending; + } finally { + vi.useRealTimers(); + } + } + }); +}); + +it('resolves stored roles before the actual active verified Identity claims without a duplicate user read', async () => { + const f = await fixture(); + const observations: string[] = []; + const resolve = createAgentPrincipalResolver({ + identity: { + ...f.identity, + async claimsFor(id) { + observations.push('claims'); + return f.identity.claimsFor(id); + }, + async getUser(id) { + observations.push('user'); + return f.identity.getUser(id); + }, + }, + roleStore: { + async listActiveRoleAssignments(id, scope) { + const result = await f.roleStore.listActiveRoleAssignments(id, scope); + observations.push('roles'); + return result; + }, + }, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }); + expect(await resolve(ownerId)).toEqual(await f.resolve(ownerId)); + expect(observations).toEqual(['roles', 'claims']); +}); + +it('refuses a real stored Admin assignment whose principal has no actual Identity account', async () => { + const f = await fixture(); + const principalId = 'orphaned-role-principal'; + const granted = await f.roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: 'orphaned-role-assignment', + principalId, + role: ADMIN_ROLE, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-orphan-test' }, + grantedAtEpochMs: Date.now(), + status: 'active', + }, + auditEventId: 'orphaned-role-audit', + }); + expect(granted.status).toBe('granted'); + expect(await f.resolve(principalId)).toBeNull(); +}); + +describe.each(['http', 'mcp'] as const)( + 'current agent authority over actual %s transport', + (transport) => { + it('accepts an actual current scoped credential through the released SDK', async () => { + const f = await fixture(); + const request = agentRequest( + transport, + f.credential.token, + JSON.stringify( + wire(transport, 'createDraft', f.createInput('allowed')), + ), + ); + const result = await logicalResponse( + await f.knowledge.handle(request), + transport, + ); + expect(result).toMatchObject({ + apiVersion: '1', + operation: 'createDraft', + result: { replayed: false }, + }); + }); + + it.each(['grant', 'role'] as const)( + 'rejects %s revocation while the actual SDK awaits request bytes before a write', + async (kind) => { + const f = await fixture(); + const body = delayedBody( + wire(transport, 'createDraft', f.createInput('body-race')), + ); + const pending = f.knowledge.handle( + agentRequest(transport, f.credential.token, body.stream), + ); + await body.reading; + try { + await f.revoke(kind); + } finally { + body.finish(); + } + expect(await logicalResponse(await pending, transport)).toMatchObject({ + error: { code: 'forbidden' }, + }); + await expect( + f.knowledge.application.getDraft(await f.access(), { + articleId: 'body-race', + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); + }, + ); + + it.each([ + { scope: knowledgeAgentScopes.draftWrite, allowed: true }, + { scope: knowledgeAgentScopes.evidenceSubmit, allowed: true }, + { scope: knowledgeAgentScopes.draftRead, allowed: false }, + ])( + 'retains the requirements permission alternative for $scope', + async ({ scope, allowed }) => { + const f = await fixture(); + const credential = await f.device([scope]); + const result = await logicalResponse( + await f.knowledge.handle( + agentRequest( + transport, + credential.token, + JSON.stringify( + wire(transport, 'getValidationRequirements', { + collectionId, + kind: draft.kind, + }), + ), + ), + ), + transport, + ); + if (allowed) + expect(result).toMatchObject({ + operation: 'getValidationRequirements', + result: { collectionId }, + }); + else expect(result).toMatchObject({ error: { code: 'forbidden' } }); + }, + ); + + it('requires both report grants while allowing report reads without draft-write authority', async () => { + const f = await fixture(); + const input = await f.reportInput('report-read-permissions'); + for (const scopes of [ + [knowledgeAgentScopes.draftRead], + [knowledgeAgentScopes.evidenceSubmit], + [knowledgeAgentScopes.draftRead, knowledgeAgentScopes.evidenceSubmit], + ]) { + const credential = await f.device(scopes); + const result = await logicalResponse( + await f.knowledge.handle( + agentRequest( + transport, + credential.token, + JSON.stringify( + wire(transport, 'getValidationRequirements', { + articleId: input.articleId, + collectionId, + kind: draft.kind, + }), + ), + ), + ), + transport, + ); + if (scopes.length === 2) + expect(result).toMatchObject({ + result: { reportLedger: { status: 'active' } }, + }); + else expect(result).toMatchObject({ error: { code: 'forbidden' } }); + } + }); + + it('keeps independent request read groups separate when one live grant is revoked', async () => { + const f = await fixture(); + await f.knowledge.application.createDraft( + await f.access(), + f.createInput('isolated-read'), + ); + const other = await f.device(); + const blocked = f.block('afterKbRead'); + const input = JSON.stringify( + wire(transport, 'getDraft', { articleId: 'isolated-read' }), + ); + const pending = f.knowledge.handle( + agentRequest(transport, f.credential.token, input), + ); + await Promise.race([ + blocked.entered, + pending.then(() => { + throw new Error('Expected the actual read barrier.'); + }), + ]); + try { + const independent = await logicalResponse( + await f.knowledge.handle(agentRequest(transport, other.token, input)), + transport, + ); + expect(independent).toMatchObject({ + result: { articleId: 'isolated-read' }, + }); + await f.revoke('grant'); + } finally { + blocked.finish(); + } + const denied = await logicalResponse(await pending, transport); + expect(denied).toMatchObject({ error: { code: 'forbidden' } }); + expect(JSON.stringify(denied)).not.toContain(draft.content.text); + expect( + await logicalResponse( + await f.knowledge.handle(agentRequest(transport, other.token, input)), + transport, + ), + ).toMatchObject({ result: { articleId: 'isolated-read' } }); + }); + + it('refuses another valid same-owner grant substituted during an actual private read', async () => { + const f = await fixture(); + await f.knowledge.application.createDraft( + await f.access(), + f.createInput('read-header-swap'), + ); + const other = await f.device(); + const blocked = f.block('afterKbRead'); + const request = agentRequest( + transport, + f.credential.token, + JSON.stringify( + wire(transport, 'getDraft', { articleId: 'read-header-swap' }), + ), + ); + const pending = f.knowledge.handle(request); + await Promise.race([ + blocked.entered, + pending.then(() => { + throw new Error('Expected the actual read barrier.'); + }), + ]); + try { + request.headers.set('Authorization', 'Bearer ' + other.token); + } finally { + blocked.finish(); + } + const result = await logicalResponse(await pending, transport); + expect(result).toMatchObject({ error: { code: 'forbidden' } }); + expect(JSON.stringify(result)).not.toContain(draft.content.text); + }); + + it.each(['grant', 'role'] as const)( + 'withholds private draft content after %s revocation during a real KB read', + async (kind) => { + const f = await fixture(); + await f.knowledge.application.createDraft( + await f.access(), + f.createInput('read-race'), + ); + const blocked = f.block('afterKbRead'); + const pending = f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify( + wire(transport, 'getDraft', { articleId: 'read-race' }), + ), + ), + ); + await blocked.entered; + try { + await f.revoke(kind); + } finally { + blocked.finish(); + } + const result = await logicalResponse(await pending, transport); + expect(result).toMatchObject({ error: { code: 'forbidden' } }); + expect(JSON.stringify(result)).not.toContain(draft.content.text); + }, + ); + + it('queues a report through the actual configured protocol without accepting KB evidence', async () => { + const f = await fixture(); + const input = await f.reportInput('report-allowed'); + const result = await logicalResponse( + await f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify(wire(transport, 'submitEvidence', input)), + ), + ), + transport, + ); + expect(result).toMatchObject({ + operation: 'submitEvidence', + result: { kind: 'pending-human-review' }, + }); + expect(JSON.stringify(result)).not.toContain(input.report.details); + const retained = await f.knowledge.evidence.list(await f.access(), { + articleId: input.articleId, + }); + expect(retained.reports).toHaveLength(1); + const queued = retained.reports[0]; + if (queued === undefined) + throw new Error('Expected the actual queued report.'); + expect(queued).toMatchObject({ status: 'pending', submittedBy: ownerId }); + const status = await logicalResponse( + await f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify( + wire(transport, 'getValidationRequirements', { + collectionId, + kind: draft.kind, + articleId: input.articleId, + reportLookup: { + ledgerEpoch: queued.ledgerEpoch, + reportId: queued.reportId, + }, + }), + ), + ), + ), + transport, + ); + expect(status).toMatchObject({ + result: { + reportLedger: { ledgerEpoch: queued.ledgerEpoch, status: 'active' }, + reportStatus: { reportId: queued.reportId, status: 'pending' }, + }, + }); + expect(JSON.stringify(status)).not.toContain(input.report.details); + expect(JSON.stringify(status)).not.toContain(ownerId); + expect( + ( + await f.knowledge.application.getEvidence(await f.access(), { + articleId: input.articleId, + }) + ).evidence, + ).toHaveLength(0); + }); + + it('preserves native shared report not-found and epoch-conflict errors at the real protocol boundary', async () => { + const f = await fixture(); + const input = await f.reportInput('report-errors'); + const missing = await logicalResponse( + await f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify( + wire(transport, 'getValidationRequirements', { + collectionId, + kind: draft.kind, + articleId: input.articleId, + reportLookup: { + ledgerEpoch: input.ledgerEpoch, + reportId: '00000000-0000-4000-8000-000000000000', + }, + }), + ), + ), + ), + transport, + ); + expect(missing).toMatchObject({ + error: { code: 'not_found', status: 404 }, + }); + const stale = await logicalResponse( + await f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify( + wire(transport, 'submitEvidence', { + ...input, + ledgerEpoch: input.ledgerEpoch + 1, + }), + ), + ), + ), + transport, + ); + expect(stale).toMatchObject({ error: { code: 'conflict', status: 409 } }); + expect( + ( + await f.knowledge.evidence.list(await f.access(), { + articleId: input.articleId, + }) + ).reports, + ).toHaveLength(0); + }); + + it.each(['grant', 'role'] as const)( + 'refuses a report after %s revocation while its actual request body is pending', + async (kind) => { + const f = await fixture(); + const input = await f.reportInput('report-body-race'); + const body = delayedBody(wire(transport, 'submitEvidence', input)); + const pending = f.knowledge.handle( + agentRequest(transport, f.credential.token, body.stream), + ); + await body.reading; + try { + await f.revoke(kind); + } finally { + body.finish(); + } + expect(await logicalResponse(await pending, transport)).toMatchObject({ + error: { code: 'forbidden' }, + }); + expect( + ( + await f.knowledge.evidence.list(await f.access(), { + articleId: input.articleId, + }) + ).reports, + ).toHaveLength(0); + }, + ); + + it.each(['grant', 'role'] as const)( + 'withholds the report acknowledgement after %s revocation at a real committed report write', + async (kind) => { + const f = await fixture(); + const input = await f.reportInput('report-commit-race'); + const blocked = f.block('afterReportCommit'); + const pending = f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify(wire(transport, 'submitEvidence', input)), + ), + ); + await blocked.entered; + try { + await f.revoke(kind); + } finally { + blocked.finish(); + } + const result = await logicalResponse(await pending, transport); + expect(result).toMatchObject({ error: { code: 'forbidden' } }); + expect(JSON.stringify(result)).not.toContain('pending-human-review'); + const retained = await f.knowledge.evidence.list(await f.access(), { + articleId: input.articleId, + }); + expect(retained.reports).toHaveLength(1); + expect(retained.reports[0]).toMatchObject({ + status: 'pending', + submittedBy: ownerId, + }); + expect( + ( + await f.knowledge.application.getEvidence(await f.access(), { + articleId: input.articleId, + }) + ).evidence, + ).toHaveLength(0); + }, + ); + + it.each([ + { kind: 'grant', failRead: false }, + { kind: 'role', failRead: false }, + { kind: 'grant', failRead: true }, + { kind: 'role', failRead: true }, + ] as const)( + 'withholds a committed report ACK on late $kind revocation during its final read (read failure=$failRead)', + async ({ kind, failRead }) => { + const f = await fixture(); + const input = await f.reportInput('deferred-report-final-read'); + const committed = f.block('afterReportCommit'); + const pending = f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify(wire(transport, 'submitEvidence', input)), + ), + ); + await committed.entered; + const finalRead = f.block('afterKbRead', undefined, failRead); + committed.finish(); + await finalRead.entered; + try { + await f.revoke(kind); + } finally { + finalRead.finish(); + } + const result = await logicalResponse(await pending, transport); + expect(result).toMatchObject({ error: { code: 'forbidden' } }); + expect(JSON.stringify(result)).not.toContain('pending-human-review'); + expect(JSON.stringify(result)).not.toContain('failure canary'); + expect(JSON.stringify(result)).not.toContain(input.report.details); + const retained = await f.knowledge.evidence.list(await f.access(), { + articleId: input.articleId, + }); + expect(retained.reports).toHaveLength(1); + expect(retained.reports[0]).toMatchObject({ + status: 'pending', + submittedBy: ownerId, + }); + expect( + ( + await f.knowledge.application.getEvidence(await f.access(), { + articleId: input.articleId, + }) + ).evidence, + ).toEqual([]); + }, + ); + + it.each(['grant', 'role'] as const)( + 'withholds the private ledger after %s revocation during its real namespace read', + async (kind) => { + const f = await fixture(); + const input = await f.reportInput('ledger-read-race'); + const blocked = f.block('afterReportRead'); + const pending = f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify( + wire(transport, 'getValidationRequirements', { + collectionId, + kind: draft.kind, + articleId: input.articleId, + }), + ), + ), + ); + await blocked.entered; + try { + await f.revoke(kind); + } finally { + blocked.finish(); + } + const result = await logicalResponse(await pending, transport); + expect(result).toMatchObject({ error: { code: 'forbidden' } }); + expect(result.result).toBeUndefined(); + expect(JSON.stringify(result)).not.toContain('reportLedger'); + }, + ); + + it.each(['grant', 'role'] as const)( + 'withholds report status after %s revocation during the actual report-row read', + async (kind) => { + const f = await fixture(); + const { input, acknowledgement } = + await f.queueReport('status-read-race'); + const blocked = f.block('afterReportRead', acknowledgement.reportId); + const pending = f.knowledge.handle( + agentRequest( + transport, + f.credential.token, + JSON.stringify( + wire(transport, 'getValidationRequirements', { + collectionId, + kind: draft.kind, + articleId: input.articleId, + reportLookup: { + ledgerEpoch: acknowledgement.ledgerEpoch, + reportId: acknowledgement.reportId, + }, + }), + ), + ), + ); + await blocked.entered; + try { + await f.revoke(kind); + } finally { + blocked.finish(); + } + const result = await logicalResponse(await pending, transport); + expect(result).toMatchObject({ error: { code: 'forbidden' } }); + expect(result.result).toBeUndefined(); + expect(JSON.stringify(result)).not.toContain(acknowledgement.receipt); + expect(JSON.stringify(result)).not.toContain(input.report.details); + }, + ); + }, +); + +it('binds the original request to its actual grant even when another valid token has the same owner/client/resource', async () => { + const f = await fixture(); + const other = await f.device(); + expect(other.grantId).not.toBe(f.credential.grantId); + const body = delayedBody( + wire('http', 'createDraft', f.createInput('grant-swap')), + ); + const request = agentRequest('http', f.credential.token, body.stream); + const pending = f.knowledge.handle(request); + await body.reading; + request.headers.set('Authorization', 'Bearer ' + other.token); + body.finish(); + expect(await logicalResponse(await pending, 'http')).toMatchObject({ + error: { code: 'forbidden' }, + }); + await expect( + f.knowledge.application.getDraft(await f.access(), { + articleId: 'grant-swap', + }), + ).rejects.toBeInstanceOf(KnowledgeBaseNotFoundError); +}); + +it('binds the exact original authorization header even when its replacement authenticates the same actual grant', async () => { + const f = await fixture(); + const input = await f.reportInput('report-header-race'); + const body = delayedBody(wire('http', 'submitEvidence', input)); + const request = agentRequest('http', f.credential.token, body.stream); + const pending = f.knowledge.handle(request); + await body.reading; + request.headers.set('Authorization', 'bearer ' + f.credential.token); + try { + const replacement = await f.agents.protectedResource.authenticate(request); + if (replacement instanceof Response) + throw new Error('Expected the same actual grant.'); + expect(replacement.grantId).toBe(f.credential.grantId); + } finally { + body.finish(); + } + expect(await logicalResponse(await pending, 'http')).toMatchObject({ + error: { code: 'forbidden' }, + }); + expect( + ( + await f.knowledge.evidence.list(await f.access(), { + articleId: input.articleId, + }) + ).reports, + ).toHaveLength(0); +}); + +it('withholds a completed write acknowledgement after revocation without claiming that the accepted write rolled back', async () => { + const f = await fixture(); + const blocked = f.block('afterKbCommit'); + const pending = f.knowledge.handle( + agentRequest( + 'http', + f.credential.token, + JSON.stringify( + wire('http', 'createDraft', f.createInput('accepted-before-revoke')), + ), + ), + ); + await blocked.entered; + try { + await f.revoke('grant'); + } finally { + blocked.finish(); + } + expect(await logicalResponse(await pending, 'http')).toMatchObject({ + error: { code: 'forbidden' }, + }); + expect( + await f.knowledge.application.getDraft(await f.access(), { + articleId: 'accepted-before-revoke', + }), + ).toMatchObject({ + articleId: 'accepted-before-revoke', + revision: { number: 1 }, + }); +}); diff --git a/worker/src/knowledge-api.ts b/worker/src/knowledge-api.ts new file mode 100644 index 0000000..9509faf --- /dev/null +++ b/worker/src/knowledge-api.ts @@ -0,0 +1,609 @@ +import { hasPermission } from '@pegma/authorization-core'; +import { + KnowledgeBaseAuthorizationError, + KnowledgeBaseNotFoundError, + KnowledgeBasePrerequisiteError, + RepositoryCapacityError, + RepositoryConflictError, + type KnowledgeBaseApplication, +} from '@pegma/knowledge-base-application'; +import { KnowledgeBaseError } from '@pegma/knowledge-base-core'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; +import { knowledgeAgentScopes } from '@pegma/knowledge-base-mcp'; +import { + ApiError, + boundedString, + exactObject, + isPlainObject, + json, + optionalKeysObject, + readJson, + requireSameOriginMutation, + TOKEN_PATTERN, +} from './api-auth'; +import { + requireCurrentBrowserAccess, + type AgentBrowserOptions, +} from './agent-authority'; +import { + AGENT_RESOURCE, + type AgentAccessRuntime, +} from './agent-access-runtime'; +import { KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION } from './support-access'; +import { + KnowledgeLedgerError, + type KnowledgeEvidenceService, +} from './knowledge-evidence'; +import { IDENTITY_ISSUER } from './identity-api'; + +export interface KnowledgeApiOptions extends AgentBrowserOptions { + readonly application: KnowledgeBaseApplication; + readonly evidence: KnowledgeEvidenceService; + readonly agentAccess: AgentAccessRuntime | null; + readonly limitBrowser: (request: Request) => Promise; + /** Server-only bounded repair; never accepts caller authority or returns DTOs. */ + readonly repairArticle?: (articleId: string) => Promise; +} + +function secured(response: Response): Response { + response.headers.set('Referrer-Policy', 'no-referrer'); + response.headers.set('X-Content-Type-Options', 'nosniff'); + return response; +} +function response(value: unknown): Response { + const encoded = JSON.stringify(value); + if (new TextEncoder().encode(encoded).byteLength > 512 * 1024) + throw new ApiError(503, 'response_capacity'); + return json(value); +} +const commandFields = ['commandId', 'correlationId', 'expectedGeneration']; +const inputFields: Readonly> = { + getCollection: ['collectionId'], + getValidationPolicy: ['policyId'], + getGovernanceConfiguration: ['collectionId'], + getDraft: ['articleId'], + getEvidence: ['articleId'], + getProvenance: ['articleId'], + getReview: ['articleId'], + getPublishedArticle: ['articleId'], + getValidationRequirements: ['collectionId', 'kind'], + createCollection: [...commandFields, 'collectionId', 'name'], + previewCollectionPolicy: ['collectionId', 'uses'], + updateCollectionPolicy: [...commandFields, 'collectionId', 'preview'], + putValidationPolicy: [...commandFields, 'policy'], + putGovernanceConfiguration: [ + ...commandFields, + 'collectionId', + 'configuration', + ], + createDraft: [...commandFields, 'articleId', 'collectionId', 'draft'], + updateDraft: [...commandFields, 'articleId', 'collectionId', 'draft'], + submitEvidence: [...commandFields, 'articleId', 'evidence', 'receipt'], + submitForReview: [...commandFields, 'articleId'], + publishArticle: [...commandFields, 'articleId', 'review'], + rejectReview: [...commandFields, 'articleId', 'reason'], + retireArticle: [...commandFields, 'articleId'], + revokeEvidence: [ + ...commandFields, + 'articleId', + 'articleRevision', + 'evidenceId', + 'evidenceVersion', + 'evidenceHash', + 'reason', + ], + listPortalCollections: [], + searchPublishedArticles: ['collectionId', 'query', 'applicability'], +}; +function sdkInput(operation: string, input: unknown): unknown { + const fields = inputFields[operation]; + if (fields === undefined) throw new ApiError(400, 'unknown_operation'); + const optional = + operation === 'updateCollectionPolicy' + ? ['approvePublic'] + : operation === 'listPortalCollections' || + operation === 'searchPublishedArticles' + ? ['limit'] + : []; + const value = optionalKeysObject(input, fields, optional); + for (const name of [ + 'commandId', + 'correlationId', + 'articleId', + 'collectionId', + 'policyId', + ]) + if (name in value) boundedString(value[name], 1, 200); + for (const name of [ + 'expectedGeneration', + 'articleRevision', + 'evidenceVersion', + 'limit', + ]) { + const count = value[name]; + if ( + name in value && + (typeof count !== 'number' || + !Number.isSafeInteger(count) || + count < (name === 'expectedGeneration' ? 0 : 1)) + ) + throw new ApiError(400, 'invalid_request'); + } + if ('approvePublic' in value && typeof value.approvePublic !== 'boolean') + throw new ApiError(400, 'invalid_request'); + return value; +} + +/** Browser operations are a closed allowlist over the released SDK validators. */ +export function createKnowledgeApi( + options: KnowledgeApiOptions, +): (request: Request) => Promise { + const app = options.application; + const operations = { + getCollection: { + method: app.getCollection, + permission: knowledgePermissions.collectionRead, + }, + getValidationPolicy: { + method: app.getValidationPolicy, + permission: knowledgePermissions.validationManage, + }, + getGovernanceConfiguration: { + method: app.getGovernanceConfiguration, + permission: knowledgePermissions.validationManage, + }, + getDraft: { + method: app.getDraft, + permission: knowledgePermissions.draftRead, + }, + getEvidence: { + method: app.getEvidence, + permission: knowledgePermissions.evidenceRead, + }, + getProvenance: { + method: app.getProvenance, + permission: knowledgePermissions.provenanceRead, + }, + getReview: { + method: app.getReview, + permission: knowledgePermissions.review, + }, + getValidationRequirements: { + method: app.getValidationRequirements, + permission: knowledgePermissions.evidenceSubmit, + }, + createCollection: { + method: app.createCollection, + permission: knowledgePermissions.collectionManage, + }, + previewCollectionPolicy: { + method: app.previewCollectionPolicy, + permission: knowledgePermissions.collectionManage, + }, + updateCollectionPolicy: { + method: app.updateCollectionPolicy, + permission: knowledgePermissions.collectionManage, + }, + putValidationPolicy: { + method: app.putValidationPolicy, + permission: knowledgePermissions.validationManage, + }, + putGovernanceConfiguration: { + method: app.putGovernanceConfiguration, + permission: knowledgePermissions.validationManage, + }, + createDraft: { + method: app.createDraft, + permission: knowledgePermissions.draftWrite, + }, + updateDraft: { + method: app.updateDraft, + permission: knowledgePermissions.draftWrite, + }, + submitEvidence: { + method: app.submitEvidence, + permission: knowledgePermissions.evidenceSubmit, + }, + submitForReview: { + method: app.submitForReview, + permission: knowledgePermissions.reviewSubmit, + }, + publishArticle: { + method: app.publishArticle, + permission: knowledgePermissions.publish, + }, + rejectReview: { + method: app.rejectReview, + permission: knowledgePermissions.review, + }, + retireArticle: { + method: app.retireArticle, + permission: knowledgePermissions.retire, + }, + revokeEvidence: { + method: app.revokeEvidence, + permission: knowledgePermissions.evidenceRevoke, + }, + }; + const portal = { + listPortalCollections: app.listPortalCollections, + searchPublishedArticles: app.searchPublishedArticles, + getPublishedArticle: app.getPublishedArticle, + }; + const reportOperations = new Set([ + 'reportList', + 'reportRead', + 'confirmReport', + 'rejectReport', + 'reassessReport', + 'reportLedger', + 'resetReports', + 'drainReports', + ]); + return async (request) => { + const url = new URL(request.url); + if ( + ![ + '/api/staff/knowledge/state', + '/api/staff/knowledge/command', + '/api/knowledge/portal', + '/api/knowledge/reports', + ].includes(url.pathname) + ) + return null; + try { + if (url.origin !== IDENTITY_ISSUER) + throw new ApiError(403, 'cross_origin_denied'); + if (url.pathname === '/api/knowledge/reports') { + if (request.method !== 'POST' && request.method !== 'GET') + return secured( + json( + { error: 'method_not_allowed' }, + { status: 405, headers: { Allow: 'GET, POST' } }, + ), + ); + const agents = options.agentAccess; + if (agents === null) + throw new ApiError(503, 'agent_access_not_configured'); + const decision = await agents.resourceLimit(request); + if (!decision.allowed) + throw new ApiError(429, 'rate_limited', decision.retryAfterSeconds); + const origin = request.headers.get('Origin'); + if (origin !== null && origin !== IDENTITY_ISSUER) + throw new ApiError(403, 'cross_origin_denied'); + const identity = await agents.protectedResource.authenticate(request); + if (identity instanceof Response) return secured(identity); + if ( + identity.resource !== AGENT_RESOURCE || + !identity.scopes.includes(knowledgeAgentScopes.evidenceSubmit) || + !hasPermission(identity.access, knowledgePermissions.evidenceSubmit) + ) + throw new ApiError(403, 'forbidden'); + // Recheck the same delegated credential after awaited input/storage. + // A current human principal alone does not establish a live grant. + const currentAgent = async () => { + const latest = await agents.protectedResource.authenticate(request); + if (latest instanceof Response) return latest; + if ( + latest.grantId !== identity.grantId || + latest.clientId !== identity.clientId || + latest.resource !== identity.resource || + latest.access.principalId !== identity.access.principalId || + !latest.scopes.includes(knowledgeAgentScopes.evidenceSubmit) || + !hasPermission(latest.access, knowledgePermissions.evidenceSubmit) + ) + throw new ApiError(403, 'forbidden'); + return latest; + }; + if (request.method === 'POST') { + if (url.search !== '') throw new ApiError(400, 'invalid_request'); + const input = await readJson(request, { timeoutMs: 10_000 }); + const latest = await currentAgent(); + if (latest instanceof Response) return secured(latest); + const value = await options.evidence.report(latest.access, input); + const final = await currentAgent(); + if (final instanceof Response) return secured(final); + return secured(response(value)); + } + const keys = [...url.searchParams.keys()]; + if (keys.length === 1 && keys[0] === 'articleId') { + const value = await options.evidence.ledger(identity.access, { + articleId: boundedString(url.searchParams.get('articleId'), 1, 200), + }); + const final = await currentAgent(); + if (final instanceof Response) return secured(final); + return secured(response(value)); + } + if ( + keys.length !== 3 || + url.searchParams.getAll('articleId').length !== 1 || + url.searchParams.getAll('reportId').length !== 1 || + url.searchParams.getAll('ledgerEpoch').length !== 1 || + !/^[1-9][0-9]*$/u.test(url.searchParams.get('ledgerEpoch') ?? '') + ) + throw new ApiError(400, 'invalid_request'); + const value = await options.evidence.status(identity.access, { + articleId: boundedString(url.searchParams.get('articleId'), 1, 200), + reportId: boundedString(url.searchParams.get('reportId'), 1, 200), + ledgerEpoch: Number(url.searchParams.get('ledgerEpoch')), + }); + const final = await currentAgent(); + if (final instanceof Response) return secured(final); + return secured(response(value)); + } + const state = url.pathname === '/api/staff/knowledge/state'; + if (request.method !== (state ? 'GET' : 'POST')) + return secured( + json( + { error: 'method_not_allowed' }, + { status: 405, headers: { Allow: state ? 'GET' : 'POST' } }, + ), + ); + if (url.search !== '') throw new ApiError(400, 'invalid_request'); + const staffCommand = url.pathname === '/api/staff/knowledge/command'; + const credentialHeaders = staffCommand + ? Object.freeze( + [ + 'Cookie', + 'Origin', + 'X-Pegma-CSRF', + 'Sec-Fetch-Site', + 'Authorization', + ].map((name) => + Object.freeze({ name, value: request.headers.get(name) }), + ), + ) + : undefined; + function sameBrowserHeaders() { + if ( + credentialHeaders?.some( + ({ name, value }) => request.headers.get(name) !== value, + ) + ) + throw new ApiError(403, 'browser_credential_changed'); + } + if (staffCommand) { + if (request.headers.has('Authorization')) + throw new ApiError(403, 'browser_session_required'); + requireSameOriginMutation(request); + const cookie = request.headers.get('Cookie'); + if (cookie === null || cookie.trim() === '' || cookie.length > 8_192) + throw new ApiError(401, 'authentication_required'); + if (!TOKEN_PATTERN.test(request.headers.get('X-Pegma-CSRF') ?? '')) + throw new ApiError(403, 'csrf_denied'); + } + await options.limitBrowser(request); + if (state) { + const { authenticated, access } = await requireCurrentBrowserAccess( + request, + options, + knowledgePermissions.collectionRead, + ); + return secured( + response({ + csrfToken: authenticated.csrfToken, + attesterId: access.principalId, + permissions: { + collectionManage: hasPermission( + access, + knowledgePermissions.collectionManage, + ), + validationManage: hasPermission( + access, + knowledgePermissions.validationManage, + ), + review: hasPermission(access, knowledgePermissions.review), + publish: hasPermission(access, knowledgePermissions.publish), + evidenceConfirm: hasPermission( + access, + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + ), + retire: hasPermission(access, knowledgePermissions.retire), + evidenceRevoke: hasPermission( + access, + knowledgePermissions.evidenceRevoke, + ), + draftWrite: hasPermission( + access, + knowledgePermissions.draftWrite, + ), + }, + }), + ); + } + // Staff POSTs parse at most64KiB after static browser/admission checks. + // Full current session/CSRF/operation authority follows the body and + // precedes EVERY protected read or application/report mutation. + if (!staffCommand) + await requireCurrentBrowserAccess( + request, + options, + knowledgePermissions.articleRead, + true, + ); + const envelope = exactObject( + await readJson(request, { timeoutMs: 10_000 }), + ['operation', 'input'], + ); + sameBrowserHeaders(); + let commandIdentity: + { sessionId: string; principalId: string } | undefined; + async function commandAccess(permission: string) { + sameBrowserHeaders(); + const current = await requireCurrentBrowserAccess( + request, + options, + permission, + true, + ); + sameBrowserHeaders(); + if (!hasPermission(current.access, knowledgePermissions.collectionRead)) + throw new ApiError(403, 'forbidden'); + if (commandIdentity === undefined) + commandIdentity = Object.freeze({ + sessionId: current.authenticated.rawSessionId, + principalId: current.access.principalId, + }); + else if ( + current.authenticated.rawSessionId !== commandIdentity.sessionId || + current.access.principalId !== commandIdentity.principalId + ) + throw new ApiError(403, 'browser_credential_changed'); + return current; + } + const operation = boundedString(envelope.operation, 1, 64); + if (url.pathname === '/api/knowledge/portal') { + if (!Object.hasOwn(portal, operation)) + throw new ApiError(400, 'unknown_operation'); + const method = portal[operation as keyof typeof portal]; + const { authenticated, access } = await requireCurrentBrowserAccess( + request, + options, + knowledgePermissions.articleRead, + true, + ); + const authority = Object.freeze({ + sessionId: authenticated.rawSessionId, + principalId: access.principalId, + permissions: Object.freeze([...access.permissions]), + }); + // The released method owns exact DTO validation. Reflect.apply forwards + // unknown JSON without asserting it is an already validated SDK DTO. + const result: unknown = await Reflect.apply(method, app, [ + access, + sdkInput(operation, envelope.input), + ]); + const final = await requireCurrentBrowserAccess( + request, + options, + knowledgePermissions.articleRead, + true, + ); + if ( + final.authenticated.rawSessionId !== authority.sessionId || + final.access.principalId !== authority.principalId + ) + throw new ApiError(403, 'browser_credential_changed'); + // Audience permissions can be narrower than the default article-read + // grant. A successful fresh login alone must not release their old DTO. + if ( + authority.permissions.some( + (permission) => !hasPermission(final.access, permission), + ) + ) + throw new ApiError(403, 'forbidden'); + return secured(response(result)); + } + if (reportOperations.has(operation)) { + const { access } = await commandAccess( + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + ); + const result = + operation === 'reportList' + ? await options.evidence.list(access, envelope.input) + : operation === 'reportRead' + ? await options.evidence.read(access, envelope.input) + : operation === 'reportLedger' + ? await options.evidence.ledger(access, envelope.input) + : operation === 'resetReports' + ? await options.evidence.reset(access, envelope.input) + : operation === 'drainReports' + ? await options.evidence.drain(access, envelope.input) + : await options.evidence.decide( + access, + envelope.input, + operation === 'confirmReport' + ? 'confirmed' + : operation === 'rejectReport' + ? 'rejected' + : 'pending', + ); + await commandAccess(KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION); + return secured(response(result)); + } + if (!Object.hasOwn(operations, operation)) + throw new ApiError(400, 'unknown_operation'); + if ( + (operation === 'createDraft' || operation === 'updateDraft') && + isPlainObject(envelope.input) && + Object.hasOwn(envelope.input, 'sourceReferences') + ) + throw new ApiError(400, 'unsupported_source_references'); + const selected = operations[operation as keyof typeof operations]; + const { access } = await commandAccess(selected.permission); + const result: unknown = await Reflect.apply(selected.method, app, [ + access, + sdkInput(operation, envelope.input), + ]); + if ( + ['publishArticle', 'retireArticle', 'revokeEvidence'].includes( + operation, + ) && + isPlainObject(envelope.input) && + typeof envelope.input.articleId === 'string' + ) { + try { + await options.repairArticle?.(envelope.input.articleId); + } catch { + // Publication/retirement/revocation already committed. A failed hint + // repair is recovered by the durable page worker, not a rollback. + try { + options.logger.log( + 'warn', + 'knowledge.retrieval_maintenance.failed', + { + stage: 'keyed', + }, + ); + } catch { + // The article command committed before this diagnostic. + } + } + } + await commandAccess(selected.permission); + return secured(response(result)); + } catch (error) { + let status = 503; + let code = 'service_unavailable'; + if (error instanceof ApiError) { + status = error.status; + code = error.code; + } else if (error instanceof KnowledgeBaseAuthorizationError) { + status = 403; + code = 'forbidden'; + } else if (error instanceof KnowledgeBaseNotFoundError) { + status = 404; + code = 'not_found'; + } else if (error instanceof KnowledgeBasePrerequisiteError) { + status = 409; + code = 'prerequisite_unavailable'; + } else if (error instanceof RepositoryConflictError) { + status = 409; + code = 'conflict'; + } else if (error instanceof RepositoryCapacityError) { + status = 409; + code = 'capacity'; + } else if (error instanceof KnowledgeBaseError) { + status = error.code === 'invalid' ? 400 : 409; + code = 'knowledge_' + error.code; + } + if (status === 503) + options.logger.log('error', 'knowledge.api_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + stage: error instanceof KnowledgeLedgerError ? error.stage : 'api', + }); + return secured( + json( + { error: code }, + { + status, + ...(error instanceof ApiError && + error.retryAfterSeconds !== undefined + ? { headers: { 'Retry-After': String(error.retryAfterSeconds) } } + : {}), + }, + ), + ); + } + }; +} diff --git a/worker/src/knowledge-body-deadline.test.ts b/worker/src/knowledge-body-deadline.test.ts new file mode 100644 index 0000000..b612ff5 --- /dev/null +++ b/worker/src/knowledge-body-deadline.test.ts @@ -0,0 +1,311 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { ApiError, readJson } from './api-auth'; + +const timeoutMs = 10_000; +const byteLimit = 64 * 1024; +const encoder = new TextEncoder(); + +function jsonRequest( + body: ReadableStream, + headers: HeadersInit = { 'Content-Type': 'application/json' }, +): Request { + const init: RequestInit & { duplex: 'half' } = { + method: 'POST', + headers, + body, + duplex: 'half', + }; + return new Request('https://pegma.dev/api/staff/knowledge/command', init); +} + +function chunksRequest(chunks: Uint8Array[]): Request { + let index = 0; + return jsonRequest( + new ReadableStream( + { + pull(controller) { + const chunk = chunks[index++]; + if (chunk === undefined) controller.close(); + else controller.enqueue(chunk); + }, + }, + { highWaterMark: 0 }, + ), + ); +} + +function fakeClock(): void { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }); +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('staff knowledge JSON body deadline', () => { + it('bounds a hung read even when the actual stream cancellation never settles', async () => { + fakeClock(); + const pull = vi.fn(() => new Promise(() => {})); + const cancel = vi.fn(() => new Promise(() => {})); + const request = jsonRequest( + new ReadableStream({ pull, cancel }, { highWaterMark: 0 }), + ); + let settled = false; + const pending = readJson(request, { timeoutMs }).finally(() => { + settled = true; + }); + const rejection = expect(pending).rejects.toMatchObject({ + status: 408, + code: 'request_timeout', + }); + await vi.advanceTimersByTimeAsync(timeoutMs - 1); + expect(settled).toBe(false); + expect(pull).toHaveBeenCalledTimes(1); + expect(cancel).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + await rejection; + expect(cancel).toHaveBeenCalledTimes(1); + expect(cancel).toHaveBeenCalledWith(expect.any(ApiError)); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it('retains the timeout failure when actual cancellation rejects', async () => { + fakeClock(); + const cancel = vi.fn(() => + Promise.reject(new Error('synthetic cancel failure')), + ); + const request = jsonRequest( + new ReadableStream({ cancel }, { highWaterMark: 0 }), + ); + const rejection = expect( + readJson(request, { timeoutMs }), + ).rejects.toMatchObject({ + status: 408, + code: 'request_timeout', + }); + await vi.advanceTimersByTimeAsync(timeoutMs); + await rejection; + expect(cancel).toHaveBeenCalledTimes(1); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it('uses one total deadline instead of renewing it after each chunk', async () => { + fakeClock(); + let source!: ReadableStreamDefaultController; + const cancel = vi.fn(); + const request = jsonRequest( + new ReadableStream( + { + start(controller) { + source = controller; + }, + cancel, + }, + { highWaterMark: 0 }, + ), + ); + const rejection = expect( + readJson(request, { timeoutMs }), + ).rejects.toMatchObject({ + status: 408, + code: 'request_timeout', + }); + await vi.advanceTimersByTimeAsync(9_000); + source.enqueue(encoder.encode('{"partial":')); + await vi.advanceTimersByTimeAsync(1_000); + await rejection; + expect(cancel).toHaveBeenCalledTimes(1); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it('accepts a delayed complete body before the deadline and clears its timer', async () => { + fakeClock(); + let source!: ReadableStreamDefaultController; + const cancel = vi.fn(); + const request = jsonRequest( + new ReadableStream( + { + start(controller) { + source = controller; + }, + cancel, + }, + { highWaterMark: 0 }, + ), + ); + const pending = readJson(request, { timeoutMs }); + await vi.advanceTimersByTimeAsync(timeoutMs - 1); + source.enqueue(encoder.encode('{"ok":true}')); + source.close(); + await expect(pending).resolves.toEqual({ ok: true }); + expect(cancel).not.toHaveBeenCalled(); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it('does not wait for a hung cancellation after the actual byte cap is exceeded', async () => { + fakeClock(); + const cancel = vi.fn(() => new Promise(() => {})); + let index = 0; + const request = jsonRequest( + new ReadableStream( + { + pull(controller) { + controller.enqueue(new Uint8Array(index++ === 0 ? byteLimit : 1)); + }, + cancel, + }, + { highWaterMark: 0 }, + ), + ); + await expect(readJson(request, { timeoutMs })).rejects.toMatchObject({ + status: 413, + code: 'request_too_large', + }); + expect(cancel).toHaveBeenCalledTimes(1); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it('propagates the original stream read failure and clears the deadline', async () => { + fakeClock(); + const failure = new Error('synthetic body read failure'); + const request = jsonRequest( + new ReadableStream( + { + pull(controller) { + controller.error(failure); + }, + }, + { highWaterMark: 0 }, + ), + ); + await expect(readJson(request, { timeoutMs })).rejects.toBe(failure); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it.each([undefined, { timeoutMs }])( + 'preserves the exact 64KiB byte boundary (%j)', + async (options) => { + fakeClock(); + const text = 'a'.repeat(byteLimit - 2); + const bytes = encoder.encode(JSON.stringify(text)); + expect(bytes.byteLength).toBe(byteLimit); + const request = chunksRequest([ + bytes.subarray(0, 31_111), + bytes.subarray(31_111), + ]); + await expect(readJson(request, options)).resolves.toBe(text); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }, + ); + + it.each([undefined, { timeoutMs }])( + 'decodes UTF-8 split across real stream chunks (%j)', + async (options) => { + fakeClock(); + const bytes = encoder.encode('{"text":"\u20ac"}'); + const request = chunksRequest([ + bytes.subarray(0, 10), + bytes.subarray(10, 11), + bytes.subarray(11), + ]); + await expect(readJson(request, options)).resolves.toEqual({ + text: '\u20ac', + }); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }, + ); + + it.each([encoder.encode('{'), new Uint8Array([0x22, 0xff, 0x22])])( + 'retains invalid JSON and fatal UTF-8 rejection', + async (bytes) => { + fakeClock(); + const request = chunksRequest([bytes]); + await expect(readJson(request, { timeoutMs })).rejects.toMatchObject({ + status: 400, + code: 'invalid_json', + }); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }, + ); + + it.each([ + { + headers: new Headers({ 'Content-Type': 'text/plain' }), + status: 415, + code: 'json_required', + }, + { + headers: new Headers({ + 'Content-Type': 'application/json', + 'Content-Length': '65537', + }), + status: 413, + code: 'request_too_large', + }, + { + headers: new Headers({ + 'Content-Type': 'application/json', + 'Content-Length': 'invalid', + }), + status: 413, + code: 'request_too_large', + }, + ])( + 'retains header rejection before reading the body ($code)', + async ({ headers, status, code }) => { + fakeClock(); + const pull = vi.fn(); + const cancel = vi.fn(); + const request = jsonRequest( + new ReadableStream({ pull, cancel }, { highWaterMark: 0 }), + headers, + ); + await expect(readJson(request, { timeoutMs })).rejects.toMatchObject({ + status, + code, + }); + expect(pull).not.toHaveBeenCalled(); + expect(cancel).not.toHaveBeenCalled(); + expect(request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }, + ); + + it('does not add a deadline to callers that omit options', async () => { + fakeClock(); + let source!: ReadableStreamDefaultController; + const cancel = vi.fn(); + const request = jsonRequest( + new ReadableStream( + { + start(controller) { + source = controller; + }, + cancel, + }, + { highWaterMark: 0 }, + ), + ); + let settled = false; + const pending = readJson(request).finally(() => { + settled = true; + }); + await vi.advanceTimersByTimeAsync(2 * timeoutMs); + expect(settled).toBe(false); + expect(cancel).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + source.enqueue(encoder.encode('{"legacy":true}')); + source.close(); + await expect(pending).resolves.toEqual({ legacy: true }); + expect(request.body?.locked).toBe(false); + }); +}); diff --git a/worker/src/knowledge-evidence.test.ts b/worker/src/knowledge-evidence.test.ts new file mode 100644 index 0000000..23234e8 --- /dev/null +++ b/worker/src/knowledge-evidence.test.ts @@ -0,0 +1,1048 @@ +import { + hasPermission, + resolveAccess, + type AccessContext, +} from '@pegma/authorization-core'; +import { + createKnowledgeBaseApplication, + type KnowledgeBaseApplication, +} from '@pegma/knowledge-base-application'; +import { + articleKinds, + knowledgePermissions, + type ValidationPolicy, +} from '@pegma/knowledge-base-contracts'; +import { + validateValidationPolicy, + type EvidenceSubmission, +} from '@pegma/knowledge-base-core'; +import { + createMemoryStore, + type CollectionDefinition, + type CollectionStore, + type Store, +} from '@pegma/storage-core'; +import { describe, expect, it } from 'vitest'; +import { + createKnowledgeEvidenceService, + KnowledgeLedgerError, + type KnowledgeEvidenceOptions, +} from './knowledge-evidence'; +import { ApiError } from './api-auth'; +import { + KNOWLEDGE_ROLE, + PEGMA_ACCESS_POLICY, + SUPPORT_ROLE, +} from './support-access'; + +const at = '2026-11-08T12:00:00.000Z'; +const owner = resolveAccess( + { principalId: 'author', roles: ['Admin'] }, + PEGMA_ACCESS_POLICY, +); +const reviewer = resolveAccess( + { principalId: 'reviewer', roles: [KNOWLEDGE_ROLE] }, + PEGMA_ACCESS_POLICY, +); +const other = resolveAccess( + { principalId: 'other-author', roles: ['Admin'] }, + PEGMA_ACCESS_POLICY, +); +const legacySupport = resolveAccess( + { principalId: 'legacy-support', roles: [SUPPORT_ROLE] }, + PEGMA_ACCESS_POLICY, +); +const restricted = (access: AccessContext): AccessContext => ({ + ...access, + permissions: [ + knowledgePermissions.draftRead, + knowledgePermissions.evidenceSubmit, + ], +}); + +interface StoredReportRow { + readonly articleId: string; + readonly id: string; + readonly payload: string; +} + +async function fixture(options: { portal?: boolean } = {}) { + const backing = createMemoryStore(); + let reportDefinition: CollectionDefinition | undefined; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + if (definition.name === 'pegma-dev.knowledge-evidence.v1') + reportDefinition = + definition as unknown as CollectionDefinition; + return backing.collection(definition); + }, + }; + function reportRows() { + if (reportDefinition === undefined) + throw new Error('The public report factory did not open its collection.'); + return backing.collection(reportDefinition); + } + let now = at; + const clock = { now: () => now }; + const principals = new Map([ + [owner.principalId, owner], + [reviewer.principalId, reviewer], + [other.principalId, other], + [legacySupport.principalId, legacySupport], + ]); + let app: KnowledgeBaseApplication; + const evidenceOptions: KnowledgeEvidenceOptions = { + store, + clock, + resolvePrincipal: async (id) => principals.get(id) ?? null, + async readContext(access, articleId) { + const draft = await app.getDraft(access, { articleId }); + const requirements = await app.getValidationRequirements(access, { + collectionId: draft.revision.collectionId, + kind: draft.revision.kind, + }); + return { + draft, + requirements, + ...(hasPermission(access, knowledgePermissions.evidenceRead) + ? { evidence: await app.getEvidence(access, { articleId }) } + : {}), + }; + }, + }; + const freshEvidence = (overrides: Partial = {}) => + createKnowledgeEvidenceService({ ...evidenceOptions, ...overrides }); + const evidence = freshEvidence(); + app = createKnowledgeBaseApplication({ + store, + clock, + evidenceVerifier: evidence.verifier, + }); + await app.createCollection(owner, { + commandId: 'collection', + correlationId: 'setup', + expectedGeneration: 0, + collectionId: 'guides', + name: 'Guides', + }); + const policy: ValidationPolicy = { + id: 'guide-policy', + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: kind + '-content', + kind, + testKind: 'content', + maxAgeMilliseconds: 60_000, + trustedRunnerIds: ['runner'], + })), + { + id: 'walkthrough-workflow', + kind: 'walkthrough', + testKind: 'workflow', + maxAgeMilliseconds: 60_000, + trustedRunnerIds: ['runner'], + }, + { + id: 'staging-check', + kind: 'walkthrough', + testKind: 'staging', + maxAgeMilliseconds: 60_000, + trustedRunnerIds: ['runner'], + }, + ], + }; + validateValidationPolicy(policy); + await app.putValidationPolicy(owner, { + commandId: 'policy', + correlationId: 'setup', + expectedGeneration: 0, + policy, + }); + await app.putGovernanceConfiguration(owner, { + commandId: 'governance', + correlationId: 'setup', + expectedGeneration: 1, + collectionId: 'guides', + configuration: { + validationPolicy: { id: 'guide-policy', version: 1 }, + expectedStagingBuildId: 'staging-1', + trustedAttesterIds: ['reviewer'], + }, + }); + if (options.portal === true) { + const preview = await app.previewCollectionPolicy(owner, { + collectionId: 'guides', + uses: { + portal: { + enabled: true, + audience: { + kind: 'permission', + permission: knowledgePermissions.articleRead, + }, + }, + bot: { enabled: false }, + }, + }); + await app.updateCollectionPolicy(owner, { + commandId: 'portal', + correlationId: 'setup', + expectedGeneration: preview.generation, + collectionId: 'guides', + preview: preview.preview, + }); + } + const draft = { + kind: 'walkthrough' as const, + title: 'Reset an example setting', + summary: 'A bounded synthetic guide.', + content: { + format: 'plain_text' as const, + text: 'Open the example settings and reset the setting.', + }, + tags: ['settings'], + applicability: { + productId: 'example', + productVersion: '1', + buildId: 'staging-1', + }, + }; + await app.createDraft(owner, { + commandId: 'draft', + correlationId: 'setup', + expectedGeneration: 0, + articleId: 'guide', + collectionId: 'guides', + draft, + }); + const revision = (await app.getDraft(owner, { articleId: 'guide' })).revision; + const submission: EvidenceSubmission = { + id: 'run-1', + articleId: 'guide', + articleRevision: revision.number, + contentHash: revision.contentHash, + validationPolicy: revision.validationPolicy, + checkId: 'staging-check', + testKind: 'staging', + applicability: revision.applicability, + stagingBuildId: 'staging-1', + steps: ['Open settings.', 'Reset the example setting.'], + result: 'passed', + executedAt: at, + runnerId: 'runner', + artifacts: [{ id: 'report-artifact', hash: 'a'.repeat(64) }], + }; + const input = { + commandId: 'report-1', + articleId: 'guide', + ledgerEpoch: 1, + evidence: submission, + report: { + summary: 'Staging test passed', + details: 'Observed the expected example setting after reset.', + }, + }; + const agent = restricted(owner); + const ack = await evidence.report(agent, input); + const view = await evidence.read(reviewer, { + articleId: 'guide', + ledgerEpoch: ack.ledgerEpoch, + reportId: ack.reportId, + }); + const confirm = { + commandId: 'confirm-1', + articleId: 'guide', + ledgerEpoch: ack.ledgerEpoch, + reportId: ack.reportId, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }; + const accept = async ( + access = agent, + fullEvidence = submission, + commandId = 'accept-1', + ) => + app.submitEvidence(access, { + commandId, + correlationId: 'test', + expectedGeneration: (await app.getDraft(owner, { articleId: 'guide' })) + .generation, + articleId: 'guide', + evidence: fullEvidence, + receipt: ack.receipt, + }); + return { + store, + reportRows, + reportDefinition: () => { + if (reportDefinition === undefined) + throw new Error('Missing the actual report collection definition.'); + return reportDefinition; + }, + freshEvidence, + app, + evidence, + clock, + principals, + agent, + submission, + input, + ack, + view, + confirm, + accept, + draft, + setTime(value: string) { + now = value; + }, + }; +} + +describe('stored staff report confirmation', () => { + it('reopens retained raw ledger rows without changing physical keys, payloads or receipts', async () => { + const f = await fixture(); + const confirmed = await f.evidence.decide(reviewer, f.confirm, 'confirmed'); + const rows = f.reportRows(); + const before = await rows.listVersioned('guide'); + const definition = f.reportDefinition(); + const physical = await rows.scan({ limit: 160 }); + expect(physical.nextCursor).toBeNull(); + expect(physical.records).toHaveLength(before.length); + for (const item of physical.records) { + expect(item.key).toEqual({ partition: 'guide', id: item.value.id }); + expect(definition.codec.encode(item.value)).toEqual({ + articleId: 'guide', + id: item.value.id, + payload: item.value.payload, + }); + } + expect(f.ack.receipt).toBe('e1.1.' + f.ack.reportId); + expect(confirmed.receipt).toBe(f.ack.receipt); + + const fresh = f.freshEvidence(); + expect(fresh.agentReports).toEqual( + expect.objectContaining({ + ledger: expect.any(Function), + report: expect.any(Function), + status: expect.any(Function), + }), + ); + expect( + await fresh.status(f.agent, { + articleId: 'guide', + ledgerEpoch: f.ack.ledgerEpoch, + reportId: f.ack.reportId, + }), + ).toEqual({ ...confirmed, status: 'confirmed' }); + expect( + await fresh.agentReports.status(f.agent, { + articleId: 'guide', + ledgerEpoch: f.ack.ledgerEpoch, + reportId: f.ack.reportId, + }), + ).toEqual({ ...confirmed, status: 'confirmed' }); + expect(await fresh.report(f.agent, f.input)).toEqual(f.ack); + expect(await fresh.decide(reviewer, f.confirm, 'confirmed')).toEqual( + confirmed, + ); + expect(await rows.listVersioned('guide')).toEqual(before); + + const reopened = createKnowledgeBaseApplication({ + store: f.store, + clock: f.clock, + evidenceVerifier: fresh.verifier, + }); + await reopened.submitEvidence(f.agent, { + commandId: 'accept-retained-receipt', + correlationId: 'test', + expectedGeneration: ( + await reopened.getDraft(owner, { articleId: 'guide' }) + ).generation, + articleId: 'guide', + evidence: f.submission, + receipt: f.ack.receipt, + }); + expect( + (await reopened.getEvidence(owner, { articleId: 'guide' })).evidence[0] + ?.attestation.id, + ).toBe(f.ack.receipt); + expect(await rows.listVersioned('guide')).toEqual(before); + }); + + it('keeps a missing actual KB target as a safe HTTP not-found refusal', async () => { + const f = await fixture(); + const before = await f.reportRows().scan({ limit: 160 }); + await expect( + f.evidence.report(f.agent, { + ...f.input, + commandId: 'missing-target', + articleId: 'missing-guide', + evidence: { ...f.submission, articleId: 'missing-guide' }, + }), + ).rejects.toMatchObject({ status: 404, code: 'not_found' }); + expect(await f.reportRows().scan({ limit: 160 })).toEqual(before); + }); + + it('preserves a controlled host context conflict and safely classifies an unknown read failure', async () => { + const f = await fixture(); + const before = await f.reportRows().listVersioned('guide'); + const key = { + articleId: 'guide', + ledgerEpoch: 1, + reportId: f.ack.reportId, + }; + const conflict = f.freshEvidence({ + async readContext() { + throw new ApiError(409, 'report_target_changed'); + }, + }); + await expect(conflict.read(reviewer, key)).rejects.toMatchObject({ + status: 409, + code: 'report_target_changed', + }); + const unavailable = f.freshEvidence({ + async readContext() { + throw new Error('private-context-error-marker'); + }, + }); + const failure: unknown = await unavailable + .read(reviewer, key) + .catch((error: unknown) => error); + expect(failure).toBeInstanceOf(KnowledgeLedgerError); + expect(failure).toMatchObject({ + stage: 'context_read', + message: 'Knowledge report ledger is unavailable.', + }); + expect(JSON.stringify(failure)).not.toContain( + 'private-context-error-marker', + ); + expect(await f.reportRows().listVersioned('guide')).toEqual(before); + }); + + it('lists the exact current report identity without changing ledger rows', async () => { + const f = await fixture(); + const rows = f.reportRows(); + const before = await rows.listVersioned('guide'); + const result = await f.evidence.list(reviewer, { articleId: 'guide' }); + expect(result.reports).toEqual([ + { + articleId: 'guide', + ledgerEpoch: f.ack.ledgerEpoch, + reportId: f.ack.reportId, + reportGeneration: f.ack.reportGeneration, + status: 'pending', + submittedBy: f.agent.principalId, + submittedAt: at, + summary: f.input.report.summary, + }, + ]); + expect(await rows.listVersioned('guide')).toEqual(before); + }); + + it.each([ + { field: 'articleId', value: 'other-guide' }, + { field: 'ledgerEpoch', value: 2 }, + { field: 'reportId', value: 'other-report' }, + ])( + 'refuses a payload-only $field mismatch without writing ledger rows', + async ({ field, value }) => { + const f = await fixture(); + const rows = f.reportRows(); + const key = { + partition: 'guide', + id: 'report:' + f.ack.ledgerEpoch + ':' + f.ack.reportId, + }; + const before = await rows.listVersioned('guide'); + const report = await rows.get(key); + if (report === null) + throw new Error('Expected the actual stored report.'); + const payload = JSON.parse(report.payload) as Record; + await rows.put({ + ...report, + payload: JSON.stringify({ ...payload, [field]: value }), + }); + const corrupted = await rows.listVersioned('guide'); + expect(corrupted).toHaveLength(before.length); + expect(corrupted.filter((item) => item.value.id !== key.id)).toEqual( + before.filter((item) => item.value.id !== key.id), + ); + expect(await rows.get(key)).toMatchObject({ + articleId: 'guide', + id: key.id, + }); + + const failure = await f.evidence + .list(reviewer, { articleId: 'guide' }) + .then( + () => null, + (error: unknown) => error, + ); + expect(failure).toBeInstanceOf(KnowledgeLedgerError); + expect(failure).toMatchObject({ + stage: 'report_identity', + message: 'Knowledge report ledger is unavailable.', + }); + expect(await rows.listVersioned('guide')).toEqual(corrupted); + }, + ); + + it('requires a browser-authorized human review before actual KB acceptance', async () => { + const f = await fixture(); + expect(f.view.status).toBe('pending'); + expect(Object.keys(f.ack).sort()).toEqual([ + 'ledgerEpoch', + 'receipt', + 'reportGeneration', + 'reportId', + ]); + await expect(f.accept()).rejects.toThrow(); + await expect( + f.evidence.decide(f.agent, f.confirm, 'confirmed'), + ).rejects.toMatchObject({ status: 403 }); + await expect( + f.evidence.decide(legacySupport, f.confirm, 'confirmed'), + ).rejects.toMatchObject({ status: 403 }); + await expect( + f.evidence.read(legacySupport, { + articleId: 'guide', + ledgerEpoch: f.ack.ledgerEpoch, + reportId: f.ack.reportId, + }), + ).rejects.toMatchObject({ status: 403 }); + expect( + await f.evidence.decide(reviewer, f.confirm, 'confirmed'), + ).toMatchObject({ reportGeneration: 2 }); + expect( + (await f.app.getEvidence(owner, { articleId: 'guide' })).evidence, + ).toEqual([]); + await f.accept(); + const actual = (await f.app.getEvidence(owner, { articleId: 'guide' })) + .evidence[0]; + expect(actual?.attestation).toEqual({ + id: f.ack.receipt, + verifiedBy: reviewer.principalId, + verifiedAt: at, + }); + expect(actual?.runnerId).toBe('runner'); + expect(actual?.artifacts).toEqual(f.submission.artifacts); + expect(hasPermission(reviewer, knowledgePermissions.validationManage)).toBe( + false, + ); + }); + + it('binds the full report, actor and submission with exact immutable command replay', async () => { + const f = await fixture(); + const rows = f.reportRows(); + const count = (await rows.list('guide')).length; + expect(await f.evidence.report(f.agent, f.input)).toEqual(f.ack); + expect((await rows.list('guide')).length).toBe(count); + await expect( + f.evidence.report(f.agent, { + ...f.input, + report: { ...f.input.report, details: 'Changed result narrative.' }, + }), + ).rejects.toMatchObject({ status: 409 }); + await f.evidence.decide(reviewer, f.confirm, 'confirmed'); + const afterConfirm = (await rows.list('guide')).length; + expect( + await f.evidence.decide(reviewer, f.confirm, 'confirmed'), + ).toMatchObject({ reportGeneration: 2 }); + expect((await rows.list('guide')).length).toBe(afterConfirm); + await expect(f.accept(restricted(other))).rejects.toThrow(); + await expect( + f.accept(f.agent, { ...f.submission, result: 'failed' }), + ).rejects.toThrow(); + await expect( + f.accept(f.agent, { + ...f.submission, + artifacts: [{ id: 'report-artifact', hash: 'b'.repeat(64) }], + }), + ).rejects.toThrow(); + expect( + await f.evidence.status(f.agent, { + articleId: 'guide', + ledgerEpoch: f.ack.ledgerEpoch, + reportId: f.ack.reportId, + }), + ).toEqual({ ...f.ack, reportGeneration: 2, status: 'confirmed' }); + await expect( + f.evidence.status(restricted(other), { + articleId: 'guide', + ledgerEpoch: f.ack.ledgerEpoch, + reportId: f.ack.reportId, + }), + ).rejects.toMatchObject({ status: 404 }); + }); + + it('rejects confirmation of a changed draft or changed governance generation', async () => { + const f = await fixture(); + await f.app.updateDraft(owner, { + commandId: 'edit', + correlationId: 'test', + expectedGeneration: 1, + articleId: 'guide', + collectionId: 'guides', + draft: { ...f.draft, title: 'Changed example guide' }, + }); + await expect( + f.evidence.decide(reviewer, f.confirm, 'confirmed'), + ).rejects.toMatchObject({ status: 409 }); + const g = await fixture(); + await g.app.putGovernanceConfiguration(owner, { + commandId: 'new-governance', + correlationId: 'test', + expectedGeneration: 2, + collectionId: 'guides', + configuration: { + validationPolicy: { id: 'guide-policy', version: 1 }, + expectedStagingBuildId: 'staging-2', + trustedAttesterIds: ['reviewer'], + }, + }); + await expect( + g.evidence.decide(reviewer, g.confirm, 'confirmed'), + ).rejects.toMatchObject({ status: 409 }); + }); + + it('preserves execution age and fails closed after reviewer revocation', async () => { + const f = await fixture(); + await f.evidence.decide(reviewer, f.confirm, 'confirmed'); + f.setTime('2026-11-08T12:01:00.001Z'); + await expect(f.accept()).rejects.toThrow(); + const g = await fixture(); + await g.evidence.decide(reviewer, g.confirm, 'confirmed'); + g.principals.set( + reviewer.principalId, + resolveAccess({ principalId: reviewer.principalId }, PEGMA_ACCESS_POLICY), + ); + await expect(g.accept()).rejects.toThrow(); + await expect( + g.evidence.read(reviewer, { + articleId: 'guide', + ledgerEpoch: g.ack.ledgerEpoch, + reportId: g.ack.reportId, + }), + ).rejects.toMatchObject({ status: 403 }); + }); + + it('keeps runner trust and exact evidence revocation in the real KB', async () => { + const f = await fixture(); + const wrong = await f.evidence.report(f.agent, { + ...f.input, + commandId: 'wrong-runner', + evidence: { + ...f.submission, + id: 'wrong-run', + runnerId: 'untrusted-runner', + }, + }); + const read = await f.evidence.read(reviewer, { + articleId: 'guide', + ledgerEpoch: wrong.ledgerEpoch, + reportId: wrong.reportId, + }); + await f.evidence.decide( + reviewer, + { + ...f.confirm, + commandId: 'review-wrong-runner', + ledgerEpoch: wrong.ledgerEpoch, + reportId: wrong.reportId, + expectedReportGeneration: read.expectedReportGeneration, + reviewBindingHash: read.reviewBindingHash, + }, + 'confirmed', + ); + await expect( + f.app.submitEvidence(f.agent, { + commandId: 'accept-wrong-runner', + correlationId: 'test', + expectedGeneration: 1, + articleId: 'guide', + evidence: { + ...f.submission, + id: 'wrong-run', + runnerId: 'untrusted-runner', + }, + receipt: wrong.receipt, + }), + ).rejects.toThrow(); + await f.evidence.decide(reviewer, f.confirm, 'confirmed'); + await f.accept(); + const accepted = (await f.app.getEvidence(owner, { articleId: 'guide' })) + .evidence[0]; + if (accepted === undefined) throw new Error('Missing actual evidence.'); + await f.app.revokeEvidence(owner, { + commandId: 'revoke', + correlationId: 'test', + expectedGeneration: 2, + articleId: 'guide', + articleRevision: 1, + evidenceId: accepted.id, + evidenceVersion: accepted.version, + evidenceHash: accepted.hash, + reason: 'Staff withdrew the test result.', + }); + expect( + (await f.app.getEvidence(owner, { articleId: 'guide' })).revokedEvidence, + ).toEqual([ + expect.objectContaining({ + id: accepted.id, + version: accepted.version, + hash: accepted.hash, + articleRevision: 1, + }), + ]); + await expect( + f.accept(f.agent, f.submission, 'reuse-revoked'), + ).rejects.toThrow(); + expect( + (await f.app.getProvenance(owner, { articleId: 'guide' })).snapshot + .references, + ).toEqual([]); + }); + + it('retains approved v1 after evidence age passes and a separate v2 draft clears current evidence', async () => { + const f = await fixture({ portal: true }); + await f.evidence.decide(reviewer, f.confirm, 'confirmed'); + await f.accept(); + for (const [checkId, testKind] of [ + ['walkthrough-content', 'content'], + ['walkthrough-workflow', 'workflow'], + ]) { + if (checkId === undefined || testKind === undefined) + throw new Error('Missing required synthetic check.'); + const submission = { + ...f.submission, + id: checkId + '-run', + checkId, + testKind, + }; + const report = await f.evidence.report(f.agent, { + ...f.input, + commandId: 'report-' + checkId, + evidence: submission, + }); + const view = await f.evidence.read(reviewer, { + articleId: 'guide', + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + }); + await f.evidence.decide( + reviewer, + { + commandId: 'confirm-' + checkId, + articleId: 'guide', + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }, + 'confirmed', + ); + await f.app.submitEvidence(f.agent, { + commandId: 'submit-' + checkId, + correlationId: 'test', + articleId: 'guide', + expectedGeneration: ( + await f.app.getDraft(owner, { articleId: 'guide' }) + ).generation, + evidence: submission, + receipt: report.receipt, + }); + } + await f.app.submitForReview(reviewer, { + commandId: 'review', + correlationId: 'test', + articleId: 'guide', + expectedGeneration: (await f.app.getDraft(owner, { articleId: 'guide' })) + .generation, + }); + const review = await f.app.getReview(reviewer, { articleId: 'guide' }); + await f.app.publishArticle(reviewer, { + commandId: 'publish', + correlationId: 'test', + articleId: 'guide', + expectedGeneration: review.generation, + review: review.review, + }); + const customer = resolveAccess( + { principalId: 'customer' }, + PEGMA_ACCESS_POLICY, + ); + const published = await f.app.getPublishedArticle(customer, { + articleId: 'guide', + }); + expect(published.revision).toBe(1); + const acceptedEvidence = await f.app.getEvidence(owner, { + articleId: 'guide', + }); + await f.evidence.reset(reviewer, { + commandId: 'retention-reset', + articleId: 'guide', + expectedLedgerEpoch: 1, + }); + await f.evidence.drain(reviewer, { articleId: 'guide', ledgerEpoch: 2 }); + expect(await f.app.getEvidence(owner, { articleId: 'guide' })).toEqual( + acceptedEvidence, + ); + expect( + await f.app.getPublishedArticle(customer, { articleId: 'guide' }), + ).toEqual(published); + f.setTime('2026-11-08T12:02:00.000Z'); + expect( + await f.app.getPublishedArticle(customer, { articleId: 'guide' }), + ).toEqual(published); + await f.app.updateDraft(owner, { + commandId: 'v2', + correlationId: 'test', + articleId: 'guide', + collectionId: 'guides', + expectedGeneration: (await f.app.getDraft(owner, { articleId: 'guide' })) + .generation, + draft: { ...f.draft, title: 'Unapproved v2' }, + }); + expect( + (await f.app.getDraft(owner, { articleId: 'guide' })).revision.number, + ).toBe(2); + expect( + (await f.app.getEvidence(owner, { articleId: 'guide' })).evidence, + ).toEqual([]); + expect( + await f.app.getPublishedArticle(customer, { articleId: 'guide' }), + ).toEqual(published); + const sources = await f.app.getProvenance(owner, { articleId: 'guide' }); + expect(sources.snapshot.references).toEqual([]); + expect(sources.publishedSnapshot?.references).toEqual([]); + }); + + it('bounds the physical report ledger before admitting another report', async () => { + const f = await fixture(); + for (let index = 1; index < 16; index += 1) + await f.evidence.report(f.agent, { + ...f.input, + commandId: 'report-' + (index + 1), + }); + const rows = f.reportRows(); + const before = await rows.list('guide'); + await expect( + f.evidence.report(f.agent, { ...f.input, commandId: 'report-over-cap' }), + ).rejects.toMatchObject({ code: 'report_capacity' }); + expect(await rows.list('guide')).toEqual(before); + expect( + (await f.evidence.list(reviewer, { articleId: 'guide' })).reports, + ).toHaveLength(16); + }); + + it('restores bounded capacity through a staff epoch reset without reviving stale commands', async () => { + const f = await fixture(); + for (let index = 1; index < 16; index += 1) + await f.evidence.report(f.agent, { + ...f.input, + commandId: 'fill-' + index, + }); + const reset = { + commandId: 'reset-1', + articleId: 'guide', + expectedLedgerEpoch: f.ack.ledgerEpoch, + }; + await expect(f.evidence.reset(f.agent, reset)).rejects.toMatchObject({ + status: 403, + }); + const started = await f.evidence.reset(reviewer, reset); + expect(started).toMatchObject({ + ledgerEpoch: 2, + status: 'resetting', + reportsRemaining: 0, + }); + await expect(f.evidence.report(f.agent, f.input)).rejects.toMatchObject({ + code: 'ledger_epoch_changed', + }); + await expect( + f.evidence.report(f.agent, { ...f.input, ledgerEpoch: 2 }), + ).rejects.toMatchObject({ code: 'ledger_resetting' }); + await expect( + f.evidence.decide(reviewer, f.confirm, 'confirmed'), + ).rejects.toMatchObject({ code: 'ledger_epoch_changed' }); + await expect( + f.evidence.status(f.agent, { + articleId: 'guide', + ledgerEpoch: 1, + reportId: f.ack.reportId, + }), + ).rejects.toMatchObject({ code: 'ledger_epoch_changed' }); + const rows = f.reportRows(); + let progress = started; + let calls = 0; + while (progress.status === 'resetting' && calls < 4) { + const before = (await rows.list('guide')).length; + progress = await f.evidence.drain(owner, { + articleId: 'guide', + ledgerEpoch: 2, + }); + expect(before - (await rows.list('guide')).length).toBeLessThanOrEqual( + 48, + ); + calls += 1; + } + expect(progress).toMatchObject({ + ledgerEpoch: 2, + status: 'active', + reportsRemaining: 16, + }); + expect(await rows.list('guide')).toHaveLength(1); + expect(await f.evidence.reset(reviewer, reset)).toEqual(progress); + const fresh = await f.evidence.report(f.agent, { + ...f.input, + ledgerEpoch: 2, + }); + const view = await f.evidence.read(reviewer, { + articleId: 'guide', + ledgerEpoch: 2, + reportId: fresh.reportId, + }); + await f.evidence.decide( + reviewer, + { + ...f.confirm, + commandId: 'confirm-fresh', + ledgerEpoch: 2, + reportId: fresh.reportId, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }, + 'confirmed', + ); + await expect( + f.accept(f.agent, f.submission, 'old-receipt'), + ).rejects.toThrow(); + await f.app.submitEvidence(f.agent, { + commandId: 'fresh-receipt', + correlationId: 'test', + expectedGeneration: 1, + articleId: 'guide', + evidence: f.submission, + receipt: fresh.receipt, + }); + expect( + (await f.app.getEvidence(owner, { articleId: 'guide' })).evidence[0] + ?.attestation.id, + ).toBe(fresh.receipt); + await f.evidence.reset(owner, { + commandId: 'reset-2', + articleId: 'guide', + expectedLedgerEpoch: 2, + }); + await f.evidence.drain(owner, { articleId: 'guide', ledgerEpoch: 3 }); + await expect(f.evidence.reset(reviewer, reset)).rejects.toMatchObject({ + code: 'ledger_epoch_changed', + }); + expect(await rows.list('guide')).toHaveLength(1); + }); + + it('allows a trusted human to reassess an unaccepted confirmation and invalidates its old receipt cycle', async () => { + const f = await fixture(); + await f.evidence.decide( + owner, + { ...f.confirm, commandId: 'owner-review' }, + 'confirmed', + ); + await expect(f.accept()).rejects.toThrow(); + const view = await f.evidence.read(reviewer, { + articleId: 'guide', + ledgerEpoch: 1, + reportId: f.ack.reportId, + }); + const pending = await f.evidence.decide( + reviewer, + { + ...f.confirm, + commandId: 'reassess', + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }, + 'pending', + ); + expect(pending.receipt).not.toBe(f.ack.receipt); + const updated = await f.evidence.read(reviewer, { + articleId: 'guide', + ledgerEpoch: 1, + reportId: f.ack.reportId, + }); + expect(updated.status).toBe('pending'); + expect(updated.confirmation).toBeNull(); + await f.evidence.decide( + reviewer, + { + ...f.confirm, + commandId: 'trusted-review', + expectedReportGeneration: updated.expectedReportGeneration, + reviewBindingHash: updated.reviewBindingHash, + }, + 'confirmed', + ); + await expect( + f.accept(f.agent, f.submission, 'old-cycle'), + ).rejects.toThrow(); + await f.app.submitEvidence(f.agent, { + commandId: 'new-cycle', + correlationId: 'test', + expectedGeneration: 1, + articleId: 'guide', + evidence: f.submission, + receipt: pending.receipt, + }); + expect( + (await f.app.getEvidence(owner, { articleId: 'guide' })).evidence[0] + ?.attestation.id, + ).toBe(pending.receipt); + }); + + it('allows an explicitly trusted Admin to human-review their own agent report', async () => { + const f = await fixture(); + await f.app.putGovernanceConfiguration(owner, { + commandId: 'trust-owner', + correlationId: 'test', + expectedGeneration: 2, + collectionId: 'guides', + configuration: { + validationPolicy: { id: 'guide-policy', version: 1 }, + expectedStagingBuildId: 'staging-1', + trustedAttesterIds: [owner.principalId], + }, + }); + const report = await f.evidence.report(f.agent, { + ...f.input, + commandId: 'same-owner-report', + }); + const view = await f.evidence.read(owner, { + articleId: 'guide', + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + }); + await f.evidence.decide( + owner, + { + commandId: 'same-owner-confirm', + articleId: 'guide', + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }, + 'confirmed', + ); + await f.app.submitEvidence(f.agent, { + commandId: 'same-owner-accept', + correlationId: 'test', + expectedGeneration: 1, + articleId: 'guide', + evidence: f.submission, + receipt: report.receipt, + }); + expect( + (await f.app.getEvidence(owner, { articleId: 'guide' })).evidence[0] + ?.attestation.verifiedBy, + ).toBe(owner.principalId); + }); +}); diff --git a/worker/src/knowledge-evidence.ts b/worker/src/knowledge-evidence.ts new file mode 100644 index 0000000..c7b87e5 --- /dev/null +++ b/worker/src/knowledge-evidence.ts @@ -0,0 +1,232 @@ +import type { AccessContext } from '@pegma/authorization-core'; +import { + createKnowledgeEvidenceReports, + KnowledgeEvidenceReportsError, + KnowledgeEvidenceReportsUnavailableError, + type KnowledgeEvidenceReports, + type KnowledgeEvidenceReportsOptions, +} from '@pegma/knowledge-base-application'; +import { ApiError, isPlainObject } from './api-auth'; +import { KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION } from './support-access'; + +export type { + KnowledgeEvidenceContext, + KnowledgeReportAcknowledgement, + KnowledgeReportLedgerState, + KnowledgeReportSummary, + KnowledgeReportView, + KnowledgeTestReport, +} from '@pegma/knowledge-base-application'; + +export type KnowledgeEvidenceOptions = Omit< + KnowledgeEvidenceReportsOptions, + 'collectionName' | 'storageLayout' | 'confirmationPermission' +>; + +type BrowserOperation = Method extends ( + ...args: infer Arguments +) => infer Result + ? Arguments extends [AccessContext, unknown, ...infer Rest] + ? (access: AccessContext, input: unknown, ...rest: Rest) => Result + : never + : never; + +/** The public factory validates the browser's untrusted JSON inputs. */ +export type KnowledgeEvidenceService = { + readonly [Name in keyof KnowledgeEvidenceReports]: Name extends 'verifier' + ? KnowledgeEvidenceReports[Name] + : BrowserOperation; +} & { + /** Native component errors remain recognizable to the actual MCP dispatcher. */ + readonly agentReports: Pick< + KnowledgeEvidenceReports, + 'report' | 'ledger' | 'status' | 'query' + >; +}; + +/** Safe host diagnostic; private records and underlying errors are never exposed. */ +export class KnowledgeLedgerError extends Error { + readonly name = 'KnowledgeLedgerError'; + constructor(readonly stage: string) { + super('Knowledge report ledger is unavailable.'); + } +} + +/** Carry only an already-controlled host refusal through the shared context port. */ +class HostContextError extends KnowledgeEvidenceReportsError { + constructor(readonly failure: ApiError) { + super('report_changed'); + } +} + +function hostError(error: unknown): Error { + if (error instanceof HostContextError) return error.failure; + if (error instanceof KnowledgeEvidenceReportsUnavailableError) + return new KnowledgeLedgerError(error.stage); + if (error instanceof KnowledgeEvidenceReportsError) { + switch (error.code) { + case 'invalid_request': + return new ApiError(400, error.code); + case 'report_too_large': + return new ApiError(413, error.code); + case 'forbidden': + return new ApiError(403, error.code); + case 'report_not_found': + return new ApiError(404, error.code); + case 'report_target_unavailable': + return new ApiError(404, 'not_found'); + case 'command_conflict': + case 'report_capacity': + case 'report_changed': + case 'report_not_verifiable': + case 'ledger_epoch_changed': + case 'ledger_resetting': + case 'ledger_changed': + case 'ledger_epoch_exhausted': + return new ApiError(409, error.code); + case 'invalid_configuration': + return new KnowledgeLedgerError('configuration'); + } + } + return new KnowledgeLedgerError('operation'); +} + +async function hostOperation(operation: () => Promise): Promise { + try { + return await operation(); + } catch (error) { + throw hostError(error); + } +} + +/** Preserve this host's existing D1 namespace, raw keys, payloads and receipts. */ +export function createKnowledgeEvidenceService( + options: KnowledgeEvidenceOptions, +): KnowledgeEvidenceService { + let reports: KnowledgeEvidenceReports; + try { + reports = createKnowledgeEvidenceReports({ + ...options, + collectionName: 'pegma-dev.knowledge-evidence.v1', + storageLayout: 'legacy-raw-v1', + confirmationPermission: KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, + async readContext(access, articleId) { + try { + return await options.readContext(access, articleId); + } catch (error) { + if (error instanceof ApiError) throw new HostContextError(error); + throw error; + } + }, + }); + } catch (error) { + throw hostError(error); + } + // These assertions cross the untrusted JSON/type boundary only. The public + // factory performs all input validation, authorization and durable operations. + return Object.freeze({ + verifier: reports.verifier, + agentReports: Object.freeze({ + report: reports.report, + ledger: reports.ledger, + status: reports.status, + query: reports.query, + }), + query: (access, input) => + hostOperation(() => + reports.query( + access, + input as Parameters[1], + ), + ), + report: (access, input) => + hostOperation(() => + reports.report( + access, + input as Parameters[1], + ), + ), + status: (access, input) => + hostOperation(() => + reports.status( + access, + input as Parameters[1], + ), + ), + read: (access, input) => + hostOperation(() => + reports.read( + access, + input as Parameters[1], + ), + ), + list: (access, input) => + hostOperation(() => + reports.list( + access, + input as Parameters[1], + ), + ), + ledger: (access, input) => + hostOperation(() => + reports.ledger( + access, + input as Parameters[1], + ), + ), + decide: (access, input, decision) => + hostOperation(() => + reports.decide( + access, + input as Parameters[1], + decision, + ), + ), + reset: (access, input) => + hostOperation(() => + reports.reset( + access, + input as Parameters[1], + ), + ), + drain: (access, input) => + hostOperation(() => + reports.drain( + access, + input as Parameters[1], + ), + ), + }); +} + +function canonical(value: unknown): string { + if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']'; + if (isPlainObject(value)) + return ( + '{' + + Object.keys(value) + .sort() + .map((key) => JSON.stringify(key) + ':' + canonical(value[key])) + .join(',') + + '}' + ); + if ( + value === null || + typeof value === 'string' || + typeof value === 'boolean' || + (typeof value === 'number' && Number.isFinite(value)) + ) + return JSON.stringify(value); + throw new TypeError('Unsupported knowledge evidence value.'); +} + +/** Shared host fingerprinting, independent of the report service's storage. */ +export async function knowledgeDigest(value: unknown): Promise { + const bytes = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(canonical(value)), + ); + return [...new Uint8Array(bytes)] + .map((byte) => byte.toString(16).padStart(2, '0')) + .join(''); +} diff --git a/worker/src/knowledge-host.test.ts b/worker/src/knowledge-host.test.ts new file mode 100644 index 0000000..4ee9ec6 --- /dev/null +++ b/worker/src/knowledge-host.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from 'vitest'; +import { handleKnowledgeRequest, isKnowledgeRequest } from './knowledge-host'; + +describe('knowledge activation boundary', () => { + it('refuses disabled requests before accessing Identity or D1', async () => { + const database = vi.fn((): D1Database => { + throw new Error('D1 must not be accessed'); + }); + const logger = { log: vi.fn() }; + const env = { + PEGMA_KNOWLEDGE_ENABLED: 'false', + PEGMA_AGENT_CLIENTS_JSON: '[]', + IDENTITY_EMAIL_CODE_SECRET_BASE64: '', + IDENTITY_EMAIL_FROM: '', + IDENTITY_EMAIL_ENABLED: 'false', + get IDENTITY_DB(): D1Database { + return database(); + }, + }; + for (const path of [ + '/.well-known/oauth-authorization-server', + '/.well-known/oauth-protected-resource/api/knowledge/mcp', + '/api/agent-access/authorize', + '/api/agent-access/token', + '/api/knowledge/mcp', + '/api/knowledge/reports', + '/api/staff/knowledge/command', + ]) { + const response = await handleKnowledgeRequest( + new Request(`https://pegma.dev${path}`), + env, + logger, + ); + expect(response.status).toBe(503); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ error: 'knowledge_disabled' }); + } + expect(database).not.toHaveBeenCalled(); + expect(logger.log).not.toHaveBeenCalled(); + }); + + it('keeps existing catalog, identity, support and unrelated discovery outside its route boundary', () => { + for (const path of [ + '/api/mcp', + '/api/identity/account', + '/api/support/tickets', + '/api/admin/roles', + '/api/releases', + '/.well-known/security.txt', + ]) { + expect(isKnowledgeRequest(path)).toBe(false); + } + }); +}); diff --git a/worker/src/knowledge-host.ts b/worker/src/knowledge-host.ts new file mode 100644 index 0000000..6b92f26 --- /dev/null +++ b/worker/src/knowledge-host.ts @@ -0,0 +1,129 @@ +import { createRoleStore } from '@pegma/authorization-storage'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { systemClock, type Logger } from '@pegma/spine'; +import { + createProductionIdentityRuntime, + type IdentityRuntimeEnv, +} from './identity-runtime'; +import { + createAgentAccessRuntime, + readAgentClients, + type AgentAccessRuntime, +} from './agent-access-runtime'; +import { createKnowledgeRuntime } from './knowledge-runtime'; +import { AUTHORIZATION_APPLICATION_ID } from './support-access'; +import { knowledgeAdmissionCount } from './knowledge-admission'; + +type KnowledgeConfiguration = { + readonly [ + Key in keyof Pick< + Env, + | 'PEGMA_KNOWLEDGE_ENABLED' + | 'PEGMA_AGENT_CLIENTS_JSON' + | 'PEGMA_KNOWLEDGE_BROWSER_LIMIT' + | 'PEGMA_AGENT_RESOURCE_LIMIT' + > + ]?: string; +}; + +const metadataPaths = new Set([ + '/.well-known/oauth-authorization-server', + '/.well-known/oauth-protected-resource/api/knowledge/mcp', +]); + +export function isKnowledgeRequest(path: string): boolean { + return ( + metadataPaths.has(path) || + path.startsWith('/api/agent-access/') || + path.startsWith('/api/knowledge/') || + path.startsWith('/api/staff/knowledge/') + ); +} + +function unavailable(error: string): Response { + return Response.json( + { error }, + { + status: 503, + headers: { + 'Cache-Control': 'no-store', + 'Referrer-Policy': 'no-referrer', + 'X-Content-Type-Options': 'nosniff', + }, + }, + ); +} + +/** One explicit composition over this site's existing Identity and D1 store. */ +export async function handleKnowledgeRequest( + request: Request, + env: IdentityRuntimeEnv & KnowledgeConfiguration, + logger: Logger, +): Promise { + if (env.PEGMA_KNOWLEDGE_ENABLED !== 'true') + return unavailable('knowledge_disabled'); + try { + const identity = createProductionIdentityRuntime(env, logger, 512); + const options = { + store: identity.store, + clock: systemClock, + sessions: identity.sessions, + identity: identity.identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + roleStore: createRoleStore(identity.store, AUTHORIZATION_APPLICATION_ID), + logger, + }; + let agentAccess: AgentAccessRuntime | null = null; + try { + agentAccess = createAgentAccessRuntime({ + ...options, + clients: readAgentClients(env.PEGMA_AGENT_CLIENTS_JSON), + resourceLimitCount: knowledgeAdmissionCount( + env.PEGMA_AGENT_RESOURCE_LIMIT, + 300, + ), + }); + } catch (error) { + // An invalid optional agent registration must not disable browser guides + // or human review. The issuer and bearer paths remain unavailable. + logger.log('error', 'agent_access.configuration_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + const path = new URL(request.url).pathname; + if (metadataPaths.has(path) || path.startsWith('/api/agent-access/')) { + if (agentAccess === null) + return unavailable('agent_access_not_configured'); + const response = + (await agentAccess.protocol.handle(request)) ?? + (await agentAccess.api(request)); + return ( + response ?? + new Response('Not Found', { + status: 404, + headers: { 'Cache-Control': 'no-store' }, + }) + ); + } + return ( + (await createKnowledgeRuntime({ + ...options, + agentAccess, + isEnabled: () => env.PEGMA_KNOWLEDGE_ENABLED === 'true', + browserLimitCount: knowledgeAdmissionCount( + env.PEGMA_KNOWLEDGE_BROWSER_LIMIT, + 120, + ), + }).handle(request)) ?? + new Response('Not Found', { + status: 404, + headers: { 'Cache-Control': 'no-store' }, + }) + ); + } catch (error) { + logger.log('error', 'knowledge.runtime_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + return unavailable('knowledge_unavailable'); + } +} diff --git a/worker/src/knowledge-integration-scenarios.ts b/worker/src/knowledge-integration-scenarios.ts new file mode 100644 index 0000000..d474c3f --- /dev/null +++ b/worker/src/knowledge-integration-scenarios.ts @@ -0,0 +1,2375 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { resolveAccess } from '@pegma/authorization-core'; +import type { + ApprovalView, + PublicClient, + TokenResult, +} from '@pegma/agent-access'; +import { + knowledgeAgentScopes, + knowledgeAgentToolNames, +} from '@pegma/knowledge-base-mcp'; +import type { + ArticleDraft, + EvidenceSubmission, +} from '@pegma/knowledge-base-core'; +import { + articleKinds, + knowledgePermissions, +} from '@pegma/knowledge-base-contracts'; +import { + KnowledgeBaseAuthorizationError, + retrievalRecords, + type ArticleAcknowledgement, + type CommandResult, + type DraftArticleDto, + type CollectionAcknowledgement, + type CollectionPolicyPreviewDto, + type ReviewDto, + type EvidenceDto, + type ValidationRequirementsDto, +} from '@pegma/knowledge-base-application'; +import { createSessionStore } from '@pegma/sessions'; +import type { + CollectionDefinition, + CollectionStore, + ScanOptions, + Store, +} from '@pegma/storage-core'; +import { type IsoTimestamp, type Logger, type PrincipalId } from '@pegma/spine'; +import { describe, expect, it, vi } from 'vitest'; +import { createAgentAccessRuntime } from './agent-access-runtime'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import type { IdentityPort, IdentityUser } from './identity-contracts'; +import { + ADMIN_ROLE, + APPLICATION_SCOPE, + AUTHORIZATION_APPLICATION_ID, + KNOWLEDGE_ROLE, + SUPPORT_ROLE, +} from './support-access'; +import { createSupportApi } from './support-api'; +import { createSupportRuntime } from './support-desk'; +import { createKnowledgeRuntime } from './knowledge-runtime'; +import { createKnowledgeRetrievalMaintenance } from './knowledge-retrieval-maintenance'; +import { createKnowledgeRetrievalReady } from './knowledge-retrieval-ready'; +import type { + KnowledgeReportAcknowledgement, + KnowledgeReportLedgerState, + KnowledgeReportView, +} from './knowledge-evidence'; + +const owner = 'integration-agent-owner' as PrincipalId; +const otherOwner = 'integration-other-agent-owner' as PrincipalId; +const reviewer = 'integration-report-reviewer' as PrincipalId; +const member = 'integration-member' as PrincipalId; +const runner = 'integration-test-runner' as PrincipalId; +const resource = 'https://pegma.dev/api/knowledge/mcp'; +const scopes = Object.values(knowledgeAgentScopes); +type EvidenceCheck = Pick< + ValidationRequirementsDto['checks'][number], + 'id' | 'testKind' +>; +const workflowCheck: EvidenceCheck = { + id: 'walkthrough-workflow', + testKind: 'workflow', +}; +const client: PublicClient = { + clientId: 'synthetic-knowledge-client', + name: 'Synthetic integration client', + redirectUris: ['https://client.example.test/callback'], + allowedScopes: scopes, + grantTypes: ['device_code', 'authorization_code'], +}; + +interface BrowserSession { + readonly cookie: string; + readonly csrfToken: string; +} + +function user(principalId: PrincipalId): IdentityUser { + return { + principalId, + email: `${principalId}@example.test`, + emailVerified: true, + status: 'active', + createdAt: '2026-11-08T12:00:00.000Z', + updatedAt: '2026-11-08T12:00:00.000Z', + }; +} + +function browserRequest( + path: string, + auth: BrowserSession, + body?: unknown, + method = 'POST', +): Request { + return new Request(`${IDENTITY_ISSUER}${path}`, { + method, + headers: { + Cookie: auth.cookie, + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + 'X-Pegma-CSRF': auth.csrfToken, + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); +} + +function formRequest(path: string, values: Record): Request { + return new Request(`${IDENTITY_ISSUER}${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams(values), + }); +} + +async function integrationFixture(store: Store, loggerOverride?: Logger) { + let now = Date.parse('2026-11-08T12:00:00.000Z'); + const clock = { now: () => new Date(now).toISOString() as IsoTimestamp }; + const logger: Logger = loggerOverride ?? { log: vi.fn() }; + const sessions = createSessionStore(store, { logger, clock }); + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + const users = new Map( + [owner, otherOwner, reviewer, member].map((id) => [id, user(id)] as const), + ); + // Identity is the existing external authentication boundary. Sessions, + // audited role assignments, OAuth grants and KB state use real packages. + const identity: IdentityPort = { + claimsFor: vi.fn(async (id: PrincipalId) => { + const current = users.get(id); + if (current === undefined) + throw Object.assign(new Error('missing'), { code: 'not_found' }); + if (current.status !== 'active' || !current.emailVerified) + throw Object.assign(new Error('unverified'), { code: 'invalid_state' }); + return { + issuer: IDENTITY_ISSUER, + subject: id, + emailVerified: true as const, + }; + }), + getUser: vi.fn(async (id: PrincipalId) => users.get(id) ?? null), + findUserByEmail: vi.fn(async () => null), + beginPasskeyRegistration: vi.fn(), + finishPasskeyRegistration: vi.fn(), + beginPasskeyAuthentication: vi.fn(), + finishPasskeyAuthentication: vi.fn(), + listPasskeys: vi.fn(async () => []), + removePasskey: vi.fn(async () => true), + }; + async function grant( + id: PrincipalId, + role: + | typeof ADMIN_ROLE + | typeof SUPPORT_ROLE + | typeof KNOWLEDGE_ROLE = ADMIN_ROLE, + ) { + const assignmentId = `${role}-${id}`; + const result = await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: assignmentId, + principalId: id, + role, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-test-setup' }, + grantedAtEpochMs: now, + status: 'active', + }, + auditEventId: `grant-${assignmentId}`, + }); + expect(result.status).toBe('granted'); + return assignmentId; + } + await grant(owner); + await grant(otherOwner); + await grant(reviewer, KNOWLEDGE_ROLE); + await grant(member, SUPPORT_ROLE); + const configuredAgents = createAgentAccessRuntime({ + store, + sessions, + identity, + roleStore, + logger, + clock, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + clients: [client], + }); + if (configuredAgents === null) + throw new Error( + 'Synthetic registered client must enable the integration runtime.', + ); + const agents = configuredAgents; + const knowledge = createKnowledgeRuntime({ + store, + clock, + sessions, + identity, + roleStore, + logger, + agentAccess: agents, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }); + async function knowledgeRequest(request: Request): Promise { + const response = await knowledge.handle(request); + if (response === null) + throw new Error( + `No knowledge route for ${new URL(request.url).pathname}`, + ); + return response; + } + function staff(operation: string, input: unknown, auth = reviewerAuth) { + return knowledgeRequest( + browserRequest('/api/staff/knowledge/command', auth, { + operation, + input, + }), + ); + } + async function staffValue( + operation: string, + input: unknown, + auth = reviewerAuth, + ): Promise { + const response = await staff(operation, input, auth); + expect(response.status, operation).toBe(200); + return (await response.json()) as T; + } + function adminValue(operation: string, input: unknown): Promise { + return staffValue(operation, input, ownerAuth); + } + function agent(token: string, operation: string, input: unknown) { + return knowledgeRequest( + new Request('https://pegma.dev/api/knowledge/v1', { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ apiVersion: '1', operation, input }), + }), + ); + } + function mcp(token: string, method: string, params: unknown) { + return knowledgeRequest( + new Request(resource, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + 'MCP-Protocol-Version': '2025-06-18', + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), + }), + ); + } + function report(token: string, input: unknown) { + return knowledgeRequest( + new Request('https://pegma.dev/api/knowledge/reports', { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(input), + }), + ); + } + function reportLedger(token: string, articleId: string) { + return knowledgeRequest( + new Request( + `https://pegma.dev/api/knowledge/reports?${new URLSearchParams({ articleId })}`, + { + headers: { Authorization: `Bearer ${token}` }, + }, + ), + ); + } + function reportStatus( + token: string, + articleId: string, + ledgerEpoch: number, + reportId: string, + ) { + return knowledgeRequest( + new Request( + `https://pegma.dev/api/knowledge/reports?${new URLSearchParams({ articleId, ledgerEpoch: String(ledgerEpoch), reportId })}`, + { + headers: { Authorization: `Bearer ${token}` }, + }, + ), + ); + } + async function configure() { + const stateResponse = await knowledgeRequest( + browserRequest( + '/api/staff/knowledge/state', + reviewerAuth, + undefined, + 'GET', + ), + ); + expect(stateResponse.status).toBe(200); + const state = (await stateResponse.json()) as { attesterId: PrincipalId }; + const collection = await adminValue< + CommandResult + >('createCollection', { + commandId: 'create-integration-collection', + correlationId: 'integration', + expectedGeneration: 0, + collectionId: 'integration-guides', + name: 'Synthetic integration guides', + }); + await adminValue('putValidationPolicy', { + commandId: 'create-integration-validation', + correlationId: 'integration', + expectedGeneration: 0, + policy: { + id: 'integration-validation', + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: `${kind}-content`, + kind, + testKind: 'content', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: [runner], + })), + { + id: workflowCheck.id, + kind: 'walkthrough', + testKind: workflowCheck.testKind, + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: [runner], + }, + ], + }, + }); + await adminValue('putGovernanceConfiguration', { + commandId: 'configure-integration-governance', + correlationId: 'integration', + expectedGeneration: collection.value.generation, + collectionId: 'integration-guides', + configuration: { + validationPolicy: { id: 'integration-validation', version: 1 }, + expectedStagingBuildId: 'integration-build-1', + trustedAttesterIds: [state.attesterId], + }, + }); + const preview = await adminValue( + 'previewCollectionPolicy', + { + collectionId: 'integration-guides', + uses: { + portal: { + enabled: true, + audience: { + kind: 'permission', + permission: 'knowledge.article.read', + }, + }, + bot: { enabled: false }, + }, + }, + ); + await adminValue('updateCollectionPolicy', { + commandId: 'enable-protected-integration-guides', + correlationId: 'integration', + expectedGeneration: preview.generation, + collectionId: 'integration-guides', + preview: preview.preview, + }); + } + async function session(id: PrincipalId): Promise { + const sessionId = `${crypto.randomUUID().replaceAll('-', '')}${'s'.repeat(11)}`; + const csrfToken = 'c'.repeat(43); + await sessions.create(sessionId, { + principalId: id, + data: JSON.stringify({ + version: 1, + csrfToken, + issuer: IDENTITY_ISSUER, + subject: id, + }), + }); + return { cookie: `${SESSION_COOKIE}=${sessionId}`, csrfToken }; + } + async function agentRequest(request: Request): Promise { + const protocol = await agents.protocol.handle(request); + if (protocol !== null) return protocol; + const response = await agents.api(request); + if (response === null) + throw new Error(`No agent route for ${new URL(request.url).pathname}`); + return response; + } + async function device(auth = ownerAuth) { + const begun = await agentRequest( + formRequest('/api/agent-access/device-authorizations', { + client_id: client.clientId, + resource, + scope: scopes.join(' '), + }), + ); + expect(begun.status).toBe(200); + const request = (await begun.json()) as { + user_code: string; + device_code: string; + interval: number; + }; + const viewed = await agentRequest( + browserRequest( + `/api/agent-access/approval?user_code=${encodeURIComponent(request.user_code)}`, + auth, + undefined, + 'GET', + ), + ); + expect(viewed.status).toBe(200); + const approval = (await viewed.json()) as ApprovalView; + expect(approval.requestedScopes.map((scope) => scope.name)).toEqual(scopes); + const approved = await agentRequest( + browserRequest('/api/agent-access/approval', auth, { + requestId: approval.requestId, + userCode: request.user_code, + decision: 'approve', + approvedScopes: scopes, + }), + ); + expect(approved.status).toBe(200); + expect(await approved.json()).toEqual({ + flow: 'device_code', + approved: true, + }); + now += request.interval * 1000; + const issued = await agentRequest( + formRequest('/api/agent-access/token', { + grant_type: 'urn:ietf:params:oauth:grant-type:device_code', + client_id: client.clientId, + resource, + device_code: request.device_code, + }), + ); + expect(issued.status).toBe(200); + const token = (await issued.json()) as TokenResult; + expect(token.scope.split(' ')).toEqual(scopes); + return { token, approval }; + } + async function pkce() { + const verifier = 'p'.repeat(64); + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(verifier), + ); + const challenge = btoa(String.fromCharCode(...new Uint8Array(digest))) + .replaceAll('+', '-') + .replaceAll('/', '_') + .replace(/=+$/, ''); + const values = new URLSearchParams({ + response_type: 'code', + client_id: client.clientId, + redirect_uri: client.redirectUris[0]!, + resource, + scope: scopes.join(' '), + code_challenge: challenge, + code_challenge_method: 'S256', + state: 'synthetic-client-state', + }); + const begun = await agentRequest( + browserRequest( + `/api/agent-access/authorize?${values}`, + ownerAuth, + undefined, + 'GET', + ), + ); + expect(begun.status).toBe(303); + const approvalUrl = new URL(begun.headers.get('Location')!); + const requestId = approvalUrl.searchParams.get('request_id'); + expect(requestId).not.toBeNull(); + const viewed = await agentRequest( + browserRequest( + `/api/agent-access/approval?request_id=${encodeURIComponent(requestId!)}`, + ownerAuth, + undefined, + 'GET', + ), + ); + const approval = (await viewed.json()) as ApprovalView; + expect(approval.requestedScopes.map((scope) => scope.name)).toEqual(scopes); + const approved = await agentRequest( + browserRequest('/api/agent-access/approval', ownerAuth, { + requestId: approval.requestId, + decision: 'approve', + approvedScopes: scopes, + }), + ); + expect(approved.status).toBe(200); + const consent = (await approved.json()) as { + flow: 'authorization_code'; + redirectUri: string; + }; + const redirect = new URL(consent.redirectUri); + expect(redirect.origin + redirect.pathname).toBe(client.redirectUris[0]); + expect(redirect.searchParams.get('state')).toBe('synthetic-client-state'); + expect(redirect.searchParams.get('iss')).toBe(IDENTITY_ISSUER); + const exchange = (codeVerifier: string) => + agentRequest( + formRequest('/api/agent-access/token', { + grant_type: 'authorization_code', + client_id: client.clientId, + resource, + code: redirect.searchParams.get('code')!, + redirect_uri: client.redirectUris[0]!, + code_verifier: codeVerifier, + }), + ); + const rejected = await exchange('incorrect-verifier'.repeat(4)); + expect(rejected.status).toBe(400); + expect(await rejected.json()).toMatchObject({ error: 'invalid_grant' }); + const issued = await exchange(verifier); + expect(issued.status).toBe(200); + const token = (await issued.json()) as TokenResult; + expect(token.scope.split(' ')).toEqual(scopes); + expect((await exchange(verifier)).status).toBe(400); + return { token, approval }; + } + const ownerAuth = await session(owner); + const otherOwnerAuth = await session(otherOwner); + const reviewerAuth = await session(reviewer); + const memberAuth = await session(member); + return { + store, + clock, + logger, + sessions, + roleStore, + users, + identity, + agents, + knowledge, + ownerAuth, + otherOwnerAuth, + reviewerAuth, + memberAuth, + agentRequest, + knowledgeRequest, + staff, + staffValue, + agent, + mcp, + report, + reportLedger, + reportStatus, + configure, + grant, + device, + pkce, + advance: (milliseconds: number) => { + now += milliseconds; + }, + }; +} + +function draft(overrides: Partial = {}): ArticleDraft { + return { + kind: 'walkthrough', + title: 'Run the synthetic export', + summary: 'A synthetic staging walkthrough.', + content: { + format: 'markdown', + text: '1. Open the staging fixture.\n2. Export the synthetic guide.\n3. Verify its contents.', + }, + tags: ['integration'], + applicability: { + productId: 'pegma-integration', + productVersion: '1.0.0', + buildId: 'integration-build-1', + }, + ...overrides, + }; +} + +async function createAgentDraft( + f: Awaited>, + token: string, +) { + await f.configure(); + const created = await f.agent(token, 'createDraft', { + commandId: 'agent-create-draft', + correlationId: 'integration', + expectedGeneration: 0, + articleId: 'integration-article', + collectionId: 'integration-guides', + draft: draft(), + }); + expect(created.status).toBe(200); + const response = (await created.json()) as { + result: CommandResult; + }; + expect(response.result.value.articleRevision).toBe(1); + return response.result.value; +} + +/** Faults only real derived writes; all authoritative storage remains real. */ +function observeRetrieval(backing: Store) { + const state = { failProjectionWrites: true }; + const scans: ScanOptions[] = []; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const target = backing.collection(definition); + return { + ...target, + async scan(options) { + if (definition.name === 'knowledge-base.records.v1') + scans.push({ ...options }); + return target.scan(options); + }, + async transact(partition, actions) { + if ( + definition.name === retrievalRecords.name && + state.failProjectionWrites + ) + throw new Error('Synthetic derived-store outage.'); + return target.transact(partition, actions); + }, + }; + }, + }; + return { store, scans, state }; +} + +async function publishSearchGuide( + f: Awaited>, + token: string, +) { + const created = await createAgentDraft(f, token); + const requirements = await f.staffValue( + 'getValidationRequirements', + { + collectionId: 'integration-guides', + kind: 'walkthrough', + }, + ); + let generation = created.generation; + for (const check of requirements.checks) { + const report = await confirmedReport( + f, + token, + created.id, + check, + 'search-publication', + ); + const response = await f.agent(token, 'submitEvidence', { + commandId: `search-evidence:${check.id}`, + correlationId: 'integration', + expectedGeneration: report.article.generation, + articleId: created.id, + evidence: report.evidence, + receipt: report.report.receipt, + }); + expect(response.status).toBe(200); + generation = ( + (await response.json()) as { + result: CommandResult; + } + ).result.value.generation; + } + const submitted = await f.staffValue>( + 'submitForReview', + { + commandId: 'submit-search-guide', + correlationId: 'integration', + expectedGeneration: generation, + articleId: created.id, + }, + ); + const review = await f.staffValue('getReview', { + articleId: created.id, + }); + const published = await f.staffValue>( + 'publishArticle', + { + commandId: 'publish-search-guide', + correlationId: 'integration', + expectedGeneration: submitted.value.generation, + articleId: created.id, + review: review.review, + }, + ); + return { created, published }; +} + +function evidenceFor( + article: DraftArticleDto, + executedAt: IsoTimestamp, + check: EvidenceCheck = workflowCheck, +): EvidenceSubmission { + return { + id: `integration-evidence:${check.id}`, + articleId: article.articleId, + articleRevision: article.revision.number, + contentHash: article.revision.contentHash, + validationPolicy: article.revision.validationPolicy, + checkId: check.id, + testKind: check.testKind, + applicability: article.revision.applicability, + stagingBuildId: 'integration-build-1', + steps: + check.testKind === 'content' + ? [ + 'Read the full synthetic guide', + 'Check the stated prerequisites and steps', + 'Confirm the guide contains no private report data', + ] + : [ + 'Open the staging fixture', + 'Export the guide', + 'Compare the synthetic output', + ], + result: 'passed', + executedAt, + runnerId: runner, + artifacts: [{ id: 'synthetic-output-report', hash: 'a'.repeat(64) }], + }; +} + +async function submitReport( + f: Awaited>, + token: string, + articleId: string, + check: EvidenceCheck = workflowCheck, + sequence = 'initial', +) { + const read = await f.agent(token, 'getDraft', { articleId }); + const article = ((await read.json()) as { result: DraftArticleDto }).result; + const evidence = evidenceFor(article, f.clock.now(), check); + const ledgerResponse = await f.reportLedger(token, articleId); + expect(ledgerResponse.status).toBe(200); + const ledger = (await ledgerResponse.json()) as KnowledgeReportLedgerState; + expect(ledger.status).toBe('active'); + const reportCommand = { + commandId: `submit-synthetic-report:${check.id}:${sequence}`, + articleId, + ledgerEpoch: ledger.ledgerEpoch, + evidence, + report: { + summary: `Synthetic ${check.testKind} check passed`, + details: + 'The independent fixture report records the steps, output comparison and synthetic artifact. This is test data.', + }, + }; + const submitted = await f.report(token, reportCommand); + expect(submitted.status).toBe(200); + const report = (await submitted.json()) as KnowledgeReportAcknowledgement; + expect(report.ledgerEpoch).toBe(ledger.ledgerEpoch); + const viewed = await f.staffValue('reportRead', { + articleId, + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + }); + expect(viewed.submittedBy).toBe(owner); + expect(viewed.evidence).toEqual(evidence); + expect(viewed.articleId).toBe(articleId); + const confirm = { + commandId: `confirm-synthetic-report:${check.id}:${sequence}`, + articleId, + ledgerEpoch: report.ledgerEpoch, + reportId: report.reportId, + expectedReportGeneration: viewed.expectedReportGeneration, + reviewBindingHash: viewed.reviewBindingHash, + }; + return { article, evidence, report, reportCommand, viewed, confirm }; +} + +async function confirmedReport( + f: Awaited>, + token: string, + articleId: string, + check: EvidenceCheck = workflowCheck, + sequence = 'initial', +) { + const prepared = await submitReport(f, token, articleId, check, sequence); + const confirmation = await f.staff('confirmReport', prepared.confirm); + expect(confirmation.status).toBe(200); + const reviewed = await f.staffValue('reportRead', { + articleId, + ledgerEpoch: prepared.report.ledgerEpoch, + reportId: prepared.report.reportId, + }); + expect(reviewed.status).toBe('confirmed'); + return prepared; +} + +async function drainReportLedger( + f: Awaited>, + state: KnowledgeReportLedgerState, +) { + let current = state; + let calls = 0; + while (current.status === 'resetting' && calls < 4) { + current = await f.staffValue('drainReports', { + articleId: current.articleId, + ledgerEpoch: current.ledgerEpoch, + }); + calls += 1; + } + expect(current.status).toBe('active'); + expect(calls).toBeGreaterThan(0); + expect(calls).toBeLessThanOrEqual(4); + return current; +} + +export interface KnowledgeIntegrationScenarioOptions { + readonly name: string; + readonly createStore: () => Store | Promise; +} + +/** The same real-package workflow assertions run against each host Store. */ +export function registerKnowledgeIntegrationScenarios( + options: KnowledgeIntegrationScenarioOptions, +): void { + describe(options.name, () => { + const fixture = async () => integrationFixture(await options.createStore()); + it('completes existing-session device consent with exactly three restricted scopes', async () => { + const f = await fixture(); + const { token, approval } = await f.device(); + const delegated = await f.agents.service.authenticate({ + token: token.access_token, + resource, + }); + expect(delegated.access.principalId).toBe(owner); + expect(delegated.access.roles).toEqual([]); + expect(delegated.access.entitlements).toEqual([]); + expect(delegated.access.permissions).toEqual(scopes); + expect(approval.flow).toBe('device_code'); + const grant = await f.agentRequest( + browserRequest( + `/api/agent-access/grants/${delegated.grantId}`, + f.ownerAuth, + undefined, + 'GET', + ), + ); + expect(grant.status).toBe(200); + expect(await grant.json()).toMatchObject({ + ownerId: owner, + status: 'active', + resource, + }); + }); + + it('completes actual PKCE consent, binds the verifier, and consumes the authorization code once', async () => { + const f = await fixture(); + const { token } = await f.pkce(); + const delegated = await f.agents.service.authenticate({ + token: token.access_token, + resource, + }); + expect(delegated.scopes).toEqual(scopes); + expect(delegated.access.permissions).toEqual(scopes); + }); + + it.each(['device', 'pkce'] as const)( + 'uses a real %s grant to create and read HTTP drafts and update the same draft through MCP', + async (flow) => { + const f = await fixture(); + const { token } = await f[flow](); + const created = await createAgentDraft(f, token.access_token); + const initialized = await f.mcp(token.access_token, 'initialize', { + protocolVersion: '2025-06-18', + capabilities: {}, + clientInfo: { name: 'synthetic-integration', version: '1' }, + }); + expect(initialized.status).toBe(200); + expect(await initialized.json()).toMatchObject({ + result: { capabilities: { tools: {} } }, + }); + const tools = await f.mcp(token.access_token, 'tools/list', {}); + expect(tools.status).toBe(200); + const listed = (await tools.json()) as { + result: { tools: { name: string }[] }; + }; + expect(listed.result.tools.map((tool) => tool.name)).toEqual( + Object.values(knowledgeAgentToolNames), + ); + const read = await f.mcp(token.access_token, 'tools/call', { + name: knowledgeAgentToolNames.getDraft, + arguments: { articleId: created.id }, + }); + const readRpc = (await read.json()) as { + result: { isError: boolean; content: { text: string }[] }; + }; + expect(readRpc.result.isError).toBe(false); + expect(JSON.parse(readRpc.result.content[0]!.text)).toMatchObject({ + result: { articleId: created.id, revision: { number: 1 } }, + }); + const updated = await f.mcp(token.access_token, 'tools/call', { + name: knowledgeAgentToolNames.updateDraft, + arguments: { + commandId: 'agent-mcp-update', + correlationId: 'integration', + expectedGeneration: created.generation, + articleId: created.id, + collectionId: 'integration-guides', + draft: draft({ title: 'Updated synthetic export walkthrough' }), + }, + }); + expect(updated.status).toBe(200); + const updateRpc = (await updated.json()) as { + result: { isError: boolean; content: { text: string }[] }; + }; + expect(updateRpc.result.isError).toBe(false); + expect(JSON.parse(updateRpc.result.content[0]!.text)).toMatchObject({ + result: { value: { articleRevision: 2 } }, + }); + const current = await f.agent(token.access_token, 'getDraft', { + articleId: created.id, + }); + expect(current.status).toBe(200); + const currentArticle = (await current.json()) as { + result: DraftArticleDto; + }; + expect(currentArticle.result.revision.title).toBe( + 'Updated synthetic export walkthrough', + ); + expect(currentArticle.result.revision.createdBy).toBe(owner); + expect(currentArticle.result.hasPublication).toBe(false); + const cookieOnly = await f.knowledgeRequest( + new Request('https://pegma.dev/api/knowledge/v1', { + method: 'POST', + headers: { + Cookie: f.ownerAuth.cookie, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + apiVersion: '1', + operation: 'getDraft', + input: { articleId: created.id }, + }), + }), + ); + expect(cookieOnly.status).toBe(401); + for (const operation of [ + 'publishArticle', + 'submitForReview', + 'getReview', + 'getProvenance', + 'setProvenance', + 'createCollection', + ]) { + const refused = await f.agent(token.access_token, operation, { + articleId: created.id, + }); + expect(refused.status).toBe(400); + expect(await refused.json()).toMatchObject({ + error: { code: 'invalid_request' }, + }); + } + const delegated = await f.agents.service.authenticate({ + token: token.access_token, + resource, + }); + await expect( + f.knowledge.application.getProvenance(delegated.access, { + articleId: created.id, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.knowledge.application.getReview(delegated.access, { + articleId: created.id, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.knowledge.application.submitForReview(delegated.access, { + articleId: created.id, + commandId: 'agent-review-denied', + correlationId: 'integration', + expectedGeneration: currentArticle.result.generation, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + const provenanceWrite = await f.agent( + token.access_token, + 'updateDraft', + { + commandId: 'agent-provenance-denied', + correlationId: 'integration', + expectedGeneration: currentArticle.result.generation, + articleId: created.id, + collectionId: 'integration-guides', + draft: draft(), + sourceReferences: [ + { + id: 'agent-supplied-source', + system: 'untrusted', + resourceId: 'untrusted-source', + version: '1', + }, + ], + }, + ); + expect(provenanceWrite.status).toBe(400); + const afterRefusal = await f.agent(token.access_token, 'getDraft', { + articleId: created.id, + }); + expect( + ((await afterRefusal.json()) as { result: DraftArticleDto }).result + .generation, + ).toBe(currentArticle.result.generation); + }, + ); + + it('requires independent staff report confirmation before scoped evidence submission and human publication', async () => { + const f = await fixture(); + const { token } = await f.device(); + const created = await createAgentDraft(f, token.access_token); + const prepared = await submitReport(f, token.access_token, created.id); + const unconfirmed = await f.agent(token.access_token, 'submitEvidence', { + commandId: 'unconfirmed-evidence-refused', + correlationId: 'integration', + expectedGeneration: prepared.article.generation, + articleId: created.id, + evidence: prepared.evidence, + receipt: prepared.report.receipt, + }); + expect(unconfirmed.status).toBe(412); + expect(await unconfirmed.json()).toMatchObject({ + error: { code: 'prerequisite' }, + }); + const selfConfirmation = await f.knowledgeRequest( + new Request('https://pegma.dev/api/staff/knowledge/command', { + method: 'POST', + headers: { + Authorization: `Bearer ${token.access_token}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + operation: 'confirmReport', + input: prepared.confirm, + }), + }), + ); + expect(selfConfirmation.status).toBe(403); + const mixedCredential = browserRequest( + '/api/staff/knowledge/command', + f.ownerAuth, + { operation: 'confirmReport', input: prepared.confirm }, + ); + mixedCredential.headers.set( + 'Authorization', + `Bearer ${token.access_token}`, + ); + expect((await f.knowledgeRequest(mixedCredential)).status).toBe(403); + const missingCsrf = browserRequest( + '/api/staff/knowledge/command', + f.reviewerAuth, + { operation: 'confirmReport', input: prepared.confirm }, + ); + missingCsrf.headers.delete('X-Pegma-CSRF'); + expect((await f.knowledgeRequest(missingCsrf)).status).toBe(403); + expect((await f.staff('confirmReport', prepared.confirm)).status).toBe( + 200, + ); + const fresh = await f.agent(token.access_token, 'getDraft', { + articleId: created.id, + }); + const current = ((await fresh.json()) as { result: DraftArticleDto }) + .result; + const evidenceCommand = { + commandId: 'confirmed-evidence-accepted', + correlationId: 'integration', + expectedGeneration: current.generation, + articleId: created.id, + evidence: prepared.evidence, + receipt: prepared.report.receipt, + }; + const accepted = await f.agent( + token.access_token, + 'submitEvidence', + evidenceCommand, + ); + expect(accepted.status).toBe(200); + const acknowledgement = ( + (await accepted.json()) as { + result: CommandResult; + } + ).result; + const replay = await f.agent( + token.access_token, + 'submitEvidence', + evidenceCommand, + ); + expect(replay.status).toBe(200); + expect(await replay.json()).toMatchObject({ + result: { replayed: true, value: acknowledgement.value }, + }); + const retained = await f.staffValue('getEvidence', { + articleId: created.id, + }); + expect(retained.evidence).toHaveLength(1); + expect(retained.evidence[0]!.attestation.verifiedBy).toBe(reviewer); + const prematureReview = await f.staff('submitForReview', { + commandId: 'human-review-missing-content-check', + correlationId: 'integration', + expectedGeneration: acknowledgement.value.generation, + articleId: created.id, + }); + expect(prematureReview.status).toBe(409); + const required = await f.agent( + token.access_token, + 'getValidationRequirements', + { collectionId: 'integration-guides', kind: 'walkthrough' }, + ); + expect(required.status).toBe(200); + const requirements = ( + (await required.json()) as { result: ValidationRequirementsDto } + ).result; + expect(requirements.checks.map((check) => check.testKind).sort()).toEqual( + ['content', 'workflow'], + ); + let completeEvidenceGeneration = acknowledgement.value.generation; + for (const check of requirements.checks) { + if (check.id === prepared.evidence.checkId) continue; + const checkedReport = await confirmedReport( + f, + token.access_token, + created.id, + check, + ); + const submittedEvidence = await f.agent( + token.access_token, + 'submitEvidence', + { + commandId: `confirmed-evidence:${check.id}`, + correlationId: 'integration', + expectedGeneration: checkedReport.article.generation, + articleId: created.id, + evidence: checkedReport.evidence, + receipt: checkedReport.report.receipt, + }, + ); + expect(submittedEvidence.status).toBe(200); + completeEvidenceGeneration = ( + (await submittedEvidence.json()) as { + result: CommandResult; + } + ).result.value.generation; + } + const completeEvidence = await f.staffValue('getEvidence', { + articleId: created.id, + }); + expect( + completeEvidence.evidence.map((item) => item.checkId).sort(), + ).toEqual(requirements.checks.map((check) => check.id).sort()); + expect( + completeEvidence.evidence.every( + (item) => item.attestation.verifiedBy === reviewer, + ), + ).toBe(true); + const submitted = await f.staffValue< + CommandResult + >('submitForReview', { + commandId: 'human-submit-review', + correlationId: 'integration', + expectedGeneration: completeEvidenceGeneration, + articleId: created.id, + }); + const review = await f.staffValue('getReview', { + articleId: created.id, + }); + const delegated = await f.agents.service.authenticate({ + token: token.access_token, + resource, + }); + await expect( + f.knowledge.application.publishArticle(delegated.access, { + commandId: 'agent-publish-denied', + correlationId: 'integration', + expectedGeneration: submitted.value.generation, + articleId: created.id, + review: review.review, + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + await expect( + f.knowledge.application.createCollection(delegated.access, { + commandId: 'agent-collection-denied', + correlationId: 'integration', + expectedGeneration: 0, + collectionId: 'agent-cannot-manage', + name: 'Denied collection', + }), + ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError); + const published = await f.staffValue< + CommandResult + >('publishArticle', { + commandId: 'human-publish-guide', + correlationId: 'integration', + expectedGeneration: submitted.value.generation, + articleId: created.id, + review: review.review, + }); + expect(published.value.state).toBe('published'); + const portal = await f.knowledgeRequest( + browserRequest('/api/knowledge/portal', f.memberAuth, { + operation: 'getPublishedArticle', + input: { articleId: created.id }, + }), + ); + expect(portal.status).toBe(200); + const portalBody = await portal.json(); + expect(portalBody).toMatchObject({ + articleId: created.id, + title: draft().title, + }); + const serialized = JSON.stringify(portalBody); + for (const privateValue of [ + prepared.report.receipt, + reviewer, + runner, + 'The independent fixture report', + 'attestation', + 'evidence', + ]) { + expect(serialized).not.toContain(privateValue); + } + }); + + it.each(['retire', 'evidence', 'policy', 'throwing-logger'] as const)( + 'repairs real published portal discovery/search after an outage and filters %s before cleanup', + async (variant) => { + const withdrawal = variant === 'throwing-logger' ? 'retire' : variant; + const observed = observeRetrieval(await options.createStore()); + const logger: Logger | undefined = + variant === 'throwing-logger' + ? { + log: vi.fn((_level, event) => { + if (event.startsWith('knowledge.retrieval_')) + throw new Error( + 'Synthetic injected repair logger failure.', + ); + }), + } + : undefined; + const f = await integrationFixture(observed.store, logger); + const { token } = await f.device(); + const { created, published } = await publishSearchGuide( + f, + token.access_token, + ); + expect(published.value.state).toBe('published'); + // Publication only enqueues a dirty hint; it never waits for repair. + // The unavailable projection store must not change that durable ACK. + expect(observed.scans).toEqual([]); + const portal = async (operation: string, input: unknown) => { + const response = await f.knowledgeRequest( + browserRequest('/api/knowledge/portal', f.memberAuth, { + operation, + input, + }), + ); + expect(response.status).toBe(200); + return response.json(); + }; + const searchInput = { + collectionId: 'integration-guides', + query: 'synthetic export', + applicability: draft().applicability, + }; + expect(await portal('listPortalCollections', {})).toEqual({ + outcome: 'no_result', + collections: [], + }); + expect(await portal('searchPublishedArticles', searchInput)).toEqual({ + outcome: 'no_result', + articles: [], + }); + expect( + await portal('getPublishedArticle', { articleId: created.id }), + ).toMatchObject({ articleId: created.id }); + expect(observed.scans).toEqual([]); + const indexAccess = resolveAccess( + { principalId: 'synthetic-index-status-reader' }, + { + version: 'synthetic-index-status-1', + defaults: [knowledgePermissions.indexManage], + }, + ); + expect(indexAccess.permissions).toEqual([ + knowledgePermissions.indexManage, + ]); + expect(indexAccess.roles).toEqual([]); + expect(indexAccess.entitlements).toEqual([]); + const maintenance = () => + createKnowledgeRetrievalMaintenance({ + store: observed.store, + clock: f.clock, + logger: f.logger, + isEnabled: () => true, + }); + const ready = () => + createKnowledgeRetrievalReady({ + store: observed.store, + clock: f.clock, + logger: f.logger, + isEnabled: () => true, + }); + await ready().runPage(); + expect(f.logger.log).toHaveBeenCalledWith( + 'error', + 'knowledge.retrieval_ready.failed', + { stage: 'repair' }, + ); + async function converge(indexed: boolean) { + // Policy-wide changes deliberately rely on complete physical cycles; + // article commands use the ready hint retained across worker failure. + const physical = !indexed && withdrawal === 'policy'; + for (let tick = 0; tick < 1024; tick++) { + const before = observed.scans.length; + if (physical) { + await maintenance().runPage(); + expect(observed.scans.length - before).toBe(1); + expect(observed.scans.at(-1)?.limit).toBe(1); + } else { + await ready().runPage(); + expect(observed.scans.length).toBe(before); + } + const status = await f.knowledge.application.getArticleIndexStatus( + indexAccess, + { articleId: created.id }, + ); + if (status.status === 'ready' && status.indexed === indexed) return; + } + throw new Error( + 'Synthetic index did not converge within bounded host ticks.', + ); + } + observed.state.failProjectionWrites = false; + await converge(true); + expect(await portal('listPortalCollections', {})).toMatchObject({ + outcome: 'results', + collections: [ + { + collectionId: 'integration-guides', + label: 'Synthetic integration guides', + }, + ], + }); + const found = await portal('searchPublishedArticles', searchInput); + expect(found).toMatchObject({ + outcome: 'results', + articles: [{ articleId: created.id, title: draft().title }], + }); + for (const privateValue of [ + reviewer, + runner, + 'attestation', + 'The independent fixture report', + ]) + expect(JSON.stringify(found)).not.toContain(privateValue); + const beforeWithdrawalScans = observed.scans.length; + // Retain stale hints until the page worker, proving immediate authority. + observed.state.failProjectionWrites = true; + if (withdrawal === 'retire') { + await f.staffValue('retireArticle', { + commandId: 'retire-search-guide', + correlationId: 'integration', + expectedGeneration: published.value.generation, + articleId: created.id, + }); + } else if (withdrawal === 'evidence') { + const current = await f.staffValue('getDraft', { + articleId: created.id, + }); + const evidence = ( + await f.staffValue('getEvidence', { + articleId: created.id, + }) + ).evidence[0]; + if (evidence === undefined) + throw new Error('Expected actual accepted publication evidence.'); + await f.staffValue('revokeEvidence', { + commandId: 'revoke-search-proof', + correlationId: 'integration', + expectedGeneration: current.generation, + articleId: created.id, + articleRevision: evidence.articleRevision, + evidenceId: evidence.id, + evidenceVersion: evidence.version, + evidenceHash: evidence.hash, + reason: 'Synthetic proof withdrawal', + }); + } else { + const preview = await f.staffValue( + 'previewCollectionPolicy', + { + collectionId: 'integration-guides', + uses: { portal: { enabled: false }, bot: { enabled: false } }, + }, + f.ownerAuth, + ); + await f.staffValue( + 'updateCollectionPolicy', + { + commandId: 'withdraw-search-policy', + correlationId: 'integration', + expectedGeneration: preview.generation, + collectionId: 'integration-guides', + preview: preview.preview, + }, + f.ownerAuth, + ); + } + expect(await portal('searchPublishedArticles', searchInput)).toEqual({ + outcome: 'no_result', + articles: [], + }); + const direct = await f.knowledgeRequest( + browserRequest('/api/knowledge/portal', f.memberAuth, { + operation: 'getPublishedArticle', + input: { articleId: created.id }, + }), + ); + expect(direct.status).toBe(404); + expect(observed.scans.length).toBe(beforeWithdrawalScans); + observed.state.failProjectionWrites = false; + await converge(false); + expect(await portal('searchPublishedArticles', searchInput)).toEqual({ + outcome: 'no_result', + articles: [], + }); + }, + ); + + it.each([ + 'revision', + 'build', + 'runner', + 'result', + 'submitting principal', + ] as const)( + 'rejects a confirmed receipt whose %s binding changes', + async (changed) => { + const f = await fixture(); + const { token } = await f.device(); + const created = await createAgentDraft(f, token.access_token); + const prepared = await confirmedReport( + f, + token.access_token, + created.id, + ); + let evidence = prepared.evidence; + let actorToken = token.access_token; + if (changed === 'revision') { + const beforeUpdate = await f.agent(token.access_token, 'getDraft', { + articleId: created.id, + }); + const before = ( + (await beforeUpdate.json()) as { result: DraftArticleDto } + ).result; + const update = await f.agent(token.access_token, 'updateDraft', { + commandId: 'revise-after-report-confirmation', + correlationId: 'integration', + expectedGeneration: before.generation, + articleId: created.id, + collectionId: 'integration-guides', + draft: draft({ + summary: 'A genuinely revised guide needs fresh report review.', + }), + }); + expect(update.status).toBe(200); + const reread = await f.agent(token.access_token, 'getDraft', { + articleId: created.id, + }); + evidence = evidenceFor( + ((await reread.json()) as { result: DraftArticleDto }).result, + f.clock.now(), + ); + } else if (changed === 'build') + evidence = { ...evidence, stagingBuildId: 'different-staging-build' }; + else if (changed === 'runner') + evidence = { + ...evidence, + runnerId: 'untrusted-runner' as PrincipalId, + }; + else if (changed === 'result') + evidence = { ...evidence, result: 'failed' }; + else actorToken = (await f.device(f.otherOwnerAuth)).token.access_token; + const current = await f.agent(actorToken, 'getDraft', { + articleId: created.id, + }); + const dto = ((await current.json()) as { result: DraftArticleDto }) + .result; + const refused = await f.agent(actorToken, 'submitEvidence', { + commandId: 'changed-evidence-binding-denied', + correlationId: 'integration', + expectedGeneration: dto.generation, + articleId: created.id, + evidence, + receipt: prepared.report.receipt, + }); + expect(refused.status).toBe(412); + expect(await refused.json()).toMatchObject({ + error: { code: 'prerequisite' }, + }); + const retained = await f.staffValue('getEvidence', { + articleId: created.id, + }); + expect(retained.evidence).toHaveLength(0); + }, + ); + + it('refuses a staff confirmation from an obsolete report view after the agent edits the actual draft', async () => { + const f = await fixture(); + const { token } = await f.device(); + const created = await createAgentDraft(f, token.access_token); + const prepared = await submitReport(f, token.access_token, created.id); + const updated = await f.agent(token.access_token, 'updateDraft', { + commandId: 'edit-before-staff-confirms', + correlationId: 'integration', + expectedGeneration: prepared.article.generation, + articleId: created.id, + collectionId: 'integration-guides', + draft: draft({ title: 'Changed after staff opened the report' }), + }); + expect(updated.status).toBe(200); + const stale = await f.staff('confirmReport', prepared.confirm); + expect(stale.status).toBe(409); + const current = await f.staffValue('reportRead', { + articleId: created.id, + ledgerEpoch: prepared.report.ledgerEpoch, + reportId: prepared.report.reportId, + }); + expect(current.status).toBe('pending'); + expect(current.confirmation).toBeNull(); + expect(current.reviewBindingHash).not.toBe( + prepared.viewed.reviewBindingHash, + ); + }); + + it('refuses a previously confirmed report after its current staff reviewer loses authority', async () => { + const f = await fixture(); + const { token } = await f.device(); + const created = await createAgentDraft(f, token.access_token); + const prepared = await confirmedReport(f, token.access_token, created.id); + const assignment = await f.roleStore.getRoleAssignment( + `${KNOWLEDGE_ROLE}-${reviewer}`, + ); + await f.roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: `${KNOWLEDGE_ROLE}-${reviewer}`, + expectedConcurrencyToken: assignment!.concurrencyToken, + revokedBy: { kind: 'principal', principalId: owner }, + revokedAtEpochMs: Date.parse(f.clock.now()) + 1, + auditEventId: 'demote-report-reviewer', + }); + const refused = await f.agent(token.access_token, 'submitEvidence', { + commandId: 'demoted-reviewer-proof-denied', + correlationId: 'integration', + expectedGeneration: prepared.article.generation, + articleId: created.id, + evidence: prepared.evidence, + receipt: prepared.report.receipt, + }); + expect(refused.status).toBe(412); + expect(await refused.json()).toMatchObject({ + error: { code: 'prerequisite' }, + }); + }); + + it('requires the currently stored Admin role and browser CSRF for actual pending consent', async () => { + const f = await fixture(); + const response = await f.agentRequest( + formRequest('/api/agent-access/device-authorizations', { + client_id: client.clientId, + resource, + scope: scopes.join(' '), + }), + ); + const pending = (await response.json()) as { + user_code: string; + device_code: string; + }; + const path = `/api/agent-access/approval?user_code=${encodeURIComponent(pending.user_code)}`; + expect( + ( + await f.agentRequest( + browserRequest(path, f.memberAuth, undefined, 'GET'), + ) + ).status, + ).toBe(403); + expect( + ( + await f.agentRequest( + browserRequest(path, f.reviewerAuth, undefined, 'GET'), + ) + ).status, + ).toBe(403); + const view = await f.agentRequest( + browserRequest(path, f.ownerAuth, undefined, 'GET'), + ); + const approval = (await view.json()) as ApprovalView; + const submitted = { + requestId: approval.requestId, + userCode: pending.user_code, + decision: 'approve', + }; + const missingCsrf = browserRequest( + '/api/agent-access/approval', + f.ownerAuth, + submitted, + ); + missingCsrf.headers.delete('X-Pegma-CSRF'); + expect((await f.agentRequest(missingCsrf)).status).toBe(403); + const current = await f.roleStore.getRoleAssignment( + `${ADMIN_ROLE}-${owner}`, + ); + await f.roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: `${ADMIN_ROLE}-${owner}`, + expectedConcurrencyToken: current!.concurrencyToken, + revokedBy: { kind: 'principal', principalId: otherOwner }, + revokedAtEpochMs: Date.parse(f.clock.now()) + 1, + auditEventId: 'demote-before-consent', + }); + expect( + ( + await f.agentRequest( + browserRequest( + '/api/agent-access/approval', + f.ownerAuth, + submitted, + ), + ) + ).status, + ).toBe(403); + }); + + it.each(['demotion', 'grant revocation', 'inactive account'] as const)( + 'rejects the next HTTP and MCP request after %s', + async (change) => { + const f = await fixture(); + const { token } = await f.device(); + const created = await createAgentDraft(f, token.access_token); + const delegated = await f.agents.service.authenticate({ + token: token.access_token, + resource, + }); + if (change === 'demotion') { + const current = await f.roleStore.getRoleAssignment( + `${ADMIN_ROLE}-${owner}`, + ); + await f.roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: `${ADMIN_ROLE}-${owner}`, + expectedConcurrencyToken: current!.concurrencyToken, + revokedBy: { kind: 'principal', principalId: otherOwner }, + revokedAtEpochMs: Date.parse(f.clock.now()) + 1, + auditEventId: 'demote-active-agent-owner', + }); + } else if (change === 'grant revocation') { + const revoked = await f.agentRequest( + browserRequest( + `/api/agent-access/grants/${delegated.grantId}`, + f.ownerAuth, + undefined, + 'DELETE', + ), + ); + expect(revoked.status).toBe(204); + } else { + f.users.set(owner, { ...user(owner), status: 'pending' }); + } + expect( + ( + await f.agent(token.access_token, 'getDraft', { + articleId: created.id, + }) + ).status, + ).toBe(401); + expect((await f.mcp(token.access_token, 'tools/list', {})).status).toBe( + 401, + ); + const refreshed = await f.agentRequest( + formRequest('/api/agent-access/token', { + grant_type: 'refresh_token', + client_id: client.clientId, + resource, + refresh_token: token.refresh_token, + }), + ); + expect(refreshed.status).toBe(400); + expect(await refreshed.json()).toMatchObject({ + error: 'invalid_grant', + }); + }, + ); + + it('refuses a report when its real grant is revoked while the request body is pending', async () => { + const f = await fixture(); + const { token } = await f.device(); + const created = await createAgentDraft(f, token.access_token); + const article = await f.knowledge.application.getDraft( + ( + await f.agents.service.authenticate({ + token: token.access_token, + resource, + }) + ).access, + { articleId: created.id }, + ); + const before = await f.staffValue('reportList', { + articleId: created.id, + }); + const input = { + commandId: 'revoked-during-report-body', + articleId: created.id, + ledgerEpoch: 1, + evidence: evidenceFor(article, f.clock.now()), + report: { + summary: 'Synthetic test result', + details: 'A fictional test report with no customer content.', + }, + }; + let reached!: () => void; + let release!: () => void; + const reading = new Promise((resolve) => { + reached = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const body = new ReadableStream( + { + async pull(controller) { + reached(); + await gate; + controller.enqueue(new TextEncoder().encode(JSON.stringify(input))); + controller.close(); + }, + }, + { highWaterMark: 0 }, + ); + const init: RequestInit & { duplex: 'half' } = { + method: 'POST', + headers: { + Authorization: `Bearer ${token.access_token}`, + 'Content-Type': 'application/json', + }, + body, + duplex: 'half', + }; + const pending = f.knowledgeRequest( + new Request('https://pegma.dev/api/knowledge/reports', init), + ); + let timeout: ReturnType | undefined; + try { + await Promise.race([ + reading, + pending.then(() => { + throw new Error('Report ended before reading its body.'); + }), + new Promise((_, reject) => { + timeout = setTimeout( + () => reject(new Error('Report body barrier timed out.')), + 10_000, + ); + }), + ]); + const delegated = await f.agents.service.authenticate({ + token: token.access_token, + resource, + }); + expect( + ( + await f.agentRequest( + browserRequest( + '/api/agent-access/grants/' + delegated.grantId, + f.ownerAuth, + undefined, + 'DELETE', + ), + ) + ).status, + ).toBe(204); + } finally { + if (timeout !== undefined) clearTimeout(timeout); + release(); + } + expect((await pending).status).toBe(401); + expect( + await f.staffValue('reportList', { articleId: created.id }), + ).toEqual(before); + }); + + it('rejects excessive consent scopes and a different protected-resource audience', async () => { + const f = await fixture(); + for (const extraScope of [ + 'knowledge.article.publish', + 'knowledge.article.provenance.write', + 'knowledge.collection.manage', + ]) { + const rejected = await f.agentRequest( + formRequest('/api/agent-access/device-authorizations', { + client_id: client.clientId, + resource, + scope: [...scopes, extraScope].join(' '), + }), + ); + expect(rejected.status).toBe(400); + expect(await rejected.json()).toMatchObject({ error: 'invalid_scope' }); + } + const wrongAudience = await f.agentRequest( + formRequest('/api/agent-access/device-authorizations', { + client_id: client.clientId, + resource: 'https://pegma.dev/api/knowledge/v1', + scope: scopes.join(' '), + }), + ); + expect(wrongAudience.status).toBe(400); + const { token } = await f.device(); + await expect( + f.agents.service.authenticate({ + token: token.access_token, + resource: 'https://foreign.example.test/mcp', + }), + ).rejects.toThrow(); + }); + + it('requires an explicit Knowledge grant and honors its removal while preserving the existing Support assignment', async () => { + const f = await fixture(); + const { token } = await f.device(); + const created = await createAgentDraft(f, token.access_token); + const prepared = await submitReport(f, token.access_token, created.id); + const supportId = `${SUPPORT_ROLE}-${member}`; + const originalSupport = await f.roleStore.getRoleAssignment(supportId); + expect(originalSupport?.assignment.role).toBe(SUPPORT_ROLE); + const state = () => + f.knowledgeRequest( + browserRequest( + '/api/staff/knowledge/state', + f.memberAuth, + undefined, + 'GET', + ), + ); + expect((await state()).status).toBe(403); + const privateOperations = [ + { operation: 'getDraft', input: { articleId: created.id } }, + { + operation: 'reportRead', + input: { + articleId: created.id, + ledgerEpoch: prepared.report.ledgerEpoch, + reportId: prepared.report.reportId, + }, + }, + { operation: 'reportLedger', input: { articleId: created.id } }, + { operation: 'getEvidence', input: { articleId: created.id } }, + { operation: 'getReview', input: { articleId: created.id } }, + { operation: 'confirmReport', input: prepared.confirm }, + { operation: 'rejectReport', input: prepared.confirm }, + { operation: 'reassessReport', input: prepared.confirm }, + { + operation: 'resetReports', + input: { + commandId: 'support-cannot-reset-ledger', + articleId: created.id, + expectedLedgerEpoch: prepared.report.ledgerEpoch, + }, + }, + { + operation: 'drainReports', + input: { + articleId: created.id, + ledgerEpoch: prepared.report.ledgerEpoch, + }, + }, + { + operation: 'submitEvidence', + input: { + commandId: 'support-cannot-submit-kb-evidence', + correlationId: 'integration', + expectedGeneration: prepared.article.generation, + articleId: created.id, + evidence: prepared.evidence, + receipt: prepared.report.receipt, + }, + }, + { + operation: 'submitForReview', + input: { + commandId: 'support-cannot-review-kb', + correlationId: 'integration', + expectedGeneration: prepared.article.generation, + articleId: created.id, + }, + }, + { operation: 'publishArticle', input: { articleId: created.id } }, + ]; + for (const command of privateOperations) { + expect( + (await f.staff(command.operation, command.input, f.memberAuth)) + .status, + command.operation, + ).toBe(403); + } + expect(await f.roleStore.getRoleAssignment(supportId)).toEqual( + originalSupport, + ); + expect( + ( + await f.roleStore.listActiveRoleAssignments(member, APPLICATION_SCOPE) + ).map((assignment) => assignment.role), + ).toEqual([SUPPORT_ROLE]); + expect( + await f.roleStore.getRoleAssignment(`${KNOWLEDGE_ROLE}-${member}`), + ).toBeNull(); + + const knowledgeId = await f.grant(member, KNOWLEDGE_ROLE); + expect((await state()).status).toBe(200); + const readable = await f.staff( + 'reportRead', + { + articleId: created.id, + ledgerEpoch: prepared.report.ledgerEpoch, + reportId: prepared.report.reportId, + }, + f.memberAuth, + ); + expect(readable.status).toBe(200); + expect(await readable.json()).toMatchObject({ + reportId: prepared.report.reportId, + submittedBy: owner, + status: 'pending', + }); + const knowledgeAssignment = + await f.roleStore.getRoleAssignment(knowledgeId); + const removed = await f.roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: knowledgeId, + expectedConcurrencyToken: knowledgeAssignment!.concurrencyToken, + revokedBy: { kind: 'principal', principalId: owner }, + revokedAtEpochMs: Date.parse(f.clock.now()) + 1, + auditEventId: 'explicitly-remove-knowledge-role', + }); + expect(removed.status).toBe('revoked'); + expect((await state()).status).toBe(403); + for (const command of privateOperations) { + expect( + (await f.staff(command.operation, command.input, f.memberAuth)) + .status, + command.operation, + ).toBe(403); + } + expect( + (await f.roleStore.getRoleAssignment(knowledgeId))?.assignment.status, + ).toBe('revoked'); + expect( + (await f.roleStore.getRoleAssignment(supportId))?.assignment, + ).toEqual(originalSupport!.assignment); + expect( + ( + await f.roleStore.listActiveRoleAssignments(member, APPLICATION_SCOPE) + ).map((assignment) => assignment.role), + ).toEqual([SUPPORT_ROLE]); + const runtime = createSupportRuntime({ + store: f.store, + sessions: f.sessions, + identity: f.identity, + logger: f.logger, + clock: f.clock, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }); + const support = createSupportApi({ + application: runtime.application, + sessions: f.sessions, + identity: f.identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + createLimiter: runtime.createLimiter, + replyLimiter: runtime.replyLimiter, + logger: f.logger, + roleStore: runtime.roleStore, + }); + expect( + ( + await support( + browserRequest('/api/support/tickets', f.ownerAuth, { + subject: 'Synthetic desk request after role removal', + body: 'Human support remains available without Knowledge access.', + category: 'feedback', + }), + ) + ).status, + ).toBe(201); + expect( + ( + await support( + browserRequest( + '/api/support/admin/queue', + f.memberAuth, + undefined, + 'GET', + ), + ) + ).status, + ).toBe(200); + }); + + it('preserves existing customer and stored Support-role request flows alongside agent linking', async () => { + const f = await fixture(); + const runtime = createSupportRuntime({ + store: f.store, + sessions: f.sessions, + identity: f.identity, + logger: f.logger, + clock: f.clock, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }); + const api = createSupportApi({ + application: runtime.application, + sessions: f.sessions, + identity: f.identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + createLimiter: runtime.createLimiter, + replyLimiter: runtime.replyLimiter, + logger: f.logger, + roleStore: runtime.roleStore, + }); + const created = await api( + browserRequest('/api/support/tickets', f.ownerAuth, { + subject: 'Synthetic integration feedback', + body: 'Existing human support remains available.', + category: 'feedback', + }), + ); + expect(created.status).toBe(201); + const ticket = (await created.json()) as { ticket: { id: string } }; + const customerRead = await api( + browserRequest( + `/api/support/tickets/${ticket.ticket.id}`, + f.ownerAuth, + undefined, + 'GET', + ), + ); + expect(customerRead.status).toBe(200); + const staffQueue = await api( + browserRequest( + '/api/support/admin/queue', + f.memberAuth, + undefined, + 'GET', + ), + ); + expect(staffQueue.status).toBe(200); + const { token } = await f.device(); + expect( + ( + await f.agents.service.authenticate({ + token: token.access_token, + resource, + }) + ).access.permissions, + ).toEqual(scopes); + expect( + ( + await f.roleStore.listActiveRoleAssignments(member, APPLICATION_SCOPE) + ).map((assignment) => assignment.role), + ).toEqual([SUPPORT_ROLE]); + }); + it('recovers a full report ledger through explicit bounded reset and refuses the old epoch and receipt', async () => { + const f = await fixture(); + const { token } = await f.device(); + const created = await createAgentDraft(f, token.access_token); + const prepared = await confirmedReport(f, token.access_token, created.id); + const discovered = await f.reportLedger(token.access_token, created.id); + expect(discovered.status).toBe(200); + const ledger = (await discovered.json()) as KnowledgeReportLedgerState; + expect(Object.keys(ledger).sort()).toEqual([ + 'articleId', + 'ledgerEpoch', + 'reportsRemaining', + 'rowsRemaining', + 'status', + ]); + expect(ledger.status).toBe('active'); + expect(ledger.reportsRemaining).toBe(15); + for (let index = 0; index < ledger.reportsRemaining; index += 1) { + const pending = await f.report(token.access_token, { + ...prepared.reportCommand, + commandId: `fill-report-capacity:${index}`, + report: { + summary: `Synthetic pending report ${index}`, + details: + 'A separately submitted bounded fixture report awaits human review.', + }, + }); + expect(pending.status).toBe(200); + } + const fullResponse = await f.reportLedger(token.access_token, created.id); + const full = (await fullResponse.json()) as KnowledgeReportLedgerState; + expect(full.reportsRemaining).toBe(0); + const refused = await f.report(token.access_token, { + ...prepared.reportCommand, + commandId: 'seventeenth-report-refused', + }); + expect(refused.status).toBe(409); + const reset = await f.staffValue( + 'resetReports', + { + commandId: 'reset-full-report-ledger', + articleId: created.id, + expectedLedgerEpoch: full.ledgerEpoch, + }, + ); + expect(reset.ledgerEpoch).toBe(full.ledgerEpoch + 1); + expect(reset.status).toBe('resetting'); + expect( + (await f.report(token.access_token, prepared.reportCommand)).status, + ).toBe(409); + expect( + ( + await f.reportStatus( + token.access_token, + created.id, + prepared.report.ledgerEpoch, + prepared.report.reportId, + ) + ).status, + ).toBe(409); + expect((await f.staff('confirmReport', prepared.confirm)).status).toBe( + 409, + ); + expect( + ( + await f.report(token.access_token, { + ...prepared.reportCommand, + commandId: 'admission-during-reset-refused', + ledgerEpoch: reset.ledgerEpoch, + }) + ).status, + ).toBe(409); + const drained = await drainReportLedger(f, reset); + expect(drained.reportsRemaining).toBe(16); + expect(drained.rowsRemaining).toBeGreaterThan(0); + expect( + (await f.report(token.access_token, prepared.reportCommand)).status, + ).toBe(409); + const currentRead = await f.agent(token.access_token, 'getDraft', { + articleId: created.id, + }); + const current = ( + (await currentRead.json()) as { result: DraftArticleDto } + ).result; + const oldReceipt = await f.agent(token.access_token, 'submitEvidence', { + commandId: 'old-epoch-cannot-authorize-new-evidence', + correlationId: 'integration', + expectedGeneration: current.generation, + articleId: created.id, + evidence: prepared.evidence, + receipt: prepared.report.receipt, + }); + expect(oldReceipt.status).toBe(412); + const recovered = await confirmedReport( + f, + token.access_token, + created.id, + workflowCheck, + 'after-reset', + ); + expect(recovered.report.ledgerEpoch).toBe(drained.ledgerEpoch); + expect(recovered.report.receipt).not.toBe(prepared.report.receipt); + const accepted = await f.agent(token.access_token, 'submitEvidence', { + commandId: 'fresh-epoch-evidence-accepted', + correlationId: 'integration', + expectedGeneration: recovered.article.generation, + articleId: created.id, + evidence: recovered.evidence, + receipt: recovered.report.receipt, + }); + expect(accepted.status).toBe(200); + const acceptedEvidence = await f.staffValue('getEvidence', { + articleId: created.id, + }); + expect(acceptedEvidence.evidence).toHaveLength(1); + expect(acceptedEvidence.evidence[0]!.attestation.id).toBe( + recovered.report.receipt, + ); + }); + + it('retains already accepted SDK evidence and publication after report ledger reset and drain', async () => { + const f = await fixture(); + const { token } = await f.pkce(); + const created = await createAgentDraft(f, token.access_token); + const required = await f.agent( + token.access_token, + 'getValidationRequirements', + { collectionId: 'integration-guides', kind: 'walkthrough' }, + ); + expect(required.status).toBe(200); + const requirements = ( + (await required.json()) as { result: ValidationRequirementsDto } + ).result; + const reports: Awaited>[] = []; + let generation = created.generation; + for (const check of requirements.checks) { + const prepared = await confirmedReport( + f, + token.access_token, + created.id, + check, + 'retained-publication', + ); + reports.push(prepared); + const accepted = await f.agent(token.access_token, 'submitEvidence', { + commandId: `retained-publication-evidence:${check.id}`, + correlationId: 'integration', + expectedGeneration: prepared.article.generation, + articleId: created.id, + evidence: prepared.evidence, + receipt: prepared.report.receipt, + }); + expect(accepted.status).toBe(200); + generation = ( + (await accepted.json()) as { + result: CommandResult; + } + ).result.value.generation; + } + const submitted = await f.staffValue< + CommandResult + >('submitForReview', { + commandId: 'submit-retained-publication', + correlationId: 'integration', + expectedGeneration: generation, + articleId: created.id, + }); + const review = await f.staffValue('getReview', { + articleId: created.id, + }); + const published = await f.staffValue< + CommandResult + >('publishArticle', { + commandId: 'publish-retained-guide', + correlationId: 'integration', + expectedGeneration: submitted.value.generation, + articleId: created.id, + review: review.review, + }); + expect(published.value.state).toBe('published'); + const portal = () => + f.knowledgeRequest( + browserRequest('/api/knowledge/portal', f.memberAuth, { + operation: 'getPublishedArticle', + input: { articleId: created.id }, + }), + ); + const beforeRead = await portal(); + expect(beforeRead.status).toBe(200); + const beforePublication = await beforeRead.json(); + const beforeEvidence = await f.staffValue('getEvidence', { + articleId: created.id, + }); + expect(beforeEvidence.evidence).toHaveLength(requirements.checks.length); + expect( + beforeEvidence.evidence.map((item) => item.attestation.id).sort(), + ).toEqual(reports.map((item) => item.report.receipt).sort()); + const ledger = await f.staffValue( + 'reportLedger', + { articleId: created.id }, + ); + const reset = await f.staffValue( + 'resetReports', + { + commandId: 'reset-retained-publication-ledger', + articleId: created.id, + expectedLedgerEpoch: ledger.ledgerEpoch, + }, + ); + await drainReportLedger(f, reset); + expect( + (await f.report(token.access_token, reports[0]!.reportCommand)).status, + ).toBe(409); + expect( + ( + await f.reportStatus( + token.access_token, + created.id, + reports[0]!.report.ledgerEpoch, + reports[0]!.report.reportId, + ) + ).status, + ).toBe(409); + const afterRead = await portal(); + expect(afterRead.status).toBe(200); + expect(await afterRead.json()).toEqual(beforePublication); + expect( + await f.staffValue('getEvidence', { + articleId: created.id, + }), + ).toEqual(beforeEvidence); + const stillPublished = await f.agent(token.access_token, 'getDraft', { + articleId: created.id, + }); + expect(await stillPublished.json()).toMatchObject({ + result: { state: 'published', hasPublication: true }, + }); + }); + + it('isolates independently consented grants and honors stored Admin demotion on the next request', async () => { + const f = await fixture(); + const first = await f.device(); + const second = await f.pkce(); + const created = await createAgentDraft(f, first.token.access_token); + const delegated = await f.agents.service.authenticate({ + token: first.token.access_token, + resource, + }); + const revoked = await f.agentRequest( + browserRequest( + '/api/agent-access/grants/' + delegated.grantId, + f.ownerAuth, + undefined, + 'DELETE', + ), + ); + expect(revoked.status).toBe(204); + expect( + ( + await f.agent(first.token.access_token, 'getDraft', { + articleId: created.id, + }) + ).status, + ).toBe(401); + expect( + ( + await f.agent(second.token.access_token, 'getDraft', { + articleId: created.id, + }) + ).status, + ).toBe(200); + const current = await f.roleStore.getRoleAssignment( + ADMIN_ROLE + '-' + owner, + ); + await f.roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: ADMIN_ROLE + '-' + owner, + expectedConcurrencyToken: current!.concurrencyToken, + revokedBy: { kind: 'principal', principalId: otherOwner }, + revokedAtEpochMs: Date.parse(f.clock.now()) + 1, + auditEventId: 'demote-owner-with-independent-grants', + }); + expect( + ( + await f.agent(second.token.access_token, 'getDraft', { + articleId: created.id, + }) + ).status, + ).toBe(401); + expect( + (await f.mcp(second.token.access_token, 'tools/list', {})).status, + ).toBe(401); + expect( + ( + await f.roleStore.listActiveRoleAssignments(member, APPLICATION_SCOPE) + ).map((assignment) => assignment.role), + ).toEqual([SUPPORT_ROLE]); + }); + }); +} diff --git a/worker/src/knowledge-integration.d1.test.ts b/worker/src/knowledge-integration.d1.test.ts new file mode 100644 index 0000000..ee29586 --- /dev/null +++ b/worker/src/knowledge-integration.d1.test.ts @@ -0,0 +1,111 @@ +import { env } from 'cloudflare:workers'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { handleKnowledgeRequest } from './knowledge-host'; +import { registerKnowledgeIntegrationScenarios } from './knowledge-integration-scenarios'; + +declare global { + namespace Cloudflare { + interface Env { + IDENTITY_DB: D1Database; + } + } +} + +// The existing host migration, executed against the real Workers D1 binding. +const schemaStatements = [ + 'CREATE TABLE IF NOT EXISTS RECORDS (partition_key TEXT NOT NULL, row_key TEXT NOT NULL, record_json TEXT, version INTEGER NOT NULL, deleted INTEGER NOT NULL CHECK (deleted IN (0, 1)), PRIMARY KEY (partition_key, row_key)) STRICT', + 'CREATE TABLE IF NOT EXISTS PEGMA_STORAGE_D1_TX_GUARD (reason TEXT NOT NULL) STRICT', + "CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_EXISTS BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD WHEN NEW.reason = 'exists' BEGIN SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_EXISTS'); END", + "CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_MISSING BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD WHEN NEW.reason = 'missing' BEGIN SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_MISSING'); END", + "CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_CHANGED BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD WHEN NEW.reason = 'changed' BEGIN SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_CHANGED'); END", +] as const; + +beforeAll(async () => { + for (const statement of schemaStatements) + await env.IDENTITY_DB.prepare(statement).run(); +}); +beforeEach(async () => { + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); +registerKnowledgeIntegrationScenarios({ + name: 'released Agent Access and KB host integration over actual D1', + createStore: () => + createCloudflareD1Store({ + database: env.IDENTITY_DB, + createSchemaIfMissing: false, + }), +}); + +describe('production knowledge activation over actual D1', () => { + it('keeps browser authentication live when optional agent registrations are malformed', async () => { + const registrationCanary = 'synthetic-agent-registration-canary'; + const configuration = { + IDENTITY_DB: env.IDENTITY_DB, + IDENTITY_EMAIL_CODE_SECRET_BASE64: btoa( + String.fromCharCode(...new Uint8Array(32).fill(7)), + ), + IDENTITY_EMAIL_FROM: 'identity@example.test', + IDENTITY_EMAIL_ENABLED: 'false', + PEGMA_KNOWLEDGE_ENABLED: 'true', + PEGMA_AGENT_CLIENTS_JSON: `{"clientId":"${registrationCanary}"`, + }; + const logger = { log: vi.fn() }; + const browser = await handleKnowledgeRequest( + new Request('https://pegma.dev/api/staff/knowledge/state'), + configuration, + logger, + ); + expect(browser.status).toBe(401); + expect(browser.headers.get('Cache-Control')).toBe('no-store'); + expect(await browser.json()).toEqual({ error: 'authentication_required' }); + + const agentRequests = [ + new Request('https://pegma.dev/.well-known/oauth-authorization-server'), + new Request( + 'https://pegma.dev/.well-known/oauth-protected-resource/api/knowledge/mcp', + ), + new Request('https://pegma.dev/api/agent-access/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: 'grant_type=urn:ietf:params:oauth:grant-type:device_code', + }), + new Request('https://pegma.dev/api/knowledge/v1'), + new Request('https://pegma.dev/api/knowledge/mcp', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }), + }), + new Request('https://pegma.dev/api/knowledge/reports?articleId=guide'), + ]; + for (const request of agentRequests) { + const response = await handleKnowledgeRequest( + request, + configuration, + logger, + ); + expect(response.status).toBe(503); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(await response.json()).toEqual({ + error: 'agent_access_not_configured', + }); + } + expect(logger.log.mock.calls).toEqual([ + ...Array.from({ length: agentRequests.length + 1 }, () => [ + 'error', + 'agent_access.configuration_unavailable', + { error: 'SyntaxError' }, + ]), + // The manual report route classifies its null-agent 503 through the + // API failure boundary after the host records unavailable configuration. + ['error', 'knowledge.api_unavailable', { error: 'Error', stage: 'api' }], + ]); + expect(JSON.stringify(logger.log.mock.calls)).not.toContain( + registrationCanary, + ); + expect(JSON.stringify(logger.log.mock.calls)).not.toContain( + configuration.IDENTITY_EMAIL_CODE_SECRET_BASE64, + ); + }); +}); diff --git a/worker/src/knowledge-integration.test.ts b/worker/src/knowledge-integration.test.ts new file mode 100644 index 0000000..1b85029 --- /dev/null +++ b/worker/src/knowledge-integration.test.ts @@ -0,0 +1,7 @@ +import { createMemoryStore } from '@pegma/storage-core'; +import { registerKnowledgeIntegrationScenarios } from './knowledge-integration-scenarios'; + +registerKnowledgeIntegrationScenarios({ + name: 'released Agent Access and KB host integration over Memory Store', + createStore: createMemoryStore, +}); diff --git a/worker/src/knowledge-maintenance.test.ts b/worker/src/knowledge-maintenance.test.ts new file mode 100644 index 0000000..12a66fc --- /dev/null +++ b/worker/src/knowledge-maintenance.test.ts @@ -0,0 +1,615 @@ +import { createDurableLimiter as createLegacyLimiter } from '@pegma/rate-limit'; +import { createDurableLimiter } from '@pegma/rate-limit-paged'; +import type { Clock, Logger } from '@pegma/spine'; +import { + createMemoryStore, + defineCollection, + type CollectionDefinition, + type CollectionStore, + type ScanOptions, + type Store, + type StoredRecord, +} from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import { runKnowledgeMaintenance } from './knowledge-maintenance'; +import { RATE_LIMIT_CRON, rateKnowledgeLaneAt } from './maintenance-schedule'; + +const START = '2026-11-08T00:00:00.000Z'; +const EXPIRED = '2026-11-08T00:02:00.000Z'; +const KEY = { partition: 'knowledge', id: 'rate-limits' } as const; +const checkpoints = defineCollection({ + name: 'pegma-dev-maintenance', + key: (value) => ({ + partition: String(value.partition), + id: String(value.id), + }), + codec: { + encode: (value) => ({ ...value }), + decode: (value) => ({ ...value }), + }, +}); + +function barrier() { + let release = () => {}; + const ready = new Promise((resolve) => { + release = resolve; + }); + return { ready, release }; +} + +interface Hooks { + readonly fail?: 'bookmark_read' | 'scan' | 'delete' | 'bookmark_write'; + readonly afterScan?: () => Promise; + readonly afterDecision?: (decision: number) => Promise; +} + +/** Delegates persistence, scans and OCC to the actual Memory Store. */ +function observe(backing: Store, hooks: Hooks = {}) { + const scans: ScanOptions[] = []; + let decisions = 0; + let deleted = 0; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const target = backing.collection(definition); + if (definition.name === checkpoints.name) + return { + ...target, + async get(key) { + if (hooks.fail === 'bookmark_read') + throw new Error('bookmark unavailable'); + return target.get(key); + }, + async update(key, decide, options) { + if (hooks.fail === 'bookmark_write') + throw new Error('bookmark unavailable'); + return target.update( + key, + async (current) => { + const result = await decide(current); + decisions += 1; + await hooks.afterDecision?.(decisions); + return result; + }, + options, + ); + }, + }; + return { + ...target, + async scan(options) { + scans.push({ ...options }); + if (hooks.fail === 'scan') throw new Error('scan unavailable'); + const page = await target.scan(options); + await hooks.afterScan?.(); + return page; + }, + async deleteIfUnchanged(key, version) { + if (hooks.fail === 'delete') throw new Error('delete unavailable'); + const removed = await target.deleteIfUnchanged(key, version); + if (removed) deleted += 1; + return removed; + }, + async list() { + throw new Error('Maintenance must use a physical page.'); + }, + async listVersioned() { + throw new Error('Maintenance must use a physical page.'); + }, + }; + }, + }; + return { store, scans, decisions: () => decisions, deleted: () => deleted }; +} + +function fixture() { + const backing = createMemoryStore(); + let at = START; + const clock: Clock = { now: () => at }; + const logger: Logger = { log: vi.fn() }; + return { + backing, + clock, + logger, + setTime: (next: string) => { + at = next; + }, + checkpoint: () => backing.collection(checkpoints).get(KEY), + }; +} + +async function seed(store: Store, count: number) { + const limiter = createDurableLimiter( + { + name: 'pegma.test.knowledge.maintenance', + limit: 1, + windowMs: 60_000, + }, + store, + ); + for (let index = 0; index < count; index++) { + expect(await limiter.allow(`subject-${index}`, START)).toEqual({ + allowed: true, + }); + } + return limiter; +} + +describe('knowledge maintenance', () => { + it('resumes one physical page of 20 across cold invocations and increments completed cycles', async () => { + const f = fixture(); + await seed(f.backing, 45); + const observed = observe(f.backing); + const runtime = { store: observed.store, clock: f.clock }; + await runKnowledgeMaintenance(runtime, f.logger); + const first = await f.checkpoint(); + expect(first).toMatchObject({ + ...KEY, + generation: 1, + cursor: expect.any(String), + }); + await runKnowledgeMaintenance({ ...runtime }, f.logger); + const second = await f.checkpoint(); + expect(second).toMatchObject({ generation: 2, cursor: expect.any(String) }); + expect(second?.cursor).not.toBe(first?.cursor); + await runKnowledgeMaintenance({ ...runtime }, f.logger); + expect(await f.checkpoint()).toEqual({ + ...KEY, + generation: 3, + cursor: null, + }); + await runKnowledgeMaintenance({ ...runtime }, f.logger); + expect(await f.checkpoint()).toMatchObject({ + generation: 4, + cursor: first?.cursor, + }); + expect(observed.scans).toEqual([ + { limit: 20 }, + { limit: 20, cursor: first?.cursor }, + { limit: 20, cursor: second?.cursor }, + { limit: 20 }, + ]); + expect(vi.mocked(f.logger.log).mock.calls).toEqual([ + [ + 'info', + 'knowledge.maintenance_page', + { task: 'rate_limits', scanned: 20, deleted: 0, hasNext: true }, + ], + [ + 'info', + 'knowledge.maintenance_page', + { task: 'rate_limits', scanned: 20, deleted: 0, hasNext: true }, + ], + [ + 'info', + 'knowledge.maintenance_page', + { task: 'rate_limits', scanned: 6, deleted: 0, hasNext: false }, + ], + [ + 'info', + 'knowledge.maintenance_page', + { task: 'rate_limits', scanned: 20, deleted: 0, hasNext: true }, + ], + ]); + }); + + it('deletes an actual expired new window while preserving active and legacy limiter counters', async () => { + const f = fixture(); + const old = createDurableLimiter( + { name: 'new-expired', limit: 1, windowMs: 60_000 }, + f.backing, + ); + const active = createDurableLimiter( + { name: 'new-active', limit: 1, windowMs: 60_000 }, + f.backing, + ); + const legacy = createLegacyLimiter( + { name: 'old-library', limit: 1, windowMs: 60_000 }, + f.backing, + ); + expect(await old.allow('same', START)).toEqual({ allowed: true }); + expect(await active.allow('same', EXPIRED)).toEqual({ allowed: true }); + expect(await legacy.allow('same', START)).toEqual({ allowed: true }); + f.setTime(EXPIRED); + const observed = observe(f.backing); + // This runtime has no feature flag, identity or OAuth registration dependency. + await runKnowledgeMaintenance( + { store: observed.store, clock: f.clock }, + f.logger, + ); + expect(observed.scans).toEqual([{ limit: 20 }]); + expect(observed.deleted()).toBe(1); + expect(await old.allow('same', START)).toEqual({ allowed: true }); + expect((await active.allow('same', EXPIRED)).allowed).toBe(false); + expect((await legacy.allow('same', START)).allowed).toBe(false); + expect(await f.checkpoint()).toEqual({ + ...KEY, + cursor: null, + generation: 1, + }); + expect(f.logger.log).toHaveBeenCalledExactlyOnceWith( + 'info', + 'knowledge.maintenance_page', + { task: 'rate_limits', scanned: 5, deleted: 1, hasNext: false }, + ); + }); + + it.each(['bookmark_read', 'scan', 'bookmark_write'] as const)( + 'preserves the durable bookmark after %s failure and resumes from it', + async (fail) => { + const f = fixture(); + await seed(f.backing, 45); + await runKnowledgeMaintenance( + { store: f.backing, clock: f.clock }, + f.logger, + ); + const before = await f.checkpoint(); + vi.mocked(f.logger.log).mockClear(); + const failed = observe(f.backing, { fail }); + await runKnowledgeMaintenance( + { store: failed.store, clock: f.clock }, + f.logger, + ); + expect(await f.checkpoint()).toEqual(before); + expect(f.logger.log).toHaveBeenCalledExactlyOnceWith( + 'error', + 'knowledge.maintenance_failed', + { task: 'rate_limits', error: 'Error' }, + ); + const resumed = observe(f.backing); + await runKnowledgeMaintenance( + { store: resumed.store, clock: f.clock }, + f.logger, + ); + expect(resumed.scans).toEqual([{ limit: 20, cursor: before?.cursor }]); + expect(await f.checkpoint()).toMatchObject({ generation: 2 }); + }, + ); + + it('preserves the completed-cycle bookmark when a real expired-window delete fails', async () => { + const f = fixture(); + await seed(f.backing, 1); + await runKnowledgeMaintenance( + { store: f.backing, clock: f.clock }, + f.logger, + ); + const before = await f.checkpoint(); + vi.mocked(f.logger.log).mockClear(); + f.setTime(EXPIRED); + const failed = observe(f.backing, { fail: 'delete' }); + await runKnowledgeMaintenance( + { store: failed.store, clock: f.clock }, + f.logger, + ); + expect(await f.checkpoint()).toEqual(before); + expect(f.logger.log).toHaveBeenCalledExactlyOnceWith( + 'error', + 'knowledge.maintenance_failed', + { task: 'rate_limits', error: 'Error' }, + ); + const resumed = observe(f.backing); + await runKnowledgeMaintenance( + { store: resumed.store, clock: f.clock }, + f.logger, + ); + expect(resumed.deleted()).toBe(1); + expect(await f.checkpoint()).toEqual({ + ...KEY, + cursor: null, + generation: 2, + }); + expect(f.logger.log).toHaveBeenLastCalledWith( + 'info', + 'knowledge.maintenance_page', + { task: 'rate_limits', scanned: 2, deleted: 1, hasNext: false }, + ); + }); + + it('rechecks the generation inside actual OCC retries even when both continuations are null', async () => { + const f = fixture(); + const entered = barrier(); + const release = barrier(); + const delayed = observe(f.backing, { + afterDecision: async (decision) => { + if (decision === 1) { + entered.release(); + await release.ready; + } + }, + }); + const first = runKnowledgeMaintenance( + { store: delayed.store, clock: f.clock }, + f.logger, + ); + await entered.ready; + await runKnowledgeMaintenance( + { store: f.backing, clock: f.clock }, + f.logger, + ); + expect(await f.checkpoint()).toEqual({ + ...KEY, + cursor: null, + generation: 1, + }); + release.release(); + await first; + expect(delayed.decisions()).toBe(2); + expect(await f.checkpoint()).toEqual({ + ...KEY, + cursor: null, + generation: 1, + }); + expect(delayed.scans).toHaveLength(1); + expect(f.logger.log).toHaveBeenCalledTimes(2); + expect(f.logger.log).toHaveBeenLastCalledWith( + 'info', + 'knowledge.maintenance_page', + { task: 'rate_limits', scanned: 0, deleted: 0, hasNext: false }, + ); + }); + + it('rejects a stale earlier cycle after newer invocations return the cursor to null', async () => { + const f = fixture(); + await seed(f.backing, 45); + const entered = barrier(); + const release = barrier(); + const delayed = observe(f.backing, { + afterScan: async () => { + entered.release(); + await release.ready; + }, + }); + const first = runKnowledgeMaintenance( + { store: delayed.store, clock: f.clock }, + f.logger, + ); + await entered.ready; + for (let page = 0; page < 3; page++) { + await runKnowledgeMaintenance( + { store: f.backing, clock: f.clock }, + f.logger, + ); + } + expect(await f.checkpoint()).toEqual({ + ...KEY, + cursor: null, + generation: 3, + }); + release.release(); + await first; + expect(await f.checkpoint()).toEqual({ + ...KEY, + cursor: null, + generation: 3, + }); + expect(delayed.scans).toEqual([{ limit: 20 }]); + expect(f.logger.log).toHaveBeenCalledTimes(4); + expect(f.logger.log).not.toHaveBeenCalledWith( + 'error', + expect.anything(), + expect.anything(), + ); + }); + + it.each([ + { cursor: '', generation: 1 }, + { cursor: 'x'.repeat(8_193), generation: 1 }, + { cursor: null, generation: -1 }, + { cursor: null, generation: 1.5 }, + { cursor: null, generation: Number.MAX_SAFE_INTEGER }, + ])( + 'fails closed on an invalid or exhausted bookmark without scanning', + async (state) => { + const f = fixture(); + await f.backing.collection(checkpoints).put({ ...KEY, ...state }); + const observed = observe(f.backing); + await runKnowledgeMaintenance( + { store: observed.store, clock: f.clock }, + f.logger, + ); + expect(observed.scans).toEqual([]); + expect(await f.checkpoint()).toEqual({ ...KEY, ...state }); + expect(f.logger.log).toHaveBeenCalledOnce(); + }, + ); + + it('honors explicit task omission and does not multiply work for duplicate selections', async () => { + const f = fixture(); + const observed = observe(f.backing); + await runKnowledgeMaintenance( + { store: observed.store, clock: f.clock }, + f.logger, + { tasks: [] }, + ); + expect(await f.checkpoint()).toBeNull(); + await runKnowledgeMaintenance( + { store: observed.store, clock: f.clock }, + f.logger, + { + tasks: ['rate_limits', 'rate_limits'], + }, + ); + expect(observed.scans).toEqual([{ limit: 20 }]); + expect(await f.checkpoint()).toEqual({ + ...KEY, + cursor: null, + generation: 1, + }); + }); + + it.each(['success', 'failure'] as const)( + 'does not throw when the %s diagnostic logger fails', + async (outcome) => { + const f = fixture(); + const observed = observe( + f.backing, + outcome === 'failure' ? { fail: 'scan' } : {}, + ); + const logger: Logger = { + log: vi.fn(() => { + throw new Error('Synthetic logger outage.'); + }), + }; + await expect( + runKnowledgeMaintenance( + { store: observed.store, clock: f.clock }, + logger, + ), + ).resolves.toBeUndefined(); + expect(await f.checkpoint()).toEqual( + outcome === 'failure' ? null : { ...KEY, cursor: null, generation: 1 }, + ); + expect(logger.log).toHaveBeenCalledOnce(); + }, + ); + + it('keeps expired backlog and age bounded during four hours of 672 counters per hour, then drains', async () => { + // Synthetic capacity evidence, not a production traffic forecast or SLA. + // Fifty browser subjects plus one subject in each of six Agent Access + // policy shapes create 56 counters per five-minute cohort. All seven + // persistent descriptors and live windows consume real scan positions. + const f = fixture(); + const observed = observe(f.backing); + const policies = [ + { name: 'browser', limit: 120, subjects: 50 }, + { name: 'authorize', limit: 60, subjects: 1 }, + { name: 'device', limit: 60, subjects: 1 }, + { name: 'token', limit: 300, subjects: 1 }, + { name: 'revoke', limit: 120, subjects: 1 }, + { name: 'agent-browser', limit: 120, subjects: 1 }, + { name: 'resource', limit: 300, subjects: 1 }, + ]; + const limiters = policies.map((policy) => ({ + subjects: policy.subjects, + limiter: createDurableLimiter( + { + name: `pegma.test.capacity.${policy.name}`, + limit: policy.limit, + windowMs: 300_000, + }, + f.backing, + { clock: f.clock }, + ), + })); + // Read-only diagnostics over rows created by public limiter.allow calls; + // no copied record encoder or raw counter seeding is used. + const records = f.backing.collection( + defineCollection({ + name: 'rate-limit-windows', + key: (value) => ({ + partition: String(value.partition), + id: String(value.id), + }), + codec: { encode: (value) => value, decode: (value) => value }, + }), + ); + async function readRows() { + const rows: StoredRecord[] = []; + let cursor: string | undefined; + do { + const page = await records.scan({ + limit: 1_000, + ...(cursor === undefined ? {} : { cursor }), + }); + rows.push(...page.records.map((row) => row.value)); + cursor = page.nextCursor ?? undefined; + } while (cursor !== undefined); + return rows; + } + const range = /^(\d+)-(\d+) \* \* \* \*$/.exec(RATE_LIMIT_CRON); + expect(range).not.toBeNull(); + const hourly: { expired: number; oldestExpiredAgeMs: number }[] = []; + const skippedMinutes: number[] = []; + let completedTrafficCycles = 0; + const start = Date.parse('2026-11-08T00:45:00.000Z'); + // Four continuing hours cross the real 58/59 gaps, followed by two hours + // at the same cadence after arrivals stop. A one-shot eventual drain would + // not expose a service rate below the continuing counter creation rate. + for (let minute = 0; minute < 360; minute++) { + const at = new Date(start + minute * 60_000).toISOString(); + f.setTime(at); + if (minute < 240 && minute % 5 === 0) { + for (const { limiter, subjects } of limiters) { + for (let ip = 1; ip <= subjects; ip++) { + expect(await limiter.allow(`192.0.2.${ip}`)).toEqual({ + allowed: true, + }); + } + } + } + const before = observed.scans.length; + const utcMinute = new Date(at).getUTCMinutes(); + const cronEligible = + utcMinute >= Number(range![1]) && utcMinute <= Number(range![2]); + const eligible = + cronEligible && rateKnowledgeLaneAt(Date.parse(at)) === 'rate_limits'; + if (eligible) { + // Reconstruct invocation state; only the actual persisted bookmark + // carries continuation across these calls. + await runKnowledgeMaintenance( + { store: observed.store, clock: f.clock }, + f.logger, + ); + const checkpoint = await f.checkpoint(); + expect(checkpoint?.generation).toBe(observed.scans.length); + if (minute < 240 && checkpoint?.cursor === null) + completedTrafficCycles += 1; + } else if (!cronEligible) skippedMinutes.push(utcMinute); + expect(observed.scans.length - before).toBe(eligible ? 1 : 0); + if (minute < 240 && minute % 60 === 59) { + // At this cohort phase all but the newest window have also passed + // the published helper's one-minute clock-skew grace. + const expired = Math.floor(minute / 5) * 56 - observed.deleted(); + const now = Date.parse(at); + const expiredRows = (await readRows()).filter( + (row) => + row.kind === 'window' && + typeof row.windowStartMs === 'number' && + typeof row.windowMs === 'number' && + row.windowStartMs + row.windowMs + 60_000 <= now, + ); + expect(expiredRows).toHaveLength(expired); + expect(expired).toBeGreaterThanOrEqual(0); + hourly.push({ + expired, + oldestExpiredAgeMs: Math.max( + 0, + ...expiredRows.map( + (row) => + now - Number(row.windowStartMs) - Number(row.windowMs) - 60_000, + ), + ), + }); + } + } + expect(hourly).toHaveLength(4); + // Compare the same workload phase after warmup, allowing one discrete + // arrival cohort of scan/cursor oscillation, not another two-hour backlog. + // The old 580-row/h ceiling falls at least 184 counters behind 672/h over + // these two continuing hours, even before retained/live-row overhead. + expect(hourly[3]!.expired).toBeLessThanOrEqual(hourly[1]!.expired + 56); + expect(hourly[3]!.oldestExpiredAgeMs).toBeLessThanOrEqual( + hourly[1]!.oldestExpiredAgeMs + 300_000, + ); + expect(completedTrafficCycles).toBeGreaterThan(0); + expect(skippedMinutes).toEqual( + Array.from({ length: 6 }, () => [58, 59]).flat(), + ); + expect(observed.deleted()).toBe(48 * 56); + const remaining = await readRows(); + expect(remaining).toHaveLength(7); + expect(remaining.every((row) => row.kind === 'policy')).toBe(true); + expect(observed.scans).toHaveLength(6 * 39); + expect(observed.scans.every((page) => page.limit === 20)).toBe(true); + expect(f.logger.log).toHaveBeenCalledTimes(6 * 39); + expect(f.logger.log).toHaveBeenLastCalledWith( + 'info', + 'knowledge.maintenance_page', + { task: 'rate_limits', scanned: 7, deleted: 0, hasNext: false }, + ); + expect(f.logger.log).not.toHaveBeenCalledWith( + 'error', + expect.anything(), + expect.anything(), + ); + }); +}); diff --git a/worker/src/knowledge-maintenance.ts b/worker/src/knowledge-maintenance.ts new file mode 100644 index 0000000..9124f13 --- /dev/null +++ b/worker/src/knowledge-maintenance.ts @@ -0,0 +1,146 @@ +import { sweepDurableWindowsPage } from '@pegma/rate-limit-paged'; +import type { Clock, Logger } from '@pegma/spine'; +import { + defineCollection, + type Store, + type StoredValue, +} from '@pegma/storage-core'; + +export interface KnowledgeMaintenanceRuntime { + readonly store: Store; + readonly clock: Clock; +} + +export type KnowledgeMaintenanceTask = 'rate_limits'; + +export interface KnowledgeMaintenanceOptions { + readonly tasks?: readonly KnowledgeMaintenanceTask[]; +} + +interface MaintenanceRecord { + readonly partition: StoredValue; + readonly id: StoredValue; + readonly cursor: StoredValue; + readonly generation: StoredValue; +} + +interface Bookmark { + readonly cursor: string | null; + readonly generation: number; +} + +const KEY = { partition: 'knowledge', id: 'rate-limits' } as const; +// Isolated cron budget: at most 20 descriptor reads and 20 conditional deletes, +// plus the scan and bookmark reads/write, within Workers Free's 50 D1 calls. +const PAGE_LIMIT = 20; +const MAX_CURSOR_LENGTH = 8_192; +const maintenance = defineCollection({ + name: 'pegma-dev-maintenance', + key: (value) => ({ + partition: String(value.partition), + id: String(value.id), + }), + codec: { + encode: (value) => ({ ...value }), + decode: (record) => ({ + partition: record.partition ?? null, + id: record.id ?? null, + cursor: record.cursor ?? null, + generation: record.generation ?? null, + }), + }, +}); + +function validCursor(value: StoredValue): value is string | null { + return ( + value === null || + (typeof value === 'string' && + value.length > 0 && + value.length <= MAX_CURSOR_LENGTH) + ); +} + +function bookmark(value: MaintenanceRecord | null): Bookmark { + if (value === null) return { cursor: null, generation: 0 }; + if ( + value.partition !== KEY.partition || + value.id !== KEY.id || + !validCursor(value.cursor) || + typeof value.generation !== 'number' || + !Number.isSafeInteger(value.generation) || + value.generation < 0 + ) { + throw new TypeError('Invalid knowledge maintenance bookmark.'); + } + return { cursor: value.cursor, generation: value.generation }; +} + +function report( + logger: Logger, + level: 'info' | 'error', + event: string, + fields: Readonly>, +): void { + try { + logger.log(level, event, fields); + } catch { + // Diagnostics must not turn completed cleanup into a failed invocation. + } +} + +/** + * One bounded global cleanup page, independently of knowledge enablement or + * OAuth client registration. The package owns all limiter record validation. + */ +export async function runKnowledgeMaintenance( + runtime: KnowledgeMaintenanceRuntime, + logger: Logger, + options: KnowledgeMaintenanceOptions = {}, +): Promise { + if (!(options.tasks ?? ['rate_limits']).includes('rate_limits')) return; + try { + const collection = runtime.store.collection(maintenance); + const prior = bookmark(await collection.get(KEY)); + if (prior.generation === Number.MAX_SAFE_INTEGER) { + throw new RangeError('Knowledge maintenance generation is exhausted.'); + } + const result = await sweepDurableWindowsPage(runtime.store, { + limit: PAGE_LIMIT, + clock: runtime.clock, + ...(prior.cursor === null ? {} : { cursor: prior.cursor }), + }); + if (!validCursor(result.nextCursor)) { + throw new TypeError('Invalid knowledge maintenance continuation.'); + } + // Capture the result before awaiting OCC. A successful null-to-null cycle + // must still advance the generation so an older invocation cannot win ABA. + const nextCursor = result.nextCursor; + await collection.update(KEY, (current) => { + const actual = bookmark(current); + if ( + actual.generation !== prior.generation || + actual.cursor !== prior.cursor + ) + return { action: 'keep' }; + return { + action: 'write', + value: { + ...KEY, + cursor: nextCursor, + generation: prior.generation + 1, + }, + }; + }); + report(logger, 'info', 'knowledge.maintenance_page', { + task: 'rate_limits', + scanned: result.scanned, + deleted: result.deleted, + hasNext: nextCursor !== null, + }); + } catch (error) { + report(logger, 'error', 'knowledge.maintenance_failed', { + task: 'rate_limits', + error: error instanceof Error ? error.name : 'unknown', + }); + } +} diff --git a/worker/src/knowledge-portal-freshness.test.ts b/worker/src/knowledge-portal-freshness.test.ts new file mode 100644 index 0000000..0108f71 --- /dev/null +++ b/worker/src/knowledge-portal-freshness.test.ts @@ -0,0 +1,659 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { retrievalRecords } from '@pegma/knowledge-base-application'; +import { + articleKinds, + knowledgePermissions, + type ValidationPolicy, +} from '@pegma/knowledge-base-contracts'; +import type { EvidenceSubmission } from '@pegma/knowledge-base-core'; +import { createSessionStore } from '@pegma/sessions'; +import { fixedClock, type PrincipalId } from '@pegma/spine'; +import { + createMemoryStore, + type CollectionDefinition, + type CollectionStore, + type Store, +} from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import type { IdentityPort, IdentityUser } from './identity-contracts'; +import { createKnowledgeRuntime } from './knowledge-runtime'; +import { + ADMIN_ROLE, + APPLICATION_SCOPE, + AUTHORIZATION_APPLICATION_ID, + KNOWLEDGE_ROLE, + SUPPORT_ROLE, +} from './support-access'; + +const authorId = 'portal-author'; +const readerId = 'portal-reader'; +const otherId = 'portal-other-reader'; +const customerId = 'portal-customer'; +const collectionId = 'restricted-guides'; +const articleId = 'restricted-export'; +const privateLabel = 'Restricted export collection'; +const privateTitle = 'Restricted export guide'; +const privateText = 'Export the restricted synthetic account settings.'; +const operations = [ + 'getPublishedArticle', + 'searchPublishedArticles', + 'listPortalCollections', +] as const; +type Operation = (typeof operations)[number]; + +async function fixture() { + const backing = createMemoryStore(); + let afterRead: (() => Promise) | undefined; + let reads = 0; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const target = backing.collection(definition); + if ( + definition.name !== 'knowledge-base.records.v1' && + definition.name !== retrievalRecords.name + ) + return target; + async function observed() { + reads += 1; + const hook = afterRead; + afterRead = undefined; + await hook?.(); + } + // Pause only after the real adapter has returned its actual KB facts. + return { + ...target, + list(partition) { + reads += 1; + return target.list(partition); + }, + listVersioned(partition) { + reads += 1; + return target.listVersioned(partition); + }, + scan(options) { + reads += 1; + return target.scan(options); + }, + async get(key) { + const value = await target.get(key); + await observed(); + return value; + }, + async getVersioned(key) { + const value = await target.getVersioned(key); + await observed(); + return value; + }, + }; + }, + }; + const clock = fixedClock('2026-11-08T12:00:00.000Z'); + const logger = { log: vi.fn() }; + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + const sessions = createSessionStore(store, { logger, clock }); + const users = new Map( + [authorId, readerId, otherId, customerId].map((principalId) => [ + principalId, + { + principalId, + email: principalId + '@example.test', + emailVerified: true, + status: 'active', + createdAt: clock.now(), + updatedAt: clock.now(), + }, + ]), + ); + // Identity is the external authority port; sessions, roles and KB state use + // their real released services over the same MemoryStore. + const identity: IdentityPort = { + async claimsFor(id) { + const user = users.get(id); + if (user === undefined || user.status !== 'active' || !user.emailVerified) + throw Object.assign(new Error('Unavailable synthetic account.'), { + code: 'invalid_state', + }); + return { + issuer: IDENTITY_ISSUER, + subject: id, + emailVerified: true, + }; + }, + getUser: async (id) => users.get(id) ?? null, + findUserByEmail: async () => null, + beginPasskeyRegistration: vi.fn(), + finishPasskeyRegistration: vi.fn(), + beginPasskeyAuthentication: vi.fn(), + finishPasskeyAuthentication: vi.fn(), + listPasskeys: async () => [], + removePasskey: async () => true, + }; + async function grant(id: string, principalId: string, role: string) { + await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id, + principalId, + role, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-portal-test' }, + grantedAtEpochMs: Date.parse(clock.now()), + status: 'active', + }, + auditEventId: 'grant-' + id, + }); + } + await grant('author-admin', authorId, ADMIN_ROLE); + await grant('reader-knowledge', readerId, KNOWLEDGE_ROLE); + await grant('other-knowledge', otherId, KNOWLEDGE_ROLE); + const sessionIds = new Map(); + for (const [index, principalId] of [ + authorId, + readerId, + otherId, + customerId, + readerId, + ].entries()) { + const id = String(index + 1).repeat(43); + await sessions.create(id, { + principalId, + data: JSON.stringify({ + version: 1, + csrfToken: 'c'.repeat(43), + issuer: IDENTITY_ISSUER, + subject: principalId, + }), + }); + sessionIds.set(index === 4 ? 'reader-second-session' : principalId, id); + } + const options = { + store, + clock, + logger, + sessions, + roleStore, + identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }; + const resolve = createAgentPrincipalResolver(options); + const author = await resolve(authorId); + if (author === null) throw new Error('Missing real author authority.'); + const runtime = createKnowledgeRuntime({ ...options, agentAccess: null }); + const app = runtime.application; + await app.createCollection(author, { + commandId: 'collection', + correlationId: 'setup', + expectedGeneration: 0, + collectionId, + name: privateLabel, + }); + const preview = await app.previewCollectionPolicy(author, { + collectionId, + uses: { + portal: { + enabled: true, + audience: { + kind: 'permission', + permission: knowledgePermissions.draftRead, + }, + }, + bot: { enabled: false }, + }, + }); + await app.updateCollectionPolicy(author, { + commandId: 'audience', + correlationId: 'setup', + collectionId, + expectedGeneration: preview.generation, + preview: preview.preview, + }); + const policy: ValidationPolicy = { + id: 'portal-policy', + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: kind + '-content', + kind, + testKind: 'content' as const, + maxAgeMilliseconds: 60_000, + trustedRunnerIds: ['portal-runner'], + })), + { + id: 'walkthrough-workflow', + kind: 'walkthrough', + testKind: 'workflow', + maxAgeMilliseconds: 60_000, + trustedRunnerIds: ['portal-runner'], + }, + { + id: 'walkthrough-staging', + kind: 'walkthrough', + testKind: 'staging', + maxAgeMilliseconds: 60_000, + trustedRunnerIds: ['portal-runner'], + }, + ], + }; + await app.putValidationPolicy(author, { + commandId: 'policy', + correlationId: 'setup', + expectedGeneration: 0, + policy, + }); + await app.putGovernanceConfiguration(author, { + commandId: 'governance', + correlationId: 'setup', + collectionId, + expectedGeneration: (await app.getCollection(author, { collectionId })) + .generation, + configuration: { + validationPolicy: { id: policy.id, version: policy.version }, + expectedStagingBuildId: 'portal-build', + trustedAttesterIds: [authorId], + }, + }); + await app.createDraft(author, { + commandId: 'draft', + correlationId: 'setup', + expectedGeneration: 0, + articleId, + collectionId, + draft: { + kind: 'explanation', + title: privateTitle, + summary: 'Restricted synthetic export instructions.', + content: { format: 'plain_text', text: privateText }, + tags: ['export'], + applicability: { productId: 'portal-product', productVersion: '1' }, + }, + }); + const current = await app.getDraft(author, { articleId }); + const evidence: EvidenceSubmission = { + id: 'portal-content-run', + articleId, + articleRevision: current.revision.number, + contentHash: current.revision.contentHash, + validationPolicy: current.revision.validationPolicy, + checkId: 'explanation-content', + testKind: 'content', + applicability: current.revision.applicability, + stagingBuildId: 'portal-build', + steps: ['Read and verify the synthetic export guide.'], + result: 'passed', + executedAt: clock.now(), + runnerId: 'portal-runner', + artifacts: [{ id: 'portal-artifact', hash: 'a'.repeat(64) }], + }; + const report = await runtime.evidence.report(author, { + commandId: 'report', + articleId, + ledgerEpoch: 1, + evidence, + report: { + summary: 'Private test report.', + details: 'Private test details.', + }, + }); + const view = await runtime.evidence.read(author, { + articleId, + reportId: report.reportId, + ledgerEpoch: report.ledgerEpoch, + }); + await runtime.evidence.decide( + author, + { + commandId: 'confirm', + articleId, + reportId: report.reportId, + ledgerEpoch: report.ledgerEpoch, + expectedReportGeneration: view.expectedReportGeneration, + reviewBindingHash: view.reviewBindingHash, + }, + 'confirmed', + ); + await app.submitEvidence(author, { + commandId: 'evidence', + correlationId: 'setup', + articleId, + expectedGeneration: current.generation, + evidence, + receipt: report.receipt, + }); + await app.submitForReview(author, { + commandId: 'review', + correlationId: 'setup', + articleId, + expectedGeneration: (await app.getDraft(author, { articleId })).generation, + }); + const review = await app.getReview(author, { articleId }); + await app.publishArticle(author, { + commandId: 'publish', + correlationId: 'setup', + articleId, + expectedGeneration: review.generation, + review: review.review, + }); + let indexed = await app.repairArticleIndex(author, { + articleId, + maxBatches: 1, + }); + for (let attempt = 0; attempt < 7 && indexed.status === 'pending'; attempt++) + indexed = await app.repairArticleIndex(author, { + articleId, + maxBatches: 1, + }); + expect(indexed.status).toBe('ready'); + + function cookie(key: string) { + const sessionId = sessionIds.get(key); + if (sessionId === undefined) throw new Error('Missing real session.'); + return SESSION_COOKIE + '=' + sessionId; + } + function request(operation: Operation, principal = readerId) { + return new Request(IDENTITY_ISSUER + '/api/knowledge/portal', { + method: 'POST', + headers: { + Cookie: cookie(principal), + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + 'X-Pegma-CSRF': 'c'.repeat(43), + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + operation, + input: + operation === 'getPublishedArticle' + ? { articleId } + : operation === 'listPortalCollections' + ? {} + : { + collectionId, + query: 'export', + applicability: current.revision.applicability, + }, + }), + }); + } + function block() { + let entered = () => {}; + let release = () => {}; + const ready = new Promise((resolve) => (entered = resolve)); + const resume = new Promise((resolve) => (release = resolve)); + afterRead = async () => { + entered(); + await resume; + }; + return { + release, + async waitFor(pending: Promise) { + let timer: ReturnType | undefined; + try { + await Promise.race([ + ready, + pending.then(() => { + throw new Error('Portal returned before its real KB barrier.'); + }), + new Promise((_resolve, reject) => { + timer = setTimeout( + () => reject(new Error('Portal did not reach its KB barrier.')), + 3_000, + ); + }), + ]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } + }, + }; + } + async function revokeReader() { + const assignment = await roleStore.getRoleAssignment('reader-knowledge'); + if (assignment === null) throw new Error('Missing actual Knowledge role.'); + const result = await roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: assignment.assignment.id, + expectedConcurrencyToken: assignment.concurrencyToken, + revokedBy: { kind: 'principal', principalId: authorId }, + revokedAtEpochMs: Date.parse(clock.now()), + reason: 'Synthetic audience revocation.', + auditEventId: 'revoke-reader', + }); + expect(result.status).toBe('revoked'); + } + return { + runtime, + request, + cookie, + block, + revokeReader, + grant, + reads: () => reads, + }; +} + +async function expectPrivateResult( + response: Response | null, + operation: Operation, +) { + expect(response?.status).toBe(200); + const value: unknown = await response?.json(); + const encoded = JSON.stringify(value); + expect(encoded).toContain( + operation === 'listPortalCollections' ? privateLabel : privateTitle, + ); + expect(encoded).not.toContain('Private test report.'); + expect(encoded).not.toContain('Private test details.'); +} + +async function controlledPortalBody(base: Request) { + const encoded = new TextEncoder().encode(await base.text()); + let source: ReadableStreamDefaultController | undefined; + let entered = () => {}; + let resume = () => {}; + const reading = new Promise((resolve) => (entered = resolve)); + const released = new Promise((resolve) => (resume = resolve)); + let closed = false; + let sent = 0; + const cancel = vi.fn(() => { + closed = true; + }); + const stream = new ReadableStream( + { + start(controller) { + source = controller; + }, + pull() { + entered(); + return released; + }, + cancel, + }, + { highWaterMark: 0 }, + ); + const options: RequestInit & { duplex: 'half' } = { + method: 'POST', + headers: base.headers, + body: stream, + duplex: 'half', + }; + return { + request: new Request(base.url, options), + reading, + cancel, + trickle() { + if (closed || source === undefined) + throw new Error('The actual portal body is no longer open.'); + const end = Math.min(encoded.length, sent + 8); + source.enqueue(encoded.slice(sent, end)); + sent = end; + }, + complete() { + if (!closed && source !== undefined) { + source.enqueue(encoded.slice(sent)); + sent = encoded.length; + source.close(); + closed = true; + } + resume(); + }, + }; +} + +describe.each(operations)( + 'authenticated portal %s body deadline', + (operation) => { + it.each(['stalled', 'trickled'] as const)( + 'rejects a %s body at the total deadline before reading private KB facts', + async (kind) => { + const f = await fixture(); + const body = await controlledPortalBody(f.request(operation)); + const initialReads = f.reads(); + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }); + let settled = false; + const pending = f.runtime.handle(body.request).finally(() => { + settled = true; + }); + try { + await body.reading; + expect(f.reads()).toBe(initialReads); + await vi.advanceTimersByTimeAsync(9_000); + if (kind === 'trickled') body.trickle(); + await vi.advanceTimersByTimeAsync(999); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + // Fail promptly on the old path; finally releases its real body so a + // ROOT RED run observes the defect without leaving a parked request. + expect(settled).toBe(true); + const result = await pending; + expect(result?.status).toBe(408); + expect(await result?.json()).toEqual({ error: 'request_timeout' }); + expect(f.reads()).toBe(initialReads); + expect(body.cancel).toHaveBeenCalledTimes(1); + expect(body.request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + } finally { + body.complete(); + try { + await pending; + } finally { + vi.useRealTimers(); + } + } + }, + ); + + it('returns the actual restricted publication when the body completes before expiry', async () => { + const f = await fixture(); + const body = await controlledPortalBody(f.request(operation)); + const initialReads = f.reads(); + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }); + let settled = false; + const pending = f.runtime.handle(body.request).finally(() => { + settled = true; + }); + try { + await body.reading; + await vi.advanceTimersByTimeAsync(9_999); + expect(settled).toBe(false); + expect(f.reads()).toBe(initialReads); + body.complete(); + await expectPrivateResult(await pending, operation); + expect(f.reads()).toBeGreaterThan(initialReads); + expect(body.cancel).not.toHaveBeenCalled(); + expect(body.request.body?.locked).toBe(false); + expect(vi.getTimerCount()).toBe(0); + } finally { + body.complete(); + try { + await pending; + } finally { + vi.useRealTimers(); + } + } + }); + }, +); + +describe('current permission-scoped portal authority after real KB reads', () => { + it.each(operations)( + 'keeps same-session authorized %s available', + async (operation) => { + const f = await fixture(); + await expectPrivateResult( + await f.runtime.handle(f.request(operation)), + operation, + ); + const customer = await f.runtime.handle(f.request(operation, customerId)); + const encoded = JSON.stringify(await customer?.json()); + expect(encoded).not.toContain(privateLabel); + expect(encoded).not.toContain(privateTitle); + expect(encoded).not.toContain(privateText); + }, + ); + + it.each(operations)( + 'withholds %s after its real audience role is revoked', + async (operation) => { + const f = await fixture(); + await expectPrivateResult( + await f.runtime.handle(f.request(operation)), + operation, + ); + const blocked = f.block(); + const pending = f.runtime.handle(f.request(operation)); + try { + await blocked.waitFor(pending); + await f.revokeReader(); + } finally { + blocked.release(); + } + const response = await pending; + expect(response?.status).toBe(403); + expect(await response?.json()).toEqual({ error: 'forbidden' }); + }, + ); + + it.each(operations)( + 'allows added grants without changing %s authority', + async (operation) => { + const f = await fixture(); + const blocked = f.block(); + const pending = f.runtime.handle(f.request(operation)); + try { + await blocked.waitFor(pending); + await f.grant('reader-support', readerId, SUPPORT_ROLE); + } finally { + blocked.release(); + } + await expectPrivateResult(await pending, operation); + }, + ); + + for (const replacement of [otherId, 'reader-second-session']) { + it.each(operations)( + `withholds %s after a valid ${replacement} session replaces the caller`, + async (operation) => { + const f = await fixture(); + const request = f.request(operation); + const blocked = f.block(); + const pending = f.runtime.handle(request); + try { + await blocked.waitFor(pending); + request.headers.set('Cookie', f.cookie(replacement)); + } finally { + blocked.release(); + } + const response = await pending; + expect(response?.status).toBe(403); + expect(await response?.json()).toEqual({ + error: 'browser_credential_changed', + }); + }, + ); + } +}); diff --git a/worker/src/knowledge-query-budget.d1.test.ts b/worker/src/knowledge-query-budget.d1.test.ts new file mode 100644 index 0000000..78a0bfe --- /dev/null +++ b/worker/src/knowledge-query-budget.d1.test.ts @@ -0,0 +1,1807 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import { env } from 'cloudflare:workers'; +import type { + ApprovalView, + PublicClient, + TokenResult, +} from '@pegma/agent-access'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { articleKinds } from '@pegma/knowledge-base-contracts'; +import type { + ArticleDraft, + EvidenceSubmission, +} from '@pegma/knowledge-base-core'; +import { + createKnowledgeBaseApplication, + knowledgeRecords, + type KnowledgeRecord, + type DraftArticleDto, +} from '@pegma/knowledge-base-application'; +import { + knowledgeAgentScopes, + knowledgeAgentToolNames, + type KnowledgeAgentOperation, +} from '@pegma/knowledge-base-mcp'; +import { createSessionStore } from '@pegma/sessions'; +import { createDurableLimiter } from '@pegma/rate-limit-paged'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { createAgentPrincipalResolver } from './agent-authority'; +import { + AGENT_RESOURCE, + createAgentAccessRuntime, +} from './agent-access-runtime'; +import { isPlainObject } from './api-auth'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import { createIdentityRuntime } from './identity-runtime'; +import { handleKnowledgeRequest } from './knowledge-host'; +import worker from './index'; +import { createKnowledgeRetrievalReady } from './knowledge-retrieval-ready'; +import { runKnowledgeMaintenance } from './knowledge-maintenance'; +import { + defineCollection, + type CollectionDefinition, + type CollectionStore, + type Store, + type StoredRecord, +} from '@pegma/storage-core'; +import { + CLEANUP_CRON, + RATE_LIMIT_CRON, + cleanupLaneAt, + rateKnowledgeLaneAt, +} from './maintenance-schedule'; +import type { KnowledgeReportView } from './knowledge-evidence'; +import { + ADMIN_ROLE, + APPLICATION_SCOPE, + AUTHORIZATION_APPLICATION_ID, + KNOWLEDGE_ROLE, +} from './support-access'; + +declare global { + namespace Cloudflare { + interface Env { + IDENTITY_DB: D1Database; + } + } +} + +const schema = [ + 'CREATE TABLE IF NOT EXISTS RECORDS (partition_key TEXT NOT NULL, row_key TEXT NOT NULL, record_json TEXT, version INTEGER NOT NULL, deleted INTEGER NOT NULL CHECK (deleted IN (0, 1)), PRIMARY KEY (partition_key, row_key)) STRICT', + 'CREATE TABLE IF NOT EXISTS PEGMA_STORAGE_D1_TX_GUARD (reason TEXT NOT NULL) STRICT', + ...(['exists', 'missing', 'changed'] as const).map( + (reason) => + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_${reason.toUpperCase()} BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD WHEN NEW.reason = '${reason}' BEGIN SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_${reason.toUpperCase()}'); END`, + ), +]; + +beforeAll(async () => { + for (const statement of schema) + await env.IDENTITY_DB.prepare(statement).run(); +}); +beforeEach(async () => { + completedBudgets.length = 0; + profileFacts = {}; + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); + +interface RequestBudget { + readonly operation: string; + calls: number; + statements: number; + batches: number; + batchSizes: number[]; + status?: number; + maximumCalls?: 50; + blockedExecutions?: number; +} + +const completedBudgets: RequestBudget[][] = []; +let profileFacts: Record = {}; +// Root's private reporter reads TestCase.meta().knowledgeQueryBudget on both +// success and failure. No filesystem capability is added to the Worker. +afterEach(({ task }) => { + Object.assign(task.meta, { + knowledgeQueryBudget: { + schemaVersion: 1, + requests: structuredClone(completedBudgets.flat()), + facts: { ...profileFacts }, + }, + }); +}); + +/** Count actual binding executions, not Store calls or prepared statements. + * Cloudflare documents one batch as one invocation-budget query: + * https://developers.cloudflare.com/d1/platform/limits/#batch-limits + */ +function measuredDatabase(backing: D1Database) { + const scope = new AsyncLocalStorage(); + const requests: RequestBudget[] = []; + let failScheduledBatch = false; + let afterScheduledKnowledgeBatch: (() => Promise) | undefined; + let beforeScheduledCheckpointWrite: + ((version: string) => Promise) | undefined; + const scheduledCheckpointWrites: { version: string; written: boolean }[] = []; + completedBudgets.push(requests); + const originals = new WeakMap(); + const bindings = new WeakMap(); + function execution(statements = 1, batch = false) { + const budget = scope.getStore(); + if (budget === undefined) return; + budget.calls += 1; + if ( + budget.maximumCalls !== undefined && + budget.calls > budget.maximumCalls + ) { + budget.blockedExecutions = (budget.blockedExecutions ?? 0) + 1; + throw new Error( + 'Synthetic invocation D1 limit reached before execution51.', + ); + } + budget.statements += statements; + if (batch) { + budget.batches += 1; + budget.batchSizes.push(statements); + } + } + function wrap( + original: D1PreparedStatement, + boundValues: readonly unknown[] = [], + ): D1PreparedStatement { + const statement: D1PreparedStatement = { + bind(...values: unknown[]) { + return wrap(original.bind(...values), values); + }, + async first>( + column?: string, + ): Promise { + execution(); + // Observe the actual conditional call's public bookmark key/version. + // Do not inspect or replace its SQL, result, or OCC decision. + const checkpoint = + beforeScheduledCheckpointWrite !== undefined && + scope.getStore()?.operation.startsWith('scheduled.') === true && + boundValues.length === 4 && + boundValues.includes('pegma-dev-maintenance:knowledge') && + boundValues.includes('rate-limits'); + const version = checkpoint ? boundValues[3] : undefined; + if (checkpoint && typeof version !== 'string') + throw new Error('Expected the actual checkpoint concurrency token.'); + if (typeof version === 'string') + await beforeScheduledCheckpointWrite?.(version); + const result = + column === undefined + ? await original.first() + : await original.first(column); + if (typeof version === 'string') + scheduledCheckpointWrites.push({ version, written: result !== null }); + return result; + }, + run>() { + execution(); + return original.run(); + }, + all>() { + execution(); + return original.all(); + }, + raw: original.raw, + }; + // Preserve the public raw overloads and the real statement receiver. + statement.raw = new Proxy(original.raw, { + apply(target, _receiver, args) { + execution(); + return Reflect.apply(target, original, args); + }, + }); + originals.set(statement, original); + bindings.set(statement, boundValues); + return statement; + } + const database: D1Database = { + prepare(query) { + return wrap(backing.prepare(query)); + }, + async batch(statements: D1PreparedStatement[]) { + const native = statements.map((statement) => { + const original = originals.get(statement); + if (original === undefined) + throw new Error('Unobserved D1 batch statement.'); + return original; + }); + execution(native.length, true); + const scheduled = + scope.getStore()?.operation.startsWith('scheduled.') === true; + if (scheduled && failScheduledBatch) { + failScheduledBatch = false; + throw new Error('Synthetic D1 transport failure.'); + } + const result = await backing.batch(native); + // The public SDK record namespace identifies its real keyed read wave. + // Do not pause checkpoint.get (also batched with readBatchSize512), + // inspect private SQL, or assume a particular batch ordinal. + const knowledgeWave = statements.some((statement) => + bindings + .get(statement) + ?.some( + (value) => + typeof value === 'string' && + value.includes(knowledgeRecords.name), + ), + ); + const after = + scheduled && knowledgeWave ? afterScheduledKnowledgeBatch : undefined; + if (after !== undefined) { + afterScheduledKnowledgeBatch = undefined; + await after(); + } + return result; + }, + exec() { + throw new Error('Unexpected D1 exec in a measured application request.'); + }, + dump() { + throw new Error('Unexpected D1 dump in a measured application request.'); + }, + withSession() { + throw new Error('The production Store must use the direct D1 binding.'); + }, + }; + return { + database, + requests, + scheduledCheckpointWrites, + beforeScheduledCheckpointWrite(hook: (version: string) => Promise) { + beforeScheduledCheckpointWrite = hook; + }, + currentOperation() { + return scope.getStore()?.operation; + }, + outsideRequest(run: () => Promise): Promise { + return scope.exit(run); + }, + failNextScheduledBatch() { + failScheduledBatch = true; + }, + afterNextScheduledKnowledgeBatch(hook: () => Promise) { + afterScheduledKnowledgeBatch = hook; + }, + async request( + operation: string, + run: () => Promise, + hardLimit = false, + ) { + const budget: RequestBudget = { + operation, + calls: 0, + statements: 0, + batches: 0, + batchSizes: [], + ...(hardLimit ? { maximumCalls: 50 as const } : {}), + }; + requests.push(budget); + return scope.run(budget, async () => { + const response = await run(); + // Include any work deferred until the HTTP/MCP response is consumed. + await response.clone().arrayBuffer(); + budget.status = response.status; + return response; + }); + }, + assertFreeBudget() { + console.info('knowledge-d1-request-budgets', JSON.stringify(requests)); + expect(requests.length).toBeGreaterThan(0); + for (const budget of requests) { + expect.soft(budget.calls, JSON.stringify(budget)).toBeGreaterThan(0); + expect + .soft(budget.calls, JSON.stringify(budget)) + .toBeLessThanOrEqual(50); + } + }, + }; +} + +// Read-only physical diagnostics, never a copied encoder or a fixture write. +const readyDiagnostics = defineCollection({ + name: 'pegma-dev.knowledge-retrieval-ready.v1', + key: (value) => ({ partition: 'knowledge', id: String(value.id) }), + codec: { encode: (value) => value, decode: (value) => value }, +}); + +// The adversary rewrites only a real producer-created bookmark, unchanged. +// No synthetic head, generation, cursor, limiter codec or SQL write is created. +const rateCheckpointDiagnostics = defineCollection({ + name: 'pegma-dev-maintenance', + key: (value) => ({ + partition: String(value.partition), + id: String(value.id), + }), + codec: { encode: (value) => value, decode: (value) => value }, +}); + +const owner = 'query-budget-owner'; +const reviewer = 'query-budget-reviewer'; +const collectionId = 'query-budget-guides'; +const articleId = 'query-budget-article'; +const scopes = Object.values(knowledgeAgentScopes); +const client: PublicClient = { + clientId: 'synthetic-query-budget-client', + name: 'Synthetic query budget client', + redirectUris: ['https://client.example.test/callback'], + allowedScopes: scopes, + grantTypes: ['authorization_code'], +}; +const draft: ArticleDraft = { + kind: 'explanation', + title: 'Synthetic measured guide', + summary: 'A complete guide used only by local D1 tests.', + content: { + format: 'plain_text', + text: 'Read the synthetic input and compare its output.', + }, + tags: [], + applicability: { + productId: 'query-budget', + productVersion: '1', + buildId: 'query-budget-1', + }, +}; +type Transport = 'http' | 'mcp'; + +function object(value: unknown): Record { + if (!isPlainObject(value)) throw new Error('Expected a public JSON object.'); + return value; +} +function text(value: unknown): string { + if (typeof value !== 'string' || value.length === 0) + throw new Error('Expected a nonempty public string.'); + return value; +} +function integer(value: unknown): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value)) + throw new Error('Expected an integer in the public result.'); + return value; +} + +async function fixture(isolateSetupAdmission = false) { + const meter = measuredDatabase(env.IDENTITY_DB); + const store = createCloudflareD1Store({ + database: meter.database, + createSchemaIfMissing: false, + }); + const logger = { log() {} }; + const clock = { now: () => new Date().toISOString() }; + const secret = btoa('q'.repeat(32)); + const identity = createIdentityRuntime( + { + store, + emailCodeSecretBase64: secret, + emailFrom: 'Pegma ', + emailEnabled: false, + }, + logger, + ).identity; + const sessions = createSessionStore(store, { logger, clock }); + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + const cookies = new Map(); + for (const [index, principalId] of [owner, reviewer].entries()) { + await identity.provisionVerifiedUser({ + principalId, + email: principalId + '@example.test', + }); + const granted = await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: 'role-' + principalId, + principalId, + role: principalId === owner ? ADMIN_ROLE : KNOWLEDGE_ROLE, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-query-budget-setup' }, + grantedAtEpochMs: Date.now(), + status: 'active', + }, + auditEventId: 'grant-' + principalId, + }); + expect(granted.status).toBe('granted'); + const sessionId = String(index) + 'q'.repeat(42); + await sessions.create(sessionId, { + principalId, + data: JSON.stringify({ + version: 1, + csrfToken: 'c'.repeat(43), + issuer: IDENTITY_ISSUER, + subject: principalId, + }), + }); + cookies.set(principalId, SESSION_COOKIE + '=' + sessionId); + } + const configuration = { + IDENTITY_DB: meter.database, + IDENTITY_EMAIL_CODE_SECRET_BASE64: secret, + IDENTITY_EMAIL_FROM: 'Pegma ', + IDENTITY_EMAIL_ENABLED: 'false', + PEGMA_KNOWLEDGE_ENABLED: 'true', + PEGMA_AGENT_CLIENTS_JSON: JSON.stringify([client]), + }; + // The production entry composes fresh Identity/AA/KB/limiters on every call. + let setupRequests = 0; + const send = (request: Request, operation?: string) => { + if (isolateSetupAdmission && operation === undefined) { + // Synthetic independent peers, <=64 setup calls per peer: unchanged + // production120/300 per-IP admission budgets still apply to every call. + const peer = Math.floor(setupRequests++ / 64) + 1; + request.headers.set('CF-Connecting-IP', '2001:db8::' + peer.toString(16)); + profileFacts.setupRequests = setupRequests; + } + const run = () => handleKnowledgeRequest(request, configuration, logger); + return operation === undefined ? run() : meter.request(operation, run); + }; + function browser(path: string, body?: unknown, principalId = reviewer) { + const cookie = cookies.get(principalId); + if (cookie === undefined) + throw new Error('Expected the real browser session.'); + return new Request(IDENTITY_ISSUER + path, { + method: body === undefined ? 'GET' : 'POST', + headers: { + Cookie: cookie, + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + 'X-Pegma-CSRF': 'c'.repeat(43), + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + } + async function staff( + operation: string, + input: unknown, + measured = true, + principalId = reviewer, + ) { + const response = await send( + browser( + '/api/staff/knowledge/command', + { operation, input }, + principalId, + ), + measured ? 'staff.' + operation : undefined, + ); + expect(response.status, operation).toBe(200); + return object(await response.json()); + } + const resolvePrincipal = createAgentPrincipalResolver({ + identity, + roleStore, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }); + const access = await resolvePrincipal(owner); + if (access === null) + throw new Error('Expected actual current setup authority.'); + const app = createKnowledgeBaseApplication({ store, clock }); + const collection = await app.createCollection(access, { + commandId: 'setup-collection', + correlationId: 'query-budget', + expectedGeneration: 0, + collectionId, + name: 'Synthetic query budget guides', + }); + await app.putValidationPolicy(access, { + commandId: 'setup-policy', + correlationId: 'query-budget', + expectedGeneration: 0, + policy: { + id: 'query-budget-policy', + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: kind + '-content', + kind, + testKind: 'content', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: ['query-budget-runner'], + })), + { + id: 'walkthrough-workflow', + kind: 'walkthrough', + testKind: 'workflow', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: ['query-budget-runner'], + }, + ], + }, + }); + await app.putGovernanceConfiguration(access, { + commandId: 'setup-governance', + correlationId: 'query-budget', + expectedGeneration: collection.value.generation, + collectionId, + configuration: { + validationPolicy: { id: 'query-budget-policy', version: 1 }, + expectedStagingBuildId: 'query-budget-1', + trustedAttesterIds: [reviewer], + }, + }); + const verifier = 'v'.repeat(64); + const challenge = btoa( + String.fromCharCode( + ...new Uint8Array( + await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(verifier), + ), + ), + ), + ) + .replaceAll('+', '-') + .replaceAll('/', '_') + .replace(/=+$/, ''); + const redirectUri = client.redirectUris[0]; + if (redirectUri === undefined) + throw new Error('Expected the explicit synthetic callback.'); + const authorization = new URLSearchParams({ + response_type: 'code', + client_id: client.clientId, + redirect_uri: redirectUri, + resource: AGENT_RESOURCE, + scope: scopes.join(' '), + code_challenge: challenge, + code_challenge_method: 'S256', + state: 'synthetic-budget-state', + }); + const begun = await send( + browser('/api/agent-access/authorize?' + authorization, undefined, owner), + ); + expect(begun.status).toBe(303); + const requestId = new URL( + text(begun.headers.get('Location')), + ).searchParams.get('request_id'); + const viewed = await send( + browser( + '/api/agent-access/approval?request_id=' + + encodeURIComponent(text(requestId)), + undefined, + owner, + ), + ); + expect(viewed.status).toBe(200); + const approval: ApprovalView = await viewed.json(); + expect(approval.requestedScopes.map((scope) => scope.name)).toEqual(scopes); + const approved = await send( + browser( + '/api/agent-access/approval', + { + requestId: approval.requestId, + decision: 'approve', + approvedScopes: scopes, + }, + owner, + ), + ); + expect(approved.status).toBe(200); + const consent = object(await approved.json()); + const redirect = new URL(text(consent.redirectUri)); + expect(redirect.origin + redirect.pathname).toBe(redirectUri); + const exchanged = await send( + new Request(IDENTITY_ISSUER + '/api/agent-access/token', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + client_id: client.clientId, + redirect_uri: redirectUri, + resource: AGENT_RESOURCE, + code: text(redirect.searchParams.get('code')), + code_verifier: verifier, + }), + }), + ); + expect(exchanged.status).toBe(200); + const token: TokenResult = await exchanged.json(); + expect(token.scope.split(' ')).toEqual(scopes); + const inspection = createAgentAccessRuntime({ + store, + clock, + logger, + identity, + sessions, + roleStore, + clients: [client], + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + }); + if (inspection === null) + throw new Error('Expected the actual configured issuer.'); + const delegated = await inspection.service.authenticate({ + token: token.access_token, + resource: AGENT_RESOURCE, + }); + expect(delegated.access.permissions.slice().sort()).toEqual( + scopes.slice().sort(), + ); + expect(delegated.access.roles).toEqual([]); + expect(delegated.access.entitlements).toEqual([]); + function agentRequest(path: string, body?: unknown) { + return new Request(IDENTITY_ISSUER + path, { + method: body === undefined ? 'GET' : 'POST', + headers: { + Authorization: 'Bearer ' + token.access_token, + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + 'MCP-Protocol-Version': '2025-06-18', + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + } + async function agent( + transport: Transport, + operation: KnowledgeAgentOperation, + input: unknown, + label: string | false = operation, + sourceIp?: string, + ) { + const wire = + transport === 'http' + ? { apiVersion: '1', operation, input } + : { + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { + name: knowledgeAgentToolNames[operation], + arguments: input, + }, + }; + const request = agentRequest( + transport === 'http' ? '/api/knowledge/v1' : '/api/knowledge/mcp', + wire, + ); + if (sourceIp !== undefined) + request.headers.set('CF-Connecting-IP', sourceIp); + const response = await send( + request, + label === false ? undefined : transport + '.' + label, + ); + expect(response.status, operation).toBe(200); + let logical = object(await response.json()); + if (transport === 'mcp') { + const rpc = object(logical.result); + expect(rpc.isError).toBe(false); + if (!Array.isArray(rpc.content)) + throw new Error('Expected real MCP tool content.'); + const first = object(rpc.content[0]); + logical = object(JSON.parse(text(first.text))); + } + expect(logical.operation).toBe(operation); + return object(logical.result); + } + let scheduledTick = Math.floor(Date.now() / 60_000) * 60_000; + let physicalTick = scheduledTick; + async function scheduled(kind: 'ready' | 'physical' = 'ready') { + let time = kind === 'ready' ? scheduledTick : physicalTick; + if (kind === 'physical') { + while ( + new Date(time).getUTCMinutes() === 59 || + cleanupLaneAt(time).kind !== 'knowledge' + ) + time += 60_000; + physicalTick = time + 60_000; + } else { + const eligible = Array.from( + { length: 120 }, + (_, offset) => time + offset * 60_000, + ).find( + (candidate) => + new Date(candidate).getUTCMinutes() <= 57 && + rateKnowledgeLaneAt(candidate) === 'retrieval_ready', + ); + if (eligible === undefined) + throw new Error('No actual ready-lane tick in the bounded schedule.'); + time = eligible; + scheduledTick = time + 60_000; + } + return meter.request( + 'scheduled.' + kind, + async () => { + const pending: Promise[] = []; + worker.scheduled( + { + cron: kind === 'ready' ? RATE_LIMIT_CRON : CLEANUP_CRON, + scheduledTime: time, + noRetry() {}, + }, + configuration as Parameters[1], + { + waitUntil(promise) { + pending.push(promise); + }, + passThroughOnException() {}, + props: {}, + exports: {}, + } as ExecutionContext, + ); + expect(pending).toHaveLength(1); + await Promise.all(pending); + return Response.json({ completed: true }); + }, + true, + ); + } + return { + meter, + scheduled, + logger, + app, + access, + send, + staff, + agent, + agentRequest, + browser, + clock, + store, + }; +} + +describe('real production KB request budgets over actual D1', () => { + it('counts real execution methods once, a multi-statement batch once, and no prepare or bind calls', async () => { + const meter = measuredDatabase(env.IDENTITY_DB); + const statement = meter.database.prepare('SELECT ? AS value').bind(1); + await meter.request('counter-calibration', async () => { + expect(meter.requests[0]?.calls).toBe(0); + await statement.first(); + await statement.all(); + await statement.run(); + await statement.raw(); + const first = meter.database.prepare('SELECT 2 AS value'); + const second = meter.database.prepare('SELECT 3 AS value'); + await meter.database.batch([first, second]); + return Response.json({ complete: true }); + }); + expect(meter.requests).toEqual([ + { + operation: 'counter-calibration', + calls: 5, + statements: 6, + batches: 1, + batchSizes: [2], + status: 200, + }, + ]); + }); + + it('throws before the51st real D1 execution, even if application code catches the quota error', async () => { + const meter = measuredDatabase(env.IDENTITY_DB); + await meter.request( + 'hard-limit-calibration', + async () => { + for (let index = 0; index < 50; index++) + await meter.database.prepare('SELECT 1 AS value').first(); + let rejected = false; + try { + await meter.database.prepare('SELECT 51 AS value').first(); + } catch { + rejected = true; + } + expect(rejected).toBe(true); + return Response.json({ complete: true }); + }, + true, + ); + expect(meter.requests[0]).toMatchObject({ + calls: 51, + statements: 50, + maximumCalls: 50, + blockedExecutions: 1, + }); + }); + + it('keeps overlapping invocation counts separate across awaited real D1 calls', async () => { + const meter = measuredDatabase(env.IDENTITY_DB); + let entered = () => {}; + let resume = () => {}; + const ready = new Promise((resolve) => { + entered = resolve; + }); + const paused = new Promise((resolve) => { + resume = resolve; + }); + const first = meter.request('pending-request', async () => { + await meter.database.prepare('SELECT 1').first(); + entered(); + await paused; + await meter.database.prepare('SELECT 2').first(); + return Response.json({ complete: true }); + }); + await ready; + try { + await meter.request('overlapping-request', async () => { + await meter.database.prepare('SELECT 3').all(); + return Response.json({ complete: true }); + }); + } finally { + resume(); + } + await first; + expect( + meter.requests.map(({ operation, calls }) => ({ operation, calls })), + ).toEqual([ + { operation: 'pending-request', calls: 2 }, + { operation: 'overlapping-request', calls: 1 }, + ]); + }); + + it('sweeps twenty real expired rows within 48 calls after two independent bookmark CAS conflicts', async () => { + const meter = measuredDatabase(env.IDENTITY_DB); + const store = createCloudflareD1Store({ + database: meter.database, + createSchemaIfMissing: false, + }); + const clock = { now: () => new Date().toISOString() }; + // Setup is outside every measured invocation. The real producer creates + // the bookmark before genuine peers can change only its opaque version. + await runKnowledgeMaintenance({ store, clock }, { log() {} }); + const checkpoints = store.collection(rateCheckpointDiagnostics); + const key = { partition: 'knowledge', id: 'rate-limits' }; + const initial = await checkpoints.getVersioned(key); + if (initial === null) + throw new Error('Missing producer-created checkpoint.'); + expect(initial.value.cursor).toBeNull(); + const limiter = createDurableLimiter( + { name: 'pegma.test.actual-d1-occ', limit: 1, windowMs: 60_000 }, + store, + ); + const expiredAt = new Date(Date.now() - 180_000).toISOString(); + for (let index = 0; index < 20; index++) + expect(await limiter.allow('192.0.2.' + (index + 1), expiredAt)).toEqual({ + allowed: true, + }); + const liveRows = () => + env.IDENTITY_DB.prepare( + 'SELECT COUNT(*) AS count FROM RECORDS WHERE deleted = 0', + ).first('count'); + // Exactly twenty real counters, their real descriptor, and the bookmark. + const beforeRows = await liveRows(); + expect(beforeRows).toBe(22); + const operation = 'scheduled.rate-limits.two-real-conflicts'; + let attempts = 0; + let peerWrites = 0; + const peerReadVersions: string[] = []; + meter.beforeScheduledCheckpointWrite(async (version) => { + attempts += 1; + expect(meter.currentOperation()).toBe(operation); + if (attempts > 2) return; + const peerNumber = attempts; + // These are other invocations, not free work inside the scheduled one. + // Each uses the same real metered D1 binding under its own ALS budget. + await meter.outsideRequest(async () => { + expect(meter.currentOperation()).toBeUndefined(); + await meter.request( + 'external.bookmark-peer-' + peerNumber, + async () => { + expect(meter.currentOperation()).toBe( + 'external.bookmark-peer-' + peerNumber, + ); + const current = await checkpoints.getVersioned(key); + if (current === null) + throw new Error('Missing actual peer target.'); + expect(current.value).toEqual(initial.value); + expect(current.version).toBe(version); + peerReadVersions.push(current.version); + const written = await checkpoints.putIfUnchanged( + current.value, + current.version, + ); + expect(written).toBe(true); + peerWrites += 1; + return Response.json({ written }); + }, + true, + ); + }); + expect(meter.currentOperation()).toBe(operation); + }); + const startMinute = Math.floor(Date.now() / 60_000) * 60_000; + const scheduledTime = Array.from( + { length: 120 }, + (_, offset) => startMinute + offset * 60_000, + ).find( + (time) => + new Date(time).getUTCMinutes() <= 57 && + rateKnowledgeLaneAt(time) === 'rate_limits', + ); + if (scheduledTime === undefined) + throw new Error('No real rate-lane tick in the bounded schedule.'); + try { + await meter.request( + operation, + async () => { + const pending: Promise[] = []; + const configuration: Parameters[1] = { + ...env, + IDENTITY_DB: meter.database, + DATADOG_API_KEY: undefined, + PEGMA_KNOWLEDGE_ENABLED: 'false', + get IDENTITY_EMAIL_CODE_SECRET_BASE64(): string { + throw new Error('Rate cleanup must not initialize Identity.'); + }, + }; + Object.defineProperty(configuration, 'PEGMA_AGENT_CLIENTS_JSON', { + value: 'not-json', + }); + worker.scheduled( + { cron: RATE_LIMIT_CRON, scheduledTime, noRetry() {} }, + configuration, + { + waitUntil(promise) { + pending.push(promise); + }, + passThroughOnException() {}, + props: {}, + exports: {}, + } as ExecutionContext, + ); + expect(pending).toHaveLength(1); + await Promise.all(pending); + return Response.json({ complete: true }); + }, + true, + ); + expect(meter.currentOperation()).toBeUndefined(); + expect(attempts).toBe(3); + expect(peerWrites).toBe(2); + expect( + meter.scheduledCheckpointWrites.map((entry) => entry.written), + ).toEqual([false, false, true]); + const attemptedVersions = meter.scheduledCheckpointWrites.map( + (entry) => entry.version, + ); + expect(new Set(attemptedVersions).size).toBe(3); + expect(peerReadVersions).toEqual(attemptedVersions.slice(0, 2)); + const final = await checkpoints.getVersioned(key); + expect(final?.value.generation).toBe( + integer(initial.value.generation) + 1, + ); + expect(final?.version).not.toBe(attemptedVersions[2]); + const afterRows = await liveRows(); + expect(afterRows).toBe(2); + const scheduled = meter.requests.find( + (entry) => entry.operation === operation, + ); + if (scheduled === undefined) throw new Error('Missing scheduled budget.'); + expect(scheduled.calls).toBeLessThanOrEqual(48); + expect(scheduled.blockedExecutions ?? 0).toBe(0); + const peers = meter.requests.filter((entry) => + entry.operation.startsWith('external.bookmark-peer-'), + ); + expect(peers.map((entry) => entry.calls)).toEqual([2, 2]); + profileFacts.rateRowsActuallyDeleted = + integer(beforeRows) - integer(afterRows); + profileFacts.rateBookmarkActualAttempts = attempts; + profileFacts.rateBookmarkActualConflicts = + meter.scheduledCheckpointWrites.filter( + (entry) => !entry.written, + ).length; + profileFacts.rateScheduledActualD1Calls = scheduled.calls; + profileFacts.rateIndependentPeerD1Calls = peers.reduce( + (sum, entry) => sum + entry.calls, + 0, + ); + profileFacts.ratePeersOutsideScheduledAls = true; + } finally { + meter.assertFreeBudget(); + } + }); + + it('rotates real pending hints after a D1 transport failure and preserves a newer enqueue during a scheduled completion', async () => { + const f = await fixture(); + const ready = () => + createKnowledgeRetrievalReady({ + store: f.store, + clock: f.clock, + logger: f.logger, + isEnabled: () => true, + }); + const ids = ['pending-a', 'pending-b', 'pending-c']; + for (const id of ids) { + await f.app.createDraft(f.access, { + commandId: 'create-' + id, + correlationId: 'test', + expectedGeneration: 0, + collectionId, + articleId: id, + draft, + }); + await ready().enqueue(id); + } + try { + f.meter.failNextScheduledBatch(); + await f.scheduled(); + let complete = false; + for (let tick = 0; tick < 48; tick++) { + await f.scheduled(); + const statuses = await Promise.all( + ids.map((id) => + f.app.getArticleIndexStatus(f.access, { articleId: id }), + ), + ); + if (statuses.every((status) => status.status === 'ready')) { + complete = true; + break; + } + } + expect(complete).toBe(true); + const hints = () => + f.store.collection(readyDiagnostics).scan({ limit: 100 }); + for (let tick = 0; tick < 16 && (await hints()).records.length; tick++) + await f.scheduled(); + expect((await hints()).records).toEqual([]); + await f.scheduled(); // Establish a persisted null cursor before reenqueuing. + // A stable ready article needs no projection mutation; race the exact + // queue version after the SDK's actual records wave, not the earlier + // checkpoint or queue read. The worker has already captured its version. + await ready().enqueue(ids[0]!); + let entered = () => {}; + let resume = () => {}; + const paused = new Promise((resolve) => { + entered = resolve; + }); + const resumed = new Promise((resolve) => { + resume = resolve; + }); + f.meter.afterNextScheduledKnowledgeBatch(async () => { + profileFacts.readyRaceAfterKnowledgeWave = true; + entered(); + await resumed; + }); + const worker = f.scheduled(); + await paused; + expect(profileFacts.readyRaceAfterKnowledgeWave).toBe(true); + const before = (await hints()).records[0]; + try { + await ready().enqueue(ids[0]!); + } finally { + resume(); + } + const newer = (await hints()).records[0]; + expect(newer?.version).not.toBe(before?.version); + await worker; + expect((await hints()).records).toEqual([newer]); + // The newer signal survives the old conditional deletion. Two cursor + // cycles must really revisit it, rather than silently dropping its ACK. + await f.scheduled(); + await f.scheduled(); + expect((await hints()).records).toEqual([]); + expect( + f.meter.requests.filter( + (request) => request.operation === 'scheduled.ready', + ).length, + ).toBeGreaterThan(3); + } finally { + f.meter.assertFreeBudget(); + } + }); + + it('recovers a genuinely lost ready enqueue through the real physical scheduled lane', async () => { + const f = await fixture(); + const id = 'lost-ready-hint'; + await f.app.createDraft(f.access, { + commandId: 'create-lost-hint', + correlationId: 'test', + expectedGeneration: 0, + collectionId, + articleId: id, + draft, + }); + let failed = false; + const faulty: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const collection = f.store.collection(definition); + return { + ...collection, + async put(value) { + if ( + definition.name === 'pegma-dev.knowledge-retrieval-ready.v1' && + !failed + ) { + failed = true; + throw new Error('Synthetic failed queue write.'); + } + return collection.put(value); + }, + }; + }, + }; + await createKnowledgeRetrievalReady({ + store: faulty, + clock: f.clock, + logger: f.logger, + isEnabled: () => true, + }).enqueue(id); + expect(failed).toBe(true); + try { + let complete = false; + for (let tick = 0; tick < 256; tick++) { + await f.scheduled('physical'); + const status = await f.app.getArticleIndexStatus(f.access, { + articleId: id, + }); + if (status.status === 'ready') { + complete = true; + break; + } + } + expect(complete).toBe(true); + } finally { + f.meter.assertFreeBudget(); + } + }); + + it.each(['http', 'mcp'] as const)( + 'keeps the complete %s report workflow within the Free per-request budget', + async (transport) => { + const f = await fixture(); + try { + await f.agent( + transport, + 'getValidationRequirements', + { collectionId, kind: draft.kind }, + 'requirements.initial', + ); + await f.agent(transport, 'createDraft', { + commandId: 'agent-create', + correlationId: 'query-budget', + expectedGeneration: 0, + articleId, + collectionId, + draft, + }); + const article: DraftArticleDto = await f.app.getDraft(f.access, { + articleId, + }); + const requirements = await f.agent( + transport, + 'getValidationRequirements', + { + collectionId, + kind: draft.kind, + articleId, + }, + 'requirements.article', + ); + const ledger = object(requirements.reportLedger); + const ledgerEpoch = integer(ledger.ledgerEpoch); + expect(ledger.status).toBe('active'); + const evidence: EvidenceSubmission = { + id: 'query-budget-evidence', + articleId, + articleRevision: article.revision.number, + contentHash: article.revision.contentHash, + validationPolicy: article.revision.validationPolicy, + checkId: 'explanation-content', + testKind: 'content', + applicability: article.revision.applicability, + stagingBuildId: 'query-budget-1', + steps: ['Read the synthetic guide', 'Compare the synthetic output'], + result: 'passed', + executedAt: f.clock.now(), + runnerId: 'query-budget-runner', + artifacts: [{ id: 'query-budget-output', hash: 'a'.repeat(64) }], + }; + const report = { + summary: 'Synthetic check passed', + details: 'Private synthetic report detail canary.', + }; + const queued = await f.agent( + transport, + 'submitEvidence', + { + commandId: 'protocol-report', + correlationId: 'query-budget', + expectedGeneration: article.generation, + articleId, + ledgerEpoch, + evidence, + report, + }, + 'report.queue', + ); + expect(queued.kind).toBe('pending-human-review'); + const reportId = text(queued.reportId); + expect( + (await f.app.getEvidence(f.access, { articleId })).evidence, + ).toEqual([]); + const lookup = { + collectionId, + kind: draft.kind, + articleId, + reportLookup: { ledgerEpoch, reportId }, + }; + const pending = await f.agent( + transport, + 'getValidationRequirements', + lookup, + 'report.poll.pending', + ); + expect(object(pending.reportStatus).status).toBe('pending'); + expect(JSON.stringify(pending)).not.toContain(report.details); + const manual = await f.send( + f.agentRequest('/api/knowledge/reports', { + commandId: 'manual-report', + articleId, + ledgerEpoch, + evidence, + report, + }), + 'manual.report.submit', + ); + expect(manual.status).toBe(200); + const manualLedger = await f.send( + f.agentRequest('/api/knowledge/reports?articleId=' + articleId), + 'manual.report.ledger', + ); + expect(manualLedger.status).toBe(200); + expect(object(await manualLedger.json()).ledgerEpoch).toBe(ledgerEpoch); + const manualStatus = await f.send( + f.agentRequest( + '/api/knowledge/reports?' + + new URLSearchParams({ + articleId, + ledgerEpoch: String(ledgerEpoch), + reportId, + }), + ), + 'manual.report.status', + ); + expect(manualStatus.status).toBe(200); + expect(object(await manualStatus.json()).status).toBe('pending'); + const viewed = await f.staff('reportRead', { + articleId, + ledgerEpoch, + reportId, + }); + // The private staff view provides the exact current binding; agents never do. + const review: Pick< + KnowledgeReportView, + 'expectedReportGeneration' | 'reviewBindingHash' + > = { + expectedReportGeneration: integer(viewed.expectedReportGeneration), + reviewBindingHash: text(viewed.reviewBindingHash), + }; + await f.staff('confirmReport', { + commandId: 'human-confirm', + articleId, + ledgerEpoch, + reportId, + ...review, + }); + const confirmed = await f.agent( + transport, + 'getValidationRequirements', + lookup, + 'report.poll.confirmed', + ); + expect(object(confirmed.reportStatus).status).toBe('confirmed'); + expect(JSON.stringify(confirmed)).not.toContain(report.details); + await f.agent( + transport, + 'submitEvidence', + { + commandId: 'accept-confirmed', + correlationId: 'query-budget', + expectedGeneration: article.generation, + articleId, + evidence, + receipt: text(queued.receipt), + }, + 'evidence.accept', + ); + expect( + (await f.app.getEvidence(f.access, { articleId })).evidence, + ).toHaveLength(1); + } finally { + // Deliberately RED on a producer/host that exceeds50; no version-conditioned waiver. + // Evaluate after the flow so baseline evidence includes every completed request. + f.meter.assertFreeBudget(); + } + }, + ); + + it('profiles both protocols and the full staff/portal lifecycle over one genuine32-proof high-history D1 article', async () => { + const f = await fixture(true); + let sequence = 0; + const command = () => 'history-' + ++sequence; + const reportBody = { + summary: 'Synthetic measured history check', + details: 'PRIVATE_HIGH_HISTORY_REPORT_CANARY', + }; + async function portal(operation: string, input: unknown, expected = 200) { + const response = await f.send( + f.browser('/api/knowledge/portal', { operation, input }), + 'portal.' + operation, + ); + expect(response.status, operation).toBe(expected); + const result = object(await response.json()); + expect(JSON.stringify(result)).not.toContain(reportBody.details); + return result; + } + async function ledger() { + const response = await f.send( + f.agentRequest('/api/knowledge/reports?articleId=' + articleId), + ); + expect(response.status).toBe(200); + return object(await response.json()); + } + async function resetLedger(measured: boolean) { + const current = await ledger(); + let next = await f.staff( + 'resetReports', + { + commandId: command(), + articleId, + expectedLedgerEpoch: integer(current.ledgerEpoch), + }, + measured, + ); + for (let page = 0; page < 4 && next.status === 'resetting'; page += 1) { + next = await f.staff( + 'drainReports', + { articleId, ledgerEpoch: integer(next.ledgerEpoch) }, + measured, + ); + } + expect(next.status).toBe('active'); + return next; + } + async function prepare( + id: string, + transport: Transport, + measured: boolean, + ) { + let head = await ledger(); + if ( + integer(head.reportsRemaining) === 0 || + integer(head.rowsRemaining) < 8 + ) + head = await resetLedger(false); + const article = await f.app.getDraft(f.access, { articleId }); + const evidence: EvidenceSubmission = { + id, + articleId, + articleRevision: article.revision.number, + contentHash: article.revision.contentHash, + validationPolicy: article.revision.validationPolicy, + checkId: 'explanation-content', + testKind: 'content', + applicability: article.revision.applicability, + stagingBuildId: 'query-budget-1', + steps: [ + 'Read the synthetic guide', + 'Compare the current synthetic output', + ], + result: 'passed', + executedAt: f.clock.now(), + runnerId: 'query-budget-runner', + artifacts: [{ id: 'history-output-' + sequence, hash: 'b'.repeat(64) }], + }; + const ledgerEpoch = integer(head.ledgerEpoch); + const input = { + commandId: command(), + articleId, + ledgerEpoch, + evidence, + report: reportBody, + }; + let ack: Record; + if (measured) { + ack = await f.agent( + transport, + 'submitEvidence', + { + ...input, + correlationId: 'query-budget', + expectedGeneration: article.generation, + }, + 'history.report.queue', + ); + expect(ack.kind).toBe('pending-human-review'); + } else { + const response = await f.send( + f.agentRequest('/api/knowledge/reports', input), + ); + expect(response.status).toBe(200); + ack = object(await response.json()); + } + return { + article, + evidence, + ack, + key: { articleId, ledgerEpoch, reportId: text(ack.reportId) }, + }; + } + async function confirm( + packet: Awaited>, + measured: boolean, + ) { + const view = await f.staff('reportRead', packet.key, measured); + expect(view.status).toBe('pending'); + expect(view.submittedBy).toBe(owner); + await f.staff( + 'confirmReport', + { + ...packet.key, + commandId: command(), + expectedReportGeneration: integer(view.expectedReportGeneration), + reviewBindingHash: text(view.reviewBindingHash), + }, + measured, + ); + } + async function accept( + packet: Awaited>, + transport: Transport, + measured: boolean, + ) { + const input = { + commandId: command(), + correlationId: 'query-budget', + expectedGeneration: packet.article.generation, + articleId, + evidence: packet.evidence, + receipt: text(packet.ack.receipt), + }; + const result = await f.agent( + transport, + 'submitEvidence', + input, + measured ? 'history.evidence.accept' : false, + ); + expect(result.replayed).toBe(false); + const stored = await f.app.getEvidence(f.access, { articleId }); + const proof = stored.evidence.find( + (value) => value.id === packet.evidence.id, + ); + if (proof === undefined) + throw new Error( + 'Actual SDK acceptance did not retain the submitted proof.', + ); + expect(proof.attestation.id).toBe(packet.ack.receipt); + return { input, proof, result }; + } + async function seed(id: string) { + const packet = await prepare(id, 'http', false); + await confirm(packet, false); + return accept(packet, 'http', false); + } + async function revoke(id: string, measured: boolean) { + const stored = await f.app.getEvidence(f.access, { articleId }); + const proof = stored.evidence.find((value) => value.id === id); + if (proof === undefined) + throw new Error('Expected a genuinely accepted current proof.'); + await f.staff( + 'revokeEvidence', + { + commandId: command(), + correlationId: 'query-budget', + expectedGeneration: stored.generation, + articleId, + articleRevision: proof.articleRevision, + evidenceId: proof.id, + evidenceVersion: proof.version, + evidenceHash: proof.hash, + reason: 'Synthetic high-history withdrawal', + }, + measured, + ); + } + async function articleRows(): Promise { + const records = f.store.collection(knowledgeRecords); + const rows: KnowledgeRecord[] = []; + let cursor: string | undefined; + for (let page = 0; page < 10; page += 1) { + const scanned = await records.scan({ + limit: 1000, + ...(cursor === undefined ? {} : { cursor }), + }); + rows.push( + ...scanned.records + .map((row) => row.value) + .filter( + (row) => + row.resourceKind === 'article' && row.resourceId === articleId, + ), + ); + if (scanned.nextCursor === null) return rows; + cursor = scanned.nextCursor; + } + throw new Error( + 'Actual high-history diagnostics exceeded their bounded scan.', + ); + } + try { + const collection = await f.staff('getCollection', { collectionId }); + expect(object(collection.collection).id).toBe(collectionId); + const governance = await f.staff( + 'getGovernanceConfiguration', + { collectionId }, + true, + owner, + ); + await f.staff( + 'putGovernanceConfiguration', + { + commandId: command(), + correlationId: 'query-budget', + expectedGeneration: integer(governance.generation), + collectionId, + configuration: governance.configuration, + }, + true, + owner, + ); + const preview = await f.staff( + 'previewCollectionPolicy', + { + collectionId, + uses: { + portal: { + enabled: true, + audience: { + kind: 'permission', + permission: 'knowledge.article.read', + }, + }, + bot: { enabled: false }, + }, + }, + true, + owner, + ); + await f.staff( + 'updateCollectionPolicy', + { + commandId: command(), + correlationId: 'query-budget', + expectedGeneration: integer(preview.generation), + collectionId, + preview: preview.preview, + }, + true, + owner, + ); + await f.agent( + 'http', + 'createDraft', + { + commandId: command(), + correlationId: 'query-budget', + expectedGeneration: 0, + articleId, + collectionId, + draft, + }, + 'history.create', + ); + const initial = await prepare('history-proof-0', 'http', true); + await confirm(initial, true); + await accept(initial, 'http', true); + const current = await f.app.getDraft(f.access, { articleId }); + await f.staff('submitForReview', { + commandId: command(), + correlationId: 'query-budget', + expectedGeneration: current.generation, + articleId, + }); + const review = await f.staff('getReview', { articleId }); + await f.staff('publishArticle', { + commandId: command(), + correlationId: 'query-budget', + expectedGeneration: integer(review.generation), + articleId, + review: review.review, + }); + const visible = await portal('getPublishedArticle', { articleId }); + expect(visible.articleId).toBe(articleId); + expect( + await portal('searchPublishedArticles', { + collectionId, + query: 'synthetic', + applicability: draft.applicability, + }), + ).toEqual({ outcome: 'no_result', articles: [] }); + let discovered = false; + for (let tick = 0; tick < 64; tick++) { + await f.scheduled(); + const status = await f.app.getArticleIndexStatus(f.access, { + articleId, + }); + if (status.status === 'ready' && status.indexed) { + discovered = true; + break; + } + } + expect(discovered).toBe(true); + const collections = await portal('listPortalCollections', {}); + expect(collections).toMatchObject({ + outcome: 'results', + collections: [{ collectionId }], + }); + const search = await portal('searchPublishedArticles', { + collectionId, + query: 'synthetic', + applicability: draft.applicability, + }); + expect(search).toMatchObject({ + outcome: 'results', + articles: [{ articleId }], + }); + await revoke('history-proof-0', true); + await portal('getPublishedArticle', { articleId }, 404); + expect( + await portal('searchPublishedArticles', { + collectionId, + query: 'synthetic', + applicability: draft.applicability, + }), + ).toEqual({ outcome: 'no_result', articles: [] }); + // Authoritative refusal above precedes any worker. Now converge the + // retained hint, and exercise a separate physical recovery invocation. + let withdrawn = false; + for (let tick = 0; tick < 64; tick++) { + await f.scheduled(); + const status = await f.app.getArticleIndexStatus(f.access, { + articleId, + }); + if (status.status === 'ready' && !status.indexed) { + withdrawn = true; + break; + } + } + expect(withdrawn).toBe(true); + await f.scheduled('physical'); + await resetLedger(true); + // Build current32 only AFTER the ordinary one-result guide was published. + // These same-check draft proofs do not qualify for a new publication. + await seed('history-proof-0'); + for (let index = 1; index < 32; index += 1) + await seed('history-proof-' + index); + for (let revocations = 1; revocations < 64; revocations += 1) { + await revoke('history-proof-0', false); + await seed('history-proof-0'); + profileFacts.seedRevocations = revocations + 1; + } + const rows = await articleRows(); + const encodedBytes = rows.reduce( + (sum, row) => + sum + + new TextEncoder().encode( + JSON.stringify(knowledgeRecords.codec.encode(row)), + ).byteLength, + 0, + ); + // Read actual public records only; keep the unchanged default1024-row, + // 256-version and16MiB budgets, plus conservative remaining-write margin. + const try96 = + rows.length + 32 * 8 + 96 <= 1024 && + rows.filter((row) => row.kind === 'evidence').length + 32 + 4 <= 256 && + encodedBytes + 2 * 1024 * 1024 < 16 * 1024 * 1024; + profileFacts.try96 = try96; + if (try96) + for (let revocations = 64; revocations < 96; revocations += 1) { + await revoke('history-proof-0', false); + await seed('history-proof-0'); + profileFacts.seedRevocations = revocations + 1; + } + const history = await f.app.getEvidence(f.access, { articleId }); + expect(history.evidence).toHaveLength(32); + expect(history.revokedEvidence.length).toBeGreaterThanOrEqual(64); + expect(history.revokedEvidence).toHaveLength(try96 ? 96 : 64); + for (const proof of history.evidence) + expect( + history.revokedEvidence.some((marker) => marker.hash === proof.hash), + ).toBe(false); + profileFacts.currentEvidence = history.evidence.length; + profileFacts.revocations = history.revokedEvidence.length; + const finalRows = await articleRows(); + profileFacts.articleRows = finalRows.length; + profileFacts.actualEncodedBytesBeforeMeasure = finalRows.reduce( + (sum, row) => + sum + + new TextEncoder().encode( + JSON.stringify(knowledgeRecords.codec.encode(row)), + ).byteLength, + 0, + ); + profileFacts.windowRolloverMeasured = false; + expect( + (await f.app.getDraft(f.access, { articleId })).hasPublication, + ).toBe(true); + for (const transport of ['http', 'mcp'] as const) { + const read = await f.agent( + transport, + 'getDraft', + { articleId }, + 'history.getDraft', + '2001:db8::c01d', + ); + expect(read.hasPublication).toBe(true); + await f.agent( + transport, + 'getValidationRequirements', + { collectionId, kind: draft.kind }, + 'history.requirements', + ); + await f.agent( + transport, + 'getValidationRequirements', + { collectionId, kind: draft.kind, articleId }, + 'history.ledger', + ); + const packet = await prepare('history-proof-0', transport, true); + const lookup = { + collectionId, + kind: draft.kind, + articleId, + reportLookup: { + ledgerEpoch: packet.key.ledgerEpoch, + reportId: packet.key.reportId, + }, + }; + const pending = await f.agent( + transport, + 'getValidationRequirements', + lookup, + 'history.pending', + ); + expect(object(pending.reportStatus).status).toBe('pending'); + expect(JSON.stringify(pending)).not.toContain(reportBody.details); + await confirm(packet, true); + const confirmed = await f.agent( + transport, + 'getValidationRequirements', + lookup, + 'history.confirmed', + ); + expect(object(confirmed.reportStatus).status).toBe('confirmed'); + const accepted = await accept(packet, transport, true); + const replay = await f.agent( + transport, + 'submitEvidence', + accepted.input, + 'history.evidence.replay', + ); + expect(replay).toEqual({ ...accepted.result, replayed: true }); + expect( + (await f.app.getEvidence(f.access, { articleId })).evidence, + ).toHaveLength(32); + } + const fullEvidence = await f.staff('getEvidence', { articleId }); + expect(fullEvidence.evidence).toHaveLength(32); + expect(fullEvidence.revokedEvidence).toHaveLength( + history.revokedEvidence.length, + ); + // Complete qualification must really fetch retained facts in a coalesced + // public-Store wave, not merely contain Promise.all in source. + expect( + f.meter.requests.some((budget) => + budget.batchSizes.some( + (size) => size >= 1 + 32 + history.revokedEvidence.length, + ), + ), + ).toBe(true); + const ending = await f.app.getDraft(f.access, { articleId }); + await f.staff('retireArticle', { + commandId: command(), + correlationId: 'query-budget', + expectedGeneration: ending.generation, + articleId, + }); + await portal('getPublishedArticle', { articleId }, 404); + profileFacts.priorPublicationRetained = ( + await f.app.getDraft(f.access, { articleId }) + ).hasPublication; + } finally { + f.meter.assertFreeBudget(); + } + }, 180_000); +}); diff --git a/worker/src/knowledge-retrieval-maintenance.test.ts b/worker/src/knowledge-retrieval-maintenance.test.ts new file mode 100644 index 0000000..1e5372e --- /dev/null +++ b/worker/src/knowledge-retrieval-maintenance.test.ts @@ -0,0 +1,447 @@ +import { resolveAccess } from '@pegma/authorization-core'; +import { + createKnowledgeBaseApplication, + retrievalRecords, +} from '@pegma/knowledge-base-application'; +import { + articleKinds, + knowledgePermissions, +} from '@pegma/knowledge-base-contracts'; +import { + createMemoryStore, + defineCollection, + type CollectionDefinition, + type CollectionStore, + type ScanOptions, + type Store, + type StoredRecord, +} from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import { createKnowledgeRetrievalMaintenance } from './knowledge-retrieval-maintenance'; + +const KEY = { partition: 'knowledge', id: 'retrieval' } as const; +const clock = { now: () => '2026-11-08T12:00:00.000Z' }; +const actor = resolveAccess( + { principalId: 'synthetic-kb-fixture-author' }, + { + version: 'synthetic-kb-fixture-1', + defaults: Object.values(knowledgePermissions), + }, +); +const checkpoints = defineCollection({ + name: 'pegma-dev-maintenance', + key: (value) => ({ + partition: String(value.partition), + id: String(value.id), + }), + codec: { encode: (value) => value, decode: (value) => value }, +}); +const checkpoint = (store: Store) => store.collection(checkpoints).get(KEY); + +function barrier() { + let release = () => {}; + const ready = new Promise((resolve) => { + release = resolve; + }); + return { ready, release }; +} + +interface Hooks { + afterScan?: () => Promise; + afterCheckpointRead?: () => Promise; + failScan?: boolean; + failCheckpoint?: boolean; + loseProjectionAck?: boolean; +} + +/** Only delays/faults a real Store; persistence and SDK processing remain real. */ +function observe(backing: Store, hooks: Hooks = {}) { + const scans: ScanOptions[] = []; + const calls = { collections: 0, projectionCommits: 0 }; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + calls.collections += 1; + const target = backing.collection(definition); + return { + ...target, + async get(key) { + const value = await target.get(key); + if (definition.name === checkpoints.name && key.id === KEY.id) + await hooks.afterCheckpointRead?.(); + return value; + }, + async scan(options) { + if (definition.name !== 'knowledge-base.records.v1') + return target.scan(options); + scans.push({ ...options }); + if (hooks.failScan) throw new Error('Synthetic scan failure.'); + const page = await target.scan(options); + await hooks.afterScan?.(); + return page; + }, + async update(key, decide, options) { + if ( + definition.name === checkpoints.name && + key.id === KEY.id && + hooks.failCheckpoint + ) + throw new Error('Synthetic checkpoint failure.'); + return target.update(key, decide, options); + }, + async transact(partition, actions) { + const result = await target.transact(partition, actions); + if (definition.name === retrievalRecords.name && result.committed) { + calls.projectionCommits += 1; + if (hooks.loseProjectionAck) { + hooks.loseProjectionAck = false; + throw new Error('Synthetic lost projection acknowledgement.'); + } + } + return result; + }, + }; + }, + }; + return { store, scans, calls }; +} + +async function seed(store: Store, count = 3) { + const app = createKnowledgeBaseApplication({ store, clock }); + for (let index = 0; index < count; index++) { + const collectionId = `synthetic-guides-${index}`; + await app.createCollection(actor, { + commandId: `create-${index}`, + correlationId: 'test', + expectedGeneration: 0, + collectionId, + name: `Synthetic guides ${index}`, + }); + const preview = await app.previewCollectionPolicy(actor, { + collectionId, + uses: { + portal: { + enabled: true, + audience: { + kind: 'permission', + permission: knowledgePermissions.articleRead, + }, + }, + bot: { enabled: false }, + }, + }); + await app.updateCollectionPolicy(actor, { + commandId: `enable-${index}`, + correlationId: 'test', + expectedGeneration: preview.generation, + collectionId, + preview: preview.preview, + }); + } + return app; +} + +function runner(store: Store, isEnabled = () => true, currentClock = clock) { + const logger = { log: vi.fn() }; + return { + logger, + maintenance: createKnowledgeRetrievalMaintenance({ + store, + clock: currentClock, + logger, + isEnabled, + }), + }; +} + +describe('bounded Knowledge retrieval maintenance', () => { + it('preserves committed checkpoints and best-effort completion when an injected Logger throws', async () => { + const backing = createMemoryStore(); + const hooks: Hooks = {}; + const seen = observe(backing, hooks); + const logger = { + log: vi.fn(() => { + throw new Error('Synthetic injected logger failure.'); + }), + }; + const maintenance = createKnowledgeRetrievalMaintenance({ + store: seen.store, + clock, + logger, + isEnabled: () => true, + }); + await expect(maintenance.runPage()).resolves.toBeUndefined(); + const committed = await checkpoint(backing); + expect(committed).toMatchObject({ generation: 1, cursor: null }); + hooks.failScan = true; + await expect(maintenance.runPage()).resolves.toBeUndefined(); + expect(await checkpoint(backing)).toEqual(committed); + }); + + it('does no Store work when disabled, or when the clock is invalid', async () => { + for (const mode of ['disabled', 'clock'] as const) { + const backing = createMemoryStore(); + const seen = observe(backing); + const { maintenance, logger } = runner( + seen.store, + () => mode !== 'disabled', + { + now: () => (mode === 'clock' ? 'not-a-time' : clock.now()), + }, + ); + await maintenance.runPage(); + expect(seen.calls.collections).toBe(0); + expect(await checkpoint(backing)).toBeNull(); + if (mode === 'disabled') expect(logger.log).not.toHaveBeenCalled(); + else + expect(JSON.stringify(logger.log.mock.calls)).not.toContain( + 'not-a-time', + ); + } + }); + + it('scans one physical row per call and resumes across reconstructed workers', async () => { + const backing = createMemoryStore(); + const app = await seed(backing); + expect((await app.listPortalCollections(actor, {})).collections).toEqual( + [], + ); + const seen = observe(backing); + let complete = false; + for (let tick = 0; tick < 256; tick++) { + const before = seen.scans.length; + await runner(seen.store).maintenance.runPage(); + expect(seen.scans.length - before).toBe(1); + expect(seen.scans.at(-1)?.limit).toBe(1); + const saved = await checkpoint(backing); + expect(saved?.generation).toBe(tick + 1); + if ( + saved?.cursor === null && + (await app.listPortalCollections(actor, {})).collections.length === 3 + ) { + complete = true; + break; + } + } + expect(complete).toBe(true); + expect( + (await app.listPortalCollections(actor, {})).collections.map( + (value) => value.collectionId, + ), + ).toEqual([ + 'synthetic-guides-0', + 'synthetic-guides-1', + 'synthetic-guides-2', + ]); + }); + + it('retains the prior cursor after a page failure and resumes from that exact cursor', async () => { + const backing = createMemoryStore(); + await seed(backing); + const hooks: Hooks = {}; + const seen = observe(backing, hooks); + await runner(seen.store).maintenance.runPage(); + const prior = await checkpoint(backing); + expect(typeof prior?.cursor).toBe('string'); + hooks.failScan = true; + await runner(seen.store).maintenance.runPage(); + expect(await checkpoint(backing)).toEqual(prior); + expect(seen.scans.at(-1)?.cursor).toBe(prior?.cursor); + hooks.failScan = false; + await runner(seen.store).maintenance.runPage(); + expect(seen.scans.at(-1)?.cursor).toBe(prior?.cursor); + expect((await checkpoint(backing))?.generation).toBe(2); + }); + + it('advances opaque continuation through a physical page containing no repair candidates', async () => { + const backing = createMemoryStore(); + const app = createKnowledgeBaseApplication({ store: backing, clock }); + for (let index = 0; index < 3; index++) { + await app.putValidationPolicy(actor, { + commandId: `validation-${index}`, + correlationId: 'test', + expectedGeneration: 0, + policy: { + id: `synthetic-validation-${index}`, + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: `${kind}-content`, + kind, + testKind: 'content', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: ['synthetic-runner'], + })), + { + id: 'walkthrough-workflow', + kind: 'walkthrough', + testKind: 'workflow', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: ['synthetic-runner'], + }, + ], + }, + }); + } + const seen = observe(backing); + const first = runner(seen.store); + await first.maintenance.runPage(); + const saved = await checkpoint(backing); + expect(typeof saved?.cursor).toBe('string'); + expect(first.logger.log).toHaveBeenCalledWith( + 'info', + 'knowledge.retrieval_maintenance.page', + expect.objectContaining({ + physicalRows: 1, + candidates: 0, + cursorSaved: true, + }), + ); + await runner(seen.store).maintenance.runPage(); + expect(seen.scans).toHaveLength(2); + expect(seen.scans[1]?.cursor).toBe(saved?.cursor); + expect(seen.calls.projectionCommits).toBe(0); + expect((await checkpoint(backing))?.generation).toBe(2); + }); + + it.each(['projection_ack', 'checkpoint'] as const)( + 'recovers partial committed work after %s failure without advancing the cursor', + async (failure) => { + const backing = createMemoryStore(); + const app = await seed(backing, 1); + const hooks: Hooks = { + loseProjectionAck: failure === 'projection_ack', + failCheckpoint: failure === 'checkpoint', + }; + const seen = observe(backing, hooks); + // A checkpoint outage retries the same physical candidate. A lost SDK + // ACK can occur later in the cycle, after earlier noncandidate pages. + if (failure === 'checkpoint') + await runner(seen.store).maintenance.runPage(); + else { + for ( + let tick = 0; + tick < 64 && seen.calls.projectionCommits === 0; + tick++ + ) + await runner(seen.store).maintenance.runPage(); + expect(seen.calls.projectionCommits).toBeGreaterThan(0); + } + const retry = await checkpoint(backing); + if (failure === 'checkpoint') expect(retry).toBeNull(); + hooks.failCheckpoint = false; + for (let tick = 0; tick < 128; tick++) { + await runner(seen.store).maintenance.runPage(); + if ( + (await app.listPortalCollections(actor, {})).collections.length === 1 + ) + break; + } + expect((await app.listPortalCollections(actor, {})).collections).toEqual([ + { collectionId: 'synthetic-guides-0', label: 'Synthetic guides 0' }, + ]); + expect(await checkpoint(backing)).not.toBeNull(); + }, + ); + + it('does not overwrite a newer cursor after a delayed overlapping page', async () => { + const backing = createMemoryStore(); + await seed(backing); + const entered = barrier(); + const resume = barrier(); + const seen = observe(backing, { + afterScan: async () => { + entered.release(); + await resume.ready; + }, + }); + const delayed = runner(seen.store).maintenance.runPage(); + await entered.ready; + await runner(backing).maintenance.runPage(); + const winner = await checkpoint(backing); + expect(winner?.generation).toBe(1); + resume.release(); + await delayed; + expect(await checkpoint(backing)).toEqual(winner); + expect(seen.scans).toHaveLength(1); + }); + + it('fences null-cycle ABA even when no physical candidate exists', async () => { + const backing = createMemoryStore(); + const entered = barrier(); + const resume = barrier(); + const seen = observe(backing, { + afterScan: async () => { + entered.release(); + await resume.ready; + }, + }); + const delayed = runner(seen.store).maintenance.runPage(); + await entered.ready; + await runner(backing).maintenance.runPage(); + await runner(backing).maintenance.runPage(); + const winner = await checkpoint(backing); + expect(winner).toMatchObject({ generation: 2, cursor: null }); + resume.release(); + await delayed; + expect(await checkpoint(backing)).toEqual(winner); + }); + + it('rechecks activation after the checkpoint read and after the awaited page', async () => { + for (const boundary of ['read', 'page'] as const) { + const backing = createMemoryStore(); + const entered = barrier(); + const resume = barrier(); + let enabled = true; + const pause = async () => { + entered.release(); + await resume.ready; + }; + const seen = observe( + backing, + boundary === 'read' + ? { afterCheckpointRead: pause } + : { afterScan: pause }, + ); + const pending = runner(seen.store, () => enabled).maintenance.runPage(); + await entered.ready; + enabled = false; + resume.release(); + await pending; + expect(await checkpoint(backing)).toBeNull(); + expect(seen.calls.projectionCommits).toBe(0); + expect(seen.scans).toHaveLength(boundary === 'read' ? 0 : 1); + } + }); + + it('refuses corrupt or exhausted checkpoints before scanning and preserves the limiter bookmark', async () => { + const invalid: readonly StoredRecord[] = [ + ...[0, -1, Number.MAX_SAFE_INTEGER].map((generation) => ({ + ...KEY, + cursor: null, + generation, + })), + { ...KEY, generation: 1 }, + { ...KEY, cursor: '', generation: 1 }, + { ...KEY, cursor: null, generation: 1, unexpected: true }, + ]; + for (const corrupt of invalid) { + const backing = createMemoryStore(); + const raw = backing.collection(checkpoints); + const limiter = { + partition: 'knowledge', + id: 'rate-limits', + cursor: 'synthetic-limiter-cursor', + generation: 7, + }; + await raw.put(corrupt); + await raw.put(limiter); + const seen = observe(backing); + await runner(seen.store).maintenance.runPage(); + expect(seen.scans).toEqual([]); + expect(await raw.get(KEY)).toEqual(corrupt); + expect( + await raw.get({ partition: 'knowledge', id: 'rate-limits' }), + ).toEqual(limiter); + } + }); +}); diff --git a/worker/src/knowledge-retrieval-maintenance.ts b/worker/src/knowledge-retrieval-maintenance.ts new file mode 100644 index 0000000..46154ca --- /dev/null +++ b/worker/src/knowledge-retrieval-maintenance.ts @@ -0,0 +1,245 @@ +import { resolveAccess } from '@pegma/authorization-core'; +import { + createKnowledgeBaseApplication, + type RepairRetrievalPageResult, +} from '@pegma/knowledge-base-application'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; +import type { Clock, Logger } from '@pegma/spine'; +import { + defineCollection, + type Store, + type StoredValue, +} from '@pegma/storage-core'; + +export interface KnowledgeRetrievalMaintenanceOptions { + readonly store: Store; + readonly clock: Clock; + readonly logger: Logger; + readonly isEnabled: () => boolean; +} + +interface BookmarkRecord { + readonly partition: StoredValue; + readonly id: StoredValue; + readonly cursor: StoredValue; + readonly generation: StoredValue; +} +interface Bookmark { + readonly cursor: string | null; + readonly generation: number; +} + +const KEY = { partition: 'knowledge', id: 'retrieval' } as const; +const PAGE_LIMIT = 1; +const MAX_CURSOR_LENGTH = 16_384; +const checkpoints = defineCollection({ + name: 'pegma-dev-maintenance', + key: (value) => ({ + partition: String(value.partition), + id: String(value.id), + }), + codec: { + encode: (value) => ({ ...value }), + decode(value) { + if ( + Object.keys(value).length !== 4 || + !['partition', 'id', 'cursor', 'generation'].every((field) => + Object.hasOwn(value, field), + ) + ) + throw new TypeError('Invalid knowledge retrieval checkpoint fields.'); + return { + partition: value.partition ?? null, + id: value.id ?? null, + cursor: value.cursor ?? null, + generation: value.generation ?? null, + }; + }, + }, +}); + +// This principal is server-owned and never resolved through human or agent +// roles. Indexing derives hints; every reader still confirms current authority. +const access = resolveAccess( + { principalId: 'pegma.dev-knowledge-index-maintenance' }, + { + version: 'pegma.dev-knowledge-index-maintenance-1', + defaults: [knowledgePermissions.indexManage], + }, +); + +function validCursor(value: StoredValue): value is string | null { + return ( + value === null || + (typeof value === 'string' && + value.length > 0 && + value.length <= MAX_CURSOR_LENGTH) + ); +} + +function bookmark(value: BookmarkRecord | null, id: string): Bookmark { + if (value === null) return { cursor: null, generation: 0 }; + if ( + value.partition !== KEY.partition || + value.id !== id || + !validCursor(value.cursor) || + typeof value.generation !== 'number' || + !Number.isSafeInteger(value.generation) || + value.generation < 1 + ) + throw new TypeError('Invalid knowledge retrieval checkpoint.'); + return { cursor: value.cursor, generation: value.generation }; +} + +function validPage(result: RepairRetrievalPageResult): boolean { + const counts = [ + result.physicalRows, + result.candidates, + result.repaired, + result.pending, + result.blocked, + ]; + return ( + counts.every((count) => Number.isSafeInteger(count) && count >= 0) && + result.physicalRows <= PAGE_LIMIT && + result.candidates <= result.physicalRows && + result.repaired + result.pending + result.blocked === result.candidates && + validCursor(result.nextCursor) + ); +} + +/** Server-owned projection authority; never a human or delegated principal. */ +export const knowledgeIndexAccess = access; + +/** Phase01 is source-free: private source snapshots fail closed in the SDK. */ +export function createKnowledgeProjectionApplication( + store: Store, + clock: Clock, +) { + return createKnowledgeBaseApplication({ store, clock }); +} + +export function knowledgeRetrievalCurrent( + options: Pick, +): boolean { + if (!options.isEnabled()) return false; + const now = options.clock.now(); + if ( + typeof now !== 'string' || + !Number.isFinite(Date.parse(now)) || + new Date(now).toISOString() !== now + ) + throw new TypeError('Knowledge retrieval requires a canonical clock.'); + return true; +} + +export function knowledgeRetrievalDiagnostic( + logger: Logger, + level: 'info' | 'warn' | 'error', + message: string, + fields: Readonly>, +): void { + try { + logger.log(level, message, fields); + } catch { + /* Best-effort diagnostics never change committed effects. */ + } +} + +/** Independent cursor cycles use the same generation fence, including null ABA. */ +export async function openKnowledgeRetrievalCheckpoint( + store: Store, + id: 'retrieval' | 'retrieval-ready', +) { + const key = { ...KEY, id }; + const collection = store.collection(checkpoints); + const prior = bookmark(await collection.get(key), id); + if (prior.generation === Number.MAX_SAFE_INTEGER) + throw new RangeError('Knowledge retrieval generation is exhausted.'); + return { + cursor: prior.cursor, + async advance( + cursor: string | null, + current: () => boolean, + ): Promise { + if (!validCursor(cursor)) + throw new TypeError('Invalid retrieval continuation.'); + const saved = await collection.update( + key, + (value) => { + const actual = bookmark(value, id); + if ( + !current() || + actual.generation !== prior.generation || + actual.cursor !== prior.cursor + ) + return { action: 'keep' }; + return { + action: 'write', + value: { ...key, cursor, generation: prior.generation + 1 }, + }; + }, + { maxAttempts: 1 }, + ); + return saved.written; + }, + }; +} + +/** No scheduler, identity, email, grant, or report-factory construction here. */ +export function createKnowledgeRetrievalMaintenance( + options: KnowledgeRetrievalMaintenanceOptions, +) { + const current = () => knowledgeRetrievalCurrent(options); + return Object.freeze({ + /** One physical row and one attempted projection transaction per candidate. */ + async runPage(): Promise { + let stage = 'configuration'; + try { + if (!current()) return; + stage = 'checkpoint_read'; + const checkpoint = await openKnowledgeRetrievalCheckpoint( + options.store, + 'retrieval', + ); + if (!current()) return; + const application = createKnowledgeProjectionApplication( + options.store, + options.clock, + ); + stage = 'repair'; + const result = await application.repairRetrievalPage(access, { + limit: PAGE_LIMIT, + maxBatches: 1, + ...(checkpoint.cursor === null ? {} : { cursor: checkpoint.cursor }), + }); + if (!validPage(result)) + throw new TypeError('Invalid knowledge retrieval page.'); + if (!current()) return; + stage = 'checkpoint_write'; + const saved = await checkpoint.advance(result.nextCursor, current); + knowledgeRetrievalDiagnostic( + options.logger, + 'info', + 'knowledge.retrieval_maintenance.page', + { + physicalRows: result.physicalRows, + candidates: result.candidates, + repaired: result.repaired, + pending: result.pending, + blocked: result.blocked, + cursorSaved: saved, + }, + ); + } catch { + // Partial derived writes can remain; retry from the saved cursor. + knowledgeRetrievalDiagnostic( + options.logger, + 'error', + 'knowledge.retrieval_maintenance.failed', + { stage }, + ); + } + }, + }); +} diff --git a/worker/src/knowledge-retrieval-ready.test.ts b/worker/src/knowledge-retrieval-ready.test.ts new file mode 100644 index 0000000..c55d40e --- /dev/null +++ b/worker/src/knowledge-retrieval-ready.test.ts @@ -0,0 +1,303 @@ +import { resolveAccess } from '@pegma/authorization-core'; +import { + createKnowledgeBaseApplication, + retrievalRecords, +} from '@pegma/knowledge-base-application'; +import { + articleKinds, + knowledgePermissions, +} from '@pegma/knowledge-base-contracts'; +import { + createMemoryStore, + defineCollection, + type CollectionDefinition, + type CollectionStore, + type Store, + type StoredRecord, +} from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import { createKnowledgeRetrievalReady } from './knowledge-retrieval-ready'; + +const clock = { now: () => '2026-11-08T12:00:00.000Z' }; +const actor = resolveAccess( + { principalId: 'synthetic-ready-author' }, + { version: 'test', defaults: Object.values(knowledgePermissions) }, +); +const raw = defineCollection({ + name: 'pegma-dev.knowledge-retrieval-ready.v1', + key: (value) => ({ partition: 'knowledge', id: String(value.id) }), + codec: { encode: (value) => value, decode: (value) => value }, +}); +const bookmarks = defineCollection({ + name: 'pegma-dev-maintenance', + key: (value) => ({ + partition: String(value.partition), + id: String(value.id), + }), + codec: { encode: (value) => value, decode: (value) => value }, +}); +const key = { partition: 'knowledge', id: 'retrieval-ready' }; +function barrier() { + let release = () => {}; + const ready = new Promise((resolve) => { + release = resolve; + }); + return { ready, release }; +} +interface Hooks { + failPut?: boolean; + failRepair?: boolean; + failCheckpoint?: boolean; + afterScan?: () => Promise; + beforeDelete?: () => Promise; +} +function observe(backing: Store, hooks: Hooks = {}) { + const calls = { collections: 0, scans: 0, puts: 0, deletes: 0, attempts: 0 }; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + calls.collections += 1; + const target = backing.collection(definition); + return { + ...target, + async put(value) { + if (definition.name === raw.name) { + calls.puts += 1; + if (hooks.failPut) throw new Error('Synthetic lost enqueue.'); + } + return target.put(value); + }, + async scan(options) { + if (definition.name !== raw.name) return target.scan(options); + calls.scans += 1; + expect(options.limit).toBe(1); + const page = await target.scan(options); + await hooks.afterScan?.(); + return page; + }, + async deleteIfUnchanged(key, version) { + if (definition.name === raw.name) { + calls.deletes += 1; + await hooks.beforeDelete?.(); + } + return target.deleteIfUnchanged(key, version); + }, + async update(key, decide, options) { + if (definition.name === bookmarks.name && hooks.failCheckpoint) + throw new Error('Synthetic checkpoint failure.'); + return target.update(key, decide, options); + }, + async transact(partition, actions) { + if (definition.name === retrievalRecords.name) { + calls.attempts += 1; + if (hooks.failRepair) + throw new Error('Synthetic projection outage.'); + } + return target.transact(partition, actions); + }, + }; + }, + }; + return { store, calls }; +} +function runner(store: Store, isEnabled = () => true) { + const logger = { log: vi.fn() }; + return { + logger, + ready: createKnowledgeRetrievalReady({ store, clock, logger, isEnabled }), + }; +} +async function seed(store: Store, articleIds: readonly string[]) { + const app = createKnowledgeBaseApplication({ store, clock }); + const collection = await app.createCollection(actor, { + commandId: 'collection', + correlationId: 'test', + expectedGeneration: 0, + collectionId: 'guides', + name: 'Synthetic guides', + }); + await app.putValidationPolicy(actor, { + commandId: 'policy', + correlationId: 'test', + expectedGeneration: 0, + policy: { + id: 'policy', + version: 1, + requirements: [ + ...articleKinds.map((kind) => ({ + id: kind + '-content', + kind, + testKind: 'content', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: ['runner'], + })), + { + id: 'walkthrough-workflow', + kind: 'walkthrough', + testKind: 'workflow', + maxAgeMilliseconds: 3_600_000, + trustedRunnerIds: ['runner'], + }, + ], + }, + }); + await app.putGovernanceConfiguration(actor, { + commandId: 'governance', + correlationId: 'test', + expectedGeneration: collection.value.generation, + collectionId: 'guides', + configuration: { + validationPolicy: { id: 'policy', version: 1 }, + expectedStagingBuildId: 'build', + trustedAttesterIds: ['staff'], + }, + }); + for (const articleId of articleIds) + await app.createDraft(actor, { + commandId: 'create-' + articleId, + correlationId: 'test', + expectedGeneration: 0, + articleId, + collectionId: 'guides', + draft: { + kind: 'explanation', + title: 'Synthetic guide', + summary: 'Synthetic summary', + content: { format: 'plain_text', text: 'Synthetic instructions.' }, + tags: [], + applicability: { + productId: 'test', + productVersion: '1', + buildId: 'build', + }, + }, + }); + return app; +} +async function rows(store: Store) { + return (await store.collection(raw).scan({ limit: 100 })).records; +} + +describe('one-step knowledge ready hints', () => { + it('coalesces one body-free overwrite per article and deletes only a converged authoritative result', async () => { + const backing = createMemoryStore(); + const app = await seed(backing, ['article/export']); + const seen = observe(backing); + await runner(seen.store).ready.enqueue('article/export'); + await runner(seen.store).ready.enqueue('article/export'); + expect(seen.calls.puts).toBe(2); + const queued = await rows(backing); + expect(queued).toHaveLength(1); + expect(Object.keys(queued[0]!.value).sort()).toEqual([ + 'articleId', + 'format', + 'id', + 'requestedAt', + ]); + expect(queued[0]!.key.id).toMatch(/^[a-f0-9]{64}$/); + for (let tick = 0; tick < 16 && (await rows(backing)).length; tick++) { + const before = { ...seen.calls }; + await runner(seen.store).ready.runPage(); + expect(seen.calls.scans - before.scans).toBe(1); + expect(seen.calls.attempts - before.attempts).toBeLessThanOrEqual(1); + } + expect(await rows(backing)).toEqual([]); + expect( + await app.getArticleIndexStatus(actor, { articleId: 'article/export' }), + ).toMatchObject({ status: 'ready', indexed: false }); + }); + + it('keeps failed work, rotates to another hint, and recovers across reconstructed workers', async () => { + const backing = createMemoryStore(); + await seed(backing, ['first', 'second']); + const hooks: Hooks = { failRepair: true }; + const seen = observe(backing, hooks); + for (const id of ['first', 'second']) + await runner(seen.store).ready.enqueue(id); + await runner(seen.store).ready.runPage(); + expect(await rows(backing)).toHaveLength(2); + const saved = await backing.collection(bookmarks).get(key); + expect(typeof saved?.cursor).toBe('string'); + hooks.failRepair = false; + for (let tick = 0; tick < 32 && (await rows(backing)).length; tick++) + await runner(seen.store).ready.runPage(); + expect(await rows(backing)).toEqual([]); + }); + + it('preserves a newer enqueue while an old worker awaits conditional deletion', async () => { + const backing = createMemoryStore(); + await seed(backing, ['article']); + await runner(backing).ready.enqueue('article'); + const entered = barrier(); + const resume = barrier(); + const seen = observe(backing, { + beforeDelete: async () => { + entered.release(); + await resume.ready; + }, + }); + let complete = false; + const process = (async () => { + for (let tick = 0; tick < 16 && !complete; tick++) + await runner(seen.store).ready.runPage(); + })(); + await entered.ready; + complete = true; + const prior = (await rows(backing))[0]; + await runner(backing).ready.enqueue('article'); + const newer = (await rows(backing))[0]; + expect(newer?.version).not.toBe(prior?.version); + resume.release(); + await process; + expect(await rows(backing)).toEqual([newer]); + await runner(backing).ready.runPage(); + if ((await rows(backing)).length) await runner(backing).ready.runPage(); + expect(await rows(backing)).toEqual([]); + }); + + it('fences stale null-cycle checkpoint completion and retains the prior cursor on checkpoint failure', async () => { + const backing = createMemoryStore(); + const entered = barrier(); + const resume = barrier(); + const seen = observe(backing, { + afterScan: async () => { + entered.release(); + await resume.ready; + }, + }); + const delayed = runner(seen.store).ready.runPage(); + await entered.ready; + await runner(backing).ready.runPage(); + await runner(backing).ready.runPage(); + const winner = await backing.collection(bookmarks).get(key); + expect(winner).toMatchObject({ generation: 2, cursor: null }); + resume.release(); + await delayed; + expect(await backing.collection(bookmarks).get(key)).toEqual(winner); + await runner( + observe(backing, { failCheckpoint: true }).store, + ).ready.runPage(); + expect(await backing.collection(bookmarks).get(key)).toEqual(winner); + }); + + it('does no disabled work and contains enqueue and diagnostic failures', async () => { + const backing = createMemoryStore(); + const seen = observe(backing); + const disabled = runner(seen.store, () => false).ready; + await disabled.enqueue('article'); + await disabled.runPage(); + expect(seen.calls.collections).toBe(0); + const failure = observe(backing, { failPut: true }); + const ready = createKnowledgeRetrievalReady({ + store: failure.store, + clock, + isEnabled: () => true, + logger: { + log() { + throw new Error('Synthetic logger outage.'); + }, + }, + }); + await expect(ready.enqueue('article')).resolves.toBeUndefined(); + expect(await rows(backing)).toEqual([]); + }); +}); diff --git a/worker/src/knowledge-retrieval-ready.ts b/worker/src/knowledge-retrieval-ready.ts new file mode 100644 index 0000000..0a69f5e --- /dev/null +++ b/worker/src/knowledge-retrieval-ready.ts @@ -0,0 +1,196 @@ +import type { ArticleIndexStatusDto } from '@pegma/knowledge-base-application'; +import type { Clock, Logger } from '@pegma/spine'; +import { defineCollection, type Store } from '@pegma/storage-core'; +import { + createKnowledgeProjectionApplication, + knowledgeIndexAccess, + knowledgeRetrievalCurrent, + knowledgeRetrievalDiagnostic, + openKnowledgeRetrievalCheckpoint, +} from './knowledge-retrieval-maintenance'; + +export interface KnowledgeRetrievalReadyOptions { + readonly store: Store; + readonly clock: Clock; + readonly logger: Logger; + readonly isEnabled: () => boolean; +} +interface ReadyHint { + readonly id: string; + readonly articleId: string; + readonly format: 1; + readonly requestedAt: string; +} +const PARTITION = 'knowledge'; +const hints = defineCollection({ + name: 'pegma-dev.knowledge-retrieval-ready.v1', + key: (value) => ({ partition: PARTITION, id: value.id }), + codec: { + encode: (value) => ({ ...value }), + decode(value) { + if ( + Object.keys(value).length !== 4 || + typeof value.id !== 'string' || + !/^[a-f0-9]{64}$/.test(value.id) || + typeof value.articleId !== 'string' || + value.articleId.length < 1 || + value.articleId.length > 200 || + value.format !== 1 || + typeof value.requestedAt !== 'string' || + !Number.isFinite(Date.parse(value.requestedAt)) || + new Date(value.requestedAt).toISOString() !== value.requestedAt + ) + throw new TypeError('Invalid knowledge retrieval hint.'); + return { + id: value.id, + articleId: value.articleId, + format: 1, + requestedAt: value.requestedAt, + }; + }, + }, +}); +async function hintId(articleId: string): Promise { + if ( + typeof articleId !== 'string' || + articleId.length < 1 || + articleId.length > 200 + ) + throw new TypeError('Invalid knowledge article identity.'); + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(JSON.stringify(articleId)), + ); + return [...new Uint8Array(digest)] + .map((value) => value.toString(16).padStart(2, '0')) + .join(''); +} +function validStatus( + result: ArticleIndexStatusDto, + articleId: string, +): boolean { + return ( + result.articleId === articleId && + ['ready', 'pending', 'blocked'].includes(result.status) && + typeof result.indexed === 'boolean' && + [result.articleGeneration, result.projectionGeneration].every( + (value) => value === null || (Number.isSafeInteger(value) && value >= 0), + ) + ); +} + +/** A lossy acceleration hint; atomic SDK jobs and full physical cycles recover loss. */ +export function createKnowledgeRetrievalReady( + options: KnowledgeRetrievalReadyOptions, +) { + const current = () => knowledgeRetrievalCurrent(options); + const diagnostic = ( + level: 'info' | 'warn' | 'error', + message: string, + fields: Readonly>, + ) => knowledgeRetrievalDiagnostic(options.logger, level, message, fields); + return Object.freeze({ + /** One body-free overwrite; the adapter's opaque version fences old workers. */ + async enqueue(articleId: string): Promise { + try { + if (!current()) return; + const id = await hintId(articleId); + if (!current()) return; + const requestedAt = options.clock.now(); + if ( + !Number.isFinite(Date.parse(requestedAt)) || + new Date(requestedAt).toISOString() !== requestedAt + ) + throw new TypeError( + 'Knowledge retrieval requires a canonical clock.', + ); + await options.store + .collection(hints) + .put({ id, articleId, format: 1, requestedAt }); + } catch { + diagnostic('warn', 'knowledge.retrieval_ready.failed', { + stage: 'enqueue', + }); + } + }, + /** One physical queue row and at most one attempted SDK projection transaction. */ + async runPage(): Promise { + let stage = 'configuration'; + try { + if (!current()) return; + stage = 'checkpoint_read'; + const checkpoint = await openKnowledgeRetrievalCheckpoint( + options.store, + 'retrieval-ready', + ); + if (!current()) return; + stage = 'scan'; + const collection = options.store.collection(hints); + const page = await collection.scan({ + limit: 1, + ...(checkpoint.cursor === null ? {} : { cursor: checkpoint.cursor }), + }); + if ( + !Array.isArray(page.records) || + page.records.length > 1 || + !( + page.nextCursor === null || + (typeof page.nextCursor === 'string' && + page.nextCursor.length > 0 && + page.nextCursor.length <= 16_384) + ) + ) + throw new TypeError('Invalid knowledge ready page.'); + if (!current()) return; + let complete = false; + const row = page.records[0]; + if (row !== undefined) { + stage = 'identity'; + if ( + row.key.partition !== PARTITION || + row.key.id !== row.value.id || + typeof row.version !== 'string' || + row.version.length === 0 || + (await hintId(row.value.articleId)) !== row.key.id + ) + throw new TypeError('Invalid knowledge hint identity.'); + if (!current()) return; + stage = 'repair'; + try { + const result = await createKnowledgeProjectionApplication( + options.store, + options.clock, + ).repairArticleIndex(knowledgeIndexAccess, { + articleId: row.value.articleId, + maxBatches: 1, + }); + if (!validStatus(result, row.value.articleId)) + throw new TypeError('Invalid knowledge repair result.'); + if (!current()) return; + if (result.status === 'ready') { + stage = 'delete'; + complete = await collection.deleteIfUnchanged( + row.key, + row.version, + ); + } + } catch { + // Rotate past failed work but retain its exact hint for the next cycle. + // The scan succeeded; no projection or deletion success is inferred. + diagnostic('error', 'knowledge.retrieval_ready.failed', { stage }); + } + } + if (!current()) return; + stage = 'checkpoint_write'; + const cursorSaved = await checkpoint.advance(page.nextCursor, current); + diagnostic('info', 'knowledge.retrieval_ready.page', { + physicalRows: page.records.length, + complete, + cursorSaved, + }); + } catch { + diagnostic('error', 'knowledge.retrieval_ready.failed', { stage }); + } + }, + }); +} diff --git a/worker/src/knowledge-runtime.test.ts b/worker/src/knowledge-runtime.test.ts new file mode 100644 index 0000000..a320a0a --- /dev/null +++ b/worker/src/knowledge-runtime.test.ts @@ -0,0 +1,504 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { hasPermission } from '@pegma/authorization-core'; +import { createRoleStore } from '@pegma/authorization-storage'; +import { createSessionStore } from '@pegma/sessions'; +import { + createMemoryStore, + type CollectionDefinition, + type CollectionStore, + type Store, +} from '@pegma/storage-core'; +import { fixedClock, type PrincipalId } from '@pegma/spine'; +import { describe, expect, it, vi } from 'vitest'; +import { createKnowledgeRuntime } from './knowledge-runtime'; +import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api'; +import type { IdentityPort, IdentityUser } from './identity-contracts'; +import { + APPLICATION_SCOPE, + AUTHORIZATION_APPLICATION_ID, + KNOWLEDGE_ROLE, + SUPPORT_STAFF_PERMISSIONS, + staffAccessContextFromRoles, +} from './support-access'; + +async function fixture(options: { browserLimitCount?: number } = {}) { + const backing = createMemoryStore(); + interface ReportRow { + readonly articleId: string; + readonly id: string; + readonly payload: string; + } + let reportDefinition: CollectionDefinition | undefined; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + if (definition.name === 'pegma-dev.knowledge-evidence.v1') + reportDefinition = + definition as unknown as CollectionDefinition; + return backing.collection(definition); + }, + }; + function reportRows() { + if (reportDefinition === undefined) + throw new Error('The public report factory did not open its collection.'); + return backing.collection(reportDefinition); + } + const clock = fixedClock('2026-11-08T12:00:00.000Z'); + const logger = { log: vi.fn() }; + const sessions = createSessionStore(store, { logger, clock }); + const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID); + const users = new Map( + ['admin', 'knowledge', 'support', 'customer'].map((principalId) => [ + principalId, + { + principalId, + email: principalId + '@example.test', + emailVerified: true, + status: 'active', + createdAt: clock.now(), + updatedAt: clock.now(), + }, + ]), + ); + const identity: IdentityPort = { + claimsFor: vi.fn(async (id: PrincipalId) => { + const current = users.get(id); + if (current === undefined) + throw Object.assign(new Error('not found'), { code: 'not_found' }); + if (current.status !== 'active' || !current.emailVerified) + throw Object.assign(new Error('not active and verified'), { + code: 'invalid_state', + }); + return { + issuer: IDENTITY_ISSUER, + subject: id, + emailVerified: true as const, + }; + }), + getUser: vi.fn(async (id: PrincipalId) => users.get(id) ?? null), + findUserByEmail: vi.fn(async () => null), + beginPasskeyRegistration: vi.fn(), + finishPasskeyRegistration: vi.fn(), + beginPasskeyAuthentication: vi.fn(), + finishPasskeyAuthentication: vi.fn(), + listPasskeys: vi.fn(async () => []), + removePasskey: vi.fn(async () => true), + }; + for (const [id, role] of [ + ['admin', 'Admin'], + ['knowledge', KNOWLEDGE_ROLE], + ['support', 'Support'], + ]) { + if (id === undefined || role === undefined) + throw new Error('Invalid synthetic assignment.'); + await roleStore.grantRoleAssignmentWithAudit({ + assignment: { + id: 'role-' + id, + principalId: id, + role, + scope: APPLICATION_SCOPE, + grantedBy: { kind: 'system', systemId: 'synthetic-test' }, + grantedAtEpochMs: Date.parse(clock.now()), + status: 'active', + }, + auditEventId: 'grant-' + id, + }); + } + const cookies = new Map(); + let index = 0; + for (const id of users.keys()) { + index += 1; + const sessionId = String(index).repeat(43); + await sessions.create(sessionId, { + principalId: id, + data: JSON.stringify({ + version: 1, + csrfToken: 'c'.repeat(43), + issuer: IDENTITY_ISSUER, + subject: id, + }), + }); + cookies.set(id, SESSION_COOKIE + '=' + sessionId); + } + const runtime = createKnowledgeRuntime({ + store, + clock, + sessions, + identity, + roleStore, + logger, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + agentAccess: null, + ...options, + }); + async function request( + path: string, + options: { + principal?: string; + body?: unknown; + headers?: Record; + method?: string; + } = {}, + ) { + const method = + options.method ?? (options.body === undefined ? 'GET' : 'POST'); + const response = await runtime.handle( + new Request(IDENTITY_ISSUER + path, { + method, + headers: { + Cookie: cookies.get(options.principal ?? 'admin') ?? '', + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + 'X-Pegma-CSRF': 'c'.repeat(43), + ...(options.body === undefined + ? {} + : { 'Content-Type': 'application/json' }), + ...options.headers, + }, + ...(options.body === undefined + ? {} + : { body: JSON.stringify(options.body) }), + }), + ); + if (response === null) + throw new Error('Expected matching knowledge route.'); + return response; + } + const command = (operation: string, input: unknown, principal = 'admin') => + request('/api/staff/knowledge/command', { + principal, + body: { operation, input }, + }); + return { + store, + reportRows, + runtime, + request, + command, + roleStore, + users, + logger, + }; +} + +describe('Knowledge Base browser composition', () => { + it('keeps browser governance usable with no registered OAuth clients', async () => { + const f = await fixture(); + const state = await f.request('/api/staff/knowledge/state'); + expect(state.status).toBe(200); + expect(await state.json()).toMatchObject({ + attesterId: 'admin', + csrfToken: 'c'.repeat(43), + permissions: { + collectionManage: true, + validationManage: true, + evidenceConfirm: true, + }, + }); + expect( + ( + await f.command('createCollection', { + commandId: 'create', + correlationId: 'test', + expectedGeneration: 0, + collectionId: 'guides', + name: 'Guides', + }) + ).status, + ).toBe(200); + expect( + (await f.command('getCollection', { collectionId: 'guides' })).status, + ).toBe(200); + for (const path of [ + '/api/knowledge/mcp', + '/api/knowledge/v1', + '/api/knowledge/reports', + ]) { + const disabled = await f.request(path); + expect(disabled.status).toBe(503); + expect(await disabled.json()).toEqual({ + error: 'agent_access_not_configured', + }); + } + expect( + await f.runtime.handle(new Request(IDENTITY_ISSUER + '/unmatched')), + ).toBeNull(); + }); + + it('gives explicitly granted Knowledge staff review controls without collection/governance mutation', async () => { + const f = await fixture(); + const state = await f.request('/api/staff/knowledge/state', { + principal: 'knowledge', + }); + expect(await state.json()).toMatchObject({ + attesterId: 'knowledge', + permissions: { + collectionManage: false, + validationManage: false, + evidenceConfirm: true, + review: true, + publish: true, + }, + }); + await f.command('createCollection', { + commandId: 'create', + correlationId: 'test', + expectedGeneration: 0, + collectionId: 'guides', + name: 'Guides', + }); + expect( + ( + await f.command( + 'getCollection', + { collectionId: 'guides' }, + 'knowledge', + ) + ).status, + ).toBe(200); + expect( + ( + await f.command( + 'getGovernanceConfiguration', + { collectionId: 'guides' }, + 'knowledge', + ) + ).status, + ).toBe(403); + expect( + (await f.command('putValidationPolicy', {}, 'knowledge')).status, + ).toBe(403); + expect( + ( + await f.command( + 'createCollection', + { + commandId: 'forbidden', + correlationId: 'test', + expectedGeneration: 0, + collectionId: 'other', + name: 'Other', + }, + 'knowledge', + ) + ).status, + ).toBe(403); + expect( + (await f.command('getCollection', { collectionId: 'other' })).status, + ).toBe(404); + }); + + it('keeps historical Support grants limited to human support without staff KB powers', async () => { + const f = await fixture(); + const support = await staffAccessContextFromRoles('support', f.roleStore); + expect(support).not.toBeNull(); + if (support === null) + throw new Error('Historical Support authority must remain.'); + expect( + SUPPORT_STAFF_PERMISSIONS.every((permission) => + hasPermission(support, permission), + ), + ).toBe(true); + expect( + (await f.request('/api/staff/knowledge/state', { principal: 'support' })) + .status, + ).toBe(403); + for (const operation of [ + 'getDraft', + 'getEvidence', + 'reportRead', + 'confirmReport', + 'submitForReview', + 'publishArticle', + ]) { + expect( + (await f.command(operation, { articleId: 'guide' }, 'support')).status, + ).toBe(403); + } + }); + + it('separates the signed-in portal DTOs from private staff operations', async () => { + const f = await fixture(); + expect( + (await f.request('/api/staff/knowledge/state', { principal: 'customer' })) + .status, + ).toBe(403); + expect( + (await f.command('getDraft', { articleId: 'private' }, 'customer')) + .status, + ).toBe(403); + const collections = await f.request('/api/knowledge/portal', { + principal: 'customer', + body: { operation: 'listPortalCollections', input: {} }, + }); + expect(collections.status).toBe(200); + expect(await collections.json()).toEqual({ + outcome: 'no_result', + collections: [], + }); + const draft = await f.request('/api/knowledge/portal', { + principal: 'customer', + body: { operation: 'getDraft', input: { articleId: 'private' } }, + }); + expect(draft.status).toBe(400); + expect(await draft.json()).toEqual({ error: 'unknown_operation' }); + const state = await f.request('/api/staff/knowledge/state', { + headers: { Authorization: 'Bearer not-a-browser-session' }, + }); + expect(state.status).toBe(403); + expect(await state.json()).toEqual({ error: 'browser_session_required' }); + }); + + it('checks same-origin CSRF and the exact released DTO before mutation', async () => { + const f = await fixture(); + const body = { + operation: 'createCollection', + input: { + commandId: 'unsafe', + correlationId: 'test', + expectedGeneration: 0, + collectionId: 'guides', + name: 'Guides', + }, + }; + expect( + ( + await f.request('/api/staff/knowledge/command', { + body, + headers: { Origin: 'https://attacker.example' }, + }) + ).status, + ).toBe(403); + expect( + ( + await f.request('/api/staff/knowledge/command', { + body, + headers: { 'X-Pegma-CSRF': 'x'.repeat(43) }, + }) + ).status, + ).toBe(403); + expect( + ( + await f.command('createCollection', { + ...body.input, + administrator: true, + }) + ).status, + ).toBe(400); + expect((await f.command('__proto__', {})).status).toBe(400); + expect( + (await f.command('getCollection', { collectionId: 'guides' })).status, + ).toBe(404); + }); + + it('does not expose unsupported provenance writes through any browser draft command', async () => { + const f = await fixture(); + expect( + ( + await f.command('setProvenance', { + commandId: 'source', + articleId: 'guide', + references: [], + }) + ).status, + ).toBe(400); + for (const operation of ['createDraft', 'updateDraft']) { + for (const sourceReferences of [ + [], + [ + { + id: 'private', + system: 'unsupported', + resourceId: 'resource', + version: '1', + }, + ], + ]) { + const rejected = await f.command(operation, { + commandId: operation, + sourceReferences, + }); + expect(rejected.status).toBe(400); + expect(await rejected.json()).toEqual({ + error: 'unsupported_source_references', + }); + } + } + }); + + it('honors actual stored role and identity revocation on the next request', async () => { + const f = await fixture(); + const assignment = await f.roleStore.getRoleAssignment('role-knowledge'); + if (assignment === null) throw new Error('Missing actual role assignment.'); + await f.roleStore.revokeRoleAssignmentWithAudit({ + assignmentId: 'role-knowledge', + expectedConcurrencyToken: assignment.concurrencyToken, + revokedBy: { kind: 'principal', principalId: 'admin' }, + revokedAtEpochMs: Date.parse('2026-11-08T12:00:00.000Z'), + reason: 'Synthetic revocation', + auditEventId: 'revoke-knowledge', + }); + expect( + ( + await f.request('/api/staff/knowledge/state', { + principal: 'knowledge', + }) + ).status, + ).toBe(403); + const user = f.users.get('admin'); + if (user === undefined) throw new Error('Missing synthetic user.'); + f.users.set('admin', { ...user, status: 'pending' }); + expect((await f.request('/api/staff/knowledge/state')).status).toBe(401); + const portal = await f.request('/api/knowledge/portal', { + principal: 'customer', + body: { operation: 'listPortalCollections', input: {} }, + }); + expect(portal.headers.get('Cache-Control')).toBe('no-store'); + expect(portal.headers.get('Referrer-Policy')).toBe('no-referrer'); + expect(portal.headers.get('X-Content-Type-Options')).toBe('nosniff'); + }); + + it('exposes the actual durable browser limiter with a bounded configurable budget', async () => { + const f = await fixture({ browserLimitCount: 1 }); + expect(f.runtime.limiters).toHaveLength(1); + expect(typeof f.runtime.limiters[0]?.sweep).toBe('function'); + expect((await f.request('/api/staff/knowledge/state')).status).toBe(200); + const limited = await f.request('/api/staff/knowledge/state'); + expect(limited.status).toBe(429); + expect(limited.headers.get('Retry-After')).toBe('300'); + await expect(fixture({ browserLimitCount: 0 })).rejects.toThrow(TypeError); + await expect(fixture({ browserLimitCount: 10_001 })).rejects.toThrow( + TypeError, + ); + }); + + it('reports persisted ledger corruption as an internal fault without logging its body', async () => { + const f = await fixture(); + const privatePayload = 'private-report-corruption-marker'; + await f.reportRows().put({ + articleId: 'broken', + id: 'head', + payload: privatePayload, + }); + const result = await f.command( + 'reportLedger', + { articleId: 'broken' }, + 'knowledge', + ); + expect(result.status).toBe(503); + expect(await result.json()).toEqual({ error: 'service_unavailable' }); + expect(f.logger.log).toHaveBeenCalledWith( + 'error', + 'knowledge.api_unavailable', + { error: 'KnowledgeLedgerError', stage: 'head_decode' }, + ); + expect(JSON.stringify(f.logger.log.mock.calls)).not.toContain( + privatePayload, + ); + const malformed = await f.command( + 'reportLedger', + { articleId: 'broken', injected: true }, + 'knowledge', + ); + expect(malformed.status).toBe(400); + }); +}); diff --git a/worker/src/knowledge-runtime.ts b/worker/src/knowledge-runtime.ts new file mode 100644 index 0000000..38c0bcd --- /dev/null +++ b/worker/src/knowledge-runtime.ts @@ -0,0 +1,522 @@ +import { hasPermission } from '@pegma/authorization-core'; +import type { AccessContext } from '@pegma/authorization-core'; +import type { DelegatedAccess } from '@pegma/agent-access'; +import { + createKnowledgeBaseApplication, + KnowledgeBaseAuthorizationError, + type KnowledgeBaseApplication, +} from '@pegma/knowledge-base-application'; +import { + knowledgePermissions, + type Clock, +} from '@pegma/knowledge-base-contracts'; +import { + createKnowledgeAgentDispatcher, + createKnowledgeAgentHttp, + createKnowledgeAgentMcp, + type KnowledgeAgentDispatcher, + type KnowledgeAgentResponse, +} from '@pegma/knowledge-base-mcp'; +import { + createDurableLimiter, + defineRateLimitPolicy, + type DurableRateLimiter, +} from '@pegma/rate-limit-paged'; +import type { Store } from '@pegma/storage-core'; +import { ApiError, json, type AuthenticationOptions } from './api-auth'; +import { + createAgentPrincipalResolver, + type AgentAuthorityOptions, +} from './agent-authority'; +import { + AGENT_API_URL, + AGENT_RESOURCE, + AGENT_RESOURCE_METADATA_URL, + type AgentAccessRuntime, +} from './agent-access-runtime'; +import { + createKnowledgeEvidenceService, + knowledgeDigest, + type KnowledgeEvidenceService, +} from './knowledge-evidence'; +import { createKnowledgeApi } from './knowledge-api'; +import { IDENTITY_ISSUER } from './identity-api'; +import { knowledgeAdmissionPolicyName } from './knowledge-admission'; +import { createKnowledgeRetrievalReady } from './knowledge-retrieval-ready'; + +export interface KnowledgeRuntimeOptions + extends AuthenticationOptions, AgentAuthorityOptions { + readonly store: Store; + readonly clock: Clock; + readonly agentAccess: AgentAccessRuntime | null; + readonly browserLimitCount?: number; + readonly isEnabled?: () => boolean; +} +export interface KnowledgeRuntime { + readonly application: KnowledgeBaseApplication; + readonly evidence: KnowledgeEvidenceService; + readonly limiters: readonly DurableRateLimiter[]; + handle(request: Request): Promise; +} + +/** Compose released services over the host's existing Store and live roles. */ +export function createKnowledgeRuntime( + options: KnowledgeRuntimeOptions, +): KnowledgeRuntime { + const browserLimitCount = options.browserLimitCount ?? 120; + if ( + !Number.isSafeInteger(browserLimitCount) || + browserLimitCount < 1 || + browserLimitCount > 10_000 + ) + throw new TypeError( + 'Knowledge browser limit must be an integer from 1 to 10000.', + ); + let application: KnowledgeBaseApplication; + const evidence = createKnowledgeEvidenceService({ + store: options.store, + clock: options.clock, + logger: options.logger, + resolvePrincipal: createAgentPrincipalResolver(options), + authoringContext: { + getAuthoringContext(access, input) { + return application.getAuthoringContext(access, input); + }, + confirmAuthoringContext(access, observation) { + return application.confirmAuthoringContext(access, observation); + }, + }, + async readContext(access, articleId) { + const observed = await application.getAuthoringContext(access, { + articleId, + includeEvidence: hasPermission( + access, + knowledgePermissions.evidenceRead, + ), + }); + return observed.context; + }, + }); + application = createKnowledgeBaseApplication({ + store: options.store, + clock: options.clock, + evidenceVerifier: evidence.verifier, + }); + const browserLimit = createDurableLimiter( + defineRateLimitPolicy({ + name: knowledgeAdmissionPolicyName( + 'pegma.knowledge.browser', + browserLimitCount, + ), + limit: browserLimitCount, + windowMs: 5 * 60_000, + }), + options.store, + { clock: options.clock }, + ); + const browser = createKnowledgeApi({ + ...options, + application, + evidence, + repairArticle: createKnowledgeRetrievalReady({ + store: options.store, + clock: options.clock, + logger: options.logger, + isEnabled: options.isEnabled ?? (() => true), + }).enqueue, + async limitBrowser(request) { + const key = await knowledgeDigest( + (request.headers.get('CF-Connecting-IP') ?? 'unavailable').slice( + 0, + 128, + ), + ); + const decision = await browserLimit.allow(key); + if (!decision.allowed) + throw new ApiError( + 429, + 'rate_limited', + decision.retryAfter === undefined + ? undefined + : Math.max(1, Math.ceil(decision.retryAfter / 1000)), + ); + }, + }); + const agents = options.agentAccess; + return Object.freeze({ + application, + evidence, + limiters: Object.freeze([browserLimit]), + async handle(request: Request) { + const path = new URL(request.url).pathname; + if ( + path !== new URL(AGENT_API_URL).pathname && + path !== new URL(AGENT_RESOURCE).pathname + ) + return browser(request); + if (agents === null) + return json( + { error: 'agent_access_not_configured' }, + { status: 503, headers: { 'Referrer-Policy': 'no-referrer' } }, + ); + const configuredAgents = agents; + const authorization = request.headers.get('Authorization'); + // A binding belongs to this exact request, including while the SDK awaits + // its body. No authority is stored across requests or captured globally. + let binding: + | Readonly< + Pick & { + readonly principalId: AccessContext['principalId']; + } + > + | undefined; + async function freshAccess( + original: AccessContext, + required: readonly string[], + requireAll = false, + ): Promise { + if (request.headers.get('Authorization') !== authorization) + throw new KnowledgeBaseAuthorizationError( + required[0] ?? knowledgePermissions.draftRead, + ); + const current = + await configuredAgents.protectedResource.authenticate(request); + if ( + current instanceof Response || + binding === undefined || + request.headers.get('Authorization') !== authorization || + current.access.principalId !== binding.principalId || + original.principalId !== binding.principalId || + current.grantId !== binding.grantId || + current.clientId !== binding.clientId || + current.resource !== binding.resource || + current.resource !== AGENT_RESOURCE + ) + throw new KnowledgeBaseAuthorizationError( + knowledgePermissions.draftRead, + ); + const access = Object.freeze({ + ...current.access, + roles: Object.freeze([]), + entitlements: Object.freeze([]), + permissions: Object.freeze( + current.access.permissions.filter( + (permission) => + original.permissions.includes(permission) && + current.scopes.includes(permission), + ), + ), + }); + const permitted = (permission: string) => + access.permissions.includes(permission); + if ( + !(requireAll ? required.every(permitted) : required.some(permitted)) + ) + throw new KnowledgeBaseAuthorizationError( + required[0] ?? knowledgePermissions.draftRead, + ); + return access; + } + async function invoke( + original: AccessContext, + required: readonly string[], + operation: (access: AccessContext) => Promise, + requireAll = false, + ): Promise { + const result = await operation( + await freshAccess(original, required, requireAll), + ); + // This can refuse a completed write's acknowledgement; it does not + // roll back that write or promise an atomic grant/article transaction. + await freshAccess(original, required, requireAll); + return result; + } + // Each actual tool invocation owns its read group, including when the MCP + // SDK runs the callback after constructing its outer response. + const configuration = createKnowledgeAgentDispatcher({ + application, + resource: AGENT_RESOURCE, + reports: evidence.agentReports, + }); + const dispatcher: KnowledgeAgentDispatcher = { + limits: configuration.limits, + ...(configuration.reportWorkflow === true + ? { reportWorkflow: true as const } + : {}), + async dispatch(identity, envelope): Promise { + let readContext: Promise | undefined; + let readOriginal: AccessContext | undefined; + let deferredReportArticle: string | undefined; + let deferredReportRead = false; + const clauses: { + required: readonly string[]; + requireAll: boolean; + }[] = []; + function recordClause( + required: readonly string[], + requireAll: boolean, + ) { + if ( + !clauses.some( + (clause) => + clause.requireAll === requireAll && + clause.required.length === required.length && + clause.required.every( + (permission, index) => permission === required[index], + ), + ) + ) + clauses.push({ + required: Object.freeze([...required]), + requireAll, + }); + } + function write( + original: AccessContext, + required: readonly string[], + operation: (access: AccessContext) => Promise, + requireAll = false, + ): Promise { + if (deferredReportArticle !== undefined) + throw new KnowledgeBaseAuthorizationError( + required[0] ?? knowledgePermissions.evidenceSubmit, + ); + recordClause(required, requireAll); + return invoke(original, required, operation, requireAll); + } + async function read( + original: AccessContext, + required: readonly string[], + operation: (access: AccessContext) => Promise, + requireAll = false, + finalReportArticle?: string, + ): Promise { + if ( + deferredReportArticle !== undefined && + (finalReportArticle !== deferredReportArticle || + deferredReportRead) + ) + throw new KnowledgeBaseAuthorizationError( + required[0] ?? knowledgePermissions.draftRead, + ); + if (deferredReportArticle !== undefined) deferredReportRead = true; + if ( + request.headers.get('Authorization') !== authorization || + original.principalId !== identity.access.principalId + ) + throw new KnowledgeBaseAuthorizationError( + required[0] ?? knowledgePermissions.draftRead, + ); + if (readContext === undefined) { + readOriginal = original; + readContext = freshAccess(original, required, requireAll); + } + const access = await readContext; + const permitted = (permission: string) => + original.permissions.includes(permission) && + access.permissions.includes(permission); + if ( + request.headers.get('Authorization') !== authorization || + !(requireAll + ? required.every(permitted) + : required.some(permitted)) + ) + throw new KnowledgeBaseAuthorizationError( + required[0] ?? knowledgePermissions.draftRead, + ); + recordClause(required, requireAll); + return operation(access); + } + const currentApplication: KnowledgeBaseApplication = { + ...application, + async getDraft(access, input) { + return read( + access, + [knowledgePermissions.draftRead], + (fresh) => application.getDraft(fresh, input), + false, + input.articleId, + ); + }, + async createDraft(access, input) { + return write(access, [knowledgePermissions.draftWrite], (fresh) => + application.createDraft(fresh, input), + ); + }, + async updateDraft(access, input) { + return write(access, [knowledgePermissions.draftWrite], (fresh) => + application.updateDraft(fresh, input), + ); + }, + async getValidationRequirements(access, input) { + return read( + access, + [ + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, + ], + (fresh) => application.getValidationRequirements(fresh, input), + ); + }, + async submitEvidence(access, input) { + return write( + access, + [knowledgePermissions.evidenceSubmit], + (fresh) => application.submitEvidence(fresh, input), + ); + }, + }; + const currentReports: KnowledgeEvidenceService['agentReports'] = { + async query(access, input) { + return read( + access, + [ + knowledgePermissions.draftRead, + knowledgePermissions.evidenceSubmit, + ], + (fresh) => evidence.agentReports.query(fresh, input), + true, + ); + }, + async report(access, input) { + const required = [ + knowledgePermissions.draftRead, + knowledgePermissions.evidenceSubmit, + ]; + if (readOriginal === undefined) + return write( + access, + required, + (fresh) => evidence.agentReports.report(fresh, input), + true, + ); + if (deferredReportArticle !== undefined) + throw new KnowledgeBaseAuthorizationError( + knowledgePermissions.evidenceSubmit, + ); + recordClause(required, true); + const fresh = await freshAccess(access, required, true); + // Only this mixed report path defers its postcommit observation. + // Afterward, permit only the same target's bounded getDraft read; + // the full original-credential gate runs before any logical result. + deferredReportArticle = input.articleId; + return evidence.agentReports.report(fresh, input); + }, + async ledger(access, input) { + return read( + access, + [ + knowledgePermissions.draftRead, + knowledgePermissions.evidenceSubmit, + ], + (fresh) => evidence.agentReports.ledger(fresh, input), + true, + ); + }, + async status(access, input) { + return read( + access, + [ + knowledgePermissions.draftRead, + knowledgePermissions.evidenceSubmit, + ], + (fresh) => evidence.agentReports.status(fresh, input), + true, + ); + }, + }; + const inner = createKnowledgeAgentDispatcher({ + application: currentApplication, + resource: AGENT_RESOURCE, + reports: currentReports, + }); + let operation: KnowledgeAgentResponse['operation'] = null; + async function finishReads(): Promise { + if (readOriginal !== undefined) { + // Reauthenticate the original credential once after ALL read work, + // before HTTP or the MCP tool callback can serialize any result. + const final = await freshAccess(readOriginal, [], true); + for (const clause of clauses) { + const permitted = (permission: string) => + final.permissions.includes(permission); + if ( + !(clause.requireAll + ? clause.required.every(permitted) + : clause.required.some(permitted)) + ) + throw new KnowledgeBaseAuthorizationError( + clause.required[0] ?? knowledgePermissions.draftRead, + ); + } + } + } + try { + let result: KnowledgeAgentResponse; + try { + result = await inner.dispatch(identity, envelope); + } catch (error) { + // A later SDK failure cannot escape the deferred report gate. + await finishReads(); + throw error; + } + operation = result.operation; + await finishReads(); + return result; + } catch (error) { + const forbidden = error instanceof KnowledgeBaseAuthorizationError; + return { + apiVersion: '1', + operation, + error: { + code: forbidden ? 'forbidden' : 'unavailable', + status: forbidden ? 403 : 503, + message: forbidden + ? 'Knowledge access is forbidden.' + : 'Knowledge service is unavailable.', + }, + }; + } + }, + }; + const transportOptions = { + dispatcher, + resource: AGENT_RESOURCE, + protectedResourceMetadataUrl: AGENT_RESOURCE_METADATA_URL, + allowedOrigins: [IDENTITY_ISSUER], + async authenticate(originalRequest: Request) { + if (originalRequest !== request) + throw new KnowledgeBaseAuthorizationError( + knowledgePermissions.draftRead, + ); + const identity = + await configuredAgents.protectedResource.authenticate( + originalRequest, + ); + if (request.headers.get('Authorization') !== authorization) + throw new KnowledgeBaseAuthorizationError( + knowledgePermissions.draftRead, + ); + if (!(identity instanceof Response)) + binding = Object.freeze({ + principalId: identity.access.principalId, + grantId: identity.grantId, + clientId: identity.clientId, + resource: identity.resource, + }); + return identity; + }, + limit: (originalRequest: Request) => + configuredAgents.resourceLimit(originalRequest), + }; + const http = createKnowledgeAgentHttp({ + ...transportOptions, + apiUrl: AGENT_API_URL, + }); + const mcp = createKnowledgeAgentMcp({ + ...transportOptions, + mcpUrl: AGENT_RESOURCE, + }); + return (await http.handle(request)) ?? (await mcp.handle(request)); + }, + }); +} diff --git a/worker/src/maintenance-cursors.d1.test.ts b/worker/src/maintenance-cursors.d1.test.ts index 8067e3a..2185d4f 100644 --- a/worker/src/maintenance-cursors.d1.test.ts +++ b/worker/src/maintenance-cursors.d1.test.ts @@ -1,6 +1,7 @@ import { env } from 'cloudflare:workers'; import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; import { createSessionStore } from '@pegma/sessions'; +import { createDurableLimiter } from '@pegma/rate-limit-paged'; import { systemClock, type Logger } from '@pegma/spine'; import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { @@ -19,7 +20,12 @@ import { createProductionSupportMaintenanceRuntime, } from './support-desk'; import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; -import { cleanupLaneAt } from './maintenance-schedule'; +import { + cleanupLaneAt, + rateKnowledgeLaneAt, + RATE_LIMIT_CRON, +} from './maintenance-schedule'; +import worker from './index'; const logger: Logger = { log: vi.fn() }; /** Semantically matches worker/migrations/0001_pegma_storage.sql. */ @@ -66,6 +72,65 @@ beforeEach(async () => { await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); }); +/** Count binding executions while all SQL still runs against the real D1. */ +function limitedD1(database: D1Database) { + let calls = 0; + const originals = new WeakMap(); + const charge = () => { + calls += 1; + if (calls > 50) + throw new Error('Synthetic Workers Free D1 call limit exceeded.'); + }; + const statement = (original: D1PreparedStatement): D1PreparedStatement => { + const counted = new Proxy(original, { + get(target, property) { + if (property === 'bind') + return (...values: unknown[]) => statement(target.bind(...values)); + const method = Reflect.get(target, property, target); + if (['first', 'run', 'all', 'raw'].includes(String(property))) { + return (...args: unknown[]) => { + charge(); + return Reflect.apply(method, target, args); + }; + } + return typeof method === 'function' ? method.bind(target) : method; + }, + }); + originals.set(counted, original); + return counted; + }; + const binding = (original: T): T => + new Proxy(original, { + get(target, property) { + if (property === 'prepare') + return (query: string) => statement(target.prepare(query)); + if (property === 'batch') + return (statements: D1PreparedStatement[]) => { + // D1 documents one invocation query for the entire batch call. + charge(); + return target.batch( + statements.map((item) => originals.get(item) ?? item), + ); + }; + if (property === 'withSession' && 'withSession' in target) { + return (constraint?: D1SessionBookmark | D1SessionConstraint) => + binding(target.withSession(constraint)); + } + const method = Reflect.get(target, property, target); + if (property === 'exec' || property === 'dump') { + if (typeof method !== 'function') + throw new TypeError('Expected a callable D1 execution method.'); + return (...args: unknown[]) => { + charge(); + return Reflect.apply(method, target, args); + }; + } + return typeof method === 'function' ? method.bind(target) : method; + }, + }); + return { database: binding(database), calls: () => calls }; +} + function fixture() { const store = createCloudflareD1Store({ database: env.IDENTITY_DB, @@ -119,6 +184,118 @@ function fixture() { } describe('maintenance cursor writes over D1', () => { + it('runs two actual isolated scheduled pages within 50 D1 calls each and persists their continuation', async () => { + const { store } = fixture(); + const start = new Date(Date.now() - 180_000).toISOString(); + const limiter = createDurableLimiter( + { name: 'pegma.test.d1.knowledge.capacity', limit: 1, windowMs: 60_000 }, + store, + ); + for (let index = 0; index < 25; index++) { + expect(await limiter.allow(`192.0.2.${index + 1}`, start)).toEqual({ + allowed: true, + }); + } + const invoke = async () => { + const metered = limitedD1(env.IDENTITY_DB); + const pending: Promise[] = []; + const secretRead = vi.fn(() => { + throw new Error('Rate maintenance must not read Identity secrets.'); + }); + const scheduledEnvironment: Parameters[1] = { + ...env, + IDENTITY_DB: metered.database, + DATADOG_API_KEY: undefined, + PEGMA_KNOWLEDGE_ENABLED: 'false', + get IDENTITY_EMAIL_CODE_SECRET_BASE64(): string { + return secretRead(); + }, + }; + // Wrangler's generated type records the deployed default literal, while + // this test intentionally supplies malformed runtime configuration. + Object.defineProperty(scheduledEnvironment, 'PEGMA_AGENT_CLIENTS_JSON', { + value: 'not-json', + }); + const startMinute = Math.floor(Date.now() / 60_000) * 60_000; + const scheduledTime = Array.from( + { length: 120 }, + (_, offset) => startMinute + offset * 60_000, + ).find( + (candidate) => + new Date(candidate).getUTCMinutes() <= 57 && + rateKnowledgeLaneAt(candidate) === 'rate_limits', + ); + if (scheduledTime === undefined) + throw new Error('No actual rate-lane tick in the bounded schedule.'); + worker.scheduled( + { + cron: RATE_LIMIT_CRON, + scheduledTime, + noRetry() {}, + }, + scheduledEnvironment, + { + waitUntil: (promise: Promise) => { + pending.push(promise); + }, + passThroughOnException() {}, + props: {}, + exports: {}, + } as ExecutionContext, + ); + await Promise.all(pending); + expect(pending).toHaveLength(1); + expect(secretRead).not.toHaveBeenCalled(); + expect(metered.calls()).toBeGreaterThan(0); + expect(metered.calls()).toBeLessThanOrEqual(50); + return metered.calls(); + }; + const read = async () => { + const row = await env.IDENTITY_DB.prepare( + "SELECT record_json FROM RECORDS WHERE partition_key = 'pegma-dev-maintenance:knowledge' AND row_key = 'rate-limits' AND deleted = 0", + ).first<{ record_json: string }>(); + return row === null ? null : JSON.parse(row.record_json); + }; + const firstCalls = await invoke(); + expect(await read()).toEqual({ + partition: 'knowledge', + id: 'rate-limits', + cursor: expect.any(String), + generation: 1, + }); + // Twenty deleted counters, five remaining counters, descriptor and bookmark. + expect( + await env.IDENTITY_DB.prepare( + 'SELECT COUNT(*) AS count FROM RECORDS WHERE deleted = 0', + ).first('count'), + ).toBe(7); + const secondCalls = await invoke(); + expect(await read()).toEqual({ + partition: 'knowledge', + id: 'rate-limits', + cursor: null, + generation: 2, + }); + expect(firstCalls).toBeGreaterThan(secondCalls); + expect([firstCalls, secondCalls]).toEqual([44, 14]); + // No other maintenance records were created by either scheduled invocation. + expect( + await env.IDENTITY_DB.prepare( + 'SELECT COUNT(*) AS count FROM RECORDS WHERE deleted = 0', + ).first('count'), + ).toBe(2); + const batching = limitedD1(env.IDENTITY_DB); + const results = await batching.database.batch([ + batching.database.prepare('SELECT 1 AS value'), + batching.database.prepare('SELECT 2 AS value'), + ]); + expect(results.map((result) => result.results[0])).toEqual([ + { value: 1 }, + { value: 2 }, + ]); + expect(batching.calls()).toBe(1); + }); + it('drains real mail jobs one per tick and resumes safely after wrapping', async () => { const { store } = fixture(); const send = vi.fn(async () => ({ @@ -197,7 +374,7 @@ describe('maintenance cursor writes over D1', () => { expect( createProductionSupportMaintenanceRuntime(env).limiters, ).toHaveLength(supportLimiters.length); - const lanes = Array.from({ length: 14 }, (_, index) => + const lanes = Array.from({ length: 15 }, (_, index) => cleanupLaneAt(Date.parse('2026-10-15T12:01:00Z') + index * 60_000), ); for (const [kind, limiters] of [ @@ -205,6 +382,7 @@ describe('maintenance cursor writes over D1', () => { ['support', supportLimiters], ] as const) { const indices = lanes + .filter((lane) => lane.kind !== 'knowledge') .filter((lane) => lane.kind === kind && lane.task === 'rate_limits') .map((lane) => lane.limiterIndex) .sort(); diff --git a/worker/src/maintenance-schedule.test.ts b/worker/src/maintenance-schedule.test.ts index 47027d9..fbd39a4 100644 --- a/worker/src/maintenance-schedule.test.ts +++ b/worker/src/maintenance-schedule.test.ts @@ -1,20 +1,43 @@ import { readFileSync } from 'node:fs'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; import { describe, expect, it, vi, beforeEach } from 'vitest'; import { MAIL_CRON, MAIL_RECONCILE_CRON, CLEANUP_CRON, + RATE_LIMIT_CRON, cleanupLaneAt, + rateKnowledgeLaneAt, } from './maintenance-schedule'; import { RELEASE_RECONCILIATION_CRON, runReleaseReconciliation, } from './release-reconciliation'; import { runIdentityMaintenance } from './identity-maintenance'; +import { runKnowledgeMaintenance } from './knowledge-maintenance'; +import { createKnowledgeRetrievalMaintenance } from './knowledge-retrieval-maintenance'; +import { createKnowledgeRetrievalReady } from './knowledge-retrieval-ready'; import { runSupportMaintenance } from './support-maintenance'; import worker from './index'; vi.mock('./identity-maintenance', () => ({ runIdentityMaintenance: vi.fn() })); +vi.mock('./knowledge-maintenance', () => ({ + runKnowledgeMaintenance: vi.fn(), +})); +vi.mock('./knowledge-retrieval-maintenance', () => ({ + createKnowledgeRetrievalMaintenance: vi.fn(() => ({ + runPage: vi.fn(async () => {}), + })), +})); +vi.mock('./knowledge-retrieval-ready', () => ({ + createKnowledgeRetrievalReady: vi.fn(() => ({ + runPage: vi.fn(async () => {}), + enqueue: vi.fn(async () => {}), + })), +})); +vi.mock('@pegma/storage-cloudflare-d1', () => ({ + createCloudflareD1Store: vi.fn(() => ({})), +})); vi.mock('./support-maintenance', () => ({ runSupportMaintenance: vi.fn() })); vi.mock('./logger', () => ({ createAppLogger: () => ({ log: vi.fn() }) })); vi.mock('./identity-runtime', () => ({ @@ -45,11 +68,31 @@ vi.mock('./release-reconciliation', async (original) => ({ runReleaseReconciliation: vi.fn(), })); -async function scheduled(cron: string, time: number) { +async function scheduled( + cron: string, + time: number, + environment: Record = {}, +) { const pending: Promise[] = []; + // This tests routing with mocked runtime builders. Storage is deliberately + // unavailable; a routing regression must not silently reach a fake database. + const unavailable = (): never => { + throw new Error('Scheduler routing fixture cannot access D1.'); + }; + const identityDatabase: D1Database = { + prepare: unavailable, + batch: unavailable, + exec: unavailable, + withSession: unavailable, + dump: unavailable, + }; + const routingEnvironment = { + ...environment, + IDENTITY_DB: identityDatabase, + }; worker.scheduled( { cron, scheduledTime: time, noRetry() {} }, - {} as Parameters[1], + routingEnvironment as Parameters[1], { waitUntil: (promise: Promise) => { pending.push(promise); @@ -60,6 +103,20 @@ async function scheduled(cron: string, time: number) { } as ExecutionContext, ); await Promise.all(pending); + return pending.length; +} + +function knowledgeCleanupTime(): number { + const start = Date.parse('2026-10-15T00:00:00Z'); + for (let minute = 0; minute < 60; minute++) { + const time = start + minute * 60_000; + if ( + new Date(time).getUTCMinutes() !== 59 && + cleanupLaneAt(time).kind === 'knowledge' + ) + return time; + } + throw new Error('Expected one knowledge cleanup lane.'); } describe('maintenance dispatch', () => { @@ -74,7 +131,7 @@ describe('maintenance dispatch', () => { ]) { expect(cleanupLaneAt(time)).toEqual( expect.objectContaining({ - kind: expect.stringMatching(/^(identity|support)$/), + kind: expect.stringMatching(/^(identity|support|knowledge)$/), }), ); } @@ -88,13 +145,17 @@ describe('maintenance dispatch', () => { new URL('../wrangler.jsonc', import.meta.url), 'utf8', ); - const crons = JSON.parse(config.match(/"crons":\s*(\[[^\]]*\])/)![1]!); + const crons = JSON.parse( + config.match(/"crons":\s*(\[[^\]]*\])/)![1]!.replace(/,\s*\]$/u, ']'), + ); expect(crons).toEqual([ MAIL_CRON, MAIL_RECONCILE_CRON, CLEANUP_CRON, + RATE_LIMIT_CRON, RELEASE_RECONCILIATION_CRON, ]); + expect(new Set(crons).size).toBe(5); }); it('advances each cleanup lane exactly once per eligible tick in the configured cron', () => { @@ -113,8 +174,8 @@ describe('maintenance dispatch', () => { observed.push(JSON.stringify(cleanupLaneAt(time))); } } - const cycle = observed.slice(0, 14); - expect(new Set(cycle).size).toBe(14); + const cycle = observed.slice(0, 15); + expect(new Set(cycle).size).toBe(15); for (let index = 0; index < observed.length; index++) { expect(observed[index]).toBe(cycle[index % cycle.length]); } @@ -128,6 +189,8 @@ describe('maintenance dispatch', () => { { tasks: ['mail_send'] }, ); expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); expect(runReleaseReconciliation).not.toHaveBeenCalled(); }); @@ -139,41 +202,54 @@ describe('maintenance dispatch', () => { { tasks: ['mail_reconcile'] }, ); expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); expect(runReleaseReconciliation).not.toHaveBeenCalled(); }); - it('covers all 14 cleanup lanes once across a UTC day boundary', async () => { + it('preserves all 15 cleanup lanes across a UTC day boundary without sharing the global rate job', async () => { const lanes = []; const start = Date.parse('2026-10-15T23:53:00Z'); - for (let minute = 0; minute < 15; minute++) { + for (let minute = 0; minute < 16; minute++) { const time = start + minute * 60_000; if (new Date(time).getUTCMinutes() === 59) continue; const lane = cleanupLaneAt(time); lanes.push(JSON.stringify(lane)); vi.clearAllMocks(); await scheduled(CLEANUP_CRON, time); - const selected = - lane.kind === 'identity' - ? runIdentityMaintenance - : runSupportMaintenance; - const other = - lane.kind === 'identity' - ? runSupportMaintenance - : runIdentityMaintenance; - expect(selected).toHaveBeenCalledExactlyOnceWith( - expect.anything(), - expect.anything(), - { - tasks: [lane.task], - ...(lane.limiterIndex === undefined - ? {} - : { limiterIndex: lane.limiterIndex }), - }, - ); - expect(other).not.toHaveBeenCalled(); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + const maintenance = { + identity: runIdentityMaintenance, + support: runSupportMaintenance, + }; + if (lane.kind !== 'knowledge') { + expect(maintenance[lane.kind]).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.anything(), + { + tasks: [lane.task], + ...(lane.limiterIndex === undefined + ? {} + : { limiterIndex: lane.limiterIndex }), + }, + ); + } + for (const [kind, other] of Object.entries(maintenance)) { + if (kind !== lane.kind) expect(other).not.toHaveBeenCalled(); + } expect(runReleaseReconciliation).not.toHaveBeenCalled(); } - expect(new Set(lanes).size).toBe(14); + expect(new Set(lanes).size).toBe(15); + expect( + lanes.filter( + (lane) => + lane === + JSON.stringify({ + kind: 'knowledge', + task: 'rate_limits', + }), + ), + ).toHaveLength(1); for (const kind of ['identity', 'support']) { for (let limiterIndex = 0; limiterIndex < 4; limiterIndex++) { expect(lanes).toContain( @@ -183,6 +259,148 @@ describe('maintenance dispatch', () => { } }); + it('isolates 39 rate pages and 19 ready pages per hour across a UTC day boundary', async () => { + const range = /^(\d+)-(\d+) \* \* \* \*$/.exec(RATE_LIMIT_CRON); + expect(range).not.toBeNull(); + const start = Date.parse('2026-10-15T23:00:00Z'); + let pages = 0; + let readyPages = 0; + for (let minute = 0; minute < 120; minute++) { + const time = start + minute * 60_000; + const utcMinute = new Date(time).getUTCMinutes(); + if (utcMinute < Number(range![1]) || utcMinute > Number(range![2])) + continue; + vi.clearAllMocks(); + expect( + await scheduled(RATE_LIMIT_CRON, time, { + PEGMA_KNOWLEDGE_ENABLED: 'true', + }), + ).toBe(1); + if (rateKnowledgeLaneAt(time) === 'rate_limits') { + expect(runKnowledgeMaintenance).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.anything(), + { tasks: ['rate_limits'] }, + ); + expect(createKnowledgeRetrievalReady).not.toHaveBeenCalled(); + } else { + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalReady).toHaveBeenCalledTimes(1); + const built = vi.mocked(createKnowledgeRetrievalReady).mock.results[0]; + if (built?.type !== 'return') + throw new Error('Expected ready composition.'); + expect(built.value.runPage).toHaveBeenCalledTimes(1); + readyPages += 1; + } + pages += vi.mocked(runKnowledgeMaintenance).mock.calls.length; + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); + expect(runIdentityMaintenance).not.toHaveBeenCalled(); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runReleaseReconciliation).not.toHaveBeenCalled(); + if (utcMinute === Number(range![2])) { + const hours = Math.floor(minute / 60) + 1; + expect(pages).toBe(hours * 39); + expect(readyPages).toBe(hours * 19); + } + } + }); + + it('isolates a failed rate invocation from later identity and support cleanup invocations', async () => { + const start = Date.parse('2026-10-15T00:00:00Z'); + for (const kind of ['identity', 'support'] as const) { + const offset = Array.from({ length: 15 }, (_, minute) => minute).find( + (minute) => cleanupLaneAt(start + minute * 60_000).kind === kind, + ); + if (offset === undefined) + throw new Error('Expected a rotating cleanup lane.'); + vi.clearAllMocks(); + vi.mocked(runKnowledgeMaintenance).mockRejectedValueOnce( + new Error('Synthetic limiter failure.'), + ); + const time = start + offset * 60_000; + expect(await scheduled(RATE_LIMIT_CRON, start)).toBe(1); + expect(runKnowledgeMaintenance).toHaveBeenCalledTimes(1); + expect(runIdentityMaintenance).not.toHaveBeenCalled(); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); + vi.clearAllMocks(); + await scheduled(CLEANUP_CRON, time); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect( + kind === 'identity' ? runIdentityMaintenance : runSupportMaintenance, + ).toHaveBeenCalledTimes(1); + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); + } + }); + + it('runs the isolated rate job while knowledge is disabled and client configuration is invalid', async () => { + await scheduled(RATE_LIMIT_CRON, Date.parse('2026-10-15T00:00:00Z'), { + PEGMA_KNOWLEDGE_ENABLED: 'false', + PEGMA_AGENT_CLIENTS_JSON: 'not-json', + }); + expect(runKnowledgeMaintenance).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + store: expect.anything(), + clock: expect.anything(), + }), + expect.anything(), + { tasks: ['rate_limits'] }, + ); + expect(runIdentityMaintenance).not.toHaveBeenCalled(); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runReleaseReconciliation).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); + }); + + it('does not construct a projection Store on a disabled ready tick, even with malformed OAuth configuration', async () => { + await scheduled(RATE_LIMIT_CRON, Date.parse('2026-10-15T00:02:00Z'), { + PEGMA_KNOWLEDGE_ENABLED: 'false', + PEGMA_AGENT_CLIENTS_JSON: 'not-json', + }); + expect(createCloudflareD1Store).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalReady).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect(runIdentityMaintenance).not.toHaveBeenCalled(); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + }); + + it('runs one enabled KB page on the existing knowledge tick without running the global rate job', async () => { + await scheduled(CLEANUP_CRON, knowledgeCleanupTime(), { + PEGMA_KNOWLEDGE_ENABLED: 'true', + PEGMA_AGENT_CLIENTS_JSON: 'not-json', + }); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).toHaveBeenCalledTimes(1); + const invocation = vi.mocked(createKnowledgeRetrievalMaintenance).mock + .results[0]; + if (invocation?.type !== 'return') + throw new Error('Expected the actual scheduler repair composition.'); + expect(invocation.value.runPage).toHaveBeenCalledTimes(1); + const options = vi.mocked(createKnowledgeRetrievalMaintenance).mock + .calls[0]?.[0]; + expect(options?.isEnabled()).toBe(true); + expect(runIdentityMaintenance).not.toHaveBeenCalled(); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runReleaseReconciliation).not.toHaveBeenCalled(); + }); + + it('keeps the isolated rate job available after enabled KB composition fails', async () => { + vi.mocked(createKnowledgeRetrievalMaintenance).mockImplementationOnce( + () => { + throw new Error('Synthetic repair composition failure.'); + }, + ); + await scheduled(CLEANUP_CRON, knowledgeCleanupTime(), { + PEGMA_KNOWLEDGE_ENABLED: 'true', + }); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).toHaveBeenCalledTimes(1); + await scheduled(RATE_LIMIT_CRON, Date.parse('2026-10-15T00:00:00Z')); + expect(runKnowledgeMaintenance).toHaveBeenCalledTimes(1); + expect(createKnowledgeRetrievalMaintenance).toHaveBeenCalledTimes(1); + }); + it('runs only release reconciliation on its own cron and ignores unknown crons', async () => { await scheduled( RELEASE_RECONCILIATION_CRON, @@ -196,5 +414,7 @@ describe('maintenance dispatch', () => { ); expect(runIdentityMaintenance).not.toHaveBeenCalled(); expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runKnowledgeMaintenance).not.toHaveBeenCalled(); + expect(createKnowledgeRetrievalMaintenance).not.toHaveBeenCalled(); }); }); diff --git a/worker/src/maintenance-schedule.ts b/worker/src/maintenance-schedule.ts index 39a6eb0..12e78f6 100644 --- a/worker/src/maintenance-schedule.ts +++ b/worker/src/maintenance-schedule.ts @@ -1,13 +1,16 @@ import type { IdentityMaintenanceTask } from './identity-maintenance'; +import type { KnowledgeMaintenanceTask } from './knowledge-maintenance'; import type { SupportMaintenanceTask } from './support-maintenance'; export const MAIL_CRON = '* * * * *'; // Skip minute zero so every trigger has a distinct schedule. export const MAIL_RECONCILE_CRON = '1-59 * * * *'; -// Cleanup skips minute 59 and rotates through 14 small lanes. +// Cleanup skips minute 59 and rotates through 15 small lanes. export const CLEANUP_CRON = '0-58 * * * *'; +// Two ticks clean rate windows, then one advances a ready KB hint. +export const RATE_LIMIT_CRON = '0-57 * * * *'; -type CleanupLane = +export type CleanupLane = | { readonly kind: 'identity'; readonly task: IdentityMaintenanceTask; @@ -17,6 +20,10 @@ type CleanupLane = readonly kind: 'support'; readonly task: SupportMaintenanceTask; readonly limiterIndex?: number; + } + | { + readonly kind: 'knowledge'; + readonly task: KnowledgeMaintenanceTask; }; const CLEANUP_LANES: readonly CleanupLane[] = [ @@ -36,6 +43,7 @@ const CLEANUP_LANES: readonly CleanupLane[] = [ task: 'rate_limits' as const, limiterIndex, })), + { kind: 'knowledge', task: 'rate_limits' }, ]; /** Deterministic across cold starts, delayed delivery, and UTC hour boundaries. */ @@ -46,3 +54,12 @@ export function cleanupLaneAt(scheduledTime: number): CleanupLane { const length = CLEANUP_LANES.length; return CLEANUP_LANES[((tick % length) + length) % length]!; } + +/** The two jobs never share an invocation or its D1 query allowance. */ +export function rateKnowledgeLaneAt( + scheduledTime: number, +): 'rate_limits' | 'retrieval_ready' { + return Math.floor(scheduledTime / 60_000) % 3 === 2 + ? 'retrieval_ready' + : 'rate_limits'; +} diff --git a/worker/src/support-access.ts b/worker/src/support-access.ts index 8bbbebb..866652d 100644 --- a/worker/src/support-access.ts +++ b/worker/src/support-access.ts @@ -7,6 +7,8 @@ import type { PolicyDocumentV1 } from '@pegma/authorization-policy'; import type { RoleAssignmentReader } from '@pegma/authorization-storage'; import type { PrincipalId } from '@pegma/spine'; import { supportPermissions } from '@pegma/support-desk-application'; +import { DEFAULT_APPROVAL_PERMISSION } from '@pegma/agent-access'; +import { knowledgePermissions } from '@pegma/knowledge-base-contracts'; /** Customer permission set for authenticated pegma.dev accounts. */ export const SUPPORT_CUSTOMER_PERMISSIONS = Object.freeze([ @@ -27,12 +29,44 @@ export const SUPPORT_STAFF_PERMISSIONS = Object.freeze([ /** The support-operator role name (docs/ROLE_ADOPTION_PLAN.md). */ export const SUPPORT_ROLE = 'Support' as const; +/** Explicitly assigned KB staff authority, independent of Support grants. */ +export const KNOWLEDGE_ROLE = 'Knowledge' as const; /** * The role-administration role name — mapped since the Phase 5 surface * shipped; the permissions below are exactly what the admin API checks. */ export const ADMIN_ROLE = 'Admin' as const; +export const AGENT_LINK_PERMISSION = DEFAULT_APPROVAL_PERMISSION; +/** Initial delegated permissions; linking and human governance are excluded. */ +export const AGENT_KNOWLEDGE_PERMISSIONS = Object.freeze([ + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceSubmit, +] as const); +/** Human review of a test report is never an OAuth consent scope. */ +export const KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION = + 'pegma.knowledge.evidence.confirm'; +export const KNOWLEDGE_STAFF_PERMISSIONS = Object.freeze([ + knowledgePermissions.collectionRead, + knowledgePermissions.articleRead, + knowledgePermissions.draftRead, + knowledgePermissions.draftWrite, + knowledgePermissions.evidenceRead, + knowledgePermissions.evidenceSubmit, + knowledgePermissions.provenanceRead, + knowledgePermissions.provenanceWrite, + knowledgePermissions.reviewSubmit, + knowledgePermissions.review, + knowledgePermissions.publish, + knowledgePermissions.evidenceRevoke, + knowledgePermissions.retire, + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, +] as const); +export const KNOWLEDGE_ADMIN_PERMISSIONS = Object.freeze([ + ...Object.values(knowledgePermissions), + KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION, +]); /** Admin permission set, granted via the {@link ADMIN_ROLE} role. */ export const ADMIN_PERMISSIONS = Object.freeze([ @@ -61,17 +95,24 @@ export const APPLICATION_SCOPE = Object.freeze({ * Customer permissions are granted to any authenticated account via * `defaults` — not a paid entitlement or invented multi-tenant role (there * is no billing ledger on pegma.dev; roles are the only stored grant). - * Staff permissions are granted via the stored, audited `Support` role, + * Support permissions are granted via the stored, audited `Support` role, + * and KB staff permissions require the separately assigned `Knowledge` role; * and role administration via the stored, audited `Admin` role — mapped - * with the Phase 5 surface (version 2 of the document). + * with the Phase 5 surface. Version 3 adds Knowledge Base permissions and + * administrator-only agent linking without replacing any stored assignment. */ export const PEGMA_ACCESS_POLICY: PolicyDocumentV1 = Object.freeze({ schemaVersion: 1, - version: 'pegma.dev-policy-2', - defaults: [...SUPPORT_CUSTOMER_PERMISSIONS], + version: 'pegma.dev-policy-3', + defaults: [...SUPPORT_CUSTOMER_PERMISSIONS, knowledgePermissions.articleRead], roles: Object.freeze({ [SUPPORT_ROLE]: [...SUPPORT_STAFF_PERMISSIONS], - [ADMIN_ROLE]: [...ADMIN_PERMISSIONS], + [KNOWLEDGE_ROLE]: [...KNOWLEDGE_STAFF_PERMISSIONS], + [ADMIN_ROLE]: [ + ...ADMIN_PERMISSIONS, + AGENT_LINK_PERMISSION, + ...KNOWLEDGE_ADMIN_PERMISSIONS, + ], }), }); @@ -91,9 +132,7 @@ export type SupportRoleReader = Pick< * server-side session (never a browser-supplied claim). Customer * permissions come from the unified policy's `defaults`. */ -export function customerAccessContext( - principalId: PrincipalId, -): AccessContext { +export function customerAccessContext(principalId: PrincipalId): AccessContext { return resolveAccess({ principalId }, PEGMA_ACCESS_POLICY); } @@ -118,8 +157,5 @@ export async function staffAccessContextFromRoles( { principalId, roles: assignments.map((assignment) => assignment.role) }, PEGMA_ACCESS_POLICY, ); - return hasPermission(context, supportPermissions.queueRead) - ? context - : null; + return hasPermission(context, supportPermissions.queueRead) ? context : null; } - diff --git a/worker/worker-configuration.d.ts b/worker/worker-configuration.d.ts index b6c0128..ea0052f 100644 --- a/worker/worker-configuration.d.ts +++ b/worker/worker-configuration.d.ts @@ -1,25 +1,29 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: 077dc894d6ddafa61f2fb71a1426732c) +// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: a18220f8dbb36158ee2acfd36ef59c5b) // Runtime types generated with workerd@1.20260722.1 2026-07-28 nodejs_compat interface __BaseEnv_Env { - IDENTITY_DB: D1Database; - IDENTITY_EMAIL_FROM: "Pegma "; - IDENTITY_EMAIL_ENABLED: "true"; - GITHUB_ORGANIZATION_ID: "309286193"; - GITHUB_ALLOWED_REPOSITORY_IDS: "1312512520,1312519623,1312811498,1312961609,1312942188,1313911960,1313917945,1314116350,1314093835,1313927900,1314239450,1314421283,1313936481"; + IDENTITY_DB: D1Database; + PEGMA_KNOWLEDGE_ENABLED: "false"; + PEGMA_AGENT_CLIENTS_JSON: "[]"; + PEGMA_KNOWLEDGE_BROWSER_LIMIT: "120"; + PEGMA_AGENT_RESOURCE_LIMIT: "300"; + IDENTITY_EMAIL_FROM: "Pegma "; + IDENTITY_EMAIL_ENABLED: "true"; + GITHUB_ORGANIZATION_ID: "309286193"; + GITHUB_ALLOWED_REPOSITORY_IDS: "1312512520,1312519623,1312811498,1312961609,1312942188,1313911960,1313917945,1314116350,1314093835,1313927900,1314239450,1314421283,1313936481"; } declare namespace Cloudflare { - interface GlobalProps { - mainModule: typeof import("./src/index"); - } - interface Env extends __BaseEnv_Env {} + interface GlobalProps { + mainModule: typeof import("./src/index"); + } + interface Env extends __BaseEnv_Env {} } interface Env extends __BaseEnv_Env {} type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; + [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; }; declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} + interface ProcessEnv extends StringifyValues> {} } // Begin runtime types diff --git a/worker/wrangler.jsonc b/worker/wrangler.jsonc index 88038fb..2cb3b3c 100644 --- a/worker/wrangler.jsonc +++ b/worker/wrangler.jsonc @@ -11,16 +11,34 @@ "pattern": "pegma.dev/api/*", "zone_name": "pegma.dev", }, + { + "pattern": "pegma.dev/.well-known/oauth-authorization-server", + "zone_name": "pegma.dev", + }, + { + "pattern": "pegma.dev/.well-known/oauth-protected-resource/api/knowledge/mcp", + "zone_name": "pegma.dev", + }, ], "vars": { + "PEGMA_KNOWLEDGE_ENABLED": "false", + "PEGMA_AGENT_CLIENTS_JSON": "[]", + "PEGMA_KNOWLEDGE_BROWSER_LIMIT": "120", + "PEGMA_AGENT_RESOURCE_LIMIT": "300", "IDENTITY_EMAIL_FROM": "Pegma ", "IDENTITY_EMAIL_ENABLED": "true", "GITHUB_ORGANIZATION_ID": "309286193", "GITHUB_ALLOWED_REPOSITORY_IDS": "1312512520,1312519623,1312811498,1312961609,1312942188,1313911960,1313917945,1314116350,1314093835,1313927900,1314239450,1314421283,1313936481", }, "triggers": { - // Separate minute mail lanes; rotating cleanup; one release repo per minute. - "crons": ["* * * * *", "1-59 * * * *", "0-58 * * * *", "0-59 */6 * * *"], + // Separate mail, rotating cleanup, isolated rate page, and release lanes. + "crons": [ + "* * * * *", + "1-59 * * * *", + "0-58 * * * *", + "0-57 * * * *", + "0-59 */6 * * *", + ], }, "d1_databases": [ {