@runeditrun/rer 0.2.93 → 0.2.94
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/agent-door.mjs +20 -10
- package/cli/agent-history-database.mjs +82 -0
- package/cli/agent-history-isolation.mjs +68 -0
- package/cli/agent-history.mjs +58 -0
- package/cli/agent-journey-fixtures.mjs +3 -3
- package/cli/agent-network.mjs +12 -6
- package/cli/business/choices.mjs +3 -3
- package/cli/business/command.mjs +19 -0
- package/cli/business/setup-command.mjs +14 -1
- package/cli/export.mjs +1 -1
- package/cli/hosted-hosts.mjs +21 -0
- package/cli/hosted-output.mjs +91 -8
- package/cli/lifecycle.mjs +5 -0
- package/cli/local.mjs +1 -1
- package/cli/port.mjs +1 -2
- package/cli/portability-evidence.d.mts +5 -0
- package/cli/portability-evidence.mjs +85 -0
- package/cli/portability-migrations.mjs +12 -4
- package/edition-authoring/module-edges.mjs +14 -1
- package/foundation/runtime/contract-anchor.mjs +87 -0
- package/foundation/runtime/contract-docs.mjs +20 -4
- package/global/CHANGELOG.md +36 -0
- package/install.sh +4 -1
- package/modules/agent-door/conformance/injection.mjs +5 -3
- package/modules/agent-door/conformance/journey.mjs +1 -1
- package/modules/deploy-kit/README.md +1 -1
- package/modules/deploy-kit/prepare.mjs +5 -2
- package/modules/portability/README.md +42 -10
- package/modules/portability/catalogue.mjs +11 -1
- package/modules/portability/checkout-history.mjs +14 -0
- package/modules/portability/index.d.mts +1 -1
- package/modules/portability/library-history.mjs +2 -7
- package/modules/portability/restore-safety.mjs +6 -3
- package/modules/portability/worker-history.d.mts +9 -0
- package/modules/portability/worker-history.mjs +29 -0
- package/onboarding/adapter.mjs +25 -13
- package/package.json +9 -1
package/cli/local.mjs
CHANGED
|
@@ -128,5 +128,5 @@ export async function refuseLegacyProcess(project,{reset=false,verb='dev',operat
|
|
|
128
128
|
}
|
|
129
129
|
return {lockProof:true};
|
|
130
130
|
}
|
|
131
|
-
if(conflict)throw refuse(`A local process holds ${conflict.reason}: PID ${conflict.pid} (${conflict.command}).
|
|
131
|
+
if(conflict)throw refuse(`A local process holds ${conflict.reason}: PID ${conflict.pid} (${conflict.command}). Close the program holding it, then retry.`);
|
|
132
132
|
}
|
package/cli/port.mjs
CHANGED
|
@@ -53,6 +53,5 @@ export async function busyPortMessage({ port, host, root, saved, env = process.e
|
|
|
53
53
|
const who = holder.server
|
|
54
54
|
? `the ${holder.server.mode} server for ${holder.checkout} (PID ${holder.pid})`
|
|
55
55
|
: `PID ${holder.pid} (${holder.command})${holder.cwd ? ` running in ${holder.cwd}` : ''}`;
|
|
56
|
-
|
|
57
|
-
return `${kind} in use by ${who}.${move}${stop}`;
|
|
56
|
+
return `${kind} in use by ${who}.${move}`;
|
|
58
57
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
import type { MigrationEvidence } from '../modules/portability/worker-history.mjs';
|
|
3
|
+
export function generateMigrationEvidence(root:string,options?:{binding?:string}):Promise<MigrationEvidence>;
|
|
4
|
+
/** Seed opt-in: generates the server-only virtual:rer-legacy-migration-evidence module. */
|
|
5
|
+
export function legacyMigrationEvidence(options?:{binding?:string}):Plugin;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { realpath, readFile, readdir } from 'node:fs/promises';
|
|
3
|
+
import { resolve, relative, isAbsolute, sep } from 'node:path';
|
|
4
|
+
import { migrationDirectory } from './portability-migrations.mjs';
|
|
5
|
+
import { splitStatements } from '../modules/portability/sql-text.mjs';
|
|
6
|
+
import { canonicalJson, sha256 } from '../modules/portability/hash.mjs';
|
|
7
|
+
import { quote, insist } from '../modules/portability/storage.mjs';
|
|
8
|
+
import { dataStatement, triggerBodies } from '../modules/portability/migration-statements.mjs';
|
|
9
|
+
import { sqliteTokens } from '../modules/portability/sqlite-tokens.mjs';
|
|
10
|
+
|
|
11
|
+
// Date functions can default to 'now'; even fixed arguments are conservatively
|
|
12
|
+
// excluded from seeded-row evidence. Their schema and statements remain intact.
|
|
13
|
+
const variable=sql=>/\b(?:random|randomblob|date|time|datetime|julianday|strftime|unixepoch|sqlite_version|sqlite_source_id)\s*\(|\bcurrent_(?:date|time|timestamp)\b/i.test(sqliteTokens(sql).map(t=>t.value).join(' '));
|
|
14
|
+
|
|
15
|
+
// Only migration-owned schema and hashed seeded-row identities enter the bundle.
|
|
16
|
+
// Never open a live database, settings file, archive, or archive-supplied path.
|
|
17
|
+
export async function generateMigrationEvidence(root,{binding='DB'}={}) {
|
|
18
|
+
root=await realpath(root);
|
|
19
|
+
const directory=await realpath(await migrationDirectory(root,binding));
|
|
20
|
+
const path=relative(root,directory);
|
|
21
|
+
insist(!isAbsolute(path) && path!=='..' && !path.startsWith('..'+sep),'schema_mismatch:legacy_evidence',409);
|
|
22
|
+
const files=await Promise.all((await readdir(directory)).filter(name=>name.endsWith('.sql')).sort().map(async name=>{
|
|
23
|
+
const file=await realpath(resolve(directory,name)),path=relative(directory,file);
|
|
24
|
+
insist(!isAbsolute(path) && path!=='..' && !path.startsWith('..'+sep),'schema_mismatch:legacy_evidence',409);
|
|
25
|
+
const bytes=await readFile(file);
|
|
26
|
+
return {name,sha256:await sha256(bytes),statements:splitStatements(bytes.toString('utf8'))};
|
|
27
|
+
}));
|
|
28
|
+
const objects=[],indices=new Map(),prefixes=[];
|
|
29
|
+
const scratch=new DatabaseSync(':memory:');
|
|
30
|
+
try {
|
|
31
|
+
// Volatile defaults, trigger bodies and reads propagate to their writers.
|
|
32
|
+
// Such rows cannot equal a fresh library replay reliably either. Preserve
|
|
33
|
+
// deterministic seeds in unrelated tables, and empty evidence everywhere.
|
|
34
|
+
const unstable=new Set(),applied=[];
|
|
35
|
+
const capture=async()=>{
|
|
36
|
+
const schema=scratch.prepare("SELECT name,sql,type,tbl_name FROM sqlite_master WHERE sql IS NOT NULL AND substr(lower(name),1,7)<>'sqlite_' AND substr(lower(name),1,4)<>'_cf_' ORDER BY name,type").all();
|
|
37
|
+
const refs=schema.map(object=>{
|
|
38
|
+
const key=canonicalJson(object);if(!indices.has(key)){indices.set(key,objects.length);objects.push(object);}return indices.get(key);
|
|
39
|
+
});
|
|
40
|
+
const shadows=scratch.prepare('PRAGMA table_list').all().filter(t=>t.type==='shadow').map(t=>t.name).sort();
|
|
41
|
+
const seeds=[];
|
|
42
|
+
for(const {name} of schema.filter(o=>o.type==='table')) {
|
|
43
|
+
const columns=scratch.prepare(`PRAGMA table_info(${quote(name)})`).all().map(c=>c.name);
|
|
44
|
+
const rows=scratch.prepare(`SELECT json_array(${columns.map(c=>`quote(${quote(c)})`).join(',')}) image FROM ${quote(name)} LIMIT 10001`).all().map(r=>r.image);
|
|
45
|
+
if(rows.length>10000 || unstable.has(name.toLowerCase()) && rows.length)continue;
|
|
46
|
+
seeds.push({name,columns,hashes:(await Promise.all(rows.map(sha256))).sort()});
|
|
47
|
+
}
|
|
48
|
+
prefixes.push({objects:refs,shadows,seeds});
|
|
49
|
+
};
|
|
50
|
+
await capture();
|
|
51
|
+
for(const file of files) {
|
|
52
|
+
for(const sql of file.statements) {
|
|
53
|
+
const data=dataStatement(sql);
|
|
54
|
+
if(data) {
|
|
55
|
+
const writers=new Set([data.target]);
|
|
56
|
+
for(const name of writers)for(const target of triggerBodies(applied,name))writers.add(target);
|
|
57
|
+
const definitions=scratch.prepare("SELECT name,sql FROM sqlite_master WHERE sql IS NOT NULL").all();
|
|
58
|
+
if(variable(sql) || data.names.some(n=>unstable.has(n)) || definitions.some(d=>writers.has(d.name.toLowerCase()) && variable(d.sql))
|
|
59
|
+
|| applied.some(s=>variable(s) && [...writers].some(n=>triggerBodies([s],data.target).includes(n))))for(const name of writers)unstable.add(name);
|
|
60
|
+
}
|
|
61
|
+
scratch.exec(sql);
|
|
62
|
+
applied.push(sql);
|
|
63
|
+
}
|
|
64
|
+
await capture();
|
|
65
|
+
}
|
|
66
|
+
}finally{scratch.close();}
|
|
67
|
+
return {version:1,files,objects,prefixes};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Explicit seed opt-in. The module is consumed only by the server/Worker graph;
|
|
71
|
+
// it is bundled and hashed by the existing Vite and deploy package paths.
|
|
72
|
+
export function legacyMigrationEvidence({binding='DB'}={}) {
|
|
73
|
+
const id='virtual:rer-legacy-migration-evidence',internal='\0'+id;
|
|
74
|
+
let root;
|
|
75
|
+
return {
|
|
76
|
+
name:'rer:legacy-migration-evidence',
|
|
77
|
+
configResolved(config){root=config.root;},
|
|
78
|
+
resolveId(source){if(source===id)return internal;},
|
|
79
|
+
async load(source){
|
|
80
|
+
if(source!==internal)return;
|
|
81
|
+
if(this.environment?.name==='client')throw new Error('Legacy migration evidence is server-only.');
|
|
82
|
+
return 'export default '+canonicalJson(await generateMigrationEvidence(root,{binding}))+';';
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -16,13 +16,21 @@ export function platformMigrationDeclaration(input={}) {
|
|
|
16
16
|
return {prefix,dataOnly};
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
// Native archive/migration checks and deploy packaging use the same seed-owned
|
|
20
|
+
// directory declaration. Only packaging supplies its historical fallback.
|
|
21
|
+
export async function migrationDirectory(root,binding,{fallback}={}) {
|
|
22
|
+
let config;
|
|
23
|
+
try { config=parseJsonc(await readFile(join(root,'wrangler.jsonc'),'utf8')); }
|
|
24
|
+
catch(error) { if(error.code!=='ENOENT' || fallback===undefined)throw error; return join(root,fallback); }
|
|
25
|
+
const bindings=config.d1_databases?.filter(entry=>entry.binding===binding) ?? [];
|
|
26
|
+
insist(bindings.length===1 || bindings.length===0 && fallback!==undefined,'migration_ledger:binding',409);
|
|
27
|
+
return join(root,bindings[0]?.migrations_dir ?? fallback ?? 'migrations');
|
|
28
|
+
}
|
|
29
|
+
|
|
19
30
|
// Reproduce the runner's stored SQL text, then recover SQLite's statement
|
|
20
31
|
// boundaries (migration-sql.mjs).
|
|
21
32
|
export async function migrationInventory(root,binding,{prefix},split) {
|
|
22
|
-
const
|
|
23
|
-
const bindings=config.d1_databases?.filter(entry=>entry.binding===binding) ?? [];
|
|
24
|
-
insist(bindings.length===1,'migration_ledger:binding',409);
|
|
25
|
-
const directory=join(root,bindings[0].migrations_dir ?? 'migrations');
|
|
33
|
+
const directory=await migrationDirectory(root,binding);
|
|
26
34
|
return Promise.all((await readdir(directory)).filter(name=>name.endsWith('.sql')).sort().map(async name=>{
|
|
27
35
|
const bytes=await readFile(join(directory,name));
|
|
28
36
|
return {name,...(split?{statements:migrationStatements(bytes.toString('utf8'),split)}:{}),sha256:createHash('sha256').update(bytes).digest('hex'),...(prefix===undefined?{}:{aliases:[prefix+name]})};
|
|
@@ -22,9 +22,16 @@ function* nodes(root) {
|
|
|
22
22
|
|
|
23
23
|
const parsed = new Map();
|
|
24
24
|
|
|
25
|
+
// Authoring follows module imports. History isolation also follows URL resources
|
|
26
|
+
// that bundlers can publish without importing them into the authoring tool.
|
|
27
|
+
export function dependencies(source, filename = 'module.mjs', {resources = false} = {}) {
|
|
28
|
+
const result = edges(source, filename);
|
|
29
|
+
return resources ? result : result.filter(request => request.kind !== 'resource');
|
|
30
|
+
}
|
|
31
|
+
|
|
25
32
|
// Parsing, including erased TS edges and calls nested in templates/JSX, precedes
|
|
26
33
|
// resolution. Every resulting edge uses the same virtual Node resolver.
|
|
27
|
-
|
|
34
|
+
function edges(source, filename) {
|
|
28
35
|
let versions = parsed.get(filename);
|
|
29
36
|
if (versions?.has(source)) return versions.get(source);
|
|
30
37
|
const plugins = ['decorators-legacy', 'deprecatedImportAssert'];
|
|
@@ -82,6 +89,12 @@ export function dependencies(source, filename = 'module.mjs') {
|
|
|
82
89
|
else if (node.type === 'ImportExpression') add(node.source, 'import');
|
|
83
90
|
else if (call(node)) {
|
|
84
91
|
let callee = unwrap(node.callee), argument = node.arguments[0];
|
|
92
|
+
// Vite emits literal import.meta.url resources, including the URL nested
|
|
93
|
+
// in Worker/SharedWorker constructors, without an import declaration.
|
|
94
|
+
const base = unwrap(node.arguments[1]), meta = unwrap(base?.object);
|
|
95
|
+
if (node.type === 'NewExpression' && callee?.type === 'Identifier' && callee.name === 'URL'
|
|
96
|
+
&& member(base) && property(base) === 'url' && meta?.type === 'MetaProperty'
|
|
97
|
+
&& meta.meta.name === 'import' && meta.property.name === 'meta') add(argument, 'resource');
|
|
85
98
|
if (member(callee) && property(callee) === 'bind' && requireFunction(callee.object)) { add(node.arguments[1], 'require'); continue; }
|
|
86
99
|
if (member(callee) && callee.object?.type === 'Identifier' && callee.object.name === 'Reflect' && ['apply', 'construct'].includes(property(callee)) && requireFunction(node.arguments[0])) {
|
|
87
100
|
add(node.arguments[property(callee) === 'apply' ? 2 : 1]?.elements?.[0], 'require'); continue;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import { execFileSync } from 'node:child_process'
|
|
4
|
+
|
|
5
|
+
export const anchorPath = 'docs/contract/ANCHOR.json'
|
|
6
|
+
const sourceFiles = ['CONTRACT.md', 'ACCEPTANCE.md', 'docs/CLAIMS.md', 'CLAIMS.md']
|
|
7
|
+
const sha = /^[0-9a-f]{40}$/
|
|
8
|
+
const fail = message => { throw Error(`${anchorPath}: contract_anchor_invalid: ${message}`) }
|
|
9
|
+
const objectId = (type, bytes) => createHash('sha1').update(`${type} ${bytes.length}\0`).update(bytes).digest('hex')
|
|
10
|
+
|
|
11
|
+
// The commit authenticates the root tree, which authenticates each source blob
|
|
12
|
+
// (and absence of optional sources). No hash supplied only by the record is trusted.
|
|
13
|
+
function resolveSnapshot(commit, load) {
|
|
14
|
+
if (!sha.test(commit)) fail('expected a full anchor commit SHA.')
|
|
15
|
+
const object = (type, id) => {
|
|
16
|
+
const bytes = load(type, id)
|
|
17
|
+
if (objectId(type, bytes) !== id) fail(`${type} ${id} has mismatching bytes.`)
|
|
18
|
+
return bytes
|
|
19
|
+
}
|
|
20
|
+
const treeId = /^tree ([0-9a-f]{40})\n/.exec(object('commit', commit).toString('utf8'))?.[1]
|
|
21
|
+
if (!treeId) fail('anchor commit has no root tree.')
|
|
22
|
+
const trees = new Map()
|
|
23
|
+
function tree(id) {
|
|
24
|
+
if (trees.has(id)) return trees.get(id)
|
|
25
|
+
const bytes = object('tree', id), entries = new Map()
|
|
26
|
+
let offset = 0
|
|
27
|
+
while (offset < bytes.length) {
|
|
28
|
+
const end = bytes.indexOf(0, offset)
|
|
29
|
+
if (end < 0 || end + 21 > bytes.length) fail(`malformed tree ${id}.`)
|
|
30
|
+
const entry = /^(40000|100644|100755|120000|160000) ([^/\0]+)$/.exec(bytes.subarray(offset, end).toString('utf8'))
|
|
31
|
+
if (!entry || entries.has(entry[2])) fail(`malformed or duplicate entry in tree ${id}.`)
|
|
32
|
+
entries.set(entry[2], { mode: entry[1], id: bytes.subarray(end + 1, end + 21).toString('hex') })
|
|
33
|
+
offset = end + 21
|
|
34
|
+
}
|
|
35
|
+
trees.set(id, entries)
|
|
36
|
+
return entries
|
|
37
|
+
}
|
|
38
|
+
const files = {}
|
|
39
|
+
for (const name of sourceFiles) {
|
|
40
|
+
const parts = name.split('/')
|
|
41
|
+
let directory = treeId, entry
|
|
42
|
+
for (const [index, part] of parts.entries()) {
|
|
43
|
+
entry = tree(directory).get(part)
|
|
44
|
+
if (!entry) break
|
|
45
|
+
if (index < parts.length - 1) {
|
|
46
|
+
if (entry.mode !== '40000') { entry = undefined; break }
|
|
47
|
+
directory = entry.id
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (!entry) continue
|
|
51
|
+
if (!['100644', '100755', '120000'].includes(entry.mode)) fail(`${name} is not a blob.`)
|
|
52
|
+
files[name] = object('blob', entry.id).toString('utf8')
|
|
53
|
+
}
|
|
54
|
+
if (!files['CONTRACT.md']) fail('anchor has no CONTRACT.md.')
|
|
55
|
+
return { commit, files }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function readAnchor(commit) {
|
|
59
|
+
if (!fs.existsSync(anchorPath)) return undefined
|
|
60
|
+
let record
|
|
61
|
+
try { record = JSON.parse(fs.readFileSync(anchorPath, 'utf8')) }
|
|
62
|
+
catch { fail('record must be valid JSON.') }
|
|
63
|
+
if (record?.schema !== 1 || record.commit !== commit || !record.objects || typeof record.objects !== 'object' || Array.isArray(record.objects))
|
|
64
|
+
fail(`expected schema 1 and anchor commit ${commit}.`)
|
|
65
|
+
const used = new Set()
|
|
66
|
+
const snapshot = resolveSnapshot(commit, (type, id) => {
|
|
67
|
+
used.add(id)
|
|
68
|
+
const entry = Object.hasOwn(record.objects, id) ? record.objects[id] : undefined
|
|
69
|
+
if (entry?.type !== type || typeof entry.data !== 'string') fail(`missing ${type} ${id}.`)
|
|
70
|
+
const bytes = Buffer.from(entry.data, 'base64')
|
|
71
|
+
if (bytes.toString('base64') !== entry.data) fail(`${type} ${id} is not canonical base64.`)
|
|
72
|
+
return bytes
|
|
73
|
+
})
|
|
74
|
+
if (Object.keys(record.objects).some(id => !used.has(id))) fail('record contains objects outside the anchor proof.')
|
|
75
|
+
return snapshot
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Run once while the anchor is available, then commit this portable proof.
|
|
79
|
+
export function createAnchor(commit) {
|
|
80
|
+
const objects = {}
|
|
81
|
+
resolveSnapshot(commit, (type, id) => {
|
|
82
|
+
const bytes = execFileSync('git', ['cat-file', type, id], { stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 })
|
|
83
|
+
objects[id] = { type, data: bytes.toString('base64') }
|
|
84
|
+
return bytes
|
|
85
|
+
})
|
|
86
|
+
return { schema: 1, commit, objects }
|
|
87
|
+
}
|
|
@@ -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
|
|
@@ -169,7 +176,7 @@ function generate(check = false) {
|
|
|
169
176
|
const coverage = read(covMapPath)
|
|
170
177
|
if (coverage !== undefined) {
|
|
171
178
|
let original
|
|
172
|
-
try { original =
|
|
179
|
+
try { original = anchoredSnapshot(JSON.parse(coverage).old?.commit) }
|
|
173
180
|
catch (error) { throw Error(`${covMapPath}: original SHA is unavailable: ${error.message}`) }
|
|
174
181
|
validateOriginalClaims(original)
|
|
175
182
|
}
|
|
@@ -380,7 +387,7 @@ function validateClaimSource(text, rows = claimRows(text), old) {
|
|
|
380
387
|
}
|
|
381
388
|
if (old && record.old !== old.commit) throw Error('CONTRACT.md: contract-claim-source old SHA differs from the coverage original.')
|
|
382
389
|
let original
|
|
383
|
-
try { original = old ??
|
|
390
|
+
try { original = old ?? anchoredSnapshot(record.old) } catch (error) { throw Error(`CONTRACT.md: contract-claim-source old ${record.old}: ${error.message}`) }
|
|
384
391
|
const selected = originalClaims(original), ids = new Set(parseContract(original.files['CONTRACT.md']).clauses.map(clause => clause.id))
|
|
385
392
|
validateOriginalClaims(original, rows)
|
|
386
393
|
if (record.claims.length !== selected.rows.length) throw Error('CONTRACT.md: contract-claim-source must retain every original claim once.')
|
|
@@ -928,12 +935,12 @@ function checkProse() {
|
|
|
928
935
|
const text = read('CONTRACT.md');
|
|
929
936
|
if (text === undefined) throw Error('CONTRACT.md does not exist.');
|
|
930
937
|
const coverage = read(covMapPath) === undefined ? undefined : covReadMap();
|
|
931
|
-
const sources = coverage ? covScope(
|
|
938
|
+
const sources = coverage ? covScope(anchoredSnapshot(coverage.old?.commit)) : [];
|
|
932
939
|
const findings = contractProseFindings({ text, clauses: parseContract(withoutSummary(text)).clauses, coverage, sources, generatedStatement: covGeneratedStatement });
|
|
933
940
|
if (printProseFindings(findings)) process.exitCode = 1;
|
|
934
941
|
}
|
|
935
942
|
|
|
936
|
-
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>]';
|
|
937
944
|
function main(args) {
|
|
938
945
|
const [command, ...rest] = args
|
|
939
946
|
const option = (name, description = 'Git reference') => {
|
|
@@ -946,6 +953,15 @@ function main(args) {
|
|
|
946
953
|
else if (command === 'check' && !rest.length) { checkProse(); generate(true) }
|
|
947
954
|
else if (command === 'check-prose' && !rest.length) checkProse()
|
|
948
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
|
+
}
|
|
949
965
|
else if (command === 'id-map') idMap(snapshot(option('--old')))
|
|
950
966
|
else if (command === 'coverage' && rest[0] === 'init') coverageInit(snapshot(option('--old')))
|
|
951
967
|
else if (command === 'coverage' && rest[0] === 'check') coverageCheck(snapshot(option('--old')))
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,41 @@
|
|
|
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
|
+
|
|
3
39
|
## 0.2.93
|
|
4
40
|
|
|
5
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).
|
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
|
|
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"
|
|
@@ -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
|
-
|
|
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
|
}
|
|
@@ -124,7 +124,7 @@ export async function runJourney(c, phase, { held = false, injections = false, r
|
|
|
124
124
|
(c.effectEvents ??= []).push(...snapshot.result.structuredContent.events);
|
|
125
125
|
}
|
|
126
126
|
if (injections && step.inject) {
|
|
127
|
-
const injected = await injectionArgs(c, step, outputs);
|
|
127
|
+
const injected = await injectionArgs(c, step, outputs, args);
|
|
128
128
|
const checked = await c.stepTool(step, injected, proof);
|
|
129
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.`);
|
|
130
130
|
}
|
|
@@ -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
|
|
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
|
|
|
@@ -7,6 +7,7 @@ import { assetsIgnore, collectFiles, regularBytes, validateArtifact, MAX_ARTIFAC
|
|
|
7
7
|
import { collectBuildModules } from './build-modules.mjs';
|
|
8
8
|
import { refuseLocalEnvFiles, refuseLocalModels } from './local-only.mjs';
|
|
9
9
|
import { readMigrationRewrites, withRewrites } from './migrations.mjs';
|
|
10
|
+
import { migrationDirectory } from '../../cli/portability-migrations.mjs';
|
|
10
11
|
|
|
11
12
|
export function assertCredentialFree(env) {
|
|
12
13
|
for (const [key,value] of Object.entries(env)) if (value && /(?:TOKEN|SECRET|PASSWORD|API_KEY|PRIVATE_KEY|AUTHORIZATION|COOKIE|CREDENTIAL)/i.test(key)) throw new Error('prepare-credential-environment-forbidden');
|
|
@@ -28,10 +29,12 @@ export async function packageBuild({root,source,runIdentity,productDirectory = '
|
|
|
28
29
|
const modules = await collectBuildModules(build,config,main);
|
|
29
30
|
const ignored = assetsIgnore(await regularBytes(join(product,'dist/client/.assetsignore'),65536).then(String,error => { if (error.code === 'ENOENT') return ''; throw error; }));
|
|
30
31
|
const assets = (await collectFiles(join(product,'dist/client'))).filter(file => !ignored(file.path));
|
|
32
|
+
const directory = await migrationDirectory(product,'DB',{fallback:'migrations/core'});
|
|
33
|
+
localPath(relative(product,directory));
|
|
31
34
|
let migrations = [];
|
|
32
|
-
for (const name of (await readdir(
|
|
35
|
+
for (const name of (await readdir(directory)).sort()) {
|
|
33
36
|
assert(/^[0-9]+_[a-zA-Z0-9_-]+\.sql$/.test(name),'unexpected-migration-file');
|
|
34
|
-
const sql = (await regularBytes(join(
|
|
37
|
+
const sql = (await regularBytes(join(directory,name),512000)).toString('utf8'); migrations.push({binding:'DB',name,sql,sha256:hash(sql)});
|
|
35
38
|
}
|
|
36
39
|
migrations = withRewrites(migrations, await readMigrationRewrites(product));
|
|
37
40
|
const artifact = {version:1,source,run:runIdentity,main,modules,assets,migrations}; validateArtifact(artifact);
|
|
@@ -576,16 +576,47 @@ created. Keep the same service instance through this initial upload; restarting
|
|
|
576
576
|
it requires uploading again. Acknowledged recovery and runner-supplied evidence
|
|
577
577
|
retain their existing paths.
|
|
578
578
|
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
579
|
+
Workers can opt into seed-owned build evidence. Add `legacyMigrationEvidence()`
|
|
580
|
+
from `@runeditrun/rer/portability-evidence` to the seed's existing Vite plugins.
|
|
581
|
+
It reads the declared D1 binding's `migrations_dir` through the same accessor
|
|
582
|
+
used by native migration checks and deployment packaging; pass `{binding:'DB'}`
|
|
583
|
+
to select a different binding. It never reads the live installation or an archive.
|
|
584
|
+
Import its generated module only in the archive's server adapter:
|
|
585
|
+
|
|
586
|
+
```js
|
|
587
|
+
import evidence from 'virtual:rer-legacy-migration-evidence';
|
|
588
|
+
import { workerMigrations } from '@runeditrun/rer/modules/portability/worker-history';
|
|
589
|
+
|
|
590
|
+
const service = await createPortability({
|
|
591
|
+
db, policy,
|
|
592
|
+
migrations: () => workerMigrations(db, policy, evidence),
|
|
593
|
+
});
|
|
594
|
+
```
|
|
595
|
+
|
|
596
|
+
For TypeScript, declare the virtual module in the seed's server declarations:
|
|
597
|
+
|
|
598
|
+
```ts
|
|
599
|
+
declare module 'virtual:rer-legacy-migration-evidence' {
|
|
600
|
+
const evidence: import('@runeditrun/rer/modules/portability/worker-history').MigrationEvidence;
|
|
601
|
+
export default evidence;
|
|
602
|
+
}
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
The generated JavaScript contains ordered checkout file hashes and statements,
|
|
606
|
+
deduplicated complete schema inventories for every prefix, and hashed identities
|
|
607
|
+
of bounded deterministic seeded rows. Volatile seeded rows cannot be vouched for;
|
|
608
|
+
their values are never bundled. Runtime policy projects each inventory through
|
|
609
|
+
the same schema identity code as live SQLite. The Worker adapter binds evidence
|
|
610
|
+
to the live hashed ledger and complete schema, then supplies the existing legacy
|
|
611
|
+
collector, archived-ledger validation, bridge and restore guards. Archive SQL is
|
|
612
|
+
never executed as evidence. Unsupported migration selections and missing evidence
|
|
613
|
+
fail closed with `schema_mismatch:legacy_evidence` (the public HTTP vocabulary
|
|
614
|
+
reports `schema_mismatch`). The ordinary automatic Node library path is unchanged.
|
|
615
|
+
|
|
616
|
+
The plugin runs for direct Vite builds and managed builds, rejects client imports,
|
|
617
|
+
and puts its module in the existing Worker bundle/package path. Seeds that do not
|
|
618
|
+
declare it generate no evidence module and need no migration or configuration
|
|
619
|
+
change. Keep the same service instance throughout the initial legacy upload.
|
|
589
620
|
|
|
590
621
|
Later data statements also qualify when a surviving trigger from that same
|
|
591
622
|
migration repeats the complete statement block, in order, on Base's restore
|
|
@@ -1076,6 +1107,7 @@ modules/portability/generated.mjs
|
|
|
1076
1107
|
modules/portability/restore-safety.mjs
|
|
1077
1108
|
modules/portability/bridge.mjs
|
|
1078
1109
|
modules/portability/library-history.mjs
|
|
1110
|
+
modules/portability/checkout-history.mjs
|
|
1079
1111
|
modules/portability/migration-history.mjs
|
|
1080
1112
|
modules/portability/ledgers.mjs
|
|
1081
1113
|
modules/portability/migration-statements.mjs
|
|
@@ -65,6 +65,10 @@ export function excludedTable(table,input={}) {
|
|
|
65
65
|
async function archived(db,config) {
|
|
66
66
|
const objects=await all(db,"SELECT name,sql,type,tbl_name FROM sqlite_master WHERE sql IS NOT NULL AND substr(lower(name),1,7) <> 'sqlite_' AND substr(lower(name),1,4) <> '_cf_' ORDER BY name");
|
|
67
67
|
const kinds=await all(db,'PRAGMA table_list');
|
|
68
|
+
return archivedInventory({objects,kinds},config);
|
|
69
|
+
}
|
|
70
|
+
function archivedInventory({objects:input,kinds},config) {
|
|
71
|
+
const objects=[...input];
|
|
68
72
|
const derived=config.derivedTables;
|
|
69
73
|
const excluded=objects.filter(x=>x.type==='table' && (excludedTable(x.name,config) || (!config.includeTables.includes(x.name) &&
|
|
70
74
|
derived.some(p=>x.name===p || (kinds.find(k=>k.name===x.name)?.type==='shadow' && x.name.startsWith(p+'_'))))));
|
|
@@ -76,7 +80,13 @@ async function archived(db,config) {
|
|
|
76
80
|
}
|
|
77
81
|
// The archive schema identity alone, for databases that need not satisfy the policy.
|
|
78
82
|
export async function schemaIdentity(db,config,{legacyExcludedObjects=false,tablesOnly=false}={}) {
|
|
79
|
-
|
|
83
|
+
return inventoryIdentity(await archived(db,config),{legacyExcludedObjects,tablesOnly});
|
|
84
|
+
}
|
|
85
|
+
// Build evidence and live SQLite use exactly the same policy projection.
|
|
86
|
+
export function inventorySchemaIdentity(inventory,config,options) {
|
|
87
|
+
return inventoryIdentity(archivedInventory(inventory,config),options);
|
|
88
|
+
}
|
|
89
|
+
function inventoryIdentity({entries,excluded,schemaObjects},{legacyExcludedObjects=false,tablesOnly=false}={}) {
|
|
80
90
|
// Acknowledged v1 recovery places an old backup using its historical
|
|
81
91
|
// projection; acknowledged recovery of a version 2 archive without an object
|
|
82
92
|
// inventory compares tables only. Current archives always retain the
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { catalogue, policy } from './catalogue.mjs';
|
|
2
|
+
import { destinationLedger, matchMigrationLedger } from './ledgers.mjs';
|
|
3
|
+
import { insist } from './storage.mjs';
|
|
4
|
+
|
|
5
|
+
// Both evidence adapters bind the seed's files to the live hashed history and
|
|
6
|
+
// complete schema before the shared legacy collector can accept an upload.
|
|
7
|
+
export async function checkoutHistory(db,input,files,replayFor) {
|
|
8
|
+
const ledger=await destinationLedger(db)??[];
|
|
9
|
+
insist(ledger.length && ledger.every(row=>row.sha256),'schema_mismatch:legacy_evidence',409);
|
|
10
|
+
const applied=matchMigrationLedger(ledger,files);
|
|
11
|
+
const replay=await replayFor(applied);
|
|
12
|
+
insist(await replay.schemaAfter(replay.names)===(await catalogue(db,policy(input))).identity,'schema_mismatch');
|
|
13
|
+
return replay;
|
|
14
|
+
}
|
|
@@ -44,7 +44,7 @@ export interface Status {schemaUnverified?:SchemaUnverifiedReceipt;id:string;kin
|
|
|
44
44
|
/** Later additive migrations an older archive was restored across. */
|
|
45
45
|
export interface Bridge {fromSchema:string;toSchema:string;migrations:string[];tables:string[];columns:Record<string,string[]>;/** Later backfills of tables the archive lacks, replayed at finalize in this order; rows is null until the apply commits. */replayed?:{migration:string;statement:number;table:string;rows:number|null}[]}
|
|
46
46
|
/** A runner's replay of the destination's applied migrations: the archive schema identity after a chosen set, and each migration's statements. */
|
|
47
|
-
export interface MigrationReplay {names:string[];/** Seed-declared data-only Platform entries without migration files. */dataOnly?:string[];/** Names generated by the seed's deployment specification for this file. */aliases?(name:string):string[]|undefined;statements(name:string):string[];/** The migration file's SHA-256 hex, where the runner read the file. */sha256?(name:string):string|undefined;schemaAfter(names:string[],options?:{tablesOnly?:boolean}):Promise<string>}
|
|
47
|
+
export interface MigrationReplay {names:string[];/** Seed-declared data-only Platform entries without migration files. */dataOnly?:string[];/** Names generated by the seed's deployment specification for this file. */aliases?(name:string):string[]|undefined;statements(name:string):string[];/** The migration file's SHA-256 hex, where the runner read the file. */sha256?(name:string):string|undefined;schemaAfter(names:string[],options?:{tablesOnly?:boolean;legacyExcludedObjects?:boolean}):Promise<string>}
|
|
48
48
|
/** Export job creation only; no record data, object keys or file paths. */
|
|
49
49
|
export interface ExportEvent {id:string;/** Opaque caller id; the direct/CLI sentinel is normalized to null. */actor:string|null;scope:'installation'}
|
|
50
50
|
export interface PortabilityOptions {
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { catalogue, policy } from './catalogue.mjs';
|
|
2
1
|
import { sha256 } from './hash.mjs';
|
|
3
|
-
import { destinationLedger, matchMigrationLedger } from './ledgers.mjs';
|
|
4
2
|
import { splitStatements } from './sql-text.mjs';
|
|
5
3
|
import { insist, PortabilityError } from './storage.mjs';
|
|
6
4
|
import { migrationReplay } from './migration-history.mjs';
|
|
5
|
+
import { checkoutHistory } from './checkout-history.mjs';
|
|
7
6
|
|
|
8
7
|
// Node library callers have the same checkout evidence as the runner. Resolve
|
|
9
8
|
// only its single declared D1 migration directory, never an archive-supplied path.
|
|
@@ -25,11 +24,7 @@ async function checkoutMigrations(db,config,root) {
|
|
|
25
24
|
const bytes=await readFile(resolve(directory,name));
|
|
26
25
|
return {name,sha256:await sha256(bytes),statements:splitStatements(bytes.toString('utf8'))};
|
|
27
26
|
}));
|
|
28
|
-
const
|
|
29
|
-
insist(ledger.length && ledger.every(row=>row.sha256),'schema_mismatch:legacy_evidence',409);
|
|
30
|
-
const applied=matchMigrationLedger(ledger,files);
|
|
31
|
-
const replay=migrationReplay(applied.map(name=>files.find(file=>file.name===name)),config);
|
|
32
|
-
insist(await replay.schemaAfter(replay.names)===(await catalogue(db,policy(config))).identity,'schema_mismatch');
|
|
27
|
+
const replay=await checkoutHistory(db,config,files,applied=>migrationReplay(applied.map(name=>files.find(file=>file.name===name)),config));
|
|
33
28
|
return async()=>replay;
|
|
34
29
|
}
|
|
35
30
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { all,statement,guard,quote,insist } from './storage.mjs';
|
|
2
|
-
import { canonicalJson } from './hash.mjs';
|
|
2
|
+
import { canonicalJson, sha256 } from './hash.mjs';
|
|
3
3
|
const identifier=value=>value.replace(/[A-Z]/g,c=>c.toLowerCase());
|
|
4
4
|
|
|
5
5
|
export async function excludedDependentGuards(db,targets,replaceable) {
|
|
@@ -40,12 +40,15 @@ export async function migrationSeeded(db,names,migrations) {
|
|
|
40
40
|
const requests=[];
|
|
41
41
|
for(const name of names)requests.push({name,columns:(await all(db,`SELECT name FROM pragma_table_info(?)`,name)).map(c=>c.name)});
|
|
42
42
|
// Without a usable replay no seed is vouched for, so those rows count as the installation's own.
|
|
43
|
-
const
|
|
43
|
+
const replay=await migrations().catch(()=>null);
|
|
44
|
+
const hashed=Boolean(replay?.rowHashes);
|
|
45
|
+
const expected=replay?await (hashed?replay.rowHashes(requests,MAX_SEED_ROWS):replay.rowImages(requests,MAX_SEED_ROWS)):new Map(),seeded=[];
|
|
44
46
|
for(const {name,columns} of requests) {
|
|
45
47
|
const want=expected.get(name);
|
|
46
48
|
if(!want || (await statement(db,`SELECT count(*) AS n FROM ${quote(name)}`).first()).n!==want.length)continue;
|
|
47
49
|
const found=(await all(db,imageSql(name,columns))).map(r=>r.image).sort();
|
|
48
|
-
|
|
50
|
+
const identities=hashed?(await Promise.all(found.map(sha256))).sort():found;
|
|
51
|
+
if(canonicalJson(identities)===canonicalJson(want))seeded.push({name,columns,images:found});
|
|
49
52
|
}
|
|
50
53
|
return seeded;
|
|
51
54
|
}
|