@runeditrun/rer 0.2.94 → 0.2.96

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 (71) hide show
  1. package/README.md +16 -2
  2. package/cli/README.md +5 -1
  3. package/cli/agent-door.mjs +4 -0
  4. package/cli/agent-journey-fixtures.mjs +1 -1
  5. package/cli/authoring.mjs +1 -1
  6. package/cli/business/carry-files.mjs +142 -0
  7. package/cli/business/carry.mjs +37 -83
  8. package/cli/business/choices.mjs +17 -8
  9. package/cli/business/connect.mjs +6 -5
  10. package/cli/business/invocation.mjs +3 -2
  11. package/cli/business/local-commands.mjs +6 -6
  12. package/cli/business/questions.mjs +4 -1
  13. package/cli/business/state.mjs +4 -1
  14. package/cli/checkout-folders.mjs +14 -0
  15. package/cli/checkout-preparation.mjs +83 -0
  16. package/cli/contract.mjs +1 -1
  17. package/cli/door-clauses.mjs +29 -2
  18. package/cli/hosted-output.mjs +14 -3
  19. package/cli/hosted-queue-producers.mjs +43 -0
  20. package/cli/jsonc.mjs +1 -115
  21. package/cli/parse.mjs +1 -1
  22. package/cli/portability-migrations.mjs +2 -12
  23. package/edition-authoring/archive-source.mjs +86 -1
  24. package/edition-authoring/base-copies.mjs +15 -45
  25. package/edition-authoring/cli.mjs +1 -1
  26. package/edition-authoring/edition-migrations.mjs +2 -2
  27. package/edition-authoring/module-closure.mjs +119 -50
  28. package/edition-authoring/module-packages.mjs +12 -5
  29. package/edition-authoring/module-syntax.mjs +13 -50
  30. package/edition-authoring/runtime-dependencies.mjs +4 -4
  31. package/foundation/runtime/contract-docs.mjs +1 -1
  32. package/global/CHANGELOG.md +70 -0
  33. package/global/README.md +16 -2
  34. package/global/cli/layout.mjs +3 -0
  35. package/global/launch/facts.mjs +1 -29
  36. package/global/launch/state.mjs +3 -6
  37. package/global/list.mjs +9 -15
  38. package/modules/agent-door/CLAUSES.md +12 -0
  39. package/modules/agent-door/conformance/audit.mjs +22 -4
  40. package/modules/agent-door/conformance/discovery.mjs +32 -1
  41. package/modules/agent-door/conformance/erasure.mjs +103 -0
  42. package/modules/agent-door/conformance/index.mjs +13 -4
  43. package/modules/agent-door/conformance/journey.mjs +19 -1
  44. package/modules/agent-door/conformance/policy-phases.mjs +34 -1
  45. package/modules/agent-door/conformance/protocol.mjs +13 -3
  46. package/modules/agent-door/conformance/relay.mjs +63 -0
  47. package/modules/agent-door/conformance/unpair.mjs +47 -0
  48. package/modules/deploy-kit/jsonc.mjs +115 -0
  49. package/modules/deploy-kit/migration-directory.mjs +16 -0
  50. package/modules/deploy-kit/prepare.mjs +1 -1
  51. package/modules/deploy-kit/templates.mjs +9 -4
  52. package/modules/erasure/cascade.mjs +4 -4
  53. package/modules/erasure/index.d.mts +1 -1
  54. package/modules/erasure/index.mjs +1 -1
  55. package/modules/import-kit/src/d1/README.md +16 -1
  56. package/modules/import-kit/src/d1/preserved-reverse.ts +5 -2
  57. package/modules/import-kit/src/d1/read-fence.ts +14 -2
  58. package/modules/import-kit/src/d1/reverse.ts +4 -1
  59. package/modules/import-kit/src/d1/sets.ts +8 -0
  60. package/modules/import-kit/src/d1/snapshot-text.ts +68 -0
  61. package/modules/import-kit/src/d1/undo-report.ts +4 -1
  62. package/modules/import-kit/src/door/ADOPTING.md +9 -4
  63. package/modules/portability/README.md +28 -2
  64. package/modules/portability/bookkeeping.mjs +8 -4
  65. package/modules/portability/checkout-history.mjs +12 -6
  66. package/modules/portability/import.mjs +1 -1
  67. package/modules/portability/storage.mjs +7 -1
  68. package/modules/portability/worker-history.d.mts +1 -1
  69. package/modules/portability/worker-history.mjs +1 -1
  70. package/onboarding/operator-migrations.mjs +5 -1
  71. package/package.json +1 -1
@@ -40,35 +40,7 @@ export async function needsInstall(root, last) {
40
40
  return false;
41
41
  }
42
42
 
43
- // A checkout is set up when its pin's describe says so (`local.prepared`, from
44
- // rer-cli-2); for older pins, when its primary private settings file holds
45
- // anything. The pin's describe names it (`local.settings`, where the pin has it).
46
- export async function hasSettings(root, described) {
47
- if (typeof described?.local?.prepared === 'boolean') return described.local.prepared;
48
- const primary = described?.local?.settings?.[0] ?? '.dev.vars';
49
- try { return (await stat(join(root, primary))).size > 0; } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
50
- }
51
-
52
- // Every pin's setup saves its answers file only once it has finished, so a
53
- // file newer than this launcher's record of its own attempt (its start for
54
- // 'running', its end for 'failed') is a setup that finished after it.
55
- async function finishedSince(root, described, at) {
56
- const saved = await mtime(join(root, described?.local?.installerState ?? '.seed/installer', 'setup-answers.json'));
57
- return saved !== undefined && typeof at === 'number' && saved > at;
58
- }
59
-
60
- // Setup runs on a checkout with no saved settings ('fresh'). When a setup this
61
- // launcher started did not finish ('running' after a kill, or 'failed') and no
62
- // setup has finished since, it runs again ('resume') and keeps what the earlier
63
- // attempt saved. A checkout set up any other way is never set up again.
64
- // A checkout that is not prepared but already holds an owner (a setting a newer
65
- // manifest added is missing) resumes too, so the saved owner and origin are
66
- // kept; one without a saved owner gets the local owner ('fresh').
67
- export async function setupNeeded(root, described, last) {
68
- if (!await hasSettings(root, described)) return described?.local?.ownerSaved === true ? 'resume' : 'fresh';
69
- if (!last || last.state === 'done') return undefined;
70
- return await finishedSince(root, described, last.at) ? undefined : 'resume';
71
- }
43
+ export { hasSettings, setupNeeded } from '../../cli/checkout-preparation.mjs';
72
44
 
73
45
  // Only a positive listener observation justifies saying another process took it.
74
46
  export async function portTaken(port) {
@@ -9,16 +9,13 @@
9
9
  // server.json that server's PID and start time, and the process rer spawned
10
10
  // stop.json when rer dev --stop last ran: a launch requested before it stops
11
11
  // pin-install.json the process installing the checkout's pinned rer package
12
- import { createHash } from 'node:crypto';
13
12
  import { appendFile, link, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
14
- import { basename, join } from 'node:path';
13
+ import { join } from 'node:path';
15
14
  import { processInfo } from '../../modules/job-queue/processes.mjs';
16
15
  import { serversDirectory } from '../registry.mjs';
17
16
 
18
- export function launchPath(checkout, env = process.env) {
19
- const name = basename(checkout).toLowerCase().replace(/[^a-z0-9-]+/g, '-').slice(0, 40) || 'checkout';
20
- return join(serversDirectory(env), 'launches', `${name}-${createHash('sha256').update(checkout).digest('hex').slice(0, 12)}`);
21
- }
17
+ import { launchPath } from '../../cli/checkout-preparation.mjs';
18
+ export { launchPath };
22
19
 
23
20
  export async function launchDirectory(checkout, env = process.env) {
24
21
  const directory = launchPath(checkout, env);
package/global/list.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  // rer list [DIR] [--json]: the immediate subfolders of DIR that hold an
2
2
  // OPERATIONS.json, newest change first, with what rer dev can do for each.
3
3
  import { execFile } from 'node:child_process';
4
- import { readdir, realpath, stat } from 'node:fs/promises';
4
+ import { realpath, stat } from 'node:fs/promises';
5
5
  import { join, resolve } from 'node:path';
6
6
  import { promisify } from 'node:util';
7
- import { descriptorProfile, dispatcher, pinnedPackage } from './checkout.mjs';
7
+ import { descriptorProfile } from './checkout.mjs';
8
8
  import { liveServers } from './registry.mjs';
9
- import { describeCheckout, setupNeeded } from './launch/facts.mjs';
10
- import { launchPath, setupState } from './launch/state.mjs';
9
+ import { checkoutPreparation } from '../cli/checkout-preparation.mjs';
10
+ import { checkoutFolders } from '../cli/checkout-folders.mjs';
11
11
 
12
12
  const run = promisify(execFile);
13
13
  const reasons = {
@@ -27,12 +27,10 @@ async function entry(path, running) {
27
27
  if (!result.launchable) result.reason = reasons[facts.profile] ?? `OPERATIONS.json is version ${facts.version ?? '(none)'}, which rer does not run`;
28
28
  result.prepared = null;
29
29
  if (profile === 'first-party') {
30
- // Set up: saved settings, and no setup a launch started left unfinished. A
31
- // checkout whose pinned rer package is not installed yet has never been
32
- // launched: rer dev installs it first.
33
- if (pinnedPackage(path)?.ready === false) result.prepared = false;
34
- else try { result.prepared = !await setupNeeded(path, await describeCheckout(path, dispatcher(path).entry, process.env), await setupState.read(launchPath(path))); }
35
- catch (failure) { result.launchable = false; result.reason = `rer describe fails here: ${failure.message.split('\n')[0]}`; }
30
+ const status = await checkoutPreparation(path);
31
+ result.prepared = status.prepared;
32
+ if (status.reason) result.reason = status.reason;
33
+ if (status.prepared === null) result.launchable = false;
36
34
  }
37
35
  result.url = running.get(path) ?? null;
38
36
  result.changedAt = new Date(await changed(path)).toISOString();
@@ -45,11 +43,7 @@ export async function listCommand(args) {
45
43
  let directory;
46
44
  try { directory = await realpath(resolve(positional[0] ?? '.')); } catch { process.stderr.write(`rer list: ${resolve(positional[0] ?? '.')} is not a folder.\n`); return 3; }
47
45
  const running = new Map((await liveServers()).map(record => [record.checkout, record.url]));
48
- const folders = [];
49
- for (const item of await readdir(directory, { withFileTypes: true })) {
50
- const path = join(directory, item.name);
51
- try { if ((await stat(path)).isDirectory() && (await stat(join(path, 'OPERATIONS.json'))).isFile()) folders.push(await realpath(path)); } catch {}
52
- }
46
+ const folders = await checkoutFolders(directory);
53
47
  const checkouts = [];
54
48
  for (let i = 0; i < folders.length; i += 4) checkouts.push(...await Promise.all(folders.slice(i, i + 4).map(path => entry(path, running))));
55
49
  checkouts.sort((a, b) => b.changedAt.localeCompare(a.changedAt) || a.name.localeCompare(b.name));
@@ -7,6 +7,18 @@ requirements proves no implementation. New Status rows start missing; later
7
7
  syncs retain the seed's status, evidence and gap, including a newer judgment.
8
8
  MCP method names below use spaced slashes; wire names omit those spaces.
9
9
 
10
+ Native subject erasure under BASE-DATA-003 overrides the personal fields and
11
+ payload replay described in BASE-AGENT-009 and BASE-AGENT-012. Keep value-free
12
+ decision fields and the existing audit sequence plus the native erasure
13
+ tombstone; in-window replay refuses without executing or echoing erased payload.
14
+ Installation-private keyed legacy replay aliases replace erased personal keys
15
+ only until the call's replay horizon: the fixed 30-day `REPLAY_WINDOW_MS` after
16
+ completion where no horizon exists. Delete aliases with their call at expiry.
17
+ An old key after expiry is a new request under current authorization and cannot
18
+ recover the erased value. Aliases never enter archives, exports or restore.
19
+ The adoption guide defines the map, native transaction and restore custody.
20
+ This clarification does not promote any clause judgment.
21
+
10
22
  ## Target clauses
11
23
 
12
24
  ### Agent surface (Base-delivered)
@@ -4,6 +4,7 @@ import { classIds } from './protocol.mjs';
4
4
  import { AGENT_CLASSES } from './surface.mjs';
5
5
  import { targetIdentity } from './target.mjs';
6
6
  import { auditRows } from './audit-rows.mjs';
7
+ import { redactedAudit, redactedReview } from './erasure.mjs';
7
8
 
8
9
  export { auditRows } from './audit-rows.mjs';
9
10
 
@@ -66,9 +67,21 @@ function continuationRows(c, rows, differs, report = () => {}) {
66
67
  }
67
68
 
68
69
  export async function auditPhase(c) {
69
- const { rows, differs } = await auditRows(c), expected = [...c.calls];
70
- const reviews = expected.some(call => call.decision?.disposition === 'review') ? (await c.personJson('/agents/api/reviews')).reviews : [];
70
+ const snapshot = await auditRows(c), differs = snapshot.differs, expected = [...c.calls];
71
+ const rows = snapshot.rows.map(row => {
72
+ if (!row.tombstone) return row;
73
+ const original = c.erasureEvidence?.get(row.id);
74
+ c.add(`BASE-AGENT-009.erasure.${row.id}`, redactedAudit(row, original), 'Native erasure must retain the exact audit sequence and value-free decision/outcome while removing personal evidence.');
75
+ return original ?? row;
76
+ });
77
+ let reviews = expected.some(call => call.decision?.disposition === 'review') ? (await c.personJson('/agents/api/reviews')).reviews : [];
71
78
  if (!Array.isArray(reviews)) throw new Error('Reviews API must return reviews');
79
+ reviews = reviews.map(review => {
80
+ if (!review.tombstone) return review;
81
+ const original = c.erasureReviews?.get(review.id);
82
+ c.add(`BASE-AGENT-009.4.erasure.${review.id}`, redactedReview(review, original), 'An erased review must remain present with its value-free outcome and no personal payload.');
83
+ return original ?? review;
84
+ });
72
85
  const continuations = continuationRows(c, rows, differs, c.add);
73
86
  c.add('BASE-AGENT-009.1.count', rows.length === expected.length + continuations.size, `Expected exactly ${expected.length} audit rows for tool calls, resource reads and approval executions plus ${continuations.size} native continuations, found ${rows.length}.`);
74
87
  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.');
@@ -82,11 +95,16 @@ export async function auditPhase(c) {
82
95
  for (const [index, call] of expected.entries()) {
83
96
  const principal = call.principal ?? { agent: { id: c.agentId, specialist: c.surface.specialist }, consent: c.consent, sponsor: c.sponsor.id };
84
97
  const candidates = perAgent.get(principal.agent.id) ?? [], decision = call.decision;
85
- const match = candidates.findIndex(row => call.kind === 'approval/execute' ? row.decision_id === decision?.id && row.id !== decision?.id
98
+ const match = candidates.findIndex(row => call.auditId ? row.id === call.auditId : call.kind === 'approval/execute' ? row.decision_id === decision?.id && row.id !== decision?.id
86
99
  : decision?.id ? row.id === decision.id : row.tool === call.name && row.decision_id === null && row.door === (call.kind === 'embedded' ? 'embedded' : 'mcp') && row.code === (call.code ?? null));
87
100
  const row = match < 0 ? undefined : candidates.splice(match, 1)[0];
88
101
  const ordered = row && positions.get(row) > (previous.get(principal.agent.id) ?? -1);
89
102
  if (row) previous.set(principal.agent.id, positions.get(row));
103
+ if (call.erasure) {
104
+ c.add(`BASE-AGENT-009.1.call.${index}.erased`, ordered && isDeepStrictEqual(row, call.erasure) && redactedAudit(row)
105
+ && row.tool === call.name && row.agent.id === principal.agent.id, 'The erasing call must retain its own ordered, value-free admission audit.');
106
+ continue;
107
+ }
90
108
  c.add(`BASE-AGENT-009.1.call.${index}`, ordered && row.tool === call.name && row.consent === principal.consent && row.agent?.id === principal.agent.id && row.agent?.specialist === principal.agent.specialist && row.sponsor?.id === principal.sponsor && (!call.principal || row.client_id === principal.clientId && row.agent?.name === principal.agent.name) && 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.`);
91
109
  if (!row) continue;
92
110
  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.`);
@@ -122,7 +140,7 @@ export async function auditPhase(c) {
122
140
  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.');
123
141
  for (const type of ['policy.adopted', 'approval.pending', 'approval.decided']) {
124
142
  const applicable = type === 'policy.adopted' || rows.some(row => row.approval);
125
- if (applicable) c.add(`BASE-AGENT-010.6.${type}`, events.some(event => event.type === type), `Missing ${type} event.`);
143
+ if (applicable) c.add(`BASE-AGENT-010.6.${type}`, [...events, ...c.effectEvents ?? []].some(event => event.type === type), `Missing ${type} event while readable, including before native erasure.`);
126
144
  }
127
145
  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));
128
146
  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.');
@@ -4,7 +4,38 @@ import { accessToken } from './crypto.mjs';
4
4
  import { narrowingContract } from './narrowing.mjs';
5
5
  import { VERSION } from './protocol.mjs';
6
6
 
7
+ async function protocolCompatibility(c) {
8
+ const token = await accessToken(c);
9
+ const raw = async (method, credential, version, headers = {}, bodyVersion = version ?? '2025-06-18') => {
10
+ const response = await c.request('/mcp', { method: 'POST', headers: {
11
+ Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json', Origin: c.origin,
12
+ ...(credential ? { Authorization: `Bearer ${credential}` } : {}),
13
+ ...(version ? { 'MCP-Protocol-Version': version } : {}), ...headers,
14
+ }, body: JSON.stringify({ jsonrpc: '2.0', id: 9001, method, params: method === 'initialize' ? { protocolVersion: bodyVersion, capabilities: {}, clientInfo: { name: 'rer-agent-conformance', version: '1' } } : {} }) });
15
+ return { status: response.status, headers: response.headers, body: await response.json() };
16
+ };
17
+ for (const method of ['initialize', 'server/discover', 'tools/list', 'tools/call']) {
18
+ for (const credential of [null, 'synthetic-invalid-token']) {
19
+ for (const version of [null, '2025-06-18', VERSION, '2099-01-01']) {
20
+ const answer = await raw(method, credential, version, { 'Mcp-Method': 'synthetic/mismatch' });
21
+ c.add(`BASE-AGENT-004.1.auth-first.${method}.${credential ? 'invalid' : 'missing'}.${version ?? 'no-header'}`, answer.status === 401 && answer.headers.get('www-authenticate') === `Bearer resource_metadata="${c.origin}/.well-known/oauth-protected-resource/mcp"` && answer.body.error?.code === -32001, 'Missing or invalid credentials must get the resource-metadata challenge before version or method-header validation.');
22
+ }
23
+ }
24
+ }
25
+ for (const version of ['2025-06-18', '2025-11-25', VERSION]) {
26
+ // Exercise each body-only initialize without requiring modern transport metadata.
27
+ const initialized = await raw('initialize', token, null, {}, version);
28
+ c.add(`BASE-AGENT-001.2.body-version.${version}`, initialized.status === 200 && initialized.body.result?.protocolVersion === version, 'Authenticated initialize must negotiate a supported body version without a version header.');
29
+ }
30
+ const listed = await raw('tools/list', token, null), explicit = await raw('tools/list', token, '2025-06-18');
31
+ c.add('BASE-AGENT-001.2.no-version-header', listed.status === 200 && explicit.status === 200 && isDeepStrictEqual(listed.body.result, explicit.body.result), 'A stateless request without a version header must use the oldest supported version.');
32
+ const unsupported = await raw('initialize', token, '2099-01-01');
33
+ const data = unsupported.body.error?.data;
34
+ c.add('BASE-AGENT-001.3.explanation', unsupported.status === 400 && unsupported.body.error?.code === -32022 && data?.requested === '2099-01-01' && [VERSION, '2025-11-25', '2025-06-18'].every(version => data?.supported?.includes(version) && data?.message?.includes(version)), 'An unsupported version must name the supported versions in a plain-language error.');
35
+ }
36
+
7
37
  export async function discoverDoor(c) {
38
+ await protocolCompatibility(c);
8
39
  const discover = await c.mcp('server/discover');
9
40
  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.');
10
41
  const limits = discover.result?._meta?.['com.runeditrun/limits'];
@@ -43,7 +74,7 @@ export async function listedDoor(c) {
43
74
  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.`);
44
75
  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.`);
45
76
  }
46
- for (const version of [VERSION, '2025-11-25']) {
77
+ for (const version of [VERSION, '2025-11-25', '2025-06-18']) {
47
78
  const initialized = await c.mcp('initialize', { protocolVersion: version, capabilities: {}, clientInfo: { name: 'rer-agent-conformance', version: '1' } }, { version });
48
79
  const listed = await c.mcp('tools/list', {}, { version });
49
80
  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.`);
@@ -0,0 +1,103 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { auditRows } from './audit-rows.mjs';
3
+ import { classIds, errorCode } from './protocol.mjs';
4
+
5
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
6
+ const text = value => typeof value === 'string' && value.trim().length > 0;
7
+ const outcome = value => ({ done: 'executed', refused: 'denied', pending: 'held', running: 'held', replayed: 'executed', failed: 'failed' })[value];
8
+ export const tombstone = value => object(value) && Object.keys(value).sort().join() === 'at,erasure_id'
9
+ && text(value.erasure_id) && Number.isFinite(Date.parse(value.at));
10
+
11
+ /** Observe original evidence through the person door before a destructive call
12
+ * can redact it. These snapshots stay in this disposable verifier, never in the
13
+ * installation. Final verification still checks every retained row in order. */
14
+ export async function beforeDestruction(c, name) {
15
+ if (!c.document || c.adoptedPolicy?.paused || !c.surface.tools.find(tool => tool.name === name)?.classes.includes('destructive')) return;
16
+ if (c.surface.tools.some(tool => tool.name === `${c.surface.seed}.events.list`)) {
17
+ const events = await c.tool(`${c.surface.seed}.events.list`, { limit: 200 });
18
+ if (!Array.isArray(events.result?.structuredContent?.events)) throw new Error('Pre-erasure events must be readable');
19
+ (c.effectEvents ??= []).push(...events.result.structuredContent.events);
20
+ }
21
+ const snapshot = await auditRows(c), reviews = await c.personJson('/agents/api/reviews');
22
+ if (!Array.isArray(reviews.reviews) || snapshot.differs !== 0) throw new Error('Pre-erasure audit or review evidence is invalid');
23
+ c.erasureEvidence ??= new Map(); c.erasureReviews ??= new Map();
24
+ for (const row of snapshot.rows) if (!row.tombstone) c.erasureEvidence.set(row.id, structuredClone(row));
25
+ for (const review of reviews.reviews) if (review.code !== 'subject_erased' && !review.tombstone) c.erasureReviews.set(review.id, structuredClone(review));
26
+ return new Set(snapshot.rows.map(row => row.id));
27
+ }
28
+
29
+ /** A tombstone is a different, closed evidence shape, not an exemption from
30
+ * audit. Preserve sequence, tool, classes, decision and outcome; forbid every
31
+ * original target, fact, person, key, trace, rule and approval/review payload. */
32
+ export function redactedAudit(row, original) {
33
+ const keys = 'agent,approval,at,classes,code,decision,id,idempotency_key,ignored_arguments,organisation_id,outcome,replay_of,resource,review,role,rules,scopes,sequence,sponsor,tombstone,tool,trace';
34
+ const valid = object(row) && Object.keys(row).sort().join() === keys && tombstone(row.tombstone)
35
+ && Number.isSafeInteger(row.sequence) && row.sequence > 0 && text(row.id) && text(row.tool) && Number.isFinite(Date.parse(row.at))
36
+ && object(row.agent) && Object.keys(row.agent).join() === 'id' && text(row.agent.id)
37
+ && Array.isArray(row.classes) && row.classes.every(item => object(item) && Object.keys(item).join() === 'class' && text(item.class))
38
+ && new Set(classIds(row.classes)).size === row.classes.length
39
+ && ['executed', 'denied', 'held', 'failed'].includes(row.outcome) && text(row.decision)
40
+ && (row.code === null || text(row.code)) && (row.role === null || text(row.role))
41
+ && (row.organisation_id === null || text(row.organisation_id))
42
+ && isDeepStrictEqual(row.sponsor, { id: '', name: '' }) && [row.scopes, row.rules, row.ignored_arguments].every(value => isDeepStrictEqual(value, []))
43
+ && [row.approval, row.review, row.resource, row.idempotency_key, row.trace ?? null, row.replay_of].every(value => value === null);
44
+ if (!valid || !original) return valid;
45
+ return row.id === original.id && row.sequence === original.sequence && row.at === original.at && row.tool === original.tool
46
+ && row.agent.id === original.agent.id && row.role === (original.role ?? null) && row.code === (original.code ?? null)
47
+ && row.decision === original.decision && row.outcome === outcome(original.outcome)
48
+ && isDeepStrictEqual(classIds(row.classes), classIds(original.classes));
49
+ }
50
+
51
+ export function redactedReview(row, original) {
52
+ return original && Object.keys(row).sort().join() === 'agent,classes,code,id,organisation_id,outcome,role,state,tombstone,tool'
53
+ && tombstone(row.tombstone) && row.id === original.id && row.tool === original.tool && row.code === null
54
+ && object(row.agent) && Object.keys(row.agent).join() === 'id' && text(row.agent.id)
55
+ && (row.role === null || text(row.role)) && (row.organisation_id === null || text(row.organisation_id))
56
+ && Array.isArray(row.classes) && row.classes.every(text) && isDeepStrictEqual(classIds(row.classes), classIds(original.classes))
57
+ && row.state === ({ open: 'executed', reviewed: 'executed', flagged: 'executed', undone: 'executed', undoing: 'held' })[original.state]
58
+ // Saved review inputs carry no execution outcome. Its retained marker stays
59
+ // held; the separate review state preserves executed/reviewed/flagged/undone.
60
+ && row.outcome === 'held';
61
+ }
62
+
63
+ export async function erasedCall(c, before, name, marker, decision) {
64
+ if (!before) throw new Error('Erasure needs pre-effect evidence');
65
+ const after = await auditRows(c), added = after.rows.filter(row => !before.has(row.id));
66
+ const row = added.length === 1 ? added[0] : undefined;
67
+ marker ??= row?.tombstone;
68
+ if (!row || !redactedAudit(row) || row.tool !== name || !isDeepStrictEqual(row.tombstone, marker)
69
+ || row.agent.id !== c.agentId || row.outcome !== 'held' || row.code !== null
70
+ || decision && (row.decision !== decision.disposition || !isDeepStrictEqual(classIds(row.classes), classIds(decision.classes)))) throw new Error('Erasure must retain exactly its ordered, value-free admission audit');
71
+ (c.erasedAdmissions ??= new Map()).set(marker.erasure_id, row);
72
+ return row;
73
+ }
74
+
75
+ export async function erasedAnswer(c, answer, before, name) {
76
+ if (errorCode(answer) !== 'subject_erased') return;
77
+ const marker = answer.result?._meta?.['com.runeditrun/error']?.tombstone;
78
+ if (!tombstone(marker) || answer.status !== 200 || !answer.result?.isError || answer.decision != null
79
+ || answer.result.structuredContent !== undefined || Object.keys(answer.result._meta).sort().join() !== 'com.runeditrun/decision,com.runeditrun/error'
80
+ || Object.keys(answer.result._meta['com.runeditrun/error']).sort().join() !== 'code,tombstone'
81
+ || !isDeepStrictEqual(answer.result.content, [{ type: 'text', text: JSON.stringify({ code: 'subject_erased', tombstone: marker }) }])) throw new Error('Erased results must expose only subject_erased and its tombstone');
82
+ const known = c.erasedAdmissions?.get(marker.erasure_id);
83
+ if (known) {
84
+ const after = await auditRows(c);
85
+ if (!before || after.rows.some(row => !before.has(row.id)) || !isDeepStrictEqual(known.tombstone, marker)) throw new Error('Erased replay must not append an audit or expose new evidence');
86
+ answer.erasure = known;
87
+ return false;
88
+ }
89
+ answer.erasure = await erasedCall(c, before, name, marker);
90
+ return true;
91
+ }
92
+
93
+ export async function erasedStep(c, step, args, answer, phase, outputs) {
94
+ const row = answer.erasure;
95
+ c.add(`BASE-AGENT-006.2.${phase}.${step.id}.erased`, redactedAudit(row) && isDeepStrictEqual(classIds(row.classes), classIds(step.expect)), 'Erasure must retain exactly the computed class identifiers and no personal facts.');
96
+ c.add(`BASE-AGENT-007.1.${phase}.${step.id}.erased`, row.decision === (phase === 'held' ? 'approval' : 'autonomous'), 'Erasure must retain the admitted policy disposition.');
97
+ const before = await c.witness(), replay = await c.stepTool(step, args), after = await c.witness();
98
+ c.add(`BASE-AGENT-012.1.${phase}.${step.id}.erased`, errorCode(replay) === 'subject_erased' && isDeepStrictEqual(replay.erasure?.tombstone, row.tombstone)
99
+ && isDeepStrictEqual(before, after), 'An erased key must refuse with the same value-free tombstone and no further native effect.');
100
+ const value = { tombstone: row.tombstone };
101
+ outputs.set(step.id, value);
102
+ return value;
103
+ }
@@ -7,19 +7,21 @@ import { createProtocol } from './protocol.mjs';
7
7
  import { autonomousPolicy, heldPolicy } from './crypto.mjs';
8
8
  import { discoverDoor, listedDoor } from './discovery.mjs';
9
9
  import { runJourney } from './journey.mjs';
10
- import { unsetPolicy, removalPhase, blockedPhases, pausePhase, consentRevocationPhase } from './policy-phases.mjs';
10
+ import { unsetPolicy, removalPhase, blockedPhases, pausePhase, consentRevocationPhase, agentRevocationPhase } from './policy-phases.mjs';
11
+ import { unpairPhase } from './unpair.mjs';
11
12
  import { negativePhase } from './negative.mjs';
12
13
  import { replayAdmissionPhase } from './replay.mjs';
13
14
  import { webhookPhase } from './webhooks.mjs';
14
15
  import { recordSecurityPhase } from './security.mjs';
15
16
  import { crossSponsorPhase } from './sponsors.mjs';
16
- import { auditPhase } from './audit.mjs';
17
+ import { auditPhase, auditRows } from './audit.mjs';
18
+ import { relayPhase } from './relay.mjs';
17
19
  import { invocationPhase } from './invocation.mjs';
18
20
 
19
21
  export { validateAgentSurface } from './surface.mjs';
20
22
 
21
23
  /** Run against a fresh, real installation using its HTTP and person doors. */
22
- export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney, nativeStep, prepare, initializeAgent }) {
24
+ export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney, nativeStep, prepare, initializeAgent, unpair }) {
23
25
  const validation = validateAgentSurface(surface), points = [...validation.points];
24
26
  if (!validation.ok) return { ok: false, points };
25
27
  const capabilities = capabilitySet(surface.capabilities);
@@ -34,7 +36,11 @@ export async function runAgentDoorConformance({ fetch, invoke, origin, surface,
34
36
  }
35
37
  }
36
38
  await c.phase('BASE-AGENT-001.transport', () => discoverDoor(c));
37
- await c.phase('BASE-AGENT-007.phase0', () => unsetPolicy(c, true));
39
+ await c.phase('BASE-AGENT-007.phase0', async () => {
40
+ await unsetPolicy(c, true);
41
+ // No Business envelope existed for these audits, so they cannot be relayed.
42
+ c.unattributedAuditIds = new Set((await auditRows(c, { agents: [null], includeFixtures: true })).rows.map(row => row.id));
43
+ });
38
44
  await c.phase('BASE-AGENT-007.phase1', () => removalPhase(c));
39
45
  await c.phase('BASE-AGENT-013.phase2', async () => { await c.adopt(autonomousPolicy()); await c.prepare('autonomous'); await listedDoor(c); await runJourney(c, 'autonomous', { injections: true, replay: true }); });
40
46
  await c.phase('BASE-AGENT-013.phase3', async () => { await c.prepare('held'); await c.adopt(heldPolicy()); await runJourney(c, 'held', { held: true }); });
@@ -42,6 +48,7 @@ export async function runAgentDoorConformance({ fetch, invoke, origin, surface,
42
48
  await c.phase('BASE-AGENT-011.phase5', () => pausePhase(c));
43
49
  await c.phase('BASE-AGENT-004.phase6', () => negativePhase(c));
44
50
  await c.phase('BASE-AGENT-004.consent', () => consentRevocationPhase(c));
51
+ await c.phase('BASE-AGENT-004.6.seed', () => agentRevocationPhase(c, initializeAgent));
45
52
  if (invoke) await c.phase('BASE-AGENT-012.invocation', () => invocationPhase(c, invoke));
46
53
  if (nativeJourney) await c.phase('BASE-AGENT-013.native-journey', async () => { await nativeJourney({ tool: c.tool }); c.add('BASE-AGENT-013.native-journey', true); });
47
54
  if (surface.tools.some(tool => tool.authority === 'none')) await c.phase('BASE-AGENT-005.no-subject', () => recordSecurityPhase(c));
@@ -50,6 +57,8 @@ export async function runAgentDoorConformance({ fetch, invoke, origin, surface,
50
57
  await c.phase('BASE-AGENT-subset.refusals', () => refusalPhase(c));
51
58
  if (capabilities.mode === 'declared' && offers(surface.capabilities, 'subscriptions')) await c.phase('BASE-AGENT-subset.subscriptions', () => subscriptionPhase(c));
52
59
  await c.phase('BASE-AGENT-009.phase7', () => auditPhase(c));
60
+ await c.phase('BASE-AGENT-009.relay', () => relayPhase(c));
53
61
  if (sponsors.length > 1) await c.phase('BASE-AGENT-004.cross-sponsor', () => crossSponsorPhase(c, sponsors, initializeAgent));
62
+ if (unpair) await c.phase('BASE-AGENT-004.7', () => unpairPhase(c, unpair, sponsors));
54
63
  return { ok: points.every(point => point.ok), points, capabilities };
55
64
  }
@@ -7,6 +7,7 @@ import { schemaErrors } from './schema.mjs';
7
7
  import { checkTarget } from './target.mjs';
8
8
  import { nativeStepHook } from './step-hooks.mjs';
9
9
  import { injectionArgs } from './injection.mjs';
10
+ import { erasedStep } from './erasure.mjs';
10
11
 
11
12
  export function checkClasses(c, step, answer, phase) {
12
13
  const actual = answer.decision?.classes;
@@ -81,6 +82,11 @@ export async function runJourney(c, phase, { held = false, injections = false, r
81
82
  } else proof = await c.proof(step.tool, args, undefined, step.client);
82
83
  }
83
84
  let answer = await c.stepTool(step, args, proof);
85
+ if (answer.erasure) {
86
+ const value = await erasedStep(c, step, args, answer, phase, outputs);
87
+ await nativeStepHook(c, 'afterStep', phase, step, args, outputs, value);
88
+ continue;
89
+ }
84
90
  checkClasses(c, step, answer, phase);
85
91
  await checkTarget(c, step, outputs, answer, phase);
86
92
  const expectedDisposition = held ? needsApproval ? 'approval' : 'review' : 'autonomous';
@@ -95,6 +101,13 @@ export async function runJourney(c, phase, { held = false, injections = false, r
95
101
  await checkTarget(c, step, outputs, answer, phase, true);
96
102
  c.add(`BASE-AGENT-008.5.approver.${step.id}`, approved.ok, `Signed-in sponsor approval returned HTTP ${approved.status}.`);
97
103
  answer = await c.stepTool(step, args, { ...proof, requestState: answer.result.requestState });
104
+ if (answer.erasure) {
105
+ c.add(`BASE-AGENT-007.5.receipt.${step.id}.erased`, approved.erasure?.decision === 'approval' && isDeepStrictEqual(approved.erasure.tombstone, answer.erasure.tombstone)
106
+ && approved.body.approval.code === 'subject_erased' && isDeepStrictEqual(approved.body.approval.summary, {}) && approved.body.approval.summary_sha256 === '', 'An approved erasure must redact its exact saved approval and refuse payload replay with the matching tombstone.');
107
+ const value = await erasedStep(c, step, args, answer, phase, outputs);
108
+ await nativeStepHook(c, 'afterStep', phase, step, args, outputs, value);
109
+ continue;
110
+ }
98
111
  const receipt = answer.result?._meta?.['com.runeditrun/receipt'];
99
112
  // Older receipts carry only the original id; their current decision's
100
113
  // computed facts may change after the effect.
@@ -125,8 +138,13 @@ export async function runJourney(c, phase, { held = false, injections = false, r
125
138
  }
126
139
  if (injections && step.inject) {
127
140
  const injected = await injectionArgs(c, step, outputs, args);
141
+ const inputSchema = c.listed.get(step.tool)?.inputSchema ?? declared.inputSchema;
142
+ const undeclaredNarrowing = declared.widens === false && Object.keys(injected).some(key => key !== 'idempotency_key' && !Object.hasOwn(inputSchema?.properties ?? {}, key));
143
+ // A cached mutation still rejects undeclared narrowing input before replay.
144
+ const beforeInjection = undeclaredNarrowing ? await c.witness() : undefined;
128
145
  const checked = await c.stepTool(step, injected, proof);
129
- 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.`);
146
+ if (undeclaredNarrowing) c.add(`BASE-AGENT-005.5.${phase}.${step.id}`, errorCode(checked) === 'invalid_arguments' && isDeepStrictEqual(beforeInjection, await c.witness()), `${step.tool} must refuse undeclared narrowing arguments as invalid_arguments without changing native state, including on replay.`);
147
+ else 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.`);
130
148
  }
131
149
  if (replay && !replayed && !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly) {
132
150
  replayed = true;
@@ -1,8 +1,10 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
2
  import { webcrypto } from 'node:crypto';
3
- import { autonomousPolicy, policyEnvelope, signJws, seconds } from './crypto.mjs';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { accessToken, autonomousPolicy, policyEnvelope, signJws, seconds } from './crypto.mjs';
4
5
  import { errorCode } from './protocol.mjs';
5
6
  import { nativeStepHook } from './step-hooks.mjs';
7
+ import { erasedStep } from './erasure.mjs';
6
8
 
7
9
  export async function unsetPolicy(c, initial = false) {
8
10
  const listed = await c.mcp('tools/list');
@@ -90,6 +92,11 @@ export async function blockedPhases(c) {
90
92
  await c.adopt(autonomousPolicy());
91
93
  }
92
94
  const completed = await c.stepTool(step, args, await c.proof(step.tool, args, undefined, step.client));
95
+ if (completed.erasure) {
96
+ const value = await erasedStep(c, step, args, completed, `blocked:${cls}`, outputs);
97
+ await nativeStepHook(c, 'afterStep', `blocked:${cls}`, step, args, outputs, value);
98
+ continue;
99
+ }
93
100
  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})`);
94
101
  outputs.set(step.id, completed.result.structuredContent);
95
102
  await nativeStepHook(c, 'afterStep', `blocked:${cls}`, step, args, outputs, completed.result.structuredContent);
@@ -123,3 +130,29 @@ export async function consentRevocationPhase(c) {
123
130
  await c.adopt(autonomousPolicy());
124
131
  c.add('BASE-AGENT-004.consent-no-effect', isDeepStrictEqual(before, await c.witness()), 'A call under revoked consent changed native state.');
125
132
  }
133
+
134
+ /** The installation's own revocation ends an agent's Business tokens: a fresh token for the same agent is refused. */
135
+ export async function agentRevocationPhase(c, initializeAgent) {
136
+ await c.adopt(autonomousPolicy());
137
+ await c.prepare('revocation');
138
+ const agentId = `rer-conformance-${randomUUID()}`, throwaway = { ...c, agentId, consent: randomUUID() };
139
+ if (initializeAgent) {
140
+ try { await initializeAgent({ agentId, person: c.person }); }
141
+ catch {
142
+ c.add('BASE-AGENT-001.agent-initializer', false, 'Native agent initialization failed; no captured mail, credentials or fixture values are logged.');
143
+ return;
144
+ }
145
+ }
146
+ const witness = { name: c.surface.witness.tool, arguments: c.resolve(c.surface.witness.args) };
147
+ const call = async method => c.mcp(method, method === 'tools/call' ? witness : {}, { token: await accessToken(throwaway), track: false });
148
+ const challenged = answer => answer.status === 401 && /resource_metadata="/.test(answer.headers.get('www-authenticate') ?? '');
149
+ const admitted = await call('tools/call');
150
+ c.add('BASE-AGENT-004.6.seed-admitted', admitted.status === 200 && admitted.result?.structuredContent !== undefined && !admitted.result.isError, 'A throwaway agent must be admitted before its revocation.');
151
+ const before = await c.witness();
152
+ const revoke = await c.personRequest(`/agents/api/agents/${encodeURIComponent(agentId)}/revoke`, { method: 'POST', body: '{}' });
153
+ await revoke.body?.cancel();
154
+ c.add('BASE-AGENT-004.6.seed-revoke', revoke.status === 200, 'The signed-in owner must be able to revoke the throwaway agent through the person door.');
155
+ const refused = await call('tools/call'), listed = await call('tools/list');
156
+ c.add('BASE-AGENT-004.6.seed-revoked', challenged(refused) && challenged(listed), 'After the installation revokes an agent, a fresh Business token for the same agent must receive 401 with a resource_metadata challenge on every method.');
157
+ c.add('BASE-AGENT-004.6.seed-unchanged', isDeepStrictEqual(before, await c.witness()), 'A call under a revoked agent changed native state, or the main agent lost access.');
158
+ }
@@ -4,6 +4,7 @@ import { accessToken, policyEnvelope, renewalEnvelope, seconds } from './crypto.
4
4
  import { AGENT_CLASSES } from './surface.mjs';
5
5
  import { phaseFixtures } from './fixtures.mjs';
6
6
  import { validToolName } from './tool-name.mjs';
7
+ import { beforeDestruction, erasedAnswer, erasedCall } from './erasure.mjs';
7
8
 
8
9
  export const VERSION = '2026-07-28';
9
10
  export const DECISION = 'com.runeditrun/decision';
@@ -81,13 +82,19 @@ export function createProtocol(context) {
81
82
  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);
82
83
  context.add(`BASE-AGENT-008.5.summary.${handle.id}`, valid, 'The person approval must expose its exact decision, revision and summary SHA-256.');
83
84
  if (!valid) throw new Error('Cannot decide an approval without its exact summary evidence');
85
+ const before = action === 'approve' ? await beforeDestruction(context, approval.tool) : undefined;
84
86
  const response = await context.personRequest(`${path}/${action}`, { method: 'POST', body: JSON.stringify({ revision: approval.revision, summary_sha256: approval.summary_sha256 }) });
85
87
  const body = await responseBody(response);
88
+ let erasure;
89
+ if (response.ok && action === 'approve' && body.approval?.code === 'subject_erased') {
90
+ erasure = await erasedCall(context, before, approval.tool, undefined, pending.decision);
91
+ context.calls.push({ kind: 'approval/execute', name: approval.tool, decision: structuredClone(pending.decision), approvalId: handle.id, erasure, auditId: erasure.id });
92
+ }
86
93
  if (response.ok && action === 'approve' && approval.state === 'pending' && ['executed', 'refused'].includes(body.approval?.state)) context.calls.push({
87
94
  kind: 'approval/execute', name: approval.tool, decision: structuredClone(pending.decision), approvalId: handle.id, principal: pending.principal,
88
95
  state: body.approval.state, code: body.approval.code ?? null,
89
96
  });
90
- return { ok: response.ok, status: response.status, body };
97
+ return { ok: response.ok, status: response.status, body, erasure };
91
98
  };
92
99
  context.mcp = async (method, params = {}, options = {}) => {
93
100
  const client = options.client === undefined ? undefined : context.clients.get(options.client);
@@ -95,20 +102,23 @@ export function createProtocol(context) {
95
102
  const { token = client?.token ?? await accessToken(context), version = VERSION, headers = {}, track = true } = options;
96
103
  const principal = client && options.token === undefined ? { agent: client.agent, clientId: client.clientId, consent: null, sponsor: context.sponsor.id } : undefined;
97
104
  const id = ++requestId, name = method === 'resources/read' ? params.uri : params.name;
105
+ const before = method === 'tools/call' ? await beforeDestruction(context, name) : undefined;
98
106
  const response = await context.request('/mcp', { method: 'POST', headers: {
99
107
  Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json', Origin: context.origin,
100
108
  'MCP-Protocol-Version': version, 'Mcp-Method': method,
101
109
  ...(['tools/call', 'resources/read', 'prompts/get'].includes(method) && name ? { 'Mcp-Name': name } : {}),
102
110
  ...(token ? { Authorization: `Bearer ${token}` } : {}), ...headers,
103
- }, 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 } } }) });
111
+ }, body: JSON.stringify({ jsonrpc: '2.0', id, method, params: ['2025-06-18', '2025-11-25'].includes(version) ? params : { ...params, _meta: { 'io.modelcontextprotocol/protocolVersion': version, 'io.modelcontextprotocol/clientCapabilities': { elicitation: { url: {} } }, 'io.modelcontextprotocol/clientInfo': { name: 'rer-agent-conformance', version: '1' }, ...params._meta } } }) });
104
112
  const body = await responseBody(response), result = body.result, decision = result?._meta?.[DECISION] ?? body.error?.data?._meta?.[DECISION];
105
113
  const answer = { status: response.status, headers: response.headers, body, message: body, result, decision, principal };
106
- if (['tools/call', 'resources/read'].includes(method) && track && (response.status !== 401 || typeof body.error?.data?.code === 'string')) context.calls.push({
114
+ const erased = await erasedAnswer(context, answer, before, name);
115
+ if (['tools/call', 'resources/read'].includes(method) && track && erased !== false && (response.status !== 401 || typeof body.error?.data?.code === 'string')) context.calls.push({
107
116
  kind: method, name: method === 'resources/read' ? 'resources/read' : params.name,
108
117
  args: structuredClone(method === 'resources/read' ? { uri: params.uri } : params.arguments ?? {}),
109
118
  decision: structuredClone(decision ?? null), code: errorCode(answer), result: structuredClone(result), principal,
110
119
  approval: structuredClone(result?._meta?.[APPROVAL] ?? body.error?.data?.approval ?? null),
111
120
  pending: result?.resultType === 'input_required' || method === 'resources/read' && errorCode(answer) === 'approval_required',
121
+ ...(answer.erasure ? { erasure: answer.erasure, auditId: answer.erasure.id } : {}),
112
122
  });
113
123
  return answer;
114
124
  };