@runeditrun/rer 0.2.91 → 0.2.94

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 (58) hide show
  1. package/cli/README.md +1 -1
  2. package/cli/agent-door.mjs +20 -10
  3. package/cli/agent-history-database.mjs +82 -0
  4. package/cli/agent-history-isolation.mjs +68 -0
  5. package/cli/agent-history.mjs +58 -0
  6. package/cli/agent-journey-fixtures.mjs +3 -3
  7. package/cli/agent-network.mjs +12 -6
  8. package/cli/business/choices.mjs +3 -3
  9. package/cli/business/command.mjs +19 -0
  10. package/cli/business/setup-command.mjs +14 -1
  11. package/cli/deploy-command.mjs +19 -8
  12. package/cli/deploy.mjs +1 -1
  13. package/cli/export.mjs +1 -1
  14. package/cli/hosted-hosts.mjs +21 -0
  15. package/cli/hosted-output.mjs +91 -8
  16. package/cli/ledger-refusal.mjs +1 -1
  17. package/cli/lifecycle.mjs +5 -0
  18. package/cli/local.mjs +1 -1
  19. package/cli/port.mjs +1 -2
  20. package/cli/portability-evidence.d.mts +5 -0
  21. package/cli/portability-evidence.mjs +85 -0
  22. package/cli/portability-migrations.mjs +21 -9
  23. package/cli/portability-worker.mjs +4 -2
  24. package/edition-authoring/module-edges.mjs +14 -1
  25. package/foundation/runtime/contract-anchor.mjs +87 -0
  26. package/foundation/runtime/contract-docs.mjs +46 -16
  27. package/global/CHANGELOG.md +63 -0
  28. package/install.sh +4 -1
  29. package/modules/agent-door/conformance/crypto.mjs +14 -2
  30. package/modules/agent-door/conformance/injection.mjs +5 -3
  31. package/modules/agent-door/conformance/journey.mjs +27 -3
  32. package/modules/agent-door/conformance/negative.mjs +4 -1
  33. package/modules/agent-door/conformance/policy-phases.mjs +43 -1
  34. package/modules/agent-door/conformance/protocol.mjs +42 -7
  35. package/modules/agent-door/conformance/sponsors.mjs +4 -0
  36. package/modules/agent-door/conformance/surface.mjs +10 -0
  37. package/modules/deploy-kit/README.md +1 -1
  38. package/modules/deploy-kit/owner-cli.mjs +9 -1
  39. package/modules/deploy-kit/prepare.mjs +5 -2
  40. package/modules/erasure/README.md +4 -2
  41. package/modules/operator-auth/identity/oidc/README.md +2 -1
  42. package/modules/portability/README.md +84 -2
  43. package/modules/portability/backfills.mjs +96 -3
  44. package/modules/portability/bridge.mjs +3 -1
  45. package/modules/portability/catalogue.mjs +11 -1
  46. package/modules/portability/checkout-history.mjs +14 -0
  47. package/modules/portability/format.mjs +1 -0
  48. package/modules/portability/import.mjs +58 -3
  49. package/modules/portability/index.d.mts +3 -1
  50. package/modules/portability/index.mjs +16 -5
  51. package/modules/portability/library-history.mjs +147 -0
  52. package/modules/portability/migration-history.mjs +3 -2
  53. package/modules/portability/restore-safety.mjs +6 -3
  54. package/modules/portability/snapshot-objects.mjs +16 -0
  55. package/modules/portability/worker-history.d.mts +9 -0
  56. package/modules/portability/worker-history.mjs +29 -0
  57. package/onboarding/adapter.mjs +28 -14
  58. package/package.json +9 -1
package/cli/README.md CHANGED
@@ -415,7 +415,7 @@ declaration refuses completion. A kit or custom-hook deploy, except `--dry-run`,
415
415
  first refuses uncommitted tracked source, naming the files, before any build or
416
416
  upload.
417
417
 
418
- The owner deployment declaration may set top-level `"productDirectory": ".rer/deploy/product"` for a product staged by the build or deploy hook. It must name a normalized checkout-relative subdirectory: no absolute path, backslash, empty, `.` or `..` segment. The directory must exist after the build or hook, with no symlink on its path. rer reads this field and passes `--product` only to the kit's packaging commands (`local-plan`, `deploy` and `health`). A public dry run runs the build lifecycle instead of the custom upload hook. A hook that invokes the kit itself still supplies `--product` on its own invocation; the wrapper reads the declaration for its own steps. Omitting the field keeps packaging at the checkout root. State, root ownership, secret changes and removal keep their existing locations and behavior; dry run needs no credentials and never reads target secrets.
418
+ The owner deployment declaration may set top-level `"productDirectory": ".rer/deploy/product"` for a product staged by the build or deploy hook. It must name a normalized checkout-relative subdirectory: no absolute path, backslash, empty, `.` or `..` segment. The directory must exist after the build or hook, with no symlink on its path. rer reads this field and passes `--product` only to the kit's packaging commands (`local-plan`, `deploy` and `health`). A public dry run passes `options.dryRun` to the seed deploy hook for offline preflight; without a custom hook, the owner deployer runs the build lifecycle. Both paths return `dryRun: true`, `deployed: false` and `providerChecked: false` while listing missing real-deploy inputs. Hooks must keep this preflight offline; the wrapper validates legacy-hook artifacts with the local plan without contacting Cloudflare. A hook that invokes the kit itself still supplies `--product` on its own invocation; the wrapper reads the declaration for its own steps. Omitting the field keeps packaging at the checkout root. State, root ownership, secret changes and removal keep their existing locations and behavior; dry run needs no credentials and never reads target secrets.
419
419
 
420
420
  For a hosted owner claim, deploy reuses the name saved by `rer setup` in the
421
421
  checkout's `.seed/installer/setup-answers.json`, under the adapter's
@@ -15,6 +15,8 @@ import { verificationSponsors } from './agent-sponsors.mjs';
15
15
  import { verificationWebhooks } from './agent-webhooks.mjs';
16
16
  import { verificationInvoke, verificationJourney } from './agent-verifier.mjs';
17
17
  import { verificationBindings } from './agent-bindings.mjs';
18
+ import { writeVerificationHistory } from './agent-history-database.mjs';
19
+ import { verificationHistory } from './agent-history.mjs';
18
20
  import { journeyFixtures } from './agent-journey-fixtures.mjs';
19
21
  import { verificationAgentInitializer } from './agent-initializer.mjs';
20
22
 
@@ -65,10 +67,10 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
65
67
  const publicKeys = { [kid]: { kty, crv, x, y, kid, alg: 'ES256', use: 'sig' } };
66
68
  const values = { issuer, installationId, appOrigin: HOSTED_ORIGIN, publicKeys: JSON.stringify(publicKeys), email, sub, token, sessionSecret: randomBytes(32).toString('hex') };
67
69
  const nativeBindings = await verificationBindings(root, native.bindings, values);
68
- const network = await createAgentConformanceNetwork(root, verification.network, { email });
69
- let hosted;
70
+ const network = await createAgentConformanceNetwork(root, verification.network, { email, sponsorEmails: principals.slice(1).map(person => person.email) });
71
+ let hosted, history;
70
72
  try {
71
- hosted = await serveHosted(root, { declaration, rpc: verification.rpc, workerEntrypoints: workerDriver ? [workerDriver.entrypoint] : [], outboundService: async request => {
73
+ hosted = await serveHosted(root, { declaration, publicHosts: verification.publicHosts, fixturePreparation: true, rpc: verification.rpc, workerEntrypoints: workerDriver ? [workerDriver.entrypoint] : [], outboundService: async request => {
72
74
  const copy = reviewers.observes(request) ? request.clone() : null, response = await network.fetch(request);
73
75
  if (copy) await reviewers.capture(copy, response.clone());
74
76
  return response;
@@ -86,9 +88,9 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
86
88
  } });
87
89
  const request = (absolute, init = {}) => {
88
90
  const url = new URL(absolute);
89
- if (url.origin !== hosted.origin) throw new RerError('agent_door_origin', 'Agent conformance request must use the fresh hosted installation origin.', 1);
91
+ if (url.username || url.password || !hosted.origins.includes(url.origin)) throw new RerError('agent_door_origin', 'Agent conformance request must use a declared hosted installation origin.', 1);
90
92
  const timeout = AbortSignal.timeout(30_000);
91
- return hosted.fetch(url.href.slice(hosted.origin.length + 1), { ...init, signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout, headers: Object.fromEntries(new Headers(init.headers)) });
93
+ return hosted.fetch(url.href.slice(url.origin.length + 1), { ...init, origin: url.origin, signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout, headers: Object.fromEntries(new Headers(init.headers)) });
92
94
  };
93
95
  const path = claim?.mode === 'signed' ? claim.path ?? '/auth/owner-claim' : owner?.path ?? claim?.path ?? '/auth/bootstrap';
94
96
  const issued = seconds();
@@ -130,7 +132,7 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
130
132
  try {
131
133
  response = await principal.initialize({ request, origin: hosted.origin, email: principal.email, sub: principal.sub,
132
134
  label: principal.label, displayName: principal.label, token, claim: { mode: 'signed', path, token: signedClaim },
133
- owner: sponsors[0], database: hosted.database, mail: network.mail, fixtures: network.fixtures, returnTo: owner?.returnTo ?? '/',
135
+ owner: sponsors[0], database: hosted.database, mail: network.mailFor(principal.email), fixtures: network.fixtures, returnTo: owner?.returnTo ?? '/',
134
136
  });
135
137
  } catch { throw new RerError('agent_sponsor_bootstrap', 'An additional sponsor could not complete its native lifecycle through the disposable installation.', 1); }
136
138
  const session = response?.headers?.getSetCookie().map(value => value.split(';', 1)[0]).join('; ');
@@ -140,15 +142,23 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
140
142
  }
141
143
  const secrets = await network.provision(hosted);
142
144
  const webhooks = await verificationWebhooks(root, verification.webhooks, secrets);
143
- const journey = await verificationJourney(root, verification.journey, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures, database: hosted.database });
144
- const prepare = await journeyFixtures(root, verification.fixtures, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures, database: hosted.database });
145
+ history = await verificationHistory(root, verification.history);
146
+ const journey = await verificationJourney(root, verification.journey, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures, ...await hosted.preparation() });
147
+ const prepare = await journeyFixtures(root, verification.fixtures, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures, ...await hosted.preparation() });
148
+ const nativeStep = history ? async value => {
149
+ await history.run(value, (declaration, rows) => writeVerificationHistory(hosted, declaration, rows));
150
+ await journey.nativeStep?.(value);
151
+ } : journey.nativeStep;
145
152
  const result = await runAgentDoorConformance({ fetch: request, origin: hosted.origin, surface: declared.surface,
146
- signer: { issuer, installationId, kid, privateKey: pair.privateKey }, person: sponsors[0], sponsors: sponsors.filter(person => !negativeOnly.has(person.label)), webhooks, business, prove, ...journey, prepare, invoke: workerDriver?.run(hosted),
153
+ signer: { issuer, installationId, kid, privateKey: pair.privateKey }, person: sponsors[0], sponsors: sponsors.filter(person => !negativeOnly.has(person.label)), webhooks, business, prove, ...journey, nativeStep, prepare, invoke: workerDriver?.run(hosted),
147
154
  initializeAgent: initializeAgent && (({ agentId, person }) => initializeAgent({ agentId, person, request, origin: hosted.origin, mail: network.mail, fixtures: network.fixtures })),
148
155
  });
149
156
  const points = [...result.points, ...reviewers.points()];
150
157
  return finish({ ...result, points, ok: points.every(point => point.ok) }, report);
151
- } finally { reviewers.close(); try { await hosted?.close(); } finally { await network.close(); } }
158
+ } finally {
159
+ try { await history?.close(); }
160
+ finally { reviewers.close(); try { await hosted?.close(); } finally { await network.close(); } }
161
+ }
152
162
  }
153
163
 
154
164
  if (process.argv[1] && await realpath(new URL(import.meta.url)) === await realpath(process.argv[1])) {
@@ -0,0 +1,82 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { RerError } from './errors.mjs';
3
+ import { FixtureDatabaseError } from '../modules/agent-door/conformance/fixtures.mjs';
4
+ import { historyInvalid, isHistoryDeclaration } from './agent-history.mjs';
5
+
6
+ const installations = new WeakMap();
7
+ export const registerHistoryInstallation = (hosted, database) => installations.set(hosted, database);
8
+
9
+ // The only caller supplies Miniflare's fresh, nonpersistent local databases.
10
+ // No URL, database id, provider client or raw prepare capability is accepted
11
+ // from fixture output. The ordinary hosted database reader stays SELECT-only.
12
+ export async function writeVerificationHistory(hosted, declaration, rows) {
13
+ try {
14
+ if (!installations.has(hosted) || !isHistoryDeclaration(declaration)) throw historyInvalid();
15
+ const database = installations.get(hosted);
16
+ if (!Array.isArray(rows) || rows.length > 1000) throw historyInvalid();
17
+ const batches = new Map(), checked = new Set();
18
+ for (const row of rows) {
19
+ if (!row || Object.keys(row).sort().join(',') !== 'statement,values' || !Array.isArray(row.values)) throw historyInvalid();
20
+ const statement = declaration.statements.get(row.statement);
21
+ if (!statement || row.values.length !== statement.parameters
22
+ || row.values.some(value => value !== null && typeof value !== 'string' && !(typeof value === 'number' && Number.isFinite(value)))) throw historyInvalid();
23
+ if (!batches.has(statement.binding)) batches.set(statement.binding, { ...await database(statement.binding), rows: [] });
24
+ const batch = batches.get(statement.binding);
25
+ const key = statement.binding + ':' + statement.table.toLowerCase();
26
+ if (!checked.has(key)) {
27
+ const table = await batch.database.prepare("SELECT sql FROM sqlite_schema WHERE type='table' AND name=? COLLATE NOCASE").bind(statement.table).first();
28
+ const trigger = await batch.database.prepare("SELECT 1 AS found FROM sqlite_schema WHERE type='trigger' AND tbl_name=? COLLATE NOCASE").bind(statement.table).first();
29
+ // Refuse every target trigger, rather than trying to parse its transitive
30
+ // effects. INSERT cannot cause foreign-key UPDATE/DELETE cascades.
31
+ if (!table || !/^CREATE TABLE\b/i.test(table.sql) || trigger) throw historyInvalid();
32
+ checked.add(key);
33
+ }
34
+ batch.rows.push({ sql: statement.sql, values: row.values });
35
+ }
36
+ for (const { batch, rows } of batches.values()) if (rows.length) await batch(rows);
37
+ } catch { throw historyInvalid(); }
38
+ }
39
+
40
+ // Both preparation APIs use this one disposable D1 writer. The public phase
41
+ // handle exposes individual statements; declared history retains atomic batches
42
+ // and its stricter insert-only, trigger-free table checks above.
43
+ export function preparationDatabase(db) {
44
+ const refuse = () => { throw new RerError('hosted_database_invalid', new FixtureDatabaseError().message, 1); };
45
+ const check = sql => {
46
+ if (typeof sql !== 'string' || sql.includes(';')) return refuse();
47
+ const readOnly = /^\s*SELECT\b/i.test(sql);
48
+ const target = /^\s*(?:UPDATE\s+|INSERT\s+INTO\s+|DELETE\s+FROM\s+)([a-z_][a-z0-9_]*)\b/i.exec(sql)?.[1];
49
+ if (!readOnly && (!target || /^(?:agent_door_|sqlite_)/i.test(target))) return refuse();
50
+ return { readOnly, target };
51
+ };
52
+ const batch = async rows => {
53
+ try {
54
+ const checked = rows.map(row => ({ ...row, ...check(row.sql) }));
55
+ for (const { target } of checked.filter(row => !row.readOnly)) {
56
+ const table = await db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=? COLLATE NOCASE").bind(target).first();
57
+ if (!table) return refuse();
58
+ }
59
+ const protectedTables = checked.some(row => !row.readOnly)
60
+ ? (await db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND lower(substr(name,1,11))='agent_door_'").all()).results : [];
61
+ const guards = protectedTables.flatMap(({ name }) => ['INSERT', 'UPDATE', 'DELETE'].map(event => ({
62
+ name: 'rer_fixture_' + randomBytes(16).toString('hex'), table: name.replaceAll('"', '""'), event,
63
+ })));
64
+ const results = await db.batch([
65
+ ...guards.map(guard => db.prepare(`CREATE TRIGGER "${guard.name}" BEFORE ${guard.event} ON "${guard.table}" BEGIN SELECT RAISE(ABORT, 'fixture protocol write refused'); END`)),
66
+ ...checked.map(({ sql, values }) => db.prepare(sql).bind(...values)),
67
+ ...guards.map(guard => db.prepare(`DROP TRIGGER "${guard.name}"`)),
68
+ ]);
69
+ return results.slice(guards.length, guards.length + checked.length);
70
+ } catch { return refuse(); }
71
+ };
72
+ const statement = (sql, values = []) => {
73
+ check(sql);
74
+ const execute = async () => (await batch([{ sql, values }]))[0];
75
+ return Object.freeze({
76
+ bind: (...bound) => statement(sql, bound), all: execute, run: execute,
77
+ first: async column => { const row = (await execute()).results[0] ?? null; return column === undefined ? row : row?.[column] ?? null; },
78
+ raw: async () => (await execute()).results.map(row => Object.values(row)),
79
+ });
80
+ };
81
+ return { database: Object.freeze({ prepare: sql => statement(sql) }), batch };
82
+ }
@@ -0,0 +1,68 @@
1
+ import { readdir, readFile, realpath } from 'node:fs/promises';
2
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import { join, relative, resolve } from 'node:path';
4
+ import { testSource } from '../composition/git-source.mjs';
5
+ import { dependencies } from '../edition-authoring/module-edges.mjs';
6
+ import { resolve as resolveModule } from '../edition-authoring/module-resolution.mjs';
7
+ import { RerError } from './errors.mjs';
8
+
9
+ const productionHistory = (name, target = name) => new RerError('agent_history_invalid', `agent_history_invalid: Production file ${name} references verification-only history module ${target}.`, 1);
10
+
11
+ // Check runtime import edges without executing test code. Scan source as well as
12
+ // unbundled output, following literal imports/re-exports, import.meta.url
13
+ // resources (including Workers), TS paths and symlinks.
14
+ // Shared native helpers remain usable by production; only the fixture's tests/
15
+ // modules are barred. An undeclared seed performs no additional scan.
16
+ export async function refuseHistoryImports(root, source) {
17
+ const files = new Set(), physical = new Map();
18
+ const ignored = new Set(['node_modules', '.git', '.rer', '.wrangler', '.seed', '.cache', 'test-results', 'playwright-report']);
19
+ async function walk(directory = '') {
20
+ for (const entry of await readdir(join(root, directory), { withFileTypes: true })) {
21
+ if (ignored.has(entry.name)) continue;
22
+ const name = directory ? directory + '/' + entry.name : entry.name;
23
+ if (entry.isDirectory()) await walk(name);
24
+ else if (entry.isFile() || entry.isSymbolicLink()) {
25
+ files.add(name);
26
+ physical.set(name, await realpath(join(root, name)));
27
+ }
28
+ }
29
+ }
30
+ await walk();
31
+ const forbidden = new Set(await Promise.all(source.modules.filter(module => relative(source.root, module.path).startsWith('tests/')).map(module => realpath(module.path))));
32
+ const tree = { has: name => {
33
+ if (files.has(name)) return true;
34
+ if (name.startsWith('../') || name.split('/').some(part => ignored.has(part))) return false;
35
+ // Literal imports may cross a contained directory symlink that the directory
36
+ // walk deliberately does not follow. Resolve that file physically too.
37
+ try {
38
+ if (!statSync(join(root, name)).isFile()) return false;
39
+ files.add(name); physical.set(name, realpathSync(join(root, name)));
40
+ return true;
41
+ } catch { return false; }
42
+ }, read: name => readFileSync(join(root, name), 'utf8') };
43
+ let paths = {};
44
+ try { paths = JSON.parse(await readFile(join(root, 'tsconfig.json'), 'utf8')).compilerOptions?.paths ?? {}; } catch { /* Relative resolution still applies. */ }
45
+ const queue = [...files].filter(name => !testSource(name) && !name.startsWith('scripts/') && /\.[cm]?[jt]sx?$/.test(name)), seen = new Set();
46
+ while (queue.length) {
47
+ const name = queue.shift();
48
+ if (seen.has(name)) continue;
49
+ seen.add(name);
50
+ if (forbidden.has(physical.get(name))) throw productionHistory(name);
51
+ for (const request of dependencies(await readFile(join(root, name), 'utf8'), name, {resources: true}).filter(request => !request.types)) {
52
+ const candidates = [request.specifier];
53
+ for (const [alias, targets] of Object.entries(paths)) {
54
+ const [prefix, suffix = ''] = alias.split('*');
55
+ if (alias.includes('*') ? request.specifier.startsWith(prefix) && request.specifier.endsWith(suffix) : request.specifier === alias) {
56
+ for (const target of targets) candidates.push('./' + relative(resolve(root, name, '..'), resolve(root, target.replace('*', request.specifier.slice(prefix.length, suffix ? -suffix.length : undefined)))));
57
+ }
58
+ }
59
+ for (const specifier of candidates) {
60
+ const target = resolveModule(tree, name, specifier, request);
61
+ if (typeof target === 'string') {
62
+ if (forbidden.has(physical.get(target))) throw productionHistory(name, target);
63
+ if (/\.[cm]?[jt]sx?$/.test(target)) queue.push(target);
64
+ }
65
+ }
66
+ }
67
+ }
68
+ }
@@ -0,0 +1,58 @@
1
+ import { relative } from 'node:path';
2
+ import { isolatedNetworkAdapter } from '../modules/agent-door/conformance/network-runtime.mjs';
3
+ import { networkAdapterModules } from '../modules/agent-door/conformance/network-modules.mjs';
4
+ import { RerError } from './errors.mjs';
5
+ import { refuseHistoryImports } from './agent-history-isolation.mjs';
6
+
7
+ export const historyInvalid = () => new RerError('agent_history_invalid', 'agent_history_invalid: Verification history requires contained test-only modules and named, insert-only statements on declared disposable tables without triggers. No fixture values or SQL are logged.', 1);
8
+ const declarations = new WeakSet();
9
+ export const isHistoryDeclaration = value => declarations.has(value);
10
+ const identifier = '[A-Za-z_][A-Za-z0-9_]*';
11
+ // A deliberately small SQL language: no SELECT, expressions, conflict updates,
12
+ // schema qualifiers, comments, pragmas or multiple statements. Literals let a
13
+ // shared native records table constrain each statement to one history kind.
14
+ const insert = new RegExp(`^INSERT INTO (${identifier})\\s*\\((${identifier}(?:\\s*,\\s*${identifier})*)\\)\\s*VALUES\\s*\\((\\?|[0-9]+|'[A-Za-z0-9_-]*')(?:\\s*,\\s*(\\?|[0-9]+|'[A-Za-z0-9_-]*'))*\\)$`, 'i');
15
+
16
+ export async function historyDeclaration(root, config) {
17
+ if (config === undefined) return;
18
+ try {
19
+ if (!config || Object.keys(config).sort().join(',') !== 'module,statements,steps'
20
+ || typeof config.module !== 'string' || !config.module.startsWith('tests/')
21
+ || !Array.isArray(config.steps) || !config.steps.length || config.steps.some(step => typeof step !== 'string' || !step)
22
+ || !config.statements || Array.isArray(config.statements) || typeof config.statements !== 'object' || !Object.keys(config.statements).length) throw historyInvalid();
23
+ const statements = new Map();
24
+ for (const [name, value] of Object.entries(config.statements)) {
25
+ if (!value || Object.keys(value).sort().join(',') !== 'binding,sql' || typeof value.binding !== 'string' || typeof value.sql !== 'string') throw historyInvalid();
26
+ const match = insert.exec(value.sql);
27
+ if (!match || /^(?:agent_door_|sqlite_|oa_)/i.test(match[1])) throw historyInvalid();
28
+ statements.set(name, { ...value, table: match[1], parameters: (value.sql.match(/\?/g) ?? []).length });
29
+ }
30
+ const source = await networkAdapterModules(root, config.module);
31
+ if (!relative(source.root, source.modules[0].path).startsWith('tests/')) throw historyInvalid();
32
+ await refuseHistoryImports(root, source);
33
+ const declaration = { module: config.module, steps: new Set(config.steps), statements };
34
+ declarations.add(declaration);
35
+ return declaration;
36
+ } catch (error) {
37
+ if (error instanceof RerError && error.code === 'agent_history_invalid') throw error;
38
+ throw historyInvalid();
39
+ }
40
+ }
41
+
42
+ /** Only checkAgentDoor starts this isolated test Worker. No application binding,
43
+ * request credentials, Node API, filesystem or external network is supplied. */
44
+ export async function verificationHistory(root, config) {
45
+ const declaration = await historyDeclaration(root, config);
46
+ if (!declaration) return;
47
+ const adapter = await isolatedNetworkAdapter(root, declaration.module, () => new Response(null, { status: 502 }));
48
+ return { declaration, close: () => adapter.close(), run: async (context, write) => {
49
+ if (context.stage !== 'beforeStep' || !['autonomous', 'held'].includes(context.phase) || !declaration.steps.has(context.step.id)) return;
50
+ try {
51
+ const { phase, step, args, outputs, now } = context;
52
+ const response = await adapter.fetch(new Request('https://history.invalid/', { method: 'POST', body: JSON.stringify({ phase, step, args, outputs, now }) }));
53
+ const body = await response.text();
54
+ if (!response.ok || body.length > 2 * 1024 * 1024) throw historyInvalid();
55
+ await write(declaration, JSON.parse(body));
56
+ } catch { throw historyInvalid(); }
57
+ } };
58
+ }
@@ -4,7 +4,7 @@ import { contained } from './project.mjs';
4
4
  import { RerError } from './errors.mjs';
5
5
  import { FixtureDatabaseError } from '../modules/agent-door/conformance/fixtures.mjs';
6
6
 
7
- /** Test tooling receives the disposable installation's doors and state reader. */
7
+ /** Test tooling receives the disposable installation's preparation context. */
8
8
  export async function journeyFixtures(root, declaration, context) {
9
9
  if (declaration === undefined) return undefined;
10
10
  if (!declaration || Object.keys(declaration).join(',') !== 'module' || typeof declaration.module !== 'string') throw new RerError('agent_fixtures_invalid', 'verification.fixtures must name a contained test module.', 1);
@@ -12,9 +12,9 @@ export async function journeyFixtures(root, declaration, context) {
12
12
  const prepare = (await import(pathToFileURL(resolve(root, declaration.module)))).default;
13
13
  if (typeof prepare !== 'function') throw new RerError('agent_fixtures_invalid', 'verification.fixtures module must default-export a phase preparation function.', 1);
14
14
  return async ({ phase, tool, now }) => {
15
- try { return await prepare({ ...context, phase, tool, now }); }
15
+ try { context.queues?.release(); return await prepare({ ...context, phase, tool, now }); }
16
16
  catch (error) {
17
- if (error?.code === 'hosted_database_invalid') throw new FixtureDatabaseError();
17
+ if (error instanceof FixtureDatabaseError || error?.code === 'hosted_database_invalid') throw new FixtureDatabaseError();
18
18
  throw new Error('Native phase preparation failed; no captured mail, credentials or fixture values are logged.');
19
19
  }
20
20
  };
@@ -30,8 +30,14 @@ export async function agentConformanceNetwork(request) {
30
30
 
31
31
  /** Extend the paid network edge for declared origins, without running seed
32
32
  * modules in this process or giving them any route to the real network. */
33
- export async function createAgentConformanceNetwork(root, config, { email } = {}) {
34
- const mail = createCapturedMail(email);
33
+ export async function createAgentConformanceNetwork(root, config, { email, sponsorEmails = [] } = {}) {
34
+ const mailboxes = new Map([email, ...sponsorEmails].map(email => [email, createCapturedMail(email)]));
35
+ const closeMail = () => { for (const mail of mailboxes.values()) mail.close(); };
36
+ const mailFor = email => {
37
+ const mail = mailboxes.get(email);
38
+ if (!mail) throw new TypeError('Captured mail requires a declared verification principal.');
39
+ return { read: options => mail.read(options) };
40
+ };
35
41
  let declaration, adapter, fixtures;
36
42
  try {
37
43
  if (config !== undefined) {
@@ -40,22 +46,22 @@ export async function createAgentConformanceNetwork(root, config, { email } = {}
40
46
  }
41
47
  fixtures = createFixtureControl(declaration?.origins ?? new Set());
42
48
  } catch (error) {
43
- mail.close();
49
+ closeMail();
44
50
  if (error instanceof NetworkAdapterError) throw new RerError('agent_network_invalid', error.message, 1);
45
51
  throw error;
46
52
  }
47
- return { mail: { read: options => mail.read(options) }, fixtures: { set: (origin, value) => fixtures.set(origin, value) },
53
+ return { mail: mailFor(email), mailFor, fixtures: { set: (origin, value) => fixtures.set(origin, value) },
48
54
  provision: async hosted => {
49
55
  if (config?.secretSource === undefined) return {};
50
56
  const secrets = await verificationSecrets(root, config.secretSource, hosted.database);
51
57
  await adapter.provision(secrets);
52
58
  return secrets;
53
59
  },
54
- close: async () => { mail.close(); fixtures.close(); await adapter?.close(); }, fetch: async request => {
60
+ close: async () => { closeMail(); fixtures.close(); await adapter?.close(); }, fetch: async request => {
55
61
  const capture = request.clone(), origin = new URL(request.url).origin;
56
62
  try {
57
63
  const response = declaration?.origins.has(origin) ? await adapter.fetch(request, fixtures.get(origin)) : await agentConformanceNetwork(request);
58
- if (response.ok) await mail.capture(capture);
64
+ if (response.ok) await Promise.all([...mailboxes.values()].map((mail, index) => mail.capture(index === mailboxes.size - 1 ? capture : capture.clone())));
59
65
  else void capture.body?.cancel();
60
66
  return response;
61
67
  }
@@ -1,4 +1,4 @@
1
- import { basename } from 'node:path';
1
+ import { basename, join } from 'node:path';
2
2
  import { installService, removeService } from './service.mjs';
3
3
  import { installPermissions, removePermissions } from './permissions.mjs';
4
4
  import { saveState } from './state.mjs';
@@ -91,7 +91,7 @@ export async function applyChoices(api, state, { reconnecting = false } = {}) {
91
91
  }
92
92
  once('choices-next-step', `After choosing this computer's apps or settings in Business, run ${businessCommand('next')} to apply them and see the next task.\n`);
93
93
  if (carried) once(`carry:${JSON.stringify(carried)}`, carried.checkouts.length
94
- ? `Apps on this computer now show ${JSON.stringify(carried.name)}: ${carried.checkouts.map(checkout => JSON.stringify(basename(checkout))).join(', ')}.\n`
95
- : `No apps on this computer were updated to show ${JSON.stringify(carried.name)}.\n`);
94
+ ? carried.checkouts.map(checkout => `Wrote the Business name ${JSON.stringify(carried.name)} to ${join(checkout, '.rer/local/business.json')}; ${JSON.stringify(basename(checkout))} shows it after it reads that file.\n`).join('')
95
+ : `No local app carry files were written for ${JSON.stringify(carried.name)}.\n`);
96
96
  return { applied: lines.length, serviceInstalled };
97
97
  }
@@ -45,8 +45,27 @@ State lives in $RER_BUSINESS_STATE_DIR when set, otherwise in ~/.rer/business.
45
45
  In an agent sandbox that writes only inside its working folder, use RER_BUSINESS_STATE_DIR="$PWD/.rer-business".
46
46
  `;
47
47
 
48
+ const verbHelp = {
49
+ connect: `Usage: rer business connect [--code CODE] [--origin URL]
50
+ Pair this computer with Business, waiting for the owner to approve the comparison
51
+ number in their browser (up to the code's 10 minutes). Run again to resume.
52
+
53
+ --code CODE Pairing code created in the Business browser.
54
+ --origin URL Business platform address (default: https://app.runeditrun.com).
55
+ Without a code, prints the path to create one or resumes this computer's pairing.
56
+ Carries the Business name into local app files for supporting apps to read.
57
+ Choose this computer's permissions and background service in the browser.
58
+ `,
59
+ token: `Usage: rer business token
60
+ Print an MCP Authorization header object for this computer's paired Business.
61
+ Send this headersHelper output directly to the MCP client; it contains a credential.
62
+ Requires an existing pairing: rer business connect.
63
+ `,
64
+ };
65
+
48
66
  export async function businessCommand(argv) {
49
67
  if (argv[0] === 'setup') return setupCommand(argv.slice(1));
68
+ if (Object.hasOwn(verbHelp, argv[0]) && argv.some(arg => ['--help', '-h'].includes(arg))) { process.stdout.write(verbHelp[argv[0]]); return 0; }
50
69
  if (!argv.length || argv[0] !== 'scan' && argv.some(arg => ['--help', '-h'].includes(arg))) { process.stdout.write(usage); return 0; }
51
70
  if (argv[0] === 'scan') return scanCommand(argv);
52
71
  try {
@@ -13,7 +13,20 @@ export async function setupCommand(args) {
13
13
  }
14
14
 
15
15
  async function setup(args){
16
- const usage='Usage: rer business setup --origin URL --session-file FILE --confirm-demo [--hosting managed|assisted|self_host] [--wait-seconds 0..240] [--json]';
16
+ const usage=`Usage: rer business setup --origin URL --session-file FILE --confirm-demo [--hosting managed|assisted|self_host] [--wait-seconds 0..240] [--json]
17
+ Provision the synthetic Run your business demo through the platform's owner routes.
18
+ Run again to resume; completed seeds are read without provisioning again.
19
+
20
+ --origin URL Platform address to set up the demo on.
21
+ --session-file FILE The signed-in session file Business setup reads: an owned,
22
+ regular 0600 file containing rer_session=VALUE or
23
+ __Host-rer_session=VALUE. Symlinks are refused.
24
+ The session is sent only as the platform Cookie header.
25
+ --confirm-demo Required confirmation to provision the synthetic demo.
26
+ --hosting MODE managed (default), assisted or self_host.
27
+ --wait-seconds N Provisioning wait, 0..240 seconds (default: 240).
28
+ --json Print the platform JSON receipt (also the default).
29
+ --help, -h Show this help without reading the session file.`;
17
30
  if(args.some(arg => ['--help', '-h'].includes(arg))){process.stdout.write(usage+'\n');return;}
18
31
  const options={};
19
32
  for(let i=0;i<args.length;i++){
@@ -14,7 +14,7 @@ import { observeOwner, ownerExchangeFailure } from './deploy-observation.mjs';
14
14
  import { committedSource } from './deploy-source.mjs';
15
15
  import { hookOrigin, waitForSource } from './deploy-hook.mjs';
16
16
  import { rememberHookState, hookState } from './deploy-hook-record.mjs';
17
- import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
17
+ import { main as owner, withLocalDeployPlan } from '../modules/deploy-kit/owner-cli.mjs';
18
18
  import { localOnlyBinding, ownerWorkerName } from '../modules/deploy-kit/owner.mjs';
19
19
  import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
20
20
  import { deployDiagnostic, migrationFailure, providerFailure, assetFailure } from '../modules/deploy-kit/diagnostics.mjs';
@@ -83,20 +83,31 @@ export async function deployCommand(context) {
83
83
  // Required secrets have been checked; retain the production sign-in guidance.
84
84
  const dryRun = async result => {
85
85
  const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
86
+ const plan = result?.plan ?? (await owner(['local-plan', '--declaration', path, '--environment', options.environment ?? 'production', ...await deployProductArguments(root, deployProductDirectory(declaration))], production.env, { cwd: root, localOnlyKeys })).plan;
87
+ result = { ...result, dryRun: true, deployed: false, providerChecked: false, plan };
86
88
  const { signIn } = await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options }) ?? {};
87
- const needed = neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: false });
89
+ const needed = [...new Set([...neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: false }), ...(result.neededForRealDeploy ?? [])])];
88
90
  reportNeeded(store, needed);
89
91
  if (declaration.secrets?.some(item => item.binding === 'INSTALLATION_KEY')) store.report('deploy: INSTALLATION_KEY is a private generated binding; INSTALLATION_KEY_PREVIOUS is optional and managed only during rotation or an explicit retired-key reopen. Values are withheld.');
90
92
  return needed.length && result && typeof result === 'object' ? { ...result, neededForRealDeploy: needed } : result;
91
93
  };
94
+ const runHook = hookContext => options.dryRun ? withLocalDeployPlan(async () => {
95
+ try { return await adapter.deploy(hookContext); }
96
+ catch (error) {
97
+ // Production-only owner/input preflights may refuse before the hook builds.
98
+ // An offline plan defers those inputs, retaining the refusal as guidance.
99
+ if (!(error instanceof RerError) || error.code !== 'missing_input') throw error;
100
+ const result = await ownerDeploy(path, adapter)(hookContext);
101
+ return { ...result, neededForRealDeploy: [error.message] };
102
+ }
103
+ }) : adapter.deploy(hookContext);
92
104
  // Custom hooks historically ignored these flags. Only the ownership controller
93
105
  // may perform them; neither a build nor a custom upload runs here.
94
106
  if (options.remove || options.setSecret || options.unsetSecret || options.reopenInstallationKey) return ownerDeploy(path, adapter)(context);
95
107
  if (options.rotateSecret?.split(',').includes('INSTALLATION_KEY')) return ownerDeploy(path, adapter)(context);
96
108
  // A hook that deployed through the kit keeps what its Worker holds: rotate there as a secret change.
97
109
  if (options.rotateSecret && !adapter.deploy.managesHostedOwner && await hookState(root, options.environment ?? 'production')) return ownerDeploy(path, adapter)(context);
98
- if (options.dryRun) return dryRun(await ownerDeploy(path, adapter)(context));
99
- if (adapter.deploy.managesHostedOwner) return adapter.deploy(context);
110
+ if (adapter.deploy.managesHostedOwner) { const result = await runHook(context); return options.dryRun ? dryRun(result) : result; }
100
111
  const productDirectory = deployProductDirectory(declaration);
101
112
  const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
102
113
  await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options });
@@ -114,7 +125,7 @@ export async function deployCommand(context) {
114
125
  // A hook keeping the kit's record in its own state file named it; every kit
115
126
  // step after the hook (inspect, secret, record-owner) reads that record.
116
127
  let hookRecord = await hookState(root, environment);
117
- const command = async (verb, extra = [], values = env, more = {}) => owner([verb, '--declaration', path, '--environment', environment, ...(hookRecord ? ['--state', hookRecord] : []), ...(['dry-run', 'deploy', 'health'].includes(verb) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
128
+ const command = async (verb, extra = [], values = env, more = {}) => owner([verb, '--declaration', path, '--environment', environment, ...(hookRecord ? ['--state', hookRecord] : []), ...(['dry-run', 'local-plan', 'deploy', 'health'].includes(verb) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
118
129
  // A hook that deployed through the kit's standard record lets rer issue and
119
130
  // retire the setup token; a hook keeping an unnamed record of its own keeps its token.
120
131
  let recorded, hookReturned = false;
@@ -133,7 +144,7 @@ export async function deployCommand(context) {
133
144
  Object.assign(process.env, env);
134
145
  // The hook builds and uploads by itself: it never sees the checkout's local settings.
135
146
  deployed = await withoutLocalSettings(root, { settings: [...(Array.isArray(adapter.settings) ? adapter.settings : []), adapter.hooks?.secrets?.file], operationToken: context.operationToken },
136
- () => adapter.deploy({ ...context, input: ownerInput.input, linkDependencies: async (origin, token) => link(token, origin) }));
147
+ () => runHook({ ...context, input: ownerInput.input, linkDependencies: async (origin, token) => link(token, origin) }));
137
148
  } finally {
138
149
  for (const key of Object.keys(process.env)) if (!Object.hasOwn(saved, key)) delete process.env[key];
139
150
  Object.assign(process.env, saved);
@@ -142,8 +153,8 @@ export async function deployCommand(context) {
142
153
  await deployProductArguments(root, productDirectory);
143
154
  await refuseLocalEnvOutput(root, adapter.devIdentity?.output, { uploaded: !options.dryRun });
144
155
  if (options.dryRun) {
145
- await command('dry-run');
146
- return dryRun(deployed);
156
+ const { plan } = await command('local-plan');
157
+ return dryRun({ ...deployed, plan });
147
158
  }
148
159
  await rememberHookState(root, environment, deployed?.state);
149
160
  hookRecord = await hookState(root, environment);
package/cli/deploy.mjs CHANGED
@@ -70,7 +70,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
70
70
  const {plan} = await owner('local-plan');
71
71
  store.report(`Would deploy: ${JSON.stringify(plan)}`);
72
72
  store.report('deploy: local dry run complete; no credentials were needed, no Cloudflare requests were made and nothing was changed remotely. Target secrets and remote readiness were not checked.');
73
- return { dryRun: true, deployed: false, plan };
73
+ return { dryRun: true, deployed: false, providerChecked: false, plan };
74
74
  }
75
75
  // A custom hook's own state file, when its deploy named one.
76
76
  const state = change.length ? recordedState : await hookState(root, environment);
package/cli/export.mjs CHANGED
@@ -12,7 +12,7 @@ sourceRoots.push('modules/agent-door/capabilities.mjs', 'modules/agent-door/capa
12
12
  sourceRoots.push('edition-authoring/archive-source.mjs');
13
13
  sourceRoots.push('edition-authoring/copy-namespaces.mjs');
14
14
  sourceRoots.push('edition-authoring/module-packages.mjs');
15
- sourceRoots.push('foundation/runtime/contract-prose.mjs', 'foundation/runtime/contract-prose-patterns.mjs');
15
+ sourceRoots.push('foundation/runtime/contract-prose.mjs', 'foundation/runtime/contract-prose-patterns.mjs', 'foundation/runtime/contract-anchor.mjs');
16
16
  export async function inventory(base, roots = sourceRoots) {
17
17
  const files = [];
18
18
  async function walk(path) {
@@ -0,0 +1,21 @@
1
+ import { RerError } from './errors.mjs';
2
+
3
+ // Admission is explicit: never infer additional hosts from arbitrary app vars.
4
+ // Each named binding must contain a bare canonical hostname in the selected
5
+ // deployment declaration, so verification and the hosted Worker agree.
6
+ export function hostedOrigins(declaration, bindings, primary) {
7
+ if (bindings === undefined) return Object.freeze([primary]);
8
+ const invalid = () => new RerError('agent_hosts_invalid', 'verification.publicHosts must list unique deployment variable names whose vars values are canonical hostnames.', 1);
9
+ if (!Array.isArray(bindings) || new Set(bindings).size !== bindings.length) throw invalid();
10
+ const origins = new Set([primary]);
11
+ for (const name of bindings) {
12
+ const host = declaration.vars?.[name];
13
+ if (typeof name !== 'string' || !/^[A-Z][A-Z0-9_]*$/.test(name) || !Object.hasOwn(declaration.vars ?? {}, name)
14
+ || typeof host !== 'string' || host.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(host)) throw invalid();
15
+ const origin = `https://${host}`;
16
+ try { if (new URL(origin).hostname !== host) throw invalid(); }
17
+ catch { throw invalid(); }
18
+ origins.add(origin);
19
+ }
20
+ return Object.freeze([...origins]);
21
+ }