@runeditrun/rer 0.2.91 → 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/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 +27 -0
- package/modules/agent-door/conformance/crypto.mjs +14 -2
- package/modules/agent-door/conformance/journey.mjs +26 -2
- package/modules/agent-door/conformance/negative.mjs +4 -1
- package/modules/agent-door/conformance/policy-phases.mjs +43 -1
- package/modules/agent-door/conformance/protocol.mjs +42 -7
- package/modules/agent-door/conformance/sponsors.mjs +4 -0
- 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/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,32 @@
|
|
|
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
|
+
|
|
3
30
|
## 0.2.91
|
|
4
31
|
|
|
5
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.
|
|
@@ -26,11 +26,23 @@ export async function accessToken(context, overrides = {}) {
|
|
|
26
26
|
}
|
|
27
27
|
export const autonomousPolicy = () => ({ schema: 'rer-agent-policy/1', catalogue: CATALOGUE, rules: [{ id: 'all', class: '*', do: 'autonomous' }], spend: { none: true } });
|
|
28
28
|
export const heldPolicy = () => ({ schema: 'rer-agent-policy/1', catalogue: CATALOGUE, rules: [{ id: 'all', class: '*', do: 'approval', approver: ['sponsor'], wait: 'PT1H' }, { id: 'standard', class: 'standard', do: 'review' }], reviewers: ['sponsor'], spend: { none: true } });
|
|
29
|
+
// A revision is immutable evidence. Reuse its signature when a helper caller
|
|
30
|
+
// refreshes that revision, including after rejected intermediate proposals.
|
|
31
|
+
const revisionSignatures = new WeakMap();
|
|
29
32
|
export async function policyEnvelope(context, document, { paused = false, revoked, revision = context.revision + 1, seq = context.seq + 1, ...overrides } = {}) {
|
|
30
33
|
const iat = seconds(context.now);
|
|
31
|
-
const
|
|
34
|
+
const claims = {
|
|
32
35
|
business: context.business, revision, document_sha256: createHash('sha256').update(canonical(document)).digest('hex'),
|
|
33
|
-
}
|
|
36
|
+
};
|
|
37
|
+
let signatures = revisionSignatures.get(context.signer.privateKey);
|
|
38
|
+
if (!signatures) revisionSignatures.set(context.signer.privateKey, signatures = new Map());
|
|
39
|
+
const key = canonical({ kid: context.signer.kid, ...claims });
|
|
40
|
+
if (document !== null && !signatures.has(key)) signatures.set(key, signJws(context.signer.privateKey, context.signer.kid, 'rer-agent-policy-revision+jwt', claims));
|
|
41
|
+
const revision_signature = document === null ? null : await signatures.get(key);
|
|
34
42
|
const payload = { v: 1, iss: context.signer.issuer, aud: context.origin, sub: context.signer.installationId, business: context.business, seq, revision, paused, catalogue: CATALOGUE, document, revision_signature, iat, exp: iat + 300, ...(revoked === undefined ? {} : { revoked }), ...overrides };
|
|
35
43
|
return { payload, policy: await signJws(context.signer.privateKey, context.signer.kid, 'rer-agent-policy+jwt', payload) };
|
|
36
44
|
}
|
|
45
|
+
export async function renewalEnvelope(context, adopted) {
|
|
46
|
+
const iat = seconds(context.now), payload = { ...adopted, iat, exp: iat + 300 };
|
|
47
|
+
return { payload, policy: await signJws(context.signer.privateKey, context.signer.kid, 'rer-agent-policy+jwt', payload) };
|
|
48
|
+
}
|
|
@@ -17,8 +17,23 @@ function checkOutput(c, step, answer, phase) {
|
|
|
17
17
|
const errors = schema === undefined ? ['missing outputSchema'] : schemaErrors(schema, answer.result?.structuredContent);
|
|
18
18
|
c.add(`BASE-AGENT-002.2.${phase}.${step.id}`, errors.length === 0, `${step.tool} output does not validate: ${errors.slice(0, 8).join('; ')}.`);
|
|
19
19
|
}
|
|
20
|
-
|
|
20
|
+
function fixtureLink(c, template, uri) {
|
|
21
|
+
if (typeof uri !== 'string') return false;
|
|
22
|
+
try {
|
|
23
|
+
const parsed = new URL(uri), declared = new URL(template);
|
|
24
|
+
if (parsed.protocol !== declared.protocol || parsed.host !== declared.host || parsed.username || parsed.password) return false;
|
|
25
|
+
if (['http:', 'https:'].includes(parsed.protocol) && parsed.origin !== c.origin) return false;
|
|
26
|
+
const pattern = template.split(/\{[^}]+\}/).map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[^/?#]+');
|
|
27
|
+
return new RegExp(`^${pattern}$`).test(uri);
|
|
28
|
+
} catch { return false; }
|
|
29
|
+
}
|
|
30
|
+
async function checkResources(c, step, answer, phase, held, outputs) {
|
|
21
31
|
const links = answer.result?.content?.filter(item => item.type === 'resource_link') ?? [];
|
|
32
|
+
const fixture = offers(c.surface.capabilities, 'resources') && step.resource;
|
|
33
|
+
const expected = fixture && c.resolve(fixture.state, outputs);
|
|
34
|
+
const matching = fixture ? links.filter(link => fixtureLink(c, fixture.uriTemplate, link.uri)) : [];
|
|
35
|
+
if (fixture) c.add(`BASE-AGENT-003.4.links.${phase}.${step.id}`, matching.length > 0, `${step.tool} must return a resource_link matching its native fixture URI template.`);
|
|
36
|
+
let written = false, withheld = false;
|
|
22
37
|
for (const [i, link] of links.entries()) {
|
|
23
38
|
const read = await c.mcp('resources/read', { uri: link.uri }, step.client === undefined ? {} : { client: step.client });
|
|
24
39
|
const classes = read.decision?.classes, needsApproval = held && classes?.some(item => item.class !== 'standard');
|
|
@@ -26,6 +41,13 @@ async function checkResources(c, step, answer, phase, held) {
|
|
|
26
41
|
c.add(`BASE-AGENT-003.4.${phase}.${step.id}.${i}`, read.status === 200 && (needsApproval
|
|
27
42
|
? errorCode(read) === 'approval_required' && read.decision?.disposition === 'approval' && !read.result?.contents?.length
|
|
28
43
|
: !read.message?.error && read.decision?.disposition === (held ? 'review' : 'autonomous') && Array.isArray(read.result?.contents) && read.result.contents.length > 0), `${step.tool} resource_link ${link.uri} must ${needsApproval ? 'withhold content pending approval' : 'read back under the current policy'}.`);
|
|
44
|
+
if (fixture && matching.includes(link)) {
|
|
45
|
+
withheld ||= needsApproval;
|
|
46
|
+
written ||= read.status === 200 && !read.message?.error && !errorCode(read) && read.result?.contents?.some(content => {
|
|
47
|
+
if (content.uri !== link.uri || typeof content.text !== 'string') return false;
|
|
48
|
+
try { return subset(JSON.parse(content.text), expected); } catch { return false; }
|
|
49
|
+
});
|
|
50
|
+
}
|
|
29
51
|
if (needsApproval) {
|
|
30
52
|
const pending = read.body?.error?.data?.approval;
|
|
31
53
|
c.add(`BASE-AGENT-007.5.resource.${phase}.${step.id}.${i}`, pending?.id && typeof pending.url === 'string' && new URL(pending.url, c.origin).origin === c.origin && Number.isFinite(Date.parse(pending.expires_at)), `${link.uri} must expose a pending approval on the native person door.`);
|
|
@@ -35,6 +57,8 @@ async function checkResources(c, step, answer, phase, held) {
|
|
|
35
57
|
}
|
|
36
58
|
}
|
|
37
59
|
}
|
|
60
|
+
// Approval-gated content must remain withheld; autonomous reads prove its state.
|
|
61
|
+
if (fixture && !withheld) c.add(`BASE-AGENT-003.4.state.${phase}.${step.id}`, written, `${step.tool} resource_link must read back the fixture's written state through this door's resources/read.`);
|
|
38
62
|
}
|
|
39
63
|
export async function runJourney(c, phase, { held = false, injections = false, replay = false } = {}) {
|
|
40
64
|
const outputs = new Map(); let replayed = false;
|
|
@@ -84,7 +108,7 @@ export async function runJourney(c, phase, { held = false, injections = false, r
|
|
|
84
108
|
if (answer.result?.isError || answer.result?.structuredContent === undefined) continue;
|
|
85
109
|
outputs.set(step.id, answer.result.structuredContent);
|
|
86
110
|
checkOutput(c, step, answer, phase);
|
|
87
|
-
await checkResources(c, step, answer, phase, held);
|
|
111
|
+
await checkResources(c, step, answer, phase, held, outputs);
|
|
88
112
|
if (narrowing) {
|
|
89
113
|
const witnessArgs = c.resolve(narrowing.witness.args, outputs);
|
|
90
114
|
c.add(`BASE-AGENT-005.narrowing.${step.tool}.target`, narrowingTargets(declared).every(target => isDeepStrictEqual(witnessArgs[target], args[target])), `${step.tool} must witness every identifier of the same targeted subject.`);
|
|
@@ -69,6 +69,9 @@ export async function negativePhase(c) {
|
|
|
69
69
|
const foreign = await c.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy: foreignBusiness.policy }) });
|
|
70
70
|
c.add('BASE-AGENT-007.8.business', !foreign.ok, 'An envelope whose Business does not match its revision signature was accepted.');
|
|
71
71
|
await foreign.body?.cancel();
|
|
72
|
-
|
|
72
|
+
// Slow requests may renew the adopted envelope before the second state read.
|
|
73
|
+
// Only its acknowledged expiry may change; every other field stays strict.
|
|
74
|
+
const sameState = actual => isDeepStrictEqual({ ...state, policy: { ...state.policy, expires_at: new Date(c.adoptedPolicy.exp * 1000).toISOString() } }, actual);
|
|
75
|
+
c.add('BASE-AGENT-007.8.state', sameState(await c.personJson('/agents/api/state')), 'An invalid envelope changed the adopted policy state or revision.');
|
|
73
76
|
c.add('BASE-AGENT-004.negative-no-effect', isDeepStrictEqual(before, await c.witness()), 'An authentication/person-door/policy-envelope negative changed native state.');
|
|
74
77
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
-
import {
|
|
2
|
+
import { webcrypto } from 'node:crypto';
|
|
3
|
+
import { autonomousPolicy, policyEnvelope, signJws, seconds } from './crypto.mjs';
|
|
3
4
|
import { errorCode } from './protocol.mjs';
|
|
4
5
|
import { nativeStepHook } from './step-hooks.mjs';
|
|
5
6
|
|
|
@@ -29,6 +30,47 @@ export async function removalPhase(c) {
|
|
|
29
30
|
await unsetPolicy(c);
|
|
30
31
|
await c.adopt(autonomousPolicy());
|
|
31
32
|
c.add('BASE-AGENT-007.2.unset-no-effect', isDeepStrictEqual(before, await c.witness()), 'Calls under the removed policy changed native state.');
|
|
33
|
+
await renewalRefusals(c);
|
|
34
|
+
}
|
|
35
|
+
async function renewalRefusals(c) {
|
|
36
|
+
const state = await c.personJson('/agents/api/state'), approvals = await c.personJson('/agents/api/approvals'), before = await c.witness();
|
|
37
|
+
const sign = payload => signJws(c.signer.privateKey, c.signer.kid, 'rer-agent-policy+jwt', payload);
|
|
38
|
+
const changed = autonomousPolicy(); changed.rules = [{ id: 'all', class: '*', do: 'blocked' }];
|
|
39
|
+
const foreign = await webcrypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']);
|
|
40
|
+
const cases = [
|
|
41
|
+
['expired', (_adopted, later) => sign({ ...later, exp: seconds(c.now) - 1 }), 'policy_invalid', 400],
|
|
42
|
+
['untrusted', (_adopted, later) => signJws(foreign.privateKey, c.signer.kid, 'rer-agent-policy+jwt', later), 'policy_invalid', 400],
|
|
43
|
+
['revision-mismatch', (_adopted, later) => sign({ ...later, document: changed }), 'policy_revision_invalid', 400],
|
|
44
|
+
['equal-iat', (adopted, later) => sign({ ...later, iat: adopted.iat }), 'policy_stale', 409],
|
|
45
|
+
['earlier-iat', (adopted, later) => sign({ ...later, iat: adopted.iat - 1 }), 'policy_stale', 409],
|
|
46
|
+
['document', (_adopted, _later, options) => policyEnvelope(c, changed, options).then(signed => signed.policy), 'policy_stale', 409],
|
|
47
|
+
['revision', (adopted, _later, options) => policyEnvelope(c, adopted.document, { ...options, revision: adopted.revision + 1 }).then(signed => signed.policy), 'policy_stale', 409],
|
|
48
|
+
['business', (adopted, _later, options) => policyEnvelope({ ...c, business: `${c.business}-other` }, adopted.document, options).then(signed => signed.policy), 'policy_stale', 409],
|
|
49
|
+
['paused', (adopted, later) => sign({ ...later, paused: !adopted.paused }), 'policy_stale', 409],
|
|
50
|
+
['revoked', (_adopted, later) => sign({ ...later, revoked: { agents: [c.agentId], consents: [c.consent] } }), 'policy_stale', 409],
|
|
51
|
+
['revision-signature', async (adopted, later) => {
|
|
52
|
+
const claims = JSON.parse(Buffer.from(adopted.revision_signature.split('.')[1], 'base64url').toString());
|
|
53
|
+
return sign({ ...later, revision_signature: await signJws(c.signer.privateKey, c.signer.kid, 'rer-agent-policy-revision+jwt', claims) });
|
|
54
|
+
}, 'policy_stale', 409],
|
|
55
|
+
['untrusted-revision', async (adopted, later, options) => {
|
|
56
|
+
const signed = await policyEnvelope({ ...c, signer: { ...c.signer, privateKey: foreign.privateKey } }, adopted.document, options);
|
|
57
|
+
return sign({ ...later, revision_signature: signed.payload.revision_signature });
|
|
58
|
+
}, 'policy_revision_invalid', 400],
|
|
59
|
+
];
|
|
60
|
+
for (const [name, candidate, code, status] of cases) {
|
|
61
|
+
await c.renewPolicy();
|
|
62
|
+
const adopted = c.adoptedPolicy, later = { ...adopted, iat: adopted.iat + 1, exp: seconds(c.now) + 300 };
|
|
63
|
+
const policy = await candidate(adopted, later, { seq: adopted.seq, revision: adopted.revision, iat: later.iat, exp: later.exp });
|
|
64
|
+
const response = await c.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy }) });
|
|
65
|
+
const body = await response.json();
|
|
66
|
+
const call = await c.tool(c.surface.witness.tool, c.resolve(c.surface.witness.args));
|
|
67
|
+
// Slow requests may legitimately renew between probes. Only the verifier's
|
|
68
|
+
// acknowledged renewal may change the expected expiry, never authority.
|
|
69
|
+
const sameState = actual => isDeepStrictEqual({ ...state, policy: { ...state.policy, expires_at: new Date(c.adoptedPolicy.exp * 1000).toISOString() } }, actual);
|
|
70
|
+
c.add(`BASE-AGENT-007.7.renew.${name}`, response.status === status && body.code === code &&
|
|
71
|
+
sameState(await c.personJson('/agents/api/state')) && isDeepStrictEqual(approvals, await c.personJson('/agents/api/approvals')) &&
|
|
72
|
+
!call.result?.isError && isDeepStrictEqual(before, call.result?.structuredContent), `${name} must refuse ${code} without changing policy, approvals or native state.`);
|
|
73
|
+
}
|
|
32
74
|
}
|
|
33
75
|
export async function blockedPhases(c) {
|
|
34
76
|
const nonstandard = [...new Set(c.surface.tools.flatMap(tool => tool.classes))].filter(cls => cls !== 'standard');
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
-
import { accessToken, policyEnvelope } from './crypto.mjs';
|
|
3
|
+
import { accessToken, policyEnvelope, renewalEnvelope, seconds } from './crypto.mjs';
|
|
4
4
|
import { AGENT_CLASSES } from './surface.mjs';
|
|
5
5
|
import { phaseFixtures } from './fixtures.mjs';
|
|
6
|
+
import { validToolName } from './tool-name.mjs';
|
|
6
7
|
|
|
7
8
|
export const VERSION = '2026-07-28';
|
|
8
9
|
export const DECISION = 'com.runeditrun/decision';
|
|
@@ -62,6 +63,7 @@ export function createProtocol(context) {
|
|
|
62
63
|
// A 429 is a capacity refusal, not an action result. Honor only a bounded,
|
|
63
64
|
// explicit Retry-After; never replay an application or policy refusal.
|
|
64
65
|
for (let attempt = 0; ; attempt++) {
|
|
66
|
+
if (new URL(path, context.origin).pathname !== '/api/rer/agent-policy') await context.renewPolicy();
|
|
65
67
|
const response = await context.fetch(new URL(path, `${context.origin}/`).href, { redirect: 'manual', ...init });
|
|
66
68
|
if (response.status !== 429) return response;
|
|
67
69
|
const header = response.headers.get('retry-after'), delay = header && /^\d+(?:\.\d+)?$/.test(header) ? Number(header) * 1000 : header ? Date.parse(header) - Date.now() : NaN;
|
|
@@ -134,19 +136,52 @@ export function createProtocol(context) {
|
|
|
134
136
|
if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error(`Witness ${context.surface.witness.tool} failed (${errorCode(answer) ?? answer.status})`);
|
|
135
137
|
return answer.result.structuredContent;
|
|
136
138
|
};
|
|
137
|
-
|
|
138
|
-
const signed = await policyEnvelope(context, document, options);
|
|
139
|
+
const postPolicy = async signed => {
|
|
139
140
|
const response = await context.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy: signed.policy }) });
|
|
140
141
|
const body = await responseBody(response);
|
|
141
142
|
if (!response.ok) throw new Error(`Policy adoption failed: HTTP ${response.status} (${typeof body.code === 'string' ? body.code : 'invalid response'})`);
|
|
143
|
+
if (!isDeepStrictEqual(body.adopted, { seq: signed.payload.seq, revision: signed.payload.revision })) throw new Error('Policy adoption acknowledgement differs from its envelope');
|
|
144
|
+
context.adoptedPolicy = structuredClone(signed.payload);
|
|
145
|
+
return body;
|
|
146
|
+
};
|
|
147
|
+
let renewing;
|
|
148
|
+
context.renewPolicy = async () => {
|
|
149
|
+
if (renewing) return renewing;
|
|
150
|
+
const adopted = context.adoptedPolicy, now = seconds(context.now);
|
|
151
|
+
if (!adopted || adopted.exp - now >= 60 || now <= adopted.iat) return;
|
|
152
|
+
renewing = (async () => { await postPolicy(await renewalEnvelope(context, adopted)); })();
|
|
153
|
+
try { await renewing; } finally { renewing = undefined; }
|
|
154
|
+
};
|
|
155
|
+
context.adopt = async (document, options = {}) => {
|
|
156
|
+
const signed = await policyEnvelope(context, document, options);
|
|
157
|
+
const body = await postPolicy(signed);
|
|
142
158
|
context.seq = signed.payload.seq; context.revision = signed.payload.revision; context.document = document;
|
|
143
|
-
const expectedClasses = [...new Set(context.surface.tools.flatMap(tool => tool.classes))];
|
|
144
159
|
const actualClasses = body.door?.classes;
|
|
145
|
-
const
|
|
160
|
+
const declared = new Set(context.surface.tools.map(tool => tool.name));
|
|
161
|
+
const shaped = Array.isArray(actualClasses) && new Set(actualClasses.map(row => row?.class)).size === actualClasses.length && actualClasses.every(row =>
|
|
146
162
|
row && Object.keys(row).sort().join(',') === 'class,tools' && AGENT_CLASSES.includes(row.class) && Array.isArray(row.tools) &&
|
|
147
|
-
|
|
163
|
+
row.tools.length <= 20 && new Set(row.tools).size === row.tools.length && row.tools.every(name => validToolName(name, context.surface.seed)));
|
|
164
|
+
// The policy answer declares native-only tools too. Retain that declaration
|
|
165
|
+
// across revisions; it must never expand the edition's public MCP surface.
|
|
166
|
+
const invokeTools = context.invokeTools ?? (shaped ? [...new Set(actualClasses.flatMap(row => row.tools).filter(name => !declared.has(name)))].map(name => ({
|
|
167
|
+
name, classes: actualClasses.filter(row => row.tools.includes(name)).map(row => row.class),
|
|
168
|
+
})) : []);
|
|
169
|
+
const policyTools = [...context.surface.tools, ...invokeTools];
|
|
170
|
+
const expectedClasses = [...new Set(policyTools.flatMap(tool => tool.classes))];
|
|
171
|
+
const validClasses = shaped && actualClasses.every(row =>
|
|
172
|
+
isDeepStrictEqual([...row.tools].sort(), policyTools.filter(tool => tool.classes.includes(row.class)).map(tool => tool.name).sort().slice(0, 20))) &&
|
|
148
173
|
expectedClasses.every(cls => actualClasses.some(row => row.class === cls));
|
|
149
|
-
|
|
174
|
+
let hidden = true;
|
|
175
|
+
if (invokeTools.length) {
|
|
176
|
+
const listed = await context.mcp('tools/list');
|
|
177
|
+
hidden = listed.status === 401 && listed.result === undefined || Array.isArray(listed.result?.tools) && invokeTools.every(tool => !listed.result.tools.some(item => item.name === tool.name));
|
|
178
|
+
for (const tool of invokeTools) {
|
|
179
|
+
const answer = await context.tool(tool.name, {});
|
|
180
|
+
hidden &&= answer.status === 400 && errorCode(answer) === 'tool_not_found' && answer.result === undefined && !answer.decision;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (validClasses && hidden) context.invokeTools = invokeTools;
|
|
184
|
+
context.add(`BASE-AGENT-007.7.adopt.${context.seq}`, Object.keys(body).sort().join(',') === 'adopted,door' && isDeepStrictEqual(body.adopted, { seq: context.seq, revision: context.revision }) && validClasses && hidden, 'Policy answer must contain exactly adopted {seq,revision} and catalogue classes with the exact declared tool mappings; native-only tools must remain absent from MCP discovery and calls, and resource-only classes have no tools.');
|
|
150
185
|
return signed;
|
|
151
186
|
};
|
|
152
187
|
phaseFixtures(context, context.prepare);
|
|
@@ -19,6 +19,10 @@ export async function crossSponsorPhase(c, sponsors, initializeAgent) {
|
|
|
19
19
|
return;
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
|
+
b.renewPolicy = async () => {
|
|
23
|
+
await c.renewPolicy();
|
|
24
|
+
b.seq = c.seq; b.revision = c.revision; b.document = c.document;
|
|
25
|
+
};
|
|
22
26
|
const prefix = `BASE-AGENT-004.cross-sponsor.${person.label}`;
|
|
23
27
|
await c.adopt(autonomousPolicy());
|
|
24
28
|
b.revision = c.revision;
|
|
@@ -63,6 +63,12 @@ export function validateAgentSurface(surface, { contract } = {}) {
|
|
|
63
63
|
if (step?.client !== undefined) add(`journey.${id}.client`, text(step.client) && text(surface.verification?.fixtures?.module), `${id} requires a named native client and verification.fixtures.`);
|
|
64
64
|
for (const item of expect) coverage.get(step?.tool)?.add(item?.class);
|
|
65
65
|
checkReferences(step?.args, `journey.${id}`, steps);
|
|
66
|
+
if (step?.resource !== undefined && offers(surface.capabilities, 'resources')) {
|
|
67
|
+
const fixture = step.resource;
|
|
68
|
+
const resourcePoint = (suffix, ok, detail) => points.push({ id: `BASE-AGENT-003.4.fixture.${id}.${suffix}`, ok: Boolean(ok), ...(!ok ? { detail } : {}) });
|
|
69
|
+
resourcePoint('state', tool?.readOnly === false && object(fixture) && Object.keys(fixture).sort().join(',') === 'state,uriTemplate' && surface.resources?.includes(fixture.uriTemplate) && object(fixture.state) && Object.keys(fixture.state).length > 0, `${id}.resource must declare a native URI template and nonempty expected written state on a mutating tool.`);
|
|
70
|
+
checkReferences(fixture?.state, `journey.${id}.resource`, new Set([...steps, id]), resourcePoint);
|
|
71
|
+
}
|
|
66
72
|
if (step?.target !== undefined) {
|
|
67
73
|
const target = step.target;
|
|
68
74
|
add(`journey.${id}.target`, object(target) && Object.keys(target).sort().join(',') === 'id,kind' && text(target.kind) && (text(target.id) || object(target.id) && ('$from' in target.id || '$sponsor' in target.id || '$fixture' in target.id)), `${id}.target must contain only a nonempty kind and an id string or journey reference.`);
|
|
@@ -92,6 +98,10 @@ export function validateAgentSurface(surface, { contract } = {}) {
|
|
|
92
98
|
for (const [name, tool] of tools) for (const cls of Array.isArray(tool?.classes) ? tool.classes : []) add(`${name}.coverage.${cls}`, coverage.get(name).has(cls), `${name} has no journey fixture for declared class ${cls}.`);
|
|
93
99
|
if (offers(surface.capabilities, 'events')) add('events', tools.has(`${surface.seed}.events.list`), `Declare built-in ${surface.seed}.events.list in the Agent surface.`);
|
|
94
100
|
if (set.mode === 'declared' && offers(surface.capabilities, 'resources')) add('resources.offered', surface.resources.length > 0, 'Declared resources must offer at least one resource template.');
|
|
101
|
+
if (offers(surface.capabilities, 'resources') && surface.resources?.length && [...tools.values()].some(tool => tool.readOnly === false)) {
|
|
102
|
+
const ok = surface.journey?.some(step => tools.get(step.tool)?.readOnly === false && step.resource !== undefined);
|
|
103
|
+
points.push({ id: 'BASE-AGENT-003.4.fixture', ok: Boolean(ok), ...(!ok ? { detail: 'A writable door with resources must declare a record-writing journey resource fixture and its expected written state.' } : {}) });
|
|
104
|
+
}
|
|
95
105
|
add('witness', object(surface.witness) && tools.get(surface.witness.tool)?.readOnly === true && object(surface.witness.args), 'witness must name a declared readOnly tool and arguments.');
|
|
96
106
|
checkReferences(surface.witness?.args, 'witness', new Set());
|
|
97
107
|
return { ok: points.every(point => point.ok), points };
|