@north-light/api 0.3.754 → 0.3.756

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +0 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/health.d.ts +0 -54
  6. package/dist/api/routes.d.ts +0 -1
  7. package/dist/api/routes.js +0 -1
  8. package/dist/build-root.d.ts +0 -3
  9. package/dist/build-root.js +0 -9
  10. package/dist/commands/sys/branch.js +1 -1
  11. package/dist/commands/sys/daemon.js +1 -1
  12. package/dist/commands/sys.js +1 -2
  13. package/dist/core/canvas/executions.d.ts +0 -3
  14. package/dist/core/canvas/executions.js +1 -17
  15. package/dist/core/canvas/pid.d.ts +0 -10
  16. package/dist/core/canvas/pid.js +0 -16
  17. package/dist/core/directory/join.js +18 -1
  18. package/dist/core/grants/mirror.d.ts +0 -5
  19. package/dist/core/grants/mirror.js +0 -7
  20. package/dist/core/grants/sync.js +2 -2
  21. package/dist/core/human/page-schema.d.ts +1 -1
  22. package/dist/core/io.js +0 -5
  23. package/dist/core/layout.d.ts +0 -2
  24. package/dist/core/layout.js +2 -19
  25. package/dist/core/runs/operations.js +6 -0
  26. package/dist/daemon/api/map.d.ts +1 -6
  27. package/dist/daemon/api/map.js +0 -16
  28. package/dist/daemon/api/operations.js +0 -1
  29. package/dist/daemon/control.d.ts +0 -8
  30. package/dist/daemon/manage.js +1 -1
  31. package/package.json +1 -1
  32. package/dist/commands/sys/migrate.d.ts +0 -1
  33. package/dist/commands/sys/migrate.js +0 -79
  34. package/dist/core/layout-migrate/index.d.ts +0 -38
  35. package/dist/core/layout-migrate/index.js +0 -523
  36. package/dist/core/layout-migrate/paths.d.ts +0 -30
  37. package/dist/core/layout-migrate/paths.js +0 -118
  38. package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
  39. package/dist/core/layout-migrate/stored-paths.js +0 -424
  40. package/dist/core/layout-migrate/stores.d.ts +0 -30
  41. package/dist/core/layout-migrate/stores.js +0 -543
  42. package/dist/core/locked-file.d.ts +0 -27
  43. package/dist/core/locked-file.js +0 -121
  44. package/dist/core/scoped-state/db.d.ts +0 -17
  45. package/dist/core/scoped-state/db.js +0 -271
  46. package/dist/core/scoped-state/legacy-profiles.d.ts +0 -11
  47. package/dist/core/scoped-state/legacy-profiles.js +0 -65
  48. package/dist/core/scoped-state/migrate.d.ts +0 -15
  49. package/dist/core/scoped-state/migrate.js +0 -332
  50. package/dist/core/scoped-state/schema.d.ts +0 -14
  51. package/dist/core/scoped-state/schema.js +0 -52
  52. package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
  53. package/dist/migrations/004-canvas-documents/apply.js +0 -113
  54. package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
  55. package/dist/migrations/004-canvas-documents/index.js +0 -89
  56. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
  57. package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
  58. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
  59. package/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
  60. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
  61. package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
  62. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
  63. package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
  64. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
  65. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
  66. package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
  67. package/dist/migrations/004-canvas-documents/plan.js +0 -410
  68. package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
  69. package/dist/migrations/004-canvas-documents/pointers.js +0 -95
  70. package/dist/migrations/activation.d.ts +0 -17
  71. package/dist/migrations/activation.js +0 -46
@@ -1,543 +0,0 @@
1
- import { DatabaseSync } from 'node:sqlite';
2
- import { closeSync, copyFileSync, existsSync, realpathSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
3
- import { execFileSync } from 'node:child_process';
4
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
- import { LEGACY_LOCAL_PERSON } from '../canvas/legacy-person.js';
6
- import { profileSpace } from '../layout.js';
7
- import { isJunkFile, movePath, sameFile, setAside, setAsidePath } from './index.js';
8
- import { rewriteBodyPaths } from './stored-paths.js';
9
- function gitInRepo(repo, args) {
10
- execFileSync('git', ['-c', `safe.directory=${repo}`, '-C', repo, ...args], { stdio: 'pipe' });
11
- }
12
- function physical(path, migration) {
13
- const { root, targetRoot } = migration.map.old;
14
- return resolve(root, relative(targetRoot, path));
15
- }
16
- /** Writable only for a real run's resolutions (closing a worktree row, clearing a lost transcript path). */
17
- function canvasDb(migration, writable = false) {
18
- const { old } = migration.map;
19
- const original = join(old.canvas, 'canvas.db');
20
- const moved = join(old.root, 'runtime', 'canvas.db');
21
- const path = existsSync(original) ? original : moved;
22
- return existsSync(path) && lstatSync(path).size > 0 ? new DatabaseSync(path, { readOnly: !writable || migration.dryRun }) : null;
23
- }
24
- function nodeApps(db) {
25
- return new Map(db.prepare('SELECT node_id, grantee FROM nodes').all().map(({ node_id, grantee }) => {
26
- const app = grantee === LEGACY_LOCAL_PERSON ? 'terminal' : grantee.startsWith('app:') ? grantee.slice(4) : '';
27
- if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(app))
28
- throw new Error(`node ${node_id} has no valid app`);
29
- return [node_id, app];
30
- }));
31
- }
32
- /** The profile-owned files folder in its app: where a profile's leftovers the layout has no slot for are kept. */
33
- function profileFiles(app, id, migration) {
34
- return join(migration.map.old.targetRoot, 'apps', app, 'files', 'profiles', id);
35
- }
36
- /**
37
- * Merge an old profile home into the app home. A file both hold with different
38
- * bytes keeps the app home's copy; the profile's copy moves to `divert` at the
39
- * same relative path.
40
- */
41
- function mergeHome(from, to, divert, migration) {
42
- if (!existsSync(from))
43
- return;
44
- if (!existsSync(to)) {
45
- movePath(from, to, migration);
46
- return;
47
- }
48
- const a = lstatSync(from);
49
- const b = lstatSync(to);
50
- if (a.isDirectory() && b.isDirectory()) {
51
- for (const name of readdirSync(from))
52
- mergeHome(join(from, name), join(to, name), join(divert, name), migration);
53
- rmdirSync(from);
54
- return;
55
- }
56
- if (a.isFile() && b.isFile() && sameFile(from, to)) {
57
- unlinkSync(from);
58
- return;
59
- }
60
- const target = physical(divert, migration);
61
- if (!migration.dryRun)
62
- movePath(from, target, migration);
63
- migration.resolutions.push(`profile-home: ${to} differs from the profile's ${from}; kept the app home's copy, moved the profile's to ${target}`);
64
- }
65
- function previewHome(from, to, divert, migration) {
66
- if (!existsSync(from) || !existsSync(to))
67
- return;
68
- const a = lstatSync(from);
69
- const b = lstatSync(to);
70
- if (a.isDirectory() && b.isDirectory()) {
71
- for (const name of readdirSync(from))
72
- previewHome(join(from, name), join(to, name), join(divert, name), migration);
73
- return;
74
- }
75
- if (a.isFile() && b.isFile() && sameFile(from, to))
76
- return;
77
- migration.resolutions.push(`profile-home: ${to} differs from the profile's ${from}; kept the app home's copy, moved the profile's to ${physical(divert, migration)}`);
78
- }
79
- function bodyPath(migration, from, to) {
80
- if (!migration.bodyPaths.some(([old]) => old === from))
81
- migration.bodyPaths.push([from, to]);
82
- }
83
- /**
84
- * A profile is its scoped-state row; the row is authoritative even when an
85
- * interrupted run already removed the old profile folder. There is no profile
86
- * folder in the new layout: the old folder's own path (the profile's
87
- * scope_owners.root) becomes its memory folder. What else the folder holds is
88
- * the profile's own files and moves to `apps/<app>/files/profiles/<id>/`; a
89
- * folder with no row moves there whole, under the terminal app.
90
- */
91
- export function profileFolders(migration) {
92
- const { map } = migration;
93
- const scoped = [join(map.old.scope, 'operations.db'), join(map.old.root, 'runtime', 'scope', 'operations.db')].find(existsSync);
94
- const profileDb = scoped ? new DatabaseSync(scoped, { readOnly: true }) : null;
95
- const profileApps = new Map();
96
- try {
97
- if (profileDb && profileDb.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='profiles'").get()) {
98
- for (const row of profileDb.prepare('SELECT id, grantee FROM profiles').all())
99
- profileApps.set(row.id, row.grantee);
100
- }
101
- }
102
- finally {
103
- profileDb?.close();
104
- }
105
- const targets = new Map();
106
- for (const [id, grantee] of profileApps) {
107
- const app = grantee == null || grantee === LEGACY_LOCAL_PERSON ? 'terminal' : grantee.startsWith('app:') ? grantee.slice(4) : '';
108
- const target = profileSpace(app, id);
109
- const old = join(map.old.storedScope, 'profiles', id);
110
- map.retire(old, target.dir);
111
- map.add(join(old, 'memory'), target.dir);
112
- map.add(join(old, 'env.json'), target.env);
113
- map.add(join(old, 'home'), target.home);
114
- targets.set(id, { target, app });
115
- }
116
- const profiles = join(map.old.scope, 'profiles');
117
- const result = { folders: [], junk: [], aside: [] };
118
- if (!existsSync(profiles))
119
- return result;
120
- for (const id of readdirSync(profiles)) {
121
- const source = join(profiles, id);
122
- if (!lstatSync(source).isDirectory()) {
123
- (isJunkFile(id) ? result.junk : result.aside).push(source);
124
- continue;
125
- }
126
- if (id === '.locks') {
127
- for (const name of readdirSync(source)) {
128
- const path = join(source, name);
129
- if (!(name.endsWith('.lock') && lstatSync(path).isFile()) && !isJunkFile(name))
130
- result.aside.push(path);
131
- }
132
- continue;
133
- }
134
- const stored = join(map.old.storedScope, 'profiles', id);
135
- const owned = targets.get(id);
136
- if (!owned) {
137
- const files = profileFiles('terminal', id, migration);
138
- map.add(stored, files);
139
- bodyPath(migration, stored, files);
140
- result.folders.push({ id, source, target: null, files, extras: [] });
141
- continue;
142
- }
143
- const files = profileFiles(owned.app, id, migration);
144
- const extras = [];
145
- for (const name of readdirSync(source)) {
146
- const stat = lstatSync(join(source, name));
147
- const slot = name === 'memory' || name === 'home' ? stat.isDirectory()
148
- : name === 'env.json' || name === 'profile.json' || name.endsWith('.lock') ? stat.isFile()
149
- : isJunkFile(name);
150
- if (slot)
151
- continue;
152
- extras.push(name);
153
- map.add(join(stored, name), join(files, name));
154
- bodyPath(migration, join(stored, name), join(files, name));
155
- }
156
- result.folders.push({ id, source, target: owned.target, files, extras });
157
- }
158
- return result;
159
- }
160
- function profileLines(plan, migration) {
161
- for (const folder of plan.folders) {
162
- if (!folder.target)
163
- migration.resolutions.push(`profile-folder: ${folder.source} has no profile row; moved whole to ${physical(folder.files, migration)}`);
164
- for (const name of folder.extras)
165
- migration.resolutions.push(`profile-extra: ${join(folder.source, name)} moved to ${physical(join(folder.files, name), migration)}`);
166
- }
167
- for (const path of plan.junk)
168
- migration.resolutions.push(`profile-leftover: deleted ${path} (not profile data)`);
169
- for (const path of plan.aside)
170
- migration.resolutions.push(`profile-leftover: ${path} is not a profile; moved to ${setAsidePath(migration, 'profiles', basename(path))}`);
171
- }
172
- export function memoryAndProfiles(migration) {
173
- const { map } = migration;
174
- movePath(join(map.old.scope, 'memory'), join(map.old.root, 'user', 'memory'), migration);
175
- const db = canvasDb(migration);
176
- if (db) {
177
- try {
178
- for (const [id, app] of nodeApps(db)) {
179
- const target = join(map.old.root, 'apps', app, 'memory', 'nodes', id);
180
- movePath(join(map.old.root, 'apps', app, 'nodes', id, 'context', 'memory'), target, migration);
181
- // A partial R23a run may have left this node at its original location.
182
- movePath(join(map.old.canvas, 'nodes', id, 'context', 'memory'), target, migration);
183
- }
184
- }
185
- finally {
186
- db.close();
187
- }
188
- }
189
- const plan = profileFolders(migration);
190
- profileLines(plan, migration);
191
- for (const { source, target, files, extras } of plan.folders) {
192
- if (!target) {
193
- movePath(source, physical(files, migration), migration, true);
194
- continue;
195
- }
196
- for (const name of extras)
197
- movePath(join(source, name), physical(join(files, name), migration), migration);
198
- movePath(join(source, 'memory'), physical(target.dir, migration), migration);
199
- movePath(join(source, 'env.json'), physical(target.env, migration), migration);
200
- mergeHome(join(source, 'home'), physical(target.home, migration), join(files, 'home'), migration);
201
- // Only the legacy manifest, lock files and junk remain; the scoped row replaces them.
202
- for (const name of readdirSync(source))
203
- unlinkSync(join(source, name));
204
- rmdirSync(source);
205
- migration.moved++;
206
- migration.changes.push(`${source} (removed)`);
207
- }
208
- for (const path of plan.junk)
209
- unlinkSync(path);
210
- for (const path of plan.aside)
211
- setAside(path, 'profiles', migration);
212
- const profiles = join(map.old.scope, 'profiles');
213
- if (existsSync(profiles)) {
214
- const locks = join(profiles, '.locks');
215
- if (existsSync(locks)) {
216
- for (const name of readdirSync(locks))
217
- unlinkSync(join(locks, name));
218
- rmdirSync(locks);
219
- }
220
- rmdirSync(profiles);
221
- }
222
- }
223
- /** Retain the old credential volume's session files as the rollback copy. */
224
- function moveSession(from, to, migration, retainSource) {
225
- if (!existsSync(from))
226
- return;
227
- if (!lstatSync(from).isFile())
228
- throw new Error(`session path is not a file: ${from}`);
229
- mkdirSync(dirname(to), { recursive: true });
230
- if (existsSync(to)) {
231
- if (lstatSync(to).isFile() && sameFile(from, to))
232
- return;
233
- const aside = setAside(to, 'replaced', migration, relative(migration.map.old.root, to));
234
- migration.resolutions.push(`stray-destination: ${to} predates the migration; moved it to ${aside} and put ${from} in its place`);
235
- }
236
- if (retainSource) {
237
- const temp = join(dirname(to), `.${basename(to)}.migrating`);
238
- if (existsSync(temp))
239
- unlinkSync(temp);
240
- copyFileSync(from, temp);
241
- const fd = openSync(temp, 'r');
242
- try {
243
- fsyncSync(fd);
244
- }
245
- finally {
246
- closeSync(fd);
247
- }
248
- if (!sameFile(from, temp))
249
- throw new Error(`session copy verification failed: ${from}`);
250
- renameSync(temp, to);
251
- migration.moved++;
252
- migration.changes.push(`${from} -> ${to} (source retained)`);
253
- return;
254
- }
255
- renameSync(from, to);
256
- migration.moved++;
257
- migration.changes.push(`${from} -> ${to}`);
258
- }
259
- /** A transcript missing from both paths is gone: its binding keeps no path, unless it is a live node's current session. */
260
- function lostTranscripts(migration, db, rows) {
261
- const live = new Set(db.prepare("SELECT s.transcript_path AS path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.unbound_at IS NULL AND n.status IN ('active', 'idle') AND s.transcript_path IS NOT NULL").all().map(row => row.path));
262
- const clear = migration.dryRun ? null : db.prepare('UPDATE sessions SET transcript_path = NULL WHERE transcript_path = ?');
263
- for (const row of rows) {
264
- if (existsSync(row.source) || existsSync(physical(row.destination, migration)))
265
- continue;
266
- if (live.has(row.transcript_path)) {
267
- migration.resolutions.push(`lost-transcript: ${row.transcript_path} is missing but is a live node's current session; kept its path`);
268
- continue;
269
- }
270
- clear?.run(row.transcript_path);
271
- migration.resolutions.push(`lost-transcript: ${row.transcript_path} is missing from both paths; cleared the session's transcript path`);
272
- }
273
- }
274
- export function conversations(migration) {
275
- const db = canvasDb(migration, true);
276
- if (!db)
277
- return;
278
- try {
279
- const apps = nodeApps(db);
280
- // Match conversationOwner/pathFor: a transferred session's active or
281
- // latest-created binding owns the file, not the last binding modified.
282
- const rows = db.prepare('SELECT session_id, node_id, transcript_path FROM sessions WHERE transcript_path IS NOT NULL ORDER BY session_id, (unbound_at IS NULL) DESC, created_at DESC, rowid DESC').all();
283
- const owners = new Map();
284
- const paths = new Map();
285
- const pathBindings = new Map();
286
- for (const row of rows) {
287
- if (!owners.has(row.session_id))
288
- owners.set(row.session_id, row.node_id);
289
- pathBindings.set(row.transcript_path, (pathBindings.get(row.transcript_path) ?? 0) + 1);
290
- const ids = paths.get(row.transcript_path) ?? new Set();
291
- ids.add(row.session_id);
292
- paths.set(row.transcript_path, ids);
293
- }
294
- const seen = new Set();
295
- const planned = [];
296
- for (const { session_id, node_id, transcript_path } of rows) {
297
- if (seen.has(transcript_path))
298
- continue;
299
- seen.add(transcript_path);
300
- if (paths.get(transcript_path).size !== 1)
301
- throw new Error(`two conversations share a transcript: ${transcript_path}`);
302
- const owner = pathBindings.get(transcript_path) > 1 ? owners.get(session_id) : node_id;
303
- const app = apps.get(owner);
304
- if (!app)
305
- throw new Error(`session belongs to unknown node: ${owner}`);
306
- if (!isAbsolute(transcript_path))
307
- throw new Error(`session path is not absolute: ${transcript_path}`);
308
- const destination = join(migration.map.old.targetRoot, 'apps', app, 'conversations', owner, basename(transcript_path));
309
- if (transcript_path === destination)
310
- continue;
311
- const agent = transcript_path === migration.map.old.storedAgent || transcript_path.startsWith(migration.map.old.storedAgent + sep);
312
- const source = agent ? join(migration.map.old.agent, relative(migration.map.old.storedAgent, transcript_path)) : transcript_path;
313
- planned.push({ transcript_path, destination, source, retain: process.platform === 'linux' && agent });
314
- }
315
- lostTranscripts(migration, db, planned);
316
- for (const { transcript_path, destination } of planned)
317
- migration.map.add(transcript_path, destination);
318
- if (migration.dryRun)
319
- return;
320
- for (const { destination, source, retain } of planned)
321
- moveSession(source, physical(destination, migration), migration, retain);
322
- }
323
- finally {
324
- db.close();
325
- }
326
- }
327
- export function repairMovedRepositories(migration) {
328
- if (process.platform !== 'linux')
329
- return;
330
- const db = canvasDb(migration);
331
- if (!db)
332
- return;
333
- try {
334
- const rows = db.prepare('SELECT node_id, path, repo_root FROM worktrees').all();
335
- const apps = nodeApps(db);
336
- for (const row of rows) {
337
- const repository = migration.map.mapPath(row.repo_root);
338
- if (repository === row.repo_root)
339
- continue;
340
- const app = apps.get(row.node_id);
341
- if (!app)
342
- throw new Error(`worktree belongs to unknown node: ${row.node_id}`);
343
- const checkout = physical(join(migration.map.old.targetRoot, 'apps', app, 'nodes', row.node_id, 'worktree'), migration);
344
- if (!existsSync(checkout))
345
- continue;
346
- gitInRepo(physical(repository, migration), ['worktree', 'repair', checkout]);
347
- const oldCheckout = row.path.startsWith(migration.map.old.storedCanvas + sep)
348
- ? join(migration.map.old.canvas, relative(migration.map.old.storedCanvas, row.path)) : row.path;
349
- repairSubmoduleLinks(oldCheckout, checkout, migration);
350
- }
351
- }
352
- finally {
353
- db.close();
354
- }
355
- }
356
- function repairSubmoduleLinks(oldCheckout, checkout, migration) {
357
- const visit = (dir) => {
358
- for (const name of readdirSync(dir)) {
359
- const path = join(dir, name);
360
- if (name === '.git' && path !== join(checkout, '.git') && lstatSync(path).isFile()) {
361
- const text = readFileSync(path, 'utf8');
362
- if (!text.startsWith('gitdir: '))
363
- throw new Error(`invalid submodule git link: ${path}`);
364
- const link = text.slice('gitdir: '.length).trim();
365
- const current = resolve(dirname(path), link);
366
- const oldLocation = join(oldCheckout, relative(checkout, path));
367
- const previous = resolve(dirname(oldLocation), link);
368
- const gitDir = existsSync(current) ? current : previous;
369
- if (!existsSync(gitDir))
370
- throw new Error(`submodule git directory missing: ${oldLocation}`);
371
- const mapped = migration?.map.mapPath(gitDir) ?? gitDir;
372
- const target = migration && mapped !== gitDir ? physical(mapped, migration) : gitDir;
373
- if (!existsSync(target))
374
- throw new Error(`moved submodule git directory missing: ${target}`);
375
- if (current !== target)
376
- writeFileSync(path, `gitdir: ${relative(dirname(path), target)}\n`);
377
- const config = join(target, 'config');
378
- const textConfig = readFileSync(config, 'utf8');
379
- if (!/^\s*worktree\s*=.*$/m.test(textConfig))
380
- throw new Error(`submodule has no worktree setting: ${config}`);
381
- const value = JSON.stringify(relative(target, dirname(path)));
382
- const updated = textConfig.replace(/^(\s*worktree\s*=).*$/m, `$1 ${value}`);
383
- if (updated !== textConfig)
384
- writeFileSync(config, updated);
385
- }
386
- else if (name !== '.git' && lstatSync(path).isDirectory())
387
- visit(path);
388
- }
389
- };
390
- visit(checkout);
391
- }
392
- function gitOut(repo, args) {
393
- return execFileSync('git', ['-c', `safe.directory=${repo}`, '-C', repo, ...args], { stdio: 'pipe', encoding: 'utf8' });
394
- }
395
- function real(path) {
396
- try {
397
- return realpathSync(path);
398
- }
399
- catch {
400
- return resolve(path);
401
- }
402
- }
403
- /** Whether the repository still records this checkout as one of its worktrees. */
404
- function registered(repo, checkout) {
405
- try {
406
- const want = real(checkout);
407
- return gitOut(repo, ['worktree', 'list', '--porcelain']).split('\n')
408
- .some(line => line.startsWith('worktree ') && real(line.slice('worktree '.length)) === want);
409
- }
410
- catch {
411
- return false;
412
- }
413
- }
414
- /** `git worktree repair` can relink a checkout only while the repository still holds its admin folder. */
415
- function repairable(repo, checkout) {
416
- if (!existsSync(repo))
417
- return false;
418
- try {
419
- const link = readFileSync(join(checkout, '.git'), 'utf8');
420
- if (!link.startsWith('gitdir: '))
421
- return false;
422
- return existsSync(resolve(checkout, link.slice('gitdir: '.length).trim()));
423
- }
424
- catch {
425
- return false;
426
- }
427
- }
428
- function closeRow(db, row, migration) {
429
- if (migration.dryRun || (row.state !== 'open' && row.cleanup_state === 'complete'))
430
- return;
431
- db.prepare("UPDATE worktrees SET state = CASE WHEN state = 'open' THEN 'closed' ELSE state END, cleanup_state = 'complete', closed_at = COALESCE(closed_at, ?) WHERE node_id = ?")
432
- .run(new Date().toISOString(), row.node_id);
433
- }
434
- export function worktrees(migration) {
435
- const db = canvasDb(migration, true);
436
- if (!db)
437
- return;
438
- try {
439
- const apps = nodeApps(db);
440
- const rows = db.prepare('SELECT node_id, state, cleanup_state, path, repo_root FROM worktrees').all();
441
- for (const row of rows) {
442
- const app = apps.get(row.node_id);
443
- if (!app)
444
- throw new Error(`worktree belongs to unknown node: ${row.node_id}`);
445
- if (!isAbsolute(row.path))
446
- throw new Error(`worktree path is not absolute: ${row.path}`);
447
- const destination = join(migration.map.old.targetRoot, 'apps', app, 'nodes', row.node_id, 'worktree');
448
- if (row.path === destination)
449
- continue;
450
- const from = row.path === migration.map.old.storedCanvas || row.path.startsWith(migration.map.old.storedCanvas + sep)
451
- ? join(migration.map.old.canvas, relative(migration.map.old.storedCanvas, row.path)) : row.path;
452
- const to = physical(destination, migration);
453
- if (!existsSync(from)) {
454
- migration.map.add(row.path, destination);
455
- if (!existsSync(to)) {
456
- if (!(row.state !== 'open' && row.cleanup_state === 'complete')) {
457
- closeRow(db, row, migration);
458
- migration.resolutions.push(`missing-worktree: ${row.path} (node ${row.node_id}) is gone; closed its row`);
459
- }
460
- }
461
- else if (!migration.dryRun && existsSync(row.repo_root)) {
462
- gitInRepo(row.repo_root, ['worktree', 'repair', to]);
463
- repairSubmoduleLinks(from, to);
464
- }
465
- continue;
466
- }
467
- if (!registered(row.repo_root, from)) {
468
- // Only an open row is still in use; a closed row's leftover folder is set aside.
469
- if (row.state === 'open' && repairable(row.repo_root, from)) {
470
- migration.resolutions.push(`unregistered-worktree: ${row.path} (node ${row.node_id}) is not registered in ${row.repo_root}; relinked it with git worktree repair`);
471
- if (!migration.dryRun)
472
- gitInRepo(row.repo_root, ['worktree', 'repair', from]);
473
- }
474
- else {
475
- const aside = setAsidePath(migration, 'worktrees', basename(from));
476
- migration.resolutions.push(`unregistered-worktree: ${row.path} (node ${row.node_id}${row.state === 'open' ? '' : `, ${row.state}`}) is not a worktree of ${existsSync(row.repo_root) ? row.repo_root : `the missing repository ${row.repo_root}`}; ${row.state === 'open' ? 'closed its row and ' : ''}moved the folder to ${aside}`);
477
- // `records` mapped this path into the node's folder; it goes aside instead.
478
- migration.map.redirect(row.path, join(migration.map.old.targetRoot, relative(migration.map.old.root, aside)));
479
- if (!migration.dryRun) {
480
- setAside(from, 'worktrees', migration);
481
- closeRow(db, row, migration);
482
- }
483
- continue;
484
- }
485
- }
486
- migration.map.add(row.path, destination);
487
- if (existsSync(to)) {
488
- const aside = setAsidePath(migration, 'replaced', relative(migration.map.old.root, to));
489
- migration.resolutions.push(`stray-destination: ${to} predates the migration; moved it to ${aside} and put the worktree ${from} in its place`);
490
- if (!migration.dryRun)
491
- setAside(to, 'replaced', migration, relative(migration.map.old.root, to));
492
- }
493
- if (migration.dryRun)
494
- continue;
495
- mkdirSync(dirname(to), { recursive: true });
496
- // Run before the hosted work directory is moved so git can still find its
497
- // common directory. `git worktree move` repairs the repository's records.
498
- try {
499
- gitInRepo(row.repo_root, ['worktree', 'move', from, to]);
500
- }
501
- catch (error) {
502
- const stderr = String(error.stderr ?? '');
503
- if (!stderr.includes('submodule'))
504
- throw error;
505
- renameSync(from, to);
506
- gitInRepo(row.repo_root, ['worktree', 'repair', to]);
507
- }
508
- repairSubmoduleLinks(from, to);
509
- migration.moved++;
510
- migration.changes.push(`${from} -> ${to} (git worktree move)`);
511
- }
512
- }
513
- finally {
514
- db.close();
515
- }
516
- if (!migration.dryRun)
517
- pruneOldNodeFolders(migration);
518
- }
519
- /** `records` keeps a node folder while its worktree is still inside; once the worktree moved, the folder is empty. */
520
- function pruneOldNodeFolders(migration) {
521
- const nodes = join(migration.map.old.canvas, 'nodes');
522
- if (!existsSync(nodes))
523
- return;
524
- for (const id of readdirSync(nodes)) {
525
- const path = join(nodes, id);
526
- if (lstatSync(path).isDirectory() && readdirSync(path).length === 0)
527
- rmdirSync(path);
528
- }
529
- if (readdirSync(nodes).length === 0)
530
- rmdirSync(nodes);
531
- }
532
- /** Every resolution the real run would make, computed without changing anything. */
533
- export function previewStores(migration) {
534
- worktrees(migration);
535
- const plan = profileFolders(migration);
536
- profileLines(plan, migration);
537
- for (const { source, target, files } of plan.folders) {
538
- if (target)
539
- previewHome(join(source, 'home'), physical(target.home, migration), join(files, 'home'), migration);
540
- }
541
- conversations(migration);
542
- rewriteBodyPaths(migration);
543
- }
@@ -1,27 +0,0 @@
1
- export type LockResult<T> = {
2
- result: T;
3
- next?: string;
4
- };
5
- /** Throws if this lock was compromised (stolen/expired) since acquisition. Callers that write
6
- * from INSIDE the critical section must call it immediately before that write, because the
7
- * post-`fn` check cannot un-write a file the callback already replaced. */
8
- export type LockHeldGuard = () => void;
9
- export type LockedFilePublish = (next: string) => void;
10
- export interface LockedFileBackend {
11
- withLockAsync<T>(fn: (current: string | undefined, assertLockHeld: LockHeldGuard, publish: LockedFilePublish) => Promise<LockResult<T>>): Promise<T>;
12
- /** The current whole-file contents, or undefined when the file does not exist yet.
13
- * Lock-free: every writer replaces the file by atomic rename. */
14
- readUnlocked(): string | undefined;
15
- }
16
- /** A 0600 JSON file guarded by a cross-process `proper-lockfile` lock on its own path. */
17
- export declare class LockedJsonFile implements LockedFileBackend {
18
- private readonly path;
19
- private readonly durable;
20
- private readonly initialContent;
21
- constructor(path: string, durable?: boolean, initialContent?: string);
22
- readUnlocked(): string | undefined;
23
- private ensureFile;
24
- /** Acquire the lock without blocking the event loop, keeping every read-modify-write
25
- * callback on the same asynchronous path. */
26
- withLockAsync<T>(fn: (current: string | undefined, assertLockHeld: LockHeldGuard, publish: LockedFilePublish) => Promise<LockResult<T>>): Promise<T>;
27
- }