wyrm-mcp 9.5.1 → 9.5.3

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.
@@ -1,22 +1,11 @@
1
- import{existsSync as l,readFileSync as h,writeFileSync as p,mkdirSync as b,chmodSync as J}from"fs";import{homedir as v,platform as k}from"os";import{join as a,dirname as w,resolve as de}from"path";import{fileURLToPath as j}from"url";import{spawnSync as P}from"child_process";import{npmGlobalPrefixFromPath as fe}from"./cli.js";import{syncWyrmHookFiles as le,describeHookSync as me,WYRM_HOOK_SUPPORT_FILES as he}from"./hook-refresh.js";function pe(){const e=v(),t=k(),n=t==="darwin"?a(e,"Library","Application Support","Code","User"):t==="win32"?a(e,"AppData","Roaming","Code","User"):a(e,".config","Code","User"),o=t==="darwin"?a(e,"Library","Application Support","Code - Insiders","User"):t==="win32"?a(e,"AppData","Roaming","Code - Insiders","User"):a(e,".config","Code - Insiders","User"),s=t==="darwin"?a(e,"Library","Application Support","Claude"):t==="win32"?a(e,"AppData","Roaming","Claude"):a(e,".config","claude"),r=t==="darwin"?a(e,".cursor"):t==="win32"?a(e,".cursor"):a(e,".cursor"),i=t==="darwin"?a(e,".codeium","windsurf"):t==="win32"?a(e,".codeium","windsurf"):a(e,".codeium","windsurf"),c=t==="darwin"?a(e,".config","zed"):t==="win32"?a(e,"AppData","Roaming","Zed"):a(e,".config","zed"),d=a(e,".continue");return[{id:"vscode-copilot",name:"VS Code (Copilot)",icon:"\u{1F4BB}",configPath:a(n,"settings.json"),configFormat:"vscode",mcpKey:"mcp.servers",detected:!1,configured:!1},{id:"vscode-insiders",name:"VS Code Insiders",icon:"\u{1F7E2}",configPath:a(o,"settings.json"),configFormat:"vscode",mcpKey:"mcp.servers",detected:!1,configured:!1},{id:"claude-desktop",name:"Claude Desktop",icon:"\u{1F916}",configPath:a(s,"claude_desktop_config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"claude-code",name:"Claude Code",icon:"\u2733\uFE0F",configPath:a(e,".claude.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"cursor",name:"Cursor",icon:"\u{1F4D0}",configPath:a(r,"mcp.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"windsurf",name:"Windsurf",icon:"\u{1F3C4}",configPath:a(i,"mcp_config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"zed",name:"Zed",icon:"\u26A1",configPath:a(c,"settings.json"),configFormat:"zed",mcpKey:"context_servers",detected:!1,configured:!1},{id:"continue",name:"Continue",icon:"\u{1F504}",configPath:a(d,"config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1}]}function ge(e){try{const t=k()==="win32"?"where":"which",n=P(t,[e],{encoding:"utf-8",timeout:5e3});return n.status===0&&!!n.stdout&&n.stdout.trim().length>0}catch{return!1}}function _(){const e=pe();for(const t of e){if(t.id==="claude-code")t.detected=l(a(w(t.configPath),".claude"))||ge("claude");else{const n=w(t.configPath);t.detected=l(n)}if(t.detected&&l(t.configPath))try{const n=h(t.configPath,"utf-8"),o=W(n);t.configured=ve(o,t)}catch{t.configured=!1}t.detected&&(t.version=ye(t))}return e}function ye(e){try{switch(e.id){case"vscode-copilot":case"vscode-insiders":{const t=e.id==="vscode-insiders"?"code-insiders":"code",n=P(t,["--version"],{encoding:"utf-8",timeout:5e3});if(n.stdout)return n.stdout.split(`
2
- `)[0];break}case"cursor":{const t=P("cursor",["--version"],{encoding:"utf-8",timeout:5e3});if(t.stdout)return t.stdout.split(`
3
- `)[0];break}case"claude-code":{const t=P("claude",["--version"],{encoding:"utf-8",timeout:5e3});if(t.stdout)return t.stdout.trim().split(`
4
- `)[0];break}}}catch{}}function ve(e,t){switch(t.configFormat){case"vscode":return e.mcp?.servers?.wyrm!==void 0;case"mcp-json":return e[t.mcpKey]?.wyrm!==void 0;case"zed":return e[t.mcpKey]?.wyrm!==void 0;default:return!1}}function R(e=k()){if(e!=="win32"){try{const s=P("which",["wyrm-mcp"],{encoding:"utf-8",timeout:5e3});if(s.stdout?.trim())return s.stdout.trim()}catch{}try{const r=P("npm",["root","-g"],{encoding:"utf-8",timeout:5e3}).stdout?.trim();if(r){const i=a(r,"wyrm-mcp","dist","index.js");if(l(i))return i}}catch{}}const t=de(w(j(import.meta.url)),"index.js");if(l(t))return t;const n=a(v(),".wyrm","node_modules","wyrm-mcp","dist","index.js");if(l(n))return n;const o=[a(v(),"Git Projects","Wyrm","packages","mcp-server","dist","index.js"),a(v(),"projects","Wyrm","packages","mcp-server","dist","index.js"),a(v(),"dev","Wyrm","packages","mcp-server","dist","index.js")];for(const s of o)if(l(s))return s;return"wyrm-mcp"}function U(){return a(v(),".wyrm","wyrm.db")}function Ie(e="mcp-json",t){const n=t?.serverPath??R(),o=t?.dbPath??U(),s=n==="wyrm-mcp",r={command:s?"npx":"node",args:s?["wyrm-mcp"]:[n],env:{WYRM_DB_PATH:o}};switch(e){case"stdio":return r;case"vscode":return{mcp:{servers:{wyrm:r}}};default:return{mcpServers:{wyrm:r}}}}function we(e,t){const n=t.serverPath,o=n==="wyrm-mcp",s=n.endsWith(".js");switch(e.configFormat){case"vscode":return{command:o?"npx":"node",args:o?["wyrm-mcp"]:[n],env:{WYRM_DB_PATH:t.dbPath}};case"mcp-json":return{command:o?"npx":"node",args:o?["wyrm-mcp"]:[n],env:{WYRM_DB_PATH:t.dbPath}};case"zed":return{command:o?"npx":"node",args:o?["wyrm-mcp"]:[n],env:{WYRM_DB_PATH:t.dbPath}};default:return{}}}function ke(e,t){if(!e||typeof e!="object"||Array.isArray(e))return{entry:t,preservedLauncher:!1};const n=e,o=n.env&&typeof n.env=="object"&&!Array.isArray(n.env)?n.env:{},s=t.env&&typeof t.env=="object"&&!Array.isArray(t.env)?t.env:{};if(n.command===t.command&&JSON.stringify(n.args??null)===JSON.stringify(t.args??null))return{entry:{...t,env:{...s,...o}},preservedLauncher:!1};const i={...o};for(const[c,d]of Object.entries(s))c in i||(i[c]=d);return{entry:{...n,env:i},preservedLauncher:!0}}function V(e,t){if(!e.detected)return{client:e,action:"skipped",message:`${e.name} not detected`};try{const n=w(e.configPath);l(n)||b(n,{recursive:!0});let o={},s=!1;if(l(e.configPath))try{const u=h(e.configPath,"utf-8");o=W(u),s=!0}catch{o={}}let r;if(s){r=`${e.configPath}.wyrm-backup`,p(r,h(e.configPath),{mode:384});try{J(r,384)}catch{}}const i=we(e,t);let c=!1;const d=(u,m)=>{const g=ke(u.wyrm,m);return u.wyrm=g.entry,g.preservedLauncher};switch(e.configFormat){case"vscode":{o.mcp||(o.mcp={});const u=o.mcp;u.servers||(u.servers={});const m=u.servers;c=d(m,i)||c;break}case"mcp-json":{o[e.mcpKey]||(o[e.mcpKey]={});const u=o[e.mcpKey];c=d(u,i)||c;break}case"zed":{o[e.mcpKey]||(o[e.mcpKey]={});const u=o[e.mcpKey];c=d(u,i)||c;break}}p(e.configPath,JSON.stringify(o,null,2)+`
5
- `,"utf-8");const f=e.configured?"updated":"configured";return e.configured=!0,{client:e,action:f,message:`${e.name} ${f==="configured"?"configured":"updated"} successfully`+(c?" (kept your custom launch command; only missing env was added)":""),backup:r}}catch(n){return{client:e,action:"failed",message:`Failed to configure ${e.name}: ${n}`}}}function Fe(e,t){try{if(!l(e.configPath))return{client:e,action:"skipped",message:"No config file"};const n=h(e.configPath,"utf-8");let o;try{o=W(n)}catch{return{client:e,action:"failed",message:"Config file is not valid JSON; refusing to touch it"}}const r=(e.configFormat==="vscode"?o.mcp?.servers:o[e.mcpKey])?.wyrm;if(!r)return{client:e,action:"skipped",message:"Wyrm not configured in this client"};const i=`${e.configPath}.wyrm-backup`;p(i,n,{encoding:"utf-8",mode:384});try{J(i,384)}catch{}return r.env={...r.env,...t},p(e.configPath,JSON.stringify(o,null,2)+`
6
- `,"utf-8"),{client:e,action:"updated",message:`env: ${Object.keys(t).join(", ")}`,backup:i}}catch(n){return{client:e,action:"failed",message:String(n)}}}function Pe(e){if(!e.detected||!e.configured)return{client:e,action:"skipped",message:`${e.name} not configured`};try{if(!l(e.configPath))return{client:e,action:"skipped",message:`${e.name} config not found`};const t=h(e.configPath,"utf-8"),n=W(t),o=`${e.configPath}.wyrm-backup`;p(o,t,{mode:384});try{J(o,384)}catch{}switch(e.configFormat){case"vscode":{const r=n.mcp?.servers;r&&delete r.wyrm;break}case"mcp-json":case"zed":{const s=n[e.mcpKey];s&&delete s.wyrm;break}}return p(e.configPath,JSON.stringify(n,null,2)+`
7
- `,"utf-8"),e.configured=!1,{client:e,action:"configured",message:`Removed Wyrm from ${e.name}`,backup:o}}catch(t){return{client:e,action:"failed",message:`Failed to remove from ${e.name}: ${t}`}}}function N(){return{id:"claude-code-hooks",name:"Claude Code (auto-memory)",icon:"\u{1FA9D}",configPath:a(v(),".claude","settings.json"),configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}const A=[{script:"wyrm-session-capture.mjs",events:["SessionEnd","PreCompact"]},{script:"wyrm-session-rehydrate.mjs",events:["SessionStart"]},{script:"wyrm-session-prune.mjs",events:["SessionEnd"]},{script:"wyrm-tool-call-trace.mjs",events:["PostToolUse"]},{script:"wyrm-run-auto.mjs",events:["SessionStart",{event:"PreToolUse",matcher:"Task"},"SessionEnd"]},{script:"wyrm-citation-audit.mjs",events:["Stop"]},{script:"wyrm-prompt-context.mjs",events:["UserPromptSubmit"]}],He=A.map(e=>e.script),L=/[$`%"]/;function Q(e,t=k()){return t==="win32"?L.test(e)?null:`node ${$(e,t)}`:/^[\w@%+=:,./-]+$/.test(e)?`node ${e}`:`node ${$(e,t)}`}function Z(e,t=k()){return{current:Q(e,t),legacy:`node ${e}`}}function Se(e,t,n){if(t.current===null)return!1;const o=t.current;let s=!1,r=!1;for(let i=0;i<e.length;i++){const c=e[i];if(!Array.isArray(c.hooks))continue;const d=c.hooks.length;c.hooks=c.hooks.filter(f=>f.command!==o&&f.command!==t.legacy?!0:s?(r=!0,!1):(s=!0,f.command!==o&&(f.command=o,r=!0),!0)),d>0&&c.hooks.length===0&&(e.splice(i,1),i--)}if(!s){const i={type:"command",command:o,timeout:30};e.push(n?{matcher:n,hooks:[i]}:{hooks:[i]}),r=!0}return r}function be(e={}){const t=e.claudeDir??a(v(),".claude");if(!l(t))return null;const n=N();e.claudeDir&&(n.configPath=a(t,"settings.json"));try{const o=a(t,"hooks");l(o)||b(o,{recursive:!0});const s=w(j(import.meta.url)),r=a(s,"..","scripts","hooks"),i=n.configPath;let c={};if(l(i))try{c=JSON.parse(h(i,"utf-8"))}catch{c={}}const d=c.hooks??{},f=a(o,"wyrm-cli.json"),u=JSON.stringify({cli:a(s,"wyrm.js")},null,2)+`
8
- `;let m=!1;try{let y=!1;try{const C=JSON.parse(h(f,"utf-8"));y=typeof C.cli=="string"&&l(C.cli)}catch{}(fe(a(s,"wyrm.js"))!==null||!y)&&!(l(f)&&h(f,"utf-8")===u)&&(p(f,u,"utf-8"),m=!0)}catch{}let g=!1;const T=[];let x="0.0.0";try{x=JSON.parse(h(a(s,"..","package.json"),"utf-8")).version??x}catch{}const D=le({hooksDir:o,scriptsDir:r,version:x,installMissing:!0,replaceModified:/^(1|true|yes|on)$/i.test(process.env.WYRM_HOOKS_REPLACE_MODIFIED??""),files:[...he,...A.map(y=>y.script)]}),E=D.results.filter(y=>y.action==="missing-source").map(y=>y.file),G=D.results.some(y=>y.action==="installed"||y.action==="updated");for(const y of A){if(E.includes(y.script))continue;const Y=a(o,y.script),C=Z(Y);if(C.current===null){T.push(y.script);continue}for(const O of y.events){const M=typeof O=="string"?O:O.event,ue=typeof O=="string"?void 0:O.matcher,z=Array.isArray(d[M])?d[M]:[];Se(z,C,ue)&&(g=!0),d[M]=z}}if(c.hooks=d,p(i,JSON.stringify(c,null,2)+`
9
- `,"utf-8"),T.length===A.length-E.length&&T.length>0)return{client:n,action:"failed",message:`${o} contains a character ($, \`, % or ") that no quoting makes safe in every Windows shell, so the hooks were not wired.`};n.configured=!0;const q=me(D).filter(y=>!y.startsWith("refreshed ")),ce=(E.length?` (missing from package: ${E.join(", ")})`:"")+(q.length?`; ${q.join("; ")}`:"");return{client:n,action:g||m||G?"configured":"skipped",message:(g?"auto-memory hooks installed":G?"hook scripts refreshed":m?"hooks already installed; CLI location refreshed":"already installed")+ce}}catch(o){return{client:n,action:"failed",message:o instanceof Error?o.message:String(o)}}}function Be(){const e=a(v(),".claude");if(!l(e))return null;const t=N();try{const n=w(j(import.meta.url)),o=Q(a(n,"wyrm-statusline.js"));if(o===null)return{client:t,action:"failed",message:'the install path contains a character ($, `, % or ") that no quoting makes safe in every Windows shell, so the statusline was not set'};const s=t.configPath;let r={};if(l(s))try{r=JSON.parse(h(s,"utf-8"))}catch{r={}}const i=r.statusLine;if(i?.command&&!/wyrm-statusline/.test(i.command))return{client:t,action:"skipped",message:`a non-Wyrm statusLine is already set (${i.command}); not overwriting`};const c=i?.command===o;return r.statusLine={type:"command",command:o,padding:0},p(s,JSON.stringify(r,null,2)+`
10
- `,"utf-8"),{client:t,action:c?"skipped":"configured",message:c?"buddy statusline already installed":"Wyrm buddy statusline installed (persistent in the Claude Code TUI)"}}catch(n){return{client:t,action:"failed",message:n instanceof Error?n.message:String(n)}}}function Ge(){const e=a(v(),".claude","settings.json");if(!l(e))return null;const t=N();try{const n=JSON.parse(h(e,"utf-8")),o=n.statusLine;return o?.command&&/wyrm-statusline/.test(o.command)?(delete n.statusLine,p(e,JSON.stringify(n,null,2)+`
11
- `,"utf-8"),{client:t,action:"configured",message:"Wyrm statusline removed"}):{client:t,action:"skipped",message:"no Wyrm statusline set"}}catch(n){return{client:t,action:"failed",message:n instanceof Error?n.message:String(n)}}}function je(e={}){const t=e.claudeDir??a(v(),".claude"),n=a(t,"settings.json");if(!l(n))return null;const o=N();e.claudeDir&&(o.configPath=n);try{const s=JSON.parse(h(n,"utf-8")),r=a(t,"hooks"),i=new Set(A.flatMap(f=>{const u=Z(a(r,f.script));return u.current===null?[u.legacy]:[u.current,u.legacy]})),c=new Set(A.flatMap(f=>f.events.map(u=>typeof u=="string"?u:u.event))),d=s.hooks;if(d){for(const f of c)Array.isArray(d[f])&&(d[f]=d[f].map(u=>({...u,hooks:Array.isArray(u.hooks)?u.hooks.filter(m=>!i.has(m.command??"")):u.hooks})).filter(u=>!Array.isArray(u.hooks)||u.hooks.length>0),d[f].length===0&&delete d[f]);Object.keys(d).length===0&&delete s.hooks}return p(n,JSON.stringify(s,null,2)+`
12
- `,"utf-8"),{client:o,action:"configured",message:"auto-memory hooks removed"}}catch(s){return{client:o,action:"failed",message:s instanceof Error?s.message:String(s)}}}const X=/wyrm-guard/,ee=5,Ae=["Bash","Edit|Write|MultiEdit|NotebookEdit"];function S(e){return e.settingsPath??process.env.CLAUDE_SETTINGS??a(v(),".claude","settings.json")}function K(e){return{id:"claude-code-guard",name:"Claude Code (failure firewall)",icon:"\u{1F6E1}\uFE0F",configPath:e,configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}function $(e,t=k()){return t==="win32"?`"${e.replace(/\\/g,"/").replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function te(e=k()){const t=w(j(import.meta.url));return e==="win32"&&L.test(t)?`the install path (${t}) contains a character ($, \`, % or ") that no quoting makes safe in every Windows shell, so the hook was not installed`:null}function oe(e,t=k()){return t==="win32"&&L.test(e)?null:`node ${$(e,t)}`}function Ce(){const e=w(j(import.meta.url)),t=a(e,"wyrm-guard.js");if(l(t))return oe(t);try{const n=k()==="win32"?"where":"which",s=P(n,["wyrm-guard"],{encoding:"utf-8",timeout:5e3}).stdout?.trim().split(`
13
- `)[0]?.trim();if(s)return $(s)}catch{}return null}function I(e,t){const n=e.hooks;if(!n||typeof n!="object"||Array.isArray(n))return!1;let o=!1;for(const s of Object.keys(n)){const r=n[s];if(!Array.isArray(r))continue;let i=!1;const c=[];for(const d of r){const f=d;if(!f||typeof f!="object"||!Array.isArray(f.hooks)){c.push(d);continue}const u=f.hooks.filter(m=>!t.test(m?.command??""));if(u.length===f.hooks.length){c.push(d);continue}o=!0,i=!0,u.length>0&&c.push({...f,hooks:u})}i&&(c.length===0?delete n[s]:n[s]=c)}return o&&Object.keys(n).length===0&&delete e.hooks,o}function ne(e){return I(e,X)}function Oe(e={}){if(!!!(e.settingsPath??process.env.CLAUDE_SETTINGS)&&!l(a(v(),".claude")))return{client:K(S(e)),action:"skipped",message:"failure firewall: ~/.claude not found on this machine (needs the Claude Code CLI). Not armed. Install Claude Code then re-run `wyrm guard`"};const n=S(e),o=K(n);try{const s=e.guardCommand??Ce();if(!s)return{client:o,action:"skipped",message:te()??"wyrm-guard bin not found (npm i -g wyrm-mcp, or build dist/); firewall hooks not installed"};b(w(n),{recursive:!0});let r={};if(l(n))try{const g=JSON.parse(h(n,"utf-8"));if(typeof g!="object"||g===null||Array.isArray(g))throw new Error("not an object");r=g}catch{return{client:o,action:"failed",message:`${n} is not valid JSON; refusing to overwrite it (fix or remove the file, then re-run)`}}const i=r.hooks;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))return{client:o,action:"failed",message:`${n} "hooks" has an unexpected shape (not a plain object); refusing to modify (fix the file, then re-run)`};const c=i?.PreToolUse;if(c!==void 0&&!Array.isArray(c))return{client:o,action:"failed",message:`${n} hooks.PreToolUse has an unexpected shape (not an array); refusing to modify (fix the file, then re-run)`};const d=JSON.stringify(r);ne(r);const f=r.hooks??{},u=Array.isArray(f.PreToolUse)?f.PreToolUse:[];for(const g of Ae)u.push({matcher:g,hooks:[{type:"command",command:s,timeout:ee}]});f.PreToolUse=u,r.hooks=f;const m=JSON.stringify(r)!==d;return m&&p(n,JSON.stringify(r,null,2)+`
14
- `,"utf-8"),o.configured=!0,{client:o,action:m?"configured":"skipped",message:m?"failure-firewall hooks installed (PreToolUse: Bash + Edit|Write|MultiEdit|NotebookEdit)":"failure-firewall hooks already installed"}}catch(s){return{client:o,action:"failed",message:s instanceof Error?s.message:String(s)}}}function _e(e={}){const t=S(e);if(!l(t))return null;const n=K(t);try{let o;try{const r=JSON.parse(h(t,"utf-8"));if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("not an object");o=r}catch{return{client:n,action:"failed",message:`${t} is not valid JSON; not touching it`}}return ne(o)?(p(t,JSON.stringify(o,null,2)+`
15
- `,"utf-8"),{client:n,action:"configured",message:"failure-firewall hooks removed"}):{client:n,action:"skipped",message:"no wyrm-guard hooks installed"}}catch(o){return{client:n,action:"failed",message:o instanceof Error?o.message:String(o)}}}function qe(e={}){const t=S(e),n=[];try{const s=JSON.parse(h(t,"utf-8")).hooks??{};for(const r of Object.values(s))if(Array.isArray(r))for(const i of r)for(const c of i?.hooks??[]){const d=c?.command;d&&X.test(d)&&n.push(d)}}catch{}return{settingsPath:t,installed:n.length>0,commands:n}}const F=/wyrm-memo/,$e=[{event:"PreToolUse",matcher:"Read"},{event:"PreToolUse",matcher:"Bash"},{event:"PostToolUse",matcher:"Read"},{event:"PostToolUse",matcher:"Bash"}];function re(e){return{id:"claude-code-memo",name:"Claude Code (token firewall)",icon:"",configPath:e,configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}function Ee(){const e=w(j(import.meta.url)),t=a(e,"wyrm-memo.js");if(l(t))return oe(t);try{const n=k()==="win32"?"where":"which",s=P(n,["wyrm-memo"],{encoding:"utf-8",timeout:5e3}).stdout?.trim().split(`
16
- `)[0]?.trim();if(s)return $(s)}catch{}return null}function Ne(e={}){const t=S(e),n=!!(e.settingsPath??process.env.CLAUDE_SETTINGS),o=re(t);if(!n&&!l(a(v(),".claude")))return{client:o,action:"skipped",message:"token firewall: ~/.claude not found on this machine (needs the Claude Code CLI). Not armed. Install Claude Code then re-run `wyrm memo`"};try{const s=e.memoCommand??Ee();if(!s)return{client:o,action:"skipped",message:te()??"wyrm-memo bin not found (npm i -g wyrm-mcp, or build dist/). Token-firewall hooks not installed"};b(w(t),{recursive:!0});let r={};if(l(t))try{const u=JSON.parse(h(t,"utf-8"));if(typeof u!="object"||u===null||Array.isArray(u))throw new Error("not an object");r=u}catch{return{client:o,action:"failed",message:`${t} is not valid JSON; refusing to overwrite it (fix or remove the file, then re-run)`}}const i=r.hooks;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))return{client:o,action:"failed",message:`${t} "hooks" has an unexpected shape (not a plain object); refusing to modify`};for(const u of["PreToolUse","PostToolUse"]){const m=i?.[u];if(m!==void 0&&!Array.isArray(m))return{client:o,action:"failed",message:`${t} hooks.${u} has an unexpected shape (not an array); refusing to modify`}}const c=JSON.stringify(r);I(r,F);const d=r.hooks??{};for(const{event:u,matcher:m}of $e){const g=Array.isArray(d[u])?d[u]:[];g.push({matcher:m,hooks:[{type:"command",command:s,timeout:ee}]}),d[u]=g}r.hooks=d;const f=JSON.stringify(r)!==c;return f&&p(t,JSON.stringify(r,null,2)+`
17
- `,"utf-8"),o.configured=!0,{client:o,action:f?"configured":"skipped",message:f?"token-firewall hooks installed (PreToolUse + PostToolUse: Read, Bash). Mode: observe (set WYRM_MEMO_MODE=warn to hand maps back)":"token-firewall hooks already installed"}}catch(s){return{client:o,action:"failed",message:s instanceof Error?s.message:String(s)}}}function Ye(e={}){const t=S(e);if(!l(t))return null;const n=re(t);try{let o;try{const r=JSON.parse(h(t,"utf-8"));if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("not an object");o=r}catch{return{client:n,action:"failed",message:`${t} is not valid JSON; not touching it`}}return I(o,F)?(p(t,JSON.stringify(o,null,2)+`
18
- `,"utf-8"),{client:n,action:"configured",message:"token-firewall hooks removed"}):{client:n,action:"skipped",message:"no wyrm-memo hooks installed"}}catch(o){return{client:n,action:"failed",message:o instanceof Error?o.message:String(o)}}}function ze(e={}){const t=S(e),n=[];try{const s=JSON.parse(h(t,"utf-8")).hooks??{};for(const r of Object.values(s))if(Array.isArray(r))for(const i of r)for(const c of i?.hooks??[]){const d=c?.command;d&&F.test(d)&&n.push(d)}}catch{}return{settingsPath:t,installed:n.length>0,commands:n}}function We(e){const t={serverPath:e?.serverPath||R(),dbPath:e?.dbPath||U(),httpPort:e?.httpPort},n=a(v(),".wyrm");l(n)||b(n,{recursive:!0});const o=_(),s=[];for(const d of o)s.push(V(d,t));se(t);const r=be();r&&s.push(r);const i=Oe();i&&s.push(i);const c=Ne();return c&&s.push(c),s}function Ve(){const e=_(),t=[];for(const s of e)t.push(Pe(s));const n=je();n&&t.push(n);const o=_e();return o&&t.push(o),t}function Te(e,t){const n={serverPath:t?.serverPath||R(),dbPath:t?.dbPath||U(),httpPort:t?.httpPort},o=_(),s=[];for(const r of o)e.includes(r.id)&&s.push(V(r,n));return se(n),s}function se(e){const t=a(v(),".wyrm","wyrm-config.json"),n=_().filter(s=>s.configured).map(s=>s.id),o={version:"3.0.0",serverPath:e.serverPath,dbPath:e.dbPath,httpPort:e.httpPort,configuredClients:n,lastSetup:new Date().toISOString(),autoUpdate:!0};p(t,JSON.stringify(o,null,2)+`
19
- `,"utf-8")}function ie(){const e=a(v(),".wyrm","wyrm-config.json");if(!l(e))return null;try{return JSON.parse(h(e,"utf-8"))}catch{return null}}function Qe(){const e=ie();return e?Te(e.configuredClients,{serverPath:e.serverPath,dbPath:e.dbPath,httpPort:e.httpPort}):We()}const ae="<!-- wyrm:start -->",H="<!-- wyrm:end -->",B=`${ae}
1
+ import{existsSync as p,readFileSync as S,writeFileSync as O,mkdirSync as W,chmodSync as oe,lstatSync as ke,realpathSync as we,statSync as ve,renameSync as be,unlinkSync as Pe}from"fs";import{homedir as g,platform as A}from"os";import{join as a,dirname as k,resolve as Se,basename as Ae}from"path";import{randomBytes as Ce}from"crypto";import{fileURLToPath as E}from"url";import{spawnSync as j}from"child_process";import{npmGlobalPrefixFromPath as je}from"./cli.js";import{syncWyrmHookFiles as $e,describeHookSync as _e,WYRM_HOOK_SUPPORT_FILES as xe}from"./hook-refresh.js";function We(){const e=g(),t=A(),o=t==="darwin"?a(e,"Library","Application Support","Code","User"):t==="win32"?a(e,"AppData","Roaming","Code","User"):a(e,".config","Code","User"),n=t==="darwin"?a(e,"Library","Application Support","Code - Insiders","User"):t==="win32"?a(e,"AppData","Roaming","Code - Insiders","User"):a(e,".config","Code - Insiders","User"),r=t==="darwin"?a(e,"Library","Application Support","Claude"):t==="win32"?a(e,"AppData","Roaming","Claude"):a(e,".config","claude"),s=t==="darwin"?a(e,".cursor"):t==="win32"?a(e,".cursor"):a(e,".cursor"),c=t==="darwin"?a(e,".codeium","windsurf"):t==="win32"?a(e,".codeium","windsurf"):a(e,".codeium","windsurf"),i=t==="darwin"?a(e,".config","zed"):t==="win32"?a(e,"AppData","Roaming","Zed"):a(e,".config","zed"),u=a(e,".continue");return[{id:"vscode-copilot",name:"VS Code (Copilot)",icon:"\u{1F4BB}",configPath:a(o,"settings.json"),configFormat:"vscode",mcpKey:"mcp.servers",detected:!1,configured:!1},{id:"vscode-insiders",name:"VS Code Insiders",icon:"\u{1F7E2}",configPath:a(n,"settings.json"),configFormat:"vscode",mcpKey:"mcp.servers",detected:!1,configured:!1},{id:"claude-desktop",name:"Claude Desktop",icon:"\u{1F916}",configPath:a(r,"claude_desktop_config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"claude-code",name:"Claude Code",icon:"\u2733\uFE0F",configPath:a(e,".claude.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"cursor",name:"Cursor",icon:"\u{1F4D0}",configPath:a(s,"mcp.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"windsurf",name:"Windsurf",icon:"\u{1F3C4}",configPath:a(c,"mcp_config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"zed",name:"Zed",icon:"\u26A1",configPath:a(i,"settings.json"),configFormat:"zed",mcpKey:"context_servers",detected:!1,configured:!1},{id:"continue",name:"Continue",icon:"\u{1F504}",configPath:a(u,"config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1}]}function Ee(e){try{const t=A()==="win32"?"where":"which",o=j(t,[e],{encoding:"utf-8",timeout:5e3});return o.status===0&&!!o.stdout&&o.stdout.trim().length>0}catch{return!1}}function D(){const e=We();for(const t of e){if(t.id==="claude-code")t.detected=p(a(k(t.configPath),".claude"))||Ee("claude");else{const o=k(t.configPath);t.detected=p(o)}if(t.detected&&p(t.configPath))try{const o=S(t.configPath,"utf-8"),n=U(o);t.configured=Oe(n,t)}catch{t.configured=!1}t.detected&&(t.version=Te(t))}return e}function Te(e){try{switch(e.id){case"vscode-copilot":case"vscode-insiders":{const t=e.id==="vscode-insiders"?"code-insiders":"code",o=j(t,["--version"],{encoding:"utf-8",timeout:5e3});if(o.stdout)return o.stdout.split(`
2
+ `)[0];break}case"cursor":{const t=j("cursor",["--version"],{encoding:"utf-8",timeout:5e3});if(t.stdout)return t.stdout.split(`
3
+ `)[0];break}case"claude-code":{const t=j("claude",["--version"],{encoding:"utf-8",timeout:5e3});if(t.stdout)return t.stdout.trim().split(`
4
+ `)[0];break}}}catch{}}function Oe(e,t){switch(t.configFormat){case"vscode":return e.mcp?.servers?.wyrm!==void 0;case"mcp-json":return e[t.mcpKey]?.wyrm!==void 0;case"zed":return e[t.mcpKey]?.wyrm!==void 0;default:return!1}}function H(e=A()){if(e!=="win32"){try{const r=j("which",["wyrm-mcp"],{encoding:"utf-8",timeout:5e3});if(r.stdout?.trim())return r.stdout.trim()}catch{}try{const s=j("npm",["root","-g"],{encoding:"utf-8",timeout:5e3}).stdout?.trim();if(s){const c=a(s,"wyrm-mcp","dist","index.js");if(p(c))return c}}catch{}}const t=Se(k(E(import.meta.url)),"index.js");if(p(t))return t;const o=a(g(),".wyrm","node_modules","wyrm-mcp","dist","index.js");if(p(o))return o;const n=[a(g(),"Git Projects","Wyrm","packages","mcp-server","dist","index.js"),a(g(),"projects","Wyrm","packages","mcp-server","dist","index.js"),a(g(),"dev","Wyrm","packages","mcp-server","dist","index.js")];for(const r of n)if(p(r))return r;return"wyrm-mcp"}function B(){return a(g(),".wyrm","wyrm.db")}function it(e="mcp-json",t){const o=t?.serverPath??H(),n=t?.dbPath??B(),r=o==="wyrm-mcp",s={command:r?"npx":"node",args:r?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:n}};switch(e){case"stdio":return s;case"vscode":return{mcp:{servers:{wyrm:s}}};default:return{mcpServers:{wyrm:s}}}}function De(e,t){const o=t.serverPath,n=o==="wyrm-mcp",r=o.endsWith(".js");switch(e.configFormat){case"vscode":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};case"mcp-json":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};case"zed":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};default:return{}}}function Me(e,t){if(!e||typeof e!="object"||Array.isArray(e))return{entry:t,preservedLauncher:!1};const o=e,n=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:{},r=t.env&&typeof t.env=="object"&&!Array.isArray(t.env)?t.env:{};if(o.command===t.command&&JSON.stringify(o.args??null)===JSON.stringify(t.args??null))return{entry:{...t,env:{...r,...n}},preservedLauncher:!1};const c={...n};for(const[i,u]of Object.entries(r))i in c||(c[i]=u);return{entry:{...o,env:c},preservedLauncher:!0}}function ne(e,t){if(!e.detected)return{client:e,action:"skipped",message:`${e.name} not detected`};try{const o=k(e.configPath);p(o)||W(o,{recursive:!0});const n=w(e.configPath);if(!n.ok)return P(e,n);const r=n.config,s=De(e,t);let c=!1;const i=(f,l)=>{const y=Me(f.wyrm,l);return f.wyrm=y.entry,y.preservedLauncher};switch(e.configFormat){case"vscode":{r.mcp||(r.mcp={});const f=r.mcp;f.servers||(f.servers={});const l=f.servers;c=i(l,s)||c;break}case"mcp-json":{r[e.mcpKey]||(r[e.mcpKey]={});const f=r[e.mcpKey];c=i(f,s)||c;break}case"zed":{r[e.mcpKey]||(r[e.mcpKey]={});const f=r[e.mcpKey];c=i(f,s)||c;break}}const u=v(e.configPath,n,r,{backup:"always"}),d=b(u),m=e.configured?"updated":"configured";return e.configured=!0,{client:e,action:m,message:`${e.name} ${u.written?m==="configured"?"configured successfully":"updated successfully":"already up to date"}`+(c?" (kept your custom launch command; only missing env was added)":"")+d.note,...d.backup?{backup:d.backup}:{}}}catch(o){return{client:e,action:"failed",message:`Failed to configure ${e.name}: ${o}`}}}function at(e,t){try{if(!p(e.configPath))return{client:e,action:"skipped",message:"No config file"};const o=w(e.configPath);if(!o.ok)return P(e,o);const n=o.config,s=(e.configFormat==="vscode"?n.mcp?.servers:n[e.mcpKey])?.wyrm;if(!s)return{client:e,action:"skipped",message:"Wyrm not configured in this client"};s.env={...s.env,...t};const c=v(e.configPath,o,n,{backup:"always"});if(!c.written)return{client:e,action:"skipped",message:`env already set: ${Object.keys(t).join(", ")}`};const i=b(c);return{client:e,action:"updated",message:`env: ${Object.keys(t).join(", ")}${i.note}`,...i.backup?{backup:i.backup}:{}}}catch(o){return{client:e,action:"failed",message:String(o)}}}function Ne(e){if(!e.detected||!e.configured)return{client:e,action:"skipped",message:`${e.name} not configured`};try{if(!p(e.configPath))return{client:e,action:"skipped",message:`${e.name} config not found`};const t=w(e.configPath);if(!t.ok)return P(e,t);const o=t.config;switch(e.configFormat){case"vscode":{const s=o.mcp?.servers;s&&delete s.wyrm;break}case"mcp-json":case"zed":{const r=o[e.mcpKey];r&&delete r.wyrm;break}}const n=b(v(e.configPath,t,o,{backup:"always"}));return e.configured=!1,{client:e,action:"configured",message:`Removed Wyrm from ${e.name}${n.note}`,...n.backup?{backup:n.backup}:{}}}catch(t){return{client:e,action:"failed",message:`Failed to remove from ${e.name}: ${t}`}}}function R(){return{id:"claude-code-hooks",name:"Claude Code (auto-memory)",icon:"\u{1FA9D}",configPath:a(g(),".claude","settings.json"),configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}const Re="Agent|Task",_=[{script:"wyrm-session-capture.mjs",events:["SessionEnd","PreCompact"]},{script:"wyrm-session-rehydrate.mjs",events:["SessionStart"]},{script:"wyrm-session-prune.mjs",events:["SessionEnd"]},{script:"wyrm-tool-call-trace.mjs",events:["PostToolUse"]},{script:"wyrm-run-auto.mjs",events:["SessionStart",{event:"PreToolUse",matcher:Re,legacyMatchers:["Task"]},"SessionEnd"]},{script:"wyrm-citation-audit.mjs",events:["Stop"]},{script:"wyrm-prompt-context.mjs",events:["UserPromptSubmit"]}],ut=_.map(e=>e.script),J=/[$`%"]/;function re(e,t=A()){return t==="win32"?J.test(e)?null:`node ${M(e,t)}`:/^[\w@%+=:,./-]+$/.test(e)?`node ${e}`:`node ${M(e,t)}`}function se(e,t=A()){return{current:re(e,t),legacy:`node ${e}`}}function Ue(e,t,o,n=[]){if(t.current===null)return!1;const r=t.current;let s=null,c=!1;for(let u=0;u<e.length;u++){const d=e[u];if(!Array.isArray(d.hooks))continue;const m=d.hooks.length;d.hooks=d.hooks.filter(f=>f.command!==r&&f.command!==t.legacy?!0:s?(c=!0,!1):(s={group:d,entry:f},f.command!==r&&(f.command=r,c=!0),!0)),m>0&&d.hooks.length===0&&(e.splice(u,1),u--)}const i=s;if(i&&o&&i.group.matcher!==void 0&&n.includes(i.group.matcher)){const{group:u,entry:d}=i;u.hooks.length===1?u.matcher=o:(u.hooks=u.hooks.filter(m=>m!==d),e.push({matcher:o,hooks:[d]})),c=!0}if(!s){const u={type:"command",command:r,timeout:30};e.push(o?{matcher:o,hooks:[u]}:{hooks:[u]}),c=!0}return c}function dt(e={}){const t=a(e.claudeDir??a(g(),".claude"),"settings.json"),o=_.find(i=>i.script==="wyrm-run-auto.mjs"),n=o.events.find(i=>typeof i!="string"&&i.event==="PreToolUse"),r=w(t);if(!r.ok)return{settingsPath:t,state:"unreadable"};const s=r.config.hooks?.PreToolUse;if(!Array.isArray(s))return{settingsPath:t,state:"absent"};const c=s.filter(i=>Array.isArray(i?.hooks)&&i.hooks.some(u=>typeof u?.command=="string"&&u.command.includes(o.script))).map(i=>i.matcher??"");return c.length===0?{settingsPath:t,state:"absent"}:c.includes(n.matcher)?{settingsPath:t,state:"current"}:c.every(i=>(n.legacyMatchers??[]).includes(i))?{settingsPath:t,state:"legacy"}:{settingsPath:t,state:"other"}}function Le(e={}){const t=e.claudeDir??a(g(),".claude");if(!p(t))return null;const o=R();e.claudeDir&&(o.configPath=a(t,"settings.json"));try{const n=a(t,"hooks");p(n)||W(n,{recursive:!0});const r=k(E(import.meta.url)),s=a(r,"..","scripts","hooks"),c=o.configPath,i=w(c);if(!i.ok)return P(o,i);const u=i.config,d=u.hooks??{},m=a(n,"wyrm-cli.json"),f=JSON.stringify({cli:a(r,"wyrm.js")},null,2)+`
5
+ `;let l=!1;try{let h=!1;try{const T=JSON.parse(S(m,"utf-8"));h=typeof T.cli=="string"&&p(T.cli)}catch{}(je(a(r,"wyrm.js"))!==null||!h)&&!(p(m)&&S(m,"utf-8")===f)&&(O(m,f,"utf-8"),l=!0)}catch{}let y=!1;const C=[];let L="0.0.0";try{L=JSON.parse(S(a(r,"..","package.json"),"utf-8")).version??L}catch{}const F=$e({hooksDir:n,scriptsDir:s,version:L,installMissing:!0,replaceModified:/^(1|true|yes|on)$/i.test(process.env.WYRM_HOOKS_REPLACE_MODIFIED??""),files:[...xe,..._.map(h=>h.script)]}),N=F.results.filter(h=>h.action==="missing-source").map(h=>h.file),Z=F.results.some(h=>h.action==="installed"||h.action==="updated");for(const h of _){if(N.includes(h.script))continue;const ee=a(n,h.script),T=se(ee);if(T.current===null){C.push(h.script);continue}for(const $ of h.events){const K=typeof $=="string"?$:$.event,ge=typeof $=="string"?void 0:$.matcher,ye=typeof $=="string"?[]:$.legacyMatchers??[],te=Array.isArray(d[K])?d[K]:[];Ue(te,T,ge,ye)&&(y=!0),d[K]=te}}u.hooks=d;const I=b(v(c,i,u));if(C.length===_.length-N.length&&C.length>0)return{client:o,action:"failed",message:`${n} contains a character ($, \`, % or ") that no quoting makes safe in every Windows shell, so the hooks were not wired.`};o.configured=!0;const X=_e(F).filter(h=>!h.startsWith("refreshed ")),he=(N.length?` (missing from package: ${N.join(", ")})`:"")+(X.length?`; ${X.join("; ")}`:"");return{client:o,action:y||l||Z?"configured":"skipped",message:(y?"auto-memory hooks installed":Z?"hook scripts refreshed":l?"hooks already installed; CLI location refreshed":"already installed")+he+I.note,...I.backup?{backup:I.backup}:{}}}catch(n){return{client:o,action:"failed",message:n instanceof Error?n.message:String(n)}}}function ft(e={}){const t=e.claudeDir??a(g(),".claude");if(!p(t))return null;const o=R();e.claudeDir&&(o.configPath=a(t,"settings.json"));try{const n=k(E(import.meta.url)),r=re(a(n,"wyrm-statusline.js"));if(r===null)return{client:o,action:"failed",message:'the install path contains a character ($, `, % or ") that no quoting makes safe in every Windows shell, so the statusline was not set'};const s=o.configPath,c=w(s);if(!c.ok)return P(o,c);const i=c.config,u=i.statusLine;if(u?.command&&!/wyrm-statusline/.test(u.command))return{client:o,action:"skipped",message:`a non-Wyrm statusLine is already set (${u.command}); not overwriting`};const d=u?.command===r;i.statusLine={type:"command",command:r,padding:0};const m=b(v(s,c,i));return{client:o,action:d?"skipped":"configured",message:(d?"buddy statusline already installed":"Wyrm buddy statusline installed (persistent in the Claude Code TUI)")+m.note,...m.backup?{backup:m.backup}:{}}}catch(n){return{client:o,action:"failed",message:n instanceof Error?n.message:String(n)}}}function lt(e={}){const t=a(e.claudeDir??a(g(),".claude"),"settings.json");if(!p(t))return null;const o=R();try{const n=w(t);if(!n.ok)return P(o,n);const r=n.config,s=r.statusLine;if(s?.command&&/wyrm-statusline/.test(s.command)){delete r.statusLine;const c=b(v(t,n,r));return{client:o,action:"configured",message:`Wyrm statusline removed${c.note}`,...c.backup?{backup:c.backup}:{}}}return{client:o,action:"skipped",message:"no Wyrm statusline set"}}catch(n){return{client:o,action:"failed",message:n instanceof Error?n.message:String(n)}}}function Fe(e={}){const t=e.claudeDir??a(g(),".claude"),o=a(t,"settings.json");if(!p(o))return null;const n=R();e.claudeDir&&(n.configPath=o);try{const r=w(o);if(!r.ok)return P(n,r);const s=r.config,c=a(t,"hooks"),i=new Set(_.flatMap(f=>{const l=se(a(c,f.script));return l.current===null?[l.legacy]:[l.current,l.legacy]})),u=new Set(_.flatMap(f=>f.events.map(l=>typeof l=="string"?l:l.event))),d=s.hooks;if(d){for(const f of u)Array.isArray(d[f])&&(d[f]=d[f].map(l=>({...l,hooks:Array.isArray(l.hooks)?l.hooks.filter(y=>!i.has(y.command??"")):l.hooks})).filter(l=>!Array.isArray(l.hooks)||l.hooks.length>0),d[f].length===0&&delete d[f]);Object.keys(d).length===0&&delete s.hooks}const m=b(v(o,r,s));return{client:n,action:"configured",message:`auto-memory hooks removed${m.note}`,...m.backup?{backup:m.backup}:{}}}catch(r){return{client:n,action:"failed",message:r instanceof Error?r.message:String(r)}}}const ce=/wyrm-guard/,ie=5,Ie=["Bash","Edit|Write|MultiEdit|NotebookEdit"];function x(e){return e.settingsPath??process.env.CLAUDE_SETTINGS??a(g(),".claude","settings.json")}function G(e){return{id:"claude-code-guard",name:"Claude Code (failure firewall)",icon:"\u{1F6E1}\uFE0F",configPath:e,configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}function M(e,t=A()){return t==="win32"?`"${e.replace(/\\/g,"/").replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function ae(e=A()){const t=k(E(import.meta.url));return e==="win32"&&J.test(t)?`the install path (${t}) contains a character ($, \`, % or ") that no quoting makes safe in every Windows shell, so the hook was not installed`:null}function ue(e,t=A()){return t==="win32"&&J.test(e)?null:`node ${M(e,t)}`}function Ke(){const e=k(E(import.meta.url)),t=a(e,"wyrm-guard.js");if(p(t))return ue(t);try{const o=A()==="win32"?"where":"which",r=j(o,["wyrm-guard"],{encoding:"utf-8",timeout:5e3}).stdout?.trim().split(`
6
+ `)[0]?.trim();if(r)return M(r)}catch{}return null}function q(e,t){const o=e.hooks;if(!o||typeof o!="object"||Array.isArray(o))return!1;let n=!1;for(const r of Object.keys(o)){const s=o[r];if(!Array.isArray(s))continue;let c=!1;const i=[];for(const u of s){const d=u;if(!d||typeof d!="object"||!Array.isArray(d.hooks)){i.push(u);continue}const m=d.hooks.filter(f=>!t.test(f?.command??""));if(m.length===d.hooks.length){i.push(u);continue}n=!0,c=!0,m.length>0&&i.push({...d,hooks:m})}c&&(i.length===0?delete o[r]:o[r]=i)}return n&&Object.keys(o).length===0&&delete e.hooks,n}function de(e){return q(e,ce)}function He(e={}){if(!!!(e.settingsPath??process.env.CLAUDE_SETTINGS)&&!p(a(g(),".claude")))return{client:G(x(e)),action:"skipped",message:"failure firewall: ~/.claude not found on this machine (needs the Claude Code CLI). Not armed. Install Claude Code then re-run `wyrm guard`"};const o=x(e),n=G(o);try{const r=e.guardCommand??Ke();if(!r)return{client:n,action:"skipped",message:ae()??"wyrm-guard bin not found (npm i -g wyrm-mcp, or build dist/); firewall hooks not installed"};W(k(o),{recursive:!0});const s=w(o);if(!s.ok)return P(n,s);const c=s.config,i=c.hooks;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))return{client:n,action:"failed",message:`${o} "hooks" has an unexpected shape (not a plain object); refusing to modify (fix the file, then re-run)`};const u=i?.PreToolUse;if(u!==void 0&&!Array.isArray(u))return{client:n,action:"failed",message:`${o} hooks.PreToolUse has an unexpected shape (not an array); refusing to modify (fix the file, then re-run)`};const d=JSON.stringify(c);de(c);const m=c.hooks??{},f=Array.isArray(m.PreToolUse)?m.PreToolUse:[];for(const C of Ie)f.push({matcher:C,hooks:[{type:"command",command:r,timeout:ie}]});m.PreToolUse=f,c.hooks=m;const l=JSON.stringify(c)!==d,y=b(l?v(o,s,c):void 0);return n.configured=!0,{client:n,action:l?"configured":"skipped",message:(l?"failure-firewall hooks installed (PreToolUse: Bash + Edit|Write|MultiEdit|NotebookEdit)":"failure-firewall hooks already installed")+y.note,...y.backup?{backup:y.backup}:{}}}catch(r){return{client:n,action:"failed",message:r instanceof Error?r.message:String(r)}}}function Be(e={}){const t=x(e);if(!p(t))return null;const o=G(t);try{const n=w(t);if(!n.ok)return P(o,n);const r=n.config;if(!de(r))return{client:o,action:"skipped",message:"no wyrm-guard hooks installed"};const c=b(v(t,n,r));return{client:o,action:"configured",message:`failure-firewall hooks removed${c.note}`,...c.backup?{backup:c.backup}:{}}}catch(n){return{client:o,action:"failed",message:n instanceof Error?n.message:String(n)}}}function mt(e={}){const t=x(e),o=[];try{const r=U(S(t,"utf-8")).hooks??{};for(const s of Object.values(r))if(Array.isArray(s))for(const c of s)for(const i of c?.hooks??[]){const u=i?.command;u&&ce.test(u)&&o.push(u)}}catch{}return{settingsPath:t,installed:o.length>0,commands:o}}const Y=/wyrm-memo/,Je=[{event:"PreToolUse",matcher:"Read"},{event:"PreToolUse",matcher:"Bash"},{event:"PostToolUse",matcher:"Read"},{event:"PostToolUse",matcher:"Bash"}];function fe(e){return{id:"claude-code-memo",name:"Claude Code (token firewall)",icon:"",configPath:e,configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}function Ge(){const e=k(E(import.meta.url)),t=a(e,"wyrm-memo.js");if(p(t))return ue(t);try{const o=A()==="win32"?"where":"which",r=j(o,["wyrm-memo"],{encoding:"utf-8",timeout:5e3}).stdout?.trim().split(`
7
+ `)[0]?.trim();if(r)return M(r)}catch{}return null}function qe(e={}){const t=x(e),o=!!(e.settingsPath??process.env.CLAUDE_SETTINGS),n=fe(t);if(!o&&!p(a(g(),".claude")))return{client:n,action:"skipped",message:"token firewall: ~/.claude not found on this machine (needs the Claude Code CLI). Not armed. Install Claude Code then re-run `wyrm memo`"};try{const r=e.memoCommand??Ge();if(!r)return{client:n,action:"skipped",message:ae()??"wyrm-memo bin not found (npm i -g wyrm-mcp, or build dist/). Token-firewall hooks not installed"};W(k(t),{recursive:!0});const s=w(t);if(!s.ok)return P(n,s);const c=s.config,i=c.hooks;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))return{client:n,action:"failed",message:`${t} "hooks" has an unexpected shape (not a plain object); refusing to modify`};for(const l of["PreToolUse","PostToolUse"]){const y=i?.[l];if(y!==void 0&&!Array.isArray(y))return{client:n,action:"failed",message:`${t} hooks.${l} has an unexpected shape (not an array); refusing to modify`}}const u=JSON.stringify(c);q(c,Y);const d=c.hooks??{};for(const{event:l,matcher:y}of Je){const C=Array.isArray(d[l])?d[l]:[];C.push({matcher:y,hooks:[{type:"command",command:r,timeout:ie}]}),d[l]=C}c.hooks=d;const m=JSON.stringify(c)!==u,f=b(m?v(t,s,c):void 0);return n.configured=!0,{client:n,action:m?"configured":"skipped",message:(m?"token-firewall hooks installed (PreToolUse + PostToolUse: Read, Bash). Mode: observe (set WYRM_MEMO_MODE=warn to hand maps back)":"token-firewall hooks already installed")+f.note,...f.backup?{backup:f.backup}:{}}}catch(r){return{client:n,action:"failed",message:r instanceof Error?r.message:String(r)}}}function pt(e={}){const t=x(e);if(!p(t))return null;const o=fe(t);try{const n=w(t);if(!n.ok)return P(o,n);const r=n.config;if(!q(r,Y))return{client:o,action:"skipped",message:"no wyrm-memo hooks installed"};const c=b(v(t,n,r));return{client:o,action:"configured",message:`token-firewall hooks removed${c.note}`,...c.backup?{backup:c.backup}:{}}}catch(n){return{client:o,action:"failed",message:n instanceof Error?n.message:String(n)}}}function ht(e={}){const t=x(e),o=[];try{const r=U(S(t,"utf-8")).hooks??{};for(const s of Object.values(r))if(Array.isArray(s))for(const c of s)for(const i of c?.hooks??[]){const u=i?.command;u&&Y.test(u)&&o.push(u)}}catch{}return{settingsPath:t,installed:o.length>0,commands:o}}function Ye(e){const t={serverPath:e?.serverPath||H(),dbPath:e?.dbPath||B(),httpPort:e?.httpPort},o=a(g(),".wyrm");p(o)||W(o,{recursive:!0});const n=D(),r=[];for(const u of n)r.push(ne(u,t));le(t);const s=Le();s&&r.push(s);const c=He();c&&r.push(c);const i=qe();return i&&r.push(i),r}function gt(){const e=D(),t=[];for(const r of e)t.push(Ne(r));const o=Fe();o&&t.push(o);const n=Be();return n&&t.push(n),t}function ze(e,t){const o={serverPath:t?.serverPath||H(),dbPath:t?.dbPath||B(),httpPort:t?.httpPort},n=D(),r=[];for(const s of n)e.includes(s.id)&&r.push(ne(s,o));return le(o),r}function le(e){const t=a(g(),".wyrm","wyrm-config.json"),o=D().filter(r=>r.configured).map(r=>r.id),n={version:"3.0.0",serverPath:e.serverPath,dbPath:e.dbPath,httpPort:e.httpPort,configuredClients:o,lastSetup:new Date().toISOString(),autoUpdate:!0};O(t,JSON.stringify(n,null,2)+`
8
+ `,"utf-8")}function me(){const e=a(g(),".wyrm","wyrm-config.json");if(!p(e))return null;try{return JSON.parse(S(e,"utf-8"))}catch{return null}}function yt(){const e=me();return e?ze(e.configuredClients,{serverPath:e.serverPath,dbPath:e.dbPath,httpPort:e.httpPort}):Ye()}const pe="<!-- wyrm:start -->",z="<!-- wyrm:end -->",V=`${pe}
20
9
  ## Wyrm Memory + Agent (auto-managed \u2014 do not edit this section)
21
10
 
22
11
  **Session start** \u2014 call \`wyrm_session_prime\` first to load project context (ground truths, open quests, recent sessions, scaffolds) before responding.
@@ -40,23 +29,24 @@ import{existsSync as l,readFileSync as h,writeFileSync as p,mkdirSync as b,chmod
40
29
  **Keep wyrm-mcp current.** Updating is the operator's step, never yours. If a newer version is mentioned (the server prints a notice when one is on npm), tell the operator to run \`wyrm update\` in a terminal: it verifies the release before installing. Do not install or update packages for Wyrm yourself.
41
30
 
42
31
  **Buddy companion** \u2014 call \`wyrm_buddy\` for warm, data-grounded check-ins. At session start (after \`wyrm_session_prime\`) for long-running work, and when the operator completes a quest or hits a milestone. The buddy speaks in a chosen persona but every claim sources a real DB row \u2014 speak it verbatim, never invent additional encouragement. Auto-federates with other registered MCPs that expose \`*_buddy\` tools.
43
- ${H}`;function Ze(e,t){const n={injected:[],skipped:[],errors:[]},o=(r,i)=>{try{const c=w(r);if(l(c)||b(c,{recursive:!0}),l(r)){const d=h(r,"utf-8"),f=d.indexOf(ae),u=d.indexOf(H);if(f!==-1&&u!==-1&&u>f){const m=d.slice(0,f),g=d.slice(u+H.length);p(r,`${m}${B}${g}`,"utf-8")}else{const m=d.endsWith(`
32
+ ${z}`;function kt(e,t){const o={injected:[],skipped:[],errors:[]},n=(s,c)=>{try{const i=k(s);if(p(i)||W(i,{recursive:!0}),p(s)){const u=S(s,"utf-8"),d=u.indexOf(pe),m=u.indexOf(z);if(d!==-1&&m!==-1&&m>d){const f=u.slice(0,d),l=u.slice(m+z.length);Q(s,`${f}${V}${l}`)}else{const f=u.endsWith(`
44
33
  `)?`
45
34
  `:`
46
35
 
47
- `;p(r,`${d}${m}${B}
48
- `,"utf-8")}}else p(r,`${B}
49
- `,"utf-8");n.injected.push(i)}catch(c){n.errors.push(`${i}: ${c}`)}},s=t.length===0?["copilot","cursor"]:t;for(const r of s){const i=r.toLowerCase();if(i==="copilot"||i==="vscode-copilot"){const c=a(e,".github","copilot-instructions.md");o(c,".github/copilot-instructions.md")}else if(i==="cursor"){const c=a(e,".cursor","rules");o(c,".cursor/rules")}else n.skipped.push(r)}return n}function W(e){let t="",n=!1;for(let o=0;o<e.length;o++){const s=e[o];if(n){if(t+=s,s==="\\"){t+=e[++o]??"";continue}s==='"'&&(n=!1);continue}if(s==='"'){n=!0,t+=s;continue}if(s==="/"&&e[o+1]==="/"){for(;o<e.length&&e[o]!==`
50
- `;)o++;t+=`
51
- `;continue}if(s==="/"&&e[o+1]==="*"){for(o+=2;o<e.length&&!(e[o]==="*"&&e[o+1]==="/");)o++;o+=1;continue}if(s===","){let r=o+1;for(;;){for(;r<e.length&&/\s/.test(e[r]);)r++;if(e[r]==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
52
- `;)r++;continue}if(e[r]==="/"&&e[r+1]==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r+=2;continue}break}if(e[r]==="}"||e[r]==="]")continue}t+=s}return JSON.parse(t)}function Xe(){const e=_(),t=e.filter(r=>r.detected),n=e.filter(r=>r.configured);let o=`\u{F115D} Wyrm Auto-Configure Status
53
-
54
- `;o+=` Detected: ${t.length}/${e.length} AI clients
55
- `,o+=` Configured: ${n.length}/${t.length} clients
56
-
57
- `;for(const r of e){const i=r.detected?r.configured?" \u25CF":" \u25D0":" \u25CB",c=r.version?` (${r.version})`:"",d=r.detected?r.configured?"configured \u2713":"detected, not configured":"not found";o+=`${i} ${r.icon} ${r.name}${c}: ${d}
58
- `}const s=ie();return s&&(o+=`
59
- Server: ${s.serverPath}
60
- `,o+=` DB: ${s.dbPath}
61
- `,o+=` Last: ${new Date(s.lastSetup).toLocaleString()}
62
- `),o}export{He as CLAUDE_HOOK_SCRIPT_NAMES,ee as GUARD_HOOK_TIMEOUT_SEC,$e as MEMO_HOOK_EVENTS,B as WYRM_INJECT_BLOCK,Fe as applyWyrmEnvToClient,We as autoConfigureAll,V as configureClient,Te as configureSpecific,_ as detectClients,Ie as exportServerConfig,R as findWyrmServerPath,U as getDefaultDbPath,Xe as getStatusSummary,Z as hookCommandForms,Q as hookNodeCommand,Ze as injectSystemPrompt,be as installClaudeCodeHooks,Be as installClaudeStatusline,Oe as installWyrmGuardHooks,Ne as installWyrmMemoHooks,ie as loadWyrmMeta,Se as mergeHookCommand,ke as mergeServerEntry,W as parseJsonWithComments,$ as quoteHookPath,Qe as reconfAll,je as removeClaudeCodeHooks,Ge as removeClaudeStatusline,Ve as removeFromAll,Pe as removeFromClient,_e as removeWyrmGuardHooks,Ye as removeWyrmMemoHooks,Ce as resolveWyrmGuardCommand,Ee as resolveWyrmMemoCommand,qe as wyrmGuardHookStatus,ze as wyrmMemoHookStatus};
36
+ `;Q(s,`${u}${f}${V}
37
+ `)}}else O(s,`${V}
38
+ `,"utf-8");o.injected.push(c)}catch(i){o.errors.push(`${c}: ${i}`)}},r=t.length===0?["copilot","cursor"]:t;for(const s of r){const c=s.toLowerCase();if(c==="copilot"||c==="vscode-copilot"){const i=a(e,".github","copilot-instructions.md");n(i,".github/copilot-instructions.md")}else if(c==="cursor"){const i=a(e,".cursor","rules");n(i,".cursor/rules")}else o.skipped.push(s)}return o}function U(e){e.charCodeAt(0)===65279&&(e=e.slice(1));let t="",o=!1;for(let n=0;n<e.length;n++){const r=e[n];if(o){if(t+=r,r==="\\"){t+=e[++n]??"";continue}r==='"'&&(o=!1);continue}if(r==='"'){o=!0,t+=r;continue}if(r==="/"&&e[n+1]==="/"){for(;n<e.length&&e[n]!==`
39
+ `;)n++;t+=`
40
+ `;continue}if(r==="/"&&e[n+1]==="*"){for(n+=2;n<e.length&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=1;continue}if(r===","){let s=n+1;for(;;){for(;s<e.length&&/\s/.test(e[s]);)s++;if(e[s]==="/"&&e[s+1]==="/"){for(;s<e.length&&e[s]!==`
41
+ `;)s++;continue}if(e[s]==="/"&&e[s+1]==="*"){for(s+=2;s<e.length&&!(e[s]==="*"&&e[s+1]==="/");)s++;s+=2;continue}break}if(e[s]==="}"||e[s]==="]")continue}t+=r}return JSON.parse(t)}function w(e){if(!p(e))return{ok:!0,config:{},existed:!1,text:"",plainJson:!0,canonical:""};const t=s=>({ok:!1,path:e,message:`${e} ${s}; refusing to change it (fix the file, then re-run)`});let o;try{o=S(e,"utf-8")}catch(s){return t(`could not be read (${s instanceof Error?s.message:String(s)})`)}if(o.replace(/^\ufeff/,"").trim()==="")return{ok:!0,config:{},existed:!0,text:o,plainJson:!0,canonical:"{}"};let n;try{n=U(o)}catch(s){return t(`could not be parsed (${s instanceof Error?s.message:String(s)})`)}if(typeof n!="object"||n===null||Array.isArray(n))return t("is not a JSON object");let r=!0;try{JSON.parse(o)}catch{r=!1}return{ok:!0,config:n,existed:!0,text:o,plainJson:r,canonical:JSON.stringify(n)}}function Q(e,t){let o=e;try{ke(e).isSymbolicLink()&&(o=we(e))}catch{}let n;try{n=ve(o).mode&4095}catch{}const r=a(k(o),`.${Ae(o)}.wyrm-tmp-${process.pid}-${Ce(4).toString("hex")}`);try{O(r,t,{encoding:"utf-8",mode:n??438,flag:"wx"}),n!==void 0&&oe(r,n),be(r,o)}catch(s){try{Pe(r)}catch{}throw s}}function Ve(e,t){const o=`${e}.wyrm-backup`;let n=o;if(p(o)){try{if(S(o,"utf-8")===t)return o}catch{}const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\..*$/,"");n=`${o}-${r}`;for(let s=2;p(n);s++)n=`${o}-${r}-${s}`}O(n,t,{encoding:"utf-8",mode:384,flag:"wx"});try{oe(n,384)}catch{}return n}function v(e,t,o,n={}){if(t.existed&&JSON.stringify(o)===t.canonical)return{written:!1,commentsDropped:!1};const r=t.existed&&!t.plainJson;let s;return t.existed&&(r||n.backup==="always")&&(s=Ve(e,t.text)),Q(e,JSON.stringify(o,null,2)+`
42
+ `),{written:!0,backup:s,commentsDropped:r}}function Qe(e){return e.commentsDropped&&e.backup?`; comments are not kept on rewrite, the original is at ${e.backup}`:""}function b(e){return e?{note:Qe(e),...e.backup?{backup:e.backup}:{}}:{note:""}}function P(e,t){return{client:e,action:"failed",message:t.message,unparsedConfig:t.path}}function wt(){const e=D(),t=e.filter(s=>s.detected),o=e.filter(s=>s.configured);let n=`\u{F115D} Wyrm Auto-Configure Status
43
+
44
+ `;n+=` Detected: ${t.length}/${e.length} AI clients
45
+ `,n+=` Configured: ${o.length}/${t.length} clients
46
+
47
+ `;for(const s of e){const c=s.detected?s.configured?" \u25CF":" \u25D0":" \u25CB",i=s.version?` (${s.version})`:"",u=s.detected?s.configured?"configured \u2713":"detected, not configured":"not found";n+=`${c} ${s.icon} ${s.name}${i}: ${u}
48
+ `}const r=me();return r&&(n+=`
49
+ Server: ${r.serverPath}
50
+ `,n+=` DB: ${r.dbPath}
51
+ `,n+=` Last: ${new Date(r.lastSetup).toLocaleString()}
52
+ `),n}export{ut as CLAUDE_HOOK_SCRIPT_NAMES,ie as GUARD_HOOK_TIMEOUT_SEC,Je as MEMO_HOOK_EVENTS,Re as RUN_AUTO_SPAWN_MATCHER,V as WYRM_INJECT_BLOCK,at as applyWyrmEnvToClient,Ye as autoConfigureAll,Qe as commentNote,ne as configureClient,ze as configureSpecific,D as detectClients,it as exportServerConfig,H as findWyrmServerPath,B as getDefaultDbPath,wt as getStatusSummary,se as hookCommandForms,re as hookNodeCommand,kt as injectSystemPrompt,Le as installClaudeCodeHooks,ft as installClaudeStatusline,He as installWyrmGuardHooks,qe as installWyrmMemoHooks,me as loadWyrmMeta,Ue as mergeHookCommand,Me as mergeServerEntry,U as parseJsonWithComments,M as quoteHookPath,w as readConfigForWrite,yt as reconfAll,Fe as removeClaudeCodeHooks,lt as removeClaudeStatusline,gt as removeFromAll,Ne as removeFromClient,Be as removeWyrmGuardHooks,pt as removeWyrmMemoHooks,Ke as resolveWyrmGuardCommand,Ge as resolveWyrmMemoCommand,dt as runAutoMatcherStatus,v as writeConfigBack,Q as writeFileAtomic,mt as wyrmGuardHookStatus,ht as wyrmMemoHookStatus};
package/dist/cloud/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import{randomBytes as R}from"node:crypto";import{writeFileSync as W}from"node:fs";import{homedir as M,hostname as F}from"node:os";import{resolve as j,dirname as B,join as U}from"node:path";import{fileURLToPath as G}from"node:url";import{createInterface as H}from"node:readline";import{CloudClient as g,CloudError as f,DEFAULT_BASE as v,SESSION_FILE as $,loadSession as y,saveSession as C,clearSession as _}from"./client.js";import{getMasterKey as Y,keyExists as k,keyFilePath as m,decrypt as J}from"./crypto.js";import{computeMachineFp as I,classifySession as q,cloudMachineId as K}from"./machine-id.js";import{runSync as z,CopiedSessionError as V,pendingPush as X,peekCursor as Q,parseSince as Z}from"./sync-engine.js";import{SyncLockedError as ee,EX_TEMPFAIL as oe}from"./sync-lock.js";import{WyrmDB as se,resolveDbPath as ne}from"../database.js";import{redactCredentials as te}from"../security.js";import{SovereignSyncManager as re,restartIntervalMinutes as ce}from"./sync-daemon.js";import{initializeLicense as le,hasFeature as ie,getTier as ae}from"../license.js";function S(){le(),ie("cloud_backup")||(console.error("\u{F115D} Wyrm Cloud sync requires a Pro license or higher."),console.error(` Current tier: ${ae()}`),console.error(" Get Pro: write to support@ghosts.lk"),console.error(" Details: https://ghosts.lk/wyrm"),console.error(" Already paid? Activate your license (wyrm_license tool, or place"),console.error(" the signed JSON at ~/.wyrm/license.json) and retry."),process.exit(1))}function b(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MiB`:`${(e/(1024*1024*1024)).toFixed(2)} GiB`}function x(e){return e?new Date(e).toISOString().replace("T"," ").slice(0,16)+" UTC":"never"}async function Be(e){const t=e[0],n=e.slice(1);try{switch(t){case void 0:case"help":case"--help":case"-h":return de();case"login":return await ue(n);case"logout":return await ge();case"status":return await me(n);case"doctor":return pe();case"devices":return await fe(n);case"sync":return await $e(n);case"daemon":return await ke(n);case"export":return await Se(n);case"delete":return await be(n);case"recovery":return await xe(n);default:console.error(`Unknown subcommand: wyrm cloud ${t}`),console.error("Try `wyrm cloud help`"),process.exit(1)}}catch(o){if(o instanceof ee&&(console.error(o.message),process.exit(oe)),o instanceof V&&process.exit(1),o instanceof f)o.status===401?console.error("\u2718 Not authenticated. Run `wyrm cloud login`."):o.status===403?console.error(`\u2718 Forbidden: ${o.message}`):o.status===0?(console.error(`\u2718 ${o.message}`),console.error(" Check your internet connection. If wyrm.ghosts.lk is unreachable, see status at https://www.cloudflarestatus.com")):o.status===501?console.error(`\u2718 Service not configured: ${o.message}`):console.error(`\u2718 ${o.message} (HTTP ${o.status})`);else if(o instanceof Error){const r=o.message;r.includes("Not logged in")?console.error("\u2718 Not logged in. Run `wyrm cloud login`."):r.includes("Wyrm Cloud key")?console.error(`\u2718 Encryption-key error: ${r}`):console.error(`\u2718 ${r}`)}else console.error("\u2718 Unexpected error:",o);process.exit(1)}}function de(){console.log(`\u{F115D} wyrm cloud: sync your Wyrm memory across devices
1
+ import{randomBytes as R}from"node:crypto";import{writeFileSync as W}from"node:fs";import{homedir as M,hostname as F}from"node:os";import{resolve as j,dirname as B,join as U}from"node:path";import{fileURLToPath as G}from"node:url";import{createInterface as H}from"node:readline";import{CloudClient as g,CloudError as f,DEFAULT_BASE as v,SESSION_FILE as $,loadSession as y,saveSession as C,clearSession as k}from"./client.js";import{getMasterKey as Y,keyExists as _,keyFilePath as m,decrypt as J}from"./crypto.js";import{computeMachineFp as I,classifySession as q,cloudMachineId as K}from"./machine-id.js";import{runSync as z,CopiedSessionError as V,pendingPush as X,peekCursor as Q,parseSince as Z}from"./sync-engine.js";import{SyncLockedError as ee,EX_TEMPFAIL as oe}from"./sync-lock.js";import{WyrmDB as se,resolveDbPath as ne}from"../database.js";import{redactCredentials as te}from"../security.js";import{SovereignSyncManager as re,restartIntervalMinutes as ce}from"./sync-daemon.js";import{initializeLicense as le,hasFeature as ie,getTier as ae}from"../license.js";function S(){le(),ie("cloud_backup")||(console.error("\u{F115D} Wyrm Cloud sync requires a Pro license or higher."),console.error(` Current tier: ${ae()}`),console.error(" Get Pro: write to support@ghosts.lk"),console.error(" Details: https://ghosts.lk/wyrm"),console.error(" Already paid? Activate your license (wyrm_license tool, or place"),console.error(" the signed JSON at ~/.wyrm/license.json) and retry."),process.exit(1))}function b(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MiB`:`${(e/(1024*1024*1024)).toFixed(2)} GiB`}function x(e){return e?new Date(e).toISOString().replace("T"," ").slice(0,16)+" UTC":"never"}async function Be(e){const t=e[0],n=e.slice(1);try{switch(t){case void 0:case"help":case"--help":case"-h":return de();case"login":return await ue(n);case"logout":return await ge();case"status":return await me(n);case"doctor":return pe();case"devices":return await fe(n);case"sync":return await $e(n);case"daemon":return await _e(n);case"export":return await Se(n);case"delete":return await be(n);case"recovery":return await xe(n);default:console.error(`Unknown subcommand: wyrm cloud ${t}`),console.error("Try `wyrm cloud help`"),process.exit(1)}}catch(o){if(o instanceof ee&&(console.error(o.message),process.exit(oe)),o instanceof V&&process.exit(1),o instanceof f)o.status===401?console.error("\u2718 Not authenticated. Run `wyrm cloud login`."):o.status===403?console.error(`\u2718 Forbidden: ${o.message}`):o.status===0?(console.error(`\u2718 ${o.message}`),console.error(" Check your internet connection. If wyrm.ghosts.lk is unreachable, see status at https://www.cloudflarestatus.com")):o.status===501?console.error(`\u2718 Service not configured: ${o.message}`):console.error(`\u2718 ${o.message} (HTTP ${o.status})`);else if(o instanceof Error){const r=o.message;r.includes("Not logged in")?console.error("\u2718 Not logged in. Run `wyrm cloud login`."):r.includes("Wyrm Cloud key")?console.error(`\u2718 Encryption-key error: ${r}`):console.error(`\u2718 ${r}`)}else console.error("\u2718 Unexpected error:",o);process.exit(1)}}function de(){console.log(`\u{F115D} wyrm cloud: sync your Wyrm memory across devices
2
2
 
3
3
  USAGE:
4
4
  wyrm cloud <subcommand> [args]
@@ -50,6 +50,6 @@ CONSTITUTION:
50
50
 
51
51
  DOMAIN:
52
52
  https://wyrm.ghosts.lk
53
- `)}async function ue(e){const t=y();if(t)try{await new g(t.base,t.session).me(),console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)}catch(i){i instanceof f&&i.status===401||(console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)),console.log("Previous session expired; starting a fresh login."),_()}const n=new g(v),o=R(32).toString("hex");let r;try{r=await n.cliInit(o)}catch(i){console.error(`\u2718 Could not start login: ${i instanceof Error?i.message:i}`),process.exit(1)}console.log(""),console.log("\u{F115D} Sign in to Wyrm Cloud"),console.log(""),console.log(" 1. Open this URL on any device:"),console.log(` ${r.browser_url}`),console.log(""),console.log(" 2. Type this code when prompted:"),console.log(` ${r.code}`),console.log(""),console.log(" 3. Sign in with Google or GitHub."),console.log(""),console.log(` Waiting (expires in ${Math.round(r.expires_in_sec/60)} min)\u2026`);const c=Date.now()+r.expires_in_sec*1e3;let l,a;for(;Date.now()<c;){await new Promise(i=>{setTimeout(i,3e3)});try{const i=await n.cliPoll(o);if(i.ready&&i.session){l=i.session,a=i.account_id;break}}catch(i){console.error(`
53
+ `)}async function ue(e){const t=y();if(t)try{await new g(t.base,t.session).me(),console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)}catch(i){i instanceof f&&i.status===401||(console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)),console.log("Previous session expired; starting a fresh login."),k()}const n=new g(v),o=R(32).toString("hex");let r;try{r=await n.cliInit(o)}catch(i){console.error(`\u2718 Could not start login: ${i instanceof Error?i.message:i}`),process.exit(1)}console.log(""),console.log("\u{F115D} Sign in to Wyrm Cloud"),console.log(""),console.log(" 1. Open this URL on any device:"),console.log(` ${r.browser_url}`),console.log(""),console.log(" 2. Type this code when prompted:"),console.log(` ${r.code}`),console.log(""),console.log(" 3. Sign in with Google or GitHub."),console.log(""),console.log(` Waiting (expires in ${Math.round(r.expires_in_sec/60)} min)\u2026`);const c=Date.now()+r.expires_in_sec*1e3;let l,a;for(;Date.now()<c;){await new Promise(i=>{setTimeout(i,3e3)});try{const i=await n.cliPoll(o);if(i.ready&&i.session){l=i.session,a=i.account_id;break}}catch(i){console.error(`
54
54
  \u2718 Login failed: ${i instanceof Error?i.message:i}`),process.exit(1)}}(!l||!a)&&(console.error("\n\u2718 Login timed out. Run `wyrm cloud login` again."),process.exit(1)),C({base:v,session:l,account_id:a,created_at:Date.now()});const d=new g(v,l);let u="";try{u=(await d.me()).account.email}catch{}const h=`${F()} (${process.platform})`;let p;try{p=(await d.registerDevice(h,void 0,K())).device.id;const w=y();w&&C({...w,email:u,device_id:p,device_name:h,machine_fp:I()})}catch(i){console.error(`
55
- \u26A0 Logged in but could not register device: ${i instanceof Error?i.message:i}`),console.error(" Re-run `wyrm cloud login` to retry.");return}console.log(""),console.log(`\u2713 Signed in as ${u}`),console.log(`\u2713 Device registered: ${h}`),console.log(`\u2713 Session saved to ${$}`);const L=!k();if(Y(),L?(console.log(`\u2713 Encryption key generated at ${m()} (0600)`),console.log(""),console.log(" \u26A0 Back up the key file. Losing it means losing access to your synced data."),console.log(" The Wyrm Cloud server CANNOT recover it; that's the operator-owns-data"),console.log(" guarantee. Run `wyrm cloud recovery show` now to get a 24-word phrase,"),console.log(" or copy the key file to a password manager / encrypted backup.")):console.log(`\u2713 Encryption key reused from ${m()}`),p)try{const i=await d.syncStatus();if(i.deltas>0){const E=(await d.syncPull(p,0,1)).deltas[0];if(E){let T=!0;try{J(E.payload_b64)}catch{T=!1}T||(console.log(""),console.log(" \u26A0 THIS DEVICE CANNOT READ THE ACCOUNT'S DATA YET"),console.log(` Login succeeded, but the key at ${m()} cannot decrypt`),console.log(` the ${i.deltas} delta(s) already on this account. They were encrypted`),console.log(" with a different master key (e.g. this is an org account whose other"),console.log(" devices hold the shared key). Until the keys match, sync will move"),console.log(" 0 rows in BOTH directions: a connected pipe that carries nothing."),console.log(""),console.log(" Fix: adopt the account key on this device by running"),console.log(" wyrm cloud recovery restore (needs the account's 24-word phrase)"),console.log(` Heads-up: restore OVERWRITES ${m()}. If this device also has`),console.log(" its OWN separate cloud data, back that key up first, or run the org"),console.log(" sync under a separate WYRM home so both keys coexist."))}}}catch{}console.log(""),console.log("Next: `wyrm cloud sync` to push your memory.")}async function ge(){const e=y();if(!e){console.log("Not logged in.");return}try{await new g(e.base,e.session).logout(),console.log("\u2713 Session revoked server-side.")}catch(t){console.error(`\u26A0 Could not revoke server-side: ${t instanceof Error?t.message:t}`),console.error(" Local session cleared anyway.")}_(),console.log(`\u2713 Local session removed (${$}).`),console.log(" Note: ~/.wyrm/cloud.key kept. Delete manually if you want a clean slate.")}function D(e){const t=new se(ne());try{const n=X(t,{all:e}),o=Q(t.getDatabase());for(const r of n.errors)console.error(`\u26A0 pending count: ${r}`);return{...n,last_push_at:o.last_push_at,last_push_attempt_at:o.last_push_attempt_at,last_pull_at:o.last_pull_at}}finally{try{t.close()}catch{}}}const N="Session expired or invalid. Run `wyrm cloud login` again.";function O(e){const t=e?.message,n=typeof t=="string"?t:String(e),o=M();return te(o&&o!=="/"?n.split(o).join("~"):n)}async function me(e){const t=e.includes("--json"),n=e.includes("--all"),o=y();if(!o){if(t){console.log(JSON.stringify({logged_in:!1})),process.exitCode=1;return}console.log("Not logged in. Run `wyrm cloud login`.");return}if(t)return ye(o,n);let r;try{const c=D(n);r=`${c.rows} row(s), ${c.tombstones} tombstone(s) not yet pushed`}catch(c){r=`unknown (${O(c)})`}const s=new g(o.base,o.session);try{const c=await s.me(),l=await s.syncStatus();console.log(""),console.log(`\u{F115D} Wyrm Cloud: ${c.account.email}`),console.log(""),console.log(` Tier: ${l.tier}`),console.log(` Storage: ${b(l.storage.used_bytes)} / ${b(l.storage.limit_bytes)} (${l.storage.percent}%)`),console.log(` Deltas: ${l.deltas}`),console.log(` Devices: ${l.devices}`),console.log(` Pending: ${r}`),console.log(` Providers:${c.identities.map(a=>" "+a.provider).join(",")}`),console.log(""),console.log(` This machine: ${o.device_name??"(not registered)"}`),console.log(` Device ID: ${o.device_id?o.device_id.slice(0,8)+"\u2026":"(none)"}`),console.log(` Session age: ${Math.round((Date.now()-o.created_at)/(1440*60*1e3))} day(s)`),P(o),console.log(""),k()?l.deltas>0&&(console.log(` Key: ${m()} (0600)`),console.log(` \u26A0 Back this file up. Losing it = losing access to your ${l.deltas} deltas.`),console.log("")):(console.log(" \u26A0 ENCRYPTION KEY MISSING"),console.log(` Expected at: ${m()}`),console.log(" Without this file, deltas already pushed cannot be decrypted."),console.log(" If you have a backup, restore it before running sync."),console.log(""))}catch(c){throw c instanceof f&&c.status===401&&(console.error(N),process.exit(1)),c}}async function ye(e,t){const n=e.device_id?e.device_id.slice(0,8):null;let o;try{o=D(t)}catch(s){console.log(JSON.stringify({logged_in:!0,device:n,error:`store: ${O(s)}`})),process.exitCode=2;return}let r;try{const s=await new g(e.base,e.session).syncStatus();r={ok:!0,tier:s.tier,deltas:s.deltas,devices:s.devices}}catch(s){r={ok:!1,error:s instanceof f&&s.status===401?N:s instanceof Error?s.message:String(s)}}console.log(JSON.stringify({logged_in:!0,device:n,push:{mark_ms:o.mark_ms,mark_iso:o.mark_ms>0?new Date(o.mark_ms).toISOString():null,last_push_at:o.last_push_at,last_push_attempt_at:o.last_push_attempt_at,pending_rows:o.rows,pending_tombstones:o.tombstones,mode:t?"all":"default"},pull:{last_pull_at:o.last_pull_at},remote:r}))}function P(e){const t=q(e.machine_fp);t.state==="match"?console.log(" Identity: \u2713 machine fingerprint matches (not a copied session)"):t.state==="adopt"?console.log(" Identity: no fingerprint yet (pre-7.0.3 session; adopted on next sync)"):(console.log(" Identity: \u26A0 FINGERPRINT MISMATCH: this session looks COPIED"),console.log(` stored ${t.stored.slice(0,12)}\u2026 vs this machine ${t.current.slice(0,12)}\u2026`),console.log(" device_id collision \u2192 cross-device pull returns 0 silently."),console.log(" Fix: rm ~/.wyrm/cloud.json ~/.wyrm/cloud-cursor.json (KEEP cloud.key),"),console.log(" then `wyrm cloud login`. (Or `wyrm cloud sync --force` if intended.)"))}function pe(){const e=y();if(console.log(""),console.log("\u{F115D} Wyrm Cloud: device identity doctor"),console.log(""),!e){console.log(" Not logged in. Run `wyrm cloud login`."),console.log("");return}console.log(` Account: ${e.email??e.account_id.slice(0,8)+"\u2026"}`),console.log(` Device ID: ${e.device_id?e.device_id.slice(0,8)+"\u2026":"(none; re-run `wyrm cloud login`)"}`),console.log(` Server: ${e.base}`),console.log(` Stored fp: ${e.machine_fp?e.machine_fp.slice(0,12)+"\u2026":"(none, pre-7.0.3 session)"}`),console.log(` This box fp: ${I().slice(0,12)}\u2026`),P(e),console.log(""),console.log(" Only ~/.wyrm/cloud.key is meant to be shared across your machines."),console.log(" cloud.json + cloud-cursor.json + machine-id are per-device."),console.log("")}async function fe(e){const t=e[0],n=g.fromSession();if(t==="revoke"){const l=e[1];l||(console.error("Usage: wyrm cloud devices revoke <device-id>"),process.exit(1));const a=await he(n,l);await n.revokeDevice(a),console.log(`\u2713 Device ${a.slice(0,8)}\u2026 revoked.`);return}const o=e.includes("--full"),{devices:r}=await n.listDevices(),c=y()?.device_id;console.log(""),console.log(`\u{F115D} Devices (${r.length})`),console.log("");for(const l of r){const a=l.id===c?"\u2605":" ",d=l.revoked?"(revoked)":"",u=o?l.id:`${l.id.slice(0,8)}\u2026`;console.log(` ${a} ${u} ${l.name.padEnd(30)} last_seen=${x(l.last_seen_at)} ${d}`)}console.log(""),console.log(" \u2605 = this machine"),console.log(" Revoke: wyrm cloud devices revoke <device-id> (an id prefix as shown above is fine)"),o||console.log(" Full ids: wyrm cloud devices --full"),console.log("")}async function he(e,t){const n=t.replace(/[….]+$/,"").trim().toLowerCase(),{devices:o}=await e.listDevices(),r=o.find(c=>c.id.toLowerCase()===n);if(r)return r.id;const s=o.filter(c=>c.id.toLowerCase().startsWith(n));if(s.length===1)return s[0].id;s.length===0&&(console.error(`\u2718 No device matches "${t}". List them with: wyrm cloud devices`),process.exit(1)),console.error(`\u2718 "${t}" is ambiguous; it matches ${s.length} devices:`);for(const c of s)console.error(` ${c.id} ${c.name}`);console.error(" Re-run with more characters, or the full id."),process.exit(1)}const we=new Set(["--dry-run","--all","--force","--since"]);function ve(e){for(let t=0;t<e.length;t++){const n=e[t];if(n==="--since"){t++;continue}if(!(n.startsWith("--since=")||we.has(n)))return n}}async function $e(e){const t=ve(e);if(t!==void 0){console.error(`\u2718 Unknown flag for \`wyrm cloud sync\`: ${t}`),console.error(" It takes --dry-run, --all, --force and --since <when>. See `wyrm cloud help`."),process.exitCode=1;return}let n;const o=e.findIndex(d=>d==="--since"||d.startsWith("--since="));if(o>=0){const d=e[o];try{n=Z(d==="--since"?e[o+1]??"":d.slice(8))}catch(u){console.error(`\u2718 ${u instanceof Error?u.message:u}`),process.exitCode=1;return}}const r=e.includes("--dry-run"),s=e.includes("--all"),c=e.includes("--force");S(),k()||(console.error("\u26A0 Encryption key not found at",m()),console.error(" A new key will be generated, but it will NOT decrypt deltas"),console.error(" pushed by other devices using a different key. If you have a backup,"),console.error(" restore it to ~/.wyrm/cloud.key (0600) before running sync."),console.error(" Continuing in 5 seconds. Press Ctrl+C to abort."),await new Promise(d=>{setTimeout(d,5e3)}));const a=await z({dryRun:r,all:s,force:c,sinceMs:n,onStart:()=>{s&&(console.log("\u{1F310} --all mode: syncing every semantic table (ignoring visibility flags)."),console.log(" Skipped: per-device logs, FTS shadows, sync internals."),console.log("")),n!==void 0&&console.log(` --since ${new Date(n).toISOString()}: rows changed at or after it are collected, below the push mark too.`)}});if(console.log(""),console.log(a.errors.length>0?"\u{F115D} Sync finished with errors":"\u{F115D} Sync complete"),console.log(""),console.log(` Pushed: ${a.pushed} row(s)${r?" (dry run)":""}`),console.log(` Pulled: ${a.pulled} row(s)`),console.log(` Deleted: ${a.deleted_local} row(s) (peer tombstones)`),a.quarantined&&a.quarantined>0&&console.log(` Quarantined: ${a.quarantined} undecryptable delta(s) set aside (see errors)`),a.errors.length>0){console.log(""),console.log(" Errors:");for(const d of a.errors)console.log(` - ${d}`);process.exitCode=1}console.log("")}function _e(){const e=U(B(G(import.meta.url)),"sync-daemon-entrypoint.js");return new re(e)}async function ke(e){S();const t=e[0]??"status",n=e.find(s=>s.startsWith("--interval="));let o;if(n){const s=Number(n.split("=")[1]);(!Number.isFinite(s)||s<=0)&&(console.error("\u2716 --interval= expects a positive number of minutes, got "+JSON.stringify(n)),process.exit(1)),o=s}const r=_e();switch(t){case"start":{y()||(console.error("\u2718 Not logged in. Run `wyrm cloud login` first."),process.exit(1));const s=r.start({interval_minutes:o});s.ok||(console.error(`\u{F115D} sovereign-sync daemon: ${s.reason??"failed to start"}${s.pid?` (pid ${s.pid})`:""}`),process.exit(s.pid?0:1)),console.log(`\u{F115D} \u2713 sovereign-sync daemon started (pid ${s.pid}). Logs: ~/.wyrm/wyrm-sovereign-sync.log`);return}case"stop":{const s=r.stop();console.log(s.ok?"\u{F115D} \u2713 sovereign-sync daemon stopped":`\u{F115D} sovereign-sync daemon: ${s.reason??"failed to stop"}`);return}case"restart":{const s=ce(o,r.status().state?.interval_ms);r.stop(),await new Promise(l=>{setTimeout(l,500)});const c=r.start({interval_minutes:s});console.log(c.ok?`\u{F115D} \u2713 sovereign-sync daemon restarted (pid ${c.pid}, every ${s} min)`:`\u{F115D} restart failed: ${c.reason??"unknown"}`);return}case"status":{const s=r.status();console.log("\u{F115D} Sovereign-sync daemon"),console.log(` Running: ${s.running?`\u2713 yes (pid ${s.pid})`:"\u2717 no"}`),s.state?.interval_ms&&console.log(` Interval: every ${s.state.interval_ms/6e4} min`),s.state?.started_ts&&console.log(` Started: ${x(s.state.started_ts)}`),s.state?.last_tick_ts&&(console.log(` Last tick: ${x(s.state.last_tick_ts)} (exit ${s.state.last_tick_exit??"n/a"})`),s.state.last_tick_summary&&console.log(` Last result: ${s.state.last_tick_summary}`));return}default:console.error(`Unknown daemon action: ${t}. Use: start, stop, restart, status`),process.exit(1)}}async function Se(e){S();const t=g.fromSession(),n=e.find(c=>!c.startsWith("-")),o=j(n??`wyrm-cloud-export-${new Date().toISOString().slice(0,10)}.json`);console.log(" Fetching account export\u2026");const r=await t.accountExport(),s=JSON.stringify(r,null,2);W(o,s,{mode:384}),console.log(""),console.log(`\u2713 Exported to ${o}`),console.log(""),console.log(` Account: ${r.account.email} (${r.account.id.slice(0,8)}\u2026)`),console.log(` Devices: ${r.devices.length}`),console.log(` Identities: ${r.identities.length}`),console.log(` Orgs: ${r.orgs.length}`),console.log(` Deltas: ${r.deltas.length}`),console.log(` Size: ${b(s.length)}`),console.log(""),console.log(" Deltas are still AES-256-GCM ciphertext. To decrypt them you"),console.log(` need the key at ${m()}. Back that up alongside this file.`),console.log("")}async function be(e){e.includes("--confirm")||(console.error("\u2718 This permanently deletes your Wyrm Cloud account."),console.error(" Re-run with --confirm to proceed:"),console.error(" wyrm cloud delete --confirm"),process.exit(1));const n=y();n||(console.error("\u2718 Not logged in. Nothing to delete."),process.exit(1)),console.log(""),console.log("\u26A0 You are about to PERMANENTLY DELETE your Wyrm Cloud account."),console.log(""),console.log(` Account: ${n.email??n.account_id}`),console.log(` Server: ${n.base}`),console.log(""),console.log(" This wipes all encrypted blobs, devices, identities, and org"),console.log(" memberships you own. The local ~/.wyrm/cloud.key is kept so"),console.log(" any backups remain decryptable. This action CANNOT be undone."),console.log(""),(await A(' Type "DELETE my account" to confirm: ')).trim()!=="DELETE my account"&&(console.error("\u2718 Confirmation phrase did not match. Aborting."),process.exit(1)),await new g(n.base,n.session).accountDelete(),_(),console.log(""),console.log("\u2713 Account deleted on server."),console.log(`\u2713 Local session removed (${$}).`),console.log(` Kept: ${m()} (in case you need to decrypt an old export).`),console.log("")}function A(e){return new Promise(t=>{const n=H({input:process.stdin,output:process.stdout});n.question(e,o=>{n.close(),t(o)})})}async function xe(e){const t=e[0];if(t==="show"){const{keyToMnemonic:n}=await import("./recovery.js"),r=n().split(" ");console.log(""),console.log("\u{1F511} Wyrm Cloud recovery phrase (BIP39, 24 words)"),console.log("");for(let s=0;s<4;s++){const c=r.slice(s*6,s*6+6).map((l,a)=>`${String(s*6+a+1).padStart(2)}. ${l.padEnd(10)}`).join(" ");console.log(` ${c}`)}console.log(""),console.log(" Write these down on PAPER and keep them somewhere safe."),console.log(" Anyone with this phrase can decrypt your synced Wyrm memory."),console.log(" Wyrm Cloud has NO COPY of this. Lose it = lose your data."),console.log("");return}if(t==="restore"){const n=e.includes("--overwrite");console.log(""),console.log("\u{1F511} Restore master key from BIP39 recovery phrase"),console.log(""),console.log(" Enter your 24 words separated by spaces (case-insensitive)."),console.log(" Press Enter when done."),console.log("");const o=await A(" > "),{mnemonicToKey:r}=await import("./recovery.js"),{path:s,overwrote:c}=r(o,{overwrite:n});console.log(""),console.log(`\u2713 Master key restored to ${s} (0600)`),c&&console.log(" Replaced existing key (you passed --overwrite)."),console.log(" Run `wyrm cloud sync` to pull deltas with the restored key."),console.log("");return}console.error("Usage:"),console.error(" wyrm cloud recovery show"),console.error(" wyrm cloud recovery restore [--overwrite]"),process.exit(1)}export{Be as cmdCloud};
55
+ \u26A0 Logged in but could not register device: ${i instanceof Error?i.message:i}`),console.error(" Re-run `wyrm cloud login` to retry.");return}console.log(""),console.log(`\u2713 Signed in as ${u}`),console.log(`\u2713 Device registered: ${h}`),console.log(`\u2713 Session saved to ${$}`);const L=!_();if(Y(),L?(console.log(`\u2713 Encryption key generated at ${m()} (0600)`),console.log(""),console.log(" \u26A0 Back up the key file. Losing it means losing access to your synced data."),console.log(" The Wyrm Cloud server CANNOT recover it; that's the operator-owns-data"),console.log(" guarantee. Run `wyrm cloud recovery show` now to get a 24-word phrase,"),console.log(" or copy the key file to a password manager / encrypted backup.")):console.log(`\u2713 Encryption key reused from ${m()}`),p)try{const i=await d.syncStatus();if(i.deltas>0){const E=(await d.syncPull(p,0,1)).deltas[0];if(E){let T=!0;try{J(E.payload_b64)}catch{T=!1}T||(console.log(""),console.log(" \u26A0 THIS DEVICE CANNOT READ THE ACCOUNT'S DATA YET"),console.log(` Login succeeded, but the key at ${m()} cannot decrypt`),console.log(` the ${i.deltas} delta(s) already on this account. They were encrypted`),console.log(" with a different master key (e.g. this is an org account whose other"),console.log(" devices hold the shared key). Until the keys match, sync will move"),console.log(" 0 rows in BOTH directions: a connected pipe that carries nothing."),console.log(""),console.log(" Fix: adopt the account key on this device by running"),console.log(" wyrm cloud recovery restore (needs the account's 24-word phrase)"),console.log(` Heads-up: restore OVERWRITES ${m()}. If this device also has`),console.log(" its OWN separate cloud data, back that key up first, or run the org"),console.log(" sync under a separate WYRM home so both keys coexist."))}}}catch{}console.log(""),console.log("Next: `wyrm cloud sync` to push your memory.")}async function ge(){const e=y();if(!e){console.log("Not logged in.");return}try{await new g(e.base,e.session).logout(),console.log("\u2713 Session revoked server-side.")}catch(t){console.error(`\u26A0 Could not revoke server-side: ${t instanceof Error?t.message:t}`),console.error(" Local session cleared anyway.")}k(),console.log(`\u2713 Local session removed (${$}).`),console.log(" Note: ~/.wyrm/cloud.key kept. Delete manually if you want a clean slate.")}function D(e){const t=new se(ne());try{const n=X(t,{all:e}),o=Q(t.getDatabase());for(const r of n.errors)console.error(`\u26A0 pending count: ${r}`);return{...n,last_push_at:o.last_push_at,last_push_attempt_at:o.last_push_attempt_at,last_pull_at:o.last_pull_at}}finally{try{t.close()}catch{}}}const N="Session expired or invalid. Run `wyrm cloud login` again.";function O(e){const t=e?.message,n=typeof t=="string"?t:String(e),o=M();return te(o&&o!=="/"?n.split(o).join("~"):n)}async function me(e){const t=e.includes("--json"),n=e.includes("--all"),o=y();if(!o){if(t){console.log(JSON.stringify({logged_in:!1})),process.exitCode=1;return}console.log("Not logged in. Run `wyrm cloud login`.");return}if(t)return ye(o,n);let r;try{const c=D(n);r=c.refused?`none: sync is refused for this store. ${c.refused}`:`${c.rows} row(s), ${c.tombstones} tombstone(s) not yet pushed`}catch(c){r=`unknown (${O(c)})`}const s=new g(o.base,o.session);try{const c=await s.me(),l=await s.syncStatus();console.log(""),console.log(`\u{F115D} Wyrm Cloud: ${c.account.email}`),console.log(""),console.log(` Tier: ${l.tier}`),console.log(` Storage: ${b(l.storage.used_bytes)} / ${b(l.storage.limit_bytes)} (${l.storage.percent}%)`),console.log(` Deltas: ${l.deltas}`),console.log(` Devices: ${l.devices}`),console.log(` Pending: ${r}`),console.log(` Providers:${c.identities.map(a=>" "+a.provider).join(",")}`),console.log(""),console.log(` This machine: ${o.device_name??"(not registered)"}`),console.log(` Device ID: ${o.device_id?o.device_id.slice(0,8)+"\u2026":"(none)"}`),console.log(` Session age: ${Math.round((Date.now()-o.created_at)/(1440*60*1e3))} day(s)`),P(o),console.log(""),_()?l.deltas>0&&(console.log(` Key: ${m()} (0600)`),console.log(` \u26A0 Back this file up. Losing it = losing access to your ${l.deltas} deltas.`),console.log("")):(console.log(" \u26A0 ENCRYPTION KEY MISSING"),console.log(` Expected at: ${m()}`),console.log(" Without this file, deltas already pushed cannot be decrypted."),console.log(" If you have a backup, restore it before running sync."),console.log(""))}catch(c){throw c instanceof f&&c.status===401&&(console.error(N),process.exit(1)),c}}async function ye(e,t){const n=e.device_id?e.device_id.slice(0,8):null;let o;try{o=D(t)}catch(s){console.log(JSON.stringify({logged_in:!0,device:n,error:`store: ${O(s)}`})),process.exitCode=2;return}let r;try{const s=await new g(e.base,e.session).syncStatus();r={ok:!0,tier:s.tier,deltas:s.deltas,devices:s.devices}}catch(s){r={ok:!1,error:s instanceof f&&s.status===401?N:s instanceof Error?s.message:String(s)}}console.log(JSON.stringify({logged_in:!0,device:n,push:{mark_ms:o.mark_ms,mark_iso:o.mark_ms>0?new Date(o.mark_ms).toISOString():null,last_push_at:o.last_push_at,last_push_attempt_at:o.last_push_attempt_at,pending_rows:o.rows,pending_tombstones:o.tombstones,...o.refused?{refused:o.refused}:{},mode:t?"all":"default"},pull:{last_pull_at:o.last_pull_at},remote:r}))}function P(e){const t=q(e.machine_fp);t.state==="match"?console.log(" Identity: \u2713 machine fingerprint matches (not a copied session)"):t.state==="adopt"?console.log(" Identity: no fingerprint yet (pre-7.0.3 session; adopted on next sync)"):(console.log(" Identity: \u26A0 FINGERPRINT MISMATCH: this session looks COPIED"),console.log(` stored ${t.stored.slice(0,12)}\u2026 vs this machine ${t.current.slice(0,12)}\u2026`),console.log(" device_id collision \u2192 cross-device pull returns 0 silently."),console.log(" Fix: rm ~/.wyrm/cloud.json ~/.wyrm/cloud-cursor.json (KEEP cloud.key),"),console.log(" then `wyrm cloud login`. (Or `wyrm cloud sync --force` if intended.)"))}function pe(){const e=y();if(console.log(""),console.log("\u{F115D} Wyrm Cloud: device identity doctor"),console.log(""),!e){console.log(" Not logged in. Run `wyrm cloud login`."),console.log("");return}console.log(` Account: ${e.email??e.account_id.slice(0,8)+"\u2026"}`),console.log(` Device ID: ${e.device_id?e.device_id.slice(0,8)+"\u2026":"(none; re-run `wyrm cloud login`)"}`),console.log(` Server: ${e.base}`),console.log(` Stored fp: ${e.machine_fp?e.machine_fp.slice(0,12)+"\u2026":"(none, pre-7.0.3 session)"}`),console.log(` This box fp: ${I().slice(0,12)}\u2026`),P(e),console.log(""),console.log(" Only ~/.wyrm/cloud.key is meant to be shared across your machines."),console.log(" cloud.json + cloud-cursor.json + machine-id are per-device."),console.log("")}async function fe(e){const t=e[0],n=g.fromSession();if(t==="revoke"){const l=e[1];l||(console.error("Usage: wyrm cloud devices revoke <device-id>"),process.exit(1));const a=await he(n,l);await n.revokeDevice(a),console.log(`\u2713 Device ${a.slice(0,8)}\u2026 revoked.`);return}const o=e.includes("--full"),{devices:r}=await n.listDevices(),c=y()?.device_id;console.log(""),console.log(`\u{F115D} Devices (${r.length})`),console.log("");for(const l of r){const a=l.id===c?"\u2605":" ",d=l.revoked?"(revoked)":"",u=o?l.id:`${l.id.slice(0,8)}\u2026`;console.log(` ${a} ${u} ${l.name.padEnd(30)} last_seen=${x(l.last_seen_at)} ${d}`)}console.log(""),console.log(" \u2605 = this machine"),console.log(" Revoke: wyrm cloud devices revoke <device-id> (an id prefix as shown above is fine)"),o||console.log(" Full ids: wyrm cloud devices --full"),console.log("")}async function he(e,t){const n=t.replace(/[….]+$/,"").trim().toLowerCase(),{devices:o}=await e.listDevices(),r=o.find(c=>c.id.toLowerCase()===n);if(r)return r.id;const s=o.filter(c=>c.id.toLowerCase().startsWith(n));if(s.length===1)return s[0].id;s.length===0&&(console.error(`\u2718 No device matches "${t}". List them with: wyrm cloud devices`),process.exit(1)),console.error(`\u2718 "${t}" is ambiguous; it matches ${s.length} devices:`);for(const c of s)console.error(` ${c.id} ${c.name}`);console.error(" Re-run with more characters, or the full id."),process.exit(1)}const we=new Set(["--dry-run","--all","--force","--since"]);function ve(e){for(let t=0;t<e.length;t++){const n=e[t];if(n==="--since"){t++;continue}if(!(n.startsWith("--since=")||we.has(n)))return n}}async function $e(e){const t=ve(e);if(t!==void 0){console.error(`\u2718 Unknown flag for \`wyrm cloud sync\`: ${t}`),console.error(" It takes --dry-run, --all, --force and --since <when>. See `wyrm cloud help`."),process.exitCode=1;return}let n;const o=e.findIndex(d=>d==="--since"||d.startsWith("--since="));if(o>=0){const d=e[o];try{n=Z(d==="--since"?e[o+1]??"":d.slice(8))}catch(u){console.error(`\u2718 ${u instanceof Error?u.message:u}`),process.exitCode=1;return}}const r=e.includes("--dry-run"),s=e.includes("--all"),c=e.includes("--force");S(),_()||(console.error("\u26A0 Encryption key not found at",m()),console.error(" A new key will be generated, but it will NOT decrypt deltas"),console.error(" pushed by other devices using a different key. If you have a backup,"),console.error(" restore it to ~/.wyrm/cloud.key (0600) before running sync."),console.error(" Continuing in 5 seconds. Press Ctrl+C to abort."),await new Promise(d=>{setTimeout(d,5e3)}));const a=await z({dryRun:r,all:s,force:c,sinceMs:n,onStart:()=>{s&&(console.log("\u{1F310} --all mode: syncing every semantic table (ignoring visibility flags)."),console.log(" Skipped: per-device logs, FTS shadows, sync internals."),console.log("")),n!==void 0&&console.log(` --since ${new Date(n).toISOString()}: rows changed at or after it are collected, below the push mark too.`)}});if(console.log(""),console.log(a.errors.length>0?"\u{F115D} Sync finished with errors":"\u{F115D} Sync complete"),console.log(""),console.log(` Pushed: ${a.pushed} row(s)${r?" (dry run)":""}`),console.log(` Pulled: ${a.pulled} row(s)`),console.log(` Deleted: ${a.deleted_local} row(s) (peer tombstones)`),a.quarantined&&a.quarantined>0&&console.log(` Quarantined: ${a.quarantined} undecryptable delta(s) set aside (see errors)`),a.skipped_tables&&a.skipped_tables.length>0&&console.log(` Skipped tables this Wyrm does not know: ${a.skipped_tables.join(", ")} (not sent; a newer Wyrm syncs them)`),a.errors.length>0){console.log(""),console.log(" Errors:");for(const d of a.errors)console.log(` - ${d}`);process.exitCode=1}console.log("")}function ke(){const e=U(B(G(import.meta.url)),"sync-daemon-entrypoint.js");return new re(e)}async function _e(e){S();const t=e[0]??"status",n=e.find(s=>s.startsWith("--interval="));let o;if(n){const s=Number(n.split("=")[1]);(!Number.isFinite(s)||s<=0)&&(console.error("\u2716 --interval= expects a positive number of minutes, got "+JSON.stringify(n)),process.exit(1)),o=s}const r=ke();switch(t){case"start":{y()||(console.error("\u2718 Not logged in. Run `wyrm cloud login` first."),process.exit(1));const s=r.start({interval_minutes:o});s.ok||(console.error(`\u{F115D} sovereign-sync daemon: ${s.reason??"failed to start"}${s.pid?` (pid ${s.pid})`:""}`),process.exit(s.pid?0:1)),console.log(`\u{F115D} \u2713 sovereign-sync daemon started (pid ${s.pid}). Logs: ~/.wyrm/wyrm-sovereign-sync.log`);return}case"stop":{const s=r.stop();console.log(s.ok?"\u{F115D} \u2713 sovereign-sync daemon stopped":`\u{F115D} sovereign-sync daemon: ${s.reason??"failed to stop"}`);return}case"restart":{const s=ce(o,r.status().state?.interval_ms);r.stop(),await new Promise(l=>{setTimeout(l,500)});const c=r.start({interval_minutes:s});console.log(c.ok?`\u{F115D} \u2713 sovereign-sync daemon restarted (pid ${c.pid}, every ${s} min)`:`\u{F115D} restart failed: ${c.reason??"unknown"}`);return}case"status":{const s=r.status();console.log("\u{F115D} Sovereign-sync daemon"),console.log(` Running: ${s.running?`\u2713 yes (pid ${s.pid})`:"\u2717 no"}`),s.state?.interval_ms&&console.log(` Interval: every ${s.state.interval_ms/6e4} min`),s.state?.started_ts&&console.log(` Started: ${x(s.state.started_ts)}`),s.state?.last_tick_ts&&(console.log(` Last tick: ${x(s.state.last_tick_ts)} (exit ${s.state.last_tick_exit??"n/a"})`),s.state.last_tick_summary&&console.log(` Last result: ${s.state.last_tick_summary}`));return}default:console.error(`Unknown daemon action: ${t}. Use: start, stop, restart, status`),process.exit(1)}}async function Se(e){S();const t=g.fromSession(),n=e.find(c=>!c.startsWith("-")),o=j(n??`wyrm-cloud-export-${new Date().toISOString().slice(0,10)}.json`);console.log(" Fetching account export\u2026");const r=await t.accountExport(),s=JSON.stringify(r,null,2);W(o,s,{mode:384}),console.log(""),console.log(`\u2713 Exported to ${o}`),console.log(""),console.log(` Account: ${r.account.email} (${r.account.id.slice(0,8)}\u2026)`),console.log(` Devices: ${r.devices.length}`),console.log(` Identities: ${r.identities.length}`),console.log(` Orgs: ${r.orgs.length}`),console.log(` Deltas: ${r.deltas.length}`),console.log(` Size: ${b(s.length)}`),console.log(""),console.log(" Deltas are still AES-256-GCM ciphertext. To decrypt them you"),console.log(` need the key at ${m()}. Back that up alongside this file.`),console.log("")}async function be(e){e.includes("--confirm")||(console.error("\u2718 This permanently deletes your Wyrm Cloud account."),console.error(" Re-run with --confirm to proceed:"),console.error(" wyrm cloud delete --confirm"),process.exit(1));const n=y();n||(console.error("\u2718 Not logged in. Nothing to delete."),process.exit(1)),console.log(""),console.log("\u26A0 You are about to PERMANENTLY DELETE your Wyrm Cloud account."),console.log(""),console.log(` Account: ${n.email??n.account_id}`),console.log(` Server: ${n.base}`),console.log(""),console.log(" This wipes all encrypted blobs, devices, identities, and org"),console.log(" memberships you own. The local ~/.wyrm/cloud.key is kept so"),console.log(" any backups remain decryptable. This action CANNOT be undone."),console.log(""),(await A(' Type "DELETE my account" to confirm: ')).trim()!=="DELETE my account"&&(console.error("\u2718 Confirmation phrase did not match. Aborting."),process.exit(1)),await new g(n.base,n.session).accountDelete(),k(),console.log(""),console.log("\u2713 Account deleted on server."),console.log(`\u2713 Local session removed (${$}).`),console.log(` Kept: ${m()} (in case you need to decrypt an old export).`),console.log("")}function A(e){return new Promise(t=>{const n=H({input:process.stdin,output:process.stdout});n.question(e,o=>{n.close(),t(o)})})}async function xe(e){const t=e[0];if(t==="show"){const{keyToMnemonic:n}=await import("./recovery.js"),r=n().split(" ");console.log(""),console.log("\u{1F511} Wyrm Cloud recovery phrase (BIP39, 24 words)"),console.log("");for(let s=0;s<4;s++){const c=r.slice(s*6,s*6+6).map((l,a)=>`${String(s*6+a+1).padStart(2)}. ${l.padEnd(10)}`).join(" ");console.log(` ${c}`)}console.log(""),console.log(" Write these down on PAPER and keep them somewhere safe."),console.log(" Anyone with this phrase can decrypt your synced Wyrm memory."),console.log(" Wyrm Cloud has NO COPY of this. Lose it = lose your data."),console.log("");return}if(t==="restore"){const n=e.includes("--overwrite");console.log(""),console.log("\u{1F511} Restore master key from BIP39 recovery phrase"),console.log(""),console.log(" Enter your 24 words separated by spaces (case-insensitive)."),console.log(" Press Enter when done."),console.log("");const o=await A(" > "),{mnemonicToKey:r}=await import("./recovery.js"),{path:s,overwrote:c}=r(o,{overwrite:n});console.log(""),console.log(`\u2713 Master key restored to ${s} (0600)`),c&&console.log(" Replaced existing key (you passed --overwrite)."),console.log(" Run `wyrm cloud sync` to pull deltas with the restored key."),console.log("");return}console.error("Usage:"),console.error(" wyrm cloud recovery show"),console.error(" wyrm cloud recovery restore [--overwrite]"),process.exit(1)}export{Be as cmdCloud};
@@ -1,5 +1,5 @@
1
- import{readFileSync as te,writeFileSync as ne,existsSync as se}from"node:fs";import{join as re}from"node:path";import{createHash as P}from"node:crypto";import{WyrmDB as oe,resolveDbPath as ae}from"../database.js";import{getLineage as ie,getCursor as A,setCursor as le,importCursorFile as ce,bumpDeviceEpoch as ue,mirrorStamp as W}from"../lineage.js";import{CloudClient as de,CloudError as pe,loadSession as _e,saveSession as fe,resolveCloudDir as he}from"./client.js";import{encrypt as me,decrypt as ye}from"./crypto.js";import{classifySession as ge,computeMachineFp as Ee}from"./machine-id.js";import{redactInboundRow as C}from"../inbound-redact.js";import{acquireSyncLock as be}from"./sync-lock.js";function M(){return re(he(),"cloud-cursor.json")}const H=2;function Se(e,t,r,n){const o=e?{...e}:{kind:t.kind,row_id:t.row_id,attempts:0,quarantined:!1,last_error:r,first_ms:n,last_ms:n};o.attempts+=1,o.last_error=r,o.last_ms=n;const s=o.attempts>=H,a=s&&!o.quarantined;return s&&(o.quarantined=!0),{entry:o,action:s?"skip":"retry",newlyQuarantined:a}}const k=[{kind:"truth",table:"ground_truths",hasVisibility:!0},{kind:"memory_artifact",table:"memory_artifacts",hasVisibility:!0},{kind:"quest",table:"quests",hasVisibility:!0},{kind:"design_token",table:"design_tokens",hasVisibility:!0},{kind:"design_reference",table:"design_references",hasVisibility:!0},{kind:"skill",table:"skills",hasVisibility:!0}],we=new Set(["sessions","agent_actions","agent_presence","session_seen_artifacts","tool_call_log","llm_query_log","external_call_log","token_savings_log","cost_tracking","usage_events","audit_log","indexing_queue","vectors","symbol_index","update_check","sync_conflicts","sync_log","sync_tombstones","wyrm_cloud_sync_state","cloud_push_ledger","mcp_client_configs","watch_dirs","global_context","schema_versions","failure_patterns","data_lake","projects"]),Ne=/_fts(_config|_data|_docsize|_idx)?$/;function q(e){const t=e.getDatabase(),r=[...k],n=new Set(k.map(o=>o.table));try{const o=t.prepare(`SELECT name FROM sqlite_master
2
- WHERE type='table' AND name NOT LIKE 'sqlite_%'`).all();for(const s of o){const a=s.name;if(n.has(a)||we.has(a)||Ne.test(a)||!w.test(a))continue;const i=t.prepare(`PRAGMA table_info(${a})`).all();if(!i.some(c=>c.name==="id"))continue;const l=i.some(c=>c.name==="cross_project_visibility");r.push({kind:a,table:a,hasVisibility:l})}}catch{}return r}function ct(e){return e}function V(e,t){if(!w.test(t))return new Set;try{const n=e.getDatabase().prepare(`PRAGMA table_info(${t})`).all();return new Set(n.filter(o=>w.test(o.name)).map(o=>o.name))}catch{return new Set}}const w=/^[a-z_][a-z0-9_]*$/i;function Y(){const e=M();if(!se(e))return null;try{const t=JSON.parse(te(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Te(e){const t={pull_cursor:0,last_push_updated_ms:0,last_push_at:0,last_push_attempt_at:0,last_pull_at:0},r=ie(e),n=Y();let o=A(e,"cloud");if(!o){if(ce(e,"cloud",M()),o=A(e,"cloud"),!o){if(!n)return t;const{store:a,...i}=n;return{...t,...i}}return{...t,...o.value}}const s=n?.store;return n&&s&&s.device_id===r.deviceId&&s.epoch===r.epoch&&s.fingerprint===W(e).fingerprint&&Number(n.last_pull_at??0)>Number(o.value.last_pull_at??0)&&ue(e,"cloud-cursor.json is ahead of the database (restored in place)"),{...t,...o.value}}function G(e){let t;try{t=A(e,"cloud")?.value}catch{}if(!t){const n=Y();if(n){const{store:o,...s}=n;t=s}}const r=n=>Number.isFinite(Number(n))?Number(n):0;return{last_push_updated_ms:r(t?.last_push_updated_ms),last_push_at:r(t?.last_push_at),last_push_attempt_at:r(t?.last_push_attempt_at??t?.last_push_at),last_pull_at:r(t?.last_pull_at)}}function Ie(e,t){try{le(e,"cloud",t)}catch{}ne(M(),JSON.stringify({...t,store:W(e)},null,2),{mode:384})}function B(e){e.getDatabase().exec(`
1
+ import{readFileSync as oe,writeFileSync as ae,existsSync as ie}from"node:fs";import{join as ce}from"node:path";import{createHash as W}from"node:crypto";import{WyrmDB as le,resolveDbPath as ue}from"../database.js";import{getLineage as de,getCursor as A,setCursor as pe,importCursorFile as _e,bumpDeviceEpoch as fe,mirrorStamp as H}from"../lineage.js";import{CloudClient as he,CloudError as me,loadSession as ye,saveSession as ge,resolveCloudDir as Ee}from"./client.js";import{encrypt as we,decrypt as be}from"./crypto.js";import{classifySession as Se,computeMachineFp as Ne}from"./machine-id.js";import{redactInboundRow as C}from"../inbound-redact.js";import{acquireSyncLock as Te}from"./sync-lock.js";import{schemaSkew as q}from"../migrations.js";function M(){return ce(Ee(),"cloud-cursor.json")}const V=2;function ke(e,t,r,s){const o=e?{...e}:{kind:t.kind,row_id:t.row_id,attempts:0,quarantined:!1,last_error:r,first_ms:s,last_ms:s};o.attempts+=1,o.last_error=r,o.last_ms=s;const n=o.attempts>=V,c=n&&!o.quarantined;return n&&(o.quarantined=!0),{entry:o,action:n?"skip":"retry",newlyQuarantined:c}}const O=[{kind:"truth",table:"ground_truths",hasVisibility:!0},{kind:"memory_artifact",table:"memory_artifacts",hasVisibility:!0},{kind:"quest",table:"quests",hasVisibility:!0},{kind:"design_token",table:"design_tokens",hasVisibility:!0},{kind:"design_reference",table:"design_references",hasVisibility:!0},{kind:"skill",table:"skills",hasVisibility:!0}],Ie=new Set(["sessions","agent_actions","agent_presence","session_seen_artifacts","tool_call_log","llm_query_log","external_call_log","token_savings_log","cost_tracking","usage_events","audit_log","indexing_queue","vectors","symbol_index","update_check","sync_conflicts","sync_log","sync_tombstones","wyrm_cloud_sync_state","cloud_push_ledger","mcp_client_configs","watch_dirs","global_context","schema_versions","failure_patterns","data_lake","projects"]),Oe=new Set(["context","entities","entity_aliases","relationships","reasoning_scaffolds","decision_edges","goals","goal_iterations","specs","failure_blocks","routing_memory","failure_anchors","write_ledger","metrics_snapshots","threads","erasure_log","failure_pattern_history","review_sample","audit_checkpoints"]);class Y extends Error{constructor(t,r){super(`This store was upgraded by a newer Wyrm (schema v${t}; this Wyrm knows up to v${r}), so it was not synced: update Wyrm before syncing. Nothing was sent. Run \`wyrm update\`, then sync again.`),this.name="NewerStoreSyncError"}}function G(e){const t=q(e);if(t.storeIsNewer)throw new Y(t.store,t.binary)}const Re=/_fts(_config|_data|_docsize|_idx)?$/;function Le(e){return B(e).tables}function B(e){const t=e.getDatabase(),r=[...O],s=[],o=new Set(O.map(n=>n.table));try{const n=t.prepare(`SELECT name FROM sqlite_master
2
+ WHERE type='table' AND name NOT LIKE 'sqlite_%'`).all();for(const c of n){const a=c.name;if(o.has(a)||Ie.has(a)||Re.test(a)||!N.test(a))continue;const i=t.prepare(`PRAGMA table_info(${a})`).all();if(!i.some(p=>p.name==="id"))continue;if(!Oe.has(a)){s.push(a);continue}const l=i.some(p=>p.name==="cross_project_visibility");r.push({kind:a,table:a,hasVisibility:l})}}catch{}return{tables:r,skipped:s.sort()}}function ht(e){return e}function X(e,t){if(!N.test(t))return new Set;try{const s=e.getDatabase().prepare(`PRAGMA table_info(${t})`).all();return new Set(s.filter(o=>N.test(o.name)).map(o=>o.name))}catch{return new Set}}const N=/^[a-z_][a-z0-9_]*$/i;function J(){const e=M();if(!ie(e))return null;try{const t=JSON.parse(oe(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function $e(e){const t={pull_cursor:0,last_push_updated_ms:0,last_push_at:0,last_push_attempt_at:0,last_pull_at:0},r=de(e),s=J();let o=A(e,"cloud");if(!o){if(_e(e,"cloud",M()),o=A(e,"cloud"),!o){if(!s)return t;const{store:c,...a}=s;return{...t,...a}}return{...t,...o.value}}const n=s?.store;return s&&n&&n.device_id===r.deviceId&&n.epoch===r.epoch&&n.fingerprint===H(e).fingerprint&&Number(s.last_pull_at??0)>Number(o.value.last_pull_at??0)&&fe(e,"cloud-cursor.json is ahead of the database (restored in place)"),{...t,...o.value}}function K(e){let t;try{t=A(e,"cloud")?.value}catch{}if(!t){const s=J();if(s){const{store:o,...n}=s;t=n}}const r=s=>Number.isFinite(Number(s))?Number(s):0;return{last_push_updated_ms:r(t?.last_push_updated_ms),last_push_at:r(t?.last_push_at),last_push_attempt_at:r(t?.last_push_attempt_at??t?.last_push_at),last_pull_at:r(t?.last_pull_at)}}function De(e,t){try{pe(e,"cloud",t)}catch{}ae(M(),JSON.stringify({...t,store:H(e)},null,2),{mode:384})}function Q(e){e.getDatabase().exec(`
3
3
  CREATE TABLE IF NOT EXISTS sync_tombstones (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  kind TEXT NOT NULL,
@@ -10,7 +10,7 @@ import{readFileSync as te,writeFileSync as ne,existsSync as se}from"node:fs";imp
10
10
  );
11
11
  CREATE INDEX IF NOT EXISTS idx_sync_tombstones_pending
12
12
  ON sync_tombstones(pushed_at_ms);
13
- `)}function Oe(e){e.exec(`
13
+ `)}function Ae(e){e.exec(`
14
14
  CREATE TABLE IF NOT EXISTS cloud_push_ledger (
15
15
  kind TEXT NOT NULL,
16
16
  row_id TEXT NOT NULL,
@@ -18,17 +18,17 @@ import{readFileSync as te,writeFileSync as ne,existsSync as se}from"node:fs";imp
18
18
  pushed_at INTEGER NOT NULL,
19
19
  PRIMARY KEY (kind, row_id)
20
20
  );
21
- `)}function ke(e){const t=Object.fromEntries(Object.keys(e).sort().map(r=>[r,e[r]]));return P("sha256").update(JSON.stringify(t)).digest("hex")}function Re(e,t){let r;try{r=e.prepare("SELECT row_id, hash FROM cloud_push_ledger WHERE kind = ?").all(t)}catch(n){if(/no such table/i.test(n instanceof Error?n.message:String(n)))return new Map;throw n}return new Map(r.map(n=>[n.row_id,n.hash]))}function Le(e,t,r,n){e.transaction(()=>{Oe(e);const o=e.prepare("DELETE FROM cloud_push_ledger WHERE kind = ? AND row_id = ?");for(const a of r)o.run(a.kind,a.row_id);const s=e.prepare(`INSERT INTO cloud_push_ledger (kind, row_id, hash, pushed_at) VALUES (?, ?, ?, ?)
22
- ON CONFLICT(kind, row_id) DO UPDATE SET hash = excluded.hash, pushed_at = excluded.pushed_at`);for(const a of t)s.run(a.kind,a.row_id,a.hash,n)})()}function $e(e,t,r){try{return e.prepare(`SELECT kind, row_id FROM cloud_push_ledger
23
- WHERE kind = ? AND row_id NOT IN (SELECT CAST(id AS TEXT) FROM ${r})`).all(t)}catch(n){if(/no such table: cloud_push_ledger/i.test(n instanceof Error?n.message:String(n)))return[];throw n}}function X(e,t,r,n){const o=t.flatMap(s=>s.hash===null?[]:[{kind:s.kind,row_id:s.row_id,hash:s.hash}]);if(!(o.length===0&&r.length===0))try{Le(e.getDatabase(),o,r,Date.now())}catch(s){const a=o.length>0?`; ${o.length} row(s) go out again with the next sync`:"";n.push(`push ledger not written: ${v(s)}${a}`)}}function ut(e,t,r){if(typeof t!="string"||t.length===0||t.length>64)return;B(e),e.getDatabase().prepare(`INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
24
- VALUES (?, ?, ?)`).run(t,String(r),Date.now())}class De extends Error{constructor(t){super(t),this.name="CopiedSessionError"}}function Ae(e){return!!e||process.env.WYRM_ALLOW_COPIED_SESSION==="1"}function Ce(e,t,r){const n=ge(e.machine_fp);if(n.state==="match")return;if(n.state==="adopt"){t(Ee());return}const o=["","\u26A0 WYRM CLOUD: this session looks COPIED from another machine.","",` Stored machine fingerprint: ${n.stored.slice(0,12)}\u2026`,` This machine's fingerprint: ${n.current.slice(0,12)}\u2026`,""," Both machines now share ONE device_id. The cloud pull query skips a"," device's own deltas, so each machine filters the OTHER's changes out:"," push works but pull silently returns 0 rows (peer memory looks MISSING).",""," FIX: give this machine its own identity (keep your encryption key):"," rm ~/.wyrm/cloud.json ~/.wyrm/cloud-cursor.json # NOT cloud.key"," wyrm cloud login",""," If this is a legitimate change (e.g. you renamed this host), re-run with:"," wyrm cloud sync --force (or set WYRM_ALLOW_COPIED_SESSION=1)",""];if(Ae(r)){console.error(o.join(`
25
- `)),console.error(" Proceeding anyway (--force / WYRM_ALLOW_COPIED_SESSION=1); fingerprint updated."),console.error(""),t(n.current);return}throw console.error(o.join(`
26
- `)),new De("Cloud session looks copied from another machine (device_id collision). Re-login or pass --force.")}async function dt(e={}){if(e.sinceMs!==void 0&&!(Number.isFinite(e.sinceMs)&&e.sinceMs>=0))throw new Error($);const t=_e();if(!t||!t.device_id)throw new Error("Not logged in or device not registered. Run `wyrm cloud login`.");Ce(t,s=>{fe({...t,machine_fp:s})},e.force);const r=new de(t.base,t.session),n=ae(),o=be(n);try{e.onStart?.();const s=new oe(n);try{return await Me(s,r,t.device_id,e)}finally{try{s.close()}catch{}}}finally{o()}}async function Me(e,t,r,n){B(e);const o=e.getDatabase(),s=Te(o),a=Number(s.last_push_at)||Number(s.last_pull_at)||0,i={pushed:0,pulled:0,deleted_local:0,errors:[],quarantined:0,conflicts:0},l=n.all?q(e):k,c=Date.now(),p=s.last_push_updated_ms,g=[],b=J(e,l,je(p,n.sinceMs),!!n.all,i.errors,{useLedger:n.sinceMs===void 0,stale:g});if(b.length>0&&!n.dryRun){const m=await Ve(t,r,b,{prevMark:p,selectedAtMs:c},i.errors);i.pushed+=m.pushed,s.last_push_updated_ms=m.mark,s.last_push_attempt_at=Date.now(),m.stopped||(s.last_push_at=s.last_push_attempt_at),Be(e,m.tombstoneIds),X(e,m.ledger,g,i.errors)}else i.pushed=b.length,n.dryRun||(s.last_push_at=s.last_push_attempt_at=Date.now(),X(e,[],g,i.errors));if(!n.dryRun){let m=s.pull_cursor,E=0;e:for(;E<50;){let _;try{_=await t.syncPull(r,m,100)}catch(d){i.errors.push(`pull failed: ${d instanceof Error?d.message:d}`);break}if(_.deltas.length===0)break;for(const d of _.deltas)try{const h=ye(d.payload_b64);if(d.kind==="tombstone"){const{kind:u,row_id:f}=JSON.parse(h);Ke(e,l,u,f)&&i.deleted_local++}else{const u=JSON.parse(h);Xe(e,l,d.kind,d.row_id,u,{remoteOrigin:`cloud:${d.device_id??"unknown"}`,lastSyncMs:a}).conflictId!==void 0&&(i.conflicts=(i.conflicts??0)+1),i.pulled++}}catch(h){const u=h instanceof Error?h.message:String(h),f=s.quarantine??={},{entry:S,action:N,newlyQuarantined:T}=Se(f[d.id],d,u,Date.now());if(f[d.id]=S,N==="skip"){T&&(i.quarantined=(i.quarantined??0)+1),i.errors.push(`quarantined ${d.kind}:${d.row_id} after ${S.attempts} attempts (${u})`);continue}i.errors.push(`apply ${d.kind}:${d.row_id}: ${u} (attempt ${S.attempts}/${H}, will retry)`);break e}if(m=_.next_cursor,!_.has_more)break;E++}s.pull_cursor=m,s.last_pull_at=Date.now()}return Ie(o,s),i}const $="--since must be an ISO date or epoch milliseconds",ve=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/i,Ue=1e12;function pt(e){const t=typeof e=="string"?e.trim():"";if(/^\d+$/.test(t)){const n=Number(t);if(!Number.isSafeInteger(n))throw new Error($);if(n<Ue)throw new Error(`${$} (epoch milliseconds, not seconds; or use YYYY-MM-DD): a number below 1000000000000 is before 2001-09-09`);return n}const r=ve.exec(t);if(r){const[,n,o,s,a="00",i="00",l="00",c,p]=r,g=new Date(Date.UTC(Number(n),Number(o)-1,Number(s))),m=g.getUTCFullYear()===Number(n)&&g.getUTCMonth()===Number(o)-1&&g.getUTCDate()===Number(s)?Date.parse(`${n}-${o}-${s}T${a}:${i}:${l}${c?`.${c}`:""}${p?p.toUpperCase():"Z"}`):NaN;if(Number.isFinite(m)&&m>=0)return m}throw new Error($)}function je(e,t){return t===void 0?e:Math.min(e,Math.max(0,t-1))}function _t(e,t={}){const r=e.getDatabase(),n=G(r).last_push_updated_ms,o=t.all?q(e):k,s=[];return{rows:J(e,o,n,!!t.all,s).filter(i=>i.tombstoneId===null).length,tombstones:xe(r),mark_ms:n,errors:s}}function xe(e){try{return e.prepare("SELECT COUNT(*) AS n FROM sync_tombstones WHERE pushed_at_ms IS NULL").get().n}catch{return 0}}function ft(e,t){const r=e.getDatabase(),n=G(r).last_push_updated_ms;if(n<=0)return null;let o=0,s=1/0;for(const i of k){if(!i.hasVisibility||!O(e,i.table,"project_id")||!O(e,i.table,"updated_at"))continue;const l=r.prepare(`SELECT COUNT(*) AS n, MIN(CAST(strftime('%s', updated_at) AS INTEGER)) AS earliest
27
- FROM ${i.table}
21
+ `)}function Ce(e){const t=Object.fromEntries(Object.keys(e).sort().map(r=>[r,e[r]]));return W("sha256").update(JSON.stringify(t)).digest("hex")}function Me(e,t){let r;try{r=e.prepare("SELECT row_id, hash FROM cloud_push_ledger WHERE kind = ?").all(t)}catch(s){if(/no such table/i.test(s instanceof Error?s.message:String(s)))return new Map;throw s}return new Map(r.map(s=>[s.row_id,s.hash]))}function ve(e,t,r,s){e.transaction(()=>{Ae(e);const o=e.prepare("DELETE FROM cloud_push_ledger WHERE kind = ? AND row_id = ?");for(const c of r)o.run(c.kind,c.row_id);const n=e.prepare(`INSERT INTO cloud_push_ledger (kind, row_id, hash, pushed_at) VALUES (?, ?, ?, ?)
22
+ ON CONFLICT(kind, row_id) DO UPDATE SET hash = excluded.hash, pushed_at = excluded.pushed_at`);for(const c of t)n.run(c.kind,c.row_id,c.hash,s)})()}function Ue(e,t,r){try{return e.prepare(`SELECT kind, row_id FROM cloud_push_ledger
23
+ WHERE kind = ? AND row_id NOT IN (SELECT CAST(id AS TEXT) FROM ${r})`).all(t)}catch(s){if(/no such table: cloud_push_ledger/i.test(s instanceof Error?s.message:String(s)))return[];throw s}}function z(e,t,r,s){const o=t.flatMap(n=>n.hash===null?[]:[{kind:n.kind,row_id:n.row_id,hash:n.hash}]);if(!(o.length===0&&r.length===0))try{ve(e.getDatabase(),o,r,Date.now())}catch(n){const c=o.length>0?`; ${o.length} row(s) go out again with the next sync`:"";s.push(`push ledger not written: ${v(n)}${c}`)}}function mt(e,t,r){if(typeof t!="string"||t.length===0||t.length>64)return;Q(e),e.getDatabase().prepare(`INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
24
+ VALUES (?, ?, ?)`).run(t,String(r),Date.now())}class xe extends Error{constructor(t){super(t),this.name="CopiedSessionError"}}function je(e){return!!e||process.env.WYRM_ALLOW_COPIED_SESSION==="1"}function Fe(e,t,r){const s=Se(e.machine_fp);if(s.state==="match")return;if(s.state==="adopt"){t(Ne());return}const o=["","\u26A0 WYRM CLOUD: this session looks COPIED from another machine.","",` Stored machine fingerprint: ${s.stored.slice(0,12)}\u2026`,` This machine's fingerprint: ${s.current.slice(0,12)}\u2026`,""," Both machines now share ONE device_id. The cloud pull query skips a"," device's own deltas, so each machine filters the OTHER's changes out:"," push works but pull silently returns 0 rows (peer memory looks MISSING).",""," FIX: give this machine its own identity (keep your encryption key):"," rm ~/.wyrm/cloud.json ~/.wyrm/cloud-cursor.json # NOT cloud.key"," wyrm cloud login",""," If this is a legitimate change (e.g. you renamed this host), re-run with:"," wyrm cloud sync --force (or set WYRM_ALLOW_COPIED_SESSION=1)",""];if(je(r)){console.error(o.join(`
25
+ `)),console.error(" Proceeding anyway (--force / WYRM_ALLOW_COPIED_SESSION=1); fingerprint updated."),console.error(""),t(s.current);return}throw console.error(o.join(`
26
+ `)),new xe("Cloud session looks copied from another machine (device_id collision). Re-login or pass --force.")}async function yt(e={}){if(e.sinceMs!==void 0&&!(Number.isFinite(e.sinceMs)&&e.sinceMs>=0))throw new Error($);const t=ye();if(!t||!t.device_id)throw new Error("Not logged in or device not registered. Run `wyrm cloud login`.");Fe(t,n=>{ge({...t,machine_fp:n})},e.force);const r=new he(t.base,t.session),s=ue(),o=Te(s);try{const n=new le(s);try{return G(n.getDatabase()),e.onStart?.(),await Pe(n,r,t.device_id,e)}finally{try{n.close()}catch{}}}finally{o()}}async function Pe(e,t,r,s){G(e.getDatabase()),Q(e);const o=e.getDatabase(),n=$e(o),c=Number(n.last_push_at)||Number(n.last_pull_at)||0,a={pushed:0,pulled:0,deleted_local:0,errors:[],quarantined:0,conflicts:0},i=s.all?B(e):{tables:O,skipped:[]},l=i.tables;i.skipped.length>0&&(a.skipped_tables=i.skipped);const p=Date.now(),E=n.last_push_updated_ms,S=[],m=Z(e,l,qe(E,s.sinceMs),!!s.all,a.errors,{useLedger:s.sinceMs===void 0,stale:S});if(m.length>0&&!s.dryRun){const y=await Ke(t,r,m,{prevMark:E,selectedAtMs:p},a.errors);a.pushed+=y.pushed,n.last_push_updated_ms=y.mark,n.last_push_attempt_at=Date.now(),y.stopped||(n.last_push_at=n.last_push_attempt_at),Ze(e,y.tombstoneIds),z(e,y.ledger,S,a.errors)}else a.pushed=m.length,s.dryRun||(n.last_push_at=n.last_push_attempt_at=Date.now(),z(e,[],S,a.errors));if(!s.dryRun){let y=n.pull_cursor,h=0;e:for(;h<50;){let f;try{f=await t.syncPull(r,y,100)}catch(d){a.errors.push(`pull failed: ${d instanceof Error?d.message:d}`);break}if(f.deltas.length===0)break;for(const d of f.deltas)try{const u=be(d.payload_b64);if(d.kind==="tombstone"){const{kind:_,row_id:w}=JSON.parse(u);nt(e,l,_,w)&&a.deleted_local++}else{const _=JSON.parse(u);et(e,l,d.kind,d.row_id,_,{remoteOrigin:`cloud:${d.device_id??"unknown"}`,lastSyncMs:c}).conflictId!==void 0&&(a.conflicts=(a.conflicts??0)+1),a.pulled++}}catch(u){const _=u instanceof Error?u.message:String(u),w=n.quarantine??={},{entry:b,action:T,newlyQuarantined:j}=ke(w[d.id],d,_,Date.now());if(w[d.id]=b,T==="skip"){j&&(a.quarantined=(a.quarantined??0)+1),a.errors.push(`quarantined ${d.kind}:${d.row_id} after ${b.attempts} attempts (${_})`);continue}a.errors.push(`apply ${d.kind}:${d.row_id}: ${_} (attempt ${b.attempts}/${V}, will retry)`);break e}if(y=f.next_cursor,!f.has_more)break;h++}n.pull_cursor=y,n.last_pull_at=Date.now()}return De(o,n),a}const $="--since must be an ISO date or epoch milliseconds",We=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/i,He=1e12;function gt(e){const t=typeof e=="string"?e.trim():"";if(/^\d+$/.test(t)){const s=Number(t);if(!Number.isSafeInteger(s))throw new Error($);if(s<He)throw new Error(`${$} (epoch milliseconds, not seconds; or use YYYY-MM-DD): a number below 1000000000000 is before 2001-09-09`);return s}const r=We.exec(t);if(r){const[,s,o,n,c="00",a="00",i="00",l,p]=r,E=new Date(Date.UTC(Number(s),Number(o)-1,Number(n))),m=E.getUTCFullYear()===Number(s)&&E.getUTCMonth()===Number(o)-1&&E.getUTCDate()===Number(n)?Date.parse(`${s}-${o}-${n}T${c}:${a}:${i}${l?`.${l}`:""}${p?p.toUpperCase():"Z"}`):NaN;if(Number.isFinite(m)&&m>=0)return m}throw new Error($)}function qe(e,t){return t===void 0?e:Math.min(e,Math.max(0,t-1))}function Et(e,t={}){const r=e.getDatabase(),s=K(r).last_push_updated_ms,o=q(r);if(o.storeIsNewer)return{rows:0,tombstones:0,mark_ms:s,errors:[],refused:new Y(o.store,o.binary).message};const n=t.all?Le(e):O,c=[];return{rows:Z(e,n,s,!!t.all,c).filter(i=>i.tombstoneId===null).length,tombstones:Ve(r),mark_ms:s,errors:c}}function Ve(e){try{return e.prepare("SELECT COUNT(*) AS n FROM sync_tombstones WHERE pushed_at_ms IS NULL").get().n}catch{return 0}}function wt(e,t){const r=e.getDatabase(),s=K(r).last_push_updated_ms;if(s<=0)return null;let o=0,n=1/0;for(const a of O){if(!a.hasVisibility||!I(e,a.table,"project_id")||!I(e,a.table,"updated_at"))continue;const i=r.prepare(`SELECT COUNT(*) AS n, MIN(CAST(strftime('%s', updated_at) AS INTEGER)) AS earliest
27
+ FROM ${a.table}
28
28
  WHERE project_id = ? AND cross_project_visibility IN ('org', 'public')
29
- AND updated_at IS NOT NULL AND strftime('%s', updated_at) * 1000 <= ?`).get(t,n);o+=l.n,l.earliest!==null&&l.earliest<s&&(s=l.earliest)}if(o===0||s===1/0)return null;const a=s*1e3;return{rows:o,earliest_ms:a,mark_ms:n,since:new Date(a).toISOString().slice(0,10)}}function J(e,t,r,n,o,s={}){const a=Ye(e,t,r,n,o,s),i=Ge(e);return[...a.map(l=>{const c=l.updated_at??Date.now();return{kind:l.kind,row_id:String(l.row_id),visibility:l.visibility,body:l.row,updated_at:c,stamp:l.stamped?c:null,tombstoneId:null,hash:l.hash}}),...i.map(l=>({kind:"tombstone",row_id:`${l.kind}:${l.row_id}`,visibility:"org",body:{kind:l.kind,row_id:l.row_id,deleted_at_ms:l.deleted_at_ms},updated_at:l.deleted_at_ms,stamp:null,tombstoneId:l.id,hash:null}))]}function Fe(e,t){let r=e,n=0;for(;n<t.length&&t[n].ok;n++)for(const s of t[n].stamps)s>r&&(r=s);let o=1/0;for(;n<t.length;n++)for(const s of t[n].stamps)s<o&&(o=s);return o===1/0?r:Math.min(r,Math.floor(o/1e3)*1e3-1)}const Q=25,Pe=new Set([400,409,413,422]),We=new Set(["storage_cap_exceeded","invalid_device_id","bad_request","no_deltas"]);function K(e){if(!(e instanceof pe)||!Pe.has(e.status))return null;const t=e.body;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function He(e){const t=K(e);return t!==null&&!We.has(String(t.error))}function qe(e){return K(e)?.index===0}const v=e=>{const t=e?.message;return typeof t=="string"?t:String(e)};async function Ve(e,t,r,n,o){const s=[];for(let _=0;_<r.length;_+=Q)s.push(r.slice(_,_+Q));const a=_=>_.flatMap(d=>d.stamp===null?[]:[d.stamp]),i=[],l=[],c=[];let p=0;const g=async(_,d)=>{const h=await e.syncPush(t,d);if(p+=h.accepted,h.rejected>0){const u=[...new Set((h.rejected_details??[]).map(f=>f.reason))].join(", ");return`the server did not store ${h.rejected} of ${d.length} delta(s)${u?` (${u})`:""}`}for(const u of _)u.tombstoneId!==null&&l.push(u.tombstoneId),u.hash!==null&&c.push(u);return null},b=async(_,d)=>{for(let h=0;h<_.length;h++)try{const u=await g([_[h]],[d[h]]);if(u!==null)return u}catch(u){if(!qe(u))return v(u);o.push(`push refused (HTTP ${u.status}) on ${_[h].kind}:${_[h].row_id}`)}return null};let m=null;for(let _=0;_<s.length&&m===null;_++){const d=s[_],h=d.map(f=>({kind:f.kind,row_id:f.row_id,visibility:f.visibility,payload_b64:me(JSON.stringify(f.body)),updated_at:f.updated_at}));let u;try{u=await g(d,h)}catch(f){u=He(f)?await b(d,h):v(f)}if(u===null){i.push({ok:!0,stamps:a(d)});continue}for(const f of s.slice(_))i.push({ok:!1,stamps:a(f)});m={chunk:_+1,why:u}}const E=Math.min(Fe(n.prevMark,i),Math.floor(n.selectedAtMs/1e3)*1e3-1);if(m!==null){const _=new Set(l),d=new Set(c),h=r.filter(u=>u.tombstoneId!==null?!_.has(u.tombstoneId):u.hash!==null?!d.has(u):u.stamp===null||u.stamp>E).length;o.push(`push stopped at chunk ${m.chunk} of ${s.length}: ${m.why}; ${h} row(s) left for the next sync`)}return{pushed:p,mark:E,tombstoneIds:l,ledger:c,stopped:m!==null}}function U(e){if(typeof e!="string"||e.length===0)return 0;const t=e.includes("T")?e:e.replace(" ","T")+"Z",r=Date.parse(t);return Number.isFinite(r)?r:0}function O(e,t,r){try{return e.getDatabase().prepare(`PRAGMA table_info(${t})`).all().some(s=>s.name===r)}catch{return!1}}function Ye(e,t,r,n,o,s={}){const a=[],i=e.getDatabase(),l=O(e,"projects","sync_policy");for(const c of t)if(w.test(c.table)&&!(!n&&!c.hasVisibility))try{const p=O(e,c.table,"updated_at"),g=c.hasVisibility?"WHERE cross_project_visibility IN ('org', 'public')":"WHERE 1=1",b=l&&O(e,c.table,"project_id")?"AND (project_id IS NULL OR project_id IN (SELECT id FROM projects WHERE sync_policy IN ('cloud', 'team')))":"",m=p?"AND (? = 0 OR updated_at IS NULL OR strftime('%s', updated_at) * 1000 > ?)":"",E=p?"ORDER BY (updated_at IS NULL) ASC, updated_at ASC":"",_=`SELECT * FROM ${c.table} ${g} ${b} ${m} ${E}`,d=i.prepare(_),h=p?d.all(r,r):d.all(),u=p||s.useLedger===!1?null:Re(i,c.kind);!p&&s.stale&&s.stale.push(...$e(i,c.kind,c.table));for(const f of h){const S=p?null:ke(f);if(u!==null&&u.get(String(f.id??"?"))===S)continue;const N=U(f.updated_at);if(r>0&&N>0&&N<=r)continue;const T=c.hasVisibility?String(f.cross_project_visibility??"within"):"org";a.push({kind:c.kind,row_id:f.id??"?",visibility:T,row:f,updated_at:N||Date.now(),stamped:N>0,hash:S})}}catch(p){const g=p instanceof Error?p.message:String(p);if(/no such table/i.test(g))continue;o.push(`collect ${c.table}: ${g}`)}return a.sort((c,p)=>(c.updated_at??0)-(p.updated_at??0)),a}function Ge(e){const t=e.getDatabase();try{return t.prepare(`SELECT id, kind, row_id, deleted_at_ms
29
+ AND updated_at IS NOT NULL AND strftime('%s', updated_at) * 1000 <= ?`).get(t,s);o+=i.n,i.earliest!==null&&i.earliest<n&&(n=i.earliest)}if(o===0||n===1/0)return null;const c=n*1e3;return{rows:o,earliest_ms:c,mark_ms:s,since:new Date(c).toISOString().slice(0,10)}}function Z(e,t,r,s,o,n={}){const c=Qe(e,t,r,s,o,n),a=ze(e);return[...c.map(i=>{const l=i.updated_at??Date.now();return{kind:i.kind,row_id:String(i.row_id),visibility:i.visibility,body:i.row,updated_at:l,stamp:i.stamped?l:null,tombstoneId:null,hash:i.hash}}),...a.map(i=>({kind:"tombstone",row_id:`${i.kind}:${i.row_id}`,visibility:"org",body:{kind:i.kind,row_id:i.row_id,deleted_at_ms:i.deleted_at_ms},updated_at:i.deleted_at_ms,stamp:null,tombstoneId:i.id,hash:null}))]}function Ye(e,t){let r=e,s=0;for(;s<t.length&&t[s].ok;s++)for(const n of t[s].stamps)n>r&&(r=n);let o=1/0;for(;s<t.length;s++)for(const n of t[s].stamps)n<o&&(o=n);return o===1/0?r:Math.min(r,Math.floor(o/1e3)*1e3-1)}const ee=25,Ge=new Set([400,409,413,422]),Be=new Set(["storage_cap_exceeded","invalid_device_id","bad_request","no_deltas"]);function te(e){if(!(e instanceof me)||!Ge.has(e.status))return null;const t=e.body;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Xe(e){const t=te(e);return t!==null&&!Be.has(String(t.error))}function Je(e){return te(e)?.index===0}const v=e=>{const t=e?.message;return typeof t=="string"?t:String(e)};async function Ke(e,t,r,s,o){const n=[];for(let h=0;h<r.length;h+=ee)n.push(r.slice(h,h+ee));const c=h=>h.flatMap(f=>f.stamp===null?[]:[f.stamp]),a=[],i=[],l=[];let p=0;const E=async(h,f)=>{const d=await e.syncPush(t,f);if(p+=d.accepted,d.rejected>0){const u=[...new Set((d.rejected_details??[]).map(_=>_.reason))].join(", ");return`the server did not store ${d.rejected} of ${f.length} delta(s)${u?` (${u})`:""}`}for(const u of h)u.tombstoneId!==null&&i.push(u.tombstoneId),u.hash!==null&&l.push(u);return null},S=async(h,f)=>{for(let d=0;d<h.length;d++)try{const u=await E([h[d]],[f[d]]);if(u!==null)return u}catch(u){if(!Je(u))return v(u);o.push(`push refused (HTTP ${u.status}) on ${h[d].kind}:${h[d].row_id}`)}return null};let m=null;for(let h=0;h<n.length&&m===null;h++){const f=n[h],d=f.map(_=>({kind:_.kind,row_id:_.row_id,visibility:_.visibility,payload_b64:we(JSON.stringify(_.body)),updated_at:_.updated_at}));let u;try{u=await E(f,d)}catch(_){u=Xe(_)?await S(f,d):v(_)}if(u===null){a.push({ok:!0,stamps:c(f)});continue}for(const _ of n.slice(h))a.push({ok:!1,stamps:c(_)});m={chunk:h+1,why:u}}const y=Math.min(Ye(s.prevMark,a),Math.floor(s.selectedAtMs/1e3)*1e3-1);if(m!==null){const h=new Set(i),f=new Set(l),d=r.filter(u=>u.tombstoneId!==null?!h.has(u.tombstoneId):u.hash!==null?!f.has(u):u.stamp===null||u.stamp>y).length;o.push(`push stopped at chunk ${m.chunk} of ${n.length}: ${m.why}; ${d} row(s) left for the next sync`)}return{pushed:p,mark:y,tombstoneIds:i,ledger:l,stopped:m!==null}}function U(e){if(typeof e!="string"||e.length===0)return 0;const t=e.includes("T")?e:e.replace(" ","T")+"Z",r=Date.parse(t);return Number.isFinite(r)?r:0}function I(e,t,r){try{return e.getDatabase().prepare(`PRAGMA table_info(${t})`).all().some(n=>n.name===r)}catch{return!1}}function Qe(e,t,r,s,o,n={}){const c=[],a=e.getDatabase(),i=I(e,"projects","sync_policy");for(const l of t)if(N.test(l.table)&&!(!s&&!l.hasVisibility))try{const p=I(e,l.table,"updated_at"),E=l.hasVisibility?"WHERE cross_project_visibility IN ('org', 'public')":"WHERE 1=1",S=i&&I(e,l.table,"project_id")?"AND (project_id IS NULL OR project_id IN (SELECT id FROM projects WHERE sync_policy IN ('cloud', 'team')))":"",m=p?"AND (? = 0 OR updated_at IS NULL OR strftime('%s', updated_at) * 1000 > ?)":"",y=p?"ORDER BY (updated_at IS NULL) ASC, updated_at ASC":"",h=`SELECT * FROM ${l.table} ${E} ${S} ${m} ${y}`,f=a.prepare(h),d=p?f.all(r,r):f.all(),u=p||n.useLedger===!1?null:Me(a,l.kind);!p&&n.stale&&n.stale.push(...Ue(a,l.kind,l.table));for(const _ of d){const w=p?null:Ce(_);if(u!==null&&u.get(String(_.id??"?"))===w)continue;const b=U(_.updated_at);if(r>0&&b>0&&b<=r)continue;const T=l.hasVisibility?String(_.cross_project_visibility??"within"):"org";c.push({kind:l.kind,row_id:_.id??"?",visibility:T,row:_,updated_at:b||Date.now(),stamped:b>0,hash:w})}}catch(p){const E=p instanceof Error?p.message:String(p);if(/no such table/i.test(E))continue;o.push(`collect ${l.table}: ${E}`)}return c.sort((l,p)=>(l.updated_at??0)-(p.updated_at??0)),c}function ze(e){const t=e.getDatabase();try{return t.prepare(`SELECT id, kind, row_id, deleted_at_ms
30
30
  FROM sync_tombstones
31
31
  WHERE pushed_at_ms IS NULL
32
32
  ORDER BY id ASC
33
- LIMIT 500`).all()}catch{return[]}}function Be(e,t){if(t.length===0)return;const r=e.getDatabase(),n=Date.now(),o=r.prepare("UPDATE sync_tombstones SET pushed_at_ms = ? WHERE id = ?"),s=r.transaction(a=>{for(const i of a)o.run(n,i)});try{s(t)}catch{}}const z=new Set(["updated_at","last_accessed_at","access_count","reuse_count","reuse_success_count","reuse_failure_count","usage_count","last_used","last_validated_at","last_verified_at"]),R=e=>e==null?null:String(e);function Z(e,t){const r=t.filter(n=>!z.has(n)).sort().map(n=>[n,R(e[n])]);return P("sha256").update(JSON.stringify(r)).digest("hex")}function j(e,t,r,n,o,s,a,i){const l=Number(n);if(Number.isSafeInteger(l))try{const c=JSON.stringify(C(t,o)),p=e.prepare("SELECT id FROM sync_conflicts WHERE resolved_at IS NULL AND source = 'cloud' AND local_kind = ? AND local_id = ? AND remote_payload = ?").get(r,l,c);return p?p.id:Number(e.prepare(`INSERT INTO sync_conflicts (local_kind, local_id, remote_payload, remote_origin, source, winner, local_payload)
34
- VALUES (?, ?, ?, ?, 'cloud', ?, ?)`).run(r,l,c,i,a,JSON.stringify(C(t,s))).lastInsertRowid)}catch{return}}function Xe(e,t,r,n,o,s={remoteOrigin:"cloud",lastSyncMs:0}){const a=t.find(y=>y.kind===r);if(!a)return{action:"skipped"};if(!w.test(a.table))throw new Error(`apply ${r}: refusing unsafe table name ${a.table}`);const i=C(a.table,o),l=V(e,a.table);if(l.size===0)throw new Error(`apply ${r}: ${a.table} has no readable schema`);const c=Object.keys(i).filter(y=>l.has(y)&&w.test(y));if(c.length===0)throw new Error(`apply ${r}: no columns from peer payload matched local schema`);const p=e.getDatabase(),g=c.map(()=>"?").join(","),b=c.join(","),m=c.map(y=>i[y]),E=c.filter(y=>y!=="id"),_=E.map(y=>`${y} = ?`).join(", "),d=i.id,h=(y,L)=>{try{return y==="insert"?p.prepare(`INSERT INTO ${a.table} (${b}) VALUES (${g})`).run(...m):E.length>0&&p.prepare(`UPDATE ${a.table} SET ${_} WHERE id = ?`).run(...E.map(I=>i[I]),d),{action:L}}catch(I){const D=Je(I)?Qe(p,a.table,l,i):void 0;if(!D)throw new Error(`apply ${r} failed: ${I instanceof Error?I.message:I}`);return{action:"kept_local",conflictId:j(p,a.table,r,D.id,i,D,"local",s.remoteOrigin)}}},u=!l.has("id")||d===void 0||d===null?void 0:p.prepare(`SELECT * FROM ${a.table} WHERE id = ?`).get(d);if(!u)return h("insert","inserted");if(!c.some(y=>!z.has(y)&&R(u[y])!==R(i[y])))return{action:"identical"};if(ee(p,a.table,l,i).some(y=>y.some(L=>R(u[L])!==R(i[L]))))return{action:"kept_local",conflictId:j(p,a.table,r,u.id,i,u,"local",s.remoteOrigin)};const f=l.has("updated_at")?U(u.updated_at):0,S=l.has("updated_at")?U(i.updated_at):0;if(f===0||S===0)return h("update","updated");const N=f===S,T=N?Z(i,c)>Z(u,c):S>f,x=N||!T||s.lastSyncMs>0&&f>s.lastSyncMs?j(p,a.table,r,d,i,u,T?"remote":"local",s.remoteOrigin):void 0;if(!T)return{action:"kept_local",conflictId:x};const F=h("update","updated");return F.action==="kept_local"?F:{action:"updated",conflictId:x}}const Je=e=>e?.code==="SQLITE_CONSTRAINT_UNIQUE"||/UNIQUE constraint failed/i.test(e instanceof Error?e.message:String(e));function ee(e,t,r,n){const o=[];if(!w.test(t))return o;const s=e.prepare(`PRAGMA index_list(${t})`).all();for(const a of s){if(!a.unique||a.origin==="pk"||a.partial||!w.test(a.name))continue;const i=e.prepare(`PRAGMA index_info(${a.name})`).all().map(l=>l.name);i.length===0||i.some(l=>!l||!w.test(l)||!r.has(l)||!(l in n))||o.push(i)}return o}function Qe(e,t,r,n){for(const o of ee(e,t,r,n)){const s=o.map(i=>`${i} IS ?`).join(" AND "),a=e.prepare(`SELECT * FROM ${t} WHERE ${s}`).get(...o.map(i=>n[i]));if(a)return a}}function Ke(e,t,r,n){const o=t.find(l=>l.kind===r);if(!o||!w.test(o.table))return!1;const s=e.getDatabase(),a=V(e,o.table);if(a.has("cross_project_visibility")){const l=a.has("project_id")?s.prepare(`SELECT cross_project_visibility AS vis, project_id FROM ${o.table} WHERE id = ?`).get(n):s.prepare(`SELECT cross_project_visibility AS vis FROM ${o.table} WHERE id = ?`).get(n);if(!l||l.vis!=="org"&&l.vis!=="public")return!1;if(l.project_id!=null&&O(e,"projects","sync_policy")){const c=s.prepare("SELECT sync_policy AS p FROM projects WHERE id = ?").get(l.project_id);if(c?.p&&c.p!=="cloud"&&c.p!=="team")return!1}}return s.prepare(`DELETE FROM ${o.table} WHERE id = ?`).run(n).changes>0}export{De as CopiedSessionError,k as DEFAULT_TABLES,H as QUARANTINE_AFTER,$ as SINCE_USAGE,Xe as applyRow,Ye as collectChangedRows,q as discoverTables,Oe as ensurePushLedgerTable,ft as groveBelowMark,Ce as guardCopiedSession,pt as parseSince,G as peekCursor,_t as pendingPush,Se as quarantineDecision,ut as recordTombstone,dt as runSync,Fe as safePushMark,J as selectPushItems};
33
+ LIMIT 500`).all()}catch{return[]}}function Ze(e,t){if(t.length===0)return;const r=e.getDatabase(),s=Date.now(),o=r.prepare("UPDATE sync_tombstones SET pushed_at_ms = ? WHERE id = ?"),n=r.transaction(c=>{for(const a of c)o.run(s,a)});try{n(t)}catch{}}const se=new Set(["updated_at","last_accessed_at","access_count","reuse_count","reuse_success_count","reuse_failure_count","usage_count","last_used","last_validated_at","last_verified_at"]),R=e=>e==null?null:String(e);function ne(e,t){const r=t.filter(s=>!se.has(s)).sort().map(s=>[s,R(e[s])]);return W("sha256").update(JSON.stringify(r)).digest("hex")}function x(e,t,r,s,o,n,c,a){const i=Number(s);if(Number.isSafeInteger(i))try{const l=JSON.stringify(C(t,o)),p=e.prepare("SELECT id FROM sync_conflicts WHERE resolved_at IS NULL AND source = 'cloud' AND local_kind = ? AND local_id = ? AND remote_payload = ?").get(r,i,l);return p?p.id:Number(e.prepare(`INSERT INTO sync_conflicts (local_kind, local_id, remote_payload, remote_origin, source, winner, local_payload)
34
+ VALUES (?, ?, ?, ?, 'cloud', ?, ?)`).run(r,i,l,a,c,JSON.stringify(C(t,n))).lastInsertRowid)}catch{return}}function et(e,t,r,s,o,n={remoteOrigin:"cloud",lastSyncMs:0}){const c=t.find(g=>g.kind===r);if(!c)return{action:"skipped"};if(!N.test(c.table))throw new Error(`apply ${r}: refusing unsafe table name ${c.table}`);const a=C(c.table,o),i=X(e,c.table);if(i.size===0)throw new Error(`apply ${r}: ${c.table} has no readable schema`);const l=Object.keys(a).filter(g=>i.has(g)&&N.test(g));if(l.length===0)throw new Error(`apply ${r}: no columns from peer payload matched local schema`);const p=e.getDatabase(),E=l.map(()=>"?").join(","),S=l.join(","),m=l.map(g=>a[g]),y=l.filter(g=>g!=="id"),h=y.map(g=>`${g} = ?`).join(", "),f=a.id,d=(g,L)=>{try{return g==="insert"?p.prepare(`INSERT INTO ${c.table} (${S}) VALUES (${E})`).run(...m):y.length>0&&p.prepare(`UPDATE ${c.table} SET ${h} WHERE id = ?`).run(...y.map(k=>a[k]),f),{action:L}}catch(k){const D=tt(k)?st(p,c.table,i,a):void 0;if(!D)throw new Error(`apply ${r} failed: ${k instanceof Error?k.message:k}`);return{action:"kept_local",conflictId:x(p,c.table,r,D.id,a,D,"local",n.remoteOrigin)}}},u=!i.has("id")||f===void 0||f===null?void 0:p.prepare(`SELECT * FROM ${c.table} WHERE id = ?`).get(f);if(!u)return d("insert","inserted");if(!l.some(g=>!se.has(g)&&R(u[g])!==R(a[g])))return{action:"identical"};if(re(p,c.table,i,a).some(g=>g.some(L=>R(u[L])!==R(a[L]))))return{action:"kept_local",conflictId:x(p,c.table,r,u.id,a,u,"local",n.remoteOrigin)};const _=i.has("updated_at")?U(u.updated_at):0,w=i.has("updated_at")?U(a.updated_at):0;if(_===0||w===0)return d("update","updated");const b=_===w,T=b?ne(a,l)>ne(u,l):w>_,F=b||!T||n.lastSyncMs>0&&_>n.lastSyncMs?x(p,c.table,r,f,a,u,T?"remote":"local",n.remoteOrigin):void 0;if(!T)return{action:"kept_local",conflictId:F};const P=d("update","updated");return P.action==="kept_local"?P:{action:"updated",conflictId:F}}const tt=e=>e?.code==="SQLITE_CONSTRAINT_UNIQUE"||/UNIQUE constraint failed/i.test(e instanceof Error?e.message:String(e));function re(e,t,r,s){const o=[];if(!N.test(t))return o;const n=e.prepare(`PRAGMA index_list(${t})`).all();for(const c of n){if(!c.unique||c.origin==="pk"||c.partial||!N.test(c.name))continue;const a=e.prepare(`PRAGMA index_info(${c.name})`).all().map(i=>i.name);a.length===0||a.some(i=>!i||!N.test(i)||!r.has(i)||!(i in s))||o.push(a)}return o}function st(e,t,r,s){for(const o of re(e,t,r,s)){const n=o.map(a=>`${a} IS ?`).join(" AND "),c=e.prepare(`SELECT * FROM ${t} WHERE ${n}`).get(...o.map(a=>s[a]));if(c)return c}}function nt(e,t,r,s){const o=t.find(i=>i.kind===r);if(!o||!N.test(o.table))return!1;const n=e.getDatabase(),c=X(e,o.table);if(c.has("cross_project_visibility")){const i=c.has("project_id")?n.prepare(`SELECT cross_project_visibility AS vis, project_id FROM ${o.table} WHERE id = ?`).get(s):n.prepare(`SELECT cross_project_visibility AS vis FROM ${o.table} WHERE id = ?`).get(s);if(!i||i.vis!=="org"&&i.vis!=="public")return!1;if(i.project_id!=null&&I(e,"projects","sync_policy")){const l=n.prepare("SELECT sync_policy AS p FROM projects WHERE id = ?").get(i.project_id);if(l?.p&&l.p!=="cloud"&&l.p!=="team")return!1}}return n.prepare(`DELETE FROM ${o.table} WHERE id = ?`).run(s).changes>0}export{xe as CopiedSessionError,O as DEFAULT_TABLES,Y as NewerStoreSyncError,V as QUARANTINE_AFTER,$ as SINCE_USAGE,et as applyRow,Qe as collectChangedRows,B as discoverSyncTables,Le as discoverTables,Ae as ensurePushLedgerTable,wt as groveBelowMark,Fe as guardCopiedSession,gt as parseSince,K as peekCursor,Et as pendingPush,ke as quarantineDecision,mt as recordTombstone,yt as runSync,Ye as safePushMark,Z as selectPushItems};