Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 89 additions & 27 deletions docs/KNOWLEDGE_COMPOSITION.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
# Knowledge Base host composition

The KB host integration is merged in
[PR #59](https://github.com/pegma-dev/pegma.dev/pull/59), with public activation
disabled. The host uses
[PR #59](https://github.com/pegma-dev/pegma.dev/pull/59). The checked-in profile
enables controlled staff authoring qualification with three explicit public client
registrations for testing against closed collections. Merging to `main` starts
the existing deployment workflow, which deploys the Worker before the Pages
site. Confirm that run and the metadata readback below before client tests.
Native-client acceptance and broader rollout remain pending. The host uses
exact published `@pegma/agent-access@0.1.1` and all four
`@pegma/knowledge-base-*` packages at `0.1.5`, over its existing Identity,
Sessions, stored roles and D1 Store. The public catalog at `/api/mcp` remains
Expand Down Expand Up @@ -42,8 +46,8 @@ at signed source
passed full-set original-byte, signature/provenance and registry-consumer
verification. Recovery retained the original prepared artifact without
repacking; the [release run completed at attempt 5](https://github.com/pegma-dev/knowledge-base/actions/runs/42576167664/attempts/5).
Activation remains disabled; producer verification and installation are not host
or actual-client acceptance.
That checkpoint records producer verification and installation, with activation
disabled. Host and actual-client acceptance remain separate.
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
Expand Down Expand Up @@ -96,15 +100,65 @@ for [commit `3a4e5c6a`](https://github.com/pegma-dev/pegma.dev/commit/3a4e5c6a39
also passed the configured frozen install, check, full 1,125 tests and build.
These results describe that source checkpoint. Review and deployment acceptance
remain pending for the changed host.
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.
Actual-client acceptances remain at zero and no pilot has run. The controlled
staff profile below permits gathering those results against closed test
collections. Broader rollout, customer AI and pilot qualification remain pending.

## Configuration and activation

`worker/wrangler.jsonc` starts with `PEGMA_KNOWLEDGE_ENABLED=false` and
`PEGMA_AGENT_CLIENTS_JSON=[]`. Disabled requests return before constructing
Identity or opening D1. Scheduled storage maintenance is a separate path and
must continue independently of this request switch.
[`worker/wrangler.jsonc`](../worker/wrangler.jsonc) sets
`PEGMA_KNOWLEDGE_ENABLED=true` and three explicit public client registrations
for controlled staff qualification. The prior profile was disabled with an empty
list. A push to `main` runs the [deployment workflow](../.github/workflows/deploy.yml)
and applies these variables after its checks pass.

Before starting client tests, confirm the deployment run succeeded for the
intended commit. Read `/.well-known/oauth-authorization-server` and
`/.well-known/oauth-protected-resource/api/knowledge/mcp` over HTTPS and confirm
both return `200` with the expected Pegma issuer, resource and three authoring scopes.
Check the authorization, device and token endpoint URLs against the configuration.
A `503` such as `agent_access_not_configured` requires investigation before
continuing. Record the deployed commit and these readbacks in each actual-client
result.

Use existing site login and Admin consent, closed staff-test collections and
fictional product documentation. Collections, navigation, roles and grants remain
unchanged. The learning-review flag stays false;
customer AI, automatic publication, engineering processing/export and other
provider capabilities remain unchanged and off. All five cron expressions and
their lanes are retained exactly.

The first tests use these operator-selected registrations. Each test verifies
them against the installed client.

| Public client ID | First intended flow | Registered callback |
| --- | --- | --- |
| `pg-kb-codex-accept-v1` | Codex CLI, authorization code with PKCE | `http://127.0.0.1/callback`; Agent Access `0.1.1` permits only the IP-loopback port substitution |
| `pg-kb-claude-accept-v1` | Claude Code, authorization code with PKCE | `http://localhost:48772/callback`; configure the client to use that exact port |
| `pg-kb-device-accept-v1` | Separate RFC 8628 host control | No redirect URI; device-code grant only |

Port `48772` was available on both IPv4 and IPv6 loopback during the local
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
2026-11-11 availability check, which closed both listeners immediately. Recheck
availability when starting the client. Record the actual callback, installed
version and provider mode during each test. Require the
registered hostname and path, with only the declared IP-loopback port
substitution. The RFC 8628 host control has its own result, separate from native
CLI proof. Codex CLI and Claude Code acceptance remain pending. Hosted Grok Bot
and T3 Code registrations and acceptance remain pending.

Each registration permits only `knowledge.article.draft.read`,
`knowledge.article.draft.write` and `knowledge.article.evidence.submit`.
Admin-only linking and the existing browser, collection-audience, human review
and exact-publication boundaries remain authoritative. Admin roles and
publication, review, collection/governance and private-provenance authority
remain outside the delegated scope.

For rollback, revoke known test grants through their existing owner controls
while available, then restore `PEGMA_KNOWLEDGE_ENABLED=false` and
`PEGMA_AGENT_CLIENTS_JSON=[]` through the same configuration/deployment path.
The false flag rejects requests before constructing Identity or opening D1.
Changing the flag leaves stored grant families unchanged. Scheduled storage
maintenance continues independently of this switch.

Missing or empty client configuration disables the OAuth issuer and delegated
transports. Invalid optional agent configuration also leaves those paths
Expand Down Expand Up @@ -135,18 +189,21 @@ documented scope rather than a trace-redaction acceptance result. The normal
check dry-runs the main config with direct Wrangler `4.128.0`, and the Node
config regression requires its normalized root redaction flag to be `true`.
The [Worker toolchain notes](../worker/README.md#toolchain-compatibility)
record the retained older type generation and test-pool parser, optional
record the current generated runtime, retained older test-pool parser, optional
workers-types mismatch and upstream Miniflare pairing.

This setting does not establish redaction of arbitrary application messages,
exception strings, or Live Tail output. Keep application diagnostics
content-free and qualify the deployed configuration with synthetic query
sentinels before private OAuth acceptance. Source configuration, tests and a
dry run alone do not prove deployed redaction.

Keep test collections closed during controlled staff acceptance. The disabled
candidate is not advertised through new global navigation or Account links.
Expose those entry points only after activation requirements pass. Actual
On 2026-11-11, after the redaction change in
[PR #63](https://github.com/pegma-dev/pegma.dev/pull/63) was deployed, three
fictional GET requests produced positive retained log rows whose observed
invocation URLs omitted their query strings and synthetic query values.
The deployed proof covers request-URL logging. Arbitrary application messages,
exception strings and Live Tail output remain unqualified, and traces remain
disabled. Keep application diagnostics content-free. Source parsing, tests and
dry runs provide local validation.

Test collections stay closed and global navigation and Account links remain
unchanged. Broader discoverability, rollout, CPU/load qualification and
supervised pilot results remain pending. Actual
existing-login/Admin consent, device/PKCE flows, scoped API/MCP operations,
revocation, and failure cases must be observed through the requested clients.
Source and full D1 tests do not establish any of the four actual client
Expand Down Expand Up @@ -294,8 +351,10 @@ provenanceRead before and after the SDK proof, with an additional original-brows
fence in HTTP. Exact accepted-receipt recovery and cancellation retain current
review/queue authority without requiring obsolete KB rights; neither operation
publishes an article or supplies new source approval. The root
request composition supplies no private-source verifier and keeps Knowledge
disabled; source-enabled production wiring is not implied by the factory seam.
request composition supplies no private-source verifier. Ordinary authoring is
enabled by the configured profile; workflows requiring private source references
remain unavailable without that verifier. Source-enabled production wiring
requires that verifier.

Once the actual KB accepts evidence and publishes revision 1, a later draft
or elapsed report/check TTL alone does not withdraw that approved publication.
Expand Down Expand Up @@ -345,8 +404,8 @@ discovery lane, for 16 exclusive lanes. That lane emits queue hints only; a
review phase runs in a later Queue invocation. The default root supplies no
trusted learning bundle and keeps the review flag off. Minutes 58 and 59 have no `RATE_LIMIT_CRON` invocation. Before
merging, inventory every Worker's current cron triggers in the deployment
account: pushes to `main` deploy these schedules even while Knowledge is
disabled. Deployment replaces this Worker's existing expressions with these
account: pushes to `main` deploy these schedules regardless of the Knowledge
flag. Deployment replaces this Worker's existing expressions with these
five. The [Workers Free allowance is five triggers per account](https://developers.cloudflare.com/workers/platform/limits/#account-plan-limits),
so this configuration leaves no capacity for another Worker's triggers.
Require the account total after replacement to fit its effective allowance;
Expand Down Expand Up @@ -438,7 +497,9 @@ bridge to `createKnowledgeRuntime`, `createKnowledgeRetrievalReady` and
`createKnowledgeRetrievalMaintenance`; request-only wiring cannot qualify
projection work. Omission blocks retained nonempty source references; there is
no allow-all fallback. The root request and scheduled compositions do not yet
supply that bridge and keep Knowledge disabled. The real-Memory
supply that bridge. Retained nonempty private source references therefore remain
unavailable. Controlled ordinary product-guide authoring omits Support/private
source references. Source-enabled learning qualification remains pending. The real-Memory
[composition test](../worker/src/support-learning-composition.test.ts) exercises
accepted Support sources and current reopen/withdraw/missing-ticket refusals
through the actual factories, without bypassing KB evidence/publication gates.
Expand All @@ -465,8 +526,9 @@ 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.
Preserve all authority and history checks. The controlled staff profile permits
closed test-collection authoring. Live-platform CPU, quota and load qualification,
source-enabled workflows and broader rollout remain pending.

Disable Knowledge if its acceptance fails. Identity and role administration
remain independent. Support Desk's human-control adoption is documented separately in
Expand Down
211 changes: 211 additions & 0 deletions src/knowledge-authoring-config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { unstable_readConfig } from 'wrangler';
import { createMemoryStore } from '@pegma/storage-core';
import { createRoleStore } from '@pegma/authorization-storage';
import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity';
import {
AGENT_ENDPOINTS,
AGENT_RESOURCE,
AGENT_RESOURCE_METADATA_URL,
createAgentAccessRuntime,
readAgentClients,
} from '../worker/src/agent-access-runtime';
import { createIdentityRuntime } from '../worker/src/identity-runtime';
import {
AGENT_KNOWLEDGE_PERMISSIONS,
AGENT_LINK_PERMISSION,
AUTHORIZATION_APPLICATION_ID,
} from '../worker/src/support-access';

function deploymentConfiguration() {
return unstable_readConfig({
config: fileURLToPath(new URL('../worker/wrangler.jsonc', import.meta.url)),
});
}

function configuredRuntime(
raw = deploymentConfiguration().vars.PEGMA_AGENT_CLIENTS_JSON,
) {
if (typeof raw !== 'string') throw new Error('Expected registered client JSON.');
const store = createMemoryStore();
const logger = { log() {} };
const identity = createIdentityRuntime(
{
store,
emailCodeSecretBase64: btoa('f'.repeat(32)),
emailFrom: 'Pegma <fictional@example.test>',
emailEnabled: false,
},
logger,
);
const runtime = createAgentAccessRuntime({
store,
sessions: identity.sessions,
identity: identity.identity,
identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims,
roleStore: createRoleStore(store, AUTHORIZATION_APPLICATION_ID),
logger,
clients: readAgentClients(raw),
});
if (runtime === null) throw new Error('Expected configured Agent Access.');
return runtime;
}

function authorizationRequest(clientId: string, redirectUri: string) {
const query = new URLSearchParams({
response_type: 'code',
client_id: clientId,
redirect_uri: redirectUri,
resource: AGENT_RESOURCE,
scope: AGENT_KNOWLEDGE_PERMISSIONS.join(' '),
code_challenge: 'A'.repeat(43),
code_challenge_method: 'S256',
state: 'fictional-config-regression',
});
return new Request(`${AGENT_ENDPOINTS.authorize}?${query}`);
}

describe('controlled authoring deployment registrations against released Agent Access', () => {
it('constructs the exact checked-in three-client profile and serves both discovery documents', async () => {
const config = deploymentConfiguration();
expect(config.vars.PEGMA_KNOWLEDGE_ENABLED).toBe('true');
expect(config.vars.PEGMA_SUPPORT_LEARNING_REVIEWS_ENABLED).toBe('false');
const runtime = configuredRuntime();
expect(runtime.configuration.clients).toEqual([
{
clientId: 'pg-kb-codex-accept-v1',
name: 'Pegma Codex CLI',
redirectUris: ['http://127.0.0.1/callback'],
allowedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS],
grantTypes: ['authorization_code'],
},
{
clientId: 'pg-kb-claude-accept-v1',
name: 'Pegma Claude Code',
redirectUris: ['http://localhost:48772/callback'],
allowedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS],
grantTypes: ['authorization_code'],
},
{
clientId: 'pg-kb-device-accept-v1',
name: 'Pegma RFC 8628 control',
redirectUris: [],
allowedScopes: [...AGENT_KNOWLEDGE_PERMISSIONS],
grantTypes: ['device_code'],
},
]);
expect(AGENT_KNOWLEDGE_PERMISSIONS).toEqual([
'knowledge.article.draft.read',
'knowledge.article.draft.write',
'knowledge.article.evidence.submit',
]);
const authorization = await runtime.protocol.handle(
new Request('https://pegma.dev/.well-known/oauth-authorization-server'),
);
expect(authorization?.status).toBe(200);
expect(await authorization?.json()).toMatchObject({
issuer: 'https://pegma.dev',
authorization_endpoint: AGENT_ENDPOINTS.authorize,
device_authorization_endpoint: AGENT_ENDPOINTS.deviceAuthorization,
token_endpoint: AGENT_ENDPOINTS.token,
scopes_supported: [...AGENT_KNOWLEDGE_PERMISSIONS],
code_challenge_methods_supported: ['S256'],
});
const resource = await runtime.protocol.handle(
new Request(AGENT_RESOURCE_METADATA_URL),
);
expect(resource?.status).toBe(200);
expect(await resource?.json()).toMatchObject({
resource: AGENT_RESOURCE,
authorization_servers: ['https://pegma.dev'],
scopes_supported: [...AGENT_KNOWLEDGE_PERMISSIONS],
});
});

it.each([
['pg-kb-codex-accept-v1', 'http://127.0.0.1:48773/callback'],
['pg-kb-claude-accept-v1', 'http://localhost:48772/callback'],
])(
'hands the registered %s PKCE request to existing login without approving it',
async (clientId, redirectUri) => {
const runtime = configuredRuntime();
const request = authorizationRequest(clientId, redirectUri);
const response = await runtime.protocol.handle(request);
expect(response?.status).toBe(303);
const location = response?.headers.get('Location');
if (!location) throw new Error('Expected existing-login handoff.');
const login = new URL(location);
expect(login.origin + login.pathname).toBe('https://pegma.dev/account');
expect(login.searchParams.get('returnTo')).toBe(
new URL(request.url).pathname + new URL(request.url).search,
);
},
);

it.each([
['pg-kb-codex-accept-v1', 'http://localhost:48773/callback'],
['pg-kb-codex-accept-v1', 'http://127.0.0.1:48773/other'],
['pg-kb-claude-accept-v1', 'http://localhost:48773/callback'],
])(
'rejects unregistered callback %s %s before login',
async (clientId, redirectUri) => {
const response = await configuredRuntime().protocol.handle(
authorizationRequest(clientId, redirectUri),
);
expect(response?.status).toBe(400);
expect(response?.headers.get('Location')).toBeNull();
},
);

it('starts only the registered device control through the actual protocol with no redirect URI', async () => {
const runtime = configuredRuntime();
for (const [clientId, expectedStatus] of [
['pg-kb-device-accept-v1', 200],
['pg-kb-codex-accept-v1', 400],
] as const) {
const response = await runtime.protocol.handle(
new Request(AGENT_ENDPOINTS.deviceAuthorization, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: clientId,
resource: AGENT_RESOURCE,
scope: AGENT_KNOWLEDGE_PERMISSIONS.join(' '),
}),
}),
);
expect(response?.status).toBe(expectedStatus);
if (expectedStatus === 200) {
expect(await response?.json()).toMatchObject({
user_code: expect.any(String),
device_code: expect.any(String),
verification_uri: AGENT_ENDPOINTS.verification,
});
}
}
});

it.each([
['scope escalation', 0, { allowedScopes: [AGENT_LINK_PERMISSION] }],
['wildcard callback', 0, { redirectUris: ['http://127.0.0.1/*'] }],
['missing localhost port', 1, { redirectUris: ['http://localhost/callback'] }],
[
'authorization code without callback',
2,
{ grantTypes: ['authorization_code'] },
],
] as const)(
'rejects %s when a checked-in registration drifts',
(_name, index, change) => {
const raw = deploymentConfiguration().vars.PEGMA_AGENT_CLIENTS_JSON;
if (typeof raw !== 'string') throw new Error('Expected registered client JSON.');
const clients = readAgentClients(raw);
if (clients === null) throw new Error('Expected registered clients.');
const changed = clients.map((client, current) =>
current === index ? { ...client, ...change } : client,
);
expect(() => configuredRuntime(JSON.stringify(changed))).toThrow();
},
);
});
Loading
Loading