opencode-github-sync 3.2.0 → 3.3.1
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/README.md +379 -160
- package/README.zh-CN.md +261 -101
- package/dist/cli/i18n.d.ts +10 -0
- package/dist/cli/i18n.d.ts.map +1 -1
- package/dist/cli/i18n.js +24 -4
- package/dist/cli/i18n.js.map +1 -1
- package/dist/cli/index.js +50 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/core/autosync.d.ts +2 -0
- package/dist/core/autosync.d.ts.map +1 -1
- package/dist/core/autosync.js +9 -0
- package/dist/core/autosync.js.map +1 -1
- package/dist/core/categories.js +1 -1
- package/dist/core/categories.js.map +1 -1
- package/dist/core/credentials.d.ts +40 -0
- package/dist/core/credentials.d.ts.map +1 -0
- package/dist/core/credentials.js +364 -0
- package/dist/core/credentials.js.map +1 -0
- package/dist/core/fsx.d.ts +2 -0
- package/dist/core/fsx.d.ts.map +1 -1
- package/dist/core/fsx.js +6 -0
- package/dist/core/fsx.js.map +1 -1
- package/dist/core/lease.d.ts +52 -0
- package/dist/core/lease.d.ts.map +1 -0
- package/dist/core/lease.js +235 -0
- package/dist/core/lease.js.map +1 -0
- package/dist/core/projects.d.ts +90 -0
- package/dist/core/projects.d.ts.map +1 -0
- package/dist/core/projects.js +225 -0
- package/dist/core/projects.js.map +1 -0
- package/dist/core/repair.d.ts +44 -0
- package/dist/core/repair.d.ts.map +1 -0
- package/dist/core/repair.js +81 -0
- package/dist/core/repair.js.map +1 -0
- package/dist/core/repo.d.ts +20 -2
- package/dist/core/repo.d.ts.map +1 -1
- package/dist/core/repo.js +65 -3
- package/dist/core/repo.js.map +1 -1
- package/dist/core/rows.d.ts +36 -0
- package/dist/core/rows.d.ts.map +1 -0
- package/dist/core/rows.js +75 -0
- package/dist/core/rows.js.map +1 -0
- package/dist/core/sessions.d.ts +34 -4
- package/dist/core/sessions.d.ts.map +1 -1
- package/dist/core/sessions.js +352 -104
- package/dist/core/sessions.js.map +1 -1
- package/dist/core/settings.d.ts +6 -0
- package/dist/core/settings.d.ts.map +1 -1
- package/dist/core/settings.js +1 -0
- package/dist/core/settings.js.map +1 -1
- package/dist/core/sqlite.d.ts +2 -0
- package/dist/core/sqlite.d.ts.map +1 -1
- package/dist/core/sqlite.js +14 -0
- package/dist/core/sqlite.js.map +1 -1
- package/dist/core/stage.d.ts +14 -1
- package/dist/core/stage.d.ts.map +1 -1
- package/dist/core/stage.js +63 -3
- package/dist/core/stage.js.map +1 -1
- package/dist/core/sync.d.ts.map +1 -1
- package/dist/core/sync.js +69 -16
- package/dist/core/sync.js.map +1 -1
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +2 -2
- package/dist/plugin/index.js.map +1 -1
- package/package.json +4 -4
package/dist/core/sessions.js
CHANGED
|
@@ -3,7 +3,9 @@ import path from "node:path";
|
|
|
3
3
|
import { gunzipSync, gzipSync } from "node:zlib";
|
|
4
4
|
import { ensureDir } from "./fsx.js";
|
|
5
5
|
import { SESSIONS_DIR } from "./paths.js";
|
|
6
|
-
import {
|
|
6
|
+
import { GLOBAL_PROJECT_ID, ProjectResolver, homeDir, storedPath, } from "./projects.js";
|
|
7
|
+
import { encodeRow, readRows, tableInfoCache, upsert } from "./rows.js";
|
|
8
|
+
import { existingTables, hasTable, openDatabase, tableColumns, } from "./sqlite.js";
|
|
7
9
|
/**
|
|
8
10
|
* Selective session sync.
|
|
9
11
|
*
|
|
@@ -28,8 +30,16 @@ import { existingTables, openDatabase, tableColumns, tablePrimaryKey, } from "./
|
|
|
28
30
|
*
|
|
29
31
|
* Import is an upsert inside a transaction, so a failure leaves the local
|
|
30
32
|
* database exactly as it was.
|
|
33
|
+
*
|
|
34
|
+
* Two database layouts exist. OpenCode 1 keeps sessions in `session` with
|
|
35
|
+
* `message`/`part`; OpenCode 2 keeps them in `session_v2` with
|
|
36
|
+
* `session_message`/`session_part` and never writes the old tables again (a
|
|
37
|
+
* fresh OpenCode 2 database does not even have them). The layout is detected
|
|
38
|
+
* per database: `session_v2` present means OpenCode 2. Each layout has its own
|
|
39
|
+
* shard format; a machine skips shards of the other one and never deletes them
|
|
40
|
+
* while they are inside the time window, so a mixed fleet keeps working.
|
|
31
41
|
*/
|
|
32
|
-
/**
|
|
42
|
+
/** OpenCode 1: tables whose rows belong to exactly one session. */
|
|
33
43
|
const SESSION_TABLES = [
|
|
34
44
|
"session_message",
|
|
35
45
|
"message",
|
|
@@ -39,8 +49,34 @@ const SESSION_TABLES = [
|
|
|
39
49
|
"session_context_epoch",
|
|
40
50
|
"session_input",
|
|
41
51
|
];
|
|
42
|
-
/**
|
|
43
|
-
|
|
52
|
+
/**
|
|
53
|
+
* OpenCode 2: tables whose rows belong to exactly one session, in insert
|
|
54
|
+
* order. `event_sequence` (keyed by `aggregate_id`) carries the session's
|
|
55
|
+
* message counter; without it a continued conversation restarts numbering and
|
|
56
|
+
* collides with its own history.
|
|
57
|
+
*
|
|
58
|
+
* Never exported: `session_inbox` (queued input would be delivered on the
|
|
59
|
+
* receiving machine), `job` and `schedule` (they would run there), `event`
|
|
60
|
+
* and `permission`.
|
|
61
|
+
*/
|
|
62
|
+
const V2_TABLES = [
|
|
63
|
+
"session_message",
|
|
64
|
+
"session_part",
|
|
65
|
+
"instruction_state",
|
|
66
|
+
"instruction_entry",
|
|
67
|
+
"blob_ref",
|
|
68
|
+
];
|
|
69
|
+
/**
|
|
70
|
+
* Columns describing what the session is doing right now on the machine that
|
|
71
|
+
* exported it. Copied as they are, they would make the receiving machine
|
|
72
|
+
* resume the conversation — and call a model — on its own.
|
|
73
|
+
*/
|
|
74
|
+
const V2_RUNTIME_COLUMNS = {
|
|
75
|
+
time_busy: null,
|
|
76
|
+
time_compacting: null,
|
|
77
|
+
time_suspended: null,
|
|
78
|
+
resume_attempts: 0,
|
|
79
|
+
};
|
|
44
80
|
function shardPath(repoRoot, sessionId) {
|
|
45
81
|
return path.join(repoRoot, SESSIONS_DIR, `${sanitizeId(sessionId)}.json.gz`);
|
|
46
82
|
}
|
|
@@ -48,8 +84,12 @@ function shardPath(repoRoot, sessionId) {
|
|
|
48
84
|
export function sanitizeId(id) {
|
|
49
85
|
return id.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
50
86
|
}
|
|
51
|
-
|
|
52
|
-
|
|
87
|
+
/** Which layout a database uses. */
|
|
88
|
+
export function sessionSchema(db) {
|
|
89
|
+
return hasTable(db, "session_v2") ? "v2" : "v1";
|
|
90
|
+
}
|
|
91
|
+
function sessionTable(schema) {
|
|
92
|
+
return schema === "v2" ? "session_v2" : "session";
|
|
53
93
|
}
|
|
54
94
|
/**
|
|
55
95
|
* Choose which sessions to export.
|
|
@@ -62,8 +102,8 @@ export function selectSessions(db, options) {
|
|
|
62
102
|
const now = options.now ?? Date.now();
|
|
63
103
|
const cutoff = now - options.days * 24 * 60 * 60 * 1000;
|
|
64
104
|
const rows = readRows(db, `SELECT id, title, directory, time_updated, time_created, project_id
|
|
65
|
-
FROM
|
|
66
|
-
ORDER BY time_updated DESC
|
|
105
|
+
FROM ${sessionTable(sessionSchema(db))}
|
|
106
|
+
ORDER BY time_updated DESC`);
|
|
67
107
|
const exclude = new Set(options.exclude);
|
|
68
108
|
const include = new Set(options.include);
|
|
69
109
|
const directories = options.directories.map((d) => path.resolve(d));
|
|
@@ -134,6 +174,81 @@ function buildShard(db, sessionId, tables) {
|
|
|
134
174
|
}
|
|
135
175
|
return shard;
|
|
136
176
|
}
|
|
177
|
+
const HASH = /^[0-9a-f]{64}$/;
|
|
178
|
+
/** Every instruction-blob hash a session's instruction rows refer to. */
|
|
179
|
+
function instructionHashes(rows) {
|
|
180
|
+
const found = new Set();
|
|
181
|
+
const visit = (value) => {
|
|
182
|
+
if (typeof value === "string") {
|
|
183
|
+
if (HASH.test(value))
|
|
184
|
+
found.add(value);
|
|
185
|
+
else if (value.startsWith("{") || value.startsWith("[")) {
|
|
186
|
+
try {
|
|
187
|
+
visit(JSON.parse(value));
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
// Not JSON — nothing to follow.
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
else if (Array.isArray(value)) {
|
|
195
|
+
for (const item of value)
|
|
196
|
+
visit(item);
|
|
197
|
+
}
|
|
198
|
+
else if (value && typeof value === "object") {
|
|
199
|
+
for (const item of Object.values(value))
|
|
200
|
+
visit(item);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
for (const row of rows)
|
|
204
|
+
for (const value of Object.values(row))
|
|
205
|
+
visit(value);
|
|
206
|
+
return [...found].sort();
|
|
207
|
+
}
|
|
208
|
+
function buildShardV2(db, sessionId, tables) {
|
|
209
|
+
const raw = readRows(db, "SELECT * FROM session_v2 WHERE id = ?", [sessionId])[0];
|
|
210
|
+
if (!raw)
|
|
211
|
+
throw new Error(`Session ${sessionId} disappeared while exporting`);
|
|
212
|
+
const session = { ...raw };
|
|
213
|
+
for (const [column, value] of Object.entries(V2_RUNTIME_COLUMNS)) {
|
|
214
|
+
if (column in session)
|
|
215
|
+
session[column] = value;
|
|
216
|
+
}
|
|
217
|
+
const shard = {
|
|
218
|
+
formatVersion: 2,
|
|
219
|
+
schema: "v2",
|
|
220
|
+
origin: { home: storedPath(homeDir()) },
|
|
221
|
+
session,
|
|
222
|
+
tables: {},
|
|
223
|
+
blobs: {},
|
|
224
|
+
exportedAt: Number(raw.time_updated ?? 0),
|
|
225
|
+
};
|
|
226
|
+
const projectId = raw.project_id;
|
|
227
|
+
if (projectId && projectId !== GLOBAL_PROJECT_ID) {
|
|
228
|
+
const project = readRows(db, "SELECT * FROM project WHERE id = ?", [projectId])[0];
|
|
229
|
+
if (project)
|
|
230
|
+
shard.project = project;
|
|
231
|
+
}
|
|
232
|
+
for (const table of tables) {
|
|
233
|
+
shard.tables[table] = readRows(db, `SELECT * FROM "${table}" WHERE session_id = ? ORDER BY rowid`, [sessionId]).map(encodeRow);
|
|
234
|
+
}
|
|
235
|
+
if (hasTable(db, "event_sequence")) {
|
|
236
|
+
shard.tables.event_sequence = readRows(db, "SELECT * FROM event_sequence WHERE aggregate_id = ?", [sessionId]).map((row) => ({ ...row, owner_id: null }));
|
|
237
|
+
}
|
|
238
|
+
const instructionRows = [
|
|
239
|
+
...(shard.tables.instruction_state ?? []),
|
|
240
|
+
...(shard.tables.instruction_entry ?? []),
|
|
241
|
+
];
|
|
242
|
+
const hashes = instructionHashes(instructionRows);
|
|
243
|
+
if (hashes.length > 0 && hasTable(db, "instruction_blob")) {
|
|
244
|
+
shard.blobs.instruction_blob = hashes.flatMap((hash) => readRows(db, "SELECT * FROM instruction_blob WHERE hash = ?", [hash]));
|
|
245
|
+
}
|
|
246
|
+
const blobHashes = [...new Set((shard.tables.blob_ref ?? []).map((r) => String(r.hash)))].sort();
|
|
247
|
+
if (blobHashes.length > 0 && hasTable(db, "blob")) {
|
|
248
|
+
shard.blobs.blob = blobHashes.flatMap((hash) => readRows(db, "SELECT * FROM blob WHERE hash = ?", [hash]).map(encodeRow));
|
|
249
|
+
}
|
|
250
|
+
return shard;
|
|
251
|
+
}
|
|
137
252
|
/** Export the selected sessions into `<repo>/_sessions`. */
|
|
138
253
|
export async function exportSessions(databaseFile, repoRoot, options, reporter) {
|
|
139
254
|
const result = { written: [], skippedTooLarge: [], considered: 0 };
|
|
@@ -141,14 +256,28 @@ export async function exportSessions(databaseFile, repoRoot, options, reporter)
|
|
|
141
256
|
return result;
|
|
142
257
|
const db = await openDatabase(databaseFile, { readOnly: true });
|
|
143
258
|
try {
|
|
144
|
-
const
|
|
259
|
+
const schema = sessionSchema(db);
|
|
260
|
+
const tables = schema === "v2"
|
|
261
|
+
? existingTables(db, [...V2_TABLES])
|
|
262
|
+
: existingTables(db, [...SESSION_TABLES]).filter((table) => tableColumns(db, table).includes("session_id"));
|
|
145
263
|
const sessions = selectSessions(db, options);
|
|
146
264
|
result.considered = sessions.length;
|
|
147
265
|
const outDir = path.join(repoRoot, SESSIONS_DIR);
|
|
148
266
|
ensureDir(outDir);
|
|
149
267
|
const keep = new Set();
|
|
150
268
|
for (const session of sessions) {
|
|
151
|
-
const
|
|
269
|
+
const file = shardPath(repoRoot, session.id);
|
|
270
|
+
// A shard that is already at least as new as this machine's copy stays
|
|
271
|
+
// as it is. It may differ in bytes only because another machine wrote it
|
|
272
|
+
// (its home, its placement); rewriting it would make every machine
|
|
273
|
+
// re-export every session it received, and could replace a newer copy
|
|
274
|
+
// this machine skipped on import with an older one.
|
|
275
|
+
if (existingShardTime(file) >= session.timeUpdated) {
|
|
276
|
+
keep.add(path.basename(file));
|
|
277
|
+
result.written.push(session.id);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
const shard = schema === "v2" ? buildShardV2(db, session.id, tables) : buildShard(db, session.id, tables);
|
|
152
281
|
const payload = gzipSync(Buffer.from(JSON.stringify(shard)), { level: 9 });
|
|
153
282
|
if (payload.byteLength > options.maxSessionBytes) {
|
|
154
283
|
result.skippedTooLarge.push({
|
|
@@ -158,7 +287,6 @@ export async function exportSessions(databaseFile, repoRoot, options, reporter)
|
|
|
158
287
|
});
|
|
159
288
|
continue;
|
|
160
289
|
}
|
|
161
|
-
const file = shardPath(repoRoot, session.id);
|
|
162
290
|
keep.add(path.basename(file));
|
|
163
291
|
// Only rewrite when the payload actually changed, otherwise every push
|
|
164
292
|
// would produce a diff for every session purely from the gzip timestamp.
|
|
@@ -167,7 +295,7 @@ export async function exportSessions(databaseFile, repoRoot, options, reporter)
|
|
|
167
295
|
}
|
|
168
296
|
result.written.push(session.id);
|
|
169
297
|
}
|
|
170
|
-
pruneShards(outDir, keep, options, reporter);
|
|
298
|
+
pruneShards(outDir, keep, schema, options, reporter);
|
|
171
299
|
}
|
|
172
300
|
finally {
|
|
173
301
|
db.close();
|
|
@@ -179,9 +307,12 @@ export async function exportSessions(databaseFile, repoRoot, options, reporter)
|
|
|
179
307
|
*
|
|
180
308
|
* A shard is removed when it is outside the retention window, so the repository
|
|
181
309
|
* does not accumulate every session ever synced. Shards for explicitly included
|
|
182
|
-
* sessions are always kept
|
|
310
|
+
* sessions are always kept, and so are recent shards of the other OpenCode
|
|
311
|
+
* major version: this machine cannot judge them, a machine still on that
|
|
312
|
+
* version exported them on purpose.
|
|
183
313
|
*/
|
|
184
|
-
function pruneShards(outDir, keep, options, reporter) {
|
|
314
|
+
function pruneShards(outDir, keep, schema, options, reporter) {
|
|
315
|
+
const cutoff = (options.now ?? Date.now()) - options.days * 24 * 60 * 60 * 1000;
|
|
185
316
|
let removed = 0;
|
|
186
317
|
const includeFiles = new Set(options.include.map((id) => `${sanitizeId(id)}.json.gz`));
|
|
187
318
|
for (const entry of fs.readdirSync(outDir)) {
|
|
@@ -189,68 +320,63 @@ function pruneShards(outDir, keep, options, reporter) {
|
|
|
189
320
|
continue;
|
|
190
321
|
if (keep.has(entry) || includeFiles.has(entry))
|
|
191
322
|
continue;
|
|
192
|
-
|
|
323
|
+
const full = path.join(outDir, entry);
|
|
324
|
+
const other = otherSchemaShard(full, schema);
|
|
325
|
+
if (other && Number(other.session.time_updated ?? 0) >= cutoff)
|
|
326
|
+
continue;
|
|
327
|
+
fs.rmSync(full, { force: true });
|
|
193
328
|
removed++;
|
|
194
329
|
}
|
|
195
330
|
if (removed > 0)
|
|
196
331
|
reporter.detail(`Removed ${removed} session shard(s) outside the retention window`);
|
|
197
332
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
333
|
+
/** `time_updated` of the session in an existing shard file, or -1 when there is none. */
|
|
334
|
+
function existingShardTime(file) {
|
|
335
|
+
if (!fs.existsSync(file))
|
|
336
|
+
return -1;
|
|
337
|
+
try {
|
|
338
|
+
return Number(parseShard(file).session.time_updated ?? -1);
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
return -1;
|
|
203
342
|
}
|
|
204
|
-
return shard;
|
|
205
343
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
* imported before it (#2).
|
|
214
|
-
*
|
|
215
|
-
* Primary-key columns are never rewritten, so composite keys such as
|
|
216
|
-
* `todo (session_id, position)` stay intact. A row that is newer locally, by
|
|
217
|
-
* `time_updated`, is left alone. `keepExisting` turns the update into a no-op
|
|
218
|
-
* for rows that must stay machine-local once they exist.
|
|
219
|
-
*/
|
|
220
|
-
function upsert(db, table, row, info, keepExisting = false) {
|
|
221
|
-
const columns = Object.keys(row).filter((column) => info.columns.has(column));
|
|
222
|
-
if (columns.length === 0)
|
|
223
|
-
return;
|
|
224
|
-
const placeholders = columns.map(() => "?").join(", ");
|
|
225
|
-
const quoted = columns.map((column) => `"${column}"`).join(", ");
|
|
226
|
-
// No conflict target: the update applies to whichever uniqueness constraint
|
|
227
|
-
// fired (primary key, composite key or a secondary UNIQUE index), matching
|
|
228
|
-
// what REPLACE used to cover. Needs SQLite 3.35+, which both drivers bundle.
|
|
229
|
-
const updates = columns.filter((column) => !info.primaryKey.includes(column));
|
|
230
|
-
let action = "DO NOTHING";
|
|
231
|
-
if (!keepExisting && updates.length > 0) {
|
|
232
|
-
const assignments = updates.map((column) => `"${column}" = excluded."${column}"`).join(", ");
|
|
233
|
-
const newerWins = columns.includes("time_updated")
|
|
234
|
-
? ` WHERE "${table}"."time_updated" IS NULL OR excluded."time_updated" >= "${table}"."time_updated"`
|
|
235
|
-
: "";
|
|
236
|
-
action = `DO UPDATE SET ${assignments}${newerWins}`;
|
|
344
|
+
function otherSchemaShard(file, schema) {
|
|
345
|
+
try {
|
|
346
|
+
const shard = parseShard(file);
|
|
347
|
+
return shardSchema(shard) === schema ? undefined : shard;
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
return undefined;
|
|
237
351
|
}
|
|
238
|
-
db.prepare(`INSERT INTO "${table}" (${quoted}) VALUES (${placeholders}) ON CONFLICT ${action}`).run(...columns.map((column) => normalize(row[column])));
|
|
239
352
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
353
|
+
function parseShard(file) {
|
|
354
|
+
const raw = gunzipSync(fs.readFileSync(file));
|
|
355
|
+
return JSON.parse(raw.toString("utf8"));
|
|
356
|
+
}
|
|
357
|
+
function shardSchema(shard) {
|
|
358
|
+
if (shard.formatVersion === 1)
|
|
359
|
+
return "v1";
|
|
360
|
+
if (shard.formatVersion === 2 && shard.schema === "v2")
|
|
361
|
+
return "v2";
|
|
362
|
+
return undefined;
|
|
363
|
+
}
|
|
364
|
+
function readShard(file) {
|
|
365
|
+
const shard = parseShard(file);
|
|
366
|
+
if (!shardSchema(shard)) {
|
|
367
|
+
throw new Error(`Unsupported shard format v${shard.formatVersion}`);
|
|
248
368
|
}
|
|
249
|
-
return
|
|
369
|
+
return shard;
|
|
250
370
|
}
|
|
251
371
|
/** Import every shard from `<repo>/_sessions` into the local database. */
|
|
252
|
-
export async function importSessions(databaseFile, repoRoot, reporter) {
|
|
253
|
-
const result = {
|
|
372
|
+
export async function importSessions(databaseFile, repoRoot, reporter, options = {}) {
|
|
373
|
+
const result = {
|
|
374
|
+
imported: 0,
|
|
375
|
+
skippedOlder: 0,
|
|
376
|
+
moved: 0,
|
|
377
|
+
skippedOtherSchema: 0,
|
|
378
|
+
failed: [],
|
|
379
|
+
};
|
|
254
380
|
const shardDir = path.join(repoRoot, SESSIONS_DIR);
|
|
255
381
|
if (!fs.existsSync(shardDir))
|
|
256
382
|
return result;
|
|
@@ -263,62 +389,56 @@ export async function importSessions(databaseFile, repoRoot, reporter) {
|
|
|
263
389
|
}
|
|
264
390
|
const db = await openDatabase(databaseFile);
|
|
265
391
|
try {
|
|
266
|
-
const
|
|
267
|
-
const columns = (
|
|
268
|
-
|
|
269
|
-
if (!info) {
|
|
270
|
-
info = {
|
|
271
|
-
columns: new Set(tableColumns(db, table)),
|
|
272
|
-
primaryKey: tablePrimaryKey(db, table),
|
|
273
|
-
};
|
|
274
|
-
infoFor.set(table, info);
|
|
275
|
-
}
|
|
276
|
-
return info;
|
|
277
|
-
};
|
|
392
|
+
const schema = sessionSchema(db);
|
|
393
|
+
const columns = tableInfoCache(db);
|
|
394
|
+
const table = sessionTable(schema);
|
|
278
395
|
const localTimes = new Map();
|
|
279
|
-
|
|
396
|
+
const localBusy = new Set();
|
|
397
|
+
const busyColumn = schema === "v2" && columns(table).columns.has("time_busy");
|
|
398
|
+
for (const row of readRows(db, `SELECT id, time_updated${busyColumn ? ", time_busy" : ""} FROM ${table}`)) {
|
|
280
399
|
localTimes.set(String(row.id), Number(row.time_updated ?? 0));
|
|
400
|
+
if (row.time_busy != null)
|
|
401
|
+
localBusy.add(String(row.id));
|
|
281
402
|
}
|
|
403
|
+
const resolver = schema === "v2"
|
|
404
|
+
? new ProjectResolver(db, {
|
|
405
|
+
home: options.home ?? homeDir(),
|
|
406
|
+
createProjects: true,
|
|
407
|
+
now: options.now ?? Date.now(),
|
|
408
|
+
})
|
|
409
|
+
: undefined;
|
|
282
410
|
for (const file of files) {
|
|
283
411
|
const full = path.join(shardDir, file);
|
|
284
412
|
try {
|
|
285
413
|
const shard = readShard(full);
|
|
414
|
+
if (shardSchema(shard) !== schema) {
|
|
415
|
+
result.skippedOtherSchema++;
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
286
418
|
const sessionId = String(shard.session.id);
|
|
287
419
|
const incoming = Number(shard.session.time_updated ?? 0);
|
|
288
420
|
const local = localTimes.get(sessionId);
|
|
289
421
|
// Last-writer-wins at session granularity. A session that is newer
|
|
290
|
-
// locally is left completely alone, so an
|
|
291
|
-
// never clobbered by a stale copy
|
|
292
|
-
if (local !== undefined && local >= incoming) {
|
|
422
|
+
// locally — or running right now — is left completely alone, so an
|
|
423
|
+
// in-progress conversation is never clobbered by a stale copy.
|
|
424
|
+
if ((local !== undefined && local >= incoming) || localBusy.has(sessionId)) {
|
|
425
|
+
if (schema === "v2" && !localBusy.has(sessionId)) {
|
|
426
|
+
if (unpark(db, shard, resolver))
|
|
427
|
+
result.moved++;
|
|
428
|
+
}
|
|
293
429
|
result.skippedOlder++;
|
|
294
430
|
continue;
|
|
295
431
|
}
|
|
296
432
|
db.exec("BEGIN IMMEDIATE");
|
|
297
433
|
try {
|
|
298
|
-
if (
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
upsert(db, "project", shard.project, columns("project"), local);
|
|
434
|
+
if (schema === "v2") {
|
|
435
|
+
importShardV2(db, shard, columns, resolver, local !== undefined, {
|
|
436
|
+
recoveryRoot: options.recoveryRoot,
|
|
437
|
+
file,
|
|
438
|
+
});
|
|
304
439
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
upsert(db, "session", shard.session, columns("session"));
|
|
308
|
-
for (const [table, rows] of Object.entries(shard.tables)) {
|
|
309
|
-
if (rows.length === 0)
|
|
310
|
-
continue;
|
|
311
|
-
let allowed;
|
|
312
|
-
try {
|
|
313
|
-
allowed = columns(table);
|
|
314
|
-
}
|
|
315
|
-
catch {
|
|
316
|
-
continue; // Table does not exist in this OpenCode version.
|
|
317
|
-
}
|
|
318
|
-
if (allowed.columns.size === 0)
|
|
319
|
-
continue;
|
|
320
|
-
for (const row of rows)
|
|
321
|
-
upsert(db, table, row, allowed);
|
|
440
|
+
else {
|
|
441
|
+
importShardV1(db, shard, columns);
|
|
322
442
|
}
|
|
323
443
|
db.exec("COMMIT");
|
|
324
444
|
result.imported++;
|
|
@@ -338,6 +458,134 @@ export async function importSessions(databaseFile, repoRoot, reporter) {
|
|
|
338
458
|
}
|
|
339
459
|
return result;
|
|
340
460
|
}
|
|
461
|
+
function importShardV1(db, shard, columns) {
|
|
462
|
+
if (shard.project) {
|
|
463
|
+
// Shards written before #4 still carry the synthetic global project.
|
|
464
|
+
// Create it if missing, but never overwrite this machine's own row.
|
|
465
|
+
const local = String(shard.project.id) === GLOBAL_PROJECT_ID;
|
|
466
|
+
upsert(db, "project", shard.project, columns("project"), local);
|
|
467
|
+
}
|
|
468
|
+
if (shard.workspace)
|
|
469
|
+
upsert(db, "workspace", shard.workspace, columns("workspace"));
|
|
470
|
+
upsert(db, "session", shard.session, columns("session"));
|
|
471
|
+
for (const [table, rows] of Object.entries(shard.tables)) {
|
|
472
|
+
if (rows.length === 0)
|
|
473
|
+
continue;
|
|
474
|
+
if (!hasTable(db, table))
|
|
475
|
+
continue; // Table does not exist in this OpenCode version.
|
|
476
|
+
const allowed = columns(table);
|
|
477
|
+
if (allowed.columns.size === 0)
|
|
478
|
+
continue;
|
|
479
|
+
for (const row of rows)
|
|
480
|
+
upsert(db, table, row, allowed);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
/** Child rows of one session, in an order that satisfies the foreign keys. */
|
|
484
|
+
function v2ChildTables(db) {
|
|
485
|
+
return existingTables(db, [...V2_TABLES]);
|
|
486
|
+
}
|
|
487
|
+
function deleteV2Children(db, sessionId) {
|
|
488
|
+
// session_part cascades from session_message; the rest are deleted directly.
|
|
489
|
+
for (const table of [...v2ChildTables(db)].reverse()) {
|
|
490
|
+
db.prepare(`DELETE FROM "${table}" WHERE session_id = ?`).run(sessionId);
|
|
491
|
+
}
|
|
492
|
+
if (hasTable(db, "event_sequence")) {
|
|
493
|
+
db.prepare("DELETE FROM event_sequence WHERE aggregate_id = ?").run(sessionId);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Save the local copy of a session that an incoming one is about to replace,
|
|
498
|
+
* when the local copy has messages the incoming one lacks — the conversation
|
|
499
|
+
* was continued on both machines. Nothing is lost, the newer copy still wins.
|
|
500
|
+
*/
|
|
501
|
+
function saveDivergedLocal(db, shard, recoveryRoot, file) {
|
|
502
|
+
if (!recoveryRoot)
|
|
503
|
+
return;
|
|
504
|
+
const sessionId = String(shard.session.id);
|
|
505
|
+
const incoming = new Set((shard.tables.session_message ?? []).map((r) => String(r.id)));
|
|
506
|
+
const localIds = readRows(db, "SELECT id FROM session_message WHERE session_id = ?", [
|
|
507
|
+
sessionId,
|
|
508
|
+
]).map((r) => String(r.id));
|
|
509
|
+
if (localIds.every((id) => incoming.has(id)))
|
|
510
|
+
return;
|
|
511
|
+
const local = buildShardV2(db, sessionId, v2ChildTables(db));
|
|
512
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-").replace("Z", "");
|
|
513
|
+
const dir = path.join(recoveryRoot, `${stamp}-session-conflict`);
|
|
514
|
+
ensureDir(dir);
|
|
515
|
+
fs.writeFileSync(path.join(dir, file), gzipSync(Buffer.from(JSON.stringify(local))));
|
|
516
|
+
}
|
|
517
|
+
function importShardV2(db, shard, columns, resolver, existsLocally, context) {
|
|
518
|
+
const sessionId = String(shard.session.id);
|
|
519
|
+
resolver.adopt(shard.project, (row) => upsert(db, "project", { ...row, time_archived: null }, columns("project"), true));
|
|
520
|
+
const placement = resolver.place({
|
|
521
|
+
directory: String(shard.session.directory ?? ""),
|
|
522
|
+
projectId: String(shard.session.project_id ?? ""),
|
|
523
|
+
path: shard.session.path == null ? null : String(shard.session.path),
|
|
524
|
+
originHome: shard.origin?.home,
|
|
525
|
+
});
|
|
526
|
+
// `place` may have created a project row.
|
|
527
|
+
if (!hasRow(db, "project", placement.projectId)) {
|
|
528
|
+
throw new Error(`no project for ${String(shard.session.directory)} on this machine`);
|
|
529
|
+
}
|
|
530
|
+
if (existsLocally) {
|
|
531
|
+
saveDivergedLocal(db, shard, context.recoveryRoot, context.file);
|
|
532
|
+
deleteV2Children(db, sessionId);
|
|
533
|
+
}
|
|
534
|
+
const session = {
|
|
535
|
+
...shard.session,
|
|
536
|
+
project_id: placement.projectId,
|
|
537
|
+
directory: placement.directory,
|
|
538
|
+
path: placement.path,
|
|
539
|
+
// Workspaces describe this machine's remote environments; a foreign id
|
|
540
|
+
// would point at nothing here.
|
|
541
|
+
workspace_id: null,
|
|
542
|
+
};
|
|
543
|
+
upsert(db, "session_v2", session, columns("session_v2"));
|
|
544
|
+
for (const [table, rows] of Object.entries(shard.blobs ?? {})) {
|
|
545
|
+
if (rows.length === 0 || !hasTable(db, table))
|
|
546
|
+
continue;
|
|
547
|
+
// Content-addressed: an existing row with the same hash is identical.
|
|
548
|
+
for (const row of rows)
|
|
549
|
+
upsert(db, table, row, columns(table), true);
|
|
550
|
+
}
|
|
551
|
+
for (const table of [...v2ChildTables(db), "event_sequence"]) {
|
|
552
|
+
const rows = shard.tables[table] ?? [];
|
|
553
|
+
if (rows.length === 0 || !hasTable(db, table))
|
|
554
|
+
continue;
|
|
555
|
+
const info = columns(table);
|
|
556
|
+
for (const row of rows)
|
|
557
|
+
upsert(db, table, row, info);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
function hasRow(db, table, id) {
|
|
561
|
+
return readRows(db, `SELECT 1 AS x FROM "${table}" WHERE id = ?`, [id]).length > 0;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Move a session that an earlier import parked in the home project into its
|
|
565
|
+
* own project, once this machine has one: the repository was cloned or opened
|
|
566
|
+
* here after the session arrived. Nothing but the session's location changes.
|
|
567
|
+
*/
|
|
568
|
+
function unpark(db, shard, resolver) {
|
|
569
|
+
const sessionId = String(shard.session.id);
|
|
570
|
+
const local = readRows(db, "SELECT project_id FROM session_v2 WHERE id = ?", [sessionId])[0];
|
|
571
|
+
const home = resolver.homeProjectId();
|
|
572
|
+
if (!local || !home || String(local.project_id) !== home)
|
|
573
|
+
return false;
|
|
574
|
+
if (String(shard.session.project_id ?? "") === home)
|
|
575
|
+
return false;
|
|
576
|
+
const placement = resolver.place({
|
|
577
|
+
directory: String(shard.session.directory ?? ""),
|
|
578
|
+
projectId: String(shard.session.project_id ?? ""),
|
|
579
|
+
path: shard.session.path == null ? null : String(shard.session.path),
|
|
580
|
+
originHome: shard.origin?.home,
|
|
581
|
+
});
|
|
582
|
+
if (placement.parked || placement.projectId === home)
|
|
583
|
+
return false;
|
|
584
|
+
if (!hasRow(db, "project", placement.projectId))
|
|
585
|
+
return false;
|
|
586
|
+
db.prepare("UPDATE session_v2 SET project_id = ?, directory = ?, path = ? WHERE id = ?").run(placement.projectId, placement.directory, placement.path, sessionId);
|
|
587
|
+
return true;
|
|
588
|
+
}
|
|
341
589
|
/** List sessions available locally, newest first — powers `sessions list`. */
|
|
342
590
|
export async function listSessions(databaseFile, limit) {
|
|
343
591
|
if (!fs.existsSync(databaseFile))
|
|
@@ -345,7 +593,7 @@ export async function listSessions(databaseFile, limit) {
|
|
|
345
593
|
const db = await openDatabase(databaseFile, { readOnly: true });
|
|
346
594
|
try {
|
|
347
595
|
const rows = readRows(db, `SELECT id, title, directory, time_updated, time_created, project_id
|
|
348
|
-
FROM
|
|
596
|
+
FROM ${sessionTable(sessionSchema(db))} ORDER BY time_updated DESC LIMIT ?`, [limit]);
|
|
349
597
|
return rows.map((row) => ({
|
|
350
598
|
id: String(row.id),
|
|
351
599
|
title: String(row.title ?? ""),
|