@north-light/cli 0.3.755 → 0.3.757

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 (138) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +3 -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 +1 -1
  8. package/dist/build-root.d.ts +0 -3
  9. package/dist/build-root.js +1 -1
  10. package/dist/builtin-memory/internal/storage-tiers.md +3 -3
  11. package/dist/cli.js +8 -9
  12. package/dist/clients/attach/viewer.js +474 -474
  13. package/dist/commands/profile/new.js +1 -1
  14. package/dist/commands/profile/project.js +1 -1
  15. package/dist/commands/sys/branch.js +1 -1
  16. package/dist/commands/sys/daemon.js +1 -1
  17. package/dist/commands/sys.js +1 -1
  18. package/dist/core/bootstrap.js +1 -1
  19. package/dist/core/canvas/boot.d.ts +0 -25
  20. package/dist/core/canvas/boot.js +1 -1
  21. package/dist/core/canvas/executions.d.ts +0 -3
  22. package/dist/core/canvas/executions.js +1 -1
  23. package/dist/core/canvas/pid.d.ts +0 -10
  24. package/dist/core/canvas/pid.js +5 -5
  25. package/dist/core/directory/join.js +1 -1
  26. package/dist/core/grants/mirror.d.ts +0 -5
  27. package/dist/core/grants/mirror.js +6 -6
  28. package/dist/core/grants/sync.js +1 -1
  29. package/dist/core/human/page-schema.d.ts +1 -1
  30. package/dist/core/io.js +4 -4
  31. package/dist/core/layout.d.ts +0 -2
  32. package/dist/core/layout.js +2 -2
  33. package/dist/core/profiles/manifest.js +1 -1
  34. package/dist/core/profiles/project-dir.d.ts +3 -0
  35. package/dist/core/profiles/project-dir.js +1 -0
  36. package/dist/core/scoped-state/db.js +2 -2
  37. package/dist/daemon/api/handlers/daemon.js +1 -1
  38. package/dist/daemon/api/handlers/profiles.js +1 -1
  39. package/dist/daemon/api/map.d.ts +1 -6
  40. package/dist/daemon/api/map.js +2 -2
  41. package/dist/daemon/api/operations.js +1 -1
  42. package/dist/daemon/api/server.js +1 -1
  43. package/dist/daemon/control.d.ts +0 -8
  44. package/dist/daemon/crtrd.js +18 -20
  45. package/dist/daemon/manage.js +3 -3
  46. package/package.json +3 -3
  47. package/packages/crouter-api/dist/api/client.js +0 -3
  48. package/packages/crouter-api/dist/api/contract.js +1 -1
  49. package/packages/crouter-api/dist/api/routes.js +0 -1
  50. package/packages/crouter-api/dist/build-root.js +0 -9
  51. package/packages/crouter-api/dist/commands/profile/new.js +2 -2
  52. package/packages/crouter-api/dist/commands/profile/project.js +2 -1
  53. package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
  54. package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
  55. package/packages/crouter-api/dist/commands/sys.js +1 -2
  56. package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
  57. package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
  58. package/packages/crouter-api/dist/core/directory/join.js +18 -1
  59. package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
  60. package/packages/crouter-api/dist/core/grants/sync.js +2 -2
  61. package/packages/crouter-api/dist/core/io.js +0 -5
  62. package/packages/crouter-api/dist/core/layout.js +2 -19
  63. package/packages/crouter-api/dist/core/profiles/manifest.js +12 -18
  64. package/packages/crouter-api/dist/core/profiles/project-dir.js +20 -0
  65. package/packages/crouter-api/dist/daemon/api/map.js +0 -16
  66. package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
  67. package/packages/crouter-api/dist/daemon/manage.js +1 -1
  68. package/packages/crouter-api/package.json +1 -1
  69. package/packages/crouter-identity/package.json +1 -1
  70. package/packages/crouter-plugin/package.json +3 -3
  71. package/runtime.lock.json +14 -14
  72. package/scripts/install-runtime.mjs +1 -30
  73. package/dist/commands/sys/migrate.d.ts +0 -1
  74. package/dist/commands/sys/migrate.js +0 -1
  75. package/dist/core/canvas/import-sqlite.d.ts +0 -46
  76. package/dist/core/canvas/import-sqlite.js +0 -19
  77. package/dist/core/canvas/migrations.d.ts +0 -16
  78. package/dist/core/canvas/migrations.js +0 -1073
  79. package/dist/core/feed/inbox-migrate.d.ts +0 -11
  80. package/dist/core/feed/inbox-migrate.js +0 -3
  81. package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
  82. package/dist/core/graph/bodies-boot-copy.js +0 -1
  83. package/dist/core/layout-migrate/index.d.ts +0 -38
  84. package/dist/core/layout-migrate/index.js +0 -4
  85. package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
  86. package/dist/core/layout-migrate/loose-keys.js +0 -1
  87. package/dist/core/layout-migrate/paths.d.ts +0 -30
  88. package/dist/core/layout-migrate/paths.js +0 -1
  89. package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
  90. package/dist/core/layout-migrate/stored-paths.js +0 -11
  91. package/dist/core/layout-migrate/stores.d.ts +0 -30
  92. package/dist/core/layout-migrate/stores.js +0 -3
  93. package/dist/core/scoped-state/migrate.d.ts +0 -15
  94. package/dist/core/scoped-state/migrate.js +0 -3
  95. package/dist/daemon/boot-migrations.d.ts +0 -14
  96. package/dist/daemon/boot-migrations.js +0 -1
  97. package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
  98. package/dist/migrations/004-canvas-documents/apply.js +0 -1
  99. package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
  100. package/dist/migrations/004-canvas-documents/index.js +0 -2
  101. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
  102. package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
  103. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
  104. package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
  105. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
  106. package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
  107. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
  108. package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
  109. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
  110. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
  111. package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +0 -6
  112. package/dist/migrations/004-canvas-documents/legacy-edges.js +0 -18
  113. package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
  114. package/dist/migrations/004-canvas-documents/plan.js +0 -3
  115. package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
  116. package/dist/migrations/004-canvas-documents/pointers.js +0 -4
  117. package/dist/migrations/activation.d.ts +0 -17
  118. package/dist/migrations/activation.js +0 -2
  119. package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
  120. package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
  121. package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
  122. package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
  123. package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
  124. package/packages/crouter-api/dist/core/locked-file.js +0 -121
  125. package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
  126. package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
  127. package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
  128. package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
  129. package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
  130. package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
  131. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
  132. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
  133. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
  134. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
  135. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
  136. package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
  137. package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
  138. package/packages/crouter-api/dist/migrations/activation.js +0 -46
@@ -1,11 +0,0 @@
1
- export interface InboxMigrationSummary {
2
- nodes: number;
3
- entries: number;
4
- cursors: number;
5
- failures: number;
6
- }
7
- /** Scan every node dir under the local canvas and migrate legacy inbox state.
8
- * Idempotent; a node that fails migration is reported and skipped so one bad
9
- * dir cannot block daemon boot (its broker stays crash-faulted, same as
10
- * before the migration existed). */
11
- export declare function migrateLegacyInboxIdentities(): InboxMigrationSummary;
@@ -1,3 +0,0 @@
1
- var h=Object.defineProperty;var d=(r,t)=>h(r,"name",{value:t,configurable:!0});import{existsSync as l,readFileSync as w,readdirSync as x,renameSync as I,rmSync as E,statSync as C,writeFileSync as O}from"node:fs";import{join as F}from"node:path";import{createHash as L}from"node:crypto";import{inboxPath as N,nodesRoot as R}from"../canvas/index.js";import{emitEvent as U}from"../events/emit.js";const S=/^(?!0{32}$)[0-9a-f]{32}$/,_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,j=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function z(r,t,e,n){return L("sha256").update(`crouter:legacy-inbox:${r}\0${t}\0${e}\0${n}`).digest("hex").slice(0,32)}d(z,"legacyIdentity");function b(r,t,e,n,i){if(i===void 0)return z(r,t,e,n);if(typeof i=="string"){if(S.test(i))return i;if(_.test(i))return i.replaceAll("-","").toLowerCase()}}d(b,"normalize");function p(r,t){const e=`${r}.tmp`;O(e,t,"utf8"),I(e,r)}d(p,"atomicWrite");function A(r){const t=N(r),e=`${t}.cursor`;let n=0,i=[];if(l(t)){const f=w(t,"utf8");if(f!==""){const s=f.split(`
2
- `);s.at(-1)===""&&s.pop();const g=s.map((a,m)=>{const o=JSON.parse(a),u=b("entry",r,m,a,o.entry_id),y=b("operation",r,m,a,o.operation_id);if(u===void 0||y===void 0)throw new Error(`unmigratable inbox row ${m}: ${String(o.entry_id)}`);const $=u!==o.entry_id||y!==o.operation_id;return $&&(n+=1),o.entry_id=u,o.operation_id=y,{line:$?JSON.stringify(o):a,ts:o.ts,entry_id:u}});i=g,n>0&&p(t,g.map(a=>`${a.line}
3
- `).join(""))}}if(!l(e))return{entries:n,cursor:!1};const c=w(e,"utf8").trim();if(c===""||S.test(c))return{entries:n,cursor:!1};if(_.test(c))return p(e,c.replaceAll("-","").toLowerCase()),{entries:n,cursor:!0};if(j.test(c)){let f=-1;for(let s=0;s<i.length;s+=1)i[s].ts<=c&&(f=s);return f<0?E(e):p(e,i[f].entry_id),{entries:n,cursor:!0}}throw new Error(`unrecognized inbox cursor: ${c.slice(0,64)}`)}d(A,"migrateNode");function X(){const r={nodes:0,entries:0,cursors:0,failures:0},t=R();if(!l(t))return r;for(const e of x(t))try{if(!C(F(t,e)).isDirectory())continue;const{entries:n,cursor:i}=A(e);(n>0||i)&&(r.nodes+=1,r.entries+=n,i&&(r.cursors+=1))}catch(n){r.failures+=1,U({level:"warn",event:"inbox.migrate.node_failed",node_id:e,error:n})}return r}d(X,"migrateLegacyInboxIdentities");export{X as migrateLegacyInboxIdentities};
@@ -1,28 +0,0 @@
1
- /** D106 first boot on a Mac: copy every document text still in the old `<canvas home>/bodies/<hh>/<hash>` files into the `bodies` table.
2
- * A file is copied only when the sha256 of its text equals its name; any other is skipped and reported. A text with NULs is stored as `canonical`
3
- * makes it (NUL → U+FFFD, under the hash of that text) and every revision naming the file's hash is rekeyed to the canonical hash in the same transaction.
4
- * Rows go in with `ON CONFLICT DO NOTHING` in batches of one transaction each, so an interrupted run resumes and a finished one changes nothing.
5
- * The files stay in place for a rollback to the previous build. Cloud roles never call this: their text was never on a disk that survives. */
6
- export interface BodiesBootCopyReport {
7
- scanned: number;
8
- copied: number;
9
- mismatched: string[];
10
- nulReplaced: Array<{
11
- hash: string;
12
- replaced: number;
13
- }>;
14
- }
15
- export declare function copyBodyFilesToTable(root?: string): Promise<BodiesBootCopyReport>;
16
- /** Rows #822 stored under the hash of the text before its NULs became U+FFFD. */
17
- export interface BodyHashRepairReport {
18
- rekeyed: number;
19
- removed: number;
20
- unresolved: string[];
21
- }
22
- /** D106 correction, every role, before readers serve: a `bodies` row whose key is not the sha256 of its text is rekeyed to the canonical hash.
23
- * Rows are found by the database hashing every text and paged by key. A mismatch is repaired only when an intact original — the retained
24
- * `<home>/bodies/<hh>/<hash>` file — becomes exactly the stored text under `storable`.
25
- * Each page is one transaction: the canonical row is stored (or confirmed to hold the same text), every revision naming the old hash is rekeyed,
26
- * and the invalid old-key row is deleted — the one place a body row is removed, as correction of an invalid duplicate, because leaving it would
27
- * keep every future dump invalid. A mismatch with no such original is never rehashed: it is returned in `unresolved`. A re-run changes nothing. */
28
- export declare function repairBodyHashes(root?: string): Promise<BodyHashRepairReport>;
@@ -1 +0,0 @@
1
- var T=Object.defineProperty;var f=(o,s)=>T(o,"name",{value:s,configurable:!0});import{existsSync as u,readdirSync as w,readFileSync as m}from"node:fs";import{join as l}from"node:path";import{openDb as y,withCanvasWrite as E}from"../canvas/db.js";import{crtrHome as b}from"../canvas/paths.js";import{canonical as x,hashOf as d,store as R,storable as v}from"./bodies.js";const F=200;async function g(o,s,p){return(await o.prepare("UPDATE revisions SET body_hash = ? WHERE body_hash = ?").run(p,s)).changes}f(g,"rekeyRevisions");async function k(o=l(b(),"bodies")){const s={scanned:0,copied:0,mismatched:[],nulReplaced:[]};if(!u(o))return s;const p=new Set((await(await y()).prepare("SELECT hash FROM bodies").all()).map(t=>t.hash));let h=[];const r=f(async()=>{if(h.length===0)return;const t=h;h=[],await E(async a=>{for(const n of t)await R(a,n.hash,n.text)&&(s.copied+=1),n.file!==n.hash&&await g(a,n.file,n.hash)})},"flush");for(const t of w(o,{withFileTypes:!0}))if(!(!t.isDirectory()||!/^[0-9a-f]{2}$/.test(t.name)))for(const a of w(l(o,t.name))){if(!/^[0-9a-f]{64}$/.test(a)||(s.scanned+=1,p.has(a)))continue;const n=m(l(o,t.name,a),"utf8");if(d(n)!==a||!a.startsWith(t.name)){s.mismatched.push(a);continue}const{text:e,hash:i}=x(n,a);e!==n&&s.nulReplaced.push({hash:a,replaced:n.split("\0").length-1}),h.push({file:a,hash:i,text:e}),h.length>=F&&await r()}return await r(),s}f(k,"copyBodyFilesToTable");const S=50;async function B(o=l(b(),"bodies")){const s={rekeyed:0,removed:0,unresolved:[]},h=(await y()).prepare(`SELECT hash, text FROM bodies WHERE hash > ? AND encode(sha256(convert_to(text, 'UTF8')), 'hex') <> hash ORDER BY hash LIMIT ${S}`);for(let r="";;){const t=await h.all(r);if(t.length===0)break;r=t[t.length-1].hash;const a=new Map;for(const e of t){const i=l(o,e.hash.slice(0,2),e.hash);if(!u(i))continue;const c=m(i,"utf8");d(c)===e.hash&&a.set(e.hash,c)}const n=t.filter(e=>a.has(e.hash)&&v(a.get(e.hash))===e.text);for(const e of t)n.includes(e)||s.unresolved.push(e.hash);n.length!==0&&await E(async e=>{for(const i of n){const c=d(i.text);await R(e,c,i.text),s.rekeyed+=await g(e,i.hash,c),s.removed+=(await e.prepare("DELETE FROM bodies WHERE hash = ?").run(i.hash)).changes}})}return s}f(B,"repairBodyHashes");export{k as copyBodyFilesToTable,B as repairBodyHashes};
@@ -1,38 +0,0 @@
1
- import { OldToNewPathMap } from './paths.js';
2
- export { OldToNewPathMap, oldToNewPathMap } from './paths.js';
3
- export interface LayoutMigration {
4
- map: OldToNewPathMap;
5
- moved: number;
6
- /** Exactly the filesystem operations that changed a source path. */
7
- changes: string[];
8
- /** One line per leftover the migration resolved itself (a dry run lists what it would do). */
9
- resolutions: string[];
10
- /** Old stored path prefix → new path, rewritten as text in migrated markdown bodies. */
11
- bodyPaths: Array<[string, string]>;
12
- /** Credential sources that did not exist; legitimate when the old volume never held one. */
13
- absentCredentials: string[];
14
- dryRun: boolean;
15
- }
16
- export declare function isJunkFile(name: string): boolean;
17
- /** Where a leftover the new layout has no place for is kept: `runtime/set-aside/<kind>/<name>`, never overwriting. */
18
- export declare function setAsidePath(migration: LayoutMigration, kind: string, name: string): string;
19
- /** Move a leftover aside (a rename; never a copy). */
20
- export declare function setAside(from: string, kind: string, migration: LayoutMigration, name?: string): string;
21
- /**
22
- * What to do with a destination that already exists before a move. A file is
23
- * renamed atomically, so a file present at both paths was never written by
24
- * this migration: an identical copy drops the source, an empty file is
25
- * removed, and anything else is kept aside under `runtime/set-aside/replaced/`.
26
- */
27
- export type Claim = {
28
- action: 'merge' | 'drop-source' | 'remove-destination' | 'set-aside-destination';
29
- line?: string;
30
- };
31
- export declare function claim(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): Claim;
32
- /** Rename within the volume; merge an existing directory on interrupted runs, never overwrite a file. */
33
- export declare function movePath(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): void;
34
- /** Dry-run lines for a move: the claims the real run would make, without touching anything. */
35
- export declare function previewMove(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): void;
36
- export declare function sameFile(from: string, to: string): boolean;
37
- export declare function daemonAnswers(socketPath: string): Promise<boolean>;
38
- export declare function migrateLayout(dryRun: boolean): Promise<LayoutMigration | null>;
@@ -1,4 +0,0 @@
1
- var X=Object.defineProperty;var l=(t,e)=>X(t,"name",{value:e,configurable:!0});import{DatabaseSync as _}from"node:sqlite";import{randomUUID as L}from"node:crypto";import{symlinkSync as Z,linkSync as ee,chmodSync as M,chownSync as j,closeSync as g,cpSync as te,existsSync as d,fsyncSync as C,lchownSync as ne,lstatSync as f,mkdirSync as v,openSync as S,readFileSync as w,readlinkSync as D,readSync as O,readdirSync as h,renameSync as k,rmSync as A,rmdirSync as b,unlinkSync as $,writeSync as R}from"node:fs";import{request as re}from"node:http";import{basename as T,dirname as m,isAbsolute as oe,join as c,relative as E,resolve as se}from"node:path";import{LEGACY_LOCAL_PERSON as ie}from"../canvas/legacy-person.js";import{LAYOUT_VERSION as ce,assertSupportedLayoutMarker as U}from"../layout.js";import{InputError as q}from"../io.js";import{syncDirectory as ae}from"../fs-utils.js";import{oldToNewPathMap as ue}from"./paths.js";import{conversations as le,memoryAndProfiles as de,previewStores as fe,profileFolders as pe,repairMovedRepositories as he,worktrees as me}from"./stores.js";import{storedPaths as ye}from"./stored-paths.js";import{OldToNewPathMap as Ge,oldToNewPathMap as Je}from"./paths.js";const ve=new Set([".DS_Store","Thumbs.db","desktop.ini"]);function we(t){return ve.has(t)||t.startsWith("._")}l(we,"isJunkFile");function F(t,e,n){const r=c(t.map.old.root,"runtime","set-aside",e);let o=c(r,n);for(let i=2;d(o);i++)o=c(r,`${n}.${i}`);return o}l(F,"setAsidePath");function I(t,e,n,r=T(t)){const o=F(n,e,r);return v(m(o),{recursive:!0}),k(t,o),n.moved++,n.changes.push(`${t} -> ${o} (set aside)`),o}l(I,"setAside");function be(t){const e=f(t);return e.isDirectory()?h(t).length===0:e.isFile()&&e.size===0}l(be,"empty");function W(t,e,n,r=!1){const o=f(t),i=f(e);if(o.isDirectory()&&i.isDirectory()&&!r)return{action:"merge"};if(o.isFile()&&i.isFile()&&K(t,e))return{action:"drop-source"};if(be(e))return{action:"remove-destination",line:`stray-destination: removed empty ${i.isDirectory()?"folder":"file"} ${e} that predates the migration`};const s=F(n,"replaced",E(n.map.old.root,e));return{action:"set-aside-destination",line:`stray-destination: ${e} predates the migration; moved it to ${s} and put ${t} in its place`}}l(W,"claim");function x(t,e,n,r=!1){if(d(t)&&t!==e){if(d(e)){const o=W(t,e,n,r);if(o.line&&n.resolutions.push(o.line),o.action==="merge"){for(const i of h(t))x(c(t,i),c(e,i),n);b(t);return}if(o.action==="drop-source"){A(t,{recursive:!0}),n.changes.push(`${t} (identical to ${e}; removed)`);return}o.action==="remove-destination"?(A(e,{recursive:!0}),n.changes.push(`${e} (removed)`)):I(e,"replaced",n,E(n.map.old.root,e))}v(m(e),{recursive:!0}),k(t,e),n.moved++,n.changes.push(`${t} -> ${e}`)}}l(x,"movePath");function z(t,e,n,r=!1){if(!d(t)||t===e||!d(e))return;const o=W(t,e,n,r);if(o.line&&n.resolutions.push(o.line),o.action==="merge")for(const i of h(t))z(c(t,i),c(e,i),n)}l(z,"previewMove");function B(t){const{map:e}=t,n=c(e.old.canvas,"nodes"),r=c(e.old.canvas,"canvas.db"),o=c(e.old.root,"runtime","canvas.db"),i=d(r)?r:d(o)&&f(o).size>0?o:"";if(!i){if(d(n))throw new Error("old node records exist without canvas.db");return null}const s=new _(i,{readOnly:t.dryRun||i!==r});try{if(i===r&&!t.dryRun&&s.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get().busy!==0)throw new Error("old canvas WAL is busy; stop every database user before migrating");return new Map(s.prepare("SELECT node_id, grantee FROM nodes").all().map(a=>{const u=a.grantee===ie?"terminal":a.grantee.startsWith("app:")?a.grantee.slice(4):"";if(!u)throw new Error(`node ${a.node_id} has no app assignment`);return[a.node_id,u]}))}finally{s.close()}}l(B,"canvasNodeApps");function G(t,e){const n=c(t.map.old.canvas,"nodes");if(!d(n))return[];const r=[];for(const o of h(n)){const i=c(n,o),s=f(i).isDirectory();e.has(o)&&s||r.push({path:i,remove:!s&&we(o)})}return r}l(G,"orphanNodeEntries");function J(t,e){return t.remove?`node-leftover: deleted ${t.path} (not a node record)`:`node-leftover: ${t.path} has no node row; moved to ${F(e,"nodes",T(t.path))}`}l(J,"orphanLine");function ge(t){const{map:e}=t,n=c(e.old.canvas,"nodes"),r=B(t);if(r){for(const[o,i]of r)e.node(o,i);if(d(n)){for(const o of G(t,r)){if(t.resolutions.push(J(o,t)),o.remove){$(o.path),t.changes.push(`${o.path} (removed)`);continue}const i=I(o.path,"nodes",t),s=c(e.old.targetRoot,E(e.old.root,i));for(const a of new Set([e.old.storedCanvas,e.old.storedScope,c(e.old.storedScope,"canvas")]))e.add(c(a,"nodes",T(o.path)),s)}for(const[o,i]of r){const s=c(n,o);if(d(s)){for(const a of["context","reports","attachments"])x(c(s,a),c(e.old.root,"apps",i,"nodes",o,a),t);for(const a of h(s))["worktree","view.sock","broker-launch.json","system-prompt.md","situational-context.md","injected-docs.json"].includes(a)||x(c(s,a),c(e.old.root,"runtime","nodes",o,a),t);h(s).length===0&&b(s)}}h(n).length===0&&b(n)}}}l(ge,"records");const Y=["auth.json","anthropic-credentials.json","openai-codex-credentials.json","openai-credentials.json","crouter-operations.db"];function Se(t,e,n){if(!d(t))return;if(!f(t).isFile())throw new Error(`credential source is not a regular file: ${t}`);const r=w(t);if(d(e)){(!f(e).isFile()||!w(e).equals(r))&&n.resolutions.push(`credential: kept the existing ${e}; the older ${t} differs and stays where it is`);return}v(m(e),{recursive:!0});const o=c(m(e),`.${L()}.tmp`);try{const i=S(o,"wx",384);try{for(let s=0;s<r.length;)s+=R(i,r,s,r.length-s);C(i)}finally{g(i)}if(k(o,e),!w(e).equals(r))throw new Error(`credential verification failed: ${e}`)}finally{d(o)&&$(o)}n.moved++,n.changes.push(`${t} -> ${e} (source retained)`)}l(Se,"copyCredential");function H(t){if(!d(t))return;const e=new _(t);try{if(e.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get().busy!==0)throw new Error(`SQLite WAL is busy: ${t}`)}finally{e.close()}}l(H,"checkpointDb");function K(t,e){if(f(t).size!==f(e).size)return!1;const n=S(t,"r"),r=S(e,"r"),o=Buffer.allocUnsafe(64*1024),i=Buffer.allocUnsafe(o.length);try{for(;;){const s=O(n,o,0,o.length,null);if(s===0)return!0;let a=0;for(;a<s;){const u=O(r,i,a,s-a,null);if(u===0)return!1;a+=u}if(!o.subarray(0,s).equals(i.subarray(0,s)))return!1}}finally{g(n),g(r)}}l(K,"sameFile");function P(t,e,n=!1){let r;try{r=f(e)}catch(u){if(u.code==="ENOENT")return!1;throw u}const o=f(t);if(o.isSymbolicLink())return r.isSymbolicLink()&&D(t)===D(e);if(o.isFile())return r.isFile()&&K(t,e);if(!o.isDirectory()||!r.isDirectory())return!1;const i=h(t).filter(u=>!n||u!==".git"),s=h(e).filter(u=>!n||u!==".git"),a=new Set(s);return i.length===s.length&&i.every(u=>a.has(u)&&P(c(t,u),c(e,u),n))}l(P,"sameTree");function ke(t,e,n){if(!d(t))return;if(!f(t).isDirectory())throw new Error(`hosted work is not a directory: ${t}`);if(d(e)){if(P(t,e,!0))return;if(!f(e).isDirectory()||h(e).length!==0){n.resolutions.push(`hosted-work: kept the existing ${e}; the old ${t} differs and stays where it is`);return}b(e)}v(m(e),{recursive:!0});const r=c(m(e),`.work-${L()}.migrating`);try{if(te(t,r,{recursive:!0,verbatimSymlinks:!0,preserveTimestamps:!0}),!P(t,r))throw new Error(`hosted work copy verification failed: ${t}`);k(r,e),n.moved++,n.changes.push(`${t} -> ${e} (source retained)`)}finally{d(r)&&A(r,{recursive:!0,force:!0})}}l(ke,"copyHostedWork");function Q(t){const{old:e}=t.map,n=c(e.root,"runtime"),r=c(n,"scope"),o=[];for(const i of["canvas.db","canvas.db-wal","canvas.db-shm","on-disk-migrations.json","requests","reviews","plugins","marketplaces","crtrd.log","crtrd.err","cache"])o.push([c(e.canvas,i),c(n,i)]);for(const i of["prompts","personas","config.json","profile-defaults.json","operations.db","operations.db-wal","operations.db-shm"])o.push([c(e.scope,i),c(r,i)]);for(const i of["support","prompt-reviews","plugins","marketplaces"])o.push([c(e.scope,i),c(n,i)]);return o.push([c(e.canvas,"secrets"),c(n,"secrets")]),o}l(Q,"topLevelMoves");function $e(t){const{old:e}=t.map,n=c(e.root,"runtime");H(c(e.scope,"operations.db"));for(const[r,o]of Q(t)){const i=Ee(r);x(r,o,t,!0),xe(i,r,o,t)}H(c(e.agent,"crouter-operations.db"));for(const r of Y)Se(c(e.agent,r),c(n,"secrets",r),t);process.platform==="linux"&&ke(e.work,c(e.root,"user","files"),t)}l($e,"topLevel");function Ee(t){if(!d(t)||!f(t).isDirectory())return[];const e=[];for(const n of h(t)){const r=c(t,n);if(!f(r).isSymbolicLink())continue;const o=D(r);oe(o)||e.push({name:n,target:o})}return e}l(Ee,"relativeLinks");function xe(t,e,n,r){if(!(t.length===0||!d(n)))for(const{name:o,target:i}of t){const s=c(n,o);if(!Ne(s))continue;const a=r.map.mapPath(se(e,i)),u=E(n,a);u!==i&&($(s),Z(u,s),r.changes.push(`${s}: link ${i} -> ${u}`))}}l(xe,"retargetLinks");function Ne(t){try{return f(t),!0}catch{return!1}}l(Ne,"lstatExists");function Le(t){if(process.platform!=="linux")return;if(process.getuid?.()!==0)throw new Error("Linux layout migration requires root for the ownership pass");const e=w("/etc/passwd","utf8").split(`
2
- `).find(s=>s.startsWith("crtrd:")),n=w("/etc/group","utf8").split(`
3
- `).find(s=>s.startsWith("crtr-data:"));if(!e||!n)throw new Error("layout migration requires crtrd user and crtr-data group");const r=Number(e.split(":")[2]),o=Number(n.split(":")[2]);if(!Number.isInteger(r)||!Number.isInteger(o))throw new Error("invalid migration user or group");const i=l((s,a)=>{if(!d(s))return;const u=f(s);if(u.isSymbolicLink()){ne(s,r,a?o:u.gid);return}if(j(s,r,a?o:u.gid),u.isDirectory()){M(s,a?1528:448);for(const y of h(s))i(c(s,y),a)}else a&&M(s,u.mode&73?504:432)},"walk");i(c(t,"runtime"),!1),i(c(t,"user"),!0),i(c(t,"apps"),!0)}l(Le,"ownership");function De(t){return new Promise(e=>{const n=re({socketPath:t,path:"/healthz",method:"GET",timeout:1e3},r=>{r.resume(),e(!0)});n.on("timeout",()=>n.destroy(new Error("daemon probe timed out"))),n.on("error",r=>{r.code==="ENOENT"||r.code==="ECONNREFUSED"?e(!1):e(!0)}),n.end()})}l(De,"daemonAnswers");async function We(t){const e=ue(),n=e.old,r=c(n.root,"runtime","layout");if(d(r))return U(r),null;const o=new Set([c(n.canvas,"crtrd.sock"),c(n.scope,"crtrd.sock"),process.platform==="linux"?"/run/crtr/api.sock":c(n.root,"runtime","api.sock")]);for(const p of o)if(await De(p))throw new q({error:"daemon_running",message:`cannot migrate while a daemon answers on ${p}`,next:"Stop the daemon that owns this volume, then run `crtr sys migrate` again."});if(process.platform==="linux"&&!d(n.agent))throw new q({error:"credential_volume_missing",message:`the old credential volume is not mounted at ${n.agent}`,next:`Mount the old provider-auth volume at ${n.agent}, then run \`crtr sys migrate\` again.`});const i=Y.map(p=>c(n.agent,p)).filter(p=>!d(p)),s={map:e,moved:0,changes:[],resolutions:[],bodyPaths:[],absentCredentials:i,dryRun:t};if(t){const p=B(s);if(p)for(const N of G(s,p))s.resolutions.push(J(N,s));for(const[N,V]of Q(s))z(N,V,s,!0);return fe(s),s}pe(s);const a=[ge,me,$e,he,de,le,ye];for(const p of a)p(s);n.canvas!==n.root&&d(n.canvas)&&h(n.canvas).length===0&&b(n.canvas),Le(n.root),v(m(r),{recursive:!0});const u=`${r}.${L()}.tmp`,y=S(u,"wx",384);try{try{if(process.platform==="linux"){const p=f(m(r));j(u,p.uid,p.gid)}R(y,`${ce}
4
- `),C(y)}finally{g(y)}try{ee(u,r)}catch(p){if(p.code==="EEXIST")U(r);else throw p}}finally{$(u)}return ae(m(r)),s}l(We,"migrateLayout");export{Ge as OldToNewPathMap,W as claim,De as daemonAnswers,we as isJunkFile,We as migrateLayout,x as movePath,Je as oldToNewPathMap,z as previewMove,K as sameFile,I as setAside,F as setAsidePath};
@@ -1,2 +0,0 @@
1
- /** Idempotent post-layout migration. Reports paths only; never key contents. */
2
- export declare function migrateLooseKeys(dryRun?: boolean): Promise<string[]>;
@@ -1 +0,0 @@
1
- var u=Object.defineProperty;var c=(o,i)=>u(o,"name",{value:i,configurable:!0});import{existsSync as p,mkdirSync as f,readFileSync as d,renameSync as l}from"node:fs";import{join as a}from"node:path";import{layoutRoot as y}from"../layout.js";import{listAppEnvNames as A,setAppEnvVar as E}from"../profiles/app-env-store.js";async function $(o=!1){if(process.platform!=="darwin")return[];const i=y(),m=a(i,"runtime","set-aside","loose-keys"),t=[];for(const n of["exa.key","composio.key","secrets.json"]){const e=a(i,n);if(!p(e))continue;const s=a(m,n);if(n==="exa.key"&&!(await A("app:terminal")).includes("EXA_API_KEY")){const r=d(e,"utf8").trim();if(!r||r.includes("\0")){t.push(`${e}: invalid or empty; left untouched`);continue}o||await E("app:terminal","EXA_API_KEY",r),t.push(`${e}: imported EXA_API_KEY into app:terminal`)}if(p(s)){t.push(`${e}: destination already exists; left untouched`);continue}o||(f(m,{recursive:!0,mode:448}),l(e,s)),t.push(`${e}: moved to ${s}`)}return t}c($,"migrateLooseKeys");export{$ as migrateLooseKeys};
@@ -1,30 +0,0 @@
1
- export interface OldLayout {
2
- root: string;
3
- targetRoot: string;
4
- canvas: string;
5
- scope: string;
6
- agent: string;
7
- storedCanvas: string;
8
- storedScope: string;
9
- storedAgent: string;
10
- work: string;
11
- }
12
- /** Sources are physical paths; stored prefixes are paths seen by the old daemon. */
13
- export declare function oldLayout(): OldLayout;
14
- export declare class OldToNewPathMap {
15
- readonly old: OldLayout;
16
- private readonly entries;
17
- private readonly retired;
18
- /** Stored paths inside a removed folder with no new location; left unchanged. */
19
- readonly dangling: Set<string>;
20
- constructor(old: OldLayout);
21
- add(from: string, to: string): void;
22
- /** A path whose planned destination changed: a worktree folder set aside instead of moving into its node. */
23
- redirect(from: string, to: string): void;
24
- /** A removed folder: the folder itself maps to `to`, and a stored path inside it with no finer entry is refused. */
25
- retire(from: string, to: string): void;
26
- node(nodeId: string, app: string): void;
27
- /** Rewrites only approved old prefixes; later steps register profile and session paths. */
28
- mapPath(path: string): string;
29
- }
30
- export declare function oldToNewPathMap(): OldToNewPathMap;
@@ -1 +0,0 @@
1
- var f=Object.defineProperty;var d=(i,t)=>f(i,"name",{value:t,configurable:!0});import{existsSync as g}from"node:fs";import{homedir as u}from"node:os";import{isAbsolute as a,join as s,relative as l,resolve as h,sep as m}from"node:path";import{layoutRoot as w}from"../layout.js";function v(){const i=w(),t=process.platform==="linux",e=t&&i==="/"?"/volume":i,r=t?"/home/agent/.crouter":e,o=g(s(e,"canvas"))?s(e,"canvas"):e,n=t?"/home/agent/.pi/agent":h(process.env.PI_CODING_AGENT_DIR||s(u(),".pi","agent"));return{root:e,targetRoot:i,canvas:o,scope:e,agent:n,storedCanvas:o===e?r:s(r,"canvas"),storedScope:r,storedAgent:n,work:"/home/crtr/work"}}d(v,"oldLayout");class b{static{d(this,"OldToNewPathMap")}old;entries=new Map;retired=new Map;dangling=new Set;constructor(t){this.old=t;const e=s(t.targetRoot,"runtime"),r=s(e,"scope");for(const o of new Set([t.storedCanvas,t.storedScope,s(t.storedScope,"canvas")]))for(const n of["canvas.db","canvas.db-wal","canvas.db-shm","requests","reviews","plugins","marketplaces","secrets","crtrd.log","crtrd.err","cache"])this.add(s(o,n),s(e,n));for(const o of["prompts","personas","config.json","profile-defaults.json","operations.db","operations.db-wal","operations.db-shm"])this.add(s(t.storedScope,o),s(r,o));for(const o of["support","prompt-reviews","plugins","marketplaces"])this.add(s(t.storedScope,o),s(e,o));this.add(s(t.storedScope,"memory"),s(t.targetRoot,"user","memory")),this.add(t.storedScope,r),this.add(t.work,s(t.targetRoot,"user","files"));for(const o of["auth.json","anthropic-credentials.json","openai-codex-credentials.json","openai-credentials.json","crouter-operations.db"])this.add(s(t.storedAgent,o),s(e,"secrets",o));for(const o of new Set([t.storedCanvas,t.storedScope,s(t.storedScope,"canvas")]))this.add(s(o,"secrets","runtime-client.json"),s(e,"secrets","runtime-client.json"))}add(t,e){if(!a(t)||!a(e))throw new Error("migration paths must be absolute");const r=this.entries.get(t);if(r&&r!==e)throw new Error(`conflicting migration path: ${t}`);this.entries.set(t,e)}redirect(t,e){if(!a(t)||!a(e))throw new Error("migration paths must be absolute");this.entries.set(t,e)}retire(t,e){if(!a(t)||!a(e))throw new Error("migration paths must be absolute");const r=this.retired.get(t);if(r&&r!==e)throw new Error(`conflicting migration path: ${t}`);this.retired.set(t,e)}node(t,e){if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t)||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e))throw new Error("unsafe migration node or app id");const r=s(this.old.targetRoot,"runtime","nodes",t),o=s(this.old.targetRoot,"apps",e,"nodes",t);for(const n of new Set([this.old.storedCanvas,this.old.storedScope,s(this.old.storedScope,"canvas")])){const p=s(n,"nodes",t);for(const c of["job","messages","meta.json","inbox.jsonl","passive.jsonl","transcript.jsonl","session.ptr"])this.add(s(p,c),s(r,c));for(const c of["context","reports","attachments","worktree"])this.add(s(p,c),s(o,c));this.add(s(p,"context","memory"),s(this.old.targetRoot,"apps",e,"memory","nodes",t))}}mapPath(t){if(!a(t))return t;const e=this.retired.get(t);if(e)return e;let r="";for(const o of this.entries.keys())(t===o||t.startsWith(o+m))&&o.length>r.length&&(r=o);for(const o of this.retired.keys())if(t.startsWith(o+m)&&o.length>r.length)return this.dangling.add(t),t;return r?h(this.entries.get(r),l(r,t)):t}}function R(){return new b(v())}d(R,"oldToNewPathMap");export{b as OldToNewPathMap,v as oldLayout,R as oldToNewPathMap};
@@ -1,9 +0,0 @@
1
- import type { LayoutMigration } from './index.js';
2
- export declare function storedPaths(migration: LayoutMigration): void;
3
- /**
4
- * Markdown links a moved profile folder by its old absolute path (or its `~/`
5
- * spelling); point each at the new location. Scans the documents the canvas
6
- * import reads: user and app memory, profile files, and node context. A dry
7
- * run scans the same documents at their old locations and writes nothing.
8
- */
9
- export declare function rewriteBodyPaths(migration: LayoutMigration): void;
@@ -1,11 +0,0 @@
1
- var P=Object.defineProperty;var y=(e,c)=>P(e,"name",{value:c,configurable:!0});import{DatabaseSync as S}from"node:sqlite";import{closeSync as F,existsSync as m,fsyncSync as C,lstatSync as D,openSync as B,readFileSync as $,readdirSync as g,renameSync as J,unlinkSync as x,writeFileSync as q}from"node:fs";import{basename as L,dirname as N,join as a,relative as v,resolve as H,sep as A}from"node:path";import{homedir as G}from"node:os";function M(e,c){return typeof e=="string"?c.map.mapPath(e):Array.isArray(e)?e.map(r=>M(r,c)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,i])=>[r,M(i,c)])):e}y(M,"mappedJson");function b(e,c){const r=JSON.parse(e),i=M(r,c);return JSON.stringify(i)===JSON.stringify(r)?e:JSON.stringify(i)}y(b,"rewriteJson");function O(e,c){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(c)!==void 0}y(O,"tableExists");function T(e,c,r){if(!m(e))return;const i=new S(e);try{i.exec("BEGIN IMMEDIATE");try{for(const[f,p]of Object.entries(c)){if(!O(i,f))continue;const u=new Set(i.prepare(`PRAGMA table_info("${f}")`).all().map(o=>o.name)),d=[...(p.paths??[]).filter(o=>u.has(o)),...(p.json??[]).filter(o=>u.has(o))];if(d.length===0)continue;const s=i.prepare(`SELECT rowid AS migration_rowid, ${d.map(o=>`"${o}"`).join(", ")} FROM "${f}"`).all();for(const o of s){const l=[];for(const n of d){const t=o[n];if(typeof t!="string")continue;const h=(p.json??[]).includes(n)?b(t,r):r.map.mapPath(t);h!==t&&l.push([n,h])}l.length&&(i.prepare(`UPDATE "${f}" SET ${l.map(([n])=>`"${n}" = ?`).join(", ")} WHERE rowid = ?`).run(...l.map(([,n])=>n),o.migration_rowid),r.moved+=l.length,r.changes.push(`${e}:${f}:${String(o.migration_rowid)} (${l.map(([n])=>n).join(", ")})`))}}i.exec("COMMIT")}catch(f){throw i.exec("ROLLBACK"),f}}finally{i.close()}}y(T,"rewriteDb");const k={nodes:{paths:["cwd","fork_source_file","pi_session_file"],json:["launch_config_json","review_binding_json","metadata_json","outcome_detail_json"]},sessions:{paths:["transcript_path","fork_source_path"]},worktrees:{paths:["path","repo_root"],json:["sweep_observed_json","abandoned_json","land_intent_json","disposal_json"]},crons:{paths:["cwd"],json:["env_json","sink"]},human_action_deliveries:{paths:["cwd"],json:["argv_json","completion_json","last_failure_json"]},deliveries:{json:["adapter_json"]},reviews:{paths:["origin_session_file","review_dir","branch_file","output_path","file","presentation_dir"],json:["result_json","specification_json"]},human_requests:{paths:["request_dir","file","presentation_dir"],json:["specification_json","action_json","progress_json","feedback_json","result_json"]},run_events:{json:["body_json"]},webhook_deliveries:{json:["payload_json","document_json","last_failure_json","argv_json"]}},W={scope_owners:{paths:["root"]},profiles:{paths:["home"]},profile_projects:{paths:["path"]},profile_defaults:{paths:["directory"]},scope_bookkeeping:{paths:["active_canvas"]},scope_settings:{json:["raw_json"]}};function E(e,c,r){if(!m(e))return;const i=$(e,"utf8"),f=r(i);if(f===i)return;const p=D(e);if(!p.isFile())throw new Error(`migration path is not a regular file: ${e}`);const u=`${e}.migration-tmp`;if(m(u))throw new Error(`migration temporary file already exists: ${u}`);try{q(u,f,{flag:"wx",mode:p.mode});const d=B(u,"r");try{C(d)}finally{F(d)}J(u,e)}finally{m(u)&&x(u)}c.moved++,c.changes.push(`${e} (stored paths)`)}y(E,"rewriteFile");function _(e,c){if(m(e))for(const r of g(e,{withFileTypes:!0})){const i=a(e,r.name);r.isDirectory()?_(i,c):r.isFile()&&c(i)}}y(_,"walk");function U(e,c,r){const{map:i}=e,{old:f}=i,p=new Map,u=new Set,d=new Set;_(c,n=>{if(!n.includes("/conversations/")||!n.endsWith(".jsonl"))return;const t=L(n);p.has(t)?u.add(t):p.set(t,a(f.targetRoot,v(f.root,n)))});const s=y(n=>{if(typeof n=="string"){if(!n.startsWith(f.storedAgent+A+"sessions"+A)||d.has(n)||i.mapPath(n)!==n)return;const t=L(n);if(u.has(t)||!p.has(t)){d.has(n)||e.resolutions.push(`lost-transcript: ${n} is referenced but ${u.has(t)?"matches more than one moved transcript":"exists nowhere"}; left the reference unchanged`),d.add(n);return}i.add(n,p.get(t))}else if(Array.isArray(n))for(const t of n)s(t);else if(n!==null&&typeof n=="object")for(const t of Object.values(n))s(t)},"reference"),o=y(n=>{if(n.endsWith("/meta.json")||n.endsWith(".json")&&(n.includes("/tickets/")||n.includes("/requests/")))s(JSON.parse($(n,"utf8")));else if(n.endsWith(".jsonl")&&n.includes("/conversations/")){const t=$(n,"utf8");s(JSON.parse(t.slice(0,t.indexOf(`
2
- `)<0?void 0:t.indexOf(`
3
- `))))}else if(n.endsWith(".md")&&(n.includes("/memory/")||n.includes("/profiles/"))){const t=$(n,"utf8");if(!t.startsWith(`---
4
- `))return;const h=t.indexOf(`
5
- ---`,4);if(h<0)return;for(const j of t.slice(0,h).split(`
6
- `)){const w=j.match(/^\s*session_file:\s*["']?([^"'\n]+)["']?$/);w&&s(w[1])}}},"inspect");_(c,o),_(a(f.root,"user","memory"),o),_(a(r,"nodes"),o),_(a(r,"tickets"),o),_(a(r,"requests"),o);const l=a(r,"canvas.db");if(m(l)){const n=new S(l,{readOnly:!0});try{for(const[t,h]of Object.entries(k)){if(!O(n,t))continue;const j=new Set(n.prepare(`PRAGMA table_info("${t}")`).all().map(w=>w.name));for(const w of[...h.paths??[],...h.json??[]].filter(R=>j.has(R)))for(const R of n.prepare(`SELECT "${w}" AS value FROM "${t}" WHERE "${w}" LIKE ?`).all(`%${f.storedAgent}/sessions/%`))(h.json??[]).includes(w)?s(JSON.parse(R.value)):s(R.value)}}finally{n.close()}}}y(U,"recoverSessionMappings");function se(e){const{root:c}=e.map.old,r=a(c,"runtime"),i=a(c,"apps");U(e,i,r),T(a(r,"canvas.db"),k,e),T(a(r,"scope","operations.db"),W,e);const f=new Set,p=a(r,"canvas.db");if(m(p)){const s=new S(p,{readOnly:!0});try{if(O(s,"nodes")&&s.prepare("PRAGMA table_info(nodes)").all().some(o=>o.name==="cwd"))for(const o of s.prepare("SELECT cwd FROM nodes").all())f.add(o.cwd)}finally{s.close()}}const u=a(r,"scope","operations.db");if(m(u)){const s=new S(u,{readOnly:!0});try{if(O(s,"profile_projects"))for(const o of s.prepare("SELECT path FROM profile_projects").all())f.add(o.path)}finally{s.close()}}for(const s of f){const o=e.map.old.targetRoot;let l=s.startsWith(o+"/")?H(c,v(o,s)):s;for(;l!==N(l);)T(a(l,".crouter","operations.db"),W,e),l=N(l)}_(a(i),s=>{s.endsWith("/.crouter/operations.db")&&T(s,W,e),s.endsWith("/meta.json")&&E(s,e,o=>b(o,e)),s.endsWith(".md")&&(s.includes("/memory/")||s.includes("/profiles/"))&&I(s,e),s.endsWith(".jsonl")&&s.includes("/conversations/")&&X(s,e)}),_(a(c,"user","memory"),s=>{s.endsWith(".md")&&I(s,e)}),Y(e);for(const s of e.map.dangling)e.resolutions.push(`dangling-path: ${s} names a file the new layout drops; left the stored path unchanged`);_(a(c,"user","files"),s=>{s.endsWith("/.crouter/operations.db")&&T(s,W,e)}),_(a(r,"nodes"),s=>{s.endsWith("/meta.json")&&E(s,e,o=>b(o,e)),s.endsWith("/session.ptr")&&x(s)}),_(a(r,"tickets"),s=>{s.endsWith(".json")&&E(s,e,o=>b(o,e))}),_(a(r,"requests"),s=>{s.endsWith(".json")&&E(s,e,o=>b(o,e))});const d=a(r,"canvas.db");if(m(d)){const s=new S(d);try{s.exec("DROP TABLE IF EXISTS layout_header_rewrites")}finally{s.close()}}}y(se,"storedPaths");function I(e,c){E(e,c,r=>{if(!r.startsWith(`---
7
- `))return r;const i=r.indexOf(`
8
- ---`,4);return i<0?r:r.slice(0,i).replace(/^(\s*session_file:\s*)([^\n]+)$/gm,(p,u,d)=>{const s=d.match(/^(["'])(.*)\1$/),o=s?s[2]:d.trim(),l=c.map.mapPath(o);return l===o?p:`${u}${s?s[1]:""}${l}${s?s[1]:""}`})+r.slice(i)})}y(I,"rewriteMemory");function X(e,c){const r=a(c.map.old.root,"runtime","canvas.db");if(!m(r)){E(e,c,f=>{const p=f.indexOf(`
9
- `),u=p<0?f:f.slice(0,p);return b(u,c)+(p<0?"":f.slice(p))});return}const i=new S(r);try{i.exec("CREATE TABLE IF NOT EXISTS layout_header_rewrites (path TEXT PRIMARY KEY, old_header TEXT NOT NULL, new_header TEXT NOT NULL)");const f=i.prepare("SELECT old_header, new_header FROM layout_header_rewrites WHERE path = ?").get(e),p=$(e,"utf8"),u=p.indexOf(`
10
- `),d=u<0?p:p.slice(0,u),s=f?.new_header??b(d,c);if(f&&d!==f.old_header&&d!==s)throw new Error(`conversation header changed during migration: ${e}`);if(!f&&s!==d){const o=a(c.map.old.targetRoot,v(c.map.old.root,e)),l=Buffer.byteLength(s)-Buffer.byteLength(d);i.exec("BEGIN IMMEDIATE");try{i.prepare("INSERT INTO layout_header_rewrites (path, old_header, new_header) VALUES (?, ?, ?)").run(e,d,s),l!==0&&O(i,"sessions")&&i.prepare("UPDATE sessions SET event_offset = event_offset + ? WHERE transcript_path = ? AND event_offset > 0").run(l,o),i.exec("COMMIT")}catch(n){throw i.exec("ROLLBACK"),n}}d!==s&&E(e,c,o=>{const l=o.indexOf(`
11
- `);if((l<0?o:o.slice(0,l))!==d)throw new Error(`conversation header changed during migration: ${e}`);return s+(l<0?"":o.slice(l))}),(f||s!==d)&&i.prepare("DELETE FROM layout_header_rewrites WHERE path = ?").run(e)}finally{i.close()}}y(X,"rewriteHeader");function K(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}y(K,"escape");function Y(e){const c=e.bodyPaths;if(c.length===0)return;const r=G(),i=[];for(const[t,h]of c)i.push([t,h]),t.startsWith(r+A)&&i.push([`~${t.slice(r.length)}`,h.startsWith(r+A)?`~${h.slice(r.length)}`:h]);i.sort((t,h)=>h[0].length-t[0].length);const f=new RegExp(`(${i.map(([t])=>K(t)).join("|")})(?![A-Za-z0-9_-])`,"g"),p=new Map(i),{root:u,scope:d,canvas:s}=e.map.old,o=y(t=>{if(!t.endsWith(".md"))return;if(e.dryRun){const j=$(t,"utf8").match(f)?.length??0;j&&e.resolutions.push(`profile-extra-link: rewrote ${j} link(s) to moved profile files in ${t}`);return}let h=0;E(t,e,j=>j.replace(f,w=>(h++,p.get(w)))),h&&e.resolutions.push(`profile-extra-link: rewrote ${h} link(s) to moved profile files in ${t}`)},"visit"),l=y(t=>{if(m(t))for(const h of g(t))_(a(t,h,"context"),o)},"nodeContexts");if(e.dryRun){_(a(d,"memory"),o),_(a(d,"profiles"),o),l(a(s,"nodes"));return}_(a(u,"user","memory"),o);const n=a(u,"apps");if(m(n))for(const t of g(n))_(a(n,t,"memory"),o),_(a(n,t,"profiles"),o),_(a(n,t,"files","profiles"),o),l(a(n,t,"nodes"))}y(Y,"rewriteBodyPaths");export{Y as rewriteBodyPaths,se as storedPaths};
@@ -1,30 +0,0 @@
1
- import { profileSpace } from '../layout.js';
2
- import type { LayoutMigration } from './index.js';
3
- export interface ProfileFolder {
4
- id: string;
5
- source: string;
6
- /** No scoped-state row: the whole folder moves to `files`. */
7
- target: ReturnType<typeof profileSpace> | null;
8
- files: string;
9
- /** Entries with no slot in the new layout, moved under `files` at the same name. */
10
- extras: string[];
11
- }
12
- /**
13
- * A profile is its scoped-state row; the row is authoritative even when an
14
- * interrupted run already removed the old profile folder. There is no profile
15
- * folder in the new layout: the old folder's own path (the profile's
16
- * scope_owners.root) becomes its memory folder. What else the folder holds is
17
- * the profile's own files and moves to `apps/<app>/files/profiles/<id>/`; a
18
- * folder with no row moves there whole, under the terminal app.
19
- */
20
- export declare function profileFolders(migration: LayoutMigration): {
21
- folders: ProfileFolder[];
22
- junk: string[];
23
- aside: string[];
24
- };
25
- export declare function memoryAndProfiles(migration: LayoutMigration): void;
26
- export declare function conversations(migration: LayoutMigration): void;
27
- export declare function repairMovedRepositories(migration: LayoutMigration): void;
28
- export declare function worktrees(migration: LayoutMigration): void;
29
- /** Every resolution the real run would make, computed without changing anything. */
30
- export declare function previewStores(migration: LayoutMigration): void;
@@ -1,3 +0,0 @@
1
- var se=Object.defineProperty;var h=(e,t)=>se(e,"name",{value:t,configurable:!0});import{DatabaseSync as z}from"node:sqlite";import{closeSync as re,copyFileSync as ne,existsSync as u,realpathSync as pe,fsyncSync as ce,lstatSync as $,mkdirSync as B,openSync as ae,readFileSync as T,readdirSync as E,renameSync as M,rmdirSync as F,unlinkSync as L,writeFileSync as J}from"node:fs";import{execFileSync as Y}from"node:child_process";import{basename as A,dirname as b,isAbsolute as Z,join as n,relative as k,resolve as C,sep as P}from"node:path";import{LEGACY_LOCAL_PERSON as q}from"../canvas/legacy-person.js";import{profileSpace as ie}from"../layout.js";import{isJunkFile as j,movePath as S,sameFile as O,setAside as x,setAsidePath as H}from"./index.js";import{rewriteBodyPaths as de}from"./stored-paths.js";function D(e,t){Y("git",["-c",`safe.directory=${e}`,"-C",e,...t],{stdio:"pipe"})}h(D,"gitInRepo");function _(e,t){const{root:s,targetRoot:p}=t.map.old;return C(s,k(p,e))}h(_,"physical");function N(e,t=!1){const{old:s}=e.map,p=n(s.canvas,"canvas.db"),o=n(s.root,"runtime","canvas.db"),r=u(p)?p:o;return u(r)&&$(r).size>0?new z(r,{readOnly:!t||e.dryRun}):null}h(N,"canvasDb");function W(e){return new Map(e.prepare("SELECT node_id, grantee FROM nodes").all().map(({node_id:t,grantee:s})=>{const p=s===q?"terminal":s.startsWith("app:")?s.slice(4):"";if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(p))throw new Error(`node ${t} has no valid app`);return[t,p]}))}h(W,"nodeApps");function G(e,t,s){return n(s.map.old.targetRoot,"apps",e,"files","profiles",t)}h(G,"profileFiles");function K(e,t,s,p){if(!u(e))return;if(!u(t)){S(e,t,p);return}const o=$(e),r=$(t);if(o.isDirectory()&&r.isDirectory()){for(const d of E(e))K(n(e,d),n(t,d),n(s,d),p);F(e);return}if(o.isFile()&&r.isFile()&&O(e,t)){L(e);return}const a=_(s,p);p.dryRun||S(e,a,p),p.resolutions.push(`profile-home: ${t} differs from the profile's ${e}; kept the app home's copy, moved the profile's to ${a}`)}h(K,"mergeHome");function Q(e,t,s,p){if(!u(e)||!u(t))return;const o=$(e),r=$(t);if(o.isDirectory()&&r.isDirectory()){for(const a of E(e))Q(n(e,a),n(t,a),n(s,a),p);return}o.isFile()&&r.isFile()&&O(e,t)||p.resolutions.push(`profile-home: ${t} differs from the profile's ${e}; kept the app home's copy, moved the profile's to ${_(s,p)}`)}h(Q,"previewHome");function V(e,t,s){e.bodyPaths.some(([p])=>p===t)||e.bodyPaths.push([t,s])}h(V,"bodyPath");function X(e){const{map:t}=e,s=[n(t.old.scope,"operations.db"),n(t.old.root,"runtime","scope","operations.db")].find(u),p=s?new z(s,{readOnly:!0}):null,o=new Map;try{if(p&&p.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='profiles'").get())for(const i of p.prepare("SELECT id, grantee FROM profiles").all())o.set(i.id,i.grantee)}finally{p?.close()}const r=new Map;for(const[i,c]of o){const w=c==null||c===q?"terminal":c.startsWith("app:")?c.slice(4):"",f=ie(w,i),y=n(t.old.storedScope,"profiles",i);t.retire(y,f.dir),t.add(n(y,"memory"),f.dir),t.add(n(y,"env.json"),f.env),t.add(n(y,"home"),f.home),r.set(i,{target:f,app:w})}const a=n(t.old.scope,"profiles"),d={folders:[],junk:[],aside:[]};if(!u(a))return d;for(const i of E(a)){const c=n(a,i);if(!$(c).isDirectory()){(j(i)?d.junk:d.aside).push(c);continue}if(i===".locks"){for(const l of E(c)){const v=n(c,l);!(l.endsWith(".lock")&&$(v).isFile())&&!j(l)&&d.aside.push(v)}continue}const w=n(t.old.storedScope,"profiles",i),f=r.get(i);if(!f){const l=G("terminal",i,e);t.add(w,l),V(e,w,l),d.folders.push({id:i,source:c,target:null,files:l,extras:[]});continue}const y=G(f.app,i,e),R=[];for(const l of E(c)){const v=$(n(c,l));(l==="memory"||l==="home"?v.isDirectory():l==="env.json"||l==="profile.json"||l.endsWith(".lock")?v.isFile():j(l))||(R.push(l),t.add(n(w,l),n(y,l)),V(e,n(w,l),n(y,l)))}d.folders.push({id:i,source:c,target:f.target,files:y,extras:R})}return d}h(X,"profileFolders");function g(e,t){for(const s of e.folders){s.target||t.resolutions.push(`profile-folder: ${s.source} has no profile row; moved whole to ${_(s.files,t)}`);for(const p of s.extras)t.resolutions.push(`profile-extra: ${n(s.source,p)} moved to ${_(n(s.files,p),t)}`)}for(const s of e.junk)t.resolutions.push(`profile-leftover: deleted ${s} (not profile data)`);for(const s of e.aside)t.resolutions.push(`profile-leftover: ${s} is not a profile; moved to ${H(t,"profiles",A(s))}`)}h(g,"profileLines");function Ce(e){const{map:t}=e;S(n(t.old.scope,"memory"),n(t.old.root,"user","memory"),e);const s=N(e);if(s)try{for(const[r,a]of W(s)){const d=n(t.old.root,"apps",a,"memory","nodes",r);S(n(t.old.root,"apps",a,"nodes",r,"context","memory"),d,e),S(n(t.old.canvas,"nodes",r,"context","memory"),d,e)}}finally{s.close()}const p=X(e);g(p,e);for(const{source:r,target:a,files:d,extras:i}of p.folders){if(!a){S(r,_(d,e),e,!0);continue}for(const c of i)S(n(r,c),_(n(d,c),e),e);S(n(r,"memory"),_(a.dir,e),e),S(n(r,"env.json"),_(a.env,e),e),K(n(r,"home"),_(a.home,e),n(d,"home"),e);for(const c of E(r))L(n(r,c));F(r),e.moved++,e.changes.push(`${r} (removed)`)}for(const r of p.junk)L(r);for(const r of p.aside)x(r,"profiles",e);const o=n(t.old.scope,"profiles");if(u(o)){const r=n(o,".locks");if(u(r)){for(const a of E(r))L(n(r,a));F(r)}F(o)}}h(Ce,"memoryAndProfiles");function le(e,t,s,p){if(u(e)){if(!$(e).isFile())throw new Error(`session path is not a file: ${e}`);if(B(b(t),{recursive:!0}),u(t)){if($(t).isFile()&&O(e,t))return;const o=x(t,"replaced",s,k(s.map.old.root,t));s.resolutions.push(`stray-destination: ${t} predates the migration; moved it to ${o} and put ${e} in its place`)}if(p){const o=n(b(t),`.${A(t)}.migrating`);u(o)&&L(o),ne(e,o);const r=ae(o,"r");try{ce(r)}finally{re(r)}if(!O(e,o))throw new Error(`session copy verification failed: ${e}`);M(o,t),s.moved++,s.changes.push(`${e} -> ${t} (source retained)`);return}M(e,t),s.moved++,s.changes.push(`${e} -> ${t}`)}}h(le,"moveSession");function fe(e,t,s){const p=new Set(t.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(r=>r.path)),o=e.dryRun?null:t.prepare("UPDATE sessions SET transcript_path = NULL WHERE transcript_path = ?");for(const r of s)if(!(u(r.source)||u(_(r.destination,e)))){if(p.has(r.transcript_path)){e.resolutions.push(`lost-transcript: ${r.transcript_path} is missing but is a live node's current session; kept its path`);continue}o?.run(r.transcript_path),e.resolutions.push(`lost-transcript: ${r.transcript_path} is missing from both paths; cleared the session's transcript path`)}}h(fe,"lostTranscripts");function ue(e){const t=N(e,!0);if(t)try{const s=W(t),p=t.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(),o=new Map,r=new Map,a=new Map;for(const c of p){o.has(c.session_id)||o.set(c.session_id,c.node_id),a.set(c.transcript_path,(a.get(c.transcript_path)??0)+1);const w=r.get(c.transcript_path)??new Set;w.add(c.session_id),r.set(c.transcript_path,w)}const d=new Set,i=[];for(const{session_id:c,node_id:w,transcript_path:f}of p){if(d.has(f))continue;if(d.add(f),r.get(f).size!==1)throw new Error(`two conversations share a transcript: ${f}`);const y=a.get(f)>1?o.get(c):w,R=s.get(y);if(!R)throw new Error(`session belongs to unknown node: ${y}`);if(!Z(f))throw new Error(`session path is not absolute: ${f}`);const l=n(e.map.old.targetRoot,"apps",R,"conversations",y,A(f));if(f===l)continue;const v=f===e.map.old.storedAgent||f.startsWith(e.map.old.storedAgent+P),m=v?n(e.map.old.agent,k(e.map.old.storedAgent,f)):f;i.push({transcript_path:f,destination:l,source:m,retain:process.platform==="linux"&&v})}fe(e,t,i);for(const{transcript_path:c,destination:w}of i)e.map.add(c,w);if(e.dryRun)return;for(const{destination:c,source:w,retain:f}of i)le(w,_(c,e),e,f)}finally{t.close()}}h(ue,"conversations");function De(e){if(process.platform!=="linux")return;const t=N(e);if(t)try{const s=t.prepare("SELECT node_id, path, repo_root FROM worktrees").all(),p=W(t);for(const o of s){const r=e.map.mapPath(o.repo_root);if(r===o.repo_root)continue;const a=p.get(o.node_id);if(!a)throw new Error(`worktree belongs to unknown node: ${o.node_id}`);const d=_(n(e.map.old.targetRoot,"apps",a,"nodes",o.node_id,"worktree"),e);if(!u(d))continue;D(_(r,e),["worktree","repair",d]);const i=o.path.startsWith(e.map.old.storedCanvas+P)?n(e.map.old.canvas,k(e.map.old.storedCanvas,o.path)):o.path;I(i,d,e)}}finally{t.close()}}h(De,"repairMovedRepositories");function I(e,t,s){const p=h(o=>{for(const r of E(o)){const a=n(o,r);if(r===".git"&&a!==n(t,".git")&&$(a).isFile()){const d=T(a,"utf8");if(!d.startsWith("gitdir: "))throw new Error(`invalid submodule git link: ${a}`);const i=d.slice(8).trim(),c=C(b(a),i),w=n(e,k(t,a)),f=C(b(w),i),y=u(c)?c:f;if(!u(y))throw new Error(`submodule git directory missing: ${w}`);const R=s?.map.mapPath(y)??y,l=s&&R!==y?_(R,s):y;if(!u(l))throw new Error(`moved submodule git directory missing: ${l}`);c!==l&&J(a,`gitdir: ${k(b(a),l)}
2
- `);const v=n(l,"config"),m=T(v,"utf8");if(!/^\s*worktree\s*=.*$/m.test(m))throw new Error(`submodule has no worktree setting: ${v}`);const oe=JSON.stringify(k(l,b(a))),U=m.replace(/^(\s*worktree\s*=).*$/m,`$1 ${oe}`);U!==m&&J(v,U)}else r!==".git"&&$(a).isDirectory()&&p(a)}},"visit");p(t)}h(I,"repairSubmoduleLinks");function he(e,t){return Y("git",["-c",`safe.directory=${e}`,"-C",e,...t],{stdio:"pipe",encoding:"utf8"})}h(he,"gitOut");function ee(e){try{return pe(e)}catch{return C(e)}}h(ee,"real");function we(e,t){try{const s=ee(t);return he(e,["worktree","list","--porcelain"]).split(`
3
- `).some(p=>p.startsWith("worktree ")&&ee(p.slice(9))===s)}catch{return!1}}h(we,"registered");function ye(e,t){if(!u(e))return!1;try{const s=T(n(t,".git"),"utf8");return s.startsWith("gitdir: ")?u(C(t,s.slice(8).trim())):!1}catch{return!1}}h(ye,"repairable");function te(e,t,s){s.dryRun||t.state!=="open"&&t.cleanup_state==="complete"||e.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 = ?").run(new Date().toISOString(),t.node_id)}h(te,"closeRow");function _e(e){const t=N(e,!0);if(t){try{const s=W(t),p=t.prepare("SELECT node_id, state, cleanup_state, path, repo_root FROM worktrees").all();for(const o of p){const r=s.get(o.node_id);if(!r)throw new Error(`worktree belongs to unknown node: ${o.node_id}`);if(!Z(o.path))throw new Error(`worktree path is not absolute: ${o.path}`);const a=n(e.map.old.targetRoot,"apps",r,"nodes",o.node_id,"worktree");if(o.path===a)continue;const d=o.path===e.map.old.storedCanvas||o.path.startsWith(e.map.old.storedCanvas+P)?n(e.map.old.canvas,k(e.map.old.storedCanvas,o.path)):o.path,i=_(a,e);if(!u(d)){e.map.add(o.path,a),u(i)?!e.dryRun&&u(o.repo_root)&&(D(o.repo_root,["worktree","repair",i]),I(d,i)):o.state!=="open"&&o.cleanup_state==="complete"||(te(t,o,e),e.resolutions.push(`missing-worktree: ${o.path} (node ${o.node_id}) is gone; closed its row`));continue}if(!we(o.repo_root,d))if(o.state==="open"&&ye(o.repo_root,d))e.resolutions.push(`unregistered-worktree: ${o.path} (node ${o.node_id}) is not registered in ${o.repo_root}; relinked it with git worktree repair`),e.dryRun||D(o.repo_root,["worktree","repair",d]);else{const c=H(e,"worktrees",A(d));e.resolutions.push(`unregistered-worktree: ${o.path} (node ${o.node_id}${o.state==="open"?"":`, ${o.state}`}) is not a worktree of ${u(o.repo_root)?o.repo_root:`the missing repository ${o.repo_root}`}; ${o.state==="open"?"closed its row and ":""}moved the folder to ${c}`),e.map.redirect(o.path,n(e.map.old.targetRoot,k(e.map.old.root,c))),e.dryRun||(x(d,"worktrees",e),te(t,o,e));continue}if(e.map.add(o.path,a),u(i)){const c=H(e,"replaced",k(e.map.old.root,i));e.resolutions.push(`stray-destination: ${i} predates the migration; moved it to ${c} and put the worktree ${d} in its place`),e.dryRun||x(i,"replaced",e,k(e.map.old.root,i))}if(!e.dryRun){B(b(i),{recursive:!0});try{D(o.repo_root,["worktree","move",d,i])}catch(c){if(!String(c.stderr??"").includes("submodule"))throw c;M(d,i),D(o.repo_root,["worktree","repair",i])}I(d,i),e.moved++,e.changes.push(`${d} -> ${i} (git worktree move)`)}}}finally{t.close()}e.dryRun||$e(e)}}h(_e,"worktrees");function $e(e){const t=n(e.map.old.canvas,"nodes");if(u(t)){for(const s of E(t)){const p=n(t,s);$(p).isDirectory()&&E(p).length===0&&F(p)}E(t).length===0&&F(t)}}h($e,"pruneOldNodeFolders");function Ae(e){_e(e);const t=X(e);g(t,e);for(const{source:s,target:p,files:o}of t.folders)p&&Q(n(s,"home"),_(p.home,e),n(o,"home"),e);ue(e),de(e)}h(Ae,"previewStores");export{ue as conversations,Ce as memoryAndProfiles,Ae as previewStores,X as profileFolders,De as repairMovedRepositories,_e as worktrees};
@@ -1,15 +0,0 @@
1
- import { type PersonSnapshot } from './person-store.js';
2
- /** Conversion is intentionally explicit. Deployment coordination must prove all legacy writers at these shared roots are stopped before calling it. */
3
- export declare function convertLegacyScopedStore(input: {
4
- kind: 'user' | 'project' | 'provider';
5
- root: string;
6
- }): void;
7
- /** Converts legacy provider pools only after the activation owner has stopped every writer sharing this agent directory. */
8
- export declare function convertLegacyProviderStore(agentDir: string): Promise<void>;
9
- export declare function personStoresCopied(): Promise<boolean>;
10
- /** Copy this install's files into the person's rows, once: profiles, scope settings and bookkeeping, the plugin and marketplace
11
- * lists, managed model accounts with their cooldowns, rotation settings, the OpenAI device id, `auth.json` API keys and the profile, app and deployment env files (sealed into `env_vars`). One
12
- * transaction, skipping any key a row already holds, ending with `canvas_meta.person_stores_copied`. The files stay, unread. */
13
- export declare function copyPersonStoresToRows(person: string, legacyUserSnapshot: PersonSnapshot | null, agentDir: string): Promise<void>;
14
- /** The install's person just became known: copy the old local files into their rows once, then load their snapshot. */
15
- export declare function adoptInstallPerson(person: string): Promise<void>;
@@ -1,3 +0,0 @@
1
- var K=Object.defineProperty;var p=(e,t)=>K(e,"name",{value:t,configurable:!0});import{prepared as E}from"../sqlite-statements.js";import{randomUUID as Y}from"node:crypto";import{chmodSync as R,copyFileSync as G,existsSync as y,mkdirSync as g,readFileSync as S,readdirSync as b,statSync as I}from"node:fs";import{basename as B,dirname as j,join as m,relative as X}from"node:path";import q from"proper-lockfile";import{CONFIG_FILE as F,PROFILE_DIR as z,STATE_FILE as k}from"../../types.js";import{LockedJsonFile as Q}from"../locked-file.js";import{assertScopedStoreReady as Z,createScopedStore as C,openScopedStore as $,discardIncompleteScopedStore as ee,legacyScopedStorePaths as D,PROFILE_ID_SHAPE as te,scopedStoreExists as v,withProjectStateLock as re,writeOwnerRoot as oe}from"./db.js";import{canonicalRoot as ae,providerStore as h,projectStore as ie,userStore as ne}from"./paths.js";import{profileSpace as P,appSpace as se}from"../layout.js";import{createScopedSchema as x}from"./schema.js";import{openDb as ce,withCanvasWrite as le}from"../canvas/db.js";import{loadSecretsKey as fe,seal as de}from"../secrets/index.js";import{putEnvRowIfAbsent as pe}from"../secrets/env-rows.js";import{DEPLOYMENT_ID as ue}from"../secrets/environment-secrets.js";import{isReservedEnvName as V,validateEnvVarName as me}from"../env-name.js";import{insertAccount as _e,upsertModelCooldown as ye}from"../subscription-state.js";import{userScopeRoot as Ee}from"../scope.js";import{secretsDir as U}from"../layout.js";import{readLegacyUserSnapshot as we}from"./legacy-profiles.js";import{revisionOf as ve}from"./person-store.js";import{loadPersonSettings as Se,applyOpsToRows as he,readSnapshotFromRows as ge}from"./person-rows.js";function w(e){return JSON.parse(S(e,"utf8"))}p(w,"json");function W(e){return e.some(y)}p(W,"existsLegacy");function O(e,t){const o=m(e,".legacy-scoped-state");try{g(o,{mode:448})}catch(a){if(a.code!=="EEXIST"||!I(o).isDirectory())throw a}R(o,448);for(const a of t)if(y(a)&&I(a).isFile()){const i=X(e,a);if(i===""||i.startsWith(".."))throw new Error(`legacy state is outside its owning root: ${a}`);const r=m(o,i);j(r)!==o&&g(j(r),{recursive:!0,mode:448}),G(a,r),R(r,384)}}p(O,"preserve");function Ie(e){const t=e.kind==="user"?ne(e.root):e.kind==="project"?ie(e.root):h(e.root);if(e.kind!=="project"&&v(t))return;if(e.kind==="provider")throw new Error("provider conversion requires convertLegacyProviderStore() under coordinated shared-agent-dir activation");const o=D(t),a=p(()=>{e.kind==="project"&&ee(t),!v(t)&&(e.kind==="project"&&W(o)&&O(t.root,o),C(t,i=>{x(i,e.kind);const r=e.kind==="user"?"user":"project";oe(i,r,t.root),e.kind==="user"?Ae(i,t.root):N(i,r,m(t.root,k))}),e.kind==="user"&&W(o)&&O(t.root,o))},"convert");e.kind==="project"?re(t.root,()=>{a(),Z(t)}):a()}p(Ie,"convertLegacyScopedStore");function ke(e){if(!y(e))return[];const t=JSON.parse(S(e,"utf8"));if(!Array.isArray(t))throw new Error(`legacy subscription pool is malformed: ${e}`);const o=new Set;return t.map((a,i)=>{if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy subscription pool entry ${i+1} is malformed: ${e}`);const r=a,l=typeof r.label=="string"?r.label.trim():"",d=typeof r.refresh=="string"?r.refresh.trim():"",n=typeof r.access=="string"?r.access.trim():"",s=Number(r.expires);if(!l||!d||!n||!Number.isFinite(s))throw new Error(`legacy subscription pool entry ${i+1} is incomplete: ${e}`);const c=l.toLowerCase();if(o.has(c))throw new Error(`legacy subscription pool has duplicate label "${l}": ${e}`);o.add(c);const f=p(u=>Number.isFinite(Number(r[u]))?Number(r[u]):0,"timing"),_=typeof r.accountId=="string"&&r.accountId.trim()!==""?r.accountId.trim():void 0;return{label:l,refresh:d,access:n,expires:s,rateLimitedUntil:f("rateLimitedUntil"),lastAttemptAt:f("lastAttemptAt"),lastRateLimitedAt:f("lastRateLimitedAt"),...r.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},..._?{accountId:_}:{}}})}p(ke,"parseLegacyProviderPool");function Oe(e){if(!y(e))return{};const t=JSON.parse(S(e,"utf8"));if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`legacy provider rotation settings are malformed: ${e}`);const o=t;return{...o.defaultFallbackStrength==="ultra"||o.defaultFallbackStrength==="strong"||o.defaultFallbackStrength==="medium"||o.defaultFallbackStrength==="light"?{defaultFallbackStrength:o.defaultFallbackStrength}:{},...typeof o.revertWhenAvailable=="boolean"?{revertWhenAvailable:o.revertWhenAvailable}:{}}}p(Oe,"parseLegacyRotation");async function Ne(e,t){const o=[];try{for(const a of e)y(a)&&o.push(await q.lock(a,{realpath:!1,retries:0,stale:3e4,update:1e4}));return await t()}finally{await Promise.allSettled(o.reverse().map(a=>a()))}}p(Ne,"withLegacyProviderLocks");async function rt(e){const t=h(e);if(v(t))return;const o=D(t);await Ne(o,async()=>{if(v(t))return;const a=new Map(o.slice(0,2).map((r,l)=>[l===0?"anthropic":"openai-codex",ke(r)])),i=Oe(o[2]);g(t.root,{recursive:!0,mode:448}),O(t.root,o);for(const[r,l]of a){const d=Object.fromEntries(l.map(s=>[Y(),{refresh:s.refresh,access:s.access,expires:s.expires,...s.accountId?{accountId:s.accountId}:{}}]));await new Q(m(t.root,`${r}-credentials.json`),!0,`{"version":1,"accounts":{}}
2
- `).withLockAsync(async(s,c,f)=>(f(`${JSON.stringify({version:1,accounts:d})}
3
- `),{result:void 0}))}C(t,r=>{x(r,"provider");for(const[l,d]of a){const n=JSON.parse(S(m(t.root,`${l}-credentials.json`),"utf8")),s=Object.keys(n.accounts),c=E(r,"INSERT INTO managed_accounts(provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure) VALUES(?,?,?,?,?,?,?,?,?)");d.forEach((f,_)=>c.run(l,s[_],f.label,f.label.toLowerCase(),_,f.lastAttemptAt,f.lastRateLimitedAt,f.rateLimitedUntil,f.authFailure??null))}(i.defaultFallbackStrength!==void 0||i.revertWhenAvailable!==void 0)&&E(r,"INSERT INTO rotation_settings(singleton,default_fallback_strength,revert_when_available) VALUES(1,?,?)").run(i.defaultFallbackStrength??null,i.revertWhenAvailable===void 0?null:i.revertWhenAvailable?1:0)})})}p(rt,"convertLegacyProviderStore");function M(e,t,o){if(!y(o))return;const a=w(o);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy config is malformed: ${o}`);E(e,"INSERT INTO scope_settings(owner_key,raw_json) VALUES(?,?)").run(t,JSON.stringify(a))}p(M,"importSettings");function N(e,t,o){if(!y(o))return;const a=w(o);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy state is malformed: ${o}`);const i=a;E(e,"INSERT INTO scope_bookkeeping(owner_key,last_self_check,active_canvas) VALUES(?,?,?)").run(t,i.last_self_check??null,i.activeCanvas??null);const r=E(e,"INSERT INTO scope_marketplaces(owner_key,name,last_updated) VALUES(?,?,?)");for(const[d,n]of Object.entries(i.marketplaces??{}))r.run(t,d,n.last_updated??null);const l=E(e,"INSERT INTO scope_plugins(owner_key,name,last_updated,etag,checked_at) VALUES(?,?,?,?,?)");for(const[d,n]of Object.entries(i.plugins??{}))l.run(t,d,n.last_updated??null,n.etag??null,n.checked_at??null)}p(N,"importState");function Ae(e,t){M(e,"user",m(t,F)),N(e,"user",m(t,k));const o=m(t,z);if(y(o))for(const i of b(o,{withFileTypes:!0})){if(!i.isDirectory()||!te.test(i.name))continue;const r=i.name,l=m(o,r),d=m(l,"profile.json");if(!y(d))throw new Error(`legacy profile manifest is missing: ${d}`);const n=w(d);if(!n||typeof n!="object"||!Array.isArray(n.projects)||typeof n.name!="string"||typeof n.created_at!="string")throw new Error(`legacy profile manifest is malformed: ${d}`);E(e,"INSERT INTO profiles(id,name,created_at,last_used_at,paused_at,default_kind,grantee,metadata_json) VALUES(?,?,?,?,?,?,?,?)").run(r,n.name,n.created_at,n.last_used_at??null,n.paused_at??null,n.default_kind??null,n.grantee??null,JSON.stringify(n.metadata??{})),E(e,"INSERT INTO scope_owners(owner_key,kind,root,profile_id) VALUES(?,?,?,?)").run(`profile:${r}`,"profile",ae(P(n.grantee??"app:terminal",r).dir),r);const s=E(e,"INSERT INTO profile_projects(profile_id,path,position) VALUES(?,?,?)"),c=E(e,"INSERT INTO legacy_project_caps(profile_id,path,memory) VALUES(?,?,?)");n.projects.forEach((f,_)=>{s.run(r,f.path,_),f.memory!==void 0&&f.memory!=="content"&&c.run(r,f.path,f.memory)}),M(e,`profile:${r}`,m(l,F)),N(e,`profile:${r}`,m(l,k))}const a=m(t,"profile-defaults.json");if(y(a)){const i=w(a);if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`legacy profile defaults are malformed: ${a}`);const r=E(e,"INSERT INTO profile_defaults(directory,profile_id) VALUES(?,?)");for(const[l,d]of Object.entries(i)){if(typeof d!="string")throw new Error(`legacy profile default is malformed: ${a}`);r.run(l,d)}}}p(Ae,"importUser");const A="person_stores_copied",L={anthropic:"anthropic-credentials.json","openai-codex":"openai-codex-credentials.json",openai:"openai-credentials.json"};async function Le(){return await(await ce()).prepare("SELECT value FROM canvas_meta WHERE key = ?").get(A)!==void 0}p(Le,"personStoresCopied");function Te(e){const t=h(e);if(!v(t))return[];const o=$(t),a=[];for(const i of Object.keys(L)){const r=m(e,L[i]);if(!y(r))continue;const l=w(r),d=E(o,"SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM managed_account_model_cooldowns WHERE provider_id=?").all(i);for(const n of E(o,"SELECT id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure FROM managed_accounts WHERE provider_id=? ORDER BY position").all(i)){const s=l.accounts?.[n.id];s!==void 0&&a.push({provider:i,id:n.id,row:{providerId:i,id:n.id,label:n.label,labelKey:n.label_key,position:n.position,lastAttemptAt:n.last_attempt_at,lastRateLimitedAt:n.last_rate_limited_at,rateLimitedUntil:n.rate_limited_until,...n.auth_failure?{authFailure:n.auth_failure}:{}},tokens:{refresh:s.refresh,access:s.access,expires:s.expires,...s.accountId?{accountId:s.accountId}:{},...s.clientId?{clientId:s.clientId}:{}},cooldowns:d.filter(c=>c.account_id===n.id).map(c=>({family:c.family,until:c.rate_limited_until,at:c.last_rate_limited_at}))})}}return a}p(Te,"readLegacyAccounts");function T(e,t){if(!y(e)||!I(e).isFile())return{};let o;try{o=w(e)}catch{return{}}const a={};if(o===null||typeof o!="object"||o.vars===null||typeof o.vars!="object"||Array.isArray(o.vars))return a;for(const[i,r]of Object.entries(o.vars))me(i).isValid&&t(i)&&typeof r=="string"&&!r.includes("\0")&&(a[i]=r);return a}p(T,"readLegacyEnvFile");const Re=new Set(["CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN"]);async function be(e,t,o){const a=m(U(),"env");if(!y(a))return;const i=p(async(r,l)=>{for(const[d,n]of Object.entries(l))await pe(e,r,d,n)},"put");for(const r of o)await i({person:t,kind:"profile",id:r.profileId},T(P(r.manifest.grantee??"app:terminal",r.profileId).env,l=>!V(l)));for(const r of b(a,{withFileTypes:!0})){if(!r.isDirectory())continue;const l=`app:${r.name}`;B(se(l).root)===r.name&&await i({person:t,kind:"app",id:l},T(m(a,r.name,"_app"),d=>!V(d)))}await i({person:null,kind:"deployment",id:ue},T(m(a,"_deployment"),r=>Re.has(r)))}p(be,"copyLegacyEnvFiles");async function je(e,t,o){const a=Te(o),i=(()=>{const s=h(o);if(v(s))return E($(s),"SELECT default_fallback_strength,revert_when_available FROM rotation_settings WHERE singleton=1").get()})(),r=m(o,"openai-device-id"),l=y(r)?S(r,"utf8").trim():"",d=m(o,"auth.json"),n=y(d)?Object.entries(w(d)).filter(([s])=>!(s in L)):[];await le(async s=>{if(await s.prepare("SELECT 1 FROM canvas_meta WHERE key = ?").get(A)===void 0){if(t!==null){const c=await ge(s,e),f=[],_=new Set(c.profiles.map(u=>u.profileId));for(const u of t.profiles)_.has(u.profileId)||f.push({op:"profile.insert",profile:u});for(const u of Object.keys(t.settings))c.settings[u]===void 0&&f.push({op:"settings.replace",owner:u,raw:t.settings[u],ifRevision:ve(void 0)});for(const u of Object.keys(t.state)){const H=t.state[u];c.state[u]===void 0&&(u==="user"||_.has(u.replace(/^profile:/,""))||t.profiles.some(J=>`profile:${J.profileId}`===u))&&f.push({op:"state.write",owner:u,state:H})}Object.keys(c.defaults).length===0&&Object.keys(t.defaults).length>0&&f.push({op:"defaults.replace",defaults:t.defaults}),f.length>0&&await he(s,e,f)}for(const c of a)if(await s.prepare("SELECT 1 FROM model_accounts WHERE person=? AND provider_id=? AND (id=? OR label_key=?)").get(e,c.provider,c.id,c.row.labelKey)===void 0){await _e(s,e,c.provider,c.row,c.tokens);for(const _ of c.cooldowns)await ye(s,e,c.provider,c.id,_.family,_.until,_.at)}i!==void 0&&await s.prepare("INSERT INTO model_settings(person,default_fallback_strength,revert_when_available) VALUES(?,?,?) ON CONFLICT(person) DO NOTHING").run(e,i.default_fallback_strength,i.revert_when_available),/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l)&&await s.prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id)").run(e,l.toLowerCase());for(const[c,f]of n){const{sealed:_,keyId:u}=de(JSON.stringify(f),fe(),`model_api_keys|${e}|${c}`);await s.prepare("INSERT INTO model_api_keys(person,provider_id,credential_sealed,key_id,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(person,provider_id) DO NOTHING").run(e,c,_,u,new Date().toISOString())}await be(s,e,t?.profiles??[]),await s.prepare("INSERT INTO canvas_meta(key,value) VALUES(?,?)").run(A,new Date().toISOString())}})}p(je,"copyPersonStoresToRows");async function ot(e){if(!await Le()){const t=Ee();Ie({kind:"user",root:t}),await je(e,we(t),U())}await Se(e)}p(ot,"adoptInstallPerson");export{ot as adoptInstallPerson,rt as convertLegacyProviderStore,Ie as convertLegacyScopedStore,je as copyPersonStoresToRows,Le as personStoresCopied};
@@ -1,14 +0,0 @@
1
- export interface BootMigrationResult {
2
- changed: boolean;
3
- summary: Record<string, unknown>;
4
- }
5
- export interface BootMigration {
6
- readonly id: string;
7
- readonly description: string;
8
- /** Runs unconditionally at every daemon boot. Must be safe to re-run every
9
- * time (idempotent via its own convergence, not a version gate) and must
10
- * isolate its own per-item failures — a thrown error here is NOT caught by
11
- * the boot sequence and would abort daemon startup. */
12
- apply(): BootMigrationResult | Promise<BootMigrationResult>;
13
- }
14
- export declare const BOOT_MIGRATIONS: readonly BootMigration[];
@@ -1 +0,0 @@
1
- var c=Object.defineProperty;var o=(e,t)=>c(e,"name",{value:t,configurable:!0});import{migrateLegacyInboxIdentities as p}from"../core/feed/inbox-migrate.js";import{backfillComputedRev as h}from"../core/grants/mirror.js";import{copyBodyFilesToTable as m,repairBodyHashes as f}from"../core/graph/bodies-boot-copy.js";import{listProfiles as u,fillProfileProjectRepo as y}from"../core/profiles/manifest.js";import{reposForCwd as g,warmCheckoutIdentities as b}from"../core/graph/repo-sync/repos.js";import{withCanvasWrite as v}from"../core/canvas/db.js";import{isCloudRole as a}from"../core/canvas/person-state.js";import{emitEvent as n}from"../core/events/emit.js";const F=[{id:"legacy-inbox-identities",description:"normalize pre-cutover inbox entry/operation ids (UUID-spelled or missing) and cursors (ISO-timestamp boundaries) into canonical 32-lowercase-hex identities the strict inbox reader requires.",apply:o(()=>{const e=p();return{changed:e.nodes>0||e.failures>0,summary:{...e}}},"apply")},{id:"grant-computed-rev",description:"mark grant rows a pre-C-D2 build wrote (scopes computed, computed_rev NULL) as computed for their revision, so the terminal grant reads as active before the first directory sync after an upgrade or rollback (NL-550). A cloud role skips it: the directory owns its shared rows.",apply:o(async()=>{if(a())return{changed:!1,summary:{}};try{const e=await h();return{changed:e>0,summary:{rows:e}}}catch(e){return n({level:"warn",event:"daemon.boot_migration.failed",error:e,fields:{migration:"grant-computed-rev"}}),{changed:!1,summary:{}}}},"apply")},{id:"bodies-to-table",description:"copy document text from the old <home>/bodies files into the bodies table (D106). Verifies each file by sha256, skips and reports mismatches, leaves the files for rollback. A cloud role copies nothing.",apply:o(async()=>{if(a())return{changed:!1,summary:{}};const e=await m();return{changed:e.copied>0||e.mismatched.length>0,summary:{...e}}},"apply")},{id:"body-hash-repair",description:"rekey bodies rows PR #822 stored under the hash of the text before NUL became U+FFFD (D106): every revision naming such a hash names the hash of the stored text, and the invalid old-key row is removed. Runs in every role and after bodies-to-table, before readers serve. A mismatch with no intact original (a retained <home>/bodies file or a repo ref body) that becomes exactly the stored text stops the boot and is reported, never rehashed.",apply:o(async()=>{const e=await f();if(e.unresolved.length>0)throw new Error(`body-hash-repair: ${e.unresolved.length} bodies row(s) do not hash to their key and no intact original explains them: ${e.unresolved.join(", ")}`);return{changed:e.rekeyed>0||e.removed>0,summary:{...e}}},"apply")},{id:"profile-project-repos",description:"give each profile folder entry with no repo the repo its checkout identifies as (the nearest enclosing one), so a node with no checkout still gets that repo's documents. A folder no repo identifies keeps its path only. An entry that has a repo is skipped, so a re-run changes nothing. A cloud role skips it: its profiles name repos directly.",apply:o(async()=>{if(a())return{changed:!1,summary:{}};let e=0,t=0;for(const{profileId:s,manifest:d}of u())for(const r of d.projects)if(!(r.path===void 0||r.repo!==void 0))try{await b(r.path);const i=(await v(async l=>await g(l,r.path)))[0];i!==void 0&&await y(s,r.path,i.id)&&e++}catch(i){t++,n({level:"warn",event:"daemon.boot_migration.failed",error:i,fields:{migration:"profile-project-repos",profile:s,path:r.path}})}return{changed:e>0,summary:{filled:e,failed:t}}},"apply")}];export{F as BOOT_MIGRATIONS};
@@ -1,8 +0,0 @@
1
- import type { ImportPlan, ImportReport } from './plan.js';
2
- import type { CanvasDb } from '../../core/canvas/db.js';
3
- /** The canvas_meta key whose presence means this home's legacy stores were imported. */
4
- export declare const IMPORT_DONE_KEY = "canvas-import";
5
- export declare const IMPORT_ID = "004-canvas-documents";
6
- export declare function readImportRecord(db: CanvasDb): Promise<ImportReport | null>;
7
- /** Run inside the caller's write transaction; each revision's text is stored in it. Throws on any divergence from the plan. */
8
- export declare function applyPlan(db: CanvasDb, plan: ImportPlan): Promise<void>;
@@ -1 +0,0 @@
1
- var x=Object.defineProperty;var c=(n,a)=>x(n,"name",{value:a,configurable:!0});import{put as N}from"../../core/graph/bodies.js";import{importDocument as O}from"../../core/graph/documents.js";import{linksIn as _}from"../../core/graph/documents.js";import{recordActedOn as M,setLinks as R}from"../../core/graph/edges.js";import{resolveName as $}from"../../core/graph/names.js";import{ensureOwner as y,nodeObject as k,ownerForGrantee as b}from"../../core/graph/objects.js";import{ensureRepo as S}from"../../core/graph/repo-sync/repos.js";import{recordWatch as T}from"../../core/graph/watches.js";import{mapAsync as A}from"../../core/async-array.js";import{personId as K}from"../../core/canvas/person.js";const v="canvas-import",j="004-canvas-documents";async function Y(n){const a=await n.prepareUncached("SELECT value FROM canvas_meta WHERE key = ?").get(v);if(a===void 0)return null;const i=JSON.parse(a.value).report;return{...i,resolutions:i.resolutions??[]}}c(Y,"readImportRecord");async function q(n,a){const i=new Map;for(const e of a.documents)for(const t of e.revisions)i.has(t.body)||i.set(t.body,await N(n,t.body));const l=new Map(a.owners.map(e=>[e.key,e])),u=new Map,w=c(async e=>{const t=u.get(e.key);if(t)return t;let o;switch(e.type){case"person":o=await b(n,K());break;case"app":o=await y(n,"app","app",`app:${e.handle}`,e.handle);break;case"profile":{const p=l.get(e.ownerKey);if(!p)throw new Error(`import: profile ${e.key} names unplanned app ${e.ownerKey}`);o=await y(n,"profile","profile",e.key.slice(8),e.handle,await w(p));break}case"repo":o=await S(n,{scheme:e.scheme,externalId:e.externalId,handleHint:e.handle},e.handle);break;case"node":o=await k(n,e.handle);break}if(e.type!=="node"&&o.name!==e.handle)throw new Error(`import: owner ${e.key} holds handle ${o.name}, planned ${e.handle}`);return u.set(e.key,o),o},"ownerRow"),I={class:"person",person:await w(l.get("person")??{key:"person",type:"person",handle:"user"})},f=new Map,m=c(async e=>{let t=f.get(e);return t||f.set(e,t=await k(n,e)),t},"node"),h=[];for(const e of a.documents){const t=await w(l.get(e.ownerKey)),o=await O(n,{owner:t,name:e.name,kind:e.kind,preview:e.preview,privacy:e.privacy,summary:e.summary,whyItExists:e.whyItExists,unlisted:e.unlisted,rules:e.rules,lintIgnore:e.lintIgnore,extensions:e.extensions,revisions:await A(e.revisions,async r=>({body_hash:i.get(r.body),author:r.authorNodeId===null?null:await m(r.authorNodeId),rationale:r.rationale,created_at:r.createdAt}))}),p=new Set(e.revisions.flatMap(r=>r.authorNodeId===null?[]:[r.authorNodeId]));h.push({doc:o,owner:t,body:e.revisions[e.revisions.length-1].body,authors:p})}for(const{doc:e,owner:t,body:o,authors:p}of h){const r=[];for(const s of _(o)){const g=s.includes("/")?[s]:[`${t.type==="node"?t.id:t.name}/${s}`,s];for(const E of g){const d=await $(n,I,E);if("object"in d){r.push({written_as:s,dst:d.object});break}if("deleted"in d){r.push({written_as:s,dst:d.deleted});break}}}await R(n,e,r);for(const s of p)await M(n,await m(s),e),await T(n,await m(s),e,"write")}await n.prepareUncached("INSERT INTO canvas_meta (key, value) VALUES (?, ?)").run(v,JSON.stringify({id:j,report:a.report}))}c(q,"applyPlan");export{v as IMPORT_DONE_KEY,j as IMPORT_ID,q as applyPlan,Y as readImportRecord};
@@ -1,16 +0,0 @@
1
- import { type ImportBlocker, type ImportReport } from './plan.js';
2
- export type { ImportBlocker, ImportReport } from './plan.js';
3
- export interface CanvasImportResult {
4
- report: ImportReport;
5
- blockers: ImportBlocker[];
6
- dryRun: boolean;
7
- /** True while this home still has to be imported (always false after a write run succeeds). */
8
- pending: boolean;
9
- }
10
- /** Whether this home's import has already been recorded. */
11
- export declare function canvasImportDone(): Promise<boolean>;
12
- /** Plan and (unless `dryRun` or blocked) apply the import. On an imported home a dry run
13
- * returns the recorded report; a write run does nothing and returns empty counts. */
14
- export declare function runCanvasImport(opts: {
15
- dryRun: boolean;
16
- }): Promise<CanvasImportResult>;
@@ -1,2 +0,0 @@
1
- var S=Object.defineProperty;var c=(r,t)=>S(r,"name",{value:t,configurable:!0});import{projectPaths as y}from"../../api/dto/profiles.js";import{existsSync as u}from"node:fs";import{join as f}from"node:path";import{openDb as l,withCanvasWrite as w}from"../../core/canvas/db.js";import{nodeAgentDir as h,nodeRecordDir as L,onDiskMigrationMarkerPath as I}from"../../core/canvas/paths.js";import{identifyCheckout as j}from"../../core/graph/repo-sync/identity.js";import{profileSpace as k,userRoot as C}from"../../core/layout.js";import{deleteLegacyProjectCaps as _,listLegacyProjectCaps as O,readLegacyUserSnapshot as P}from"../../core/scoped-state/legacy-profiles.js";import{personIdAsync as b}from"../../core/canvas/person.js";import{userStore as A}from"../../core/scoped-state/paths.js";import{userScopeRoot as g}from"../../core/scope.js";import{LEGACY_LOCAL_PERSON as D}from"../../core/canvas/legacy-person.js";import{applyPlan as v,readImportRecord as R}from"./apply.js";import{readLegacyCorpus as x,readMarkerIds as M}from"./legacy/discover.js";import{planImport as N}from"./plan.js";const T=c(()=>({stores:[],counts:{},rewrites:[],droppedFields:[],skipped:[],resolutions:[]}),"emptyReport");async function F(){const r=g(),t=P(r)?.profiles??[],o=O(r),d=A(r).path,a=t.map(({profileId:e,manifest:i})=>{const s=i.grantee??"app:terminal",m=new Map(o.filter(n=>n.profileId===e).map(n=>[n.path,n.memory]));return{id:e,name:i.name,app:s,memory:k(s,e).dir,projects:y(i.projects),raw:{projects:y(i.projects).map(n=>m.has(n)?{path:n,memory:m.get(n)}:{path:n})},manifestPath:`${d}#${e}`}}),p=await(await l()).prepareUncached("SELECT node_id, cwd, grantee FROM node_rows ORDER BY created").all(),E=p.map(e=>{const i=e.grantee===D?"app:terminal":e.grantee,s=i?.startsWith("app:")?h(e.node_id,i):null,m=s!==null&&(u(f(s,"context"))||u(f(s,"reports")))?s:L(e.node_id);return{id:e.node_id,dir:m}});return{roots:{userMemory:f(C(),"memory"),profiles:a,nodeCwds:[...new Set(p.map(e=>e.cwd))],nodes:E},stored:t}}c(F,"legacyRoots");async function U(){const{roots:r,stored:t}=await F(),o=x(r),d=await(await l()).prepareUncached(`SELECT o.type, o.name AS handle, i.external_id AS externalId FROM objects o
2
- LEFT JOIN identities i ON i.object = o.id WHERE o.type IN ('person','app','repo','profile')`).all();return N(o,{roots:r,markerIds:M(I()),repoIdentity:j,existingOwners:d,storedProfiles:t.map(a=>({id:a.profileId,deliveryLimits:{...a.manifest.delivery_limits??{}}}))})}c(U,"plan");async function or(){return await R(await l())!==null}c(or,"canvasImportDone");async function tr(r){const t=await R(await l());if(t!==null)return{report:r.dryRun?t:T(),blockers:[],dryRun:r.dryRun,pending:!1};const o=await U();if(r.dryRun||o.blockers.length>0)return{report:o.report,blockers:o.blockers,dryRun:r.dryRun,pending:!0};const d=await b();return await w(async a=>{for(const p of o.profileLimits)if((await a.prepare("UPDATE profiles SET delivery_limits_json = ? WHERE id = ? AND person = ?").run(JSON.stringify(p.deliveryLimits),p.profileId,d)).changes!==1)throw new Error(`no stored profile ${p.profileId}`)}),_(g()),await w(async a=>await v(a,o)),{report:o.report,blockers:[],dryRun:!1,pending:!1}}c(tr,"runCanvasImport");export{or as canvasImportDone,tr as runCanvasImport};
@@ -1,16 +0,0 @@
1
- import type { LegacyCorpus, LegacyProfile, LegacyRoots } from './types.js';
2
- export type { LegacyCorpus, LegacyDoc, LegacyOwnerRef, LegacyProfile, LegacyRoots, LegacyStoreRoot, LegacyHistoryRecord } from './types.js';
3
- /** Every stored profile manifest, read as raw JSON (the current manifest reader
4
- * is not used). `memoryFor(app, id)` resolves the profile's store path. */
5
- export declare function readLegacyProfiles(profilesRoot: string, memoryFor: (app: string, id: string) => string): {
6
- profiles: LegacyProfile[];
7
- skipped: Array<{
8
- path: string;
9
- reason: string;
10
- }>;
11
- };
12
- /** Ids listed in `<canvas home>/on-disk-migrations.json`, or null when the marker is absent. */
13
- export declare function readMarkerIds(markerPath: string): string[] | null;
14
- export declare function readLegacyCorpus(roots: LegacyRoots): LegacyCorpus;
15
- /** Cheap probe: is there any legacy document to import? */
16
- export declare function hasLegacyContent(roots: LegacyRoots): boolean;
@@ -1 +0,0 @@
1
- var J=Object.defineProperty;var l=(t,o)=>J(t,"name",{value:o,configurable:!0});import{existsSync as D,readdirSync as b,readFileSync as x,realpathSync as P,statSync as R}from"node:fs";import{basename as T,dirname as C,isAbsolute as L,join as i,relative as A,resolve as F}from"node:path";import{walkFiles as I}from"../../../core/fs-utils.js";import{historyLogPath as O,HISTORY_DIR as z,readHistory as X}from"./history.js";import{walkNestedStores as W}from"./nested.js";import{contextDocName as _,parseFile as $,rawFile as E,storeDocName as q}from"./parse.js";const G=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;function k(t){try{return P(t)}catch{return F(t)}}l(k,"real");const w=l(t=>{try{return R(t).isDirectory()}catch{return!1}},"isDir"),Y=l(t=>["canvas","canvas.db","runtime","profiles"].some(o=>D(i(t,o))),"isCrouterHome"),H=l(t=>I(t,o=>o.toLowerCase().endsWith(".md"),o=>o.startsWith(".")).sort(),"markdownIn");function re(t,o){const s=[],y=[];if(!w(t))return{profiles:s,skipped:y};for(const j of b(t).sort()){const d=i(t,j,"profile.json");if(!G.test(j)||!D(d))continue;let h;try{const p=JSON.parse(x(d,"utf8"));if(p===null||typeof p!="object"||Array.isArray(p))throw new Error("not a JSON object");h=p}catch(p){y.push({path:d,reason:`invalid-manifest: ${p.message}`});continue}const v=typeof h.grantee=="string"?h.grantee:"app:terminal",M=Array.isArray(h.projects)?h.projects.flatMap(p=>typeof p=="string"?[p]:p!==null&&typeof p=="object"&&typeof p.path=="string"?[p.path]:[]):[];s.push({id:j,name:typeof h.name=="string"?h.name:j,app:v,memory:o(v,j),projects:M,raw:h,manifestPath:d})}return{profiles:s,skipped:y}}l(re,"readLegacyProfiles");function ne(t){if(!D(t))return null;const o=JSON.parse(x(t,"utf8"));if(!Array.isArray(o))throw new Error(`${t}: not a JSON array`);return o.map(s=>typeof s=="string"?s:String(s.id))}l(ne,"readMarkerIds");function B(t){const o=i(t,".git");if(w(o))return k(o);if(!D(o))return null;const s=/^gitdir:\s*(.+)$/m.exec(x(o,"utf8"));if(!s)return null;const y=L(s[1].trim())?s[1].trim():F(t,s[1].trim()),j=i(y,"commondir");if(!D(j))return k(y);const d=x(j,"utf8").trim();return k(L(d)?d:F(y,d))}l(B,"gitCommonDir");function K(t){const o={docs:[],storeRoots:[],skipped:[],orphanHistory:0,orphanNodeDirs:0,nonMarkdown:0,injectedDocs:0},s=new Set([t.userMemory,...t.profiles.map(e=>e.memory)].map(k)),y=l((e,r,c)=>{const u=H(e),S=new Set(u.map(n=>O(e,n)));o.orphanHistory+=I(i(e,z),n=>n.endsWith(".jsonl")).filter(n=>!S.has(n)).length;let g=0;for(const n of u){const f=c+q(A(e,n));let m;try{m=$(n)}catch(N){o.docs.push({path:n,owner:r,name:f,source:"store",...E(n),history:[],invalid:{kind:"invalid-source",reason:`invalid frontmatter: ${N.message}`}}),g+=1;continue}let a;try{a=X(O(e,n))}catch(N){o.docs.push({path:n,owner:r,name:f,source:"store",...m,history:[],invalid:{kind:"invalid-history",reason:`unreadable history log: ${N.message}`}}),g+=1;continue}o.docs.push({path:n,owner:r,name:f,source:"store",...m,history:a}),g+=1}o.storeRoots.push({root:e,owner:r,docs:g})},"readStore");w(t.userMemory)&&y(t.userMemory,{type:"person"},"");for(const e of t.profiles)w(e.memory)&&y(e.memory,{type:"profile",id:e.id},"");const j=l(e=>{let r=null;for(let c=k(e);;c=C(c)){if(D(i(c,".git")))return c;const u=i(c,".crouter","memory");if(r===null&&w(u)&&!s.has(k(u))&&!Y(i(c,".crouter"))&&(r=c),C(c)===c)return r}},"projectRoot"),d=[];for(const e of[...t.profiles.flatMap(r=>r.projects),...t.nodeCwds]){if(!w(e))continue;const r=j(e);r!==null&&d.push(r)}const h=new Map,v=new Set,M=[];for(;d.length>0;){const e=d.shift();if(v.has(e))continue;v.add(e);const r=B(e);if(M.push({root:e,commonDir:r}),r!==null){h.set(r,[...h.get(r)??[],e]);const c=C(r);T(r)===".git"&&w(i(c,".git"))&&d.push(c)}d.push(...W(e).embeddedRepos)}for(const{root:e,commonDir:r}of M.sort((c,u)=>c.root.localeCompare(u.root))){const c=r===null?[e]:h.get(r),u=c.find(a=>w(i(a,".git")))??[...c].sort()[0],S=i(e,".crouter","memory"),g=w(S)&&!s.has(k(S)),n=W(e).nested.filter(a=>!s.has(k(i(e,a,".crouter","memory"))));let f=null;if(g&&D(i(S,"INDEX.md")))try{const a=$(i(S,"INDEX.md")).frontmatter?.namespace;typeof a=="string"&&a!==""&&(f=a)}catch{}const m={type:"repo",root:e,commonDir:r,namespace:f};if(e!==u){g&&o.storeRoots.push({root:S,owner:m,docs:0,skipped:"duplicate-worktree"});for(const a of n)o.storeRoots.push({root:i(e,a,".crouter","memory"),owner:m,docs:0,skipped:"duplicate-worktree"});continue}g&&y(S,m,"");for(const a of n)y(i(e,a,".crouter","memory"),m,a.split(/[\\/]/).join("/")+"/")}const p=new Set(t.nodes.map(e=>e.id));for(const e of new Set(t.nodes.map(r=>C(r.dir))))for(const r of b(e,{withFileTypes:!0}))r.isDirectory()&&!p.has(r.name)&&(o.orphanNodeDirs+=1);for(const{id:e,dir:r}of t.nodes){const c={type:"node",id:e};D(i(r,"injected-docs.json"))&&(o.injectedDocs+=1);const u=i(r,"context");w(i(u,"memory"))&&y(i(u,"memory"),c,"");const S=l((n,f,m)=>{try{o.docs.push({path:n,owner:c,name:f,source:m,...$(n),history:[]})}catch(a){o.docs.push({path:n,owner:c,name:f,source:m,...E(n),history:[],invalid:{kind:"invalid-source",reason:`invalid frontmatter: ${a.message}`}})}},"readPlain");for(const n of I(u,()=>!0,f=>f.startsWith(".")).sort()){const f=A(u,n),m=f.split(/[\\/]/)[0];m==="memory"||m==="jobs"||(n.toLowerCase().endsWith(".md")?S(n,_(f),"context"):o.nonMarkdown+=1)}const g=i(r,"reports");if(w(g))for(const n of b(g,{withFileTypes:!0}).sort((f,m)=>f.name.localeCompare(m.name)))n.isFile()&&(n.name.toLowerCase().endsWith(".md")?S(i(g,n.name),`reports/${n.name.replace(/\.md$/i,"")}`,"report"):o.nonMarkdown+=1)}return o}l(K,"readLegacyCorpus");function se(t){const o=l(s=>w(s)&&H(s).length>0,"anyMd");return o(t.userMemory)||t.profiles.some(s=>o(s.memory))||t.nodes.some(s=>o(i(s.dir,"context"))||o(i(s.dir,"reports")))?!0:K({...t,nodes:[]}).docs.length>0}l(se,"hasLegacyContent");export{se as hasLegacyContent,K as readLegacyCorpus,re as readLegacyProfiles,ne as readMarkerIds};
@@ -1,5 +0,0 @@
1
- import type { LegacyHistoryRecord } from './types.js';
2
- export declare const HISTORY_DIR = ".history";
3
- export declare function historyLogPath(storeRoot: string, docPath: string): string;
4
- /** Records of the current life, or throws naming the bad line. */
5
- export declare function readHistory(logPath: string): LegacyHistoryRecord[];
@@ -1,2 +0,0 @@
1
- var c=Object.defineProperty;var o=(r,t)=>c(r,"name",{value:t,configurable:!0});import{existsSync as f,readFileSync as l}from"node:fs";import{join as a,relative as y}from"node:path";const h=".history";function w(r,t){return a(r,h,y(r,t).replace(/\.md$/i,"")+".jsonl")}o(w,"historyLogPath");function x(r){if(!f(r))return[];const t=[];return l(r,"utf8").split(`
2
- `).forEach((n,i)=>{if(n.trim()==="")return;let s;try{s=JSON.parse(n)}catch(p){throw new Error(`line ${i+1}: ${p.message}`)}const e=s;if(e===null||typeof e!="object"||typeof e.op!="string"||typeof e.at!="string"||typeof e.after!="string")throw new Error(`line ${i+1}: not a history record`);e.op==="delete"?t.length=0:t.push(e)}),t}o(x,"readHistory");export{h as HISTORY_DIR,w as historyLogPath,x as readHistory};
@@ -1,7 +0,0 @@
1
- export interface NestedWalk {
2
- /** `<rel>` of each `<root>/<rel>/.crouter/memory`, rel non-empty. */
3
- nested: string[];
4
- /** Folders below the root holding their own `.git`. */
5
- embeddedRepos: string[];
6
- }
7
- export declare function walkNestedStores(root: string): NestedWalk;
@@ -1 +0,0 @@
1
- var m=Object.defineProperty;var d=(s,e)=>m(s,"name",{value:e,configurable:!0});import{existsSync as c,readdirSync as p}from"node:fs";import{join as i,relative as u}from"node:path";function l(s){const e={nested:[],embeddedRepos:[]},o=[s];for(;o.length>0;){const t=o.pop();if(t!==s){if(c(i(t,".git"))){e.embeddedRepos.push(t);continue}c(i(t,".crouter","memory"))&&e.nested.push(u(s,t))}let r;try{r=p(t,{withFileTypes:!0})}catch{continue}for(const n of r)!n.isDirectory()||n.name.startsWith(".")||n.name==="node_modules"||o.push(i(t,n.name))}return e.nested.sort(),e.embeddedRepos.sort(),e}d(l,"walkNestedStores");export{l as walkNestedStores};
@@ -1,14 +0,0 @@
1
- export interface ParsedFile {
2
- frontmatter: Record<string, unknown> | null;
3
- body: string;
4
- mtime: string;
5
- }
6
- /** Throws when the frontmatter is not valid YAML. */
7
- export declare function parseFile(path: string): ParsedFile;
8
- /** A file whose frontmatter does not parse: the whole text is the body. */
9
- export declare function rawFile(path: string): ParsedFile;
10
- /** Frozen store naming: drop `.md`, strip each segment's `NN-` ordering prefix,
11
- * fold `a/INDEX` to `a`; the store's root `INDEX.md` is `index`. */
12
- export declare function storeDocName(relPath: string): string;
13
- /** A node context file's name: its folder-relative path without `.md`. */
14
- export declare function contextDocName(relPath: string): string;
@@ -1 +0,0 @@
1
- var m=Object.defineProperty;var r=(e,t)=>m(e,"name",{value:t,configurable:!0});import{readFileSync as n,statSync as o}from"node:fs";import{parseFrontmatterGeneric as a}from"../../../core/frontmatter.js";function f(e){const t=a(n(e,"utf8"));return{frontmatter:t.data,body:t.body,mtime:o(e).mtime.toISOString()}}r(f,"parseFile");function u(e){return{frontmatter:null,body:n(e,"utf8"),mtime:o(e).mtime.toISOString()}}r(u,"rawFile");function d(e){const t=e.replace(/\\/g,"/").replace(/\.md$/i,"").split("/").map(i=>i.replace(/^\d{2}-/,""));return t[t.length-1]==="INDEX"&&t.pop(),t.length===0?"index":t.join("/")}r(d,"storeDocName");function s(e){return e.replace(/\\/g,"/").replace(/\.md$/i,"")}r(s,"contextDocName");export{s as contextDocName,f as parseFile,u as rawFile,d as storeDocName};