@runeditrun/rer 0.2.90 → 0.2.93
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/README.md +1 -1
- package/cli/agent-door.mjs +15 -4
- package/cli/agent-initializer.mjs +27 -0
- package/cli/agent-journey-fixtures.mjs +8 -4
- package/cli/agent-verifier.mjs +5 -1
- package/cli/deploy-command.mjs +19 -8
- package/cli/deploy.mjs +1 -1
- package/cli/ledger-refusal.mjs +1 -1
- package/cli/portability-migrations.mjs +9 -5
- package/cli/portability-worker.mjs +4 -2
- package/foundation/runtime/contract-docs.mjs +26 -12
- package/global/CHANGELOG.md +47 -0
- package/modules/agent-door/conformance/audit.mjs +82 -7
- package/modules/agent-door/conformance/crypto.mjs +14 -2
- package/modules/agent-door/conformance/fixtures.mjs +22 -3
- package/modules/agent-door/conformance/index.mjs +9 -2
- package/modules/agent-door/conformance/journey.mjs +26 -2
- package/modules/agent-door/conformance/negative.mjs +29 -1
- package/modules/agent-door/conformance/policy-phases.mjs +43 -1
- package/modules/agent-door/conformance/protocol.mjs +44 -8
- package/modules/agent-door/conformance/sponsors.mjs +12 -1
- package/modules/agent-door/conformance/step-hooks.mjs +3 -1
- package/modules/agent-door/conformance/surface.mjs +10 -0
- package/modules/deploy-kit/owner-cli.mjs +9 -1
- package/modules/erasure/README.md +4 -2
- package/modules/operator-auth/identity/oidc/README.md +2 -1
- package/modules/portability/README.md +52 -2
- package/modules/portability/backfills.mjs +96 -3
- package/modules/portability/bridge.mjs +3 -1
- package/modules/portability/format.mjs +1 -0
- package/modules/portability/import.mjs +58 -3
- package/modules/portability/index.d.mts +2 -0
- package/modules/portability/index.mjs +16 -5
- package/modules/portability/library-history.mjs +152 -0
- package/modules/portability/migration-history.mjs +3 -2
- package/modules/portability/snapshot-objects.mjs +16 -0
- package/onboarding/adapter.mjs +3 -1
- package/package.json +1 -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
|
|
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
|
package/cli/agent-door.mjs
CHANGED
|
@@ -16,6 +16,7 @@ import { verificationWebhooks } from './agent-webhooks.mjs';
|
|
|
16
16
|
import { verificationInvoke, verificationJourney } from './agent-verifier.mjs';
|
|
17
17
|
import { verificationBindings } from './agent-bindings.mjs';
|
|
18
18
|
import { journeyFixtures } from './agent-journey-fixtures.mjs';
|
|
19
|
+
import { verificationAgentInitializer } from './agent-initializer.mjs';
|
|
19
20
|
|
|
20
21
|
function finish(result, report) {
|
|
21
22
|
if (result.capabilities) report(`Agent capabilities (${result.capabilities.mode}): declared=${result.capabilities.declared.join(',')}; refused=${result.capabilities.refused.join(',')}; unscoped=${result.capabilities.unscoped.join(',')}.`);
|
|
@@ -35,6 +36,7 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
|
|
|
35
36
|
const manifest = setupManifest ?? JSON.parse(await readFile(join(root, 'rer-setup.json'), 'utf8'));
|
|
36
37
|
const claim = manifest.steps?.find(step => step.type === 'owner-claim');
|
|
37
38
|
const verification = declared.surface.verification ?? {};
|
|
39
|
+
const initializeAgent = await verificationAgentInitializer(root, verification.agent);
|
|
38
40
|
const workerDriver = await verificationInvoke(root, verification.invoke);
|
|
39
41
|
let prove;
|
|
40
42
|
if (verification.proof !== undefined) {
|
|
@@ -43,7 +45,15 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
|
|
|
43
45
|
prove = (await import(pathToFileURL(resolve(root, verification.proof.module)))).default;
|
|
44
46
|
if (typeof prove !== 'function') throw new RerError('agent_proof_invalid', 'verification.proof module must default-export a native proof test function.', 1);
|
|
45
47
|
}
|
|
46
|
-
const
|
|
48
|
+
const negativeOnly = new Set();
|
|
49
|
+
const sponsorDeclarations = Array.isArray(verification.sponsors) ? verification.sponsors.map((principal, index) => {
|
|
50
|
+
if (!principal || typeof principal !== 'object' || Array.isArray(principal)) return principal;
|
|
51
|
+
const { negativeOnly: probeOnly, ...declaration } = principal;
|
|
52
|
+
if (probeOnly !== undefined && typeof probeOnly !== 'boolean' || probeOnly && index === 0) throw new RerError('agent_sponsors_invalid', 'Only additional verification sponsors may declare negativeOnly:true.', 1);
|
|
53
|
+
if (probeOnly) negativeOnly.add(principal.label);
|
|
54
|
+
return declaration;
|
|
55
|
+
}) : verification.sponsors;
|
|
56
|
+
const principals = await verificationSponsors(root, { ...verification, sponsors: sponsorDeclarations }), native = principals[0], { email, sub } = native;
|
|
47
57
|
if (verification.reviewers !== undefined && !native.initialize) throw new RerError('agent_reviewer_invalid', 'verification.reviewers requires a native owner initializer to drive invitation and independent review.', 1);
|
|
48
58
|
const reviewers = await verificationReviewers(root, verification.reviewers, email);
|
|
49
59
|
if (claim?.mode && !['signed', 'setup-token'].includes(claim.mode) && !native.initialize) throw new RerError('agent_owner_invalid', `Owner claim mode ${claim.mode} requires verification.owner.initializer using the seed's production lifecycle.`, 1);
|
|
@@ -130,10 +140,11 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
|
|
|
130
140
|
}
|
|
131
141
|
const secrets = await network.provision(hosted);
|
|
132
142
|
const webhooks = await verificationWebhooks(root, verification.webhooks, secrets);
|
|
133
|
-
const journey = await verificationJourney(root, verification.journey, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures });
|
|
134
|
-
const prepare = await journeyFixtures(root, verification.fixtures, { request, origin: hosted.origin, email, cookie, mail: network.mail, fixtures: network.fixtures });
|
|
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 });
|
|
135
145
|
const result = await runAgentDoorConformance({ fetch: request, origin: hosted.origin, surface: declared.surface,
|
|
136
|
-
signer: { issuer, installationId, kid, privateKey: pair.privateKey }, person: sponsors[0], sponsors, webhooks, business, prove, ...journey, prepare, invoke: workerDriver?.run(hosted),
|
|
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),
|
|
147
|
+
initializeAgent: initializeAgent && (({ agentId, person }) => initializeAgent({ agentId, person, request, origin: hosted.origin, mail: network.mail, fixtures: network.fixtures })),
|
|
137
148
|
});
|
|
138
149
|
const points = [...result.points, ...reviewers.points()];
|
|
139
150
|
return finish({ ...result, points, ok: points.every(point => point.ok) }, report);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { contained } from './project.mjs';
|
|
4
|
+
import { RerError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
/** Load test tooling before starting the disposable installation. */
|
|
7
|
+
export async function verificationAgentInitializer(root, declaration) {
|
|
8
|
+
if (declaration === undefined) return undefined;
|
|
9
|
+
const invalid = () => new RerError('agent_initializer_invalid', 'verification.agent must name a contained initializer module with a function default export.', 1);
|
|
10
|
+
if (!declaration || typeof declaration !== 'object' || Array.isArray(declaration)
|
|
11
|
+
|| Object.keys(declaration).join(',') !== 'initializer' || typeof declaration.initializer !== 'string') throw invalid();
|
|
12
|
+
let initialize;
|
|
13
|
+
try {
|
|
14
|
+
await contained(root, declaration.initializer);
|
|
15
|
+
initialize = (await import(pathToFileURL(resolve(root, declaration.initializer)))).default;
|
|
16
|
+
if (typeof initialize !== 'function') throw invalid();
|
|
17
|
+
} catch { throw invalid(); }
|
|
18
|
+
return ({ agentId, person, request, origin, mail, fixtures }) => initialize({ agentId, origin, email: person.email, sub: person.sub, mail, fixtures,
|
|
19
|
+
request: (absolute, { headers, ...init } = {}) => {
|
|
20
|
+
const sessionHeaders = new Headers(headers);
|
|
21
|
+
sessionHeaders.set('Origin', origin);
|
|
22
|
+
sessionHeaders.set('Cookie', person.cookie);
|
|
23
|
+
if (!sessionHeaders.has('Content-Type')) sessionHeaders.set('Content-Type', 'application/json');
|
|
24
|
+
return request(new URL(absolute, origin).href, { ...init, headers: sessionHeaders });
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -2,16 +2,20 @@ import { resolve } from 'node:path';
|
|
|
2
2
|
import { pathToFileURL } from 'node:url';
|
|
3
3
|
import { contained } from './project.mjs';
|
|
4
4
|
import { RerError } from './errors.mjs';
|
|
5
|
+
import { FixtureDatabaseError } from '../modules/agent-door/conformance/fixtures.mjs';
|
|
5
6
|
|
|
6
|
-
/** Test tooling receives
|
|
7
|
+
/** Test tooling receives the disposable installation's doors and state reader. */
|
|
7
8
|
export async function journeyFixtures(root, declaration, context) {
|
|
8
9
|
if (declaration === undefined) return undefined;
|
|
9
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);
|
|
10
11
|
await contained(root, declaration.module);
|
|
11
12
|
const prepare = (await import(pathToFileURL(resolve(root, declaration.module)))).default;
|
|
12
13
|
if (typeof prepare !== 'function') throw new RerError('agent_fixtures_invalid', 'verification.fixtures module must default-export a phase preparation function.', 1);
|
|
13
|
-
return async ({ phase, tool }) => {
|
|
14
|
-
try { return await prepare({ ...context, phase, tool }); }
|
|
15
|
-
catch
|
|
14
|
+
return async ({ phase, tool, now }) => {
|
|
15
|
+
try { return await prepare({ ...context, phase, tool, now }); }
|
|
16
|
+
catch (error) {
|
|
17
|
+
if (error?.code === 'hosted_database_invalid') throw new FixtureDatabaseError();
|
|
18
|
+
throw new Error('Native phase preparation failed; no captured mail, credentials or fixture values are logged.');
|
|
19
|
+
}
|
|
16
20
|
};
|
|
17
21
|
}
|
package/cli/agent-verifier.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { resolve } from 'node:path';
|
|
|
2
2
|
import { pathToFileURL } from 'node:url';
|
|
3
3
|
import { contained } from './project.mjs';
|
|
4
4
|
import { RerError } from './errors.mjs';
|
|
5
|
+
import { FixtureDatabaseError } from '../modules/agent-door/conformance/fixtures.mjs';
|
|
5
6
|
|
|
6
7
|
export async function verificationInvoke(root, config) {
|
|
7
8
|
if (config === undefined) return;
|
|
@@ -23,7 +24,10 @@ export async function verificationJourney(root, path, context) {
|
|
|
23
24
|
if (typeof module.default !== 'function' || ['beforeStep', 'afterStep'].some(key => module[key] !== undefined && typeof module[key] !== 'function')) throw new RerError('agent_journey_invalid', 'verification.journey must default-export a native journey; optional beforeStep and afterStep exports must be functions.', 1);
|
|
24
25
|
const call = async (fn, value) => {
|
|
25
26
|
try { await fn({ ...context, ...value }); }
|
|
26
|
-
catch
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (error?.code === 'hosted_database_invalid') throw new FixtureDatabaseError();
|
|
29
|
+
throw new Error('Native verification journey failed; no captured mail or fixture values are logged.');
|
|
30
|
+
}
|
|
27
31
|
};
|
|
28
32
|
return { nativeJourney: value => call(module.default, value),
|
|
29
33
|
nativeStep: async ({ stage, ...value }) => { if (module[stage]) await call(module[stage], value); },
|
package/cli/deploy-command.mjs
CHANGED
|
@@ -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 (
|
|
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
|
-
() =>
|
|
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('
|
|
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/ledger-refusal.mjs
CHANGED
|
@@ -14,5 +14,5 @@ const fixes = {
|
|
|
14
14
|
export function ledgerRefusal(receipt) {
|
|
15
15
|
const [, kind, ...name] = receipt.reason.split(':');
|
|
16
16
|
const named = receipt.unapplied ?? (name.length ? name.join(':') : undefined);
|
|
17
|
-
return `Migration history refused (${receipt.reason}): ${named ?
|
|
17
|
+
return `Migration history refused (${receipt.reason}): ${named ? `${kind === 'multiple' ? 'ledger' : 'migration'} ${named}: ` : ''}${fixes[kind] ?? 'its history does not match this checkout.'}`;
|
|
18
18
|
}
|
|
@@ -37,11 +37,15 @@ export async function appliedMigrations(root,db,binding,declaration,split) {
|
|
|
37
37
|
|
|
38
38
|
// Ledger contents can contain private values. Report constant categories,
|
|
39
39
|
// retaining the transfer's canonical compatibility and hash-matching policy.
|
|
40
|
-
function constantRefusal(error) {
|
|
40
|
+
function constantRefusal(error,files) {
|
|
41
41
|
if(!(error instanceof PortabilityError))return error;
|
|
42
42
|
const code=error.code.startsWith('migration_ledger:')?error.code.split(':').slice(0,2).join(':')
|
|
43
43
|
:error.code==='schema_mismatch:uncertain_migrations'?'migration_ledger:uncertain':'migration_ledger:incompatible';
|
|
44
|
-
|
|
44
|
+
// Only checkout-owned names may accompany the constant category. A ledger
|
|
45
|
+
// entry with no matching file or declared alias can contain private values.
|
|
46
|
+
const name=error.code.split(':').slice(2).join(':');
|
|
47
|
+
const identity=['migration_ledger:unknown','migration_ledger:ambiguous','migration_ledger:conflict'].includes(code) && name && files.some(file=>file.name===name || file.aliases?.includes(name))?name:undefined;
|
|
48
|
+
return Object.assign(new PortabilityError(code,409),error.migration===undefined?{}:{migration:error.migration},identity?{identity}:{});
|
|
45
49
|
}
|
|
46
50
|
|
|
47
51
|
// For adapters with their own archive format: the entries of a migration ledger
|
|
@@ -59,7 +63,7 @@ export async function mapMigrationLedger({root,binding='DB',platformMigrations,e
|
|
|
59
63
|
const mapped=entries.map(({name,sha256})=>({name:matchMigrationLedger([{name,sha256}],files,declaration)[0]??name,sha256}));
|
|
60
64
|
insist(new Set(mapped.map(entry=>entry.name)).size===mapped.length,'migration_ledger:ambiguous',409);
|
|
61
65
|
return mapped;
|
|
62
|
-
} catch(error) { throw constantRefusal(error); }
|
|
66
|
+
} catch(error) { throw constantRefusal(error,files); }
|
|
63
67
|
}
|
|
64
68
|
|
|
65
69
|
// Older runners leave Wrangler's bookkeeping beside their authoritative hashed
|
|
@@ -89,7 +93,7 @@ export async function nativeMigrationPreflight({root,db,binding='DB',platformMig
|
|
|
89
93
|
const declaration=platformMigrationDeclaration(platformMigrations);
|
|
90
94
|
const tables=await all(db,`SELECT type,name FROM sqlite_master WHERE lower(name) IN (${ledgerNames.map(name=>`'${name}'`).join(',')})`);
|
|
91
95
|
const legacyPair=tables.length===2 && ['_rer_deploy_migrations','d1_migrations'].every(name=>tables.some(row=>row.name===name));
|
|
92
|
-
|
|
96
|
+
if(tables.length>1 && !legacyPair)throw Object.assign(new PortabilityError('migration_ledger:multiple',409),tables.some(row=>row.name==='rer_migrations')?{identity:'rer_migrations'}:{});
|
|
93
97
|
insist(tables.every(row=>row.type==='table' && ledgerNames.includes(row.name)),'migration_ledger:incompatible',409);
|
|
94
98
|
const table=legacyPair?'_rer_deploy_migrations':tables[0]?.name;
|
|
95
99
|
if(!table)return {nativeApply:true};
|
|
@@ -105,6 +109,6 @@ export async function nativeMigrationPreflight({root,db,binding='DB',platformMig
|
|
|
105
109
|
nativeApply=table==='d1_migrations' && files.some(file=>!applied.includes(file.name));
|
|
106
110
|
// The checkout file is named: it is the seed's own, never a ledger value.
|
|
107
111
|
if(table!=='d1_migrations')for(const file of files)if(!applied.includes(file.name))throw Object.assign(new PortabilityError('migration_ledger:unapplied',409),{migration:file.name});
|
|
108
|
-
} catch(error) { throw constantRefusal(error); }
|
|
112
|
+
} catch(error) { throw constantRefusal(error,files); }
|
|
109
113
|
return {nativeApply};
|
|
110
114
|
}
|
|
@@ -79,8 +79,10 @@ catch (error) {
|
|
|
79
79
|
// Erasure-fence refusals name the fence: an older archive is refused, not a failed transfer.
|
|
80
80
|
const refusal = error instanceof PortabilityError && (error.status === 409 || ['wrong_product', 'schema_mismatch', 'migration_ledger', 'table_inventory', 'configuration_inventory', 'erased_row', 'erasure_epoch', 'later_journal', 'invalid_journal', 'staged_validation'].includes(error.code.split(':')[0]));
|
|
81
81
|
const exitCode = error.message === 'archive_json' ? 2 : refusal || error.code === 'EEXIST' ? 4 : 1;
|
|
82
|
-
// Report
|
|
83
|
-
|
|
82
|
+
// Report symbolic codes and identities verified against the checkout or the
|
|
83
|
+
// known Platform ledger name; native database errors can contain private data.
|
|
84
|
+
const ledgerIdentity = error instanceof PortabilityError && error.code.startsWith('migration_ledger:') ? error.migration ?? error.identity : undefined;
|
|
85
|
+
const reason = error instanceof PortabilityError ? (error.code.startsWith('migration_ledger:') ? error.code + (ledgerIdentity ? ':' + ledgerIdentity : '') : error.code.split(':')[0]) : /^[A-Z_]+$/.test(error.code ?? '') ? error.code : error.message === 'archive_json' ? 'archive_json' : 'native_error';
|
|
84
86
|
// A later migration that changes restorable data is named: it is a file of this installation.
|
|
85
87
|
const migration = error instanceof PortabilityError && error.code.startsWith('schema_mismatch:migration_data:') ? error.code.slice('schema_mismatch:migration_data:'.length) : undefined;
|
|
86
88
|
// An unapplied migration is a file of this checkout: it is named so it can be applied.
|
|
@@ -137,23 +137,26 @@ function generatedFiles(text) {
|
|
|
137
137
|
if (!rows.length) claims.push('No homepage claims are mapped yet.')
|
|
138
138
|
else {
|
|
139
139
|
claims.push('A product claim is done when every clause behind it is done, missing when every one is missing, and partial otherwise. Explicit source-bound non-product facts are unassessed; their historical status is history, not current proof.')
|
|
140
|
-
const hasSection = rows.some(row => row.header.some(cell => /^Section$/i.test(plainText(cell))))
|
|
140
|
+
const hasSection = rows.some(row => row.header.some(cell => /^(Section|Screen)$/i.test(plainText(cell))))
|
|
141
|
+
const hasBacking = rows.some(row => row.header.some(cell => claimHeader(cell) === 'Backing'))
|
|
141
142
|
const hasNonProduct = provenance?.claims.some(row => row.nonProduct)
|
|
142
|
-
const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasNonProduct ? ['Basis'] : []), ...(provenance ? ['Historical status'] : []), 'Status']
|
|
143
|
+
const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasBacking ? ['Backing'] : []), ...(hasNonProduct ? ['Basis'] : []), ...(provenance ? ['Historical status'] : []), 'Status']
|
|
143
144
|
const table = [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`], counts = { done: 0, partial: 0, missing: 0, unassessed: 0 }
|
|
144
145
|
for (const [index, row] of rows.entries()) {
|
|
145
146
|
const value = label => claimValue(row, label)
|
|
146
147
|
const source = provenance?.claims[index]
|
|
148
|
+
const location = hasSection ? [value('Section|Screen')] : []
|
|
149
|
+
const backing = hasBacking ? [value('Backing')] : []
|
|
147
150
|
if (source?.nonProduct) {
|
|
148
151
|
counts.unassessed++
|
|
149
|
-
table.push(`| ${[value('#'), ...
|
|
152
|
+
table.push(`| ${[value('#'), ...location, value('Claim'), '', ...backing, `Non-product: ${source.nonProduct}`, source.status || 'Not recorded', 'unassessed'].map(tableCell).join(' | ')} |`)
|
|
150
153
|
continue
|
|
151
154
|
}
|
|
152
155
|
const ids = idsIn(value('Clauses?')), linked = ids.map(id => clauses.find(clause => clause.id === id))
|
|
153
156
|
if (!ids.length || linked.some(clause => !clause)) throw Error(`CONTRACT.md:${row.line}: Homepage claim needs existing clause ids.`)
|
|
154
157
|
const state = linked.every(clause => clause.status === 'done') ? 'done' : linked.every(clause => clause.status === 'missing') ? 'missing' : 'partial'
|
|
155
158
|
counts[state]++
|
|
156
|
-
table.push(`| ${[value('#') || String(index + 1), ...
|
|
159
|
+
table.push(`| ${[value('#') || String(index + 1), ...location, value('Claim'), linked.map(clause => `\`${clause.id}\` ${clause.status}`).join('; '), ...backing, ...(hasNonProduct ? ['Product'] : []), ...(provenance ? [source?.status || 'Not recorded'] : []), state].map(tableCell).join(' | ')} |`)
|
|
157
160
|
}
|
|
158
161
|
claims.push(table.join('\n'), `Claims: ${rows.length}; ${counts.done} done, ${counts.partial} partial, ${counts.missing} missing.${hasNonProduct ? ` Non-product: ${counts.unassessed} unassessed.` : ''}`)
|
|
159
162
|
if (provenance) claims.push(`Historical claim source: \`${provenance.old}\`. Exact source files, lines, text and historical statuses are retained in CONTRACT.md's contract-claim-source record.`)
|
|
@@ -318,15 +321,20 @@ function requirementAndAcceptance(body, oldAcceptance, clause) {
|
|
|
318
321
|
return { text: result.join('\n\n'), history }
|
|
319
322
|
}
|
|
320
323
|
// Only spellings observed in the launch seeds' immutable homepage tables.
|
|
321
|
-
const claimHeaders = new Set(['claim', 'claims', 'claim on the page', 'what the page claims', 'claim text'])
|
|
324
|
+
const claimHeaders = new Set(['claim', 'claims', 'claim on the page', 'what the page claims', 'claim text', 'capability claimed'])
|
|
322
325
|
function claimHeader(cell) {
|
|
323
326
|
const value = plainText(cell).toLowerCase()
|
|
324
327
|
if (claimHeaders.has(value)) return 'Claim'
|
|
325
328
|
if (['clause', 'clauses', 'clause(s)', 'clause id(s)'].includes(value)) return 'Clauses'
|
|
326
329
|
if (value === 'claim #') return '#'
|
|
330
|
+
if (value === 'code and target contract backing' || value === 'backing') return 'Backing'
|
|
327
331
|
return plainText(cell)
|
|
328
332
|
}
|
|
329
|
-
const claimValue = (row, label) => row.cells[row.header.findIndex(cell => new RegExp(
|
|
333
|
+
const claimValue = (row, label) => row.cells[row.header.findIndex(cell => new RegExp(`^(?:${label})$`, 'i').test(claimHeader(cell)))] ?? ''
|
|
334
|
+
// Backing mixes explicit clause links with code and caveats. Only the links
|
|
335
|
+
// supply clauses; retain the complete cell separately as historical provenance.
|
|
336
|
+
const claimReferences = row => row.header.some(cell => claimHeader(cell) === 'Clauses')
|
|
337
|
+
? claimValue(row, 'Clauses') : idsIn(claimValue(row, 'Backing').replace(/\.(?=\s|$)/g, '')).join(', ')
|
|
330
338
|
const claimRows = text => homepageClaims(text).flatMap(table => table.rows.map(row => ({ ...row, header: table.header })))
|
|
331
339
|
function originalClaims(old) {
|
|
332
340
|
const candidates = Object.entries(old.files).filter(([name, text]) => name === 'CONTRACT.md' || /(?:^|\/)CLAIMS\.md$/.test(name) && !text.startsWith('<!-- Generated from CONTRACT.md by contract-docs.')).map(([name, text]) => ({ name, tables: homepageClaims(text) }))
|
|
@@ -337,7 +345,7 @@ function originalClaims(old) {
|
|
|
337
345
|
function nonProductBasis(source, basis, ids, label) {
|
|
338
346
|
// These are explicit classifications, never a fallback for an unresolved ID.
|
|
339
347
|
const allowed = {
|
|
340
|
-
'license/public-repository ownership': /^["“]?(?:100% free, open source alternative to [^"”\n]+|100% free and open source
|
|
348
|
+
'license/public-repository ownership': /^["“]?(?:100% free, open source alternative to [^"”\n]+|100% free and open source(?:\. MIT licensed\.)?|MIT licen[cs](?:e|ed)\.?)["”]?$/i,
|
|
341
349
|
'launcher identity': /^(?:Terminal:\s*)?`npx -y @runeditrun\/rer dev [^`]+` starts [\w -]+\.?$/,
|
|
342
350
|
'hosted-demo action': /^["“]Try the demo["”] opens the hosted demo\.?$/i,
|
|
343
351
|
'boundary': /^Limits:\s*["“]No [^"”\n]+["”]\.?$/i,
|
|
@@ -351,7 +359,9 @@ function nonProductBasis(source, basis, ids, label) {
|
|
|
351
359
|
throw Error(`${label}: non-product basis must explicitly describe a license/public-repository ownership, launcher identity, hosted-demo action or boundary with its required original references and no original product clause link; product promises need real clauses.`)
|
|
352
360
|
}
|
|
353
361
|
function sourceClaim(file, row, index) {
|
|
354
|
-
return { file, line: row.line, number: claimValue(row, '#') || String(index + 1), claim: claimValue(row, 'Claim'), status: claimValue(row, 'Status'), clauses:
|
|
362
|
+
return { file, line: row.line, number: claimValue(row, '#') || String(index + 1), claim: claimValue(row, 'Claim'), status: claimValue(row, 'Status'), clauses: claimReferences(row),
|
|
363
|
+
...(row.header.some(cell => /^Screen$/i.test(plainText(cell))) ? { screen: claimValue(row, 'Screen') } : {}),
|
|
364
|
+
...(row.header.some(cell => claimHeader(cell) === 'Backing') ? { backing: claimValue(row, 'Backing') } : {}), text: row.raw }
|
|
355
365
|
}
|
|
356
366
|
function readClaimSource(text) {
|
|
357
367
|
const records = [...text.matchAll(/<!-- contract-claim-source\s*\n([\s\S]*?)\n-->/g)]
|
|
@@ -379,6 +389,9 @@ function validateClaimSource(text, rows = claimRows(text), old) {
|
|
|
379
389
|
if (!source || Object.entries(expected).some(([key, value]) => source[key] !== value)) throw Error(`${label}: source SHA/file/line/number/text/historical status must match the immutable original.`)
|
|
380
390
|
const row = rows[index]
|
|
381
391
|
if (claimValue(row, '#') !== source.number || claimValue(row, 'Claim') !== source.claim) throw Error(`${label}: current claim number/text must match the original.`)
|
|
392
|
+
if (source.screen !== undefined && claimValue(row, 'Section|Screen') !== source.screen ||
|
|
393
|
+
source.backing !== undefined && claimValue(row, 'Backing') !== source.backing)
|
|
394
|
+
throw Error(`${label}: current screen/backing provenance must match the original.`)
|
|
382
395
|
const basis = claimValue(row, 'Basis')
|
|
383
396
|
if (source.nonProduct !== undefined) {
|
|
384
397
|
nonProductBasis(source, source.nonProduct, ids, label)
|
|
@@ -435,17 +448,18 @@ function contractClaims(old, ids, claimMapPath) {
|
|
|
435
448
|
}
|
|
436
449
|
}
|
|
437
450
|
if (!rows.length) return 'No homepage claims are mapped yet.'
|
|
438
|
-
const hasSection = rows.some(row => row.header.some(label => /^
|
|
451
|
+
const hasSection = rows.some(row => row.header.some(label => /^(Section|Screen)$/i.test(plainText(label))))
|
|
452
|
+
const hasBacking = rows.some(row => row.header.some(label => claimHeader(label) === 'Backing'))
|
|
439
453
|
const hasNonProduct = [...mapped.values()].some(entry => entry.nonProduct)
|
|
440
|
-
const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasNonProduct ? ['Basis'] : [])]
|
|
454
|
+
const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasBacking ? ['Backing'] : []), ...(hasNonProduct ? ['Basis'] : [])]
|
|
441
455
|
const table = [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`], problems = []
|
|
442
456
|
for (const [index, row] of rows.entries()) {
|
|
443
457
|
const mapping = mapped.get(row.line), nonProduct = mapping?.nonProduct
|
|
444
|
-
const references = nonProduct ? '' : mapping?.clauses.join(', ') ??
|
|
458
|
+
const references = nonProduct ? '' : mapping?.clauses.join(', ') ?? claimReferences(row)
|
|
445
459
|
const linked = idsIn(references)
|
|
446
460
|
if (!nonProduct && (!linked.length || linked.some(id => !ids.has(id))))
|
|
447
461
|
problems.push(`${file}:${row.line}: Homepage claim ${JSON.stringify(value(row, 'Claim'))} needs existing product clause ids (found ${JSON.stringify(references)}). Supply --claim-map <file> with schema 1, old ${old.commit}, and claims entries {file, line, claim, clauses}; map only to the actual obligations, never invent a link.`)
|
|
448
|
-
table.push(`| ${[value(row, '#') || String(index + 1), ...(hasSection ? [value(row, 'Section')] : []), value(row, 'Claim'), references, ...(hasNonProduct ? [nonProduct ? `Non-product: ${nonProduct}` : 'Product'] : [])].map(tableCell).join(' | ')} |`)
|
|
462
|
+
table.push(`| ${[value(row, '#') || String(index + 1), ...(hasSection ? [value(row, 'Section|Screen')] : []), value(row, 'Claim'), references, ...(hasBacking ? [value(row, 'Backing')] : []), ...(hasNonProduct ? [nonProduct ? `Non-product: ${nonProduct}` : 'Product'] : [])].map(tableCell).join(' | ')} |`)
|
|
449
463
|
}
|
|
450
464
|
if (problems.length) throw Error(problems.join('\n'))
|
|
451
465
|
if (hasNonProduct) table.unshift('Explicit non-product facts have current derived status unassessed. The source record retains historical statuses as history, not current proof.', '')
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.93
|
|
4
|
+
|
|
5
|
+
- Integrated inputs: deploydry-2 (HappyToHelp dry-run hook dispatch and unchecked-provider receipt), ledgertok-2 (HappyToHelp ledger refusal identities), adoptdoc-1 (safe adoption examples), reslink-1 (native record-link conformance), copy-1 (product-led optional homepage copy), and handset-history-1 (historical claim context).
|
|
6
|
+
|
|
7
|
+
- Preserve Handset history screen, backing and time context during contract claim conversion; explicit clause links alone determine current product mappings and historical judgments remain unchanged.
|
|
8
|
+
|
|
9
|
+
- Lead seed homepage heroes with what the product does for its owner, keeping free/open-source copy secondary. Optional plain-text `RunData.leadLine` supplies the composed homepage heading and the Run page introduction; omitting it preserves existing HTML and needs no seed migration.
|
|
10
|
+
|
|
11
|
+
- Agent-door conformance requires a record-write resource fixture when a writable door offers resources. BASE-AGENT-003 acceptance 4 now rejects missing or foreign links and checks the written JSON state through the same door's resources/read; approval-gated reads still withhold content.
|
|
12
|
+
|
|
13
|
+
- Reword agent-door verification path and binding examples, plus erasure column and OIDC method examples, to avoid credential-shaped quoted assignments while preserving their meaning.
|
|
14
|
+
|
|
15
|
+
- Restore identity suffixes in migration-history refusal tokens for pending checkout files, mixed Platform ledgers and checkout-owned migration identities, retaining constant adapter error codes, exit statuses and recovery guidance. Deliberately leave `migration_ledger:unknown:initial-page.sql` unrestored when it has no checkout provenance: the privacy contract excludes unchecked ledger values from diagnostics.
|
|
16
|
+
|
|
17
|
+
- Restore seed offline deploy hooks for `rer deploy --dry-run`. Hook and generic dry-run receipts include `providerChecked: false`, and local preflight keeps listing missing real-deploy inputs without contacting Cloudflare.
|
|
18
|
+
- Preserve local plans and defer missing production owner inputs when running seed dry-run hooks. Legacy hooks using the deployment kit stay offline; real deployments retain their owner preflight refusals.
|
|
19
|
+
|
|
20
|
+
## 0.2.92
|
|
21
|
+
|
|
22
|
+
- Renew the verifier's adopted policy before requests without changing its authority or lifetime; equal-sequence adoption may change only issue and expiry times.
|
|
23
|
+
|
|
24
|
+
- Inkwell transient-snapshot restore: restore fresh archives containing schema objects on policy-excluded transient tables absent from the destination, while retaining durable schema and original archive digest verification.
|
|
25
|
+
|
|
26
|
+
- Agent tools may opt into `exposure: 'invoke'` for native worker admission, hidden from MCP discovery, calls, tool-list subscriptions and unshared OAuth scopes while retaining full invoke policy, identity, replay and audit checks.
|
|
27
|
+
|
|
28
|
+
- Spool legacy archive restore: verify hashed legacy v2 ledgers through the Node library restore door before durable staging; admit migration data repeated by its surviving restore-commit trigger. Worker build-time evidence remains pending.
|
|
29
|
+
|
|
30
|
+
## 0.2.91
|
|
31
|
+
|
|
32
|
+
- Security: the agent door refuses a Business access token whose email is no longer its subject's current native email, with the same HTTP 401 and no effect as an unknown or inactive sponsor, so a token no longer outlives a change of address.
|
|
33
|
+
- Probe sponsor admission with verifier-signed access tokens for an unknown subject and a known subject with a changed email. Native negative-phase fixtures may declare `sponsors: {inactive: {sub,email}, excluded: {sub,email}}` for lifecycle-prepared persons. Each probe requires a typed HTTP 401/403 refusal and an unchanged native witness; omitted states are reported as undeclared without passing points. Fixtures receive no signing authority and failure diagnostics omit their values and identities. See `modules/agent-door/ADOPTING.md`.
|
|
34
|
+
- Additional `verification.sponsors` may declare `negativeOnly: true` when their native subjects must be registered for these probes. Their normal initialization and Business binding still run; successful cross-sponsor journeys remain required for regular sponsors.
|
|
35
|
+
|
|
36
|
+
- Account for linked native continuations and refused approval executions in agent-door audit conformance without shifting later harness rows; unrelated or policy-inconsistent extra rows still fail.
|
|
37
|
+
|
|
38
|
+
- Refuse continuation tools under unset, removed or unavailable policy and Business Pause before validating or resolving native continuation items, retaining current scope, revocation and once-only execution checks.
|
|
39
|
+
|
|
40
|
+
- Pass the disposable state reader and current verifier time to conformance phase fixtures and native step hooks. Database refusals retain a typed, redacted diagnostic; writable backdated history remains pending at the hosted state boundary.
|
|
41
|
+
|
|
42
|
+
- Audit native refusals under review policy by their refused outcome, matching returned code and absence of a review; retain linked reviews for completed effects and reject changes in bracketing native witnesses.
|
|
43
|
+
|
|
44
|
+
- Run a contained `verification.agent.initializer` once per chosen conformance agent ID, before its first public-door phase, using only the sponsor's session-bound native request and disposable mail/fixture controls. Invalid declarations refuse before installation and failures use a fixed diagnostic.
|
|
45
|
+
|
|
46
|
+
- Resource adapters now receive consent and operation identity; a resource that changes between check and read refuses `resource_changed`.
|
|
47
|
+
|
|
48
|
+
- For the 0.2.91 seed refresh, relock run-uptime (workflow lines 98, 256) and run-happytohelp (47, 170): drop `github.run_attempt` from shared build artifact names, use `<seed>-verify-build-<sha>-<run_id>` for both upload and download, and add `overwrite: true` to the upload. Verify's workflow guard rejects attempt-qualified downloads and their shared uploads; apply the same patch to any seed with this pattern on its next refresh. See `export/VERIFY-WORKFLOW.md`.
|
|
49
|
+
|
|
3
50
|
## 0.2.90
|
|
4
51
|
|
|
5
52
|
- Withhold optional copied Base modules and workflow helpers whose required packages the edition has not declared. Refresh preserves supported dependency closure and explains the package declaration needed to opt in.
|
|
@@ -6,19 +6,88 @@ import { targetIdentity } from './target.mjs';
|
|
|
6
6
|
import { auditRows } from './audit-rows.mjs';
|
|
7
7
|
|
|
8
8
|
export { auditRows } from './audit-rows.mjs';
|
|
9
|
+
|
|
10
|
+
// Reuse recorded native witnesses without replaying the refused operation or
|
|
11
|
+
// comparing across another effect or policy/fixture round.
|
|
12
|
+
function refusalWitness(c, calls, index, direction) {
|
|
13
|
+
const witness = c.surface.witness;
|
|
14
|
+
for (let i = index + direction; i >= 0 && i < calls.length; i += direction) {
|
|
15
|
+
const call = calls[i];
|
|
16
|
+
if (call.decision?.revision !== calls[index].decision.revision) return;
|
|
17
|
+
if (call.name === witness.tool && isDeepStrictEqual(call.args, c.resolve(witness.args))) return call.result?.isError ? undefined : call.result?.structuredContent;
|
|
18
|
+
if (!c.surface.tools.find(tool => tool.name === call.name)?.readOnly && !call.code) return;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function reviewProblem(c, calls, index, row, reviews) {
|
|
23
|
+
const call = calls[index];
|
|
24
|
+
if (row.outcome === 'refused') {
|
|
25
|
+
if (typeof call.code !== 'string' || !call.code) return 'the returned refusal code is missing';
|
|
26
|
+
if (row.code !== call.code) return 'the audit refusal code differs from the returned code';
|
|
27
|
+
if (row.review !== null || call.result?._meta?.['com.runeditrun/review'] || reviews.some(review => review.decision_id === row.id)) return 'a refused call opened a review row';
|
|
28
|
+
const before = refusalWitness(c, calls, index, -1), after = refusalWitness(c, calls, index, 1);
|
|
29
|
+
if (before !== undefined && after !== undefined && !isDeepStrictEqual(before, after)) return 'the native witness changed across the refusal';
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (!['done', 'replayed'].includes(row.outcome)) return `the audit outcome ${row.outcome} is neither completed nor refused`;
|
|
33
|
+
if (row.code != null || call.code || call.result?.isError) return 'the completed audit row contradicts the returned refusal code';
|
|
34
|
+
if (!row.review?.id) return 'the completed call is missing its review row';
|
|
35
|
+
if (!reviews.some(review => review.id === row.review.id && review.decision_id === (row.replay_of ?? row.id))) return 'the review row is not linked to the completed call';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Only an earlier harness row can establish the origin of native work. A
|
|
39
|
+
// marker alone never exempts an embedded call from the ordered expectations.
|
|
40
|
+
function continuationRows(c, rows, differs, report = () => {}) {
|
|
41
|
+
const recorded = new Map(c.calls.filter(call => call.kind !== 'approval/execute' && call.decision?.id).map(call => [call.decision.id, call]));
|
|
42
|
+
const origins = new Map(), accepted = new Set(); let index = 0;
|
|
43
|
+
for (const row of rows) {
|
|
44
|
+
const call = recorded.get(row.id);
|
|
45
|
+
if (call) {
|
|
46
|
+
const principal = call.principal ?? { agent: { id: c.agentId, name: 'Agent door conformance', specialist: c.surface.specialist }, consent: c.consent, sponsor: c.sponsor.id, clientId: call.kind === 'embedded' ? null : 'rer-agent-conformance' };
|
|
47
|
+
if (row.tool === call.name && row.agent?.id === principal.agent.id && row.agent?.name === principal.agent.name && row.agent?.specialist === principal.agent.specialist && row.sponsor?.id === principal.sponsor && row.consent === principal.consent && row.client_id === principal.clientId && typeof row.operation_id === 'string' && row.operation_id) {
|
|
48
|
+
if (!origins.has(row.operation_id)) origins.set(row.operation_id, []);
|
|
49
|
+
origins.get(row.operation_id).push(row);
|
|
50
|
+
}
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (row.continuation_item_id === undefined) continue;
|
|
54
|
+
const origin = origins.get(row.operation_id)?.find(item => isDeepStrictEqual(item.agent, row.agent) && isDeepStrictEqual(item.sponsor, row.sponsor) && item.consent === row.consent && item.client_id === row.client_id);
|
|
55
|
+
const dispositions = ['autonomous', 'review', 'approval', 'blocked', 'unset', 'unavailable', 'paused'];
|
|
56
|
+
const classes = Array.isArray(row.classes) && row.classes.length > 0 && new Set(classIds(row.classes)).size === row.classes.length && row.classes.every(item => AGENT_CLASSES.includes(item.class) && item.facts && typeof item.facts === 'object');
|
|
57
|
+
const rules = classes && Array.isArray(row.rules) && isDeepStrictEqual(classIds(row.rules), classIds(row.classes)) && row.rules.every(rule => dispositions.includes(rule.do) && (['unset', 'unavailable', 'paused'].includes(rule.do) ? rule.rule === null : typeof rule.rule === 'string' && rule.rule.length > 0));
|
|
58
|
+
const valid = Boolean(origin) && row.door === 'embedded' && typeof row.continuation_item_id === 'string' && row.continuation_item_id.trim().length > 0
|
|
59
|
+
&& typeof row.label === 'string' && row.label.includes(' for ') && Number.isFinite(Date.parse(row.at))
|
|
60
|
+
&& Number.isSafeInteger(row.revision) && row.revision > 0 && rules && row.decision === dispositions[Math.max(...row.rules.map(rule => dispositions.indexOf(rule.do)))]
|
|
61
|
+
&& (row.outcome === 'done' && ['autonomous', 'review', 'approval'].includes(row.decision) && row.code === null || row.outcome === 'refused' && typeof row.code === 'string' && row.code.length > 0) && differs === 0;
|
|
62
|
+
report(`BASE-AGENT-009.1.continuation.${index++}`, valid, 'Native continuation must link an earlier harness operation with the same agent, sponsor, consent and client, a recorded policy decision and a completed or coded refused outcome.');
|
|
63
|
+
if (valid) accepted.add(row);
|
|
64
|
+
}
|
|
65
|
+
return accepted;
|
|
66
|
+
}
|
|
67
|
+
|
|
9
68
|
export async function auditPhase(c) {
|
|
10
69
|
const { rows, differs } = await auditRows(c), expected = [...c.calls];
|
|
11
|
-
|
|
70
|
+
const reviews = expected.some(call => call.decision?.disposition === 'review') ? (await c.personJson('/agents/api/reviews')).reviews : [];
|
|
71
|
+
if (!Array.isArray(reviews)) throw new Error('Reviews API must return reviews');
|
|
72
|
+
const continuations = continuationRows(c, rows, differs, c.add);
|
|
73
|
+
c.add('BASE-AGENT-009.1.count', rows.length === expected.length + continuations.size, `Expected exactly ${expected.length} audit rows for tool calls, resource reads and approval executions plus ${continuations.size} native continuations, found ${rows.length}.`);
|
|
12
74
|
c.add('BASE-AGENT-009.1.unique', new Set(rows.map(row => row.id)).size === rows.length, 'Every tool call, resource read and approval execution must have its own audit ID.');
|
|
13
|
-
const perAgent = new Map();
|
|
75
|
+
const perAgent = new Map(), positions = new Map(), previous = new Map();
|
|
14
76
|
for (const row of rows) {
|
|
77
|
+
if (continuations.has(row)) continue;
|
|
15
78
|
if (!perAgent.has(row.agent?.id)) perAgent.set(row.agent?.id, []);
|
|
79
|
+
positions.set(row, perAgent.get(row.agent?.id).length);
|
|
16
80
|
perAgent.get(row.agent?.id).push(row);
|
|
17
81
|
}
|
|
18
82
|
for (const [index, call] of expected.entries()) {
|
|
19
83
|
const principal = call.principal ?? { agent: { id: c.agentId, specialist: c.surface.specialist }, consent: c.consent, sponsor: c.sponsor.id };
|
|
20
|
-
const
|
|
21
|
-
|
|
84
|
+
const candidates = perAgent.get(principal.agent.id) ?? [], decision = call.decision;
|
|
85
|
+
const match = candidates.findIndex(row => call.kind === 'approval/execute' ? row.decision_id === decision?.id && row.id !== decision?.id
|
|
86
|
+
: decision?.id ? row.id === decision.id : row.tool === call.name && row.decision_id === null && row.door === (call.kind === 'embedded' ? 'embedded' : 'mcp') && row.code === (call.code ?? null));
|
|
87
|
+
const row = match < 0 ? undefined : candidates.splice(match, 1)[0];
|
|
88
|
+
const ordered = row && positions.get(row) > (previous.get(principal.agent.id) ?? -1);
|
|
89
|
+
if (row) previous.set(principal.agent.id, positions.get(row));
|
|
90
|
+
c.add(`BASE-AGENT-009.1.call.${index}`, ordered && row.tool === call.name && row.consent === principal.consent && row.agent?.id === principal.agent.id && row.agent?.specialist === principal.agent.specialist && row.sponsor?.id === principal.sponsor && (!call.principal || row.client_id === principal.clientId && row.agent?.name === principal.agent.name) && typeof row.label === 'string' && row.label.includes(' for ') && Number.isFinite(Date.parse(row.at)) && row.door === (call.kind === 'embedded' ? 'embedded' : 'mcp'), `${call.name} lacks its complete ordered audit row.`);
|
|
22
91
|
if (!row) continue;
|
|
23
92
|
if (call.code === 'native_proof_required') c.add(`BASE-AGENT-004.native-proof.audit.${index}`, row.outcome === 'refused' && row.code === call.code, `${call.name} native proof challenge must retain its refused audit outcome.`);
|
|
24
93
|
c.add(`BASE-AGENT-009.1.resource.${index}`, call.kind === 'resources/read' ? row.resource === call.args.uri : row.resource === null || targetIdentity(row.resource), `${call.name} audit resource must identify the requested URI or the seed-resolved native kind and id.`);
|
|
@@ -27,11 +96,16 @@ export async function auditPhase(c) {
|
|
|
27
96
|
c.add(`BASE-AGENT-006.6.audit.${index}`, validClasses && (decision ? isDeepStrictEqual(classIds(row.classes), classIds(decision.classes)) && decision.classes.every(item => row.classes.some(actual => actual.class === item.class && isDeepStrictEqual(actual.facts, item.facts))) : call.kind === 'resources/read' || row.classes.length === 0), `${call.name} audit classes/facts differ from its computed decision.`);
|
|
28
97
|
if (decision) c.add(`BASE-AGENT-009.2.decision.${index}`, (call.kind === 'approval/execute' || row.id === decision.id) && row.decision === decision.disposition && row.revision === decision.revision && isDeepStrictEqual(row.rules, decision.classes.map(({ class: cls, rule, do: disposition }) => ({ class: cls, rule, do: disposition }))), `${call.name} audit decision or revision differs from the response.`);
|
|
29
98
|
else if (call.kind === 'resources/read') c.add(`BASE-AGENT-009.2.resource-rules.${index}`, Array.isArray(row.rules) && isDeepStrictEqual(classIds(row.rules), classIds(row.classes)) && row.rules.every(rule => typeof rule.rule === 'string' && ['autonomous', 'review', 'approval', 'blocked', 'unset'].includes(rule.do)), 'Resource audit classes must each carry the applied policy rule and disposition.');
|
|
30
|
-
if (decision?.disposition === 'review')
|
|
99
|
+
if (decision?.disposition === 'review') {
|
|
100
|
+
const problem = reviewProblem(c, expected, index, row, reviews);
|
|
101
|
+
c.add(`BASE-AGENT-009.4.review.${index}`, !problem, `${call.name} review audit: ${problem}.`);
|
|
102
|
+
}
|
|
31
103
|
if (call.pending) c.add(`BASE-AGENT-009.2.pending.${index}`, row.outcome === 'pending' && Boolean(call.approval?.id) && row.approval?.id === call.approval.id, `${call.name} must retain its original pending audit outcome and approval handle after the approval executes.`);
|
|
32
|
-
if (call.kind === 'approval/execute') c.add(`BASE-AGENT-008.5.execution.${index}`, row.approval?.id === call.approvalId && row.approval.by?.includes(
|
|
104
|
+
if (call.kind === 'approval/execute') c.add(`BASE-AGENT-008.5.execution.${index}`, row.approval?.id === call.approvalId && row.approval.by?.includes(principal.sponsor) && row.outcome === (call.state === 'refused' ? 'refused' : 'done') && row.code === (call.code ?? null), `${call.name} approval execution must retain its returned outcome, code and named sponsor approval.`);
|
|
33
105
|
if (call.result?._meta?.['com.runeditrun/receipt']) c.add(`BASE-AGENT-008.5.audit.${index}`, Boolean(row.approval?.id) && row.approval.by?.includes(row.sponsor.id), `${call.name} approval receipt lacks the signed-in sponsor as approver.`);
|
|
34
106
|
}
|
|
107
|
+
let extraIndex = 0;
|
|
108
|
+
for (const extra of perAgent.values()) for (const row of extra) c.add(`BASE-AGENT-009.1.extra.${extraIndex++}`, false, `${row.tool} has no recorded harness call or valid native continuation.`);
|
|
35
109
|
c.add('BASE-AGENT-007.7.differs-from-policy', differs === 0, `Audit evidence has ${differs} decisions that differ from the policy in force.`);
|
|
36
110
|
// Audit is read before the events tool: its own call is audited as well, but
|
|
37
111
|
// cannot occur in a snapshot taken before it was made.
|
|
@@ -61,5 +135,6 @@ export async function auditPhase(c) {
|
|
|
61
135
|
c.add('BASE-AGENT-010.3.cursor', first.length > 0 && isDeepStrictEqual(first, second.slice(0, first.length)) && first[0] === events[1].id, 'Replaying one cursor must return the same retained event ids in order.');
|
|
62
136
|
}
|
|
63
137
|
const final = await auditRows(c);
|
|
64
|
-
|
|
138
|
+
const finalContinuations = continuationRows(c, final.rows, final.differs);
|
|
139
|
+
c.add('BASE-AGENT-009.1.events-audited', final.rows.length === c.calls.length + finalContinuations.size && final.differs === 0, `events.list audit calls mismatch: ${final.rows.length} audit rows for ${c.calls.length} calls and ${finalContinuations.size} native continuations.`);
|
|
65
140
|
}
|