@runeditrun/rer 0.2.85 → 0.2.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +138 -29
  2. package/cli/README.md +61 -1
  3. package/cli/agent-door.mjs +149 -0
  4. package/cli/agent-fixtures.mjs +16 -0
  5. package/cli/agent-mail.mjs +54 -0
  6. package/cli/agent-network.mjs +64 -0
  7. package/cli/agent-reviewers.mjs +110 -0
  8. package/cli/agent-secrets.mjs +23 -0
  9. package/cli/agent-sponsors.mjs +43 -0
  10. package/cli/agent-surface.mjs +34 -0
  11. package/cli/agent-webhooks.mjs +19 -0
  12. package/cli/authoring.mjs +2 -1
  13. package/cli/business/archive-task.mjs +32 -0
  14. package/cli/business/carry.mjs +3 -1
  15. package/cli/business/catchup-task.mjs +42 -0
  16. package/cli/business/choices.mjs +97 -0
  17. package/cli/business/command.mjs +23 -5
  18. package/cli/business/connect.mjs +19 -7
  19. package/cli/business/detector.mjs +4 -1
  20. package/cli/business/device.mjs +13 -0
  21. package/cli/business/export-inputs.mjs +69 -0
  22. package/cli/business/export-task.mjs +17 -0
  23. package/cli/business/invocation.mjs +8 -1
  24. package/cli/business/keychain.mjs +8 -1
  25. package/cli/business/lease.mjs +11 -1
  26. package/cli/business/local-commands.mjs +79 -31
  27. package/cli/business/outbound.mjs +9 -4
  28. package/cli/business/parsers-config.mjs +8 -7
  29. package/cli/business/parsers-syntax.mjs +7 -3
  30. package/cli/business/permissions.mjs +2 -0
  31. package/cli/business/questions.mjs +89 -9
  32. package/cli/business/setup-command.mjs +49 -0
  33. package/cli/business/setup-company.json +15 -0
  34. package/cli/business/setup-demo.mjs +95 -0
  35. package/cli/business/state.mjs +44 -10
  36. package/cli/business/supervisor.mjs +94 -35
  37. package/cli/business/vendor-door.mjs +230 -0
  38. package/cli/business/vendors/README.md +29 -3
  39. package/cli/business/vendors/common.mjs +8 -6
  40. package/cli/business/vendors/index.mjs +22 -11
  41. package/cli/business/vendors/sorry.mjs +106 -0
  42. package/cli/contract.mjs +2 -2
  43. package/cli/demo-deploy-error.mjs +14 -0
  44. package/cli/demo-native.mjs +4 -1
  45. package/cli/deploy-config.mjs +1 -1
  46. package/cli/deploy-owner-input.mjs +3 -1
  47. package/cli/deploy-variables.mjs +58 -0
  48. package/cli/door-clauses.mjs +157 -0
  49. package/cli/export.mjs +16 -4
  50. package/cli/hosted-output.mjs +17 -7
  51. package/cli/inspect.mjs +4 -0
  52. package/cli/jsonc.mjs +8 -4
  53. package/cli/lifecycle.mjs +3 -1
  54. package/cli/main.mjs +1 -0
  55. package/cli/managed-data-schema.mjs +14 -1
  56. package/cli/portability-empty.mjs +6 -0
  57. package/cli/portability-migrations.mjs +26 -4
  58. package/cli/production-auth.mjs +1 -1
  59. package/cli/production-mail.mjs +8 -2
  60. package/edition-authoring/archive-source.mjs +59 -0
  61. package/edition-authoring/base-copies.mjs +92 -18
  62. package/edition-authoring/cli.mjs +1 -1
  63. package/edition-authoring/edition-migrations.mjs +7 -3
  64. package/edition-authoring/module-closure.mjs +2 -16
  65. package/edition-authoring/workflow-copies.mjs +1 -1
  66. package/edition-authoring/workflow-scripts.mjs +12 -3
  67. package/foundation/runtime/contract-docs.mjs +215 -32
  68. package/foundation/runtime/contract-prose-patterns.mjs +14 -0
  69. package/foundation/runtime/contract-prose.mjs +88 -0
  70. package/global/CHANGELOG.md +93 -0
  71. package/global/README.md +138 -29
  72. package/global/door/command.mjs +3 -1
  73. package/global/main.mjs +1 -1
  74. package/modules/agent-door/CLAUSES.md +215 -0
  75. package/modules/agent-door/conformance/audit.mjs +66 -0
  76. package/modules/agent-door/conformance/authority.d.mts +2 -0
  77. package/modules/agent-door/conformance/authority.mjs +17 -0
  78. package/modules/agent-door/conformance/crypto.mjs +36 -0
  79. package/modules/agent-door/conformance/discovery.mjs +61 -0
  80. package/modules/agent-door/conformance/index.mjs +41 -0
  81. package/modules/agent-door/conformance/invocation.mjs +32 -0
  82. package/modules/agent-door/conformance/journey.mjs +112 -0
  83. package/modules/agent-door/conformance/narrowing.d.mts +1 -0
  84. package/modules/agent-door/conformance/narrowing.mjs +21 -0
  85. package/modules/agent-door/conformance/negative.mjs +47 -0
  86. package/modules/agent-door/conformance/network-modules.mjs +86 -0
  87. package/modules/agent-door/conformance/network-runtime.mjs +46 -0
  88. package/modules/agent-door/conformance/policy-phases.mjs +75 -0
  89. package/modules/agent-door/conformance/protocol.mjs +145 -0
  90. package/modules/agent-door/conformance/replay.mjs +38 -0
  91. package/modules/agent-door/conformance/schema.mjs +71 -0
  92. package/modules/agent-door/conformance/security.mjs +33 -0
  93. package/modules/agent-door/conformance/sponsors.mjs +68 -0
  94. package/modules/agent-door/conformance/surface.mjs +89 -0
  95. package/modules/agent-door/conformance/target.mjs +18 -0
  96. package/modules/agent-door/conformance/tool-name.d.mts +1 -0
  97. package/modules/agent-door/conformance/tool-name.mjs +7 -0
  98. package/modules/agent-door/conformance/webhooks.mjs +30 -0
  99. package/modules/container/image-variables.mjs +8 -2
  100. package/modules/demo-host/README.md +6 -0
  101. package/modules/demo-host/ownership.mjs +39 -0
  102. package/modules/demo-host/plan.mjs +2 -1
  103. package/modules/demo-host/remove.mjs +6 -1
  104. package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
  105. package/modules/import-kit/schema/importers.schema.json +107 -0
  106. package/modules/import-kit/src/door/ADOPTING.md +20 -0
  107. package/modules/import-kit/src/door/README.md +2 -1
  108. package/modules/import-kit/src/door/admission.ts +5 -3
  109. package/modules/import-kit/src/door/archive.ts +5 -2
  110. package/modules/import-kit/src/door/authority.ts +1 -0
  111. package/modules/import-kit/src/door/grants.ts +1 -1
  112. package/modules/import-kit/src/door/handler.ts +14 -8
  113. package/modules/import-kit/src/door/index.ts +1 -1
  114. package/modules/import-kit/src/door/jobs.ts +40 -0
  115. package/modules/import-kit/src/door/operator.ts +3 -3
  116. package/modules/import-kit/src/door/planning.ts +10 -6
  117. package/modules/import-kit/src/door/protocol.ts +2 -2
  118. package/modules/import-kit/src/door/raw.ts +25 -0
  119. package/modules/import-kit/src/door/refusals.ts +1 -0
  120. package/modules/import-kit/src/door/types.ts +26 -6
  121. package/modules/import-kit/src/receipt/encoding.ts +37 -0
  122. package/modules/import-kit/src/receipt/index.ts +69 -0
  123. package/modules/import-kit/src/receipt/policy.ts +24 -0
  124. package/modules/import-kit/src/receipt/types.ts +64 -0
  125. package/modules/import-kit/src/receipt/uri.ts +45 -0
  126. package/modules/import-kit/src/receipt/validation.ts +87 -0
  127. package/modules/import-kit/src/status/encoding.ts +13 -0
  128. package/modules/import-kit/src/status/evidence.ts +218 -0
  129. package/modules/import-kit/src/status/index.ts +56 -0
  130. package/modules/import-kit/src/status/schema.ts +208 -0
  131. package/modules/import-kit/src/status/types.ts +86 -0
  132. package/modules/operator-auth/accounts/delegated.mjs +48 -0
  133. package/modules/operator-auth/index.d.mts +7 -0
  134. package/modules/operator-auth/service.mjs +2 -0
  135. package/modules/portability/README.md +32 -11
  136. package/modules/portability/bridge.mjs +22 -2
  137. package/modules/portability/copies.mjs +8 -1
  138. package/modules/portability/derived.mjs +33 -0
  139. package/modules/portability/http-errors.mjs +1 -1
  140. package/modules/portability/import.mjs +14 -7
  141. package/package.json +4 -2
  142. package/scripts/publish-check/copy_identities.py +3 -1
  143. package/scripts/publish-check/github_refs.py +32 -13
  144. package/cli/business/opt-ins.mjs +0 -37
@@ -0,0 +1,66 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { classIds } from './protocol.mjs';
3
+ import { AGENT_CLASSES } from './surface.mjs';
4
+ import { targetIdentity } from './target.mjs';
5
+
6
+ export async function auditRows(c) {
7
+ const rows = []; let cursor = null, differs = 0;
8
+ for (let page = 0; page < 100; page++) {
9
+ const result = await c.personJson(`/agents/api/audit?agent=${encodeURIComponent(c.agentId)}${cursor ? `&after=${encodeURIComponent(cursor)}` : ''}`);
10
+ if (!Array.isArray(result.rows) || !Number.isInteger(result.differs_from_policy)) throw new Error('Audit API must return rows and differs_from_policy');
11
+ rows.push(...result.rows); differs += result.differs_from_policy;
12
+ if (result.cursor == null || result.cursor === cursor) return { rows, differs };
13
+ cursor = result.cursor;
14
+ }
15
+ throw new Error('Audit pagination exceeded 100 pages');
16
+ }
17
+ export async function auditPhase(c) {
18
+ const { rows, differs } = await auditRows(c), expected = [...c.calls];
19
+ c.add('BASE-AGENT-009.1.count', rows.length === expected.length, `Expected exactly ${expected.length} audit rows for tool calls, resource reads and approval executions, found ${rows.length}.`);
20
+ c.add('BASE-AGENT-009.1.unique', new Set(rows.map(row => row.id)).size === rows.length, 'Every tool call, resource read and approval execution must have its own audit ID.');
21
+ for (const [index, call] of expected.entries()) {
22
+ const row = rows[index], decision = call.decision;
23
+ c.add(`BASE-AGENT-009.1.call.${index}`, Boolean(row) && row.tool === call.name && row.consent === c.consent && row.agent?.id === c.agentId && row.agent?.specialist === c.surface.specialist && row.sponsor?.id === c.sponsor.id && typeof row.label === 'string' && row.label.includes(' for ') && Number.isFinite(Date.parse(row.at)) && row.door === (call.kind === 'embedded' ? 'embedded' : 'mcp'), `${call.name} lacks its complete ordered audit row.`);
24
+ if (!row) continue;
25
+ if (call.code === 'native_proof_required') c.add(`BASE-AGENT-004.native-proof.audit.${index}`, row.outcome === 'refused' && row.code === call.code, `${call.name} native proof challenge must retain its refused audit outcome.`);
26
+ c.add(`BASE-AGENT-009.1.resource.${index}`, call.kind === 'resources/read' ? row.resource === call.args.uri : row.resource === null || targetIdentity(row.resource), `${call.name} audit resource must identify the requested URI or the seed-resolved native kind and id.`);
27
+ c.add(`BASE-AGENT-009.2.link.${index}`, call.kind === 'approval/execute' ? row.id !== decision?.id && row.decision_id === decision?.id : row.decision_id === null, `${call.name} must ${call.kind === 'approval/execute' ? 'link its own execution row to the pending decision' : 'have its own call row without an approval execution link'}.`);
28
+ const validClasses = Array.isArray(row.classes) && new Set(classIds(row.classes)).size === row.classes.length && row.classes.every(item => AGENT_CLASSES.includes(item.class) && item.facts && typeof item.facts === 'object');
29
+ c.add(`BASE-AGENT-006.6.audit.${index}`, validClasses && (decision ? isDeepStrictEqual(classIds(row.classes), classIds(decision.classes)) && decision.classes.every(item => row.classes.some(actual => actual.class === item.class && isDeepStrictEqual(actual.facts, item.facts))) : call.kind === 'resources/read' || row.classes.length === 0), `${call.name} audit classes/facts differ from its computed decision.`);
30
+ if (decision) c.add(`BASE-AGENT-009.2.decision.${index}`, (call.kind === 'approval/execute' || row.id === decision.id) && row.decision === decision.disposition && row.revision === decision.revision && isDeepStrictEqual(row.rules, decision.classes.map(({ class: cls, rule, do: disposition }) => ({ class: cls, rule, do: disposition }))), `${call.name} audit decision or revision differs from the response.`);
31
+ else if (call.kind === 'resources/read') c.add(`BASE-AGENT-009.2.resource-rules.${index}`, Array.isArray(row.rules) && isDeepStrictEqual(classIds(row.rules), classIds(row.classes)) && row.rules.every(rule => typeof rule.rule === 'string' && ['autonomous', 'review', 'approval', 'blocked', 'unset'].includes(rule.do)), 'Resource audit classes must each carry the applied policy rule and disposition.');
32
+ if (decision?.disposition === 'review') c.add(`BASE-AGENT-009.4.review.${index}`, Boolean(row.review?.id), `${call.name} was decided review without a review row.`);
33
+ if (call.pending) c.add(`BASE-AGENT-009.2.pending.${index}`, row.outcome === 'pending' && Boolean(call.approval?.id) && row.approval?.id === call.approval.id, `${call.name} must retain its original pending audit outcome and approval handle after the approval executes.`);
34
+ if (call.kind === 'approval/execute') c.add(`BASE-AGENT-008.5.execution.${index}`, row.approval?.id === call.approvalId && row.approval.by?.includes(c.sponsor.id) && row.outcome === 'done', `${call.name} approved execution lacks its completed row and named sponsor approval.`);
35
+ if (call.result?._meta?.['com.runeditrun/receipt']) c.add(`BASE-AGENT-008.5.audit.${index}`, Boolean(row.approval?.id) && row.approval.by?.includes(row.sponsor.id), `${call.name} approval receipt lacks the signed-in sponsor as approver.`);
36
+ }
37
+ c.add('BASE-AGENT-007.7.differs-from-policy', differs === 0, `Audit evidence has ${differs} decisions that differ from the policy in force.`);
38
+ // Audit is read before the events tool: its own call is audited as well, but
39
+ // cannot occur in a snapshot taken before it was made.
40
+ const events = []; let after;
41
+ for (let page = 0; page < 100; page++) {
42
+ const result = await c.tool(`${c.surface.seed}.events.list`, { ...(after ? { after } : {}), limit: 200 });
43
+ const content = result.result?.structuredContent;
44
+ if (!Array.isArray(content?.events)) throw new Error('events.list did not return {events,cursor}');
45
+ events.push(...content.events);
46
+ if (content.events.length < 200 || content.cursor === after) break;
47
+ after = content.cursor;
48
+ }
49
+ c.add('BASE-AGENT-010.2.events', events.length > 0 && new Set(events.map(event => event.id)).size === events.length && events.every(event => typeof event.id === 'string' && typeof event.type === 'string' && typeof event.uri === 'string' && event.actor && Number.isFinite(Date.parse(event.at))), 'Events must have stable unique ids, type, URI, actor and time.');
50
+ for (const type of ['policy.adopted', 'approval.pending', 'approval.decided']) {
51
+ const applicable = type === 'policy.adopted' || rows.some(row => row.approval);
52
+ if (applicable) c.add(`BASE-AGENT-010.6.${type}`, events.some(event => event.type === type), `Missing ${type} event.`);
53
+ }
54
+ const writeTools = new Set(rows.filter(row => row.tool !== 'resources/read' && ['done', 'replayed'].includes(row.outcome) && c.surface.tools.find(tool => tool.name === row.tool)?.readOnly === false).map(row => row.tool));
55
+ c.add('BASE-AGENT-010.1.effects', !writeTools.size || [...events, ...c.effectEvents ?? []].some(event => event.actor?.kind === 'agent' && !['policy.decision', 'approval.pending', 'approval.decided'].includes(event.type)), 'Completed writes must produce record-change events attributed to the agent while their native resources are readable.');
56
+ if (events.length > 1) {
57
+ const cursor = events[0].id;
58
+ const replay1 = await c.tool(`${c.surface.seed}.events.list`, { after: cursor, limit: 200 });
59
+ const replay2 = await c.tool(`${c.surface.seed}.events.list`, { after: cursor, limit: 200 });
60
+ const ids = result => result.result?.structuredContent?.events?.map(event => event.id) ?? [];
61
+ const first = ids(replay1), second = ids(replay2);
62
+ c.add('BASE-AGENT-010.3.cursor', first.length > 0 && isDeepStrictEqual(first, second.slice(0, first.length)) && first[0] === events[1].id, 'Replaying one cursor must return the same retained event ids in order.');
63
+ }
64
+ const final = await auditRows(c);
65
+ c.add('BASE-AGENT-009.1.events-audited', final.rows.length === c.calls.length && final.differs === 0, `events.list audit calls mismatch: ${final.rows.length} audit rows for ${c.calls.length} calls.`);
66
+ }
@@ -0,0 +1,2 @@
1
+ export function recordOnlySchema(schema: unknown, depth?: number): boolean
2
+ export function recordOnlyAuthority(tool: unknown): boolean
@@ -0,0 +1,17 @@
1
+ // A no-subject security tool may change a record, but its declared input must
2
+ // have no place to carry an authority subject, role or grant. Fail closed on
3
+ // open objects, opaque schemas, references and unbounded schema composition.
4
+ const subject = /(?:^|_)(?:person|people|user|member|owner|sponsor|agent|role|scope|grant|credential|permission|authorit(?:y|ies)|principal|privilege|entitlement|capabilit(?:y|ies)|authorization|identity|consent|token)(?:s|id|ids)?(?:_|$)/;
5
+ const field = name => name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase().replace(/[^a-z0-9]+/g, '_');
6
+ export function recordOnlySchema(schema, depth = 0) {
7
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema) || depth > 32
8
+ || Object.keys(schema).some(key => ['$ref', '$dynamicRef', 'allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else', 'patternProperties', 'dependentSchemas', 'unevaluatedProperties'].includes(key))) return false;
9
+ if (schema.type === 'object') return schema.additionalProperties === false && schema.properties !== null && typeof schema.properties === 'object' && !Array.isArray(schema.properties)
10
+ && Object.entries(schema.properties).every(([name, value]) => !subject.test(field(name)) && recordOnlySchema(value, depth + 1));
11
+ if (schema.type === 'array') return recordOnlySchema(schema.items, depth + 1);
12
+ return ['string', 'boolean', 'number', 'integer', 'null'].includes(schema.type);
13
+ }
14
+ export const recordOnlyAuthority = tool => tool?.authority === 'none' && tool.readOnly === false
15
+ && Array.isArray(tool.classes) && tool.classes.includes('security') && !tool.classes.includes('access')
16
+ && tool.effect?.kind === 'record' && typeof tool.effect.justification === 'string' && tool.effect.justification.trim().length > 0
17
+ && recordOnlySchema(tool.inputSchema);
@@ -0,0 +1,36 @@
1
+ import { createHash, randomUUID, webcrypto } from 'node:crypto';
2
+
3
+ export const CATALOGUE = 'rer-agent-classes/1';
4
+ export function canonical(value) {
5
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
6
+ if (value && typeof value === 'object') return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(',')}}`;
7
+ return JSON.stringify(value);
8
+ }
9
+ export async function signJws(privateKey, kid, typ, payload) {
10
+ const input = [Buffer.from(JSON.stringify({ alg: 'ES256', typ, kid })).toString('base64url'), Buffer.from(JSON.stringify(payload)).toString('base64url')].join('.');
11
+ const signature = await webcrypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, privateKey, new TextEncoder().encode(input));
12
+ return `${input}.${Buffer.from(signature).toString('base64url')}`;
13
+ }
14
+ export function seconds(now) {
15
+ const value = typeof now === 'function' ? now() : now ?? Date.now();
16
+ return Math.floor((value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : value) / 1000);
17
+ }
18
+ export async function accessToken(context, overrides = {}) {
19
+ const iat = seconds(context.now);
20
+ return signJws(context.signer.privateKey, context.signer.kid, 'at+jwt', {
21
+ iss: context.signer.issuer, aud: `${context.origin}/mcp`, sub: context.person.sub, email: context.person.email.toLowerCase(),
22
+ act: { sub: context.agentId, name: 'Agent door conformance', specialist: context.surface.specialist }, client_id: 'rer-agent-conformance',
23
+ scope: [...new Set([...context.surface.tools.map(tool => tool.scope), ...(context.resourceScopes ?? []), 'events:read'])].join(' '), business: context.business,
24
+ consent: context.consent, jti: randomUUID(), iat, exp: iat + 300, ...overrides,
25
+ });
26
+ }
27
+ export const autonomousPolicy = () => ({ schema: 'rer-agent-policy/1', catalogue: CATALOGUE, rules: [{ id: 'all', class: '*', do: 'autonomous' }], spend: { none: true } });
28
+ export const heldPolicy = () => ({ schema: 'rer-agent-policy/1', catalogue: CATALOGUE, rules: [{ id: 'all', class: '*', do: 'approval', approver: ['sponsor'], wait: 'PT1H' }, { id: 'standard', class: 'standard', do: 'review' }], reviewers: ['sponsor'], spend: { none: true } });
29
+ export async function policyEnvelope(context, document, { paused = false, revoked, revision = context.revision + 1, seq = context.seq + 1, ...overrides } = {}) {
30
+ const iat = seconds(context.now);
31
+ const revision_signature = document === null ? null : await signJws(context.signer.privateKey, context.signer.kid, 'rer-agent-policy-revision+jwt', {
32
+ business: context.business, revision, document_sha256: createHash('sha256').update(canonical(document)).digest('hex'),
33
+ });
34
+ const payload = { v: 1, iss: context.signer.issuer, aud: context.origin, sub: context.signer.installationId, business: context.business, seq, revision, paused, catalogue: CATALOGUE, document, revision_signature, iat, exp: iat + 300, ...(revoked === undefined ? {} : { revoked }), ...overrides };
35
+ return { payload, policy: await signJws(context.signer.privateKey, context.signer.kid, 'rer-agent-policy+jwt', payload) };
36
+ }
@@ -0,0 +1,61 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { accessToken } from './crypto.mjs';
3
+ import { narrowingContract } from './narrowing.mjs';
4
+ import { VERSION } from './protocol.mjs';
5
+
6
+ export async function discoverDoor(c) {
7
+ const discover = await c.mcp('server/discover');
8
+ c.add('BASE-AGENT-001.1', discover.status === 200 && discover.result && Array.isArray(discover.result.supportedVersions) && discover.result.supportedVersions.includes(VERSION) && discover.result.supportedVersions.includes('2025-11-25') && discover.result.capabilities && discover.result._meta?.['io.modelcontextprotocol/serverInfo'] && typeof discover.result.instructions === 'string', 'server/discover must identify versions, capabilities, serverInfo and instructions.');
9
+ const limits = discover.result?._meta?.['com.runeditrun/limits'];
10
+ c.add('BASE-AGENT-001.6.limits', Number.isSafeInteger(limits?.requestsPerMinute) && limits.requestsPerMinute > 0 && Number.isSafeInteger(limits?.maxBodyBytes) && limits.maxBodyBytes > 0 && discover.result.instructions.includes(c.surface.specialist), 'Discovery must name the specialist and the capacity limits in force.');
11
+ const foreign = await c.mcp('server/discover', {}, { headers: { Origin: 'https://foreign.invalid' } });
12
+ c.add('BASE-AGENT-001.5.origin', foreign.status === 403, `Foreign Origin returned ${foreign.status}.`);
13
+ const mismatch = await c.mcp('server/discover', {}, { headers: { 'Mcp-Method': 'tools/list' } });
14
+ c.add('BASE-AGENT-001.5.method', mismatch.status === 400 && mismatch.message?.error?.code === -32020, 'A header/body method mismatch must return HeaderMismatch.');
15
+ const unsupported = await c.mcp('server/discover', {}, { version: '2099-01-01' });
16
+ c.add('BASE-AGENT-001.3', unsupported.status === 400 && unsupported.message?.error?.code === -32022 && unsupported.message.error.data?.supported?.includes(VERSION), 'An unsupported version must return UnsupportedProtocolVersion.');
17
+ const metadata = await c.request('/.well-known/oauth-protected-resource/mcp');
18
+ let oauth; try { oauth = await metadata.json(); } catch {}
19
+ c.resourceScopes = Array.isArray(oauth?.scopes_supported) ? oauth.scopes_supported.filter(scope => typeof scope === 'string') : [];
20
+ c.add('BASE-AGENT-004.1.metadata', metadata.ok && oauth?.resource === `${c.origin}/mcp` && oauth.authorization_servers?.includes(c.signer.issuer) && c.surface.tools.every(tool => oauth.scopes_supported?.includes(tool.scope)), 'Resource metadata must identify the canonical MCP resource, trusted issuer and all declared scopes.');
21
+ const oversize = await c.request('/mcp', { method: 'POST', headers: { Authorization: `Bearer ${await accessToken(c)}`, Origin: c.origin, 'Content-Type': 'application/json', 'MCP-Protocol-Version': VERSION, 'Mcp-Method': 'tools/call', 'Mcp-Name': c.surface.witness.tool }, body: JSON.stringify({ jsonrpc: '2.0', id: 9999, method: 'tools/call', params: { name: c.surface.witness.tool, arguments: { oversized: 'x'.repeat(limits?.maxBodyBytes + 1 || 2 * 1024 * 1024) } } }) });
22
+ c.add('BASE-AGENT-001.6', oversize.status === 413, `Oversized body returned ${oversize.status}.`);
23
+ await oversize.body?.cancel();
24
+ }
25
+
26
+ export async function listedDoor(c) {
27
+ const first = await c.mcp('tools/list'), second = await c.mcp('tools/list');
28
+ const tools = first.result?.tools ?? [], names = tools.map(tool => tool.name), expected = c.surface.tools.map(tool => tool.name).sort();
29
+ c.listed = new Map(tools.map(tool => [tool.name, tool]));
30
+ c.add('BASE-AGENT-002.1.registry', isDeepStrictEqual(names, expected), `tools/list differs from surface: actual ${names.join(', ')}, expected ${expected.join(', ')}.`);
31
+ c.add('BASE-AGENT-001.4', isDeepStrictEqual(first.result, second.result) && typeof first.result?.ttlMs === 'number' && first.result.ttlMs >= 0 && first.result.cacheScope === 'private', 'Repeated tools/list results must have deterministic order, ttlMs and private cache scope.');
32
+ for (const declared of c.surface.tools) {
33
+ const tool = c.listed.get(declared.name);
34
+ if (declared.proof) c.add(`BASE-AGENT-004.proof.${declared.name}.declaration`, tool?._meta?.['com.runeditrun/proof'] === declared.proof && tool?._meta?.['com.runeditrun/proof-kind'] === declared.proofKind, `${declared.name} must expose its native proof requirement.`);
35
+ if (declared.widens === false) {
36
+ const { idempotency_key: _key, expected_revision: _revision, ...properties } = tool?.inputSchema?.properties ?? {};
37
+ const schema = { ...tool?.inputSchema, properties, required: tool?.inputSchema?.required?.filter(key => !['idempotency_key', 'expected_revision'].includes(key)) };
38
+ c.add(`BASE-AGENT-005.narrowing.${declared.name}.schema`, narrowingContract({ ...declared, inputSchema: schema }) && tool?._meta?.['com.runeditrun/widens'] === false && isDeepStrictEqual(tool?._meta?.['com.runeditrun/narrowing'], declared.narrowing) && isDeepStrictEqual(schema, declared.inputSchema), `${declared.name} narrowing check requires the runtime's exact closed target-only schema and effect.`);
39
+ }
40
+ if (declared.authority === 'none') c.add(`BASE-AGENT-005.no-subject.schema.${declared.name}`, tool?._meta?.['com.runeditrun/authority'] === 'none' && isDeepStrictEqual(tool?._meta?.['com.runeditrun/effect'], declared.effect) && isDeepStrictEqual(Object.fromEntries(Object.entries(tool?.inputSchema?.properties ?? {}).filter(([key]) => !['idempotency_key', 'expected_revision'].includes(key))), declared.inputSchema.properties), 'No-subject declarations must match the actual runtime schema and record effect.');
41
+ c.add(`BASE-AGENT-002.2.schema.${declared.name}`, tool?.inputSchema?.type === 'object' && tool.outputSchema !== undefined, `${declared.name} must carry input and output schemas.`);
42
+ c.add(`BASE-AGENT-002.3.${declared.name}`, tool?.annotations?.readOnlyHint === declared.readOnly && tool?.annotations?.destructiveHint === declared.classes.includes('destructive') && tool?.annotations?.openWorldHint === declared.classes.includes('external'), `${declared.name} annotations differ from its declared behavior.`);
43
+ c.add(`BASE-AGENT-006.1.${declared.name}`, isDeepStrictEqual([...(tool?._meta?.['com.runeditrun/classes'] ?? [])].sort(), [...declared.classes].sort()) && tool?._meta?.['com.runeditrun/scope'] === declared.scope && isDeepStrictEqual([...(tool?._meta?.['com.runeditrun/clauses'] ?? [])].sort(), [...declared.clauses].sort()), `${declared.name} classes, scope or clauses differ from the Agent surface.`);
44
+ }
45
+ for (const version of [VERSION, '2025-11-25']) {
46
+ const initialized = await c.mcp('initialize', { protocolVersion: version, capabilities: {}, clientInfo: { name: 'rer-agent-conformance', version: '1' } }, { version });
47
+ const listed = await c.mcp('tools/list', {}, { version });
48
+ c.add(`BASE-AGENT-001.2.${version}`, !initialized.headers.has('mcp-session-id') && initialized.result?.protocolVersion === version && isDeepStrictEqual(listed.result?.tools?.map(tool => tool.name), names), `${version} must negotiate and expose the same tools.`);
49
+ }
50
+ const march = await c.mcp('initialize', { protocolVersion: '2025-03-26', capabilities: {} }, { version: '2025-03-26' });
51
+ c.add('BASE-AGENT-001.3.2025-03-26', march.status === 400 && march.message?.error?.code === -32022 && march.message.error.message === 'UnsupportedProtocolVersion', 'March 2025 batching is not implemented; refuse its negotiation explicitly.');
52
+ const templates = await c.mcp('resources/templates/list');
53
+ c.add('BASE-AGENT-003.1', isDeepStrictEqual((templates.result?.resourceTemplates ?? []).map(item => item.uriTemplate).sort(), [...c.surface.resources].sort()), 'resources/templates/list must match the Agent surface.');
54
+ const prompts = await c.mcp('prompts/list');
55
+ c.add('BASE-AGENT-013.5.prompts', Array.isArray(prompts.result?.prompts), 'prompts/list must list the declared specialist prompts.');
56
+ if (prompts.result?.prompts?.length) {
57
+ const prompt = await c.mcp('prompts/get', { name: prompts.result.prompts[0].name });
58
+ c.add('BASE-AGENT-001.1.prompts', Array.isArray(prompt.result?.messages) && prompt.result.messages.length > 0, 'A specialist prompt must be retrievable with Mcp-Name.');
59
+ }
60
+
61
+ }
@@ -0,0 +1,41 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { validateAgentSurface } from './surface.mjs';
3
+ import { createProtocol } from './protocol.mjs';
4
+ import { autonomousPolicy, heldPolicy } from './crypto.mjs';
5
+ import { discoverDoor, listedDoor } from './discovery.mjs';
6
+ import { runJourney } from './journey.mjs';
7
+ import { unsetPolicy, removalPhase, blockedPhases, pausePhase, consentRevocationPhase } from './policy-phases.mjs';
8
+ import { negativePhase } from './negative.mjs';
9
+ import { replayAdmissionPhase } from './replay.mjs';
10
+ import { webhookPhase } from './webhooks.mjs';
11
+ import { recordSecurityPhase } from './security.mjs';
12
+ import { crossSponsorPhase } from './sponsors.mjs';
13
+ import { auditPhase } from './audit.mjs';
14
+ import { invocationPhase } from './invocation.mjs';
15
+
16
+ export { validateAgentSurface } from './surface.mjs';
17
+
18
+ /** Run against a fresh, real installation using its HTTP and person doors. */
19
+ export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney }) {
20
+ const validation = validateAgentSurface(surface), points = [...validation.points];
21
+ if (!validation.ok) return { ok: false, points };
22
+ if (typeof fetch !== 'function' || !signer?.privateKey || !signer.issuer || !signer.installationId || !signer.kid || !person?.email || !person.cookie || typeof person.sub !== 'string' || !person.sub.trim() || typeof consent !== 'string' || !consent.trim() || new URL(origin).origin !== origin) throw new TypeError('Conformance requires fetch, canonical origin, signer, consent and signed-in person {email,cookie,sub}');
23
+ const c = createProtocol({ fetch, origin, surface, signer, person, business, consent, now, prove, points, agentId: `rer-conformance-${randomUUID()}`, seq: 0, revision: 0, listed: new Map() });
24
+ await c.phase('BASE-AGENT-001.transport', () => discoverDoor(c));
25
+ await c.phase('BASE-AGENT-007.phase0', () => unsetPolicy(c, true));
26
+ await c.phase('BASE-AGENT-007.phase1', () => removalPhase(c));
27
+ await c.phase('BASE-AGENT-013.phase2', async () => { await c.adopt(autonomousPolicy()); await listedDoor(c); await runJourney(c, 'autonomous', { injections: true, replay: true }); });
28
+ await c.phase('BASE-AGENT-013.phase3', async () => { await c.adopt(heldPolicy()); await runJourney(c, 'held', { held: true }); });
29
+ await c.phase('BASE-AGENT-007.phase4', () => blockedPhases(c));
30
+ await c.phase('BASE-AGENT-011.phase5', () => pausePhase(c));
31
+ await c.phase('BASE-AGENT-004.phase6', () => negativePhase(c));
32
+ await c.phase('BASE-AGENT-004.consent', () => consentRevocationPhase(c));
33
+ if (invoke) await c.phase('BASE-AGENT-012.invocation', () => invocationPhase(c, invoke));
34
+ if (nativeJourney) await c.phase('BASE-AGENT-013.native-journey', async () => { await nativeJourney({ tool: c.tool }); c.add('BASE-AGENT-013.native-journey', true); });
35
+ if (surface.tools.some(tool => tool.authority === 'none')) await c.phase('BASE-AGENT-005.no-subject', () => recordSecurityPhase(c));
36
+ if (surface.verification?.replayAdmission) await c.phase('BASE-AGENT-012.replay', () => replayAdmissionPhase(c, surface.verification.replayAdmission));
37
+ if (webhooks) await c.phase('BASE-AGENT-006.webhook', () => webhookPhase(c, webhooks));
38
+ await c.phase('BASE-AGENT-009.phase7', () => auditPhase(c));
39
+ if (sponsors.length > 1) await c.phase('BASE-AGENT-004.cross-sponsor', () => crossSponsorPhase(c, sponsors));
40
+ return { ok: points.every(point => point.ok), points };
41
+ }
@@ -0,0 +1,32 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { autonomousPolicy } from './crypto.mjs';
3
+ import { auditRows } from './audit.mjs';
4
+
5
+ /** The adapter drains serialized job input through the edition's real invoke door. */
6
+ export async function invocationPhase(c, invoke) {
7
+ const step = c.surface.journey.find(item => !c.surface.tools.find(tool => tool.name === item.tool)?.readOnly);
8
+ if (!step) throw new Error('Durable invocation conformance requires a mutating journey step.');
9
+ await c.adopt(autonomousPolicy());
10
+ const who = { person: { id: c.sponsor.id }, agent: { id: c.agentId, name: 'Agent door conformance', specialist: c.surface.specialist }, consent: c.consent, scopes: [c.surface.tools.find(tool => tool.name === step.tool).scope] };
11
+ const schedule = () => JSON.stringify({ name: step.tool, args: c.args(step, new Map(), { unresolved: true }), who });
12
+ const run = async saved => {
13
+ const job = JSON.parse(saved), result = await invoke(job.name, job.args, job.who);
14
+ c.calls.push({ kind: 'embedded', name: job.name, args: job.args, decision: result.decision, code: result.code });
15
+ return { job, result };
16
+ };
17
+ const before = await c.witness(), first = await run(schedule()), after = await c.witness();
18
+ c.add('BASE-AGENT-012.invocation-effect', first.result.outcome === 'done' && !isDeepStrictEqual(before, after), 'A serialized invocation under live consent must complete its native effect.');
19
+ const saved = schedule();
20
+ await c.adopt(autonomousPolicy(), { revoked: { agents: [], consents: [c.consent] } });
21
+ const second = await run(saved);
22
+ c.add('BASE-AGENT-012.invocation-revoked', second.result.outcome === 'refused' && second.result.code === 'consent_revoked', 'Final worker admission must refuse the saved originating consent with consent_revoked.');
23
+ const { rows } = await auditRows(c);
24
+ for (const [label, { job, result }] of [['done', first], ['refused', second]]) {
25
+ const row = rows.find(item => item.door === 'embedded' && item.idempotency_key === job.args.idempotency_key);
26
+ c.add(`BASE-AGENT-012.invocation-audit.${label}`, row?.consent === c.consent && row.agent?.id === who.agent.id && row.sponsor?.id === who.person.id
27
+ && row.tool === job.name && row.outcome === result.outcome && row.code === (result.code ?? null) && Number.isFinite(Date.parse(row.at)) && Boolean(row.id)
28
+ && (label !== 'refused' || row.revision === c.revision), 'Durable invocation audit must retain consent, agent, sponsor, tool, time, revision and outcome.');
29
+ }
30
+ await c.adopt(autonomousPolicy());
31
+ c.add('BASE-AGENT-012.invocation-no-effect', isDeepStrictEqual(after, await c.witness()), 'A saved job under revoked consent changed native state.');
32
+ }
@@ -0,0 +1,112 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { classIds, subset, errorCode, APPROVAL } from './protocol.mjs';
4
+ import { grantSet } from './narrowing.mjs';
5
+ import { schemaErrors } from './schema.mjs';
6
+ import { checkTarget } from './target.mjs';
7
+
8
+ export function checkClasses(c, step, answer, phase) {
9
+ const actual = answer.decision?.classes;
10
+ c.add(`BASE-AGENT-006.2.${phase}.${step.id}`, isDeepStrictEqual(classIds(actual), classIds(step.expect)) && step.expect.every(expected => actual?.some(item => item.class === expected.class && subset(item.facts, expected.facts ?? {}))), `${step.tool} computed classes/facts differ from ${step.id}: ${JSON.stringify(actual)}.`);
11
+ }
12
+ function checkOutput(c, step, answer, phase) {
13
+ const schema = c.listed.get(step.tool)?.outputSchema;
14
+ const errors = schema === undefined ? ['missing outputSchema'] : schemaErrors(schema, answer.result?.structuredContent);
15
+ c.add(`BASE-AGENT-002.2.${phase}.${step.id}`, errors.length === 0, `${step.tool} output does not validate: ${errors.slice(0, 8).join('; ')}.`);
16
+ }
17
+ async function checkResources(c, step, answer, phase, held) {
18
+ const links = answer.result?.content?.filter(item => item.type === 'resource_link') ?? [];
19
+ for (const [i, link] of links.entries()) {
20
+ const read = await c.mcp('resources/read', { uri: link.uri });
21
+ const classes = read.decision?.classes, needsApproval = held && classes?.some(item => item.class !== 'standard');
22
+ c.add(`BASE-AGENT-006.2.resource.${phase}.${step.id}.${i}`, Array.isArray(classes) && classes.length > 0 && read.decision.revision === c.revision && classes.every(item => item.do === (held ? item.class === 'standard' ? 'review' : 'approval' : 'autonomous')), `${link.uri} must apply the policy to its computed resource classes.`);
23
+ c.add(`BASE-AGENT-003.4.${phase}.${step.id}.${i}`, read.status === 200 && (needsApproval
24
+ ? errorCode(read) === 'approval_required' && read.decision?.disposition === 'approval' && !read.result?.contents?.length
25
+ : !read.message?.error && read.decision?.disposition === (held ? 'review' : 'autonomous') && Array.isArray(read.result?.contents) && read.result.contents.length > 0), `${step.tool} resource_link ${link.uri} must ${needsApproval ? 'withhold content pending approval' : 'read back under the current policy'}.`);
26
+ if (needsApproval) {
27
+ const pending = read.body?.error?.data?.approval;
28
+ c.add(`BASE-AGENT-007.5.resource.${phase}.${step.id}.${i}`, pending?.id && typeof pending.url === 'string' && new URL(pending.url, c.origin).origin === c.origin && Number.isFinite(Date.parse(pending.expires_at)), `${link.uri} must expose a pending approval on the native person door.`);
29
+ if (pending?.id) {
30
+ const { approval } = await c.personJson(`/agents/api/approvals/${encodeURIComponent(pending.id)}`);
31
+ c.add(`BASE-AGENT-008.5.resource-summary.${phase}.${step.id}.${i}`, approval?.id === pending.id && approval.decision_id === read.decision.id && approval.revision === c.revision && /^[a-f0-9]{64}$/.test(approval.summary_sha256), `${link.uri} pending read must expose its exact summary hash and revision.`);
32
+ }
33
+ }
34
+ }
35
+ }
36
+ export async function runJourney(c, phase, { held = false, injections = false, replay = false } = {}) {
37
+ const outputs = new Map(); let replayed = false;
38
+ try {
39
+ for (const step of c.surface.journey) {
40
+ const args = c.args(step, outputs), needsApproval = held && step.expect.some(item => item.class !== 'standard');
41
+ const narrowing = !held && c.surface.narrowings?.find(fixture => fixture.step === step.id);
42
+ const grantsBefore = narrowing ? await grantSet(c, narrowing.witness, outputs) : null;
43
+ const before = needsApproval ? await c.witness() : undefined;
44
+ const declared = c.surface.tools.find(tool => tool.name === step.tool);
45
+ let proof = {};
46
+ if (declared.proof) {
47
+ if (!held) {
48
+ const original = await c.witness(), challenge = await c.tool(step.tool, args), bogus = await c.tool(step.tool, args, { proofReference: 'bogus-native-proof' });
49
+ const fields = challenge.result?._meta?.['com.runeditrun/error'];
50
+ c.add(`BASE-AGENT-004.native-proof.${step.id}.challenge`, errorCode(challenge) === 'native_proof_required' && fields?.kind === declared.proofKind && typeof fields?.handoff === 'string' && new URL(fields.handoff).origin === c.origin, `${step.tool} requires its named native proof and a local human handoff.`);
51
+ c.add(`BASE-AGENT-004.native-proof.${step.id}.bogus`, errorCode(bogus) === 'native_proof_required' && isDeepStrictEqual(original, await c.witness()), `${step.tool} must refuse bogus proof with no native effect.`);
52
+ proof = await c.proof(step.tool, args, fields?.handoff);
53
+ } else proof = await c.proof(step.tool, args);
54
+ }
55
+ let answer = await c.tool(step.tool, args, proof);
56
+ checkClasses(c, step, answer, phase);
57
+ await checkTarget(c, step, outputs, answer, phase);
58
+ const expectedDisposition = held ? needsApproval ? 'approval' : 'review' : 'autonomous';
59
+ c.add(`BASE-AGENT-007.1.${phase}.${step.id}`, answer.decision?.disposition === expectedDisposition && answer.decision.revision === c.revision && answer.decision.classes.every(item => item.do === (held ? item.class === 'standard' ? 'review' : 'approval' : 'autonomous')), `${step.tool} must receive ${expectedDisposition} under revision ${c.revision}.`);
60
+ if (needsApproval) {
61
+ const approval = answer.result?._meta?.[APPROVAL];
62
+ c.add(`BASE-AGENT-007.5.pending.${step.id}`, answer.result?.resultType === 'input_required' && approval?.id && typeof approval.url === 'string' && new URL(approval.url, c.origin).origin === c.origin && Number.isFinite(Date.parse(approval.expires_at)), `${step.tool} must return a pending handle, URL elicitation and expiry.`);
63
+ const after = await c.witness();
64
+ c.add(`BASE-AGENT-007.5.no-effect.${step.id}`, isDeepStrictEqual(before, after), `${step.tool} changed native state before approval.`);
65
+ if (!approval?.id) continue;
66
+ const approved = await c.decideApproval(answer);
67
+ await checkTarget(c, step, outputs, answer, phase, true);
68
+ c.add(`BASE-AGENT-008.5.approver.${step.id}`, approved.ok, `Signed-in sponsor approval returned HTTP ${approved.status}.`);
69
+ answer = await c.tool(step.tool, args, { ...proof, requestState: answer.result.requestState });
70
+ checkClasses(c, step, answer, `${phase}.approved`);
71
+ c.add(`BASE-AGENT-007.5.receipt.${step.id}`, !answer.result?.isError && answer.result?.resultType !== 'input_required' && Boolean(answer.result?._meta?.['com.runeditrun/receipt']) && answer.decision?.disposition === 'approval', 'The approved retry must complete with an approval receipt.');
72
+ }
73
+ c.add(`BASE-AGENT-013.4.${phase}.${step.id}`, answer.status === 200 && answer.result && !answer.result.isError && answer.result.resultType !== 'input_required', `${step.tool} did not complete (${errorCode(answer) ?? answer.status}).`);
74
+ if (answer.result?.isError || answer.result?.structuredContent === undefined) continue;
75
+ outputs.set(step.id, answer.result.structuredContent);
76
+ checkOutput(c, step, answer, phase);
77
+ await checkResources(c, step, answer, phase, held);
78
+ if (narrowing) {
79
+ c.add(`BASE-AGENT-005.narrowing.${step.tool}.target`, isDeepStrictEqual(c.resolve(narrowing.witness.args, outputs)[declared.narrowing.target], args[declared.narrowing.target]), `${step.tool} must witness the same targeted subject.`);
80
+ const after = await grantSet(c, narrowing.witness, outputs);
81
+ c.add(`BASE-AGENT-005.narrowing.${step.tool}.subset`, after.length < grantsBefore.length && after.every(grant => grantsBefore.includes(grant)), `${step.tool} must strictly reduce the targeted subject's native grant set.`);
82
+ const beforeInjection = await c.witness();
83
+ const smuggled = await c.tool(step.tool, { ...args, idempotency_key: randomUUID(), grant_to_add: 'admin' });
84
+ c.add(`BASE-AGENT-005.narrowing.${step.tool}.undeclared`, errorCode(smuggled) === 'invalid_arguments' && isDeepStrictEqual(beforeInjection, await c.witness()), `${step.tool} must refuse an undeclared widening argument without an effect.`);
85
+ }
86
+ if (!c.surface.tools.find(tool => tool.name === step.tool)?.readOnly) {
87
+ const snapshot = await c.tool(`${c.surface.seed}.events.list`, { limit: 200 });
88
+ if (!Array.isArray(snapshot.result?.structuredContent?.events)) throw new Error('Post-effect events.list must return events');
89
+ (c.effectEvents ??= []).push(...snapshot.result.structuredContent.events);
90
+ }
91
+ if (injections && step.inject) {
92
+ const injected = { ...args, ...c.resolve(step.inject, outputs), ...(!c.surface.tools.find(tool => tool.name === step.tool)?.readOnly ? { idempotency_key: randomUUID() } : {}) };
93
+ const checked = await c.tool(step.tool, injected, proof);
94
+ c.add(`BASE-AGENT-005.5.${phase}.${step.id}`, isDeepStrictEqual(checked.decision?.classes, answer.decision?.classes) && checked.decision?.disposition === answer.decision?.disposition && !checked.result?.isError, `${step.tool} changed class, facts or decision for additional arguments.`);
95
+ }
96
+ if (replay && !replayed && !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly) {
97
+ replayed = true;
98
+ const beforeReplay = await c.witness(), repeated = await c.tool(step.tool, args, proof), afterReplay = await c.witness();
99
+ c.add(`BASE-AGENT-012.1.${phase}`, !repeated.result?.isError && isDeepStrictEqual(answer.result.structuredContent, repeated.result?.structuredContent) && isDeepStrictEqual(beforeReplay, afterReplay), `${step.tool} replay changed native state or returned a different result.`);
100
+
101
+ }
102
+ }
103
+ } finally {
104
+ if (!held) for (const step of c.surface.escalations ?? []) await c.phase(`BASE-AGENT-005.escalation.${step.id}`, async () => {
105
+ const args = c.args(step, outputs), before = await c.witness();
106
+ const answer = await c.tool(step.tool, args), after = await c.witness();
107
+ c.add(`BASE-AGENT-005.1.${step.id}`, errorCode(answer) === 'self_escalation', `${step.tool} must refuse sponsor escalation with self_escalation (${errorCode(answer) ?? answer.status}).`);
108
+ c.add(`BASE-AGENT-005.2.${step.id}`, isDeepStrictEqual(before, after), `${step.tool} changed native state while attempting sponsor escalation.`);
109
+ });
110
+ }
111
+ return outputs;
112
+ }
@@ -0,0 +1 @@
1
+ export function narrowingContract(tool: unknown): boolean
@@ -0,0 +1,21 @@
1
+ /** A closed target-only schema cannot encode a grant to add. Unknown schema
2
+ * constructs fail closed, rather than hiding widening fields in a union/ref. */
3
+ export function narrowingContract(tool) {
4
+ const schema = tool?.inputSchema, target = tool?.narrowing?.target;
5
+ if (tool?.widens !== false || !['revoke', 'narrow'].includes(tool.narrowing?.effect) || typeof target !== 'string'
6
+ || !/^(?:id|[a-z][a-z0-9_]*_id)$/.test(target) || !schema || schema.type !== 'object' || schema.additionalProperties !== false
7
+ || Object.keys(schema).some(key => !['type', 'properties', 'required', 'additionalProperties'].includes(key))
8
+ || !Array.isArray(schema.required) || schema.required.length !== 1 || schema.required[0] !== target
9
+ || !schema.properties || Object.keys(schema.properties).length !== 1) return false;
10
+ const field = schema.properties[target];
11
+ return field?.type === 'string' && Object.keys(field).every(key => ['type', 'minLength', 'maxLength', 'pattern', 'enum', 'description', 'title'].includes(key));
12
+ }
13
+
14
+ export async function grantSet(c, witness, outputs) {
15
+ const answer = await c.tool(witness.tool, c.resolve(witness.args, outputs));
16
+ if (answer.result?.isError) throw new Error('Native grant witness refused');
17
+ let value = answer.result?.structuredContent;
18
+ for (const part of witness.pointer.split('/').slice(1)) value = value?.[part.replace(/~1/g, '/').replace(/~0/g, '~')];
19
+ if (!Array.isArray(value) || value.some(grant => typeof grant !== 'string') || new Set(value).size !== value.length) throw new Error('Native grant witness must return a unique string grant set');
20
+ return value;
21
+ }
@@ -0,0 +1,47 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { webcrypto } from 'node:crypto';
3
+ import { accessToken, autonomousPolicy, policyEnvelope, seconds, signJws } from './crypto.mjs';
4
+ import { errorCode, VERSION } from './protocol.mjs';
5
+
6
+ export async function negativePhase(c) {
7
+ await c.adopt(autonomousPolicy());
8
+ const before = await c.witness(), iat = seconds(c.now);
9
+ const unavailable = await c.mcp('resources/read', { uri: `unregistered://${crypto.randomUUID()}` });
10
+ c.add('BASE-AGENT-003.refusal-code', unavailable.message?.error?.data?.code === 'tool_not_found' && unavailable.result === undefined, 'An unregistered resource must refuse with JSON-RPC error.data.code and no content.');
11
+ const noToken = await c.mcp('tools/list', {}, { token: null });
12
+ c.add('BASE-AGENT-004.1.challenge', noToken.status === 401 && /resource_metadata=/.test(noToken.headers.get('www-authenticate') ?? ''), 'An unauthenticated call must return 401 and a resource_metadata challenge.');
13
+ for (const [name, overrides] of [
14
+ ['audience', { aud: 'https://sibling.invalid/mcp' }],
15
+ ['expired', { iat: iat - 600, exp: iat - 1 }],
16
+ ['lifetime', { iat, exp: iat + 901 }],
17
+ ]) {
18
+ const answer = await c.mcp('tools/list', {}, { token: await accessToken(c, overrides) });
19
+ c.add(`BASE-AGENT-004.${name === 'audience' ? '2' : '3'}.${name}`, answer.status === 401, `${name} token returned HTTP ${answer.status}, expected 401.`);
20
+ }
21
+ const write = c.surface.journey.find(step => !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly);
22
+ if (write) {
23
+ const answer = await c.tool(write.tool, c.args(write, new Map(), { unresolved: true }), { token: await accessToken(c, { scope: 'events:read' }) });
24
+ const needed = c.surface.tools.find(tool => tool.name === write.tool).scope;
25
+ c.add('BASE-AGENT-004.4', answer.status === 403 && errorCode(answer) === 'insufficient_scope' && (answer.headers.get('www-authenticate') ?? '').includes(needed), 'A token missing the write scope must be refused with all needed scopes in its challenge.');
26
+ }
27
+ const queryToken = await accessToken(c);
28
+ const query = await c.request(`/mcp?access_token=${encodeURIComponent(queryToken)}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'MCP-Protocol-Version': VERSION, 'Mcp-Method': 'tools/list' }, body: JSON.stringify({ jsonrpc: '2.0', id: 9876, method: 'tools/list', params: {} }) });
29
+ c.add('BASE-AGENT-004.5', query.status === 401, `A query-string token returned HTTP ${query.status}.`);
30
+ await query.body?.cancel();
31
+ const agentOnPersonDoor = await c.request('/agents/api/pause', { method: 'POST', headers: { Origin: c.origin, Authorization: `Bearer ${await accessToken(c)}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ paused: false }) });
32
+ c.add('BASE-AGENT-008.2.person-door', agentOnPersonDoor.status === 403, `An agent token at a person's pause control returned HTTP ${agentOnPersonDoor.status}.`);
33
+ await agentOnPersonDoor.body?.cancel();
34
+ const state = await c.personJson('/agents/api/state');
35
+ const signed = await policyEnvelope(c, autonomousPolicy());
36
+ const foreignKeys = await webcrypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']);
37
+ const badSignature = await signJws(foreignKeys.privateKey, c.signer.kid, 'rer-agent-policy+jwt', signed.payload);
38
+ const invalid = await c.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy: badSignature }) });
39
+ c.add('BASE-AGENT-007.8.signature', !invalid.ok, 'A policy envelope signed by an untrusted key was accepted.');
40
+ await invalid.body?.cancel();
41
+ const foreignBusiness = await policyEnvelope(c, autonomousPolicy(), { business: 'conformance-foreign-business' });
42
+ const foreign = await c.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy: foreignBusiness.policy }) });
43
+ c.add('BASE-AGENT-007.8.business', !foreign.ok, 'An envelope whose Business does not match its revision signature was accepted.');
44
+ await foreign.body?.cancel();
45
+ c.add('BASE-AGENT-007.8.state', isDeepStrictEqual(state, await c.personJson('/agents/api/state')), 'An invalid envelope changed the adopted policy state or revision.');
46
+ c.add('BASE-AGENT-004.negative-no-effect', isDeepStrictEqual(before, await c.witness()), 'An authentication/person-door/policy-envelope negative changed native state.');
47
+ }
@@ -0,0 +1,86 @@
1
+ import { readFile, realpath, stat } from 'node:fs/promises';
2
+ import { dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { parse } from '../../../edition-authoring/vendor/babel-parser/babel-parser/index.mjs';
4
+
5
+ export class NetworkAdapterError extends Error {}
6
+ const invalid = message => new NetworkAdapterError(`Agent conformance network: ${message}`);
7
+ const contained = (root, path) => {
8
+ const name = relative(root, path);
9
+ return name !== '' && name !== '..' && !name.startsWith(`..${sep}`) && !isAbsolute(name);
10
+ };
11
+
12
+ export function validateNetworkAdapter(config) {
13
+ if (!config || typeof config !== 'object' || Array.isArray(config) ||
14
+ Object.keys(config).some(key => !['module', 'origins'].includes(key)) ||
15
+ typeof config.module !== 'string' || !config.module || isAbsolute(config.module) || config.module.includes('\\') ||
16
+ !Array.isArray(config.origins) || !config.origins.length) {
17
+ throw invalid('verification.network must declare a seed-relative module and a nonempty origins array.');
18
+ }
19
+ const origins = new Set();
20
+ for (const origin of config.origins) {
21
+ let url;
22
+ try { url = new URL(origin); } catch { /* Report only the declaration field, never a credential-bearing URL. */ }
23
+ if (typeof origin !== 'string' || !url || !['http:', 'https:'].includes(url.protocol) || url.origin !== origin || url.username || url.password) {
24
+ throw invalid('verification.network.origins must contain exact HTTP(S) origins without credentials, paths, queries or fragments.');
25
+ }
26
+ if (origins.has(origin)) throw invalid('verification.network.origins must not repeat an origin.');
27
+ origins.add(origin);
28
+ }
29
+ return { module: config.module, origins };
30
+ }
31
+
32
+ function imports(source) {
33
+ let ast;
34
+ try { ast = parse(source, { sourceType: 'module', createImportExpressions: true }); }
35
+ catch { throw invalid('the adapter or a relative helper is not valid ES module JavaScript.'); }
36
+ const pending = [ast], result = [];
37
+ while (pending.length) {
38
+ const node = pending.pop();
39
+ let specifier;
40
+ if (['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration', 'ImportExpression'].includes(node.type) && node.source) {
41
+ if (node.source.type !== 'StringLiteral') throw invalid('adapter imports must use literal relative module paths.');
42
+ specifier = node.source.value;
43
+ }
44
+ if (specifier !== undefined) {
45
+ if (!(specifier.startsWith('./') || specifier.startsWith('../')) || specifier.includes('\\') || specifier.includes('?') || specifier.includes('#')) {
46
+ throw invalid('adapter imports must be relative JavaScript modules; packages, Node APIs and runtime built-ins are unavailable.');
47
+ }
48
+ result.push(specifier);
49
+ }
50
+ for (const value of Object.values(node)) {
51
+ if (Array.isArray(value)) pending.push(...value.filter(item => item && typeof item.type === 'string'));
52
+ else if (value && typeof value.type === 'string') pending.push(value);
53
+ }
54
+ }
55
+ return result;
56
+ }
57
+
58
+ // Supply only snapshotted, checked module bytes to workerd. It has no filesystem
59
+ // loader, so an unresolved or computed import cannot read another host file.
60
+ export async function networkAdapterModules(root, entry) {
61
+ let directory;
62
+ try { directory = await realpath(root); }
63
+ catch { throw invalid('the seed root is unreadable.'); }
64
+ const pending = [resolve(directory, entry)], seen = new Set(), modules = [];
65
+ while (pending.length) {
66
+ const path = pending.shift();
67
+ if (seen.has(path)) continue;
68
+ if (!contained(directory, path) || !['.mjs', '.js'].includes(extname(path))) {
69
+ throw invalid('the adapter and every helper must be .mjs or .js files contained in the seed root.');
70
+ }
71
+ let canonical, contents;
72
+ try {
73
+ canonical = await realpath(path);
74
+ if (!contained(directory, canonical)) throw invalid('an adapter module symlink escapes the seed root.');
75
+ if (!(await stat(canonical)).isFile()) throw invalid('an adapter module is not a regular file.');
76
+ contents = await readFile(canonical, 'utf8');
77
+ } catch (error) {
78
+ if (error instanceof NetworkAdapterError) throw error;
79
+ throw invalid('the declared adapter or a relative helper cannot be read. Use explicit relative .mjs or .js file paths.');
80
+ }
81
+ seen.add(path);
82
+ modules.push({ type: 'ESModule', path, contents });
83
+ pending.push(...imports(contents).map(specifier => resolve(dirname(path), specifier)));
84
+ }
85
+ return { root: directory, modules };
86
+ }
@@ -0,0 +1,46 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join, relative } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { networkAdapterModules, NetworkAdapterError } from './network-modules.mjs';
5
+
6
+ // The adapter runs in its own disposable workerd instance, with neither app
7
+ // bindings nor Node compatibility. Its own fetch can never reach the network.
8
+ export async function isolatedNetworkAdapter(root, entry, deny) {
9
+ const source = await networkAdapterModules(root, entry);
10
+ let mf;
11
+ try {
12
+ const wrangler = createRequire(join(root, 'package.json')).resolve('wrangler/package.json');
13
+ const { Miniflare, convertV4MiniflareOptions = options => options } = await import(pathToFileURL(createRequire(wrangler).resolve('miniflare')));
14
+ // Host control data is carried on a private request header, overwritten on
15
+ // every dispatch and removed before the seed adapter sees its native request.
16
+ // There is no control URL or app binding. Adapter egress is still denied.
17
+ const header = 'x-rer-conformance-fixture', urlHeader = 'x-rer-conformance-url', entry = join(source.root, '__rer_network_entry__.mjs');
18
+ if (source.modules.some(module => module.path === entry)) throw new Error('Reserved network entry');
19
+ const wrapper = { type: 'ESModule', path: entry, contents: `import adapter from ${JSON.stringify('./' + relative(source.root, source.modules[0].path))};
20
+ export default { async fetch(request, env) {
21
+ const encoded = request.headers.get(${JSON.stringify(header)});
22
+ const fixture = encoded ? JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(encoded), char => char.charCodeAt(0)))) : null;
23
+ const url = new URL(request.headers.get(${JSON.stringify(urlHeader)}));
24
+ const headers = new Headers(request.headers); headers.delete(${JSON.stringify(header)}); headers.delete(${JSON.stringify(urlHeader)}); headers.set('host', url.host);
25
+ return adapter.fetch(new Request(url, { method: request.method, headers, redirect: 'manual', ...(!['GET','HEAD'].includes(request.method) ? { body: request.body } : {}) }), { fixture, secrets: env.secrets });
26
+ } };` };
27
+ const options = { host: '127.0.0.1', port: 0, cf: false, unsafeLocalExplorer: false,
28
+ modules: [wrapper, ...source.modules], modulesRoot: source.root, compatibilityDate: '2026-09-01', compatibilityFlags: [],
29
+ bindings: {}, outboundService: deny,
30
+ };
31
+ mf = new Miniflare(convertV4MiniflareOptions(options));
32
+ let loopback = await mf.ready;
33
+ return { fetch: (request, fixture) => {
34
+ const headers = new Headers(request.headers);
35
+ headers.set(header, Buffer.from(JSON.stringify(fixture ?? null)).toString('base64'));
36
+ headers.set(urlHeader, request.url);
37
+ return fetch(loopback, { method: request.method, headers: Object.fromEntries(headers), body: request.body, duplex: 'half', redirect: 'manual' });
38
+ }, provision: async secrets => {
39
+ await mf.setOptions(convertV4MiniflareOptions({ ...options, bindings: { secrets } }));
40
+ loopback = await mf.ready;
41
+ }, close: () => mf.dispose() };
42
+ } catch {
43
+ if (mf) await mf.dispose();
44
+ throw new NetworkAdapterError('Agent conformance network: the adapter could not start in isolated workerd. Check the seed\'s installed wrangler and use Worker-compatible ES modules with a default fetch export; Node APIs and runtime bindings are unavailable.');
45
+ }
46
+ }