@north-light/cli 0.3.755 → 0.3.756
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +1 -2
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/health.d.ts +0 -54
- package/dist/api/routes.d.ts +0 -1
- package/dist/api/routes.js +1 -1
- package/dist/build-root.d.ts +0 -3
- package/dist/build-root.js +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +1 -1
- package/dist/cli.js +8 -9
- package/dist/clients/attach/viewer.js +481 -481
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys.js +1 -1
- package/dist/core/bootstrap.js +1 -1
- package/dist/core/canvas/boot.d.ts +0 -25
- package/dist/core/canvas/boot.js +1 -1
- package/dist/core/canvas/executions.d.ts +0 -3
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/pid.d.ts +0 -10
- package/dist/core/canvas/pid.js +5 -5
- package/dist/core/directory/join.js +1 -1
- package/dist/core/grants/mirror.d.ts +0 -5
- package/dist/core/grants/mirror.js +6 -6
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/page-schema.d.ts +1 -1
- package/dist/core/io.js +4 -4
- package/dist/core/layout.d.ts +0 -2
- package/dist/core/layout.js +2 -2
- package/dist/core/scoped-state/db.js +2 -2
- package/dist/daemon/api/handlers/daemon.js +1 -1
- package/dist/daemon/api/map.d.ts +1 -6
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/control.d.ts +0 -8
- package/dist/daemon/crtrd.js +18 -20
- package/dist/daemon/manage.js +3 -3
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +0 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +0 -1
- package/packages/crouter-api/dist/build-root.js +0 -9
- package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
- package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
- package/packages/crouter-api/dist/commands/sys.js +1 -2
- package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
- package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
- package/packages/crouter-api/dist/core/directory/join.js +18 -1
- package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
- package/packages/crouter-api/dist/core/grants/sync.js +2 -2
- package/packages/crouter-api/dist/core/io.js +0 -5
- package/packages/crouter-api/dist/core/layout.js +2 -19
- package/packages/crouter-api/dist/daemon/api/map.js +0 -16
- package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
- package/packages/crouter-api/dist/daemon/manage.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/migrate.d.ts +0 -1
- package/dist/commands/sys/migrate.js +0 -1
- package/dist/core/feed/inbox-migrate.d.ts +0 -11
- package/dist/core/feed/inbox-migrate.js +0 -3
- package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
- package/dist/core/graph/bodies-boot-copy.js +0 -1
- package/dist/core/layout-migrate/index.d.ts +0 -38
- package/dist/core/layout-migrate/index.js +0 -4
- package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
- package/dist/core/layout-migrate/loose-keys.js +0 -1
- package/dist/core/layout-migrate/paths.d.ts +0 -30
- package/dist/core/layout-migrate/paths.js +0 -1
- package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
- package/dist/core/layout-migrate/stored-paths.js +0 -11
- package/dist/core/layout-migrate/stores.d.ts +0 -30
- package/dist/core/layout-migrate/stores.js +0 -3
- package/dist/core/scoped-state/migrate.d.ts +0 -15
- package/dist/core/scoped-state/migrate.js +0 -3
- package/dist/daemon/boot-migrations.d.ts +0 -14
- package/dist/daemon/boot-migrations.js +0 -1
- package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
- package/dist/migrations/004-canvas-documents/apply.js +0 -1
- package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/index.js +0 -2
- package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
- package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
- package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
- package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
- package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
- package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
- package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
- package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
- package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
- package/dist/migrations/004-canvas-documents/plan.js +0 -3
- package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
- package/dist/migrations/004-canvas-documents/pointers.js +0 -4
- package/dist/migrations/activation.d.ts +0 -17
- package/dist/migrations/activation.js +0 -2
- package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
- package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
- package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
- package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
- package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
- package/packages/crouter-api/dist/core/locked-file.js +0 -121
- package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
- package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
- package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
- package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
- package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
- package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
- package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
- package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
- package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
- package/packages/crouter-api/dist/migrations/activation.js +0 -46
|
@@ -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};
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
/** Frozen copy of the history record shape the retired store-file history wrote. */
|
|
2
|
-
export interface LegacyHistoryRecord {
|
|
3
|
-
op: 'create' | 'edit' | 'delete' | 'move';
|
|
4
|
-
at: string;
|
|
5
|
-
node?: string;
|
|
6
|
-
cwd: string;
|
|
7
|
-
from?: string;
|
|
8
|
-
rationale?: string;
|
|
9
|
-
verbatim?: boolean;
|
|
10
|
-
before: string;
|
|
11
|
-
after: string;
|
|
12
|
-
}
|
|
13
|
-
export interface LegacyProfile {
|
|
14
|
-
id: string;
|
|
15
|
-
name: string;
|
|
16
|
-
/** The owning app (`grantee`), `app:terminal` for older manifests without one. */
|
|
17
|
-
app: string;
|
|
18
|
-
/** The profile's store (`<app space>/profiles/<id>`), resolved by the caller. */
|
|
19
|
-
memory: string;
|
|
20
|
-
/** Every `projects[].path` in the manifest. */
|
|
21
|
-
projects: string[];
|
|
22
|
-
/** The manifest as parsed JSON, for fields the plan converts (`projects[].memory`). */
|
|
23
|
-
raw?: Record<string, unknown>;
|
|
24
|
-
manifestPath?: string;
|
|
25
|
-
}
|
|
26
|
-
export interface LegacyRoots {
|
|
27
|
-
userMemory: string;
|
|
28
|
-
profiles: LegacyProfile[];
|
|
29
|
-
nodeCwds: string[];
|
|
30
|
-
/** Node rows that exist in canvas.db and their folders (`<nodes>/<id>`). */
|
|
31
|
-
nodes: Array<{
|
|
32
|
-
id: string;
|
|
33
|
-
dir: string;
|
|
34
|
-
}>;
|
|
35
|
-
}
|
|
36
|
-
export type LegacyOwnerRef = {
|
|
37
|
-
type: 'person';
|
|
38
|
-
} | {
|
|
39
|
-
type: 'profile';
|
|
40
|
-
id: string;
|
|
41
|
-
} | {
|
|
42
|
-
type: 'repo';
|
|
43
|
-
root: string;
|
|
44
|
-
commonDir: string | null;
|
|
45
|
-
namespace: string | null;
|
|
46
|
-
} | {
|
|
47
|
-
type: 'node';
|
|
48
|
-
id: string;
|
|
49
|
-
};
|
|
50
|
-
export interface LegacyDoc {
|
|
51
|
-
path: string;
|
|
52
|
-
owner: LegacyOwnerRef;
|
|
53
|
-
/** The document name under its owner (INDEX folding, nested prefix, `reports/<stem>`, root `INDEX.md` → `index`). */
|
|
54
|
-
name: string;
|
|
55
|
-
source: 'store' | 'context' | 'report';
|
|
56
|
-
frontmatter: Record<string, unknown> | null;
|
|
57
|
-
body: string;
|
|
58
|
-
mtime: string;
|
|
59
|
-
/** Records of the file's current life (after its last `delete`), in file order; store documents only. */
|
|
60
|
-
history: LegacyHistoryRecord[];
|
|
61
|
-
/** Set when the file could not be read as written: `invalid-source` (unparseable
|
|
62
|
-
* frontmatter; `body` is the whole file and `frontmatter` null) or `invalid-history`
|
|
63
|
-
* (its history log is unreadable; `history` is empty). */
|
|
64
|
-
invalid?: {
|
|
65
|
-
kind: 'invalid-source' | 'invalid-history';
|
|
66
|
-
reason: string;
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
export interface LegacyStoreRoot {
|
|
70
|
-
root: string;
|
|
71
|
-
owner: LegacyOwnerRef;
|
|
72
|
-
docs: number;
|
|
73
|
-
skipped?: 'duplicate-worktree';
|
|
74
|
-
}
|
|
75
|
-
export interface LegacyCorpus {
|
|
76
|
-
docs: LegacyDoc[];
|
|
77
|
-
storeRoots: LegacyStoreRoot[];
|
|
78
|
-
/** Files or roots not read, with the reason; informational. */
|
|
79
|
-
skipped: Array<{
|
|
80
|
-
path: string;
|
|
81
|
-
reason: string;
|
|
82
|
-
}>;
|
|
83
|
-
/** History logs whose document file no longer exists. */
|
|
84
|
-
orphanHistory: number;
|
|
85
|
-
/** Folders beside the given node folders with no node row. */
|
|
86
|
-
orphanNodeDirs: number;
|
|
87
|
-
/** Non-markdown files under node `context/` and `reports/` folders (not imported). */
|
|
88
|
-
nonMarkdown: number;
|
|
89
|
-
/** `injected-docs.json` ledgers found in node folders (not imported; the roll ends their sessions). */
|
|
90
|
-
injectedDocs: number;
|
|
91
|
-
}
|
|
File without changes
|
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import { type CheckoutIdentity } from '../../core/graph/repo-sync/identity.js';
|
|
2
|
-
import type { Privacy, RuleSpec } from '../../core/graph/types.js';
|
|
3
|
-
import { type DocumentKind } from './fields.js';
|
|
4
|
-
import type { LegacyCorpus, LegacyRoots } from './legacy/types.js';
|
|
5
|
-
/** The store migrations every plan assumes already ran (the previous release's lanes). */
|
|
6
|
-
export declare const CONVERGED_MARKER_IDS: readonly ["001-surfaces-frontmatter", "002-profile-project-memory", "003-repository-root-memory-identity"];
|
|
7
|
-
export type OwnerType = 'person' | 'app' | 'profile' | 'repo' | 'node';
|
|
8
|
-
export interface PlannedOwner {
|
|
9
|
-
/** Stable key documents point at: `person`, `app:<handle>`, `profile:<id>`, `repo:<externalId>`, `node:<id>`. */
|
|
10
|
-
key: string;
|
|
11
|
-
type: OwnerType;
|
|
12
|
-
handle: string;
|
|
13
|
-
/** Repo identity (`ensureRepo`). */
|
|
14
|
-
scheme?: 'git' | 'local-path';
|
|
15
|
-
externalId?: string;
|
|
16
|
-
/** A profile's owning app, as an owner key (`app:<handle>`). */
|
|
17
|
-
ownerKey?: string;
|
|
18
|
-
}
|
|
19
|
-
export interface PlannedRevision {
|
|
20
|
-
body: string;
|
|
21
|
-
authorNodeId: string | null;
|
|
22
|
-
rationale: string | null;
|
|
23
|
-
createdAt: string;
|
|
24
|
-
}
|
|
25
|
-
export interface PlannedDocument {
|
|
26
|
-
ownerKey: string;
|
|
27
|
-
name: string;
|
|
28
|
-
kind: DocumentKind;
|
|
29
|
-
privacy: Privacy;
|
|
30
|
-
preview: string;
|
|
31
|
-
summary: string | null;
|
|
32
|
-
whyItExists: string | null;
|
|
33
|
-
unlisted: boolean;
|
|
34
|
-
lintIgnore: unknown;
|
|
35
|
-
extensions: unknown;
|
|
36
|
-
rules: RuleSpec[];
|
|
37
|
-
/** Oldest first; the last one is the head, whose body carries the pointer rewrite. */
|
|
38
|
-
revisions: PlannedRevision[];
|
|
39
|
-
sourcePath: string;
|
|
40
|
-
}
|
|
41
|
-
/** A stored-profile update (scoped-state `profiles.delivery_limits_json`): the legacy
|
|
42
|
-
* profile.json `projects[].memory` caps, keyed by repo handle, merged over the row's limits. */
|
|
43
|
-
export interface PlannedProfileLimits {
|
|
44
|
-
profileId: string;
|
|
45
|
-
deliveryLimits: Record<string, string>;
|
|
46
|
-
}
|
|
47
|
-
/** Something that stops the import. Only a runtime that skipped the previous
|
|
48
|
-
* release's store migrations blocks; every other finding resolves itself. */
|
|
49
|
-
export interface ImportBlocker {
|
|
50
|
-
kind: 'marker';
|
|
51
|
-
message: string;
|
|
52
|
-
paths: string[];
|
|
53
|
-
}
|
|
54
|
-
/** One finding the plan resolved on its own, with what it did. */
|
|
55
|
-
export interface ImportResolution {
|
|
56
|
-
kind: 'invalid-source' | 'invalid-history' | 'name-clash' | 'repo-handle' | 'profile-handle' | 'repo-identity' | 'delivery-limit' | 'empty-preview';
|
|
57
|
-
message: string;
|
|
58
|
-
paths: string[];
|
|
59
|
-
}
|
|
60
|
-
export interface ImportReport {
|
|
61
|
-
stores: LegacyCorpus['storeRoots'];
|
|
62
|
-
counts: Record<string, number>;
|
|
63
|
-
rewrites: Array<{
|
|
64
|
-
path: string;
|
|
65
|
-
from: string;
|
|
66
|
-
to: string;
|
|
67
|
-
}>;
|
|
68
|
-
droppedFields: Array<{
|
|
69
|
-
path: string;
|
|
70
|
-
field: string;
|
|
71
|
-
}>;
|
|
72
|
-
skipped: LegacyCorpus['skipped'];
|
|
73
|
-
/** Every clash or unreadable source the plan resolved, one line each. */
|
|
74
|
-
resolutions: ImportResolution[];
|
|
75
|
-
}
|
|
76
|
-
export interface ImportPlan {
|
|
77
|
-
owners: PlannedOwner[];
|
|
78
|
-
documents: PlannedDocument[];
|
|
79
|
-
profileLimits: PlannedProfileLimits[];
|
|
80
|
-
blockers: ImportBlocker[];
|
|
81
|
-
report: ImportReport;
|
|
82
|
-
}
|
|
83
|
-
export interface PlanContext {
|
|
84
|
-
roots: LegacyRoots;
|
|
85
|
-
/** Ids in `on-disk-migrations.json`, or null when it is absent. */
|
|
86
|
-
markerIds: string[] | null;
|
|
87
|
-
/** Repo identity of a git checkout root (repo-sync `identifyCheckout`). */
|
|
88
|
-
repoIdentity: (root: string) => CheckoutIdentity;
|
|
89
|
-
/** Owner objects already in canvas.db; a new handle must not take one of theirs. */
|
|
90
|
-
existingOwners: Array<{
|
|
91
|
-
type: string;
|
|
92
|
-
handle: string;
|
|
93
|
-
externalId: string | null;
|
|
94
|
-
}>;
|
|
95
|
-
/** Stored profile rows (scoped-state) with their current `delivery_limits`. */
|
|
96
|
-
storedProfiles: Array<{
|
|
97
|
-
id: string;
|
|
98
|
-
deliveryLimits: Record<string, string>;
|
|
99
|
-
}>;
|
|
100
|
-
home?: string;
|
|
101
|
-
}
|
|
102
|
-
export declare function planImport(corpus: LegacyCorpus, ctx: PlanContext): ImportPlan;
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var ae=Object.defineProperty;var c=(o,a)=>ae(o,"name",{value:a,configurable:!0});import{realpathSync as de}from"node:fs";import{homedir as pe}from"node:os";import{isAbsolute as le,join as ce,relative as fe}from"node:path";import{parseFrontmatterGeneric as he}from"../../core/frontmatter.js";import{handleHint as me}from"../../core/graph/repo-sync/identity.js";import{andIntoRules as ue,documentFields as ye}from"./fields.js";import{rewritePointers as we}from"./pointers.js";const $e=["001-surfaces-frontmatter","002-profile-project-memory","003-repository-root-memory-identity"],U=["none","name","preview","content"];function O(o){try{return de(o)}catch{return o}}c(O,"real");const X=c(o=>o.replace(/^app:/,""),"appHandle");function Re(o,a){const v=[],m={},d=c((e,n=1)=>{m[e]=(m[e]??0)+n},"count"),p=[],u=[],g=[],l=c(e=>{g.push(e),d(`resolutions.${e.kind}`)},"resolve");o.docs.length>0&&[...a.markerIds??[]].sort().join(`
|
|
2
|
-
`)!==[...$e].sort().join(`
|
|
3
|
-
`)&&v.push({kind:"marker",paths:[],message:`this runtime skipped the store migrations of the previous release (on-disk-migrations.json lists ${a.markerIds===null?"nothing":JSON.stringify(a.markerIds)}); start the previous crtr release once, then upgrade`});for(const e of o.docs)e.invalid!==void 0&&l({kind:e.invalid.kind,paths:[e.path],message:e.invalid.kind==="invalid-source"?`${e.path}: ${e.invalid.reason} \u2014 imported the whole file as the body, with no rules`:`${e.path}: ${e.invalid.reason} \u2014 imported the current file without its history`});const k=new Map,G=new Map,x=c((e,n)=>G.get(`${e}\0${n}`),"held"),S=c((e,n,t)=>{G.set(`${e}\0${n}`,t)},"hold"),Y=c(e=>e.type==="repo"&&e.externalId!==null?`repo:${e.externalId}`:e.type==="person"?"person":e.type==="profile"&&e.externalId!==null?`profile:${e.externalId}`:`${e.type}:${e.handle}`,"keyOfExisting");for(const e of a.existingOwners)S(e.type,e.handle,Y(e));const W=c((e,n)=>{let t=2;for(;x(e,`${n}-${t}`)!==void 0;)t+=1;return`${n}-${t}`},"freeHandle"),M=c(e=>{const n=k.get(e.key);if(n!==void 0)return n;const t=x(e.type,e.handle),r=t!==void 0&&t!==e.key?W(e.type,e.handle):e.handle,s={...e,handle:r};return S(s.type,r,s.key),k.set(s.key,s),s},"claim");for(const e of a.existingOwners)e.type==="person"&&k.set("person",{key:"person",type:"person",handle:e.handle});const z=M({key:"person",type:"person",handle:"user"}),Z=new Map(a.roots.profiles.map(e=>[e.id,e])),ee=new Set(a.roots.nodes.map(e=>e.id)),te=new Map(a.roots.nodes.map(e=>[e.id,e.dir])),C=new Map;for(const e of[...a.roots.profiles].sort((n,t)=>n.id.localeCompare(t.id))){const n=x("profile",e.name);if(n===void 0||n===`profile:${e.id}`){C.set(e.id,e.name),S("profile",e.name,`profile:${e.id}`);continue}const t=x("profile",e.id)===void 0?e.id:W("profile",e.id);C.set(e.id,t),S("profile",t,`profile:${e.id}`),l({kind:"profile-handle",paths:e.manifestPath===void 0?[]:[e.manifestPath],message:`profile ${e.id} shares the name \`${e.name}\` with ${n}; it takes the handle \`${t}\``})}const N=new Map,E=new Map,B=c((e,n)=>{if(E.has(e.root))return;const t=e.commonDir===null?{ok:!1,code:"not-a-repo",dir:e.root,reason:"no .git"}:a.repoIdentity(e.root);let r="local-path",s=O(e.root),i=me(s);t.ok?(r=t.scheme,s=t.externalId,i=t.handleHint):t.code!=="not-a-repo"&&l({kind:"repo-identity",paths:n,message:`${e.root}: repo identity lookup failed (${t.code}: ${t.reason}); imported as the local-path repo ${s}`});const f=`repo:${s}`;E.set(e.root,f);const h=a.existingOwners.find(y=>y.type==="repo"&&y.externalId===s),w=N.get(f);w!==void 0?w.roots.push(e.root):N.set(f,{key:f,scheme:r,externalId:s,wanted:h?.handle??e.namespace??i,roots:[e.root]})},"identify");for(const e of o.storeRoots)e.owner.type==="repo"&&e.skipped===void 0&&B(e.owner,[e.root]);for(const e of o.docs)e.owner.type==="repo"&&B(e.owner,[e.path]);const J=new Map,K=new Map;for(const e of N.values())K.set(e.wanted,[...K.get(e.wanted)??[],e]);for(const[e,n]of[...K].sort(([t],[r])=>t.localeCompare(r))){const t=c(r=>x("repo",e)===r.key?0:r.scheme==="git"?1:2,"rank");n.sort((r,s)=>t(r)-t(s)||r.externalId.localeCompare(s.externalId));for(const r of n){const s=M({key:r.key,type:"repo",handle:e,scheme:r.scheme,externalId:r.externalId});s.handle!==e&&(J.set(r.key,{from:e,to:s.handle}),l({kind:"repo-handle",paths:r.roots,message:`repo ${r.externalId} (${r.roots.join(", ")}) wanted the handle \`${e}\`, held by ${x("repo",e)}; it takes \`${s.handle}\` and its documents' \`[[${e}/\u2026]]\` links are rewritten to match`}))}}const P=new Map;for(const[e,n]of E)P.set(e,k.get(n));const ne=c(e=>P.get(e.root),"repoOwner"),oe=c(e=>{const n=Z.get(e),t=M({key:`app:${X(n?.app??"app:terminal")}`,type:"app",handle:X(n?.app??"app:terminal")});return M({key:`profile:${e}`,type:"profile",handle:C.get(e)??n?.name??e,ownerKey:t.key})},"profileOwner"),re=c(e=>{switch(e.owner.type){case"person":return z;case"profile":return oe(e.owner.id);case"repo":return ne(e.owner);case"node":return M({key:`node:${e.owner.id}`,type:"node",handle:e.owner.id})}},"ownerFor"),R=new Map;for(const e of o.docs)e.owner.type==="repo"&&e.mtime>(R.get(e.owner.root)??"")&&R.set(e.owner.root,e.mtime);const D=new Map;for(const[e,n]of P){const t=D.get(n.key);(t===void 0||(R.get(e)??"")>(R.get(t)??""))&&D.set(n.key,e)}const A=[...o.skipped],T=new Set,H=[],j=new Map;for(const e of o.docs){const n=re(e);if(e.owner.type==="repo"&&D.get(n.key)!==e.owner.root){T.has(e.owner.root)||(T.add(e.owner.root),A.push({path:e.owner.root,reason:`duplicate-clone: ${n.handle} imports from ${D.get(n.key)}`})),d("documents.duplicate-clone");continue}let t=n.key,r=e.name;const s=e.source==="report",i=ye(e.invalid?.kind==="invalid-source"?null:e.frontmatter,e.body,{...s?{kind:"report"}:{},missingPrivacy:n.type==="repo"?"public":"private"});for(const $ of i.dropped)p.push({path:e.path,field:$});let f=i.rules,h=i.preview;e.source==="context"&&r==="roadmap"&&(f=[...f,{on:"boot",deliver:"content"}],h=h||`The roadmap of node ${n.handle}`),h.trim()===""&&(h=e.name,l({kind:"empty-preview",paths:[e.path],message:`${e.path} has no text to preview; its preview is its name, ${e.name}`})),n.type==="repo"&&i.privacy!=="public"&&(f=ue(f,{repo:n.handle}),t=z.key,r=`${n.handle}/${r}`,d("documents.private-repo-to-person"));const w=ke(e,ee,l),y=k.get(t).handle,b={doc:e,qualified:`${y}/${r}`,contextDir:e.owner.type==="node"?ce(te.get(e.owner.id)??"","context"):null,repoKey:e.owner.type==="repo"?n.key:null,planned:{ownerKey:t,name:r,kind:i.kind,privacy:i.privacy,preview:h,summary:i.summary,whyItExists:i.whyItExists,unlisted:i.unlisted,lintIgnore:i.lintIgnore,extensions:i.extensions,rules:f,revisions:w,sourcePath:e.path}},_=`${t}\0${r}`,I=j.get(_);if(I!==void 0){const $=I.doc.mtime<=e.mtime?I:b;let L=1;for(;j.has(`${t}\0${r}.conflict-${L}`);)L+=1;$.planned.name=`${r}.conflict-${L}`,$.qualified=`${y}/${$.planned.name}`,j.set(`${t}\0${$.planned.name}`,$),j.set(_,$===I?b:I),l({kind:"name-clash",paths:[I.doc.path,e.path],message:`${I.doc.path} and ${e.path} both import as \`${y}/${r}\`; the newer keeps the name and ${$.doc.path} imports as \`${$.planned.name}\``})}else j.set(_,b);H.push(b),d(`documents.${i.kind}`),d(`documents.owner.${k.get(t).type}`),d("revisions",w.length)}const q=new Map,V=new Set,Q=new Set;for(const e of H){q.set(e.doc.path,e.qualified),q.set(O(e.doc.path),e.qualified),e.doc.source==="report"&&V.add(e.qualified);const n=k.get(e.planned.ownerKey);e.planned.name==="index"&&n.type!=="node"&&Q.add(n.handle)}const ie={byPath:q,reports:V,indexHandles:Q,home:a.home??pe(),real:O};for(const e of H){const n=e.planned.revisions[e.planned.revisions.length-1],t=we(n.body,ie,{contextDir:e.contextDir}),r=e.repoKey===null?void 0:J.get(e.repoKey);if(r!==void 0){const s=`[[${r.from}/`,i=`[[${r.to}/`;t.body.includes(s)&&(t.body=t.body.split(s).join(i),t.rewrites.push({from:s,to:i}))}if(t.rewrites.length!==0){n.body=t.body;for(const s of t.rewrites)u.push({path:e.doc.path,...s});d("documents.rewritten")}}const F=[],se=new Map(a.storedProfiles.map(e=>[e.id,e.deliveryLimits]));for(const e of a.roots.profiles){if(e.raw===void 0||e.manifestPath===void 0)continue;const n=Array.isArray(e.raw.projects)?e.raw.projects:[];if(!n.some(i=>i!==null&&typeof i=="object"&&"memory"in i))continue;const t=se.get(e.id);if(t===void 0){A.push({path:e.manifestPath,reason:`profile-not-stored: profile ${e.id} has a manifest but no stored profile row; its memory caps are not carried over`});continue}const r={...t},s=new Map;n.forEach(i=>{if(i===null||typeof i!="object"||!("memory"in i))return i;const{memory:f,...h}=i;if(f==="content"||typeof h.path!="string")return h;const w=ge(h.path,a,P);if(w===null)return A.push({path:e.manifestPath,reason:`delivery-limit-dropped: project ${h.path} (memory ${String(f)}) is in no repo and has no project store`}),h;const y=r[w];if(y!==void 0&&y!==f){const b=U.indexOf(String(f))>U.indexOf(y)?String(f):y;if(l({kind:"delivery-limit",paths:[e.manifestPath],message:`profile ${e.name}: ${s.get(w)??"delivery_limits"} and ${h.path} both map to repo \`${w}\` with different memory caps (${y}, ${String(f)}); kept the larger, ${b}`}),b===y)return h}return r[w]=String(f),s.set(w,h.path),h}),Object.keys(r).some(i=>r[i]!==t[i])&&F.push({profileId:e.id,deliveryLimits:r})}return d("profile-limits",F.length),m.stores=o.storeRoots.filter(e=>e.skipped===void 0).length,m["stores.duplicate-worktree"]=o.storeRoots.filter(e=>e.skipped!==void 0).length,m.owners=k.size,m["orphan-history"]=o.orphanHistory,m["orphan-node-dirs"]=o.orphanNodeDirs,m["non-markdown"]=o.nonMarkdown,m["exposure-ledgers-not-imported"]=o.injectedDocs,{owners:[...k.values()],documents:H.map(e=>e.planned),profileLimits:F,blockers:v,report:{stores:o.storeRoots,counts:m,rewrites:u,droppedFields:p,skipped:A,resolutions:g}}}c(Re,"planImport");function ge(o,a,v){const m=O(o);let d=null;for(const[u,g]of v){const l=fe(O(u),m);(l===""||!l.startsWith("..")&&!le(l))&&(d===null||u.length>d.root.length)&&(d={root:u,owner:g})}const p=a.repoIdentity(m);if(p.ok){const u=[...v.values()].find(l=>l.externalId===p.externalId);return u?u.handle:a.existingOwners.find(l=>l.type==="repo"&&l.externalId===p.externalId)?.handle??p.handleHint}return d?.owner.handle??null}c(ge,"projectHandle");function ke(o,a,v){const m=c(p=>typeof p=="string"&&a.has(p)?p:null,"author");if(o.source!=="store")return[{body:o.body,authorNodeId:o.owner.type==="node"&&a.has(o.owner.id)?o.owner.id:null,rationale:null,createdAt:o.mtime}];const d=[];for(const p of o.history){if(p.op!=="create"&&p.op!=="edit"&&p.op!=="move")continue;let u;try{u=he(p.after).body}catch(g){return v({kind:"invalid-history",paths:[o.path],message:`${o.path}: history record at ${p.at} has invalid frontmatter (${g.message}); imported the current file without its history`}),[{body:o.body,authorNodeId:null,rationale:null,createdAt:o.mtime}]}d.length>0&&d[d.length-1].body===u||d.push({body:u,authorNodeId:m(p.node),rationale:p.rationale??null,createdAt:p.at})}if(d.length===0){const p=o.frontmatter?.origin??{},u=c(l=>typeof l=="string"?l:l instanceof Date?l.toISOString():null,"stamp"),g=u(p.created)??u(o.frontmatter?.["last-updated"])??o.mtime;return[{body:o.body,authorNodeId:m(p.node),rationale:null,createdAt:g}]}return d[d.length-1].body!==o.body&&d.push({body:o.body,authorNodeId:null,rationale:"changed outside crtr before import",createdAt:o.mtime}),d}c(ke,"revisionsOf");export{$e as CONVERGED_MARKER_IDS,Re as planImport};
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
export interface PointerTargets {
|
|
2
|
-
/** Absolute file path (as read and realpath) → qualified document name. */
|
|
3
|
-
byPath: ReadonlyMap<string, string>;
|
|
4
|
-
/** `<node-id>/reports/<stem>` of every imported report. */
|
|
5
|
-
reports: ReadonlySet<string>;
|
|
6
|
-
/** Owner handles that have an imported `index` document. */
|
|
7
|
-
indexHandles: ReadonlySet<string>;
|
|
8
|
-
home: string;
|
|
9
|
-
/** Resolve symlinks of a path that is not in `byPath` as written; returns the input when it does not exist. */
|
|
10
|
-
real: (path: string) => string;
|
|
11
|
-
}
|
|
12
|
-
export interface PointerContext {
|
|
13
|
-
/** The node folder's `context/` dir when the document is owned by a node (for `$CRTR_CONTEXT_DIR/…`). */
|
|
14
|
-
contextDir: string | null;
|
|
15
|
-
}
|
|
16
|
-
/** Rewrite one head body; `rewrites` receives every replacement made. */
|
|
17
|
-
export declare function rewritePointers(body: string, t: PointerTargets, ctx: PointerContext): {
|
|
18
|
-
body: string;
|
|
19
|
-
rewrites: Array<{
|
|
20
|
-
from: string;
|
|
21
|
-
to: string;
|
|
22
|
-
}>;
|
|
23
|
-
};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var T=Object.defineProperty;var f=(s,t)=>T(s,"name",{value:t,configurable:!0});import{join as a}from"node:path";const _=/(?<![\w./$-])((?:~|\$CRTR_CONTEXT_DIR|\$\{CRTR_CONTEXT_DIR\})?\/[^\s()[\]<>`'"]*?\.md)(?![\w-]|\.[\w-])/g,m=/(?<![\w/-])([a-z0-9]+(?:-[a-z0-9]+)+):reports\/([A-Za-z0-9._-]+?)(?:\.md)?(?![\w-]|\.[\w-])/g,g=/\[\[([^\]|#/\s]+)((?:[|#][^\]]*)?)\]\]/g;function R(s,t,l){let r;if(s.startsWith("~/"))r=a(t.home,s.slice(2));else if(s.startsWith("$")){if(l.contextDir===null)return null;r=a(l.contextDir,s.slice(s.indexOf("/")+1))}else r=s;return t.byPath.get(r)??t.byPath.get(t.real(r))??null}f(R,"resolvePointer");function $(s,t,l){const r=`${s}/reports/${t}`;return l.reports.has(r)?r:null}f($,"resolveReport");function d(s,t,l,r){const c=f((e,n)=>n===null?e:(r.push({from:e,to:`[[${n}]]`}),`[[${n}]]`),"sub");return s.replace(_,(e,n)=>c(e,R(n,t,l))).replace(m,(e,n,u)=>c(e,$(n,u,t))).replace(g,(e,n,u)=>{if(!t.indexHandles.has(n))return e;const o=`[[${n}/index${u}]]`;return r.push({from:e,to:o}),o})}f(d,"rewriteText");function x(s,t,l,r,c){const e=t.trim(),n=/^([a-z0-9]+(?:-[a-z0-9]+)+):reports\/([A-Za-z0-9._-]+?)(?:\.md)?$/.exec(e),u=n!==null?$(n[1],n[2],l):/^(?:~|\$CRTR_CONTEXT_DIR|\$\{CRTR_CONTEXT_DIR\})?\/\S*\.md$/.test(e)?R(e,l,r):null;return u===null?s:(c.push({from:s,to:`[[${u}]]`}),`[[${u}]]`)}f(x,"rewriteCodeSpan");function D(s,t,l){const r=[],c=[];let e=null,n=[];const u=f(()=>{if(n.length===0)return;const o=n.join(`
|
|
2
|
-
`),i=[];let h=0;for(const p of o.matchAll(/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/g))i.push(d(o.slice(h,p.index),t,l,r)),i.push(x(p[0],p[2],t,l,r)),h=p.index+p[0].length;i.push(d(o.slice(h),t,l,r)),c.push(i.join("")),n=[]},"flush");for(const o of s.split(`
|
|
3
|
-
`)){const i=/^\s*(`{3,}|~{3,})/.exec(o)?.[1];e===null&&i!==void 0?(u(),e=i,c.push(o)):e!==null?(c.push(o),i!==void 0&&i[0]===e[0]&&i.length>=e.length&&o.trim()===i&&(e=null)):n.push(o)}return u(),{body:c.join(`
|
|
4
|
-
`),rewrites:r}}f(D,"rewritePointers");export{D as rewritePointers};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { type CanvasImportResult } from './004-canvas-documents/index.js';
|
|
2
|
-
export type { CanvasImportResult } from './004-canvas-documents/index.js';
|
|
3
|
-
/** A migration blocker is a STANDING condition, not a transient fault: the same
|
|
4
|
-
* stores produce the same blockers on every boot, so a caller that retries a
|
|
5
|
-
* daemon start against one retries forever. Typing it lets the startup path
|
|
6
|
-
* tell "try again" apart from "this needs a human", and carry the repair line
|
|
7
|
-
* to whoever can act on it. */
|
|
8
|
-
export declare class MigrationBlockedError extends Error {
|
|
9
|
-
readonly blockerPaths: readonly string[];
|
|
10
|
-
constructor(message: string, blockerPaths: readonly string[]);
|
|
11
|
-
}
|
|
12
|
-
/** Startup: import the legacy stores unless already recorded. Throws `MigrationBlockedError` when the plan has blockers. */
|
|
13
|
-
export declare function activateCanvasImport(): Promise<CanvasImportResult | null>;
|
|
14
|
-
/** `crtr sys migrate`: plan (and unless `dryRun`, apply) regardless of startup state. */
|
|
15
|
-
export declare function runForcedCanvasImport(opts: {
|
|
16
|
-
dryRun: boolean;
|
|
17
|
-
}): Promise<CanvasImportResult>;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var s=Object.defineProperty;var o=(r,t)=>s(r,"name",{value:t,configurable:!0});import{mkdirSync as c}from"node:fs";import{dirname as m}from"node:path";import{onDiskMigrationLockPath as u}from"../core/canvas/paths.js";import{withExclusiveDirectoryLockAsync as p}from"../core/exclusive-lock.js";import{DAEMON_STARTUP_WINDOW_MS as l}from"../daemon/startup-policy.js";import{canvasImportDone as h,runCanvasImport as e}from"./004-canvas-documents/index.js";class d extends Error{static{o(this,"MigrationBlockedError")}blockerPaths;constructor(t,n){super(t),this.name="MigrationBlockedError",this.blockerPaths=n}}function i(r){const t=u();return c(m(t),{recursive:!0,mode:448}),p(t,async()=>r(),{timeoutMs:l,timeoutError:o(()=>new Error(`timed out waiting for the canvas import lock: ${t}`),"timeoutError")})}o(i,"coordinate");async function E(){return await i(async()=>{if(await h())return null;const r=await e({dryRun:!1});if(r.blockers.length>0){const t=[...new Set(r.blockers.flatMap(a=>a.paths))],n=[`canvas import (004-canvas-documents) blocked by ${r.blockers.length} finding(s)`,...r.blockers.map(a=>`${a.kind}: ${a.message}`)];throw n.push("Repair each finding, then: crtr sys migrate --dry-run, then crtr sys migrate"),new d(n.join(`
|
|
2
|
-
`),t)}return r})}o(E,"activateCanvasImport");async function M(r){return await i(async()=>await e(r))}o(M,"runForcedCanvasImport");export{d as MigrationBlockedError,E as activateCanvasImport,M as runForcedCanvasImport};
|