@runeditrun/rer 0.2.94 → 0.2.95

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 (54) hide show
  1. package/README.md +3 -0
  2. package/cli/README.md +3 -0
  3. package/cli/agent-journey-fixtures.mjs +1 -1
  4. package/cli/authoring.mjs +1 -1
  5. package/cli/business/carry-files.mjs +115 -0
  6. package/cli/business/carry.mjs +20 -81
  7. package/cli/business/choices.mjs +12 -7
  8. package/cli/contract.mjs +1 -1
  9. package/cli/door-clauses.mjs +28 -2
  10. package/cli/hosted-output.mjs +4 -2
  11. package/cli/hosted-queue-producers.mjs +43 -0
  12. package/cli/jsonc.mjs +1 -115
  13. package/cli/parse.mjs +1 -1
  14. package/cli/portability-migrations.mjs +2 -12
  15. package/edition-authoring/archive-source.mjs +86 -1
  16. package/edition-authoring/base-copies.mjs +15 -45
  17. package/edition-authoring/cli.mjs +1 -1
  18. package/edition-authoring/edition-migrations.mjs +2 -2
  19. package/edition-authoring/module-closure.mjs +119 -50
  20. package/edition-authoring/module-packages.mjs +12 -5
  21. package/edition-authoring/module-syntax.mjs +13 -50
  22. package/edition-authoring/runtime-dependencies.mjs +4 -4
  23. package/global/CHANGELOG.md +38 -0
  24. package/global/README.md +3 -0
  25. package/modules/agent-door/CLAUSES.md +12 -0
  26. package/modules/agent-door/conformance/audit.mjs +22 -4
  27. package/modules/agent-door/conformance/discovery.mjs +32 -1
  28. package/modules/agent-door/conformance/erasure.mjs +103 -0
  29. package/modules/agent-door/conformance/journey.mjs +19 -1
  30. package/modules/agent-door/conformance/policy-phases.mjs +6 -0
  31. package/modules/agent-door/conformance/protocol.mjs +13 -3
  32. package/modules/deploy-kit/jsonc.mjs +115 -0
  33. package/modules/deploy-kit/migration-directory.mjs +16 -0
  34. package/modules/deploy-kit/prepare.mjs +1 -1
  35. package/modules/deploy-kit/templates.mjs +9 -4
  36. package/modules/erasure/cascade.mjs +4 -4
  37. package/modules/erasure/index.d.mts +1 -1
  38. package/modules/erasure/index.mjs +1 -1
  39. package/modules/import-kit/src/d1/README.md +16 -1
  40. package/modules/import-kit/src/d1/preserved-reverse.ts +5 -2
  41. package/modules/import-kit/src/d1/read-fence.ts +14 -2
  42. package/modules/import-kit/src/d1/reverse.ts +4 -1
  43. package/modules/import-kit/src/d1/sets.ts +8 -0
  44. package/modules/import-kit/src/d1/snapshot-text.ts +68 -0
  45. package/modules/import-kit/src/d1/undo-report.ts +4 -1
  46. package/modules/import-kit/src/door/ADOPTING.md +9 -4
  47. package/modules/portability/README.md +28 -2
  48. package/modules/portability/bookkeeping.mjs +8 -4
  49. package/modules/portability/checkout-history.mjs +12 -6
  50. package/modules/portability/import.mjs +1 -1
  51. package/modules/portability/storage.mjs +7 -1
  52. package/modules/portability/worker-history.d.mts +1 -1
  53. package/modules/portability/worker-history.mjs +1 -1
  54. package/package.json +1 -1
@@ -1,53 +1,16 @@
1
- // Lex module syntax without treating comments, strings or template text as code.
2
- // Template interpolations are code, including nested templates and import().
3
- export function tokens(source) {
4
- const result = [];
5
- let i = 0;
6
- function quoted(quote) {
7
- const start = i++;
8
- while (i < source.length) {
9
- if (source[i] === '\\') { i += 2; continue; }
10
- if (source[i++] === quote) break;
11
- }
12
- return source.slice(start, i);
13
- }
14
- function template() {
15
- const start = i++;
16
- let interpolated = false;
17
- while (i < source.length) {
18
- if (source[i] === '\\') { i += 2; continue; }
19
- if (source[i] === '`') { i++; break; }
20
- if (source[i] === '$' && source[i + 1] === '{') {
21
- interpolated = true; i += 2; result.push(';'); scan(true); result.push(';');
22
- } else i++;
23
- }
24
- if (!interpolated) result.push(source.slice(start, i));
25
- }
26
- function scan(interpolation = false) {
27
- let braces = 0;
28
- while (i < source.length) {
29
- const c = source[i];
30
- if (/\s/.test(c)) { i++; continue; }
31
- if (source.startsWith('//', i)) {
32
- while (i < source.length && source[i] !== '\n') i++;
33
- continue;
34
- }
35
- if (source.startsWith('/*', i)) {
36
- const end = source.indexOf('*/', i + 2); i = end < 0 ? source.length : end + 2; continue;
37
- }
38
- if (c === "'" || c === '"') { result.push(quoted(c)); continue; }
39
- if (c === '`') { template(); continue; }
40
- if (interpolation && c === '}' && !braces) { i++; return; }
41
- if (c === '{') braces++;
42
- if (c === '}') braces--;
43
- if (/[\w$]/.test(c)) {
44
- const start = i++;
45
- while (i < source.length && /[\w$]/.test(source[i])) i++;
46
- result.push(source.slice(start, i));
47
- } else { result.push(c); i++; }
48
- }
49
- }
50
- scan(); return result;
1
+ import {parse} from './vendor/babel-parser/babel-parser/index.mjs';
2
+
3
+ // Let the maintained parser distinguish strings, regex literals and template
4
+ // text. Keep raw token spelling for the conservative binding/export checks.
5
+ export function tokens(source, filename = 'module.ts') {
6
+ const plugins = ['decorators-legacy', 'deprecatedImportAssert'];
7
+ if (/\.[cm]?tsx?$/.test(filename)) plugins.push(['typescript', {dts: /\.d\.[cm]?ts$/.test(filename)}]);
8
+ if (/\.[jt]sx$/.test(filename)) plugins.push('jsx');
9
+ const ast = parse(source, {sourceFilename: filename, sourceType: 'unambiguous', tokens: true,
10
+ allowReturnOutsideFunction: true, allowUndeclaredExports: true, plugins});
11
+ return ast.tokens.filter(token => typeof token.type !== 'string' &&
12
+ !['eof', 'template', '`'].includes(token.type.label)).map(token =>
13
+ token.type.label === '${' ? ';' : source.slice(token.start, token.end));
51
14
  }
52
15
 
53
16
  export function unquote(value) {
@@ -5,8 +5,8 @@ export {resolve, external} from './module-resolution.mjs';
5
5
  export {dependencies} from './module-edges.mjs';
6
6
 
7
7
  // Binding checks are lexical: unknown export forms remain unknown, never absent.
8
- export function bindings(source, types = false) {
9
- const t = tokens(source), result = new Map();
8
+ export function bindings(source, types = false, filename = 'module.ts') {
9
+ const t = tokens(source, filename), result = new Map();
10
10
  for (let i = 0; i < t.length; i++) {
11
11
  if (!['import', 'export'].includes(t[i]) || ['.', '('].includes(t[i + 1])) continue;
12
12
  let end = i + 1;
@@ -31,8 +31,8 @@ export function bindings(source, types = false) {
31
31
  }
32
32
  return result;
33
33
  }
34
- export function lexicalExports(source, star, types = false) {
35
- const t = tokens(source), names = new Set();
34
+ export function lexicalExports(source, star, types = false, filename = 'module.ts') {
35
+ const t = tokens(source, filename), names = new Set();
36
36
  for (let i = 0; i < t.length; i++) {
37
37
  if (t[i] !== 'export') continue;
38
38
  let j = i + 1;
@@ -1,5 +1,43 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.95
4
+
5
+ ### Native agent erasure and safe replay
6
+
7
+ - Native subject erasure now covers mapped agent-door payloads together with the subject, including identifier-linked proposals and recorded-name and colon mentions. Value-free decision custody and secret-keyed replay refusal aliases are retained only for the fixed 30-day completion window, and replay aliases are excluded from archives.
8
+ - Known limit, accepted 30 Oct 2026: a numeric-only recorded name such as `1` also redacts unrelated text such as `1:30 PM`. Erasure fails closed rather than leaving the name behind.
9
+ - Adopters append the custody and window schema in their own new migrations (Base's reference migrations are `0038_agent_erasure_custody.sql` and `0039_agent_replay_window.sql`), map every installed agent table and column into their existing native erasure transaction, reuse the installation secret and fence, and schedule `expireReplayCalls`. Recipe: `modules/agent-door/ADOPTING.md`. Seed acceptance is not promoted automatically.
10
+
11
+ ### MCP clients and native admission
12
+
13
+ - The agent door accepts the June 2025 MCP protocol alongside November 2025 and July 2026. It authenticates before validating the protocol, accepts a body-only `initialize`, and treats headerless stateless requests as June 2025. Modern clients keep consistent version, method and name metadata.
14
+ - Concurrent native admissions wait for the bounded policy slot and recheck current authority and policy before any effect.
15
+ - Narrowing injection conformance requires `invalid_arguments`. Declared disposable queue producers can be failed and restored before enqueue. Refresh the complete shared door and conformance dependency set. Sources: `modules/agent-door/README.md`, `modules/agent-door/ADOPTING.md`, `cli/hosted-queue-producers.mjs`.
16
+
17
+ ### Preserved data import and undo
18
+
19
+ - Large preserved-data undo and undo-report resume operations (tens of thousands of effects) now complete within the D1 transport limit with their atomic guarantees unchanged. The complete atomic snapshot for `readD1PersistedImport` exports retains its existing 2 MiB transport cap; oversized exports still refuse with `ImportSizeLimitError` naming `targetKinds`.
20
+
21
+ ### Spool native-Wrangler history restore
22
+
23
+ - Optional seed-owned build evidence now supports a plain `d1_migrations` ledger only when its names select an exact ordered file prefix whose replay reproduces the complete live schema. Unknown, gapped or reordered history and schema drift refuse before any restore write. Archive history still needs its own authenticated proof, and no historical hashes are invented or backfilled.
24
+ - Adopt `legacyMigrationEvidence()` from `@runeditrun/rer/portability-evidence` in existing Vite plugins, import `virtual:rer-legacy-migration-evidence` in the archive server adapter, and pass `migrations: () => workerMigrations(db, policy, evidence)` to `createPortability`. Retain the reviewed applied migration files, refresh helpers and copied portability runtime together, and retain one service through the initial upload. Recipe: `modules/portability/README.md`. This is Base support; Spool's published-package restore proof is reported separately.
25
+
26
+ ### Source refresh and recovery
27
+
28
+ - `rer refresh-base` closes the dependencies imported by retained seed modules, includes the deploy-kit JSONC and migration-directory helpers, and refuses undeclared retained dependencies before any write.
29
+ - Refresh from a full immutable commit SHA, an extracted `--base-archive DIR`, or authenticated `--from-api` reads. A tag name is not accepted as `--ref`; resolve it first with `git rev-parse 'rer-v0.2.95^{commit}'`. Archive source identity is caller-supplied and cannot prove missing historical ancestry; API reads use checked immutable objects. See `edition-authoring/ADOPTING.md` and `edition-authoring/README.md`.
30
+
31
+ ### Shared duties clause handling
32
+
33
+ - `rer door clauses --write` requires a `## Shared duties (Base)` table with a `Base duty` column and skips the inherited duties listed there, preserving existing status, evidence, gap and judgment. Read-only `--check` still inspects clause definitions, including listed duties.
34
+ - Review the generated contract views and regenerate the seed's source lock last. A seed's rows have not passed merely because Base delivered the duties. Commands and behavior: `modules/agent-door/ADOPTING.md`.
35
+
36
+ ### Previously carried local checkouts
37
+
38
+ - Business check-in refreshes the existing carry in stopped checkouts as well as live ones, keeping the identity and private-file checks and the prior carry when a refresh is refused. Update the installed CLI and use the existing supervisor check-in; there is no new connect authority and no claim that an app has applied the carry.
39
+ - Follow-up: N-07's four minor follow-ups remain later work and are not part of this release.
40
+
3
41
  ## 0.2.94
4
42
 
5
43
  - Include the shared checkout-history validator in the documented portability runtime copy, preserving self-contained Worker and CLI adoption.
package/global/README.md CHANGED
@@ -23,6 +23,9 @@ for adoption, refusal behavior, JSON fields and the original Base-checkout form.
23
23
  contract, preserving its judgments and its own specialist clauses, then runs
24
24
  contract document generation and checking. `rer door clauses --check` reports
25
25
  missing or stale requirements without writing; use `--cwd DIR` to select a seed.
26
+ Writing requires a `Shared duties (Base)` table and skips duties listed in its
27
+ `Base duty` column. Unlisted duties are synchronized as clauses; a missing table
28
+ refuses the write. The read-only check still inspects clause definitions.
26
29
  The CLI can sync a contract before runtime adoption; regenerate the seed's source lock last.
27
30
  See [agent door adoption](https://github.com/runeditrun/base/blob/main/modules/agent-door/ADOPTING.md#contract-clauses).
28
31
 
@@ -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,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;
@@ -3,6 +3,7 @@ import { webcrypto } from 'node:crypto';
3
3
  import { autonomousPolicy, policyEnvelope, signJws, seconds } from './crypto.mjs';
4
4
  import { errorCode } from './protocol.mjs';
5
5
  import { nativeStepHook } from './step-hooks.mjs';
6
+ import { erasedStep } from './erasure.mjs';
6
7
 
7
8
  export async function unsetPolicy(c, initial = false) {
8
9
  const listed = await c.mcp('tools/list');
@@ -90,6 +91,11 @@ export async function blockedPhases(c) {
90
91
  await c.adopt(autonomousPolicy());
91
92
  }
92
93
  const completed = await c.stepTool(step, args, await c.proof(step.tool, args, undefined, step.client));
94
+ if (completed.erasure) {
95
+ const value = await erasedStep(c, step, args, completed, `blocked:${cls}`, outputs);
96
+ await nativeStepHook(c, 'afterStep', `blocked:${cls}`, step, args, outputs, value);
97
+ continue;
98
+ }
93
99
  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
100
  outputs.set(step.id, completed.result.structuredContent);
95
101
  await nativeStepHook(c, 'afterStep', `blocked:${cls}`, step, args, outputs, completed.result.structuredContent);
@@ -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
  };