@runeditrun/rer 0.2.85 → 0.2.87

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 (162) hide show
  1. package/README.md +138 -29
  2. package/cli/README.md +61 -1
  3. package/cli/agent-bindings.mjs +25 -0
  4. package/cli/agent-door.mjs +145 -0
  5. package/cli/agent-fixtures.mjs +16 -0
  6. package/cli/agent-journey-fixtures.mjs +17 -0
  7. package/cli/agent-mail.mjs +54 -0
  8. package/cli/agent-network.mjs +64 -0
  9. package/cli/agent-reviewers.mjs +110 -0
  10. package/cli/agent-rpc.mjs +23 -0
  11. package/cli/agent-secrets.mjs +23 -0
  12. package/cli/agent-sponsors.mjs +43 -0
  13. package/cli/agent-surface.mjs +34 -0
  14. package/cli/agent-verifier.mjs +31 -0
  15. package/cli/agent-webhooks.mjs +19 -0
  16. package/cli/authoring.mjs +2 -1
  17. package/cli/business/archive-task.mjs +32 -0
  18. package/cli/business/carry.mjs +3 -1
  19. package/cli/business/catchup-task.mjs +42 -0
  20. package/cli/business/choices.mjs +97 -0
  21. package/cli/business/command.mjs +23 -5
  22. package/cli/business/connect.mjs +19 -7
  23. package/cli/business/detector.mjs +4 -1
  24. package/cli/business/device.mjs +13 -0
  25. package/cli/business/export-inputs.mjs +69 -0
  26. package/cli/business/export-task.mjs +17 -0
  27. package/cli/business/invocation.mjs +8 -1
  28. package/cli/business/keychain.mjs +8 -1
  29. package/cli/business/lease.mjs +11 -1
  30. package/cli/business/local-commands.mjs +79 -31
  31. package/cli/business/outbound.mjs +9 -4
  32. package/cli/business/parsers-config.mjs +8 -7
  33. package/cli/business/parsers-syntax.mjs +7 -3
  34. package/cli/business/permissions.mjs +2 -0
  35. package/cli/business/questions.mjs +89 -9
  36. package/cli/business/setup-command.mjs +49 -0
  37. package/cli/business/setup-company.json +15 -0
  38. package/cli/business/setup-demo.mjs +95 -0
  39. package/cli/business/state.mjs +44 -10
  40. package/cli/business/supervisor.mjs +94 -35
  41. package/cli/business/vendor-door.mjs +230 -0
  42. package/cli/business/vendors/README.md +29 -3
  43. package/cli/business/vendors/common.mjs +8 -6
  44. package/cli/business/vendors/index.mjs +22 -11
  45. package/cli/business/vendors/sorry.mjs +106 -0
  46. package/cli/contract.mjs +2 -2
  47. package/cli/demo-deploy-error.mjs +14 -0
  48. package/cli/demo-native.mjs +4 -1
  49. package/cli/deploy-config.mjs +1 -1
  50. package/cli/deploy-owner-input.mjs +3 -1
  51. package/cli/deploy-variables.mjs +89 -0
  52. package/cli/door-clauses.mjs +157 -0
  53. package/cli/export.mjs +17 -4
  54. package/cli/hosted-output.mjs +31 -8
  55. package/cli/inspect.mjs +4 -0
  56. package/cli/jsonc.mjs +8 -4
  57. package/cli/lifecycle.mjs +3 -1
  58. package/cli/main.mjs +1 -0
  59. package/cli/managed-data-schema.mjs +14 -1
  60. package/cli/managed-data.mjs +8 -4
  61. package/cli/portability-empty.mjs +6 -0
  62. package/cli/portability-migrations.mjs +26 -4
  63. package/cli/portability-worker.mjs +2 -1
  64. package/cli/portability.mjs +1 -0
  65. package/cli/production-auth.mjs +2 -2
  66. package/cli/production-mail.mjs +19 -3
  67. package/cli/server-registry.mjs +2 -0
  68. package/edition-authoring/archive-source.mjs +65 -0
  69. package/edition-authoring/base-copies.mjs +108 -21
  70. package/edition-authoring/cli.mjs +1 -1
  71. package/edition-authoring/copy-namespaces.mjs +28 -0
  72. package/edition-authoring/edition-migrations.mjs +7 -3
  73. package/edition-authoring/files.mjs +2 -1
  74. package/edition-authoring/module-closure.mjs +58 -27
  75. package/edition-authoring/module-edges.mjs +13 -2
  76. package/edition-authoring/workflow-copies.mjs +1 -1
  77. package/edition-authoring/workflow-scripts.mjs +12 -3
  78. package/foundation/runtime/contract-docs.mjs +220 -32
  79. package/foundation/runtime/contract-prose-patterns.mjs +14 -0
  80. package/foundation/runtime/contract-prose.mjs +88 -0
  81. package/global/CHANGELOG.md +151 -0
  82. package/global/README.md +138 -29
  83. package/global/door/command.mjs +3 -1
  84. package/global/main.mjs +1 -1
  85. package/modules/agent-door/CLAUSES.md +215 -0
  86. package/modules/agent-door/conformance/audit-pages.mjs +11 -0
  87. package/modules/agent-door/conformance/audit-rows.mjs +20 -0
  88. package/modules/agent-door/conformance/audit.mjs +63 -0
  89. package/modules/agent-door/conformance/authority.d.mts +2 -0
  90. package/modules/agent-door/conformance/authority.mjs +17 -0
  91. package/modules/agent-door/conformance/crypto.mjs +36 -0
  92. package/modules/agent-door/conformance/discovery.mjs +61 -0
  93. package/modules/agent-door/conformance/fixtures.mjs +41 -0
  94. package/modules/agent-door/conformance/index.mjs +41 -0
  95. package/modules/agent-door/conformance/injection.mjs +24 -0
  96. package/modules/agent-door/conformance/invocation.mjs +33 -0
  97. package/modules/agent-door/conformance/journey.mjs +117 -0
  98. package/modules/agent-door/conformance/narrowing.d.mts +2 -0
  99. package/modules/agent-door/conformance/narrowing.mjs +29 -0
  100. package/modules/agent-door/conformance/negative.mjs +48 -0
  101. package/modules/agent-door/conformance/network-modules.mjs +86 -0
  102. package/modules/agent-door/conformance/network-runtime.mjs +46 -0
  103. package/modules/agent-door/conformance/policy-phases.mjs +83 -0
  104. package/modules/agent-door/conformance/protocol.mjs +153 -0
  105. package/modules/agent-door/conformance/replay.mjs +39 -0
  106. package/modules/agent-door/conformance/schema.mjs +71 -0
  107. package/modules/agent-door/conformance/security.mjs +34 -0
  108. package/modules/agent-door/conformance/sponsors.mjs +68 -0
  109. package/modules/agent-door/conformance/step-hooks.mjs +4 -0
  110. package/modules/agent-door/conformance/surface.mjs +92 -0
  111. package/modules/agent-door/conformance/target.mjs +19 -0
  112. package/modules/agent-door/conformance/tool-name.d.mts +1 -0
  113. package/modules/agent-door/conformance/tool-name.mjs +7 -0
  114. package/modules/agent-door/conformance/webhooks.mjs +31 -0
  115. package/modules/container/image-variables.mjs +8 -2
  116. package/modules/delivery-producer/mail.mjs +20 -0
  117. package/modules/demo-host/README.md +6 -0
  118. package/modules/demo-host/ownership.mjs +39 -0
  119. package/modules/demo-host/plan.mjs +2 -1
  120. package/modules/demo-host/remove.mjs +6 -1
  121. package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
  122. package/modules/import-kit/schema/importers.schema.json +107 -0
  123. package/modules/import-kit/src/door/ADOPTING.md +20 -0
  124. package/modules/import-kit/src/door/README.md +2 -1
  125. package/modules/import-kit/src/door/admission.ts +5 -3
  126. package/modules/import-kit/src/door/archive.ts +5 -2
  127. package/modules/import-kit/src/door/authority.ts +1 -0
  128. package/modules/import-kit/src/door/grants.ts +1 -1
  129. package/modules/import-kit/src/door/handler.ts +14 -8
  130. package/modules/import-kit/src/door/index.ts +1 -1
  131. package/modules/import-kit/src/door/jobs.ts +40 -0
  132. package/modules/import-kit/src/door/operator.ts +3 -3
  133. package/modules/import-kit/src/door/planning.ts +10 -6
  134. package/modules/import-kit/src/door/protocol.ts +2 -2
  135. package/modules/import-kit/src/door/raw.ts +25 -0
  136. package/modules/import-kit/src/door/refusals.ts +1 -0
  137. package/modules/import-kit/src/door/types.ts +26 -6
  138. package/modules/import-kit/src/receipt/encoding.ts +37 -0
  139. package/modules/import-kit/src/receipt/index.ts +69 -0
  140. package/modules/import-kit/src/receipt/policy.ts +24 -0
  141. package/modules/import-kit/src/receipt/types.ts +64 -0
  142. package/modules/import-kit/src/receipt/uri.ts +45 -0
  143. package/modules/import-kit/src/receipt/validation.ts +87 -0
  144. package/modules/import-kit/src/status/encoding.ts +13 -0
  145. package/modules/import-kit/src/status/evidence.ts +218 -0
  146. package/modules/import-kit/src/status/index.ts +56 -0
  147. package/modules/import-kit/src/status/schema.ts +208 -0
  148. package/modules/import-kit/src/status/types.ts +86 -0
  149. package/modules/operator-auth/accounts/delegated.mjs +48 -0
  150. package/modules/operator-auth/index.d.mts +7 -0
  151. package/modules/operator-auth/service.mjs +2 -0
  152. package/modules/portability/README.md +37 -13
  153. package/modules/portability/bridge.mjs +22 -2
  154. package/modules/portability/catalogue.mjs +12 -2
  155. package/modules/portability/copies.mjs +8 -1
  156. package/modules/portability/derived.mjs +33 -0
  157. package/modules/portability/http-errors.mjs +1 -1
  158. package/modules/portability/import.mjs +14 -7
  159. package/package.json +4 -2
  160. package/scripts/publish-check/copy_identities.py +3 -1
  161. package/scripts/publish-check/github_refs.py +32 -13
  162. package/cli/business/opt-ins.mjs +0 -37
@@ -0,0 +1,71 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+
3
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const types = { null: value => value === null, object, array: Array.isArray, string: value => typeof value === 'string', boolean: value => typeof value === 'boolean', number: value => typeof value === 'number' && Number.isFinite(value), integer: Number.isSafeInteger };
5
+ const pointer = (root, ref) => ref.split('/').slice(1).reduce((value, key) => value?.[key.replace(/~1/g, '/').replace(/~0/g, '~')], root);
6
+
7
+ /** JSON Schema assertions used by tool output declarations; returns diagnostic paths. */
8
+ export function schemaErrors(schema, value, root = schema, path = '$', depth = 0) {
9
+ if (depth > 100) return [`${path}: schema recursion limit`];
10
+ if (schema === true) return [];
11
+ if (schema === false) return [`${path}: forbidden`];
12
+ if (!object(schema)) return [`${path}: schema must be an object or boolean`];
13
+ const errors = [], add = (ok, detail) => { if (!ok) errors.push(`${path}: ${detail}`); };
14
+ const check = (sub, item = value, at = path) => schemaErrors(sub, item, root, at, depth + 1);
15
+ if ('$ref' in schema) {
16
+ if (typeof schema.$ref !== 'string' || !schema.$ref.startsWith('#')) add(false, 'only local schema references are supported');
17
+ else { const target = schema.$ref === '#' ? root : pointer(root, schema.$ref.slice(1)); if (target === undefined) add(false, `unresolved ${schema.$ref}`); else errors.push(...check(target)); }
18
+ }
19
+ if (schema.type !== undefined) add((Array.isArray(schema.type) ? schema.type : [schema.type]).some(type => Object.hasOwn(types, type) && types[type](value)), `expected ${JSON.stringify(schema.type)}`);
20
+ if (schema.const !== undefined) add(isDeepStrictEqual(value, schema.const), 'const mismatch');
21
+ if (schema.enum) add(schema.enum.some(item => isDeepStrictEqual(item, value)), 'enum mismatch');
22
+ if (schema.allOf) for (const sub of schema.allOf) errors.push(...check(sub));
23
+ if (schema.anyOf) add(schema.anyOf.some(sub => !check(sub).length), 'no anyOf alternative matched');
24
+ if (schema.oneOf) add(schema.oneOf.filter(sub => !check(sub).length).length === 1, 'expected one matching oneOf alternative');
25
+ if (schema.not) add(check(schema.not).length > 0, 'not schema matched');
26
+ if (schema.if) errors.push(...check(!check(schema.if).length ? schema.then ?? true : schema.else ?? true));
27
+ if (typeof value === 'number') {
28
+ if (schema.minimum !== undefined) add(value >= schema.minimum, 'below minimum');
29
+ if (schema.maximum !== undefined) add(value <= schema.maximum, 'above maximum');
30
+ if (typeof schema.exclusiveMinimum === 'number') add(value > schema.exclusiveMinimum, 'below exclusiveMinimum');
31
+ if (typeof schema.exclusiveMaximum === 'number') add(value < schema.exclusiveMaximum, 'above exclusiveMaximum');
32
+ if (schema.multipleOf !== undefined) add(Math.abs(value / schema.multipleOf - Math.round(value / schema.multipleOf)) < Number.EPSILON * 8, 'multipleOf mismatch');
33
+ }
34
+ if (typeof value === 'string') {
35
+ if (schema.minLength !== undefined) add([...value].length >= schema.minLength, 'below minLength');
36
+ if (schema.maxLength !== undefined) add([...value].length <= schema.maxLength, 'above maxLength');
37
+ if (schema.pattern !== undefined) { try { add(new RegExp(schema.pattern, 'u').test(value), 'pattern mismatch'); } catch { add(false, 'invalid schema pattern'); } }
38
+ if (schema.format === 'date-time') add(/^\d{4}-\d{2}-\d{2}T/.test(value) && Number.isFinite(Date.parse(value)), 'invalid date-time');
39
+ if (schema.format === 'email') add(/^[^\s@]+@[^\s@]+$/.test(value), 'invalid email');
40
+ if (schema.format === 'uuid') add(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(value), 'invalid uuid');
41
+ if (schema.format === 'uri') { try { new URL(value); } catch { add(false, 'invalid URI'); } }
42
+ }
43
+ if (Array.isArray(value)) {
44
+ if (schema.minItems !== undefined) add(value.length >= schema.minItems, 'below minItems');
45
+ if (schema.maxItems !== undefined) add(value.length <= schema.maxItems, 'above maxItems');
46
+ if (schema.uniqueItems) add(value.every((item, i) => value.slice(0, i).every(other => !isDeepStrictEqual(item, other))), 'duplicate array items');
47
+ const tuple = schema.prefixItems ?? (Array.isArray(schema.items) ? schema.items : []);
48
+ for (let i = 0; i < value.length; i++) {
49
+ const itemSchema = tuple[i] ?? (Array.isArray(schema.items) ? schema.additionalItems : schema.items);
50
+ if (itemSchema !== undefined) errors.push(...check(itemSchema, value[i], `${path}[${i}]`));
51
+ }
52
+ if (schema.contains) { const count = value.filter(item => !check(schema.contains, item).length).length; add(count >= (schema.minContains ?? 1) && count <= (schema.maxContains ?? Infinity), 'contains count mismatch'); }
53
+ }
54
+ if (object(value)) {
55
+ const keys = Object.keys(value);
56
+ if (schema.minProperties !== undefined) add(keys.length >= schema.minProperties, 'below minProperties');
57
+ if (schema.maxProperties !== undefined) add(keys.length <= schema.maxProperties, 'above maxProperties');
58
+ for (const key of schema.required ?? []) add(Object.hasOwn(value, key), `missing required ${key}`);
59
+ for (const key of keys) {
60
+ const at = `${path}.${key}`, matches = [];
61
+ if (Object.hasOwn(schema.properties ?? {}, key)) matches.push(schema.properties[key]);
62
+ for (const [pattern, sub] of Object.entries(schema.patternProperties ?? {})) { try { if (new RegExp(pattern, 'u').test(key)) matches.push(sub); } catch { add(false, 'invalid patternProperties pattern'); } }
63
+ if (!matches.length && schema.additionalProperties !== undefined) matches.push(schema.additionalProperties);
64
+ for (const sub of matches) errors.push(...check(sub, value[key], at));
65
+ if (schema.propertyNames) errors.push(...check(schema.propertyNames, key, at));
66
+ for (const dependency of schema.dependentRequired?.[key] ?? []) add(Object.hasOwn(value, dependency), `${key} requires ${dependency}`);
67
+ if (schema.dependentSchemas?.[key]) errors.push(...check(schema.dependentSchemas[key]));
68
+ }
69
+ }
70
+ return errors;
71
+ }
@@ -0,0 +1,34 @@
1
+ import { auditRows } from './audit.mjs';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { autonomousPolicy } from './crypto.mjs';
4
+ import { errorCode } from './protocol.mjs';
5
+ import { validateAgentSurface } from './surface.mjs';
6
+
7
+ /** Normal journey phases already require security policy and native approval.
8
+ * This phase checks the explicit no-subject contract and undeclared widening. */
9
+ export async function recordSecurityPhase(c) {
10
+ const tools = c.surface.tools.filter(tool => tool.authority === 'none');
11
+ if (!tools.length) return;
12
+ await c.adopt(autonomousPolicy());
13
+ await c.prepare('no-subject');
14
+ const outputs = new Map();
15
+ for (const step of c.surface.journey) {
16
+ const prepared = c.args(step, outputs);
17
+ const answer = await c.stepTool(step, prepared, await c.proof(step.tool, prepared, undefined, step.client));
18
+ if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error('Could not prepare no-subject security journey.');
19
+ outputs.set(step.id, answer.result.structuredContent);
20
+ if (!tools.some(tool => tool.name === step.tool)) continue;
21
+ const prefix = `BASE-AGENT-005.no-subject.${step.id}`;
22
+ const before = await c.witness(), args = { ...c.args(step, outputs), role: 'owner', scopes: ['*'], person_id: c.sponsor.id };
23
+ const refused = await c.stepTool(step, args);
24
+ c.add(`${prefix}.undeclared`, errorCode(refused) === 'undeclared_arguments' && refused.result?.structuredContent === undefined, 'A no-subject tool must refuse undeclared widening arguments.');
25
+ c.add(`${prefix}.unchanged`, isDeepStrictEqual(before, await c.witness()), 'An undeclared authority argument changed native state.');
26
+ const rows = await auditRows(c);
27
+ c.add(`${prefix}.audit`, rows.rows?.some(row => row.tool === step.tool && row.authority === 'none' && row.outcome === 'done')
28
+ && rows.rows?.some(row => row.tool === step.tool && row.authority === 'none' && row.code === 'undeclared_arguments'), 'Audit must record the explicit authority class on successful and refused calls.');
29
+ const invalid = structuredClone(c.surface), tool = invalid.tools.find(tool => tool.name === step.tool);
30
+ tool.inputSchema.properties.person_id = { type: 'string' };
31
+ const validation = validateAgentSurface(invalid);
32
+ c.add(`${prefix}.negative-declaration`, !validation.ok && validation.points.some(point => point.id.endsWith(`${step.tool}.authority-none`) && !point.ok), 'A no-subject declaration carrying a person or grant must fail static validation.');
33
+ }
34
+ }
@@ -0,0 +1,68 @@
1
+ import { auditRows } from './audit.mjs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { accessToken, autonomousPolicy } from './crypto.mjs';
5
+ import { createProtocol, errorCode, APPROVAL } from './protocol.mjs';
6
+
7
+ /** Additional principals use real native sessions and signed credentials. All
8
+ * record and approval probes cross the same public doors as the main journey. */
9
+ export async function crossSponsorPhase(c, sponsors) {
10
+ const declaration = c.surface.verification?.crossSponsor;
11
+ if (!declaration || !Array.isArray(declaration.prepare) || !declaration.prepare.length || !declaration.read || !declaration.change) throw new Error('Multiple sponsors require verification.crossSponsor {prepare,read,change} fixtures.');
12
+ for (const person of sponsors.slice(1)) {
13
+ const b = createProtocol({ fetch: c.fetch, origin: c.origin, surface: c.surface, signer: c.signer, person,
14
+ business: c.business, consent: randomUUID(), now: c.now, points: c.points, agentId: `rer-conformance-${randomUUID()}`, seq: c.seq, revision: c.revision, listed: c.listed });
15
+ const prefix = `BASE-AGENT-004.cross-sponsor.${person.label}`;
16
+ await c.adopt(autonomousPolicy());
17
+ b.revision = c.revision;
18
+ await b.mcp('tools/list');
19
+ const inventory = await c.personJson('/agents/api/agents');
20
+ const agent = inventory.agents?.find(item => item.id === b.agentId);
21
+ b.sponsor.id = agent?.sponsor?.id;
22
+ c.add(`${prefix}.binding`, typeof b.sponsor.id === 'string' && b.sponsor.id !== c.sponsor.id, 'Each labelled sponsor must resolve to a distinct active native principal.');
23
+ const outputs = new Map(), ownOutputs = new Map();
24
+ for (const id of declaration.prepare) {
25
+ const step = c.surface.journey.find(item => item.id === id);
26
+ if (!step) throw new Error('crossSponsor.prepare must name journey steps.');
27
+ const a = await c.tool(step.tool, c.args(step, outputs));
28
+ if (a.result?.isError || a.result?.structuredContent === undefined) throw new Error('Could not prepare private native records for cross-sponsor checks.');
29
+ outputs.set(step.id, a.result.structuredContent);
30
+ const own = await b.tool(step.tool, b.args(step, ownOutputs));
31
+ if (own.result?.structuredContent !== undefined) ownOutputs.set(step.id, own.result.structuredContent);
32
+ c.add(`${prefix}.own.${id}`, own.status === 200 && own.result?.structuredContent !== undefined && !own.result.isError, 'The second sponsor must successfully use its own signed agent credential.');
33
+ }
34
+ const before = await c.witness();
35
+ for (const [kind, step] of [['read', declaration.read], ['change', declaration.change]]) {
36
+ const answer = await b.tool(step.tool, b.args(step, outputs));
37
+ c.add(`${prefix}.${kind}`, answer.result?.isError === true && typeof errorCode(answer) === 'string' && answer.result?.structuredContent === undefined, 'The second sponsor must not read or change the first sponsor\'s private record.');
38
+ }
39
+ c.add(`${prefix}.unchanged`, isDeepStrictEqual(before, await c.witness()), 'Cross-sponsor probes changed the first sponsor\'s private native state.');
40
+ const held = autonomousPolicy(); held.rules = [{ id: 'all', class: '*', do: 'approval', approver: ['sponsor'], wait: 'PT1H' }];
41
+ await c.adopt(held);
42
+ const args = c.args(declaration.change, outputs), pending = await c.tool(declaration.change.tool, args), handle = pending.result?._meta?.[APPROVAL];
43
+ c.add(`${prefix}.pending`, pending.result?.resultType === 'input_required' && typeof handle?.id === 'string', 'Cross-sponsor approval must be a real pending native action.');
44
+ if (!handle?.id) throw new Error('No cross-sponsor approval handle.');
45
+ const path = `/agents/api/approvals/${encodeURIComponent(handle.id)}`;
46
+ const view = (await c.personJson(path)).approval;
47
+ const hidden = await b.personRequest(path);
48
+ c.add(`${prefix}.approval-private`, [403, 404].includes(hidden.status), 'Another sponsor\'s person session must not read private approval details.');
49
+ await hidden.body?.cancel();
50
+ const body = JSON.stringify({ revision: view.revision, summary_sha256: view.summary_sha256 });
51
+ const rejected = await b.personRequest(`${path}/approve`, { method: 'POST', body });
52
+ c.add(`${prefix}.approval-person`, [403, 404].includes(rejected.status), 'A second sponsor must not approve the first sponsor\'s action.');
53
+ await rejected.body?.cancel();
54
+ const agentAttempt = await b.request(`${path}/approve`, { method: 'POST', headers: { Origin: c.origin, Authorization: `Bearer ${await accessToken(b)}`, 'Content-Type': 'application/json' }, body });
55
+ c.add(`${prefix}.approval-agent`, agentAttempt.status === 403, 'A second sponsor\'s agent credential cannot act as the first sponsor\'s approver.');
56
+ await agentAttempt.body?.cancel();
57
+ const after = (await c.personJson(path)).approval;
58
+ c.add(`${prefix}.approval-unchanged`, after.state === 'pending' && after.approvals.length === 0, 'Cross-sponsor approval attempts changed its state.');
59
+ await c.decideApproval(pending, 'reject');
60
+ await c.adopt(autonomousPolicy());
61
+ for (const principal of [c, b]) {
62
+ const audit = await auditRows({ ...c, agentId: principal.agentId });
63
+ const row = audit.rows?.findLast(item => item.tool === c.surface.journey.find(step => step.id === declaration.prepare[0]).tool && item.outcome === 'done');
64
+ c.add(`${prefix}.attribution.${principal.person.label ?? 'first'}`, row?.sponsor?.id === principal.sponsor.id && row.agent?.id === principal.agentId && row.label?.includes(agentName(principal, inventory)), 'Native audit attribution must name the acting agent and its own sponsor.');
65
+ }
66
+ }
67
+ }
68
+ const agentName = (principal, inventory) => inventory.agents.find(item => item.id === principal.agentId)?.sponsor?.name ?? principal.person.email;
@@ -0,0 +1,4 @@
1
+ export async function nativeStepHook(c, stage, phase, step, args, outputs, result) {
2
+ if (!c.nativeStep) return;
3
+ await c.nativeStep({ stage, phase, step: structuredClone(step), args: structuredClone(args), outputs: structuredClone(Object.fromEntries(outputs)), ...(result === undefined ? {} : { result: structuredClone(result) }), tool: c.tool });
4
+ }
@@ -0,0 +1,92 @@
1
+ import { recordOnlyAuthority } from './authority.mjs';
2
+ import { narrowingContract, narrowingTargets } from './narrowing.mjs';
3
+ import { validToolName } from './tool-name.mjs';
4
+
5
+ export const AGENT_CLASSES = Object.freeze(['standard', 'external', 'money', 'commitment', 'accounts', 'gated', 'access', 'security', 'destructive', 'sensitive', 'live']);
6
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
7
+ const hasClause = (contract, clause) => typeof clause === 'string' && contract.split(/[^A-Za-z0-9_.-]+/).includes(clause);
8
+ const text = value => typeof value === 'string' && value.trim().length > 0;
9
+
10
+ /** Validate the edition's static declaration without loading application code. */
11
+ export function validateAgentSurface(surface, { contract } = {}) {
12
+ const points = [], add = (id, ok, detail) => points.push({ id: `BASE-AGENT-013.surface.${id}`, ok: Boolean(ok), ...(!ok ? { detail } : {}) });
13
+ add('schema', object(surface) && surface.schema === 'rer-agent-surface/1', 'Agent surface must use schema rer-agent-surface/1.');
14
+ if (!object(surface)) return { ok: false, points };
15
+ add('seed', text(surface.seed) && /^[a-z][a-z0-9-]*$/.test(surface.seed), `Invalid seed ${JSON.stringify(surface.seed)}.`);
16
+ add('specialist', text(surface.specialist), 'Agent surface must name its specialist.');
17
+ add('tools', Array.isArray(surface.tools) && surface.tools.length > 0, 'Agent surface must declare its tools.');
18
+ add('notTools', Array.isArray(surface.notTools), 'Agent surface must declare notTools.');
19
+ add('resources', Array.isArray(surface.resources), 'Agent surface must declare resources.');
20
+ for (const uri of Array.isArray(surface.resources) ? surface.resources : []) add(`resource.${String(uri)}`, text(uri), 'Resource template must be a URI string.');
21
+ add('journey', Array.isArray(surface.journey) && surface.journey.length > 0, 'Agent surface must declare its journey.');
22
+ const escalation = (id, ok, detail) => points.push({ id: `BASE-AGENT-005.surface.${id}`, ok: Boolean(ok), ...(!ok ? { detail } : {}) });
23
+ escalation('escalations', surface.escalations === undefined || Array.isArray(surface.escalations), 'Agent surface must declare its escalations.');
24
+ const tools = new Map(), steps = new Set(), coverage = new Map();
25
+ for (const [i, tool] of (Array.isArray(surface.tools) ? surface.tools : []).entries()) {
26
+ const name = tool?.name, label = text(name) ? name : `tools[${i}]`;
27
+ add(`${label}.name`, validToolName(name, surface.seed) && !tools.has(name), `Malformed, duplicate or foreign-seed tool ${JSON.stringify(name)}.`);
28
+ add(`${label}.scope`, text(tool?.scope), `${label} must declare its scope.`);
29
+ add(`${label}.readOnly`, typeof tool?.readOnly === 'boolean', `${label} must declare readOnly.`);
30
+ add(`${label}.classes`, Array.isArray(tool?.classes) && tool.classes.length > 0 && new Set(tool.classes).size === tool.classes.length && tool.classes.every(cls => AGENT_CLASSES.includes(cls)), `${label} has an empty, duplicate or uncatalogued class: ${JSON.stringify(tool?.classes)}.`);
31
+ if (tool?.sponsorEscalation !== undefined) escalation(`${label}.sponsor-escalation`, typeof tool.sponsorEscalation === 'boolean' && Array.isArray(tool.classes) && tool.classes.some(cls => ['access', 'security'].includes(cls)), `${label} sponsorEscalation must be a boolean on an access or security tool.`);
32
+ if (tool?.authority === 'none') escalation(`${label}.authority-none`, recordOnlyAuthority(tool), `${label} authority:none requires a closed record-only schema and a justified record effect, with no authority-bearing fields.`);
33
+ const clauses = Array.isArray(tool?.clauses) ? tool.clauses : [];
34
+ add(`${label}.clauses`, clauses.length > 0 && clauses.every(text), `${label} must name its contract clauses.`);
35
+ if (contract !== undefined) for (const clause of clauses) add(`${label}.clause.${clause}`, hasClause(contract, clause), `${label} names clause ${clause}, absent from CONTRACT.md.`);
36
+ if (tool?.proof !== undefined || tool?.proofKind !== undefined) add(`${label}.proof`, tool.proof === 'native' && typeof tool.proofKind === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(tool.proofKind), `${label} must declare proof native and its named proofKind.`);
37
+ if (tool?.widens !== undefined || tool?.narrowing !== undefined) escalation(`${label}.narrowing-contract`, tool.widens === false && tool.readOnly === false && tool.classes?.some(cls => ['access', 'security'].includes(cls)) && narrowingContract(tool), `${label} narrowing requires revoke/narrow and a closed target-only string schema.`);
38
+ tools.set(name, tool); coverage.set(name, new Set());
39
+ }
40
+ for (const [i, item] of (Array.isArray(surface.notTools) ? surface.notTools : []).entries()) {
41
+ add(`notTools.${i}`, object(item) && ['device', 'screen', 'connector', 'import-door', 'installation'].includes(item.reason) && Array.isArray(item.clauses) && item.clauses.length > 0 && item.clauses.every(text), `notTools[${i}] must name clauses and a concrete reason other than risk.`);
42
+ if (contract !== undefined && Array.isArray(item?.clauses)) for (const clause of item.clauses) add(`notTools.${i}.${clause}`, hasClause(contract, clause), `notTools[${i}] names clause ${clause}, absent from CONTRACT.md.`);
43
+ }
44
+ const references = (value, visit) => {
45
+ if (Array.isArray(value)) value.forEach(item => references(item, visit));
46
+ else if (object(value)) { if ('$from' in value || '$sponsor' in value || '$fixture' in value) visit(value); else Object.values(value).forEach(item => references(item, visit)); }
47
+ };
48
+ const checkReferences = (value, label, available, addPoint = add) => references(value, ref => {
49
+ if ('$sponsor' in ref) addPoint(`${label}.sponsor`, Object.keys(ref).length === 1 && ['id', 'email'].includes(ref.$sponsor), `${label} must reference the sponsor as {$sponsor:'id'} or {$sponsor:'email'}.`);
50
+ else if ('$fixture' in ref) addPoint(`${label}.fixture`, text(surface.verification?.fixtures?.module) && text(ref.$fixture) && Object.keys(ref).sort().join(',') === '$fixture,pointer' && typeof ref.pointer === 'string' && (ref.pointer === '' || ref.pointer.startsWith('/')), `${label} requires verification.fixtures and a named fixture with a JSON pointer.`);
51
+ else addPoint(`${label}.ref.${ref.$from}`, available.has(ref.$from) && typeof ref.pointer === 'string' && (ref.pointer === '' || ref.pointer.startsWith('/')), `${label} references ${ref.$from} before its structuredContent is available, or has an invalid JSON pointer.`);
52
+ });
53
+ for (const [i, step] of (Array.isArray(surface.journey) ? surface.journey : []).entries()) {
54
+ const id = text(step?.id) ? step.id : `journey[${i}]`, tool = tools.get(step?.tool);
55
+ add(`journey.${id}`, object(step) && text(step.id) && !steps.has(step.id) && Boolean(tool) && object(step.args) && Array.isArray(step.expect) && step.expect.length > 0, `Invalid or duplicate journey step ${id}, tool ${JSON.stringify(step?.tool)}.`);
56
+ const expect = Array.isArray(step?.expect) ? step.expect : [];
57
+ add(`journey.${id}.classes`, new Set(expect.map(item => item?.class)).size === expect.length && expect.every(item => object(item) && Array.isArray(tool?.classes) && tool.classes.includes(item.class) && (item.facts === undefined || object(item.facts))), `${id} expects duplicate, undeclared or malformed classes.`);
58
+ if (step?.client !== undefined) add(`journey.${id}.client`, text(step.client) && text(surface.verification?.fixtures?.module), `${id} requires a named native client and verification.fixtures.`);
59
+ for (const item of expect) coverage.get(step?.tool)?.add(item?.class);
60
+ checkReferences(step?.args, `journey.${id}`, steps);
61
+ if (step?.target !== undefined) {
62
+ const target = step.target;
63
+ add(`journey.${id}.target`, object(target) && Object.keys(target).sort().join(',') === 'id,kind' && text(target.kind) && (text(target.id) || object(target.id) && ('$from' in target.id || '$sponsor' in target.id || '$fixture' in target.id)), `${id}.target must contain only a nonempty kind and an id string or journey reference.`);
64
+ checkReferences(target, `journey.${id}.target`, steps);
65
+ }
66
+ if (step?.inject !== undefined) add(`journey.${id}.inject`, object(step.inject), `${id}.inject must be an object of additional arguments.`);
67
+ checkReferences(step?.inject, `journey.${id}.inject`, steps);
68
+ steps.add(step?.id);
69
+ }
70
+ const escalationIds = new Set(), escalationTools = new Set();
71
+ for (const [i, step] of (Array.isArray(surface.escalations) ? surface.escalations : []).entries()) {
72
+ const id = text(step?.id) ? step.id : `escalations[${i}]`, tool = tools.get(step?.tool);
73
+ escalation(id, object(step) && text(step.id) && !escalationIds.has(step.id) && Boolean(tool) && object(step.args), `Invalid or duplicate escalation ${id}, tool ${JSON.stringify(step?.tool)}.`);
74
+ escalation(`${id}.authority`, Array.isArray(tool?.classes) && tool.classes.some(cls => ['access', 'security'].includes(cls)) && tool.widens !== false && tool.sponsorEscalation !== false, `${id} must exercise a tool declared capable of widening its sponsor's authority.`);
75
+ checkReferences(step?.args, `escalations.${id}`, steps, escalation);
76
+ escalationIds.add(step?.id); escalationTools.add(step?.tool);
77
+ }
78
+ const narrowingTools = new Set();
79
+ for (const [i, fixture] of (Array.isArray(surface.narrowings) ? surface.narrowings : []).entries()) {
80
+ const tool = tools.get(fixture?.tool), witness = fixture?.witness;
81
+ const targets = narrowingTargets(tool);
82
+ escalation(`narrowing.${i}`, tool?.widens === false && !narrowingTools.has(fixture.tool) && steps.has(fixture.step) && surface.journey.some(step => step.id === fixture.step && step.tool === fixture.tool) && tools.get(witness?.tool)?.readOnly === true && object(witness?.args) && targets.length > 0 && targets.every(target => Object.hasOwn(witness.args, target)) && typeof witness?.pointer === 'string' && (witness.pointer === '' || witness.pointer.startsWith('/')), 'Narrowing fixture must name its journey step and a native grant-set witness with every target identifier.');
83
+ checkReferences(witness?.args, `narrowing.${i}.witness`, steps, escalation);
84
+ narrowingTools.add(fixture?.tool);
85
+ }
86
+ for (const [name, tool] of tools) if (Array.isArray(tool?.classes) && tool.classes.some(cls => ['access', 'security'].includes(cls))) escalation(`${name}.coverage`, tool.authority === 'none' && recordOnlyAuthority(tool) || (tool.widens === false ? narrowingTools.has(name) : tool.sponsorEscalation === false || escalationTools.has(name)), `${name} has no ${tool.widens === false ? 'narrowing check' : 'sponsor escalation fixture'}.`);
87
+ for (const [name, tool] of tools) for (const cls of Array.isArray(tool?.classes) ? tool.classes : []) add(`${name}.coverage.${cls}`, coverage.get(name).has(cls), `${name} has no journey fixture for declared class ${cls}.`);
88
+ add('events', tools.has(`${surface.seed}.events.list`), `Declare built-in ${surface.seed}.events.list in the Agent surface.`);
89
+ add('witness', object(surface.witness) && tools.get(surface.witness.tool)?.readOnly === true && object(surface.witness.args), 'witness must name a declared readOnly tool and arguments.');
90
+ checkReferences(surface.witness?.args, 'witness', new Set());
91
+ return { ok: points.every(point => point.ok), points };
92
+ }
@@ -0,0 +1,19 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { auditRows } from './audit-rows.mjs';
3
+ import { APPROVAL } from './protocol.mjs';
4
+
5
+ export const targetIdentity = value => value !== null && typeof value === 'object' && !Array.isArray(value)
6
+ && Object.keys(value).sort().join() === 'id,kind' && [value.kind, value.id].every(item => typeof item === 'string' && item.trim().length);
7
+
8
+ /** A journey expectation comes from native fixture state, never tool arguments alone. */
9
+ export async function checkTarget(c, step, outputs, answer, phase, execution = false) {
10
+ if (!step.target) return;
11
+ const expected = c.resolve(step.target, outputs), { rows } = await auditRows(c);
12
+ const row = execution ? rows.findLast(row => row.decision_id === answer.decision?.id) : rows.find(row => row.id === answer.decision?.id);
13
+ c.add(`BASE-AGENT-009.target.${phase}.${step.id}${execution ? '.execution' : ''}`, targetIdentity(expected) && isDeepStrictEqual(row?.resource, expected), `${step.tool} must audit its resolved native kind and id: ${JSON.stringify(row?.resource)} != ${JSON.stringify(expected)}.`);
14
+ const approval = answer.result?._meta?.[APPROVAL];
15
+ if (approval?.id && !execution) {
16
+ const view = await c.personJson(`/agents/api/approvals/${encodeURIComponent(approval.id)}`);
17
+ c.add(`BASE-AGENT-008.target.${phase}.${step.id}`, isDeepStrictEqual(view.approval?.summary?.nativeTarget, expected), `${step.tool} must bind the resolved native target into its approval summary.`);
18
+ }
19
+ }
@@ -0,0 +1 @@
1
+ export function validToolName(name: unknown, seed: string): boolean;
@@ -0,0 +1,7 @@
1
+ // One grammar for declaration validation, runtime registration and MCP exposure.
2
+ // MCP tool names are limited to 128 ASCII letters, digits, underscores, dots or
3
+ // hyphens. The seed prefix retains the existing seed-id grammar.
4
+ export function validToolName(name, seed) {
5
+ return typeof name === 'string' && name.length <= 128 &&
6
+ /^[a-z][a-z0-9-]*\.[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/.test(name) && name.split('.')[0] === seed;
7
+ }
@@ -0,0 +1,31 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { autonomousPolicy } from './crypto.mjs';
3
+
4
+ export async function webhookPhase(c, webhooks) {
5
+ await c.adopt(autonomousPolicy());
6
+ await c.prepare('webhook');
7
+ const outputs = new Map();
8
+ for (const id of webhooks.prepare) {
9
+ const step = c.surface.journey.find(step => step.id === id);
10
+ if (!step) throw new Error('Webhook preparation must name existing journey steps.');
11
+ const answer = await c.stepTool(step, c.args(step, outputs));
12
+ if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error('Could not prepare native webhook records.');
13
+ outputs.set(id, answer.result.structuredContent);
14
+ }
15
+ const requests = await webhooks.requests({ origin: c.origin, outputs });
16
+ for (const kind of ['valid', 'invalid']) {
17
+ const request = requests?.[kind];
18
+ if (!request || new URL(request.url).origin !== c.origin || request.method !== 'POST') throw new Error('Webhook probes must be POST requests to the disposable installation origin.');
19
+ }
20
+ const before = await c.witness();
21
+ const invalid = requests.invalid;
22
+ const denied = await c.request(invalid.url, { method: invalid.method, headers: Object.fromEntries(invalid.headers), body: await invalid.arrayBuffer() });
23
+ c.add('BASE-AGENT-006.webhook.invalid', [401, 403].includes(denied.status), 'The seed must refuse an inbound webhook signed with the wrong per-install key.');
24
+ await denied.body?.cancel();
25
+ c.add('BASE-AGENT-006.webhook.unchanged', isDeepStrictEqual(before, await c.witness()), 'A wrongly signed inbound webhook changed native state.');
26
+ const valid = requests.valid;
27
+ const accepted = await c.request(valid.url, { method: valid.method, headers: Object.fromEntries(valid.headers), body: await valid.arrayBuffer() });
28
+ c.add('BASE-AGENT-006.webhook.valid', accepted.ok, 'The seed must accept the inbound webhook signed with its own per-install random key.');
29
+ await accepted.body?.cancel();
30
+ c.add('BASE-AGENT-006.webhook.effect', !isDeepStrictEqual(before, await c.witness()), 'The accepted inbound webhook must retain its native effect.');
31
+ }
@@ -3,10 +3,16 @@ import {deliveryDeclarationSources} from '../../cli/delivery-declarations.mjs';
3
3
  import {sourcePath} from '../delivery-producer/migrations.mjs';
4
4
  import {usesManagedMail,validateMailSpec} from '../delivery-producer/mail.mjs';
5
5
 
6
+ /** Shared binding comparison for source checks and emitted image validation. */
7
+ export function imageVariableSecrets(vars, secrets) {
8
+ return secrets.filter(secret => Object.hasOwn(vars, secret.binding));
9
+ }
10
+
6
11
  /** Drop empty runtime-secret placeholders; admit only managed-mail public legacy values. */
7
12
  export async function checkImageVariables(root,vars,secrets) {
8
- const placeholders=secrets.filter(secret=>Object.hasOwn(vars,secret.binding) && vars[secret.binding] === '');
9
- const overlaps=secrets.filter(secret=>Object.hasOwn(vars,secret.binding) && vars[secret.binding] !== '');
13
+ const declared=imageVariableSecrets(vars,secrets);
14
+ const placeholders=declared.filter(secret=>vars[secret.binding] === '');
15
+ const overlaps=declared.filter(secret=>vars[secret.binding] !== '');
10
16
  if (!overlaps.length) {
11
17
  for (const {binding} of placeholders) delete vars[binding];
12
18
  return;
@@ -3,6 +3,25 @@ import {keys, strings} from './bindings.mjs';
3
3
  const publicNames = ['MAIL_PROVIDER', 'MAIL_FROM', 'MAIL_RELAY_URL'];
4
4
  const providerLabels = {rer: 'RER managed mail', resend: 'Resend', sendgrid: 'SendGrid', cloudflare: 'Cloudflare Email Sending'};
5
5
 
6
+ /** Empty defaults leave the single MAIL_FROM input unconfigured. Never choose between senders. */
7
+ export function validateMailSenders(sources) {
8
+ let sender;
9
+ for (const source of sources) {
10
+ if (typeof source.value !== 'string' || !source.value.trim()) continue;
11
+ if (sender && sender.value !== source.value) {
12
+ throw Object.assign(Error(`Conflicting MAIL_FROM senders: ${sender.source} (${JSON.stringify(sender.value)}) and ${source.source} (${JSON.stringify(source.value)}). Declare one sender consistently.`), {code:'mail_sender_conflict'});
13
+ }
14
+ sender = source;
15
+ }
16
+ }
17
+
18
+ /** The delivery policy owns classification; a deploy input may supply this same public binding. */
19
+ export function publicMailSender(spec) {
20
+ if (!usesManagedMail(spec.mail)) return false;
21
+ const names = spec.publicVariableNames ?? Object.keys(spec.publicVariables ?? {});
22
+ return names.includes('MAIL_FROM') && ![...(spec.secretNames ?? []), ...(spec.optionalSecretNames ?? [])].includes('MAIL_FROM');
23
+ }
24
+
6
25
  /** Managed mail is an explicit capability, independent of direct provider adapters. */
7
26
  export function usesManagedMail(mail) {
8
27
  if (mail === undefined) return false;
@@ -35,6 +54,7 @@ export function generateMailSetupFields(mail) {
35
54
 
36
55
  export function validateMailSpec(spec) {
37
56
  if (!usesManagedMail(spec.mail)) return;
57
+ if (!publicMailSender(spec)) throw Error('Managed mail requires one public MAIL_FROM sender, not a secret MAIL_FROM');
38
58
  for (const name of publicNames) {
39
59
  if (!Object.hasOwn(spec.publicVariables, name)) throw Error(`Managed mail requires public ${name}`);
40
60
  }
@@ -36,6 +36,12 @@ host. See [adoption and deployment](https://github.com/runeditrun/base/blob/main
36
36
  - `upgrade.mjs`: verifies ownership, removes the old Container application and
37
37
  derives the class migration from deployed namespaces and migration tag.
38
38
  - `remove.mjs`: exact-id teardown, ownership collision checks and absence reads.
39
+ - `ownership.mjs`: read-only recovery when secret PUT removed the version message.
40
+ The served version must be newest, with a contiguous secret-triggered history
41
+ back to this demo's rer record and identical script ETag, runtime and bindings
42
+ (including secret names and bound resource IDs). Only upload-tool provenance may
43
+ differ. Missing history, changed resources or a foreign message refuses before
44
+ writes. The next ordinary deploy writes the annotation again.
39
45
 
40
46
  The historical resource-name hash remains stable so released container demos
41
47
  can upgrade and be removed from a fresh checkout. Portable container hosting
@@ -0,0 +1,39 @@
1
+ import { hash, uuid, identifier } from '../deploy-kit/validation.mjs';
2
+
3
+ // Secret PUT drops the version message but retains code, runtime and bindings
4
+ // (secret values are not readable). Ignore only the upload tool's provenance;
5
+ // compare every other resource field, including assets and binding identities.
6
+ function identity(version) {
7
+ const resources = version?.resources, script = resources?.script, bindings = resources?.bindings;
8
+ if (typeof script?.etag !== 'string' || !script.etag || !resources.script_runtime?.compatibility_date
9
+ || !Array.isArray(bindings) || !bindings.every(row => identifier(row?.name) && typeof row.type === 'string')
10
+ || new Set(bindings.map(row => row.name)).size !== bindings.length) return null;
11
+ const content = { ...script };
12
+ // The provider changes this from wrangler to api on a secret PUT.
13
+ delete content.last_deployed_from;
14
+ return hash({ ...resources, script: content, bindings: [...bindings].sort((a, b) => a.name.localeCompare(b.name)) });
15
+ }
16
+
17
+ /** Read-only proof under this account and Worker name. Never jump over a foreign
18
+ * version to find an older rer mark, or accept an undeployed/split successor. */
19
+ export async function secretRotationOwned(api, plan, served) {
20
+ if (!served.current || served.annotation !== undefined) return false;
21
+ const path = `/workers/scripts/${plan.worker}/versions`;
22
+ const items = (await api.request(path))?.items;
23
+ if (!Array.isArray(items) || items[0]?.id !== served.versionId || !items.every(row => uuid(row?.id))
24
+ || new Set(items.map(row => row.id)).size !== items.length) return false;
25
+ let expected;
26
+ for (const { id } of items) {
27
+ let version;
28
+ try { version = await api.request(`${path}/${id}`); }
29
+ catch (error) { if (error.status === 404) return false; throw error; }
30
+ if (version?.id !== id) return false;
31
+ const fingerprint = identity(version);
32
+ if (!fingerprint || expected && fingerprint !== expected) return false;
33
+ expected ??= fingerprint;
34
+ const message = version.annotations?.['workers/message'];
35
+ if (message !== undefined) return message === plan.record;
36
+ if (version.annotations?.['workers/triggered_by'] !== 'secret') return false;
37
+ }
38
+ return false;
39
+ }
@@ -57,6 +57,7 @@ export function demoPlan({ project, environment, compatibilityDate, originVar, h
57
57
 
58
58
  /** The demo's record of what `rer deploy --demo` creates, kept on the provider so a
59
59
  * fresh checkout (a CI runner) can remove it: the deploy writes it as the Worker
60
- * version's message, and only a Worker serving it is taken for the demo's own. */
60
+ * version's message. A secret-only successor can prove continuity against that
61
+ * retained version without changing the provider during inventory. */
61
62
  export const demoRecord = ({ worker, hostname, hostnames = [hostname], container }) =>
62
63
  `rer-demo:${hash({ worker, hostname, container, ...(hostnames.length > 1 ? { hostnames } : {}) })}`;
@@ -2,6 +2,7 @@ import { ownedBucket, removeBucket } from './native/deploy-r2.mjs';
2
2
  import { assert } from '../deploy-kit/validation.mjs';
3
3
  import { workerSettings } from '../deploy-kit/owner.mjs';
4
4
  import { servedVersion } from '../deploy-kit/site.mjs';
5
+ import { secretRotationOwned } from './ownership.mjs';
5
6
  import { deleteWorker } from '../deploy-kit/teardown.mjs';
6
7
 
7
8
  // Exact-id teardown and ownership inventory, shared by native upgrades.
@@ -23,7 +24,11 @@ export async function demoInventory(api, plan) {
23
24
  for (const row of named) if (row.service !== plan.worker) throw refuse('resource-name-collision', `domain:${row.hostname}`);
24
25
  if (worker) {
25
26
  const served = await servedVersion(api, plan.worker);
26
- if (served.annotation !== plan.record) throw refuse('resource-name-collision', `worker:${plan.worker}`);
27
+ if (served.annotation !== plan.record && !await secretRotationOwned(api, plan, served)) {
28
+ const error = refuse('resource-name-collision', `worker:${plan.worker}`);
29
+ error.ownershipReason = served.annotation === undefined ? 'missing-annotation' : 'different-annotation';
30
+ throw error;
31
+ }
27
32
  if (!served.current) throw refuse('owned-resource-replaced', `worker:${plan.worker}`);
28
33
  for (const row of attached) if (!plan.hostnames.includes(row.hostname)) throw refuse('resource-not-in-record', `domain:${row.hostname}`);
29
34
  } else if (named.length || attached.length || apps.length) {