@runeditrun/rer 0.2.93 → 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.
- package/cli/agent-door.mjs +20 -10
- package/cli/agent-history-database.mjs +82 -0
- package/cli/agent-history-isolation.mjs +68 -0
- package/cli/agent-history.mjs +58 -0
- package/cli/agent-journey-fixtures.mjs +3 -3
- package/cli/agent-network.mjs +12 -6
- package/cli/business/choices.mjs +3 -3
- package/cli/business/command.mjs +19 -0
- package/cli/business/setup-command.mjs +14 -1
- package/cli/export.mjs +1 -1
- package/cli/hosted-hosts.mjs +21 -0
- package/cli/hosted-output.mjs +91 -8
- package/cli/lifecycle.mjs +5 -0
- package/cli/local.mjs +1 -1
- package/cli/port.mjs +1 -2
- package/cli/portability-evidence.d.mts +5 -0
- package/cli/portability-evidence.mjs +85 -0
- package/cli/portability-migrations.mjs +12 -4
- package/edition-authoring/module-edges.mjs +14 -1
- package/foundation/runtime/contract-anchor.mjs +87 -0
- package/foundation/runtime/contract-docs.mjs +20 -4
- package/global/CHANGELOG.md +36 -0
- package/install.sh +4 -1
- package/modules/agent-door/conformance/injection.mjs +5 -3
- package/modules/agent-door/conformance/journey.mjs +1 -1
- package/modules/deploy-kit/README.md +1 -1
- package/modules/deploy-kit/prepare.mjs +5 -2
- package/modules/portability/README.md +42 -10
- package/modules/portability/catalogue.mjs +11 -1
- package/modules/portability/checkout-history.mjs +14 -0
- package/modules/portability/index.d.mts +1 -1
- package/modules/portability/library-history.mjs +2 -7
- package/modules/portability/restore-safety.mjs +6 -3
- package/modules/portability/worker-history.d.mts +9 -0
- package/modules/portability/worker-history.mjs +29 -0
- package/onboarding/adapter.mjs +25 -13
- package/package.json +9 -1
package/cli/agent-door.mjs
CHANGED
|
@@ -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.
|
|
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(
|
|
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.
|
|
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
|
-
|
|
144
|
-
const
|
|
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 {
|
|
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
|
|
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
|
};
|
package/cli/agent-network.mjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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:
|
|
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 () => {
|
|
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
|
}
|
package/cli/business/choices.mjs
CHANGED
|
@@ -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
|
-
?
|
|
95
|
-
: `No
|
|
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
|
}
|
package/cli/business/command.mjs
CHANGED
|
@@ -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
|
|
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++){
|
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
|
+
}
|
package/cli/hosted-output.mjs
CHANGED
|
@@ -9,8 +9,13 @@ import { migrate } from '../modules/container/migrations.mjs';
|
|
|
9
9
|
import { readMigrationRewrites, withRewrites } from '../modules/deploy-kit/migrations.mjs';
|
|
10
10
|
import { RerError } from './errors.mjs';
|
|
11
11
|
import { hostedMailCredentials } from './hosted-mail.mjs';
|
|
12
|
+
import { deliveryDeclarationSources } from './delivery-declarations.mjs';
|
|
13
|
+
import { sourcePath } from '../modules/delivery-producer/migrations.mjs';
|
|
12
14
|
import { shared } from './shared.mjs';
|
|
15
|
+
import { registerHistoryInstallation, preparationDatabase } from './agent-history-database.mjs';
|
|
13
16
|
import { verificationRpc } from './agent-rpc.mjs';
|
|
17
|
+
import { hostedOrigins } from './hosted-hosts.mjs';
|
|
18
|
+
import { FixtureDatabaseError } from '../modules/agent-door/conformance/fixtures.mjs';
|
|
14
19
|
|
|
15
20
|
// Serve the production build the way rer deploy hosts it (assets behind the
|
|
16
21
|
// Worker, deploy identity bound, a public https origin) on loopback, with no
|
|
@@ -43,9 +48,42 @@ async function miniflareFor(root) {
|
|
|
43
48
|
const standIn = (item, field) => typeof item.verifyStandIn === 'string' && item.verifyStandIn ? item.verifyStandIn : field?.kind === 'email' ? 'owner@example.com' : typeof field?.default === 'string' && field.default ? field.default : randomBytes(24).toString('hex');
|
|
44
49
|
const links = html => [...html.matchAll(/(?:src|href)=["'](\/[^"'#?\s]+)/g)].map(match => match[1].slice(1)).filter(path => !path.startsWith('/') && /\.[A-Za-z0-9]+$/.test(path));
|
|
45
50
|
|
|
51
|
+
// Verification-only runtime bindings. Never write defaults back to the source
|
|
52
|
+
// declaration or build: deploy and packaging must still require real inputs.
|
|
53
|
+
async function hostedPublicVariables(root, config, declaration, manifest) {
|
|
54
|
+
const present = value => typeof value === 'string' ? Boolean(value.trim()) : value !== undefined && value !== null;
|
|
55
|
+
const vars = { ...declaration.vars }, names = new Set([...Object.keys(config.vars ?? {}), ...Object.keys(vars)]);
|
|
56
|
+
const defaults = source => { for (const [name, value] of Object.entries(source ?? {})) if (!present(vars[name])) vars[name] = value; };
|
|
57
|
+
defaults(config.vars);
|
|
58
|
+
for (const [candidate, select] of deliveryDeclarationSources) {
|
|
59
|
+
const path = await sourcePath(root, candidate, { optional: true });
|
|
60
|
+
if (!path) continue;
|
|
61
|
+
const spec = select(JSON.parse(await readFile(path, 'utf8')));
|
|
62
|
+
if (!spec) continue;
|
|
63
|
+
for (const name of spec.publicVariableNames ?? Object.keys(spec.publicVariables ?? {})) names.add(name);
|
|
64
|
+
defaults(spec.publicVariables);
|
|
65
|
+
}
|
|
66
|
+
const { setupConditionMatches } = await shared('schema/setup-validation.mjs');
|
|
67
|
+
const fields = (manifest.fields ?? []).filter(field => field.kind !== 'secret' && names.has(field.name));
|
|
68
|
+
// A required field may depend on another public input declared after it.
|
|
69
|
+
let changed = true;
|
|
70
|
+
while (changed) {
|
|
71
|
+
changed = false;
|
|
72
|
+
for (const field of fields) {
|
|
73
|
+
if (present(vars[field.name]) || field.when && !setupConditionMatches(field.when, vars)) continue;
|
|
74
|
+
const presentation = field.presentations?.find(item => setupConditionMatches(item.when, vars));
|
|
75
|
+
if (field.presentations && !presentation || !(presentation?.required ?? field.required)) continue;
|
|
76
|
+
vars[field.name] = field.default?.trim() ? field.default : field.kind === 'url' ? `${HOSTED_ORIGIN}/`
|
|
77
|
+
: field.kind === 'select' ? field.options?.find(option => option.value)?.value || standIn({}, field) : standIn({}, field);
|
|
78
|
+
changed = true;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return vars;
|
|
82
|
+
}
|
|
83
|
+
|
|
46
84
|
/** The build served as rer deploy hosts it, with declared vars, origin and
|
|
47
|
-
*
|
|
48
|
-
export async function serveHosted(root, { declaration: declarationPath = 'deploy.json', bindings = {}, outboundService, rpc, workerEntrypoints = [] } = {}) {
|
|
85
|
+
* required public inputs and deploy/Managed mail secret stand-ins. `fetch(path, init)` uses the deployed origin. */
|
|
86
|
+
export async function serveHosted(root, { declaration: declarationPath = 'deploy.json', bindings = {}, outboundService, rpc, workerEntrypoints = [], publicHosts, fixturePreparation = false } = {}) {
|
|
49
87
|
const { loopbackFetch } = await shared('loopback-fetch.mjs');
|
|
50
88
|
const build = join(root, 'dist/server'), client = join(root, 'dist/client');
|
|
51
89
|
let config;
|
|
@@ -54,6 +92,7 @@ export async function serveHosted(root, { declaration: declarationPath = 'deploy
|
|
|
54
92
|
let declaration;
|
|
55
93
|
try { declaration = await read(join(root, declarationPath)); }
|
|
56
94
|
catch { throw new RerError('hosted_output_missing', `No readable deploy declaration at ${declarationPath}. A seed whose deploy reads another file names it with the commandAdapter option deployDeclaration.`, 1); }
|
|
95
|
+
const origins = hostedOrigins(declaration, publicHosts, HOSTED_ORIGIN);
|
|
57
96
|
const manifest = await optional(join(root, 'rer-setup.json'));
|
|
58
97
|
const { Miniflare, convertV4MiniflareOptions = options => options } = await miniflareFor(root);
|
|
59
98
|
const entry = join(build, config.main);
|
|
@@ -70,9 +109,10 @@ export async function serveHosted(root, { declaration: declarationPath = 'deploy
|
|
|
70
109
|
for (const binding of await hostedMailCredentials(root)) {
|
|
71
110
|
if (!Object.hasOwn(secrets, binding)) secrets[binding] = standIn({}, manifest.fields?.find(field => field.name === binding));
|
|
72
111
|
}
|
|
73
|
-
const
|
|
112
|
+
const publicVariables = await hostedPublicVariables(root, config, declaration, manifest);
|
|
113
|
+
const options = { host: '127.0.0.1', port: 0, cf: false, workers: [{ name: 'ingress', modules: true, script: ingress, serviceBindings: { APP: 'app', ...nativeBindings } }, ...rpcServices.workers, {
|
|
74
114
|
name: 'app', ...(outboundService ? { outboundService } : {}), modules, modulesRoot: build, compatibilityDate: config.compatibility_date, compatibilityFlags: config.compatibility_flags,
|
|
75
|
-
bindings: { ...
|
|
115
|
+
bindings: { ...publicVariables, ...secrets, ...(declaration.originVar ? { [declaration.originVar]: HOSTED_ORIGIN } : {}),
|
|
76
116
|
RER_DEPLOY_SOURCE: identity.sourceSha, RER_DEPLOY_FINGERPRINT: identity.fingerprint, RER_VERSION: { id: identity.versionId, tag: '', timestamp: new Date().toISOString() }, ...bindings },
|
|
77
117
|
d1Databases: Object.fromEntries((config.d1_databases ?? []).map(item => [item.binding, item.database_id ?? item.database_name])),
|
|
78
118
|
r2Buckets: Object.fromEntries((config.r2_buckets ?? []).map(item => [item.binding, item.bucket_name])),
|
|
@@ -85,7 +125,24 @@ export async function serveHosted(root, { declaration: declarationPath = 'deploy
|
|
|
85
125
|
serviceBindings: rpcServices.serviceBindings,
|
|
86
126
|
durableObjects: Object.fromEntries((config.durable_objects?.bindings ?? []).filter(item => !item.script_name).map(item => [item.name, { className: item.class_name, useSQLite: true }])),
|
|
87
127
|
...(config.assets ? { assets: { directory: client, binding: config.assets.binding ?? 'ASSETS', routerConfig: { has_user_worker: true, invoke_user_worker_ahead_of_assets: RUN_WORKER_FIRST } } } : {}),
|
|
88
|
-
}] }
|
|
128
|
+
}] };
|
|
129
|
+
let preparation, held = false;
|
|
130
|
+
const waiting = new Set();
|
|
131
|
+
const release = () => { held = false; for (const resume of waiting) resume(); waiting.clear(); };
|
|
132
|
+
// Install the gate before owner hooks retain any D1 handles; replacing
|
|
133
|
+
// Miniflare options later would disconnect those existing handles.
|
|
134
|
+
if (fixturePreparation) {
|
|
135
|
+
const app = options.workers.find(worker => worker.name === 'app');
|
|
136
|
+
const wrapper = join(build, '__rer_preparation.mjs');
|
|
137
|
+
const native = './' + config.main;
|
|
138
|
+
app.modules = [{ type: 'ESModule', path: wrapper, contents:
|
|
139
|
+
`import app from ${JSON.stringify(native)};export * from ${JSON.stringify(native)};export default {...app,async queue(batch,env,ctx){await env.RER_PREPARATION_QUEUE_GATE.fetch('https://queue.invalid');return app.queue(batch,env,ctx)}}` }, ...modules];
|
|
140
|
+
app.serviceBindings = { ...app.serviceBindings, RER_PREPARATION_QUEUE_GATE: async () => {
|
|
141
|
+
if (held) await new Promise(resume => waiting.add(resume));
|
|
142
|
+
return new Response(null, { status: 204 });
|
|
143
|
+
} };
|
|
144
|
+
}
|
|
145
|
+
const mf = new Miniflare(convertV4MiniflareOptions(options));
|
|
89
146
|
let loopback;
|
|
90
147
|
try {
|
|
91
148
|
loopback = await mf.ready;
|
|
@@ -99,11 +156,32 @@ export async function serveHosted(root, { declaration: declarationPath = 'deploy
|
|
|
99
156
|
await migrate(await mf.getD1Database(item.binding, 'app'), withRewrites(plan, await readMigrationRewrites(root), { partial: true }));
|
|
100
157
|
}
|
|
101
158
|
} catch (error) { await mf.dispose(); throw error; }
|
|
102
|
-
|
|
159
|
+
const preparedDatabase = async binding => {
|
|
160
|
+
if (!(config.d1_databases ?? []).some(item => item.binding === binding)) throw new RerError('hosted_database_invalid', new FixtureDatabaseError().message, 1);
|
|
161
|
+
return preparationDatabase(await mf.getD1Database(binding, 'app'));
|
|
162
|
+
};
|
|
163
|
+
const hosted = { client, identity, origin: HOSTED_ORIGIN, origins,
|
|
103
164
|
worker: async entrypoint => {
|
|
104
165
|
if (!Object.hasOwn(nativeWorkers, entrypoint)) throw new RerError('agent_invoke_invalid', 'Verification can invoke only its declared native Worker entrypoint.', 1);
|
|
105
166
|
return (await mf.getBindings('ingress'))[nativeWorkers[entrypoint]];
|
|
106
167
|
},
|
|
168
|
+
// Only the conformance call sites request these powers. Ordinary hosted
|
|
169
|
+
// checks and owner initialization keep their SELECT-only reader below.
|
|
170
|
+
preparation: async () => preparation ??= (async () => {
|
|
171
|
+
if (!fixturePreparation) throw new RerError('hosted_database_invalid', 'Native preparation requires a disposable conformance host.', 1);
|
|
172
|
+
return Object.freeze({
|
|
173
|
+
database: async binding => (await preparedDatabase(binding)).database,
|
|
174
|
+
scheduled: async ({ scheduledTime = Date.now() } = {}) => {
|
|
175
|
+
if (!Number.isFinite(scheduledTime)) throw new Error('Native scheduled preparation requires a finite Unix millisecond time.');
|
|
176
|
+
try {
|
|
177
|
+
const result = await (await mf.getWorker('app')).scheduled({ scheduledTime });
|
|
178
|
+
if (result.outcome !== 'ok') throw new Error();
|
|
179
|
+
}
|
|
180
|
+
catch { throw new Error('Native scheduled preparation failed; fixture values are not logged.'); }
|
|
181
|
+
},
|
|
182
|
+
queues: Object.freeze({ hold: () => { held = true; }, release }),
|
|
183
|
+
});
|
|
184
|
+
})(),
|
|
107
185
|
database: async binding => {
|
|
108
186
|
if (!(config.d1_databases ?? []).some(item => item.binding === binding)) throw new RerError('hosted_database_invalid', 'Verification can read only a declared disposable database binding.', 1);
|
|
109
187
|
const db = await mf.getD1Database(binding, 'app');
|
|
@@ -111,8 +189,13 @@ export async function serveHosted(root, { declaration: declarationPath = 'deploy
|
|
|
111
189
|
if (typeof sql !== 'string' || !/^\s*SELECT\b/i.test(sql) || sql.includes(';')) throw new RerError('hosted_database_invalid', 'Verification state access is read-only SELECT.', 1);
|
|
112
190
|
return db.prepare(sql);
|
|
113
191
|
} };
|
|
114
|
-
}, close: () => mf.dispose(),
|
|
115
|
-
fetch: (path, { headers, ...init } = {}) =>
|
|
192
|
+
}, close: () => { release(); return mf.dispose(); },
|
|
193
|
+
fetch: (path, { headers, origin = HOSTED_ORIGIN, ...init } = {}) => {
|
|
194
|
+
if (!origins.includes(origin)) throw new RerError('agent_door_origin', 'Agent conformance request must use a declared hosted installation origin.', 1);
|
|
195
|
+
return loopbackFetch(loopback, { ...init, redirect: 'manual', headers: { ...headers, 'x-rer-original-url': `${origin}/${path}` } });
|
|
196
|
+
} };
|
|
197
|
+
if (fixturePreparation) registerHistoryInstallation(hosted, preparedDatabase);
|
|
198
|
+
return hosted;
|
|
116
199
|
}
|
|
117
200
|
|
|
118
201
|
export async function checkHostedOutput(root, options) {
|
package/cli/lifecycle.mjs
CHANGED
|
@@ -20,6 +20,11 @@ import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
|
|
|
20
20
|
import { announceDoorRoute } from './door-mode.mjs';
|
|
21
21
|
|
|
22
22
|
export async function runCommand(project, options, out) {
|
|
23
|
+
if (project.profile === 'first-party' && ['build', 'dev', 'preview', 'deploy'].includes(options.verb)) {
|
|
24
|
+
const { readAgentSurface } = await import('./agent-surface.mjs');
|
|
25
|
+
const surface = await readAgentSurface(project.root);
|
|
26
|
+
if (surface?.surface.verification?.history !== undefined) await (await import('./agent-history.mjs')).historyDeclaration(project.root, surface.surface.verification.history);
|
|
27
|
+
}
|
|
23
28
|
if (options.verb === 'deploy' && !options.site && !options.demo) {
|
|
24
29
|
const { validateDeployOptions } = await import('./deploy-command.mjs');
|
|
25
30
|
validateDeployOptions(options);
|