sourceServerWorkspaceAliasRepo.test.ts 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  1. import { createHash } from "node:crypto";
  2. import { DatabaseSync } from "node:sqlite";
  3. import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { describe, expect, it, vi } from "vitest";
  7. import { getWorkspaceHash } from "#src/paths.js";
  8. import { TaskIndexRepo } from "#src/session/taskIndexRepo.js";
  9. import { SourceServerWorkspaceAliasRepo } from "#src/session/sourceServerWorkspaceAliasRepo.js";
  10. async function createTaskDb(path: string): Promise<DatabaseSync> {
  11. // 使用正式索引 schema,避免精简夹具漏掉搜索、未读与模型等持久化投影列。
  12. const index = new TaskIndexRepo(undefined, undefined, path);
  13. try {
  14. await index.ensureReady();
  15. } finally {
  16. index.close();
  17. }
  18. return new DatabaseSync(path);
  19. }
  20. function createSessionDb(path: string): DatabaseSync {
  21. const db = new DatabaseSync(path);
  22. db.exec(`
  23. CREATE TABLE session (
  24. id TEXT PRIMARY KEY,
  25. workspace_id TEXT,
  26. directory TEXT NOT NULL,
  27. path TEXT,
  28. time_updated INTEGER NOT NULL
  29. );
  30. `);
  31. return db;
  32. }
  33. describe("Source Server workspace canonical alias", () => {
  34. it.each([
  35. ["task-merge", "full"],
  36. ["session-merge", "full"],
  37. ["task-merge", "rollback"],
  38. ["session-merge", "rollback"],
  39. ["task-conflict", "rollback"],
  40. ["config-conflict", "rollback"],
  41. ["abandon", "rollback"],
  42. ] as const)("%s preserves the original SQLite error after %s", async (stage, failure) => {
  43. const root = await mkdtemp(join(tmpdir(), "zcode-alias-full-"));
  44. const taskDbPath = join(root, "tasks-index.sqlite");
  45. const sessionDbPath = join(root, "db.sqlite");
  46. const workspacePath = "/repo";
  47. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  48. const sourceKey = "remote:ssh:source:22:user:/repo";
  49. (await createTaskDb(taskDbPath)).close();
  50. createSessionDb(sessionDbPath).close();
  51. const repo = new SourceServerWorkspaceAliasRepo({
  52. taskDbPath,
  53. sessionDbPath,
  54. backupRoot: join(root, "backups"),
  55. migrationId: () => "full-migration",
  56. });
  57. await repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: canonicalKey });
  58. const taskDb = new DatabaseSync(taskDbPath);
  59. const sessionDb = new DatabaseSync(sessionDbPath);
  60. const insert = taskDb.prepare(`INSERT INTO tasks
  61. (workspace_key, workspace_path, task_id, title, created_at, updated_at, meta_json)
  62. VALUES (?, '/repo', ?, 'Task', 1, ?, ?)`);
  63. insert.run(canonicalKey, "task-c", 20, JSON.stringify({ cronAutomationId: "cron-c" }));
  64. insert.run(
  65. sourceKey,
  66. stage === "task-conflict" ? "task-c" : "task-s",
  67. 10,
  68. JSON.stringify({ cronAutomationId: "cron-s" }),
  69. );
  70. sessionDb
  71. .prepare("INSERT INTO session VALUES ('session-s', ?, '/repo', '/repo', 10)")
  72. .run(sourceKey);
  73. if (stage === "config-conflict") {
  74. for (const key of [canonicalKey, sourceKey]) {
  75. const dir = join(root, "sessions", getWorkspaceHash(workspacePath, key));
  76. await mkdir(dir, { recursive: true });
  77. await writeFile(join(dir, "state.json"), key);
  78. }
  79. }
  80. if (stage === "abandon") {
  81. taskDb
  82. .prepare(`INSERT INTO workspace_migration_ledger
  83. (migration_id, path, canonical_key, variant_keys_json, status, phase,
  84. task_backup_path, created_at, updated_at)
  85. VALUES ('full-migration', '/repo', ?, ?, 'failed', NULL, '', 1, 1)`)
  86. .run(canonicalKey, JSON.stringify([canonicalKey, sourceKey]));
  87. }
  88. const failingDb = stage === "session-merge" ? sessionDb : taskDb;
  89. const trigger =
  90. stage === "task-merge"
  91. ? "UPDATE OF workspace_key ON tasks"
  92. : stage === "session-merge"
  93. ? "UPDATE OF workspace_id ON session"
  94. : stage === "abandon"
  95. ? "UPDATE OF status ON workspace_migration_ledger WHEN NEW.status = 'abandoned'"
  96. : "INSERT ON workspace_migration_conflicts";
  97. failingDb.exec(`CREATE TABLE test_full_payload (payload BLOB);
  98. CREATE TRIGGER exhaust_pages BEFORE ${trigger}
  99. BEGIN
  100. SELECT mark_full_attempt();
  101. ${
  102. failure === "full"
  103. ? "INSERT INTO test_full_payload VALUES (zeroblob(1048576));"
  104. : "SELECT RAISE(ROLLBACK, 'original transaction failure');"
  105. }
  106. END;`);
  107. taskDb.close();
  108. sessionDb.close();
  109. let attempts = 0;
  110. const exec = DatabaseSync.prototype.exec;
  111. // 在真实 SQLite 边界制造 FULL 或自动回滚;FULL 是否回滚取决于 SQLite 的失败位置。
  112. const fault = vi.spyOn(DatabaseSync.prototype, "exec").mockImplementation(function (
  113. this: DatabaseSync,
  114. sql: string,
  115. ) {
  116. if (
  117. sql === "BEGIN IMMEDIATE" &&
  118. this.prepare("SELECT 1 FROM sqlite_master WHERE name = 'test_full_payload'").get()
  119. ) {
  120. this.function("mark_full_attempt", () => {
  121. attempts += 1;
  122. return 1;
  123. });
  124. const pages = this.prepare("PRAGMA page_count").get()!.page_count;
  125. exec.call(this, `PRAGMA max_page_count = ${pages}`);
  126. }
  127. return exec.call(this, sql);
  128. });
  129. try {
  130. await expect(
  131. stage === "abandon"
  132. ? repo.abandonFailedWorkspace(workspacePath)
  133. : repo.resolveCanonicalWorkspaceKey({ workspacePath }),
  134. ).rejects.toMatchObject(
  135. failure === "full"
  136. ? { errcode: 13, message: "database or disk is full" }
  137. : { errcode: 1811, message: "original transaction failure" },
  138. );
  139. expect(attempts).toBe(1);
  140. } finally {
  141. fault.mockRestore();
  142. await rm(root, { recursive: true, force: true });
  143. }
  144. });
  145. it.each(["completed", "running", "phase", "canonical", "variants", "deleted"] as const)(
  146. "rejects abandon when %s changes before the write transaction without overwriting the winner",
  147. async (change) => {
  148. const root = await mkdtemp(join(tmpdir(), "zcode-abandon-race-"));
  149. const taskDbPath = join(root, "tasks-index.sqlite");
  150. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  151. const sourceKey = "remote:ssh:source:22:user:/repo";
  152. (await createTaskDb(taskDbPath)).close();
  153. let concurrentWrite: (() => void) | undefined;
  154. const repo = new SourceServerWorkspaceAliasRepo({
  155. taskDbPath,
  156. sessionDbPath: join(root, "missing.sqlite"),
  157. now: () => {
  158. const write = concurrentWrite;
  159. concurrentWrite = undefined;
  160. write?.();
  161. return 10;
  162. },
  163. });
  164. await repo.listMigrationReports();
  165. const db = new DatabaseSync(taskDbPath);
  166. try {
  167. db.prepare(`INSERT INTO workspace_migration_ledger
  168. (migration_id, path, canonical_key, variant_keys_json, status, phase,
  169. task_backup_path, created_at, updated_at)
  170. VALUES ('abandon-race', '/repo', ?, ?, 'failed', NULL, '', 10, 10)`).run(
  171. canonicalKey,
  172. JSON.stringify([canonicalKey, sourceKey]),
  173. );
  174. db.prepare("INSERT INTO workspace_alias VALUES ('/repo', ?, 10, 10)").run(canonicalKey);
  175. let winner;
  176. // now 在配置 IO 完成后、写事务前读取;由另一数据库连接提交并发写,时间戳保持相同。
  177. concurrentWrite = () => {
  178. if (change === "deleted") db.exec("DELETE FROM workspace_migration_ledger");
  179. else if (change === "completed" || change === "running")
  180. db.prepare("UPDATE workspace_migration_ledger SET status = ?").run(change);
  181. else if (change === "phase")
  182. db.exec("UPDATE workspace_migration_ledger SET phase = 'backups-created'");
  183. else if (change === "canonical")
  184. db.prepare("UPDATE workspace_migration_ledger SET canonical_key = ?").run(sourceKey);
  185. else
  186. db.prepare("UPDATE workspace_migration_ledger SET variant_keys_json = ?").run(
  187. JSON.stringify([canonicalKey, sourceKey, "remote:docker:third:/repo"]),
  188. );
  189. db.prepare("UPDATE workspace_alias SET canonical_key = ?").run(sourceKey);
  190. winner = db.prepare("SELECT * FROM workspace_migration_ledger").all();
  191. };
  192. await expect(repo.abandonFailedWorkspace("/repo", "abandon-race")).rejects.toMatchObject({
  193. retryable: true,
  194. });
  195. expect(concurrentWrite).toBeUndefined();
  196. expect(db.prepare("SELECT * FROM workspace_migration_ledger").all()).toEqual(winner);
  197. expect(db.prepare("SELECT canonical_key FROM workspace_alias").get()).toEqual({
  198. canonical_key: sourceKey,
  199. });
  200. } finally {
  201. db.close();
  202. await rm(root, { recursive: true, force: true });
  203. }
  204. },
  205. );
  206. it("uses the legacy digest algorithm for unversioned abandoned baselines", async () => {
  207. const root = await mkdtemp(join(tmpdir(), "zcode-r3-abandoned-digest-v1-"));
  208. const taskDbPath = join(root, "tasks-index.sqlite");
  209. (await createTaskDb(taskDbPath)).close();
  210. const repo = new SourceServerWorkspaceAliasRepo({
  211. taskDbPath,
  212. sessionDbPath: join(root, "missing.sqlite"),
  213. });
  214. await repo.listMigrationReports();
  215. const legacyDigest = createHash("sha256");
  216. for (const table of [
  217. "tasks",
  218. "task_group_members",
  219. "task_group_view_node_orders",
  220. "automations",
  221. "automation_runs",
  222. "off_peak_tasks",
  223. ]) {
  224. legacyDigest.update(table);
  225. legacyDigest.update("[]");
  226. }
  227. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  228. const sourceKey = "remote:ssh:source:22:user:/repo";
  229. const db = new DatabaseSync(taskDbPath);
  230. db.prepare(`INSERT INTO workspace_migration_ledger (
  231. migration_id, path, canonical_key, variant_keys_json, status, phase,
  232. task_backup_path, session_backup_path, error, created_at, updated_at,
  233. abandoned_at, abandoned_trigger, abandoned_activity_json
  234. ) VALUES ('legacy-abandoned', '/repo', ?, ?, 'abandoned', NULL,
  235. '', NULL, NULL, 1, 1, 1, 'user', ?)`).run(
  236. canonicalKey,
  237. JSON.stringify([canonicalKey, sourceKey]),
  238. JSON.stringify({ [sourceKey]: legacyDigest.digest("hex") }),
  239. );
  240. db.close();
  241. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  242. rows: [expect.objectContaining({ migrationId: "legacy-abandoned", status: "abandoned" })],
  243. });
  244. });
  245. it("captures task writes committed by the abandon transaction in its digest baseline", async () => {
  246. const root = await mkdtemp(join(tmpdir(), "zcode-r3-abandon-digest-transaction-"));
  247. const taskDbPath = join(root, "tasks-index.sqlite");
  248. (await createTaskDb(taskDbPath)).close();
  249. const repo = new SourceServerWorkspaceAliasRepo({
  250. taskDbPath,
  251. sessionDbPath: join(root, "missing.sqlite"),
  252. now: () => 10,
  253. });
  254. await repo.listMigrationReports();
  255. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  256. const sourceKey = "remote:ssh:source:22:user:/repo";
  257. const db = new DatabaseSync(taskDbPath);
  258. db.prepare(`INSERT INTO workspace_migration_ledger (
  259. migration_id, path, canonical_key, variant_keys_json, status, phase,
  260. task_backup_path, session_backup_path, error, created_at, updated_at
  261. ) VALUES ('abandon-trigger', '/repo', ?, ?, 'failed', NULL,
  262. '', NULL, 'workspace-task-identity-conflict', 1, 1)`).run(
  263. canonicalKey,
  264. JSON.stringify([canonicalKey, sourceKey]),
  265. );
  266. db.exec(`
  267. CREATE TRIGGER add_task_during_abandon
  268. BEFORE UPDATE OF status ON workspace_migration_ledger
  269. WHEN NEW.status = 'abandoned'
  270. BEGIN
  271. INSERT INTO tasks (
  272. workspace_key, workspace_path, workspace_identity, task_id, title,
  273. created_at, updated_at
  274. ) VALUES (
  275. '${sourceKey}', '/repo', '${sourceKey}', 'trigger-task', 'trigger', 1, 2
  276. );
  277. END;
  278. `);
  279. db.close();
  280. await repo.abandonFailedWorkspace("/repo", "abandon-trigger");
  281. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  282. rows: [expect.objectContaining({ migrationId: "abandon-trigger", status: "abandoned" })],
  283. });
  284. });
  285. it("counts only the latest path state and exposes migration recovery metadata", async () => {
  286. const root = await mkdtemp(join(tmpdir(), "zcode-r3-migration-report-metadata-"));
  287. const taskDbPath = join(root, "tasks-index.sqlite");
  288. (await createTaskDb(taskDbPath)).close();
  289. const repo = new SourceServerWorkspaceAliasRepo({
  290. taskDbPath,
  291. sessionDbPath: join(root, "missing.sqlite"),
  292. });
  293. await repo.listMigrationReports();
  294. const db = new DatabaseSync(taskDbPath);
  295. const insert = db.prepare(`INSERT INTO workspace_migration_ledger (
  296. migration_id, path, canonical_key, variant_keys_json, status, phase,
  297. task_backup_path, session_backup_path, error, created_at, updated_at,
  298. abandoned_at, abandoned_trigger, abandoned_activity_json
  299. ) VALUES (?, '/repo', 'remote:ssh:host:22:user:/repo', '[]', ?, NULL,
  300. '/backup/tasks.sqlite', '/backup/session.sqlite', NULL, ?, ?, ?, ?, ?)`);
  301. insert.run("z-failed-old", "failed", 1, 1, null, null, null);
  302. insert.run(
  303. "a-abandoned-new",
  304. "abandoned",
  305. 1,
  306. 1,
  307. 1,
  308. "user",
  309. JSON.stringify({ schemaVersion: 2, digests: {} }),
  310. );
  311. db.close();
  312. await expect(repo.getFailedPathCount()).resolves.toBe(0);
  313. await expect(repo.getAbandonedPathCount()).resolves.toBe(1);
  314. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  315. rows: [
  316. expect.objectContaining({
  317. migrationId: "a-abandoned-new",
  318. abandonedTrigger: "user",
  319. taskBackupPath: "/backup/tasks.sqlite",
  320. sessionBackupPath: "/backup/session.sqlite",
  321. }),
  322. expect.objectContaining({ migrationId: "z-failed-old" }),
  323. ],
  324. });
  325. });
  326. it("refuses to abandon a failed ledger that still owns a resumable phase", async () => {
  327. const root = await mkdtemp(join(tmpdir(), "zcode-r3-abandon-resume-owner-"));
  328. const taskDbPath = join(root, "tasks-index.sqlite");
  329. (await createTaskDb(taskDbPath)).close();
  330. const repo = new SourceServerWorkspaceAliasRepo({
  331. taskDbPath,
  332. sessionDbPath: join(root, "missing"),
  333. });
  334. await repo.listMigrationReports();
  335. const db = new DatabaseSync(taskDbPath);
  336. db.prepare(`INSERT INTO workspace_migration_ledger (
  337. migration_id, path, canonical_key, variant_keys_json, status, phase,
  338. task_backup_path, session_backup_path, error, created_at, updated_at
  339. ) VALUES ('resume-owner', '/repo', 'remote:ssh:host:22:user:/repo', '[]',
  340. 'failed', 'backups-created', '/backup', NULL, 'crash', 1, 1)`).run();
  341. db.close();
  342. await expect(repo.abandonFailedWorkspace("/repo")).rejects.toThrow(
  343. "resumable migration cannot be abandoned",
  344. );
  345. });
  346. it("fails closed on a newer migration schema version", async () => {
  347. const root = await mkdtemp(join(tmpdir(), "zcode-r3-newer-schema-"));
  348. const taskDbPath = join(root, "tasks-index.sqlite");
  349. const db = await createTaskDb(taskDbPath);
  350. db.exec(`CREATE TABLE workspace_migration_schema_version (
  351. schema_name TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at INTEGER NOT NULL
  352. ); INSERT INTO workspace_migration_schema_version VALUES ('workspace-migration', 4, 1);`);
  353. db.close();
  354. const repo = new SourceServerWorkspaceAliasRepo({
  355. taskDbPath,
  356. sessionDbPath: join(root, "missing"),
  357. });
  358. await expect(repo.listMigrationReports()).rejects.toThrow(
  359. "Unsupported newer Source Server migration schema version: 4",
  360. );
  361. });
  362. it("chooses the most recently active legacy key, backs up and merges both databases", async () => {
  363. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-"));
  364. const taskDbPath = join(root, "tasks-index.sqlite");
  365. const sessionDbPath = join(root, "db.sqlite");
  366. const backupRoot = join(root, "backups");
  367. const workspacePath = "/srv/project";
  368. const keyA = "remote:ssh:old.example:22:alice:/srv/project";
  369. const keyB = "remote:ssh:new.example:22:alice:/srv/project";
  370. const taskDb = await createTaskDb(taskDbPath);
  371. taskDb
  372. .prepare(
  373. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  374. )
  375. .run(keyA, workspacePath, keyA, "task-a", "A", 1, 10);
  376. taskDb
  377. .prepare(
  378. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  379. )
  380. .run(keyB, workspacePath, keyB, "task-b", "B", 2, 20);
  381. taskDb.close();
  382. const sessionDb = createSessionDb(sessionDbPath);
  383. sessionDb
  384. .prepare(
  385. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES (?, ?, ?, ?, ?)",
  386. )
  387. .run("task-a", keyA, workspacePath, workspacePath, 10);
  388. sessionDb
  389. .prepare(
  390. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES (?, ?, ?, ?, ?)",
  391. )
  392. .run("task-b", keyB, workspacePath, workspacePath, 20);
  393. sessionDb.close();
  394. const repo = new SourceServerWorkspaceAliasRepo({
  395. taskDbPath,
  396. sessionDbPath,
  397. backupRoot,
  398. now: () => 123,
  399. migrationId: () => "migration-1",
  400. });
  401. const result = await repo.resolveCanonicalWorkspaceKey({
  402. workspacePath,
  403. legacyRouteHint: keyA,
  404. });
  405. expect(result).toMatchObject({
  406. canonicalKey: keyB,
  407. mergedKeys: [keyA],
  408. migrationId: "migration-1",
  409. });
  410. const verifyTasks = new DatabaseSync(taskDbPath);
  411. expect(
  412. verifyTasks
  413. .prepare("SELECT workspace_key, workspace_identity, task_id FROM tasks ORDER BY task_id")
  414. .all(),
  415. ).toEqual([
  416. { workspace_key: keyB, workspace_identity: keyB, task_id: "task-a" },
  417. { workspace_key: keyB, workspace_identity: keyB, task_id: "task-b" },
  418. ]);
  419. expect(verifyTasks.prepare("SELECT path, canonical_key FROM workspace_alias").get()).toEqual({
  420. path: workspacePath,
  421. canonical_key: keyB,
  422. });
  423. expect(verifyTasks.prepare("SELECT status FROM workspace_migration_ledger").get()).toEqual({
  424. status: "completed",
  425. });
  426. verifyTasks.close();
  427. const verifySessions = new DatabaseSync(sessionDbPath);
  428. expect(verifySessions.prepare("SELECT DISTINCT workspace_id FROM session").all()).toEqual([
  429. { workspace_id: keyB },
  430. ]);
  431. verifySessions.close();
  432. await expect(
  433. access(join(backupRoot, "migration-1", "tasks-index.sqlite")),
  434. ).resolves.toBeUndefined();
  435. await expect(access(join(backupRoot, "migration-1", "db.sqlite"))).resolves.toBeUndefined();
  436. await expect(
  437. repo.resolveCanonicalWorkspaceKey({
  438. workspacePath,
  439. legacyRouteHint: keyA,
  440. }),
  441. ).resolves.toMatchObject({ canonicalKey: keyB, mergedKeys: [] });
  442. });
  443. it.each(["remote:docker:dev:/workspace", "remote:server:owner:/workspace"])(
  444. "uses route hint %s without rewriting data when the workspace has no history",
  445. async (hint) => {
  446. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-empty-"));
  447. const taskDbPath = join(root, "tasks-index.sqlite");
  448. (await createTaskDb(taskDbPath)).close();
  449. const repo = new SourceServerWorkspaceAliasRepo({
  450. taskDbPath,
  451. sessionDbPath: join(root, "missing.sqlite"),
  452. backupRoot: join(root, "backups"),
  453. });
  454. await expect(
  455. repo.resolveCanonicalWorkspaceKey({
  456. workspacePath: "/workspace",
  457. legacyRouteHint: hint,
  458. }),
  459. ).resolves.toMatchObject({ canonicalKey: hint, mergedKeys: [] });
  460. },
  461. );
  462. it("resumes the same migration plan after task DB commit without re-electing canonical", async () => {
  463. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-resume-"));
  464. const taskDbPath = join(root, "tasks-index.sqlite");
  465. const sessionDbPath = join(root, "db.sqlite");
  466. const workspacePath = "/srv/project";
  467. const keyA = "remote:ssh:a.example:22:alice:/srv/project";
  468. const keyB = "remote:ssh:b.example:22:alice:/srv/project";
  469. const taskDb = await createTaskDb(taskDbPath);
  470. const insertTask = taskDb.prepare(
  471. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  472. );
  473. insertTask.run(keyA, workspacePath, keyA, "task-a", "A", 1, 10);
  474. insertTask.run(keyB, workspacePath, keyB, "task-b", "B", 1, 20);
  475. taskDb.close();
  476. const sessionDb = createSessionDb(sessionDbPath);
  477. const insertSession = sessionDb.prepare(
  478. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES (?, ?, ?, ?, ?)",
  479. );
  480. insertSession.run("task-a", keyA, workspacePath, workspacePath, 10);
  481. insertSession.run("task-b", keyB, workspacePath, workspacePath, 20);
  482. sessionDb.close();
  483. const crashingRepo = new SourceServerWorkspaceAliasRepo({
  484. taskDbPath,
  485. sessionDbPath,
  486. backupRoot: join(root, "backups"),
  487. migrationId: () => "migration-frozen",
  488. afterPhaseCommitted: (phase: string) => {
  489. if (phase === "task-db-merged") throw new Error("simulated crash");
  490. },
  491. });
  492. await expect(
  493. crashingRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: keyA }),
  494. ).rejects.toThrow("simulated crash");
  495. const changedActivity = new DatabaseSync(sessionDbPath);
  496. changedActivity
  497. .prepare("UPDATE session SET time_updated = 200 WHERE workspace_id = ?")
  498. .run(keyA);
  499. changedActivity.close();
  500. const resumedRepo = new SourceServerWorkspaceAliasRepo({
  501. taskDbPath,
  502. sessionDbPath,
  503. backupRoot: join(root, "backups"),
  504. migrationId: () => "migration-unexpected",
  505. });
  506. await expect(
  507. resumedRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: keyA }),
  508. ).resolves.toEqual({
  509. canonicalKey: keyB,
  510. mergedKeys: [keyA],
  511. migrationId: "migration-frozen",
  512. });
  513. const verifyTasks = new DatabaseSync(taskDbPath);
  514. expect(
  515. verifyTasks
  516. .prepare(
  517. "SELECT migration_id, canonical_key, status, phase FROM workspace_migration_ledger",
  518. )
  519. .all(),
  520. ).toEqual([
  521. {
  522. migration_id: "migration-frozen",
  523. canonical_key: keyB,
  524. status: "completed",
  525. phase: "completed",
  526. },
  527. ]);
  528. expect(verifyTasks.prepare("SELECT DISTINCT workspace_key FROM tasks").all()).toEqual([
  529. { workspace_key: keyB },
  530. ]);
  531. verifyTasks.close();
  532. const verifySessions = new DatabaseSync(sessionDbPath);
  533. expect(verifySessions.prepare("SELECT DISTINCT workspace_id FROM session").all()).toEqual([
  534. { workspace_id: keyB },
  535. ]);
  536. verifySessions.close();
  537. });
  538. it("persists the frozen plan before creating backups", async () => {
  539. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-preflight-"));
  540. const taskDbPath = join(root, "tasks-index.sqlite");
  541. const workspacePath = "/srv/project";
  542. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  543. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  544. const taskDb = await createTaskDb(taskDbPath);
  545. const insertTask = taskDb.prepare(
  546. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  547. );
  548. insertTask.run(sourceKey, workspacePath, sourceKey, "task-source", "source", 1, 10);
  549. insertTask.run(canonicalKey, workspacePath, canonicalKey, "task-canonical", "canonical", 1, 20);
  550. taskDb.close();
  551. const backupRoot = join(root, "backups");
  552. const crashingRepo = new SourceServerWorkspaceAliasRepo({
  553. taskDbPath,
  554. sessionDbPath: join(root, "missing.sqlite"),
  555. backupRoot,
  556. migrationId: () => "preflight-migration",
  557. afterPhaseCommitted: (phase: string) => {
  558. if (phase === "preflight") throw new Error("preflight crash");
  559. },
  560. });
  561. await expect(
  562. crashingRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  563. ).rejects.toThrow("preflight crash");
  564. await expect(access(backupRoot)).rejects.toThrow();
  565. const failed = new DatabaseSync(taskDbPath);
  566. expect(failed.prepare("SELECT status, phase FROM workspace_migration_ledger").get()).toEqual({
  567. status: "failed",
  568. phase: "preflight",
  569. });
  570. failed.close();
  571. const resumedRepo = new SourceServerWorkspaceAliasRepo({
  572. taskDbPath,
  573. sessionDbPath: join(root, "missing.sqlite"),
  574. backupRoot,
  575. migrationId: () => "unexpected-migration",
  576. });
  577. await expect(
  578. resumedRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  579. ).resolves.toMatchObject({
  580. canonicalKey,
  581. migrationId: "preflight-migration",
  582. });
  583. });
  584. it("fails the frozen resume plan before moving data when a new identity conflict appears", async () => {
  585. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-resume-conflict-"));
  586. const taskDbPath = join(root, "tasks-index.sqlite");
  587. const workspacePath = "/srv/project";
  588. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  589. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  590. const taskDb = await createTaskDb(taskDbPath);
  591. const insertTask = taskDb.prepare(
  592. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at, meta_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
  593. );
  594. insertTask.run(sourceKey, workspacePath, sourceKey, "source-only", "source", 1, 10, "{}");
  595. insertTask.run(
  596. canonicalKey,
  597. workspacePath,
  598. canonicalKey,
  599. "canonical-only",
  600. "canonical",
  601. 1,
  602. 20,
  603. "{}",
  604. );
  605. taskDb.close();
  606. const crashingRepo = new SourceServerWorkspaceAliasRepo({
  607. taskDbPath,
  608. sessionDbPath: join(root, "missing.sqlite"),
  609. backupRoot: join(root, "backups"),
  610. migrationId: () => "resume-conflict-migration",
  611. afterPhaseCommitted: (phase) => {
  612. if (phase === "backups-created") throw new Error("crash after backup");
  613. },
  614. });
  615. await expect(
  616. crashingRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  617. ).rejects.toThrow("crash after backup");
  618. const changed = new DatabaseSync(taskDbPath);
  619. const insertConflict = changed.prepare(
  620. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at, meta_json) VALUES (?, ?, ?, 'new-conflict', 'conflict', 2, ?, ?)",
  621. );
  622. insertConflict.run(
  623. canonicalKey,
  624. workspacePath,
  625. canonicalKey,
  626. 30,
  627. JSON.stringify({ taskId: "new-conflict", cronAutomationId: "canonical-cron" }),
  628. );
  629. insertConflict.run(
  630. sourceKey,
  631. workspacePath,
  632. sourceKey,
  633. 25,
  634. JSON.stringify({ taskId: "new-conflict", cronAutomationId: "source-cron" }),
  635. );
  636. changed.close();
  637. const resumedRepo = new SourceServerWorkspaceAliasRepo({
  638. taskDbPath,
  639. sessionDbPath: join(root, "missing.sqlite"),
  640. backupRoot: join(root, "backups"),
  641. migrationId: () => "unexpected-second-migration",
  642. });
  643. await expect(
  644. resumedRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  645. ).rejects.toMatchObject({ code: "workspace-task-identity-conflict" });
  646. const verify = new DatabaseSync(taskDbPath);
  647. expect(
  648. verify
  649. .prepare(
  650. "SELECT migration_id, status, phase, error FROM workspace_migration_ledger WHERE path = ?",
  651. )
  652. .all(workspacePath),
  653. ).toEqual([
  654. {
  655. migration_id: "resume-conflict-migration",
  656. status: "failed",
  657. phase: null,
  658. error: "workspace-task-identity-conflict",
  659. },
  660. ]);
  661. expect(
  662. verify.prepare("SELECT DISTINCT workspace_key FROM tasks ORDER BY workspace_key").all(),
  663. ).toEqual([{ workspace_key: canonicalKey }, { workspace_key: sourceKey }]);
  664. verify.close();
  665. await expect(resumedRepo.abandonFailedWorkspace(workspacePath)).resolves.toBeUndefined();
  666. });
  667. it("rechecks config conflicts before resuming a frozen pre-merge plan", async () => {
  668. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-resume-config-"));
  669. const taskDbPath = join(root, "tasks-index.sqlite");
  670. const workspacePath = "/srv/project";
  671. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  672. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  673. const taskDb = await createTaskDb(taskDbPath);
  674. const insertTask = taskDb.prepare(
  675. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  676. );
  677. insertTask.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  678. insertTask.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  679. taskDb.close();
  680. const backupRoot = join(root, "backups");
  681. const crashingRepo = new SourceServerWorkspaceAliasRepo({
  682. taskDbPath,
  683. sessionDbPath: join(root, "missing.sqlite"),
  684. backupRoot,
  685. migrationId: () => "resume-config-migration",
  686. afterPhaseCommitted: (phase) => {
  687. if (phase === "backups-created") throw new Error("crash after backup");
  688. },
  689. });
  690. await expect(
  691. crashingRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  692. ).rejects.toThrow("crash after backup");
  693. const canonicalDir = join(root, "sessions", getWorkspaceHash(workspacePath, canonicalKey));
  694. const sourceDir = join(root, "sessions", getWorkspaceHash(workspacePath, sourceKey));
  695. await Promise.all([
  696. mkdir(canonicalDir, { recursive: true }),
  697. mkdir(sourceDir, { recursive: true }),
  698. ]);
  699. await Promise.all([
  700. writeFile(join(canonicalDir, "settings.json"), "canonical", "utf8"),
  701. writeFile(join(sourceDir, "settings.json"), "source", "utf8"),
  702. ]);
  703. const resumedRepo = new SourceServerWorkspaceAliasRepo({
  704. taskDbPath,
  705. sessionDbPath: join(root, "missing.sqlite"),
  706. backupRoot,
  707. });
  708. await expect(
  709. resumedRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  710. ).rejects.toMatchObject({ code: "workspace-config-file-conflict" });
  711. await expect(resumedRepo.listMigrationReports()).resolves.toMatchObject({
  712. rows: [
  713. expect.objectContaining({
  714. migrationId: "resume-config-migration",
  715. status: "failed",
  716. errorCode: "workspace-config-file-conflict",
  717. conflicts: [expect.objectContaining({ relativePath: "settings.json" })],
  718. }),
  719. ],
  720. });
  721. const failed = new DatabaseSync(taskDbPath);
  722. expect(failed.prepare("SELECT phase FROM workspace_migration_ledger").get()).toEqual({
  723. phase: null,
  724. });
  725. failed.close();
  726. await expect(resumedRepo.abandonFailedWorkspace(workspacePath)).resolves.toBeUndefined();
  727. });
  728. it("checks task identity conflicts inside the task merge transaction", async () => {
  729. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-transaction-conflict-"));
  730. const taskDbPath = join(root, "tasks-index.sqlite");
  731. const workspacePath = "/srv/project";
  732. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  733. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  734. const taskDb = await createTaskDb(taskDbPath);
  735. const insertTask = taskDb.prepare(
  736. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at, meta_json) VALUES (?, ?, ?, ?, ?, 1, ?, ?)",
  737. );
  738. insertTask.run(sourceKey, workspacePath, sourceKey, "source", "source", 10, "{}");
  739. insertTask.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20, "{}");
  740. taskDb.close();
  741. const repo = new SourceServerWorkspaceAliasRepo({
  742. taskDbPath,
  743. sessionDbPath: join(root, "missing.sqlite"),
  744. backupRoot: join(root, "backups"),
  745. migrationId: () => "transaction-conflict-migration",
  746. afterPhaseCommitted: (phase) => {
  747. if (phase !== "backups-created") return;
  748. const changed = new DatabaseSync(taskDbPath);
  749. const add = changed.prepare(
  750. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at, meta_json) VALUES (?, ?, ?, 'late-conflict', 'late', 2, 30, ?)",
  751. );
  752. add.run(
  753. canonicalKey,
  754. workspacePath,
  755. canonicalKey,
  756. JSON.stringify({ cronAutomationId: "canonical-cron" }),
  757. );
  758. add.run(
  759. sourceKey,
  760. workspacePath,
  761. sourceKey,
  762. JSON.stringify({ cronAutomationId: "source-cron" }),
  763. );
  764. changed.close();
  765. },
  766. });
  767. await expect(
  768. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  769. ).rejects.toMatchObject({ code: "workspace-task-identity-conflict" });
  770. const verify = new DatabaseSync(taskDbPath);
  771. expect(
  772. verify.prepare("SELECT DISTINCT workspace_key FROM tasks ORDER BY workspace_key").all(),
  773. ).toEqual([{ workspace_key: canonicalKey }, { workspace_key: sourceKey }]);
  774. verify.close();
  775. });
  776. it("records a structured config conflict that appears after resume preflight", async () => {
  777. const root = await mkdtemp(join(tmpdir(), "zcode-r3-late-config-conflict-"));
  778. const taskDbPath = join(root, "tasks-index.sqlite");
  779. const workspacePath = "/srv/project";
  780. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  781. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  782. const taskDb = await createTaskDb(taskDbPath);
  783. const insertTask = taskDb.prepare(
  784. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  785. );
  786. insertTask.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  787. insertTask.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  788. taskDb.close();
  789. const repo = new SourceServerWorkspaceAliasRepo({
  790. taskDbPath,
  791. sessionDbPath: join(root, "missing.sqlite"),
  792. backupRoot: join(root, "backups"),
  793. migrationId: () => "late-config-conflict",
  794. afterPhaseCommitted: async (phase) => {
  795. if (phase !== "session-db-merged") return;
  796. const canonicalDir = join(root, "sessions", getWorkspaceHash(workspacePath, canonicalKey));
  797. const sourceDir = join(root, "sessions", getWorkspaceHash(workspacePath, sourceKey));
  798. await Promise.all([
  799. mkdir(canonicalDir, { recursive: true }),
  800. mkdir(sourceDir, { recursive: true }),
  801. ]);
  802. await Promise.all([
  803. writeFile(join(canonicalDir, "settings.json"), "canonical", "utf8"),
  804. writeFile(join(sourceDir, "settings.json"), "source", "utf8"),
  805. ]);
  806. },
  807. });
  808. await expect(
  809. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  810. ).rejects.toMatchObject({ code: "workspace-config-file-conflict" });
  811. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  812. rows: [
  813. expect.objectContaining({
  814. migrationId: "late-config-conflict",
  815. phase: "session-db-merged",
  816. errorCode: "workspace-config-file-conflict",
  817. conflicts: [expect.objectContaining({ relativePath: "settings.json" })],
  818. }),
  819. ],
  820. });
  821. });
  822. it("fails closed when a frozen session backup generation disappears", async () => {
  823. const root = await mkdtemp(join(tmpdir(), "zcode-r3-missing-frozen-session-db-"));
  824. const taskDbPath = join(root, "tasks-index.sqlite");
  825. (await createTaskDb(taskDbPath)).close();
  826. const repo = new SourceServerWorkspaceAliasRepo({
  827. taskDbPath,
  828. sessionDbPath: join(root, "missing.sqlite"),
  829. });
  830. await repo.listMigrationReports();
  831. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  832. const sourceKey = "remote:ssh:source:22:user:/repo";
  833. const db = new DatabaseSync(taskDbPath);
  834. db.prepare(`INSERT INTO workspace_migration_ledger (
  835. migration_id, path, canonical_key, variant_keys_json, status, phase,
  836. task_backup_path, session_backup_path, error, created_at, updated_at
  837. ) VALUES ('missing-session', '/repo', ?, ?, 'failed', 'task-db-merged',
  838. '/backup/tasks.sqlite', '/backup/session.sqlite', 'crash', 1, 1)`).run(
  839. canonicalKey,
  840. JSON.stringify([canonicalKey, sourceKey]),
  841. );
  842. db.close();
  843. await expect(
  844. repo.resolveCanonicalWorkspaceKey({ workspacePath: "/repo", legacyRouteHint: sourceKey }),
  845. ).rejects.toMatchObject({ code: "workspace-session-generation-changed" });
  846. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  847. rows: [expect.objectContaining({ errorCode: "workspace-session-generation-changed" })],
  848. });
  849. });
  850. it("fails closed when the session database is recreated at the same path after session merge", async () => {
  851. const root = await mkdtemp(join(tmpdir(), "zcode-r3-recreated-session-db-"));
  852. const taskDbPath = join(root, "tasks-index.sqlite");
  853. const sessionDbPath = join(root, "db.sqlite");
  854. const workspacePath = "/repo";
  855. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  856. const sourceKey = "remote:ssh:source:22:user:/repo";
  857. const taskDb = await createTaskDb(taskDbPath);
  858. const addTask = taskDb.prepare(
  859. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  860. );
  861. addTask.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  862. addTask.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  863. taskDb.close();
  864. const sessionDb = createSessionDb(sessionDbPath);
  865. sessionDb
  866. .prepare(
  867. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES ('source', ?, ?, ?, 10)",
  868. )
  869. .run(sourceKey, workspacePath, workspacePath);
  870. sessionDb.close();
  871. const backupRoot = join(root, "backups");
  872. const crashing = new SourceServerWorkspaceAliasRepo({
  873. taskDbPath,
  874. sessionDbPath,
  875. backupRoot,
  876. migrationId: () => "recreated-session-migration",
  877. afterPhaseCommitted: (phase) => {
  878. if (phase === "session-db-merged") throw new Error("crash after session merge");
  879. },
  880. });
  881. await expect(
  882. crashing.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  883. ).rejects.toThrow("crash after session merge");
  884. await rm(sessionDbPath, { force: true });
  885. createSessionDb(sessionDbPath).close();
  886. const resumed = new SourceServerWorkspaceAliasRepo({
  887. taskDbPath,
  888. sessionDbPath,
  889. backupRoot,
  890. });
  891. await expect(
  892. resumed.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  893. ).rejects.toMatchObject({ code: "workspace-session-generation-changed" });
  894. });
  895. it("resumes a legacy v2 post-merge ledger by validating the session backup lineage", async () => {
  896. const root = await mkdtemp(join(tmpdir(), "zcode-r3-v2-session-generation-"));
  897. const taskDbPath = join(root, "tasks-index.sqlite");
  898. const sessionDbPath = join(root, "db.sqlite");
  899. const backupRoot = join(root, "backups");
  900. const workspacePath = "/repo";
  901. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  902. const sourceKey = "remote:ssh:source:22:user:/repo";
  903. const migrationId = "legacy-v2-post-merge";
  904. const taskDb = await createTaskDb(taskDbPath);
  905. const addTask = taskDb.prepare(
  906. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  907. );
  908. addTask.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  909. addTask.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  910. taskDb.close();
  911. const sessionDb = createSessionDb(sessionDbPath);
  912. sessionDb
  913. .prepare(
  914. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES ('source', ?, ?, ?, 10)",
  915. )
  916. .run(sourceKey, workspacePath, workspacePath);
  917. sessionDb.close();
  918. const crashing = new SourceServerWorkspaceAliasRepo({
  919. taskDbPath,
  920. sessionDbPath,
  921. backupRoot,
  922. migrationId: () => migrationId,
  923. afterPhaseCommitted: (phase) => {
  924. if (phase === "session-db-merged") throw new Error("legacy crash");
  925. },
  926. });
  927. await expect(
  928. crashing.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  929. ).rejects.toThrow("legacy crash");
  930. for (const path of [sessionDbPath, join(backupRoot, migrationId, "db.sqlite")]) {
  931. const db = new DatabaseSync(path);
  932. db.exec("DROP TABLE zcode_database_identity");
  933. // 旧 v2 制品尚无正式 identity migration,fixture 同时还原结构与账本。
  934. db.exec("DELETE FROM schema_migration WHERE id = '0024_session_database_identity'");
  935. db.close();
  936. }
  937. const legacyTaskDb = new DatabaseSync(taskDbPath);
  938. legacyTaskDb.exec("ALTER TABLE workspace_migration_ledger DROP COLUMN session_db_generation");
  939. legacyTaskDb.exec(
  940. "DELETE FROM tasks_schema_migration WHERE id = '0005_source_server_workspace_schema'",
  941. );
  942. legacyTaskDb
  943. .prepare(
  944. "UPDATE workspace_migration_schema_version SET version = 2 WHERE schema_name = 'workspace-migration'",
  945. )
  946. .run();
  947. legacyTaskDb.close();
  948. const resumed = new SourceServerWorkspaceAliasRepo({
  949. taskDbPath,
  950. sessionDbPath,
  951. backupRoot,
  952. });
  953. await expect(
  954. resumed.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  955. ).resolves.toMatchObject({ canonicalKey, migrationId });
  956. });
  957. it("allows abandoning a pre-merge plan when a populated session database appears", async () => {
  958. const root = await mkdtemp(join(tmpdir(), "zcode-r3-empty-late-session-db-"));
  959. const taskDbPath = join(root, "tasks-index.sqlite");
  960. const sessionDbPath = join(root, "db.sqlite");
  961. const workspacePath = "/repo";
  962. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  963. const sourceKey = "remote:ssh:source:22:user:/repo";
  964. const db = await createTaskDb(taskDbPath);
  965. const add = db.prepare(
  966. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  967. );
  968. add.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  969. add.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  970. db.close();
  971. const crashing = new SourceServerWorkspaceAliasRepo({
  972. taskDbPath,
  973. sessionDbPath,
  974. backupRoot: join(root, "backups"),
  975. migrationId: () => "late-empty-session",
  976. afterPhaseCommitted: (phase) => {
  977. if (phase === "backups-created") throw new Error("crash after backup");
  978. },
  979. });
  980. await expect(
  981. crashing.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  982. ).rejects.toThrow("crash after backup");
  983. const lateSessionDb = createSessionDb(sessionDbPath);
  984. lateSessionDb
  985. .prepare(
  986. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES ('late', ?, ?, ?, 30)",
  987. )
  988. .run(sourceKey, workspacePath, workspacePath);
  989. lateSessionDb.close();
  990. const resumed = new SourceServerWorkspaceAliasRepo({
  991. taskDbPath,
  992. sessionDbPath,
  993. backupRoot: join(root, "backups"),
  994. });
  995. await expect(
  996. resumed.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  997. ).rejects.toMatchObject({ code: "workspace-session-generation-changed" });
  998. await expect(resumed.abandonFailedWorkspace(workspacePath)).resolves.toBeUndefined();
  999. await expect(
  1000. resumed.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1001. ).resolves.toEqual({ canonicalKey, mergedKeys: [] });
  1002. });
  1003. it("ignores an empty session database created after a session-less plan was frozen", async () => {
  1004. const root = await mkdtemp(join(tmpdir(), "zcode-r3-empty-late-session-db-"));
  1005. const taskDbPath = join(root, "tasks-index.sqlite");
  1006. const sessionDbPath = join(root, "db.sqlite");
  1007. const workspacePath = "/repo";
  1008. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  1009. const sourceKey = "remote:ssh:source:22:user:/repo";
  1010. const db = await createTaskDb(taskDbPath);
  1011. const add = db.prepare(
  1012. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  1013. );
  1014. add.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  1015. add.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  1016. db.close();
  1017. const backupRoot = join(root, "backups");
  1018. const crashing = new SourceServerWorkspaceAliasRepo({
  1019. taskDbPath,
  1020. sessionDbPath,
  1021. backupRoot,
  1022. migrationId: () => "late-empty-session",
  1023. afterPhaseCommitted: (phase) => {
  1024. if (phase === "backups-created") throw new Error("crash after backup");
  1025. },
  1026. });
  1027. await expect(
  1028. crashing.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1029. ).rejects.toThrow("crash after backup");
  1030. createSessionDb(sessionDbPath).close();
  1031. const resumed = new SourceServerWorkspaceAliasRepo({
  1032. taskDbPath,
  1033. sessionDbPath,
  1034. backupRoot,
  1035. });
  1036. await expect(
  1037. resumed.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1038. ).resolves.toMatchObject({ migrationId: "late-empty-session", canonicalKey });
  1039. const untouched = new DatabaseSync(sessionDbPath);
  1040. expect(untouched.prepare("SELECT COUNT(*) AS count FROM session").get()).toEqual({ count: 0 });
  1041. expect(
  1042. untouched
  1043. .prepare(
  1044. "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'zcode_database_identity'",
  1045. )
  1046. .get(),
  1047. ).toBeUndefined();
  1048. untouched.close();
  1049. });
  1050. it("fails a frozen resume when a new workspace variant appears", async () => {
  1051. const root = await mkdtemp(join(tmpdir(), "zcode-r3-new-frozen-variant-"));
  1052. const taskDbPath = join(root, "tasks-index.sqlite");
  1053. const workspacePath = "/repo";
  1054. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  1055. const sourceKey = "remote:ssh:source:22:user:/repo";
  1056. const newKey = "remote:ssh:new:22:user:/repo";
  1057. const db = await createTaskDb(taskDbPath);
  1058. const add = db.prepare(
  1059. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  1060. );
  1061. add.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  1062. add.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  1063. db.close();
  1064. const backupRoot = join(root, "backups");
  1065. const crashing = new SourceServerWorkspaceAliasRepo({
  1066. taskDbPath,
  1067. sessionDbPath: join(root, "missing.sqlite"),
  1068. backupRoot,
  1069. migrationId: () => "new-variant-migration",
  1070. afterPhaseCommitted: (phase) => {
  1071. if (phase === "backups-created") throw new Error("crash after backup");
  1072. },
  1073. });
  1074. await expect(
  1075. crashing.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1076. ).rejects.toThrow("crash after backup");
  1077. const changed = new DatabaseSync(taskDbPath);
  1078. changed
  1079. .prepare(
  1080. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, 'new-task', 'new', 2, 30)",
  1081. )
  1082. .run(newKey, workspacePath, newKey);
  1083. changed.close();
  1084. const resumed = new SourceServerWorkspaceAliasRepo({
  1085. taskDbPath,
  1086. sessionDbPath: join(root, "missing.sqlite"),
  1087. backupRoot,
  1088. });
  1089. await expect(
  1090. resumed.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1091. ).rejects.toMatchObject({ code: "workspace-migration-plan-diverged" });
  1092. await expect(resumed.listMigrationReports()).resolves.toMatchObject({
  1093. rows: [
  1094. expect.objectContaining({
  1095. migrationId: "new-variant-migration",
  1096. status: "failed",
  1097. errorCode: "workspace-migration-plan-diverged",
  1098. }),
  1099. ],
  1100. });
  1101. const failed = new DatabaseSync(taskDbPath);
  1102. expect(failed.prepare("SELECT phase FROM workspace_migration_ledger").get()).toEqual({
  1103. phase: null,
  1104. });
  1105. failed.close();
  1106. await expect(resumed.abandonFailedWorkspace(workspacePath)).resolves.toBeUndefined();
  1107. });
  1108. it("finishes a post-merge frozen plan before migrating a newly appeared variant", async () => {
  1109. const root = await mkdtemp(join(tmpdir(), "zcode-r3-post-merge-follow-up-"));
  1110. const taskDbPath = join(root, "tasks-index.sqlite");
  1111. const workspacePath = "/repo";
  1112. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  1113. const sourceKey = "remote:ssh:source:22:user:/repo";
  1114. const newKey = "remote:ssh:new:22:user:/repo";
  1115. const db = await createTaskDb(taskDbPath);
  1116. const add = db.prepare(
  1117. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  1118. );
  1119. add.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  1120. add.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  1121. db.close();
  1122. const backupRoot = join(root, "backups");
  1123. const crashing = new SourceServerWorkspaceAliasRepo({
  1124. taskDbPath,
  1125. sessionDbPath: join(root, "missing.sqlite"),
  1126. backupRoot,
  1127. migrationId: () => "frozen-migration",
  1128. afterPhaseCommitted: (phase) => {
  1129. if (phase === "task-db-merged") throw new Error("crash after task merge");
  1130. },
  1131. });
  1132. await expect(
  1133. crashing.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1134. ).rejects.toThrow("crash after task merge");
  1135. const changed = new DatabaseSync(taskDbPath);
  1136. changed
  1137. .prepare(
  1138. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, 'new-task', 'new', 2, 30)",
  1139. )
  1140. .run(newKey, workspacePath, newKey);
  1141. changed.close();
  1142. const resumed = new SourceServerWorkspaceAliasRepo({
  1143. taskDbPath,
  1144. sessionDbPath: join(root, "missing.sqlite"),
  1145. backupRoot,
  1146. migrationId: () => "follow-up-migration",
  1147. });
  1148. await expect(
  1149. resumed.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1150. ).resolves.toMatchObject({
  1151. canonicalKey,
  1152. mergedKeys: [sourceKey, newKey],
  1153. migrationId: "follow-up-migration",
  1154. });
  1155. const verify = new DatabaseSync(taskDbPath);
  1156. expect(verify.prepare("SELECT DISTINCT workspace_key FROM tasks").all()).toEqual([
  1157. { workspace_key: canonicalKey },
  1158. ]);
  1159. expect(
  1160. verify
  1161. .prepare(
  1162. "SELECT migration_id, status, phase FROM workspace_migration_ledger ORDER BY created_at, migration_id",
  1163. )
  1164. .all(),
  1165. ).toEqual([
  1166. { migration_id: "frozen-migration", status: "completed", phase: "completed" },
  1167. { migration_id: "follow-up-migration", status: "completed", phase: "completed" },
  1168. ]);
  1169. verify.close();
  1170. });
  1171. it("bounds follow-up migrations when new variants keep appearing", async () => {
  1172. const root = await mkdtemp(join(tmpdir(), "zcode-r3-follow-up-budget-"));
  1173. const taskDbPath = join(root, "tasks-index.sqlite");
  1174. const workspacePath = "/repo";
  1175. const canonicalKey = "remote:ssh:canonical:22:user:/repo";
  1176. const sourceKey = "remote:ssh:source:22:user:/repo";
  1177. const db = await createTaskDb(taskDbPath);
  1178. const add = db.prepare(
  1179. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?)",
  1180. );
  1181. add.run(canonicalKey, workspacePath, canonicalKey, "canonical", "canonical", 20);
  1182. add.run(sourceKey, workspacePath, sourceKey, "source", "source", 10);
  1183. db.close();
  1184. let completedCount = 0;
  1185. let migrationCount = 0;
  1186. const repo = new SourceServerWorkspaceAliasRepo({
  1187. taskDbPath,
  1188. sessionDbPath: join(root, "missing.sqlite"),
  1189. backupRoot: join(root, "backups"),
  1190. migrationId: () => `migration-${++migrationCount}`,
  1191. afterPhaseCommitted: (phase) => {
  1192. if (phase !== "completed") return;
  1193. completedCount += 1;
  1194. if (completedCount > 4) throw new Error("unbounded follow-up");
  1195. const key = `remote:ssh:churn-${completedCount}:22:user:/repo`;
  1196. const changed = new DatabaseSync(taskDbPath);
  1197. changed
  1198. .prepare(
  1199. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, 'churn', 2, ?)",
  1200. )
  1201. .run(key, workspacePath, key, `churn-${completedCount}`, 20 + completedCount);
  1202. changed.close();
  1203. },
  1204. });
  1205. await expect(
  1206. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1207. ).rejects.toMatchObject({ code: "workspace-migration-plan-diverged" });
  1208. expect(completedCount).toBeLessThanOrEqual(4);
  1209. });
  1210. it.each([
  1211. "backups-created",
  1212. "session-db-merged",
  1213. "config-dirs-merged",
  1214. "alias-published",
  1215. "completed",
  1216. ])("resumes idempotently after %s", async (crashPhase) => {
  1217. const root = await mkdtemp(join(tmpdir(), `zcode-r3-workspace-alias-${crashPhase}-`));
  1218. const taskDbPath = join(root, "tasks-index.sqlite");
  1219. const workspacePath = "/srv/project";
  1220. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  1221. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  1222. const taskDb = await createTaskDb(taskDbPath);
  1223. const insertTask = taskDb.prepare(
  1224. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  1225. );
  1226. insertTask.run(sourceKey, workspacePath, sourceKey, "task-source", "source", 1, 10);
  1227. insertTask.run(canonicalKey, workspacePath, canonicalKey, "task-canonical", "canonical", 1, 20);
  1228. taskDb.close();
  1229. const migrationId = `migration-${crashPhase}`;
  1230. const crashingRepo = new SourceServerWorkspaceAliasRepo({
  1231. taskDbPath,
  1232. sessionDbPath: join(root, "missing.sqlite"),
  1233. backupRoot: join(root, "backups"),
  1234. migrationId: () => migrationId,
  1235. afterPhaseCommitted: (phase: string) => {
  1236. if (phase === crashPhase) throw new Error(`crash after ${phase}`);
  1237. },
  1238. });
  1239. await expect(
  1240. crashingRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1241. ).rejects.toThrow(`crash after ${crashPhase}`);
  1242. const resumedRepo = new SourceServerWorkspaceAliasRepo({
  1243. taskDbPath,
  1244. sessionDbPath: join(root, "missing.sqlite"),
  1245. backupRoot: join(root, "backups"),
  1246. migrationId: () => "unexpected-migration",
  1247. });
  1248. await expect(
  1249. resumedRepo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1250. ).resolves.toMatchObject({ canonicalKey, migrationId });
  1251. const verify = new DatabaseSync(taskDbPath);
  1252. expect(
  1253. verify.prepare("SELECT migration_id, status, phase FROM workspace_migration_ledger").all(),
  1254. ).toEqual([{ migration_id: migrationId, status: "completed", phase: "completed" }]);
  1255. verify.close();
  1256. });
  1257. it("incrementally merges a new legacy route variant after the alias already exists", async () => {
  1258. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-incremental-"));
  1259. const taskDbPath = join(root, "tasks-index.sqlite");
  1260. const sessionDbPath = join(root, "db.sqlite");
  1261. const workspacePath = "/srv/project";
  1262. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  1263. const lateKey = "remote:ssh:late.example:22:alice:/srv/project";
  1264. const taskDb = await createTaskDb(taskDbPath);
  1265. taskDb
  1266. .prepare(
  1267. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  1268. )
  1269. .run(canonicalKey, workspacePath, canonicalKey, "task-a", "A", 1, 10);
  1270. taskDb.close();
  1271. const sessionDb = createSessionDb(sessionDbPath);
  1272. sessionDb
  1273. .prepare(
  1274. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES (?, ?, ?, ?, ?)",
  1275. )
  1276. .run("task-a", canonicalKey, workspacePath, workspacePath, 10);
  1277. sessionDb.close();
  1278. const repo = new SourceServerWorkspaceAliasRepo({
  1279. taskDbPath,
  1280. sessionDbPath,
  1281. backupRoot: join(root, "backups"),
  1282. migrationId: () => "incremental-migration",
  1283. });
  1284. await repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: canonicalKey });
  1285. const lateTaskDb = new DatabaseSync(taskDbPath);
  1286. lateTaskDb
  1287. .prepare(
  1288. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  1289. )
  1290. .run(lateKey, workspacePath, lateKey, "task-b", "B", 2, 20);
  1291. lateTaskDb.close();
  1292. const lateSessionDb = new DatabaseSync(sessionDbPath);
  1293. lateSessionDb
  1294. .prepare(
  1295. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES (?, ?, ?, ?, ?)",
  1296. )
  1297. .run("task-b", lateKey, workspacePath, workspacePath, 20);
  1298. lateSessionDb.close();
  1299. await expect(
  1300. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: lateKey }),
  1301. ).resolves.toMatchObject({
  1302. canonicalKey,
  1303. mergedKeys: [lateKey],
  1304. migrationId: "incremental-migration",
  1305. });
  1306. const verifyTasks = new DatabaseSync(taskDbPath);
  1307. expect(
  1308. verifyTasks.prepare("SELECT workspace_key, task_id FROM tasks ORDER BY task_id").all(),
  1309. ).toEqual([
  1310. { workspace_key: canonicalKey, task_id: "task-a" },
  1311. { workspace_key: canonicalKey, task_id: "task-b" },
  1312. ]);
  1313. verifyTasks.close();
  1314. });
  1315. it("merges a hinted late variant that only owns a run and session config", async () => {
  1316. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-hinted-late-"));
  1317. const taskDbPath = join(root, "tasks-index.sqlite");
  1318. const workspacePath = "/srv/project";
  1319. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  1320. const lateKey = "remote:ssh:late.example:22:alice:/srv/project";
  1321. const taskDb = await createTaskDb(taskDbPath);
  1322. taskDb
  1323. .prepare(
  1324. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, 'task-canonical', 'canonical', 1, 20)",
  1325. )
  1326. .run(canonicalKey, workspacePath, canonicalKey);
  1327. taskDb.close();
  1328. const repo = new SourceServerWorkspaceAliasRepo({
  1329. taskDbPath,
  1330. sessionDbPath: join(root, "missing.sqlite"),
  1331. backupRoot: join(root, "backups"),
  1332. migrationId: (() => {
  1333. let id = 0;
  1334. return () => `hinted-migration-${++id}`;
  1335. })(),
  1336. });
  1337. await repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: canonicalKey });
  1338. const lateDb = new DatabaseSync(taskDbPath);
  1339. lateDb
  1340. .prepare(
  1341. "INSERT INTO automation_runs (run_id, automation_id, workspace_key, session_id, created_at, updated_at) VALUES ('run-late', 'automation-missing', ?, NULL, 1, 1)",
  1342. )
  1343. .run(lateKey);
  1344. lateDb.close();
  1345. const lateConfigDir = join(root, "sessions", getWorkspaceHash(workspacePath, lateKey));
  1346. await mkdir(lateConfigDir, { recursive: true });
  1347. await writeFile(join(lateConfigDir, "late.json"), "late", "utf8");
  1348. await expect(
  1349. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: lateKey }),
  1350. ).resolves.toEqual({
  1351. canonicalKey,
  1352. mergedKeys: [lateKey],
  1353. migrationId: "hinted-migration-1",
  1354. });
  1355. const verify = new DatabaseSync(taskDbPath);
  1356. expect(verify.prepare("SELECT workspace_key FROM automation_runs").get()).toEqual({
  1357. workspace_key: canonicalKey,
  1358. });
  1359. verify.close();
  1360. const canonicalConfigDir = join(
  1361. root,
  1362. "sessions",
  1363. getWorkspaceHash(workspacePath, canonicalKey),
  1364. );
  1365. await expect(readFile(join(canonicalConfigDir, "late.json"), "utf8")).resolves.toBe("late");
  1366. });
  1367. it("merges every workspace-owned row and session config file into canonical", async () => {
  1368. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-inventory-"));
  1369. const taskDbPath = join(root, "tasks-index.sqlite");
  1370. const sessionDbPath = join(root, "db.sqlite");
  1371. const workspacePath = "/srv/project";
  1372. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  1373. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  1374. const taskDb = await createTaskDb(taskDbPath);
  1375. const insertTask = taskDb.prepare(
  1376. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  1377. );
  1378. insertTask.run(sourceKey, workspacePath, sourceKey, "task-source", "source", 1, 10);
  1379. insertTask.run(canonicalKey, workspacePath, canonicalKey, "task-canonical", "canonical", 1, 20);
  1380. taskDb
  1381. .prepare("UPDATE tasks SET meta_json = ? WHERE workspace_key = ? AND task_id = 'task-source'")
  1382. .run(JSON.stringify({ taskId: "task-source", workspaceIdentity: sourceKey }), sourceKey);
  1383. taskDb.exec(
  1384. "INSERT INTO task_groups (group_id, title, created_at, updated_at) VALUES ('group-1', 'Test', 1, 1)",
  1385. );
  1386. taskDb
  1387. .prepare(
  1388. "INSERT INTO task_group_members (group_id, workspace_key, workspace_path, workspace_identity, task_id, added_at, created_at, updated_at) VALUES ('group-1', ?, ?, ?, 'task-source', 1, 1, 1)",
  1389. )
  1390. .run(sourceKey, workspacePath, sourceKey);
  1391. taskDb
  1392. .prepare("INSERT INTO task_group_workspace_bootstraps VALUES (?, 'group-1', 1, 1)")
  1393. .run(sourceKey);
  1394. taskDb
  1395. .prepare("INSERT INTO task_group_view_node_orders VALUES ('task', ?, 1, 1, 1)")
  1396. .run(JSON.stringify([sourceKey, "task-source"]));
  1397. taskDb
  1398. .prepare(
  1399. "INSERT INTO automations (automation_id, workspace_key, workspace_path, workspace_identity, target_task_id, updated_at, created_at, cron_expr, prompt) VALUES ('automation-1', ?, ?, ?, 'task-source', 10, 1, '* * * * *', 'test')",
  1400. )
  1401. .run(sourceKey, workspacePath, sourceKey);
  1402. taskDb
  1403. .prepare(
  1404. "INSERT INTO automation_runs (run_id, automation_id, workspace_key, session_id, created_at, updated_at) VALUES ('run-1', 'automation-1', ?, 'task-source', 1, 1)",
  1405. )
  1406. .run(sourceKey);
  1407. taskDb
  1408. .prepare(
  1409. "INSERT INTO off_peak_tasks (off_peak_task_id, workspace_key, workspace_path, workspace_identity, session_id, updated_at, created_at, queued_at, prompt, permission_mode, status) VALUES ('off-peak-1', ?, ?, ?, 'task-source', 10, 1, 1, 'test', 'default', 'queued')",
  1410. )
  1411. .run(sourceKey, workspacePath, sourceKey);
  1412. taskDb.close();
  1413. const sessionDb = createSessionDb(sessionDbPath);
  1414. sessionDb
  1415. .prepare(
  1416. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES ('task-source', ?, ?, ?, 10)",
  1417. )
  1418. .run(sourceKey, workspacePath, workspacePath);
  1419. sessionDb.close();
  1420. const sessionsRoot = join(root, "sessions");
  1421. const sourceConfigDir = join(sessionsRoot, getWorkspaceHash(workspacePath, sourceKey));
  1422. const canonicalConfigDir = join(sessionsRoot, getWorkspaceHash(workspacePath, canonicalKey));
  1423. await mkdir(join(sourceConfigDir, "nested"), { recursive: true });
  1424. await mkdir(canonicalConfigDir, { recursive: true });
  1425. await writeFile(join(sourceConfigDir, "source.json"), "source", "utf8");
  1426. await writeFile(join(sourceConfigDir, "nested", "shared.json"), "same", "utf8");
  1427. await mkdir(join(canonicalConfigDir, "nested"), { recursive: true });
  1428. await writeFile(join(canonicalConfigDir, "canonical.json"), "canonical", "utf8");
  1429. await writeFile(join(canonicalConfigDir, "nested", "shared.json"), "same", "utf8");
  1430. const repo = new SourceServerWorkspaceAliasRepo({
  1431. taskDbPath,
  1432. sessionDbPath,
  1433. backupRoot: join(root, "backups"),
  1434. migrationId: () => "inventory-migration",
  1435. });
  1436. await repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey });
  1437. const verify = new DatabaseSync(taskDbPath);
  1438. for (const table of [
  1439. "tasks",
  1440. "task_group_members",
  1441. "task_group_workspace_bootstraps",
  1442. "automations",
  1443. "automation_runs",
  1444. "off_peak_tasks",
  1445. ]) {
  1446. expect(
  1447. verify
  1448. .prepare(`SELECT COUNT(*) AS count FROM ${table} WHERE workspace_key = ?`)
  1449. .get(sourceKey),
  1450. ).toEqual({ count: 0 });
  1451. }
  1452. expect(
  1453. verify
  1454. .prepare("SELECT node_key FROM task_group_view_node_orders WHERE node_type = 'task'")
  1455. .get(),
  1456. ).toEqual({ node_key: JSON.stringify([canonicalKey, "task-source"]) });
  1457. expect(
  1458. verify
  1459. .prepare(
  1460. "SELECT workspace_key, workspace_identity, target_task_id FROM automations WHERE automation_id = 'automation-1'",
  1461. )
  1462. .get(),
  1463. ).toEqual({
  1464. workspace_key: canonicalKey,
  1465. workspace_identity: canonicalKey,
  1466. target_task_id: "task-source",
  1467. });
  1468. const movedTask = verify
  1469. .prepare("SELECT workspace_identity, meta_json FROM tasks WHERE task_id = 'task-source'")
  1470. .get() as { workspace_identity: string; meta_json: string };
  1471. expect(movedTask.workspace_identity).toBe(canonicalKey);
  1472. expect(JSON.parse(movedTask.meta_json)).toMatchObject({ workspaceIdentity: canonicalKey });
  1473. verify.close();
  1474. await expect(readFile(join(canonicalConfigDir, "source.json"), "utf8")).resolves.toBe("source");
  1475. await expect(readFile(join(canonicalConfigDir, "canonical.json"), "utf8")).resolves.toBe(
  1476. "canonical",
  1477. );
  1478. await expect(readFile(join(canonicalConfigDir, "nested", "shared.json"), "utf8")).resolves.toBe(
  1479. "same",
  1480. );
  1481. await expect(access(sourceConfigDir)).rejects.toThrow();
  1482. });
  1483. it("fails config collisions before backup or row movement and records one report", async () => {
  1484. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-config-conflict-"));
  1485. const taskDbPath = join(root, "tasks-index.sqlite");
  1486. const workspacePath = "/srv/project";
  1487. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  1488. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  1489. const taskDb = await createTaskDb(taskDbPath);
  1490. const insertTask = taskDb.prepare(
  1491. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
  1492. );
  1493. insertTask.run(sourceKey, workspacePath, sourceKey, "task-source", "source", 1, 10);
  1494. insertTask.run(canonicalKey, workspacePath, canonicalKey, "task-canonical", "canonical", 1, 20);
  1495. taskDb.close();
  1496. const sourceConfigDir = join(root, "sessions", getWorkspaceHash(workspacePath, sourceKey));
  1497. const canonicalConfigDir = join(
  1498. root,
  1499. "sessions",
  1500. getWorkspaceHash(workspacePath, canonicalKey),
  1501. );
  1502. await mkdir(sourceConfigDir, { recursive: true });
  1503. await mkdir(canonicalConfigDir, { recursive: true });
  1504. await writeFile(join(sourceConfigDir, "state.json"), "source", "utf8");
  1505. await writeFile(join(canonicalConfigDir, "state.json"), "canonical", "utf8");
  1506. const backupRoot = join(root, "backups");
  1507. const repo = new SourceServerWorkspaceAliasRepo({
  1508. taskDbPath,
  1509. sessionDbPath: join(root, "missing.sqlite"),
  1510. backupRoot,
  1511. migrationId: () => "config-conflict",
  1512. now: () => 123,
  1513. });
  1514. await expect(
  1515. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1516. ).rejects.toMatchObject({
  1517. code: "workspace-config-file-conflict",
  1518. retryable: false,
  1519. relativePath: "state.json",
  1520. });
  1521. await expect(access(backupRoot)).rejects.toThrow();
  1522. await expect(repo.getFailedPathCount()).resolves.toBe(1);
  1523. const verify = new DatabaseSync(taskDbPath);
  1524. expect(
  1525. verify.prepare("SELECT DISTINCT workspace_key FROM tasks ORDER BY workspace_key").all(),
  1526. ).toEqual([{ workspace_key: canonicalKey }, { workspace_key: sourceKey }]);
  1527. expect(
  1528. verify
  1529. .prepare(
  1530. "SELECT migration_id, status, phase, task_backup_path, error FROM workspace_migration_ledger",
  1531. )
  1532. .get(),
  1533. ).toEqual({
  1534. migration_id: "config-conflict",
  1535. status: "failed",
  1536. phase: null,
  1537. task_backup_path: "",
  1538. error: "workspace-config-file-conflict",
  1539. });
  1540. expect(
  1541. verify
  1542. .prepare(
  1543. "SELECT conflict_kind, conflict_key, task_id, relative_path, source_key FROM workspace_migration_conflicts",
  1544. )
  1545. .get(),
  1546. ).toEqual({
  1547. conflict_kind: "config-file",
  1548. conflict_key: "state.json",
  1549. task_id: null,
  1550. relative_path: "state.json",
  1551. source_key: sourceKey,
  1552. });
  1553. verify.close();
  1554. });
  1555. it("discovers and merges variants that exist only in automation-owned tables", async () => {
  1556. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-automation-only-"));
  1557. const taskDbPath = join(root, "tasks-index.sqlite");
  1558. const workspacePath = "/srv/project";
  1559. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  1560. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  1561. const taskDb = await createTaskDb(taskDbPath);
  1562. taskDb
  1563. .prepare(
  1564. "INSERT INTO automations (automation_id, workspace_key, workspace_path, workspace_identity, target_task_id, updated_at, created_at, cron_expr, prompt) VALUES ('automation-1', ?, ?, ?, NULL, 10, 1, '* * * * *', 'test')",
  1565. )
  1566. .run(sourceKey, workspacePath, sourceKey);
  1567. taskDb
  1568. .prepare(
  1569. "INSERT INTO automation_runs (run_id, automation_id, workspace_key, session_id, created_at, updated_at) VALUES ('run-1', 'automation-1', ?, NULL, 1, 1)",
  1570. )
  1571. .run(sourceKey);
  1572. taskDb
  1573. .prepare(
  1574. "INSERT INTO off_peak_tasks (off_peak_task_id, workspace_key, workspace_path, workspace_identity, session_id, updated_at, created_at, queued_at, prompt, permission_mode, status) VALUES ('off-peak-1', ?, ?, ?, NULL, 20, 1, 1, 'test', 'default', 'queued')",
  1575. )
  1576. .run(canonicalKey, workspacePath, canonicalKey);
  1577. taskDb.close();
  1578. const repo = new SourceServerWorkspaceAliasRepo({
  1579. taskDbPath,
  1580. sessionDbPath: join(root, "missing.sqlite"),
  1581. backupRoot: join(root, "backups"),
  1582. migrationId: () => "automation-only-migration",
  1583. });
  1584. await expect(
  1585. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1586. ).resolves.toEqual({
  1587. canonicalKey,
  1588. mergedKeys: [sourceKey],
  1589. migrationId: "automation-only-migration",
  1590. });
  1591. const verify = new DatabaseSync(taskDbPath);
  1592. expect(
  1593. verify.prepare("SELECT workspace_key, workspace_identity FROM automations").get(),
  1594. ).toEqual({ workspace_key: canonicalKey, workspace_identity: canonicalKey });
  1595. expect(verify.prepare("SELECT workspace_key FROM automation_runs").get()).toEqual({
  1596. workspace_key: canonicalKey,
  1597. });
  1598. verify.close();
  1599. });
  1600. it("fails the whole workspace idempotently before moving data when task identity conflicts", async () => {
  1601. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-conflict-"));
  1602. const taskDbPath = join(root, "tasks-index.sqlite");
  1603. const workspacePath = "/srv/project";
  1604. const canonicalKey = "remote:ssh:canonical.example:22:alice:/srv/project";
  1605. const sourceKey = "remote:ssh:source.example:22:alice:/srv/project";
  1606. const taskDb = await createTaskDb(taskDbPath);
  1607. const insert = taskDb.prepare(
  1608. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at, meta_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
  1609. );
  1610. insert.run(
  1611. canonicalKey,
  1612. workspacePath,
  1613. canonicalKey,
  1614. "shared-task",
  1615. "Same title",
  1616. 1,
  1617. 20,
  1618. JSON.stringify({ taskId: "shared-task", cronAutomationId: "cron-a" }),
  1619. );
  1620. insert.run(
  1621. sourceKey,
  1622. workspacePath,
  1623. sourceKey,
  1624. "shared-task",
  1625. "Same title",
  1626. 1,
  1627. 10,
  1628. JSON.stringify({ taskId: "shared-task", cronAutomationId: "cron-b" }),
  1629. );
  1630. taskDb.exec(
  1631. "INSERT INTO task_groups (group_id, title, created_at, updated_at) VALUES ('source-group', 'Source', 1, 1)",
  1632. );
  1633. taskDb
  1634. .prepare(
  1635. "INSERT INTO task_group_members (group_id, workspace_key, workspace_path, workspace_identity, task_id, added_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, 1, 1)",
  1636. )
  1637. .run("source-group", sourceKey, workspacePath, sourceKey, "shared-task");
  1638. taskDb.close();
  1639. const sessionDbPath = join(root, "db.sqlite");
  1640. const sessionDb = createSessionDb(sessionDbPath);
  1641. sessionDb
  1642. .prepare(
  1643. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES (?, ?, ?, ?, ?)",
  1644. )
  1645. .run("source-session", sourceKey, workspacePath, workspacePath, 10);
  1646. sessionDb.close();
  1647. let migrationSequence = 0;
  1648. const repo = new SourceServerWorkspaceAliasRepo({
  1649. taskDbPath,
  1650. sessionDbPath,
  1651. backupRoot: join(root, "backups"),
  1652. migrationId: vi.fn(() =>
  1653. migrationSequence++ === 0 ? "conflict-migration" : "retry-conflict-migration",
  1654. ),
  1655. now: () => 123,
  1656. });
  1657. await expect(
  1658. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1659. ).rejects.toMatchObject({
  1660. code: "workspace-task-identity-conflict",
  1661. retryable: false,
  1662. });
  1663. const evolved = new DatabaseSync(taskDbPath);
  1664. const insertEvolved = evolved.prepare(
  1665. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at, meta_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
  1666. );
  1667. insertEvolved.run(
  1668. canonicalKey,
  1669. workspacePath,
  1670. canonicalKey,
  1671. "second-conflict",
  1672. "Second",
  1673. 2,
  1674. 30,
  1675. JSON.stringify({ taskId: "second-conflict", offPeakTaskId: "off-peak-a" }),
  1676. );
  1677. insertEvolved.run(
  1678. sourceKey,
  1679. workspacePath,
  1680. sourceKey,
  1681. "second-conflict",
  1682. "Second",
  1683. 2,
  1684. 25,
  1685. JSON.stringify({ taskId: "second-conflict", offPeakTaskId: "off-peak-b" }),
  1686. );
  1687. evolved.close();
  1688. await expect(
  1689. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1690. ).rejects.toThrow("workspace task identity conflict");
  1691. const verify = new DatabaseSync(taskDbPath);
  1692. expect(
  1693. verify
  1694. .prepare(
  1695. "SELECT workspace_key, meta_json FROM tasks WHERE task_id = ? ORDER BY workspace_key",
  1696. )
  1697. .all("shared-task"),
  1698. ).toEqual([
  1699. {
  1700. workspace_key: canonicalKey,
  1701. meta_json: JSON.stringify({ taskId: "shared-task", cronAutomationId: "cron-a" }),
  1702. },
  1703. {
  1704. workspace_key: sourceKey,
  1705. meta_json: JSON.stringify({ taskId: "shared-task", cronAutomationId: "cron-b" }),
  1706. },
  1707. ]);
  1708. expect(
  1709. verify
  1710. .prepare(
  1711. "SELECT task_id, source_key, canonical_key, reason FROM workspace_migration_conflicts ORDER BY task_id",
  1712. )
  1713. .all(),
  1714. ).toEqual([
  1715. {
  1716. task_id: "second-conflict",
  1717. source_key: sourceKey,
  1718. canonical_key: canonicalKey,
  1719. reason: "task-identity-metadata-conflict",
  1720. },
  1721. {
  1722. task_id: "shared-task",
  1723. source_key: sourceKey,
  1724. canonical_key: canonicalKey,
  1725. reason: "task-identity-metadata-conflict",
  1726. },
  1727. ]);
  1728. expect(verify.prepare("SELECT workspace_key, task_id FROM task_group_members").all()).toEqual([
  1729. { workspace_key: sourceKey, task_id: "shared-task" },
  1730. ]);
  1731. expect(
  1732. verify
  1733. .prepare("SELECT status, error FROM workspace_migration_ledger ORDER BY created_at")
  1734. .all(),
  1735. ).toEqual([
  1736. {
  1737. status: "failed",
  1738. error: "workspace-task-identity-conflict",
  1739. },
  1740. ]);
  1741. verify.close();
  1742. const verifySessions = new DatabaseSync(sessionDbPath);
  1743. expect(verifySessions.prepare("SELECT workspace_id FROM session").all()).toEqual([
  1744. { workspace_id: sourceKey },
  1745. ]);
  1746. verifySessions.close();
  1747. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  1748. rows: [
  1749. expect.objectContaining({
  1750. migrationId: "conflict-migration",
  1751. workspacePath,
  1752. status: "failed",
  1753. conflicts: [
  1754. expect.objectContaining({ kind: "task-identity", taskId: "second-conflict" }),
  1755. expect.objectContaining({ kind: "task-identity", taskId: "shared-task" }),
  1756. ],
  1757. }),
  1758. ],
  1759. });
  1760. await repo.abandonFailedWorkspace(workspacePath);
  1761. await expect(repo.getAbandonedPathCount()).resolves.toBe(1);
  1762. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  1763. rows: [expect.objectContaining({ status: "abandoned" })],
  1764. });
  1765. await expect(
  1766. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: sourceKey }),
  1767. ).resolves.toEqual({ canonicalKey, mergedKeys: [] });
  1768. const afterAbandonedReopen = new DatabaseSync(taskDbPath);
  1769. expect(
  1770. afterAbandonedReopen
  1771. .prepare("SELECT migration_id, status FROM workspace_migration_ledger WHERE path = ?")
  1772. .all(workspacePath),
  1773. ).toEqual([{ migration_id: "conflict-migration", status: "abandoned" }]);
  1774. const abandonedActivity = afterAbandonedReopen
  1775. .prepare("SELECT abandoned_activity_json FROM workspace_migration_ledger WHERE path = ?")
  1776. .get(workspacePath) as { abandoned_activity_json: string };
  1777. expect(JSON.parse(abandonedActivity.abandoned_activity_json)).toMatchObject({
  1778. schemaVersion: 2,
  1779. digests: expect.any(Object),
  1780. });
  1781. afterAbandonedReopen
  1782. .prepare("INSERT INTO task_group_view_node_orders VALUES ('task', ?, 1, 1, 1)")
  1783. .run(JSON.stringify(["remote:ssh:unrelated:/other", "unrelated-task"]));
  1784. afterAbandonedReopen.close();
  1785. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  1786. rows: [expect.objectContaining({ status: "abandoned" })],
  1787. });
  1788. const bootstrapChange = new DatabaseSync(taskDbPath);
  1789. bootstrapChange
  1790. .prepare("INSERT INTO task_group_workspace_bootstraps VALUES (?, 'source-group', 1, 1)")
  1791. .run(sourceKey);
  1792. bootstrapChange.close();
  1793. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  1794. rows: [expect.objectContaining({ status: "abandoned-diverged" })],
  1795. });
  1796. const abandonedConfigDir = join(root, "sessions", getWorkspaceHash(workspacePath, sourceKey));
  1797. await mkdir(abandonedConfigDir, { recursive: true });
  1798. await writeFile(join(abandonedConfigDir, "changed-after-abandon.json"), "{}", "utf8");
  1799. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  1800. rows: [expect.objectContaining({ status: "abandoned-diverged" })],
  1801. });
  1802. await expect(repo.retryFailedWorkspace(workspacePath)).rejects.toThrow(
  1803. "workspace task identity conflict",
  1804. );
  1805. await expect(repo.listMigrationReports()).resolves.toMatchObject({
  1806. rows: expect.arrayContaining([
  1807. expect.objectContaining({ migrationId: "retry-conflict-migration", status: "failed" }),
  1808. expect.objectContaining({
  1809. migrationId: "conflict-migration",
  1810. status: "abandoned-diverged",
  1811. abandonedAt: 123,
  1812. }),
  1813. ]),
  1814. });
  1815. const flippedTasks = new DatabaseSync(taskDbPath);
  1816. flippedTasks
  1817. .prepare("UPDATE tasks SET updated_at = 200 WHERE workspace_key = ?")
  1818. .run(sourceKey);
  1819. flippedTasks.close();
  1820. const flippedSessions = new DatabaseSync(sessionDbPath);
  1821. flippedSessions
  1822. .prepare("UPDATE session SET time_updated = 200 WHERE workspace_id = ?")
  1823. .run(sourceKey);
  1824. flippedSessions.close();
  1825. await expect(
  1826. repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: canonicalKey }),
  1827. ).rejects.toThrow("workspace task identity conflict");
  1828. const verifyFlipped = new DatabaseSync(taskDbPath);
  1829. expect(
  1830. verifyFlipped
  1831. .prepare(
  1832. "SELECT COUNT(*) AS count, MAX(canonical_key) AS canonical_key FROM workspace_migration_ledger WHERE path = ? AND status = 'failed'",
  1833. )
  1834. .get(workspacePath),
  1835. ).toEqual({ count: 1, canonical_key: canonicalKey });
  1836. verifyFlipped.close();
  1837. });
  1838. // 写事务逐个并入 source,预检必须比较累积结果;否则 source 之间的冲突要到备份后才暴露,
  1839. // 且每次打开都会重新建账、备份两库。
  1840. it.each([
  1841. ["cronAutomationId", "canonical-missing-task"],
  1842. ["offPeakTaskId", "canonical-missing-task"],
  1843. ["forkedFromTaskId", "canonical-missing-task"],
  1844. ["cronAutomationId", "canonical-task-without-identity"],
  1845. ] as const)(
  1846. "detects %s conflicts between sources before backups when %s",
  1847. async (field, canonicalShape) => {
  1848. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-source-conflict-"));
  1849. const taskDbPath = join(root, "tasks-index.sqlite");
  1850. const sessionDbPath = join(root, "db.sqlite");
  1851. const backupRoot = join(root, "backups");
  1852. const workspacePath = "/srv/project";
  1853. const canonicalKey = "remote:ssh:a.example:22:alice:/srv/project";
  1854. const firstSourceKey = "remote:ssh:b.example:22:alice:/srv/project";
  1855. const secondSourceKey = "remote:ssh:c.example:22:alice:/srv/project";
  1856. (await createTaskDb(taskDbPath)).close();
  1857. createSessionDb(sessionDbPath).close();
  1858. let migrationSequence = 0;
  1859. const repo = new SourceServerWorkspaceAliasRepo({
  1860. taskDbPath,
  1861. sessionDbPath,
  1862. backupRoot,
  1863. migrationId: () => `migration-${++migrationSequence}`,
  1864. now: () => 123,
  1865. });
  1866. // 先发布 canonical,再写入 source 数据,避免 source session 参与首次选举。
  1867. await repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: canonicalKey });
  1868. const sessionDb = new DatabaseSync(sessionDbPath);
  1869. sessionDb
  1870. .prepare(
  1871. "INSERT INTO session (id, workspace_id, directory, path, time_updated) VALUES (?, ?, ?, ?, ?)",
  1872. )
  1873. .run("source-session", firstSourceKey, workspacePath, workspacePath, 10);
  1874. sessionDb.close();
  1875. const taskDb = new DatabaseSync(taskDbPath);
  1876. const insert = taskDb.prepare(
  1877. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at, meta_json) VALUES (?, ?, ?, ?, 'Shared', 1, ?, ?)",
  1878. );
  1879. if (canonicalShape === "canonical-task-without-identity") {
  1880. insert.run(canonicalKey, workspacePath, canonicalKey, "shared-task", 30, "{}");
  1881. }
  1882. insert.run(
  1883. firstSourceKey,
  1884. workspacePath,
  1885. firstSourceKey,
  1886. "shared-task",
  1887. 10,
  1888. JSON.stringify({ [field]: "identity-b" }),
  1889. );
  1890. insert.run(
  1891. secondSourceKey,
  1892. workspacePath,
  1893. secondSourceKey,
  1894. "shared-task",
  1895. 20,
  1896. JSON.stringify({ [field]: "identity-c" }),
  1897. );
  1898. const tasksBefore = taskDb
  1899. .prepare("SELECT workspace_key, meta_json FROM tasks ORDER BY workspace_key")
  1900. .all();
  1901. taskDb.close();
  1902. for (const attempt of [
  1903. () => repo.resolveCanonicalWorkspaceKey({ workspacePath }),
  1904. () => repo.resolveCanonicalWorkspaceKey({ workspacePath }),
  1905. () => repo.retryFailedWorkspace(workspacePath),
  1906. ]) {
  1907. await expect(attempt()).rejects.toMatchObject({
  1908. code: "workspace-task-identity-conflict",
  1909. retryable: false,
  1910. });
  1911. }
  1912. const verify = new DatabaseSync(taskDbPath);
  1913. expect(
  1914. verify.prepare("SELECT workspace_key, meta_json FROM tasks ORDER BY workspace_key").all(),
  1915. ).toEqual(tasksBefore);
  1916. expect(
  1917. verify
  1918. .prepare(
  1919. "SELECT migration_id, canonical_key, status, phase, task_backup_path, error FROM workspace_migration_ledger WHERE path = ?",
  1920. )
  1921. .all(workspacePath),
  1922. ).toEqual([
  1923. {
  1924. migration_id: "migration-1",
  1925. canonical_key: canonicalKey,
  1926. status: "failed",
  1927. phase: null,
  1928. task_backup_path: "",
  1929. error: "workspace-task-identity-conflict",
  1930. },
  1931. ]);
  1932. expect(
  1933. verify.prepare("SELECT task_id, source_key FROM workspace_migration_conflicts").all(),
  1934. ).toEqual([{ task_id: "shared-task", source_key: secondSourceKey }]);
  1935. verify.close();
  1936. const verifySessions = new DatabaseSync(sessionDbPath);
  1937. expect(verifySessions.prepare("SELECT workspace_id FROM session").all()).toEqual([
  1938. { workspace_id: firstSourceKey },
  1939. ]);
  1940. verifySessions.close();
  1941. await expect(access(backupRoot)).rejects.toMatchObject({ code: "ENOENT" });
  1942. await rm(root, { recursive: true, force: true });
  1943. },
  1944. );
  1945. it("merges a task shared by sources when their identities are compatible", async () => {
  1946. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-source-merge-"));
  1947. const taskDbPath = join(root, "tasks-index.sqlite");
  1948. const workspacePath = "/srv/project";
  1949. const canonicalKey = "remote:ssh:a.example:22:alice:/srv/project";
  1950. const firstSourceKey = "remote:ssh:b.example:22:alice:/srv/project";
  1951. const secondSourceKey = "remote:ssh:c.example:22:alice:/srv/project";
  1952. (await createTaskDb(taskDbPath)).close();
  1953. const repo = new SourceServerWorkspaceAliasRepo({
  1954. taskDbPath,
  1955. sessionDbPath: join(root, "absent-session.sqlite"),
  1956. backupRoot: join(root, "backups"),
  1957. });
  1958. await repo.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: canonicalKey });
  1959. const taskDb = new DatabaseSync(taskDbPath);
  1960. const insert = taskDb.prepare(
  1961. "INSERT INTO tasks (workspace_key, workspace_path, workspace_identity, task_id, title, created_at, updated_at, meta_json) VALUES (?, ?, ?, 'shared-task', 'Shared', 1, ?, ?)",
  1962. );
  1963. insert.run(firstSourceKey, workspacePath, firstSourceKey, 10, '{"cronAutomationId":"cron-x"}');
  1964. insert.run(
  1965. secondSourceKey,
  1966. workspacePath,
  1967. secondSourceKey,
  1968. 20,
  1969. '{"offPeakTaskId":"off-peak-x"}',
  1970. );
  1971. taskDb.close();
  1972. await expect(repo.resolveCanonicalWorkspaceKey({ workspacePath })).resolves.toMatchObject({
  1973. canonicalKey,
  1974. mergedKeys: [firstSourceKey, secondSourceKey],
  1975. });
  1976. const verify = new DatabaseSync(taskDbPath);
  1977. const rows = verify
  1978. .prepare("SELECT workspace_key, cron_automation_id, off_peak_task_id, meta_json FROM tasks")
  1979. .all();
  1980. expect(rows).toEqual([
  1981. {
  1982. workspace_key: canonicalKey,
  1983. cron_automation_id: "cron-x",
  1984. off_peak_task_id: "off-peak-x",
  1985. meta_json: expect.any(String),
  1986. },
  1987. ]);
  1988. expect(JSON.parse(String(rows[0]!.meta_json))).toMatchObject({
  1989. cronAutomationId: "cron-x",
  1990. offPeakTaskId: "off-peak-x",
  1991. });
  1992. expect(verify.prepare("SELECT status FROM workspace_migration_ledger").all()).toEqual([
  1993. { status: "completed" },
  1994. ]);
  1995. verify.close();
  1996. await rm(root, { recursive: true, force: true });
  1997. });
  1998. it("rebuilds the legacy ledger schema for phases and abandoned audit without losing rows", async () => {
  1999. const root = await mkdtemp(join(tmpdir(), "zcode-r3-workspace-alias-schema-"));
  2000. const taskDbPath = join(root, "tasks-index.sqlite");
  2001. const legacy = await createTaskDb(taskDbPath);
  2002. legacy.exec(`
  2003. CREATE TABLE workspace_migration_ledger (
  2004. migration_id TEXT PRIMARY KEY,
  2005. path TEXT NOT NULL,
  2006. canonical_key TEXT NOT NULL,
  2007. variant_keys_json TEXT NOT NULL,
  2008. status TEXT NOT NULL CHECK(status IN ('running', 'completed', 'failed')),
  2009. task_backup_path TEXT NOT NULL,
  2010. session_backup_path TEXT,
  2011. error TEXT,
  2012. created_at INTEGER NOT NULL,
  2013. updated_at INTEGER NOT NULL
  2014. );
  2015. CREATE TABLE workspace_migration_conflicts (
  2016. migration_id TEXT NOT NULL,
  2017. path TEXT NOT NULL,
  2018. task_id TEXT NOT NULL,
  2019. source_key TEXT NOT NULL,
  2020. canonical_key TEXT NOT NULL,
  2021. reason TEXT NOT NULL,
  2022. created_at INTEGER NOT NULL,
  2023. PRIMARY KEY (migration_id, task_id, source_key)
  2024. );
  2025. `);
  2026. const insertLedger = legacy.prepare(`
  2027. INSERT INTO workspace_migration_ledger VALUES (?, ?, ?, ?, ?, '', NULL, ?, 1, 1)
  2028. `);
  2029. insertLedger.run(
  2030. "completed-old",
  2031. "/completed",
  2032. "remote:ssh:canonical:/completed",
  2033. JSON.stringify(["remote:ssh:canonical:/completed"]),
  2034. "completed",
  2035. null,
  2036. );
  2037. insertLedger.run(
  2038. "failed-old",
  2039. "/failed",
  2040. "remote:ssh:canonical:/failed",
  2041. JSON.stringify(["remote:ssh:canonical:/failed", "remote:ssh:source:/failed"]),
  2042. "failed",
  2043. "workspace-task-identity-conflict",
  2044. );
  2045. insertLedger.run(
  2046. "running-old",
  2047. "/running",
  2048. "remote:ssh:canonical:/running",
  2049. JSON.stringify(["remote:ssh:canonical:/running", "remote:ssh:source:/running"]),
  2050. "running",
  2051. null,
  2052. );
  2053. legacy
  2054. .prepare(
  2055. "INSERT INTO workspace_migration_conflicts VALUES ('failed-old', '/failed', 'task-1', 'remote:ssh:source:/failed', 'remote:ssh:canonical:/failed', 'task-identity-metadata-conflict', 1)",
  2056. )
  2057. .run();
  2058. legacy.close();
  2059. const repo = new SourceServerWorkspaceAliasRepo({
  2060. taskDbPath,
  2061. sessionDbPath: join(root, "missing.sqlite"),
  2062. });
  2063. await expect(repo.getFailedPathCount()).resolves.toBe(1);
  2064. const upgraded = new DatabaseSync(taskDbPath);
  2065. upgraded
  2066. .prepare(`
  2067. INSERT INTO workspace_migration_ledger (
  2068. migration_id, path, canonical_key, variant_keys_json, status, phase,
  2069. task_backup_path, session_backup_path, error, created_at, updated_at,
  2070. abandoned_at, abandoned_trigger, abandoned_activity_json
  2071. ) VALUES ('abandoned-new', '/abandoned', 'remote:ssh:canonical:/abandoned', '[]',
  2072. 'abandoned', NULL, '', NULL, NULL, 2, 2, 2, 'user', '{}')
  2073. `)
  2074. .run();
  2075. expect(
  2076. upgraded
  2077. .prepare(
  2078. "SELECT migration_id, status, phase FROM workspace_migration_ledger ORDER BY migration_id",
  2079. )
  2080. .all(),
  2081. ).toEqual([
  2082. { migration_id: "abandoned-new", status: "abandoned", phase: null },
  2083. { migration_id: "completed-old", status: "completed", phase: "completed" },
  2084. { migration_id: "failed-old", status: "failed", phase: null },
  2085. { migration_id: "running-old", status: "running", phase: "preflight" },
  2086. ]);
  2087. expect(
  2088. upgraded
  2089. .prepare("SELECT conflict_kind, conflict_key, task_id FROM workspace_migration_conflicts")
  2090. .get(),
  2091. ).toEqual({
  2092. conflict_kind: "task-identity",
  2093. conflict_key: "task-1",
  2094. task_id: "task-1",
  2095. });
  2096. upgraded.close();
  2097. await expect(repo.getFailedPathCount()).resolves.toBe(1);
  2098. await expect(repo.getAbandonedPathCount()).resolves.toBe(1);
  2099. });
  2100. });