From 898b1838836512821eabb8886aa37834e8cbffe6 Mon Sep 17 00:00:00 2001
From: Nathan Rover
Date: Sun, 8 Nov 2026 09:40:59 -0500
Subject: [PATCH 1/7] [PG-01] Compose signed-in Knowledge Base and scoped agent
access
---
docs/KNOWLEDGE_COMPOSITION.md | 102 ++
package.json | 5 +
pnpm-lock.yaml | 135 +-
public/_headers | 16 +
public/account.js | 36 +
public/agent-access.js | 291 ++++
public/knowledge.js | 169 +++
public/staff-knowledge.js | 577 ++++++++
src/layouts/Base.astro | 1 +
src/pages/account.astro | 8 +
src/pages/account/agents/authorize.astro | 51 +
src/pages/account/agents/device.astro | 57 +
src/pages/knowledge.astro | 48 +
src/pages/staff/knowledge.astro | 100 ++
worker/src/agent-access-api.ts | 162 +++
worker/src/agent-access-runtime.test.ts | 489 +++++++
worker/src/agent-access-runtime.ts | 267 ++++
worker/src/agent-authority.ts | 127 ++
worker/src/index.ts | 5 +
worker/src/knowledge-api.ts | 407 ++++++
worker/src/knowledge-evidence.test.ts | 567 ++++++++
worker/src/knowledge-evidence.ts | 806 +++++++++++
worker/src/knowledge-host.test.ts | 54 +
worker/src/knowledge-host.ts | 105 ++
worker/src/knowledge-integration.d1.test.ts | 1145 ++++++++++++++++
worker/src/knowledge-integration.test.ts | 1367 +++++++++++++++++++
worker/src/knowledge-runtime.test.ts | 374 +++++
worker/src/knowledge-runtime.ts | 171 +++
worker/src/support-access.ts | 59 +-
worker/worker-configuration.d.ts | 26 +-
worker/wrangler.jsonc | 10 +
31 files changed, 7708 insertions(+), 29 deletions(-)
create mode 100644 docs/KNOWLEDGE_COMPOSITION.md
create mode 100644 public/agent-access.js
create mode 100644 public/knowledge.js
create mode 100644 public/staff-knowledge.js
create mode 100644 src/pages/account/agents/authorize.astro
create mode 100644 src/pages/account/agents/device.astro
create mode 100644 src/pages/knowledge.astro
create mode 100644 src/pages/staff/knowledge.astro
create mode 100644 worker/src/agent-access-api.ts
create mode 100644 worker/src/agent-access-runtime.test.ts
create mode 100644 worker/src/agent-access-runtime.ts
create mode 100644 worker/src/agent-authority.ts
create mode 100644 worker/src/knowledge-api.ts
create mode 100644 worker/src/knowledge-evidence.test.ts
create mode 100644 worker/src/knowledge-evidence.ts
create mode 100644 worker/src/knowledge-host.test.ts
create mode 100644 worker/src/knowledge-host.ts
create mode 100644 worker/src/knowledge-integration.d1.test.ts
create mode 100644 worker/src/knowledge-integration.test.ts
create mode 100644 worker/src/knowledge-runtime.test.ts
create mode 100644 worker/src/knowledge-runtime.ts
diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md
new file mode 100644
index 0000000..54c8b85
--- /dev/null
+++ b/docs/KNOWLEDGE_COMPOSITION.md
@@ -0,0 +1,102 @@
+# Knowledge Base host composition
+
+The host consumes exact published `@pegma/agent-access@0.1.1` and the four
+`@pegma/knowledge-base-*` packages at `0.1.2`. It composes the existing
+Identity, Sessions, stored roles and D1 Store. The public catalog server at
+`/api/mcp` remains separate from protected article authoring.
+
+## Configuration and activation
+
+`worker/wrangler.jsonc` starts with `PEGMA_KNOWLEDGE_ENABLED=false` and
+`PEGMA_AGENT_CLIENTS_JSON=[]`. Disabled requests fail before opening Identity
+or D1. Empty client configuration disables the OAuth issuer and delegated
+transports, while the browser KB composition can still operate independently.
+
+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 and scopes,
+and delegates redirect and OAuth validation to Agent Access. Never infer a
+client registration or callback from a synthetic test. Record the actual
+requested client, installed version, provider mode, callback and observed flow.
+No dynamic registration endpoint or client secret is supplied.
+
+Wrangler owns these plain variables; a deploy replaces dashboard-added plain
+variables. Change configuration through review and regenerate Worker types.
+The two exact root discovery routes are also part of the checked-in Worker
+ingress. No database migration is added: all new collections use the existing
+generic Storage Core schema with `createSchemaIfMissing:false`.
+
+Before customer availability, retain actual existing-login/Admin consent,
+device-code and PKCE results for the requested clients, scoped API/MCP flows,
+revocation and authority failures, and real D1 evidence handling. Keep test
+collections closed while completing controlled staff acceptance. Source tests
+do not prove installed-client compatibility, production operation or a pilot.
+
+## Browser and agent boundaries
+
+- `/account/agents/device` accepts the human device code. The authorize shell
+ displays the exact pending request and requires an explicit decision.
+- `/api/agent-access/*` composes released device, authorization, token and
+ revocation endpoints plus browser-only consent and known-grant controls.
+- `/.well-known/oauth-authorization-server` describes the existing host issuer.
+ The protected resource metadata path is
+ `/.well-known/oauth-protected-resource/api/knowledge/mcp`.
+- `/api/knowledge/mcp` is the single canonical OAuth audience. The versioned
+ HTTP endpoint `/api/knowledge/v1` uses that same audience and dispatcher.
+- `/staff/knowledge` provides current-permission-gated governance, article,
+ report and publication controls. `/knowledge` uses only signed-in published
+ article and portal DTOs.
+
+Only a current stored Admin may link an agent. Each bearer use and refresh
+rechecks the active account and current role permissions. The initial scopes
+are exactly draft read, draft write and evidence submission. They confer no
+Admin/Support role, publication, review, collection or governance control, or
+private provenance access. Adding future scopes requires explicit configuration
+and fresh consent; it cannot silently widen an existing grant.
+
+Browser mutations retain the existing same-origin/session/CSRF boundary.
+Protected transports require a header bearer; a browser cookie is insufficient.
+Grant controls are owner-only and require a known returned grant ID. Browser
+logout revokes its session, not every separately approved agent grant; use the
+explicit grant revocation control for that family.
+
+## Staff-confirmed test reports
+
+An agent with evidence-submission scope submits a bounded report through
+`/api/knowledge/reports`. It receives only its own acknowledgement and opaque
+receipt/status, without staff identities or private report listings. Staff
+inspect the report and exact article/check/build bindings through their browser
+session. Confirmation is a human review decision, not accepted KB evidence.
+
+The confirmation binds the complete submission, intended submitting principal,
+exact draft, report generation and the released validation-requirements DTO.
+That DTO includes governance generation, policy, expected staging build and
+check freshness. A changed view requires fresh review. Staff do not need
+governance mutation authority to confirm a report.
+
+The agent then calls the actual released `submitEvidence` operation with its
+receipt. The host rechecks the confirmation and current reviewer authority;
+the KB checks trusted attester/runner, exact revision/hash/policy/applicability,
+build, result and execution freshness. Confirmation never resets execution
+time. Actual evidence revocation is a separate KB command. Article publication
+still requires staff approval of the complete current review snapshot.
+
+Reports and KB evidence remain private verification records. The initial host
+does not attach reports as private article source references or accept arbitrary
+source-reference writes. A future support-ticket integration must compose its
+actual source authorization and withdrawal verifier before enabling provenance
+writes. Draft changes must not withdraw an otherwise valid earlier publication.
+
+## Operational limits
+
+Distributed protocol, browser and protected-resource admission uses the host's
+released durable rate limiter. Report storage has explicit physical capacity
+bounds; exhaustion refuses new work. Configure collection governance, trusted
+reviewers/runners, retention/deletion procedures and operational monitoring
+before enabling a customer cohort. This source slice does not assert those
+operator settings have been applied or that retention maintenance has run.
+
+Disable the feature with its host switch if acceptance fails. Existing Identity,
+role administration, human Support Desk and public catalog routes continue
+through their original composition. No model/provider, automatic knowledge
+publication, GitHub export or customer notification is enabled by this slice.
diff --git a/package.json b/package.json
index 2a186c0..cadfb69 100644
--- a/package.json
+++ b/package.json
@@ -21,6 +21,7 @@
},
"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,6 +30,10 @@
"@pegma/authorization-storage": "0.4.0",
"@pegma/health": "^0.2.0",
"@pegma/identity": "0.1.2",
+ "@pegma/knowledge-base-application": "0.1.2",
+ "@pegma/knowledge-base-contracts": "0.1.2",
+ "@pegma/knowledge-base-core": "0.1.2",
+ "@pegma/knowledge-base-mcp": "0.1.2",
"@pegma/logger-cloudflare": "^0.1.1",
"@pegma/logger-datadog": "^0.1.1",
"@pegma/logger-tee": "^0.1.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 310204f..a53028e 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.2
+ version: 0.1.2
+ '@pegma/knowledge-base-contracts':
+ specifier: 0.1.2
+ version: 0.1.2
+ '@pegma/knowledge-base-core':
+ specifier: 0.1.2
+ version: 0.1.2
+ '@pegma/knowledge-base-mcp':
+ specifier: 0.1.2
+ version: 0.1.2
'@pegma/logger-cloudflare':
specifier: ^0.1.1
version: 0.1.1
@@ -79,7 +94,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 +413,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 +1036,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 +1103,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 +1151,22 @@ packages:
resolution: {integrity: sha512-r8AsVTnwCSBU2LZZjieW5FgIJ2TUWi5DlU9kp+4tuaWDFfl85EezkD6F5omAFjTnaFqCRN1T2d/KsHoESarB2A==}
engines: {node: '>=22'}
+ '@pegma/knowledge-base-application@0.1.2':
+ resolution: {integrity: sha512-PMhCUU02EuQLPN7zziVk+kt2kChzb0R0mwXVEXz75hH6QX/2CmrCHjW9zx5VZI5RJRLXjIlq8LVLZ5BNM75HuQ==}
+ engines: {node: '>=22'}
+
+ '@pegma/knowledge-base-contracts@0.1.2':
+ resolution: {integrity: sha512-CMgkGxEcqT6e6gtC5iMwK4Ma0tTa8y5H8ciZNDJ0mHDphJyqmDYmFfwmEagerUjAVT+KKa+T0PhI85iNyO3UYA==}
+ engines: {node: '>=22'}
+
+ '@pegma/knowledge-base-core@0.1.2':
+ resolution: {integrity: sha512-AvRr8twDKdYFLZssQeyjPAmFkUmbICQFTQJN86YubF97usDmGTj10EngPZwp2JquA5kQglrBbqWBhfT2wOJJ6A==}
+ engines: {node: '>=22'}
+
+ '@pegma/knowledge-base-mcp@0.1.2':
+ resolution: {integrity: sha512-n1WGKUjSXqjkZm1XJnZozjXVQK0zLpVuMu0RZKjFg6TyRAUnOGnWi0dqYJOyrakzQkbhQ1IkVSqXYckpYYa+4Q==}
+ engines: {node: '>=22'}
+
'@pegma/logger-cloudflare@0.1.1':
resolution: {integrity: sha512-ZAcj5ekxWvpBtx3yzNeNBiydYlYsUMPyKcQEbsbuyGktdlTObKrnUYnyZn/8KL5cvKSoLO5GnsFW2pxIeXaMZA==}
engines: {node: '>=22'}
@@ -1147,6 +1195,10 @@ packages:
resolution: {integrity: sha512-EV0Zq8KJX7r7ybI+eIHUCAhnd261bveZykMQVmmZibSDRJVcd2bOuYCPvPg4wax7GmrUrdtVFJYEJqHl4PkhwQ==}
engines: {node: '>=22'}
+ '@pegma/spine@0.1.2':
+ resolution: {integrity: sha512-jueFYJ3oJUacKdiERkEZ7R34xDMiEWXqn4MSA5bpTXzsXhWSap4EJUzKXtXnXuLPPjwJWLn5uoQe98kWQ6NS8A==}
+ engines: {node: '>=22'}
+
'@pegma/storage-cloudflare-d1@0.4.1':
resolution: {integrity: sha512-nVH+ppAWi3QwyEX8QVkPOLXNjtblO0jDnnGqCHpbZZzPvFQAVyd/1Bhxg8JdsuOD/UWGktJ26asAKzpNjRol0w==}
engines: {node: '>=22'}
@@ -3079,6 +3131,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 +3454,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
@@ -3828,7 +3885,7 @@ snapshots:
dependencies:
zod: 4.4.3
- '@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 +3905,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 +4056,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 +4115,35 @@ snapshots:
unicode-case-folding: 1.1.1
unorm: 1.6.0
+ '@pegma/knowledge-base-application@0.1.2':
+ dependencies:
+ '@pegma/audit': 0.2.0
+ '@pegma/authorization-core': 0.4.0
+ '@pegma/knowledge-base-contracts': 0.1.2
+ '@pegma/knowledge-base-core': 0.1.2
+ '@pegma/spine': 0.1.2
+ '@pegma/storage-core': 0.4.0
+
+ '@pegma/knowledge-base-contracts@0.1.2':
+ dependencies:
+ '@pegma/spine': 0.1.2
+
+ '@pegma/knowledge-base-core@0.1.2':
+ dependencies:
+ '@pegma/knowledge-base-contracts': 0.1.2
+
+ '@pegma/knowledge-base-mcp@0.1.2':
+ 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.2
+ '@pegma/knowledge-base-contracts': 0.1.2
+ '@pegma/knowledge-base-core': 0.1.2
+ zod: 4.6.7
+ transitivePeerDependencies:
+ - supports-color
+
'@pegma/logger-cloudflare@0.1.1':
dependencies:
'@pegma/spine': 0.1.1
@@ -4056,6 +4173,8 @@ snapshots:
'@pegma/spine@0.1.1': {}
+ '@pegma/spine@0.1.2': {}
+
'@pegma/storage-cloudflare-d1@0.4.1':
dependencies:
'@pegma/storage-core': 0.4.0
@@ -4360,12 +4479,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 +6124,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..ad4ddeb
--- /dev/null
+++ b/public/agent-access.js
@@ -0,0 +1,291 @@
+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;
+
+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 failure(error) {
+ if (error.status === 401) {
+ csrfToken = '';
+ approval = null;
+ currentGrant = null;
+ panel.hidden = true;
+ signedOut.hidden = false;
+ status('Sign in to continue.');
+ return;
+ }
+ if (error.status === 403) {
+ approval = null;
+ currentGrant = null;
+ panel.hidden = true;
+ }
+ status(
+ 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;
+ 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 <= 512 ? 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;
+ approval = null;
+ requestPanel.hidden = true;
+ status('Loading the request...');
+ const result = await api(`/api/agent-access/approval?${selector}`);
+ if (generation !== loadGeneration) return;
+ if (result.flow !== flow) throw new Error('invalid_request');
+ approval = result;
+ approvalUserCode = userCode;
+ grantInput.value = result.requestId;
+ document.querySelector('#agent-client').textContent = result.clientName;
+ details(document.querySelector('#agent-details'), [
+ ['Client ID', result.clientId],
+ ['Resource', result.resource],
+ ['Grant / 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}.`,
+ );
+}
+
+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;
+ 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 = '';
+ status(
+ result.approved
+ ? 'Approved. Return to your agent to finish connecting. Keep this grant ID for revocation.'
+ : 'Request denied.',
+ );
+ } catch (error) {
+ failure(error);
+ } finally {
+ setMutationPending(false);
+ }
+});
+
+deviceForm?.addEventListener('submit', async (event) => {
+ event.preventDefault();
+ if (mutationPending) return;
+ const code = userCodeInput.value.trim();
+ if (!code) return;
+ try {
+ await loadApproval(new URLSearchParams({ user_code: code }), code);
+ } catch (error) {
+ failure(error);
+ }
+});
+
+document
+ .querySelector('#agent-grant-lookup')
+ .addEventListener('submit', async (event) => {
+ event.preventDefault();
+ const id = grantInput.value.trim();
+ if (!id || mutationPending) return;
+ const generation = ++grantGeneration;
+ currentGrant = null;
+ grantPanel.hidden = true;
+ try {
+ const grant = await api(
+ `/api/agent-access/grants/${encodeURIComponent(id)}`,
+ );
+ if (generation !== grantGeneration) 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;
+ setMutationPending(mutationPending);
+ status('Grant loaded.');
+ } catch (error) {
+ failure(error);
+ }
+ });
+
+revokeButton.addEventListener('click', async () => {
+ if (mutationPending || currentGrant === null) return;
+ const id = currentGrant.grantId;
+ if (!window.confirm('Revoke this agent grant and its credentials?')) return;
+ setMutationPending(true);
+ try {
+ await api(`/api/agent-access/grants/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ });
+ currentGrant = null;
+ grantPanel.hidden = true;
+ status('Grant revoked.');
+ } catch (error) {
+ failure(error);
+ } 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) {
+ failure(error);
+ }
+}
+
+await start();
diff --git a/public/knowledge.js b/public/knowledge.js
new file mode 100644
index 0000000..22befd3
--- /dev/null
+++ b/public/knowledge.js
@@ -0,0 +1,169 @@
+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 === 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;
+ 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...');
+ 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.');
+}
+
+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).catch(failure);
+ });
+ 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/staff-knowledge.js b/public/staff-knowledge.js
new file mode 100644
index 0000000..7b56b5f
--- /dev/null
+++ b/public/staff-knowledge.js
@@ -0,0 +1,577 @@
+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 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;
+ 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.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;
+ 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-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-evidence-read', 'getEvidence'],
+ ['#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.');
+ }),
+ );
+}
+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.');
+ });
+});
+
+async function readReport(reportId) {
+ report = null;
+ select('#kb-report-panel').hidden = true;
+ select('#kb-report-detail').textContent = '';
+ report = await call('reportRead', { articleId: requireArticle(), reportId });
+ 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() });
+ 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)),
+ );
+ 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'],
+]) {
+ 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,
+ 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.'
+ : '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/src/layouts/Base.astro b/src/layouts/Base.astro
index 4d75e86..bd7dd6f 100644
--- a/src/layouts/Base.astro
+++ b/src/layouts/Base.astro
@@ -15,6 +15,7 @@ const nav = [
{ href: '/roadmap', label: 'Roadmap' },
{ href: '/examples', label: 'Examples' },
{ href: '/runbooks', label: 'Runbooks' },
+ { href: '/knowledge', label: 'Knowledge base' },
{ href: '/feedback', label: 'Feedback' },
{ href: '/account', label: 'Account' },
];
diff --git a/src/pages/account.astro b/src/pages/account.astro
index ccd8a7f..f407b6d 100644
--- a/src/pages/account.astro
+++ b/src/pages/account.astro
@@ -74,6 +74,14 @@ import Base from '../layouts/Base.astro';
Open feedback
+ Knowledge base
+ Browse product guides
+
+ Staff: review knowledge and test reports .
+ Administrators: link a local agent or
+ view or revoke a known agent grant .
+
+
Passkeys
+ Retry loading the approved grant controls
diff --git a/src/pages/staff/knowledge.astro b/src/pages/staff/knowledge.astro
index d22a57d..5c8138f 100644
--- a/src/pages/staff/knowledge.astro
+++ b/src/pages/staff/knowledge.astro
@@ -7,16 +7,17 @@ import Base from '../../layouts/Base.astro';
Staff · Knowledge Base
Knowledge administration
Configure collections, inspect drafts and test reports, and explicitly review publication. Current staff permissions are checked for every operation.
+ Knowledge access requires an explicitly assigned Knowledge role or Admin access. Support Desk access alone does not grant these permissions.
Checking staff access...
Sign in required Sign in with your staff account, then return here.
+
Test reports
+ Inspect report ledger capacity
+
+
+ Resetting starts a new report epoch and permanently invalidates earlier report receipts and commands. It does not revoke accepted Knowledge Base evidence or retire a publication. Use the separate controls above for those actions.
+ Reset this report ledger
+ Continue bounded report cleanup
+
List reports for this article
Report ID Inspect report and current bindings
@@ -86,7 +104,8 @@ import Base from '../../layouts/Base.astro';
Inspect the report, artifact hashes, result and execution time against the exact article revision, content hash, check, policy, applicability, staging build, and runner shown above. Confirm only the report you actually reviewed.
- Confirm reviewed report Reject this report
+ Human review is separate from Knowledge Base acceptance. If submission fails a trusted-attester prerequisite, a currently trusted reviewer must inspect and reassess the report; confirmation alone is not verified evidence.
+ Confirm reviewed report Reject this report Reassess this exact report
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
Admin
+ Knowledge
+
+ 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.
+
Assign
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
index 1d8902d..37624f8 100644
--- a/worker/src/agent-access-api.ts
+++ b/worker/src/agent-access-api.ts
@@ -63,6 +63,7 @@ export function createAgentAccessApi(
options,
request.method !== 'GET',
);
+ const principalId = context.access.principalId;
if (path === '/api/agent-access/state') {
if (url.search !== '') throw new ApiError(400, 'invalid_request');
response = json({
@@ -133,6 +134,16 @@ export function createAgentAccessApi(
};
response = json(await options.service.approve(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',
+ );
+ if (final.context.access.principalId !== principalId)
+ throw new ApiError(403, 'forbidden');
} catch (error) {
if (error instanceof ApiError)
response = json(
diff --git a/worker/src/agent-access-runtime.test.ts b/worker/src/agent-access-runtime.test.ts
index d864ea1..46d5dc2 100644
--- a/worker/src/agent-access-runtime.test.ts
+++ b/worker/src/agent-access-runtime.test.ts
@@ -20,7 +20,10 @@ import {
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,
@@ -56,7 +59,7 @@ async function fixture() {
const sessions = createSessionStore(store, { logger });
const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID);
const users = new Map();
- for (const id of ['admin', 'other-admin', 'staff', 'member'])
+ for (const id of ['admin', 'other-admin', 'staff', 'knowledge', 'member'])
users.set(id, {
principalId: id,
email: `${id}@example.test`,
@@ -103,12 +106,14 @@ async function fixture() {
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);
@@ -201,6 +206,25 @@ async function fixture() {
}
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();
@@ -243,6 +267,10 @@ describe('Agent Access host composition', () => {
(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,
@@ -255,9 +283,31 @@ describe('Agent Access host composition', () => {
await f.roleStore.listRoleAssignments('admin', APPLICATION_SCOPE),
).toEqual(history);
const staff = await createAgentPrincipalResolver(f.options)('staff');
- expect(staff?.permissions).toContain(KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION);
+ 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 () => {
diff --git a/worker/src/agent-access-runtime.ts b/worker/src/agent-access-runtime.ts
index 56d132e..ebe149a 100644
--- a/worker/src/agent-access-runtime.ts
+++ b/worker/src/agent-access-runtime.ts
@@ -15,8 +15,9 @@ import {
createDurableLimiter,
defineRateLimitPolicy,
type DurableRateLimiter,
-} from '@pegma/rate-limit';
+} 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,
@@ -133,6 +134,7 @@ 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;
@@ -187,7 +189,11 @@ export function createAgentAccessRuntime(
const limiters: DurableRateLimiter[] = [];
function admission(name: string, limit: number) {
const limiter = createDurableLimiter(
- defineRateLimitPolicy({ name, limit, windowMs: 5 * 60_000 }),
+ defineRateLimitPolicy({
+ name: knowledgeAdmissionPolicyName(name, limit),
+ limit,
+ windowMs: 5 * 60_000,
+ }),
options.store,
{ clock },
);
@@ -214,7 +220,10 @@ export function createAgentAccessRuntime(
revocation: admission('pegma.agent.revoke', 120),
};
const browserLimit = admission('pegma.agent.browser', 120);
- const resourceLimit = admission('pegma.agent.resource', 300);
+ const resourceLimit = admission(
+ 'pegma.agent.resource',
+ options.resourceLimitCount ?? 300,
+ );
const protocol = createAgentAccessHttp({
service,
configuration,
diff --git a/worker/src/agent-browser-freshness.test.ts b/worker/src/agent-browser-freshness.test.ts
new file mode 100644
index 0000000..6b3323e
--- /dev/null
+++ b/worker/src/agent-browser-freshness.test.ts
@@ -0,0 +1,444 @@
+import type { PublicClient } from '@pegma/agent-access';
+import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity';
+import { createRoleStore } from '@pegma/authorization-storage';
+import { createSessionStore } from '@pegma/sessions';
+import {
+ createMemoryStore,
+ type CollectionDefinition,
+ type CollectionStore,
+ type Store,
+} from '@pegma/storage-core';
+import { describe, expect, it } from 'vitest';
+import {
+ createAgentAccessRuntime,
+ AGENT_RESOURCE,
+} from './agent-access-runtime';
+import { isPlainObject } from './api-auth';
+import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api';
+import { createIdentityRuntime } from './identity-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'],
+};
+
+function barrier() {
+ let release = () => {};
+ const ready = new Promise((resolve) => {
+ release = resolve;
+ });
+ return { ready, release };
+}
+
+interface StoreHooks {
+ afterGrantRead: (() => Promise) | undefined;
+ afterGrantCommit: (() => Promise) | undefined;
+}
+
+/** Only delay actual AA 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);
+ if (definition.name !== 'agent-access.records.v1') return target;
+ return {
+ ...target,
+ async getVersioned(key) {
+ const value = await target.getVersioned(key);
+ await hooks.afterGrantRead?.();
+ return value;
+ },
+ async transact(partition, actions) {
+ const result = await target.transact(partition, actions);
+ if (result.committed) await hooks.afterGrantCommit?.();
+ 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,
+ };
+ 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 candidateRuntime = createAgentAccessRuntime({
+ store,
+ clock,
+ logger,
+ identity,
+ sessions,
+ roleStore,
+ clients: [client],
+ identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims,
+ });
+ if (candidateRuntime === null)
+ throw new Error('Expected the explicitly registered synthetic client.');
+ const runtime = candidateRuntime;
+ 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],
+ },
+ };
+ }
+ 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 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);
+ }
+ 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,
+ browser,
+ cookie,
+ prepared,
+ approved,
+ revokeAdmin,
+ restoreAdmin,
+ revokeSession,
+ 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',
+ });
+ });
+});
diff --git a/worker/src/index.ts b/worker/src/index.ts
index b2a4c08..973d922 100644
--- a/worker/src/index.ts
+++ b/worker/src/index.ts
@@ -40,6 +40,9 @@ import {
type SupportRuntimeEnv,
} from './support-desk';
import { runSupportMaintenance } from './support-maintenance';
+import { runKnowledgeMaintenance } from './knowledge-maintenance';
+import { createKnowledgeRetrievalMaintenance } from './knowledge-retrieval-maintenance';
+import { systemClock } from '@pegma/spine';
import {
MAIL_CRON,
MAIL_RECONCILE_CRON,
@@ -57,6 +60,12 @@ type AppEnv = Env &
SupportRuntimeEnv &
CatalogFetchEnv;
+function knowledgeRetrievalEnabled(environment: {
+ readonly PEGMA_KNOWLEDGE_ENABLED?: string;
+}): boolean {
+ return environment.PEGMA_KNOWLEDGE_ENABLED === 'true';
+}
+
function createSupportHandler(
env: AppEnv,
logger: ReturnType,
@@ -453,6 +462,44 @@ export default {
})(),
);
+ if (cleanup?.kind === 'knowledge')
+ ctx.waitUntil(
+ (async () => {
+ try {
+ await runKnowledgeMaintenance(
+ { store: createProductionStore(env), clock: systemClock },
+ logger,
+ { tasks: [cleanup.task] },
+ );
+ } catch (error) {
+ logger.log('error', 'knowledge.maintenance_unavailable', {
+ error: error instanceof Error ? error.name : 'unknown',
+ });
+ }
+ })(),
+ );
+
+ // Keep the existing limiter lane independent of Knowledge activation and
+ // failures. Only the new KB page requires the current Knowledge gate.
+ if (cleanup?.kind === 'knowledge' && knowledgeRetrievalEnabled(env))
+ ctx.waitUntil(
+ (async () => {
+ try {
+ if (!knowledgeRetrievalEnabled(env)) return;
+ await createKnowledgeRetrievalMaintenance({
+ store: createProductionStore(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..977326d
--- /dev/null
+++ b/worker/src/knowledge-agent-freshness.test.ts
@@ -0,0 +1,909 @@
+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,
+ 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 } 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() {
+ const pending = await agents.service.beginDeviceAuthorization({
+ clientId: client.clientId,
+ resource: AGENT_RESOURCE,
+ scopes: [...AGENT_KNOWLEDGE_PERMISSIONS],
+ });
+ 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: [...AGENT_KNOWLEDGE_PERMISSIONS],
+ }),
+ );
+ 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(
+ [...AGENT_KNOWLEDGE_PERMISSIONS].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) {
+ 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;
+ };
+ return { entered: entered.ready, finish: finish.release };
+ }
+ return {
+ knowledge,
+ agents,
+ access,
+ credential,
+ device,
+ createInput,
+ reportInput,
+ queueReport,
+ revoke,
+ block,
+ };
+}
+
+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(['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(['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
index 523ce37..07b0f92 100644
--- a/worker/src/knowledge-api.ts
+++ b/worker/src/knowledge-api.ts
@@ -16,6 +16,7 @@ import {
exactObject,
isPlainObject,
json,
+ optionalKeysObject,
readJson,
} from './api-auth';
import {
@@ -27,7 +28,10 @@ import {
type AgentAccessRuntime,
} from './agent-access-runtime';
import { KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION } from './support-access';
-import type { KnowledgeEvidenceService } from './knowledge-evidence';
+import {
+ KnowledgeLedgerError,
+ type KnowledgeEvidenceService,
+} from './knowledge-evidence';
import { IDENTITY_ISSUER } from './identity-api';
export interface KnowledgeApiOptions extends AgentBrowserOptions {
@@ -35,6 +39,8 @@ export interface KnowledgeApiOptions extends AgentBrowserOptions {
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 {
@@ -48,6 +54,83 @@ function response(value: unknown): Response {
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(
@@ -150,6 +233,10 @@ export function createKnowledgeApi(
'reportRead',
'confirmReport',
'rejectReport',
+ 'reassessReport',
+ 'reportLedger',
+ 'resetReports',
+ 'drainReports',
]);
return async (request) => {
const url = new URL(request.url);
@@ -190,35 +277,57 @@ export function createKnowledgeApi(
!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');
- return secured(
- response(
- await options.evidence.report(
- identity.access,
- await readJson(request),
- ),
- ),
- );
+ const input = await readJson(request);
+ 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 (
- [...url.searchParams.keys()].length !== 2 ||
+ keys.length !== 3 ||
url.searchParams.getAll('articleId').length !== 1 ||
- url.searchParams.getAll('reportId').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');
- return secured(
- response(
- await options.evidence.status(identity.access, {
- articleId: boundedString(
- url.searchParams.get('articleId'),
- 1,
- 200,
- ),
- reportId: boundedString(url.searchParams.get('reportId'), 1, 200),
- }),
- ),
- );
+ 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'))
@@ -297,7 +406,7 @@ export function createKnowledgeApi(
// unknown JSON without asserting it is an already validated SDK DTO.
const result: unknown = await Reflect.apply(method, app, [
access,
- envelope.input,
+ sdkInput(operation, envelope.input),
]);
await requireCurrentBrowserAccess(
request,
@@ -319,11 +428,21 @@ export function createKnowledgeApi(
? await options.evidence.list(access, envelope.input)
: operation === 'reportRead'
? await options.evidence.read(access, envelope.input)
- : await options.evidence.decide(
- access,
- envelope.input,
- operation === 'confirmReport' ? 'confirmed' : 'rejected',
- );
+ : 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 requireCurrentBrowserAccess(
request,
options,
@@ -349,8 +468,33 @@ export function createKnowledgeApi(
);
const result: unknown = await Reflect.apply(selected.method, app, [
access,
- envelope.input,
+ 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 requireCurrentBrowserAccess(
request,
options,
@@ -382,13 +526,11 @@ export function createKnowledgeApi(
} else if (error instanceof KnowledgeBaseError) {
status = error.code === 'invalid' ? 400 : 409;
code = 'knowledge_' + error.code;
- } else if (error instanceof TypeError || error instanceof SyntaxError) {
- status = 400;
- code = 'invalid_request';
}
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(
diff --git a/worker/src/knowledge-evidence.test.ts b/worker/src/knowledge-evidence.test.ts
index b1bed7f..90d5250 100644
--- a/worker/src/knowledge-evidence.test.ts
+++ b/worker/src/knowledge-evidence.test.ts
@@ -16,13 +16,24 @@ import {
validateValidationPolicy,
type EvidenceSubmission,
} from '@pegma/knowledge-base-core';
-import { createMemoryStore } from '@pegma/storage-core';
+import {
+ createMemoryStore,
+ type CollectionDefinition,
+ type CollectionStore,
+ type Store,
+} from '@pegma/storage-core';
import { describe, expect, it } from 'vitest';
import {
createKnowledgeEvidenceService,
- knowledgeEvidenceRecords,
+ KnowledgeLedgerError,
+ type KnowledgeEvidenceOptions,
} from './knowledge-evidence';
-import { PEGMA_ACCESS_POLICY } from './support-access';
+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(
@@ -30,13 +41,17 @@ const owner = resolveAccess(
PEGMA_ACCESS_POLICY,
);
const reviewer = resolveAccess(
- { principalId: 'reviewer', roles: ['Support'] },
+ { 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: [
@@ -45,17 +60,38 @@ const restricted = (access: AccessContext): AccessContext => ({
],
});
+interface StoredReportRow {
+ readonly articleId: string;
+ readonly id: string;
+ readonly payload: string;
+}
+
async function fixture(options: { portal?: boolean } = {}) {
- const store = createMemoryStore();
+ 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 evidence = createKnowledgeEvidenceService({
+ const evidenceOptions: KnowledgeEvidenceOptions = {
store,
clock,
resolvePrincipal: async (id) => principals.get(id) ?? null,
@@ -73,7 +109,10 @@ async function fixture(options: { portal?: boolean } = {}) {
: {}),
};
},
- });
+ };
+ const freshEvidence = (overrides: Partial = {}) =>
+ createKnowledgeEvidenceService({ ...evidenceOptions, ...overrides });
+ const evidence = freshEvidence();
app = createKnowledgeBaseApplication({
store,
clock,
@@ -196,6 +235,7 @@ async function fixture(options: { portal?: boolean } = {}) {
const input = {
commandId: 'report-1',
articleId: 'guide',
+ ledgerEpoch: 1,
evidence: submission,
report: {
summary: 'Staging test passed',
@@ -206,11 +246,13 @@ async function fixture(options: { portal?: boolean } = {}) {
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,
@@ -231,6 +273,13 @@ async function fixture(options: { portal?: boolean } = {}) {
});
return {
store,
+ reportRows,
+ reportDefinition: () => {
+ if (reportDefinition === undefined)
+ throw new Error('Missing the actual report collection definition.');
+ return reportDefinition;
+ },
+ freshEvidence,
app,
evidence,
clock,
@@ -250,10 +299,196 @@ async function fixture(options: { portal?: boolean } = {}) {
}
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(Object.keys(fresh.agentReports).sort()).toEqual([
+ 'ledger',
+ 'report',
+ 'status',
+ ]);
+ 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',
@@ -262,6 +497,16 @@ describe('stored staff report confirmation', () => {
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 });
@@ -272,7 +517,7 @@ describe('stored staff report confirmation', () => {
const actual = (await f.app.getEvidence(owner, { articleId: 'guide' }))
.evidence[0];
expect(actual?.attestation).toEqual({
- id: f.ack.reportId,
+ id: f.ack.receipt,
verifiedBy: reviewer.principalId,
verifiedAt: at,
});
@@ -285,7 +530,7 @@ describe('stored staff report confirmation', () => {
it('binds the full report, actor and submission with exact immutable command replay', async () => {
const f = await fixture();
- const rows = f.store.collection(knowledgeEvidenceRecords);
+ 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);
@@ -314,12 +559,14 @@ describe('stored staff report confirmation', () => {
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 });
@@ -370,6 +617,7 @@ describe('stored staff report confirmation', () => {
await expect(
g.evidence.read(reviewer, {
articleId: 'guide',
+ ledgerEpoch: g.ack.ledgerEpoch,
reportId: g.ack.reportId,
}),
).rejects.toMatchObject({ status: 403 });
@@ -388,6 +636,7 @@ describe('stored staff report confirmation', () => {
});
const read = await f.evidence.read(reviewer, {
articleId: 'guide',
+ ledgerEpoch: wrong.ledgerEpoch,
reportId: wrong.reportId,
});
await f.evidence.decide(
@@ -395,6 +644,7 @@ describe('stored staff report confirmation', () => {
{
...f.confirm,
commandId: 'review-wrong-runner',
+ ledgerEpoch: wrong.ledgerEpoch,
reportId: wrong.reportId,
expectedReportGeneration: read.expectedReportGeneration,
reviewBindingHash: read.reviewBindingHash,
@@ -473,6 +723,7 @@ describe('stored staff report confirmation', () => {
});
const view = await f.evidence.read(reviewer, {
articleId: 'guide',
+ ledgerEpoch: report.ledgerEpoch,
reportId: report.reportId,
});
await f.evidence.decide(
@@ -480,6 +731,7 @@ describe('stored staff report confirmation', () => {
{
commandId: 'confirm-' + checkId,
articleId: 'guide',
+ ledgerEpoch: report.ledgerEpoch,
reportId: report.reportId,
expectedReportGeneration: view.expectedReportGeneration,
reviewBindingHash: view.reviewBindingHash,
@@ -520,6 +772,21 @@ describe('stored staff report confirmation', () => {
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' }),
@@ -554,7 +821,7 @@ describe('stored staff report confirmation', () => {
...f.input,
commandId: 'report-' + (index + 1),
});
- const rows = f.store.collection(knowledgeEvidenceRecords);
+ const rows = f.reportRows();
const before = await rows.list('guide');
await expect(
f.evidence.report(f.agent, { ...f.input, commandId: 'report-over-cap' }),
@@ -564,4 +831,216 @@ describe('stored staff report confirmation', () => {
(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
index fe1a56c..50471b7 100644
--- a/worker/src/knowledge-evidence.ts
+++ b/worker/src/knowledge-evidence.ts
@@ -1,244 +1,196 @@
-import { hasPermission, type AccessContext } from '@pegma/authorization-core';
-import { auditEvent } from '@pegma/audit';
-import type { EvidenceSubmission } from '@pegma/knowledge-base-core';
+import type { AccessContext } from '@pegma/authorization-core';
import {
- knowledgePermissions,
- type Applicability,
- type ArticleRevision,
- type Clock,
- type PrincipalId,
-} from '@pegma/knowledge-base-contracts';
-import type {
- DraftArticleDto,
- EvidenceDto,
- EvidenceVerifier,
- ValidationRequirementsDto,
+ createKnowledgeEvidenceReports,
+ KnowledgeEvidenceReportsError,
+ KnowledgeEvidenceReportsUnavailableError,
+ type KnowledgeEvidenceReports,
+ type KnowledgeEvidenceReportsOptions,
} from '@pegma/knowledge-base-application';
-import { defineCollection, type Store } from '@pegma/storage-core';
-import {
- ApiError,
- boundedString,
- exactObject,
- isPlainObject,
- optionalKeysObject,
-} from './api-auth';
+import { ApiError, isPlainObject } from './api-auth';
import { KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION } from './support-access';
-const MAX_REPORTS = 16;
-const MAX_ROWS = 160;
-const MAX_RECORD_BYTES = 60_000;
+export type {
+ KnowledgeEvidenceContext,
+ KnowledgeReportAcknowledgement,
+ KnowledgeReportLedgerState,
+ KnowledgeReportSummary,
+ KnowledgeReportView,
+ KnowledgeTestReport,
+} from '@pegma/knowledge-base-application';
-/** Only host confirmation data lives here; articles remain in the released KB. */
-interface LedgerRow {
- readonly articleId: string;
- readonly id: string;
- readonly payload: string;
-}
-export const knowledgeEvidenceRecords = defineCollection({
- name: 'pegma-dev.knowledge-evidence.v1',
- key: (row) => ({ partition: row.articleId, id: row.id }),
- codec: {
- encode: (row) => ({
- articleId: row.articleId,
- id: row.id,
- payload: row.payload,
- }),
- decode: (row) => ({
- articleId: scalar(row.articleId),
- id: scalar(row.id),
- payload: boundedString(row.payload, 1, MAX_RECORD_BYTES, {
- allowMultiline: true,
- }),
- }),
- },
-});
+export type KnowledgeEvidenceOptions = Omit<
+ KnowledgeEvidenceReportsOptions,
+ 'collectionName' | 'storageLayout' | 'confirmationPermission'
+>;
-export interface KnowledgeTestReport {
- readonly summary: string;
- readonly details: string;
-}
-export interface KnowledgeReportAcknowledgement {
- readonly reportId: string;
- readonly receipt: string;
- readonly reportGeneration: number;
-}
-export interface KnowledgeReportSummary {
- readonly reportId: string;
- readonly articleId: string;
- readonly reportGeneration: number;
- readonly status: 'pending' | 'confirmed' | 'rejected';
- readonly submittedBy: PrincipalId;
- readonly submittedAt: string;
- readonly summary: string;
-}
-interface Confirmation {
- readonly reviewerId: PrincipalId;
- readonly confirmedAt: string;
-}
-interface ReportRecord extends Omit {
- readonly evidence: EvidenceSubmission;
- readonly report: KnowledgeTestReport;
- readonly submissionHash: string;
- readonly reportHash: string;
- readonly articleHash: string;
- readonly governanceHash: string;
- readonly confirmation: Confirmation | null;
-}
-export interface KnowledgeEvidenceContext {
- readonly draft: DraftArticleDto;
- readonly requirements: ValidationRequirementsDto;
- readonly evidence?: EvidenceDto;
-}
-export interface KnowledgeReportView extends KnowledgeReportSummary {
- readonly evidence: EvidenceSubmission;
- readonly report: KnowledgeTestReport;
- readonly reportHash: string;
- readonly submissionHash: string;
- readonly governanceHash: string;
- readonly draft: DraftArticleDto;
- readonly requirements: ValidationRequirementsDto;
- readonly reviewBindingHash: string;
- readonly expectedReportGeneration: number;
- readonly confirmation: Confirmation | null;
-}
-export interface KnowledgeEvidenceOptions {
- readonly store: Store;
- readonly clock: Clock;
- readonly resolvePrincipal: (id: PrincipalId) => Promise;
- /** A read-only, current view of actual released KB records. */
- readonly readContext: (
- access: AccessContext,
- articleId: string,
- ) => Promise;
-}
-export interface KnowledgeEvidenceService {
- readonly verifier: EvidenceVerifier;
- report(
- access: AccessContext,
- input: unknown,
- ): Promise;
- status(
- access: AccessContext,
- input: unknown,
- ): Promise<
- KnowledgeReportAcknowledgement & {
- readonly status: KnowledgeReportSummary['status'];
- }
+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'
>;
- list(
- access: AccessContext,
- input: unknown,
- ): Promise<{ readonly reports: readonly KnowledgeReportSummary[] }>;
- read(access: AccessContext, input: unknown): Promise;
- decide(
- access: AccessContext,
- input: unknown,
- decision: 'confirmed' | 'rejected',
- ): Promise;
-}
+};
-function scalar(value: unknown, maximum = 200): string {
- return boundedString(value, 1, maximum);
-}
-function positive(value: unknown, minimum = 1): number {
- if (
- typeof value !== 'number' ||
- !Number.isSafeInteger(value) ||
- value < minimum
- )
- throw new ApiError(400, 'invalid_request');
- return value;
-}
-function timestamp(value: unknown): string {
- const text = scalar(value, 32);
- if (
- !Number.isFinite(Date.parse(text)) ||
- new Date(text).toISOString() !== text
- )
- throw new ApiError(400, 'invalid_request');
- return text;
+/** 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.');
+ }
}
-function hash(value: unknown): string {
- const text = scalar(value, 64);
- if (!/^[a-f0-9]{64}$/u.test(text)) throw new ApiError(400, 'invalid_request');
- return text;
+
+/** Carry only an already-controlled host refusal through the shared context port. */
+class HostContextError extends KnowledgeEvidenceReportsError {
+ constructor(readonly failure: ApiError) {
+ super('report_changed');
+ }
}
-function array(value: unknown, maximum: number): readonly unknown[] {
- if (!Array.isArray(value) || value.length > maximum)
- throw new ApiError(400, 'invalid_request');
- return value;
+
+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');
}
-function applicability(value: unknown): Applicability {
- const object = optionalKeysObject(
- value,
- ['productId', 'productVersion'],
- ['buildId', 'locale'],
- );
- return {
- productId: scalar(object.productId),
- productVersion: scalar(object.productVersion),
- ...(object.buildId === undefined
- ? {}
- : { buildId: scalar(object.buildId) }),
- ...(object.locale === undefined ? {} : { locale: scalar(object.locale) }),
- };
+
+async function hostOperation(operation: () => Promise): Promise {
+ try {
+ return await operation();
+ } catch (error) {
+ throw hostError(error);
+ }
}
-export function parseKnowledgeEvidence(value: unknown): EvidenceSubmission {
- const input = exactObject(value, [
- 'id',
- 'articleId',
- 'articleRevision',
- 'contentHash',
- 'validationPolicy',
- 'checkId',
- 'testKind',
- 'applicability',
- 'stagingBuildId',
- 'steps',
- 'result',
- 'executedAt',
- 'runnerId',
- 'artifacts',
- ]);
- const policy = exactObject(input.validationPolicy, ['id', 'version']);
- if (
- input.result !== 'passed' &&
- input.result !== 'failed' &&
- input.result !== 'inconclusive'
- )
- throw new ApiError(400, 'invalid_request');
- const steps = array(input.steps, 16).map((step) => scalar(step, 1000));
- if (steps.length === 0) throw new ApiError(400, 'invalid_request');
- return {
- id: scalar(input.id),
- articleId: scalar(input.articleId),
- articleRevision: positive(input.articleRevision),
- contentHash: hash(input.contentHash),
- validationPolicy: {
- id: scalar(policy.id),
- version: positive(policy.version),
- },
- checkId: scalar(input.checkId),
- testKind: scalar(input.testKind, 64),
- applicability: applicability(input.applicability),
- stagingBuildId: scalar(input.stagingBuildId),
- steps,
- result: input.result,
- executedAt: timestamp(input.executedAt),
- runnerId: scalar(input.runnerId),
- artifacts: array(input.artifacts, 8).map((item) => {
- const artifact = exactObject(item, ['id', 'hash']);
- return { id: scalar(artifact.id), hash: hash(artifact.hash) };
+
+/** 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,
}),
- };
-}
-function parseReport(value: unknown): KnowledgeTestReport {
- const report = exactObject(value, ['summary', 'details']);
- return {
- summary: scalar(report.summary, 1000),
- details: boundedString(report.details, 1, 16_000, { allowMultiline: true }),
- };
+ 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))
@@ -259,6 +211,8 @@ function canonical(value: unknown): string {
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',
@@ -268,539 +222,3 @@ export async function knowledgeDigest(value: unknown): Promise {
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('');
}
-function row(articleId: string, id: string, value: unknown): LedgerRow {
- const payload = canonical(value);
- if (new TextEncoder().encode(payload).byteLength > MAX_RECORD_BYTES)
- throw new ApiError(413, 'report_too_large');
- return { articleId, id, payload };
-}
-function decodeReport(payload: string): ReportRecord {
- const value: unknown = JSON.parse(payload);
- const item = exactObject(value, [
- 'reportId',
- 'articleId',
- 'reportGeneration',
- 'status',
- 'submittedBy',
- 'submittedAt',
- 'evidence',
- 'report',
- 'submissionHash',
- 'reportHash',
- 'articleHash',
- 'governanceHash',
- 'confirmation',
- ]);
- if (
- item.status !== 'pending' &&
- item.status !== 'confirmed' &&
- item.status !== 'rejected'
- )
- throw new TypeError('Invalid evidence ledger.');
- let confirmation: Confirmation | null = null;
- if (item.confirmation !== null) {
- const proof = exactObject(item.confirmation, ['reviewerId', 'confirmedAt']);
- confirmation = {
- reviewerId: scalar(proof.reviewerId),
- confirmedAt: timestamp(proof.confirmedAt),
- };
- }
- if ((item.status === 'confirmed') !== (confirmation !== null))
- throw new TypeError('Invalid evidence ledger.');
- return {
- reportId: scalar(item.reportId),
- articleId: scalar(item.articleId),
- reportGeneration: positive(item.reportGeneration),
- status: item.status,
- submittedBy: scalar(item.submittedBy),
- submittedAt: timestamp(item.submittedAt),
- evidence: parseKnowledgeEvidence(item.evidence),
- report: parseReport(item.report),
- submissionHash: hash(item.submissionHash),
- reportHash: hash(item.reportHash),
- articleHash: hash(item.articleHash),
- governanceHash: hash(item.governanceHash),
- confirmation,
- };
-}
-function summary(report: ReportRecord): KnowledgeReportSummary {
- return {
- reportId: report.reportId,
- articleId: report.articleId,
- reportGeneration: report.reportGeneration,
- status: report.status,
- submittedBy: report.submittedBy,
- submittedAt: report.submittedAt,
- summary: report.report.summary,
- };
-}
-function acknowledgement(report: ReportRecord): KnowledgeReportAcknowledgement {
- return {
- reportId: report.reportId,
- receipt: report.reportId,
- reportGeneration: report.reportGeneration,
- };
-}
-
-/** Stored human review is the trust root; a bearer token alone never confirms. */
-export function createKnowledgeEvidenceService(
- options: KnowledgeEvidenceOptions,
-): KnowledgeEvidenceService {
- const records = options.store.collection(knowledgeEvidenceRecords);
- async function current(
- access: AccessContext,
- permission: string,
- ): Promise {
- const resolved = await options.resolvePrincipal(access.principalId);
- if (
- resolved === null ||
- resolved.principalId !== access.principalId ||
- !hasPermission(access, permission) ||
- !hasPermission(resolved, permission) ||
- access.permissions.some((grant) => !hasPermission(resolved, grant))
- )
- throw new ApiError(403, 'forbidden');
- return access;
- }
- async function staff(access: AccessContext): Promise {
- const fresh = await current(access, KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION);
- for (const permission of [
- knowledgePermissions.draftRead,
- knowledgePermissions.evidenceRead,
- ])
- if (!hasPermission(fresh, permission))
- throw new ApiError(403, 'forbidden');
- return fresh;
- }
- async function load(
- articleId: string,
- reportId: string,
- ): Promise {
- const stored = await records.get({
- partition: articleId,
- id: 'report:' + reportId,
- });
- if (stored === null) throw new ApiError(404, 'report_not_found');
- const report = decodeReport(stored.payload);
- if (report.articleId !== articleId || report.reportId !== reportId)
- throw new TypeError('Invalid evidence ledger identity.');
- return report;
- }
- async function contextHashes(
- context: KnowledgeEvidenceContext,
- ): Promise<{ articleHash: string; governanceHash: string }> {
- return {
- articleHash: await knowledgeDigest(context.draft.revision),
- governanceHash: await knowledgeDigest(context.requirements),
- };
- }
- async function valid(
- report: ReportRecord,
- article: ArticleRevision,
- context: KnowledgeEvidenceContext,
- reviewer: AccessContext,
- at: string,
- ): Promise {
- if (!hasPermission(reviewer, KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION))
- return false;
- if (
- report.reportHash !==
- (await knowledgeDigest({
- reportId: report.reportId,
- articleId: report.articleId,
- evidence: report.evidence,
- report: report.report,
- submittedBy: report.submittedBy,
- articleHash: report.articleHash,
- governanceHash: report.governanceHash,
- })) ||
- report.articleHash !== (await knowledgeDigest(article)) ||
- report.governanceHash !== (await contextHashes(context)).governanceHash ||
- report.submissionHash !== (await knowledgeDigest(report.evidence)) ||
- context.evidence?.revokedEvidence.some(
- (item) =>
- item.id === report.evidence.id &&
- item.articleRevision === report.evidence.articleRevision,
- )
- )
- return false;
- const submission = report.evidence;
- const requirement = context.requirements.checks.find(
- (item) =>
- item.id === submission.checkId && item.testKind === submission.testKind,
- );
- const executed = Date.parse(submission.executedAt);
- const now = Date.parse(at);
- return (
- submission.articleId === article.articleId &&
- submission.articleRevision === article.number &&
- submission.contentHash === article.contentHash &&
- (await knowledgeDigest(submission.applicability)) ===
- (await knowledgeDigest(article.applicability)) &&
- (await knowledgeDigest(submission.validationPolicy)) ===
- (await knowledgeDigest(context.requirements.validationPolicy)) &&
- (await knowledgeDigest(article.validationPolicy)) ===
- (await knowledgeDigest(context.requirements.validationPolicy)) &&
- submission.stagingBuildId ===
- context.requirements.expectedStagingBuildId &&
- (article.applicability.buildId === undefined ||
- submission.stagingBuildId === article.applicability.buildId) &&
- requirement !== undefined &&
- executed >= Date.parse(article.createdAt) &&
- executed <= now &&
- now - executed <= requirement.maxAgeMilliseconds &&
- (report.confirmation === null ||
- (Date.parse(report.confirmation.confirmedAt) >= executed &&
- Date.parse(report.confirmation.confirmedAt) <= now))
- );
- }
- async function replay(
- articleId: string,
- commandId: string,
- fingerprint: string,
- ): Promise {
- const stored = await records.get({
- partition: articleId,
- id: 'command:' + (await knowledgeDigest(commandId)),
- });
- if (stored === null) return null;
- const receipt = exactObject(JSON.parse(stored.payload), [
- 'fingerprint',
- 'result',
- ]);
- if (receipt.fingerprint !== fingerprint)
- throw new ApiError(409, 'command_conflict');
- const result = exactObject(receipt.result, [
- 'reportId',
- 'receipt',
- 'reportGeneration',
- ]);
- return {
- reportId: scalar(result.reportId),
- receipt: scalar(result.receipt),
- reportGeneration: positive(result.reportGeneration),
- };
- }
- async function write(
- access: AccessContext,
- commandId: string,
- fingerprint: string,
- report: ReportRecord,
- previousVersion?: string,
- ): Promise {
- const head = await records.getVersioned({
- partition: report.articleId,
- id: 'head',
- });
- const state =
- head === null
- ? { reports: 0, rows: 1 }
- : exactObject(JSON.parse(head.value.payload), ['reports', 'rows']);
- const reports =
- positive(state.reports, 0) + (previousVersion === undefined ? 1 : 0);
- const rows =
- positive(state.rows, 1) + (previousVersion === undefined ? 3 : 2);
- if (reports > MAX_REPORTS || rows > MAX_ROWS)
- throw new ApiError(409, 'report_capacity');
- const commandKey = 'command:' + (await knowledgeDigest(commandId));
- const result = acknowledgement(report);
- const event = auditEvent({
- id: commandKey,
- occurredAt: options.clock.now(),
- actor: { kind: 'principal', principalId: access.principalId },
- action: 'knowledge.report.' + report.status,
- subject: report.articleId,
- details: {
- reportId: report.reportId,
- reportHash: report.reportHash,
- generation: report.reportGeneration,
- },
- });
- const fresh = await current(
- access,
- previousVersion === undefined
- ? knowledgePermissions.evidenceSubmit
- : KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION,
- );
- if (fresh.principalId !== access.principalId)
- throw new ApiError(403, 'forbidden');
- const headRow = row(report.articleId, 'head', { reports, rows });
- const reportRow = row(
- report.articleId,
- 'report:' + report.reportId,
- report,
- );
- const outcome = await records.transact(report.articleId, [
- head === null
- ? { action: 'insert', value: headRow }
- : { action: 'putIfUnchanged', value: headRow, version: head.version },
- previousVersion === undefined
- ? { action: 'insert', value: reportRow }
- : {
- action: 'putIfUnchanged',
- value: reportRow,
- version: previousVersion,
- },
- {
- action: 'insert',
- value: row(report.articleId, commandKey, { fingerprint, result }),
- },
- {
- action: 'insert',
- value: row(report.articleId, 'audit:' + commandKey, event),
- },
- ]);
- if (!outcome.committed) {
- const accepted = await replay(report.articleId, commandId, fingerprint);
- if (accepted !== null) return accepted;
- throw new ApiError(409, 'report_changed');
- }
- return result;
- }
- async function verified(
- report: ReportRecord,
- article: ArticleRevision,
- ): Promise {
- if (report.status !== 'confirmed' || report.confirmation === null)
- return false;
- const reviewer = await options.resolvePrincipal(
- report.confirmation.reviewerId,
- );
- if (
- reviewer === null ||
- !hasPermission(reviewer, KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION)
- )
- return false;
- const context = await options.readContext(reviewer, report.articleId);
- if (!(await valid(report, article, context, reviewer, options.clock.now())))
- return false;
- const latest = await load(report.articleId, report.reportId);
- await staff(reviewer);
- return (await knowledgeDigest(latest)) === (await knowledgeDigest(report));
- }
- const verifier: EvidenceVerifier = {
- async verify(request) {
- try {
- const report = await load(
- request.article.articleId,
- scalar(request.receipt),
- );
- if (
- request.access.principalId !== report.submittedBy ||
- (await knowledgeDigest(request.submission)) !==
- report.submissionHash ||
- !(await verified(report, request.article)) ||
- report.confirmation === null
- )
- return null;
- const reviewer = await options.resolvePrincipal(
- report.confirmation.reviewerId,
- );
- if (reviewer === null) return null;
- if (
- !request.configuration.trustedAttesterIds.includes(
- report.confirmation.reviewerId,
- )
- )
- return null;
- const context = await options.readContext(reviewer, report.articleId);
- if (
- request.configuration.expectedStagingBuildId !==
- context.requirements.expectedStagingBuildId ||
- (await knowledgeDigest(request.configuration.validationPolicy)) !==
- (await knowledgeDigest(context.requirements.validationPolicy))
- )
- return null;
- if (
- !hasPermission(
- await current(request.access, knowledgePermissions.evidenceSubmit),
- knowledgePermissions.evidenceSubmit,
- )
- )
- return null;
- await staff(reviewer);
- return {
- id: report.reportId,
- verifiedBy: report.confirmation.reviewerId,
- verifiedAt: report.confirmation.confirmedAt,
- };
- } catch {
- return null;
- }
- },
- };
- return Object.freeze({
- verifier,
- async report(access, value) {
- access = await current(access, knowledgePermissions.evidenceSubmit);
- const input = exactObject(value, [
- 'commandId',
- 'articleId',
- 'evidence',
- 'report',
- ]);
- const commandId = scalar(input.commandId);
- const articleId = scalar(input.articleId);
- const evidence = parseKnowledgeEvidence(input.evidence);
- const report = parseReport(input.report);
- if (evidence.articleId !== articleId)
- throw new ApiError(400, 'invalid_request');
- const fingerprint = await knowledgeDigest({
- actor: access.principalId,
- operation: 'report',
- commandId,
- articleId,
- evidence,
- report,
- });
- const accepted = await replay(articleId, commandId, fingerprint);
- if (accepted !== null) {
- await current(access, knowledgePermissions.evidenceSubmit);
- return accepted;
- }
- const context = await options.readContext(access, articleId);
- const hashes = await contextHashes(context);
- const reportId = crypto.randomUUID();
- const stored: ReportRecord = {
- reportId,
- articleId,
- reportGeneration: 1,
- status: 'pending',
- submittedBy: access.principalId,
- submittedAt: timestamp(options.clock.now()),
- evidence,
- report,
- submissionHash: await knowledgeDigest(evidence),
- reportHash: await knowledgeDigest({
- reportId,
- articleId,
- evidence,
- report,
- submittedBy: access.principalId,
- ...hashes,
- }),
- ...hashes,
- confirmation: null,
- };
- return write(access, commandId, fingerprint, stored);
- },
- async status(access, value) {
- access = await current(access, knowledgePermissions.evidenceSubmit);
- const input = exactObject(value, ['articleId', 'reportId']);
- const report = await load(
- scalar(input.articleId),
- scalar(input.reportId),
- );
- if (report.submittedBy !== access.principalId)
- throw new ApiError(404, 'report_not_found');
- await current(access, knowledgePermissions.evidenceSubmit);
- return { ...acknowledgement(report), status: report.status };
- },
- async list(access, value) {
- access = await staff(access);
- const input = exactObject(value, ['articleId']);
- const articleId = scalar(input.articleId);
- const rows = await records.list(articleId);
- if (rows.length > MAX_ROWS) throw new ApiError(409, 'report_capacity');
- const reports = rows
- .filter((item) => item.id.startsWith('report:'))
- .map((item) => summary(decodeReport(item.payload)));
- await staff(access);
- return { reports };
- },
- async read(access, value) {
- access = await staff(access);
- const input = exactObject(value, ['articleId', 'reportId']);
- const report = await load(
- scalar(input.articleId),
- scalar(input.reportId),
- );
- const context = await options.readContext(access, report.articleId);
- const reviewBindingHash = await knowledgeDigest({ report, context });
- await staff(access);
- return {
- ...summary(report),
- evidence: report.evidence,
- report: report.report,
- draft: context.draft,
- reportHash: report.reportHash,
- submissionHash: report.submissionHash,
- governanceHash: report.governanceHash,
- requirements: context.requirements,
- reviewBindingHash,
- expectedReportGeneration: report.reportGeneration,
- confirmation: report.confirmation,
- };
- },
- async decide(access, value, decision) {
- access = await staff(access);
- const input = exactObject(value, [
- 'commandId',
- 'articleId',
- 'reportId',
- 'expectedReportGeneration',
- 'reviewBindingHash',
- ]);
- const commandId = scalar(input.commandId);
- const articleId = scalar(input.articleId);
- const reportId = scalar(input.reportId);
- const expected = positive(input.expectedReportGeneration);
- const binding = hash(input.reviewBindingHash);
- const fingerprint = await knowledgeDigest({
- actor: access.principalId,
- operation: decision,
- commandId,
- articleId,
- reportId,
- expected,
- binding,
- });
- const accepted = await replay(articleId, commandId, fingerprint);
- if (accepted !== null) {
- await staff(access);
- return accepted;
- }
- const saved = await records.getVersioned({
- partition: articleId,
- id: 'report:' + reportId,
- });
- if (saved === null) throw new ApiError(404, 'report_not_found');
- const report = decodeReport(saved.value.payload);
- if (report.status !== 'pending' || report.reportGeneration !== expected)
- throw new ApiError(409, 'report_changed');
- const context = await options.readContext(access, articleId);
- if ((await knowledgeDigest({ report, context })) !== binding)
- throw new ApiError(409, 'report_changed');
- const at = timestamp(options.clock.now());
- if (
- decision === 'confirmed' &&
- !(await valid(report, context.draft.revision, context, access, at))
- )
- throw new ApiError(409, 'report_not_verifiable');
- const latestContext = await options.readContext(
- await staff(access),
- articleId,
- );
- if (
- (await knowledgeDigest(context)) !==
- (await knowledgeDigest(latestContext))
- )
- throw new ApiError(409, 'report_changed');
- return write(
- access,
- commandId,
- fingerprint,
- {
- ...report,
- reportGeneration: report.reportGeneration + 1,
- status: decision,
- confirmation:
- decision === 'confirmed'
- ? { reviewerId: access.principalId, confirmedAt: at }
- : null,
- },
- saved.version,
- );
- },
- } satisfies KnowledgeEvidenceService);
-}
diff --git a/worker/src/knowledge-host.ts b/worker/src/knowledge-host.ts
index 906dd50..53c5598 100644
--- a/worker/src/knowledge-host.ts
+++ b/worker/src/knowledge-host.ts
@@ -8,15 +8,20 @@ import {
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_ENABLED'
+ | 'PEGMA_AGENT_CLIENTS_JSON'
+ | 'PEGMA_KNOWLEDGE_BROWSER_LIMIT'
+ | 'PEGMA_AGENT_RESOURCE_LIMIT'
>
]?: string;
};
@@ -68,10 +73,23 @@ export async function handleKnowledgeRequest(
roleStore: createRoleStore(identity.store, AUTHORIZATION_APPLICATION_ID),
logger,
};
- const agentAccess = createAgentAccessRuntime({
- ...options,
- clients: readAgentClients(env.PEGMA_AGENT_CLIENTS_JSON),
- });
+ 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)
@@ -88,9 +106,15 @@ export async function handleKnowledgeRequest(
);
}
return (
- (await createKnowledgeRuntime({ ...options, agentAccess }).handle(
- request,
- )) ??
+ (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' },
diff --git a/worker/src/knowledge-integration-scenarios.ts b/worker/src/knowledge-integration-scenarios.ts
new file mode 100644
index 0000000..56ccb07
--- /dev/null
+++ b/worker/src/knowledge-integration-scenarios.ts
@@ -0,0 +1,2358 @@
+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 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.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_maintenance.'))
+ 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');
+ // Failed bounded keyed repair must not lie about the durable publish.
+ expect(f.logger.log).toHaveBeenCalledWith(
+ 'warn',
+ 'knowledge.retrieval_maintenance.failed',
+ { stage: 'keyed' },
+ );
+ 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,
+ });
+ async function converge(indexed: boolean) {
+ for (let tick = 0; tick < 128; tick++) {
+ const before = observed.scans.length;
+ // A new composition each tick proves the cursor survives restart.
+ await maintenance().runPage();
+ expect(observed.scans.length - before).toBe(1);
+ expect(observed.scans.at(-1)?.limit).toBe(10);
+ 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
index ad209e9..ee29586 100644
--- a/worker/src/knowledge-integration.d1.test.ts
+++ b/worker/src/knowledge-integration.d1.test.ts
@@ -1,646 +1,8 @@
import { env } from 'cloudflare:workers';
import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1';
-import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity';
-import { createRoleStore } from '@pegma/authorization-storage';
-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 } from '@pegma/knowledge-base-contracts';
-import {
- KnowledgeBaseAuthorizationError,
- 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 { Store } from '@pegma/storage-core';
-import { type IsoTimestamp, type Logger, type PrincipalId } from '@pegma/spine';
import { beforeAll, beforeEach, 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,
- SUPPORT_ROLE,
-} from './support-access';
-import { createKnowledgeRuntime } from './knowledge-runtime';
-import type { KnowledgeReportView } from './knowledge-evidence';
-
-const owner = 'integration-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) {
- let now = Date.parse('2026-11-08T12:00:00.000Z');
- const clock = { now: () => new Date(now).toISOString() as IsoTimestamp };
- const logger: Logger = { log: vi.fn() };
- const sessions = createSessionStore(store, { logger, clock });
- const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID);
- const users = new Map(
- [owner, 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.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 = 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(reviewer);
- 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): Promise {
- const response = await staff(operation, input);
- expect(response.status, operation).toBe(200);
- return (await response.json()) as T;
- }
- 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 }),
- }),
- );
- }
- 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 staffValue<
- CommandResult
- >('createCollection', {
- commandId: 'create-integration-collection',
- correlationId: 'integration',
- expectedGeneration: 0,
- collectionId: 'integration-guides',
- name: 'Synthetic integration guides',
- });
- await staffValue('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 staffValue('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 staffValue(
- 'previewCollectionPolicy',
- {
- collectionId: 'integration-guides',
- uses: {
- portal: {
- enabled: true,
- audience: {
- kind: 'permission',
- permission: 'knowledge.article.read',
- },
- },
- bot: { enabled: false },
- },
- },
- );
- await staffValue('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 reviewerAuth = await session(reviewer);
- const memberAuth = await session(member);
- return {
- store,
- clock,
- logger,
- sessions,
- roleStore,
- users,
- identity,
- agents,
- knowledge,
- ownerAuth,
- reviewerAuth,
- memberAuth,
- agentRequest,
- knowledgeRequest,
- staff,
- staffValue,
- agent,
- mcp,
- configure,
- 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;
-}
-
-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,
-) {
- 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 submitted = await f.knowledgeRequest(
- new Request('https://pegma.dev/api/knowledge/reports', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${token}`,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- commandId: `submit-synthetic-report:${check.id}`,
- articleId,
- 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.',
- },
- }),
- }),
- );
- expect(submitted.status).toBe(200);
- const report = (await submitted.json()) as {
- reportId: string;
- receipt: string;
- reportGeneration: number;
- };
- const viewed = await f.staffValue('reportRead', {
- articleId,
- 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}`,
- articleId,
- reportId: report.reportId,
- expectedReportGeneration: viewed.expectedReportGeneration,
- reviewBindingHash: viewed.reviewBindingHash,
- };
- return { article, evidence, report, viewed, confirm };
-}
-
-async function confirmedReport(
- f: Awaited>,
- token: string,
- articleId: string,
- check: EvidenceCheck = workflowCheck,
-) {
- const prepared = await submitReport(f, token, articleId, check);
- const confirmation = await f.staff('confirmReport', prepared.confirm);
- expect(confirmation.status).toBe(200);
- const reviewed = await f.staffValue('reportRead', {
- articleId,
- reportId: prepared.report.reportId,
- });
- expect(reviewed.status).toBe('confirmed');
- return prepared;
-}
+import { handleKnowledgeRequest } from './knowledge-host';
+import { registerKnowledgeIntegrationScenarios } from './knowledge-integration-scenarios';
declare global {
namespace Cloudflare {
@@ -667,479 +29,83 @@ beforeEach(async () => {
await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run();
await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run();
});
-function d1Fixture() {
- return integrationFixture(
+registerKnowledgeIntegrationScenarios({
+ name: 'released Agent Access and KB host integration over actual D1',
+ createStore: () =>
createCloudflareD1Store({
database: env.IDENTITY_DB,
createSchemaIfMissing: false,
}),
- );
-}
-
-describe('released Agent Access and KB host integration over actual D1', () => {
- it.each(['device', 'pkce'] as const)(
- 'persists real %s consent and HTTP/MCP draft changes through the public package adapters',
- async (flow) => {
- const f = await d1Fixture();
- const { token } = await f[flow]();
- const created = await createAgentDraft(f, token.access_token);
- const updated = await f.mcp(token.access_token, 'tools/call', {
- name: knowledgeAgentToolNames.updateDraft,
- arguments: {
- commandId: 'd1-mcp-update',
- correlationId: 'integration',
- expectedGeneration: created.generation,
- articleId: created.id,
- collectionId: 'integration-guides',
- draft: draft({ title: 'D1 synthetic walkthrough' }),
- },
- });
- expect(updated.status).toBe(200);
- const rpc = (await updated.json()) as {
- result: { isError: boolean; content: { text: string }[] };
- };
- expect(rpc.result.isError).toBe(false);
- expect(JSON.parse(rpc.result.content[0]!.text)).toMatchObject({
- result: { value: { articleRevision: 2 } },
- });
- const read = await f.agent(token.access_token, 'getDraft', {
- articleId: created.id,
- });
- expect(read.status).toBe(200);
- const current = (await read.json()) as { result: DraftArticleDto };
- expect(current.result.revision).toMatchObject({
- number: 2,
- title: 'D1 synthetic walkthrough',
- createdBy: owner,
- });
- expect(current.result.hasPublication).toBe(false);
- const delegated = await f.agents.service.authenticate({
- token: token.access_token,
- resource,
- });
- expect(delegated.access.roles).toEqual([]);
- expect(delegated.access.permissions).toEqual(scopes);
- await expect(
- f.knowledge.application.getProvenance(delegated.access, {
- articleId: created.id,
- }),
- ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError);
- 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);
- },
- );
+});
- it('honors durable grant revocation and stored Admin demotion on the next protected request', async () => {
- const f = await d1Fixture();
- 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',
+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)),
),
- );
- 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: reviewer },
- revokedAtEpochMs: Date.parse(f.clock.now()) + 1,
- auditEventId: 'd1-demote-agent-owner',
- });
- 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]);
- });
- it('requires independent staff report confirmation before scoped evidence submission and human publication', async () => {
- const f = await d1Fixture();
- 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,
+ IDENTITY_EMAIL_FROM: 'identity@example.test',
+ IDENTITY_EMAIL_ENABLED: 'false',
+ PEGMA_KNOWLEDGE_ENABLED: 'true',
+ PEGMA_AGENT_CLIENTS_JSON: `{"clientId":"${registrationCanary}"`,
};
- 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,
+ 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',
),
- ).toBe(true);
- const submitted = await f.staffValue>(
- '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',
+ 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',
}),
- ).rejects.toBeInstanceOf(KnowledgeBaseAuthorizationError);
- const published = await f.staffValue>(
- '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 },
+ 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' }),
}),
- );
- 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([
- 'revision',
- 'build',
- 'runner',
- 'result',
- 'submitting principal',
- ] as const)(
- 'rejects a confirmed receipt whose %s binding changes',
- async (changed) => {
- const f = await d1Fixture();
- 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.reviewerAuth)).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,
+ 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(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 d1Fixture();
- 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,
- reportId: prepared.report.reportId,
- });
- expect(current.status).toBe('pending');
- expect(current.confirmation).toBeNull();
- expect(current.reviewBindingHash).not.toBe(
- prepared.viewed.reviewBindingHash,
+ }
+ 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,
);
- });
-
- it('refuses a previously confirmed report after its current staff reviewer loses authority', async () => {
- const f = await d1Fixture();
- 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(
- `${ADMIN_ROLE}-${reviewer}`,
+ expect(JSON.stringify(logger.log.mock.calls)).not.toContain(
+ configuration.IDENTITY_EMAIL_CODE_SECRET_BASE64,
);
- await f.roleStore.revokeRoleAssignmentWithAudit({
- assignmentId: `${ADMIN_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' },
- });
});
});
diff --git a/worker/src/knowledge-integration.test.ts b/worker/src/knowledge-integration.test.ts
index ac171bb..1b85029 100644
--- a/worker/src/knowledge-integration.test.ts
+++ b/worker/src/knowledge-integration.test.ts
@@ -1,1367 +1,7 @@
-import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity';
-import { createRoleStore } from '@pegma/authorization-storage';
-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 } from '@pegma/knowledge-base-contracts';
-import {
- KnowledgeBaseAuthorizationError,
- 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 { createMemoryStore, type 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,
- SUPPORT_ROLE,
-} from './support-access';
-import { createSupportApi } from './support-api';
-import { createSupportRuntime } from './support-desk';
-import { createKnowledgeRuntime } from './knowledge-runtime';
-import type { KnowledgeReportView } from './knowledge-evidence';
+import { createMemoryStore } from '@pegma/storage-core';
+import { registerKnowledgeIntegrationScenarios } from './knowledge-integration-scenarios';
-const owner = 'integration-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 = createMemoryStore()) {
- let now = Date.parse('2026-11-08T12:00:00.000Z');
- const clock = { now: () => new Date(now).toISOString() as IsoTimestamp };
- const logger: Logger = { log: vi.fn() };
- const sessions = createSessionStore(store, { logger, clock });
- const roleStore = createRoleStore(store, AUTHORIZATION_APPLICATION_ID);
- const users = new Map(
- [owner, 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.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 = 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(reviewer);
- 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): Promise {
- const response = await staff(operation, input);
- expect(response.status, operation).toBe(200);
- return (await response.json()) as T;
- }
- 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 }),
- }),
- );
- }
- 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 staffValue<
- CommandResult
- >('createCollection', {
- commandId: 'create-integration-collection',
- correlationId: 'integration',
- expectedGeneration: 0,
- collectionId: 'integration-guides',
- name: 'Synthetic integration guides',
- });
- await staffValue('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 staffValue('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 staffValue(
- 'previewCollectionPolicy',
- {
- collectionId: 'integration-guides',
- uses: {
- portal: {
- enabled: true,
- audience: {
- kind: 'permission',
- permission: 'knowledge.article.read',
- },
- },
- bot: { enabled: false },
- },
- },
- );
- await staffValue('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 reviewerAuth = await session(reviewer);
- const memberAuth = await session(member);
- return {
- store,
- clock,
- logger,
- sessions,
- roleStore,
- users,
- identity,
- agents,
- knowledge,
- ownerAuth,
- reviewerAuth,
- memberAuth,
- agentRequest,
- knowledgeRequest,
- staff,
- staffValue,
- agent,
- mcp,
- configure,
- 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;
-}
-
-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,
-) {
- 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 submitted = await f.knowledgeRequest(
- new Request('https://pegma.dev/api/knowledge/reports', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${token}`,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- commandId: `submit-synthetic-report:${check.id}`,
- articleId,
- 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.',
- },
- }),
- }),
- );
- expect(submitted.status).toBe(200);
- const report = (await submitted.json()) as {
- reportId: string;
- receipt: string;
- reportGeneration: number;
- };
- const viewed = await f.staffValue('reportRead', {
- articleId,
- 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}`,
- articleId,
- reportId: report.reportId,
- expectedReportGeneration: viewed.expectedReportGeneration,
- reviewBindingHash: viewed.reviewBindingHash,
- };
- return { article, evidence, report, viewed, confirm };
-}
-
-async function confirmedReport(
- f: Awaited>,
- token: string,
- articleId: string,
- check: EvidenceCheck = workflowCheck,
-) {
- const prepared = await submitReport(f, token, articleId, check);
- const confirmation = await f.staff('confirmReport', prepared.confirm);
- expect(confirmation.status).toBe(200);
- const reviewed = await f.staffValue('reportRead', {
- articleId,
- reportId: prepared.report.reportId,
- });
- expect(reviewed.status).toBe('confirmed');
- return prepared;
-}
-
-describe('released Agent Access and KB host integration over Memory Store', () => {
- it('completes existing-session device consent with exactly three restricted scopes', async () => {
- const f = await integrationFixture();
- 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 integrationFixture();
- 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 integrationFixture();
- 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);
- 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 integrationFixture();
- 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>(
- '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>(
- '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([
- 'revision',
- 'build',
- 'runner',
- 'result',
- 'submitting principal',
- ] as const)(
- 'rejects a confirmed receipt whose %s binding changes',
- async (changed) => {
- const f = await integrationFixture();
- 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.reviewerAuth)).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 integrationFixture();
- 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,
- 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 integrationFixture();
- 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(
- `${ADMIN_ROLE}-${reviewer}`,
- );
- await f.roleStore.revokeRoleAssignmentWithAudit({
- assignmentId: `${ADMIN_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 integrationFixture();
- 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);
- 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: reviewer },
- 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 integrationFixture();
- 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: reviewer },
- 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('rejects excessive consent scopes and a different protected-resource audience', async () => {
- const f = await integrationFixture();
- 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('preserves existing customer and stored Support-role request flows alongside agent linking', async () => {
- const f = await integrationFixture();
- 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]);
- });
+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..8f3d85f
--- /dev/null
+++ b/worker/src/knowledge-maintenance.test.ts
@@ -0,0 +1,395 @@
+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';
+
+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 ten across cold invocations and increments completed cycles', async () => {
+ const f = fixture();
+ await seed(f.backing, 25);
+ 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: 10 },
+ { limit: 10, cursor: first?.cursor },
+ { limit: 10, cursor: second?.cursor },
+ { limit: 10 },
+ ]);
+ expect(f.logger.log).not.toHaveBeenCalled();
+ });
+
+ 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: 10 }]);
+ 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).not.toHaveBeenCalled();
+ });
+
+ 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, 25);
+ await runKnowledgeMaintenance(
+ { store: f.backing, clock: f.clock },
+ f.logger,
+ );
+ const before = await f.checkpoint();
+ 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: 10, 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();
+ 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);
+ 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).toHaveBeenCalledExactlyOnceWith(
+ 'error',
+ 'knowledge.maintenance_failed',
+ { task: 'rate_limits', error: 'Error' },
+ );
+ });
+
+ 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).not.toHaveBeenCalled();
+ });
+
+ it('rejects a stale earlier cycle after newer invocations return the cursor to null', async () => {
+ const f = fixture();
+ await seed(f.backing, 25);
+ 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: 10 }]);
+ expect(f.logger.log).not.toHaveBeenCalled();
+ });
+
+ 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: 10 }]);
+ expect(await f.checkpoint()).toEqual({
+ ...KEY,
+ cursor: null,
+ generation: 1,
+ });
+ });
+});
diff --git a/worker/src/knowledge-maintenance.ts b/worker/src/knowledge-maintenance.ts
new file mode 100644
index 0000000..8b283c6
--- /dev/null
+++ b/worker/src/knowledge-maintenance.ts
@@ -0,0 +1,125 @@
+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;
+const PAGE_LIMIT = 10;
+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 };
+}
+
+/**
+ * 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,
+ },
+ };
+ });
+ } catch (error) {
+ logger.log('error', 'knowledge.maintenance_failed', {
+ task: 'rate_limits',
+ error: error instanceof Error ? error.name : 'unknown',
+ });
+ }
+}
diff --git a/worker/src/knowledge-retrieval-maintenance.test.ts b/worker/src/knowledge-retrieval-maintenance.test.ts
new file mode 100644
index 0000000..f0ef5fa
--- /dev/null
+++ b/worker/src/knowledge-retrieval-maintenance.test.ts
@@ -0,0 +1,438 @@
+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);
+ await expect(
+ maintenance.repairArticleBestEffort(''),
+ ).resolves.toBeUndefined();
+ expect(logger.log).toHaveBeenCalledWith(
+ 'warn',
+ 'knowledge.retrieval_maintenance.failed',
+ { stage: 'keyed' },
+ );
+ });
+
+ 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();
+ await maintenance.repairArticleBestEffort('synthetic-guide');
+ 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 ten-row page 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 < 32; 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(10);
+ const saved = await checkpoint(backing);
+ expect(saved?.generation).toBe(tick + 1);
+ if (saved?.cursor === null) {
+ 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: 10,
+ 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);
+ await runner(seen.store).maintenance.runPage();
+ expect(seen.calls.projectionCommits).toBeGreaterThan(0);
+ expect(await checkpoint(backing)).toBeNull();
+ hooks.failCheckpoint = false;
+ for (let tick = 0; tick < 8; tick++) {
+ await runner(seen.store).maintenance.runPage();
+ if ((await checkpoint(backing))?.cursor === null) 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..9e503ea
--- /dev/null
+++ b/worker/src/knowledge-retrieval-maintenance.ts
@@ -0,0 +1,229 @@
+import { resolveAccess } from '@pegma/authorization-core';
+import {
+ createKnowledgeBaseApplication,
+ type KnowledgeBaseApplication,
+ 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;
+ /** Only the actual request application, including its trusted source ports. */
+ readonly application?: Pick;
+}
+
+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 = 10;
+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): 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 < 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)
+ );
+}
+
+/** No scheduler, identity, email, grant, or report-factory construction here. */
+export function createKnowledgeRetrievalMaintenance(
+ options: KnowledgeRetrievalMaintenanceOptions,
+) {
+ function diagnostic(
+ level: 'info' | 'warn' | 'error',
+ message: string,
+ fields: Readonly>,
+ ): void {
+ try {
+ options.logger.log(level, message, fields);
+ } catch {
+ // A generic injected Logger must not turn best-effort repair into an
+ // article acknowledgement failure or invalidate a committed checkpoint.
+ }
+ }
+
+ function current() {
+ 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;
+ }
+
+ return Object.freeze({
+ /** One physical scan page; projection reads/writes have their own SDK bounds. */
+ async runPage(): Promise {
+ let stage = 'configuration';
+ try {
+ if (!current()) return;
+ const collection = options.store.collection(checkpoints);
+ stage = 'checkpoint_read';
+ const prior = bookmark(await collection.get(KEY));
+ if (!current()) return;
+ if (prior.generation === Number.MAX_SAFE_INTEGER)
+ throw new RangeError('Knowledge retrieval generation is exhausted.');
+ // Current phase 01 has no private-source authoring. Retained nonempty
+ // source snapshots fail closed without their real eligibility ports.
+ const application = createKnowledgeBaseApplication({
+ store: options.store,
+ clock: options.clock,
+ });
+ stage = 'repair';
+ const result = await application.repairRetrievalPage(access, {
+ limit: PAGE_LIMIT,
+ ...(prior.cursor === null ? {} : { cursor: prior.cursor }),
+ });
+ if (!validPage(result))
+ throw new TypeError('Invalid knowledge retrieval page.');
+ if (!current()) return;
+ stage = 'checkpoint_write';
+ const saved = await collection.update(KEY, (value) => {
+ const actual = bookmark(value);
+ if (
+ !current() ||
+ actual.generation !== prior.generation ||
+ actual.cursor !== prior.cursor
+ )
+ return { action: 'keep' };
+ // Even null -> null advances, fencing delayed completion of a cycle.
+ return {
+ action: 'write',
+ value: {
+ ...KEY,
+ cursor: result.nextCursor,
+ generation: prior.generation + 1,
+ },
+ };
+ });
+ diagnostic('info', 'knowledge.retrieval_maintenance.page', {
+ physicalRows: result.physicalRows,
+ candidates: result.candidates,
+ repaired: result.repaired,
+ pending: result.pending,
+ blocked: result.blocked,
+ cursorSaved: saved.written,
+ });
+ } catch {
+ // A partial repair may have committed; the prior cursor is retried.
+ diagnostic('error', 'knowledge.retrieval_maintenance.failed', {
+ stage,
+ });
+ }
+ },
+
+ /** Never changes a committed article command's acknowledgement on failure. */
+ async repairArticleBestEffort(articleId: string): Promise {
+ try {
+ if (!current()) return;
+ const application =
+ options.application ??
+ createKnowledgeBaseApplication({
+ store: options.store,
+ clock: options.clock,
+ });
+ const result = await application.repairArticleIndex(access, {
+ articleId,
+ });
+ if (!current()) return;
+ diagnostic('info', 'knowledge.retrieval_maintenance.keyed', {
+ status: result.status,
+ indexed: result.indexed,
+ });
+ } catch {
+ diagnostic('warn', 'knowledge.retrieval_maintenance.failed', {
+ stage: 'keyed',
+ });
+ }
+ },
+ });
+}
diff --git a/worker/src/knowledge-runtime.test.ts b/worker/src/knowledge-runtime.test.ts
index f03f648..52e6635 100644
--- a/worker/src/knowledge-runtime.test.ts
+++ b/worker/src/knowledge-runtime.test.ts
@@ -1,7 +1,13 @@
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 } from '@pegma/storage-core';
+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';
@@ -10,16 +16,38 @@ 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() {
- const store = createMemoryStore();
+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', 'support', 'customer'].map((principalId) => [
+ ['admin', 'knowledge', 'support', 'customer'].map((principalId) => [
principalId,
{
principalId,
@@ -48,6 +76,7 @@ async function fixture() {
};
for (const [id, role] of [
['admin', 'Admin'],
+ ['knowledge', KNOWLEDGE_ROLE],
['support', 'Support'],
]) {
if (id === undefined || role === undefined)
@@ -90,6 +119,7 @@ async function fixture() {
logger,
identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims,
agentAccess: null,
+ ...options,
});
async function request(
path: string,
@@ -129,7 +159,16 @@ async function fixture() {
principal,
body: { operation, input },
});
- return { store, runtime, request, command, roleStore, users };
+ return {
+ store,
+ reportRows,
+ runtime,
+ request,
+ command,
+ roleStore,
+ users,
+ logger,
+ };
}
describe('Knowledge Base browser composition', () => {
@@ -176,13 +215,13 @@ describe('Knowledge Base browser composition', () => {
).toBeNull();
});
- it('gives Support actual review controls without collection/governance mutation', async () => {
+ 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: 'support',
+ principal: 'knowledge',
});
expect(await state.json()).toMatchObject({
- attesterId: 'support',
+ attesterId: 'knowledge',
permissions: {
collectionManage: false,
validationManage: false,
@@ -199,21 +238,26 @@ describe('Knowledge Base browser composition', () => {
name: 'Guides',
});
expect(
- (await f.command('getCollection', { collectionId: 'guides' }, 'support'))
- .status,
+ (
+ await f.command(
+ 'getCollection',
+ { collectionId: 'guides' },
+ 'knowledge',
+ )
+ ).status,
).toBe(200);
expect(
(
await f.command(
'getGovernanceConfiguration',
{ collectionId: 'guides' },
- 'support',
+ 'knowledge',
)
).status,
).toBe(403);
- expect((await f.command('putValidationPolicy', {}, 'support')).status).toBe(
- 403,
- );
+ expect(
+ (await f.command('putValidationPolicy', {}, 'knowledge')).status,
+ ).toBe(403);
expect(
(
await f.command(
@@ -225,7 +269,7 @@ describe('Knowledge Base browser composition', () => {
collectionId: 'other',
name: 'Other',
},
- 'support',
+ 'knowledge',
)
).status,
).toBe(403);
@@ -234,6 +278,35 @@ describe('Knowledge Base browser composition', () => {
).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(
@@ -345,19 +418,22 @@ describe('Knowledge Base browser composition', () => {
it('honors actual stored role and identity revocation on the next request', async () => {
const f = await fixture();
- const assignment = await f.roleStore.getRoleAssignment('role-support');
+ const assignment = await f.roleStore.getRoleAssignment('role-knowledge');
if (assignment === null) throw new Error('Missing actual role assignment.');
await f.roleStore.revokeRoleAssignmentWithAudit({
- assignmentId: 'role-support',
+ 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-support',
+ auditEventId: 'revoke-knowledge',
});
expect(
- (await f.request('/api/staff/knowledge/state', { principal: 'support' }))
- .status,
+ (
+ 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.');
@@ -371,4 +447,49 @@ describe('Knowledge Base browser composition', () => {
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
index 0868a6d..3afead6 100644
--- a/worker/src/knowledge-runtime.ts
+++ b/worker/src/knowledge-runtime.ts
@@ -1,6 +1,9 @@
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 {
@@ -12,7 +15,11 @@ import {
createKnowledgeAgentHttp,
createKnowledgeAgentMcp,
} from '@pegma/knowledge-base-mcp';
-import { createDurableLimiter, defineRateLimitPolicy } from '@pegma/rate-limit';
+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 {
@@ -32,16 +39,21 @@ import {
} from './knowledge-evidence';
import { createKnowledgeApi } from './knowledge-api';
import { IDENTITY_ISSUER } from './identity-api';
+import { knowledgeAdmissionPolicyName } from './knowledge-admission';
+import { createKnowledgeRetrievalMaintenance } from './knowledge-retrieval-maintenance';
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;
}
@@ -49,10 +61,20 @@ export interface KnowledgeRuntime {
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),
async readContext(access, articleId) {
const draft = await application.getDraft(access, { articleId });
@@ -63,25 +85,14 @@ export function createKnowledgeRuntime(
const accepted = hasPermission(access, knowledgePermissions.evidenceRead)
? await application.getEvidence(access, { articleId })
: undefined;
- // These are authoritative reads, not a copied governance cache. An
- // observed draft/governance change aborts the host report operation.
+ // The final draft generation fences the requirements/evidence reads.
+ // The SDK separately rechecks governance around evidence acceptance.
const latestDraft = await application.getDraft(access, { articleId });
- const latestRequirements = await application.getValidationRequirements(
- access,
- {
- collectionId: latestDraft.revision.collectionId,
- kind: latestDraft.revision.kind,
- },
- );
- if (
- draft.generation !== latestDraft.generation ||
- (await knowledgeDigest(requirements)) !==
- (await knowledgeDigest(latestRequirements))
- )
+ if (draft.generation !== latestDraft.generation)
throw new ApiError(409, 'report_target_changed');
return {
draft: latestDraft,
- requirements: latestRequirements,
+ requirements,
...(accepted === undefined ? {} : { evidence: accepted }),
};
},
@@ -93,8 +104,11 @@ export function createKnowledgeRuntime(
});
const browserLimit = createDurableLimiter(
defineRateLimitPolicy({
- name: 'pegma.knowledge.browser',
- limit: 120,
+ name: knowledgeAdmissionPolicyName(
+ 'pegma.knowledge.browser',
+ browserLimitCount,
+ ),
+ limit: browserLimitCount,
windowMs: 5 * 60_000,
}),
options.store,
@@ -104,6 +118,13 @@ export function createKnowledgeRuntime(
...options,
application,
evidence,
+ repairArticle: createKnowledgeRetrievalMaintenance({
+ store: options.store,
+ clock: options.clock,
+ logger: options.logger,
+ isEnabled: options.isEnabled ?? (() => true),
+ application,
+ }).repairArticleBestEffort,
async limitBrowser(request) {
const key = await knowledgeDigest(
(request.headers.get('CF-Connecting-IP') ?? 'unavailable').slice(
@@ -123,49 +144,204 @@ export function createKnowledgeRuntime(
},
});
const agents = options.agentAccess;
- const dispatcher = createKnowledgeAgentDispatcher({
- application,
- resource: AGENT_RESOURCE,
- });
- const transportOptions = {
- dispatcher,
- resource: AGENT_RESOURCE,
- protectedResourceMetadataUrl: AGENT_RESOURCE_METADATA_URL,
- allowedOrigins: [IDENTITY_ISSUER],
- authenticate: (request: Request) =>
- agents === null
- ? json({ error: 'agent_access_not_configured' }, { status: 503 })
- : agents.protectedResource.authenticate(request),
- limit: (request: Request) =>
- agents === null ? { allowed: false } : agents.resourceLimit(request),
- };
- const http = createKnowledgeAgentHttp({
- ...transportOptions,
- apiUrl: AGENT_API_URL,
- });
- const mcp = createKnowledgeAgentMcp({
- ...transportOptions,
- mcpUrl: AGENT_RESOURCE,
- });
return Object.freeze({
application,
evidence,
+ limiters: Object.freeze([browserLimit]),
async handle(request: Request) {
const path = new URL(request.url).pathname;
if (
- agents === null &&
- (path === new URL(AGENT_API_URL).pathname ||
- path === new URL(AGENT_RESOURCE).pathname)
+ 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' } },
);
- return (
- (await http.handle(request)) ??
- (await mcp.handle(request)) ??
- (await browser(request))
- );
+ 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 {
+ 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),
+ ),
+ ),
+ });
+ 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;
+ }
+ // The real dispatcher continues to own all five schemas and attenuation;
+ // these request-bound methods only refresh authority before the real KB call.
+ const currentApplication: KnowledgeBaseApplication = {
+ ...application,
+ async getDraft(access, input) {
+ return invoke(access, [knowledgePermissions.draftRead], (fresh) =>
+ application.getDraft(fresh, input),
+ );
+ },
+ async createDraft(access, input) {
+ return invoke(access, [knowledgePermissions.draftWrite], (fresh) =>
+ application.createDraft(fresh, input),
+ );
+ },
+ async updateDraft(access, input) {
+ return invoke(access, [knowledgePermissions.draftWrite], (fresh) =>
+ application.updateDraft(fresh, input),
+ );
+ },
+ async getValidationRequirements(access, input) {
+ return invoke(
+ access,
+ [
+ knowledgePermissions.draftWrite,
+ knowledgePermissions.evidenceSubmit,
+ ],
+ (fresh) => application.getValidationRequirements(fresh, input),
+ );
+ },
+ async submitEvidence(access, input) {
+ return invoke(
+ access,
+ [knowledgePermissions.evidenceSubmit],
+ (fresh) => application.submitEvidence(fresh, input),
+ );
+ },
+ };
+ const currentReports: KnowledgeEvidenceService['agentReports'] = {
+ async report(access, input) {
+ return invoke(
+ access,
+ [
+ knowledgePermissions.draftRead,
+ knowledgePermissions.evidenceSubmit,
+ ],
+ (fresh) => evidence.agentReports.report(fresh, input),
+ true,
+ );
+ },
+ async ledger(access, input) {
+ return invoke(
+ access,
+ [
+ knowledgePermissions.draftRead,
+ knowledgePermissions.evidenceSubmit,
+ ],
+ (fresh) => evidence.agentReports.ledger(fresh, input),
+ true,
+ );
+ },
+ async status(access, input) {
+ return invoke(
+ access,
+ [
+ knowledgePermissions.draftRead,
+ knowledgePermissions.evidenceSubmit,
+ ],
+ (fresh) => evidence.agentReports.status(fresh, input),
+ true,
+ );
+ },
+ };
+ const dispatcher = createKnowledgeAgentDispatcher({
+ application: currentApplication,
+ resource: AGENT_RESOURCE,
+ reports: currentReports,
+ });
+ 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..2a832e3 100644
--- a/worker/src/maintenance-cursors.d1.test.ts
+++ b/worker/src/maintenance-cursors.d1.test.ts
@@ -197,7 +197,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 +205,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..97acb37 100644
--- a/worker/src/maintenance-schedule.test.ts
+++ b/worker/src/maintenance-schedule.test.ts
@@ -11,10 +11,21 @@ import {
runReleaseReconciliation,
} from './release-reconciliation';
import { runIdentityMaintenance } from './identity-maintenance';
+import { runKnowledgeMaintenance } from './knowledge-maintenance';
+import { createKnowledgeRetrievalMaintenance } from './knowledge-retrieval-maintenance';
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 () => {}),
+ repairArticleBestEffort: vi.fn(async () => {}),
+ })),
+}));
vi.mock('./support-maintenance', () => ({ runSupportMaintenance: vi.fn() }));
vi.mock('./logger', () => ({ createAppLogger: () => ({ log: vi.fn() }) }));
vi.mock('./identity-runtime', () => ({
@@ -45,11 +56,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);
@@ -62,6 +93,19 @@ async function scheduled(cron: string, time: number) {
await Promise.all(pending);
}
+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', () => {
beforeEach(() => vi.clearAllMocks());
@@ -74,7 +118,7 @@ describe('maintenance dispatch', () => {
]) {
expect(cleanupLaneAt(time)).toEqual(
expect.objectContaining({
- kind: expect.stringMatching(/^(identity|support)$/),
+ kind: expect.stringMatching(/^(identity|support|knowledge)$/),
}),
);
}
@@ -113,8 +157,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 +172,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 +185,53 @@ 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('covers all 15 cleanup lanes once across a UTC day boundary', 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;
+ const maintenance = {
+ identity: runIdentityMaintenance,
+ support: runSupportMaintenance,
+ knowledge: runKnowledgeMaintenance,
+ };
+ const selected = maintenance[lane.kind];
expect(selected).toHaveBeenCalledExactlyOnceWith(
expect.anything(),
expect.anything(),
{
tasks: [lane.task],
- ...(lane.limiterIndex === undefined
+ ...(!('limiterIndex' in lane) || lane.limiterIndex === undefined
? {}
: { limiterIndex: lane.limiterIndex }),
},
);
- expect(other).not.toHaveBeenCalled();
+ 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 +241,75 @@ describe('maintenance dispatch', () => {
}
});
+ it('dispatches knowledge cleanup while knowledge is disabled and client configuration is invalid', async () => {
+ const start = Date.parse('2026-10-15T00:00:00Z');
+ let time: number | undefined;
+ for (let minute = 0; minute < 60; minute++) {
+ const candidate = start + minute * 60_000;
+ if (
+ new Date(candidate).getUTCMinutes() !== 59 &&
+ cleanupLaneAt(candidate).kind === 'knowledge'
+ ) {
+ time = candidate;
+ break;
+ }
+ }
+ if (time === undefined)
+ throw new Error('Expected one knowledge cleanup lane.');
+ await scheduled(CLEANUP_CRON, time, {
+ 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('runs one enabled KB page on the existing knowledge tick despite a limiter failure or invalid clients', async () => {
+ vi.mocked(runKnowledgeMaintenance).mockRejectedValueOnce(
+ new Error('Synthetic limiter failure.'),
+ );
+ await scheduled(CLEANUP_CRON, knowledgeCleanupTime(), {
+ PEGMA_KNOWLEDGE_ENABLED: 'true',
+ PEGMA_AGENT_CLIENTS_JSON: 'not-json',
+ });
+ expect(runKnowledgeMaintenance).toHaveBeenCalledTimes(1);
+ 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('preserves the limiter lane when 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).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 +323,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..41d4921 100644
--- a/worker/src/maintenance-schedule.ts
+++ b/worker/src/maintenance-schedule.ts
@@ -1,13 +1,14 @@
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 * * * *';
-type CleanupLane =
+export type CleanupLane =
| {
readonly kind: 'identity';
readonly task: IdentityMaintenanceTask;
@@ -17,6 +18,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 +41,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. */
diff --git a/worker/src/support-access.ts b/worker/src/support-access.ts
index 1897748..866652d 100644
--- a/worker/src/support-access.ts
+++ b/worker/src/support-access.ts
@@ -29,6 +29,8 @@ 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
@@ -93,7 +95,8 @@ 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 3 adds Knowledge Base permissions and
* administrator-only agent linking without replacing any stored assignment.
@@ -103,10 +106,8 @@ export const PEGMA_ACCESS_POLICY: PolicyDocumentV1 = Object.freeze({
version: 'pegma.dev-policy-3',
defaults: [...SUPPORT_CUSTOMER_PERMISSIONS, knowledgePermissions.articleRead],
roles: Object.freeze({
- [SUPPORT_ROLE]: [
- ...SUPPORT_STAFF_PERMISSIONS,
- ...KNOWLEDGE_STAFF_PERMISSIONS,
- ],
+ [SUPPORT_ROLE]: [...SUPPORT_STAFF_PERMISSIONS],
+ [KNOWLEDGE_ROLE]: [...KNOWLEDGE_STAFF_PERMISSIONS],
[ADMIN_ROLE]: [
...ADMIN_PERMISSIONS,
AGENT_LINK_PERMISSION,
diff --git a/worker/worker-configuration.d.ts b/worker/worker-configuration.d.ts
index e0137eb..ea0052f 100644
--- a/worker/worker-configuration.d.ts
+++ b/worker/worker-configuration.d.ts
@@ -1,10 +1,12 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --config=worker/wrangler.jsonc worker/worker-configuration.d.ts` (hash: 2c18913693aa2a7b223bfb756c331ebd)
+// 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;
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";
@@ -21,7 +23,7 @@ type StringifyValues> = {
[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 d120597..4de1368 100644
--- a/worker/wrangler.jsonc
+++ b/worker/wrangler.jsonc
@@ -23,6 +23,8 @@
"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",
From 137d8dd41a125ad181102f6a2927aa21d8eeaad4 Mon Sep 17 00:00:00 2001
From: Nathan Rover
Date: Mon, 9 Nov 2026 18:01:56 -0500
Subject: [PATCH 3/7] Qualify PG-01 on published storage and enforce current
portal authority
---
docs/KNOWLEDGE_COMPOSITION.md | 218 ++-
evals/assembly-eval.test.ts | 21 +-
package.json | 10 +-
pnpm-lock.yaml | 66 +-
src/data/catalog-enrichment.ts | 31 +-
src/data/components.ts | 3 +-
src/data/recipe-backlog.ts | 21 +-
worker/src/agent-access-runtime.test.ts | 7 +-
worker/src/agent-authority.ts | 18 +-
worker/src/agent-browser-freshness.test.ts | 349 +++-
worker/src/api-auth.ts | 62 +-
worker/src/identity-runtime.ts | 2 +
worker/src/index.ts | 68 +-
worker/src/knowledge-agent-freshness.test.ts | 260 ++-
worker/src/knowledge-api.ts | 137 +-
worker/src/knowledge-body-deadline.test.ts | 311 ++++
worker/src/knowledge-evidence.test.ts | 12 +-
worker/src/knowledge-evidence.ts | 10 +-
worker/src/knowledge-host.ts | 2 +-
worker/src/knowledge-integration-scenarios.ts | 43 +-
worker/src/knowledge-maintenance.test.ts | 182 +-
worker/src/knowledge-maintenance.ts | 25 +-
worker/src/knowledge-portal-freshness.test.ts | 504 ++++++
worker/src/knowledge-query-budget.d1.test.ts | 1589 +++++++++++++++++
.../knowledge-retrieval-maintenance.test.ts | 47 +-
worker/src/knowledge-retrieval-maintenance.ts | 212 ++-
worker/src/knowledge-retrieval-ready.test.ts | 303 ++++
worker/src/knowledge-retrieval-ready.ts | 196 ++
worker/src/knowledge-runtime.test.ts | 19 +-
worker/src/knowledge-runtime.ts | 371 +++-
worker/src/maintenance-cursors.d1.test.ts | 164 +-
worker/src/maintenance-schedule.test.ts | 156 +-
worker/src/maintenance-schedule.ts | 11 +
worker/wrangler.jsonc | 10 +-
34 files changed, 4930 insertions(+), 510 deletions(-)
create mode 100644 worker/src/knowledge-body-deadline.test.ts
create mode 100644 worker/src/knowledge-portal-freshness.test.ts
create mode 100644 worker/src/knowledge-query-budget.d1.test.ts
create mode 100644 worker/src/knowledge-retrieval-ready.test.ts
create mode 100644 worker/src/knowledge-retrieval-ready.ts
diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md
index 3654e81..5d08151 100644
--- a/docs/KNOWLEDGE_COMPOSITION.md
+++ b/docs/KNOWLEDGE_COMPOSITION.md
@@ -2,7 +2,7 @@
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.3`, over its existing Identity,
+`@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.
@@ -16,21 +16,50 @@ 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.3` packages, including the shared report factory, are now
-installed in the manifest and lockfile. The
-[verified `0.1.3` release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.3)
+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
-[`8b4c25aa6a40f0c56be97f07e3b7b5ac6136a99b`](https://github.com/pegma-dev/knowledge-base/commit/8b4c25aa6a40f0c56be97f07e3b7b5ac6136a99b)
+[`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/42533473529/attempts/5).
-Host type/runtime/build/review gates remain pending and activation is disabled;
-producer verification and installation are not host or actual-client acceptance.
+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 523 tests: 475 Node tests across 45 files, 46 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
@@ -83,6 +112,9 @@ The [host policy](../worker/src/support-access.ts) keeps authority explicit:
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
@@ -206,65 +238,123 @@ 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
-
-The [Knowledge limiter cleanup lane](../worker/src/knowledge-maintenance.ts) scans one
-global physical page of 10 rows each time its scheduled turn runs, regardless
-of the Knowledge feature flag or agent registration. It shares the scheduler
-with the existing Identity/Support lanes and uses the paged helper instead of
-enumerating live configured policies. Its 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. The new lane
-does not silently migrate old limiter storage. Existing Identity/Support
-maintenance remains in place. This source candidate does not establish live
-maintenance execution.
+### Limiter window cleanup and the shared cron
+
+The [scheduler](../worker/src/index.ts) keeps five distinct cron expressions.
+`RATE_LIMIT_CRON` remains `0-57 * * * *`, but its 58 eligible minutes now
+alternate between two isolated invocations:
+
+- Even UTC minutes run one [global limiter cleanup](../worker/src/knowledge-maintenance.ts)
+ page of at most 20 physical rows: 29 pages per hour. This runs independently
+ of the Knowledge flag and optional agent registrations.
+- Odd UTC minutes run one [ready-hint page](../worker/src/knowledge-retrieval-ready.ts)
+ when Knowledge is enabled. They do not also run limiter cleanup or physical
+ KB recovery. An empty ready queue does not trigger another heavy task.
+
+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
+activation, confirm account-wide cron usage: this configuration already uses
+five expressions and does not add a sixth for retrieval.
+
+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 580 physical rows per hour if all 29 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 now creates 12 five-minute windows for five IPs
+across seven policies: 420 counters, with the minute-58/59 gaps retained. It
+checks actual drainage at the revised cadence; it is not a production
+benchmark or a 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
-[createKnowledgeRetrievalMaintenance](../worker/src/knowledge-retrieval-maintenance.ts)
-uses an internal server-owned principal with only `knowledge.index.manage`,
-without an Admin role or new staff/agent grants. On the existing Knowledge turn
-of the [15-lane cleanup schedule](../worker/src/maintenance-schedule.ts),
-`runPage()` invokes one real `repairRetrievalPage` with a physical scan limit of 10. This is a separate KB projection page, not the ten limiter-window rows.
-Additional SDK keyed reads and projection writes have their own bounds. The
-new page requires the current exact `PEGMA_KNOWLEDGE_ENABLED=true` gate;
-limiter cleanup remains independent of that flag and of projection failures.
-The existing cleanup cron remains `0-58 * * * *`.
-
-The projection bookmark uses the separate `pegma-dev-maintenance` key
-`{ partition: 'knowledge', id: 'retrieval' }`. Its cursor and monotonic
-generation advance through OCC only when the prior cursor/generation still
-match, including a generation increment for `null` to `null`. A failed page
-does not advance its checkpoint, and stale overlapping completions cannot
-replace newer progress. Checkpoint
-acknowledgement uncertainty is resolved by rereading durable state; projection
-writes already completed are not rolled back. Retry the retained continuation
-and repeat complete cursor cycles, including
-no-match pages and pending work. Logs contain coarse counts/status/stages,
-not article IDs, cursors, queries, private bodies or exception text.
-
-Successful `publishArticle`, `retireArticle` and `revokeEvidence` commands also
-attempt one private bounded keyed `repairArticleIndex` through the
-[API/runtime hook](../worker/src/knowledge-runtime.ts). HTTP requests do not
-scan the corpus or expose maintenance operations/DTOs. A repair failure leaves
-the committed mutation intact and does not replace its result. The existing
-final browser-authority check still runs after the awaited hook and can
-withhold an acknowledgement if authority changed.
-
-The page worker constructs the actual application from the same Store and
-clock without report-factory, login, provider or agent-client construction.
-Publication eligibility still checks retained accepted evidence and current
-policy. These hosts currently have no `privateSources` verifier: retained
-nonempty private-source references remain blocked/unavailable. A future
-source-enabled composition must supply its real eligibility/currentness ports
-to both request and repair paths; there is no allow-all fallback.
-
-Keyed repair is best effort and does not guarantee immediate portal discovery
-or search readiness. Collection/policy changes, missed work and cleanup still
-need repeated page cycles. There is no indexing latency/SLA claim. Customer
-retrieval always rechecks actual publication, audience and proof/source
-revocation; stale index hints cannot grant access or restore approval.
+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 eight-case 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
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 8e23dcf..c53713d 100644
--- a/package.json
+++ b/package.json
@@ -30,10 +30,10 @@
"@pegma/authorization-storage": "0.4.0",
"@pegma/health": "^0.2.0",
"@pegma/identity": "0.1.2",
- "@pegma/knowledge-base-application": "0.1.3",
- "@pegma/knowledge-base-contracts": "0.1.3",
- "@pegma/knowledge-base-core": "0.1.3",
- "@pegma/knowledge-base-mcp": "0.1.3",
+ "@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",
@@ -42,7 +42,7 @@
"@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 6b3246d..ba6c290 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -39,17 +39,17 @@ importers:
specifier: 0.1.2
version: 0.1.2
'@pegma/knowledge-base-application':
- specifier: 0.1.3
- version: 0.1.3
+ specifier: 0.1.4
+ version: 0.1.4
'@pegma/knowledge-base-contracts':
- specifier: 0.1.3
- version: 0.1.3
+ specifier: 0.1.4
+ version: 0.1.4
'@pegma/knowledge-base-core':
- specifier: 0.1.3
- version: 0.1.3
+ specifier: 0.1.4
+ version: 0.1.4
'@pegma/knowledge-base-mcp':
- specifier: 0.1.3
- version: 0.1.3
+ specifier: 0.1.4
+ version: 0.1.4
'@pegma/logger-cloudflare':
specifier: ^0.1.1
version: 0.1.1
@@ -75,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
@@ -1154,20 +1154,20 @@ packages:
resolution: {integrity: sha512-r8AsVTnwCSBU2LZZjieW5FgIJ2TUWi5DlU9kp+4tuaWDFfl85EezkD6F5omAFjTnaFqCRN1T2d/KsHoESarB2A==}
engines: {node: '>=22'}
- '@pegma/knowledge-base-application@0.1.3':
- resolution: {integrity: sha512-X5vYihkaM5u+ewxDXQxNLzAv8Uc7bsH4rPcCU7oOG0hHhviNNQe9y9Qk+OXTKH8WPjpQNm8LQODHQr1yN4KjWQ==}
+ '@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.3':
- resolution: {integrity: sha512-4DYL5NXOZs7bL8ghsnsJxLFF2B7VL5iEyC+TNkFiabVzEEHrQmQqhxV+i6s10kp9vkCIYArOXYlCqwijEbpEog==}
+ '@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.3':
- resolution: {integrity: sha512-K6k8/8y/u3wdlGkAx1CjN+gKgQvpDgYw/2tuHngxCUOAl/q1HjQyILYRbjIMr1KwORKMXkay4h2XucXkfqEV9w==}
+ '@pegma/knowledge-base-core@0.1.4':
+ resolution: {integrity: sha512-eztpYFfXyTgvJTgx9PxitXkwLrFP+h03yJYxhQnM8mbNZNjulXF1j//eH8FjmQZzLRDGU1vW9Ec35T9xL43G1A==}
engines: {node: '>=22'}
- '@pegma/knowledge-base-mcp@0.1.3':
- resolution: {integrity: sha512-TY9vYnXbLtghb+lraQwqo8jjGTknsPxp3dmfHfNI5xx9bF458Orx0MYxVaIB0EfwLzv3XdmYKGQGJPvZnE327w==}
+ '@pegma/knowledge-base-mcp@0.1.4':
+ resolution: {integrity: sha512-Lk9Ig88bIWsxVEzutPJLLwv6yfK+e7QjdmnWPArDCe+NahmNtAWrLK7fomslmJ+PCEHMh3EeXzi85xxPuJHGow==}
engines: {node: '>=22'}
'@pegma/logger-cloudflare@0.1.1':
@@ -1206,8 +1206,8 @@ packages:
resolution: {integrity: sha512-jueFYJ3oJUacKdiERkEZ7R34xDMiEWXqn4MSA5bpTXzsXhWSap4EJUzKXtXnXuLPPjwJWLn5uoQe98kWQ6NS8A==}
engines: {node: '>=22'}
- '@pegma/storage-cloudflare-d1@0.4.1':
- resolution: {integrity: sha512-nVH+ppAWi3QwyEX8QVkPOLXNjtblO0jDnnGqCHpbZZzPvFQAVyd/1Bhxg8JdsuOD/UWGktJ26asAKzpNjRol0w==}
+ '@pegma/storage-cloudflare-d1@0.4.6':
+ resolution: {integrity: sha512-DjBRoRq5C6sWgL2KWdWOcW0F3N7HHuRu1i7Gr8SM4Aeh4FpEh1hQwIdMvkXpPHCd48CMqLJz8M5HYYR+/sRUgw==}
engines: {node: '>=22'}
'@pegma/storage-core@0.4.0':
@@ -3886,11 +3886,11 @@ 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.6)(zod@4.4.3)':
dependencies:
@@ -4122,31 +4122,31 @@ snapshots:
unicode-case-folding: 1.1.1
unorm: 1.6.0
- '@pegma/knowledge-base-application@0.1.3':
+ '@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.3
- '@pegma/knowledge-base-core': 0.1.3
+ '@pegma/knowledge-base-contracts': 0.1.4
+ '@pegma/knowledge-base-core': 0.1.4
'@pegma/spine': 0.1.2
'@pegma/storage-core': 0.4.0
- '@pegma/knowledge-base-contracts@0.1.3':
+ '@pegma/knowledge-base-contracts@0.1.4':
dependencies:
'@pegma/spine': 0.1.2
- '@pegma/knowledge-base-core@0.1.3':
+ '@pegma/knowledge-base-core@0.1.4':
dependencies:
- '@pegma/knowledge-base-contracts': 0.1.3
+ '@pegma/knowledge-base-contracts': 0.1.4
- '@pegma/knowledge-base-mcp@0.1.3':
+ '@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.3
- '@pegma/knowledge-base-contracts': 0.1.3
- '@pegma/knowledge-base-core': 0.1.3
+ '@pegma/knowledge-base-application': 0.1.4
+ '@pegma/knowledge-base-contracts': 0.1.4
+ '@pegma/knowledge-base-core': 0.1.4
zod: 4.6.7
transitivePeerDependencies:
- supports-color
@@ -4187,7 +4187,7 @@ snapshots:
'@pegma/spine@0.1.2': {}
- '@pegma/storage-cloudflare-d1@0.4.1':
+ '@pegma/storage-cloudflare-d1@0.4.6':
dependencies:
'@pegma/storage-core': 0.4.0
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/worker/src/agent-access-runtime.test.ts b/worker/src/agent-access-runtime.test.ts
index 46d5dc2..6224ed2 100644
--- a/worker/src/agent-access-runtime.test.ts
+++ b/worker/src/agent-access-runtime.test.ts
@@ -70,8 +70,13 @@ async function fixture() {
});
const identity: IdentityPort = {
claimsFor: vi.fn(async (principalId: string) => {
- if (!users.has(principalId))
+ 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,
diff --git a/worker/src/agent-authority.ts b/worker/src/agent-authority.ts
index 820fe24..0dd8aa4 100644
--- a/worker/src/agent-authority.ts
+++ b/worker/src/agent-authority.ts
@@ -35,6 +35,12 @@ 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);
@@ -60,18 +66,6 @@ export function createAgentPrincipalResolver(
link.subject !== principalId
)
return null;
- const assignments = await options.roleStore.listActiveRoleAssignments(
- principalId,
- APPLICATION_SCOPE,
- );
- const user = await options.identity.getUser(principalId);
- if (
- user === null ||
- user.principalId !== principalId ||
- user.status !== 'active' ||
- user.emailVerified !== true
- )
- return null;
return resolveAccess(
{ principalId, roles: assignments.map((assignment) => assignment.role) },
PEGMA_ACCESS_POLICY,
diff --git a/worker/src/agent-browser-freshness.test.ts b/worker/src/agent-browser-freshness.test.ts
index 6b3323e..f03dd9f 100644
--- a/worker/src/agent-browser-freshness.test.ts
+++ b/worker/src/agent-browser-freshness.test.ts
@@ -1,6 +1,7 @@
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 { createSessionStore } from '@pegma/sessions';
import {
createMemoryStore,
@@ -14,8 +15,10 @@ import {
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,
@@ -44,24 +47,41 @@ function barrier() {
interface StoreHooks {
afterGrantRead: (() => Promise) | undefined;
afterGrantCommit: (() => Promise) | undefined;
+ afterKbRead: (() => Promise) | undefined;
+ afterKbCommit: (() => Promise) | undefined;
+ beforeSessionRead: (() => Promise) | undefined;
}
-/** Only delay actual AA adapter operations; all records and authority are real. */
+/** 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);
- if (definition.name !== 'agent-access.records.v1') return target;
+ 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);
- await hooks.afterGrantRead?.();
+ 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) await hooks.afterGrantCommit?.();
+ if (result.committed) {
+ if (grant) await hooks.afterGrantCommit?.();
+ if (kb) await hooks.afterKbCommit?.();
+ }
return result;
},
};
@@ -83,6 +103,9 @@ async function fixture() {
const hooks: StoreHooks = {
afterGrantRead: undefined,
afterGrantCommit: undefined,
+ afterKbRead: undefined,
+ afterKbCommit: undefined,
+ beforeSessionRead: undefined,
};
const store = observedStore(backing, hooks);
const logger = { log() {} };
@@ -130,19 +153,32 @@ async function fixture() {
cookies.set(principalId, SESSION_COOKIE + '=' + sessionId);
sessionIds.set(principalId, sessionId);
}
- const candidateRuntime = createAgentAccessRuntime({
+ const options = {
store,
clock,
logger,
identity,
sessions,
roleStore,
- clients: [client],
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)
@@ -269,6 +305,9 @@ async function fixture() {
}
return {
runtime,
+ knowledge,
+ access,
+ hooks,
browser,
cookie,
prepared,
@@ -442,3 +481,301 @@ describe('actual current browser authority after AA service awaits', () => {
});
});
});
+
+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,
+ };
+}
+
+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 973d922..a3ec163 100644
--- a/worker/src/index.ts
+++ b/worker/src/index.ts
@@ -42,12 +42,16 @@ import {
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';
@@ -66,6 +70,17 @@ function knowledgeRetrievalEnabled(environment: {
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,
@@ -394,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 () => {
@@ -462,32 +507,15 @@ export default {
})(),
);
- if (cleanup?.kind === 'knowledge')
- ctx.waitUntil(
- (async () => {
- try {
- await runKnowledgeMaintenance(
- { store: createProductionStore(env), clock: systemClock },
- logger,
- { tasks: [cleanup.task] },
- );
- } catch (error) {
- logger.log('error', 'knowledge.maintenance_unavailable', {
- error: error instanceof Error ? error.name : 'unknown',
- });
- }
- })(),
- );
-
- // Keep the existing limiter lane independent of Knowledge activation and
- // failures. Only the new KB page requires the current Knowledge gate.
+ // 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: createProductionStore(env),
+ store: createKnowledgeProjectionStore(env),
clock: systemClock,
logger,
isEnabled: () => knowledgeRetrievalEnabled(env),
diff --git a/worker/src/knowledge-agent-freshness.test.ts b/worker/src/knowledge-agent-freshness.test.ts
index 977326d..e640865 100644
--- a/worker/src/knowledge-agent-freshness.test.ts
+++ b/worker/src/knowledge-agent-freshness.test.ts
@@ -9,6 +9,7 @@ import type {
} from '@pegma/knowledge-base-core';
import {
knowledgeAgentToolNames,
+ knowledgeAgentScopes,
type KnowledgeAgentOperation,
} from '@pegma/knowledge-base-mcp';
import { createSessionStore } from '@pegma/sessions';
@@ -290,11 +291,13 @@ async function fixture() {
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
}
- async function device() {
+ async function device(
+ scopes: readonly string[] = AGENT_KNOWLEDGE_PERMISSIONS,
+ ) {
const pending = await agents.service.beginDeviceAuthorization({
clientId: client.clientId,
resource: AGENT_RESOURCE,
- scopes: [...AGENT_KNOWLEDGE_PERMISSIONS],
+ scopes: [...scopes],
});
const viewed = await agents.api(
browser(
@@ -313,7 +316,7 @@ async function fixture() {
requestId: approval.requestId,
userCode: pending.user_code,
decision: 'approve',
- approvedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS],
+ approvedScopes: [...scopes],
}),
);
expect(approved?.status).toBe(200);
@@ -330,7 +333,7 @@ async function fixture() {
expect(delegated.access.roles).toEqual([]);
expect(delegated.access.entitlements).toEqual([]);
expect(delegated.access.permissions.slice().sort()).toEqual(
- [...AGENT_KNOWLEDGE_PERMISSIONS].sort(),
+ [...scopes].sort(),
);
return {
token: tokens.access_token,
@@ -467,7 +470,11 @@ async function fixture() {
).toBe('revoked');
}
}
- function block(hook: keyof StoreHooks, rowIdContains?: string) {
+ function block(
+ hook: keyof StoreHooks,
+ rowIdContains?: string,
+ failAfterRead = false,
+ ) {
const entered = barrier();
const finish = barrier();
hooks[hook] = async (rowId) => {
@@ -476,6 +483,8 @@ async function fixture() {
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 };
}
@@ -490,9 +499,59 @@ async function fixture() {
queueReport,
revoke,
block,
+ identity,
+ roleStore,
+ resolve,
};
}
+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) => {
@@ -543,6 +602,147 @@ describe.each(['http', 'mcp'] as const)(
},
);
+ 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) => {
@@ -755,6 +955,56 @@ describe.each(['http', 'mcp'] as const)(
},
);
+ 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) => {
diff --git a/worker/src/knowledge-api.ts b/worker/src/knowledge-api.ts
index 07b0f92..71749a6 100644
--- a/worker/src/knowledge-api.ts
+++ b/worker/src/knowledge-api.ts
@@ -18,6 +18,8 @@ import {
json,
optionalKeysObject,
readJson,
+ requireSameOriginMutation,
+ TOKEN_PATTERN,
} from './api-auth';
import {
requireCurrentBrowserAccess,
@@ -338,6 +340,38 @@ export function createKnowledgeApi(
),
);
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(
@@ -377,51 +411,95 @@ export function createKnowledgeApi(
}),
);
}
- // Authenticate before reading any browser command body. Per-operation
- // permission is checked again before entering the actual SDK service.
- await requireCurrentBrowserAccess(
- request,
- options,
- url.pathname === '/api/knowledge/portal'
- ? knowledgePermissions.articleRead
- : knowledgePermissions.collectionRead,
- true,
+ // 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,
+ staffCommand ? { timeoutMs: 10_000 } : undefined,
+ ),
+ ['operation', 'input'],
);
- const envelope = exactObject(await readJson(request), [
- '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 { access } = await requireCurrentBrowserAccess(
+ 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),
]);
- await requireCurrentBrowserAccess(
+ 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 requireCurrentBrowserAccess(
- request,
- options,
+ const { access } = await commandAccess(
KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION,
- true,
);
const result =
operation === 'reportList'
@@ -443,12 +521,7 @@ export function createKnowledgeApi(
? 'rejected'
: 'pending',
);
- await requireCurrentBrowserAccess(
- request,
- options,
- KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION,
- true,
- );
+ await commandAccess(KNOWLEDGE_EVIDENCE_CONFIRM_PERMISSION);
return secured(response(result));
}
if (!Object.hasOwn(operations, operation))
@@ -460,12 +533,7 @@ export function createKnowledgeApi(
)
throw new ApiError(400, 'unsupported_source_references');
const selected = operations[operation as keyof typeof operations];
- const { access } = await requireCurrentBrowserAccess(
- request,
- options,
- selected.permission,
- true,
- );
+ const { access } = await commandAccess(selected.permission);
const result: unknown = await Reflect.apply(selected.method, app, [
access,
sdkInput(operation, envelope.input),
@@ -495,12 +563,7 @@ export function createKnowledgeApi(
}
}
}
- await requireCurrentBrowserAccess(
- request,
- options,
- selected.permission,
- true,
- );
+ await commandAccess(selected.permission);
return secured(response(result));
} catch (error) {
let status = 503;
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