@runeditrun/rer 0.2.91 → 0.2.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/cli/README.md +1 -1
  2. package/cli/agent-door.mjs +20 -10
  3. package/cli/agent-history-database.mjs +82 -0
  4. package/cli/agent-history-isolation.mjs +68 -0
  5. package/cli/agent-history.mjs +58 -0
  6. package/cli/agent-journey-fixtures.mjs +3 -3
  7. package/cli/agent-network.mjs +12 -6
  8. package/cli/business/choices.mjs +3 -3
  9. package/cli/business/command.mjs +19 -0
  10. package/cli/business/setup-command.mjs +14 -1
  11. package/cli/deploy-command.mjs +19 -8
  12. package/cli/deploy.mjs +1 -1
  13. package/cli/export.mjs +1 -1
  14. package/cli/hosted-hosts.mjs +21 -0
  15. package/cli/hosted-output.mjs +91 -8
  16. package/cli/ledger-refusal.mjs +1 -1
  17. package/cli/lifecycle.mjs +5 -0
  18. package/cli/local.mjs +1 -1
  19. package/cli/port.mjs +1 -2
  20. package/cli/portability-evidence.d.mts +5 -0
  21. package/cli/portability-evidence.mjs +85 -0
  22. package/cli/portability-migrations.mjs +21 -9
  23. package/cli/portability-worker.mjs +4 -2
  24. package/edition-authoring/module-edges.mjs +14 -1
  25. package/foundation/runtime/contract-anchor.mjs +87 -0
  26. package/foundation/runtime/contract-docs.mjs +46 -16
  27. package/global/CHANGELOG.md +63 -0
  28. package/install.sh +4 -1
  29. package/modules/agent-door/conformance/crypto.mjs +14 -2
  30. package/modules/agent-door/conformance/injection.mjs +5 -3
  31. package/modules/agent-door/conformance/journey.mjs +27 -3
  32. package/modules/agent-door/conformance/negative.mjs +4 -1
  33. package/modules/agent-door/conformance/policy-phases.mjs +43 -1
  34. package/modules/agent-door/conformance/protocol.mjs +42 -7
  35. package/modules/agent-door/conformance/sponsors.mjs +4 -0
  36. package/modules/agent-door/conformance/surface.mjs +10 -0
  37. package/modules/deploy-kit/README.md +1 -1
  38. package/modules/deploy-kit/owner-cli.mjs +9 -1
  39. package/modules/deploy-kit/prepare.mjs +5 -2
  40. package/modules/erasure/README.md +4 -2
  41. package/modules/operator-auth/identity/oidc/README.md +2 -1
  42. package/modules/portability/README.md +84 -2
  43. package/modules/portability/backfills.mjs +96 -3
  44. package/modules/portability/bridge.mjs +3 -1
  45. package/modules/portability/catalogue.mjs +11 -1
  46. package/modules/portability/checkout-history.mjs +14 -0
  47. package/modules/portability/format.mjs +1 -0
  48. package/modules/portability/import.mjs +58 -3
  49. package/modules/portability/index.d.mts +3 -1
  50. package/modules/portability/index.mjs +16 -5
  51. package/modules/portability/library-history.mjs +147 -0
  52. package/modules/portability/migration-history.mjs +3 -2
  53. package/modules/portability/restore-safety.mjs +6 -3
  54. package/modules/portability/snapshot-objects.mjs +16 -0
  55. package/modules/portability/worker-history.d.mts +9 -0
  56. package/modules/portability/worker-history.mjs +29 -0
  57. package/onboarding/adapter.mjs +28 -14
  58. package/package.json +9 -1
@@ -5,6 +5,7 @@ import path from 'node:path'
5
5
  import { execFileSync } from 'node:child_process'
6
6
  import { parseContract, clauseIdSource, plainText } from './seed-contract.mjs'
7
7
  import { contractProseFindings, printProseFindings } from './contract-prose.mjs'
8
+ import { anchorPath, createAnchor, readAnchor } from './contract-anchor.mjs'
8
9
 
9
10
  const marker = '<!-- Generated from CONTRACT.md by contract-docs. Edit CONTRACT.md, then regenerate. -->'
10
11
  const idPattern = new RegExp(`^${clauseIdSource}$`)
@@ -54,6 +55,12 @@ function snapshot(reference) {
54
55
  if (!files['CONTRACT.md']) throw Error(`${reference} has no CONTRACT.md.`)
55
56
  return { commit, files }
56
57
  }
58
+ function anchoredSnapshot(commit) {
59
+ const recorded = readAnchor(commit)
60
+ if (recorded) return recorded
61
+ try { return snapshot(commit) }
62
+ catch (error) { throw Error(`${anchorPath}: contract_anchor_missing: original ${commit} is unavailable; record it with anchor --old <ref> in a checkout with history. ${error.message}`) }
63
+ }
57
64
  function summaryRange(text) {
58
65
  const lines = linesOf(text), start = lines.findIndex(line => cells(line).join('|') === 'Clauses|Done|Partial|Missing|Total')
59
66
  if (start < 0) return undefined
@@ -137,23 +144,26 @@ function generatedFiles(text) {
137
144
  if (!rows.length) claims.push('No homepage claims are mapped yet.')
138
145
  else {
139
146
  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))))
147
+ const hasSection = rows.some(row => row.header.some(cell => /^(Section|Screen)$/i.test(plainText(cell))))
148
+ const hasBacking = rows.some(row => row.header.some(cell => claimHeader(cell) === 'Backing'))
141
149
  const hasNonProduct = provenance?.claims.some(row => row.nonProduct)
142
- const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasNonProduct ? ['Basis'] : []), ...(provenance ? ['Historical status'] : []), 'Status']
150
+ const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasBacking ? ['Backing'] : []), ...(hasNonProduct ? ['Basis'] : []), ...(provenance ? ['Historical status'] : []), 'Status']
143
151
  const table = [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`], counts = { done: 0, partial: 0, missing: 0, unassessed: 0 }
144
152
  for (const [index, row] of rows.entries()) {
145
153
  const value = label => claimValue(row, label)
146
154
  const source = provenance?.claims[index]
155
+ const location = hasSection ? [value('Section|Screen')] : []
156
+ const backing = hasBacking ? [value('Backing')] : []
147
157
  if (source?.nonProduct) {
148
158
  counts.unassessed++
149
- table.push(`| ${[value('#'), ...(hasSection ? [value('Section')] : []), value('Claim'), '', `Non-product: ${source.nonProduct}`, source.status || 'Not recorded', 'unassessed'].map(tableCell).join(' | ')} |`)
159
+ table.push(`| ${[value('#'), ...location, value('Claim'), '', ...backing, `Non-product: ${source.nonProduct}`, source.status || 'Not recorded', 'unassessed'].map(tableCell).join(' | ')} |`)
150
160
  continue
151
161
  }
152
162
  const ids = idsIn(value('Clauses?')), linked = ids.map(id => clauses.find(clause => clause.id === id))
153
163
  if (!ids.length || linked.some(clause => !clause)) throw Error(`CONTRACT.md:${row.line}: Homepage claim needs existing clause ids.`)
154
164
  const state = linked.every(clause => clause.status === 'done') ? 'done' : linked.every(clause => clause.status === 'missing') ? 'missing' : 'partial'
155
165
  counts[state]++
156
- table.push(`| ${[value('#') || String(index + 1), ...(hasSection ? [value('Section')] : []), value('Claim'), linked.map(clause => `\`${clause.id}\` ${clause.status}`).join('; '), ...(hasNonProduct ? ['Product'] : []), ...(provenance ? [source?.status || 'Not recorded'] : []), state].map(tableCell).join(' | ')} |`)
166
+ 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
167
  }
158
168
  claims.push(table.join('\n'), `Claims: ${rows.length}; ${counts.done} done, ${counts.partial} partial, ${counts.missing} missing.${hasNonProduct ? ` Non-product: ${counts.unassessed} unassessed.` : ''}`)
159
169
  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.`)
@@ -166,7 +176,7 @@ function generate(check = false) {
166
176
  const coverage = read(covMapPath)
167
177
  if (coverage !== undefined) {
168
178
  let original
169
- try { original = snapshot(JSON.parse(coverage).old?.commit) }
179
+ try { original = anchoredSnapshot(JSON.parse(coverage).old?.commit) }
170
180
  catch (error) { throw Error(`${covMapPath}: original SHA is unavailable: ${error.message}`) }
171
181
  validateOriginalClaims(original)
172
182
  }
@@ -318,15 +328,20 @@ function requirementAndAcceptance(body, oldAcceptance, clause) {
318
328
  return { text: result.join('\n\n'), history }
319
329
  }
320
330
  // 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'])
331
+ const claimHeaders = new Set(['claim', 'claims', 'claim on the page', 'what the page claims', 'claim text', 'capability claimed'])
322
332
  function claimHeader(cell) {
323
333
  const value = plainText(cell).toLowerCase()
324
334
  if (claimHeaders.has(value)) return 'Claim'
325
335
  if (['clause', 'clauses', 'clause(s)', 'clause id(s)'].includes(value)) return 'Clauses'
326
336
  if (value === 'claim #') return '#'
337
+ if (value === 'code and target contract backing' || value === 'backing') return 'Backing'
327
338
  return plainText(cell)
328
339
  }
329
- const claimValue = (row, label) => row.cells[row.header.findIndex(cell => new RegExp(`^${label}$`, 'i').test(claimHeader(cell)))] ?? ''
340
+ const claimValue = (row, label) => row.cells[row.header.findIndex(cell => new RegExp(`^(?:${label})$`, 'i').test(claimHeader(cell)))] ?? ''
341
+ // Backing mixes explicit clause links with code and caveats. Only the links
342
+ // supply clauses; retain the complete cell separately as historical provenance.
343
+ const claimReferences = row => row.header.some(cell => claimHeader(cell) === 'Clauses')
344
+ ? claimValue(row, 'Clauses') : idsIn(claimValue(row, 'Backing').replace(/\.(?=\s|$)/g, '')).join(', ')
330
345
  const claimRows = text => homepageClaims(text).flatMap(table => table.rows.map(row => ({ ...row, header: table.header })))
331
346
  function originalClaims(old) {
332
347
  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 +352,7 @@ function originalClaims(old) {
337
352
  function nonProductBasis(source, basis, ids, label) {
338
353
  // These are explicit classifications, never a fallback for an unresolved ID.
339
354
  const allowed = {
340
- 'license/public-repository ownership': /^["“]?(?:100% free, open source alternative to [^"”\n]+|100% free and open source\. MIT licensed\.|MIT licen[cs](?:e|ed)\.?)["”]?$/i,
355
+ '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
356
  'launcher identity': /^(?:Terminal:\s*)?`npx -y @runeditrun\/rer dev [^`]+` starts [\w -]+\.?$/,
342
357
  'hosted-demo action': /^["“]Try the demo["”] opens the hosted demo\.?$/i,
343
358
  'boundary': /^Limits:\s*["“]No [^"”\n]+["”]\.?$/i,
@@ -351,7 +366,9 @@ function nonProductBasis(source, basis, ids, label) {
351
366
  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
367
  }
353
368
  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: claimValue(row, 'Clauses?'), text: row.raw }
369
+ return { file, line: row.line, number: claimValue(row, '#') || String(index + 1), claim: claimValue(row, 'Claim'), status: claimValue(row, 'Status'), clauses: claimReferences(row),
370
+ ...(row.header.some(cell => /^Screen$/i.test(plainText(cell))) ? { screen: claimValue(row, 'Screen') } : {}),
371
+ ...(row.header.some(cell => claimHeader(cell) === 'Backing') ? { backing: claimValue(row, 'Backing') } : {}), text: row.raw }
355
372
  }
356
373
  function readClaimSource(text) {
357
374
  const records = [...text.matchAll(/<!-- contract-claim-source\s*\n([\s\S]*?)\n-->/g)]
@@ -370,7 +387,7 @@ function validateClaimSource(text, rows = claimRows(text), old) {
370
387
  }
371
388
  if (old && record.old !== old.commit) throw Error('CONTRACT.md: contract-claim-source old SHA differs from the coverage original.')
372
389
  let original
373
- try { original = old ?? snapshot(record.old) } catch (error) { throw Error(`CONTRACT.md: contract-claim-source old ${record.old}: ${error.message}`) }
390
+ try { original = old ?? anchoredSnapshot(record.old) } catch (error) { throw Error(`CONTRACT.md: contract-claim-source old ${record.old}: ${error.message}`) }
374
391
  const selected = originalClaims(original), ids = new Set(parseContract(original.files['CONTRACT.md']).clauses.map(clause => clause.id))
375
392
  validateOriginalClaims(original, rows)
376
393
  if (record.claims.length !== selected.rows.length) throw Error('CONTRACT.md: contract-claim-source must retain every original claim once.')
@@ -379,6 +396,9 @@ function validateClaimSource(text, rows = claimRows(text), old) {
379
396
  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
397
  const row = rows[index]
381
398
  if (claimValue(row, '#') !== source.number || claimValue(row, 'Claim') !== source.claim) throw Error(`${label}: current claim number/text must match the original.`)
399
+ if (source.screen !== undefined && claimValue(row, 'Section|Screen') !== source.screen ||
400
+ source.backing !== undefined && claimValue(row, 'Backing') !== source.backing)
401
+ throw Error(`${label}: current screen/backing provenance must match the original.`)
382
402
  const basis = claimValue(row, 'Basis')
383
403
  if (source.nonProduct !== undefined) {
384
404
  nonProductBasis(source, source.nonProduct, ids, label)
@@ -435,17 +455,18 @@ function contractClaims(old, ids, claimMapPath) {
435
455
  }
436
456
  }
437
457
  if (!rows.length) return 'No homepage claims are mapped yet.'
438
- const hasSection = rows.some(row => row.header.some(label => /^section$/i.test(plainText(label))))
458
+ const hasSection = rows.some(row => row.header.some(label => /^(Section|Screen)$/i.test(plainText(label))))
459
+ const hasBacking = rows.some(row => row.header.some(label => claimHeader(label) === 'Backing'))
439
460
  const hasNonProduct = [...mapped.values()].some(entry => entry.nonProduct)
440
- const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasNonProduct ? ['Basis'] : [])]
461
+ const header = ['#', ...(hasSection ? ['Section'] : []), 'Claim', 'Clauses', ...(hasBacking ? ['Backing'] : []), ...(hasNonProduct ? ['Basis'] : [])]
441
462
  const table = [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`], problems = []
442
463
  for (const [index, row] of rows.entries()) {
443
464
  const mapping = mapped.get(row.line), nonProduct = mapping?.nonProduct
444
- const references = nonProduct ? '' : mapping?.clauses.join(', ') ?? value(row, 'Clauses?')
465
+ const references = nonProduct ? '' : mapping?.clauses.join(', ') ?? claimReferences(row)
445
466
  const linked = idsIn(references)
446
467
  if (!nonProduct && (!linked.length || linked.some(id => !ids.has(id))))
447
468
  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(' | ')} |`)
469
+ 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
470
  }
450
471
  if (problems.length) throw Error(problems.join('\n'))
451
472
  if (hasNonProduct) table.unshift('Explicit non-product facts have current derived status unassessed. The source record retains historical statuses as history, not current proof.', '')
@@ -914,12 +935,12 @@ function checkProse() {
914
935
  const text = read('CONTRACT.md');
915
936
  if (text === undefined) throw Error('CONTRACT.md does not exist.');
916
937
  const coverage = read(covMapPath) === undefined ? undefined : covReadMap();
917
- const sources = coverage ? covScope(snapshot(coverage.old?.commit)) : [];
938
+ const sources = coverage ? covScope(anchoredSnapshot(coverage.old?.commit)) : [];
918
939
  const findings = contractProseFindings({ text, clauses: parseContract(withoutSummary(text)).clauses, coverage, sources, generatedStatement: covGeneratedStatement });
919
940
  if (printProseFindings(findings)) process.exitCode = 1;
920
941
  }
921
942
 
922
- const usage = 'Usage: contract-docs.mjs write|check|check-prose|id-map --old <ref>|coverage init|check --old <ref>|coverage rebase --from <ref> --onto <ref>|convert --old <ref> [--old-acceptance <ref>] [--claim-map <file>]';
943
+ const usage = 'Usage: contract-docs.mjs write|check|check-prose|anchor --old <ref>|id-map --old <ref>|coverage init|check --old <ref>|coverage rebase --from <ref> --onto <ref>|convert --old <ref> [--old-acceptance <ref>] [--claim-map <file>]';
923
944
  function main(args) {
924
945
  const [command, ...rest] = args
925
946
  const option = (name, description = 'Git reference') => {
@@ -932,6 +953,15 @@ function main(args) {
932
953
  else if (command === 'check' && !rest.length) { checkProse(); generate(true) }
933
954
  else if (command === 'check-prose' && !rest.length) checkProse()
934
955
  else if (command === '--help' && !rest.length) console.log(usage)
956
+ else if (command === 'anchor') {
957
+ const old = snapshot(option('--old'))
958
+ const expected = read(covMapPath) === undefined ? undefined : covReadMap().old?.commit
959
+ if (expected !== undefined && old.commit !== expected) throw Error(`${anchorPath}: contract_anchor_invalid: --old must match COVERAGE.json old.commit ${expected}.`)
960
+ const provenance = readClaimSource(read('CONTRACT.md') ?? '')
961
+ if (provenance && old.commit !== provenance.old) throw Error(`${anchorPath}: contract_anchor_invalid: --old must match contract-claim-source old ${provenance.old}.`)
962
+ put(anchorPath, json(createAnchor(old.commit)))
963
+ console.log(`Recorded ${anchorPath} for ${old.commit}.`)
964
+ }
935
965
  else if (command === 'id-map') idMap(snapshot(option('--old')))
936
966
  else if (command === 'coverage' && rest[0] === 'init') coverageInit(snapshot(option('--old')))
937
967
  else if (command === 'coverage' && rest[0] === 'check') coverageCheck(snapshot(option('--old')))
@@ -1,5 +1,68 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.94
4
+
5
+ - Include the shared checkout-history validator in the documented portability runtime copy, preserving self-contained Worker and CLI adoption.
6
+
7
+ - Business connect, next and run report the local Business name file written without claiming an app has already applied it.
8
+ - Explain the signed-in session file in Business setup help, give connect and token their own usage, and show the Business help path after install.sh.
9
+ - On occupied ports, suggest moving the checkout with `rer setup --port` and reserve server stop advice for this checkout's own registered server; omit kill commands for unmanaged processes.
10
+
11
+ - Let archive-owning Workers verify legacy migration ledgers through optional seed-owned build evidence, using the library door's existing validation and restore guards.
12
+
13
+ - Diagnose misbound application ports from declared bindings and socket ownership without sending HTTP health requests to auxiliary runtime listeners during startup.
14
+
15
+ - Share the guarded disposable host writer with isolated, named insert-only history fixtures. Native phase preparation can age native history, run scheduled work and hold queue deliveries; atomic guards protect every agent-door table while owner initialization stays read-only.
16
+
17
+ - Add an optional native company-policy decision hook to the shared agent door. Allow retains class policy; hold uses its signed-in, revision-bound approval flow; deny refuses before effects. Native decisions are audited, rechecked on retries and approval execution, and cannot bypass policy, Pause or native authority.
18
+
19
+ - Retain native continuation identity and current policy evidence in private audit when an identity-matched originating operation is still running; keep the operation_mismatch response and execution refusal unchanged.
20
+
21
+ - Admit explicitly declared agent-verification public hosts from the selected deployment's hostname variables, preserving their URL and Host through disposable ingress while refusing undeclared hosts. One-host verification keeps its existing origin.
22
+
23
+ - Contract document generation can verify a committed historical anchor record in snapshots and shallow checkouts. Missing history without a record and tampered records still refuse; full-history checkouts need no record.
24
+
25
+ - Integrated inputs: hist-1 (repaired by hist-3), injkey-1, migdir-2, sponsor-1, hostedpub-1, lamp-anchoredhist-1, lamp-dualhost-2, contaudit-2, hh-companypolicy-1, mango-fixtures-2, onboarding-probe-1, spool-workerlegacy-2, and ux57-cli-1.
26
+
27
+ - Supply required declared public inputs only inside hosted-output verification, using setup defaults and disposable stand-ins when unset. Preserve configured public values and leave optional integrations unconfigured; deployment declarations and built artifacts are unchanged.
28
+
29
+ - Give each additional Business sponsor verifier initializer its own captured-mail reader, with the owner's existing provider, size, count and age limits. Native invitation confirmation can complete without exposing another principal's mail.
30
+
31
+ - Package deploy migrations from the seed's declared `DB.migrations_dir`, sharing the native archive lookup; undeclared seeds retain `migrations/core` and their existing package bytes.
32
+
33
+ - Reuse the original admission key when resolving agent-door injection arguments, so once-only native preparation is replayed without a second effect.
34
+
35
+ - Follow literal import.meta.url resources, including Worker and SharedWorker URLs, when refusing production references to declared history fixtures; keep authoring module-import closure unchanged.
36
+
37
+ - Let seeds declare an isolated, test-only history fixture before named agent-door journey steps. Only allowlisted INSERT statements reach fresh disposable databases; protected tables and target triggers are refused, production imports fail closed, and the normal state reader and clock remain unchanged.
38
+
39
+ ## 0.2.93
40
+
41
+ - 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).
42
+
43
+ - 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.
44
+
45
+ - 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.
46
+
47
+ - 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.
48
+
49
+ - 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.
50
+
51
+ - 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.
52
+
53
+ - 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.
54
+ - 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.
55
+
56
+ ## 0.2.92
57
+
58
+ - Renew the verifier's adopted policy before requests without changing its authority or lifetime; equal-sequence adoption may change only issue and expiry times.
59
+
60
+ - 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.
61
+
62
+ - 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.
63
+
64
+ - 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.
65
+
3
66
  ## 0.2.91
4
67
 
5
68
  - 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.
package/install.sh CHANGED
@@ -156,7 +156,10 @@ NODE
156
156
  if [ "$#" -gt 0 ]; then no_next=1; fi
157
157
  RER_INSTALL_CHANNEL=script RER_INSTALL_NO_NEXT=$no_next "$node_binary" "$work/stage/package/global/rer.mjs" cli install </dev/null \
158
158
  || fail "rer cli install failed; any previous install is still selected."
159
- if [ "$#" -eq 0 ]; then return; fi
159
+ if [ "$#" -eq 0 ]; then
160
+ printf 'For Business setup: %s business setup --help\n' "$HOME/.local/bin/rer"
161
+ return
162
+ fi
160
163
  # The command can tell the person how to run rer again from their own shell,
161
164
  # where ~/.local/bin may not be on PATH yet.
162
165
  RER_INVOKED_AS="$HOME/.local/bin/rer"
@@ -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 revision_signature = document === null ? null : await signJws(context.signer.privateKey, context.signer.kid, 'rer-agent-policy-revision+jwt', {
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
+ }
@@ -2,7 +2,7 @@ import { errorCode } from './protocol.mjs';
2
2
 
3
3
  // Refresh read dependencies only. Repeating a write here would create another
4
4
  // effect, and resolving its old output cannot provide a current native revision.
5
- export async function injectionArgs(c, step, outputs) {
5
+ export async function injectionArgs(c, step, outputs, admittedArgs) {
6
6
  const fresh = new Map(outputs), refreshed = new Set();
7
7
  async function visit(value) {
8
8
  if (!value || typeof value !== 'object') return;
@@ -18,7 +18,9 @@ export async function injectionArgs(c, step, outputs) {
18
18
  } else for (const item of Object.values(value)) await visit(item);
19
19
  }
20
20
  await visit(step.args);
21
- const args = c.args(step, fresh);
22
21
  const write = !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly;
23
- return { ...args, ...c.resolve(step.inject, fresh), ...(write ? { idempotency_key: args.idempotency_key } : {}) };
22
+ // A mutation keeps its admitted arguments, including revision and key. Fresh
23
+ // read dependencies must not turn its injection probe into a different call.
24
+ const args = write ? admittedArgs : c.resolve(step.args, fresh);
25
+ return { ...args, ...c.resolve(step.inject, fresh), ...(write ? { idempotency_key: admittedArgs.idempotency_key } : {}) };
24
26
  }
@@ -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
- async function checkResources(c, step, answer, phase, held) {
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.`);
@@ -100,7 +124,7 @@ export async function runJourney(c, phase, { held = false, injections = false, r
100
124
  (c.effectEvents ??= []).push(...snapshot.result.structuredContent.events);
101
125
  }
102
126
  if (injections && step.inject) {
103
- const injected = await injectionArgs(c, step, outputs);
127
+ const injected = await injectionArgs(c, step, outputs, args);
104
128
  const checked = await c.stepTool(step, injected, proof);
105
129
  c.add(`BASE-AGENT-005.5.${phase}.${step.id}`, isDeepStrictEqual(checked.decision?.classes, answer.decision?.classes) && checked.decision?.disposition === answer.decision?.disposition && !checked.result?.isError, `${step.tool} changed class, facts or decision for additional arguments.`);
106
130
  }
@@ -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
- c.add('BASE-AGENT-007.8.state', isDeepStrictEqual(state, await c.personJson('/agents/api/state')), 'An invalid envelope changed the adopted policy state or revision.');
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 { autonomousPolicy } from './crypto.mjs';
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
- context.adopt = async (document, options = {}) => {
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 validClasses = Array.isArray(actualClasses) && new Set(actualClasses.map(row => row?.class)).size === actualClasses.length && actualClasses.every(row =>
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
- isDeepStrictEqual([...row.tools].sort(), context.surface.tools.filter(tool => tool.classes.includes(row.class)).map(tool => tool.name).sort().slice(0, 20))) &&
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
- 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, 'Policy answer must contain exactly adopted {seq,revision} and catalogue classes with the exact declared tool mappings; resource-only classes have no tools.');
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 };
@@ -85,7 +85,7 @@ The seed declares bindings, never names:
85
85
  "vars": { "MAIL_PROVIDER": "sendgrid" }, "originVar": "APP_ORIGIN" }
86
86
  ```
87
87
 
88
- Names are deterministic. The Worker is `<last segment of project>-<environment>`, for example `penny-production`. Each D1 database, R2 bucket, KV namespace and Queue is `<worker>-<binding in lower case, _ as ->`, for example `penny-production-db` and `penny-production-jobs-dead`. Durable Object namespaces belong to the Worker and are created by its upload migration. `originVar` receives `https://<worker>.<account subdomain>.workers.dev`. Migrations come from the packaged build's `migrations/core/*.sql` files. A name over 63 characters is refused, not shortened.
88
+ Names are deterministic. The Worker is `<last segment of project>-<environment>`, for example `penny-production`. Each D1 database, R2 bucket, KV namespace and Queue is `<worker>-<binding in lower case, _ as ->`, for example `penny-production-db` and `penny-production-jobs-dead`. Durable Object namespaces belong to the Worker and are created by its upload migration. `originVar` receives `https://<worker>.<account subdomain>.workers.dev`. Migrations come from the product's `wrangler.jsonc` declaration for `DB.migrations_dir`, using the same lookup as native archive/migration checks. The directory must stay within the product. Without a declaration, packaging retains `migrations/core/*.sql`. A name over 63 characters is refused, not shortened.
89
89
 
90
90
  A declaration may also bind another owner-deployed Worker and may keep its own workers.dev route off. Both keys are optional, and a declaration without them renders and fingerprints exactly as before:
91
91