@cleocode/core 2026.11.6 → 2026.11.7-rc.ci.724
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/dist/.source-stamp.json +1 -1
- package/dist/build-provenance.json +2 -2
- package/dist/config/legacy-keys.d.ts +14 -0
- package/dist/config/legacy-keys.js +32 -0
- package/dist/config/legacy-keys.js.map +1 -1
- package/dist/config.js +7 -3
- package/dist/config.js.map +1 -1
- package/dist/docs/doctor.js +101 -38
- package/dist/docs/doctor.js.map +1 -1
- package/dist/doctor/cleo-runtime-tracking.d.ts +174 -0
- package/dist/doctor/cleo-runtime-tracking.js +437 -0
- package/dist/doctor/cleo-runtime-tracking.js.map +1 -0
- package/dist/doctor/cloud-sync-folder.d.ts +88 -0
- package/dist/doctor/cloud-sync-folder.js +211 -0
- package/dist/doctor/cloud-sync-folder.js.map +1 -0
- package/dist/git/hooks-install.js +10 -2
- package/dist/git/hooks-install.js.map +1 -1
- package/dist/hooks/handlers/work-capture-hooks.js +2 -0
- package/dist/hooks/handlers/work-capture-hooks.js.map +1 -1
- package/dist/hooks/registry.d.ts +4 -2
- package/dist/hooks/registry.js +19 -10
- package/dist/hooks/registry.js.map +1 -1
- package/dist/hooks/types.d.ts +2 -0
- package/dist/hooks/types.js.map +1 -1
- package/dist/hygiene/census.d.ts +24 -4
- package/dist/hygiene/census.js +137 -9
- package/dist/hygiene/census.js.map +1 -1
- package/dist/init.js +25 -0
- package/dist/init.js.map +1 -1
- package/dist/memory/graph-auto-populate.d.ts +2 -2
- package/dist/memory/graph-auto-populate.js +8 -3
- package/dist/memory/graph-auto-populate.js.map +1 -1
- package/dist/orchestrate/spawn-ops.d.ts +2 -0
- package/dist/orchestrate/spawn-ops.js +4 -0
- package/dist/orchestrate/spawn-ops.js.map +1 -1
- package/dist/orchestrate/worker-records.d.ts +2 -0
- package/dist/orchestrate/worker-records.js +4 -2
- package/dist/orchestrate/worker-records.js.map +1 -1
- package/dist/orchestration/dashboard.d.ts +17 -0
- package/dist/orchestration/dashboard.js +79 -3
- package/dist/orchestration/dashboard.js.map +1 -1
- package/dist/orchestration/spawn.d.ts +7 -0
- package/dist/orchestration/spawn.js +8 -4
- package/dist/orchestration/spawn.js.map +1 -1
- package/dist/release/ci-evidence.d.ts +75 -0
- package/dist/release/ci-evidence.js +117 -1
- package/dist/release/ci-evidence.js.map +1 -1
- package/dist/render/session/doctor.js +8 -2
- package/dist/render/session/doctor.js.map +1 -1
- package/dist/scaffold/ensure-config.d.ts +6 -1
- package/dist/scaffold/ensure-config.js +4 -2
- package/dist/scaffold/ensure-config.js.map +1 -1
- package/dist/session/engine-ops.d.ts +2 -2
- package/dist/session/engine-ops.js +4 -0
- package/dist/session/engine-ops.js.map +1 -1
- package/dist/store/backup-recover.d.ts +9 -10
- package/dist/store/backup-recover.js +7 -5
- package/dist/store/backup-recover.js.map +1 -1
- package/dist/store/dual-scope-db.d.ts +2 -0
- package/dist/store/dual-scope-db.js +63 -3
- package/dist/store/dual-scope-db.js.map +1 -1
- package/dist/store/memory-sqlite.js +3 -24
- package/dist/store/memory-sqlite.js.map +1 -1
- package/dist/store/open-cleo-db.d.ts +15 -0
- package/dist/store/open-cleo-db.js +124 -3
- package/dist/store/open-cleo-db.js.map +1 -1
- package/dist/store/recover-malformed-db.js +2 -0
- package/dist/store/recover-malformed-db.js.map +1 -1
- package/dist/store/repair-store-files.d.ts +25 -0
- package/dist/store/repair-store-files.js +273 -0
- package/dist/store/repair-store-files.js.map +1 -0
- package/dist/store/repair-store-salvage.d.ts +13 -0
- package/dist/store/repair-store-salvage.js +765 -0
- package/dist/store/repair-store-salvage.js.map +1 -0
- package/dist/store/repair-store.d.ts +14 -0
- package/dist/store/repair-store.js +499 -0
- package/dist/store/repair-store.js.map +1 -0
- package/dist/store/restore-marker.d.ts +5 -0
- package/dist/store/restore-marker.js +15 -0
- package/dist/store/restore-marker.js.map +1 -1
- package/dist/store/schema/cleo-global/agent-registry.d.ts +1 -1
- package/dist/store/schema/cleo-project/provenance-rest.d.ts +1 -1
- package/dist/store/schema/provenance/releases.d.ts +1 -1
- package/dist/store/snapshot-gate.js +17 -7
- package/dist/store/snapshot-gate.js.map +1 -1
- package/dist/store/sqlite-backup.js +6 -9
- package/dist/store/sqlite-backup.js.map +1 -1
- package/dist/store/sqlite-native.d.ts +2 -0
- package/dist/store/sqlite-native.js +11 -0
- package/dist/store/sqlite-native.js.map +1 -1
- package/dist/store/worktree-isolation-guard.js +2 -0
- package/dist/store/worktree-isolation-guard.js.map +1 -1
- package/dist/system/health.d.ts +4 -2
- package/dist/system/health.js +42 -1
- package/dist/system/health.js.map +1 -1
- package/dist/tasks/add.js +5 -12
- package/dist/tasks/add.js.map +1 -1
- package/dist/tasks/merge-close.d.ts +14 -0
- package/dist/tasks/merge-close.js +21 -2
- package/dist/tasks/merge-close.js.map +1 -1
- package/dist/upgrade.d.ts +2 -0
- package/dist/upgrade.js +38 -1
- package/dist/upgrade.js.map +1 -1
- package/dist/validation/doctor/checks.d.ts +5 -3
- package/dist/validation/doctor/checks.js +14 -4
- package/dist/validation/doctor/checks.js.map +1 -1
- package/package.json +13 -13
- package/templates/CLEO-INJECTION.md +3 -2
- package/templates/CLEO-REFERENCE.md +4 -2
- package/templates/cleo-gitignore +3 -0
- package/templates/config.template.json +1 -2
- package/templates/git-hooks/legacy-hashes.json +2 -1
- package/templates/git-hooks/pre-commit +66 -7
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
/** Copy-only SQLite salvage. No handle in this module ever opens the live store. */
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { closeSync, existsSync, openSync, readSync, realpathSync, statSync } from 'node:fs';
|
|
4
|
+
import { basename } from 'node:path';
|
|
5
|
+
import { openCleoDbSnapshot } from './open-cleo-db.js';
|
|
6
|
+
import { repairSalvageHeader } from './repair-store-files.js';
|
|
7
|
+
import { ensureTriggerSuspendTable, withTriggersSuspended } from './sync/trigger-classes.js';
|
|
8
|
+
const ROWID = '__cleo_repair_rowid';
|
|
9
|
+
/** Quote an identifier obtained from a private database's schema. */
|
|
10
|
+
export function repairIdentifier(name) {
|
|
11
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
12
|
+
}
|
|
13
|
+
/** Enumerate even a partially readable schema, preserving rows yielded before an error. */
|
|
14
|
+
function tables(db, diagnostics, file) {
|
|
15
|
+
const found = [];
|
|
16
|
+
try {
|
|
17
|
+
db.exec('PRAGMA writable_schema=ON');
|
|
18
|
+
const complete = readRows(db, file, { name: 'sqlite_schema', root: 1, sql: '' }, (row) => {
|
|
19
|
+
if (row.type === 'table' && typeof row.name === 'string' && typeof row.sql === 'string') {
|
|
20
|
+
found.push({ name: row.name, sql: row.sql, root: Number(row.rootpage) });
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
if (!complete)
|
|
24
|
+
diagnostics.push('sqlite_schema: unreadable ranges; schema coverage is incomplete');
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
diagnostics.push(`schema: ${error instanceof Error ? error.message : String(error)}`);
|
|
28
|
+
}
|
|
29
|
+
return found;
|
|
30
|
+
}
|
|
31
|
+
function columns(db, table) {
|
|
32
|
+
return db
|
|
33
|
+
.prepare(`PRAGMA main.table_xinfo(${repairIdentifier(table)})`)
|
|
34
|
+
.all()
|
|
35
|
+
.filter((r) => r.hidden === 0 || r.hidden === 0n)
|
|
36
|
+
.map((r) => ({ name: String(r.name), pk: Number(r.pk) }));
|
|
37
|
+
}
|
|
38
|
+
function timestamp(value) {
|
|
39
|
+
if (typeof value === 'number' || typeof value === 'bigint') {
|
|
40
|
+
const n = Number(value);
|
|
41
|
+
return Number.isFinite(n)
|
|
42
|
+
? Math.abs(n) < 100_000_000_000
|
|
43
|
+
? n * 1000
|
|
44
|
+
: n
|
|
45
|
+
: Number.NEGATIVE_INFINITY;
|
|
46
|
+
}
|
|
47
|
+
if (typeof value !== 'string')
|
|
48
|
+
return Number.NEGATIVE_INFINITY;
|
|
49
|
+
if (/^\d+(?:\.\d+)?$/.test(value))
|
|
50
|
+
return timestamp(Number(value));
|
|
51
|
+
const iso = value.replace(/^(\d{4}-\d\d-\d\d) /, '$1T');
|
|
52
|
+
const parsed = Date.parse(/^\d{4}-\d\d-\d\dT/.test(iso) && !/(?:Z|[+-]\d\d:\d\d)$/i.test(iso) ? `${iso}Z` : iso);
|
|
53
|
+
return Number.isNaN(parsed) ? Number.NEGATIVE_INFINITY : parsed;
|
|
54
|
+
}
|
|
55
|
+
/** SQLite varint, including signed rowids represented as unsigned 64-bit integers. */
|
|
56
|
+
function varint(page, start) {
|
|
57
|
+
let value = 0n;
|
|
58
|
+
for (let i = 0; i < 9 && start + i < page.length; i++) {
|
|
59
|
+
const b = page[start + i];
|
|
60
|
+
if (b === undefined)
|
|
61
|
+
return null;
|
|
62
|
+
value = (value << BigInt(i === 8 ? 8 : 7)) | BigInt(i === 8 ? b : b & 127);
|
|
63
|
+
if (i === 8 || b < 128)
|
|
64
|
+
return { value, end: start + i + 1 };
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Visit rowid leaf ranges directly from the b-tree. A zeroed leaf does not
|
|
70
|
+
* prevent seeking into its later siblings, unlike resuming a failed cursor.
|
|
71
|
+
* The private WAL view is checkpointed first, so page addresses match SQLite.
|
|
72
|
+
*/
|
|
73
|
+
function leafRanges(file, root, visit) {
|
|
74
|
+
const fd = openSync(file, 'r');
|
|
75
|
+
try {
|
|
76
|
+
const header = Buffer.alloc(100);
|
|
77
|
+
readSync(fd, header, 0, 100, 0);
|
|
78
|
+
const rawSize = header.readUInt16BE(16);
|
|
79
|
+
const size = rawSize === 1 ? 65536 : rawSize;
|
|
80
|
+
if (size < 512 || size > 65536 || (size & (size - 1)) !== 0)
|
|
81
|
+
// @sync-invariant none:local-only local recovery refuses before publishing a staged store image
|
|
82
|
+
throw new Error('Unreadable SQLite page size');
|
|
83
|
+
const pages = Math.floor(statSync(file).size / size);
|
|
84
|
+
const seen = new Set();
|
|
85
|
+
const walk = (pageNo, lo, hi) => {
|
|
86
|
+
if (pageNo < 1 || pageNo > pages || seen.has(pageNo)) {
|
|
87
|
+
visit(lo, hi, []);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
seen.add(pageNo);
|
|
91
|
+
const page = Buffer.alloc(size);
|
|
92
|
+
readSync(fd, page, 0, size, (pageNo - 1) * size);
|
|
93
|
+
const h = pageNo === 1 ? 100 : 0;
|
|
94
|
+
const kind = page[h];
|
|
95
|
+
if (kind !== 5 && kind !== 13) {
|
|
96
|
+
visit(lo, hi, []);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const n = page.readUInt16BE(h + 3);
|
|
100
|
+
const start = h + (kind === 5 ? 12 : 8);
|
|
101
|
+
if (start + n * 2 > page.length) {
|
|
102
|
+
visit(lo, hi, []);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
let lower = lo;
|
|
106
|
+
const ids = [];
|
|
107
|
+
for (let i = 0; i < n; i++) {
|
|
108
|
+
const cell = page.readUInt16BE(start + i * 2);
|
|
109
|
+
if (cell < start || cell >= page.length)
|
|
110
|
+
continue;
|
|
111
|
+
if (kind === 5) {
|
|
112
|
+
if (cell + 4 >= page.length)
|
|
113
|
+
continue;
|
|
114
|
+
const key = varint(page, cell + 4);
|
|
115
|
+
if (!key)
|
|
116
|
+
continue;
|
|
117
|
+
const upper = BigInt.asIntN(64, key.value);
|
|
118
|
+
if (upper < lower || upper > hi)
|
|
119
|
+
continue;
|
|
120
|
+
walk(page.readUInt32BE(cell), lower, upper);
|
|
121
|
+
lower = upper + 1n;
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
const payload = varint(page, cell);
|
|
125
|
+
const key = payload && varint(page, payload.end);
|
|
126
|
+
if (key)
|
|
127
|
+
ids.push(BigInt.asIntN(64, key.value));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (kind === 5)
|
|
131
|
+
walk(page.readUInt32BE(h + 8), lower, hi);
|
|
132
|
+
else
|
|
133
|
+
visit(lo, hi, ids);
|
|
134
|
+
};
|
|
135
|
+
walk(root, -(1n << 63n), (1n << 63n) - 1n);
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
closeSync(fd);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function hasRowid(sql) {
|
|
142
|
+
return (!/\bWITHOUT\s+ROWID\b/i.test(sql) &&
|
|
143
|
+
(!/\bVIRTUAL\s+TABLE\b/i.test(sql) || /\bUSING\s+fts[345]\b/i.test(sql)));
|
|
144
|
+
}
|
|
145
|
+
/** Stream readable rows; isolate bad pages without scanning an unbounded integer keyspace. */
|
|
146
|
+
function readRows(db, file, table, accept) {
|
|
147
|
+
const q = repairIdentifier(table.name);
|
|
148
|
+
const rowid = hasRowid(table.sql);
|
|
149
|
+
const select = `SELECT ${rowid ? `_rowid_ AS ${repairIdentifier(ROWID)}, ` : ''}* FROM main.${q} NOT INDEXED`;
|
|
150
|
+
let iterator;
|
|
151
|
+
try {
|
|
152
|
+
const stmt = db.prepare(select);
|
|
153
|
+
stmt.setReadBigInts(true);
|
|
154
|
+
iterator = stmt.iterate();
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
if (!(error instanceof Error) ||
|
|
158
|
+
!/malformed|corrupt|no such|not a database/i.test(error.message))
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
while (iterator) {
|
|
162
|
+
let next;
|
|
163
|
+
try {
|
|
164
|
+
next = iterator.next();
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
if (next.done)
|
|
170
|
+
return true;
|
|
171
|
+
// A merge rejection is not a read failure and must never be skipped.
|
|
172
|
+
accept(next.value);
|
|
173
|
+
}
|
|
174
|
+
if (!rowid || table.root < 1)
|
|
175
|
+
return false;
|
|
176
|
+
let complete = true;
|
|
177
|
+
leafRanges(file, table.root, (lo, hi, ids) => {
|
|
178
|
+
if (ids.length === 0)
|
|
179
|
+
complete = false;
|
|
180
|
+
let rows;
|
|
181
|
+
try {
|
|
182
|
+
const stmt = db.prepare(`${select} WHERE _rowid_ BETWEEN ? AND ?`);
|
|
183
|
+
stmt.setReadBigInts(true);
|
|
184
|
+
rows = stmt.all(lo, hi);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
complete = false;
|
|
188
|
+
for (const id of ids) {
|
|
189
|
+
let row;
|
|
190
|
+
try {
|
|
191
|
+
const stmt = db.prepare(`${select} WHERE _rowid_ = ?`);
|
|
192
|
+
stmt.setReadBigInts(true);
|
|
193
|
+
row = stmt.get(id);
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (row)
|
|
199
|
+
accept(row);
|
|
200
|
+
}
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
for (const row of rows)
|
|
204
|
+
accept(row);
|
|
205
|
+
});
|
|
206
|
+
return complete;
|
|
207
|
+
}
|
|
208
|
+
/** Run the optional SQLite recovery extension into a separate, disposable database. */
|
|
209
|
+
function sqliteRecover(file, diagnostics) {
|
|
210
|
+
const sqlFile = `${file}.recover.sql`;
|
|
211
|
+
const fd = openSync(sqlFile, 'wx');
|
|
212
|
+
let recovered;
|
|
213
|
+
try {
|
|
214
|
+
recovered = spawnSync('sqlite3', ['-safe', file, '.recover --ignore-freelist'], {
|
|
215
|
+
stdio: ['ignore', fd, 'pipe'],
|
|
216
|
+
timeout: 60_000,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
closeSync(fd);
|
|
221
|
+
}
|
|
222
|
+
if (recovered.error || recovered.status !== 0) {
|
|
223
|
+
diagnostics.push(`sqlite3 .recover: ${recovered.error?.message ?? recovered.stderr?.toString().trim() ?? recovered.status}`);
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
const recoveredFile = `${file}.recovered`;
|
|
227
|
+
const input = openSync(sqlFile, 'r');
|
|
228
|
+
try {
|
|
229
|
+
const applied = spawnSync('sqlite3', ['-safe', recoveredFile], {
|
|
230
|
+
stdio: [input, 'ignore', 'pipe'],
|
|
231
|
+
timeout: 60_000,
|
|
232
|
+
});
|
|
233
|
+
if (applied.error || applied.status !== 0) {
|
|
234
|
+
diagnostics.push(`sqlite3 recovered SQL: ${applied.error?.message ?? applied.stderr?.toString().trim()}`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
closeSync(input);
|
|
239
|
+
}
|
|
240
|
+
return existsSync(recoveredFile) && statSync(recoveredFile).size > 0 ? recoveredFile : null;
|
|
241
|
+
}
|
|
242
|
+
/** Count all physical tables, including journal and FTS shadow tables. */
|
|
243
|
+
export function repairTableCounts(db) {
|
|
244
|
+
const counts = {};
|
|
245
|
+
Object.setPrototypeOf(counts, null);
|
|
246
|
+
for (const row of db.prepare("SELECT name FROM main.sqlite_schema WHERE type='table'").all()) {
|
|
247
|
+
const table = String(row.name);
|
|
248
|
+
counts[table] = Number(db.prepare(`SELECT count(*) AS n FROM main.${repairIdentifier(table)}`).get()?.n);
|
|
249
|
+
}
|
|
250
|
+
return counts;
|
|
251
|
+
}
|
|
252
|
+
/** Preserve a readable value without JSON's bigint and binary conversion losses. */
|
|
253
|
+
function recordRecovery(receipt, kind, table, reason, row, source) {
|
|
254
|
+
receipt.recovery ??= { file: null, rows: [] };
|
|
255
|
+
const values = {};
|
|
256
|
+
Object.setPrototypeOf(values, null);
|
|
257
|
+
for (const [name, value] of Object.entries(row)) {
|
|
258
|
+
values[name] =
|
|
259
|
+
typeof value === 'bigint'
|
|
260
|
+
? { type: 'bigint', value: value.toString() }
|
|
261
|
+
: value instanceof Uint8Array
|
|
262
|
+
? { type: 'blob', value: Buffer.from(value).toString('base64') }
|
|
263
|
+
: value;
|
|
264
|
+
}
|
|
265
|
+
receipt.recovery.rows.push({ kind, table, reason, values, ...(source ? { source } : {}) });
|
|
266
|
+
}
|
|
267
|
+
function rowKey(row, identity) {
|
|
268
|
+
return JSON.stringify(identity.map((name) => row[name] ?? null), (_key, value) => (typeof value === 'bigint' ? value.toString() : value));
|
|
269
|
+
}
|
|
270
|
+
/** SQLite identifies FTS shadow tables; vec0 also has module-owned bookkeeping tables. */
|
|
271
|
+
function shadowTables(db, schema) {
|
|
272
|
+
const shadows = new Set();
|
|
273
|
+
try {
|
|
274
|
+
for (const row of db.prepare('PRAGMA main.table_list').all())
|
|
275
|
+
if (row.type === 'shadow')
|
|
276
|
+
shadows.add(String(row.name));
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
/* A partial schema is still salvaged below. */
|
|
280
|
+
}
|
|
281
|
+
for (const table of schema.filter((t) => /\bUSING\s+vec0\b/i.test(t.sql))) {
|
|
282
|
+
for (const child of schema) {
|
|
283
|
+
if (child.name.startsWith(`${table.name}_`) &&
|
|
284
|
+
/^(?:info|chunks|rowids|vector_chunks\d+|metadatachunks\d+|metadatatext\d+)$/i.test(child.name.slice(table.name.length + 1)))
|
|
285
|
+
shadows.add(child.name);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return shadows;
|
|
289
|
+
}
|
|
290
|
+
/** Recreate virtual storage from logical content; never copy module-owned shadow pages. */
|
|
291
|
+
function rebuildVirtual(db, table) {
|
|
292
|
+
const name = repairIdentifier(table.name);
|
|
293
|
+
const externalFts = /\bUSING\s+fts[345]\b/i.test(table.sql) && /\bcontent\s*=/i.test(table.sql);
|
|
294
|
+
if (externalFts) {
|
|
295
|
+
db.exec(`DROP TABLE main.${name}`);
|
|
296
|
+
db.prepare(table.sql).run();
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
const names = columns(db, table.name).map((c) => c.name);
|
|
300
|
+
if (hasRowid(table.sql))
|
|
301
|
+
names.unshift('rowid');
|
|
302
|
+
const cols = names.map(repairIdentifier).join(',');
|
|
303
|
+
// TEMP holds logical vectors/documents while their module rebuilds its own shadow tables.
|
|
304
|
+
db.exec(`CREATE TEMP TABLE cleo_repair_virtual AS SELECT ${cols} FROM main.${name}`);
|
|
305
|
+
db.exec(`DROP TABLE main.${name}`);
|
|
306
|
+
db.prepare(table.sql).run();
|
|
307
|
+
db.exec(`INSERT INTO main.${name} (${cols}) SELECT ${cols} FROM temp.cleo_repair_virtual`);
|
|
308
|
+
db.exec('DROP TABLE temp.cleo_repair_virtual');
|
|
309
|
+
}
|
|
310
|
+
/** Locate an FK offender even in a composite-key WITHOUT ROWID table. */
|
|
311
|
+
function orphanRows(db, violation) {
|
|
312
|
+
const q = repairIdentifier(String(violation.table));
|
|
313
|
+
if (violation.rowid !== null) {
|
|
314
|
+
const stmt = db.prepare(`SELECT _rowid_ AS ${repairIdentifier(ROWID)}, * FROM main.${q} WHERE _rowid_=?`);
|
|
315
|
+
stmt.setReadBigInts(true);
|
|
316
|
+
return stmt.all(violation.rowid ?? null);
|
|
317
|
+
}
|
|
318
|
+
const parent = String(violation.parent);
|
|
319
|
+
const pk = columns(db, parent)
|
|
320
|
+
.filter((c) => c.pk > 0)
|
|
321
|
+
.sort((a, b) => a.pk - b.pk);
|
|
322
|
+
const foreign = db
|
|
323
|
+
.prepare(`PRAGMA main.foreign_key_list(${q})`)
|
|
324
|
+
.all()
|
|
325
|
+
.filter((r) => Number(r.id) === Number(violation.fkid))
|
|
326
|
+
.sort((a, b) => Number(a.seq) - Number(b.seq));
|
|
327
|
+
const nonNull = foreign
|
|
328
|
+
.map((r) => `c.${repairIdentifier(String(r.from))} IS NOT NULL`)
|
|
329
|
+
.join(' AND ');
|
|
330
|
+
const join = foreign
|
|
331
|
+
.map((r, i) => `p.${repairIdentifier(String(r.to ?? pk[i]?.name))} = c.${repairIdentifier(String(r.from))}`)
|
|
332
|
+
.join(' AND ');
|
|
333
|
+
const stmt = db.prepare(`SELECT c.* FROM main.${q} AS c WHERE ${nonNull} AND NOT EXISTS (SELECT 1 FROM main.${repairIdentifier(parent)} AS p WHERE ${join})`);
|
|
334
|
+
stmt.setReadBigInts(true);
|
|
335
|
+
return stmt.all();
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Merge readable content from private damaged views, preserving incompatible rows separately.
|
|
339
|
+
* The first view is authoritative only for tables it reads completely. Later views fill gaps;
|
|
340
|
+
* timestamps can establish a newer value, but never turn an older main-only view authoritative.
|
|
341
|
+
* All writes target the staged snapshot (gate 28), under trigger suspension (gate 36).
|
|
342
|
+
*/
|
|
343
|
+
export function salvageIntoSnapshot(staged, views, receipt) {
|
|
344
|
+
if (basename(realpathSync(staged)) === 'cleo.db')
|
|
345
|
+
// @sync-invariant none:local-only local recovery refuses before publishing a staged store image
|
|
346
|
+
throw new Error('Salvage writes require a staged snapshot, never a canonical store or quarantine original');
|
|
347
|
+
Object.setPrototypeOf(receipt.tables, null);
|
|
348
|
+
const journal = [];
|
|
349
|
+
const journalKeys = new Set();
|
|
350
|
+
const target = openCleoDbSnapshot(staged, {
|
|
351
|
+
readOnly: false,
|
|
352
|
+
applyPragmas: false,
|
|
353
|
+
loadSqliteVec: true,
|
|
354
|
+
});
|
|
355
|
+
try {
|
|
356
|
+
const db = target.db;
|
|
357
|
+
db.exec('PRAGMA foreign_keys=OFF');
|
|
358
|
+
ensureTriggerSuspendTable(db);
|
|
359
|
+
const originalTriggers = db
|
|
360
|
+
.prepare("SELECT name, sql FROM main.sqlite_schema WHERE type='trigger'")
|
|
361
|
+
.all();
|
|
362
|
+
const initialSchema = tables(db, receipt.diagnostics, staged);
|
|
363
|
+
const targetTables = new Set(initialSchema.map((t) => t.name));
|
|
364
|
+
const targetShadows = shadowTables(db, initialSchema);
|
|
365
|
+
const virtual = new Map(initialSchema.filter((t) => /\bVIRTUAL\s+TABLE\b/i.test(t.sql)).map((t) => [t.name, t]));
|
|
366
|
+
const keys = new Map();
|
|
367
|
+
const authority = new Map();
|
|
368
|
+
const newestKeys = new Map();
|
|
369
|
+
const baseKeys = new Map();
|
|
370
|
+
const pending = [];
|
|
371
|
+
const deletedKeys = new Map();
|
|
372
|
+
const alternateVersions = new Set();
|
|
373
|
+
const reportFor = (name) => {
|
|
374
|
+
receipt.tables[name] ??= { snapshot: 0, salvaged: 0, merged: 0, unreadable: 0, final: 0 };
|
|
375
|
+
return receipt.tables[name];
|
|
376
|
+
};
|
|
377
|
+
const removeBase = (table, row, identity) => {
|
|
378
|
+
if (baseKeys.get(table)?.delete(rowKey(row, identity))) {
|
|
379
|
+
const report = reportFor(table);
|
|
380
|
+
report.baseRemoved = (report.baseRemoved ?? 0) + 1;
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
const recordDeleted = (table, row, identity, reason) => {
|
|
384
|
+
const deleted = deletedKeys.get(table) ?? new Set();
|
|
385
|
+
deletedKeys.set(table, deleted);
|
|
386
|
+
const key = rowKey(row, identity);
|
|
387
|
+
if (deleted.has(key))
|
|
388
|
+
return;
|
|
389
|
+
deleted.add(key);
|
|
390
|
+
reportFor(table).deleted = deleted.size;
|
|
391
|
+
recordRecovery(receipt, 'deleted', table, reason, row);
|
|
392
|
+
};
|
|
393
|
+
db.exec('BEGIN IMMEDIATE');
|
|
394
|
+
try {
|
|
395
|
+
withTriggersSuspended(db, ['all'], 'rewind', () => {
|
|
396
|
+
for (const trigger of originalTriggers)
|
|
397
|
+
db.exec(`DROP TRIGGER ${repairIdentifier(String(trigger.name))}`);
|
|
398
|
+
for (const table of virtual.values())
|
|
399
|
+
rebuildVirtual(db, table);
|
|
400
|
+
for (const name of targetShadows)
|
|
401
|
+
reportFor(name).rebuilt = true;
|
|
402
|
+
for (const table of initialSchema) {
|
|
403
|
+
if (targetShadows.has(table.name) ||
|
|
404
|
+
['cleo_trigger_suspend', 'sqlite_sequence', '__drizzle_migrations'].includes(table.name))
|
|
405
|
+
continue;
|
|
406
|
+
if (/\bUSING\s+fts[345]\b/i.test(table.sql) && /\bcontent\s*=/i.test(table.sql)) {
|
|
407
|
+
reportFor(table.name).rebuilt = true;
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
const cols = columns(db, table.name);
|
|
411
|
+
let identity = cols
|
|
412
|
+
.filter((c) => c.pk > 0)
|
|
413
|
+
.sort((a, b) => a.pk - b.pk)
|
|
414
|
+
.map((c) => c.name);
|
|
415
|
+
if (identity.length === 0)
|
|
416
|
+
identity = hasRowid(table.sql) ? [ROWID] : cols.map((c) => c.name);
|
|
417
|
+
const base = new Set();
|
|
418
|
+
readRows(db, staged, table, (row) => base.add(rowKey(row, identity)));
|
|
419
|
+
baseKeys.set(table.name, base);
|
|
420
|
+
}
|
|
421
|
+
for (const view of views) {
|
|
422
|
+
try {
|
|
423
|
+
const cp = openCleoDbSnapshot(view, {
|
|
424
|
+
readOnly: false,
|
|
425
|
+
applyPragmas: false,
|
|
426
|
+
loadSqliteVec: true,
|
|
427
|
+
});
|
|
428
|
+
try {
|
|
429
|
+
cp.db.exec('PRAGMA writable_schema=ON; PRAGMA wal_checkpoint(TRUNCATE)');
|
|
430
|
+
}
|
|
431
|
+
finally {
|
|
432
|
+
cp.close();
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
receipt.diagnostics.push(`checkpoint ${view}: ${error instanceof Error ? error.message : String(error)}`);
|
|
437
|
+
}
|
|
438
|
+
const recovered = sqliteRecover(view, receipt.diagnostics);
|
|
439
|
+
const headerRecovered = repairSalvageHeader(view, staged);
|
|
440
|
+
if (headerRecovered)
|
|
441
|
+
receipt.diagnostics.push(`Reconstructed a disposable header for ${view}; original remains quarantined`);
|
|
442
|
+
for (const source of [view, recovered, headerRecovered].filter((path) => path !== null)) {
|
|
443
|
+
let snap;
|
|
444
|
+
try {
|
|
445
|
+
snap = openCleoDbSnapshot(source, { applyPragmas: false, loadSqliteVec: true });
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
for (const report of Object.values(receipt.tables))
|
|
449
|
+
report.unreadable = null;
|
|
450
|
+
receipt.diagnostics.push(`open ${source}: ${error instanceof Error ? error.message : String(error)}`);
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
try {
|
|
454
|
+
const beforeSchema = receipt.diagnostics.length;
|
|
455
|
+
const sourceTables = tables(snap.db, receipt.diagnostics, source);
|
|
456
|
+
const incompleteSchema = receipt.diagnostics.length !== beforeSchema;
|
|
457
|
+
if (incompleteSchema)
|
|
458
|
+
for (const report of Object.values(receipt.tables))
|
|
459
|
+
report.unreadable = null;
|
|
460
|
+
const shadows = shadowTables(snap.db, sourceTables);
|
|
461
|
+
for (const table of sourceTables) {
|
|
462
|
+
const report = reportFor(table.name);
|
|
463
|
+
if (shadows.has(table.name)) {
|
|
464
|
+
report.rebuilt = true;
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
if (table.name === 'cleo_trigger_suspend' || table.name === 'sqlite_sequence')
|
|
468
|
+
continue;
|
|
469
|
+
const externalFts = /\bUSING\s+fts[345]\b/i.test(table.sql) && /\bcontent\s*=/i.test(table.sql);
|
|
470
|
+
if (!targetTables.has(table.name)) {
|
|
471
|
+
try {
|
|
472
|
+
if (!/^\s*CREATE\s+(?:VIRTUAL\s+)?TABLE\b/i.test(table.sql))
|
|
473
|
+
// @sync-invariant none:input-shape a recovered schema row must declare a table
|
|
474
|
+
throw new Error(`Invalid recovered table definition: ${table.name}`);
|
|
475
|
+
const ddl = db.prepare(table.sql);
|
|
476
|
+
ddl.setReadBigInts(true);
|
|
477
|
+
ddl.run();
|
|
478
|
+
targetTables.add(table.name);
|
|
479
|
+
if (/\bVIRTUAL\s+TABLE\b/i.test(table.sql))
|
|
480
|
+
virtual.set(table.name, table);
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
receipt.diagnostics.push(`${table.name}: cannot recreate schema: ${error instanceof Error ? error.message : String(error)}`);
|
|
484
|
+
const complete = readRows(snap.db, source, table, (row) => {
|
|
485
|
+
report.salvaged++;
|
|
486
|
+
report.conflicts = (report.conflicts ?? 0) + 1;
|
|
487
|
+
recordRecovery(receipt, 'conflict', table.name, `schema: ${error instanceof Error ? error.message : String(error)}`, row);
|
|
488
|
+
});
|
|
489
|
+
if (!complete)
|
|
490
|
+
report.unreadable = null;
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (externalFts) {
|
|
495
|
+
report.rebuilt = true;
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (table.name === '__drizzle_migrations') {
|
|
499
|
+
const complete = readRows(snap.db, source, table, (row) => {
|
|
500
|
+
const key = String(row.id ?? row[ROWID]);
|
|
501
|
+
if (!journalKeys.has(key)) {
|
|
502
|
+
journalKeys.add(key);
|
|
503
|
+
journal.push(row);
|
|
504
|
+
report.salvaged++;
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
if (!complete) {
|
|
508
|
+
report.unreadable = null;
|
|
509
|
+
receipt.diagnostics.push(`${table.name}: unreadable migration-journal ranges; their row count is unknown`);
|
|
510
|
+
}
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
const destColumns = columns(db, table.name);
|
|
514
|
+
const incoming = columns(snap.db, table.name).map((c) => c.name);
|
|
515
|
+
const common = destColumns
|
|
516
|
+
.filter((c) => incoming.includes(c.name))
|
|
517
|
+
.map((c) => c.name);
|
|
518
|
+
const missing = incoming.filter((c) => !common.includes(c));
|
|
519
|
+
let pk = destColumns
|
|
520
|
+
.filter((c) => c.pk > 0)
|
|
521
|
+
.sort((a, b) => a.pk - b.pk)
|
|
522
|
+
.map((c) => c.name);
|
|
523
|
+
if (pk.length === 0 && hasRowid(table.sql)) {
|
|
524
|
+
pk = [ROWID];
|
|
525
|
+
common.unshift(ROWID);
|
|
526
|
+
}
|
|
527
|
+
const identity = pk.length > 0 ? pk : common;
|
|
528
|
+
const col = (c) => repairIdentifier(c === ROWID ? '_rowid_' : c);
|
|
529
|
+
const q = `main.${repairIdentifier(table.name)}`;
|
|
530
|
+
const where = identity.map((c) => `${col(c)} IS ?`).join(' AND ');
|
|
531
|
+
const find = db.prepare(`SELECT * FROM ${q} WHERE ${where} LIMIT 1`);
|
|
532
|
+
find.setReadBigInts(true);
|
|
533
|
+
const ins = db.prepare(`INSERT INTO ${q} (${common.map(col).join(',')}) VALUES (${common.map(() => '?').join(',')})`);
|
|
534
|
+
ins.setReadBigInts(true);
|
|
535
|
+
const stamp = ['updated_at', 'updatedAt', 'modified_at', 'modifiedAt'].find((c) => common.includes(c));
|
|
536
|
+
const updates = common.filter((c) => !pk.includes(c));
|
|
537
|
+
const update = updates.length > 0
|
|
538
|
+
? db.prepare(`UPDATE ${q} SET ${updates.map((c) => `${col(c)}=?`).join(',')} WHERE ${where}`)
|
|
539
|
+
: null;
|
|
540
|
+
update?.setReadBigInts(true);
|
|
541
|
+
const seen = keys.get(table.name) ?? new Set();
|
|
542
|
+
keys.set(table.name, seen);
|
|
543
|
+
if (!baseKeys.has(table.name)) {
|
|
544
|
+
const base = new Set();
|
|
545
|
+
readRows(db, staged, table, (row) => base.add(rowKey(row, identity)));
|
|
546
|
+
baseKeys.set(table.name, base);
|
|
547
|
+
}
|
|
548
|
+
const thisRead = new Set();
|
|
549
|
+
const apply = (row, first) => {
|
|
550
|
+
const values = identity.map((c) => row[c] ?? null);
|
|
551
|
+
const old = find.get(...values);
|
|
552
|
+
if (!old) {
|
|
553
|
+
ins.run(...common.map((c) => row[c] ?? null));
|
|
554
|
+
report.merged++;
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
const incomingAt = stamp ? timestamp(row[stamp]) : Number.NEGATIVE_INFINITY;
|
|
558
|
+
const oldAt = stamp ? timestamp(old[stamp]) : Number.NEGATIVE_INFINITY;
|
|
559
|
+
const provenOlder = Number.isFinite(incomingAt) && Number.isFinite(oldAt) && oldAt > incomingAt;
|
|
560
|
+
const provenNewer = Number.isFinite(incomingAt) && Number.isFinite(oldAt) && incomingAt > oldAt;
|
|
561
|
+
if (!update || provenOlder)
|
|
562
|
+
return;
|
|
563
|
+
const different = updates.some((c) => {
|
|
564
|
+
const a = row[c] ?? null, b = old[c] ?? null;
|
|
565
|
+
return a instanceof Uint8Array && b instanceof Uint8Array
|
|
566
|
+
? !Buffer.from(a).equals(b)
|
|
567
|
+
: a !== b;
|
|
568
|
+
});
|
|
569
|
+
if (!different)
|
|
570
|
+
return;
|
|
571
|
+
if (!provenNewer && (!first || view !== views[0])) {
|
|
572
|
+
const version = `${table.name}\0${view}\0${rowKey(row, identity)}`;
|
|
573
|
+
if (!alternateVersions.has(version)) {
|
|
574
|
+
alternateVersions.add(version);
|
|
575
|
+
report.conflicts = (report.conflicts ?? 0) + 1;
|
|
576
|
+
recordRecovery(receipt, 'conflict', table.name, 'An alternate damaged view disagrees with the retained row; no timestamp proves it newer', row, source);
|
|
577
|
+
}
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
update.run(...updates.map((c) => row[c] ?? null), ...values);
|
|
581
|
+
report.merged++;
|
|
582
|
+
};
|
|
583
|
+
let complete = false;
|
|
584
|
+
try {
|
|
585
|
+
complete = readRows(snap.db, source, table, (row) => {
|
|
586
|
+
const key = rowKey(row, identity);
|
|
587
|
+
thisRead.add(key);
|
|
588
|
+
if (view === views[0]) {
|
|
589
|
+
const newest = newestKeys.get(table.name) ?? new Set();
|
|
590
|
+
newest.add(key);
|
|
591
|
+
newestKeys.set(table.name, newest);
|
|
592
|
+
}
|
|
593
|
+
const first = !seen.has(key);
|
|
594
|
+
if (first) {
|
|
595
|
+
seen.add(key);
|
|
596
|
+
report.salvaged++;
|
|
597
|
+
}
|
|
598
|
+
if (missing.length > 0 && first)
|
|
599
|
+
recordRecovery(receipt, 'unmerged-columns', table.name, `Columns outside the current schema: ${missing.join(', ')}`, row);
|
|
600
|
+
// A complete WAL view proves that an older main-only row was deleted.
|
|
601
|
+
if (authority.has(table.name) && !authority.get(table.name)?.has(key)) {
|
|
602
|
+
recordDeleted(table.name, row, identity, 'Readable only in an older main-only view; absent from the complete WAL view');
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
try {
|
|
606
|
+
apply(row, first);
|
|
607
|
+
}
|
|
608
|
+
catch {
|
|
609
|
+
pending.push(() => {
|
|
610
|
+
try {
|
|
611
|
+
apply(row, first);
|
|
612
|
+
}
|
|
613
|
+
catch (error) {
|
|
614
|
+
report.conflicts = (report.conflicts ?? 0) + 1;
|
|
615
|
+
recordRecovery(receipt, 'conflict', table.name, error instanceof Error ? error.message : String(error), row, source);
|
|
616
|
+
}
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
catch (error) {
|
|
622
|
+
receipt.diagnostics.push(`${table.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
623
|
+
}
|
|
624
|
+
if ((source === views[0] || source === `${views[0]}.header-recovered`) &&
|
|
625
|
+
complete &&
|
|
626
|
+
!incompleteSchema)
|
|
627
|
+
authority.set(table.name, thisRead);
|
|
628
|
+
if (!complete) {
|
|
629
|
+
report.unreadable = null;
|
|
630
|
+
receipt.diagnostics.push(`${table.name}: unreadable b-tree ranges; their row count is unknown`);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
finally {
|
|
635
|
+
snap.close();
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
for (const [name, base] of baseKeys) {
|
|
640
|
+
const table = tables(db, receipt.diagnostics, staged).find((t) => t.name === name);
|
|
641
|
+
if (!table)
|
|
642
|
+
continue;
|
|
643
|
+
const cols = columns(db, name);
|
|
644
|
+
let identity = cols
|
|
645
|
+
.filter((c) => c.pk > 0)
|
|
646
|
+
.sort((a, b) => a.pk - b.pk)
|
|
647
|
+
.map((c) => c.name);
|
|
648
|
+
if (identity.length === 0)
|
|
649
|
+
identity = hasRowid(table.sql) ? [ROWID] : cols.map((c) => c.name);
|
|
650
|
+
const current = db.prepare(`SELECT ${identity.includes(ROWID) ? `_rowid_ AS ${repairIdentifier(ROWID)}, ` : ''}* FROM main.${repairIdentifier(name)}`);
|
|
651
|
+
current.setReadBigInts(true);
|
|
652
|
+
const rows = current.all();
|
|
653
|
+
const authoritative = authority.get(name);
|
|
654
|
+
const report = reportFor(name);
|
|
655
|
+
for (const row of rows) {
|
|
656
|
+
const key = rowKey(row, identity);
|
|
657
|
+
if (authoritative ? authoritative.has(key) : newestKeys.get(name)?.has(key))
|
|
658
|
+
continue;
|
|
659
|
+
if (!base.has(key))
|
|
660
|
+
continue;
|
|
661
|
+
if (!authoritative) {
|
|
662
|
+
report.possiblyResurrected = (report.possiblyResurrected ?? 0) + 1;
|
|
663
|
+
recordRecovery(receipt, 'possibly-resurrected', name, 'Incomplete damaged read cannot prove this snapshot row was deleted', row);
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
const where = identity
|
|
667
|
+
.map((c) => `${repairIdentifier(c === ROWID ? '_rowid_' : c)} IS ?`)
|
|
668
|
+
.join(' AND ');
|
|
669
|
+
const del = db.prepare(`DELETE FROM main.${repairIdentifier(name)} WHERE ${where}`);
|
|
670
|
+
del.setReadBigInts(true);
|
|
671
|
+
del.run(...identity.map((c) => row[c] ?? null));
|
|
672
|
+
removeBase(name, row, identity);
|
|
673
|
+
recordDeleted(name, row, identity, 'Absent from a complete damaged view');
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
for (const retry of pending)
|
|
677
|
+
retry();
|
|
678
|
+
// Removing one orphan may expose a child orphan; converge with all actions disabled.
|
|
679
|
+
for (;;) {
|
|
680
|
+
const check = db.prepare('PRAGMA foreign_key_check');
|
|
681
|
+
check.setReadBigInts(true);
|
|
682
|
+
const violations = check.all();
|
|
683
|
+
if (violations.length === 0)
|
|
684
|
+
break;
|
|
685
|
+
let removed = 0;
|
|
686
|
+
for (const violation of violations) {
|
|
687
|
+
const name = String(violation.table);
|
|
688
|
+
const q = repairIdentifier(name);
|
|
689
|
+
const pk = columns(db, name)
|
|
690
|
+
.filter((c) => c.pk > 0)
|
|
691
|
+
.sort((a, b) => a.pk - b.pk)
|
|
692
|
+
.map((c) => c.name);
|
|
693
|
+
const identity = pk.length ? pk : [ROWID];
|
|
694
|
+
for (const row of orphanRows(db, violation)) {
|
|
695
|
+
recordRecovery(receipt, 'conflict', name, `Foreign key ${violation.fkid} references unreadable or absent ${violation.parent}`, row);
|
|
696
|
+
const report = reportFor(name);
|
|
697
|
+
report.conflicts = (report.conflicts ?? 0) + 1;
|
|
698
|
+
removeBase(name, row, identity);
|
|
699
|
+
const where = identity
|
|
700
|
+
.map((c) => `${repairIdentifier(c === ROWID ? '_rowid_' : c)} IS ?`)
|
|
701
|
+
.join(' AND ');
|
|
702
|
+
const del = db.prepare(`DELETE FROM main.${q} WHERE ${where}`);
|
|
703
|
+
del.setReadBigInts(true);
|
|
704
|
+
del.run(...identity.map((c) => row[c] ?? null));
|
|
705
|
+
removed++;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
if (removed === 0)
|
|
709
|
+
// @sync-invariant none:local-only unexpected foreign-key schema prevents a safe staged publication
|
|
710
|
+
throw new Error('Foreign-key violations could not be isolated to readable rows');
|
|
711
|
+
}
|
|
712
|
+
for (const table of virtual.values()) {
|
|
713
|
+
if (/\bUSING\s+fts[345]\b/i.test(table.sql) && /\bcontent\s*=/i.test(table.sql)) {
|
|
714
|
+
const q = repairIdentifier(table.name);
|
|
715
|
+
db.exec(`INSERT INTO main.${q} (${q}) VALUES ('rebuild')`);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
for (const trigger of originalTriggers)
|
|
719
|
+
if (typeof trigger.sql === 'string')
|
|
720
|
+
db.exec(trigger.sql);
|
|
721
|
+
});
|
|
722
|
+
db.exec('COMMIT');
|
|
723
|
+
}
|
|
724
|
+
catch (error) {
|
|
725
|
+
db.exec('ROLLBACK');
|
|
726
|
+
throw error;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
finally {
|
|
730
|
+
target.close();
|
|
731
|
+
}
|
|
732
|
+
return function mergeRecoveredJournal() {
|
|
733
|
+
if (journal.length === 0)
|
|
734
|
+
return;
|
|
735
|
+
const target = openCleoDbSnapshot(staged, {
|
|
736
|
+
readOnly: false,
|
|
737
|
+
applyPragmas: false,
|
|
738
|
+
loadSqliteVec: true,
|
|
739
|
+
});
|
|
740
|
+
try {
|
|
741
|
+
const names = columns(target.db, '__drizzle_migrations').map((c) => c.name);
|
|
742
|
+
const find = target.db.prepare('SELECT 1 FROM main.__drizzle_migrations WHERE id = ? OR hash = ?');
|
|
743
|
+
// gate-28: staged-snapshot mergeRecoveredJournal
|
|
744
|
+
const ins = target.db.prepare(`INSERT INTO main.__drizzle_migrations (${names.map(repairIdentifier).join(',')}) VALUES (${names.map(() => '?').join(',')})`);
|
|
745
|
+
ins.setReadBigInts(true);
|
|
746
|
+
for (const row of journal) {
|
|
747
|
+
if (find.get(row.id ?? null, row.hash ?? null))
|
|
748
|
+
continue;
|
|
749
|
+
try {
|
|
750
|
+
ins.run(...names.map((name) => row[name] ?? null));
|
|
751
|
+
const report = receipt.tables.__drizzle_migrations;
|
|
752
|
+
if (report)
|
|
753
|
+
report.merged++;
|
|
754
|
+
}
|
|
755
|
+
catch (error) {
|
|
756
|
+
recordRecovery(receipt, 'conflict', '__drizzle_migrations', error instanceof Error ? error.message : String(error), row);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
finally {
|
|
761
|
+
target.close();
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
//# sourceMappingURL=repair-store-salvage.js.map
|