@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,75 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { autonomousPolicy } from './crypto.mjs';
3
+ import { errorCode } from './protocol.mjs';
4
+
5
+ export async function unsetPolicy(c, initial = false) {
6
+ const listed = await c.mcp('tools/list');
7
+ c.add(`BASE-AGENT-007.2.${initial ? 'initial' : 'removed'}.list`, isDeepStrictEqual(listed.result?.tools, []), 'An unanswered door must list no tools.');
8
+ if (initial) {
9
+ const inventory = await c.personJson('/agents/api/agents');
10
+ const sponsor = inventory.agents?.find(agent => agent.id === c.agentId)?.sponsor;
11
+ c.add('BASE-AGENT-004.6.sponsor', typeof sponsor?.id === 'string' && sponsor.id.length > 0, 'The native person agents inventory must identify the authenticated agent sponsor.');
12
+ if (!sponsor?.id) throw new Error('Cannot resolve native sponsor ID from the person agents door');
13
+ c.sponsor.id = sponsor.id;
14
+ }
15
+ for (const step of c.surface.journey) {
16
+ // No prior result exists here; unresolved references cannot identify native
17
+ // records. Resolvable calls still retain their computed classification.
18
+ const answer = await c.tool(step.tool, c.args(step, new Map(), { unresolved: true }));
19
+ c.add(`BASE-AGENT-007.2.${initial ? 'initial' : 'removed'}.${step.id}`, errorCode(answer) === 'policy_unset', `${step.tool} must refuse with policy_unset before setup.`);
20
+ }
21
+ }
22
+ export async function removalPhase(c) {
23
+ await c.adopt(autonomousPolicy());
24
+ const before = await c.witness();
25
+ await c.adopt(null);
26
+ await unsetPolicy(c);
27
+ await c.adopt(autonomousPolicy());
28
+ c.add('BASE-AGENT-007.2.unset-no-effect', isDeepStrictEqual(before, await c.witness()), 'Calls under the removed policy changed native state.');
29
+ }
30
+ export async function blockedPhases(c) {
31
+ const nonstandard = [...new Set(c.surface.tools.flatMap(tool => tool.classes))].filter(cls => cls !== 'standard');
32
+ for (const cls of nonstandard) {
33
+ await c.adopt(autonomousPolicy());
34
+ const outputs = new Map();
35
+ for (const step of c.surface.journey) {
36
+ const args = c.args(step, outputs);
37
+ if (step.expect.some(item => item.class === cls)) {
38
+ const policy = autonomousPolicy(); policy.rules.push({ id: `block-${cls}`, class: cls, do: 'blocked' });
39
+ await c.adopt(policy);
40
+ const before = await c.witness(), refused = await c.tool(step.tool, args), after = await c.witness();
41
+ c.add(`BASE-AGENT-007.1.blocked.${cls}.${step.id}`, errorCode(refused) === 'policy_blocked' && refused.decision?.disposition === 'blocked' && refused.decision.revision === c.revision && refused.decision.classes.some(item => item.class === cls && item.do === 'blocked'), `${step.tool} must be blocked by ${cls}.`);
42
+ c.add(`BASE-AGENT-007.1.blocked-no-effect.${cls}.${step.id}`, isDeepStrictEqual(before, after), `${step.tool} changed native state while ${cls} was blocked.`);
43
+ await c.adopt(autonomousPolicy());
44
+ }
45
+ const completed = await c.tool(step.tool, args, await c.proof(step.tool, args));
46
+ if (completed.result?.isError || completed.result?.structuredContent === undefined) throw new Error(`Could not prepare ${step.id} for the ${cls} blocked variant (${errorCode(completed) ?? completed.status})`);
47
+ outputs.set(step.id, completed.result.structuredContent);
48
+ }
49
+ }
50
+ }
51
+ export async function pausePhase(c) {
52
+ await c.adopt(autonomousPolicy());
53
+ const before = await c.witness();
54
+ await c.adopt(autonomousPolicy(), { paused: true });
55
+ for (const tool of c.surface.tools) {
56
+ const step = c.surface.journey.find(item => item.tool === tool.name);
57
+ const paused = await c.tool(tool.name, c.args(step, new Map(), { unresolved: true }));
58
+ c.add(`BASE-AGENT-011.6.pause.${tool.name}`, errorCode(paused) === 'agents_paused', `${tool.name} ran while Business Pause was set.`);
59
+ }
60
+ const state = await c.personJson('/agents/api/state');
61
+ c.add('BASE-AGENT-011.6.person', state.paused?.business === true, 'The signed-in person must still read paused state.');
62
+ await c.adopt(autonomousPolicy());
63
+ c.add('BASE-AGENT-011.6.resume', isDeepStrictEqual(before, await c.witness()), 'Pause calls changed native state, or resume did not restore access.');
64
+ }
65
+
66
+ export async function consentRevocationPhase(c) {
67
+ await c.adopt(autonomousPolicy());
68
+ const before = await c.witness();
69
+ await c.adopt(autonomousPolicy(), { revoked: { agents: [], consents: [c.consent] } });
70
+ const step = c.surface.journey[0];
71
+ const refused = await c.tool(step.tool, c.args(step, new Map(), { unresolved: true }));
72
+ c.add('BASE-AGENT-004.consent-revoked', refused.status === 401, 'A revoked originating consent must refuse the next authenticated call.');
73
+ await c.adopt(autonomousPolicy());
74
+ c.add('BASE-AGENT-004.consent-no-effect', isDeepStrictEqual(before, await c.witness()), 'A call under revoked consent changed native state.');
75
+ }
@@ -0,0 +1,145 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { accessToken, policyEnvelope } from './crypto.mjs';
4
+ import { AGENT_CLASSES } from './surface.mjs';
5
+
6
+ export const VERSION = '2026-07-28';
7
+ export const DECISION = 'com.runeditrun/decision';
8
+ export const ERROR = 'com.runeditrun/error';
9
+ export const APPROVAL = 'com.runeditrun/approval';
10
+ export const subset = (actual, expected) => expected && typeof expected === 'object'
11
+ ? actual !== null && typeof actual === 'object' && Object.entries(expected).every(([key, value]) => subset(actual[key], value))
12
+ : isDeepStrictEqual(actual, expected);
13
+ export const classIds = items => (items ?? []).map(item => typeof item === 'string' ? item : item.class).sort();
14
+ export function errorCode(answer) {
15
+ const error = answer.result?._meta?.[ERROR] ?? answer.message?.error?.data?._meta?.[ERROR] ?? answer.message?.error?.data ?? answer.message?.error;
16
+ return typeof error === 'string' ? error : error?.code ?? answer.body?.code ?? null;
17
+ }
18
+ export function resolveArgs(value, outputs, { unresolved = false, sponsor } = {}) {
19
+ if (Array.isArray(value)) return value.map(item => resolveArgs(item, outputs, { unresolved, sponsor }));
20
+ if (value && typeof value === 'object') {
21
+ if ('$sponsor' in value) {
22
+ const result = sponsor?.[value.$sponsor];
23
+ if (!['id', 'email'].includes(value.$sponsor) || typeof result !== 'string' || !result) throw new Error(`Sponsor reference ${value.$sponsor} is unavailable`);
24
+ return result;
25
+ }
26
+ if ('$from' in value) {
27
+ if (!outputs.has(value.$from)) {
28
+ if (unresolved) return `unresolved-${value.$from}`;
29
+ throw new Error(`Reference ${value.$from} has no structuredContent in this phase`);
30
+ }
31
+ let result = outputs.get(value.$from);
32
+ for (const part of value.pointer.split('/').slice(1)) result = result?.[part.replace(/~1/g, '/').replace(/~0/g, '~')];
33
+ if (result === undefined) throw new Error(`Reference ${value.$from}${value.pointer} is missing`);
34
+ return structuredClone(result);
35
+ }
36
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolveArgs(item, outputs, { unresolved, sponsor })]));
37
+ }
38
+ return value;
39
+ }
40
+ async function responseBody(response) {
41
+ const raw = await response.text();
42
+ if (response.headers.get('content-type')?.includes('text/event-stream')) {
43
+ const messages = raw.split(/\r?\n\r?\n/).map(block => block.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n')).filter(Boolean).map(value => JSON.parse(value));
44
+ return messages.findLast(item => item.id !== undefined) ?? messages.at(-1) ?? {};
45
+ }
46
+ try { return JSON.parse(raw); } catch { return { nonJson: true }; }
47
+ }
48
+
49
+ export function createProtocol(context) {
50
+ let requestId = 0;
51
+ context.calls = [];
52
+ context.sponsor = { email: context.person.email.toLowerCase() };
53
+ context.add = (id, ok, detail) => context.points.push({ id, ok: Boolean(ok), ...(!ok ? { detail: String(detail ?? 'Contract assertion failed') } : {}) });
54
+ context.phase = async (name, fn) => {
55
+ try { await fn(); } catch (error) { context.add(name, false, error.message); }
56
+ };
57
+ context.request = async (path, init = {}) => {
58
+ // A 429 is a capacity refusal, not an action result. Honor only a bounded,
59
+ // explicit Retry-After; never replay an application or policy refusal.
60
+ for (let attempt = 0; ; attempt++) {
61
+ const response = await context.fetch(new URL(path, `${context.origin}/`).href, { redirect: 'manual', ...init });
62
+ if (response.status !== 429) return response;
63
+ const header = response.headers.get('retry-after'), delay = header && /^\d+(?:\.\d+)?$/.test(header) ? Number(header) * 1000 : header ? Date.parse(header) - Date.now() : NaN;
64
+ await response.body?.cancel();
65
+ if (attempt >= 2 || !Number.isFinite(delay) || delay < 0 || delay > 60_000) throw new Error('429 capacity refusal without a bounded Retry-After (maximum 60 seconds, two retries)');
66
+ await new Promise(resolve => setTimeout(resolve, delay));
67
+ }
68
+ };
69
+ context.personRequest = async (path, { headers, ...init } = {}) => context.request(path, { ...init, headers: { Origin: context.origin, Cookie: context.person.cookie, 'Content-Type': 'application/json', ...headers } });
70
+ context.personJson = async path => { const response = await context.personRequest(path); if (!response.ok) throw new Error(`${path}: HTTP ${response.status}`); return responseBody(response); };
71
+ context.decideApproval = async (pending, action = 'approve') => {
72
+ if (!['approve', 'reject'].includes(action)) throw new Error('Approval decision must be approve or reject');
73
+ const handle = pending.result?._meta?.[APPROVAL], path = `/agents/api/approvals/${encodeURIComponent(handle.id)}`;
74
+ const { approval } = await context.personJson(path);
75
+ const valid = approval?.id === handle.id && approval.decision_id === pending.decision?.id && approval.revision === pending.decision?.revision && /^[a-f0-9]{64}$/.test(approval.summary_sha256);
76
+ context.add(`BASE-AGENT-008.5.summary.${handle.id}`, valid, 'The person approval must expose its exact decision, revision and summary SHA-256.');
77
+ if (!valid) throw new Error('Cannot decide an approval without its exact summary evidence');
78
+ const response = await context.personRequest(`${path}/${action}`, { method: 'POST', body: JSON.stringify({ revision: approval.revision, summary_sha256: approval.summary_sha256 }) });
79
+ const body = await responseBody(response);
80
+ if (response.ok && action === 'approve' && body.approval?.state === 'executed') context.calls.push({
81
+ kind: 'approval/execute', name: approval.tool, decision: structuredClone(pending.decision), approvalId: handle.id,
82
+ });
83
+ return { ok: response.ok, status: response.status, body };
84
+ };
85
+ context.mcp = async (method, params = {}, options = {}) => {
86
+ const { token = await accessToken(context), version = VERSION, headers = {}, track = true } = options;
87
+ const id = ++requestId, name = method === 'resources/read' ? params.uri : params.name;
88
+ const response = await context.request('/mcp', { method: 'POST', headers: {
89
+ Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json', Origin: context.origin,
90
+ 'MCP-Protocol-Version': version, 'Mcp-Method': method,
91
+ ...(['tools/call', 'resources/read', 'prompts/get'].includes(method) && name ? { 'Mcp-Name': name } : {}),
92
+ ...(token ? { Authorization: `Bearer ${token}` } : {}), ...headers,
93
+ }, body: JSON.stringify({ jsonrpc: '2.0', id, method, params: version === '2025-11-25' ? params : { ...params, _meta: { 'io.modelcontextprotocol/protocolVersion': version, 'io.modelcontextprotocol/clientCapabilities': { elicitation: { url: {} } }, 'io.modelcontextprotocol/clientInfo': { name: 'rer-agent-conformance', version: '1' }, ...params._meta } } }) });
94
+ const body = await responseBody(response), result = body.result, decision = result?._meta?.[DECISION] ?? body.error?.data?._meta?.[DECISION];
95
+ const answer = { status: response.status, headers: response.headers, body, message: body, result, decision };
96
+ if (['tools/call', 'resources/read'].includes(method) && track && (response.status !== 401 || typeof body.error?.data?.code === 'string')) context.calls.push({
97
+ kind: method, name: method === 'resources/read' ? 'resources/read' : params.name,
98
+ args: structuredClone(method === 'resources/read' ? { uri: params.uri } : params.arguments ?? {}),
99
+ decision: structuredClone(decision ?? null), code: errorCode(answer), result: structuredClone(result),
100
+ approval: structuredClone(result?._meta?.[APPROVAL] ?? body.error?.data?.approval ?? null),
101
+ pending: result?.resultType === 'input_required' || method === 'resources/read' && errorCode(answer) === 'approval_required',
102
+ });
103
+ return answer;
104
+ };
105
+ context.proof = async (name, args, handoff) => {
106
+ const tool = context.surface.tools.find(tool => tool.name === name);
107
+ if (!tool?.proof) return {};
108
+ if (typeof context.prove !== 'function') throw new Error(`${name} requires the seed-declared verification.proof module`);
109
+ const reference = await context.prove({ tool: name, args, kind: tool.proofKind, handoff, origin: context.origin, agentId: context.agentId, request: (path, init) => {
110
+ const url = new URL(path, context.origin);
111
+ if (url.origin !== context.origin) throw new Error('Native proof test request must use the fresh installation origin');
112
+ return context.personRequest(url.href, init);
113
+ } });
114
+ if (typeof reference !== 'string' || !reference) throw new Error('Native proof test hook must return a reference');
115
+ return { proofReference: reference };
116
+ };
117
+ context.tool = (name, args, options) => context.mcp('tools/call', { name, arguments: args, ...(options?.proofReference ? { _meta: { 'com.runeditrun/native-proof': options.proofReference } } : {}), ...(options?.requestState === undefined ? {} : { requestState: options.requestState }) }, options);
118
+ context.resolve = (value, outputs = new Map(), options = {}) => resolveArgs(value, outputs, { ...options, sponsor: context.sponsor });
119
+ context.args = (step, outputs, options) => {
120
+ const args = context.resolve(step.args, outputs, options);
121
+ if (!context.surface.tools.find(tool => tool.name === step.tool)?.readOnly) args.idempotency_key = randomUUID();
122
+ return args;
123
+ };
124
+ context.witness = async () => {
125
+ const answer = await context.tool(context.surface.witness.tool, context.resolve(context.surface.witness.args));
126
+ if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error(`Witness ${context.surface.witness.tool} failed (${errorCode(answer) ?? answer.status})`);
127
+ return answer.result.structuredContent;
128
+ };
129
+ context.adopt = async (document, options = {}) => {
130
+ const signed = await policyEnvelope(context, document, options);
131
+ const response = await context.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy: signed.policy }) });
132
+ const body = await responseBody(response);
133
+ if (!response.ok) throw new Error(`Policy adoption failed: HTTP ${response.status} (${typeof body.code === 'string' ? body.code : 'invalid response'})`);
134
+ context.seq = signed.payload.seq; context.revision = signed.payload.revision; context.document = document;
135
+ const expectedClasses = [...new Set(context.surface.tools.flatMap(tool => tool.classes))];
136
+ const actualClasses = body.door?.classes;
137
+ const validClasses = Array.isArray(actualClasses) && new Set(actualClasses.map(row => row?.class)).size === actualClasses.length && actualClasses.every(row =>
138
+ row && Object.keys(row).sort().join(',') === 'class,tools' && AGENT_CLASSES.includes(row.class) && Array.isArray(row.tools) &&
139
+ isDeepStrictEqual([...row.tools].sort(), context.surface.tools.filter(tool => tool.classes.includes(row.class)).map(tool => tool.name).sort().slice(0, 20))) &&
140
+ expectedClasses.every(cls => actualClasses.some(row => row.class === cls));
141
+ context.add(`BASE-AGENT-007.7.adopt.${context.seq}`, Object.keys(body).sort().join(',') === 'adopted,door' && isDeepStrictEqual(body.adopted, { seq: context.seq, revision: context.revision }) && validClasses, 'Policy answer must contain exactly adopted {seq,revision} and catalogue classes with the exact declared tool mappings; resource-only classes have no tools.');
142
+ return signed;
143
+ };
144
+ return context;
145
+ }
@@ -0,0 +1,38 @@
1
+ import { auditRows } from './audit.mjs';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { accessToken, autonomousPolicy } from './crypto.mjs';
4
+ import { errorCode } from './protocol.mjs';
5
+
6
+ export async function replayAdmissionPhase(c, declaration) {
7
+ if (!Array.isArray(declaration.prepare) || !declaration.prepare.length) throw new Error('replayAdmission.prepare must name preparation journey steps ending in a write.');
8
+ await c.adopt(autonomousPolicy());
9
+ const outputs = new Map(); let call;
10
+ for (const id of declaration.prepare) {
11
+ const step = c.surface.journey.find(step => step.id === id);
12
+ if (!step) throw new Error('Unknown replay preparation step.');
13
+ const args = c.args(step, outputs), answer = await c.tool(step.tool, args);
14
+ if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error('Could not prepare a successful idempotent call.');
15
+ outputs.set(id, answer.result.structuredContent); call = { step, args, answer };
16
+ }
17
+ if (!call.args.idempotency_key) throw new Error('Replay admission must finish preparation with a mutating tool.');
18
+ const before = await c.witness(), repeated = await c.tool(call.step.tool, call.args);
19
+ c.add('BASE-AGENT-012.replay.current', !repeated.result?.isError && isDeepStrictEqual(repeated.result?.structuredContent, call.answer.result.structuredContent) && isDeepStrictEqual(before, await c.witness()), 'An admitted replay must return the saved result without another native effect.');
20
+ await c.adopt(autonomousPolicy(), { paused: true });
21
+ const paused = await c.tool(call.step.tool, call.args);
22
+ c.add('BASE-AGENT-012.replay.paused', errorCode(paused) === 'agents_paused' && paused.result?.structuredContent === undefined, 'A previously successful key must not expose cached content while agents are paused.');
23
+ const rows = await auditRows(c);
24
+ const row = rows.rows?.findLast(row => row.idempotency_key === call.args.idempotency_key);
25
+ c.add('BASE-AGENT-012.replay.audit', row?.code === 'agents_paused' && row.outcome === 'refused' && row.agent?.id === c.agentId && row.sponsor?.id === c.sponsor.id && row.tool === call.step.tool && row.decision === 'paused' && row.revision === c.revision && Number.isFinite(Date.parse(row.at)), 'The refused replay needs its own complete audit with current attribution and policy revision.');
26
+ const blocked = autonomousPolicy(); blocked.rules = [{ id: 'all', class: '*', do: 'blocked' }];
27
+ await c.adopt(blocked);
28
+ const refused = await c.tool(call.step.tool, call.args);
29
+ c.add('BASE-AGENT-012.replay.policy', errorCode(refused) === 'policy_blocked' && refused.result?.structuredContent === undefined, 'Current per-tool policy must run before replay lookup.');
30
+ const held = autonomousPolicy(); held.rules = [{ id: 'all', class: '*', do: 'approval', approver: ['sponsor'], wait: 'PT1H' }];
31
+ await c.adopt(held);
32
+ const approval = await c.tool(call.step.tool, call.args);
33
+ c.add('BASE-AGENT-012.replay.approval', errorCode(approval) === 'approval_required' && approval.result?.structuredContent === undefined, 'A newly required approval cannot be satisfied by an older autonomous result.');
34
+ await c.adopt(autonomousPolicy());
35
+ const missing = await c.tool(call.step.tool, call.args, { token: await accessToken(c, { scope: 'events:read' }) });
36
+ c.add('BASE-AGENT-012.replay.scope', missing.status === 403 && errorCode(missing) === 'insufficient_scope' && missing.result?.structuredContent === undefined, 'Current write scope is required even when the key has a successful outcome.');
37
+ c.add('BASE-AGENT-012.replay.once', isDeepStrictEqual(before, await c.witness()), 'Authority changes and refused replays executed the effect again.');
38
+ }
@@ -0,0 +1,71 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+
3
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const types = { null: value => value === null, object, array: Array.isArray, string: value => typeof value === 'string', boolean: value => typeof value === 'boolean', number: value => typeof value === 'number' && Number.isFinite(value), integer: Number.isSafeInteger };
5
+ const pointer = (root, ref) => ref.split('/').slice(1).reduce((value, key) => value?.[key.replace(/~1/g, '/').replace(/~0/g, '~')], root);
6
+
7
+ /** JSON Schema assertions used by tool output declarations; returns diagnostic paths. */
8
+ export function schemaErrors(schema, value, root = schema, path = '$', depth = 0) {
9
+ if (depth > 100) return [`${path}: schema recursion limit`];
10
+ if (schema === true) return [];
11
+ if (schema === false) return [`${path}: forbidden`];
12
+ if (!object(schema)) return [`${path}: schema must be an object or boolean`];
13
+ const errors = [], add = (ok, detail) => { if (!ok) errors.push(`${path}: ${detail}`); };
14
+ const check = (sub, item = value, at = path) => schemaErrors(sub, item, root, at, depth + 1);
15
+ if ('$ref' in schema) {
16
+ if (typeof schema.$ref !== 'string' || !schema.$ref.startsWith('#')) add(false, 'only local schema references are supported');
17
+ else { const target = schema.$ref === '#' ? root : pointer(root, schema.$ref.slice(1)); if (target === undefined) add(false, `unresolved ${schema.$ref}`); else errors.push(...check(target)); }
18
+ }
19
+ if (schema.type !== undefined) add((Array.isArray(schema.type) ? schema.type : [schema.type]).some(type => Object.hasOwn(types, type) && types[type](value)), `expected ${JSON.stringify(schema.type)}`);
20
+ if (schema.const !== undefined) add(isDeepStrictEqual(value, schema.const), 'const mismatch');
21
+ if (schema.enum) add(schema.enum.some(item => isDeepStrictEqual(item, value)), 'enum mismatch');
22
+ if (schema.allOf) for (const sub of schema.allOf) errors.push(...check(sub));
23
+ if (schema.anyOf) add(schema.anyOf.some(sub => !check(sub).length), 'no anyOf alternative matched');
24
+ if (schema.oneOf) add(schema.oneOf.filter(sub => !check(sub).length).length === 1, 'expected one matching oneOf alternative');
25
+ if (schema.not) add(check(schema.not).length > 0, 'not schema matched');
26
+ if (schema.if) errors.push(...check(!check(schema.if).length ? schema.then ?? true : schema.else ?? true));
27
+ if (typeof value === 'number') {
28
+ if (schema.minimum !== undefined) add(value >= schema.minimum, 'below minimum');
29
+ if (schema.maximum !== undefined) add(value <= schema.maximum, 'above maximum');
30
+ if (typeof schema.exclusiveMinimum === 'number') add(value > schema.exclusiveMinimum, 'below exclusiveMinimum');
31
+ if (typeof schema.exclusiveMaximum === 'number') add(value < schema.exclusiveMaximum, 'above exclusiveMaximum');
32
+ if (schema.multipleOf !== undefined) add(Math.abs(value / schema.multipleOf - Math.round(value / schema.multipleOf)) < Number.EPSILON * 8, 'multipleOf mismatch');
33
+ }
34
+ if (typeof value === 'string') {
35
+ if (schema.minLength !== undefined) add([...value].length >= schema.minLength, 'below minLength');
36
+ if (schema.maxLength !== undefined) add([...value].length <= schema.maxLength, 'above maxLength');
37
+ if (schema.pattern !== undefined) { try { add(new RegExp(schema.pattern, 'u').test(value), 'pattern mismatch'); } catch { add(false, 'invalid schema pattern'); } }
38
+ if (schema.format === 'date-time') add(/^\d{4}-\d{2}-\d{2}T/.test(value) && Number.isFinite(Date.parse(value)), 'invalid date-time');
39
+ if (schema.format === 'email') add(/^[^\s@]+@[^\s@]+$/.test(value), 'invalid email');
40
+ if (schema.format === 'uuid') add(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(value), 'invalid uuid');
41
+ if (schema.format === 'uri') { try { new URL(value); } catch { add(false, 'invalid URI'); } }
42
+ }
43
+ if (Array.isArray(value)) {
44
+ if (schema.minItems !== undefined) add(value.length >= schema.minItems, 'below minItems');
45
+ if (schema.maxItems !== undefined) add(value.length <= schema.maxItems, 'above maxItems');
46
+ if (schema.uniqueItems) add(value.every((item, i) => value.slice(0, i).every(other => !isDeepStrictEqual(item, other))), 'duplicate array items');
47
+ const tuple = schema.prefixItems ?? (Array.isArray(schema.items) ? schema.items : []);
48
+ for (let i = 0; i < value.length; i++) {
49
+ const itemSchema = tuple[i] ?? (Array.isArray(schema.items) ? schema.additionalItems : schema.items);
50
+ if (itemSchema !== undefined) errors.push(...check(itemSchema, value[i], `${path}[${i}]`));
51
+ }
52
+ if (schema.contains) { const count = value.filter(item => !check(schema.contains, item).length).length; add(count >= (schema.minContains ?? 1) && count <= (schema.maxContains ?? Infinity), 'contains count mismatch'); }
53
+ }
54
+ if (object(value)) {
55
+ const keys = Object.keys(value);
56
+ if (schema.minProperties !== undefined) add(keys.length >= schema.minProperties, 'below minProperties');
57
+ if (schema.maxProperties !== undefined) add(keys.length <= schema.maxProperties, 'above maxProperties');
58
+ for (const key of schema.required ?? []) add(Object.hasOwn(value, key), `missing required ${key}`);
59
+ for (const key of keys) {
60
+ const at = `${path}.${key}`, matches = [];
61
+ if (Object.hasOwn(schema.properties ?? {}, key)) matches.push(schema.properties[key]);
62
+ for (const [pattern, sub] of Object.entries(schema.patternProperties ?? {})) { try { if (new RegExp(pattern, 'u').test(key)) matches.push(sub); } catch { add(false, 'invalid patternProperties pattern'); } }
63
+ if (!matches.length && schema.additionalProperties !== undefined) matches.push(schema.additionalProperties);
64
+ for (const sub of matches) errors.push(...check(sub, value[key], at));
65
+ if (schema.propertyNames) errors.push(...check(schema.propertyNames, key, at));
66
+ for (const dependency of schema.dependentRequired?.[key] ?? []) add(Object.hasOwn(value, dependency), `${key} requires ${dependency}`);
67
+ if (schema.dependentSchemas?.[key]) errors.push(...check(schema.dependentSchemas[key]));
68
+ }
69
+ }
70
+ return errors;
71
+ }
@@ -0,0 +1,33 @@
1
+ import { auditRows } from './audit.mjs';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { autonomousPolicy } from './crypto.mjs';
4
+ import { errorCode } from './protocol.mjs';
5
+ import { validateAgentSurface } from './surface.mjs';
6
+
7
+ /** Normal journey phases already require security policy and native approval.
8
+ * This phase checks the explicit no-subject contract and undeclared widening. */
9
+ export async function recordSecurityPhase(c) {
10
+ const tools = c.surface.tools.filter(tool => tool.authority === 'none');
11
+ if (!tools.length) return;
12
+ await c.adopt(autonomousPolicy());
13
+ const outputs = new Map();
14
+ for (const step of c.surface.journey) {
15
+ const prepared = c.args(step, outputs);
16
+ const answer = await c.tool(step.tool, prepared, await c.proof(step.tool, prepared));
17
+ if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error('Could not prepare no-subject security journey.');
18
+ outputs.set(step.id, answer.result.structuredContent);
19
+ if (!tools.some(tool => tool.name === step.tool)) continue;
20
+ const prefix = `BASE-AGENT-005.no-subject.${step.id}`;
21
+ const before = await c.witness(), args = { ...c.args(step, outputs), role: 'owner', scopes: ['*'], person_id: c.sponsor.id };
22
+ const refused = await c.tool(step.tool, args);
23
+ c.add(`${prefix}.undeclared`, errorCode(refused) === 'undeclared_arguments' && refused.result?.structuredContent === undefined, 'A no-subject tool must refuse undeclared widening arguments.');
24
+ c.add(`${prefix}.unchanged`, isDeepStrictEqual(before, await c.witness()), 'An undeclared authority argument changed native state.');
25
+ const rows = await auditRows(c);
26
+ c.add(`${prefix}.audit`, rows.rows?.some(row => row.tool === step.tool && row.authority === 'none' && row.outcome === 'done')
27
+ && rows.rows?.some(row => row.tool === step.tool && row.authority === 'none' && row.code === 'undeclared_arguments'), 'Audit must record the explicit authority class on successful and refused calls.');
28
+ const invalid = structuredClone(c.surface), tool = invalid.tools.find(tool => tool.name === step.tool);
29
+ tool.inputSchema.properties.person_id = { type: 'string' };
30
+ const validation = validateAgentSurface(invalid);
31
+ c.add(`${prefix}.negative-declaration`, !validation.ok && validation.points.some(point => point.id.endsWith(`${step.tool}.authority-none`) && !point.ok), 'A no-subject declaration carrying a person or grant must fail static validation.');
32
+ }
33
+ }
@@ -0,0 +1,68 @@
1
+ import { auditRows } from './audit.mjs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { accessToken, autonomousPolicy } from './crypto.mjs';
5
+ import { createProtocol, errorCode, APPROVAL } from './protocol.mjs';
6
+
7
+ /** Additional principals use real native sessions and signed credentials. All
8
+ * record and approval probes cross the same public doors as the main journey. */
9
+ export async function crossSponsorPhase(c, sponsors) {
10
+ const declaration = c.surface.verification?.crossSponsor;
11
+ if (!declaration || !Array.isArray(declaration.prepare) || !declaration.prepare.length || !declaration.read || !declaration.change) throw new Error('Multiple sponsors require verification.crossSponsor {prepare,read,change} fixtures.');
12
+ for (const person of sponsors.slice(1)) {
13
+ const b = createProtocol({ fetch: c.fetch, origin: c.origin, surface: c.surface, signer: c.signer, person,
14
+ business: c.business, consent: randomUUID(), now: c.now, points: c.points, agentId: `rer-conformance-${randomUUID()}`, seq: c.seq, revision: c.revision, listed: c.listed });
15
+ const prefix = `BASE-AGENT-004.cross-sponsor.${person.label}`;
16
+ await c.adopt(autonomousPolicy());
17
+ b.revision = c.revision;
18
+ await b.mcp('tools/list');
19
+ const inventory = await c.personJson('/agents/api/agents');
20
+ const agent = inventory.agents?.find(item => item.id === b.agentId);
21
+ b.sponsor.id = agent?.sponsor?.id;
22
+ c.add(`${prefix}.binding`, typeof b.sponsor.id === 'string' && b.sponsor.id !== c.sponsor.id, 'Each labelled sponsor must resolve to a distinct active native principal.');
23
+ const outputs = new Map(), ownOutputs = new Map();
24
+ for (const id of declaration.prepare) {
25
+ const step = c.surface.journey.find(item => item.id === id);
26
+ if (!step) throw new Error('crossSponsor.prepare must name journey steps.');
27
+ const a = await c.tool(step.tool, c.args(step, outputs));
28
+ if (a.result?.isError || a.result?.structuredContent === undefined) throw new Error('Could not prepare private native records for cross-sponsor checks.');
29
+ outputs.set(step.id, a.result.structuredContent);
30
+ const own = await b.tool(step.tool, b.args(step, ownOutputs));
31
+ if (own.result?.structuredContent !== undefined) ownOutputs.set(step.id, own.result.structuredContent);
32
+ c.add(`${prefix}.own.${id}`, own.status === 200 && own.result?.structuredContent !== undefined && !own.result.isError, 'The second sponsor must successfully use its own signed agent credential.');
33
+ }
34
+ const before = await c.witness();
35
+ for (const [kind, step] of [['read', declaration.read], ['change', declaration.change]]) {
36
+ const answer = await b.tool(step.tool, b.args(step, outputs));
37
+ c.add(`${prefix}.${kind}`, answer.result?.isError === true && typeof errorCode(answer) === 'string' && answer.result?.structuredContent === undefined, 'The second sponsor must not read or change the first sponsor\'s private record.');
38
+ }
39
+ c.add(`${prefix}.unchanged`, isDeepStrictEqual(before, await c.witness()), 'Cross-sponsor probes changed the first sponsor\'s private native state.');
40
+ const held = autonomousPolicy(); held.rules = [{ id: 'all', class: '*', do: 'approval', approver: ['sponsor'], wait: 'PT1H' }];
41
+ await c.adopt(held);
42
+ const args = c.args(declaration.change, outputs), pending = await c.tool(declaration.change.tool, args), handle = pending.result?._meta?.[APPROVAL];
43
+ c.add(`${prefix}.pending`, pending.result?.resultType === 'input_required' && typeof handle?.id === 'string', 'Cross-sponsor approval must be a real pending native action.');
44
+ if (!handle?.id) throw new Error('No cross-sponsor approval handle.');
45
+ const path = `/agents/api/approvals/${encodeURIComponent(handle.id)}`;
46
+ const view = (await c.personJson(path)).approval;
47
+ const hidden = await b.personRequest(path);
48
+ c.add(`${prefix}.approval-private`, [403, 404].includes(hidden.status), 'Another sponsor\'s person session must not read private approval details.');
49
+ await hidden.body?.cancel();
50
+ const body = JSON.stringify({ revision: view.revision, summary_sha256: view.summary_sha256 });
51
+ const rejected = await b.personRequest(`${path}/approve`, { method: 'POST', body });
52
+ c.add(`${prefix}.approval-person`, [403, 404].includes(rejected.status), 'A second sponsor must not approve the first sponsor\'s action.');
53
+ await rejected.body?.cancel();
54
+ const agentAttempt = await b.request(`${path}/approve`, { method: 'POST', headers: { Origin: c.origin, Authorization: `Bearer ${await accessToken(b)}`, 'Content-Type': 'application/json' }, body });
55
+ c.add(`${prefix}.approval-agent`, agentAttempt.status === 403, 'A second sponsor\'s agent credential cannot act as the first sponsor\'s approver.');
56
+ await agentAttempt.body?.cancel();
57
+ const after = (await c.personJson(path)).approval;
58
+ c.add(`${prefix}.approval-unchanged`, after.state === 'pending' && after.approvals.length === 0, 'Cross-sponsor approval attempts changed its state.');
59
+ await c.decideApproval(pending, 'reject');
60
+ await c.adopt(autonomousPolicy());
61
+ for (const principal of [c, b]) {
62
+ const audit = await auditRows({ ...c, agentId: principal.agentId });
63
+ const row = audit.rows?.findLast(item => item.tool === c.surface.journey.find(step => step.id === declaration.prepare[0]).tool && item.outcome === 'done');
64
+ c.add(`${prefix}.attribution.${principal.person.label ?? 'first'}`, row?.sponsor?.id === principal.sponsor.id && row.agent?.id === principal.agentId && row.label?.includes(agentName(principal, inventory)), 'Native audit attribution must name the acting agent and its own sponsor.');
65
+ }
66
+ }
67
+ }
68
+ const agentName = (principal, inventory) => inventory.agents.find(item => item.id === principal.agentId)?.sponsor?.name ?? principal.person.email;
@@ -0,0 +1,89 @@
1
+ import { recordOnlyAuthority } from './authority.mjs';
2
+ import { narrowingContract } from './narrowing.mjs';
3
+ import { validToolName } from './tool-name.mjs';
4
+
5
+ export const AGENT_CLASSES = Object.freeze(['standard', 'external', 'money', 'commitment', 'accounts', 'gated', 'access', 'security', 'destructive', 'sensitive', 'live']);
6
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ const hasClause = (contract, clause) => typeof clause === 'string' && contract.split(/[^A-Za-z0-9_.-]+/).includes(clause);
8
+ const text = value => typeof value === 'string' && value.trim().length > 0;
9
+
10
+ /** Validate the edition's static declaration without loading application code. */
11
+ export function validateAgentSurface(surface, { contract } = {}) {
12
+ const points = [], add = (id, ok, detail) => points.push({ id: `BASE-AGENT-013.surface.${id}`, ok: Boolean(ok), ...(!ok ? { detail } : {}) });
13
+ add('schema', object(surface) && surface.schema === 'rer-agent-surface/1', 'Agent surface must use schema rer-agent-surface/1.');
14
+ if (!object(surface)) return { ok: false, points };
15
+ add('seed', text(surface.seed) && /^[a-z][a-z0-9-]*$/.test(surface.seed), `Invalid seed ${JSON.stringify(surface.seed)}.`);
16
+ add('specialist', text(surface.specialist), 'Agent surface must name its specialist.');
17
+ add('tools', Array.isArray(surface.tools) && surface.tools.length > 0, 'Agent surface must declare its tools.');
18
+ add('notTools', Array.isArray(surface.notTools), 'Agent surface must declare notTools.');
19
+ add('resources', Array.isArray(surface.resources), 'Agent surface must declare resources.');
20
+ for (const uri of Array.isArray(surface.resources) ? surface.resources : []) add(`resource.${String(uri)}`, text(uri), 'Resource template must be a URI string.');
21
+ add('journey', Array.isArray(surface.journey) && surface.journey.length > 0, 'Agent surface must declare its journey.');
22
+ const escalation = (id, ok, detail) => points.push({ id: `BASE-AGENT-005.surface.${id}`, ok: Boolean(ok), ...(!ok ? { detail } : {}) });
23
+ escalation('escalations', surface.escalations === undefined || Array.isArray(surface.escalations), 'Agent surface must declare its escalations.');
24
+ const tools = new Map(), steps = new Set(), coverage = new Map();
25
+ for (const [i, tool] of (Array.isArray(surface.tools) ? surface.tools : []).entries()) {
26
+ const name = tool?.name, label = text(name) ? name : `tools[${i}]`;
27
+ add(`${label}.name`, validToolName(name, surface.seed) && !tools.has(name), `Malformed, duplicate or foreign-seed tool ${JSON.stringify(name)}.`);
28
+ add(`${label}.scope`, text(tool?.scope), `${label} must declare its scope.`);
29
+ add(`${label}.readOnly`, typeof tool?.readOnly === 'boolean', `${label} must declare readOnly.`);
30
+ add(`${label}.classes`, Array.isArray(tool?.classes) && tool.classes.length > 0 && new Set(tool.classes).size === tool.classes.length && tool.classes.every(cls => AGENT_CLASSES.includes(cls)), `${label} has an empty, duplicate or uncatalogued class: ${JSON.stringify(tool?.classes)}.`);
31
+ if (tool?.sponsorEscalation !== undefined) escalation(`${label}.sponsor-escalation`, typeof tool.sponsorEscalation === 'boolean' && Array.isArray(tool.classes) && tool.classes.some(cls => ['access', 'security'].includes(cls)), `${label} sponsorEscalation must be a boolean on an access or security tool.`);
32
+ if (tool?.authority === 'none') escalation(`${label}.authority-none`, recordOnlyAuthority(tool), `${label} authority:none requires a closed record-only schema and a justified record effect, with no authority-bearing fields.`);
33
+ const clauses = Array.isArray(tool?.clauses) ? tool.clauses : [];
34
+ add(`${label}.clauses`, clauses.length > 0 && clauses.every(text), `${label} must name its contract clauses.`);
35
+ if (contract !== undefined) for (const clause of clauses) add(`${label}.clause.${clause}`, hasClause(contract, clause), `${label} names clause ${clause}, absent from CONTRACT.md.`);
36
+ if (tool?.proof !== undefined || tool?.proofKind !== undefined) add(`${label}.proof`, tool.proof === 'native' && typeof tool.proofKind === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(tool.proofKind), `${label} must declare proof native and its named proofKind.`);
37
+ if (tool?.widens !== undefined || tool?.narrowing !== undefined) escalation(`${label}.narrowing-contract`, tool.widens === false && tool.readOnly === false && tool.classes?.some(cls => ['access', 'security'].includes(cls)) && narrowingContract(tool), `${label} narrowing requires revoke/narrow and a closed target-only string schema.`);
38
+ tools.set(name, tool); coverage.set(name, new Set());
39
+ }
40
+ for (const [i, item] of (Array.isArray(surface.notTools) ? surface.notTools : []).entries()) {
41
+ add(`notTools.${i}`, object(item) && ['device', 'screen', 'connector', 'import-door', 'installation'].includes(item.reason) && Array.isArray(item.clauses) && item.clauses.length > 0 && item.clauses.every(text), `notTools[${i}] must name clauses and a concrete reason other than risk.`);
42
+ if (contract !== undefined && Array.isArray(item?.clauses)) for (const clause of item.clauses) add(`notTools.${i}.${clause}`, hasClause(contract, clause), `notTools[${i}] names clause ${clause}, absent from CONTRACT.md.`);
43
+ }
44
+ const references = (value, visit) => {
45
+ if (Array.isArray(value)) value.forEach(item => references(item, visit));
46
+ else if (object(value)) { if ('$from' in value || '$sponsor' in value) visit(value); else Object.values(value).forEach(item => references(item, visit)); }
47
+ };
48
+ const checkReferences = (value, label, available, addPoint = add) => references(value, ref => {
49
+ if ('$sponsor' in ref) addPoint(`${label}.sponsor`, Object.keys(ref).length === 1 && ['id', 'email'].includes(ref.$sponsor), `${label} must reference the sponsor as {$sponsor:'id'} or {$sponsor:'email'}.`);
50
+ else addPoint(`${label}.ref.${ref.$from}`, available.has(ref.$from) && typeof ref.pointer === 'string' && (ref.pointer === '' || ref.pointer.startsWith('/')), `${label} references ${ref.$from} before its structuredContent is available, or has an invalid JSON pointer.`);
51
+ });
52
+ for (const [i, step] of (Array.isArray(surface.journey) ? surface.journey : []).entries()) {
53
+ const id = text(step?.id) ? step.id : `journey[${i}]`, tool = tools.get(step?.tool);
54
+ add(`journey.${id}`, object(step) && text(step.id) && !steps.has(step.id) && Boolean(tool) && object(step.args) && Array.isArray(step.expect) && step.expect.length > 0, `Invalid or duplicate journey step ${id}, tool ${JSON.stringify(step?.tool)}.`);
55
+ const expect = Array.isArray(step?.expect) ? step.expect : [];
56
+ add(`journey.${id}.classes`, new Set(expect.map(item => item?.class)).size === expect.length && expect.every(item => object(item) && Array.isArray(tool?.classes) && tool.classes.includes(item.class) && (item.facts === undefined || object(item.facts))), `${id} expects duplicate, undeclared or malformed classes.`);
57
+ for (const item of expect) coverage.get(step?.tool)?.add(item?.class);
58
+ checkReferences(step?.args, `journey.${id}`, steps);
59
+ if (step?.target !== undefined) {
60
+ const target = step.target;
61
+ add(`journey.${id}.target`, object(target) && Object.keys(target).sort().join(',') === 'id,kind' && text(target.kind) && (text(target.id) || object(target.id) && ('$from' in target.id || '$sponsor' in target.id)), `${id}.target must contain only a nonempty kind and an id string or journey reference.`);
62
+ checkReferences(target, `journey.${id}.target`, steps);
63
+ }
64
+ if (step?.inject !== undefined) add(`journey.${id}.inject`, object(step.inject), `${id}.inject must be an object of additional arguments.`);
65
+ checkReferences(step?.inject, `journey.${id}.inject`, steps);
66
+ steps.add(step?.id);
67
+ }
68
+ const escalationIds = new Set(), escalationTools = new Set();
69
+ for (const [i, step] of (Array.isArray(surface.escalations) ? surface.escalations : []).entries()) {
70
+ const id = text(step?.id) ? step.id : `escalations[${i}]`, tool = tools.get(step?.tool);
71
+ escalation(id, object(step) && text(step.id) && !escalationIds.has(step.id) && Boolean(tool) && object(step.args), `Invalid or duplicate escalation ${id}, tool ${JSON.stringify(step?.tool)}.`);
72
+ escalation(`${id}.authority`, Array.isArray(tool?.classes) && tool.classes.some(cls => ['access', 'security'].includes(cls)) && tool.widens !== false && tool.sponsorEscalation !== false, `${id} must exercise a tool declared capable of widening its sponsor's authority.`);
73
+ checkReferences(step?.args, `escalations.${id}`, steps, escalation);
74
+ escalationIds.add(step?.id); escalationTools.add(step?.tool);
75
+ }
76
+ const narrowingTools = new Set();
77
+ for (const [i, fixture] of (Array.isArray(surface.narrowings) ? surface.narrowings : []).entries()) {
78
+ const tool = tools.get(fixture?.tool), witness = fixture?.witness;
79
+ escalation(`narrowing.${i}`, tool?.widens === false && !narrowingTools.has(fixture.tool) && steps.has(fixture.step) && surface.journey.some(step => step.id === fixture.step && step.tool === fixture.tool) && tools.get(witness?.tool)?.readOnly === true && object(witness?.args) && Object.hasOwn(witness.args, tool.narrowing?.target) && typeof witness?.pointer === 'string' && (witness.pointer === '' || witness.pointer.startsWith('/')), 'Narrowing fixture must name its journey step and a native target grant-set witness.');
80
+ checkReferences(witness?.args, `narrowing.${i}.witness`, steps, escalation);
81
+ narrowingTools.add(fixture?.tool);
82
+ }
83
+ for (const [name, tool] of tools) if (Array.isArray(tool?.classes) && tool.classes.some(cls => ['access', 'security'].includes(cls))) escalation(`${name}.coverage`, tool.authority === 'none' && recordOnlyAuthority(tool) || (tool.widens === false ? narrowingTools.has(name) : tool.sponsorEscalation === false || escalationTools.has(name)), `${name} has no ${tool.widens === false ? 'narrowing check' : 'sponsor escalation fixture'}.`);
84
+ for (const [name, tool] of tools) for (const cls of Array.isArray(tool?.classes) ? tool.classes : []) add(`${name}.coverage.${cls}`, coverage.get(name).has(cls), `${name} has no journey fixture for declared class ${cls}.`);
85
+ add('events', tools.has(`${surface.seed}.events.list`), `Declare built-in ${surface.seed}.events.list in the Agent surface.`);
86
+ add('witness', object(surface.witness) && tools.get(surface.witness.tool)?.readOnly === true && object(surface.witness.args), 'witness must name a declared readOnly tool and arguments.');
87
+ checkReferences(surface.witness?.args, 'witness', new Set());
88
+ return { ok: points.every(point => point.ok), points };
89
+ }
@@ -0,0 +1,18 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { APPROVAL } from './protocol.mjs';
3
+
4
+ export const targetIdentity = value => value !== null && typeof value === 'object' && !Array.isArray(value)
5
+ && Object.keys(value).sort().join() === 'id,kind' && [value.kind, value.id].every(item => typeof item === 'string' && item.trim().length);
6
+
7
+ /** A journey expectation comes from native fixture state, never tool arguments alone. */
8
+ export async function checkTarget(c, step, outputs, answer, phase, execution = false) {
9
+ if (!step.target) return;
10
+ const expected = c.resolve(step.target, outputs), { rows } = await c.personJson(`/agents/api/audit?agent=${encodeURIComponent(c.agentId)}`);
11
+ const row = execution ? rows.findLast(row => row.decision_id === answer.decision?.id) : rows.find(row => row.id === answer.decision?.id);
12
+ c.add(`BASE-AGENT-009.target.${phase}.${step.id}${execution ? '.execution' : ''}`, targetIdentity(expected) && isDeepStrictEqual(row?.resource, expected), `${step.tool} must audit its resolved native kind and id: ${JSON.stringify(row?.resource)} != ${JSON.stringify(expected)}.`);
13
+ const approval = answer.result?._meta?.[APPROVAL];
14
+ if (approval?.id && !execution) {
15
+ const view = await c.personJson(`/agents/api/approvals/${encodeURIComponent(approval.id)}`);
16
+ c.add(`BASE-AGENT-008.target.${phase}.${step.id}`, isDeepStrictEqual(view.approval?.summary?.nativeTarget, expected), `${step.tool} must bind the resolved native target into its approval summary.`);
17
+ }
18
+ }
@@ -0,0 +1 @@
1
+ export function validToolName(name: unknown, seed: string): boolean;
@@ -0,0 +1,7 @@
1
+ // One grammar for declaration validation, runtime registration and MCP exposure.
2
+ // MCP tool names are limited to 128 ASCII letters, digits, underscores, dots or
3
+ // hyphens. The seed prefix retains the existing seed-id grammar.
4
+ export function validToolName(name, seed) {
5
+ return typeof name === 'string' && name.length <= 128 &&
6
+ /^[a-z][a-z0-9-]*\.[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/.test(name) && name.split('.')[0] === seed;
7
+ }
@@ -0,0 +1,30 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { autonomousPolicy } from './crypto.mjs';
3
+
4
+ export async function webhookPhase(c, webhooks) {
5
+ await c.adopt(autonomousPolicy());
6
+ const outputs = new Map();
7
+ for (const id of webhooks.prepare) {
8
+ const step = c.surface.journey.find(step => step.id === id);
9
+ if (!step) throw new Error('Webhook preparation must name existing journey steps.');
10
+ const answer = await c.tool(step.tool, c.args(step, outputs));
11
+ if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error('Could not prepare native webhook records.');
12
+ outputs.set(id, answer.result.structuredContent);
13
+ }
14
+ const requests = await webhooks.requests({ origin: c.origin, outputs });
15
+ for (const kind of ['valid', 'invalid']) {
16
+ const request = requests?.[kind];
17
+ if (!request || new URL(request.url).origin !== c.origin || request.method !== 'POST') throw new Error('Webhook probes must be POST requests to the disposable installation origin.');
18
+ }
19
+ const before = await c.witness();
20
+ const invalid = requests.invalid;
21
+ const denied = await c.request(invalid.url, { method: invalid.method, headers: Object.fromEntries(invalid.headers), body: await invalid.arrayBuffer() });
22
+ c.add('BASE-AGENT-006.webhook.invalid', [401, 403].includes(denied.status), 'The seed must refuse an inbound webhook signed with the wrong per-install key.');
23
+ await denied.body?.cancel();
24
+ c.add('BASE-AGENT-006.webhook.unchanged', isDeepStrictEqual(before, await c.witness()), 'A wrongly signed inbound webhook changed native state.');
25
+ const valid = requests.valid;
26
+ const accepted = await c.request(valid.url, { method: valid.method, headers: Object.fromEntries(valid.headers), body: await valid.arrayBuffer() });
27
+ c.add('BASE-AGENT-006.webhook.valid', accepted.ok, 'The seed must accept the inbound webhook signed with its own per-install random key.');
28
+ await accepted.body?.cancel();
29
+ c.add('BASE-AGENT-006.webhook.effect', !isDeepStrictEqual(before, await c.witness()), 'The accepted inbound webhook must retain its native effect.');
30
+ }