wyrm-mcp 9.5.2 → 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/database.js CHANGED
@@ -1,14 +1,14 @@
1
- import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSync as v,readdirSync as Q,statSync as z,writeFileSync as K,chmodSync as X}from"fs";import{homedir as W}from"os";import{join as u,basename as Z,resolve as ee,normalize as te}from"path";import{spawnSync as D}from"child_process";import{getResilienceManager as se}from"./resilience.js";import{getStoreLogger as re}from"./logger.js";import{runMigrations as ie,schemaSkew as ne,getSchemaVersion as oe,retryOpenOnBusy as ae}from"./migrations.js";import{recordGovernanceEvent as L}from"./governance.js";import{enforceReadOnlyOpen as ce,newerStoreMessage as le,newerStoreWritesAllowed as de,NEWER_STORE_OVERRIDE_ENV as ue}from"./store-readonly.js";import{describeStoreError as it}from"./store-readonly.js";import{validateProjectPath as F,buildFtsMatchQuery as R,redactCredentials as m,redactCredentialsDeep as pe,redactedJson as U,redactField as E}from"./security.js";import{ValidationError as Ee}from"./validate.js";import{isEncryptedValue as he}from"./crypto.js";import{emitEvent as _,eventsSince as me,subscribeEvents as _e,isLiveMemoryEnabled as ge,ingestRemoteEvent as Se,ingestRemoteEventDetailed as fe,eventsForPush as Re,pruneEvents as Te,getMeta as be,setMeta as Ne}from"./events.js";import{getActor as x}from"./handlers/boundary.js";import{eraseLakeRows as Oe}from"./erasure.js";import{readSkillContent as q,skillFrontmatter as ye,slugify as Ce,skillContentSha as ke}from"./skill-author.js";import{resolveProjectForPath as De,projectIdByPathKey as P}from"./project-resolve.js";function et(){return process.env.WYRM_DB_PATH??process.env.WYRM_DB??u(W(),".wyrm","wyrm.db")}function Le(p,t){const e=(s,r)=>{try{h(s)&&X(s,r)}catch{}};t&&e(t,448),e(p,384),e(`${p}-wal`,384),e(`${p}-shm`,384)}const Ie={truth:{select:`SELECT t.cross_project_visibility AS vis, t.project_id AS pid, p.name AS pname, p.sync_policy AS policy
1
+ import{openDatabase as z}from"./storage/index.js";import{existsSync as h,mkdirSync as v,readdirSync as K,statSync as X,writeFileSync as Z,chmodSync as ee}from"fs";import{homedir as W}from"os";import{join as u,basename as te,resolve as se,normalize as re}from"path";import{spawnSync as D}from"child_process";import{getResilienceManager as ie}from"./resilience.js";import{getStoreLogger as ne}from"./logger.js";import{runMigrations as oe,schemaSkew as ae,getSchemaVersion as ce,retryOpenOnBusy as le}from"./migrations.js";import{recordGovernanceEvent as L}from"./governance.js";import{enforceReadOnlyOpen as de,newerStoreMessage as ue,newerStoreWritesAllowed as pe,NEWER_STORE_OVERRIDE_ENV as Ee}from"./store-readonly.js";import{describeStoreError as nt}from"./store-readonly.js";import{validateProjectPath as F,buildFtsMatchQuery as R,redactCredentials as m,redactCredentialsDeep as he,redactedJson as U,redactField as E}from"./security.js";import{ValidationError as x}from"./validate.js";import{isEncryptedValue as me}from"./crypto.js";import{emitEvent as _,eventsSince as _e,subscribeEvents as ge,isLiveMemoryEnabled as Se,ingestRemoteEvent as fe,ingestRemoteEventDetailed as Re,eventsForPush as Te,pruneEvents as be,getMeta as Ne,setMeta as Oe}from"./events.js";import{getActor as P}from"./handlers/boundary.js";import{eraseLakeRows as ye}from"./erasure.js";import{readSkillContent as q,skillFrontmatter as Ce,slugify as ke,skillContentSha as De}from"./skill-author.js";import{resolveProjectForPath as Le,projectIdByPathKey as B}from"./project-resolve.js";function tt(){return process.env.WYRM_DB_PATH??process.env.WYRM_DB??u(W(),".wyrm","wyrm.db")}const G=["critical","high","medium","low"];function Ie(p,t){const e=(s,r)=>{try{h(s)&&ee(s,r)}catch{}};t&&e(t,448),e(p,384),e(`${p}-wal`,384),e(`${p}-shm`,384)}const Ae={truth:{select:`SELECT t.cross_project_visibility AS vis, t.project_id AS pid, p.name AS pname, p.sync_policy AS policy
2
2
  FROM ground_truths t LEFT JOIN projects p ON p.id = t.project_id WHERE t.id = ?`,update:"UPDATE ground_truths SET cross_project_visibility = ?, updated_at = datetime('now') WHERE id = ?"},memory:{select:`SELECT t.cross_project_visibility AS vis, t.project_id AS pid, p.name AS pname, p.sync_policy AS policy
3
3
  FROM memory_artifacts t LEFT JOIN projects p ON p.id = t.project_id WHERE t.id = ?`,update:"UPDATE memory_artifacts SET cross_project_visibility = ?, updated_at = datetime('now') WHERE id = ?"},quest:{select:`SELECT t.cross_project_visibility AS vis, t.project_id AS pid, p.name AS pname, p.sync_policy AS policy
4
- FROM quests t LEFT JOIN projects p ON p.id = t.project_id WHERE t.id = ?`,update:"UPDATE quests SET cross_project_visibility = ?, updated_at = datetime('now') WHERE id = ?"}},Ae=new Set(["within","org","public"]),we=["objectives","completed","issues","commits","files_changed","notes","summary"];function B(p){const t={...p};for(const e of we)typeof t[e]=="string"&&(t[e]=m(t[e]));return t}function G(p,t){return{value:he(p)?p:m(p),metadata:t?JSON.stringify(pe(t)):null}}function y(p){return[m(p),p]}function je(p){return p==="connector_config"||p.startsWith("connector:")}const Me="(key <> 'connector_config' AND key NOT GLOB 'connector:*')",He="(key = 'connector_config' OR key GLOB 'connector:*')";class tt{db;BATCH_SIZE=1e3;resilience;logger;dbPath;constructor(t){const e=u(W(),".wyrm");h(e)||v(e,{recursive:!0,mode:448}),this.dbPath=t||u(e,"wyrm.db"),this.logger=re(this.dbPath),this.resilience=se(),this.db=this.initializeDatabase(this.dbPath),Le(this.dbPath,e);const s=ae(()=>(this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("busy_timeout = 5000"),this.db.pragma("mmap_size = 268435456"),this.db.pragma("page_size = 4096"),this.db.pragma("foreign_keys = ON"),this.db.pragma("secure_delete = ON"),ie(this.db))),r=ne(this.db);r.storeIsNewer&&(de()?this.logger.warn(`This store is at schema v${r.store}, newer than this Wyrm knows (v${r.binary}). ${ue}=1 is set, so this older binary is writing to it under older rules. Upgrade wyrm-mcp on this machine.`):(ce(this.db,r),this.logger.warn(le(r.store,r.binary)))),s.length>0&&this.logger.info(`Applied ${s.length} migration(s), now at v${oe(this.db)}`),this.recoverIncompleteOperations()}getDatabase(){return this.db}getDatabasePath(){return this.dbPath}initializeDatabase(t){const e=this.resilience.withRetrySync(()=>J(t),"database_init",{maxAttempts:3,baseDelayMs:500});if(!e.success)throw this.logger.error("Failed to initialize database",{path:t,error:e.error?.message}),e.error||new Error("Database initialization failed");return e.data}recoverIncompleteOperations(){const t=this.resilience.getIncompleteOperations();for(const e of t)this.logger.warn("Found incomplete operation from previous session",{operation:e.operation,stage:e.stage,id:e.id}),e.operation==="batch_insert"&&this.logger.info("Batch insert was incomplete - data may need re-import"),this.resilience.completeCheckpoint(e.id)}addWatchDir(t,e=!0){return F(t),this.db.prepare(`
4
+ FROM quests t LEFT JOIN projects p ON p.id = t.project_id WHERE t.id = ?`,update:"UPDATE quests SET cross_project_visibility = ?, updated_at = datetime('now') WHERE id = ?"}},we=new Set(["within","org","public"]),je=["objectives","completed","issues","commits","files_changed","notes","summary"];function $(p){const t={...p};for(const e of je)typeof t[e]=="string"&&(t[e]=m(t[e]));return t}function Y(p,t){return{value:me(p)?p:m(p),metadata:t?JSON.stringify(he(t)):null}}function y(p){return[m(p),p]}function Me(p){return p==="connector_config"||p.startsWith("connector:")}const He="(key <> 'connector_config' AND key NOT GLOB 'connector:*')",ve="(key = 'connector_config' OR key GLOB 'connector:*')";class st{db;BATCH_SIZE=1e3;resilience;logger;dbPath;constructor(t){const e=u(W(),".wyrm");h(e)||v(e,{recursive:!0,mode:448}),this.dbPath=t||u(e,"wyrm.db"),this.logger=ne(this.dbPath),this.resilience=ie(),this.db=this.initializeDatabase(this.dbPath),Ie(this.dbPath,e);const s=le(()=>(this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("cache_size = -64000"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("busy_timeout = 5000"),this.db.pragma("mmap_size = 268435456"),this.db.pragma("page_size = 4096"),this.db.pragma("foreign_keys = ON"),this.db.pragma("secure_delete = ON"),oe(this.db))),r=ae(this.db);r.storeIsNewer&&(pe()?this.logger.warn(`This store is at schema v${r.store}, newer than this Wyrm knows (v${r.binary}). ${Ee}=1 is set, so this older binary is writing to it under older rules. Upgrade wyrm-mcp on this machine.`):(de(this.db,r),this.logger.warn(ue(r.store,r.binary)))),s.length>0&&this.logger.info(`Applied ${s.length} migration(s), now at v${ce(this.db)}`),this.recoverIncompleteOperations()}getDatabase(){return this.db}getDatabasePath(){return this.dbPath}initializeDatabase(t){const e=this.resilience.withRetrySync(()=>z(t),"database_init",{maxAttempts:3,baseDelayMs:500});if(!e.success)throw this.logger.error("Failed to initialize database",{path:t,error:e.error?.message}),e.error||new Error("Database initialization failed");return e.data}recoverIncompleteOperations(){const t=this.resilience.getIncompleteOperations();for(const e of t)this.logger.warn("Found incomplete operation from previous session",{operation:e.operation,stage:e.stage,id:e.id}),e.operation==="batch_insert"&&this.logger.info("Batch insert was incomplete - data may need re-import"),this.resilience.completeCheckpoint(e.id)}addWatchDir(t,e=!0){return F(t),this.db.prepare(`
5
5
  INSERT INTO watch_dirs (path, recursive)
6
6
  VALUES (?, ?)
7
7
  ON CONFLICT(path) DO UPDATE SET recursive = excluded.recursive
8
8
  RETURNING *
9
- `).get(t,e?1:0)}getWatchDirs(){return this.db.prepare("SELECT * FROM watch_dirs").all()}removeWatchDir(t){this.db.prepare("DELETE FROM watch_dirs WHERE path = ?").run(t)}scanForProjects(t,e=!0){F(t);const s=[],r=(i,n=0)=>{if(!(n>3&&e))try{const a=Q(i,{withFileTypes:!0});for(const o of a){if(!o.isDirectory()||o.name.startsWith(".")&&o.name!==".git")continue;const c=u(i,o.name),l=u(c,".git");if(h(l)){const d=this.registerProjectFromPath(c);d&&s.push(d)}else e&&n<3&&r(c,n+1)}}catch{}};return r(t),this.db.prepare(`
9
+ `).get(t,e?1:0)}getWatchDirs(){return this.db.prepare("SELECT * FROM watch_dirs").all()}removeWatchDir(t){this.db.prepare("DELETE FROM watch_dirs WHERE path = ?").run(t)}scanForProjects(t,e=!0){F(t);const s=[],r=(i,n=0)=>{if(!(n>3&&e))try{const a=K(i,{withFileTypes:!0});for(const o of a){if(!o.isDirectory()||o.name.startsWith(".")&&o.name!==".git")continue;const c=u(i,o.name),l=u(c,".git");if(h(l)){const d=this.registerProjectFromPath(c);d&&s.push(d)}else e&&n<3&&r(c,n+1)}}catch{}};return r(t),this.db.prepare(`
10
10
  UPDATE watch_dirs SET last_scan = datetime('now') WHERE path = ?
11
- `).run(t),s}scanAllWatchDirs(){const t=this.getWatchDirs(),e=[];for(const s of t){const r=this.scanForProjects(s.path,!!s.recursive);e.push(...r)}return e}registerProjectFromPath(t){try{const e=te(ee(t));if(!h(e)||!z(e).isDirectory())return null;const s=Z(e);let r,i,n,a;try{const o=D("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf-8",timeout:5e3,shell:!1});o.status===0&&(r=o.stdout.trim());const c=D("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf-8",timeout:5e3,shell:!1});c.status===0&&(i=c.stdout.trim());const l=D("git",["log","-1","--format=%h %s"],{cwd:e,encoding:"utf-8",timeout:5e3,shell:!1});l.status===0&&(n=l.stdout.trim())}catch{}return h(u(e,"package.json"))?(a="Node.js",h(u(e,"next.config.js"))||h(u(e,"next.config.ts"))||h(u(e,"next.config.mjs"))?a="Next.js":h(u(e,"vite.config.ts"))&&(a="Vite")):h(u(e,"requirements.txt"))||h(u(e,"pyproject.toml"))?a="Python":h(u(e,"composer.json"))?a="PHP":h(u(e,"Cargo.toml"))?a="Rust":h(u(e,"go.mod"))&&(a="Go"),this.registerProject(s,e,r,a,n,i)}catch{return null}}registerProject(t,e,s,r,i,n,a=process.platform){const o=E(s||null),c=E(i||null),l=()=>this.db.prepare(`
11
+ `).run(t),s}scanAllWatchDirs(){const t=this.getWatchDirs(),e=[];for(const s of t){const r=this.scanForProjects(s.path,!!s.recursive);e.push(...r)}return e}registerProjectFromPath(t){try{const e=re(se(t));if(!h(e)||!X(e).isDirectory())return null;const s=te(e);let r,i,n,a;try{const o=D("git",["config","--get","remote.origin.url"],{cwd:e,encoding:"utf-8",timeout:5e3,shell:!1});o.status===0&&(r=o.stdout.trim());const c=D("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf-8",timeout:5e3,shell:!1});c.status===0&&(i=c.stdout.trim());const l=D("git",["log","-1","--format=%h %s"],{cwd:e,encoding:"utf-8",timeout:5e3,shell:!1});l.status===0&&(n=l.stdout.trim())}catch{}return h(u(e,"package.json"))?(a="Node.js",h(u(e,"next.config.js"))||h(u(e,"next.config.ts"))||h(u(e,"next.config.mjs"))?a="Next.js":h(u(e,"vite.config.ts"))&&(a="Vite")):h(u(e,"requirements.txt"))||h(u(e,"pyproject.toml"))?a="Python":h(u(e,"composer.json"))?a="PHP":h(u(e,"Cargo.toml"))?a="Rust":h(u(e,"go.mod"))&&(a="Go"),this.registerProject(s,e,r,a,n,i)}catch{return null}}registerProject(t,e,s,r,i,n,a=process.platform){const o=E(s||null),c=E(i||null),l=()=>this.db.prepare(`
12
12
  INSERT INTO projects (name, path, repo, stack, last_commit, branch)
13
13
  VALUES (?, ?, ?, ?, ?, ?)
14
14
  ON CONFLICT(path) DO UPDATE SET
@@ -19,7 +19,7 @@ import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSy
19
19
  branch = COALESCE(excluded.branch, projects.branch),
20
20
  updated_at = datetime('now')
21
21
  RETURNING *
22
- `).get(t,e,o,r||null,c,n||null);return a!=="win32"?l():this.db.transaction(()=>{const f=this.db.prepare("SELECT 1 FROM projects WHERE path = ?").get(e)?void 0:P(this.db,e,a);return f===void 0?l():this.db.prepare(`
22
+ `).get(t,e,o,r||null,c,n||null);return a!=="win32"?l():this.db.transaction(()=>{const f=this.db.prepare("SELECT 1 FROM projects WHERE path = ?").get(e)?void 0:B(this.db,e,a);return f===void 0?l():this.db.prepare(`
23
23
  UPDATE projects SET
24
24
  name = ?,
25
25
  repo = COALESCE(?, repo),
@@ -29,18 +29,18 @@ import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSy
29
29
  updated_at = datetime('now')
30
30
  WHERE id = ?
31
31
  RETURNING *
32
- `).get(t,o,r||null,c,n||null,f)}).immediate()}getProject(t,e=process.platform){const s=this.db.prepare("SELECT * FROM projects WHERE path = ?").get(t);if(s||e!=="win32")return s;const r=P(this.db,t,e);return r===void 0?void 0:this.getProjectById(r)}getProjectForPath(t,e=process.platform){const{id:s,root:r}=De(this.db,t,e);return s!==null&&r!==null?{id:s,path:r}:void 0}getProjectById(t){return this.db.prepare("SELECT * FROM projects WHERE id = ?").get(t)}getProjectByName(t){return this.db.prepare("SELECT * FROM projects WHERE name = ?").get(t)}getAllProjects(t=100,e=0){return this.db.prepare(`
32
+ `).get(t,o,r||null,c,n||null,f)}).immediate()}getProject(t,e=process.platform){const s=this.db.prepare("SELECT * FROM projects WHERE path = ?").get(t);if(s||e!=="win32")return s;const r=B(this.db,t,e);return r===void 0?void 0:this.getProjectById(r)}getProjectForPath(t,e=process.platform){const{id:s,root:r}=Le(this.db,t,e);return s!==null&&r!==null?{id:s,path:r}:void 0}getProjectById(t){return this.db.prepare("SELECT * FROM projects WHERE id = ?").get(t)}getProjectByName(t){return this.db.prepare("SELECT * FROM projects WHERE name = ?").get(t)}getAllProjects(t=100,e=0){return this.db.prepare(`
33
33
  SELECT * FROM projects ORDER BY updated_at DESC LIMIT ? OFFSET ?
34
34
  `).all(t,e)}searchProjects(t){const e=`%${t}%`;return this.db.prepare(`
35
35
  SELECT * FROM projects
36
36
  WHERE name LIKE ? OR stack LIKE ? OR repo LIKE ?
37
37
  ORDER BY updated_at DESC
38
38
  LIMIT 50
39
- `).all(e,e,e)}createSession(t,e){e=B(e);const s=this.estimateTokens((e.objectives||"")+(e.completed||"")+(e.issues||"")+(e.notes||"")),r=x(),i=this.resilience.withRetrySync(()=>this.db.prepare(`
39
+ `).all(e,e,e)}createSession(t,e){e=$(e);const s=this.estimateTokens((e.objectives||"")+(e.completed||"")+(e.issues||"")+(e.notes||"")),r=P(),i=this.resilience.withRetrySync(()=>this.db.prepare(`
40
40
  INSERT INTO sessions (project_id, date, objectives, completed, issues, commits, files_changed, notes, tokens_estimate, agent_id, run_id)
41
41
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
42
42
  RETURNING *
43
- `).get(t,e.date||new Date().toISOString().split("T")[0],e.objectives||"",e.completed||"",e.issues||"",e.commits||"",e.files_changed||"",e.notes||"",s,r.agent_id,r.run_id),"createSession");if(!i.success)throw i.error||new Error("Failed to create session");return _(this.db,{projectId:t,kind:"session_update",refTable:"sessions",refId:i.data.id}),i.data}updateSession(t,e){e=B(e);const s=[],r=[],i=new Set(["objectives","completed","issues","commits","files_changed","notes","summary","is_archived"]);for(const[a,o]of Object.entries(e))i.has(a)&&o!==void 0&&(s.push(`${a} = ?`),r.push(o));if(s.length===0)return this.getSession(t);if(e.objectives||e.completed||e.issues||e.notes){const a=this.getSession(t);if(a){const o=this.estimateTokens((e.objectives||a.objectives)+(e.completed||a.completed)+(e.issues||a.issues)+(e.notes||a.notes));s.push("tokens_estimate = ?"),r.push(o)}}r.push(t);const n=this.resilience.withRetrySync(()=>this.db.prepare(`
43
+ `).get(t,e.date||new Date().toISOString().split("T")[0],e.objectives||"",e.completed||"",e.issues||"",e.commits||"",e.files_changed||"",e.notes||"",s,r.agent_id,r.run_id),"createSession");if(!i.success)throw i.error||new Error("Failed to create session");return _(this.db,{projectId:t,kind:"session_update",refTable:"sessions",refId:i.data.id}),i.data}updateSession(t,e){e=$(e);const s=[],r=[],i=new Set(["objectives","completed","issues","commits","files_changed","notes","summary","is_archived"]);for(const[a,o]of Object.entries(e))i.has(a)&&o!==void 0&&(s.push(`${a} = ?`),r.push(o));if(s.length===0)return this.getSession(t);if(e.objectives||e.completed||e.issues||e.notes){const a=this.getSession(t);if(a){const o=this.estimateTokens((e.objectives||a.objectives)+(e.completed||a.completed)+(e.issues||a.issues)+(e.notes||a.notes));s.push("tokens_estimate = ?"),r.push(o)}}r.push(t);const n=this.resilience.withRetrySync(()=>this.db.prepare(`
44
44
  UPDATE sessions SET ${s.join(", ")} WHERE id = ? RETURNING *
45
45
  `).get(...r),"updateSession");if(!n.success)throw n.error||new Error("Failed to update session");return _(this.db,{projectId:n.data.project_id,kind:"session_update",refTable:"sessions",refId:t}),n.data}getSession(t){return this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(t)}updateContinuity(t,e,s){const r=m(e.trim());if(!r)return;const i=12e3,n=this.db.prepare("SELECT thread, turn_count FROM project_continuity WHERE project_id = ?").get(t),a=new Date().toISOString(),o=`[${a}${s?" \xB7 "+s:""}] ${r}`;let c=n?.thread?n.thread+`
46
46
 
@@ -102,7 +102,7 @@ import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSy
102
102
  `).run(t,t,e).changes}getSessionTokenUsage(t){return this.db.prepare(`
103
103
  SELECT COALESCE(SUM(tokens_estimate), 0) as total
104
104
  FROM sessions WHERE project_id = ? AND is_archived = 0
105
- `).get(t).total}addQuest(t,e,s,r="medium",i){const n=x(),a=this.db.prepare(`
105
+ `).get(t).total}addQuest(t,e,s,r="medium",i){if(!G.includes(r))throw new x("priority",`must be one of: ${G.join(", ")}`);const n=P(),a=this.db.prepare(`
106
106
  INSERT INTO quests (project_id, title, description, priority, tags, agent_id, run_id, updated_at)
107
107
  VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
108
108
  RETURNING *
@@ -176,7 +176,7 @@ import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSy
176
176
  SELECT value FROM context WHERE project_id = ? AND key = ?
177
177
  `).get(t,e)?.value}getAllContext(t){const e=this.db.prepare(`
178
178
  SELECT key, value FROM context WHERE project_id = ?
179
- `).all(t),s={};for(const r of e)s[r.key]=r.value;return s}liveMemoryEnabled(){return ge()}eventsSince(t,e=0,s=100){return me(this.db,t,e,s)}subscribeEvents(t,e=20){return _e(this.db,t,e)}publishEvent(t){_(this.db,t)}pruneEvents(t={}){return Te(this.db,t)}ingestRemoteEvent(t,e,s){return Se(this.db,t,e,s)}ingestRemoteEventDetailed(t,e,s){return fe(this.db,t,e,s)}eventsForPush(t,e=0,s=200){return Re(this.db,t,e,s)}getMeta(t){return be(this.db,t)}setMeta(t,e){Ne(this.db,t,e)}setGlobalContext(t,e){if(je(t))throw new Ee("key","is a connector setting; manage it with `wyrm connector`");this.writeGlobalContext(t,E(e))}setGlobalSetting(t,e){this.writeGlobalContext(t,e)}writeGlobalContext(t,e){this.db.prepare(`
179
+ `).all(t),s={};for(const r of e)s[r.key]=r.value;return s}liveMemoryEnabled(){return Se()}eventsSince(t,e=0,s=100){return _e(this.db,t,e,s)}subscribeEvents(t,e=20){return ge(this.db,t,e)}publishEvent(t){_(this.db,t)}pruneEvents(t={}){return be(this.db,t)}ingestRemoteEvent(t,e,s){return fe(this.db,t,e,s)}ingestRemoteEventDetailed(t,e,s){return Re(this.db,t,e,s)}eventsForPush(t,e=0,s=200){return Te(this.db,t,e,s)}getMeta(t){return Ne(this.db,t)}setMeta(t,e){Oe(this.db,t,e)}setGlobalContext(t,e){if(Me(t))throw new x("key","is a connector setting; manage it with `wyrm connector`");this.writeGlobalContext(t,E(e))}setGlobalSetting(t,e){this.writeGlobalContext(t,e)}writeGlobalContext(t,e){this.db.prepare(`
180
180
  INSERT INTO global_context (key, value)
181
181
  VALUES (?, ?)
182
182
  ON CONFLICT(key) DO UPDATE SET
@@ -184,7 +184,7 @@ import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSy
184
184
  updated_at = datetime('now')
185
185
  `).run(t,e)}getGlobalContext(t){return this.db.prepare(`
186
186
  SELECT value FROM global_context WHERE key = ?
187
- `).get(t)?.value}getAllGlobalContext(){const t=this.db.prepare(`SELECT key, value FROM global_context WHERE ${Me}`).all(),e={};for(const s of t)e[s.key]=s.value;return e}countGlobalSettings(){return this.db.prepare(`SELECT COUNT(*) AS n FROM global_context WHERE ${He}`).get().n}registerSkill(t,e,s,r,i,n,a,o){const c=o?.tier!==void 0,l=Array.isArray(o?.governs),d=Array.isArray(o?.composes),f=o?.tier??"atomic",T=U(l?o.governs:[]),b=U(d?o.composes:[]),g=q({skillPath:s,name:t}),N=g?.content??null,O=g?.sha256??null,$=g?new Date().toISOString():null,S=k=>typeof k=="string"&&k.trim()!==""?E(k):null,I=g?ye(g.content):{},A=S(e),w=S(r),Y=A??S(I.description)??t,V=w??S(I.category),j=S(i),M=S(n),H=S(a),C=this.resilience.withRetrySync(()=>this.db.prepare(`
187
+ `).get(t)?.value}getAllGlobalContext(){const t=this.db.prepare(`SELECT key, value FROM global_context WHERE ${He}`).all(),e={};for(const s of t)e[s.key]=s.value;return e}countGlobalSettings(){return this.db.prepare(`SELECT COUNT(*) AS n FROM global_context WHERE ${ve}`).get().n}registerSkill(t,e,s,r,i,n,a,o){const c=o?.tier!==void 0,l=Array.isArray(o?.governs),d=Array.isArray(o?.composes),f=o?.tier??"atomic",T=U(l?o.governs:[]),b=U(d?o.composes:[]),g=q({skillPath:s,name:t}),N=g?.content??null,O=g?.sha256??null,V=g?new Date().toISOString():null,S=k=>typeof k=="string"&&k.trim()!==""?E(k):null,I=g?Ce(g.content):{},A=S(e),w=S(r),J=A??S(I.description)??t,Q=w??S(I.category),j=S(i),M=S(n),H=S(a),C=this.resilience.withRetrySync(()=>this.db.prepare(`
188
188
  INSERT INTO skills (name, description, skill_path, category, author, version, tags, tier, governs, composes, content, content_sha256, content_updated_at, is_active, usage_count)
189
189
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0)
190
190
  ON CONFLICT(name) DO UPDATE SET
@@ -206,7 +206,7 @@ import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSy
206
206
  updated_at = datetime('now'),
207
207
  is_active = 1
208
208
  RETURNING *
209
- `).get(t,Y,s,V,j,M,H,f,T,b,N,O,$,A!==null?1:0,w!==null?1:0,j!==null?1:0,M!==null?1:0,H!==null?1:0,c?1:0,l?1:0,d?1:0),"registerSkill");if(!C.success)throw C.error||new Error("Failed to register skill");return C.data}getSkill(t){const e=this.db.prepare("SELECT * FROM skills WHERE name = ?").get(t);return e&&this.db.prepare("UPDATE skills SET last_used = datetime('now'), usage_count = usage_count + 1 WHERE id = ?").run(e.id),e}backfillSkillContent(t={}){const e=t.read??q,s=this.db.prepare("SELECT id, name, skill_path, content_sha256 FROM skills").all();let r=0,i=0,n=0;const a=this.db.prepare("UPDATE skills SET content = ?, content_sha256 = ?, content_updated_at = ?, updated_at = datetime('now') WHERE id = ?");return this.db.transaction(()=>{for(const c of s){const l=e({skillPath:c.skill_path,name:c.name,skillsDir:t.skillsDir});if(!l){n++;continue}if(c.content_sha256&&c.content_sha256===l.sha256){i++;continue}a.run(l.content,l.sha256,new Date().toISOString(),c.id),r++}})(),{total:s.length,filled:r,unchanged:i,missing:n}}exportSkillContent(t,e={}){const s=e.includeInactive?"":" WHERE is_active = 1",r=this.db.prepare(`SELECT name, content FROM skills${s} ORDER BY name`).all();let i=0,n=0,a=0;const o=new Set;for(const c of r){if(c.content==null){n++;continue}let l=Ce(c.name);if(!l){n++;continue}o.has(l)&&(l=`${l}-${ke(c.name).slice(0,8)}`,a++),o.add(l);const d=u(t,l);v(d,{recursive:!0}),K(u(d,"SKILL.md"),c.content,"utf-8"),i++}return{total:r.length,written:i,skipped_no_content:n,collisions:a}}setSkillVisibility(t,e){return this.db.transaction(()=>{const s=this.db.prepare("UPDATE skills SET cross_project_visibility = ?, updated_at = datetime('now') WHERE name = ? RETURNING *").get(e,t);return s&&L(this.db,"visibility.set",{kind:"skill",row_id:s.id,to:e}),s})()}setAllSkillsVisibility(t,e={}){const s=[],r=[t];e.includeInactive||s.push("is_active = 1"),e.tier&&(s.push("tier = ?"),r.push(e.tier));const i=s.length?" WHERE "+s.join(" AND "):"";return this.db.transaction(()=>{const n=this.db.prepare(`UPDATE skills SET cross_project_visibility = ?, updated_at = datetime('now')${i}`).run(...r);return n.changes>0&&L(this.db,"visibility.set",{kind:"skill",count:n.changes,to:t}),n.changes})()}setRowVisibility(t,e,s){const r=Ie[t];if(!r)throw new Error(`Unknown visibility kind: ${String(t)} (use truth|memory|quest)`);if(!Ae.has(s))throw new Error(`Unknown visibility: ${String(s)} (use within|org|public)`);const i=this.db.prepare(r.select).get(e),n={kind:t,id:e,visibility:s};if(!i)return{...n,outcome:"not_found",projectId:null,projectName:null,syncPolicy:null,egressEligible:!1};const a={projectId:i.pid,projectName:i.pname,syncPolicy:i.policy,previous:i.vis},o=c=>c!=="within"&&(i.pid==null||i.policy==="cloud"||i.policy==="team");return s!=="within"&&i.policy==="private"?{...n,...a,outcome:"refused_private_grove",egressEligible:!1}:i.vis===s?{...n,...a,outcome:"unchanged",egressEligible:o(s)}:(this.db.transaction(()=>{this.db.prepare(r.update).run(s,e),L(this.db,"visibility.set",{kind:t,row_id:e,from:i.vis,to:s},{projectId:i.pid})})(),{...n,...a,outcome:"updated",egressEligible:o(s)})}listSkills(t,e,s,r){let i="SELECT * FROM skills WHERE 1=1";const n=[];if(t!==void 0&&(i+=" AND is_active = ?",n.push(t?1:0)),e&&(i+=" AND category = ?",n.push(e)),r&&(i+=" AND tier = ?",n.push(r)),s){const a=R(s);a&&(i+=" AND id IN (SELECT rowid FROM skills_fts WHERE skills_fts MATCH ?)",n.push(a))}return i+=" ORDER BY updated_at DESC",this.db.prepare(i).all(...n)}searchSkills(t,e=20,s){const r=R(t);if(!r)return[];const i=s?" AND s.tier = ?":"",n=this.db.prepare(`
209
+ `).get(t,J,s,Q,j,M,H,f,T,b,N,O,V,A!==null?1:0,w!==null?1:0,j!==null?1:0,M!==null?1:0,H!==null?1:0,c?1:0,l?1:0,d?1:0),"registerSkill");if(!C.success)throw C.error||new Error("Failed to register skill");return C.data}getSkill(t){const e=this.db.prepare("SELECT * FROM skills WHERE name = ?").get(t);return e&&this.db.prepare("UPDATE skills SET last_used = datetime('now'), usage_count = usage_count + 1 WHERE id = ?").run(e.id),e}backfillSkillContent(t={}){const e=t.read??q,s=this.db.prepare("SELECT id, name, skill_path, content_sha256 FROM skills").all();let r=0,i=0,n=0;const a=this.db.prepare("UPDATE skills SET content = ?, content_sha256 = ?, content_updated_at = ?, updated_at = datetime('now') WHERE id = ?");return this.db.transaction(()=>{for(const c of s){const l=e({skillPath:c.skill_path,name:c.name,skillsDir:t.skillsDir});if(!l){n++;continue}if(c.content_sha256&&c.content_sha256===l.sha256){i++;continue}a.run(l.content,l.sha256,new Date().toISOString(),c.id),r++}})(),{total:s.length,filled:r,unchanged:i,missing:n}}exportSkillContent(t,e={}){const s=e.includeInactive?"":" WHERE is_active = 1",r=this.db.prepare(`SELECT name, content FROM skills${s} ORDER BY name`).all();let i=0,n=0,a=0;const o=new Set;for(const c of r){if(c.content==null){n++;continue}let l=ke(c.name);if(!l){n++;continue}o.has(l)&&(l=`${l}-${De(c.name).slice(0,8)}`,a++),o.add(l);const d=u(t,l);v(d,{recursive:!0}),Z(u(d,"SKILL.md"),c.content,"utf-8"),i++}return{total:r.length,written:i,skipped_no_content:n,collisions:a}}setSkillVisibility(t,e){return this.db.transaction(()=>{const s=this.db.prepare("UPDATE skills SET cross_project_visibility = ?, updated_at = datetime('now') WHERE name = ? RETURNING *").get(e,t);return s&&L(this.db,"visibility.set",{kind:"skill",row_id:s.id,to:e}),s})()}setAllSkillsVisibility(t,e={}){const s=[],r=[t];e.includeInactive||s.push("is_active = 1"),e.tier&&(s.push("tier = ?"),r.push(e.tier));const i=s.length?" WHERE "+s.join(" AND "):"";return this.db.transaction(()=>{const n=this.db.prepare(`UPDATE skills SET cross_project_visibility = ?, updated_at = datetime('now')${i}`).run(...r);return n.changes>0&&L(this.db,"visibility.set",{kind:"skill",count:n.changes,to:t}),n.changes})()}setRowVisibility(t,e,s){const r=Ae[t];if(!r)throw new Error(`Unknown visibility kind: ${String(t)} (use truth|memory|quest)`);if(!we.has(s))throw new Error(`Unknown visibility: ${String(s)} (use within|org|public)`);const i=this.db.prepare(r.select).get(e),n={kind:t,id:e,visibility:s};if(!i)return{...n,outcome:"not_found",projectId:null,projectName:null,syncPolicy:null,egressEligible:!1};const a={projectId:i.pid,projectName:i.pname,syncPolicy:i.policy,previous:i.vis},o=c=>c!=="within"&&(i.pid==null||i.policy==="cloud"||i.policy==="team");return s!=="within"&&i.policy==="private"?{...n,...a,outcome:"refused_private_grove",egressEligible:!1}:i.vis===s?{...n,...a,outcome:"unchanged",egressEligible:o(s)}:(this.db.transaction(()=>{this.db.prepare(r.update).run(s,e),L(this.db,"visibility.set",{kind:t,row_id:e,from:i.vis,to:s},{projectId:i.pid})})(),{...n,...a,outcome:"updated",egressEligible:o(s)})}listSkills(t,e,s,r){let i="SELECT * FROM skills WHERE 1=1";const n=[];if(t!==void 0&&(i+=" AND is_active = ?",n.push(t?1:0)),e&&(i+=" AND category = ?",n.push(e)),r&&(i+=" AND tier = ?",n.push(r)),s){const a=R(s);a&&(i+=" AND id IN (SELECT rowid FROM skills_fts WHERE skills_fts MATCH ?)",n.push(a))}return i+=" ORDER BY updated_at DESC",this.db.prepare(i).all(...n)}searchSkills(t,e=20,s){const r=R(t);if(!r)return[];const i=s?" AND s.tier = ?":"",n=this.db.prepare(`
210
210
  SELECT s.* FROM skills s
211
211
  JOIN skills_fts ON s.id = skills_fts.rowid
212
212
  WHERE skills_fts MATCH ?${i}
@@ -230,14 +230,14 @@ import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSy
230
230
  WHERE project_id = ?
231
231
  AND (tags = ? OR tags LIKE ? OR tags LIKE ? OR tags LIKE ?)
232
232
  LIMIT 1
233
- `).get(t,e,`${e},%`,`%,${e}`,`%,${e},%`)}updateQuestFields(t,e){const s=[],r=[];if(e.title!==void 0&&(s.push("title = ?"),r.push(m(e.title))),e.description!==void 0&&(s.push("description = ?"),r.push(m(e.description))),e.tags!==void 0&&(s.push("tags = ?"),r.push(E(e.tags))),s.length===0)return this.db.prepare("SELECT * FROM quests WHERE id = ?").get(t);s.push("updated_at = datetime('now')"),r.push(t);const i=this.db.prepare(`UPDATE quests SET ${s.join(", ")} WHERE id = ? RETURNING *`).get(...r);return i&&_(this.db,{projectId:i.project_id,kind:"quest",refTable:"quests",refId:t}),i}insertData(t,e,s,r,i){const n=G(r,i),a=this.resilience.withRetrySync(()=>this.db.prepare(`
233
+ `).get(t,e,`${e},%`,`%,${e}`,`%,${e},%`)}updateQuestFields(t,e){const s=[],r=[];if(e.title!==void 0&&(s.push("title = ?"),r.push(m(e.title))),e.description!==void 0&&(s.push("description = ?"),r.push(m(e.description))),e.tags!==void 0&&(s.push("tags = ?"),r.push(E(e.tags))),s.length===0)return this.db.prepare("SELECT * FROM quests WHERE id = ?").get(t);s.push("updated_at = datetime('now')"),r.push(t);const i=this.db.prepare(`UPDATE quests SET ${s.join(", ")} WHERE id = ? RETURNING *`).get(...r);return i&&_(this.db,{projectId:i.project_id,kind:"quest",refTable:"quests",refId:t}),i}insertData(t,e,s,r,i){const n=Y(r,i),a=this.resilience.withRetrySync(()=>this.db.prepare(`
234
234
  INSERT INTO data_lake (project_id, category, key, value, metadata)
235
235
  VALUES (?, ?, ?, ?, ?)
236
236
  RETURNING *
237
237
  `).get(t,E(e),E(s),n.value,n.metadata),"insertData");if(!a.success)throw a.error||new Error("Insert data failed");return a.data}batchWrites(t,e){return this.db.transaction(r=>r.map(i=>e(i)))(t)}insertDataBatch(t){const e=this.resilience.generateOperationId("batch_insert"),s=this.BATCH_SIZE;let r=0;this.resilience.createCheckpoint(e,"batch_insert","started",{totalItems:t.length,batchSize:s});const i=this.db.prepare(`
238
238
  INSERT INTO data_lake (project_id, category, key, value, metadata)
239
239
  VALUES (?, ?, ?, ?, ?)
240
- `);try{for(let n=0;n<t.length;n+=s){const a=t.slice(n,n+s),o=Math.floor(n/s)+1;this.resilience.updateCheckpoint(e,`batch_${o}`,{processed:n,currentBatch:o});const c=this.resilience.withRetrySync(()=>this.batchWrites(a,l=>{const d=G(l.value,l.metadata);return i.run(l.projectId,E(l.category),E(l.key),d.value,d.metadata),1}).length,`batch_insert_${o}`,{maxAttempts:3});if(!c.success){this.logger.error("Batch insert failed",{batch:o,processed:r,error:c.error?.message}),this.resilience.updateCheckpoint(e,"partial_failure",{inserted:r,failedAt:n});const l=c.error??new Error(`Batch insert failed at chunk ${o}`);throw l.inserted=r,l}r+=c.data}return this.resilience.completeCheckpoint(e),r}catch(n){throw n!==null&&typeof n=="object"&&"inserted"in n||(this.logger.error("Batch insert exception",{inserted:r,error:n.message}),this.resilience.updateCheckpoint(e,"exception",{inserted:r,error:n.message}),n!==null&&typeof n=="object"&&(n.inserted=r)),n}}queryData(t,e,s=100,r=0){return e?this.db.prepare(`
240
+ `);try{for(let n=0;n<t.length;n+=s){const a=t.slice(n,n+s),o=Math.floor(n/s)+1;this.resilience.updateCheckpoint(e,`batch_${o}`,{processed:n,currentBatch:o});const c=this.resilience.withRetrySync(()=>this.batchWrites(a,l=>{const d=Y(l.value,l.metadata);return i.run(l.projectId,E(l.category),E(l.key),d.value,d.metadata),1}).length,`batch_insert_${o}`,{maxAttempts:3});if(!c.success){this.logger.error("Batch insert failed",{batch:o,processed:r,error:c.error?.message}),this.resilience.updateCheckpoint(e,"partial_failure",{inserted:r,failedAt:n});const l=c.error??new Error(`Batch insert failed at chunk ${o}`);throw l.inserted=r,l}r+=c.data}return this.resilience.completeCheckpoint(e),r}catch(n){throw n!==null&&typeof n=="object"&&"inserted"in n||(this.logger.error("Batch insert exception",{inserted:r,error:n.message}),this.resilience.updateCheckpoint(e,"exception",{inserted:r,error:n.message}),n!==null&&typeof n=="object"&&(n.inserted=r)),n}}queryData(t,e,s=100,r=0){return e?this.db.prepare(`
241
241
  SELECT * FROM data_lake
242
242
  WHERE project_id = ? AND category IN (?, ?)
243
243
  ORDER BY created_at DESC
@@ -279,8 +279,8 @@ import{openDatabase as J}from"./storage/index.js";import{existsSync as h,mkdirSy
279
279
  WHERE project_id = ?
280
280
  GROUP BY category
281
281
  ORDER BY count DESC
282
- `).all(t)}forgetData(t){const e=[],s=[];if(t.match){e.push("(key LIKE ? OR value LIKE ?)");const d=`%${t.match}%`;s.push(d,d)}if(t.dataset&&(e.push("category IN (?, ?)"),s.push(...y(t.dataset))),typeof t.olderThanDays=="number"&&(e.push("created_at < datetime('now', ?)"),s.push(`-${Math.max(0,Math.floor(t.olderThanDays))} days`)),t.projectId!=null&&(e.push("project_id = ?"),s.push(t.projectId)),e.length===0)return{matched:0,deleted:0,samples:[],counts:{},erasureId:null};const r=e.join(" AND "),i=this.db.prepare(`SELECT id, category, key FROM data_lake WHERE ${r}`).all(...s),n=i.length,a=this.db.prepare(`SELECT category, key, created_at FROM data_lake WHERE ${r} ORDER BY created_at LIMIT 5`).all(...s),o=t.dryRun!==!1,c=Oe(this.db,i,{subject:t.match,dryRun:o,reason:t.reason??(t.match?"subject":t.dataset?"source":"age"),predicate:{match:!!t.match,dataset:t.dataset??null,older_than_days:typeof t.olderThanDays=="number"?t.olderThanDays:null,project:t.projectId!=null},actor:t.actor??null}),l=o?0:c.counts.data_lake??0;return{matched:n,deleted:l,samples:a,counts:c.counts,erasureId:c.erasureId}}deleteDataCategory(t,e){return this.db.prepare(`
282
+ `).all(t)}forgetData(t){const e=[],s=[];if(t.match){e.push("(key LIKE ? OR value LIKE ?)");const d=`%${t.match}%`;s.push(d,d)}if(t.dataset&&(e.push("category IN (?, ?)"),s.push(...y(t.dataset))),typeof t.olderThanDays=="number"&&(e.push("created_at < datetime('now', ?)"),s.push(`-${Math.max(0,Math.floor(t.olderThanDays))} days`)),t.projectId!=null&&(e.push("project_id = ?"),s.push(t.projectId)),e.length===0)return{matched:0,deleted:0,samples:[],counts:{},erasureId:null};const r=e.join(" AND "),i=this.db.prepare(`SELECT id, category, key FROM data_lake WHERE ${r}`).all(...s),n=i.length,a=this.db.prepare(`SELECT category, key, created_at FROM data_lake WHERE ${r} ORDER BY created_at LIMIT 5`).all(...s),o=t.dryRun!==!1,c=ye(this.db,i,{subject:t.match,dryRun:o,reason:t.reason??(t.match?"subject":t.dataset?"source":"age"),predicate:{match:!!t.match,dataset:t.dataset??null,older_than_days:typeof t.olderThanDays=="number"?t.olderThanDays:null,project:t.projectId!=null},actor:t.actor??null}),l=o?0:c.counts.data_lake??0;return{matched:n,deleted:l,samples:a,counts:c.counts,erasureId:c.erasureId}}deleteDataCategory(t,e){return this.db.prepare(`
283
283
  DELETE FROM data_lake WHERE project_id = ? AND category IN (?, ?)
284
284
  `).run(t,...y(e)).changes}*streamSessions(t){const e=this.db.prepare(`
285
285
  SELECT * FROM sessions WHERE project_id = ? ORDER BY date DESC
286
- `);for(const s of e.iterate(t))yield s}*streamData(t,e){const s=e?this.db.prepare("SELECT * FROM data_lake WHERE project_id = ? AND category IN (?, ?)"):this.db.prepare("SELECT * FROM data_lake WHERE project_id = ?"),r=e?[t,...y(e)]:[t];for(const i of s.iterate(...r))yield i}getStats(){const t=this.db.prepare("SELECT COUNT(*) as count FROM projects").get(),e=this.db.prepare("SELECT COUNT(*) as count FROM sessions").get(),s=this.db.prepare("SELECT COUNT(*) as count FROM quests").get(),r=this.db.prepare("SELECT COUNT(*) as count FROM memory_artifacts").get(),i=this.db.prepare("SELECT COUNT(*) as count FROM data_lake").get(),n=this.db.prepare("SELECT COALESCE(SUM(tokens_estimate), 0) as total FROM sessions WHERE is_archived = 0").get(),a=this.db.pragma("page_count",{simple:!0}),o=this.db.pragma("page_size",{simple:!0}),c=a*o/(1024*1024);return{projects:t.count,sessions:e.count,quests:s.count,artifacts:r.count,dataPoints:i.count,totalTokens:n.total,dbSize:`${c.toFixed(2)} MB`}}getProjectStats(t){const e=this.db.prepare("SELECT COUNT(*) as count FROM sessions WHERE project_id = ?").get(t),s=this.db.prepare("SELECT COUNT(*) as count FROM quests WHERE project_id = ? AND status IN ('pending', 'in_progress')").get(t),r=this.db.prepare("SELECT COUNT(*) as count FROM quests WHERE project_id = ? AND status = 'completed'").get(t),i=this.db.prepare("SELECT COUNT(*) as count FROM data_lake WHERE project_id = ?").get(t),n=this.db.prepare("SELECT COALESCE(SUM(tokens_estimate), 0) as total FROM sessions WHERE project_id = ? AND is_archived = 0").get(t);return{sessions:e.count,quests:{pending:s.count,completed:r.count},dataPoints:i.count,tokens:n.total}}estimateTokens(t){return Math.ceil(t.length/4)}vacuum(){this.db.exec("VACUUM")}checkpoint(){this.db.pragma("wal_checkpoint(TRUNCATE)")}getResilienceStatus(){const t=this.resilience.getCircuitStatus(),e=this.resilience.getIncompleteOperations();return{circuitState:t.state,failures:t.failures,incompleteOps:e.length}}resetCircuitBreaker(){this.resilience.resetCircuit()}close(){try{this.checkpoint(),this.logger.info("Database checkpoint completed")}catch(t){this.logger.error("Checkpoint failed during close",{error:t.message})}try{this.db.close(),this.logger.info("Database closed successfully")}catch(t){this.logger.error("Database close failed",{error:t.message})}}checkIntegrity(){const t=[];try{const e=this.db.pragma("integrity_check",{simple:!0});e!=="ok"&&t.push(`Integrity check failed: ${e}`)}catch(e){t.push(`Integrity check error: ${e.message}`)}try{const e=this.db.pragma("foreign_key_check");e.length>0&&t.push(`Foreign key violations: ${e.length}`)}catch(e){t.push(`FK check error: ${e.message}`)}return{ok:t.length===0,issues:t}}}export{tt as WyrmDB,it as describeStoreError,je as isGlobalSettingKey,et as resolveDbPath,Le as tightenStorePermissions};
286
+ `);for(const s of e.iterate(t))yield s}*streamData(t,e){const s=e?this.db.prepare("SELECT * FROM data_lake WHERE project_id = ? AND category IN (?, ?)"):this.db.prepare("SELECT * FROM data_lake WHERE project_id = ?"),r=e?[t,...y(e)]:[t];for(const i of s.iterate(...r))yield i}getStats(){const t=this.db.prepare("SELECT COUNT(*) as count FROM projects").get(),e=this.db.prepare("SELECT COUNT(*) as count FROM sessions").get(),s=this.db.prepare("SELECT COUNT(*) as count FROM quests").get(),r=this.db.prepare("SELECT COUNT(*) as count FROM memory_artifacts").get(),i=this.db.prepare("SELECT COUNT(*) as count FROM data_lake").get(),n=this.db.prepare("SELECT COALESCE(SUM(tokens_estimate), 0) as total FROM sessions WHERE is_archived = 0").get(),a=this.db.pragma("page_count",{simple:!0}),o=this.db.pragma("page_size",{simple:!0}),c=a*o/(1024*1024);return{projects:t.count,sessions:e.count,quests:s.count,artifacts:r.count,dataPoints:i.count,totalTokens:n.total,dbSize:`${c.toFixed(2)} MB`}}getProjectStats(t){const e=this.db.prepare("SELECT COUNT(*) as count FROM sessions WHERE project_id = ?").get(t),s=this.db.prepare("SELECT COUNT(*) as count FROM quests WHERE project_id = ? AND status IN ('pending', 'in_progress')").get(t),r=this.db.prepare("SELECT COUNT(*) as count FROM quests WHERE project_id = ? AND status = 'completed'").get(t),i=this.db.prepare("SELECT COUNT(*) as count FROM data_lake WHERE project_id = ?").get(t),n=this.db.prepare("SELECT COALESCE(SUM(tokens_estimate), 0) as total FROM sessions WHERE project_id = ? AND is_archived = 0").get(t);return{sessions:e.count,quests:{pending:s.count,completed:r.count},dataPoints:i.count,tokens:n.total}}estimateTokens(t){return Math.ceil(t.length/4)}vacuum(){this.db.exec("VACUUM")}checkpoint(){this.db.pragma("wal_checkpoint(TRUNCATE)")}getResilienceStatus(){const t=this.resilience.getCircuitStatus(),e=this.resilience.getIncompleteOperations();return{circuitState:t.state,failures:t.failures,incompleteOps:e.length}}resetCircuitBreaker(){this.resilience.resetCircuit()}close(){try{this.checkpoint(),this.logger.info("Database checkpoint completed")}catch(t){this.logger.error("Checkpoint failed during close",{error:t.message})}try{this.db.close(),this.logger.info("Database closed successfully")}catch(t){this.logger.error("Database close failed",{error:t.message})}}checkIntegrity(){const t=[];try{const e=this.db.pragma("integrity_check",{simple:!0});e!=="ok"&&t.push(`Integrity check failed: ${e}`)}catch(e){t.push(`Integrity check error: ${e.message}`)}try{const e=this.db.pragma("foreign_key_check");e.length>0&&t.push(`Foreign key violations: ${e.length}`)}catch(e){t.push(`FK check error: ${e.message}`)}return{ok:t.length===0,issues:t}}}export{G as QUEST_PRIORITIES,st as WyrmDB,nt as describeStoreError,Me as isGlobalSettingKey,tt as resolveDbPath,Ie as tightenStorePermissions};
@@ -1,5 +1,5 @@
1
- import{readFileSync as P,statSync as G}from"node:fs";import{isAbsolute as ie,relative as oe,resolve as I,sep as V}from"node:path";import{sanitizeFtsQuery as ae,trySanitizeFtsQuery as se,redactCredentials as L}from"./security.js";import{WyrmCrypto as Q}from"./crypto.js";import{emitEvent as D,isLiveMemoryEnabled as ce}from"./events.js";import{getActor as m,hasExplicitAttribution as M}from"./handlers/boundary.js";import{screenRecordedId as le}from"./recorded-text-screen.js";import{readActor as de,resolveAttribution as ue}from"./attribution.js";import{recordGovernanceEvent as U}from"./governance.js";import{normalizeContentSignature as pe,containsFailedSignature as Z,redactedContentSignature as X}from"./content-signature.js";const W=new Set(["a","an","the","this","that","these","those","and","or","but","if","then","than","so","to","of","in","on","at","by","for","from","with","without","no","not","as","is","are","was","were","be","been","being","will","would","can","could","should","it","its","i","we","you","my","our","your","again","just","now","please","let","lets","do","does","did","into","over","about"]),J={run:0,project:1,global:2},fe=8,qe="source changed since this failure was recorded \u2014 re-verify",_e="no hits in the quiet period, so it warns instead of blocking; recording it again re-arms the block",C="operator;cli",he=60,Ee=44;function ve(a=process.env){const e=(a.WYRM_FAILURE_QUIET_DAYS??"").trim();if(e==="")return he;if(/^(off|false|no)$/i.test(e))return 0;const t=Number(e);return Number.isFinite(t)&&t>0?t:0}const k=200,O=5,$e="a similar record, not this action: only the same action, the same target or an equivalent command blocks";function xe(a,e,t){if(!a)return"the record could not be re-read";if(a.operator_confirmed||a.quarantine_scope==="run"&&a.run_id!==null&&a.run_id===e)return null;const n=a.operator_confirmation_stale?"it changed since the operator confirmed it":null;return a.project_id===null||a.quarantine_scope==="global"?n??"it is a global record and the operator has not confirmed it":a.agent_id!==null&&!t?n??`an agent (${le(a.agent_id,40)}) recorded it and the operator has not confirmed it`:null}function Be(a=process.env){return/^(1|true|yes|on)$/i.test(a.WYRM_GUARD_AGENT_BLOCKS??"")}function Ye(a,e,t){return a.match==="exact"?"exact":a.match==="target"||e.has(b(a.target))?"target":a.match==="canonical"||a.scope==="command"&&a.match!=="related"&&t.has(A(a.target))?"canonical":null}function F(a){const e=[],t=o=>{const s=o.trim();s&&s.length<=1e3&&!e.includes(s)&&e.push(s)},n=[];let r="",i=null;for(let o=0;o<a.length;o++){const s=a[o];if(i){r+=s,s===i&&a[o-1]!=="\\"&&(i=null);continue}if(s==="'"||s==='"'){i=s,r+=s;continue}const l=a.slice(o,o+2);if(l==="&&"||l==="||"){n.push(r),r="",o++;continue}if(s===";"||s==="|"||s===`
2
- `){n.push(r),r="";continue}r+=s}n.push(r);for(const o of n){t(o);let s=o.trim(),l=!1;for(let d=0;d<8;d++){const h=s.match(/^(?:sudo(?:\s+-[A-Za-z]+)*|doas|time|nohup|exec|command|stdbuf(?:\s+-\S+)*|env|[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*))\s+/);if(!h)break;s=s.slice(h[0].length).trim(),l=!0}l&&t(s);const _=s.match(/^(?:ba|z|k)?sh\s+-c\s+(['"])([\s\S]*)\1\s*$/);if(_)for(const d of F(_[2]))t(d)}return e}function ze(a){const e=r=>Object.entries(r).filter(([,i])=>i>0).map(([i,o])=>`${i} ${o}`).join(" \xB7 ")||"none",t=r=>r.map(i=>`${"who"in i?i.who:i.run_id} \xD7${i.count}`).join(" \xB7 ")||"none",n=a.blocked.this_run.run_id===null?"- This run: (no run identity; export WYRM_RUN_ID or pass run_id)":`- This run (${a.blocked.this_run.run_id}): ${a.blocked.this_run.blocked} repeat(s) blocked`;return`\u{F115D} **Failure Analytics** (${a.project_id===null?"all projects":`project #${a.project_id}`})
1
+ import{readFileSync as P,statSync as G}from"node:fs";import{isAbsolute as ie,relative as oe,resolve as I,sep as V}from"node:path";import{sanitizeFtsQuery as ae,trySanitizeFtsQuery as se,redactCredentials as L}from"./security.js";import{WyrmCrypto as Q}from"./crypto.js";import{emitEvent as D,isLiveMemoryEnabled as ce}from"./events.js";import{getActor as m,hasExplicitAttribution as M}from"./handlers/boundary.js";import{screenRecordedId as le}from"./recorded-text-screen.js";import{readActor as de,resolveAttribution as ue}from"./attribution.js";import{recordGovernanceEvent as U}from"./governance.js";import{normalizeContentSignature as pe,containsFailedSignature as Z,redactedContentSignature as X}from"./content-signature.js";const W=new Set(["a","an","the","this","that","these","those","and","or","but","if","then","than","so","to","of","in","on","at","by","for","from","with","without","no","not","as","is","are","was","were","be","been","being","will","would","can","could","should","it","its","i","we","you","my","our","your","again","just","now","please","let","lets","do","does","did","into","over","about"]),J={run:0,project:1,global:2},fe=8,qe="source changed since this failure was recorded \u2014 re-verify",_e="no hits in the quiet period, so it warns instead of blocking; recording it again re-arms the block",C="operator;cli",he=60,Ee=44;function ve(a=process.env){const e=(a.WYRM_FAILURE_QUIET_DAYS??"").trim();if(e==="")return he;if(/^(off|false|no)$/i.test(e))return 0;const t=Number(e);return Number.isFinite(t)&&t>0?t:0}const F=200,O=5,$e=["exact","fuzzy","target","canonical","related"],xe="a similar record, not this action: only the same action, the same target or an equivalent command blocks";function Be(a,e,t){if(!a)return"the record could not be re-read";if(a.operator_confirmed||a.quarantine_scope==="run"&&a.run_id!==null&&a.run_id===e)return null;const n=a.operator_confirmation_stale?"it changed since the operator confirmed it":null;return a.project_id===null||a.quarantine_scope==="global"?n??"it is a global record and the operator has not confirmed it":a.agent_id!==null&&!t?n??`an agent (${le(a.agent_id,40)}) recorded it and the operator has not confirmed it`:null}function Ye(a=process.env){return/^(1|true|yes|on)$/i.test(a.WYRM_GUARD_AGENT_BLOCKS??"")}function ze(a,e,t){return a.match==="exact"?"exact":a.match==="target"||e.has(b(a.target))?"target":a.match==="canonical"||a.scope==="command"&&a.match!=="related"&&t.has(A(a.target))?"canonical":null}function k(a){const e=[],t=o=>{const s=o.trim();s&&s.length<=1e3&&!e.includes(s)&&e.push(s)},n=[];let r="",i=null;for(let o=0;o<a.length;o++){const s=a[o];if(i){r+=s,s===i&&a[o-1]!=="\\"&&(i=null);continue}if(s==="'"||s==='"'){i=s,r+=s;continue}const l=a.slice(o,o+2);if(l==="&&"||l==="||"){n.push(r),r="",o++;continue}if(s===";"||s==="|"||s===`
2
+ `){n.push(r),r="";continue}r+=s}n.push(r);for(const o of n){t(o);let s=o.trim(),l=!1;for(let d=0;d<8;d++){const h=s.match(/^(?:sudo(?:\s+-[A-Za-z]+)*|doas|time|nohup|exec|command|stdbuf(?:\s+-\S+)*|env|[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|\S*))\s+/);if(!h)break;s=s.slice(h[0].length).trim(),l=!0}l&&t(s);const _=s.match(/^(?:ba|z|k)?sh\s+-c\s+(['"])([\s\S]*)\1\s*$/);if(_)for(const d of k(_[2]))t(d)}return e}function Pe(a){const e=r=>Object.entries(r).filter(([,i])=>i>0).map(([i,o])=>`${i} ${o}`).join(" \xB7 ")||"none",t=r=>r.map(i=>`${"who"in i?i.who:i.run_id} \xD7${i.count}`).join(" \xB7 ")||"none",n=a.blocked.this_run.run_id===null?"- This run: (no run identity; export WYRM_RUN_ID or pass run_id)":`- This run (${a.blocked.this_run.run_id}): ${a.blocked.this_run.blocked} repeat(s) blocked`;return`\u{F115D} **Failure Analytics** (${a.project_id===null?"all projects":`project #${a.project_id}`})
3
3
 
4
4
  **Recorded:** ${a.recorded.total} failure(s), ${a.recorded.unresolved} unresolved
5
5
  - By quarantine: ${e(a.recorded.by_quarantine_scope)}
@@ -147,21 +147,21 @@ ${n}
147
147
  AND (quarantine_scope <> 'run' OR run_id = @run)
148
148
  ORDER BY occurrences DESC, last_seen DESC
149
149
  LIMIT @cap
150
- `).all({lo:l,hi:_,project:n??null,run:s,cap:k}).filter(h=>b(h.target)===i).slice(0,O)}canonicalMatches(e,t,n,r){return e!=="command"?[]:H(t,O,i=>this.canonicalFor(i,n,r))}canonicalFor(e,t,n){const r=A(e);if(r.length===0)return[];const i=n?.callerRunId!==void 0?n.callerRunId:m().run_id;return this.db.prepare(`
150
+ `).all({lo:l,hi:_,project:n??null,run:s,cap:F}).filter(h=>b(h.target)===i).slice(0,O)}canonicalMatches(e,t,n,r){return e!=="command"?[]:H(t,O,i=>this.canonicalFor(i,n,r))}canonicalFor(e,t,n){const r=A(e);if(r.length===0)return[];const i=n?.callerRunId!==void 0?n.callerRunId:m().run_id;return this.db.prepare(`
151
151
  SELECT * FROM failure_patterns
152
152
  WHERE resolved = 0 AND scope = 'command' AND canonical_target = @canon
153
153
  AND (project_id IS @project OR project_id = @project OR project_id IS NULL)
154
154
  AND (quarantine_scope <> 'run' OR run_id = @run)
155
155
  ORDER BY occurrences DESC, last_seen DESC
156
156
  LIMIT @cap
157
- `).all({canon:r,project:t??null,run:i,cap:k}).filter(s=>A(s.target)===r).slice(0,O)}commandHeadFamily(e,t,n,r){return e!=="command"?[]:H(t,O,i=>this.headFamilyFor(i,n,r))}headFamilyFor(e,t,n){const r=ee(e);if(r.length===0)return[];const i=n?.callerRunId!==void 0?n.callerRunId:m().run_id;return this.db.prepare(`
157
+ `).all({canon:r,project:t??null,run:i,cap:F}).filter(s=>A(s.target)===r).slice(0,O)}commandHeadFamily(e,t,n,r){return e!=="command"?[]:H(t,O,i=>this.headFamilyFor(i,n,r))}headFamilyFor(e,t,n){const r=ee(e);if(r.length===0)return[];const i=n?.callerRunId!==void 0?n.callerRunId:m().run_id;return this.db.prepare(`
158
158
  SELECT * FROM failure_patterns
159
159
  WHERE resolved = 0 AND scope = 'command' AND command_head = @head
160
160
  AND (project_id IS @project OR project_id = @project OR project_id IS NULL)
161
161
  AND (quarantine_scope <> 'run' OR run_id = @run)
162
162
  ORDER BY occurrences DESC, last_seen DESC
163
163
  LIMIT @cap
164
- `).all({head:r,project:t??null,run:i,cap:k}).slice(0,O)}recordBlock(e,t){if(!(!e.blocked||e.matches.length===0))try{const n=m(),r=e.matches.find(i=>!i.stale_anchor)??e.matches[0];this.db.prepare(`
164
+ `).all({head:r,project:t??null,run:i,cap:F}).slice(0,O)}recordBlock(e,t){if(!(!e.blocked||e.matches.length===0))try{const n=m(),r=e.matches.find(i=>!i.stale_anchor)??e.matches[0];this.db.prepare(`
165
165
  INSERT INTO failure_blocks (failure_id, project_id, agent_id, run_id)
166
166
  VALUES (?, ?, ?, ?)
167
167
  `).run(r.id,t??null,n.agent_id,n.run_id)}catch{}}pruneBlocks(e){const t=Math.max(1,Math.floor(e));try{return this.db.prepare("DELETE FROM failure_blocks WHERE blocked_at < datetime('now', @cut)").run({cut:`-${t} days`}).changes}catch{return 0}}failureStats(e){const t=e?.projectId??null,n=e?.callerRunId!==void 0?e.callerRunId:m().run_id,r={project:t},i=this.db.prepare(`
@@ -224,7 +224,7 @@ ${n}
224
224
  AND (@tier IS NULL OR fp.quarantine_scope = @tier)
225
225
  ORDER BY fp.occurrences DESC, fp.last_seen DESC
226
226
  LIMIT 5
227
- `).all({...l,q:R,scope:e}).map(g=>({...g,_match:"fuzzy"}))}catch{return[]}}relatedTextMatches(e,t,n,r,i,o){if(!t)return[];const s=be(t.slice(0,1e3),t.length>=1e3),l=F(s);for(const p of s.matchAll(/\$\(([^()]+)\)/g))for(const S of F(p[1]))l.includes(S)||l.push(S);const _=l.map(p=>Oe(p).slice(0,re)).filter(p=>p.length>0).slice(0,Re);if(_.length===0)return[];const d=new Set([t,...l].map(p=>b(p))),h=new Set(l.map(p=>A(p)).filter(p=>p.length>0)),c=p=>d.has(b(p.target))||p.scope==="command"&&h.has(A(p.target)),u=e!=="command"&&_.length===1&&_[0].length===1,f=_.filter(p=>p.length>1||u||j(p[0])).map(p=>({toks:p,lone:p.length===1})),R=p=>{const S=se(p);return S?`"${S.replace(/"/g,"")}"`:null},E=p=>[...new Set(p.filter(S=>S!==null))],g=E(_.map(p=>R(v(p[0]))));if(g.length===0)return[];const y=E(_.flat().map(p=>R(v(p)))),ne=i?.callerRunId!==void 0?i.callerRunId:m().run_id,x=i?.runScope??"any";let B;try{B=this.db.prepare(`
227
+ `).all({...l,q:R,scope:e}).map(g=>({...g,_match:"fuzzy"}))}catch{return[]}}relatedTextMatches(e,t,n,r,i,o){if(!t)return[];const s=be(t.slice(0,1e3),t.length>=1e3),l=k(s);for(const p of s.matchAll(/\$\(([^()]+)\)/g))for(const S of k(p[1]))l.includes(S)||l.push(S);const _=l.map(p=>Oe(p).slice(0,re)).filter(p=>p.length>0).slice(0,Re);if(_.length===0)return[];const d=new Set([t,...l].map(p=>b(p))),h=new Set(l.map(p=>A(p)).filter(p=>p.length>0)),c=p=>d.has(b(p.target))||p.scope==="command"&&h.has(A(p.target)),u=e!=="command"&&_.length===1&&_[0].length===1,f=_.filter(p=>p.length>1||u||j(p[0])).map(p=>({toks:p,lone:p.length===1})),R=p=>{const S=se(p);return S?`"${S.replace(/"/g,"")}"`:null},E=p=>[...new Set(p.filter(S=>S!==null))],g=E(_.map(p=>R(v(p[0]))));if(g.length===0)return[];const y=E(_.flat().map(p=>R(v(p)))),ne=i?.callerRunId!==void 0?i.callerRunId:m().run_id,x=i?.runScope??"any";let B;try{B=this.db.prepare(`
228
228
  SELECT fp.* FROM failure_patterns fp
229
229
  JOIN failure_patterns_fts fts ON fts.rowid = fp.id
230
230
  WHERE failure_patterns_fts MATCH @q
@@ -241,4 +241,4 @@ ${n}
241
241
  UPDATE failure_patterns
242
242
  SET resolved = 1, resolution_note = ?
243
243
  WHERE id = ?
244
- `).run(t!=null?L(t):null,e);return r.changes>0&&U(this.db,"failure.resolve",{failure_id:e}),r})();return{row:this.get(e),authorized:!0,changed:n.changes>0}}delete(e){return M(m())?this.db.transaction(()=>{try{this.db.prepare("DELETE FROM failure_anchors WHERE failure_id = ?").run(e)}catch{}const t=this.db.prepare("DELETE FROM failure_patterns WHERE id = ?").run(e);return t.changes>0&&U(this.db,"failure.delete",{failure_id:e}),t.changes>0})():!1}}export{fe as ANCHOR_CAP,he as DEFAULT_FAILURE_QUIET_DAYS,N as FailurePatterns,C as OPERATOR_CONFIRMATION_ID,Ee as QUIET_CLOCK_MIGRATION,_e as QUIET_DOWNGRADE_FLAG,$e as SIMILAR_ONLY_FLAG,qe as STALE_ANCHOR_FLAG,Be as agentBlocksEnabled,xe as blockAuthorityGap,Ye as blockTier,A as canonicalizeCommand,ee as commandHead,F as commandSegments,ve as failureQuietDays,ge as matchConfidence,b as normalizeIdentity,K as normalizeSignal,ze as renderFailureStats,be as stripHeredocBodies,ye as textRelation};
244
+ `).run(t!=null?L(t):null,e);return r.changes>0&&U(this.db,"failure.resolve",{failure_id:e}),r})();return{row:this.get(e),authorized:!0,changed:n.changes>0}}delete(e){return M(m())?this.db.transaction(()=>{try{this.db.prepare("DELETE FROM failure_anchors WHERE failure_id = ?").run(e)}catch{}const t=this.db.prepare("DELETE FROM failure_patterns WHERE id = ?").run(e);return t.changes>0&&U(this.db,"failure.delete",{failure_id:e}),t.changes>0})():!1}}export{fe as ANCHOR_CAP,he as DEFAULT_FAILURE_QUIET_DAYS,$e as FAILURE_MATCH_TIERS,N as FailurePatterns,C as OPERATOR_CONFIRMATION_ID,Ee as QUIET_CLOCK_MIGRATION,_e as QUIET_DOWNGRADE_FLAG,xe as SIMILAR_ONLY_FLAG,qe as STALE_ANCHOR_FLAG,Ye as agentBlocksEnabled,Be as blockAuthorityGap,ze as blockTier,A as canonicalizeCommand,ee as commandHead,k as commandSegments,ve as failureQuietDays,ge as matchConfidence,b as normalizeIdentity,K as normalizeSignal,Pe as renderFailureStats,be as stripHeredocBodies,ye as textRelation};
package/dist/goals.js CHANGED
@@ -1,9 +1,9 @@
1
- import{redactField as a}from"./security.js";class E{db;constructor(t){this.db=t}set(t){const e=this.db.prepare(`
1
+ import{redactField as a}from"./security.js";function l(s){const t=typeof s=="number"&&Number.isFinite(s)?Math.ceil(s):20;return Math.max(1,Math.min(t,200))}class u{db;constructor(t){this.db=t}set(t){const e=this.db.prepare(`
2
2
  INSERT INTO goals
3
3
  (project_id, title, description, success_criteria, deadline,
4
4
  priority, max_iterations)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?)
6
- `).run(t.project_id??null,a(t.title),a(t.description??null),a(t.success_criteria??null),a(t.deadline??null),t.priority??"medium",Math.max(1,Math.min(t.max_iterations??20,200)));return this.get(e.lastInsertRowid)}get(t){return this.db.prepare("SELECT * FROM goals WHERE id = ?").get(t)??null}list(t){const e=[],s=[];t?.status&&(e.push("status = ?"),s.push(t.status)),t?.project_id!=null&&(e.push("project_id = ?"),s.push(t.project_id));const o=`
6
+ `).run(t.project_id??null,a(t.title),a(t.description??null),a(t.success_criteria??null),a(t.deadline??null),t.priority??"medium",l(t.max_iterations));return this.get(e.lastInsertRowid)}get(t){return this.db.prepare("SELECT * FROM goals WHERE id = ?").get(t)??null}list(t){const e=[],o=[];t?.status&&(e.push("status = ?"),o.push(t.status)),t?.project_id!=null&&(e.push("project_id = ?"),o.push(t.project_id));const r=`
7
7
  SELECT * FROM goals
8
8
  ${e.length?"WHERE "+e.join(" AND "):""}
9
9
  ORDER BY
@@ -12,21 +12,21 @@ import{redactField as a}from"./security.js";class E{db;constructor(t){this.db=t}
12
12
  COALESCE(last_pursued_at, '1970-01-01') ASC,
13
13
  created_at ASC
14
14
  LIMIT ?
15
- `;return s.push(t?.limit??50),this.db.prepare(o).all(...s)}nextToPursue(t){const e=[];let s="status = 'active' AND iterations_count < max_iterations";t!=null&&(s+=" AND project_id = ?",e.push(t));const o=`
15
+ `;return o.push(t?.limit??50),this.db.prepare(r).all(...o)}nextToPursue(t){const e=[];let o="status = 'active' AND iterations_count < max_iterations";t!=null&&(o+=" AND project_id = ?",e.push(t));const r=`
16
16
  SELECT * FROM goals
17
- WHERE ${s}
17
+ WHERE ${o}
18
18
  ORDER BY
19
19
  CASE priority WHEN 'critical' THEN 0 WHEN 'high' THEN 1
20
20
  WHEN 'medium' THEN 2 ELSE 3 END,
21
21
  COALESCE(last_pursued_at, '1970-01-01') ASC
22
22
  LIMIT 1
23
- `;return this.db.prepare(o).get(...e)??null}recordIteration(t,e){const s=this.get(t);if(!s)throw new Error(`Goal ${t} not found`);const o=s.iterations_count+1,i=this.db.prepare(`
23
+ `;return this.db.prepare(r).get(...e)??null}recordIteration(t,e){const o=this.get(t);if(!o)throw new Error(`Goal ${t} not found`);const r=o.iterations_count+1,n=this.db.prepare(`
24
24
  INSERT INTO goal_iterations
25
25
  (goal_id, iteration_num, observe_summary, orient_summary,
26
26
  decided_action, action_result, outcome, notes,
27
27
  latency_ms, tokens_in, tokens_out, model)
28
28
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
29
- `).run(t,o,a(e.observe_summary??null),a(e.orient_summary??null),a(e.decided_action??null),a(e.action_result??null),e.outcome,a(e.notes??null),Math.max(0,Math.round(e.latency_ms)),e.tokens_in??null,e.tokens_out??null,e.model??null),r=e.outcome==="done";return this.db.prepare(`
29
+ `).run(t,r,a(e.observe_summary??null),a(e.orient_summary??null),a(e.decided_action??null),a(e.action_result??null),e.outcome,a(e.notes??null),Math.max(0,Math.round(e.latency_ms)),e.tokens_in??null,e.tokens_out??null,e.model??null),i=e.outcome==="done";return this.db.prepare(`
30
30
  UPDATE goals
31
31
  SET iterations_count = iterations_count + 1,
32
32
  last_pursued_at = datetime('now'),
@@ -35,7 +35,7 @@ import{redactField as a}from"./security.js";class E{db;constructor(t){this.db=t}
35
35
  status = CASE WHEN ? = 1 THEN 'completed' ELSE status END,
36
36
  completed_at = CASE WHEN ? = 1 THEN datetime('now') ELSE completed_at END
37
37
  WHERE id = ?
38
- `).run(e.outcome,r?1:0,r?1:0,t),this.db.prepare("SELECT * FROM goal_iterations WHERE id = ?").get(i.lastInsertRowid)}iterationsFor(t,e=50){return this.db.prepare(`
38
+ `).run(e.outcome,i?1:0,i?1:0,t),this.db.prepare("SELECT * FROM goal_iterations WHERE id = ?").get(n.lastInsertRowid)}iterationsFor(t,e=50){return this.db.prepare(`
39
39
  SELECT * FROM goal_iterations
40
40
  WHERE goal_id = ? ORDER BY iteration_num DESC LIMIT ?
41
41
  `).all(t,e)}complete(t,e){return this.db.prepare(`
@@ -55,4 +55,4 @@ import{redactField as a}from"./security.js";class E{db;constructor(t){this.db=t}
55
55
  updated_at = datetime('now'),
56
56
  last_outcome = COALESCE(?, last_outcome)
57
57
  WHERE id = ?
58
- `).run(a(e??null),t),this.get(t)}}export{E as Goals};
58
+ `).run(a(e??null),t),this.get(t)}}export{u as Goals,l as goalIterationCap};